id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3398382
import json import time import os import sys from kafka import KafkaProducer from websource.tfgm import Tfgm SUBS_KEY = os.getenv("TFGM_SUBS_KEY") DELAY_SECONDS = 1 def get_latest_departures(): tfgm = Tfgm(SUBS_KEY) departures = tfgm.get_departures() return departures def send_departures_to_queue(pro...
StarcoderdataPython
179275
from functions import functions_util, inference_fcns import math, sys def cost_est(model,bits,**kwargs): content_ac = model[0] cost_add_flt={64:32,32:16,16:8,8:4} cost_mult_flt={64:120,32:25,16:5,8:1} cost_reg={64:40,32:20,16:10,8:5} cost_sram={64:200,32:100,16:50,8:25} par_num = sum([1 for...
StarcoderdataPython
1654079
<reponame>jgwerner/django from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import UserChangeForm from .forms import UserCreationForm from .models import IllumiDeskUser User = get...
StarcoderdataPython
25566
import re import pyUnicodeSteganography.zerowidth as zerowidth import pyUnicodeSteganography.lookalikes as lookalikes import pyUnicodeSteganography.snow as snow import pyUnicodeSteganography.emoji as emoji from pyUnicodeSteganography.zerowidth import zwc_4 def encode(unencoded_string, msg, method="zw", binary=False, ...
StarcoderdataPython
163442
# Generated by Django 2.1 on 2019-06-23 12:37 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0008_auto_20190623_1105'), ] operations = [ migrations.AlterModelOptions( name='profile', options={'permissions': (('...
StarcoderdataPython
55212
<filename>zetuptools/api.py import getpass import logging import os import shutil import subprocess import sys from typing import Optional import docker import docker.errors import zmtools from pkg_resources import resource_filename LOGGER = logging.getLogger(__name__) class PipPackage(): def __init__(self, na...
StarcoderdataPython
1755272
# Copyright (c) 2016-present, Facebook, 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...
StarcoderdataPython
3266795
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:encoding=utf-8 # # levenshtein_distance_implement.py # python # # 🎂"Here's to the crazy ones. The misfits. The rebels. # The troublemakers. The round pegs in the square holes. # The ones who see things differently. They're not found # of rules. And they have no res...
StarcoderdataPython
1732742
<filename>test/unit3/test_grammar.py<gh_stars>1-10 import unittest import test.ann_module as ann_module from test import ann_module2 import test # Note: since several test cases filter out floats by looking for "e" and ".", # don't add hexadecimal literals that contain "e" or "E". VALID_UNDERSCORE_LITERALS = [ '0_...
StarcoderdataPython
3236090
<filename>oop/oop_operator-overloading.py # Python Operator overloading import math class Circle: def __init__(self, radius): self.__radius = radius def get_radius(self): return self.__radius def set_radius(self, radius): self.__radius = radius def area(self): return self.__radius**2 * math.pi def _...
StarcoderdataPython
3245406
## Function to join automotive data def auto_join(autos, makes): import pandas as pd key = ['make-id'] ## Define key column ## Return the joined dataframe return pd.merge(autos, makes, on = key, how = 'left') ## Function to prepare the automotive data def prep_auto(df, col_names): import p...
StarcoderdataPython
3301657
<filename>Step1-PythonBasic/Practices/zhanghw/16-17/ex16.py #ex16.py # -*- coding:utf-8 -*- from sys import argv import os #获取文件名 #script, filename = argv #filename = raw_input('filename>>>>') filename = r'd:\aa.txt' #打印文件原始内容 print "We're going to erase %r." % filename #询问 print "If you don't wan...
StarcoderdataPython
3396425
import tensorflow as tf from tensorflow.keras.layers import Conv2D, Softmax from config.config import cfg from model.utils.generate_anchors import generate_anchor_ref, generate_anchors from model.layer.proposal_layer import proposal_layer from model.layer.proposal_to_target import proposal_to_target from model.layer.an...
StarcoderdataPython
66001
<gh_stars>0 from werkzeug import Request, Response, parse_cookie from werkzeug.contrib.securecookie import SecureCookie def test_basic_support(): """Basid SecureCookie support""" c = SecureCookie(secret_key='foo') assert c.new print c.modified, c.should_save assert not c.modified assert not c....
StarcoderdataPython
1772800
<filename>netforce_mfg/netforce_mfg/models/production_qc.py # Copyright (c) 2012-2015 Netforce Co. Ltd. # # 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 witho...
StarcoderdataPython
1737656
<reponame>snoopyjc/pythonizer def _caller(expr=None): """ Implementation of caller function in perl""" try: fr = sys._getframe(2 if expr is None else (max(int(expr),0)+1)) package = 'main' if hasattr(fr.f_builtins, '__PACKAGE__'): package = fr.f_builtins.__PACKAGE__ ...
StarcoderdataPython
3268650
from django.urls import path from .api import animals from .views import ClassBasedView, GenericClassBasedView urlpatterns = [ path('', GenericClassBasedView.as_view(), name='main'), path('frontend', ClassBasedView.as_view(), {'template': 'frontend.html'}, name='frontend'), path('api/animals/', animals, n...
StarcoderdataPython
3341375
<filename>festival/tests.py<gh_stars>1-10 from django.test import TestCase from festival.models import Artist NAME = '<NAME>' class ArtImageNamersCase(TestCase): def setUp(self): Artist.objects.create(name = NAME, festival='2015') def test_headshotNamer(self): artist = Artist.objects.get(name=...
StarcoderdataPython
1678650
#!/usr/bin/env python3 # # Copyright (c) 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...
StarcoderdataPython
3255150
<reponame>Ikusey/itc110-sum2019 #exercises chapter 3 import math def b2(): n = int(input("Enter a number: ")) equa = (n * (n-1)) / 2 print(equa) def c2(): r = int(input("Enter a sphere radius: ")) area = 4 * math.pi * r**2 print(area) def d2(): r = 3 a = 2 b = 4 ...
StarcoderdataPython
175677
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html from scrapy import Field, Item class CisSpidersItem(Item): # define the fields for your item here like: # name = Field() idx = Field() spider_name = Fiel...
StarcoderdataPython
1738952
import os import re import csv import sys import json import argparse import random from random import shuffle import logging from glob import glob import numpy as np from statistics import mean OFFSET_IDX = 1e5 # start roughly after memesdataset files max idx logging.basicConfig(format='%(asctime)s : %(levelname)s -...
StarcoderdataPython
4808173
<gh_stars>1-10 #!/usr/bin/env python #import dbus, dbus.glib, dbus.service import dbus, dbus.service from gi.repository import GObject as gobject from gi.repository import GLib from dbus.mainloop.glib import DBusGMainLoop import os DBusGMainLoop(set_as_default=True) #import dbus, dbus.glib, dbus.service import...
StarcoderdataPython
120835
<reponame>Kminassch/CoScal<filename>local_client/cpu_avg_count.py<gh_stars>0 # -*- coding: utf-8 -*- import numpy as np import pandas as pd dataset = pd.read_csv('report.csv') data_120 = dataset.iloc[-120:, :] cpu = data_120['CPU '] cpu_add = 0 for i in range(0, 120): cpu_add = cpu_add + cpu[i] cpu_avg =...
StarcoderdataPython
3300931
""" PUP Plugin implementing the 'download' API. """ import hashlib import logging import httpx class Step: """ Downloads files from the given URL. Caches them to avoid future downloads. """ @staticmethod def usable_in(ctx): return True def __call__(self, ctx, dsp, url): ...
StarcoderdataPython
1626655
<reponame>pazamelin/openvino # # relu6 paddle model generator # import numpy as np from save_model import saveModel import paddle import sys def relu6(name: str, x, threshold: float = 6.0, data_type='float32'): paddle.enable_static() with paddle.static.program_guard(paddle.static.Program(), paddle.static.Pro...
StarcoderdataPython
3200642
import fileinput import os import itertools import string class Community: def __init__(self, id): self.id = id self.users = [] pass def addUser(self, user): self.users.append(user) pass class User: def __init__(self, id): self.id = id pass d...
StarcoderdataPython
3369744
<gh_stars>0 import csv import json as jsonlib import pickle from tabulate import tabulate # https://pypi.org/project/tabulate/ import asciichartpy as chart from math import nan from spyql.log import user_error from spyql.nulltype import NULL, NullSafeDict class Writer: @staticmethod def make_writer(writer_n...
StarcoderdataPython
1776110
#! /usr/bin/env python from concurrent import futures import logging import random import time import sys import os import grpc from test_server_pb2_grpc import TestServerServicer, add_TestServerServicer_to_server from test_server_pb2 import CallRequest, CallResponse class TestServer(TestServerServicer): def C...
StarcoderdataPython
3399430
# @FILENAME : __init__.py # @AUTHOR : lonsty # @DATE : 2019/9/9 8:46
StarcoderdataPython
3311957
from google.cloud import storage from google import auth class BigstoreClient(): def __init__(self, creds): self.client = storage.Client( credentials=auth.default(scopes=creds.get_scopes())[0], project=creds.get_project_id()) self.bucket = self.client.get_bucket(creds.get_b...
StarcoderdataPython
3371455
<reponame>kumokay/placethings from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from copy import deepcopy from future.utils import iteritems import logging from placethings.config import nw_device_data from placethings....
StarcoderdataPython
190645
<filename>vrc_online/records/models.py from django.db import models from django.utils.translation import ugettext_lazy as _ from farms.models import Farm from session.models import Profile class Horse(models.Model): """ Necessary fields: age (in months), dob, name, gender, pregnant Optional fields...
StarcoderdataPython
64986
from __future__ import absolute_import from __future__ import division from __future__ import print_function # from smac.env.multiagentenv import MultiAgentEnv # from smac.env.starcraft2.maps import get_map_params from ..multiagentenv import MultiAgentEnv from ..starcraft2.maps import get_map_params import atexit fro...
StarcoderdataPython
1770135
<gh_stars>10-100 import torch import torch.nn as nn from torch.autograd import Variable from torch import optim import torch.nn.functional as F import math import torch.nn.utils.rnn as rnn_utils from data import get_cuda class EncoderDecoder(nn.Module): def __init__(self, vocab_size, embedding_size, hidden_size, ...
StarcoderdataPython
41411
from typing import List, Optional BIP32_PRIME = 0x80000000 UINT32_MAX = (1 << 32) - 1 def decode_bip44_path(path: str) -> List[int]: def _parse_node(node: str) -> Optional[int]: if not node or node == "m" or node == "M": return None is_hardened = node.endswith("'") or node.endswith("h...
StarcoderdataPython
3249309
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
StarcoderdataPython
1619810
import os class CommentsList(object): """ Stores comments, that can be later used utilized by Change::setReview """ comments = {} def __init__(self): pass def addComment(self, path, line, message): if path in self.comments: self.comments[path].append({"line": line, ...
StarcoderdataPython
1656163
<reponame>arnaudmorin/weechat-extra # -*- coding: utf-8 -*- # vim:set shiftwidth=4 tabstop=4 softtabstop=4 expandtab textwidth=250: import requests import weechat # script variables SCRIPT_NAME = "notify" SCRIPT_AUTHOR = "<NAME> <<EMAIL>>" SCRIPT_VERSION = "0.0.1" SCRIPT_LICENSE = "APACHE2" SCRIPT_DESC = "Send notifi...
StarcoderdataPython
148850
from rlpyt.utils.launching.affinity import encode_affinity from rlpyt.utils.launching.exp_launcher import run_experiments from rlpyt.utils.launching.variant import make_variants, VariantLevel script = "rlpyt/experiments/scripts/dm_control/qpg/sac/train/dm_control_sac_autoreg.py" affinity_code = encode_affinity( n...
StarcoderdataPython
230
<reponame>ministryofjustice/mtp-api<gh_stars>1-10 from django.db import migrations, models import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20180404_1515'), ] operations = [ migrations.CreateModel( ...
StarcoderdataPython
3241631
# -*- coding: utf-8 -*- # # Copyright (C) 2021 <NAME> <<EMAIL>> # All rights reserved. # # This code is licensed under the MIT License. # # 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 withou...
StarcoderdataPython
3580
<reponame>shenoyn/libcloud # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # libcloud.org licenses this file to You under the Apache License, Version 2.0 # (...
StarcoderdataPython
58351
<reponame>codelucas/wintria.com from django.contrib import admin from wintria.article.models import Article, Source class ArticleAdmin(admin.ModelAdmin): list_display = ('title', 'url', 'thumb_url', 'timestamp', 'click_count',) list_filter = ('source',) ordering = ('-click_count', '-timestamp',) ...
StarcoderdataPython
3298808
#!/usr/bin/env python3 import sys from collections import defaultdict def count(s1, s2): return len([0 for x1, x2 in zip(s1, s2) if x1 != x2]) == 1 def main(args): data = [s.strip() for s in sys.stdin] for x in data: for y in data: if count(x, y): print("".join([x1 for...
StarcoderdataPython
1718886
import os import pickle import numpy import music21 import itertools from src import DATA_DIR from src.helpers import save_pickle, load_pickle, get_pitch_space def tokenize(chars): if type(chars) == bytes: chars = chars.decode("utf-8") return chars.replace('(', ' ( ').replace(')', ' ) ').split() def t...
StarcoderdataPython
119330
from django.http import HttpResponse import simplejson import BeautifulSoup from oa_dashboard.tasks import async_sort_board, async_del_board, save_board from oa_cache.views import render_hashed from oa_dashboard.models import DashboardPanel from oa_cache.models import interpret_hash, build_hash from django.template.loa...
StarcoderdataPython
1689327
<reponame>tswicegood/bokeh # -*- coding: utf-8 -*- import numpy as np import scipy.special from bokeh.plotting import * mu, sigma = 0, 0.5 # NOTE: you can tinker with these values if you like # sample the distribution measured = np.random.normal(mu, sigma, 10000) hist, edges = np.histogram(measured, density=T...
StarcoderdataPython
3377215
<filename>sephiroth/providers/asn.py import requests from sephiroth.providers.base_provider import BaseProvider class ASN(BaseProvider): def __init__(self, targets_in, excludeip6=False): self.source_ranges = self._get_ranges(targets_in) self.processed_ranges = self._process_ranges(excludeip6) ...
StarcoderdataPython
1743405
<gh_stars>1-10 # coding=utf-8 # Copyright 2022 The Google Research Authors. # # 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 requi...
StarcoderdataPython
3332432
from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from django.contrib import admin from django.contrib.admin.sites import NotRegistered from models import UserOpenidAssociation class OpenIDInline(admin.StackedInline): model = UserOpenidAssociation class UserAdminWithOpen...
StarcoderdataPython
1697719
<reponame>AlexandruGhergut/wouso #!/usr/bin/env python # To test, run from parent folder using a command such as: # PYTHONPATH=../:. python utils/add_races.py utils/sample-data/sample-race-list.csv import sys import csv import wouso.utils.user_util def main(): if len(sys.argv) != 2: print 'Usage: python ...
StarcoderdataPython
3339550
# packages from hyperopt import hp, fmin, tpe, STATUS_OK, Trials import sys, os, random sys.path.append("C:/BERTVision/code/torch") from data.bert_processors.processors import * from common.trainers.bert_search_trainer import BertSearchTrainer from models.hypersearch.args import get_args import numpy as np import torch...
StarcoderdataPython
130976
from PIL import Image template = Image.new('P', (16, 16), '#AF7CAA') template = template.convert('PA') oldimage = Image.open("./template/block.png").convert('PA') oldimage.putpalette(template.getpalette()) oldimage = oldimage.convert('RGBA') oldimage.show()
StarcoderdataPython
112270
<reponame>umrest/teleop #!/usr/bin/env python import rospy import serial from teleop.msg import ControlMsg def handleControlMessage(data, ser): ser.write(makeString(data)) def serialNode(ser): rospy.init_node('serial_node', anonymous=True) rospy.Subscriber("/serial_control", ControlMsg, handl...
StarcoderdataPython
1796732
def mergeSort(arr): if len(arr) > 1: middle = len(arr)//2 positionLeft = arr[:middle] positionRight = arr[middle:] mergeSort(positionLeft) mergeSort(positionRight) i = j = k = 0 while i < len(positionLeft) and j < len(positionRight): if positionL...
StarcoderdataPython
1793775
<gh_stars>0 # from .output import Output # from .config import Config from .tracer import AsynchronousTracer # from .exceptions import PyCallGraphException class VisualCodeRun(object): def __init__(self): """output can be a single Output instance or an iterable with many of them. Example usage:...
StarcoderdataPython
23021
<filename>src/financial_statements/old/balance_sheet.py import time import threading import argparse import tushare as ts import numpy as np import pandas as pd from pandas import datetime as dt from tqdm import tqdm from utils import * with open('../../tushare_token.txt', 'r') as f: token = f.readline() ts.set_t...
StarcoderdataPython
138309
# third-party imports import pytest # local imports from shpkpr import template_filters def test_filter_items(): values = template_filters.filter_items({"X": "a", "Y": "b", "Z": "c"}) assert ("X", "a") in values assert ("Y", "b") in values assert ("Z", "c") in values def test_filter_items_with_star...
StarcoderdataPython
1692652
import sqlalchemy import time; from datetime import date, timedelta import datetime from sqlalchemy import func import stun_alchemy from stun_alchemy import Stun_User session = stun_alchemy.Session(); active_time = datetime.datetime.utcnow() - timedelta(seconds=15); # <peer_timeout> seconds into the past. resultse...
StarcoderdataPython
3384727
import struct from skyhookdmclient.skyhook_common import * import awkward class SkyhookDM: def __init__(self): self.client = None self.addr = None def connect(self, ip, ceph_pool_name): addr = ip+':8786' self.addr = addr client = Client(addr) self.client = clien...
StarcoderdataPython
4831167
# -*- encoding: utf-8 -*- # # The MIT License (MIT) # # Copyright (c) 2016-2018 <NAME> <<EMAIL>> # # 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 limit...
StarcoderdataPython
1705229
import sys sys.path.append(".") import sagemaker import os import boto3 import re from deploy_env import DeployEnv from sagemaker.pytorch import PyTorchModel from text_classification import config env = DeployEnv() def s3_bucket_from_url(s3_url): return re.search('//(.+)/',s3_url).groups()[0] def upload_model_da...
StarcoderdataPython
1683676
from ansiblelint import AnsibleLintRule class InconsistentNaming(AnsibleLintRule): id = 'ANSIBLE0014' description = 'Human meaningful name of the role or task to communicate the purpose' severity = 'medium' tags = {'clarity'} version_added = 'v1.0.0' # _modules = ['hosts'] shortdesc = 'Inc...
StarcoderdataPython
1728703
import datetime from typing import Dict, List, Union import pytz from django.conf import settings from django.utils.timezone import get_default_timezone from opening_hours.decorators import datetime_args_to_default_timezone from opening_hours.hours import ( Period, TimeElement, get_opening_hours, get_...
StarcoderdataPython
195847
import requests import json import os from config import * from video_downloader_yt import safeDownloadFile test_url = "https://static-gamespotvideo.cbsistatic.com/vr/2016/12/03/Trailer_Persona5_ThePhantomThieves_20161203_4000.mp4" THRESHOLD = 300 def download_video(name, url, playlist_urls): size_header = requ...
StarcoderdataPython
26905
<filename>tests/integration/test_integration_foreign_payment_codes.py from visma.models import ForeignPaymentCodes class TestForeignPaymentCodes: def test_list_foregin_payment_codes(self): codes = ForeignPaymentCodes.objects.all() assert len(codes) is not 0
StarcoderdataPython
1763737
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('managers', '0001_initial'), ] operations = [ migrations.AddField( model_name='ma...
StarcoderdataPython
3292464
<filename>src/run.py import argparse import locale import logging import sys from config import parse_config from driver import init_driver from hunter import hunt # required for price parsing logic locale.setlocale(locale.LC_ALL, 'es_ES.utf8') def parse_args(): parser = argparse.ArgumentParser() parser.ad...
StarcoderdataPython
1717799
<gh_stars>1-10 import sys import os sys.path.append(os.getcwd()) import subprocess import serial.tools.list_ports import esptool from typing import List from io import StringIO import re class OutputCapture(list): def __enter__(self): self._stdout = sys.stdout sys.stdout = self._stringio = StringIO() return ...
StarcoderdataPython
13864
<gh_stars>0 from .device import SampleDevice from .codeobject import SampleDeviceCodeObject __all__ = ['SampleDevice', 'SampleDeviceCodeObject']
StarcoderdataPython
45113
<reponame>m-zakeri/ADAFEST """ The main module of DAFEST project. ADAFEST is an abbreviation: 'A Data-Driven Approach to Estimating / Evaluating Software Testability' The full version of source code will be available as soon as the relevant paper(s) are published. """ class Main(): """Welcome to project ADAFE...
StarcoderdataPython
176062
import connexion import six from tapi_server.models.inline_object1 import InlineObject1 # noqa: E501 from tapi_server.models.inline_object12 import InlineObject12 # noqa: E501 from tapi_server.models.inline_object13 import InlineObject13 # noqa: E501 from tapi_server.models.inline_object14 import InlineObject14 # ...
StarcoderdataPython
188266
# Python 3.6-compatible wrapper for using cached_property # If you're pre-Python 3.8, you get no caching. You'll be okay. try: import functools apt_cached_property = functools.cached_property except: apt_cached_property = property
StarcoderdataPython
131288
<filename>test.py def prime(num): flag=False for a in range(2,num-1): #basically prime no are divisible by itself and by 1 only so set input value -1 so i takes previous num if num%a==0: flag=True if flag==False: print("prime") else: print("not prime") nu...
StarcoderdataPython
3326408
from gym_dssat.envs.dssat_env import DssatEnv import logging import shutil import pathlib import utils if __name__ == '__main__': dirs = ['./dssat_samples', './figures'] utils.make_folder(dirs) sampling = True date_steps = 40 date_delta = 5 n_loss_samples = int(1e5) id_soil = 'MCGI100001' ...
StarcoderdataPython
3278738
<reponame>julienbiau/CGP-IP<filename>cgpip/function_viewer.py import matplotlib.pyplot as plt from functions import Functions from fct_std_uint8 import STD_UINT8 #from supp_functions import SuppFunctions from skimage import data import time class FunctionViewer(object): def __init__(self,functions): self...
StarcoderdataPython
105075
<filename>RecordMapper/appliers/RenameApplier.py<gh_stars>1-10 from typing import List, Union from collections import namedtuple class RenameApplier(object): """An applier that applies a renaming process using the defined aliases on the schema using the avro convention. """ def __init__(self, custom...
StarcoderdataPython
4831252
<gh_stars>1-10 # Minimum settings used for testing. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'factory_test.db', }, } SITE_ID = 'testing' INSTALLED_APPS = ['assemblyline', 'django.contrib.flatpages']
StarcoderdataPython
33452
<filename>test_net.py import cv2 import caffe import tools import sys import os import numpy as np from functools import partial import config def gen_scales(w, h, min_imgsize, net_imgsize): scales = [] scale = float(net_imgsize) / min_imgsize; minhw = min(w, h) * scale; while minhw > net_imgsize: ...
StarcoderdataPython
183858
<gh_stars>0 # pylint: skip-file __version__ = '2019.09.06'
StarcoderdataPython
3277098
<gh_stars>1-10 class SensorData: """ Parameters ---------- frame : int Frame count when the data was generated. timestamp : float Simulation-time when the data was generated. location : Location object 3D point in simulation. rotation : Rotation object ...
StarcoderdataPython
97015
<reponame>BennyThink/pyweathercn #!/usr/bin/python # coding:utf-8 # pyweathercn - web.py # 2018/5/22 16:32 # For running up tornado __author__ = 'Benny <<EMAIL>>' import json import socket from platform import uname from concurrent.futures import ThreadPoolExecutor from tornado import web, ioloop, htt...
StarcoderdataPython
4808284
<filename>setup.py from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup(packages=find_packages(), name="drgpy", version="0.0.1", description="drgpy is a Python library for assigning a combination of diagnosis and procedure codes to Diagnosis...
StarcoderdataPython
1749780
from enum import Enum import logging import mido ROLAND_ID_BYTES = b"\x41\x10\x00\x00\x00\x28" logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) logger.setLevel(logging.WARNING) class RolandCmd(Enum): READ = b"\x11" WRITE = b"\x12" def discover(idx: int = 0) -> str: logger....
StarcoderdataPython
1629989
import mne import logging import os.path as op from mne_bids import ( write_raw_bids, write_meg_calibration, write_meg_crosstalk, BIDSPath, ) from pathlib import Path from glob import glob from pymento_meg.config import channel_types from pymento_meg.orig.behavior import write_to_df logging.basicCon...
StarcoderdataPython
48152
from django.db import models from sessions_coding.models import Classroom_session,Subject,Axis,Skill,Learning_goal,Copus_code DIALOGIC_CHOICES = ( ('Autoritativo', 'Autoritativo'), ('Dialogico', 'Dialógico'), ('NA', 'NA'), ) class Discourse_form(models.Model): session = models.ForeignKey(Classroom_ses...
StarcoderdataPython
3332844
"""Test the match.py file.""" import pytest from collections import namedtuple from itertools import zip_longest from hydrate.component import Component from hydrate.match import Matcher FILE = 'hydrate.match' class TestMatcher(): """Test suite for the Matcher class.""" tst_repo_components = [Component(n...
StarcoderdataPython
119275
class MdFile(): def __init__(self, file_path, base_name, title, mdlinks): self.uid = 0 self.file_path = file_path self.base_name = base_name self.title = title if title else base_name self.mdlinks = mdlinks def __str__(self): return f'{self.uid}: {self.file_pat...
StarcoderdataPython
120991
<gh_stars>0 from .database import Base from sqlalchemy import Column, Integer, String, Boolean from sqlalchemy.sql.expression import text from sqlalchemy.sql.sqltypes import TIMESTAMP class Post(Base): __tablename__ = "posts" id = Column(Integer, primary_key=True, nullable=False) title = Column(String, nu...
StarcoderdataPython
1681487
<filename>bot/commands/usr_misc.py import discord from datetime import datetime, timedelta from aiohttp import client_exceptions import operator import traceback from . import commandsDB as botCommands from . import util_help from .. import lib, botState from ..cfg import cfg, bbData, versionInfo from ..users import b...
StarcoderdataPython
1733505
<gh_stars>100-1000 import os from .utils import image_loader class SegDataset(object): """SegDataset This class is for common semantic segmentation scenario. Data organization adopted from PASCAL VOC datasets. http://host.robots.ox.ac.uk/pascal/VOC/index.html The trainval.txt, train.txt or val.txt shoul...
StarcoderdataPython
92730
"""https://www.educative.io/courses/grokking-the-coding-interview/xl2g3vxrMq3 """ def find_string_anagrams(input_str: str, pattern: str) -> list[str]: """Find all anagrams of a specified pattern in the given string. Anagram is actually a Permutation of a string. For example, “abc” has the following six ...
StarcoderdataPython
88803
#coding: UTF-8 # 信息利用率低:不同的机器学习算法和模型对数据中信息的利用是不同的,之前提到在线性模型中,使用对定性特征哑编码可以达到非线性的效果。类似地,对定量变量多项式化,或者进行其他的转换,都能达到非线性的效果。 from sklearn.preprocessing import PolynomialFeatures import numpy as np X = np.arange(6).reshape(3, 2) print(X) poly = PolynomialFeatures(2) print(poly.fit_transform(X)) poly = PolynomialFeatures(int...
StarcoderdataPython
170980
import pathlib ROOT = pathlib.Path().absolute() FOLDER_NAME = "formatting_helper" TEXT_FILE_PATH = ROOT / FOLDER_NAME / "format_me.txt" OUTPUT_FILE_PATH = ROOT / FOLDER_NAME / "formatted.txt" #editable constants: #constants are used in the order they appear #indicates the number of symbols to remove from the start o...
StarcoderdataPython
65132
import numpy as np import pandas as pd from docplex.mp.model import Model as Model def offline_optimal(df_tasks, df_nodes, n_time, n_tasks, n_nodes, gap=0.1): mdl = Model(name='Maximise social welfare') # set the tolerance to 1% mdl.parameters.mip.tolerances.mipgap = 0.01 # auxiliary variable represe...
StarcoderdataPython
3307668
<filename>DSLR/autoencoder.py<gh_stars>1-10 import argparse import torch import torch.utils.data import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from torchvision import datasets, transforms from pydoc import locate import tensorboardX from torchsummary import summary from tqdm impo...
StarcoderdataPython
37307
import collections import datetime import logging import os import sys from pathlib import Path import numpy as np import pdfkit as pdfkit from bs4 import BeautifulSoup from sklearn.metrics import mean_absolute_error, mean_squared_error, confusion_matrix, classification_report, \ accuracy_score from tldextract imp...
StarcoderdataPython
1644445
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from telemetry.core import browser_finder from telemetry.core import util from telemetry.unittest import options_for_unittests class Te...
StarcoderdataPython
1734727
import pymysql import logging class MySQLHelper: host="localhost" user="root" password="<PASSWORD>" db="cnblogdb" port=3306 charset="utf8" def __init__(self): pass #插入数据 #sqltext 插入数据的SQL语句 def InsertData(self,sqltext): db= pymysql.connect(host=self.host,user...
StarcoderdataPython