id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
4948943
<reponame>SilentByte/lyngua from fastapi import APIRouter, Response ping_router = APIRouter() @ping_router.get('/ping', status_code=204, response_class=Response) def ping() -> None: pass
StarcoderdataPython
3554726
<reponame>guiguid/core """Tests for the Abode module.""" from unittest.mock import patch from homeassistant.components.abode import ( DOMAIN as ABODE_DOMAIN, SERVICE_CAPTURE_IMAGE, SERVICE_SETTINGS, SERVICE_TRIGGER_AUTOMATION, ) from homeassistant.components.alarm_control_panel import DOMAIN as ALARM_D...
StarcoderdataPython
1910678
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def plusOne(self, head: ListNode) -> ListNode: sentinel = ListNode(0, head) nonNineNode = sentinel while head: if...
StarcoderdataPython
3561182
""" 2D covolution: image filtering Low pass filter(LPF): help to remove noises High pass filter(HPF): help to find edges Question: how to get the kernel I want? """ import cv2 import matplotlib.pyplot as plt """ Image blurring: with LPF 1. Averaging This is done by convolving image with a normalized box filter. It ...
StarcoderdataPython
6582063
from a10sdk.common.A10BaseClass import A10BaseClass class Ds(A10BaseClass): """ :param ds_delete: {"default": 0, "optional": true, "type": "number", "description": "Delete the DS file", "format": "flag"} :param zone_name: {"description": "DNS zone name of the child zone", "format": "string", "minLengt...
StarcoderdataPython
202167
#!/usr/bin/env python3.7 from .swaszek_strategy import SwaszekStrategy from .agent import AgentNextPos, AgentRandom, AgentSamePos
StarcoderdataPython
1822696
<reponame>vanigupta20024/Programming-Challenges<gh_stars>10-100 ''' A string is a valid parentheses string (denoted VPS) if it meets one of the following: It is an empty string "", or a single character not equal to "(" or ")", It can be written as AB (A concatenated with B), where A and B are VPS's, or It can be writ...
StarcoderdataPython
1816797
from flask_restplus import Api, Resource, reqparse, Namespace from flask import request from os import path, remove from classes import RecordedVideo from classes import apikey from classes import upvotes from classes.shared import db from globals import globalvars api = Namespace('clip', description='Clip Related Q...
StarcoderdataPython
11384718
from typing import Callable, Dict import logging log = logging.getLogger(__name__) class Registry: registry: Dict[str, Callable] = {} @classmethod def register(cls, name: str) -> Callable: def wrapper(wrapped: Callable) -> Callable: if name in cls.registry: log.warn...
StarcoderdataPython
1740663
import netrc import os netrcFileName = '.netrc' def get_credentials_from_file( service, authFile=None ): if not authFile is None: if os.path.isdir(authFile): authFile = os.path.join( authFile, netrcFileName ) creds = netrc.netrc( authFile ).authenticators(service) return creds def get...
StarcoderdataPython
4914773
<reponame>thepineapplepirate/galaxy<gh_stars>0 import pytest from galaxy.model import tool_shed_install as model from ...testing_utils import ( dbcleanup_wrapper, initialize_model, ) @pytest.fixture(scope="module") def init_model(engine): """Create model objects in the engine's database.""" # Must us...
StarcoderdataPython
4979540
from collections import namedtuple import numpy as np import torch import torch.nn.functional as F from rlpyt.utils.tensor import infer_leading_dims, restore_leading_dims, to_onehot, select_at_indexes from rlpyt.models.mlp import MlpModel from rlpyt.distributions.gaussian import Gaussian, DistInfoStd from rlpyt.distr...
StarcoderdataPython
11274027
# Copyright (c) 2020, Huawei Technologies.All rights reserved. # # Licensed under the BSD 3-Clause License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://opensource.org/licenses/BSD-3-Clause # # Unless required by applicable law...
StarcoderdataPython
6703825
<filename>w02-calling-functions/checkpoint-boxes/boxes.py import math items = int(input("Enter the number of items: ")) items_box = int(input("Enter the number of items per box: ")) boxes = math.ceil(items / items_box) print(f"For {items} items, packing {items_box} items in each box, you will need {boxes} boxes.")
StarcoderdataPython
5066676
<gh_stars>0 ''' Created on 04.03.2013 @author: hlampesberger ''' from base import Result from regular import nfa from regular.dfa import DFA import unittest class TestDFA(unittest.TestCase): def setUp(self): alphabet = ["a", "b"] s = ["q1", "q2", "q3", "q4"] transitions = [("q1", "b", "...
StarcoderdataPython
357032
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 15 15:30:15 2021 @author: altair """ import math import pandas_datareader as web import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense, LSTM import m...
StarcoderdataPython
9601837
<reponame>ilmcconnell/Cosmos<filename>cosmos/ingestion/ingest/process/detection/src/torch_model/model/__init__.py """ Model specification dir """
StarcoderdataPython
9717456
#!/usr/bin/env python # coding: utf-8 import glob import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import numpy as np import pandas as pd import sklearn import tensorflow as tf import yaml from IPython.display import display from tqdm.notebook import tqdm from transformers import BertConfig impo...
StarcoderdataPython
3317738
import os import cv2 import time import face_recognition import pickle pTime = 0 cTime = 0 KNOWN_FACES_DIR = 'known_faces' UNKNOWN_FACES_DIR = 'unknown_faces' TOLERANCE = 0.7 FRAME_THICKNESS = 2 FONT_THICKNESS = 2 MODEL = 'cnn' cap = cv2.VideoCapture(0) known_faces = [] known_names = [] if not os.path.exists(f"./{...
StarcoderdataPython
3423978
import os from os.path import join from pathlib import Path from PIL import Image if __name__ == "__main__": print('Making B&W') input_folder = '../../res/dataset/y/splitted/' output_folder = '../../res/dataset/x/splitted/' for name in ['train', 'test', 'val']: Path(join(output_folder, name, '...
StarcoderdataPython
9667732
<reponame>LaudateCorpus1/oci-python-sdk # coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.ap...
StarcoderdataPython
6608517
# -------------------------------------------------------- # Pytorch multi-GPU Faster R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by <NAME>, <NAME>, based on code from Ross Girshick # -------------------------------------------------------- from __future__ import absolute_import from __fu...
StarcoderdataPython
5056192
<filename>reg_tests/lib/errorPlotting.py # # Copyright 2017 National Renewable Energy Laboratory # # 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...
StarcoderdataPython
62237
<reponame>ComtecSystem-dev/Python_DB_Pool<filename>Demo/cims_db.py<gh_stars>0 # -*- coding: utf-8 -*- ################################################################################ # _____ _ # # / ____ | | ...
StarcoderdataPython
1849972
revision = '<KEY>' down_revision = '0dec7733925d' branch_labels = None depends_on = None import alembic import sqlalchemy def upgrade(): alembic.op.alter_column('users', 'patreon_user', new_column_name="patreon_user_id") def downgrade(): alembic.op.alter_column('users', 'patreon_user_id', new_column_name="patreon_...
StarcoderdataPython
6641054
<filename>ghidra_scripts/RunSolve.py #Run angr solver using given parameters #@author jackdekleuver #@category Concolic #@keybinding #@menupath Tools.Concolic Execution.Run #@toolbar import argparse def run_script(server_host, server_port): import ghidra_bridge # load something ghidra doesn't have impor...
StarcoderdataPython
234794
<reponame>CarlosMatheus/Python-Web-Framework """ This exemplify how a WSGI works """ # This is a function from a default python library that allow us to make a WSGI server. from wsgiref.simple_server import make_server from wsgi.web_server_gateway_interface import WebServerGatewayInterface def web_app(environment, ...
StarcoderdataPython
8059784
from __future__ import annotations from ..typecheck import * from enum import IntEnum from ..import core from .import dap from ..watch import Watch from .debugger import Debugger from .error import Error from ..breakpoints import ( Breakpoints, SourceBreakpoint, ) from .variable import ( Variable, SourceLocati...
StarcoderdataPython
4908056
<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/10/24 9:37 # @Author : ganliang # @File : test_tf_bpn.py # @Desc : bpn反向传播 import unittest from mtensorflow import tf_bpn class TestTensorflowBpn(unittest.TestCase): def test_bpn(self): tf_bpn.bpn(epochs=1, batch_size=1...
StarcoderdataPython
5013679
from absl import app from absl import flags import time from os.path import expanduser import os import signal from .mv_screenshot import mv_default from .settings import init, change_savedir, change_jikanwari from .daemonize import interval_run, start_daemon, log_to_stdout FLAGS = flags.FLAGS flags.DEFINE_bool( ...
StarcoderdataPython
3400168
<reponame>marcus-pham/test<filename>book/code/nba - project 5 get list of all couch.py # already try with requests, this module not work from bs4 import BeautifulSoup from selenium import webdriver # from original link nba.com # get all coaches name driver = webdriver.PhantomJS(executable_path = r'C:\phantomjs-2.1.1-...
StarcoderdataPython
4903593
<reponame>csinchok/drf-nested-serializer<filename>nested_serializers/serializers.py<gh_stars>0 from django.db import transaction from rest_framework import serializers from rest_framework.fields import set_value, empty from rest_framework.compat import OrderedDict from rest_framework.serializers import ValidationError...
StarcoderdataPython
9706541
<reponame>Artanis/icecrate<gh_stars>1-10 from setuptools import setup, find_packages def get_version(): version_file = "icecrate/_version.py" loc = {} with open(version_file, "r") as f_version: code = compile(f_version.read(), "_version.py", "exec") exec(code, {}, loc) return loc.get("...
StarcoderdataPython
6685565
<filename>source/main.py import os import pandas from pandas.errors import ParserError from scipy.signal import savgol_filter import csv class StackDiffraction: def __init__(self): """The lines below are commented out as they are defunct in the GUI implementation""" #self.path = path #self.files = self.GetF...
StarcoderdataPython
1696373
<filename>menu/menu_api.py<gh_stars>1-10 # General Package Import import re from flask import json, jsonify, request, abort from flask.views import MethodView # User Package Import from utilities.errorcodes import * from utilities.filelogger import Log from utilities.databaselayer import DatabaseLayer from utilities.va...
StarcoderdataPython
9616036
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file './window.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtG...
StarcoderdataPython
6602492
from asyncio import Future, ensure_future, wait_for, TimeoutError class CombineMessage: def __init__(self): self.message_type_list = list() self.combine_message = None self.error_message = None self.timeout = 1.0 self.keep_origin = False self.future = Future() ...
StarcoderdataPython
4889340
<reponame>Marghrid/Forest from .condition_distinguisher import ConditionDistinguisher from .regex_distinguisher import RegexDistinguisher
StarcoderdataPython
3320444
""" Copyright 2019 <NAME>. 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 distribut...
StarcoderdataPython
3459966
from typing import Text import tensorflow as tf import io import json import numpy as np from tensorboard.backend.event_processing import event_accumulator import warnings from tc_utils.util import numpy_to_tensor, tensor_to_numpy from tc_logging.logger import Logger, LogReader class TensorBoardLogger(Logger): de...
StarcoderdataPython
6439555
<reponame>t3hi3x/hue<gh_stars>10-100 #!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, ...
StarcoderdataPython
9686604
import itertools import math import numpy as np import pytest from hypothesis import given, strategies as st from scipy.sparse import coo_matrix from tmtoolkit import bow @given(dtm=st.lists(st.integers(0, 10), min_size=2, max_size=2).flatmap( lambda size: st.lists(st.lists(st.integers(0, 10), ...
StarcoderdataPython
5042182
<reponame>CGYR/gongchengmiao_BBS import datetime from haystack import indexes from .models import ArticlePost class ArticlePostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) #author = indexes.CharField(model_attr='author') #pub_date = indexes.Dat...
StarcoderdataPython
3587992
<filename>CADRE/power_dymos/power_cell_voltage.py """ Power discipline for CADRE: Power Cell Voltage component. """ from __future__ import print_function, division, absolute_import from six.moves import range import os import numpy as np from openmdao.api import ExplicitComponent from MBI import MBI class PowerCel...
StarcoderdataPython
1633561
import numpy as np from scipy.spatial import distance from scipy.sparse import csgraph from matplotlib import pyplot from matplotlib.widgets import Slider, Button, RadioButtons import linear_utilities as lu def rkm(X, init_W, s, plot_ax=None): """ Regularized K-means for principal path, MINIMIZER. Arg...
StarcoderdataPython
11289034
# -*- coding: utf-8 -*- import sys sys.path.append('.') from common import TestCase import unittest import fatuv as uv from fatuv import dns TEST_IPV4 = '127.0.0.1' TEST_PORT1 = 12345 class TestDNS(TestCase): def test_dns_async(self): def got_addrinfo(request, code, addrinfo): self.assert_true(addrinfo) #...
StarcoderdataPython
12823940
<reponame>Dataforsyningen/skraafoto_tile_public """TIFF read exceptions.""" class HTTPError(Exception): """Represents an upstream http error""" exit_code = 1 def __init__(self, message, status=None): self.message = message self.status = status class HTTPRangeNotSupportedError(Exception...
StarcoderdataPython
1623760
<reponame>Softeq/PyCats from common.facade.api import BaseRequestModel, BaseResponseModel, endpoint_factory from common.facade.api import SKIP, pycats_dataclass from common.facade import raw_config, logger # TODO - find solution to set dataclass fields properly after initialization def query_builder(city, token, unit...
StarcoderdataPython
9602759
<reponame>emilljungberg/pyMERLIN #!/usr/bin/env python3 from .plot import plot_3plane from .dataIO import read_image_h5, parse_fname import matplotlib.pyplot as plt import argparse import os import h5py import numpy as np import SimpleITK as sitk def create_info(matrix, voxel_size, read_points, read_gap, spokes_hi, ...
StarcoderdataPython
5176233
from app.configuration import get_value from app.helper import output_start, php, output_error def execute(): output_start('phpunit') check_dir = get_value('check-dir') argument = get_test_argument(check_dir) if get_value('phpunit-coverage') == 'true': argument = argument+get_coverage_argume...
StarcoderdataPython
4886452
import torchvision.transforms as transforms from torch.utils.data import DataLoader from torchvision.datasets.mnist import MNIST def get_mnist(path="./data/mnist", batch_size=256, shuffle=True, num_workers=8): train_data = MNIST(path, download=True, transform=transforms.Compose([ transforms.Resize((32, 32...
StarcoderdataPython
6690255
from app.api.wechat import wechat
StarcoderdataPython
256543
from setuptools import setup, find_packages from setuptools import * setup( name = "dCrypy", version = "1.0.1", author = "Stealth.py", url = "https://github.com/Stealth-py", description = "A CLI to decode ciphertext to plaintext from the given options.", license = "Apache", packages = find_...
StarcoderdataPython
1678457
from dataclasses import dataclass from typing import List from lakey_finicity.models.report.voa.voa_account_record import VoaAccountRecord @dataclass class VoaInstitutionRecord(object): _unused_fields: dict # this is for forward compatibility and should be empty id: int name: str accounts: List[VoaA...
StarcoderdataPython
1673189
<filename>Script2.py<gh_stars>0 #Tarea 2# print(u"\u001b[32mHello World") print (u"\u001b[0m")
StarcoderdataPython
11322023
<filename>tests/annotator/test_pos_annotator.py #!/usr/bin/env python """Tests for the POSAnnotator that annotates a sentence with part of speech tags that align with the token tier.""" from __future__ import absolute_import import unittest from epitator.annotator import AnnoDoc from epitator.pos_annotator import P...
StarcoderdataPython
4807019
from .scan import DocScanner
StarcoderdataPython
9758090
<filename>bc/bc_grammar.py from parsy import forward_declaration, regex, Parser, string, seq, letter, digit from bc_ast import * chr2int = lambda x: ord(x) str2int = lambda x: int(x) hexstr2int = lambda x: int(x, 16) comment = regex(r'//[^\r\n]*').desc('comment') whitespace = regex(r'[ \t]').desc('whitespace') whitesp...
StarcoderdataPython
9611199
from utils.randomGen import generateRandomString from asyncProducerUtil.utils.connect import Connect from services.ASG import ASG class AutoScalingDefinition(Connect): api_name = 'auto-scaling' table_name = 'scheduler_state_logs' def asg_def(self, asg, schedule): OS = asg.operating_system ...
StarcoderdataPython
5010695
<gh_stars>1-10 from collections import OrderedDict from typing import Any, Dict, Iterable, Mapping, Optional, Sequence, Tuple from .dataset import Dataset, build_processors, resolve_samples from .processors import Processor class OneShotLoader: def __init__( self, definition: Optional[str] = None...
StarcoderdataPython
3486322
<gh_stars>1-10 from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils im...
StarcoderdataPython
6452424
import copy import six from .error import SchemaError, Error, Invalid class Schema(object): """ A schema that validates data given to it using the specified rules. The ``schema`` must be a dictionary of key-value mappings. Values must be callable validators. See ``XX``. The ``entire`` argument...
StarcoderdataPython
208403
<gh_stars>0 import Tester import json import time import random import sys reload(sys) sys.setdefaultencoding('utf8') def shuffled(iterable): perm = range(len(iterable)) random.shuffle(perm) return [iterable[i] for i in perm] class SearchTester(Tester.Tester): def __init__(self, details): su...
StarcoderdataPython
3589105
"""Author: <NAME>, Copyright 2019 Word Pack.""" import tensorflow as tf from wordpack.net.multi_head_attention import MultiHeadAttention class Transformer(tf.keras.layers.Layer): def __init__(self, vocab_size, embedding_size, num_heads, hidden_sizes, output_sizes, fc_hidden_sizes, fc_ou...
StarcoderdataPython
6441252
<filename>30_day_leetcoding_challenge/week_2/min_stack.py<gh_stars>0 class MinStack: def __init__(self): """ initialize your data structure here. """ self.__min = 0 self.__topnum = 0 self.__len = 0 self.__val = [] def push(self, x: int) -> None:...
StarcoderdataPython
173686
from polls.tests.test_rules.rule_2.bad_factories import ( PollFactory as BadPollFactory, ) from polls.tests.test_rules.rule_2.good_factories import ( PollFactory as GoodPollFactory, ) def test_bad_to_string_with_non_premium_question_without_author(): poll = BadPollFactory.build() assert str(poll) == "...
StarcoderdataPython
11371285
# -*- coding: utf-8 -*- ''' Created on 2018. 9. 12. @author: jason96 ''' import unittest from splunklib.client import Index from sputil.splunk import Indexer, Searcher, ITSIManager from sputil.base import SPINDEX import urllib3 import time urllib3.disable_warnings() class SplunkIndexerTest(unittest.TestCase): ...
StarcoderdataPython
3419237
<filename>tests/conftest.py from itertools import zip_longest from typing import Dict, List, Optional from arche.readers.items import CollectionItems, JobItems from arche.rules.result import Result import numpy as np import pandas as pd import pytest cloud_items = [ {"_key": "112358/13/21/0", "price": 0, "name":...
StarcoderdataPython
5080945
from django.db import models # Create your models here. # 新闻类别表 class Cate(models.Model): # cate_id = models.CharField(blank=False, max_length=64, verbose_name='ID', unique=True) cate_name = models.CharField(max_length=64, verbose_name='名字') def __str__(self): return self.cate_name class ...
StarcoderdataPython
12850260
<reponame>neogeo-technologies/collab<filename>geocontrib/migrations/0014_featuretype_title_optional.py # Generated by Django 2.2.24 on 2021-09-21 10:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('geocontrib', '0013_importtask'), ] operation...
StarcoderdataPython
3583515
import json from typing import Tuple import pigpio direction_type = int velocity_type = int motor_command_type = Tuple[direction_type, velocity_type] drive_command_type = Tuple[motor_command_type, motor_command_type] class DifferentialDrive(object): def __init__(self, pin_setup: str, drive_config: str): ...
StarcoderdataPython
4897865
<gh_stars>1-10 import inspect def serialize(x): if isinstance(x, (basestring, bool, float, int, long, type(None))): return x if isinstance(x, dict): return {k: serialize(v) for (k, v) in x.items()} if isinstance(x, (list, tuple)): return [serialize(i) for i in x] method = get...
StarcoderdataPython
11201932
<filename>finmarketpy/backtest/backtestengine.py<gh_stars>1-10 __author__ = 'saeedamen' # # Copyright 2016 Cuemacro # # 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/licens...
StarcoderdataPython
8141765
<filename>plio/io/io_json.py import json import numpy as np import datetime class NumpyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.ndarray): return obj.tolist() elif isinstance(obj, datetime.date): return obj.isoformat() return json.JSONE...
StarcoderdataPython
301909
<filename>agency/urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.home, name='home'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
StarcoderdataPython
3259975
<gh_stars>1000+ # Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE file in the project root for full license information. import numpy as np def target_function(w,b): x = 2*w+3*b y=2*b+1 z=x*y return x,y,z def single_variable(w,b,t): print("\nsingle vari...
StarcoderdataPython
6409350
#!/usr/bin/env python import requests import bs4 import pandas as pd import argparse import datetime import time import sys from io import StringIO from finviz.screener import Screener from junit_xml import TestSuite, TestCase from scrap_utils import * # ---------------------------------------------------------------...
StarcoderdataPython
11364983
<filename>tests/scanner/test_data/fake_lien_scanner_data.py # Copyright 2018 The Forseti Security 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://w...
StarcoderdataPython
3554471
<reponame>johan--/commcare-hq from django.core.management.base import BaseCommand from corehq.apps.custom_data_fields import models as cdm from corehq.apps.locations.models import Location from corehq.apps.domain.models import Domain class Command(BaseCommand): """ Create a CustomDataFieldsDefinition based on...
StarcoderdataPython
94834
import os import shutil #フォルダ名指定 dir_name1 = "画像フォルダ" dir_name2 = "音声フォルダ" dir_name3 = "映像フォルダ" dir_name4 = "テキストフォルダ" #整頓するデータの最低数指定 data_number = 3 if(len(os.listdir()) >= data_number): try: data_files = os.listdir() os.mkdir(dir_name1) os.mkdir(dir_name2) os....
StarcoderdataPython
1759243
import re import lxml.html from link_crawler import link_crawler FIELDS = ('area', 'population', 'iso', 'country', 'capital', 'continent', 'tld', 'currency_code', 'currency_name', 'phone', 'postal_code_format', 'postal_code_regex', 'languages', 'neighbours') def scrape_callback(url, html): if re.search('/view/',url...
StarcoderdataPython
8122775
from harborclient import base class RepositoryManager(base.Manager): def get(self, id): """Get a Repository.""" return self._get("/repositories/%s" % id) def list(self, project): """Get repositories accompany with relevant project and repo name.""" repositories = self._list("/...
StarcoderdataPython
11232766
<gh_stars>0 def mytest(): print('test_module_3_hello')
StarcoderdataPython
230618
<filename>v_m_b/image/generateManifest.py # downloading region import io import logging import sys from pathlib import PurePath, Path import aiofiles from PIL import Image IMG_JPG='JPEG' IMG_TIF='TIFF' JPG_EXT= 'JPG' TIF_EXT= 'TIF' # The keys are the image file types as extracted from the blob # The values are lis...
StarcoderdataPython
11235410
<reponame>TrongNghiaRyt/SE347-project-Django-Website from django.contrib import admin from .models import * class Answers(admin.TabularInline): model = Answer admin.site.site_header = 'VehiTest admin' class QuestionAndAnswers(admin.ModelAdmin): inlines = [Answers] list_display = ('id', 'kind', 'content')...
StarcoderdataPython
3510359
# Generated by Django 2.0.7 on 2018-09-25 14:20 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('profiles_api', '0001_initial'), ] operations = [ migrations....
StarcoderdataPython
320476
""" Test CPS and PUF data file contents. """ import os import pytest import numpy as np def unique_recid(data, dataname): """ Test that RECID values are unique. """ recid = data['RECID'] unique, counts = np.unique(recid, return_counts=True) recid_count = dict(zip(unique, counts)) duplicate...
StarcoderdataPython
3280209
''' This script includes two functionalities: chain2vcf and chain2bed chain2vcf: Converts a chain file to a VCF file. This conversion is not capble of handling translocations and inversions. Users should specify a list of "chain ids" that contain only indels. Example: # This output VCF is used to...
StarcoderdataPython
4960084
<filename>steerclear/settings/windows_settings.py SQLALCHEMY_DATABASE_URI = 'sqlite:///C://steerclear.db' TEST_SQLALCHEMY_DATABASE_URI = 'sqlite:///C://test.db'
StarcoderdataPython
366325
<filename>setup.py #!/usr/bin/env python3 from setuptools import setup, find_packages install_requires = [ 'beancount', 'pyyaml', ] setup( name="BeanPorter", version='0.1', description="Beancount importer", long_description= """ Beancount importer. """, license="MIT", author="WeZZard", author...
StarcoderdataPython
3364452
<reponame>smartanthill/smartanthill # Copyright (C) <NAME> <<EMAIL>> # See LICENSE for details. from binascii import hexlify from smartanthill.litemq.exchange import ExchangeFactory from smartanthill.service import SAMultiService class LiteMQService(SAMultiService): def __init__(self, name, options): S...
StarcoderdataPython
8158611
<filename>QCA4020_SDK/target/sectools/qdn/sectools/features/isc/parsegen/elf_support/elf_vars.py # =============================================================================== # # Copyright (c) 2013-2017 Qualcomm Technologies, Inc. # All Rights Reserved. # Confidential and Proprietary - Qualcomm Technologies, Inc...
StarcoderdataPython
375779
<filename>gym_walk/envs/walk_env.py import sys import numpy as np from six import StringIO from string import ascii_uppercase from typing import Optional import gym from gym import spaces, utils from gym.envs.toy_text.utils import categorical_sample WEST, EAST = 0, 1 class WalkEnv(gym.Env): metadata = {'render...
StarcoderdataPython
8061399
<filename>sensors/veml6075.py import time import board import busio import logging import adafruit_veml6075 i2c = busio.I2C(board.SCL, board.SDA) veml = adafruit_veml6075.VEML6075(i2c, integration_time=100) stardustLogger = logging.getLogger("StardustLogger") def uv(): print("UV a:", veml.uva) print("UV b:", veml.u...
StarcoderdataPython
3465009
<filename>app/tests/test_app.py import falcon import pytest from apispec import APISpec from apispec.ext.marshmallow import MarshmallowPlugin from falcon_apispec import FalconPlugin from app.app import application from app.db.database import StorageError @pytest.fixture() def app(): return falcon.API() @pytest...
StarcoderdataPython
6552847
""" Tests for the bootstrap_calcs.py file. """ import unittest import numpy as np import numpy.testing as npt import pandas as pd from scipy.stats import norm, gumbel_r import pylogit.bootstrap_calcs as bc try: # Python 3.x does not natively support xrange from past.builtins import xrange except ImportError:...
StarcoderdataPython
4877636
<filename>easy/array/flood_fill/flood_fill.py class Solution(object): def __flood_fill_recursion(self, image, sr, sc, old_color, newColor): image[sr][sc] = newColor if sr > 0 and image[sr-1][sc] == old_color: image = self.__flood_fill_recursion( image, sr-1, sc, old_colo...
StarcoderdataPython
20951
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # ...
StarcoderdataPython
3481685
<gh_stars>1-10 from django.shortcuts import render def entry_list(request): return render(request, 'entry_list.html') def entry_add(request): return render(request, 'entry_add.html') def entry(request, post_id): return render(request, 'entry.html', {'id': post_id})
StarcoderdataPython
8055787
<filename>dummy.py #this is a dummy python script to check #the proper installtion of the virtual env #and other required modules #this project uses python version 3.7.3 #=========required modules========== #pip install virtualenv #pip install --upgrade google-api-python-client #pip install --upgrade google-auth-oauth...
StarcoderdataPython