content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from SpellCorrect import input_processing
from Organize_Names import Corpus_Combo, Combined_words,Word_Classfication,import_file,Remov_Num,Remove_nan,Remove_strNum,Clean_Word,Valuable_word
from Import_corpus import input_file
from Get_Synonyms import Get_SynonymFromlst
from Standard_corpus import standarlized_outpu... | python |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : environ.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 01/19/2018
#
# This file is part of Jacinle.
# Distributed under terms of the MIT license.
import contextlib
from copy import deepcopy
from jacinle.utils.meta import dict_deep_keys,... | python |
import uuid
import json
from django.core.cache import cache
from django.core.mail import send_mail
from django.shortcuts import reverse
from django.conf import settings
def validate_email(user, email):
title = '验证你的电子邮箱 | conus 通知推送'
token = uuid.uuid4().hex
body = (
'请打开下方连接以验证你的电子邮箱:\n'
... | python |
import unittest
from braintreehttp.testutils import TestHarness
from braintreehttp.serializers import FormPart
class FormPartTest(unittest.TestCase):
def test_init_lowercase_headers(self):
form_part = FormPart({ "key": "value" }, { "content-type": "application/json" })
self.assertTrue("Content-T... | python |
#!/usr/bin/python
from pathlib import Path
import os
import shutil
from readConfig import ReadConfig
from datetime import datetime
class Utils:
"""
工具类
"""
@staticmethod
def save_file(file_name, row_list, mode):
"""
将 row_list 中的股票数据保存到 file_name 路径文件中
:param file_name: 路径文... | python |
"""
Switch based on e.g. a MCP23017 IC, connected to a Raspberry Pi board.
It is expected that a server part is running, through a Redis in-memory database. Commands are
sent to the Redis database, and responses captured. The server would then process the actions
in background.
Author: find me on codeproject.com --> Ju... | python |
import logging
import os
from rich import print
from typing import Dict
from sfaira.commands.utils import get_ds
from sfaira.consts.utils import clean_doi
from sfaira.data import DatasetBase
log = logging.getLogger(__name__)
class H5adExport:
datasets: Dict[str, DatasetBase]
doi: str
doi_sfaira_repr: ... | python |
from typing import Optional, Sequence
from kubragen import KubraGen
from kubragen.builder import Builder
from kubragen.consts import PROVIDER_K3D, PROVIDER_K3S
from kubragen.data import ValueData
from kubragen.exception import InvalidParamError, InvalidNameError
from kubragen.helper import QuotedStr
from kubragen.kdat... | python |
from pathlib import Path
import pandas as pd
from modules.settings.settings import SettingsManager
class PseudoIDManager:
""" Class for setting, getting pseudo_id filepaths and getting pseudo_id value """
def __init__(self, l2c: dict, settm: SettingsManager):
self._settm = settm
self._l2c = ... | python |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distribu... | python |
# -*- coding: utf-8 -*-
"""
Helpers for our web and worker (scraper) instances
"""
from werkzeug.contrib.atom import AtomFeed
from flask import make_response
import json
from bson import json_util
import datetime
import pymongo
from conn import db
def _get_plans(count=1000, query={}):
return list(db.plans.find... | python |
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from .views import CreatePollViewSet, GetResultViewSet, PollViewSet
v1_router = DefaultRouter()
v1_router.register('createPoll', CreatePollViewSet, basename='create_poll')
v1_router.register('poll', PollViewSet, basename='vote_poll... | python |
# Gumby theft detection program
# Created Feb 8, 2018
# Copyright (c) Sambhav Saggi 2018
# All rights reserved
# Created for Gregory Calvetti
# Output may be wrong
#Set some constants
DENSITY_THRESH=0.7
#Get ready to compare numbers
def takeClosest(list, derp):
meme = []
for i in list:
meme.append(abs... | python |
from . import command
from opensfm.actions import match_features
class Command(command.CommandBase):
name = 'match_features'
help = 'Match features between image pairs'
def run_impl(self, dataset, args):
match_features.run_dataset(dataset)
def add_arguments_impl(self, parser):
pass
| python |
# -*- coding: utf-8 -*-
"""
Jakob Seidl, Nanoelectronics Group UNSW Sydney
"""
import pyvisa as visa
import pyneMeas.Instruments.Instrument as Instrument
import time
import math
import numpy as np
@Instrument.enableOptions
class SRS830(Instrument.Instrument):
"""
SRS830 Lock-In Amplifier
... | python |
# Copyright (C) 2020-Present the hyssop authors and contributors.
#
# This module is part of hyssop and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
'''
File created: November 21st 2020
Modified By: hsky77
Last Updated: March 27th 2021 19:31:11 pm
'''
from .server import Ai... | python |
# -*- coding: utf-8 -*-
"""
lantz.drivers.newport
~~~~~~~~~~~~~~~~~~~~~
:company: Newport.
:description: Test and Measurement Equipment.
:website: http://www.newport.com/
---
:copyright: 2015, see AUTHORS for more details.
:license: GPLv3,
"""
from .motionesp301 import ESP301, ESP30... | python |
import typing
import os
import aiohttp
from urllib.parse import quote
from deta.utils import _get_project_key_id
from deta.base import FetchResponse, Util
def AsyncBase(name: str):
project_key, project_id = _get_project_key_id()
return _AsyncBase(name, project_key, project_id)
class _AsyncBase:
def __... | python |
#!/usr/bin/env python3
# Software License Agreement (BSD License)
#
# Copyright (c) 2018, UFACTORY, Inc.
# All rights reserved.
#
# Author: Vinman <vinman.wen@ufactory.cc> <vinman.cub@gmail.com>
from ..core.config.x_config import XCONF
class APIState(object):
NOT_CONNECTED = -1 # 已断开或未连接
NOT_READY = -2 # ... | python |
from pykgr.package import Package
from pykgr.shell import Shell
from pykgr.configuration import conf as config
from pykgr.environment import Environment
from pykgr.builder import Builder
from pykgr.package import Package | python |
#!/usr/bin/env python
# encoding: utf-8
from unittest import TestCase
from ycyc.libs.statelib.state import (
FreeState, SequenceState, QSequenceState,
StateNotAllowError, EndOfSequenceStateError, SequenceStateFinishedError,
)
class TestFreeState(TestCase):
def test_usage(self):
stat... | python |
import streamlit as st
# https://github.com/streamlit/release-demos/blob/master/0.65/demos/query_params.py
query_params = st.experimental_get_query_params()
default = query_params["text"][0] if "text" in query_params else ""
x = st.text_area('Enter Text', value=default)
st.write('The text in uppercase is ', x.upper(... | python |
from parser import EPL
import glob
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.lines import Line2D
import copy
class Experiment:
def __init__(self, suppath, file_regex='*-analyzed.txt', parser=EPL):
self.suppath = suppath
self.parser = parser
... | python |
import time
import picamerax
frames = 60
with picamerax.PiCamera() as camera:
camera.resolution = (1024, 768)
camera.framerate = 30
camera.start_preview()
# Give the camera some warm-up time
time.sleep(2)
start = time.time()
camera.capture_sequence([
'image%02d.jpg' % i
for... | python |
#-----------------------------------------------------------------------------
# Copyright (c) 2013-2019, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this s... | python |
#!/usr/bin/env python
from flask_babel import _
import os
basedir = os.path.abspath(os.path.dirname(__file__))
POSTGRES = {
'user': 'catalog',
'pw': 'catalog',
'db': 'catalog',
'host': 'localhost',
'port': '5432',
}
class Config(object):
""" App configuration """
CLIENT_SECRET_JSON = os.... | python |
#!/usr/bin/env python3
""" Simulate 3D aggregate mixing
Generate simulated aggregates that can be analyzed by `analyze_3d_aggregate_mixing.py`
.. code-block:: bash
$ ./simulate_3d_aggregate_mixing.py \\
--num-red 400 \\
--num-green 127 \\
--aggregate-radius 75.3 \\
--neighbor-rad... | python |
from statuscheck.services.bases._statuspageio import BaseStatusPageAPI
class ServiceAPI(BaseStatusPageAPI):
name = "Epic Games"
domain_id = "ft308v428dv3"
status_url = "https://status.epicgames.com/"
service_url = "http://epicgames.com/"
| python |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import unittest
from tr55.water_quality import get_volume_of_runoff, get_pollutant_load
from tr55.tables import POLLUTION_LOADS
class TestWaterQuality(unittest.TestCase):
def tes... | python |
import pytorch_lightning as pl
class TeacherForcingAnnealCallback(pl.Callback):
def __init__(self, start, end, epochs):
assert start >= end
self.start = start
self.end = end
self.epochs = epochs
self.slope = float((start - end)) / epochs
def on_validation_ep... | python |
import datetime
import pandas as pd
import io
import os
import boto3
from io import BytesIO
from io import StringIO
from airflow import DAG
from airflow.providers.amazon.aws.operators.redshift_sql import RedshiftSQLOperator
from airflow.operators.dummy import DummyOperator
from airflow.operators.redshift_to_s3_operat... | python |
import databases
import sqlalchemy
import logging
import os
import json
from fastapi import FastAPI
from sqlalchemy import text
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
db_string = "postgresql://{0}:{1}@{2}/{3}".format(os.getenv("POSTGRES_USER"),
... | python |
#!/usr/bin/env python
import socket
import warnings
import pytest
from flask import _request_ctx_stack
from ._internal import _determine_scope
from ._internal import _make_accept_header
from ._internal import _rewrite_server_name
from .live_server import LiveServer
@pytest.fixture
def client(app):
"""A Flask te... | python |
from Jumpscale import j
def main(self):
"""
to run:
kosmos 'j.clients.zdb._tests_run(name="admin")'
"""
c = j.servers.zdb.test_instance.client_admin_get()
c.reset()
c.namespaces_list()
assert c.namespaces_list() == ["default"]
c.namespace_new("test_namespace")
assert c.nam... | python |
class IdentityHashingService:
def hash(self, value):
return value
| python |
class Solution:
"""
@param s: a string
@param words: a list of words
@return: all starting indices of substring(s)
"""
def findSubstring(self, s, words):
# write your code here
m = len(s)
target = len(words)
result = []
if m == 0 or target == 0:
... | python |
import requests
import json
import logging
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
auth_server = 'https://api.amazon.com/auth/register'
alexa_user_name = 'username... | python |
#!/usr/bin/env python
a = [66.25, 333, 333, 1, 1234.5]
print("\na=", a)
print("\na.count(333) = %d, a.count(66.25) = %d, a.count('x') = %d" % (a.count(333), a.count(66.25), a.count('x')) )
print("\na.insert(2, -1) = ", a.insert(2, -1))
print("a = ", a)
print("\na.append(333) = ", a.append(333))
print("a = ", a)
pr... | python |
'''The doc module provides decorator functions that will modify a
functions __apidoc__ object. For example, when using `method('GET')`
it will set the value of the functions method as 'get' on its __apidoc__'''
from http import HTTPStatus
from oapispec.core.utils import merge, not_none
def doc(**kwargs):
'''A d... | python |
import itertools
import json
from collections import defaultdict
from django.core.serializers.json import DjangoJSONEncoder
from .orm_lookups import get_django_filter
from .query import BoundQuery
from .types import ASC, DSC
def _filter(qs, path_str, filter_):
negation = False
lookup = filter_.lookup
i... | python |
"""
Unit tests for \
landlab.components.vegetation_dynamics.vegetation_dynamics
"""
from nose.tools import assert_equal, assert_true, assert_raises, with_setup
from numpy.testing import assert_array_almost_equal
try:
from nose.tools import assert_is_instance
except ImportError:
from landlab.testing.tools im... | python |
import os
#We don't want to show the pygmy version and welcome message. Snif
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
from random import uniform,randint
import tqdm
"""
We import pygame in order to create a patch for the long calculations
If the QLearning calculation time or the creation of the path is t... | python |
# -*- coding: utf-8 -*-
import time
# from datetime import datetime, timedelta
from flask import Blueprint, request, Response, abort
from sqlalchemy import func, and_, or_
import os
import math
import ujson
import logging
from datetime import datetime
from models import FDMEvent, FDMEventType, FDMEventGroup, DataQarSe... | python |
from typing import Tuple
import requests
from bs4 import BeautifulSoup
from hospital_types import (
ScrapedData,
AppointmentAvailability,
HospitalAvailabilitySchema,
)
import aiohttp, asyncio
URL: str = "http://netreg.afph.tsgh.ndmctsgh.edu.tw/webreg/calendar_type/5xn1z9fPG5H4JDJEV98dHQ%3D%3D"
async def... | python |
from django.contrib.auth import get_user_model
from django.test import TestCase
UserModel = get_user_model()
class UserModelTest(TestCase):
def setUp(self) -> None:
self.user = UserModel.objects.create_user(
email='test@abv.bg',
)
self.user.set_password = '1234567890Mazen'
... | python |
#!/usr/bin/env python
##################################################
# Gnuradio Python Flow Graph
# Title: FCCH Bursts Detector
# Author: Piotr Krysik
#
# Description: Detects positions of FCCH bursts. At the end of each
# detected FCCH burst adds to the stream a tag with key "fcch" and value
# which is a frequen... | python |
import logging
def get_logger(LEVEL='info', log_file = None,name=None):
head = '[%(asctime)-15s] [%(levelname)s] %(message)s'
if LEVEL == 'info':
logging.basicConfig(level=logging.INFO, format=head)
elif LEVEL == 'debug':
logging.basicConfig(level=logging.DEBUG, format=head)
logger = lo... | python |
from sklearn.neighbors import KNeighborsClassifier
from sklearn import datasets
from sklearn.metrics import accuracy_score
iris = datasets.load_iris()
X, y = iris.data, iris.target
knn = KNeighborsClassifier()
knn.fit(X, y)
accuracy_score(y, knn.predict(X))
| python |
import random
import discord
from discord.ext import commands
from .inputs import cl, cf, chill, cfe, ur
from .utils import COLOR
class Coffee(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(aliases=['ask_out'])
async def wannagrabacoffee(self, ctx, *, member: d... | python |
# Copyright (c) Facebook, Inc. and its affiliates.
import unittest
import torch
from mmf.common.sample import Sample
from mmf.models.transformers.heads.itm import ITM
from mmf.models.transformers.heads.mlm import MLM
from mmf.models.transformers.heads.mlp import MLP
from omegaconf import OmegaConf
from tests.test_uti... | python |
import pandas as pd
from sklearn.model_selection import train_test_split
class DataLoader:
def __init__(self):
self.dataset = None
self.sensor = None
self.target = None
def load(self,file,isTest=False):
if not isTest:
print("loading")
self.dataset = pd.r... | python |
#!/usr/bin/env python3
import sys
def isBalanced(expression):
if len(expression) & 1:
return False
parentheses = []
for c in expression:
if c == '(' or c == '{' or c == '[':
parentheses.append(c)
elif c == ')' or c == '}' or c == ']':
offset = 1 if c == ')' else 2
if len(parent... | python |
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Any, DefaultDict, Optional, Type, TypeVar
from discord import Guild
from commanderbot.lib import FromDataMixin, GuildID, JsonSerializable, LogOptions
from commanderbot.lib.utils import dict_without_ellipsis, dict_without_f... | python |
from flask_restful import Resource, current_app
from backend.services.campaign_service import CampaignService
from backend.services.organisation_service import OrganisationService
from backend.models.postgis.utils import NotFound
from backend.services.users.authentication_service import token_auth
class Organisation... | python |
#!/usr/bin/env python
#coding: utf-8
__author__ = 'Toshihiro Kamiya <kamiya@mbj.nifty.com>'
__status__ = 'experimental'
import os.path
import re
import sys
import subprocess
UNIZP_COMMAND = "/usr/bin/unzip"
def get_class_names_from_jar(jar_file):
class_names = []
pat = re.compile(r"^\s*testing:\s*(.+)[.]cla... | python |
# Copyright 2020 Katteli Inc.
# TestFlows.com Open-Source Software Testing Framework (http://testflows.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/lice... | python |
from pathlib import Path
import importlib
import tensorflow as tf
from annoy import AnnoyIndex
DEFAULT_CONFIG = {
"dataset": "Dataset",
"model": "RetreivalModel",
"network": "retrieval_basic_factorization",
"network_args": {
"embedding_dimension": 32,
}
}
class Ret... | python |
# Generated by Django 2.1.3 on 2018-12-08 07:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('staf', '0010_process_slug'),
('multiplicity', '0023_referencespacetype_process'),
]
operations = [
... | python |
from __future__ import absolute_import, division, print_function
try:
from threading import local
except ImportError:
from django.utils._threading_local import local
_thread_locals = local()
def get_current_request():
""" returns the request object for this thread """
return getattr(_thr... | python |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | python |
from rest_framework import serializers
from .models import ListModel
from utils import datasolve
class BinsizeGetSerializer(serializers.ModelSerializer):
bin_size = serializers.CharField(read_only=True, required=False)
bin_size_w = serializers.FloatField(read_only=True, required=False)
bin_size_d = seriali... | python |
"""
https://leetcode.com/problems/logger-rate-limiter/
Tags: Google; Medium; Stack
"""
from typing import List
from operator import add, sub, mul, floordiv
def div(op1: int, op2: int) -> int:
neg = (op1 < 0 < op2) or (op2 < 0 < op1)
ans = floordiv(abs(op1), abs(op2))
return ans * (-1 if neg el... | python |
# -*- coding: utf-8 -*-
from .aapt import Aapt
from .minicap import Minicap
from .rotation import Rotation
from .performance.fps import Fps
from .performance.cpu import Cpu
from .performance.meminfo import Meminfo
from .performance import DeviceWatcher
__all__ = ['Aapt', 'Minicap', 'Rotation', 'Fps', 'Cpu', 'Meminfo'... | python |
import numpy, re
def encode_onehot(index, size):
onehot = numpy.zeros(size, dtype=numpy.int8)
onehot[index] = 1
return onehot
def prettify_string(string, replace_newline_with_space=True):
pretty_string = str(string).strip()
if replace_newline_with_space:
pretty_string = pre... | python |
from unittest import TestCase
from ddsc.core.consistency import UploadDetails, ProjectChecker, DSResourceNotConsistentError
from mock import Mock, patch, call
class TestUploadDetails(TestCase):
def test_inconsistent_status(self):
mock_dds_file = Mock()
mock_dds_file.name = 'file1.dat'
mock... | python |
# Global Benchmark Database (GBD)
# Copyright (C) 2020 Markus Iser, Karlsruhe Institute of Technology (KIT)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or... | python |
import pianohat
import time
from pygame import mixer
my_sound_files = [
"/home/pi/Downloads/despacito.wav",
"/home/pi/Downloads/Metal.wav",
"/home/pi/Downloads/Metal.wav",
"/home/pi/Downloads/Metal.wav",
"/home/pi/Downloads/Metal.wav",
"/home/pi/Downloads/despacito.wav",
"/home/pi/Downloads/... | python |
from django.db import models
# Create your models here.
class Employee(models.Model):
Name = models.CharField(max_length=64)
Email = models.CharField(max_length=64)
Password = models.CharField(max_length=64)
Position = models.CharField(max_length=64)
Salary = models.IntegerField()
def __str__... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
# Use 2to3 build conversion if required
try:
from distutils.command.build_py import build_py_2to3 as build_py
except ImportError:
# 2.x
from distutils.command.build_py import build_py
setup(
name="snpy",
description="A... | python |
# Copyright (C) 2021 ServiceNow, Inc.
import pytest
from nrcan_p2.data_processing.preprocessing_str import (
add_newline,
sentence_tokenize_spacy_sm,
sentence_tokenize_spacy_lg,
tokenize_spacy_sm,
tokenize_spacy_lg,
rm_stopwords_spacy,
rm_punct,
rm_newline
)
@pytest.mark.parametrize("i... | python |
"""
Helper functions and classes around GeoIP lookups, based on Maxmind's
`maxminddb <https://pypi.python.org/pypi/maxminddb>`_ and
`geoip2 <https://pypi.python.org/pypi/geoip2>`_ Python packages.
"""
import logging
import time
import genc
from geoip2.database import Reader
from geoip2.errors import AddressNotFoundEr... | python |
#define the main() function
def main():
i = 0
x = 119.0
for i in range(120):
if((i%2)==0):
x += 3.
else:
x -= 5.
s = "%3.2e" % x
print(s)
if __name__ == "__main__":
main() | python |
import asyncio
from userbot import CMD_HELP, StartTime, bot
from userbot.utils import bash, edit_or_reply, zelda_cmd
@zelda_cmd(pattern="sxs (.*)")
async def amireallysxs(sxs):
user = await bot.get_me()
capt = str(sxs.pattern_match.group(1).split(" ", 2)[0])
link = str(sxs.pattern_match.group(1).split(" "... | python |
#!/usr/bin/env python
from flexbe_core import EventState, Logger
import actionlib
import rospy
from jacobian_control.msg import DoAdaptionAction, DoAdaptionGoal, DoAdaptionResult, DoAdaptionFeedback
class HandoverAdaptionExec(EventState):
''' Calls jacobian-control node for adaption. '''
def __init__(self... | python |
from .receipt_parser import parse_receipt # noqa
| python |
import animal
class Bear(animal.Animal):
pass
| python |
from dataclasses import dataclass
from minsk.analysis.binding.expression import BoundExpression
from minsk.analysis.binding.kind import BoundNodeKind
from minsk.analysis.binding.operators.unary import BoundUnaryOperator
from minsk.analysis.type import MinskType
@dataclass(frozen=True)
class BoundUnaryExpression(Boun... | python |
from zeit.cms.i18n import MessageFactory as _
import fb
import gocept.form.grouped
import requests
import urllib
import urlparse
import zeit.cms.browser.menu
import zope.app.appsetup.product
import zope.formlib.form
import zope.session.interfaces
class IFacebookApp(zope.interface.Interface):
app_id = zope.schema... | python |
import FWCore.ParameterSet.Config as cms
from DQMOffline.Trigger.razorHemispheres_cff import *
from DQMOffline.Trigger.RazorMonitor_cfi import hltRazorMonitoring
# HLT_Rsq0p35_v*
Rsq0p35_RazorMonitoring = hltRazorMonitoring.clone()
Rsq0p35_RazorMonitoring.FolderName = cms.string('HLT/SUSY/Rsq0p35/')
Rsq0p35_RazorMon... | python |
project = 'matador-test'
environments = {
'test': {'dbms': 'oracle', 'connection': 'user@instance'}
}
credentials = {
'test': {'user': 'test_user', 'password': 'test_password'}
}
| python |
events = ["evt1", "evt2", "evt3"]
def my_pop():
if events:
evt = events.pop(0)
print(evt)
print(events)
my_pop()
my_pop()
my_pop()
my_pop()
| python |
"Models for managing site sections and ad placements."
from __future__ import unicode_literals
from django.conf import settings
from django.core.cache import cache
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from .conf import SECTION_CACHE_KEY, PLACEMENTS_KEY_FORMAT
from... | python |
from .base_regularizer import BaseRegularizer
from .center_invariant_regularizer import CenterInvariantRegularizer
from .regular_face_regularizer import RegularFaceRegularizer
from .lp_regularizer import LpRegularizer
from .zero_mean_regularizer import ZeroMeanRegularizer
from .sparse_centers_regularizer import Sp... | python |
#!/usr/bin/env python
"""circuits Hello World"""
from circuits import Component, Event
class hello(Event):
"""hello Event"""
class App(Component):
def hello(self):
"""Hello Event Handler"""
print("Hello World!")
def started(self, component):
"""Started Event Handler
... | python |
#!/usr/bin/env python
# Very useful script because I know the DMC steps start from s005
import re
import sys
import argparse
#import numpy as np
import autorunner
@autorunner.dmc_dat()
def common(x):
return x
# this style is not optimal but fine for now regardless
@autorunner.qmcpack_output()
def output_capturer(... | python |
# Generated by Django 4.0.4 on 2022-04-21 02:30
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Cheese',
fields=[
('slug', models.SlugField... | python |
import os
from PIL import Image
wnid = 'n03082979'
image_dir = './downloaded_images/{}/{}_urlimages'.format(wnid, wnid)
for filename in os.listdir(image_dir):
# if filename.endswith('.png'):
try:
filepath = os.path.join(image_dir, filename)
img = Image.open(filepath) # open the image file
img.verify() # ... | python |
# INTERSECTION OF TWO ARRAYS LEETCODE SOLUTION:
# creating a class.
class Solution(object):
# creating a function to solve the problem.
def intersection(self, nums1, nums2):
# returning the intersection between the two arrays.
return list(set(nums1).intersection(set(nums2))) | python |
import enum
import math
import time
import warnings
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union, cast
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim
from torch import Tensor
from . import functional as rtdlF
ModuleType = Union[str, Callable[..., n... | python |
#coding: utf8
from rust.core import db as models
class Permission(models.Model):
"""
资源权限
"""
resource = models.CharField(default='', max_length=128) # 资源名
method = models.CharField(default='GET', max_length=32) # 方法名
created_at = models.DateTimeField(auto_now_add=True) # 更新时间
class Meta(obj... | python |
from phoopy.kernel import Bundle
from os import path
class AppBundle(Bundle):
def service_path(self):
return path.join(self.get_bundle_dir(), 'config', 'services.yml') # pragma: no cover
| python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Collection of tests for :mod:`orion.core.utils.working_dir`."""
import os
import shutil
from pathlib import Path
import pytest
from orion.core.utils.working_dir import SetupWorkingDir
class ExperimentStub:
def __init__(self, working_dir=None):
self.name =... | python |
#!/usr/bin/python
import matplotlib.pyplot as plt
from matplotlib import *
import sys, getopt
import copy
import time
import datetime
import random
import sys
import os
import re
def get_data(file_list, type, start, finish, nice):
mapped_reqs, running_reqs, refused_reqs = [], [], []
mapped_requests_dict = di... | python |
from pyexcel.renderer import Renderer
from pyexcel_echarts.options import MANAGER
DEFAULT_TITLE = 'pyexcel via pyechars'
class Chart(Renderer):
def render_sheet(self, sheet, chart_type='bar', mode='embed',
title=DEFAULT_TITLE,
subtitle="",
width=800... | python |
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
S = {-1: set()}
for x in sorted(nums):
S[x] = max((S[d] for d in S if x % d == 0), key=len) | {x}
return list(max(S.values(), key=len))
| python |
# coding=utf-8
"""execution.py - This module provides classes that execute commands.
"""
import os
import sys
import signal
import subprocess
from .config import Config
from .base import PluginManager
from .log import LogManager
class ExecutionManager(PluginManager):
"""This class is used to execute commands for ... | python |
# -*- encoding: utf-8 -*-
import numpy as np
def get_seq_graph(edge):
dy, dx = np.array([-1,0,1,1,1,0,-1,-1]), np.array([-1,-1,-1,0,1,1,1,0])
def get_neighbors(node):
Y, X = node[0]+dy, node[1]+dx
neighbors = edge[Y, X]
Y, X = Y[neighbors], X[neighbors]
return zip(Y,X)
grap... | python |
from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.utils as vutils
from torch.aut... | python |
import numpy as np
# 对一维数组的切片
origin = np.arange(1,100)
print(origin)
print(origin[0:2])
print(origin[:12:4])
print(origin[:12:])
print(origin[5:])
print(origin[::-1]) #倒序
# 二维数组切片
origin = np.random.random((3,4))
print(origin)
print(origin[-2:,:2])
print(origin[::-2,::-1]) | python |
"""
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distri... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.