id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
6513255
<filename>tests/test_kubernetes_tools.py import unittest from typing import Sequence import mock import pytest from kubernetes.client import V1AWSElasticBlockStoreVolumeSource from kubernetes.client import V1Container from kubernetes.client import V1ContainerPort from kubernetes.client import V1Deployment from kuberne...
StarcoderdataPython
1764466
<reponame>reven86/dava.engine import sys import glob, os import re import argparse import subprocess from contextlib import closing def GetDavaVersion( pathToFramework ): os.chdir(pathToFramework) file = open("Sources/Internal/DAVAVersion.h"); p = re.compile('DAVAENGINE_VERSION "([\w\.]+)"'); ...
StarcoderdataPython
158933
<filename>tests/endpoints/steps/get_all_type_games_endpoint_steps.py from .util.util_neo4j import UtilNeo4j CODE = "code" NAME = "name" LEVEL = "level" TYPE_GAME_1_EXPECT = "type_game_1" LEVEL_EXPECT = 50 class ShouldGetAllTypeGameSteps: def given(self, client, user_id, type_games): self.user_id = user_i...
StarcoderdataPython
4849547
from api.models import AlbumComment from .comment_serializer import CommentSerializer from .generic_audited_model_serializer import GenericAuditedModelSerializer class AlbumCommentSerializer(GenericAuditedModelSerializer): comment = CommentSerializer() class Meta: model = AlbumComment fields...
StarcoderdataPython
6637071
# Copyright 2011-2016 MongoDB, 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 writin...
StarcoderdataPython
3350872
import os.path import os import pickle import time import numpy as np from numpy.testing import assert_almost_equal, assert_equal, assert_allclose import scipy.stats as stats # Before removing what appear to be unused imports think twice. # Some of the tests use eval, which requires the imports. import refnx.reflect._...
StarcoderdataPython
3211919
import matplotlib.pyplot as plt import numpy as np from api.folders import IMAGES_FOLDER from api.parameters import RegLambda def plot_accuracy_comparison(accuracies, titles, ax=None): x = [lmbd.value for lmbd in RegLambda] xticks = np.linspace(0, 1, len(x)) colors = ['C{}'.format(i) for i in range(8)] ...
StarcoderdataPython
9765386
<reponame>identixone/fastapi_contrib def test_settings_from_env_and_defaults(): from fastapi_contrib.conf import settings assert settings.fastapi_app == "tests.conftest.app" assert settings.now_function is None assert settings.Config.secrets_dir == "/tmp/secrets" assert settings.jaeger_sampler_rate ...
StarcoderdataPython
6701043
# <NAME> import os import platform import numpy as np from time import sleep from PIL import ImageGrab from game_control import * from predict import predict from game_control import * from keras.models import model_from_json def main(): # Get Model: model_file = open('data/model/model.json', 'r') model =...
StarcoderdataPython
23336
from typing import Dict import numpy as np import torch from torch.nn.functional import linear, log_softmax, embedding from torch.nn import Dropout, LogSoftmax, NLLLoss from allennlp.common import Params from allennlp.models.model import Model from allennlp.data.vocabulary import Vocabulary, DEFAULT_PADDING_TOKEN from...
StarcoderdataPython
5155342
<filename>tests/conftest.py<gh_stars>10-100 import pytest from . import utils @pytest.fixture(scope='session') def url(request): utils.cd_test_dir() utils.start_server() url = utils.get_url() from twill import set_output from twill.commands import go, find set_output() try: go(u...
StarcoderdataPython
8037390
<reponame>zhj12138/ebook-manager # 此文件存储搜索方法 # 解析查询字符串 def parseString(sear_str): pass # 根据书名查找 def searchByName(name): pass # 按照作者查询 def searchByAuthor(author_name): pass # 按照出版商查询 def searchByPublisher(publisher_name): pass # 按照标签查询 def searchByTag(tag): pass # 按照书单查询 def searchByBookLi...
StarcoderdataPython
9726637
<gh_stars>1-10 import sphinx_bootstrap_theme html_css_files = [ "https://cdn.jsdelivr.net/gh/ickc/markdown-latex-css/css/_table.min.css", "https://cdn.jsdelivr.net/gh/ickc/markdown-latex-css/fonts/fonts.min.css", ] extensions = [ "sphinx.ext.autodoc", "sphinx.ext.autosummary", "sphinx.ext.coverage...
StarcoderdataPython
11241694
import keras from keras.layers import Input, Embedding, LSTM, Bidirectional, Reshape, Lambda from keras.layers import concatenate import keras.backend as K def get_shape(x): return K.int_shape(x) def create_vector_input(dim): return Input(shape=(dim,), dtype='float32') def create_sequence_input(sequence_l...
StarcoderdataPython
1842688
from selenium.webdriver.common.keys import Keys from random import choice, randint from selenium import webdriver from time import sleep class Instagram_ComentBot: def __init__(self, username, password): self.username = username self.password = password self.driver = webdriver.Firefox() ...
StarcoderdataPython
11210920
<filename>src/DataJoin/controller/sync_convert_data_block.py # Copyright 2020 The 9nFL Authors. 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....
StarcoderdataPython
11378599
# -*- coding: utf-8 -*- # This file is auto-generated, don't edit it. Thanks. class Client: """ This is a number module """ @staticmethod def parse_int( raw: str, ) -> int: return int(raw) @staticmethod def parse_long( raw: str, ) -> int: r...
StarcoderdataPython
3213667
<filename>code/Q3pre.py import numpy as np import pandas as pd pr_mat=pd.read_csv('data3/pr.csv',index_col=0) index=[] for i,r in pr_mat.iterrows(): if r.values[0]>0.05 and r.values[1]>0.05: pr_mat=pr_mat.drop(i) index.append(i) print(index) print(len(index)) pr_mat.to_csv('./dropData.csv')
StarcoderdataPython
1882685
<reponame>phlong3105/onevision<filename>src/onevision/models/detection/scaled_yolov4/ensemble.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ """ from __future__ import annotations import argparse import csv import itertools import os import test from onevision.utils import pretrained_dir if __name__ == "__ma...
StarcoderdataPython
12836931
# -*- coding: utf-8 -*- # Author: <NAME> <<EMAIL>> # License: BSD 3 clause """ Unitary tests for bigfish.stack.filter module. """ import pytest import numpy as np import bigfish.stack as stack from bigfish.stack.filter import _define_kernel from numpy.testing import assert_array_equal from numpy.testing import ass...
StarcoderdataPython
6652281
# MIT License # # Copyright (c) 2017 <NAME> # # 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, pub...
StarcoderdataPython
8130247
<filename>cifar10/dev/utils_data.py<gh_stars>0 import os # import imageio # import yaml import torch import torchvision from torch.utils.data.dataset import Subset from torchvision.transforms import (CenterCrop, Compose, RandomHorizontalFlip, Resize, ToTensor) import pickle import numpy as np import pdb st = pdb.set_tr...
StarcoderdataPython
1791782
from imdb import IMDB # from pascal_voc import PascalVOC # from cityscape import CityScape # from coco import coco from road_images import RoadImages
StarcoderdataPython
1854340
<gh_stars>0 from pytest import mark, raises from sls.parser.lexer import ErrorCodes, LexerException, Tokenizer def tokenize(text): """Returns a list of tokens""" return [*Tokenizer(text).tokenize()] def simple_tokenize(text): """Return a list of only the token ids""" toks = tokenize(text) retur...
StarcoderdataPython
3482105
from datetime import datetime, timedelta import numpy as np import pytides from pytides import constituent as cons from pytides.tide import Tide as PyTide from .constants import DATE_FORMAT, FOOT, HIGH, UTC, METERS NOAA_CONSTITUENTS = [c for c in cons.noaa if c != cons._Z0] + [cons._Z0] SIX_HOURS = timedelta(hours...
StarcoderdataPython
8025927
<reponame>sprocter/lab-games from clocks.clock import Clock class Increment(Clock): increment = 0 # Stores the amount to increment the player's clocks by def __init__(self, player_count=0, player_names=None, increment_amount=30, starting_clock=5): super().__init__(player_count=player_count, player_n...
StarcoderdataPython
1757909
<filename>apps/web/forms/issues.py from django import forms from django.core.exceptions import ValidationError from apps.web.forms.bootstrap import BootStrapForm from apps.web.models import Issues, ProjectUser, IssuesType, Module, IssuesReply, ProjectInvite class IssuesModelForm(BootStrapForm, forms.ModelForm): "...
StarcoderdataPython
4973014
<reponame>luispedro/Coelho2021_GMGCv1_analysis import numpy as np from scipy import stats from glob import glob from itertools import islice def build_ctable(g0, g1, total): c = np.zeros((2,2)) c[1,1] = len(g0 & g1) c[1,0] = len(g0 - g1) c[0,1] = len(g1 - g0) c[0,0] = total - c.sum() return c ...
StarcoderdataPython
5085476
<gh_stars>10-100 # -*- coding: utf-8 -*- """ Arguments Created on 2020/5/13 """ __author__ = "<NAME>" class Arguments: """ General settings of arguments """ # Device device = 'cuda' # Path raw_data_dir = '../data/raw' raw_data_train = raw_data_dir + '/train.csv' raw_data_val =...
StarcoderdataPython
4991313
<filename>qcfractal/interface/orm/torsiondrive_orm.py """ A ORM for TorsionDrive """ import json class TorsionDriveORM: """ A interface to the raw JSON data of a TorsionDrive torsion scan run. """ # Maps {internal_status : FractalServer status} __json_mapper = { "_id": "id", "_su...
StarcoderdataPython
3362003
# -*- coding: utf-8 -*- # Simple Bot (SimpBot) # Copyright 2016-2017, <NAME> (kwargs) from simpbot.bottools import text import time class user: def __init__(self, user, host, nick, realname=None, account=None): self.user = user self.host = host self.nick = nick self.realname = re...
StarcoderdataPython
9638426
import rethinkdb as r def handler(db_conn, event): servers = r.db('rethinkdb').table('server_status').run(db_conn) server_count = len(list(servers)) return "I'm in a cluster with %d rethinkdb servers" % server_count
StarcoderdataPython
11207715
from trello import TrelloClient import pprint, requests,os client = TrelloClient( api_key=os.environ.get('Trello_API_KEY'), token=os.environ.get('Trello_API_TOKEN'),) attachments = [] def list_all_boards(client): """ get list of all boards to determine the ID for further...
StarcoderdataPython
134054
import glob import os import pickle import shlex import tarfile import tempfile import threading from typing import Any, Dict, Iterable, List, NamedTuple, Optional, Set, Tuple, Union import boto3 from redun.file import File from redun.hashing import hash_stream from redun.scheduler import Job # Constants. REDUN_PROG...
StarcoderdataPython
12863964
<reponame>seculayer/automl-mlps # -*- coding: utf-8 -*- # Author : <NAME> # e-mail : <EMAIL> # Powered by Seculayer © 2021 Service Model Team from mlps.core.data.cnvrtr.ConvertAbstract import ConvertAbstract class IPTransferDivide(ConvertAbstract): def __init__(self, **kwargs): super().__init__(**kwargs)...
StarcoderdataPython
3286682
from django.urls import path from cride.circles.views import list_circles, create_cricle urlpatterns = [ path('circles/', list_circles), path('circles/create/', create_cricle), ]
StarcoderdataPython
90263
<filename>volatility/volatility/plugins/linux/keyboard_notifiers.py<gh_stars>1-10 # Volatility # # This file is part of Volatility. # # Volatility is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License Version 2 as # published by the Free Software Foundation. You...
StarcoderdataPython
1995087
################################################################################################################################ # *** Copyright Notice *** # # "Price Based Local Power Distribution Management System (Local Power Distribution Manager) v1.0" # Copyright (c) 2016, The Regents of the University of Califor...
StarcoderdataPython
8113226
'''初始化''' from .qrcodegenerator import QRCodeGenerator
StarcoderdataPython
11375519
# =============================================================================== # Copyright 2016 dgketchum # # 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...
StarcoderdataPython
292782
<gh_stars>1-10 import math def isPrime(n): if n == 1: return False i = 2 while i*i <= n: if n % i == 0: return False i += 1 return True t = int(input()) finalAns = [] for i in range(t): n = int(input()) if(n<4): readList = [i for i in range(1,...
StarcoderdataPython
1930366
# coding: utf-8 import datetime import os AUTHOR = '<NAME>' SITENAME = '<NAME>' SITESUBTITLE = "Hello, I'm Martin, and this is my webpage." SITEURL = '' MENUITEMS = ( # Put this page first (it's "hidden" and must appear before categories in # the menu) ("About me", "aboutme.html"), ) PATH = 'content' STA...
StarcoderdataPython
6424565
import numpy as np import pandas as pd from src.testing.rapid_test_reactions import rapid_test_reactions def test_rapid_test_reactions(): states = pd.DataFrame() states["quarantine_compliance"] = [0.0, 0.2, 0.4, 0.6, 0.8] states["cd_received_rapid_test"] = 0 states["is_tested_positive_by_rapid_test"]...
StarcoderdataPython
12826576
<reponame>Emiyalzn/EI328-hw1 import time import pickle import os import numpy as np import argparse from utils import load_data, mse_loss, plot_boundaries, partition_data, plot_minmax_boundaries, result_dir, plot_datapoints from model import MLP, MLQP from copy import deepcopy from multiprocessing import Pool def pars...
StarcoderdataPython
11307927
from math import exp, factorial class Erlang(object): def __init__(self, shrinkage:float=0.35, calls:int=200, aht:int=400, tat:int=20, ap:int=60): super().__init__() self.shrinkage = shrinkage self.calls = calls self.aht = aht self.tat = tat self.ap = ap def __call__(self, sh...
StarcoderdataPython
1999147
"""Manage in-memory profile interaction.""" from collections import OrderedDict from typing import Any, Mapping, Type from ..config.injection_context import InjectionContext from ..storage.base import BaseStorage from ..utils.classloader import DeferLoad from ..wallet.base import BaseWallet from .profile import Prof...
StarcoderdataPython
264187
from django.conf import settings from django.core.exceptions import ImproperlyConfigured class Config(object): def __init__(self, **kwargs): self.defaults = kwargs def __getattr_(self, name): try: return getattr(settings, name) except AttributeError: if name n...
StarcoderdataPython
6415485
<filename>src/fizzbuzz/fizzbuzz.py def fizzbuzz(n: int) -> dict: error = _invalid_n(n) if error: return dict(error=error) fizzbuzz = [_do_fizzbuzz(i) for i in range(1, n + 1)] return dict(data=fizzbuzz) def _do_fizzbuzz(n: int) -> str: parts = [] if n % 3 == 0: parts.append("f...
StarcoderdataPython
6598440
# Copyright 2014 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Umpire RPC base class.""" def RPCCall(method): """Enables the method to be Umpire RPC function. Args: method: an unbound derived UmpireRPC c...
StarcoderdataPython
4853567
<filename>make_CSVs.py #This file takes the survey response data from the original Excel file and transforms #it into two CSV files suitable for NLP analysis. import pandas as pd import numpy as np import pickle #Read in the Excel file data_dict = pd.read_excel('data_files/NPS_SignificanceUnderstanding.xlsx', sheetn...
StarcoderdataPython
9723787
import sqlalchemy from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Posts(Base): __tablename__ = 'posts' post_id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True) post_hash = sqlalchemy.Column(sqlalchemy.String) file_name = sqlalchemy.Column(sqlalchemy.Str...
StarcoderdataPython
8154027
<reponame>jabra98/aoc import sys; datafilepath = sys.argv[1] lines = open(datafilepath).read().splitlines() pairs = {'(':')','<':'>','[':']','{':'}', ')':'(','>':'<',']':'[','}':'{'} end_seqs = list() ans = 0 for i in lines: s = list() is_valid=True for j in i: if j in ['(','<','[','{']: ...
StarcoderdataPython
11357974
# Generated by Django 3.2.9 on 2021-12-09 18:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('meals', '0001_initial'), ] operations = [ migrations.AddField( model_name='meal', name='prev_status', fi...
StarcoderdataPython
8041814
# Generated by Django 3.1.1 on 2020-10-21 17:36 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('nutrihacker', '0010_auto_20201021_1333'), ] operations = [ migrations.RenameField( model_name='recipefood', old_name='amount...
StarcoderdataPython
3263338
<filename>events/migrations/0003_auto_20200421_0138.py # Generated by Django 3.0.5 on 2020-04-21 05:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('events', '0002_auto_20200421_0134'), ] operations = [ migrations.RemoveField( ...
StarcoderdataPython
8139240
from pom_pages.recreations import RecreationsPage recreation_name = "text=playwright-test" def test_find_recreation_is_working(page): recreation_page = RecreationsPage(page) recreation_page.open() recreation_page.select_recreation(recreation_name) # verify hike name assert page.inner_text( ...
StarcoderdataPython
9083
import sqlite3 from bottle import route, run,debug,template,request,redirect @route('/todo') def todo_list(): conn = sqlite3.connect('todo.db') c = conn.cursor() c.execute("SELECT id, task FROM todo WHERE status LIKE '1'") result = c.fetchall() c.close() output = template('make_table', rows=res...
StarcoderdataPython
345140
<reponame>banesullivan/PVGeophysics __all__ = [ 'TensorMeshReader', 'TensorMeshAppender', 'TopoMeshAppender', ] __displayname__ = 'Tensor Mesh' import os import sys import numpy as np import pandas as pd import vtk from .. import _helpers, interface from ..base import AlgorithmBase from .two_file_base i...
StarcoderdataPython
8151062
<reponame>iamdanialkamali/zibal-wallet from mongoengine import * class Wallet(Document): id = ObjectIdField() name = StringField() credit = FloatField() class Transaction(Document): id = ObjectIdField() source_wallet_id = ObjectIdField() destination_wallet_id = ObjectIdField(default=None) ...
StarcoderdataPython
1814345
import encrypt import decrypt MORSE_CODE_DICT = {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '-...
StarcoderdataPython
9759195
<filename>neptune-notebooks/__init__.py # # 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 # # ...
StarcoderdataPython
4904555
import math from BitTornado.clock import clock from .CurrentRateMeasure import Measure DEBUG = False MAX_RATE_PERIOD = 20.0 MAX_RATE = 10e10 PING_BOUNDARY = 1.2 PING_SAMPLES = 7 PING_DISCARDS = 1 PING_THRESHHOLD = 5 PING_DELAY = 5 # cycles 'til first upward adjustment PING_DELAY_NEXT = 2 # 'til next ADJUST_UP = 1.0...
StarcoderdataPython
11342323
# 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 # distrib...
StarcoderdataPython
136283
__all__ = ["InvalidECFGFormatException"] class InvalidECFGFormatException(Exception): pass
StarcoderdataPython
6468891
# Copyright (C) 2019-2021 by Vd. # This file is part of Wheelchair, the async CouchDB connector. # Wheelchair is released under the MIT License (see LICENSE). import pytest from wheelchair import Connection @pytest.mark.asyncio async def test_session(admin_connection: Connection): await admin_connection.authen...
StarcoderdataPython
11269993
<reponame>leon3110l/katana_tsl_patch from typing import List from .pedals.pedal import BasePedal, FXPedal from .pedals.delay import Delay from .pedals.fx import FX from importlib import import_module import json class Patch(): def __init__(self, name: str, pedals: List[BasePedal] = []): self.name = name ...
StarcoderdataPython
3364124
<reponame>ggsdc/corn """ This file contains the base for a sign up endpoint """ from flask import current_app from cornflow_core.authentication import BaseAuth from cornflow_core.constants import AUTH_LDAP, AUTH_OID from cornflow_core.exceptions import ( EndpointNotImplemented, InvalidCredentials, Invalid...
StarcoderdataPython
5057439
<gh_stars>1-10 #!/usr/bin/env python """ @file fixedTimeControl.py @author <NAME> @date 31/01/2013 class for fixed time signal control """ import signalControl, readJunctionData, traci class fixedTimeControl(signalControl.signalControl): def __init__(self, junctionData): super(fixedTimeControl, se...
StarcoderdataPython
5009493
<filename>community_tca9555.py # SPDX-FileCopyrightText: 2017 <NAME>, written for Adafruit Industries # SPDX-FileCopyrightText: Copyright (c) 2021 <NAME> # # SPDX-License-Identifier: MIT """ `community_tca9555` ================================================================================ CircuitPython library for ...
StarcoderdataPython
12850529
<filename>src/Noncircular/Calculations/_Appendix13_7_c.py<gh_stars>1-10 import math # TODO: Implement acceptibility tests class Appendix13_7_cParams: def __init__( self, internal_pressure, corner_radius, short_side_half_length, long_side_half_length, ...
StarcoderdataPython
11212762
<gh_stars>1-10 import time import random import re import os from requests.sessions import Session import json try: import execjs is_execjs_imported = True except: is_execjs_imported = False if not is_execjs_imported: try: """ Name: Js2Py Version: 0.37 ...
StarcoderdataPython
80218
#!/usr/bin/env python """ Created by howie.hu at 08/04/2018. """ import asyncio import sys import time sys.path.append('../../') from hproxy.database import DatabaseSetting from hproxy.utils import logger from hproxy.spider.proxy_tools import get_proxy_info db_client = DatabaseSetting() async def valid_proxies():...
StarcoderdataPython
6465572
<reponame>Bohdanski/fuzzy-lookup<filename>fuzzy_lookup.py import os import sys import csv import xlsxwriter from fuzzywuzzy import fuzz from fuzzywuzzy import process # User input base = "tblTopsMatch.csv" match = "tblWegmansMatch.csv" base_field = "topsDesc" match_field = "wegmansDesc" method = "sort" threshold = ...
StarcoderdataPython
5034720
<reponame>lavanyashukla/ray<gh_stars>1-10 import ray from ray import serve import requests ray.init() client = serve.start() def say_hello(request): return "hello " + request.query_params["name"] + "!" # Form a backend from our function and connect it to an endpoint. client.create_backend("my_backend", say_hel...
StarcoderdataPython
4827513
#!/usr/bin/env python ''' Copyright (c) 2016 anti-XSS developers ''' pass
StarcoderdataPython
1613574
class UserAlreadyExistsError(Exception): #raised them the user already exists pass class DatabaseConnectionError(Exception): #raised when there is a problem with the database pass class PasswordsDontMatchError(Exception): #raised when passwords do not match pass class InvalidPasswordError(Exc...
StarcoderdataPython
1687162
<gh_stars>10-100 from accountancy.helpers import (bulk_delete_with_history, create_historical_records, get_action, get_historical_change) from contacts.models import Contact from django.db import models from django.test import TestCase class GetActionT...
StarcoderdataPython
11307382
from torch import nn from constants import * from layers import * import torch class Transformer(nn.Module): def __init__(self, src_vocab_size, trg_vocab_size): super().__init__() self.src_vocab_size = src_vocab_size self.trg_vocab_size = trg_vocab_size self.src_embe...
StarcoderdataPython
11229781
import requests import json import argparse import time import logging import sys HDRS = { "Accept": "application/json", "Content-Type": "application/json" } LOG = logging.getLogger("setup_aion") def request(url, data=None, method=None, headers=HDRS, params={}, allow_redirects=True, files=None, ...
StarcoderdataPython
1680091
import json from argo_workflows.model.object_field_selector import ObjectFieldSelector from argo_workflows.models import ConfigMapKeySelector, EnvVarSource, SecretKeySelector from pydantic import BaseModel from hera import ConfigMapEnvSpec, EnvSpec, FieldEnvSpec, SecretEnvSpec class MockModel(BaseModel): field1...
StarcoderdataPython
6496412
<gh_stars>0 """Top-level package for python_template.""" from ._version import get_versions __author__ = """<NAME>""" __email__ = '<EMAIL>' __version__ = get_versions()['version'] del get_versions from ._version import get_versions __version__ = get_versions()['version'] del get_versions
StarcoderdataPython
8020803
from django.urls import path from worlds.views import * urlpatterns = [ path('pipeline/start/', start_pipeline), path('pipelines/', pipeline_list), path('jobs/', job_list), path('job/<int:jid>/', job_details), path('job/<int:jid>/shelix-logs/', job_shelix_log), path('job/<int:jid>/kill/', job_...
StarcoderdataPython
6476636
<filename>backpack/extensions/secondorder/diag_ggn/convtransposend.py<gh_stars>100-1000 from backpack.extensions.secondorder.diag_ggn.diag_ggn_base import DiagGGNBaseModule from backpack.utils import conv_transpose as convUtils class DiagGGNConvTransposeND(DiagGGNBaseModule): def bias(self, ext, module, grad_inp,...
StarcoderdataPython
6541969
#Data Types #String #Hello is quotes is the string or output print("Hello") #Subscript #looks at the position within the string and outputs just that character #below will output just H print("Hello"[0]) #below will output just o print("Hello"[4]) #Integer #actual numbers in the code for calculating #displayed just...
StarcoderdataPython
4820182
<filename>scout/parse/cytoband.py import intervaltree def parse_cytoband(lines): """Parse iterable with cytoband coordinates Args: lines(iterable): Strings on format "chr1\t2300000\t5400000\tp36.32\tgpos25" Returns: cytobands(dict): Dictionary with chromosome names as keys and ...
StarcoderdataPython
12829784
<reponame>rahulbahal7/restricted-python<gh_stars>0 ############################################################################## # # Copyright (c) 2002 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany t...
StarcoderdataPython
4958286
from opencivicdata.core.models import Post, PostContactDetail, PostLink from .base import BaseImporter class PostImporter(BaseImporter): _type = 'post' model_class = Post related_models = {'contact_details': (PostContactDetail, 'post_id', {}), 'links': (PostLink, 'post_id', {}) ...
StarcoderdataPython
8156536
<filename>pre-refactor/reverse.py #!/usr/bin/env python3 # reverse words or sentences import random import sys def reverse_words(input_array): output_array = [] for item in input_array: playstring = '' for i in range(0, len(item)): playstring += item[len(item) - 1 - i] out...
StarcoderdataPython
179543
import streamlit as st import statsmodels.api as s_api import matplotlib.pyplot as plt class lin_mod: #perform linear regression using sklearn and stamodels def __init__(self,x,y): self.x=x self.y=y def model_imp(self): x=s_api.add_constant(self.x) y=self.y mod=s_api.OLS(...
StarcoderdataPython
5106053
<gh_stars>100-1000 from django.http import HttpResponse from django.core.exceptions import ImproperlyConfigured from django.core.serializers.json import DjangoJSONEncoder from django.utils import six # Django 1.5+ compat try: import json except ImportError: # pragma: no cover from django.utils import simplejs...
StarcoderdataPython
8114053
import unittest from pybooru import Safebooru, SafebooruImage from .common import CommonTests object_data = { "directory": "3375", "hash": "image_name", "height": 1, "id": 1, "image": "image.ext", "change": 1, "owner": "owner", "parent_id": 0, "rating": "rating", "sample": Tru...
StarcoderdataPython
11399591
<reponame>deHasara/modin<gh_stars>0 # Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team licenses this file to you under the # Apache License, Versio...
StarcoderdataPython
5182429
from ocr4all_helper_scripts.helpers import legacyconvert_helper from pathlib import Path import click @click.command("legacy-convert", help="Convert legacy OCR4all projects to latest.") @click.option("-p", "--path", type=str, required=True, help="Path to the OCR4all project.") def legacyconvert_cli(path): for xm...
StarcoderdataPython
3251871
# -*- coding: utf-8 -*- """ Created on 2017/6/9 @author: MG """ import logging import threading import inspect from ctp import ApiStruct, MdApi, TraderApi import hashlib, os, sys, tempfile, time, re from config import Config, PeriodType, PositionDateType from backend.fh_utils import str_2_bytes, bytes_2_str from dateti...
StarcoderdataPython
9607161
<gh_stars>0 from django.db import models from accounts.models import Account from django.db import models from django.db.models import Avg # Create your models here. class Post(models.Model): user = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True) image = models.ImageField(upload_to='images') ...
StarcoderdataPython
6438327
from __future__ import print_function import os import numpy as np from keras.models import Model from keras.layers import Input, concatenate, Conv1D, MaxPooling1D, Conv2DTranspose,Lambda,BatchNormalization,LSTM from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint from keras import backend as ...
StarcoderdataPython
5145660
<filename>mmfewshot/classification/apis/test.py # Copyright (c) OpenMMLab. All rights reserved. import copy from typing import Dict, Optional, Union import mmcv import numpy as np import torch from mmcls.apis.test import collect_results_cpu from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv....
StarcoderdataPython
4890536
<gh_stars>0 """Tests for move groups.""" import asyncio from typing import Iterator import pytest from _pytest.fixtures import FixtureRequest from opentrons_hardware.firmware_bindings import NodeId from opentrons_hardware.firmware_bindings.messages.message_definitions import ( AddLinearMoveRequest, GetMoveGrou...
StarcoderdataPython
12841414
<filename>lib/data_coll/source_file.py import os import config def walk(): """ 遍历源文件目录 :return: Generator """ for root in config.Source.include: for path, _, files in os.walk(root): if path not in config.Source.exclude: for file in files: yie...
StarcoderdataPython
5055204
<filename>test_cmds_txs.py import binascii TRANSACTIONS = [ { "id": "0f51ac8bd9c7413ea9a6ceb1d67688f1786dd43f6bb71b9715e9ff0ebda61136", "tokens": [ "<KEY>", "<KEY>", "<KEY>", "<KEY>" ], "outputs": [ { "index...
StarcoderdataPython