text
string
size
int64
token_count
int64
import os import pytest import sys from time import time try: thisdir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(thisdir, '..')) except: sys.path.append('..') import trinomial def test_basic(): trinomial.set_unique_key('x') assert trinomial.anon('foo@bar.com') == ...
501
205
# -*- coding: utf-8 -*- from openprocurement.api.utils import opresource from openprocurement.tender.openua.views.award_complaint_document import TenderUaAwardComplaintDocumentResource @opresource(name='Tender EU Award Complaint Documents', collection_path='/tenders/{tender_id}/awards/{award_id}/complaint...
667
211
# -*- coding: utf-8 -*- from __future__ import print_function, division import torch import torch.nn as nn def get_acti_func(acti_func, params): acti_func = acti_func.lower() if(acti_func == 'relu'): inplace = params.get('relu_inplace', False) return nn.ReLU(inplace) elif(acti_func == 'l...
2,398
931
# Copyright 2021 Amado Tejada # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
3,359
1,041
# -*- coding: utf-8 -*- """ Created on Tue May 26 14:29:26 2020 @author: Walter Dempsey & Jamie Yap """ #%% ############################################################################### # Build a RJMCMC class ############################################################################### from pymc import Stochast...
3,183
1,004
from unittest.mock import MagicMock from slack.user import User from baseball.team import Team reusableUser = User(token='blah', id='UB00123', team=None) testTeam = Team(abbreviation='CN', location='City Name', full_name='City Name Players', record='0W-162L', division='CL Beast', wins=0, losses=162, standing=5...
2,021
781
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, with_statement import os import sys import logging import time import kaptan from .. import Window, config, exc from ..workspacebuilder import WorkspaceBuilder, freeze from .helpers import TmuxTestCase logger = logging.getLogger...
1,934
614
# -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import import os import tensorflow as tf import math """ GCL + OMEGA = 180 / 512. {'0.6': {'ground-track-field': 0.573582489319409, 'harbor': 0.3891521609424017, 'bridge': 0.2563337419887201, 'small-vehicle': 0.5648505388890961, 'plane'...
9,132
5,817
""" Test cases for AST calculator """ from unittest import TestCase from calc import evaluate class TestCaclEvaluate(TestCase): """ Test cases for AST calculator - evaluation """ def test_simple_expression(self): """ Test expression without functions or constants """ ...
1,488
412
from flask import request from app.main.extensions import cache def clear_cache(key_prefix): keys = [key for key in cache.cache._cache.keys() if key.startswith(key_prefix)] cache.delete_many(*keys) def cache_json_keys(): json_data = tuple(sorted(request.get_json().items())) return json_data
315
101
# -*- coding: utf-8 -*- from __future__ import unicode_literals from gum.utils import elasticsearch_connection class ElasticsearchManager(object): """Like a `ModelManager` gives to the user methods to apply queries to Elasticsearch from a specific model. """ def __init__(self, model=None, mapping_ty...
1,931
529
import pickle import json import numpy as np from flask import Flask, request, jsonify app = Flask(__name__) with open('models/regressor.pkl', 'rb') as f: model = pickle.load(f) def __process_input(posted_data) -> np.array: ''' transforms JSON type data acquired from request and transforms it into 2D ...
1,732
542
#!/usr/bin/python # -*- coding: utf-8 -*- import rospy import math from sensor_msgs.msg import * from geometry_msgs.msg import * from sobit_bringup.msg import * #---グローバル変数----------------------------- motion = [0]*21 TIME = 0.1 serial_joint = Serial_motion() state_jointstate = JointState() state_jointstate.name =["...
4,734
2,560
#!/usr/bin/env python """ # Author: Xiong Lei # Created Time : Thu 10 Jan 2019 07:38:10 PM CST # File Name: metrics.py # Description: """ import numpy as np import scipy from sklearn.neighbors import NearestNeighbors, KNeighborsRegressor def batch_entropy_mixing_score(data, batches, n_neighbors=100, n_pools=100, n...
2,789
962
from miniciti.bilding import Bilding class ColorBilding(Bilding): def __init__(self, color="bli"): self.color = color def isBli(self): return self.color == "bli"
189
67
import pandas as pd import random import time # Source: https://stackoverflow.com/a/553320/556935 def str_time_prop(start, end, date_format, prop): """Get a time at a proportion of a range of two formatted times. start and end should be strings specifying times formated in the given format (strftime-styl...
2,603
894
#!/usr/bin/env python3 ''' #ccpc20qhd-f => 最大联通子图 #如果都是联通的,所有节点都要放进去, #友好值=联通子图中边的个数-点的个数 #应该所有(友好值>0)联通子图加起来? #DFS搜索,或者是并查集? 数一数有多少联通块? #最短路用广搜,全部解用深搜 连通图的复杂度是O(V+E).. 为什么会Runtime Error? 分析: 解法1: DFS做联通块 解法2: 看不包含哪些人,相当于走个捷径! ''' def f(n,l): el = [[] for _ in range(n)] for x,y in l: if x>y...
1,317
619
import unittest import pandas as pd from code.feature_extraction.list_counter import PhotosNum, URLsNum, HashtagNum, MentionNum, TokenNum from code.util import COLUMN_PHOTOS, COLUMN_URLS, COLUMN_HASHTAGS, COLUMN_MENTIONS class PhotosNumTest(unittest.TestCase): def setUp(self) -> None: self.INPUT_COLUMN ...
2,920
1,065
import unittest from operator import index from EasyMCDM.models.Promethee import Promethee class TestPrometheeMethods(unittest.TestCase): def test_str_str_str(self): d = "data/partiels_donnees.csv" p = Promethee(data=d, verbose=False) res = p.solve( weights=[0.3, ...
926
451
''' Vortex OpenSplice This software and documentation are Copyright 2006 to TO_YEAR ADLINK Technology Limited, its affiliated companies and licensors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the Lice...
1,207
352
import typing import torch from .. import utils @utils.docs def regression_of_squares( output: torch.Tensor, target: torch.Tensor, reduction: typing.Callable[[torch.Tensor,], torch.Tensor,] = torch.sum, ) -> torch.Tensor: return reduction(output - torch.mean(target)) ** 2 @utils.docs def squares_o...
2,027
769
#!/usr/bin/env python2.7 # -*- coding:UTF-8 -*-2 u"""hold.py Copyright (c) 2019 Yukio Kuro This software is released under BSD license. ホールドピース管理モジュール。 """ import pieces as _pieces import utils.const as _const import utils.layouter as _layouter class Hold(object): u"""ホールドピース管理。 """ __slots__ = ( ...
6,028
2,016
from urllib.parse import urlparse def host(url): if not url: return "" data = urlparse(url) if data.netloc: return data.netloc value = data.path.split("/")[0] if "@" not in value or ":" not in value: return value from_ = value.find("@") + 1 for_ = value.find(":") ...
347
120
import cv2 import numpy as np # draw_ped() function to draw bounding box with top labeled text def draw_ped(img, label, x0, y0, xt, yt, font_size=0.4, alpha=0.5, bg_color=(255,0,0), ouline_color=(255,255,255), text_color=(0,0,0)): overlay = np.zeros_like(img) y0, yt = max(y0 - 15, 0) , min(yt + 15, img.shape[...
1,554
588
""" Code modified from: apps.fishandwhistle.net/archives/1155 """ from __future__ import print_function import serial import sys import glob port_list = {} def identifyPort(port): """ tests the port and identifies what device is attached to it from probing it :param port: :return: a port list dict w...
2,204
676
from app.python.utils import get_datetime def test_get_datetime(): assert isinstance(get_datetime(), str)
112
34
from nornir.core.plugins.inventory import InventoryPluginRegister from nornir.core.plugins.runners import RunnersPluginRegister from nornir.plugins.inventory import SimpleInventory from nornir.plugins.runners import SerialRunner, ThreadedRunner from nornir_utils.plugins.inventory import YAMLInventory class Test: ...
883
240
from setuptools import setup, find_packages setup( name="tessled", version="0.0.1", url='http://github.com/hodgestar/tesseract-control-software', license='MIT', description="Tesseract control software and simulator.", long_description=open('README.rst', 'r').read(), author='Simon Cross', ...
1,411
451
GITLAB_URL = "XXXXXX" GITLAB_TOKEN = "XXXXX"
45
25
#!/usr/bin/python # -*- coding: utf-8 -*- import time def Epoch(data): '''Patching Epoch timestamps.''' for record in data: record['last_updated'] = time.strftime('%Y-%m-%d', time.localtime(record['last_updated'])) return data def Date(data): '''Patching date stamps.''' for record in data: m = t...
481
186
from nltk.tokenize import TweetTokenizer import io def read_en_lines(lines): tknzr = TweetTokenizer() result = [] for line in lines: result.append(tknzr.tokenize(line)) return result def read_mrl_lines(lines): result = [] for line in lines: tgt = '' for i, ch in enume...
1,875
711
states = ['AP', 'AR', 'AS', 'BR', 'CG', 'GA', 'GJ', 'HR', 'HP', 'JH', 'KA', 'KL', 'MP', 'MH', 'MN', 'ML', 'MZ', 'NL', 'OD', 'PB', 'RJ', 'SK', 'TN', 'TS', 'TR', 'UP', 'UK', 'WB', 'AN', 'CH', 'DD', 'DL', 'JK', 'LA', 'LD', 'PY'] def resultplate(plate): result=...
2,228
748
#!/usr/bin/env python3 from setuptools import setup from distutils.util import convert_path main_ns = {} vpath = convert_path('photorename/version.py') with open(vpath) as vfile: exec(vfile.read(), main_ns) setup( name='photorename', version=main_ns['__version__'], description='bulk rename photos in ...
667
234
# -*- coding: utf-8 -*- # UTF-8 encoding when using korean import numpy as np import math input_l = [] while True: user_input = int(input('')) input_l.append(user_input) if len(input_l[1:]) == input_l[0]: #user_input = user_input.split('\n') cnt_input = [] for i in range(1, len(input_l)): if np.sqrt(input...
456
214
from setuptools import setup, find_packages setup( name='ContextNet', version='latest', packages=find_packages(), description='ContextNet: Improving Convolutional Neural Networks for Automatic Speech Recognition with Global Context', author='Sangchun Ha', author_email='seomk9896@naver.com', ...
454
151
from operator import mul def main_diagonal_product(matrix): return reduce(mul, (matrix[a][a] for a in xrange(len(matrix))))
130
44
from __future__ import annotations import toolcli from ctc.protocols import curve_utils def get_command_spec() -> toolcli.CommandSpec: return { 'f': async_curve_pools_command, 'help': 'list curve pools', 'args': [ { 'name': '--verbose', 'help'...
1,643
613
""" db constants """ DB_HOST = 'localhost' DB_PORT = 28015 # Database is cavilling DB_NAME = 'cavilling' DB_TABLE_CAVILLS = 'cavills' DB_TABLE_HAIRDOS = 'hairdos' DB_TABLE_POLRUS = 'polrus' DB_TABLE_USERS = 'users'
218
103
from flask import Blueprint, render_template, request, abort, jsonify, Response from socfakerservice import status, HTMLRenderer, set_renderers from socfakerservice.model import TokenModel from socfaker import SocFaker socfaker = SocFaker() api_bp = Blueprint( 'api', __name__ ) def validate_request(request)...
76,062
22,121
# coding=utf-8 import torch import torch.nn as nn import torch.nn.functional as F from jdit.trainer.single.classification import ClassificationTrainer from jdit.model import Model from jdit.optimizer import Optimizer from jdit.dataset import FashionMNIST from jdit.parallel import SupParallelTrainer class SimpleModel(...
3,494
1,344
def lego(plotter, t): h = t * 5.0 w = t * 3.0 plotter.move(-t * 2.0, 0) l(h, plotter, t, w) plotter.move(0, w + t) e(h, plotter, t, w) plotter.move(0, w + t) g(plotter, t) plotter.move(0, w + t) o(plotter, t) def o(plotter, t): # O plotter.move(t, 0) plotter.line(3...
1,701
870
#Initialize packages import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import sklearn.model_selection as model_selection from sklearn import linear_model import sklearn.metrics as metrics from sklearn.preprocessing import StandardScaler from sklearn.ensemble import Ra...
5,711
2,206
# -*- coding: utf-8 -*- """ Solution to Project Euler problem 142 - Perfect Square Collection Author: Jaime Liew https://github.com/jaimeliew1/Project_Euler_Solutions """ from itertools import combinations import numpy as np def run(): N = 1000000 candids = {} # generate all pairs of squares which differ...
1,287
427
""" Activity ======== Activities are self generated classes to which you can pass an identifier, and a list of tasks to perform. The activities are in between the decider and the task. For ease, two types of task runners are available: SyncTasks and AsyncTasks. If you need something more specific, you should either c...
6,032
1,571
import sys import csv import json import argparse from collections import namedtuple # diff info DiffInfo = namedtuple('DiffInfo', [ 'mark', # diff kind (!, -, +) 'address', # row/column addresses of diff 'keyname', # row/column key names of diff 'value', # values of diff ]) def ...
7,754
2,655
import os from time import time import pandas as pd from sqlalchemy import create_engine import logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class AbstractDataSource: def __int__(self): pass class AbstractDataSourcePointer(AbstractDataSource): def __int__(self): ...
2,563
714
import codecs import os import sys from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand def read(*parts): filename = os.path.join(os.path.dirname(__file__), *parts) with codecs.open(filename, encoding='utf-8') as fp: return fp.read() test_requires = [ ...
3,431
1,110
# -*- coding: utf-8 -*- # snapshottest: v1 - https://goo.gl/zC4yUc from __future__ import unicode_literals from snapshottest import Snapshot snapshots = Snapshot() snapshots['test_etc 1'] = '[{"lineno": 2, "value": "tup = (1, 2, 3)"}, {"lineno": 3, "source": ["tup\\n"], "value": "(1, 2, 3)"}, {"lineno": 5, "value":...
504
227
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__)....
1,823
817
from copy import copy import re class Cpu: def __init__(self, mem): self.mem = mem def addr(self, a, b, c): self.mem[c] = self.mem[a] + self.mem[b] def addi(self, a, b, c): self.mem[c] = self.mem[a] + b def mulr(self, a, b, c): self.mem[c] = self.mem[a] * self.mem[b]...
2,761
1,134
import streamlit as st def app(): st.title("About") st.markdown(''' During the Cyclone Fani which hit Odisha in 2019 a lot of places ran out of electricity, water and other basic necessities. During this period most of the rescue workers relied on data accumulated pre disaster to guide rescue services but this was...
2,700
626
# pylint: disable=missing-docstring import unittest import numpy as np import tensorflow as tf import tf_encrypted as tfe class TestReduceSum(unittest.TestCase): def setUp(self): tf.reset_default_graph() def test_reduce_sum_1d(self): t = [1, 2] with tf.Session() as sess: out = tf.reduce_sum(t...
1,617
593
import pytest from GraphModels.models.Sarah.model_agricultural_water import AgriculturalWaterNodes from GraphModels.models.Sarah.model_freshwater_available import FreshwaterAvailableNodes from GraphModels.models.Sarah.model_municipal_water import MunicipalWaterNodes nodes_list = AgriculturalWaterNodes + FreshwaterAv...
1,010
326
from django.db import transaction from db.scaffold import Scaffold from typing import List from telegram import models as tg_models from pyrogram import types class GetUpdatedMessageEntityTypes(Scaffold): def get_updated_message_entity_types( self, *, db_message: 'tg_models.M...
1,350
345
from flask import Blueprint, request, jsonify from web_util import assert_data_has_keys from users.user import User user_api = Blueprint('users_api', __name__, url_prefix='/api/user') @user_api.route('/reset_password', methods=['POST']) def sync(): params = assert_data_has_keys(request, {'email', 'password', 'ne...
486
151
import discord from discord.ext import commands from omdb_api import * from tmdb_api import * class Commands(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def movie(self, ctx, *, in_str=""): # input format: *movie {movie name} / {year} if in...
2,783
944
""" CryptoAPIs Crypto APIs 2.0 is a complex and innovative infrastructure layer that radically simplifies the development of any Blockchain and Crypto related applications. Organized around REST, Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with the development of thei...
92,070
22,763
""" RANdom CHoice baseline (RANCH): random image from the target class """ import random import numpy as np import tensorflow_datasets as tfds from tqdm import tqdm # output_pattern = '/home/ec2-user/gan_submission_1/mnist/mnist_v2/ranch_baselines_%d' # tfds_name = 'mnist' # target_size = [28, 28, 1] # num_class = 1...
1,853
749
import sqlite3, os con = sqlite3.connect('database.sqlite') im = con.cursor() tablo = """CREATE TABLE IF NOT EXISTS writes(day, topic, texti)""" deger = """INSERT INTO writes VALUES('oneDay', 'nmap', 'nmaple ilgili bisiler')""" im.execute(tablo) im.execute(deger) con.commit() im.execute("""SELECT * FROM writes""") ...
359
127
import cv2 import numpy as np from basicsr.metrics.metric_util import reorder_image, to_y_channel def calculate_psnr(img1, img2, crop_border, input_order='HWC', test_y_channel=False): """Calculate PSNR (Peak Signal-to-Noise Ratio). ...
6,075
2,298
import os import numpy as np import torch from tqdm import tqdm from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils from skimage import io, transform from utils.Config import opt from skimage import exposure import matplotlib.pylab as plt from utils import array_tool as at from sk...
14,224
4,831
import json import os.path as p from collections import defaultdict import pandas as pd from datasets import load_dataset from datasets import concatenate_datasets from datasets import Sequence, Value, Features, Dataset, DatasetDict from utils.tools import get_args f = Features( { "answers": Sequence( ...
8,344
3,461
import os import shutil import pyembroidery import test_fractals def test_simple(): pattern = pyembroidery.EmbPattern() pattern.add_thread({ "rgb": 0x0000FF, "name": "Blue Test", "catalog": "0033", "brand": "PyEmbroidery Brand Thread" }) pattern.add_thread({ "...
1,737
596
# Train the selected neural network model on spectrograms for birds and a few other classes. # Train the selected neural network model on spectrograms for birds and a few other classes. # To see command-line arguments, run the script with -h argument. import argparse import math import matplotlib.pyplot as plt import ...
21,317
6,286
from __future__ import division from numpy import ascontiguousarray, copy, ones, var from numpy_sugar.linalg import economic_qs from glimix_core.glmm import GLMMExpFam def estimate(pheno, lik, K, covs=None, verbose=True): r"""Estimate the so-called narrow-sense heritability. It supports Normal, Bernoulli, ...
2,002
720
import argparse, importlib, sys import pyrat from pyrat import name, version, logger # This returns a function to be called by a subparser below # We assume in the tool's submodule there's a function called 'start(args)' # That takes over the execution of the program. def tool_(tool_name): def f(args): s...
2,739
851
from .objectview import to_json, from_json def load_event(event): try: return from_json(event) except ValueError as ex: # Report malformed JSON input. if event == b'': return {'event': 'EXCEPTION', 'reason': 'EOF', 'input': event} return {'event': 'EXCEPTION', 'reas...
485
156
#!/usr/bin/env python3 """Longest Collatz sequence. The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that...
2,007
736
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
1,823
572
from weldx.asdf.util import dataclass_serialization_class from weldx.measurement import SignalSource __all__ = ["SignalSource", "SignalSourceConverter"] SignalSourceConverter = dataclass_serialization_class( class_type=SignalSource, class_name="measurement/source", version="0.1.0" )
291
93
""" GraphSense API GraphSense API # noqa: E501 The version of the OpenAPI document: 0.5.1 Generated by: https://openapi-generator.tech """ import unittest import graphsense from graphsense.api.entities_api import EntitiesApi # noqa: E501 class TestEntitiesApi(unittest.TestCase): """Entities...
1,706
554
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import os import unittest import pure_interface class TestVersionsMatch(unittest.TestCase): def test_versions(self): setup_py = os.path.join(os.path.dirname(__file__), '..', 'setup.cfg') wit...
622
187
from dataclasses import dataclass from bindings.wfs.get_capabilities_type_2 import GetCapabilitiesType2 __NAMESPACE__ = "http://www.opengis.net/wfs/2.0" @dataclass class GetCapabilities2(GetCapabilitiesType2): class Meta: name = "GetCapabilities" namespace = "http://www.opengis.net/wfs/2.0"
315
111
""" This module is to define how TimeStamp model is represented in the Admin site It also registers the model to be shown in the admin site .. seealso:: :class:`..models.TimeStamp` """ from django.contrib import admin from .models import TimeStamp class FilterUserAdmin(admin.ModelAdmin): """ Makes the ...
2,169
604
from setuptools import setup, find_packages setup( name='izeni-django-accounts', version='1.1.2a', namespace_packages=['izeni', 'izeni.django'], packages=find_packages(), include_package_data=True, author='Izeni, Inc.', author_email='django-accounts@izeni.com', description=open('README....
718
266
# Copyright (c) Ville de Montreal. All rights reserved. # Licensed under the MIT license. # See LICENSE file in the project root for full license information. import os import json import torch import argparse import datetime from utils.factories import ModelFactory, OptimizerFactory, TrainerFactory if __name__ == "...
2,973
857
""" Generate the wavelength templates for SOAR Goodman""" import os from pypeit.core.wavecal import templates from IPython import embed def soar_goodman_400(overwrite=False): binspec = 2 outroot = 'soar_goodman_400_SYZY.fits' # PypeIt fits wpath = os.path.join(templates.template_path, 'SOAR_Goodman',...
1,036
397
from simple_playgrounds.entities.agents.sensors.sensor import * from simple_playgrounds.entities.agents.sensors.semantic_sensors import * from collections import defaultdict from pymunk.vec2d import Vec2d import math #@SensorGenerator.register('lidar') class LidarSensor(SemanticSensor): def __init__(self, anchor...
5,062
1,399
from django.db import models class Departement(models.Model): id = models.AutoField(primary_key=True) nom = models.CharField(max_length=255, unique=True) code_insee = models.CharField(max_length=3, unique=True) code_postal = models.CharField(max_length=3) def natural_key(self): return (s...
511
182
#!/bin/python import sys, os, re, subprocess, math import argparse import psutil from pysam import pysam from Bio import SeqIO import numpy as np import numpy.random import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt #import seaborn as sns import pandas as pd import scipy.stats from scipy.stats imp...
4,310
1,603
# -*- coding: utf-8 from django.http import JsonResponse, HttpResponse # from commons.settings import ARCHON_HOST class CORSMiddleware: def process_request(self, request): if request.method == 'OPTIONS': r = HttpResponse('', content_type='text/plain', status=200) r['Access-Contro...
713
212
class PxlapiException(Exception): """ The base exception for anything related to pypxl """ pass class InvalidFlag(PxlapiException): pass class InvalidFilter(PxlapiException): pass class InvalidEyes(PxlapiException): pass class TooManyCharacters(PxlapiException): pass class InvalidSa...
538
167
import unittest from algorithm import NQueens class TestNQueens(unittest.TestCase): def test_1_queen(self): self.assertEqual(NQueens(1).solutions, 1) def test_2_queen(self): self.assertEqual(NQueens(2).solutions, 0) def test_3_queen(self): self.assertEqual(NQueens(3).solutions, ...
1,061
424
import functools from dataclasses import dataclass from itertools import combinations import click import syntropy_sdk as sdk from syntropy_sdk import utils from syntropynac.exceptions import ConfigureNetworkError from syntropynac.fields import ALLOWED_PEER_TYPES, ConfigFields, PeerState, PeerType @dataclass class ...
18,524
5,097
"""This module contains the implementation of the cluster node interface.""" import datetime from typing import Optional, Any, Callable import bitmath import fabric.operations import fabric.tasks import fabric.decorators from fabric.exceptions import CommandTimeout from fabric.state import env from idact.core.retry ...
10,298
2,678
"""create table for hierarchy of accounts Revision ID: 17fb1559a5cd Revises: 3b7de32aebed Create Date: 2015-09-16 14:20:30.972593 """ # revision identifiers, used by Alembic. revision = '17fb1559a5cd' down_revision = '3b7de32aebed' branch_labels = None depends_on = None from alembic import op, context import sqlalc...
2,012
690
from __future__ import unicode_literals, division, absolute_import import os from tests import FlexGetBase class TestMigrate(FlexGetBase): __yaml__ = """ tasks: test: mock: - {title: 'foobar'} accept_all: yes """ def setup(self): import log...
1,076
317
""" Problem 1 of Chapter 8 in CtCi Triple Step: A child is running up a staircase with N steps and can hop either 1 step, 2 steps, or 3 steps at a time. Return the number of possible ways exist this can be done. General idea of the solution: At any step N, the child must necessarily come from the steps N-3, N-2 or N-1...
2,422
879
from JumpScale import j j.base.loader.makeAvailable(j, 'tools') from Docker import Docker j.tools.docker = Docker()
117
38
#!/usr/bin/env python2 import sys import socket import datetime import math import time from time import sleep # The c binary for controlling the stepper motor is loaded via ctypes from ctypes import * stepper_lib = cdll.LoadLibrary('./stepper.so') # buffer containing the incomplete commands recvBuffer = str() # ...
3,704
1,110
import os import math import sys from typing import List, Tuple # for kaggle-environments from abn.game_ext import GameExtended from abn.jobs import Task, Job, JobBoard from abn.actions import Actions from lux.game_map import Position, Cell, RESOURCE_TYPES from lux.game_objects import City from lux.game_constants impo...
20,335
5,965
from copy import copy from tkinter import * from tkinter import ttk from src import app_data from src.CharData.augment import Cyberware from src.Tabs.notebook_tab import NotebookTab from src.statblock_modifier import StatMod from src.utils import treeview_get, recursive_treeview_fill, calculate_attributes, get_variabl...
12,503
3,733
from datadog import initialize, statsd import time import random import os options = { 'statsd_host':os.environ['DD_AGENT_HOST'], 'statsd_port':8125 } initialize(**options) i = 0 while(1): i += 1 r = random.randint(0, 1000) statsd.gauge('mymetric',r , tags=["environment:dev"]) time.sleep(int(os.envi...
337
136
n = [0,0,0,0,0,0,0,0,0,0] t = [0,0,0,0,0,0,0,0,0,0] c=0 while(c<10): n[c]=input("Digite o nome") t[c]=input("Digite o telefone") c+=1 const="" while(const!="fim"): cons=input("Digite nome a consultar") if(n[c]==const): print(f"TEl: {t[c]}") c+=1
277
150
#!/usr/bin/env python3 """A flask server for Robojam""" import json import time from io import StringIO import pandas as pd import tensorflow as tf import robojam from tensorflow.compat.v1.keras import backend as K from flask import Flask, request from flask_cors import CORS # Start server. tf.compat.v1.logging.set_v...
8,979
7,253
from datetime import datetime import os import re import subprocess from . import app, celery, db from .database import Job @celery.task() def make_audio(youtube_id): worker_path = os.path.join(app.root_path, 'worker.sh') env = { 'DYNAMIC_AUDIO_NORMALIZER_BIN': app.config['DYNAMIC_AUDIO_NORMALIZER_BI...
1,024
371
from setuptools import setup setup( name="python-sdk-example", version="0.1", description="The dispatch model loader - lambda part.", url="https://github.com/garethrylance/python-sdk-example", author="Gareth Rylance", author_email="gareth@rylance.me.uk", packages=["example_sdk"], instal...
560
193
### IMPORTS import json import glob import string import random import spacy from spacy.lang.en.stop_words import STOP_WORDS import markovify ### CONSTANTS/GLOBALS/LAMBDAS SYMBOLS_TO_RM = tuple(list(string.punctuation) + ['\xad']) NUMBERS_TO_RM = tuple(string.digits) spacy.prefer_gpu() NLP_ENGINE = spacy.load("en_c...
4,140
1,849
#/********************************************************************************** # Copyright (c) 2021 Joseph Reeves and Cayden Codel, Carnegie Mellon University # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and # associated documentation files (the "Software"), t...
6,211
2,015
import pathlib import pytest from betel import app_page_scraper from betel import betel_errors from betel import utils ICON_HTML = """ <img src="%s" class="T75of sHb2Xb"> """ CATEGORY_HTML = """ <a itemprop="genre">Example</a> """ FILTERED_CATEGORY_HTML = """ <a itemprop="genre">Filtered</a> """ SIMPLE_HTML = """ <...
4,171
1,587