text
string
size
int64
token_count
int64
#!/usr/bin/env python3 import os import re import glob import sys import operator import ast import argparse ############################################################################################### # This script was written as part of the analysis conducted on the output generated by # # hmmsearch, when...
2,848
1,051
""" All permissions are defined here. They are also defined in permissions.zcml. The two files must be kept in sync. bika.lims.__init__ imports * from this file, so bika.lims.PermName or bika.lims.permissions.PermName are both valid. """ from Products.CMFCore.permissions import AddPortalContent #...
6,349
2,080
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Li...
5,140
1,747
#!/usr/bin/env python # -*- coding:utf-8 -*- import os import json from collections import Counter, defaultdict from data_convert.format.text2tree import Entity_Type, Text2Tree from data_convert.task_format.event_extraction import Event, DyIEPP, Conll04 from data_convert.utils import read_file, check_output, data_count...
7,645
2,195
from scrapy.utils.misc import walk_modules from scrapy.utils.spider import iter_spider_classes def get_spider_cls(url, spider_packages, default): """ Return spider class based on provided url. :param url: if it looks like `spider://spidername` it tries to load spider named `spidername`, otherwise...
1,246
360
import torch import torch.nn as nn from torch.nn import init import torch.nn.functional as F class Social_Encoder(nn.Module): def __init__(self, features, embed_dim, social_adj_lists, aggregator, base_model=None, cuda="cpu"): super(Social_Encoder, self).__init__() self.features = features ...
1,165
381
import click import time from deephub.common.io import resolve_glob_pattern from deephub.models.feeders.tfrecords.meta import generate_fileinfo, get_fileinfo, TFRecordValidationError, \ TFRecordInfoMissingError @click.group() def cli(): """ General purpose CLI utils. """ pass @cli.command() @cl...
3,280
894
import numpy as np import cPickle import os from scipy.io import loadmat import time import h5py import json import copy import bz2 def unique_rows(a): b = np.ascontiguousarray(a).view(np.dtype((np.void, a.dtype.itemsize * a.shape[1]))) _, idx = np.unique(b, return_index=True) return a[idx], idx; def setdiff2d(...
10,072
3,843
dict = {} lista = [] soma = 0 while True: dict['nome'] = str(input('Nome: ')).capitalize() dict['sexo'] = str(input('Sexo: ')).strip().upper()[0] while dict['sexo'] not in 'MF': print('ERRO! Por favor, digite apenas M ou F') dict['sexo'] = str(input('Sexo: ')).strip().upper()[0] dict['id...
1,085
415
# -*- coding: utf8 -*- """ ====================================== Project Name: NLP File Name: linears Author: czh Create Date: 2021/11/15 -------------------------------------- Change Activity: ====================================== """ import math import torch import torch.nn as nn import torch....
7,894
2,578
import requests def company(SIREN): r = requests.get('https://entreprise.data.gouv.fr/api/sirene/v2/siren/'+SIREN+'') json_object = r.json() settings = dict() if json_object['sirene']['status'] == 404: return None if json_object['sirene']['data']['siege_social']['nom_raison_sociale'...
2,037
776
""" Opdracht 9 - Loonbrief https://dodona.ugent.be/nl/exercises/990750894/ """ # functie voor start amount def get_start_amount(): # return start amount return int(input("Start bedrag: ")) # functie voor salaris def get_salary(): # array van salaris maken salary = [] # count op nul zetten c...
2,036
692
# coding: utf-8 from cv2 import cv2 import numpy as np cap = cv2.VideoCapture(0) while(1): # Take each frame _, frame = cap.read() # Convert BGR to HSV hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # define range of blue color in HSV lower_blue = np.array([110,50,50]) upper_blue = np.arr...
1,845
664
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
9,411
2,679
# Generated by Django 3.1.4 on 2020-12-30 00:27 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('votes', '0003_auto_20201229_1301'), ] operations...
830
263
from turtle import Turtle FONT = ("Arial", 10, "normal") ALIGN = "center" class Score(Turtle): def __init__(self): super().__init__() self.score = 0 self.color("White") self.penup() self.goto(0, 270) self.update() self.hideturtle() def update(self): ...
576
216
import numpy def layer_method(): return {"pi": "{0:.2f}".format(numpy.pi)}
81
32
"""Coverage based QC calculations. """ import glob import os import subprocess from bcbio.bam import ref, readstats, utils from bcbio.distributed import transaction from bcbio.heterogeneity import chromhacks import bcbio.pipeline.datadict as dd from bcbio.provenance import do from bcbio.variation import coverage as co...
5,520
1,914
""" Utility functions for argument parsing """ import argparse def str2bool(val): """ Resolving boolean arguments if they are not given in the standard format Arguments: val (bool or string): boolean argument type Returns: bool: the desired value {True, False} """ if isinstan...
1,210
340
from concepts.letter_addition import LetterAddition from learners.sim_memoryless_learner import SimMemorylessLearner def test_see_example(): concept = LetterAddition(6) learner = SimMemorylessLearner(concept, list(range(0, 7))) learner.see_example(((0, 1), 10))
277
98
import logging import pandas as pd from datetime import datetime from typing import ( Any, Callable, Dict, Hashable, Iterable, List, NamedTuple, Optional, Pattern, Set, Tuple, Union, ) logger = logging.getLogger(__name__) # add_jde_batch() {{{1...
2,536
887
import os import shutil import logging class BColors(object): HEADER = "\033[95m" OK_BLUE = "\033[94m" OK_CYAN = "\033[96m" OK_GREEN = "\033[92m" WARNING = "\033[93m" FAIL = "\033[91m" END_C = "\033[0m" BOLD = "\033[1m" UNDERLINE = "\033[4m" def touch(fname: str, times=None, crea...
2,159
839
#!/usr/bin/env python from __future__ import division, absolute_import, print_function from setuptools import setup import os import re import shutil _versionRE = re.compile(r'__version__\s*=\s*\"([^\"]+)\"') # read the version number for the settings file with open('drawBot/drawBotSettings.py', "r") as settings: ...
2,090
654
def get_p_distance(list1, list2): count = 0 i = 0 while i < len(list1): if (list1[i] != list2[i]): count += .1 i += 1 return count def get_p_distance_matrix(list1, list2, list3, list4): dna1 = get_p_distance(list1, list1), get_p_distance(list1, list2), get_p_distance(lis...
784
325
# # PySNMP MIB module ZHONE-COM-IP-FILTER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-COM-IP-FILTER-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:47:04 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 ...
38,634
13,626
############################################################################### # WaterTAP Copyright (c) 2021, The Regents of the University of California, # through Lawrence Berkeley National Laboratory, Oak Ridge National # Laboratory, National Renewable Energy Laboratory, and National Energy # Technology Laboratory ...
11,160
4,197
# Copyright 2013 Google Inc. All Rights Reserved. """Deletes a Cloud SQL instance.""" from googlecloudapis.apitools.base import py as apitools_base from googlecloudsdk.calliope import base from googlecloudsdk.calliope import exceptions from googlecloudsdk.core import log from googlecloudsdk.core.util import console_io...
2,680
703
"""Exceptions for this library""" class NSBaseError(Exception): """Base Error for all custom exceptions""" pass class RateLimitReached(NSBaseError): """Rate Limit was reached""" class NSServerBaseException(NSBaseError): """Exceptions that the server returns""" pass class APIError(NSServerBaseEx...
804
246
# lines 1-4 imports the necessary libraries import pygame import os import random import math import sys import hlp import intro import dsb # this is the last module with the description files ''' declaring some global variables beacause in Python, we can set global variables that can be used in future functions se...
62,639
18,070
import aiohttp import asyncio import async_timeout import logging from collections import namedtuple, deque from .events import Events from html.parser import HTMLParser log = logging.getLogger(__name__) class Parser(HTMLParser): def handle_starttag(self, tag, attrs): log.debug("Encountered a start tag:...
8,514
2,586
from ..models import Classify, Fields, Asset, AssetBind, ClassifyBind from django.db.models import Q from collections import OrderedDict from django.forms.models import model_to_dict class OperateInstance: @staticmethod def get_classify(id): """通过ID 查找指定分类表""" return Classify.objects.filter(id...
7,009
2,489
import subprocess from pathlib import Path from urllib.parse import urlparse def mirror_repo(repo_url, target_dir): repo_dir = Path(str(target_dir) + urlparse(repo_url).path) repo_dir.parent.mkdir(parents=True, exist_ok=True) if repo_dir.exists(): print(f'Updating from {repo_url}...') subp...
525
185
import os import torch from modeling.unet import * from modeling.bAttenUnet import MDecoderUNet, MMultiBAUNet, MMultiBUNet def build_model(args, nchannels, nclass, model='unet'): if model == 'unet': return UNet( n_channels=nchannels, n_classes=nclass, bilinear=True, ...
3,880
1,282
import os from os import listdir from os.path import isfile, join dir_path = os.path.dirname(os.path.realpath(__file__)) filesys = [f for f in listdir(dir_path) if isfile(join(dir_path, f))] def get_dir_size(path=dir_path): total = 0 with os.scandir(dir_path) as it: for entry in it: if en...
1,356
478
# coding=utf-8 from __future__ import unicode_literals from api_x.utils import response from api_x.utils.entry_auth import verify_request from flask import request from . import application_mod as mod from .. import dba from .. import bankcard from api_x.utils.parser import to_bool from pytoolbox.util.log import get_l...
3,111
1,062
import asyncio import os try: from aiohttp import web except ImportError: web = None class Httpd(object): def __init__(self): if not web: print('httpd is specified in conf but aiohttp not available') return self.app = web.Application() self._setup_routes()...
2,928
974
import math num = int(input()) is_prime = True if num < 2: print("Not prime") for i in range(2, int(math.sqrt(num)+1)): if num / i == 0: is_prime = False print(is_prime)
196
83
from django.apps import AppConfig class BadgifyConfig(AppConfig): name = 'badgify' verbose_name = 'Badgify' def ready(self): super(BadgifyConfig, self).ready() self.module.autodiscover()
218
73
from uliweb.i18n import ugettext_lazy as _ def test_1(): """ >>> x = _('Hello') >>> print repr(x) ugettext_lazy('Hello') """ def test_1(): """ >>> x = _('Hello {0}') >>> print x.format('name') Hello name """
249
99
import KeyPressModule as kp from djitellopy import tello import time import cv2 global img kp.init() skynet = tello.Tello() skynet.connect() print(skynet.get_battery()) skynet.streamon() def getKeyboardInput(): lr, fb, ud, yv = 0, 0, 0, 0 speed = 50 if kp.getKey("LEFT"): lr = -speed elif kp.getKey(...
1,041
466
from foolbox import zoo import numpy as np import foolbox import sys import pytest from foolbox.zoo.model_loader import ModelLoader from os.path import join, dirname @pytest.fixture(autouse=True) def unload_foolbox_model_module(): # reload foolbox_model from scratch for every run # to ensure atomic tests with...
1,479
528
""" Copyright 2015-2017 Peter Urda 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, softwar...
8,464
2,539
import cv2 import numpy as np import os from auto_pose.meshrenderer import meshrenderer from auto_pose.ae.utils import lazy_property class PoseVisualizer: def __init__(self, mp_pose_estimator, downsample=1, vertex_scale=False): self.downsample = downsample self.vertex_scale = [mp_pose_estimator...
5,417
1,981
# SPDX-FileCopyrightText: 2021 Carnegie Mellon University # # SPDX-License-Identifier: Apache-2.0 import cv2 import numpy as np import rospy from gabriel_protocol import gabriel_pb2 from std_msgs.msg import UInt8MultiArray def run_node(client_filter, source_name): rospy.init_node(source_name + "_subscriber_node"...
1,128
366
# -*- coding: utf-8 -*- """ :copyright: ©2018 by IPIP.net """ from .district import District class BaseStation(District): pass
138
58
""" User module """ import discord import random import asyncio from discord.ext import commands from discord.ext.commands import has_permissions, MissingPermissions, BadArgument import requests, json, pyfiglet from datetime import timedelta, datetime class User(commands.Cog): api_key = "bbde6a19c33fb4c3962e36b...
13,034
3,925
def sync_read(socket, size): """ Perform a (temporary) blocking read. The amount read may be smaller than the amount requested if a timeout occurs. """ timeout = socket.gettimeout() socket.settimeout(None) try: return socket.recv(size) finally: socket.settimeout(time...
622
182
#Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None import sys class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ temp = ListNode(-1) ...
976
267
# Copyright 2017 F5 Networks 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 writi...
1,334
420
"""Admin sites for the ``django-tinylinks`` app.""" from django.contrib import admin from django.template.defaultfilters import truncatechars from django.utils.translation import ugettext_lazy as _ from django.template.loader import render_to_string from tinylinks.forms import TinylinkAdminForm from tinylinks.models ...
1,281
409
import requests import json def main(): host = "http://localhost:5006" urlpattern = "/user/" response = requests.post(f"{host}{urlpattern}", json={'key1': 'random value'}) if 199 < response.status_code < 300: for k, v in response.headers.items(): print(f"{k} -> {v}") prin...
562
198
#!/usr/bin/env python from XilinxKcu1500Pgp3.XilinxKcu1500Pgp3 import *
73
41
#!/usr/bin/python import os import glob import traceback import datetime import dandan from flask import Flask from flask import abort from flask import send_file from flask import send_from_directory from flask import render_template from werkzeug.routing import BaseConverter import config __VERSI...
2,517
874
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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 ...
2,961
1,019
from .array import Array from .string import String from .problem import Constraint, Loop from .main import SatType, Var, Number from .expr import Expr
155
44
import os __magma_codegen_debug_info = False if os.environ.get("MAGMA_CODEGEN_DEBUG_INFO", False): __magma_codegen_debug_info = True def set_codegen_debug_info(val): global __magma_codegen_debug_info __magma_codegen_debug_info = val def get_codegen_debug_info(): return __magma_codegen_debug_info ...
470
177
#!/usr/bin/env python3 from subprocess import Popen, PIPE, DEVNULL, run import socket import sys import traceback import argparse import time import logging import os logger = logging.getLogger("django") def startProcess(command, port): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
3,560
1,063
NAME="Sensor Location" UUID=0x2A5D
35
18
import random from tqdm import tqdm def random_seq(): return [str(random.randint(1, 9)) for x in range(random.randint(2, 15))] if __name__ == "__main__": with open("sequences-1-train.txt", "w") as f: for i in tqdm(range(5000)): f.write(",".join(random_seq()) + "\n")
296
116
"""Datatest main program""" import sys as _sys from unittest import TestProgram as _TestProgram from unittest import defaultTestLoader as _defaultTestLoader try: from unittest.signals import installHandler except ImportError: installHandler = None from datatest import DataTestRunner __unittest = True __datat...
3,585
894
# Copyright 2017 IBM Corp. # # 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 t...
17,503
5,298
""" Q146 LRU Cache Medium Author: Lingqing Gan Date: 08/06/2019 Question: Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return ...
3,481
1,092
# This script reads *VizParams.list files that define Vizlet parameters # and generates .h files for them, making runtime access to them much faster. # This allows new parameters to be added just by editing one file. import sys import os import re types={"bool":"BOOL","int":"INT","double":"DBL","string":"STR"} realt...
9,940
3,942
import cv2 import numpy as np import matplotlib.pyplot as plt #Read the image as grayscale: image = cv2.imread('building.jpg', 0) #Compute the gradient approximations using the Sobel operator: dx = cv2.Sobel(image, cv2.CV_32F, 1, 0) dy = cv2.Sobel(image, cv2.CV_32F, 0, 1) #Visualize the results: plt.figu...
712
340
# -*- coding: utf-8 -*- # reporter-cli/sql-pdf/python/src/reporterprimary/__init__.py # ============================================================================= # Reporter Multilang. Version 0.5.9 # ============================================================================= # A tool to generate human-readable re...
956
256
import numpy as np from uncertainties import umath as um def getTeqpl(Teffst, aR, ecc, A=0, f=1/4.): """Return the planet equilibrium temperature. Relation adapted from equation 4 page 4 in http://www.mpia.de/homes/ppvi/chapter/madhusudhan.pdf and https://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law...
3,494
1,319
import pandas as pd import re import os from tqdm import tqdm ## Cleaning train raw dataset train = open('./data/raw/train.crash').readlines() train_ids = [] train_texts = [] train_labels = [] for id, line in tqdm(enumerate(train)): line = line.strip() if line.startswith("train_"): train_ids.append...
1,656
634
import functools from types import SimpleNamespace from typing import List from . import globs from .context import BaseContext from .exceptions import FixtureProcessError from .reloader import Reloader from .static_registry import static_registry def _dummy_exception_handler(ctx: BaseContext, exc: Exception): r...
6,456
1,953
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import numpy as np import os import sys from observations.util import maybe_download_and_extract def chest_sizes(path): """Chest measurements of 5738 Scottish Militiamen ...
1,772
572
import pathlib from setuptools import setup, find_packages HERE = pathlib.Path(__file__).parent README = (HERE / "README.md").read_text() setup(name="google-ads-api-report-fetcher", version="0.1", description="Library for fetching reports from Google Ads API and saving them locally / BigQuery.", lo...
1,365
420
#!/usr/bin/env python3 # Copyright 2004-present Facebook. All Rights Reserved. import asyncio import logging import time from collections import defaultdict from typing import DefaultDict, Dict, List from tglib.clients.prometheus_client import PrometheusClient, consts from tglib.exceptions import ClientRuntimeError ...
2,880
805
import glob import os from io import StringIO from threading import Thread import logging from logger import TimeHandler from costants import THREADS, INFERENCE_GRAPH from pipeline import pipeline logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.addHandler(TimeHandler().handler) ...
1,866
622
# -*- coding: utf-8 -*- # Python 2 standard library imports import csv import io import logging import os # Python 2 non-standard library imports import pandas as pd # Imports from Oasis core repos + subpackages or modules within keys_server from oasislmf.utils.coverages import COVERAGE_TYPES from oasislmf.utils.per...
12,319
4,463
import time import sys import json import argparse from tqdm import trange from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch import numpy as np from scipy.spatial.distance import jensenshannon import gym import matplotlib.pyplot as plt from matplotlib.axes import Axes fr...
18,485
6,909
from fractions import Fraction from math import gcd import numpy as np """ Convert the style of gambling odds to Function Name (Decimal, American, Fractional). TO DO: Fix edge case related to Fraction module that causes weird rounding / slightly off output """ def american_odds(odds): """ :param odds: ...
3,289
1,199
# Copyright (c) 2017 Sony Corporation. 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 applicabl...
16,438
6,658
# # Copyright (c) 2019, Neptune Labs Sp. z o.o. # # 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 agr...
2,973
911
#!/usr/bin/python3 -S # -*- coding: utf-8 -*- """ `Redis Map Tests` --·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·-- 2015 Jared Lunde © The MIT License (MIT) http://github.com/jaredlunde """ import datetime import time import pickle import unittest from redis_structures.debug ...
5,219
1,832
# -*- coding: utf-8 -*- from beacontools import parse_packet # Eddystone UID packet uid_packet = b"\x02\x01\x06\x03\x03\xaa\xfe\x17\x16\xaa\xfe\x00\xe3\x12\x34\x56\x78\x90\x12" \ b"\x34\x67\x89\x01\x00\x00\x00\x00\x00\x01\x00\x00" uid_frame = parse_packet(uid_packet) print("Namespace: %s" % uid_frame.nam...
4,480
2,376
from kedro.io import DataCatalog, MemoryDataSet from kedro.pipeline import Pipeline from kedro.runner import SequentialRunner import mlsurvey as mls from mlsurvey.workflows.learning_workflow import LearningWorkflow class MultipleLearningWorkflow(LearningWorkflow): def run(self): """ Run the wor...
1,228
343
# Generated by Django 2.2.12 on 2020-06-15 16:55 import datetime from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('project', '0001_initial'), ] operations = [ migrations.CreateModel( ...
2,542
844
# -*- coding: utf-8 -*- """ base.py Base Cipher Object class @author: Douglas Daly @date: 1/12/2017 """ # # Imports # from abc import ABCMeta, abstractmethod from ..alphabets import English # # Classes # class Cipher(object, metaclass=ABCMeta): """ Base Cipher Class """ def __init__(self,...
1,055
328
from setuptools import setup setup( name="codewars_unittest", version="0.1.0", packages=["codewars_unittest"], license="MIT", description="unittest runner with Codewars output", install_requires=[], url="https://github.com/Codewars/python-unittest", )
281
94
""" FactSet Funds API FactSet Mutual Funds data offers over 50 fund- and share class-specific data points for mutual funds listed in the United States. <p>FactSet Mutual Funds Reference provides fund-specific reference information as well as FactSet's proprietary classification system. It includes but is not l...
16,628
4,281
import os, sys import subprocess import xmltodict import lymask from lymask import batch_drc_main from conftest import test_dir drc_file = os.path.join(test_dir, 'tech', 'lymask_example_tech', 'drc', 'default.yml') layout_file = os.path.join(test_dir, '2_drc_src.oas') outfile = os.path.join(test_dir, '2_drc_run.lyrdb...
1,637
587
"""Rendering formatter parameter handling.""" import typing from . import base __all__ = ['FORMATTERS', 'verify_formatter', 'Formatter'] FORMATTERS = {'cairo', 'core', 'gd', 'gdiplus', 'gdwbmp', 'xlib'} REQUIRED = False def verify_formatter(fo...
1,731
507
import torch CONFIG = {"device": torch.device("cuda" if torch.cuda.is_available() else "cpu")} def get(): return CONFIG["device"] def set_device(device): CONFIG["device"] = device
183
63
import logging import random import os import json from typing import Tuple, List import requests def predict(player_name: str) -> str: next_move = _predict_next_move(*_get_player_games(player_name)) return _convert_game_to_json(next_move) R_rock, P_paper, S_scissors, V_spock, L_lizard = ('R', ...
5,727
2,166
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import shutil import logging import tensorflow as tf from src.cifar10.data_utils import read_data from src.cifar10.general_child import GeneralChild import src.cifar10_flags from src.cifar10_flags impo...
5,410
1,901
from django.apps import AppConfig class OperConfig(AppConfig): name = 'oper' verbose_name = '用户操作管理' def ready(self): from oper import signals
175
63
# -*- coding: utf-8 -*- import io import collections from stella.core.utils import RewindableIterator from stella.core.interpreter.productions import Token __all__ = ['Tokenizer', 'Lexer'] ################################################################################ ### Tokenizer ################################...
1,952
481
import matplotlib.pyplot as plt import numpy as np import tensorflow as tf tf.logging.set_verbosity(tf.logging.ERROR) max_epochs = 6000 init_stddev = 0.0001 source_embedding_size = 2 target_embedding_size = 2 source_state_size = 2 preattention_size = 2 target_state_size = 2 max_seq_len = 10 source_tokens = [ ...
12,628
4,059
import codecs def encode_macaroon(macaroon): encoded_macaroon = codecs.encode(macaroon, 'hex') return encoded_macaroon def read_file(file_path): opened_file = open(file_path, 'rb').read() return opened_file
226
81
import numpy as np from ctapipe.core import Component from ctapipe.containers import MuonRingContainer from .fitting import kundu_chaudhuri_circle_fit, taubin_circle_fit import traitlets as traits # the fit methods do not expose the same interface, so we # force the same interface onto them, here. # we also modify th...
1,649
576
import pandas as pd from os import listdir import numpy from sklearn.model_selection import StratifiedKFold from FS_ALO import WFS from FW_ALO import WFW from WFSWFW_ALO import WFSWFW import matplotlib.pyplot as plt def main_CV(): path='./datasets' direc=sorted(listdir(path)) print(direc) ...
1,873
794
#! /usr/bin/env python # -*-coding: utf-8 -*- __author__ = 'dracarysX' from django.db import models class Publisher(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) class Meta: db_table = 'Publisher' def __str__(self): return 'Publisher:...
1,189
412
# Copyright © 2019 Province of British Columbia # # 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 agr...
4,796
1,279
from django.conf import settings from django.conf.urls import * from django.conf.urls.static import static from django.contrib import admin from django.contrib.sitemaps.views import sitemap from django.views.decorators.cache import cache_page from django.views.generic import TemplateView from ajax_select import urls as...
2,334
812
import datetime from database.database_schemas import Schemas from sqlalchemy import Column, Integer, String, DateTime from database.base import Base class Contacts(Base): """Maps to contacts table in chemprop databases.""" __tablename__ = 'contacts' __table_args__ = {'schema': Schemas.qsar_schema} ...
899
269
""" Gradescope autograder configuration generator for Otter Generate """ import os import json import shutil # import subprocess import zipfile import tempfile import pathlib import pkg_resources import yaml from glob import glob from subprocess import PIPE from jinja2 import Template from .token import APIClient fr...
7,487
2,144