text
string
size
int64
token_count
int64
# *************************************************************** # Copyright (c) 2020 Jittor. Authors: Dun Liang <randonlang@gmail.com>. All Rights Reserved. # This file is subject to the terms and conditions defined in # file 'LICENSE.txt', which is part of this source code package. # ********************************...
5,377
2,087
from typing import Union from mre.Regex import Regex class Range(Regex): def __init__(self, minimum: Union[str, int] = 0, maximum: Union[str, int] = 9): super().__init__('{}-{}'.format(minimum, maximum)) @staticmethod def digits(minimum: int = 0, maximum: int = 9): return Range(minimum, ...
846
242
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
3,463
1,334
from Artist import Artist class Artwork: def __init__(self, title='None', year_created=0,\ artist=Artist()): self.title = title self.year_created = year_created self.artist = artist def print_info(self): self.artist.print_info() print('Title: %s, %d' % (self.title,...
341
111
#!/usr/bin/env python from collections import defaultdict from itertools import product import json import random import sys from annoy import AnnoyIndex from Bio import SeqIO import numpy as np class FeatureGenerator: def __init__(self, k=2): ''' ''' self.k = k self.alphabet = [ 'A'...
2,249
746
# tf.transformations alternative is not yet available in tf2 from tf.transformations import quaternion_from_euler if __name__ == '__main__': # RPY to convert: 90deg, 0, -90deg q = quaternion_from_euler(1.5707, 0, -1.5707) print "The quaternion representation is %s %s %s %s." % (q[0], q[1], q[2], q[3])
314
133
import datetime from django.contrib.auth.models import User, Group from django.utils import timezone from rest_framework.test import APITestCase import fvh_courier.models.base from fvh_courier import models class FVHAPITestCase(APITestCase): def assert_dict_contains(self, superset, subset, path=''): for...
2,997
896
""" Binder classes perform two functions through their format method - given a query template with %(somevar)s python substition class MyClass(object): pass arg1 = MyClass() arg1.customer = 101 default = MyClass() default.customer = 201 arg2.country = "CAN" qry, sub = format(" ...
12,039
3,607
# -*- coding: utf-8 -*- # # parselglossy -- Generic input parsing library, speaking in tongues # Copyright (C) 2020 Roberto Di Remigio, Radovan Bast, and contributors. # # This file is part of parselglossy. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associate...
4,313
1,389
import numpy as np def print_initial_values(init_cell): phi_sn, phi_se, phi_sg, phi_dn, phi_de, phi_dg, phi_msn, phi_mdn, phi_msg, phi_mdg = init_cell.membrane_potentials() E_Na_sn, E_Na_sg, E_Na_dn, E_Na_dg, E_K_sn, E_K_sg, E_K_dn, E_K_dg, E_Cl_sn, E_Cl_sg, E_Cl_dn, E_Cl_dg, E_Ca_sn, E_Ca_dn = init_...
2,765
1,268
# -*- coding: utf-8 -*- import glob import os import json from collections import OrderedDict import itertools import re from datetime import datetime import six from six import iteritems from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy import or_ from .. import field_names, localization from ..models impo...
21,021
6,647
# -*- coding: utf-8 -*- """ (c) 2020 - Copyright Red Hat Inc Authors: Pierre-Yves Chibon <pingou@pingoured.fr> """ from __future__ import unicode_literals, absolute_import import datetime import json import unittest import shutil import sys import tempfile import os import pygit2 from celery.result import Ea...
7,709
2,355
# Copyright 2020 Google LLC. 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 applicable law or a...
3,827
1,273
import unittest import sys import os import py_compile from vatools import vcf_info_annotator import tempfile from filecmp import cmp class VcfInfoEncoderTests(unittest.TestCase): @classmethod def setUpClass(cls): base_dir = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file_...
4,707
1,541
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: peer/admin.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _re...
17,965
6,096
from pathlib import Path from tempfile import mkdtemp from nose.tools import eq_ from anycache import AnyCache from anycache import get_defaultcache from anycache import anycache def test_basic(): """Basic functionality.""" @anycache() def myfunc(posarg, kwarg=3): # count the number of calls ...
4,002
1,663
"""A run_fn method called by the TFX Trainer component.""" import os import logging from tfx import v1 as tfx from tfx_taxifare_tips.model_training import defaults from tfx_taxifare_tips.model_training import model_trainer from tfx_taxifare_tips.model_training import model_exporter # TFX Trainer will call ...
2,173
710
import random, os, string, subprocess, shutil, requests from discord import Webhook, RequestsWebhookAdapter, Embed from dotenv import dotenv_values import argparse, colorama from colorama import Fore class Settings(): def __init__(self): for k, v in dotenv_values(".settings").items(): setattr(...
4,602
1,499
from .board import Board from .slide import slide_action from .corner import corner_action from .control import control_action from .penalty import penalty_action from .throwin import throwin_action from .kickoff import kickoff_action from .goalkick import goalkick_action from .freekick import freekick_action from .wit...
357
98
"""Bin Testing""" # standard library from importlib.machinery import SourceFileLoader from importlib.util import module_from_spec, spec_from_loader from typing import List # third-party from typer.testing import CliRunner # dynamically load bin/tcex file spec = spec_from_loader('app', SourceFileLoader('app', 'bin/tce...
3,447
1,059
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
16,752
4,664
# coding=utf-8 """LeNet for MNIST""" import os from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D from keras.utils import np_utils from keras.callbacks import ModelCheckpoint, TensorBoard from snntoolbox.parsing.utils import \ ...
1,847
767
import numpy as np x = 1.0 #define a float y = 2.0 #define another float #trigonometry print(f"np.sin({x}) = {np.sin(x)}") #sin(x) print(f"np.cos({x}) = {np.cos(x)}") #cos(x) print(f"np.tan({x}) = {np.tan(x)}") #tan(x) print(f"np.arcsin({x}) = {np.arcsin(x)}") #arcsin(x) print(f"np.arccos({x}) = {np.arccos(x)...
856
454
# Generated by Django 2.1.2 on 2018-10-27 15:50 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django_countries.fields class Migration(migrations.Migration): dependencies = [ ('workshops', '0157_auto_20181006_0859'), ] operation...
10,544
2,910
import argparse from mahjong.shanten import Shanten from multiprocessing import Pool import os import sys from log_parser.discard_prediction_parser import parse_discard_prediction SHANTEN = Shanten() INPUT_DATA_FOLDER = "data/raw" OUTPUT_DATA_DIR = "data/single_hand_efficiency" def tiles34_to_list(tiles): resul...
2,365
793
from JumpScale import j class system_alerts(j.tools.code.classGetBase()): """ Alerts handler """ def __init__(self): self._te = {} self.actorname = "alertshandler" self.appname = "system" self.alertmodel = j.data.models.system.Alert def update(self, state, aler...
1,942
557
# This file is only used to generate documentation # VM class class vm(): def getGPRState(): """Obtain the current general purpose register state. :returns: GPRState (an object containing the GPR state). """ pass def getFPRState(): """Obtain the current floating p...
17,628
4,725
# -*- coding: utf-8 -*- """Scrapy settings.""" BOT_NAME = 'krkbipscraper' SPIDER_MODULES = ['krkbipscraper.spiders'] NEWSPIDER_MODULE = 'krkbipscraper.spiders' ITEM_PIPELINES = ['krkbipscraper.pipelines.JsonWriterPipeline']
227
102
# Importação da biblioteca. # Certifique-se de ter a biblioteca instalada. import pyhdb # Essa função traz/chama outro arquivo que contém a senha, visando não deixar exposta na aplicação. # Caso não queira utilizar esse método e inserir diretamente a senha na conexão, exclua esse bloco e insira a senha diretamente no...
1,797
597
# Copyright 2019 Ondrej Skopek. # # 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...
2,418
879
""" Download CellO's resources files. These files include CellO's pre-trained models, gene ID-to-symbol mappings, and training sets for training CellO's models on new gene sets. Authors: Matthew Bernstein <mbernstein@morgridge.org> """ import subprocess from os.path import join from shutil import which def download(...
1,033
331
def sum_digit(n): total = 0 while n != 0: total += n % 10 n /= 10 return total def factorial(n): if n <= 0: return 1 return n * factorial(n - 1)
190
78
from abc import ABCMeta, abstractmethod import torch import torch.nn.functional as F from addict import Dict from mmtrack.models import TRACKERS @TRACKERS.register_module() class BaseTracker(metaclass=ABCMeta): """Base tracker model. Args: momentums (dict[str:float], optional): Momentums to update ...
7,755
2,400
# Copyright 2019-2022 The University of Manchester, UK # Copyright 2020-2022 Vlaams Instituut voor Biotechnologie (VIB), BE # Copyright 2020-2022 Barcelona Supercomputing Center (BSC), ES # Copyright 2020-2022 Center for Advanced Studies, Research and Development in Sardinia (CRS4), IT # Copyright 2022 École Polytechni...
3,675
1,316
#!/usr/bin/python from __future__ import print_function import unittest import json import os import sys import requests sys.path.insert(0, os.path.abspath(os.path.join( os.path.dirname(os.path.realpath(__file__)), os.pardir, "cli"))) from cli.marathon import Marathon from cli.appconfig import AppConfig from mocki...
3,791
1,206
numbers = list(map(int, input().split(','))) print(len(numbers))
65
23
from flask import Flask, request import json app = Flask(__name__) def runsomething(): print "This is triggered" @app.route('/',methods=['POST']) def trigger(): data = json.loads(request.data) print "New commit by: {}".format(data['commits'][0]['author']['name']) print "New commit by: {}".format(data['c...
496
165
import pytest import nlp from nlp4e import Rules, Lexicon, Grammar, ProbRules, ProbLexicon, ProbGrammar, E0 from nlp4e import Chart, CYK_parse, subspan, astar_search_parsing, beam_search_parsing # Clumsy imports because we want to access certain nlp.py globals explicitly, because # they are accessed by functions...
4,349
1,815
#!/usr/bin/python3 import binascii import random import cosim class LoopbackTester(cosim.CosimBase): """Provides methods to test the loopback simulations.""" def test_list(self): ifaces = self.cosim.list().wait().ifaces assert len(ifaces) > 0 def test_open_close(self): ifaces = self.cosim.list()....
1,598
617
""" Module for common target stage stack configurations. """ import logging import numpy as np from datetime import datetime import os from ophyd.device import Device import json import jsonschema import yaml from itertools import chain from pcdsdevices.epics_motor import _GetMotorClass from .interface import tweak_b...
48,282
14,264
#!/usr/bin/env python # # time # # Copyright Jelmer Vernooij 2010 <jelmer@samba.org> # # 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 3 of the License, or # (at your option) any ...
1,564
492
import unittest import redis import socket import pytest from bokchoy.conductors.dummy import DummyConductor from bokchoy.results.redis import RedisResult from bokchoy.serializers.json import JSONSerializer from exam import fixture from .base import JobTests def redis_is_available(): try: socket.create...
900
292
# Copyright (c) 2020 # Author: xiaoweixiang """Contains purely network-related utilities. """
97
40
class Global: sand_box = True app_key = None # your secret secret = None callback_url = None server_url = None log = None def __init__(self, config): Global.sand_box = config.get_env() Global.app_key = config.get_app_key() Global.secret = config.get_secret()...
1,153
362
DEFAULT_KUBE_VERSION=1.14 KUBE_VERSION="kubeVersion" USER_ID="userId" DEFAULT_USER_ID=1 CLUSTER_NAME="clusterName" CLUSTER_MASTER_IP="masterHostIP" CLUSTER_WORKER_IP_LIST="workerIPList" FRAMEWORK_TYPE= "frameworkType" FRAMEWORK_VERSION="frameworkVersion" FRAMEWORK_RESOURCES="frameworkResources" FRAMEWORK_VOLUME_SIZE= ...
3,004
1,408
# -*- coding: utf-8 -*- from django.conf.urls import url from django.views.generic.base import RedirectView from mpcontribs.portal import views app_name = "mpcontribs_portal" urlpatterns = [ url(r"^$", views.index, name="index"), url(r"^healthcheck/?$", views.healthcheck, name="healthcheck"), url( ...
1,582
612
from typing import List, Optional, Tuple from collections import defaultdict from mp_api.core.client import BaseRester, MPRestError import warnings class DielectricRester(BaseRester): suffix = "dielectric" def get_dielectric_from_material_id(self, material_id: str): """ Get dielectric data...
3,363
976
from wtforms import TextField, IntegerField, PasswordField from wtforms.ext.sqlalchemy.fields import ( QuerySelectField, QuerySelectMultipleField) from wtforms.validators import Required from pynuts.view import BaseForm import database from application import nuts class EmployeeView(nuts.ModelView): model = ...
1,598
457
#!/usr/bin/env python3 import sys from Bio import SeqIO import os genome = sys.argv[1] in_aa = f'hits/{genome}.hits' in_up = f'fa/{genome}.upstream' hits = SeqIO.to_dict(SeqIO.parse(in_aa, 'fasta')) raes = SeqIO.to_dict(SeqIO.parse(in_up, 'fasta')) for k in hits.keys(): i = k.split('|')[1] print(raes[i].format('...
330
151
"""AirTouch 4 component to control of AirTouch 4 Climate Devices.""" from __future__ import annotations import logging from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( FAN_AUTO, FAN_DIFFUSE, FAN_FOCUS, FAN_HIGH, FAN_LOW, FAN_MEDIUM...
11,674
3,915
import json import requests class GiosgApiMixin(object): URL_USERS = '/api/v3/customer/personnel' URL_CHATS = '/api/v3/chat/chatsessions' def build_request_url(self, base, page_size=25, page=1): domain = self.data.get('sub') return '%s://%s%s?page_size=%s&page=%s' % (self._protocol, domai...
772
277
#MenuTitle: Delete Duplicate Components # -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals __doc__=""" Looks for duplicate components (same component, same x/y values) and keeps only one of them. """ Font = Glyphs.font selectedLayers = Font.selectedLayers def getAttr( thisLayer,...
1,415
488
""" Error classes, when needed for exceptions. """ from _ast import AST from dataclasses import dataclass, field from typing import Optional, Union from src.compiler.Util import Util @dataclass(frozen=True) class ObjectAlreadyDefinedError(NameError): """ For our compilation scheme, objects can only be define...
3,317
905
# -*- coding: utf-8 -*- import argparse from github.accounts.github_account import GithubAccount from github.domain.github import GithubUser from github.recorders.github.common import get_result from zvdata.api import get_entities from zvdata.domain import get_db_session from zvdata.recorder import TimeSeriesDataRecor...
4,314
1,220
from pyTooling.Decorators import export __version__ = "0.1.0" @export class Filter: pass
94
39
# Importing needed libraries import uuid from decouple import config from dotenv import load_dotenv from flask import Flask, render_template, request, jsonify from sklearn.externals import joblib import traceback import pandas as pd import numpy as np from flask_sqlalchemy import SQLAlchemy # Saving DB var DB = SQLAlc...
1,766
539
import pandas as pd import os from sklearn.svm import SVC from sklearn.preprocessing import StandardScaler from sklearn.metrics import classification_report, confusion_matrix from sklearn.model_selection import train_test_split import pickle BASE_PATH = os.path.join(os.getcwd() , "dataset") df = None i = 0 for file_na...
1,237
459
# -*- coding: utf-8 -*- """ Created on Mon Aug 14 20:21:23 2017 @author: DKIM """ import pandas as pd import numpy as np # required libraries loaded import pandas as pd import numpy as np import matplotlib matplotlib.style.use('ggplot') import matplotlib.pyplot as plt seednumber = 319 data = pd.read_csv('Data.csv...
6,266
2,402
#!/usr/bin/env python """Testplan that is expected to time out.""" import sys import threading import testplan from testplan.testing import multitest @multitest.testsuite class TimeoutSuite(object): @multitest.testcase def blocks(self, env, result): result.log('Blocking...') threading.Event(...
597
188
# Python3 def makeArrayConsecutive2(statues): return (max(statues) - min(statues) + 1) - len(statues)
107
43
# ! /usr/bin/python # -*- coding: utf-8 -*- # import funkcí z jiného adresáře # import sys import os.path path_to_script = os.path.dirname(os.path.abspath(__file__)) # sys.path.append(os.path.join(path_to_script, "../extern/pyseg_base/src/")) # sys.path.append(os.path.join(path_to_script, "../extern/sed3/")) # sys.pat...
1,127
492
from flask import Flask # import pyodbc app = Flask(__name__) @app.route("/") def hello(): # Some other example server values are # server = 'localhost\sqlexpress' # for a named instance # server = 'myserver,port' # to specify an alternate port # server = 'tcp:mytest.centralus.cloudapp.azure.com...
751
265
from sweeps.sweepFunctions import * import numpy as np def SMTBFSweep(SMTBFSweepInput,ourInput): myRange = SMTBFSweepInput["range"] if dictHasKey(SMTBFSweepInput,"range") else False myStickyRange=SMTBFSweepInput["sticky-range"] if dictHasKey(SMTBFSweepInput,"sticky-range") else False sticky=False if type(...
3,906
1,160
from __future__ import unicode_literals import pytest # noqa import sys pytestmark = pytest.mark.skipif(sys.version_info[0] < 3, reason="pyecore is not Python 2 compatible") # noqa pyecore = pytest.importorskip("pyecore") # noqa import textx from textx.metamodel import metamodel_from_...
1,708
560
# -*- coding: utf-8 -*- import boto3 from botocore.exceptions import ClientError import attr from attrs_mate import AttrsClass import weakref @attr.s class S3Object(AttrsClass): aws_profile = attr.ib() bucket = attr.ib() # type: str key = attr.ib() # type: str _s3_client_cache = weakref.WeakValueDic...
863
283
from android.runnable import run_on_ui_thread from jnius import autoclass, cast mActivity = autoclass("org.kivy.android.PythonActivity").mActivity Toast = autoclass("android.widget.Toast") CharSequence = autoclass("java.lang.CharSequence") String = autoclass("java.lang.String") @run_on_ui_thread def android_toast(t...
543
173
#!/usr/bin/env python3 # coding: utf-8 # author: Francesco Lumachi <francesco.lumachi@gmail.com> import pandas as pd import numpy as np from itertools import islice from sklearn.utils.validation import check_X_y class KTopScoringPair: """ K-Top Scoring Pair classifier. This classifier evaluate maximum-li...
9,395
2,842
import datetime import picmodels.models from picmodels.models.utils import filter_db_queryset_by_id from picmodels.models.care_advisors.navigator_models.services.read import filter_navigator_objs_by_f_and_l_name from picmodels.models.care_advisors.navigator_models.services.read import filter_navigator_objs_by_first_na...
11,089
3,308
class CompressorUtils(object): @staticmethod def encode(_cell, _list): if not _cell: data = "-" elif _cell not in _list: data = str(len(_list)) _list.append(_cell) else: data = str(_list.index(_cell)) return data ...
949
312
# Copyright 2018 TWO SIGMA OPEN SOURCE, 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
3,405
1,030
from datetime import datetime from typing import List import dateutil from datasets import TextDataset from miscc.config import cfg_from_file, cfg from torchvision.transforms import transforms from attnganw.train import GanTrainerWrapper, BirdGenerationFromCaption def get_text_dataset(tree_base_size: int, tree_bran...
2,512
709
''' @brief Base class for system data classes. This class defines the interface for cata classes which are intended to hold a specific data item (packet, channel, event). This data item includes the time of the data as well as data such as channel value or argument value. @date Created July 2, 2018 @author R. Joseph ...
2,469
693
## # Copyright (c) 2011-2015 Apple 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 # # Unless required by applicable l...
3,063
929
# ERFNet full model definition for Pytorch # Sept 2017 # Eduardo Romera ####################### import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F class DownsamplerBlock (nn.Module): def __init__(self, ninput, noutput): super().__init__() self.conv = n...
8,259
3,408
#!/usr/bin/env python # -*- coding: utf-8 -*- """ WSGI script Setup Application, Authentication, ... """ import os from eve import Eve from evedom import loader # from your_app.authentication.token import TokenBasedAuth __author__ = "nam4dev" __created__ = '08/11/2017' ROOT_PATH = os.path.dirname( os.pa...
1,009
371
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2019-01-18 17:16 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('workflow', '0026_auto_20190116_1357'), ] operation...
1,654
535
import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import random from util.util import pad, detect_aes_ecb, generate_key, ammend_plaintext, encrypt_random # Chosen plaintext plaintext = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" # Generate data and encrypt plaintext key = g...
753
274
# Copyright (c) 2017 Uber Technologies, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publ...
5,457
1,625
# -*- coding: utf-8 -*- """ A data clustering widget for the Orange3. This is a data clustering widget for Orange3, that implements the OPTICS algorithm. OPTICS stands for "Ordering Points To Identify the Clustering Structure". This is a very useful algorithm for clustering data when the dataset is unlabel...
10,766
3,433
import json from message_prototypes.exceptions import MissingModelException class BaseMessage: _serializable_fields = [] def pack(self, unpacking_info=True): result = { '_model': self.__class__.__name__, } if unpacking_info else {} def serialize_node(node=None): ...
2,590
651
# -*- coding: utf-8 -* import pytest from pyleecan.Classes.Circle import Circle from pyleecan.Classes.Segment import Segment from pyleecan.Classes.SurfLine import SurfLine # Configuring the test of is_inside inside_test = list() # Test 1 : checking if a point is inside a circle of radius 1 at 0 + 0j C1 = ...
2,015
873
import time from nitter_scraper import NitterScraper last_tweet_id = None with NitterScraper(port=8008) as nitter: while True: for tweet in nitter.get_tweets("dgnsrekt", pages=1, break_on_tweet_id=last_tweet_id): if tweet.is_pinned is True: continue if tweet.is_r...
542
192
# Generated by Django 3.1.6 on 2021-02-25 00:50 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('contenttypes', '0002_remove_content_type_name'), migrations.swa...
11,697
3,302
# flake8: noqa from .sampler import Sampler
45
18
from tools.com.alpha import Flow, Path def test_flow(): p = Path("TEST", "layer", ["TASK", "SUB"]) f = Flow(content="abc123", path=p, format="text", a=1, b=7, c="aaaa") s = str(p).encode() + b""" text a: 1 b: 7 c: aaaa abc123""" assert f.to_bytes()[5:] == s
295
142
import argparse import os import subprocess from subprocess import call def compile_separate(): cmd = "docker run -v " + contractsdir + ":/data ethereum/solc:stable --bin --abi --overwrite -o /data /data/" + filename print(cmd) call(cmd, shell=True) def comile_combined(): cmd = "docker run -v " + con...
907
307
import re import joblib from sklearn.ensemble import RandomForestClassifier from typing import List, Tuple # Cleans up a messed up HTML / tabbed raw content into space delimited content def clean_up_raw_body(raw_text: str) -> str: return ' '.join([line.strip() for line in raw_text.strip().splitlines() \ if li...
1,283
407
import os import sendgrid from sendgrid.helpers.mail import Content, Email, Mail from bs4 import BeautifulSoup class SendGrid(object): """Send an email through SendGrid""" def __init__(self): # Check if we are not in heroku sendgrid_api_key = os.environ.get('SENDGRID_APY_KEY') if os.environ.ge...
1,637
450
import json class kilpailija: def __init__(self,etunimi,sukunimi,puhelinnumero,seura,kilpasarja,bibnumber): self.etunimi = etunimi self.sukunimi = sukunimi self.puhelinnumero = puhelinnumero self.seura = seura self.kilpasarja = kilpasarja self.bibnumber = bibn...
2,141
843
#!/usr/bin/python3 ## Tommy from botbase import * _frankfurt_st = re.compile(r"Stand:\s*(\d\d?\. *\w+ 20\d\d, \d\d?(?::\d\d)?) Uhr") def frankfurt(sheets): import locale locale.setlocale(locale.LC_TIME, "de_DE.UTF-8") soup = get_soup("https://frankfurt.de/service-und-rathaus/verwaltung/aemter-und-instituti...
1,436
596
# Copyright 2013-2018 Aerospike, Inc. # # 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 writ...
2,065
609
"""from django.contrib import admin from .models import DemoModel admin.site.register(DemoModel)"""
101
28
import lanelines from compgraph import CompGraph, CompGraphRunner import numpy as np import cv2 func_dict = { 'grayscale': lanelines.grayscale, 'get_image_shape': lambda im : im.shape, 'canny': lanelines.canny, 'define_lanes_region': lanelines.define_lanes_region, 'apply_region_mask': lanelines.ap...
2,015
812
import random from random import Random def write_test_line(f, r, c, clear, o = 0): f.write("\n") if(o == 0): if clear == 0: o = r.randint(1, 8) elif clear == 1: o = 9 else: o = r.randint(1, 9) if o == 1: f.write("prepend") f.wri...
2,904
1,296
# LSTM(GRU) 예시 : KODEX200 주가 (2010 ~ 현재)를 예측해 본다. # KODEX200의 종가와, 10일, 40일 이동평균을 이용하여 향후 10일 동안의 종가를 예측해 본다. # 과거 20일 (step = 20) 종가, 이동평균 패턴을 학습하여 예측한다. # 일일 주가에 대해 예측이 가능할까 ?? # # 2018.11.22, 아마추어퀀트 (조성현) # -------------------------------------------------------------------------- import tensorflow as tf import nump...
4,305
2,525
"""media.py: Module for movie_trailer_website, contains Movie class""" import webbrowser import urllib import json class Movie(object): """This class provides a way to store movie related information. constructor takes movie title, imdb_id and a url for a youtube trailer as input. All other values are po...
1,486
446
""" A collection of useful functions for manipulating/encoding pandas dataframes for data science. """
103
24
import torch import torchvision import torchvision.transforms as transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import numpy as np from model_utils import * class down(nn.Module): """ A class for creating neural network blocks containing layers: Average P...
23,493
8,924
# -*- coding: utf-8 -*- """ In this file are all the needed functions to calculate an adaptive fractionation treatment plan. The value_eval and the result_calc function are the only ones that should be used This file requires all sparing factors to be known, therefore, it isnt suited to do active treatment planning ...
11,970
3,808
from django.contrib import admin # Register your models here. from ltc.base.models import Project, Test, Configuration # Register your models here. admin.site.register(Project) admin.site.register(Test) admin.site.register(Configuration)
240
65