id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1672564
#!/usr/bin/env python import unittest import Factorial class FactorialTest(unittest.TestCase): f=open('Factorial_Python_results.csv','w') @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): FactorialTest.f.close() def setUp(self): pass def test_1(self): if ...
StarcoderdataPython
1634586
from django.test import TestCase from dj_emailauth.models import User class UserModelTest(TestCase): def setUp(self): self.user = User.objects.create_user( password="password", email="<EMAIL>" ) self.user.full_clean() self.superuser = User.objects.create_superuser( ...
StarcoderdataPython
1607780
# Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All contributing project au...
StarcoderdataPython
3374272
from typing import List, Tuple, Optional from enum import Enum import subprocess import re import time from colorama import Fore from test_base import TestData from tests import TestSet import os.path class TestResult(Enum): PASSED = 1 FAILED = 2 IGNORED = 3 TestColors = { TestResult.PASSED: Fore.G...
StarcoderdataPython
1798493
<filename>app/starling/routes.py import base64 import hashlib import json from flask import request from dateutil import parser from app import db from app.helpers import json_response from app.starling import bp from app.starling.models import StarlingTransaction from app.users.models import User @bp.route('/webho...
StarcoderdataPython
4801188
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Version of WMCore/Services/Rucio intended to be used with mock or unittest.mock """ from __future__ import print_function, division from future.utils import listitems # from builtins import object # avoid importing this, it beraks things import json import logging impo...
StarcoderdataPython
124676
""" Created on Mon Feb 1 10:08:31 2016 """ #------------------------------------------------------------------------------ #CHAPTER 6: The Finite-Element Method #------------------------------------------------------------------------------ import numpy as np import matplotlib.pyplot as plt # Basic parameters nt = 1...
StarcoderdataPython
24856
import logging import sys import os from logging.handlers import RotatingFileHandler from multiprocessing.pool import ThreadPool from optparse import OptionParser import requests from requests.packages import urllib3 urllib3.disable_warnings() # Workers configurations ASYNC_WORKERS_COUNT = 100 # How many threads wi...
StarcoderdataPython
1690164
__author__ = 'steffenfb' import re from bs4 import BeautifulSoup import json def cookieToOneLine(): file = open('cookie.txt','r') content = file.read() clean = content.replace('\n','') clean = content.replace('\"','\'') file = open('cookie.txt','w') file.write(clean) file.close() tes...
StarcoderdataPython
130598
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="discovery_imaging_utils", # Replace with your own username version="v0.1.4", author="<NAME>", author_email="<EMAIL>", description="A package to aid in resting-state fMRI analysis", lon...
StarcoderdataPython
1626653
<gh_stars>1-10 class f: def __init__(self,t,q,p): self.t=t;self.q=q;self.p=p input=__import__('sys').stdin.readline n,x=map(int,input().split());d={};a=[] for _ in range(n): u,t,q,p=input().split() if u not in d.keys(): d[u]=f(t,int(q),int(p)) else: if d[u].q<int(q) or (d[u].q==i...
StarcoderdataPython
126257
#!/usr/bin/env python from .technical_analysis import TechnicalAnalysisStrategy from hummingbot.strategy.asset_price_delegate import AssetPriceDelegate from hummingbot.strategy.order_book_asset_price_delegate import OrderBookAssetPriceDelegate from hummingbot.strategy.api_asset_price_delegate import APIAssetPriceDeleg...
StarcoderdataPython
3238448
#!/usr/local/bin/python3.4 """ ## Copyright (c) 2015 SONATA-NFV, 2017 5GTANGO [, ANY ADDITIONAL AFFILIATION] ## 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 ## ## ...
StarcoderdataPython
1660317
<filename>setup.py #!/usr/bin/env python """ Pygr ==== Pygr is an open source software project used to develop graph database interfaces for the popular Python language, with a strong emphasis on bioinformatics applications ranging from genome-wide analysis of alternative splicing patterns, to comparative genomics que...
StarcoderdataPython
1642642
<reponame>yemi33/grasshopperfund<gh_stars>0 from django.test import TestCase from django.urls import reverse from django.contrib.auth.models import User from django.contrib import auth from django.core.files.uploadedfile import SimpleUploadedFile from ..models import Profile class TestUpdateProfile(TestCase): d...
StarcoderdataPython
4816459
<filename>pypy/module/gc/app_referents.py # NOT_RPYTHON import gc def dump_rpy_heap(file): """Write a full dump of the objects in the heap to the given file (which can be a file, a file name, or a file descritor). Format for each object (each item is one machine word): [addr] [typeindex] [size] [...
StarcoderdataPython
3338029
<reponame>Koalacards/2048AI import random from GameAgent import GameAgent, play_n_times class RandomAgent(GameAgent): def get_move(self, board): return random.choice(board.get_legal_moves()) play_n_times(RandomAgent(), 1000)
StarcoderdataPython
3388032
# Generated by Django 3.1.5 on 2021-02-08 01:35 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Intent', fields=[ ...
StarcoderdataPython
1714297
<reponame>esgomezm/deepcell-tf # Copyright 2016-2019 The <NAME> at the California Institute of # Technology (Caltech), with support from the Paul Allen Family Foundation, # Google, & National Institutes of Health (NIH) under Grant U24CA224309-01. # All rights reserved. # # Licensed under a modified Apache License, Vers...
StarcoderdataPython
3264373
<filename>delivery_bots/api/__init__.py import os import sentry_sdk sentry_sdk.init( os.getenv('SENTRY_URL', 'SENTRY'), traces_sample_rate=1.0, )
StarcoderdataPython
196444
<filename>revisiting_rainbow/Agents/dqn_agent_new.py """Compact implementation of a DQN agent Specifically, we implement the following components: * prioritized replay * huber_loss * mse_loss * double_dqn * noisy * dueling * Munchausen Details in: "Human-level control through deep reinforcement learni...
StarcoderdataPython
3229534
<reponame>earthobservatory/isce2<gh_stars>1-10 #!/usr/bin/env python3 from __future__ import print_function import logging import numbers import sys class DictUtils: @staticmethod # if a value for a given key is "empty" (like '',[],{}, None etc, except for zero) then the pair is removed def cleanDict...
StarcoderdataPython
109071
from epsilon.extime import Time from axiom.store import Store from axiom import attributes from axiom.tags import Catalog from axiom.item import Item from axiom.dependency import installOn from nevow.livetrial import testcase from nevow import tags, loaders from nevow.athena import expose from xmantissa.webtheme imp...
StarcoderdataPython
1766061
import json, urllib2, serial from websocket import create_connection port = '/dev/tty.usbmodem641' ard = serial.Serial(port, 115200, timeout=5) def set_valve(valve_number, state): message = chr(valve_number | (int(state) << 3)) ard.write(message) def get_states(distances): states = [False] * 6 for i...
StarcoderdataPython
93875
""" Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example 1: Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] Example 2: Input: n = 1 Output: ["()"] Constraints: 1 <= n <= 8 """ class Solution: def generateParenthesis(self, n: int...
StarcoderdataPython
105842
<filename>hyperband/torch_model.py import torch import torch.optim as optim import torch.nn as nn import torch.nn.functional as F class HiddenLayerNet(nn.Module): def __init__(self, n_features=10, n_outputs=1, n_hidden=100, activation="relu"): super().__init__() self.fc1 = nn.Linear(n_features, n_h...
StarcoderdataPython
1773797
<filename>day22_pong/main.py from turtle import Screen from score_board import Score from draw_center_line import DrawCenterLine from paddle import Paddle import main from ball import Ball import time WIDTH = 900 HEIGHT = 600 game_on = True active_player = 'left' player_1_score = 0 player_2_score = 0 scr...
StarcoderdataPython
1730652
<gh_stars>1-10 import logging from typing import List, Dict from bs4 import BeautifulSoup from parsers.pin7_cleanings import clean_row from storages.local import FileStorage, CsvStorage logger = logging.getLogger(__name__) class ParsedPages: def __init__(self, file: FileStorage, csv: CsvStorage) -> None: ...
StarcoderdataPython
107125
<filename>src/pypevue/examples/autoAdder3e.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- -- jiw 15 Oct 2020 # This pypevu plugin develops Delaunay triangulations. Is used by # variants of eg-auto-8-237 and eg-auto-test-2 for automatically # making edges (cylinders) between posts. autoAdder3e was adapted # from a...
StarcoderdataPython
1677540
<reponame>jaidevd/scikit-image import numpy as np from numpy.testing import assert_equal, assert_almost_equal import skimage from skimage import data from skimage.filters.thresholding import (threshold_adaptive, threshold_otsu, thresho...
StarcoderdataPython
191651
<filename>webserver/createdb.py import sqlite3 conn = sqlite3.connect('leaguemate.db') c = conn.cursor() sql_file=open('Newdatabase.sql') sql_as_str=sql_file.read() c.executescript(sql_as_str)
StarcoderdataPython
3351201
<filename>rosbag_decode/bag-decode.py from rosbags.rosbag2 import Reader from rosbags.serde import deserialize_cdr from datetime import datetime path = "rosbag_decode/test-logs/rosbag2_2021_06_01-19_24_43" def list_topics_test(): with Reader(path) as reader: # topic and msgtype information is available on...
StarcoderdataPython
1649561
<gh_stars>1-10 ''' Created on 1.12.2016 @author: Darren '''''' Implement a basic calculator to evaluate a simple expression string. The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces . You may assume that the given expr...
StarcoderdataPython
1768708
<filename>setup.py from setuptools import setup, find_packages setup( name='python-katas', packages=find_packages(), version='0.1', description='A Python GitHub repository for practicing katas.', author='<NAME>', author_email='<EMAIL>', url='https://github.com/DEV3L/python_katas', downl...
StarcoderdataPython
37826
from midiutil.MidiFile import MIDIFile import os def _create_midi_mapping(): """ Create a dictionary that maps note name to midi note integer """ middle_c = 60 notes = "c", "c#", "d", "d#", "e", "f", "f#", "g", "g#", "a", "a#", "b" equiv = (("c#", "db"), ("d#", "eb"), ("f#", "gb"...
StarcoderdataPython
3216336
<gh_stars>0 """ Different model components to use in building the overall model. The main component of interest is SentenceEncoder, which all the models use. """ import torch import torch.utils.data import torch.utils.data.distributed from allennlp.models.model import Model # StackedSelfAttentionEncoder from allennl...
StarcoderdataPython
3255652
""" 事件对象 threading.Event set() 将“Flag”设置为True clear() 将“Flag”设置为False wait() 如果“Flag”值为 False,主线程就会阻塞;如果“Flag”值为True,主线程不再阻塞。 isSet() 判断“Flag”值是否为True。 """ import threading import time #实例化一个事件对象 event = threading.Event() def run(): while not event.isSet(): print(threading.current_thread().getName(), ti...
StarcoderdataPython
149633
<reponame>mcorne/python-by-example<filename>examples/math.lgamma/ex1.py import math print(math.lgamma(2))
StarcoderdataPython
3338877
<filename>patterns/behavioral/template_method.py # -*- coding: utf-8 -*- # -------------------------------------------------------- # Licensed under the terms of the BSD 3-Clause License # (see LICENSE for details). # Copyright © 2018-2021, <NAME> # All rights reserved. # -----------------------------------------------...
StarcoderdataPython
3312738
<reponame>camidvorkin/frux-app-server<filename>frux_app_server/schema.py import graphene from .graphqlschema.mutation import Mutation from .graphqlschema.query import Query # pylint: disable=unused-argument schema = graphene.Schema(query=Query, mutation=Mutation)
StarcoderdataPython
3341995
<reponame>HuchieWuchie/AffordanceNet<filename>utils/drawing_utils.py import tensorflow as tf from PIL import Image, ImageDraw import matplotlib.pyplot as plt from utils import bbox_utils import numpy as np import cv2 background = [200, 222, 250, 0] contain = [255, 0, 0, 100] cut = [0, 153, 0, 100] display = [192, 192,...
StarcoderdataPython
64418
<filename>vkbottle/tools/dev_tools/auto_reload.py import os import sys from watchgod import awatch from vkbottle.modules import logger _startup_cwd = os.getcwd() def restart(): """ https://github.com/cherrypy/cherrypy/blob/0857fa81eb0ab647c7b59a019338bab057f7748b/cherrypy/process/wspbus.py#L305 """ arg...
StarcoderdataPython
3320823
## <NAME> ## September 28, 2020 """ ========================== Tools for the HRRR Archive ========================== to_180 For longitude values to be from -180 W to 180 E (not 0-360 E). get_crs Get cartopy projection object from xarray.Dataset pluck_points Pluck values at specific latitude/longitude poin...
StarcoderdataPython
63654
<reponame>illicitDev/DS-Unit-3-Sprint-2-SQL-and-Databases TOTAL_CHARACTERS = """ SELECT COUNT(name) FROM charactercreator_character; """ TOTAL_SUBCLASS = """ SELECT (SELECT COUNT(*) FROM charactercreator_cleric ) as cleric, (SELECT COUNT(*) FROM charactercreator_fig...
StarcoderdataPython
39928
from typing import Tuple, Optional import ray from ray import workflow @ray.remote def intentional_fail() -> str: raise RuntimeError("oops") @ray.remote def cry(error: Exception) -> None: print("Sadly", error) @ray.remote def celebrate(result: str) -> None: print("Success!", result) @ray.remote def...
StarcoderdataPython
1670321
<gh_stars>0 l=[5,1,4,4,3,3,9,8,8,9,9] l.sort() print(l) n=len(l) print(n) duplicatelist=[] prev=l[0] for i in range(1,n): curr=l[i] if curr==prev: if not prev in duplicatelist: duplicatelist=duplicatelist+[prev] prev=curr print(duplicatelist)
StarcoderdataPython
3218790
import argparse import re import jvmtunerInterface from jvmtunerInterface import JvmFlagsTunerInterface argparser = argparse.ArgumentParser(parents=[jvmtunerInterface.argparser]) argparser.add_argument( '--jvm_spec_startup', default='java -jar SPECjvm2008.jar {source} -ikv -crf false --jvmArgs "{Opt_flags}"', hel...
StarcoderdataPython
99909
def solution(value): print("Solution: {}".format(value))
StarcoderdataPython
35194
# ============================================================================= # System imports import logging import RPi.GPIO as RPiGPIO # ============================================================================= # Logger setup logger = logging.getLogger(__name__) # =============================================...
StarcoderdataPython
70805
<gh_stars>0 #!/usr/bin/env python3 # # This file is part of LiteX-Boards. # # Copyright (c) 2021 <NAME> <<EMAIL>> # Copyright (c) 2019-2020 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause import os import argparse from migen import * from litex_boards.platforms import snickerdoodle from litex.build.xilinx....
StarcoderdataPython
1707523
vel = float(input('Você está rodando a quantos km/h? ')) if vel <= 80: print('Muito bem! Continue com segurança.') else: print('Você excedeu o limite de 80km/h e foi multado. A multa é de R${:.2f}.'.format((vel-80)*7))
StarcoderdataPython
1664507
__all__ = [ 'GenerateKeys', 'GenerateKeysDeterministic' ] import os from ..base import ComputationStep from ...lookup.factory import KeyServerFactory from ...utils.exceptions import OasisException from ...utils.coverages import SUPPORTED_COVERAGE_TYPES from ...utils.data import get_utctimestamp class Gener...
StarcoderdataPython
3247835
# -*- coding: utf-8 -*- from __future__ import unicode_literals from vulyk.models.task_types import AbstractTaskType from vulyk_ner.models.tasks import NERTaggingAnswer, NERTaggingTask class NERTaggingTaskType(AbstractTaskType): """ NER Tagging Task to work with Vulyk. """ answer_model = NERTaggingAn...
StarcoderdataPython
4842567
<filename>lisa/lisa_user_data/coverage_test.py from lisa.core.lisa_core import LISA_Core from lisa.lisa_public_data.genes_test import FromGenes from lisa.core.data_interface import PACKAGE_PATH, REQURED_DATASET_VERSION, INSTALL_PATH from lisa.core.lisa_core import CONFIG_PATH as base_config_path import numpy as np from...
StarcoderdataPython
184406
import sys sys.path.insert(1, '/Users/anthonywohns/Documents/mcvean_group/age_inference/tsdate') import tsdate import tskit import tsinfer ts = tskit.load('truncated_simulation_tree.trees') tip_weights = tsdate.find_node_tip_weights_ts(ts) prior = tsdate.make_prior(ts.num_samples, 10000) mixture_prior = tsdate.get_m...
StarcoderdataPython
4831679
<filename>test/functional/p2p_add_connections.py<gh_stars>10-100 #!/usr/bin/env python3 # Copyright (c) 2020-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test add_outbound_p2p_connection test ...
StarcoderdataPython
154424
<gh_stars>1-10 from .vae import VAE from .mvae import MultimodalVAE from .pmvae import PartitionedMultimodalVAE from .hier_pmvae import HierPMVAE_v1, HierPMVAE_v2
StarcoderdataPython
1622174
""" Spew the contents of a file to standard output. Similar to Unix command 'cat' or Windows command 'type' for a single file. The file given on the command line is interpreted relative to a path that may be specified on the command line as -D path or in the configuration file as DOCROOT. """ import config impor...
StarcoderdataPython
1752886
<gh_stars>0 import numpy as np class DataSet: def __init__(self): self.input = None self.context = None self.output = None self.output_scaler = None self.output_columns = None self.output_dates = None def get_input(self, model_name: str) -> []: if mode...
StarcoderdataPython
1626012
from allauth.account.views import SignupView from users.forms import CustomUserCreationForm class MySignupView(SignupView): form_class = CustomUserCreationForm
StarcoderdataPython
1315
<filename>mango/__init__.py # In --strict mode, mypy complains about imports unless they're done this way. # # It complains 'Module has no attribute ABC' or 'Module "mango" does not explicitly export # attribute "XYZ"; implicit reexport disabled'. We could dial that back by using the # --implicit-reexport parameter, bu...
StarcoderdataPython
157942
<gh_stars>10-100 import numpy as np import matplotlib.pyplot as plt L = 3 Y, X = np.mgrid[-L:L:100j, -L:L:100j] U = -1 - X**2 + Y V = 1 + X - Y**2 speed = np.sqrt(U*U + V*V) plt.imshow(speed, extent=[-L, L, -L, L], alpha=0.5) plt.colorbar(label='speed') plt.streamplot(X, Y, U, V, linewidth=0.2*speed) plt.title('Str...
StarcoderdataPython
4822144
import os from pathlib import Path from shutil import copy2 import pytest from yappa.cli_helpers import create_function_version from yappa.config_generation import create_default_config from yappa.packaging.s3 import delete_bucket from yappa.utils import save_yaml from yappa.yc import YC @pytest.fixture(scope="sess...
StarcoderdataPython
92556
from __future__ import print_function import numpy as np import pandas as pd import inspect import os import time from . import Model from . import Utils as U #------------------------------ #FINDING NEAREST NEIGHBOR #------------------------------ def mindistance(x,xma,Nx): distx = 0 mindist = 1000000 * U.P...
StarcoderdataPython
1631745
<reponame>AlexArcPy/GDBee # -*- coding: UTF-8 -*- """Container of tabs.""" from PyQt5.QtWidgets import (QTabWidget, QAction, QToolButton, QMessageBox) from PyQt5.QtCore import Qt from tab import Tab from geodatabase import Geodatabase from cfg import dev_mode, not_connected_to_gdb_message ##########################...
StarcoderdataPython
23568
<gh_stars>1-10 # -*- coding: utf-8 -*- # --------------------------------------------------------------------- # main.pool application # --------------------------------------------------------------------- # Copyright (C) 2007-2019 The NOC Project # See LICENSE for details # -------------------------------------------...
StarcoderdataPython
1767074
<reponame>kenneym/py-feat<gh_stars>10-100 import cv2 import numpy as np import pandas as pd import torch import math import pandas as pd import numpy as np import feat.au_detectors.JAANet.JAANet_model as network import torch.nn as nn from PIL import Image from torchvision import transforms from feat.utils import get_re...
StarcoderdataPython
3358906
# Copyright (C) 2016 by VLAM3D Software inc. https://www.vlam3d.com # This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) from __future__ import print_function import argparse import vulkanmitts as vk import numpy as np from cube_data import * from vkcontextmanager import vkreleasing,...
StarcoderdataPython
156301
#------------------------------------------------------------------------------- # Name: powerlaw.py # Purpose: This is a set of power law coefficients(a,b) for the calculation of # empirical rain attenuation model A = a*R^b. #------------------------------------------------------------------------------- ...
StarcoderdataPython
3332605
<filename>tests/test_xarray_plugin.py import os.path import xarray as xr HERE = os.path.dirname(__file__) def test_xarray_open_dataset(): cog_file = os.path.join(HERE, "sample.tif") ds = xr.open_dataset(cog_file, engine="gdal-raw") assert isinstance(ds, xr.Dataset) assert "band1" in ds.data_vars ...
StarcoderdataPython
1626846
<reponame>darkless456/Python<filename>class7.py # class.py class num(object): def __init__(self,value): self.value = value def getNeg(self): return -self.value def setNeg(self,value): self.value = -value def delNeg(self): print("Value also deleted") del self.v...
StarcoderdataPython
90419
<gh_stars>1-10 # This file is based on the original C++ modeltest.cpp from: # http://code.qt.io/cgit/qt/qtbase.git/tree/tests/auto/other/modeltest/modeltest.cpp # Licensed under the following terms: # # Copyright (C) 2015 The Qt Company Ltd. # Contact: http://www.qt.io/licensing/ # # This file is part of the test suite...
StarcoderdataPython
3269793
<filename>backend/dataportal/test_plots.py import pytest from datetime import datetime, timedelta import random from .plots import pulsar_summary_plot def generate_random_utcs(n=10): min_year = 2018 max_year = 2020 start = datetime(min_year, 1, 1, 00, 00, 00) years = max_year - min_year + 1 end ...
StarcoderdataPython
3240734
<filename>tests/test_beam.py from __future__ import absolute_import, division, print_function import os import dxtbx from dxtbx.model.beam import BeamFactory def test_beam(): dxtbx_dir = dxtbx.__path__[0] image = os.path.join(dxtbx_dir, "tests", "phi_scan_001.cbf") assert BeamFactory.imgCIF(image)
StarcoderdataPython
1768214
from KnapsackProblem.KnapsackProblem import KnapsackProblem if __name__ == '__main__': print("------------- Knapsack Informations -------------") max_weight = int(input("Select max weight of knapsack: ")) length_items = int(input("Select max amount of items in the knapsack: ")) max_weight_items = int(input("Se...
StarcoderdataPython
1762696
<gh_stars>1-10 import time import oauth2 as oauth import requests from yahoo_weather.config.config import yahoo from yahoo_weather.config.units import Unit def get_city_url(API_param, city, unit=Unit.celsius): return oauth.Request(method="GET", url=yahoo.url_city.format(city=city, unit=unit), parameters=_get_pa...
StarcoderdataPython
1683119
import json import logging import os from smda.Disassembler import Disassembler def detectBackend(): backend = "" version = "" try: import idaapi import idautils backend = "IDA" version = idaapi.IDA_SDK_VERSION except: pass return (backend, version) if __...
StarcoderdataPython
100673
# -*- coding: utf-8 -*- __title__ = 'apostle' __version__ = '0.1.0' __build__ = 0x000100 __author__ = '<NAME>' __license__ = 'MIT' __copyright__ = 'Copyright 2013 Apostle.io' import os domain_key = os.getenv('APOSTLE_DOMAIN_KEY') delivery_host = os.getenv('APOSTLE_DELIVERY_HOST', 'https://deliver.apostle.io') from ...
StarcoderdataPython
164740
""" Copyright (c) 2022, Magentix This code is licensed under simplified BSD license (see LICENSE for details) StaPy JsMin Plugin - Version 1.0.0 Requirements: - jsmin """ from pathlib import Path import jsmin import os def file_content_opened(content, args: dict) -> str: if _get_file_extension(args['path']) != '...
StarcoderdataPython
3212355
import os from sklearn.model_selection import train_test_split path='../train_wav' train_txt='../meta/vox2_train.txt' val_txt='../meta/vox2_val.txt' def generate_txt(path): datasets = os.listdir(path) i = 0 data_list=[] label=[] for dataset in datasets: dataset_path = os.path.jo...
StarcoderdataPython
1673370
<gh_stars>0 # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright(c)2013 NTT corp. 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.apac...
StarcoderdataPython
3304786
<reponame>kelmore5/python-json-utilities import json as jsons from typing import Sequence, Union, Any, Dict, List, Set, Callable, Optional, Type from kelmore_arrays import ArrayTools as Arrays from kelmore_arrays.arrays import Matrix Items = Union[None, Dict[str, Any]] JSONList = List[Dict[Any, Any]] class DictObje...
StarcoderdataPython
1610528
#!/usr/bin/python # ecoding: utf-8 import sys, getopt, time, os import numpy as np from ratlib import * import matplotlib.pyplot as mpl helpmsg = """ drawh5sec.py -i rat.xvg -o rat5h.pdf -d 9:00 -n 20:53 -i Input extracted rat data -o Output filename (PDF format) -d Day-time start, HH:MM -n Night-time start, HH:M...
StarcoderdataPython
199698
<filename>app/article/permissions.py from rest_framework import permissions from core.models import Article class AuthorAccessPermission(permissions.BasePermission): def has_permission(self, request, view): if request.user.is_anonymous: return False elif request.user.is_author: ...
StarcoderdataPython
1602277
from django.db import models, OperationalError from django.urls import reverse import os from hashlib import sha256 from prplatform.core.models import TimeStampedModel from prplatform.users.models import User, StudentGroup from prplatform.courses.models import Course from prplatform.exercises.models import Submission...
StarcoderdataPython
3316559
<gh_stars>1-10 import json from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse from rest_framework import status from rest_framework.test import RequestsClient from rest_framework.test import APIRequestFactory from rest_framework.test import APITestCase class ...
StarcoderdataPython
4823214
<reponame>amartin-git/vpp-snmp-agent #!/usr/bin/env python3 # -*- coding: utf-8 -*- from vppstats import VPPStats from vppapi import VPPApi import sys import agentx try: import argparse except ImportError: print("ERROR: install argparse manually: sudo pip install argparse") sys.exit(2) class MyAgent(age...
StarcoderdataPython
1753669
<reponame>ProzorroUKR/reports<filename>reports/tests/utils.py<gh_stars>0 # coding: utf-8 import mock import os.path test_data = { "procurementMethod": "open", "doc_type": "Tender", "qualificationPeriod": { "startDate": "2017-11-14T15:15:00+02:00" }, "date": "2017-11-15T00:01:50Z", "own...
StarcoderdataPython
3206014
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2017 <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 # # Un...
StarcoderdataPython
101755
<reponame>x22x22/python-ceph-cfg # Import Python Libs from __future__ import absolute_import # Python imports import os import os.path import platform import logging import shlex import tempfile try: import ConfigParser except: import configparser as ConfigParser # local modules from . import constants from ....
StarcoderdataPython
137414
import errno import json import os import time from packaging import version from . import __version__, settings, utils def get_global_config_path(): old_path = os.path.join(os.path.expanduser("~"), settings.ALDRYN_DOT_FILE) if os.path.exists(old_path): return old_path else: return setti...
StarcoderdataPython
1792123
<filename>migrations/versions/f3c80e79066f_.py """empty message Revision ID: f3c80e79066f Revises: <PASSWORD> Create Date: 2019-06-05 20:12:49.715771 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = 'f3c80e79066f' down_revisi...
StarcoderdataPython
117895
<filename>script/cardiff_20_20/read_data.py<gh_stars>1-10 import os from os import path import pathlib import matplotlib.pyplot as plt import compound_poisson import dataset def main(): path_here = pathlib.Path(__file__).parent.absolute() figure_dir = path.join(path_here, "figure") if not path.isdir(fi...
StarcoderdataPython
76812
<reponame>gbudd3/spectre-api-python #!/usr/local/bin/python3 """ The spectre module is used to make access to Lumeta's Spectre API a little easier (Lumeta and Spectre are trademarks of the Lumeta Corporation). """ import requests import urllib3 import spectreapi import json from typing import Optional, List, Iterable ...
StarcoderdataPython
35002
from src.uint8 import uint8 def test_constructor1(): assert int(uint8(20)) == 20 def test_constructor2(): assert uint8(256) == uint8(0) assert uint8(260) == uint8(4) assert uint8(-1) == uint8(255) assert uint8(-5) == uint8(251) assert uint8(-5) != uint8(252) def test_add_other(): asser...
StarcoderdataPython
1661254
# -*- coding: utf-8 -*- from app.common.http_methods import post_request, get_request from app.common.target_urls import GENERIC_MISSION_PAGE, MISSION_STOPOVER from app.missions.missionparser import parse_all_missions_in_page, get_country_list, parse_stopover def list_missions(mission_type, countries_list): resu...
StarcoderdataPython
1628202
<reponame>kislam01/skelebot import argparse import unittest from unittest import mock import skelebot as sb class TestPrime(unittest.TestCase): def test_addParsers(self): parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) subparsers = parser.add_subparsers(dest="prime...
StarcoderdataPython
1750876
<reponame>fmitch/incubator-tvm<gh_stars>0 import logging import time import sys import os import numpy as np from multiprocessing import Pool, cpu_count import random import string from tensors import * import pickle import tvm import topi from topi.testing import conv2d_nchw_python from tvm import te from tvm import...
StarcoderdataPython
1607280
<filename>source/index.py import os import io import requests from lxml import etree service_index_source = 'https://www.kulturarvsdata.se/ksamsok/api?method=getServiceOrganization&value=all' r = requests.get(service_index_source) xml = etree.XML(r.content) institutions = list() services = list() for institution_n...
StarcoderdataPython
174158
<gh_stars>0 import os from urllib.parse import urljoin, urlparse import urllib import ntpath is_win32 = os.name == "nt" def createDirectory(base, new_dir): if is_win32: new_dir = cleanName(new_dir, ".") if not base.startswith("\\\\?\\"): base = "\\\\?\\" + base path_new_dir = os.path.join(base...
StarcoderdataPython