content
stringlengths
0
894k
type
stringclasses
2 values
# Copyright 2016, FBPIC contributors # Authors: Remi Lehe, Manuel Kirchen # License: 3-Clause-BSD-LBNL """ This file is part of the Fourier-Bessel Particle-In-Cell code (FB-PIC) It defines the structure necessary to implement the moving window. """ from fbpic.utils.threading import njit_parallel, prange # Check if CUDA...
python
from django.shortcuts import render from swpp.models import Profile from swpp.serializers import ProfileSerializer from rest_framework import generics, mixins, permissions from swpp.permissions import IsOwnerOrReadOnly class ProfileList(generics.ListAPIView): queryset = Profile.objects.all() serializer_class =...
python
KIND = { 'JOB': 'job', 'DEPLOYMENT': 'deployment' } COMMAND = { 'DELETE': 'delete', 'CREATE': 'create' }
python
# Copied from http://www.djangosnippets.org/snippets/369/ import re import unicodedata from htmlentitydefs import name2codepoint from django.utils.encoding import smart_unicode, force_unicode from slughifi import slughifi def slugify(s, entities=True, decimal=True, hexadecimal=True, model=None, slug_field='slug', p...
python
from typing import Optional from typing import Tuple import attr @attr.s(auto_attribs=True) class SlotAttentionParams: # model configs resolution: Tuple[int, int] = (128, 128) # since we not using ViT # Slot Attention module params num_slots: int = 7 # at most 6 obj per image/video # dim of sl...
python
from verifai.simulators.car_simulator.examples.control_utils.LQR_computation import * from verifai.simulators.car_simulator.simulator import * from verifai.simulators.car_simulator.lane import * from verifai.simulators.car_simulator.car_object import * from verifai.simulators.car_simulator.client_car_sim import * impor...
python
import numpy as np from mesostat.metric.impl.mar import unstack_factor, rel_err def predict(x, alpha, u, beta): # return np.einsum('ai,ijk', alpha, x) + np.einsum('ai,ijk', beta, u) return x.dot(alpha.T) + u.dot(beta.T) def fit_mle(x, y, u): # # Construct linear system for transition matrices # M11 ...
python
''' The MIT License (MIT) Copyright © 2021 Opentensor.ai Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,...
python
from srf.io.listmode import save_h5 import numpy as np data = np.fromfile("normal_scan_true.txt", dtype=np.float32).reshape(-1,7) result = {'fst': data[:, :3], 'snd': data[:, 3:6], 'weight': np.ones_like(data[:,0])} save_h5('input.h5', result)
python
from flask import Flask from . import api, web app = Flask( __name__, static_url_path='/assets', static_folder='static', template_folder='templates') app.config['SECRET_KEY'] = 'secret' # this is fine if running locally app.register_blueprint(api.bp) app.register_blueprint(web.bp)
python
default_app_config = 'user_deletion.apps.UserDeletionConfig'
python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Copyright 2012-2021 Smartling, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this work except in compliance with the License. * You may obtain a copy of the License in the LICENSE file, or at: * * http://www.apache.org/l...
python
# =============================================================================== # NAME: SerialHVisitor.py # # DESCRIPTION: A visitor responsible for the generation of header file # for each serializable class. # # AUTHOR: reder # EMAIL: reder@jpl.nasa.gov # DATE CREATED : June 4, 2007 # # Copyright 201...
python
import time import os import binascii import re from datetime import datetime from bson.json_util import dumps, loads from flask.helpers import get_template_attribute from flask import render_template from init import app, rdb from utils.jsontools import * from utils.dbtools import makeUserMeta from db i...
python
import socket import threading class Server: def __init__(self, ip, port): self.sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sck.bind((ip, port)) self.sck.listen() self.conCallback = None self.clientThrCallback = None self.disconCallback = None self.clients = { } self.nextClID = 0 def...
python
from math import pi, cos, log, floor from torch.optim.lr_scheduler import _LRScheduler class CosineWarmupLR(_LRScheduler): ''' Cosine lr decay function with warmup. Ref: https://github.com/PistonY/torch-toolbox/blob/master/torchtoolbox/optimizer/lr_scheduler.py https://github.com/Randl/MobileNetV...
python
from construct import * from construct.lib import * switch_integers__opcode = Struct( 'code' / Int8ub, 'body' / Switch(this.code, {1: Int8ub, 2: Int16ul, 4: Int32ul, 8: Int64ul, }), ) switch_integers = Struct( 'opcodes' / GreedyRange(LazyBound(lambda: switch_integers__opcode)), ) _schema = switch_integers
python
# -*- coding: utf-8 -*- # bricks.py: utility collections. # # Copyright (C) 2009, 2010 Raymond Hettinger <python@rcn.com> # Copyright (C) 2010 Lukáš Lalinský <lalinsky@gmail.com> # Copyright (C) 2010 Yesudeep Mangalapilly <yesudeep@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a c...
python
# -*- coding: utf-8 -*- """ PyEVO reCAPTCHA API module =============================================== .. module:: pyevo.api.recaptcha :platform: Unix, Windows :synopsis: PyEVO reCAPTCHA API module .. moduleauthor:: (C) 2012 Oliver Gutiérrez TODO: Check recaptcha API module for incomplete class method get_ch...
python
from ._container import AadModelContainer from onnxconverter_common.topology import Topology from onnxconverter_common.data_types import FloatTensorType from ad_examples.aad.forest_aad_detector import AadForest def _get_aad_operator_name(model): # FIXME: not all possible AAD models are currently supported if not is...
python
#import matplotlib.pyplot as plt from flask import Flask, render_template, jsonify import requests import json import numpy as np import time app = Flask(__name__) @app.route('/') def index(): r = requests.get("http://127.0.0.1:5000/chain").text r = json.loads(r) # Fetch the chain length chain_leng...
python
import numpy as np import lsst.afw.table as afwTable import lsst.pex.config as pexConfig import lsst.pipe.base as pipeBase import lsst.geom as geom import lsst.sphgeom as sphgeom from lsst.meas.base.forcedPhotCcd import ForcedPhotCcdTask, ForcedPhotCcdConfig from .forcedPhotDia import DiaSrcReferencesTask __all__ = ...
python
# Generated by Django 2.1 on 2018-09-08 14:06 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0003_market'), ] operations = [ migrations.AlterUniqueTogether( name='market', unique_together={('name', 'exchange')}, ...
python
import serial import struct import time def init_Serial(): print("Opening Serial Port COM 10") ser = serial.Serial( port='COM10', baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS ) return ser def wait_for_Pi(se...
python
from .Updater import Converters class _DataManager: def unpack(self, data): return self.unpackItems(data.items()) def unpackItems(self, items): return {key: self.itemsToDict(value) for key, value in items} def itemsToDict(self, data): if hasattr(data, "__dict__"): ret...
python
#!/usr/bin/env python from __future__ import print_function import roslib roslib.load_manifest('mct_watchdog') import rospy import threading import functools import numpy import mct_introspection import yaml import cv import Image as PILImage import ImageDraw as PILImageDraw import ImageFont as PILImageFont from cv_b...
python
#!/usr/bin/python # # Example of complex # Graph representing a network # import gvgen # Creates the new graph instance graph = gvgen.GvGen(None, "overlap=\"scale\";\nlabelfloat=\"true\";\nsplines=\"true\";") # We define different styles graph.styleAppend("router", "shapefile", "router.png") graph.styleAppend("router...
python
""" Functions related to calculating the rotational energy of asymmetric molecules. Townes and Schawlow, Ch. 4 """ from pylab import poly1d def asymmetry (A,B,C): """ Ray's asymmetry parameter for molecular rotation. For a prolate symmetric top (B = C), kappa = -1. For an oblate symmetric top (B = A), kappa =...
python
import matplotlib.pyplot as plt import numpy as np import torch # from scipy.special import softmax # from mpl_toolkits.axes_grid1 import make_axes_locatable def compare_distogram(outputs, targets): plt.figure(num=1, figsize=[15, 10]) plt.clf() # names = ['Distance','Omega','Phi','Theta'] names = ['dN...
python
import functools import requests import suds.transport as transport import traceback try: import cStringIO as StringIO except ImportError: import StringIO __all__ = ['RequestsTransport'] def handle_errors(f): @functools.wraps(f) def wrapper(*args, **kwargs): try: return f(*args,...
python
''' @author: Frank ''' import zstacklib.utils.http as http import zstacklib.utils.log as log import zstacklib.utils.plugin as plugin import zstacklib.utils.jsonobject as jsonobject import zstacklib.utils.daemon as daemon import zstacklib.utils.iptables as iptables import os.path import functools import t...
python
#a POC of queue manager with two button to increment and decrement the current value and broadcast it by wifi import machine from machine import I2C, Pin import time import network #set to True to enable a display, False to disable it use_display=True if use_display: #display setup, i have a 128x32 oled on this...
python
import sys import PyNexusZipCrawler # GET NEXUS MODS MOD ID FROM USER INPUT f_id = raw_input("Enter the Nexus Mods File ID you want to crawl: ") # CRAWL IT PyNexusZipCrawler.crawl_zip_content(f_id, "110")
python
import logging import os import pyaudio, wave, pylab import numpy as np import librosa, librosa.display import matplotlib.pyplot as plt from scipy.io.wavfile import write from setup_logging import setup_logging INPUT_DEVICE = 0 MAX_INPUT_CHANNELS = 1 # Max input channels DEFAULT_SAMPLE_RATE = 44100 # Default sample...
python
# ------------------------------------------------------------- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you unde...
python
from flask import Flask, jsonify import json from flask import Flask, render_template import numpy as np from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func engine = create_engine("sqlite:///Resources/hawaii.sqlite") # reflect an ...
python
class User(): def __init__(self, first_name, last_name, gender, email): self.first_name = first_name self.last_name = last_name self.gender = gender self.email = email self.login_attempts = 0 def describe_user(self): print(self.first_name) print...
python
#!/usr/bin/env python import pod import sys, binascii from StringIO import StringIO def ConvertMac(dotted): if dotted.find(":") == -1: str = binascii.unhexlify(dotted) else: str = "".join([chr(eval("0x"+i)) for i in dotted.split(":")]) if len(str) != 6: raise ValueError("Not a MAC address") ret...
python
from typing import List from ..codes import * from dataclasses import dataclass @dataclass(repr=True, eq=True) class OppoCommand: """Represents a command to an OppoDevice""" code: OppoCodeType _parameters: List[str] _response_codes: List[str] def __init__(self, code: OppoCodeType, parameters: List[str] = No...
python
from django.urls import path from rest_framework import routers from .views import * router = routers.DefaultRouter() router.register('notes', NoteViewSet, basename='notes') router.register('projects', ProjectViewSet, basename='projects') router.register('habits', HabitViewSet, basename='habits') urlpatterns = router...
python
import torch.nn as nn import torch from Postional import PositionalEncoding class TransAm(nn.Module): def __init__(self, feature_size=200, num_layers=1, dropout=0.1): super(TransAm, self).__init__() self.model_type = 'Transformer' self.src_mask = None self.pos_encoder = PositionalE...
python
# just a package
python
class Solution: def isPalindrome(self, x: int) -> bool: temp = str(x) length = len(temp) flag = 0 for i in range(0,length): if temp[i:i+1] != temp[length-1-i:length-i]: flag = 1 if flag == 1: return False else: retur...
python
from django.contrib import admin from .models import Pokemon admin.site.register(Pokemon)
python
#!/usr/local/bin/python3 #-*- encoding: utf-8 -*- from flask import Flask from flask_restx import Api from setting import config from app.api.client import worker_client def run(): app = Flask(__name__) api = Api( app, version='dev_0.1', title='Integrated Worker Server API', de...
python
# ==============================CS-199================================== # FILE: MyAI.py # # AUTHOR: Vaibhav Yengul # # DESCRIPTION: This file contains the MyAI class. You will implement your # agent in this file. You will write the 'getAction' function, # the constructor, and...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import getopt import os.path sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) from datetime import datetime from TwitterEngine import instances, BackendChooser def parseargs(name, argv): date = datetime.now() execut...
python
from django.contrib import admin from django.contrib.auth.decorators import login_required, permission_required from django.urls import path from . import views from .api import views as api_views app_name = 'main_app' urlpatterns = [ path('api/sites/', api_views.SitesListCreateAPIView.as_view(), name='sites_rest_...
python
import numpy as np from features.DetectorDescriptorTemplate import DetectorDescriptorBundle from features.cv_sift import cv_sift class SiftDetectorDescriptorBundle(DetectorDescriptorBundle): def __init__(self, descriptor): sift = cv_sift() super(SiftDetectorDescriptorBundle, self).__init__(sift, d...
python
import torch import torch.nn.functional as F import torch.nn as nn from transformers import BertModel # Convlution,MaxPooling層からの出力次元の算出用関数 def out_size(sequence_length, filter_size, padding = 0, dilation = 1, stride = 1): length = sequence_length + 2 * padding - dilation * (filter_size - 1) - 1 length...
python
from pi import KafkaProducerClient class LogProducer(object): # TODO: Implement parallel processing producer = KafkaProducerClient() for idx in range(1000): data = { "res": { "body": { "success": False, "code": "INTERNAL_SERVER_ER...
python
#!/usr/bin/env python import os, sys from typing import Union, List import pprint pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr) from google.protobuf.compiler import plugin_pb2 as plugin from google.protobuf.descriptor_pool import DescriptorPool from google.protobuf.descriptor import Descriptor, FieldDescrip...
python
import json import os import toml # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) CONFIG_FILE = 'config.toml' CONFIG_FILE_DIR = os.path.join(BASE_DIR, CONFIG_FILE) CONFIG_DATA = toml.load(CONFIG_FILE_DIR) # SECURITY WARNI...
python
from location import GeoCoordinate, geo_to_cartesian import time class Value: def __init__(self, value, unit): self.value = value self.unit = unit class Measurement: def __init__(self, row): self.parameter = row["parameter"] self.value = Value(row["value"], row["unit"]) ...
python
""" LC89. Gray Code The gray code is a binary numeral system where two successive values differ in only one bit. Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. Example 1: Input: 2 Output: [0,1,3,2] Explanation...
python
"""The IPython HTML Notebook""" import os # Packagers: modify this line if you store the notebook static files elsewhere DEFAULT_STATIC_FILES_PATH = os.path.join(os.path.dirname(__file__), "static") del os from .nbextensions import install_nbextension
python
import unittest import pytest from anchore_engine.db import Image, get_thread_scoped_session from anchore_engine.services.policy_engine.engine.tasks import ImageLoadTask from anchore_engine.services.policy_engine.engine.policy.gate import ExecutionContext from anchore_engine.services.policy_engine import _init_distro_m...
python
#!/usr/bin/python import csv import pycurl import json def insertToElasticSearch(data): esData={'year' : data[0], 'week': data[1], 'state' : data[2], 'area': data[3], 'location' : data[4], 'totalCase' :...
python
# -*- coding: utf-8 -*- # Copyright 2015 Metaswitch Networks # # 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 applicab...
python
# vim: fdm=marker ''' author: Fabio Zanini date: 11/12/14 content: Get trees of haplotype alignments. ''' # Modules import os import argparse from operator import itemgetter, attrgetter import numpy as np from matplotlib import cm import matplotlib.pyplot as plt from Bio import Phylo from hivwholeseq.pati...
python
#!/usr/bin/env python from csvkit.unicsv import UnicodeCSVReader, UnicodeCSVWriter class CSVKitReader(UnicodeCSVReader): """ A unicode-aware CSV reader with some additional features. """ pass class CSVKitWriter(UnicodeCSVWriter): """ A unicode-aware CSV writer with some additional features. ...
python
#! /usr/bin/env python from tkinter import NoDefaultRoot, Tk, ttk, filedialog from _tkinter import getbusywaitinterval from tkinter.constants import * from math import sin, pi import base64, zlib, os ################################################################################ ICON = b'eJxjYGAEQgEBBiApwZDBzMAgxsDA...
python
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os import subprocess from typing import Tuple import torch try: torch.classes.load_library( f"{os.environ['CONDA_PREFIX']}/...
python
from unittest.mock import patch from datetime import datetime import httpx import pytest from src.zever_local.inverter import ( Inverter, InverterData, ZeversolarError, ZeversolarTimeout, ) _registry_id = "EAB241277A36" _registry_key = "ZYXTBGERTXJLTSVS" _hardware_version = "M11" _software_version = ...
python
""" Tests for the game class """ import unittest import numpy as np from nashpy.algorithms.vertex_enumeration import vertex_enumeration class TestVertexEnumeration(unittest.TestCase): """ Tests for the vertex enumeration algorithm """ def test_three_by_two_vertex_enumeration(self): A = np.a...
python
#!/usr/bin/env python3 __author__ = "Will Kamp" __copyright__ = "Copyright 2013, Matrix Mariner Inc." __license__ = "BSD" __email__ = "will@mxmariner.com" __status__ = "Development" # "Prototype", "Development", or "Production" '''This is the wrapper program that ties it all together to complete this set of programs...
python
import time import numpy as np import dolfin as df from finmag.energies import Demag from finmag.field import Field from finmag.util.meshes import sphere import matplotlib.pyplot as plt radius = 5.0 maxhs = [0.2, 0.4, 0.5, 0.6, 0.7, 0.8, 0.85, 0.9, 0.95, 1.0] unit_length = 1e-9 m_0 = (1, 0, 0) Ms = 1 H_ref = np.array(...
python
from datetime import datetime, timezone from hamcrest.core.string_description import StringDescription from pytest import mark, raises from preacher.core.datetime import DatetimeWithFormat from preacher.core.verification.hamcrest import after, before ORIGIN = datetime(2019, 12, 15, 12, 34, 56, tzinfo=timezone.utc) ...
python
#!/usr/bin/env python from setuptools import setup, find_packages import dbbackup def get_requirements(): return open('requirements.txt').read().splitlines() def get_test_requirements(): return open('requirements-tests.txt').read().splitlines() keywords = [ 'django', 'database', 'media', 'backup', ...
python
from utils.rooster_utils import prediction, get_model, load_configurations, set_seed import torch import sys TARGET_SR = 44100 settings = load_configurations(mode="detector") if(settings == -1): print("Error: Failed while loading configurations") sys.exit() set_seed(settings["globals"]["seed"]) melspectrogra...
python
# Given an integer array nums, find the contiguous # subarray (containing at least one number) which # has the largest sum and return its sum. # Example: # Input: [-2,1,-3,4,-1,2,1,-5,4], # Output: 6 # Explanation: [4,-1,2,1] has the largest sum = 6. # Follow up: # If you have figured out the O(n) solution, try c...
python
from funcx_endpoint.endpoint.utils.config import Config from parsl.providers import LocalProvider config = Config( scaling_enabled=True, provider=LocalProvider( init_blocks=1, min_blocks=1, max_blocks=1, ), max_workers_per_node=2, funcx_service_address='https://api.funcx.org...
python
import abc from numpy import ndarray class AbstractGAN(abc.ABC): def __init__(self, run_dir: str, outputs_dir: str, model_dir: str, generated_datasets_dir: str, resolution: int, channels: int, epochs: int, output_save_frequency: int, model_save_frequency: int, loss_save_frequenc...
python
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import os from comnetsemu.cli import CLI, spawnXtermDocker from comnetsemu.net import Containernet, VNFManager from mininet.link import TCLink from mininet.log import info, setLogLevel from mininet.node import Controller, RemoteController if __name__ == "__main__": ...
python
import streamlit as st import pandas as pd import joblib model = joblib.load('/content/drive/MyDrive/models/cc_foodrcmdns.pkl') df = pd.read_csv('dataset/indianfoodMAIN.csv') recp_name = st.selectbox("Select Recipe", df['recp_name'].values) st.write(recp_name) def findRcmdn(value): data = [] index = df[df['...
python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn # Some utility functions def average_norm_clip(grad, clip_val): ''' Compute...
python
import gc import numpy as np import pandas as pd from datetime import datetime from functools import partial import tensorflow as tf from sklearn import preprocessing from .. import utils from ..config import cfg from .base_model import BaseModel class Graph(): '''Container class for tf.Graph and associated variab...
python
import cosypose import os import yaml from joblib import Memory from pathlib import Path import getpass import socket import torch.multiprocessing torch.multiprocessing.set_sharing_strategy('file_system') hostname = socket.gethostname() username = getpass.getuser() PROJECT_ROOT = Path(cosypose.__file__)....
python
from django.contrib.auth.models import User from django.core import mail from django.test import TestCase from hc.api.models import Check from hc.test import BaseTestCase class LogoutTestCase(BaseTestCase): def test_it_logs_out_users(self): form = {'email': 'alice@example.org', 'password': 'password'} ...
python
""" Human-explainable AI. This is the class and function reference of FACET for advanced model selection, inspection, and simulation. """ __version__ = "1.2.0" __logo__ = ( r""" _ ____ _ _ ___ __ ___ _____ _-´ _- / ___\ / \ /\ /\ /\ /\ / \ ...
python
"""LiveSimulator: This class reads in various Bro IDS logs. The class utilizes the BroLogReader and simply loops over the static bro log file, replaying rows and changing any time stamps Args: eps (int): Events Per Second that the simulator will emit events (default...
python
from unittest import TestCase from dynamic_fixtures.fixtures.basefixture import BaseFixture class BaseFixtureTestCase(TestCase): def test_load_not_implemented(self): """ Case: load is not implemented Expected: Error get raised """ fixture = BaseFixture("Name", "Module") ...
python
from empregado import Empregado class Operario(Empregado): def __init__(self, nome, endereco, telefone, codigo_setor, salario_base, imposto, valor_producao, comissao): super().__init__(nome, endereco, telefone, codigo_setor, salario_base, imposto) self._valor_producao = valor_producao self...
python
import inspect import typing from chia import instrumentation class Factory: name_to_class_mapping: typing.Optional[typing.Dict] = None default_section: typing.Optional[str] = None i_know_that_var_args_are_not_supported = False @classmethod def create(cls, config: dict, observers=(), **kwargs): ...
python
from useintest.modules.consul.consul import ConsulServiceController, consul_service_controllers, \ Consul1_0_0ServiceController, Consul0_8_4ServiceController, ConsulDockerisedService
python
import math # S1: A quick brown dog jumps over the lazy fox. # S2: A quick brown fox jumps over the lazy dog. # With the two sentences above I will implement the calculation based on calculation # values. def magnitude(v1): vResult = [abs(a * b) for a, b in zip(v1, v1)] mag = math.sqrt(sum(vResult, 0)) r...
python
import time import asyncio from typing import List import threading import numpy as np import spotipy from spotipy.oauth2 import SpotifyOAuth from eventhook import EventHook class NotPlayingError(Exception): def __init__(self): self.message = "Spotify not playing" class MonitorConfig: def __init_...
python
a, b = input().split() print("Yes" if (int(a + b) ** (1 / 2)).is_integer() else "No")
python
# pip3 install PySocks import socks import socket from urllib import request from urllib.error import URLError socks.set_default_proxy(socks.SOCKS5, '127.0.0.1', 9742) socket.socket = socks.socksocket try: response = request.urlopen('http://httpbin.org/get') print(response.read().decode('utf-8')) except URLE...
python
import torch from kondo import Spec from torchrl.experiments import BaseExperiment from torchrl.utils.storage import TransitionTupleDataset from torchrl.contrib.controllers import DDPGController class DDPGExperiment(BaseExperiment): def __init__(self, actor_lr=1e-4, critic_lr=1e-3, gamma=0.99, tau=1e...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from numap import NuMap def hello_world(element, *args, **kwargs): print "Hello element: %s " % element, print "Hello args: %s" % (args,), print "Hello kwargs: %s" % (kwargs,) return element ELEMENTS = ('element_0', 'element_1', 'element_2', 'element_3', '...
python
import collections import itertools import json from pathlib import Path import re import sqlite3 import string import attr import nltk import numpy as np def clamp(value, abs_max): value = max(-abs_max, value) value = min(abs_max, value) return value def to_dict_with_sorted_values(d, key=None): re...
python
# SPDX-FileCopyrightText: 2022 Eva Herrada for Adafruit Industries # SPDX-License-Identifier: MIT import board from kmk.kmk_keyboard import KMKKeyboard as _KMKKeyboard from kmk.matrix import DiodeOrientation class KMKKeyboard(_KMKKeyboard): row_pins = (board.D10, board.MOSI, board.MISO, board.D8) col_pins =...
python
# -*- coding: utf-8 -*- counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "John" # A string print (counter) print (miles) print (name)
python
from .tests import _index def main(): suites = _index.suites passes = 0 fails = 0 for s in suites: s.run() print(s) passes += s.passes fails += s.fails print(f'###################\nSUMMARY OF ALL TEST SUITES\nTotal Passing Tests: {passes}\nTotal Failing Tests: {fails...
python
#!/usr/bin/python # -*- coding: latin-1 -*- import os, subprocess import numpy as np import GenericUsefulScripts as GUS from astropy import units as u from astropy.io import ascii, fits from astropy.convolution import convolve from astropy.stats import SigmaClip from astropy.coordinates import SkyCoord from photutils....
python
def model_to_dicts(Schema, model): # 如果是分页器返回,需要传入model.items common_schema = Schema(many=True) # 用已继承ma.ModelSchema类的自定制类生成序列化类 output = common_schema.dump(model) # 生成可序列化对象 return output
python
"""OsservaPrezzi class for aio_osservaprezzi.""" from .const import ENDPOINT, REGIONS from .models import Station from .exceptions import ( RegionNotFoundException, StationsNotFoundException, OsservaPrezziConnectionError, OsservaPrezziException, ) from typing import Any import asyncio import aiohttp im...
python
import telebot import os TOKEN = os.getenv('TELE_TOKEN') bot = telebot.TeleBot(TOKEN) @bot.message_handler(commands=['start']) def start_message(message): markup = telebot.types.ReplyKeyboardMarkup() # start_btn = telebot.types.KeyboardButton("/start") help_btn = telebot.types.KeyboardButton("/help") ...
python
# [h] paint and arrange groups '''Paint each group of glyphs in the font with a different color.''' # debug import hTools2 reload(hTools2) if hTools2.DEBUG: import hTools2.modules.color reload(hTools2.modules.color) # import from hTools2.modules.color import paint_groups # run f = CurrentFont() paint_gr...
python