id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
62645
<reponame>krishotte/env_data2<gh_stars>0 from orator.migrations import Migration class AddDataPressure(Migration): def up(self): """ Run the migrations. """ with self.schema.table('data') as table: table.float('pressure') def down(self): """ Revert...
StarcoderdataPython
18990
<reponame>sladinji/blousebrothers<gh_stars>1-10 from django.db import migrations from decimal import Decimal from dateutil.relativedelta import relativedelta from datetime import date def fix_subscription(apps, schema_editor): Subscription = apps.get_model('confs', 'Subscription') SubscriptionType = apps.get...
StarcoderdataPython
3349715
<reponame>InfernalAzazel/dragon import time from fastapi import APIRouter, Request, BackgroundTasks from loguru import logger from robak import Jdy, JdySerialize from conf import Settings from func.jd_web_hook.models import WebHookItem doc = ''' 客户自销量奖励核算申请 -> 流程完成 -> 触发 目标表单: U8应收单过渡表 ...
StarcoderdataPython
1699237
<reponame>ftomassetti/pydiffparser from model import * # Diff Parser, produce Diff representations. class Parser: class SectionParser: def eat(self, lines, i, diff): if len(lines)==i: return if not lines[i].startswith("--- "): raise Exceptio...
StarcoderdataPython
140414
from django.apps import AppConfig class SharingmylinkfrontendConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'SharingMyLinkFrontEnd'
StarcoderdataPython
4841834
from unittest import skip import numpy as np from VariableUnittest import VariableUnitTest from gwlfe.AFOS.nonGrazingAnimals.Losses import NGLostBarnNSum class TestNGLostBarnNSum(VariableUnitTest): @skip('Not Ready Yet.') def test_NGLostBarnNSum(self): z = self.z np.testing.assert_array_almo...
StarcoderdataPython
114632
while True: try: n = int(input("Enter N: ")) except ValueError: print("Enter correct number!") else: if n <= 100: print("Error: N must be greater than 100!") else: for i in range(11, n + 1): s = i i = (i-1) + i*i ...
StarcoderdataPython
161725
<reponame>shahparth123/deploying-research from flask import Flask, redirect, url_for, request app = Flask(__name__) @app.route('/calculator/add/<a>/<b>') def add1(a, b): ans = int(a)+int(b) return 'answer is %s' % ans @app.route('/calculator/mul/<a>/<b>') def mul1(a, b): ans = int(a)*int(b) return 'answer...
StarcoderdataPython
83452
<filename>app.py #!/usr/bin/env python3 # local imports from os import name from os.path import abspath, dirname, join import time import logging import sqlite3 from sqlite3 import Error import requests from flask import flash, Flask, Markup, redirect, render_template, url_for, request from flask_sqlalchemy import ...
StarcoderdataPython
3274399
<reponame>c-yan/atcoder def f(data, total, targets): if total <= 0: return 0 result = INF for i in range(len(targets)): p, _, score, subtotal = data[targets[i]] t = (total + score - 1) // score if t < p and t < result: result = t nt = tuple(targets[0:i] + ...
StarcoderdataPython
3335038
from distutils.core import setup import py2exe setup( name = "Mal", description = "Python-based App", version = "1.0", console=["rawpymal.py"], options = { "py2exe": { "unbuffered": True, "optimize": 2, "bundle_files": 1, "packages":"ctypes", "includes": "base64,sys,socket,struct,time,code,platform,ge...
StarcoderdataPython
1793006
<gh_stars>0 import array import os from MSTClustering import * from optparse import OptionParser usage = 'test_MST.py reconFile [opt] <reconFile>' parser = OptionParser() parser.add_option('-o', '--output-file', type = str, dest = 'o', default = None, help = 'path to the output f...
StarcoderdataPython
193387
<reponame>sos1sos2Sixteen/tool-shack<filename>tests/basic.py import traceback import argparse import tool_shack.debug as debug import tool_shack.core as core import tool_shack.scripting as scripting import tool_shack.data as data from tool_shack.debug import testcase def tprint(*args, **kwargs): print(' ', en...
StarcoderdataPython
137542
<filename>modules/show_case/src/pages/examplebutton/examplebutton.py from kivy.uix.screenmanager import Screen from kivy.lang import Builder from kivy.uix.floatlayout import FloatLayout from kivy.clock import Clock from kivy_modules.kivyapi import kivyapi class ExampleButton(Screen): def __init__(self, **kwargs):...
StarcoderdataPython
3307293
<reponame>RohanTej/restaurant-manager from django.shortcuts import render from django.http import HttpResponse from .models import Post from django.urls import reverse from django.views.generic import ListView, DetailView, CreateView def home_view(request): context = { 'posts': Post.objects.all() } return render(...
StarcoderdataPython
1795849
import os, sys import tensorflow as tf # pass in model path as arg (eg - /tf-output/latest_model) # python score-model.py '../tf-output/latest_model' model_path = sys.argv[1] label_lines = [line.rstrip() for line in tf.gfile.GFile(model_path + "/got_retrained_labels.txt")] with tf.gfile.FastGFile(model_path + "/got...
StarcoderdataPython
1640968
<filename>code/ThreadDTO.py<gh_stars>0 class ThreadDTO: def __init__(self, id, subject, author, comment, fileurl, published, sticky, closed): self.id = id; self.subject = subject; self.author = author; self.comment = comment; self.fileurl = fileurl; self.published = published.strftime('%c'); ...
StarcoderdataPython
1610886
# Copyright 2018 PerfKitBenchmarker 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.org/licenses/LICENSE-2.0 # # Unless required by appli...
StarcoderdataPython
1712634
<reponame>EHilly/dreamnet import random import os import requests import pattern.en as en from dreamnet.english_cnet import * current_dir = os.path.dirname(__file__) dream_ideas = open(os.path.join(current_dir, "nounlist.txt")).read().splitlines() def locationItems(concept, min_weight=2, min_items=3): """Return no...
StarcoderdataPython
17076
<reponame>allanwright/media-classifier '''Defines a pipeline step which prepares training and test data for named entity recognition. ''' import ast import json import pickle from mccore import EntityRecognizer from mccore import ner from mccore import persistence import pandas as pd from sklearn.utils import resamp...
StarcoderdataPython
3237452
from aioflow.service import Service, ServiceStatus, service_deco from aioflow.pipeline import Pipeline from aioflow.middlewareabc import MiddlewareABC from aioflow.mixins import PercentMixin __author__ = "a.lemets"
StarcoderdataPython
3281599
<reponame>kenahoo/recurrent<gh_stars>1-10 import unittest import datetime from dateutil import rrule from recurrent.event_parser import RecurringEvent NOW = datetime.datetime(2010, 1, 1) class ExpectedFailure(object): def __init__(self, v): self.correct_value = v expressions = [ # recurring ev...
StarcoderdataPython
150438
<reponame>aagusti/sp2d<gh_stars>0 from ..models import SipkdBase, SipkdDBSession from datetime import datetime from sqlalchemy import ( Column, Integer, BigInteger, SmallInteger, Text, DateTime, Date, String, ForeignKey, text, UniqueConstraint, Numeric, ...
StarcoderdataPython
1681991
<reponame>MaxStrange/ArtieInfant """ Online logging script to be run concurrently with make train. """ import functools import itertools import math import matplotlib.pyplot as plt import matplotlib.animation as animation import sys import random FILE_PATH = "log.csv" class Plotter: def __init__(self, x1, y1, x2...
StarcoderdataPython
27500
import numpy as np from pathlib import Path import sys, os if __name__ == "__main__": """ Jobs: 1) VAE (VAE loss) for data=[dsprites, celeba, chairs] 2) VAE (beta-TC loss with alpha=beta=gamma=1) for data=[dsprites, celeba, chairs] 3) beta-TCVAE for alpha=gamma=[0.5, 1, 2], for beta=[3,6],...
StarcoderdataPython
3361365
"""Provides the main class for Merkle-trees and related functionalites """ from .hashing import hash_machine from .utils import log_2, decompose, NONE from .nodes import Node, Leaf from .proof import Proof from .serializers import MerkleTreeSerializer from .exceptions import LeafConstructionError, NoChildException, Em...
StarcoderdataPython
33475
<gh_stars>0 import torch class GradReverse(torch.autograd.Function): @staticmethod def forward(ctx, x): return x.view_as(x) @staticmethod def backward(ctx, grad_output): return - grad_output class LambdaLayer(torch.nn.Module): def __init__(self, fn): super().__init__() ...
StarcoderdataPython
149627
MX_ROBOT_MAX_NB_ACCELEROMETERS = 1 MX_DEFAULT_ROBOT_IP = "192.168.0.100" MX_ROBOT_TCP_PORT_CONTROL = 10000 MX_ROBOT_TCP_PORT_FEED = 10001 MX_ROBOT_UDP_PORT_TRACE = 10002 MX_ROBOT_UDP_PORT_RT_CTRL = 10003 MX_CHECKPOINT_ID_MIN = 1 MX_CHECKPOINT_ID_MAX = 8000 MX_ACCELEROMETER_UNIT_PER_G = 16000 MX_GRAVITY_MPS2 = 9.8067 MX...
StarcoderdataPython
3392618
<gh_stars>1-10 import os import json import pickle from datetime import date languages = ['fi', 'sv'] def process_articles(path="../data/yle", start_year=2012, end_year=2014): articles = {lang: [] for lang in languages} None_id = '18-3626' for lang in languages: print("Processing articles in: ", ...
StarcoderdataPython
1721750
<reponame>brechmos-stsci/deleteme<filename>cubeviz/image_viewer.py # This file contains a sub-class of the glue image viewer with further # customizations. import numpy as np from astropy import units as u from astropy.coordinates import SkyCoord from qtpy.QtWidgets import QLabel from glue.core.message import Setti...
StarcoderdataPython
124186
from pathlib import Path import configparser from logger import logger def change_config(**options): """takes arbitrary keyword arguments and writes their values into the config""" # overwrite values for k, v in options.items(): config.set('root', k, v) # write back, but without the mand...
StarcoderdataPython
1701602
<filename>space_invader.py import pygame import os import time import random import ctypes pygame.font.init() pygame.init() ctypes.windll.user32.SetProcessDPIAware() WIDTH, HEIGHT = pygame.display.Info().current_w, pygame.display.Info().current_h ENEMY_SHIP_SIZE_TRANSFORM = 0.08 WIN = pygame.display.set_mod...
StarcoderdataPython
3308475
import os import torch from pathlib import Path from typing import Dict, List from dotenv import load_dotenv from transformers import AutoModelForCausalLM, AutoTokenizer from rome import repr_tools from .layer_stats import layer_stats from .rome_hparams import ROMEHyperParams # Cache variables inv_mom2_cache = {} #...
StarcoderdataPython
1649772
<filename>test_autoarray/structures/test_kernel_2d.py from os import path import numpy as np import pytest from astropy import units from astropy.modeling import functional_models from astropy.coordinates import Angle import autoarray as aa from autoarray import exc test_data_dir = path.join("{}".format(pat...
StarcoderdataPython
1566
import pygame, math from game import map, ui window = pygame.display.set_mode([800, 600]) ui.window = window screen = "game" s = {"fullscreen": False} running = True gamedata = {"level": 0, "coal": 0, "iron": 1, "copper":0} tiles = pygame.sprite.Group() rails = pygame.sprite.Group() carts = pygame.sprite.Group() inter...
StarcoderdataPython
38112
def test_Dict(): x: dict[i32, i32] x = {1: 2, 3: 4} # x = {1: "2", "3": 4} -> sematic error y: dict[str, i32] y = {"a": -1, "b": -2} z: i32 z = y["a"] z = y["b"] z = x[1] def test_dict_insert(): y: dict[str, i32] y = {"a": -1, "b": -2} y["c"] = -3 def test_dict_get(...
StarcoderdataPython
60487
import logging from logging.handlers import RotatingFileHandler from flask.logging import default_handler from app import app if __name__ == '__main__': handler = RotatingFileHandler(filename='./log/app.log', maxBytes=1048576, backupCount=3) formatter = logging.Formatter(fmt='%(asctime)s - %(name)s[line:%(line...
StarcoderdataPython
4810271
<gh_stars>1-10 import numpy as np import pylab as plt from dopamine.stochastics import * from ipdb import set_trace as debug class DiscWorld(object): '''This provides a simulation environment for testing reinforcement learning algorithms. It provides a one-dimensional space with a one- dimensional a...
StarcoderdataPython
133758
<gh_stars>0 import json from app.service.http_client import http_client service_name = 'uaa' def get_user(login, jwt): return http_client('get', service_name, '/api/users/{}'.format(login), jwt=jwt) def send_message(message, jwt): return http_client('post', service_name, '/api/messages/send', body=json.du...
StarcoderdataPython
58859
# -*- python -*- import math import numpy import Shadow from Shadow.ShadowPreprocessorsXraylib import prerefl, pre_mlayer, bragg from srxraylib.sources import srfunc from sirepo.template import transfer_mat_bl from pykern.pkcollections import PKDict from pykern import pkjson sigmax = 0.0045000000000000005 sigdix = 2....
StarcoderdataPython
3373208
<filename>delft3dfmpy/io/gridio.py import netCDF4 import numpy as np import sys sys.path.append('D:/Documents/GitHub/delft3dfmpy') from delft3dfmpy.datamodels.cstructures import meshgeom, meshgeomdim import logging logger = logging.getLogger(__name__) def to_netcdf_old(meshgeom, path): outformat = "NETCDF3_CLA...
StarcoderdataPython
3217705
import math N = int(input()) X = list(map(int, input().split())) m, y, c = 0, 0, 0 for x in X: c = max(c, abs(x)) x = abs(x) m += x y += x**2 print(m) print(math.sqrt(y)) print(c)
StarcoderdataPython
4814206
from rest_framework import serializers from .models import Client, Contact, Employee class ClientSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = Client class ContactSerializer(serializers.ModelSerializer): def validate(self, data): """Проверка, что ко...
StarcoderdataPython
182442
<reponame>kungfumas/bahasa-alami # Latent Semantic Analysis using Python # Importing the Libraries from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import TruncatedSVD # Sample Data dataset = ["The amount of polution is increasing day by day", "The concert was just gre...
StarcoderdataPython
94340
<reponame>tschiex/toulbar2-diverse #!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import os, sys import matplotlib.pyplot as plt from utils import dissim, read_cfn_gzip, read_sim_mat python_path = "python3 /home/tschiex/toulbar2-diverse/python-scripts/" tb2 = "/home/tschiex/toulbar2-diverse/build/bin/...
StarcoderdataPython
1639776
from api.models import ( Account, Asset, CashAsset, ModelSerializerFactory, ModelViewSetFactory, Position, Share, StockAsset, ) from django.contrib.auth.models import User from django.urls import include, path from rest_framework import routers router = routers.DefaultRouter() router.re...
StarcoderdataPython
121485
<filename>algorithms.py<gh_stars>1-10 from grid import * from numpy.random import randint def dijkstra(draw, grid, start, end): print("started") inf = 100000 d = np.empty((len(grid), len(grid))) d.fill(inf) q = PriorityQueue() q.put((0, start)) d[start.get_pos()[0]][start.get_pos()[1]] = 0 ...
StarcoderdataPython
5763
<gh_stars>0 """Functional authentication tests with fake MRP Apple TV.""" import inspect from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop import pyatv from pyatv import exceptions from pyatv.const import Protocol from pyatv.conf import MrpService, AppleTV from pyatv.mrp.server_auth import PIN_CODE, ...
StarcoderdataPython
3379896
<filename>checksec.py #!/usr/bin/env python3 import json import sys import asyncio import os from pathlib import Path from urllib import request # PE files winchecksec_required_all = { "aslr": "Present", # randomised virtual memory layouts "dynamicBase": "Present", # enables the program to by loaded anywhere...
StarcoderdataPython
119192
<reponame>Stranger6667/Flask-Postmark<filename>test/conftest.py import pytest from flask import Flask, json, request from flask_postmark import Postmark @pytest.fixture def app(server_token, postmark_request): app = Flask(__name__) app.config["POSTMARK_SERVER_TOKEN"] = server_token app.config["JSONIFY_PR...
StarcoderdataPython
3268932
<reponame>KopelmanLab/au_nanosnake_dda import os import time import subprocess import argparse import pickle def main(): parser = argparse.ArgumentParser() parser.add_argument('dirno', type=int) args = parser.parse_args() os.chdir('wavelengths_{}'.format(args.dirno)) time_taken = None start_...
StarcoderdataPython
3291928
"""Mock AiiDA database""" import os from datetime import datetime as timezone from sqlalchemy import ( Column, DateTime, ForeignKey, Integer, String, create_engine, event, ) from sqlalchemy.orm import declarative_base, relationship, sessionmaker from sqlalchemy.orm.session import Session fr...
StarcoderdataPython
125504
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- import torch import torch.nn.functional import numpy as np def conv2d_size_out(size, kernel_size=4, stride=2): return (size - (kernel_size - 1) - 1) // stride + 1 class QNetwork(torch.nn.Module): def __init__(self, obs_shape, act_shape): sup...
StarcoderdataPython
3337539
""" Creates a neat little batch file that can be used to download Advent of Code input files and also stores the day's part 1 website for offline use Prep work: - get the session cookie value (e.g. from Chrome's cookies) and update it below - create the required directories (mkdir xx from a command prompt) - i should ...
StarcoderdataPython
3323840
""" Find Angle MBC https://www.hackerrank.com/challenges/find-angle/problem """ from math import atan2, pi AB = int(input()) BC = int(input()) print(u"{}°".format(round(atan2(AB, BC) * 180 / pi)))
StarcoderdataPython
1602132
<reponame>UDICatNCHU/KCM-Data-Source-Extractor # -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import import logging from itertools import takewhile, count from six.moves import zip from dcard import api from dcard.utils import flatten_lists logger = logging.getLogger(__name__) ...
StarcoderdataPython
1656607
import sys FILE = sys.stdin # FILE = open('sample.in') test_cases = range(int(FILE.readline())) for tc in test_cases: # number of stores to visit n = int(FILE.readline().strip()) # positions on Long street x = list(map(int, FILE.readline().strip().split())) print(2 * (max(x) - min(x)))
StarcoderdataPython
29525
class KeyBoardService(): def __init__(self): pass def is_key_pressed(self, *keys): pass def is_key_released(self, *key): pass
StarcoderdataPython
4816844
from pylab import * def marker(m,name): size = 256,16 dpi = 72.0 figsize= size[0]/float(dpi),size[1]/float(dpi) fig = figure(figsize=figsize, dpi=dpi) fig.patch.set_alpha(0) axes([0,0,1,1],frameon=False) X = np.arange(11) Y = np.ones(11) plot(X,Y,color='w', lw=1, marker=m, ms=10, mf...
StarcoderdataPython
1781972
import argparse import re import os import random import json from tqdm import tqdm import math import rdkit.Chem as Chem from template.generate_retro_templates import process_an_example from template.rdchiral.main import rdchiralRun, rdchiralReaction, rdchiralReactants import pdb def smi_tokenizer(smi): """ ...
StarcoderdataPython
1660198
<filename>config/urls.py from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^accounts/reset/(?...
StarcoderdataPython
3316021
import smtplib from email.mime import MimeText class Notifiers: def __init__(self): self._default = None self._notifiers = {} def add(self, name, kind, default=False, **kwargs): notifier = _known_notifiers[kind](**kwargs) self._notifiers[name] = notifier if default: ...
StarcoderdataPython
1664609
import os import sys import cv2 import numpy as np DRONE_IMAGE_SIZE = (5300, 7950) CASE1_CONFIG = ["./images/CASE_1", "drone7.JPG", 800, 600, 4096, 4096] CASE2_CONFIG = ["./images/CASE_2", "drone10.JPG", 409, 1200, 4096, 4096] CASE3_CONFIG = ["./images/CASE_3", "drone8.JPG", 700, 200, 4096, 4096] CASE4_CONFIG = ["./i...
StarcoderdataPython
3323800
<filename>tests/test_rk4step.py<gh_stars>1-10 # # test_varstep.py # from delsmm.systems.lag_doublepen import LagrangianDoublePendulum import torch import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt def test(): torch.set_default_dtype(torch.float64) torch.manual_seed(1) sys = LagrangianDoub...
StarcoderdataPython
4817181
import numpy as np BIG_NUM = 1000000 # try factors of 10 until solution found goal = 33100000 houses_a = np.zeros(BIG_NUM) houses_b = np.zeros(BIG_NUM) for elf in xrange(1, BIG_NUM): houses_a[elf::elf] += 10 * elf houses_b[elf:(elf+1)*50:elf] += 11 * elf print(np.nonzero(houses_a >= goal)[0][0]) print(np.n...
StarcoderdataPython
1753552
import logging from django import forms from django.contrib import admin, messages from django.contrib.admin import ModelAdmin, SimpleListFilter, widgets from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import Group from django.forms import Form from django.template.response import Templ...
StarcoderdataPython
27889
<filename>EllipticCurves/Curve.py import matplotlib.pyplot as plt import numpy as np def main(): a = -1 b = 1 y, x = np.ogrid[-5:5:100j, -5:5:100j] plt.contour( x.ravel(), y.ravel(), pow(y, 2) - pow(x, 3) - x * a - b, [0] ) plt.plot(1, 1, 'ro') plt.grid() ...
StarcoderdataPython
1774454
<gh_stars>1-10 ########################################################################### ### Calibration of the conceptual groundwater model using NSGA-II ### ### Author : <NAME> ### ### Last Edit: 07 Jul 2020 ### ...
StarcoderdataPython
1643614
<reponame>vmgabriel/tabu-base<filename>src/config/__init__.py<gh_stars>0 """ Configuration of env """ # Modules from src.config.tabu import configuration as config_tabu configuration = { 'tabu': config_tabu, }
StarcoderdataPython
153909
<reponame>94JuHo/Algorithm_study import sys input_data = sys.stdin.readline().rstrip() print(input_data)
StarcoderdataPython
188762
import twitter import ccxt import logging import wget import pytesseract from datetime import datetime, timedelta, timezone from dynaconf import settings from PIL import Image logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)-40s %(levelname)-8s %(message)s") logger = logging.getLogger(__name__) bit...
StarcoderdataPython
4800104
import pandas as pd student={'A':39,'B':41,'C':42,'D':44} s=pd.Series(student) print(s)
StarcoderdataPython
108218
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from webbreaker.webbreakerlogger import Logger json_scan_settings = { "settingsName": "", "overrides": { "scanName": "" } } def formatted_settings_payload(settings, scan_name, runenv, scan_mode, scan_scope, login_macro, scan_polic...
StarcoderdataPython
1724658
<gh_stars>0 import time import gzip import csv import logging import sys if sys.version_info.minor < 7: import importlib_resources else: import importlib.resources as importlib_resources import tqdm import pandas as pd import numpy as np import scipy.sparse from sklearn.metrics import pairwise_distances, pair...
StarcoderdataPython
3266917
import unittest from bingocardgenerator.square_getter import filter_candidates class TestFilterCanidates(unittest.TestCase): def test_filter_unique_candidates_returns_identity(self): self.assertEqual(filter_candidates(['a', 'b', 'c']), ['a', 'b', 'c']) def test_filter_redundant_candidates(self): ...
StarcoderdataPython
3284260
import pandas as pd from tqdm.notebook import tqdm as tqdm import multiprocessing from functools import reduce import numpy as np def get_sub_timeseries(df_x, index, window_start, window_end, identifier): """ Helper method which extracts a sub dataframe of a pandas dataframe. The sub dataframe is defined by a ...
StarcoderdataPython
3325089
<reponame>KonstantinPakulev/OSM-one-shot-multispeaker<filename>src/main.py<gh_stars>0 import argparse import yaml import os from tts_modules.common.multispeaker import MultispeakerManager if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("main_config_path", type=str, ...
StarcoderdataPython
160625
<reponame>niole/Parse-Graph import collections def parseGraphFromString(inputLines): graph = collections.defaultdict(set) for line in inputLines: graph[line[0]].add(line[5]) return graph output = { 'a' : {'b', 'c'}, 'b' : {'c', 'f'}, 'd' : {'a'} } inputLines = """a ...
StarcoderdataPython
1752031
<reponame>Amourspirit/ooo_uno_tmpl<gh_stars>0 # coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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
4809883
from model import profile class SessionHelper: def __init__(self, app): self.app = app def get_url(self): return self.app.driver.current_url def login(self, user): driver = self.app.driver if not driver.current_url.endswith("/account"): driver.get("https://ucb...
StarcoderdataPython
1630926
import collections, time, functools from matplotlib.patches import FancyArrowPatch from mpl_toolkits.mplot3d import proj3d class Arrow3D(FancyArrowPatch): """ Arrow used in the plotting of 3D vecotrs ex. a = Arrow3D([0, 1], [0, 1], [0, 1], mutation_scale=20, lw=1, arrowstyle="-|>", color=...
StarcoderdataPython
3268620
<gh_stars>1-10 #!/usr/bin/python3 # -*- coding: UTF-8 -*- # @license : Copyright(C), Your Company # @Author: <NAME> # @Contact : <EMAIL> # @Date: 2020-09-15 21:41 # @Description: # https://www.jianshu.com/p/1e498888f505 # https://github.com/jllan/jannlp # @Software : PyCharm import re impor...
StarcoderdataPython
4839055
''' input: list of words or raw string output: dictionary mapping words to frequencies ''' def word_frequency(text): if type(text) == str: text = text.split(' ') d = dict() for word in set(text): d[word] = 0 for word in text: d[word] += 1 return 'word_frequency',d ''' input: list of words or raw string outp...
StarcoderdataPython
3295439
#!/usr/bin/env python3 import argparse import socket import time import struct from collections import OrderedDict class Barrier: def __init__(self, host, port, waitFor, printer=None): self.host = host self.port = port self.waitFor = waitFor self.printer = printer self.star...
StarcoderdataPython
3330349
<filename>coop2/bin/thread.py #!/usr/bin/env python3 import RPi.GPIO as GPIO from time import sleep import threading # basackwards relay setup RUN = False STOP = True # setup I/O Constants DOOR_UP = 4 DOOR_DOWN = 5 DOOR_LOCK = 6 LIGHTS = 7 MAN_UP = 22 MAN_DOWN = 23 MAN_LIGHT = 24 UP_PROX = 26 DOWN_PROX = 27 # setup...
StarcoderdataPython
1614270
<reponame>yaakov-github/notifiers import pytest import datetime import time from email import utils from notifiers.exceptions import BadArguments from notifiers.core import FAILURE_STATUS provider = 'mailgun' class TestMailgun: def test_mailgun_metadata(self, provider): assert provider.metadata == { ...
StarcoderdataPython
98952
# coding=utf-8 import time from service.mahjong.models.hutype.basetype import BaseType from service.mahjong.constants.carddefine import CardType from service.mahjong.models.hutype.basetype import BaseType from service.mahjong.constants.carddefine import CardType, CARD_SIZE from service.mahjong.models.card.hand_card im...
StarcoderdataPython
1778002
<reponame>ftconan/python3 """ @author: magician @date: 2019/11/22 @file: namedtuple_demo.py """ import json from collections import namedtuple Car = namedtuple('Car', 'color mileage') class MyCarWithMethods(Car): """ MyCarWithMethods """ def hexcolor(self): if self.color == 'red':...
StarcoderdataPython
3281585
import logging from hetdesrun.component.load import base_module_path from hetdesrun.runtime.exceptions import ( RuntimeExecutionError, DAGProcessingError, UncaughtComponentException, MissingOutputDataError, ComponentDataValidationError, WorkflowOutputValidationError, WorkflowInputDataValida...
StarcoderdataPython
45078
#!/usr/bin/env python3 """TPatrick | Alta3 Research Creating a simple dice program utilizing classes.""" from random import randint class Player: def __init__(self): self.dice = [] def roll(self): self.dice = [] for i in range(3): self.dice.append(randint(1,6)) de...
StarcoderdataPython
69655
def solution(lottos, win_nums): answer = [] zeros=0 for i in lottos: if(i==0) : zeros+=1 correct = list(set(lottos).intersection(set(win_nums))) _dict = {6:1,5:2,4:3,3:4,2:5,1:6,0:6} answer.append(_dict[len(correct)+zeros]) answer.append(_dict[len(correct)]) return answer
StarcoderdataPython
1799547
<gh_stars>0 import json import sys from pathlib import Path from django.conf import settings from django.contrib import messages from django.core.exceptions import ObjectDoesNotExist from django.db.models import F from django.forms import formset_factory from django.http import HttpResponse, HttpResponseRedirect from ...
StarcoderdataPython
1623353
<reponame>lars-frogner/bifrost-rust #!/usr/bin/env python import os import sys import re import pathlib import logging import shutil import csv import warnings import numpy as np from tqdm import tqdm from ruamel.yaml import YAML from joblib import Parallel, delayed from matplotlib.offsetbox import AnchoredText try: ...
StarcoderdataPython
3237292
from datetime import datetime from ..schema import BaseTransformer class Transformer(BaseTransformer): """Transform South Carolina raw data for consolidation.""" postal_code = "SC" fields = dict( company="company", location="location", notice_date="date", jobs="jobs", ...
StarcoderdataPython
1609785
"""Density plot from a distribution of points in 3D""" import numpy as np from vedo import * n = 3000 p = np.random.normal(7, 0.3, (n,3)) p[:int(n*1/3) ] += [1,0,0] # shift 1/3 of the points along x by 1 p[ int(n*2/3):] += [1.7,0.4,0.2] pts = Points(p, alpha=0.5) vol = pts.density().c('Dark2').alpha([0.1,1]) #...
StarcoderdataPython
1677051
from __future__ import absolute_import from django.utils.translation import ugettext_lazy as _ from sentry import http, options from sentry.identity.pipeline import IdentityProviderPipeline from sentry.identity.github import get_user_info from sentry.integrations import IntegrationProvider, IntegrationMetadata from s...
StarcoderdataPython
4834526
import sys,os curr_path = os.path.dirname(os.path.abspath(__file__)) # 当前文件所在绝对路径 parent_path = os.path.dirname(curr_path) # 父路径 sys.path.append(parent_path) # 添加路径到系统路径 import gym import torch import numpy as np import datetime from common.utils import plot_rewards from common.utils import save_results,make_dir from ...
StarcoderdataPython
4823576
<reponame>tylerclair/py3canvas<filename>py3canvas/apis/submissions.py """Submissions API Version 1.0. This API client was generated using a template. Make sure this code is valid before using it. """ import logging from datetime import date, datetime from .base import BaseCanvasAPI from .base import BaseModel class ...
StarcoderdataPython
122038
import numpy as np import sympy as sp from scipy.misc import derivative from prettytable import PrettyTable import math from math import * def nuevosValoresa(ecua, derivadas, Ecuaciones, variables,var): valor_ini = [] func_numerica = [] derv_numerica = [] funcs = vars(math) for i in range(0, Ecuac...
StarcoderdataPython
4829234
# python3 -m annotator.panoptic_segmenter from detectron2.data import MetadataCatalog from detectron2.config import get_cfg from detectron2.engine import DefaultPredictor from detectron2 import model_zoo class PanopticSegmenter(object): def __init__(self, *args): super(PanopticSegmenter, self).__init__(*...
StarcoderdataPython