text
string
size
int64
token_count
int64
import pytest from copy import deepcopy from indy_node.test import waits from stp_core.loop.eventually import eventually from plenum.common.constants import VERSION, NAME from plenum.common.util import randomString from plenum.test.test_node import checkNodesConnected from indy_common.constants import SHA256, CANCEL, ...
4,146
1,409
import sys import os sys.path.insert(0, os.path.abspath('..')) import json from urobot.helper import * from urobot import Beeper, World, Wall, Position, JsonDrawer def turn_right(): for i in range(3): robot.turn_left() world = World(walls=[Wall(Position(1, 0), Position(2, 0))], drawer=JsonDrawer()) beepe...
811
336
from xml.dom import minidom import os # We firt create a minidom document. root = minidom.Document() # Names the main element 'root' of the dom. xml = root.createElement('root') # We insert it on the file. root.appendChild(xml) # Creates the secondary element 'product'. productChild = root.createElement('product') #...
690
223
from math import factorial def solve(n: int=100) -> str: return sum(int(digit) for digit in str(factorial(n)))
117
43
from tests.test import WebTest from models import Test from database import db_session from datetime import datetime from lxml import html import requests class SoftwareTest(WebTest): def __init__(self, scan): self.scan = scan def init(self): self.test = Test(scan_id=self.scan.id, name="HEAD...
1,139
335
# Generated by Django 2.0 on 2017-12-09 01:04 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('grades', '0002_auto_20171209_0901'), ] operations = [ migrations.RenameModel( old_name='Grdes', new_name='Grades', ), ...
326
127
import copy from pure_mcts.keyset import KeySet from pure_mcts.mcts_dpw import MCTSStochastic, StochasticAction, StochasticState import numpy as np from race_components.race_ol_uct import strategic_rollout from helpers import (argmax, is_atari_game, copy_atari_state, restore_atari_state, stable_normalizer) class Ra...
6,803
1,993
from configuration import settings # pylint: disable=no-name-in-module from common.helpers import get_player def run_command(message, message_content, session): subcommand = ' '.join(message_content.split(" ")[1:2]) if len(message_content.split(" ")) > 1 else None player = get_player(session, message.author....
1,708
462
from setuptools import setup setup( name="foyer-cookiecutter", version="0.0.0", description="A Cookiecutter template for creating foyer recipes", author="Ray Matsumoto", author_email="ray.a.matsumoto@vanderbilt.edu" )
263
85
#!/usr/bin/env python3 from generator import gen_url import sys try: cant = int(sys.argv[1]) except: cant = 5 try: valormagico = int(sys.argv[2]) except: valormagico = 20 gen_url(cant, True, valormagico)
222
92
import statistics # importa a biblioteca de estatística do python import PySimpleGUI as sg import matplotlib.pyplot as plt global amt amt:int = 0 while amt <= 0: sg.theme('DarkGreen6') # Add some color to the window # Very basic window. Return values using auto numbered keys layout = [ [sg....
5,653
2,379
#!/usr/bin/env python # coding: utf-8 from django.contrib.auth.models import User from django.core.management.base import BaseCommand, CommandError from django.utils.translation import ugettext_lazy from onadata.apps.logger.models import XForm from onadata.libs.utils.logger_tools import mongo_sync_status class Comma...
2,318
585
""" soapdenovo2_map.py A wrapper script for SOAPdenovo2 map module Copyright Peter Li - GigaScience and BGI-HK """ import optparse, os, shutil, subprocess, sys, tempfile def stop_err(msg): sys.stderr.write(msg) sys.exit() def cleanup_before_exit(tmp_dir): if tmp_dir and os.path.exists(tmp_dir): ...
4,626
1,620
import logging from terra import util_terra from terra.execute_type import ( _execute_type, ) from .borrow import ( handle_deposit_borrow, handle_repay_withdraw, ) def handle(exporter, elem, txinfo, index): execute_msg = util_terra._execute_msg(elem, index) if "send" in execute_msg: msg = ...
758
240
import os import shutil import time import json import execute_func_oracle empresas = 1 socios = 1 cnaes_sec = 1 qualif_socio = 1 natu_jur = 1 motivos_situ = 1 PATH_RFB_ANTIGOS = 'rfb_antigos/' PATH_DATA = 'data/' PATH_OUTPUT = 'output/' date_start = time.strftime("%Y-%m-%d") if not os.path.isdir(PATH_RFB_ANTIGOS): ...
3,387
1,502
#!/usr/bin/python import itertools # Ctrl + C to interrupt for i in itertools.count(100, 2): print(i) # if i > 20: # break
148
63
__title__ = 'yc-secret' __description__ = 'Library for interaction with the Yandex Cloud Lockbox service' __version__ = '0.1.2' __author__ = 'Aksyanov Rustam' __author_email__ = 'rustam@akrustam.com' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2022 Aksyanov Rustam' __url__ = 'https://yc-secret.readthedocs.io'...
321
127
# # run.py - the base code that is run # # # some hardcoded locations for things # import os from sys import argv from math import copysign import matplotlib.pyplot as plt import pickle import numpy # Hard coded directories. Please change these accordingly. imageJjarName = '/Users/ainglis/Applications/ImageJ-platI...
6,288
2,289
# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# import sys import tsvIO # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# NA_VALUE = -999999 # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# def dupClinInfo(dataD): ...
3,601
1,410
"""All the models that are used in the experiments: Mixture of Experts (MoE)(Alternative) with/out shared weights Predictive U-Net (PU-Net) Predictive Mixture of Experts (PMoE) """ from pathlib import Path import sys try: sys.path.append(str(Path("../").resolve())) except: raise RuntimeError("Can't append root...
14,731
4,781
from unittest import TestCase import json import textwrap class TestIndent(TestCase): def test_indent(self): h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth', {'nifty': 87}, {'field': 'yes', 'morefield': False} ] expect = textwrap.dedent("""\ [ ...
1,094
443
import csv from django.core.management.base import BaseCommand from django.conf import settings from django.db import reset_queries from django.db.models import Sum from filing.models import xml_submission, master_observed_xpath, observed_xpath, known_version_string from filing.schema_name_utils import get_version_...
2,008
638
from seleniumpm.webelements.element import Element class TextElement(Element): def __init__(self, driver, locator): super(TextElement, self).__init__(driver, locator)
181
53
# -*- coding: utf-8 -*- from django.core import signing from rest_framework import permissions from .signing import unsign_filters_and_actions class SignedPermission(permissions.BasePermission): """ Allow access to a particular set of filters if the sign is valid. This permission allows access to sets ...
2,401
617
import numpy as np from tor4 import tensor def test_tensor_from_scalar(): a = tensor(data=1) assert a.tolist() == 1 assert not a.requires_grad assert a.is_leaf a = tensor(data=2.0, requires_grad=True) assert a.tolist() == 2.0 assert a.requires_grad assert a.is_leaf def test_tensor_...
713
294
def factors(value:int) -> list[int]: factors = [] factor = 2 # Starting at 2, calculate all the factors of `value`. while value > 1: if (value / factor).is_integer(): factors.append(factor) value = int(value / factor) else: factor += 1 return fact...
324
94
# -*- coding: utf-8 -*- # utopia-cms Markup Language import markdown import re from django.template import Library from django.template.loader import render_to_string from django.template.defaultfilters import stringfilter from django.utils.encoding import force_unicode from django.utils.safestring import mark_safe fr...
3,772
1,284
import os from pathlib import Path from click.testing import CliRunner from tests.conftest import load_class from tests.conftest import validate_bindings from xsdata import cli os.chdir(Path(__file__).parent.parent.parent) def test_integration(): schema = Path("tests/fixtures/defxmlschema/chapter10/chapter10....
5,043
1,682
import random class Food(): def __init__(self, width, height): self.rangeX = (0,width-1) self.rangeY = (0,height-1) self.actual_food = [ random.randint(self.rangeX[0], self.rangeX[1]), random.randint(self.rangeY[0], self.rangeY[1]) ] def generate_food(...
676
245
from setuptools import setup, find_packages setup( name='pysqlar', version='0.1.2', description='Pure Python library for working with SQLite Archives.', long_description="""# pysqlar Module for working with [SQLite Archive files](https://www.sqlite.org/sqlar.html) with an API mimicking the zipfile mo...
790
252
import logging import warnings from datetime import datetime, timezone from pathlib import Path import gsw import numpy as np import pandas as pd import scipy.signal as sig from . import get_ctdcal_config, io, oxy_fitting cfg = get_ctdcal_config() log = logging.getLogger(__name__) warnings.filterwarnings("ignore", ...
28,722
9,534
#! /usr/bin/env -S python3 -u """This script verifies the behavior of the AnalogIn instruments channel range settings.""" import numpy as np import matplotlib.pyplot as plt import random from pydwf import DwfLibrary # (1) changing the attenuation changes that setting, but also the channel offset and range. # (2) c...
4,887
1,575
#! /usr/bin/env python """ Copyright 2015 Akamai Technologies, Inc. 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 Unle...
9,748
2,977
import math from pickle import TRUE from tabnanny import verbose import torch import torch.nn as nn import torch.nn.functional as F from .resnet import resnet18 from .factory import create_model from .registry import register_model from .helpers import build_model_with_cfg from timm.data import IMAGENET_DEFAULT_MEAN, I...
6,298
2,368
# -*- coding: utf-8 -*- """ testing login using scrapy 1. start_reqeust do the init fetch, get the form data back 2. parse_login then fill the user and pass field in the form, by doing this, url change to dashboard, nor sign_in 3. parse the dashboard page Note that, run from command line and pass the user and pass...
1,576
457
""" Project Euler - Problem Solution 018 Copyright (c) Justin McGettigan. All rights reserved. https://github.com/jwmcgettigan/project-euler-solutions """ triangle = ''' 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47...
1,093
627
from flask import Flask, flash, redirect, render_template, Response, request, session, abort from imutils import paths import face_recognition import pickle import cv2 import os import shutil import pandas as pd import csv import numpy as np import os import matplotlib import matplotlib.pyplot as plt impor...
22,598
8,043
import csv from pandas import read_csv from app.controllers.controller import ControllerBase from calc.calculator import Calculator from flask import render_template, request, flash, redirect, url_for class CalculatorController(ControllerBase): @staticmethod def post(): if request.form['value1'] == ''...
2,074
523
print("Minion Game") palabra = input("introducir cadena de caracteres: ") kevin = [] manolo=[] def p (): for i in palabra: if i == "a" or i == "e" or i == "i" or i == "o" or i == "u": kevin.append(i) print("kevin",kevin) for i in palabra: if i != "a" and i != "e" and...
688
262
"""Artificial States""" # Author: Lucas David -- <ld492@drexel.edu> # License: MIT (c) 2016 import abc import copy as copy_lib import six class State(object): """State. Keeps track of episodic updates in the environment, maintaining a sequence through a recursive reference to parent states. A...
5,321
1,453
from defcfg import JBoxDefaultConfigVol __author__ = 'tan'
60
20
# # Hello World server in Python # Binds REP socket to tcp://*:5555 # Expects b"Hello" from client, replies with b"World" # import time import zmq context = zmq.Context() socket = context.socket(zmq.PULL) socket.bind("tcp://*:5555") socket2 = context.socket(zmq.PUSH) socket2.connect("tcp://localhost:5556") # w...
892
320
#!/usr/bin/env python # coding: utf-8 import pandas as pd def open_data(file, info = False): """ Open the data and transform it in a DataFrame Arguments : file : CSV to read and convert into a pandas DataFrame info = False : Bool...
2,482
579
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 19 09:40:58 2020 Image enhancement functions @author: Vasileios Vonikakis (bbonik@gmail.com) """ import math import imageio import numpy as np import matplotlib.pyplot as plt from skimage.color import rgb2gray from skimage import img_as_float from...
65,509
21,105
import configparser import logging import os from fotobox.misc import generate_timestamp from fotobox.file_system import ROOT_PATH, mkdir_if_not_exist # reading config file CONFIG = configparser.ConfigParser() CONFIG.sections() CONFIG.read(os.path.join(ROOT_PATH, 'config.ini')) # initialize logging LOG_PATH = os.path...
617
219
# -*- coding: utf-8 -*- from maya import cmds from . import common from . import lang from . import qt import maya.api.OpenMaya as om import traceback import json import os import imp import copy import math try: imp.find_module('PySide2') from PySide2.QtWidgets import * from PySide2.QtGui import * from...
16,284
5,931
"""Create a task for a given queue with an arbitrary payload.""" import logging from google.cloud import tasks_v2beta3 from google.protobuf import timestamp_pb2 import settings def insert_task(handler, queue, payload=None): client = tasks_v2beta3.CloudTasksClient() parent = client.queue_path(settings.GCP_P...
1,310
377
from urllib.request import Request, urlopen, build_opener, HTTPCookieProcessor from urllib.parse import urlencode #import ssl import json from http import cookiejar from getpass import getpass import re import pickle import os class Session: def __init__(self, client_id, client_secret, customer_id, ...
5,327
1,558
# importing the Python-provided time library to access delays (time.sleep) import time # importing the Subinitial library to access the Stacks commands import subinitial.stacks as stacks # Connecting to the Stacks Core and Analog Deck core = stacks.Core(host="192.168.1.49") analogdeck = stacks.AnalogDeck(core_deck=co...
839
303
from rest_framework import routers from user_profile.views import UserProfileViewSet user_profile_router = routers.DefaultRouter() user_profile_router.register('', UserProfileViewSet)
186
51
#!/usr/bin/env python3 # Copyright 2018-present, HKUST-KnowComp. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """Functions for putting examples into torch format.""" from collections import Counter import torch def ve...
6,649
2,445
from knot_hash import knot_hash def day14b(data): used_spaces = set() for i in range(128): row = data + '-' + str(i) hash = knot_hash(row) bin_string = bin(int(hash, 16))[2:] while len(bin_string) < 128: bin_string = '0'+bin_string for ch in range(l...
1,571
550
import math import time from itertools import count import cloudpickle import torch import torch.nn.functional as F from torch import nn import utils SQRT2 = math.sqrt(2.0) ACT = nn.ReLU class DQN(nn.Module): def __init__(self, in_channels=4, n_actions=14): super(DQN, self).__init__() self.conv...
23,787
7,695
#!/usr/bin/env python3 import io import os import argparse # Imports the Google Cloud client library from google.cloud import translate # Instantiates a client translate_client = translate.Client() parser = argparse.ArgumentParser(description='Uploads and gets provided text file to/from Google translate API') parse...
1,126
346
#!/usr/bin/env python2 # -*- coding: iso-8859-1 -*- # # Copyright (C) 2020 John de Rooij # # This software is licensed as described in the file LICENSE, which # you should have received as part of this distribution. from setuptools import find_packages, setup with open("README.md", "r") as fh: long_description =...
1,472
488
import pytest from nws_wwa import get_all, get_hazards, get_warnings @pytest.mark.vcr() def test_all(): get_all() @pytest.mark.vcr() def test_hazards(): get_hazards() @pytest.mark.vcr() def test_warnings(): get_warnings()
241
106
from node import Node class List: def __init__(self): self.head: Node = None self.tail: Node = None def isEmpty(self)->bool: return self.head is None def numberOfElements(self)->int: if self.isEmpty(): return 0 else: current: Node = self.hea...
4,333
1,058
from .kernel import kernel
27
7
VAR01 = "" VAR02 = "hello" VAR03 = '' VAR04 = 'hi' VAR05 = "\"" VAR06 = '\'' VAR07 = "'''" VAR08 = '"""' VAR21 = r"" VAR22 = u"hello" VAR23 = R'' VAR24 = U'hi' VAR25 = b"\"" VAR26 = B'\'' VAR27 = br"'''" VAR28 = Br'"""' VAR29 = bR"hello" VAR30 = BR"hello" # Python >= 3.3 VAR31 = rb"hello" VAR32 = rB"hello" VAR33 = Rb...
574
299
# Copyright 2020 Verizon Inc. # Licensed under the terms of the Apache License 2.0. # See LICENSE file in project root for terms. import pytest import time from safecache import CacheExpired from safecache import safecache def test_bug_expiration_ttl(): """Bug expiration equality check was reversed and immutabl...
695
248
import luigi from tasks.process.log_analysis import GenerateCrawlLogReports from tasks.common import logger class GenerateCrawlReport(luigi.Task): """ """ task_namespace = 'scan' job = luigi.Parameter() launch = luigi.Parameter() #def requires(self): # return GenerateCrawlLogReports(se...
542
197
# This python script accesses Tello's camera, takes off, and then detects markers to perform certain commands # In this case we detect marker id 33 and do a forward flip while marker id 1 commands Tello to land # Modify this script to suit your needs and feel free to open a GitHub issue with any questions import cv2 i...
3,766
1,214
print('COCO YOLO annotation translations') def convert(size, box): dw = 1. / size[0] dh = 1. / size[1] x = (box[0] + box[1]) / 2.0 y = (box[2] + box[3]) / 2.0 w = box[1] - box[0] h = box[3] - box[2] x = x * dw w = w * dw y = y * dh h = h * dh return (x, y, w, h) ann_file ...
675
319
# -*- coding: utf-8 -*- """ Mostrar la trayectoria, velocidad y aceleración de un movimiento rectilíneo uniformemente variado. """ import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation # Limpiar la terminal from IPython import get_ipython get_ipython().magic('clear') # Sol...
4,254
1,614
import os import base64 import io import pandas as pd import geopandas as gpd from shapely.geometry import Polygon import numpy as np import plotly.graph_objs as go from shapely.geometry import Point from gisele.functions import * from gisele.functions2 import * from gisele import initialization, clustering, processing...
10,733
3,903
""" Implements objects for calling Version APIs """ __author__ = 'Don Thorp' __email__ = 'don@donthorp.net' __since__ = '2012-03-23' import sys from . import api try: import poster except ImportError: print "You need to install poster.\n use: sudo pip install poster\n" sys.exit(1) class AppVersions(ap...
4,853
1,508
import machine, motor, bot, time print('creating i2c and motors ...') i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4)) motors = motor.DCMotors(i2c) #creates motors object LEFT=0 #M0 - left motor RIGHT=3 #M4 - right motor print('creating robot ...') robot = bot.Robot(motors, LEFT, RIGHT) # creates robot dt =...
846
361
import datetime from sqlalchemy import Text from app import db class Category(db.Model): __table_args__ = {"extend_existing": True} __tablename__ = 'category' def to_json(self): item = self.__dict__ if "_sa_instance_state" in item: del item["_sa_instance_state"] retu...
1,965
668
from csv import reader as csv_reader def parse_phosphosite(phoshosite_file, organism): """ Parses the phosphocite tsv file :param phoshosite_file: :param organism: :return: """ base = [] ret_dict = {} with open(phoshosite_file, 'rt', encoding='latin-1') as source: # usage...
949
300
# -*- coding: utf-8 -*- import numpy from numpy.random import randint, choice from pymatgen.analysis.structure_matcher import StructureMatcher from pymatgen.analysis.elasticity.strain import Strain, convert_strain_to_deformation from pymatgen.transformations.standard_transformations import ( PerturbStructureTrans...
33,652
9,171
#!/usr/bin/python #-*-coding:UTF-8-*- import datetime import urllib2 today_str = datetime.datetime.now().strftime('%Y%m%d') strStockCode = 'sz399001' #strStockCode = 'sh000001' url = 'http://qt.gtimg.cn/q='+strStockCode req = urllib2.Request(url) resp = urllib2.urlopen(req) response = resp.read() stockdate_str = res...
437
195
import librosa import numpy as np # from scipy.fftpack import dct import pdb # If you want to see the spectrogram picture import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def plot_spectrogram(spec, note, file_name): """Draw the spectrogram picture :param spec: a feature_dim by num...
6,319
2,535
##@package main #@author Sebastien MATHIEU import sys, getopt, os import src.options as options import src.tools as tools from src.system import System ## Entry point of the program. def main(argv): # Read instance folder if len(argv) < 1 : displayHelp() sys.exit(2) folderPath=argv[-1] ...
2,484
1,000
import datetime from datetime import date from django.test import TestCase from mock import patch from custom.icds_reports.reports.bihar_api import get_mother_details from custom.icds_reports.tasks import update_bihar_api_table @patch( 'custom.icds_reports.utils.aggregation_helpers.distributed.bihar_api_demogra...
13,031
4,874
class User: """TODO: potentially switch to slack official api client: https://github.com/slackapi/python-slackclient""" def __init__(self, slack_id: str, slack_name: str = None, **kwargs): self.slack_id, self.slack_name = slack_id, slack_name for k, v in kwargs.items(): setattr(self...
998
354
# catalog.management # Management commands for the catalog app. # # Author: Benjamin Bengfort <bbengfort@districtdatalabs.com> # Created: Sun Aug 23 21:17:10 2015 -0500 # # Copyright (C) 2015 District Data Labs # For license information, see LICENSE.txt # # ID: __init__.py [] benjamin@bengfort.com $ """ Management ...
516
153
# tests/test_provider_sethvargo_filesystem.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:16:21 UTC) def test_provider_import(): import terrascript.provider.sethvargo.filesystem def test_resource_import(): from terrascript.resource.sethvargo.filesystem import filesystem_file_reader f...
824
271
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"Field_on_grid": "field_on_grid.ipynb", "NTHREAD": "field_on_grid.ipynb", "EPS": "field_on_grid.ipynb"} modules = ["field_on_grid.py"] doc_url = "https://{saitosmst}.github.io/two_point_cl...
452
186
from .history import TensorboardCallback, ExcelMetricsLogger, History
70
17
import qrencode import StringIO import Image def qrcode_stream(text, pixel_size=8, format='png', **kwargs): (version, size, im) = qrcode_scale(qrencode.encode(text, **kwargs), pixel_size) buf = StringIO.StringIO() #qrencode.encode_scaled(text, size, **kwargs)[2].save(buf, format=format) # AllanC - en...
1,925
681
import os import sys import pickle import matplotlib.pyplot as plt import numpy as np import h5py import argparse from sklearn.decomposition import PCA from sklearn.linear_model import LinearRegression from matplotlib.colors import Normalize sys.path.insert(0, os.getcwd()) from src.utils.helpers import * import statsmo...
7,106
2,469
from adventofcode.year_2015.day_09_2015 import get_all_routes, get_all_cities, get_fastest_route, get_slowest_route test_input = [ 'London to Dublin = 464', 'London to Belfast = 518', 'Dublin to Belfast = 141', ] def test_get_all_cities(): dist_dict = {} expected_dist_dict = { ('London', ...
2,007
772
from doltpy.cli import Dolt from typing import List import pytest from doltpy.cli.write import write_rows, CREATE, UPDATE from .helpers import compare_rows_helper from doltpy.cli.read import read_rows, read_pandas, read_columns from doltpy.shared.helpers import columns_to_rows def compare_rows_helper(expected: List[di...
3,215
1,180
''' This is the evaluation code modified from the originally released code. 1) Remove dependency on Polygon library 2) Fix input prediction format to x0,y0,x1,y1,... ''' import file_util import numpy as np import math import cv2 project_root = '../../' pred_root = project_root + 'results/submit_msra/' gt_root = proj...
3,402
1,285
from django.contrib import admin from .models import Receipt # Register your models here. admin.site.register(Receipt)
118
31
import torch import torch.nn as nn class Model(nn.Module): def __init__(self, input_dim, output_class_num, **kwargs): super(Model, self).__init__() self.linear = nn.Linear(input_dim, output_class_num) def forward(self, features): pooled = features.mean(dim=1) predicted = self....
360
118
from collections import defaultdict import os import random import time import pandas as pd def main(): base_path = '/Volumes/Passport-1/data/shakespeare-and-co' results_directory_path = base_path + '/query-results' combined_results_path = base_path + '/goodreads_query_results.combined.csv' df_lis...
587
201
import re import requests from saq.proxy import proxies class Phishfry(): def __init__(self, server, version): self.server = server self.version = version self.session = requests.Session() self.session.headers.update({ 'Content-Type': 'text/xml; charset=utf-8', ...
8,849
2,583
#!/usr/bin/env python ''' Copyright (c) 2011 Joseph Lewis <joehms22@gmail.com> 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 2 of the License, or (at your opt...
20,010
5,910
import numpy as np from scipy.signal import hamming from typing import List def amplify_signal(signal: np.ndarray, emphasis: float): return np.append(signal[0], signal[1:] - emphasis * signal[:-1]) def frame_signal(signal: np.ndarray, window_size: int, stride: int) -> np.ndarray: frames: List[np.ndarray] = ...
759
276
from . import items import csv class Exit(items.Item): REVERSAL_GUIDE = { "north": "south", "south": "north", "east": "west", "west": "east", "up": "down", "down": "up", "n": "s", "s": "n", "e": "w", "w": "e" } def __init...
6,367
1,764
""" Data visualization, Compare learning rates File name: jpyter/src/lrnratediff.py Author: József Varga Date created: 4/07/2020 See dtavis.py CSV header : timestep,reward,episode,timestamp """ import io from urllib.request import urlopen import pandas as pd import seaborn as sns import matpl...
1,038
442
import pytest import atc_chain.utils.bls as bls from atc_chain.utils.blake import blake @pytest.fixture(scope="session") def privkeys(): return [int.from_bytes(blake(str(i).encode('utf-8'))[:4], 'big') for i in range(1000)] @pytest.fixture(scope="session") def keymap(privkeys): keymap = {} for i, k in ...
543
213
""" Make a glacier class which uses fortran's code The main difference with pyglacier.wrapper's Glacier class is that the latter does not store state information (instead, all is in fortran), whereas the Glacier class of this module is a true class, which can be duplicated and so on, and all necessary state informatio...
18,885
5,949
#!/usr/bin/env python3 from prime_factors import prime_factors from random_integer_generator import generator import numpy as np import time def main(): input_number = np.arange(1,1001,1) decomp_data = [] for i in input_number: print("---------------------------") print(i, "inputs") generator1 = generator(i) ...
828
319
from concurrent.futures import ThreadPoolExecutor from pprint import pprint from tabnanny import verbose from time import sleep from requests import request from core.engines import discovered_engines, discovered_plugins from core.engines.coreEngine import CoreEngine from core.engines.HttpBuzzEngine import BytesIOSock...
5,326
1,483
import argparse from pathlib import Path parser = argparse.ArgumentParser(description= "Filename checker for matching name with other extension" ) parser.add_argument('--dirPath', '-d', help='Directory Path') parser.add_argument('--firstExtension', '-fe', help='matching file extension') parser.add_argumen...
1,110
346
from django.apps import AppConfig class BuyStudentConfig(AppConfig): name = 'buy_student'
96
31
class Test: def __init__(self): print('Constructor execution..') t=Test() t1=Test() t2=Test()
97
39
import unittest import adventofcode.adv_10 as adv SAMPLE_INPUT = """value 5 goes to bot 2 bot 2 gives low to bot 1 and high to bot 0 value 3 goes to bot 1 bot 1 gives low to output 1 and high to bot 0 bot 0 gives low to output 2 and high to output 0 value 2 goes to bot 2""".splitlines() class Test10(unittest.TestCas...
831
307