content
stringlengths
5
1.05M
#! /usr/bin/env python3 from typing import List, Tuple, Dict, T # Linked List class Node : val : int nxt : T def __init__(self, val) : self.val = val self.nxt = None class CupGame : head: Node ndes: List[Node] def __init__(self, ls: List[int]) -> None : self.ndes = ...
#!/usr/bin/env python u""" test_coordinates.py (08/2020) Verify forward and backwards coordinate conversions """ import warnings import pytest import numpy as np import pyTMD.convert_ll_xy #-- parameterize projections @pytest.mark.parametrize("PROJ", ['3031','CATS2008','3976','PSNorth','4326']) #-- PURPOSE: verify for...
# # PySNMP MIB module CISCO-UBE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-UBE-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:14:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
# coding: utf-8 """ Metal API This is the API for Equinix Metal. The API allows you to programmatically interact with all of your Equinix Metal resources, including devices, networks, addresses, organizations, projects, and your user account. The official API docs are hosted at <https://metal.equinix.com/dev...
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------ # file: $Id$ # lib: genemail.sender # auth: Philip J Grabner <grabner@cadit.com> # date: 2013/07/09 # copy: (C) Copyright 2013 Cadit Health Inc., All Rights Reserved. #-----------------------------------------------...
# -*- coding: utf-8 -*- # # Copyright (C) 2020 alzp. # # testInvenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Default configuration for testInvenio. You overwrite and set instance-specific configuration by either: - Configu...
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
# -*- coding: utf-8 -*- ## Demonstration of Link with multiple outputs: Combined-Heat-and-Power (CHP) with fixed heat-power ratio # # For a CHP with a more complicated heat-power feasible operational area, see https://pypsa.readthedocs.io/en/latest/examples/power-to-gas-boiler-chp.html. # # This example demonstrates a ...
import argparse import math import numpy as np import torch from torch import nn from basicsr.archs.stylegan2_arch import StyleGAN2Generator from basicsr.metrics.fid import (calculate_fid, extract_inception_features, load_patched_inception_v3) def calculate_stylegan2_fid(): devic...
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
import unittest import networkx as nx from core.placement.swsolver import RecShortestWalkSolver class TestShorthestWalkSolverMethods(unittest.TestCase): def setUp(self): self.g1 = nx.read_weighted_edgelist('tests/test_graph_2.txt', create_using=nx.MultiDiGraph, nodetype=int) def test_shortest_walk(se...
# 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 # distributed under the...
from fourparts.commons.Orbit import Orbit import pytest def test_cases(): orbit_1 = [1, 2, 3] orbit_2 = ("X", "Y", "Z", "T") return [ ([1], 0, [1]), (orbit_1, 0, [1, 2, 3]), (orbit_1, 1, [2, 3, 1]), (orbit_2, 3, ["T", "X", "Y", "Z"]), ] @pytest.mark.parametrize("orbi...
from flask import jsonify from flask import Flask,request from flaskext.mysql import MySQL from flask_cors import CORS, cross_origin mysql = MySQL() app = Flask(__name__) CORS(app) app.config['MYSQL_DATABASE_USER'] = 'demo' app.config['MYSQL_DATABASE_PASSWORD'] = '37cnit73' app.config['MYSQL_DATABASE_DB'] = 'mysql'...
texto = '' print(f'Resultado: {texto}') texto = str(input('Escreva algo: ')) print(f'Resultado: {texto}') texto = 4 print(f'Resultado: {texto}')
import json import logging import faker from .coordinator import CoordinatorAgent from .passenger import PassengerAgent from .taxi import TaxiAgent logger = logging.getLogger() faker_factory = faker.Factory.create() class Scenario(object): """ A scenario object reads a file with a JSON representation of a...
# -*- coding: utf-8 -*- { "name" : "POS Repair Order", "summary" : "POS Repair Order.", "category" : "Point Of Sale", "version" : "1.0.0", "author" : "Prolitus Technologies Pvt. Ltd.", "license" : "Other proprietary", ...
# Created byMartin.cz # Copyright (c) Martin Strohalm. All rights reserved. import pero class DrawTest(pero.Graphics): """Test case for text properties drawing.""" def draw(self, canvas, *args, **kwargs): """Draws the test.""" # clear canvas canvas.fill(pero.color...
# Generated by Django 3.1 on 2021-01-21 10:40 import django.db.models.deletion from django.db import migrations, models import elearn.models class Migration(migrations.Migration): dependencies = [ ('elearn', '0011_auto_20210108_0028'), ] operations = [ migrations.CreateModel( ...
from typing import Callable import socketio import config class SocketClient(): def __init__(self) -> None: super().__init__() self.on_exercise_data_received: Callable[[dict], None] = None self.on_duration_received: Callable[[int], None] = None self.on_idle_received: Callable[[bool...
# MIT License # # Copyright (c) 2019 Nihaal Sangha (Orangutan) # # 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, c...
""" Copyright (c) 2016-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. An additional grant of patent rights can be found in the PATENTS file in the same directory. """ import grpc import logging ...
#!/usr/bin/env python3 # Import standard modules ... import glob # Import special modules ... try: import PIL import PIL.Image except: raise Exception("\"PIL\" is not installed; run \"pip install --user Pillow\"") from None # Import my modules ... try: import pyguymer3 import pyguymer3.image exce...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import logging import sys from typing import Dict from ml.rl.evaluation.evaluator import Evaluator from ml.rl.preprocessing.normalization import ( construct_action_scale_tensor, get_num_output_features, ) from ml.rl...
import numpy as np from gensim.models import KeyedVectors from resources import EMBEDDING_PATH from sklearn.metrics.pairwise import cosine_similarity def averageEmbedding(model,sentence,lowercase=True): if lowercase: sentence = sentence.lower() vecs = [] for w in sentence.split(): # assume it's already tok...
import hashlib import json def get_hash(block): """ Creates a SHA-256 hash of a Block :param block: Block """ # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes block_string = json.dumps(block, sort_keys=True).encode() return hashlib.sha256(block_string)...
print(1/3) # Division returns float, even dividing two ints.
# encoding: UTF-8 """ 横盘突破策略 注意事项:作者不对交易盈利做任何保证,策略代码仅供参考 """ from __future__ import division import numpy as np import talib import time from cyvn.trader.vtObject import VtBarData from cyvn.trader.vtConstant import EMPTY_STRING from cyvn.trader.app.ctaStrategy.ctaTemplate import (CtaTemplate, ...
import re from typing import Optional, List from controller.helpers import get_player_colour from data import enums, params, consts from data.enums import ResponseFlags as rF from state.game import GameState from state.context import context from lib.amongUsParser.gameEngine import PlayerClass UNKNOWN = "unknown" c...
# -*- coding: utf-8 -*- ''' :codeauthor: Pedro Algarvio (pedro@algarvio.me) :copyright: Copyright 2017 by the SaltStack Team, see AUTHORS for more details. tests.unit.beacons.test_status ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Status beacon test cases ''' # Python libs from __future__ import absolute_imp...
from .attention import Attention from .ffnn import Ffnn from .mu_sigma_ffnn import MuSigmaFfnn from .decoders.pointer_gen_network import PointerGenNetwork from .out_embds import OutEmbds
import os import gym from stable_baselines3 import PPO from stable_baselines3.common.vec_env import DummyVecEnv from stable_baselines3.common.callbacks import EvalCallback, StopTrainingOnRewardThreshold from stable_baselines3.common.evaluation import evaluate_policy # VARIABLES environment_name = 'CartPole-v0' log_pat...
# -*- coding: utf-8 -*- """ Created on Sat Jun 29 19:34:04 2019 @author: Administrator """ class Solution: def generatePossibleNextMoves(self, s: str) -> list: ans = [] tmp = list(s) for k in range(len(tmp)-1): if tmp[k] == '+' and tmp[k+1] == '+': tmp[k] = '-' ...
import numpy as np import cv2 def predict_puzzle(model, img_path): image = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) crop_size = int((image.shape[0]) / 9) crops = [] for col in range(9): for row in range(9): crop = image[int(col * crop_size): int(col * crop_size + crop_size), ...
from pysyne.draw import Path from pysyne.visualizer import vis_for from pysyne.processor import Processor, WINDOW_TYPES, window_type from pysyne.main import main
# "print" test from wrap import * def printTest(objet): for i in range(1,30): print("-", end=' ') print("\nPrint test of", objet) for i in range(1,30): print("-", end=' ') print('') exec('print '+objet) #import apps.qs.cont2; #domain = apps.qs.cont2.getDomain() import apps.ale.qsUzi; domain = a...
from abc import ABC, abstractmethod from osp.core.session.registry import Registry from osp.core.session.result import returns_query_result class Session(ABC): """ Abstract Base Class for all Sessions. Defines the common standard API and sets the registry. """ def __init__(self): self._re...
import sys str = sys.stdin.readline() print str
from string import ascii_lowercase, digits ships = [("Carrier", 5), ("Battleship", 4), ("Cruiser", 3), ("Submarine",2), ("Destroyer", 2)] def parse_ship_location(loc): loc = loc.lower().strip().replace(" ", "") row = ascii_lowercase.index(loc[0]) col = digits.index(lo...
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root # for full license information. # ============================================================================== from __future__ import division import numpy as np from ..learners import * from .....
# coding=utf-8 # Copyright 2021 The HuggingFace Inc. team. # # 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...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.externals import joblib from sklearn.neural_network import MLPClassifier def input_data(age, sex, chest_pain_type, rest_blood_pressure, serum_cholestrol, high_fasting_blood_sugar, resting_ecg, max_heart_rate, exercise_...
import numpy as np import torch EPS = 1e-12 def embedded_dropout(embed, words, dropout=0.1, scale=None): if dropout: mask = embed.weight.data.new(embed.weight.size(0), 1).bernoulli_(1 - dropout) masked_embed_weight = mask * embed.weight / (1 - dropout) if EPS: masked_embed_weight.masked_fill_(m...
# pylint: disable=protected-access """Backend for three terms recursion generator.""" import numpy def ttr_call(self, order, dist): "TTR call backend wrapper" assert order.shape == (len(dist), self.size) graph = self.graph self.dist, dist_ = dist, self.dist graph.add_node(dist, key=order) if...
#!/usr/bin/env python3 import glob import subprocess import sys import os os.chdir(os.path.dirname(__file__)); os.chdir('..') for name in glob.glob('tests/*.nim'): if 'flycheck_' in name: continue lines = open(name).read().splitlines() if not (lines and lines[0].startswith('# TEST.')): if lines an...
# Generated by Django 3.1.2 on 2021-02-07 22:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('gui', '0007_patientdemographic_mrn'), ] operations = [ migrations.CreateModel( name='Timeline', fields=[ ...
'''test methods for the OrbitalBallRoller class in the rolling ball package ''' from nose.tools import raises from RollingBall import rolling_ball class TestBallRollerInstantiation(): '''test the orbital ball roller object instantiation ''' def test_ball_roller_object(self): '''test successful in...
#!/usr/bin/env python class Solution: def replaceBlank(self, str): print(str) res = '' for char in str: if char == ' ': res += '%20' else: res += char return res if __name__ == '__main__': str = "Hello Python World!" ...
import uuid import pickle as pickle import os, json import pika from .io import * import logging from datetime import datetime class EngineRule: def __init__(self, type, field_name, global_name=None): self.Type = type if self.Type not in ["replace","remove"]: raise ValueError("%s rule t...
# TieRopes.py def tieRopes(K, A): # Devuelve el numero de sogas atadas o no # que son mayores o iguales a k numSogas = 0 largo = 0 for i in A: largo += i # Se van atando sumando los largos if largo >= K: numSogas += 1 largo = 0 return numSog...
# -*- coding: utf-8 -*- """ Convert files with uniform grid to netcdf4 @author: rringuet, 2022 Date: 2020-05-05 00:00 Model: TS18 Bin: Esw 1.1 mV/m, Bang 178 deg., tilt 13.1 deg. Grid: Uniform (lat_step: 1.00, lon_step: 2.00 [deg]) MLAT [deg] MLT [hr] Pot [kV] Vazm [deg] Vmag [m/s] ----------...
# -*- coding: utf-8 -*- try: from urllib import urlopen except ImportError: from urllib.request import urlopen import sys import zipfile import tarfile import io import os import distutils.log import ctypes if ctypes.sizeof(ctypes.c_void_p) == 8: PLATFORM = 'x64' else: PLATFORM = 'x86' DEBUG = os.p...
'''FBAS definition helpers''' def get_hierarchical_base_definition(n_orgs, t_orgs, n_nodes, t_nodes): '''Get quorum slice definition for n_orgs orgs with n_node nodes each''' return { 'threshold': t_orgs, 'nodes': set(), 'children_definitions': [ { 'threshold...
from .dictionary import DictionaryTree from typing import Dict __all__ = ('Translator',) class Translator: def __init__(self, trees: Dict[str, DictionaryTree], use: str = None): assert len(trees) > 0 self.trees = trees self.all_uses = list(trees.keys()) if not use or use not in ...
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # 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...
# Copyright 2021 Zefeng Zhu # # 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...
from stable_baselines3.ppo.policies import CnnPolicy, MlpPolicy from stable_baselines3.ppo.ppo import PPO
import time from selenium import webdriver browser = webdriver.Chrome() browser.get("http://www.seleniumframework.com/python-course/") browser.implicitly_wait(10) browser.maximize_window() # click the subscribe button subscribe = browser.find_element_by_xpath('//*[@id="text-11"]/div/form/input[3]').click() # Get th...
from collections import OrderedDict from django.core.paginator import InvalidPage from rest_framework import status from rest_framework.exceptions import NotFound from rest_framework.pagination import _positive_int from rest_framework_datatables.pagination import DatatablesPageNumberPagination, DatatablesMixin from re...
import json import os from copy import deepcopy from django.core.files.uploadedfile import UploadedFile from django.core.management.base import BaseCommand from couchforms.models import DefaultAuthContext from corehq.apps.hqadmin.management.commands.export_domain_forms_raw import ( FormMetadata, ) from corehq.ap...
import json import fileinput import os import struct import numpy as np import matplotlib.pyplot as plt from math import pow ##def read_data(void): ## temp="" ### C:\\Users\LeeBruce\Desktop\\idkp1-10.txt def delete_black(FileName): file1 = open(FileName, 'r', encoding='utf-8') # 要去掉空行的文件 fi...
import numpy as np import matplotlib.pyplot as plt import matplotlib.cm import matplotlib.colors # named colors WHITE = "#ffffff" BLACK = "#000000" BLUE = "#1f77b4" # matplotlib C0 ORANGE = "#ff7f0e" # matplotlib C1 GREEN = "#2ca02c" # matplotlib C2 RED = "#d62728" # matplotlib C3 PURPLE = "#9467bd" # matplotlib...
""" Helper function for parsing config file """ import configparser import logging from logging.config import fileConfig # Setup logging fileConfig('log_config.ini') logger = logging.getLogger() conf_file = '/var/crackq/files/crackq.conf' def hc_conf(): """ Parse config file and return dictionary of...
####################################################### # Takes esigner360 chart and repository index # finds newest version in the repository # iterates throu dependencies and if there is newer dependency, # it is updated ####################################################### from requests.models import HTTPBasicA...
#encoding=utf-8 import datetime, time import re def get_year_start_end(): import calendar day_now = time.localtime() day_begin = '%d-01-01' % (day_now.tm_year) # 月初肯定是1号 wday, monthRange = calendar.monthrange(day_now.tm_year, 12) day_end = '%d-12-%02d' % (day_now.tm_year,monthRange) return d...
import warnings import numpy as np import pandas as pd import pymc3 as pm import arviz as az import theano.tensor as tt from gumbi.utils.misc import assert_in, assert_is_subset from gumbi.utils.gp_utils import get_ℓ_prior from gumbi.aggregation import DataSet from gumbi.arrays import * from gumbi.arrays...
from pyDOE2 import * import pandas as pd import os from scipy import stats def ci(exp, metric): if '1' in exp: design = ff2n(2) batch_column = [row[0] for row in design] epochs_column = [row[1] for row in design] else: design = ff2n(4) cores_column = [row[0] for...
# -*- coding: UTF-8 -*- """ literature """ __version__ = '4.0' content = { 'book_headline': [ '<#book_pseudoscience_author#>','<#book_pseudoscience_title#>','<#book_pseudoscientific#>', '<#book_title_front#>', ], 'book_section': ['Books', 'Books', 'Books', 'Books', 'Books', 'Books', ...
import imagehash from PIL import Image from skimage.measure import compare_ssim from imagehash import average_hash, phash, dhash, whash from mir_eval.separation import bss_eval_sources_framewise from neural_loop_combiner.config import settings def ssim_similarity(array_1, array_2): if len(array_1) > len(array_2)...
''' This is to convert letters to numbers when calculations occur ''' dictionar_of_letters_to_numbers = { 'a': 1, 'b': 2, 'c': 3, 'd':4, 'e': 5, 'f': 6, 'g':7, 'h': 8 } ''' This is to save the corrdinates of where the user pressed, in order to promote the pawn to the correct piece ''' promotion_piece ...
import pyaudio import time import wave def start_recording(): chunk = 1024 sample_format = pyaudio.paInt16 channels = 2 fs = 44100 seconds = 3 filename = "./require/roll_call.wav" p = pyaudio.PyAudio() print("Recoding : \n") inp...
import json import logging from six.moves.urllib.parse import urlencode import django from django.core.exceptions import MiddlewareNotUsed from django.http import HttpResponse from django.shortcuts import redirect from django.urls import reverse try: from django.utils.deprecation import MiddlewareMixin except: #...
from SpotifyView import SpotifyMainView import time import functools import os class SpotifyCtrl: def __init__(self, model, view): self.get_data = model self.view = view self.connect_signals() def _saveSong(self): name = self.view.inputFile() if name: folder...
from __future__ import print_function, division import sys from ...py3k_compat import urlopen, BytesIO, url_content_length def bytes_to_string(nbytes): if nbytes < 1024: return '%ib' % nbytes nbytes /= 1024. if nbytes < 1024: return '%.1fkb' % nbytes nbytes /= 1024. if nbytes <...
"""NLRN model for denoise dataset """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import models def update_argparser(parser): models.update_argparser(parser) args, _ = parser.parse_known_args() parser.add_argument( ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Stuff that should eventually go into a model.cfg file. """ import os # to-do: get these inputs from command line or config file model_path = '/data02/MyArchive/aisteer_3Dencoders/models/gashydrates_enhancer' if not os.path.exists(model_path): os.makedirs(model...
# Miyu (2041007) | Ludibrium Hair Salon (220000004) # Male: 36000 - 36990 (Eastern Rocker to Big Point) # Female: 38000 - 38990 (Harmony to Glam Shiny) from net.swordie.ms.loaders import StringData options = [] al = chr.getAvatarData().getAvatarLook() hairColour = al.getHair() % 10 if al.getGender() == 0: baseI...
import pytest from sqlalchemy import create_engine from cthaeh.models import Base from cthaeh.session import Session @pytest.fixture(scope="session") def engine(): # PRO-TIP: Set `echo=True` for lots more SQL debug log output. return create_engine("sqlite:///:memory:", echo=False) @pytest.fixture(scope="se...
###################################### # this files processes the social distancing data by considering the # number of devices that are completely at home within a census block group # https://docs.safegraph.com/docs/social-distancing-metrics # zhizhenzhong@csail.mit.edu ###################################### import ...
from .annealing import Ketcham1999, Ketcham2007 from .structures import Grain, Sample from .viewer import Viewer from .age_calculations import calculate_central_age as central_age from .age_calculations import calculate_pooled_age as pooled_age from .age_calculations import calculate_ages as single_grain_ages from .age...
"""Defines Averager class.""" import collections class Averager(object): """Keeps a running average with limited history.""" def __init__(self, max_count): """Initialize the averager with maximum number of (latest) samples to keep.""" self._max_count = max_count if max_count > 1 else...
# -*- coding: utf-8 -*- """ Created on Tue Sep 25 11:50:05 2018 @author: kennedy """ __author__ = "kennedy Czar" __email__ = "kennedyczar@gmail.com" __version__ = '1.0' import os class Data_collector(object): def __init__(self, path): ''' :Argument: :path: Enter the w...
import logging import yaml import logging.config import os import argparse with open('config/log_config.yaml', 'r') as stream: config = yaml.load(stream, Loader=yaml.FullLoader) # get path to logs file in config and create folder if not already created log_path = config['handlers']['file']['filename'] ...
import warnings from typing import IO, Tuple, Mapping, List, Dict, TextIO, Union from importlib import import_module from click.utils import LazyFile from yaml import safe_dump, safe_load from faker.providers import BaseProvider as FakerProvider from .data_gen_exceptions import DataGenNameError from .output_streams i...
# coding=utf-8 import codecs def calculate(x,y,id2word,id2tag,res=[]): entity=[] for j in range(len(x)): if x[j]==0 or y[j]==0: continue if id2tag[y[j]][0]=='B': entity=[id2word[x[j]]+'/'+id2tag[y[j]]] elif id2tag[y[j]][0]=='M' and len(entity)!=0 and entity[-1].sp...
import json from app.api.mines.mine.models.mine_disturbance_code import MineDisturbanceCode def test_get_all_mine_disturbance_types(test_client, db_session, auth_headers): disturbances = MineDisturbanceCode.query.filter_by(active_ind=True).all() disturbance_codes = map(lambda c: c.mine_disturbance_code, dist...
import numpy as np from PIL import Image import pandas as pd import cv2 import sys import os import json print(os.path.dirname(os.path.realpath(__file__))) sys.path.append(os.path.dirname(os.path.realpath(__file__)) ) print(sys.path) from bentoml import api, artifacts, env, BentoService from bentoml.artifact import K...
from django.urls import path from . import views from django.views.generic.base import TemplateView urlpatterns = { path('add_annotation', views.add_annotation), path('getChatGroupPapers', views.getChatGroupPapers), path('getChatGroupMembers', views.getChatGroupMembers), path('createChatGroup', views.c...
import threading import requests import argparse from time import sleep """ArgParse for CLI input""" parser=argparse.ArgumentParser(description='WebProbe V0.1') parser.add_argument('-f','--filename',type=str,required=True,help="Specify filename.") parser.add_argument('-t','--threads',type=int,const=5,nargs='?',help="...
from myModules.github.github_api import gitApi import requests class Repo: def __init__(self, user, repo=None): self.rep = self.getRepos(user, repo) def getRepos(self, owner, repo): """ get Json data :param owner: the user :param repo: the repository """ ...
from m5ui import * import utime as time import random clear_bg(0x111111) rgb = RGB_Bar() btnA = M5Button(name="ButtonA", text="ButtonA", visibility=False) btnB = M5Button(name="ButtonB", text="ButtonB", visibility=False) btnC = M5Button(name="ButtonC", text="ButtonC", visibility=False) ##############################...
from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class BinTree: def printTree(self,root:TreeNode)->None: LevelList = [root] self.printLevel(LevelList) def printLevel(self,LevelList:...
import requests from bs4 import BeautifulSoup as bs class SejongAuth: def __init__(self): self.TIMEOUT_SEC = 10 def do_sejong(self, id: str, pw: str): header = { "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5)\ AppleWebKit 537.36 (KHTML, like Gecko) Chrom...
import os import io import httpretty class APIMock(): """ Responses should be a {method: filename} map """ def __init__(self, mock_url, mock_dir, responses): self.mock_url = mock_url self.responses = responses self.mock_dir = mock_dir def request_callback(self, request, ur...
import random import math from typing import NamedTuple import uuid from timeit import default_timer as timer from datetime import datetime import numba as nb import numpy as np import pandas as pd from .scenario import Scenario from .evse import EVSEType, EVSEDef, Bank from .powertrain import Powertrain, PType fro...
import requests from bs4 import BeautifulSoup # function to return index of second longest element def second_longest(listi): new_list = listi.copy() new_list.remove(max(new_list)) return listi.index(max(new_list)) # function to get lyrics def get_lyrics(song): url = requests.get('https://www.azlyrics...
""" byceps.blueprints.site.authentication.login.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from flask import abort, g, request, url_for from flask_babel import gettext from .....services.authentication....
from hk_sp import * from numberGen import generate class SpData(): def createData(self): enabled = [1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0] hk_packet = bytearray(hk_sp_enabled(enabled)) hk_packet.extend(hk_sp_errors([1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0])) hk_packe...
import pytest from django.conf import settings from django_fsm_log.models import StateLog pytestmark = pytest.mark.ignore_article def test_log_not_created_if_model_ignored(article): assert len(StateLog.objects.all()) == 0 article.submit() article.save() assert len(StateLog.objects.all()) == 0 de...
import os import pandas as pd import json from tqdm import tqdm DATA_DIR = os.path.join(os.environ['data'], 'allstate') # Collect arguments (if any) parser = argparse.ArgumentParser() # Data directory parser.add_argument('--data_dir', type=str, default=DATA_DIR, help='Path to the csv files.') args = parser.parse_ar...