text
string
size
int64
token_count
int64
#!/usr/bin/env python3 import math import sys import os import time import pybullet as p from time import sleep import time import rospy import tf from scipy import signal import pybullet_data import rospkg from transforms3d.quaternions import quat2mat from wolfgang_pybullet_sim.terrain import Terrain import numpy as...
20,825
6,861
from torch.utils.data import Dataset, DataLoader import torchvision.transforms as transforms import random import numpy as np from PIL import Image import json import os from torchnet.meter import AUCMeter def uniform_mix_C(mixing_ratio, num_classes): ''' returns a linear interpolation of a uniform matrix and a...
11,641
3,670
#Autogenerated by ReportLab guiedit do not edit from reportlab.graphics.shapes import _DrawingEditorMixin, Drawing, Group, Rect, String from reportlab.lib.colors import Color, CMYKColor, PCMYKColor class ExplodedDrawing_Drawing(_DrawingEditorMixin,Drawing): def __init__(self,width=756.284,height=240.20000000000002,*a...
4,134
1,872
# -*- coding: utf-8 -*- import numpy as np import pytest from vecGraphComp.base import MatrixValues, ValueHolder, Block, NodeType, ExpressionWriter def test_numpy_structure_of_arrays_with_expand_dims(): m,n = 200,100 x1=np.random.random((n,1)) x2=np.random.random((n,1)) A=np.random.random((m,n)) x...
2,971
1,338
""" Curates an output STAR file from Relion to work as input for pyseg.pyorg scripts for microtubules Input: - STAR file with the particles to curate - STAR file to pair tomograms used for reconstruction with the one segmented used to pick the particles Output: - A curated output STAR file ...
6,421
2,290
import unittest from copy import deepcopy from datatypes.exceptions import DataDoesNotMatchSchemaException from datatypes import proprietor_validator from datatypes.core import unicoded proprietor = unicoded({ "title" : "Mrs", "full_name": "Bootata Smick", "decoration": "tidy" }) proprietor_with_additi...
1,954
609
from ..models.base_agent import BaseAgent class MockAgent(BaseAgent): def __init__(self, testapp, moves, game_id, player): self.testapp = testapp self.args = [] self.kwargs = [] self.moves = iter(moves) self.past_end = False super().__init__(game_id, player) de...
2,999
1,529
from selenium import webdriver import time from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException options = webdriver.ChromeOptions() options.add_argument('--disable-web-security') url='http://127...
1,888
643
''' 多重继承 - 通过多重继承可以给一个类的对象具备多方面的能力 - 这样在设计类的时候可以避免设计太多层次的复杂的继承关系 ''' class Father(object): def _init_(self, name): self._name = name def gamble(self): print('%s在打麻将.' % self._name) def eat(self): print('%s在大吃大喝.' % self._name) class Monk(object): def _init_(self, name): ...
815
424
import os import pickle import numpy as np import matplotlib.font_manager as font_manager import matplotlib.pyplot as plt import seaborn as sns # Plot sns.set(context="paper", style="whitegrid", font="STIXGeneral", font_scale=1.25) def plot(): CURRENT_PATH = os.path.dirname(os.path.realpath(__file__)) # Fi...
907
350
from django.conf import settings from django.db import models from django.shortcuts import redirect class TimeStamp(models.Model): """timestamp to capture all the time of event in the database""" created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) c...
1,661
511
from nimbusinator.nimbus import Nimbus from nimbusinator.command import Command if __name__ == '__main__': # Create and bind nimbusinator objects: nim = Nimbus(full_screen=True) cmd = Command(nim) nim.boot() # Boot the Nimbus cmd.set_mode(40) # Low resolution mode cmd.set_border(1)...
709
261
import threading def start_threading(param): print('Executa algo....') print(f'Utiliza o parâmetro recebido: {param}') return print(f'Resultado final: {param * param}') th = threading.Thread(target=start_threading, args=(5,)) th.start() th.join()
264
95
#!/usr/bin/env python3 # # SPDX-License-Identifier: Apache-2.0 # Copyright 2021, Intel Corporation # This script implements generate() method, which may be invoked by run_benchmark.py directly, # or used as standalone application, which prints configuration json (also validated against schema) # to stdout. Such once g...
2,386
783
class Endpoint: def __init__(self, domain=None): self.domain = domain def get(self): endpoint_list = ['https://outlook.office365.com/autodiscover/autodiscover.svc'] if self.domain: endpoint_list.append("https://{}/autodiscover/autodiscover.svc".format(self.domain)) ...
453
149
from collections import Counter from random import choice import numpy as np # Figuring out the roads to victory requiring the minimum number of cards to achieve victory in catan class Ledger: def __init__( self, victoryPointCondition=10, villageSettlement=1, citySettlement=2, startVillages=...
9,450
3,002
# Import all the useful libraries import numpy as np import pandas as pd import fancyimpute from sklearn import model_selection from sklearn.model_selection import StratifiedKFold from sklearn.ensemble import AdaBoostClassifier # PROBABILITY from sklearn.tree import DecisionTreeClassifier # PROBABILITY from sklearn....
29,745
11,294
import sys from bs4 import BeautifulSoup import re import urllib.request, urllib.error import xlwt # 进行Excel操作 import time def main(): Baseurl = 'https://weibo.cn/thepapernewsapp?page=' # 1.爬取网页 datalist = getdata(Baseurl) #IDlence = (len(datalist) - 1) savepath = "澎湃新闻.xls" # 3...
4,455
2,037
# -*- coding: utf-8 -*- import pyautogui as pyg import os import subprocess import programa class Mouse(object): def __init__(self, QuadroXI, QuadroYI, Dimensao): self.TEMPO = 0 #Touchpad do monitor self.QuadroXI = QuadroXI - Dimensao self.QuadroYI = QuadroYI - Dimensao + int(Dimensao/3) self.QuadroXF ...
3,273
1,668
import subprocess def check_external_packages(): try: stilts_path = subprocess.check_output(['which','stilts.sh']) except: raise ValueError('Cannot find STILTS please install and ensure it is in the shell path') try: stilts_path = subprocess.check_output(['which','sex']) ...
549
157
""" day16ab - https://adventofcode.com/2020/day/16 --- Day 16: Ticket Translation --- * Part 1 Three input files: the rules for ticket fields the numbers on your ticket the numbers on other nearby tickets The rules for ticket fields specify a list of fields that exist somewhere on the ticket and the valid r...
6,084
1,892
import random random.seed("lel") class table(object): changes= { '1':"@", '0':" " } def __init__(self, lists): self.data = lists @classmethod def gen_matix(cls, x, y): return cls( [ [random.choice((1,0)) for y in range(y)] for x in range(x) ...
712
245
''' while else loop (DEPRECATED) ''' def main(): a = False i = 0 while i < 10: i += 1 else: a = True TestError( a==True ) b = False i = 0 while i < 10: i += 1 break else: b = True TestError( b==False )
228
122
import PySide.QtGui as QtGui import PySide.QtCore as QtCore import GravitionalObject as go class Firefly(go.GravitationalObject): def __init__(self): super(Firefly, self).__init__() self._acc = QtCore.QPointF() self._vel = QtCore.QPointF() self._pos = QtCore.QPointF() ...
2,116
781
#! /usr/bin/env python3 import sys #1 DONE!!! Passed 9/10 def translate_sequence(rna_sequence, genetic_code): pass # Read and get the RNA string rna = rna_sequence.upper() print ("\n \n RNA String: ", rna) x=len(rna) if x < 3: return '' # RNA codon table(make sure you have it) protein...
14,325
5,255
from datetime import datetime, timedelta from typing import Union def parse_unix_to_date(unix_time: Union[int, float]) -> str: if unix_time == 0: return "навсегда" return (datetime.utcfromtimestamp(unix_time)+timedelta(hours=3)).strftime("до %d.%m.%Y %H:%M:%S МСК")
289
111
#!/usr/bin/env python # encoding: utf-8 # # Copyright SAS Institute # # 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 b...
4,226
1,287
from django.forms import ModelForm from django.utils.safestring import mark_safe from django.utils.html import escape from .models import DisplayReservationLine, Display class DisplayReservationLineForm(ModelForm): class Meta: model = DisplayReservationLine exclude = ('display_reservation', '...
721
201
#!C:\A_Visit\ForRegression\visit-deps\windowsbuild\MSVC2017\python\3.7.7\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'pygments==2.5.2','console_scripts','pygmentize' __requires__ = 'pygments==2.5.2' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(...
468
207
# build an automatic pizza order program. # ask the user the size and extra ingredients inputs print("Welcome to Python Pizza Deliveries!") size = input("What size pizza do you want? S, M, or L \n") add_pepperoni = input("Do you want pepperoni? Y or N \n") extra_cheese = input("Do you want extra cheese? Y or N \n") # ...
1,034
382
from Agent import * from Stream import * from MergeSplitOpStructures import * def window_many_to_many(f, in_streams, num_out_streams, window_size, step_size, state=None): def transition(in_lists, state=None): range_out = range((num_out_streams)) range_in = range(len(in_streams)) output_list...
2,091
675
#this files process commands entered through the front end from modules.sense import * from modules.mainsystem import * def Pcommand(command): command=command.lower() if command.startswith("speak"): #speak function to debug command=command.replace("","speak") speak(command) elif command.star...
623
171
def get_maximums(set): fuz_set = [(set.membership(x), x) for x in set] fuz_set.sort() fuz_set = [x for (ux, x) in fuz_set if ux == fuz_set[-1][0]] fuz_set.sort() return fuz_set
197
92
import os import dill import unittest import collections from pyjob import Script from swamp.utils import remove from swamp.mr.mrjob import MrJob RESULTS = collections.namedtuple('results', ['results']) WORKDIR = os.path.join(os.environ['CCP4_SCR'], 'test_workdir') class MrJobTestCase(unittest.TestCase): def te...
2,177
805
import math import numpy as np from torch.utils.data import Subset from .strategy import Strategy class PartitionStrategy(Strategy): """ Provides a wrapper around most of the strategies implemented in DISTIL that allows one to select portions of the budget from specific partitions of the unlabeled d...
6,306
1,670
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2019/8/2 @Author : AnNing """ import os from lib.lib_path import get_aid_path, GFSSI_DIR aid_path = get_aid_path() # 无效数据的填充值 FULL_VALUE = -999 # 辅助文件 BASEMAP_FY4_4KM = os.path.join(aid_path, 'ditu_fy4a_4km.png') LON_LAT_LUT_FY4_4KM = os.path.join(aid_pat...
2,120
1,402
import logging from django.test.runner import DiscoverRunner class TestRunner(DiscoverRunner): """ When migrations are disabled for the test runner, the `pre_migrate` signal does not emit. So we need another hook for installing the extension. Prior to Django 1.9, the `pre_syncdb` signal worked for that. ...
1,647
446
import re from foliant.preprocessors.apireferences.apireferences import DEFAULT_REF_REGEX from foliant.preprocessors.apireferences.classes import Reference from unittest import TestCase class TestReference(TestCase): def test_repr_doesnt_throw_errors(self): ref = Reference( source='`MyAPI: GE...
3,706
1,132
import math DEBUG = 1 PARKING_NODE_COLOR = '#FF0099' EXIT_NODE_COLOR = 'r' STREET_NODE_COLOR = 'g' COP_NODE_COLOR = '#3c3ccc' VISUAL = 1 COP_MODE = 0 COP_INTERSECTION_THRESHOLD = 0 COP_CONGESTION_THRESHOLD = 0.5 COP_EVACUATION_THRESHOLD = 0 DEPTH_OF_AWARENESS = 1 EAST_TENDENCY = 0 SPACE_TIME_TRADEOFF = 1 DEAD_END = [] ...
460
258
from selenium import webdriver import time driver = webdriver.Chrome() driver.get('http://localhost/se/33.html') driver.execute_script("document.body.style.zoom = '1.5'") time.sleep(1) driver.find_element_by_css_selector('button').click() time.sleep(1) driver.switch_to_alert().accept() time.sleep(1) driver.close()
316
111
# coding=utf-8 # Copyright 2021 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...
3,611
1,214
import gym import torch.nn as nn import torch.nn.functional as F import numpy as np import deep_rl.deepq as deepq from deep_rl import register_trainer class Model(nn.Module): def __init__(self): super().__init__() def init_weights(m): if type(m) == nn.Linear: nn.init....
1,515
523
from django.http import Http404 from django.shortcuts import render # Create your views here. from django.contrib.auth.models import User, Group from rest_framework import views, status from rest_framework.response import Response from account.serializers import * class ListCustomers(views.APIView): def get(se...
3,314
922
from setuptools import setup, find_packages install_requires = [ 'numpy>=1.17.0', 'scipy>=1.4.1', 'mpi4py>=3.0', 'matplotlib>=3.1.3' ] extras_requires = { 'docs': [ 'sphinx' ], 'tests': [ 'tox', ] } def long_description(): with open('README.rst') as f: ret...
1,063
400
#!/usr/bin/env python3 def add_numbers(*args): total = 0 for arg in args: total += arg print(total) add_numbers(3) add_numbers(3, 2) add_numbers(1, 3, 5, 6, 7, 8)
185
83
# Update the code to have a function that reads in the file and returns contents as a list def open_sample_func(sample_text): with open(sample_text) as file: lines = file.readlines() return lines # Update the code to have a function that converts the list of book lines into a list of the words def ...
2,590
726
import mitogen.core import testlib import simple_pkg.ping # TODO: this is a joke. 2/3 interop is one of the hardest bits to get right. # There should be 100 tests in this file. class TwoThreeCompatTest(testlib.RouterMixin, testlib.TestCase): if mitogen.core.PY3: python_path = 'python2' else: ...
648
221
import glob, os from cococonvert import convert_csv_labels, convert_csv_outputs from cocoeval import COCO, COCOeval import sys class StdoutRedirection: """Standard output redirection context manager""" def __init__(self, path): self._path = path def __enter__(self): sys.stdout = open(se...
1,439
541
# # Jogo da Velha utilizando Visao Computacional e Realidade aumentada. # Definicao de funcoes auxiliares # import numpy as np # Funcao que verifica se e o fim do jogo. def won(tabuleiro): if (tabuleiro[0] == tabuleiro[1] == tabuleiro[2] == 0): return 1 elif (tabuleiro[0] == tabuleiro[3] == tabuleiro...
3,076
1,417
#! /usr/bin/env python3 import discord from discord.ext import commands import subprocess import re import os, sys import json import basic import datetime import traceback import iksm_discord TOKEN = basic.DISCORD_TOKENS["0"] startup_extensions = ["splat"] # cogの導入 description = f"stat.inkへ戦績自動アップロードを行うbotです。\nまずはs...
1,407
607
from tls.CustomEnums import UInt8Enum class Alert(Exception): def __init__(self, level, description): self.level = level self.description = description class AlertLevel(UInt8Enum): warning = 1 fatal = 2 class AlertDescription(UInt8Enum): close_notify = 0 unexpected_message = 10...
1,019
366
from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse, JsonResponse, Http404 from django.contrib.auth.decorators import login_required from django.core.exceptions import ObjectDoesNotExist from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from ...
21,922
6,385
from . import ( users, search, )
41
16
import time from typing import Any, Callable, List, Optional from google.protobuf.timestamp_pb2 import Timestamp from optur.errors import NotFoundError from optur.proto.study_pb2 import StudyInfo from optur.proto.study_pb2 import Trial as TrialProto from optur.storages.backends.backend import StorageBackend def _re...
7,806
2,191
import atexit import os from os.path import join import shutil import tempfile from pymclevel import mclevel __author__ = 'Rio' tempdir = os.path.join(tempfile.gettempdir(), "pymclevel_test") if not os.path.exists(tempdir): os.mkdir(tempdir) def mktemp(suffix): td = tempfile.mkdtemp(suffix, dir=tempdir) ...
1,394
434
import itertools from loguru import logger from opensearchpy.helpers import scan as os_scan from oss_know.libs.base_dict.opensearch_index import OPENSEARCH_INDEX_GITHUB_COMMITS, \ OPENSEARCH_INDEX_GITHUB_ISSUES_TIMELINE from oss_know.libs.util.opensearch_api import OpensearchAPI from oss_know.libs.util.base import ...
5,157
1,549
# Copyright (c) 2014, Stanford University # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the ...
10,274
3,144
import glob from shutil import copyfile emotions = ["neutral", "anger", "contempt", "disgust", "fear", "happy", "sadness", "surprise"] # Define emotion order participants = glob.glob("source_emotion\\*") # Returns a list of all folders with participant numbers for x in participants: part = "%s" % x[-4:] ...
1,457
455
from .Runtime import Runtime from .Type import Type from .Instance import Instance
83
20
from django.conf.urls import url, include from apps.BlogContent.views import SeeBP urlpatterns = [ url(r'^MyBlogs', SeeBP.as_view() , name='see_BP'), ]
156
60
from app.core import create_app app = create_app('flask.cfg')
62
22
#!/usr/bin/env python3 """ Makes UCL PHAS results better """ __author__ = "Hayk Khachatryan" __version__ = "0.1.4.4" __license__ = "MIT" import argparse import csv import sys import itertools import pathlib as pathlib import inquirer ######################### # # # # # ...
13,549
3,778
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 6 11:36:49 2021 @author: Jose Antonio """ import random from networkx.algorithms.isomorphism import is_isomorphic from dmg.graphUtils import edge_match_type as edge_match from dmg.graphUtils import node_match_type as node_match import networkx as ...
1,981
607
""" The Pipeline object in sci-kit learn is very useful for constructing simple and complex modeling pipelines. However, out of the box it is cumbersome to build pipelines that involve heterogenous data. Most transformers assume that the entirety of the input datasets are of the same dtype. So, how do y...
14,689
3,928
from django.urls import path, include from rest_framework_simplejwt import views as jwt_views from .views import (RegisterUserView) AUTH_PATTERNS = [ path('token/', jwt_views.TokenObtainPairView.as_view(), name='token-obtain'), path('token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token-refresh') ...
455
152
from dataclasses import dataclass from typing import Tuple, Any, List, Union import ruamel.yaml from ruamel.yaml.constructor import SafeConstructor import dacite import numpy as np @dataclass class CornerSelectionConfig: """ Config for the corner selection phase of KLT """ quality_level: float mi...
4,598
1,434
def map_squares(numbers): """ :param numbers: list of numbers :return: square of the numbers """ return list(map(lambda x: x ** 2, numbers))
161
51
from html_url_extractor import HtmlUrlExtractor from request_getter import RequestGetter from sitemap_fetcher import SitemapFetcher from urlparse import urljoin class UrlFetcher(object): """ Handles url fetching from both html source and sitemaps """ def __init__(self, request_limit=10): self.html_url...
1,400
414
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import Session from ec_config import SQLITE_PATH, MYSQL_HOST, MYSQL_USER, MYSQL_PASS Base = declarative_base() engine = None def connect(db_name): global engine if db_name.startswith('sqlite:'):...
7,207
2,321
# -*- coding: utf-8 -*- """alert controlller.""" from typing import Any, Dict, List, Literal, Optional, Sequence, Tuple, overload from flask_sqlalchemy import Pagination from chaos_genius.databases.models.alert_model import Alert ALERT_CHANNELS = { "email": "E-mail", "slack": "Slack", } """A mapping of chann...
2,995
967
from kivy.app import App from kivy.uix.behaviors import button from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label class teste(App): def build(self): #Interface box = BoxLayout( orientation='vertical') button=Butt...
783
257
"""Provides Flask Forms related functionality.""" from wtforms import SelectField, BooleanField from flask_wtf import FlaskForm from webapp import config def _get_pbf_gb_choices(): """Prepares list of PBF size choices for drop-down menu. Returns ------------------------- pbf_gb_choices : list ...
1,160
387
# 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 # d...
1,798
675
""" """ try: from stage_check import Output except ImportError: import Output class Base(Output.Base): """ """ def __init__(self): super().__init__() self.__full_name = "OutputRedundancyDatabaseConn.Base" self.status = Output.Status.OK """ no_node_data """ def proc_no_node_d...
2,776
817
class DBTable(object): def __init__(self, db_location: str): self._db_location = db_location
105
33
IMPORTANT = b'important' NOT_IMPORTANT = b'not-important' SHOULD_BE_IMPORTANT = b'should-be-important' SHOULD_BE_NOT_IMPORTANT = b'should-be-not-important' RETRAIN = b'retrain' RELABEL = b'relabel' DELETED = b'\\Deleted'
221
102
from type_mappers import *
27
9
from django.db import models class Pick(models.Model): reason = models.CharField(max_length=30, default='', verbose_name='사유') comment = models.TextField(default='', verbose_name='덧글') member = models.ForeignKey('MEMBER.Member', on_delete=models.CASCADE) product = models.ForeignKey('PRODUCT.Product', o...
504
174
def test_add(): assert 1 + 2 == 3, "bad add" def test_sub(): assert 2 - 1 == 1, "bad sub" def test_sub_fail(): assert 2 - 2 == 1, "bad sub"
154
71
# Copyright 2020 Alibaba Group Holding Limited. 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 ...
5,134
1,640
import torch from torch import Tensor from torch.nn.utils.rnn import pad_sequence from typing import List, Optional __all__ = [ 'to_tensor', 'truncate', 'add_token', ] def to_tensor(input: List[List[int]], padding_value: Optional[int] = None) -> Tensor: if padding_value is None: output = torc...
1,099
360
#!/usr/bin/env python ''' Simple script to add a device to the database. ''' from ZensorDevice import ZensorDevice from enumerations import * import sys import random def main(argv): if len(argv) != 2: print "Usage:", argv[0], "<device_id>" return -1 devid = sys.argv[1] device = ZensorDev...
913
284
########################################################################## # # Copyright (c) 2012, John Haddon. All rights reserved. # Copyright (c) 2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that ...
6,901
2,439
from django.conf import settings from django.test import TestCase from django.test.utils import override_settings from copy import deepcopy from .. import models as testapps_models from .. import factories as testapps_factories class StackStoreManagerTest(TestCase): def test_delete(self): with self.asser...
5,881
1,739
""" A sample python script that illustrates how to use the gcm module. As a first step, we need to find the model's parameters - c,w,b (we will assume r = 2). This is done using MLE. After we find the parameters, we use them to find the corresponding probabilities using the functions from the gcm module. The following ...
6,915
2,348
from qiskit import * import matplotlib.pyplot as plt import numpy as np # define the oracle circuit oracle = QuantumCircuit(2, name='oracle') oracle.cz(0,1) -> cz-matrix ((1,0,0,0), (0,1,0,0), (0,0,1,0), (0,0,0,1)) oracle.to_gate() backend = Aer.get_backend('statevector_simulator') reflect = QuantumCircuit(2, name ...
948
421
from sympy.crypto.crypto import (alphabet_of_cipher, cycle_list, encipher_shift, encipher_affine, encipher_substitution, encipher_vigenere, decipher_vigenere, bifid5_square, bifid6_square, bifid7_square, encipher_hill, decipher_hill, encipher_bifid5, encipher_bifid6, encipher_bifid7, decip...
687
295
import json from typing import Tuple, List class Config: """Config stack layers - Default config - Model default config - Load from config file - User argument config """ size = (300, 300) ssd_attributes = ['feature_map', 'steps', 'sizes', 'aspect_ratios'] ssd = { "aspec...
2,656
932
#!/usr/bin/python # -*- coding: utf8 -*- from datetime import datetime from base_test_case import BaseTestCase from models import Goal from flow import app as tst_app from models import Habit, Task import json import imp try: imp.find_module('secrets', ['settings']) except ImportError: from settings import sec...
5,200
1,348
import sys from kivy.app import App from kivy.uix.anchorlayout import AnchorLayout from kivy.properties import * from replication import recover_progression_binary from kivy.clock import Clock class Binary(AnchorLayout): ''' Manage binaries download window ''' progress = ObjectProperty() def ini...
937
276
import json from django.contrib.gis.db import models class Geo(models.Model): STATE_TYPE, COUNTY_TYPE, TRACT_TYPE, METRO_TYPE, MICRO_TYPE = range(1, 6) METDIV_TYPE, = range(6, 7) TYPES = [(STATE_TYPE, 'State'), (COUNTY_TYPE, 'County'), (TRACT_TYPE, 'Census Tract'), (METRO_TYPE, 'Metropolitan...
3,019
925
import collections import os counter = collections.Counter() dir_name = 'accent_archive' text_file_name = 'reading-passage.txt' print('creating dictionary from "{}"'.format(os.path.join(dir_name, 'AA_unpacked', text_file_name))) # The Accent Archive uses the same text transcript for every audio recording text ...
2,798
1,036
import string import struct from necroassembler.exceptions import NotInBitRange, InvalidBitRange def neg_fix(value, bits): negative = 1 << (bits - 1) if value & negative: return -(1 << (bits)) + value return value def pack_byte(*args): return struct.pack('B' * len(args), *[n & 0xff if n is n...
5,308
1,772
import torch import torch.nn as nn import torchvision.models as models import torch.nn.functional as F import math class EncoderCNN(nn.Module): def __init__(self, embed_size): super(EncoderCNN, self).__init__() resnet = models.resnet50(pretrained=True) for param in resnet.parameters(): ...
3,367
1,016
""" Stage is a way to serialize data flows. Data Flow is a sequence (list, generator) of (metadata, content) tuples. Metadata is a key-value dictionary with several key names reserved: ``rubric``, ``name``, ``part``, `format``, and ``payload``. Content is useful application data (payload) or miscellaneous informatio...
724
197
from .libs.sh import verbose
29
9
import json import logging import os from abc import ABC, abstractmethod import pandas as pd from typing import List from running_modes.configurations.general_configuration_envelope import GeneralConfigurationEnvelope from running_modes.configurations.logging.scoring_log_configuration import ScoringLoggerConfiguratio...
3,585
1,054
from django.conf import settings from django.utils.translation import ugettext_lazy as _ from ....payment import PaymentProvider, PaymentFailure, PaymentType from . import forms from . import models import stripe import datetime class StripeProvider(PaymentProvider): form_class = forms.StripeReceiptForm pay...
2,697
766
import json import logging import os import time import boto3 import mail # Set up logging log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) def _get_sfn_execution_name(reservation): """ Generate a human-readable execution named composed of the passenger's check in details followed by a tim...
2,424
720
import a9a.encoder import a9a.decoder import a9a.dir_reader import a9a.dir_writer class Archive: def __init__(self, nodes=None): if nodes is None: nodes = {} self.content = nodes def to_bytes(self): return b"a9a\n" + encoder.encode_nodes(self.content) def __repr__(sel...
723
251