id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
268416
<filename>pybamm/parameters/size_distribution_parameters.py """ Adding particle-size distribution parameter values to a parameter set """ import pybamm import numpy as np def get_size_distribution_parameters( param, R_n_av=None, R_p_av=None, sd_n=0.3, sd_p=0.3, R_min_n=None, R_min_p=None...
StarcoderdataPython
291774
<reponame>Wollacy/Python ## Verificar uma String nome=str(input('Qual seu nome? ')) print('') if nome == 'Wollacy': print('Que nome bonito!') elif nome == 'Pedro' or nome == 'Maria' or nome == 'João': print('Nome popular no Brasil!') else: print('Nome comum!') print('') print('Olá {}!'.format(nome))
StarcoderdataPython
83422
from typing import Union, Iterable import torch import torch.nn.functional as F def cross_entropy( outs: torch.Tensor, labels: torch.Tensor, reduction: str = "mean" ) -> torch.Tensor: """ cross entropy with logits """ return F.cross_entropy(outs, labels, reduction=reduction) def cross...
StarcoderdataPython
8056346
<gh_stars>1-10 from enum import IntEnum class StatusCode(IntEnum): REQUEST_CANCELLED = 0 CONTINUE = 100 SWITCHING_PROTOCOLS = 101 PROCESSING = 102 OK = 200 CREATED = 201 ACCEPTED = 202 NON_AUTHORATIVE = 203 NO_CONTENT = 204 RESET_CONTENT = 205 PARTIAL_CONTENT = 206 MU...
StarcoderdataPython
5065816
import json from datetime import datetime, timedelta from uuid import uuid4 from django.core.management import call_command from django.test.testcases import TestCase import requests_mock from freezegun import freeze_time from djadyen import settings from djadyen.choices import Status from djadyen.models import Adye...
StarcoderdataPython
8024336
import data.simulation as sim import package.params as params import package.instance as inst import package.experiment as exp import package.batch as ba import pprint import zipfile def example_create_instance(): # we use the params default data to create a dataset: model_data = sim.create_dataset(params.OP...
StarcoderdataPython
11253491
<gh_stars>1-10 """API for Tasks""" from flask import Blueprint, jsonify from flask_login import login_required from ..tasks import channels_renew, list_all_tasks, remove_all_tasks from ..utils import admin_required api_task_blueprint = Blueprint("api_task", __name__) api_task_blueprint.before_request(admin_required) ...
StarcoderdataPython
6427116
from spira.log import SPIRA_LOG as LOG from spira.yevon.filters.filter import Filter from spira.yevon.gdsii.elem_list import ElementList from spira.yevon.geometry.ports.port_list import PortList from spira.yevon.process import get_rule_deck RDD = get_rule_deck() __all__ = [ 'ProcessBooleanFilter', 'Simplify...
StarcoderdataPython
208324
<reponame>mdeloge/opengrid # -*- coding: utf-8 -*- """ A setuptools based setup module for opengrid. Adapted from https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consis...
StarcoderdataPython
9692069
<filename>shop/spiders/markethot_spider.py # coding=utf-8 import datetime import logging import scrapy from shop.items import ShopItem logger = logging.getLogger('mycustomlogger') class MarkethotSpider(scrapy.Spider): name = 'markethot.ru' base_url = 'https://markethot.ru' search = '/catalog/search?sort=...
StarcoderdataPython
6420966
import populate_test_tables from archive.utils.mock_di_api import mock_api from archive.utils.operator_test import operator_test api = mock_api(__file__) # class instance of mock_api mock_api.print_send_msg = False # set class variable for printing api.send optest = operator_test(__file__) # config param...
StarcoderdataPython
3333301
<gh_stars>0 from bs4 import BeautifulSoup ''' beautiful soup xml html scraper must be imported from bs4 like this''' path = 'C:\some_path\fb_file.html' file = open(path,'rb') soup = BeautifulSoup(file,'html5lib',) #classes #_12gz = note titles #_2pin = things you posted (on walls, incl. notes, and self wall) #_3-96 _2l...
StarcoderdataPython
11283032
from flask import Flask, render_template, request, redirect, url_for from apiclient.discovery import build import configparser import json from flask_mail import Mail, Message from bin import utils from bin.weather import Weather from bin.mailmanager import MailManager app = Flask(__name__) #Load config.ini file. con...
StarcoderdataPython
3488119
<reponame>BMW-InnovationLab/BMW-Semantic-Segmentation-Training-GUI from domain.exceptions.application_error import ApplicationError class ConfigurationError(ApplicationError): def __init__(self, configuration_name: str, additional_message: str = ''): super().__init__('Could not create Configuration: ', ad...
StarcoderdataPython
9758843
# -*- coding: utf-8 -*- import datetime import locale import sys import time from random import choice from threading import Thread import os import lxml import requests from bs4 import BeautifulSoup as bs4 from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import QDate from PyQt5.QtGui import QIcon from Py...
StarcoderdataPython
5133861
from gyomei_trainer.builder import ( Builder, BaseBuilder, State, AverageValueMeter ) from gyomei_trainer.model import Model import gyomei_trainer.metrics import gyomei_trainer.modules __version__ = "1.0.2"
StarcoderdataPython
6702480
<reponame>faisaltheparttimecoder/carelogBackend from products.models import Product from products.serializers import ProductsSerializer from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from common.utilities import get...
StarcoderdataPython
291928
# -*- coding: utf-8 -*- # @Time : 2018/3/13 08:30 # @Author : play4fun # @File : compare_photos.py # @Software: PyCharm """ compare_photos.py: """ import cv2, pickle from pprint import pprint with open('photo_mat', 'rb') as f: mat = pickle.load(f) pairs = [] # 配对好的 lenX = 9 # 行 lenY = 8 # 列 def get_...
StarcoderdataPython
6608109
from typing import List import numpy as np from EOSMixture import EOSMixture from Factories.EOSMixFactory import createEOSMix from Properties import Props from compounds import SubstanceProp class MixtureModel: def __init__(self): self.propsliq: Props = None self.propsvap: Props = None ...
StarcoderdataPython
3236121
''' Created on Nov 26, 2009 @author: <NAME> ''' import numpy as N import scipy.signal as SS import scipy.interpolate as I import scipy.optimize as O import pylab as P class SplineFitting: def __init__(self, xnodes, spline_order = 3): ''' ''' self.xnodes = xnodes self.k = spli...
StarcoderdataPython
167516
<reponame>tcoxon/fishpye import numpy as np import world from math import * def sign(x): return cmp(x, 0) def positive(x): return x if x > 0 else 0 def trace_from_to(f, start, end): """ f(x,y,z) -> Bool """ last = (floor(end[0]), floor(end[1]), floor(end[2])) trace( lambda x, y, z...
StarcoderdataPython
11239490
<gh_stars>0 """ A module to simplify data wrangling using python. Mostly used to work on biological specimen data. The data manipulation is done using pandas. """ import os from glob import glob import pandas as pd def clean_duplicates(df,params): """Clean specify duplicates specimens. Keep t...
StarcoderdataPython
3586853
from requests.exceptions import HTTPError from .models.maven_model import maven_model_proxy, maven_model_hosted, maven_model_group from .models.docker_model import docker_model_proxy, docker_model_group, docker_model_hosted from .models.npm_model import npm_model_group, npm_model_hosted, npm_model_proxy from .models.yu...
StarcoderdataPython
8080441
<filename>web_scraping/seleniumtest_mac.py<gh_stars>0 import time, csv from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains url = "https://www.strava.com/login" # driver = webdriver.Chrome(executable_path="~/Documents/Ecole_Ingé/2A/Stage/projet_startup/web_scraping/chro...
StarcoderdataPython
3231106
<reponame>rortiz9/meleeml<filename>models/GAIL.py import torch import torch.nn as nn import torch.nn.functional as F from envs.dataset import * device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class Actor(nn.Module): def __init__(self, state_dim, action_dim): super(Actor, self).__in...
StarcoderdataPython
234426
<filename>2018/day_5/star_2/star.py from datetime import datetime def remove_all_from_polymer(polymer, type): p = polymer p = p.replace(type.lower(), "") p = p.replace(type.upper(), "") return p def react_polymer(polymer): start_time = datetime.now() i = 0 while i + 1 < len(polymer) - 1: if will_rea...
StarcoderdataPython
19448
import requests as reqlib import os import re import random import time import pickle import abc import hashlib import threading from urllib.parse import urlparse from purifier import TEAgent from purifier.logb import getLogger from enum import IntEnum from typing import Tuple, List, Dict, Optional cl...
StarcoderdataPython
5071838
""" author: <NAME> (E-mail: <EMAIL>) """ import torch import torch.nn as nn from torch_custom.stft_helper import StftHelper import torch_custom.spectral_ops as spo from torch_custom.custom_layers import CustomModel from torch_custom.wpe_th_utils import wpe_mb_torch_ri # class NeuralWPE(nn.Module): class NeuralWPE(C...
StarcoderdataPython
3203236
<gh_stars>1-10 import os import numpy as np import torch import copy from pytorch_pretrained_bert.file_utils import PYTORCH_PRETRAINED_BERT_CACHE from pytorch_pretrained_bert import BertTokenizer, BertModel # load data # processor = NerProcessor() # label_list = processor.get_labels() # num_labels = len(label_list) +...
StarcoderdataPython
4993537
import os import sys from shutil import rmtree from zipfile import ZipFile from ..parameters import ZIP_OPTIONS from ..core.helpers import console, splitModRef GH_BASE = os.path.expanduser(f'~/github') DW_BASE = os.path.expanduser(f'~/Downloads') TEMP = '_temp' RELATIVE = 'tf' HELP = ''' USAGE text-fabric-zip --hel...
StarcoderdataPython
8177162
<reponame>angelakuo/jupyter-extensions from notebook.utils import url_path_join from jupyterlab_vizier.handlers import ListHandler from jupyterlab_vizier.version import VERSION __version__ = VERSION def _jupyter_server_extension_paths(): return [{'module': 'jupyterlab_vizier'}] def load_jupyter_server_extension...
StarcoderdataPython
4888207
import os from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker DATABASE_URL = os.environ["DATABASE_URL"].replace("postgres://", "postgresql://") """ From https://docs.sqlalchemy.org/en/14/core/pooling.html Default pool/overflow size is 5/1...
StarcoderdataPython
3451242
<filename>repositories/actions/customer.py<gh_stars>0 from .baseactions import BaseActions from models.customer import Customer import re class CustomerActions(BaseActions): @classmethod def _regular_attribute_actions(cls, diff: dict, obj, old_obj=None): actions = [] for root_attr in diff: ...
StarcoderdataPython
44769
"""Utilities for tests""" import copy import re BAD_ID = "line %s: id '%s' doesn't match '%s'" BAD_SEQLEN = "line %s: %s is not the same length as the first read (%s)" BAD_BASES = "line %s: %s is not in allowed set of bases %s" BAD_PLUS = "line %s: expected '+', got %s" BAD_QUALS = "line %s: %s is not the same lengt...
StarcoderdataPython
317285
from time import sleep import rnc.corpora as rnc from tests.corpora.template import TemplateCorpusTest class TestAccentologicalCorpus(TemplateCorpusTest): corp_type = rnc.AccentologicalCorpus corp_normal_obj = corp_type('ты', 1, dpp=5, spd=1) corp_kwic_obj = corp_type('ты', 1, dpp=5, spd=1, out='kwic') ...
StarcoderdataPython
3596061
<reponame>loleg/kandidaten<filename>api/api.py from flask_peewee.rest import RestAPI, RestResource, UserAuthentication, AdminAuthentication, RestrictOwnerResource from app import app from auth import auth from models import Councillor, Promise, Decision, Comment api = RestAPI(app) admin_auth = AdminAuthentication(aut...
StarcoderdataPython
3511927
<gh_stars>1-10 #!/usr/bin/env python ''' Features for prepare source code. - prepare :: generic - autoconf :: run "configure" script found in source directory - cmake :: run cmake These features all rely on the "unpack" step to have run. It produces a "prepare" step. ''' from waflib.TaskGen import feature imp...
StarcoderdataPython
1787938
from changer import AmbientBackgrounds class Main: def run(self): self.ambient_bg = AmbientBackgrounds() self.ambient_bg.begin() if __name__ == "__main__": Main().run()
StarcoderdataPython
9758427
# -*- coding: utf-8 -*- from flask import Blueprint, render_template from duffy.models import Host blueprint = Blueprint('seamicro', __name__, url_prefix='/seamicro', template_folder='templates') @blueprint.route('/kickstarts/<hostname>') def kickstart(hostname): h = Host.query.filter(Host...
StarcoderdataPython
5053761
import os from collections import namedtuple from hislicing import env_const import logging logger = logging.getLogger(__name__) Cfg = namedtuple("Config", ["repoPath", "execPath", "sourceRoot", "classRoot", "startCommit", "endCommit", "buildScriptPath", "testScope", "touchSetPath"])...
StarcoderdataPython
9670413
<filename>remme/token/token_cli.py # Copyright 2018 REMME # # 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 ...
StarcoderdataPython
1969864
<reponame>mtianyan/TensorFlowPlayDemo # -*- coding: UTF-8 -*- """ RNN-LSTM 循环神经网络 """ import tensorflow as tf import keras # 神经网络的模型 def network_model(inputs, num_pitch, weights_file=None): model = keras.models.Sequential() model.add(keras.layers.LSTM( 512, # 输出的维度 input_shape=(inputs.shape[1...
StarcoderdataPython
9738898
<filename>setup.py import os from setuptools import setup # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(f_name): return open(os...
StarcoderdataPython
1839851
<reponame>asantinc/python-architecture-patters<filename>tests/test_model.py<gh_stars>0 from datetime import datetime, date, timedelta import pytest from model import OrderLine, Batch, allocate, OutOfStockError def make_batch_and_line(sku, batch_qty, line_qty, line_sku=None): line_sku = line_sku if line_sku else...
StarcoderdataPython
4854042
import dataclasses from typing import Optional from dis_snek.models import Guild, Member from ElevatorBot.backendNetworking.http import BaseBackendConnection from ElevatorBot.backendNetworking.routes import ( destiny_weapons_get_all_route, destiny_weapons_get_top_route, destiny_weapons_get_weapon_route, )...
StarcoderdataPython
11341897
from pettingzoo.utils.deprecated_module import DeprecatedModule adversarial_pursuit_v0 = DeprecatedModule("adversarial_pursuit", "v0", "v3") adversarial_pursuit_v1 = DeprecatedModule("adversarial_pursuit", "v1", "v3") adversarial_pursuit_v2 = DeprecatedModule("adversarial_pursuit", "v2", "v3") battle_v0 = DeprecatedMo...
StarcoderdataPython
4947203
<gh_stars>1-10 import copy import numpy as np from .utils import NAOParsing from nasws.cnn.search_space.darts.operations import WSBNOPS from nasws.cnn.search_space.darts.genotype import PRIMITIVES, Genotype from nasws.cnn.search_space.darts.darts_search_space import DartsModelSpec ALLOWED_OPS = PRIMITIVES DARTS_Node2A...
StarcoderdataPython
3521037
<reponame>mosesbaraza/docx from . import docxfile from . import docxmodify
StarcoderdataPython
279437
##--<NAME> ##--v2.0.1 [2013-10-21] # See install notes for directions # This script must be run with root permissions # sudo python setup.py ( /-client/-server) (-link) import sys , os , time ##--Bash install name--## ##--Ex: fl , filel , flocket, f-l , etc--## bashClientName = 'fl' bashServerName = 'fl-server...
StarcoderdataPython
3411092
<filename>esi_bot/request.py """Make GET requests to ESI.""" import re import json import time import html import http from esi_bot import ESI from esi_bot import ESI_CHINA from esi_bot import SNIPPET from esi_bot import command from esi_bot import do_request from esi_bot import multi_request from esi_bot.utils impo...
StarcoderdataPython
5013271
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 13 22:06:06 2020 @author: zuoxichen """ def String_to_list (Strings): list1=list(Strings.split(" ")) return list1 def main_approach (num1,num2): i=0 a=num1 b=num2 while a<=b : i+=1 a=a*3 b=b*2 else...
StarcoderdataPython
6494868
"""Author: <NAME>, Copyright 2019""" import tensorflow as tf from mineral.algorithms.critics.critic import Critic class TwinCritic(Critic): def __init__( self, critic1, critic2, **kwargs ): Critic.__init__(self, **kwargs) self.critic1 = critic...
StarcoderdataPython
9722432
i = 0 while(i<119): print(i) i += 10
StarcoderdataPython
282890
""" analytics.py Author: <NAME> Description: This module implements the Analytics class which provides handy statistics from data obtained while running the synthesizer. The .dat files produced from calling the save_data method of the plotter class can analyzed and the mean, std deviation and the like can be returned...
StarcoderdataPython
9777245
<filename>spacq/devices/tektronix/tests/server/test_awg5014b.py import logging log = logging.getLogger(__name__) from nose.tools import eq_ from numpy import linspace from numpy.testing import assert_array_almost_equal from unittest import main from spacq.interface.units import Quantity from spacq.tests.tool.box impo...
StarcoderdataPython
367584
# -*- coding: utf-8 -*- """ Created on Sun Aug 29 21:46:34 2021 @author: User """ ##################################################################### # Escribí otra leer_arboles(nombre_archivo) que lea el archivo indicado y # devuelva una lista de diccionarios con la información de todos los árboles # en el archiv...
StarcoderdataPython
6562585
# Copyright 2018 The TensorFlow Probability 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 required by applicable law o...
StarcoderdataPython
6686126
<filename>jaqalpaq/parser/tree.py<gh_stars>1-10 # Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains # certain rights in this software. """Functions and data types creating and acting on parse trees.""" f...
StarcoderdataPython
360553
from fastapi import FastAPI, Request, UploadFile, File from fastapi.templating import Jinja2Templates from fastapi.staticfiles import StaticFiles import uvicorn from src import const, preprocess import os import shutil from pathlib import Path import json templates = Jinja2Templates(directory="./templates") app = Fas...
StarcoderdataPython
295647
from os import path from setuptools import setup # get version __version__ = None exec(open('protobuf_serialization/version.py').read()) this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md')) as f: long_description = f.read() setup( name='protobuf-serializatio...
StarcoderdataPython
3544016
<reponame>cedadev/ndg_security_server """Paste related helper utilities (moved from ndg.security.test.unit.wsgi) NERC DataGrid Project """ __author__ = "<NAME>" __date__ = "25/01/11" __copyright__ = "(C) 2011 Science and Technology Facilities Council" __license__ = "BSD - see LICENSE file in top-level directory" __con...
StarcoderdataPython
8156065
<gh_stars>10-100 #/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2010-2012 <NAME> # # This file is part of e-cidadania. # # e-cidadania is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either ver...
StarcoderdataPython
3532581
# -*- coding: utf-8 -*- # Generated by Django 1.11.27 on 2020-02-19 10:37 from __future__ import unicode_literals from django.conf import settings import django.contrib.postgres.fields.jsonb import django.core.validators from django.db import migrations, models import django.db.models.deletion import outpost.django.ba...
StarcoderdataPython
5055896
<gh_stars>0 import numpy as np import pandas as pd import streamlit as st from .constants import RANDOM_STATE def app(): gpt = pd.read_csv('data/gpt.csv') gpt['file_path'] = gpt['audio_path'].str[1:] # gpt_split = pd.read_csv('data/gpt_split.csv') # gpt_split['file_path'] = gpt_split['file_path'].st...
StarcoderdataPython
3276755
<gh_stars>100-1000 # ------------------------------------------ # VQ-Diffusion # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # written By <NAME> # ------------------------------------------ import torch import math from torch import nn from image_synthesis.utils.misc import instantiate_from_...
StarcoderdataPython
1717338
""" Unreify RDF values in KGTK files """ from argparse import ArgumentParser, Namespace import attr from pathlib import Path import sys import typing from kgtk.kgtkformat import KgtkFormat from kgtk.io.kgtkreader import KgtkReader, KgtkReaderMode, KgtkReaderOptions from kgtk.io.kgtkwriter import KgtkWriter from kgtk.u...
StarcoderdataPython
3302962
from __future__ import unicode_literals from django.conf import settings from django.db.models import F, Case, When from django_filters.rest_framework.backends import DjangoFilterBackend from rest_framework.permissions import IsAuthenticatedOrReadOnly from geotrek.api.v2 import serializers as api_serializers, \ v...
StarcoderdataPython
396615
<reponame>mikimaus78/ml_monorepo<filename>BiBloSA/exp_SC/src/utils/time_counter.py<gh_stars>100-1000 import time class TimeCounter(object): def __init__(self): self.data_round = 0 self.global_training_time = 0 # todo: updated self.epoch_time_list = [] self.batch_time_list = [] ...
StarcoderdataPython
396960
<filename>connector/discord/discord_bot_connector.py import os import time import requests import discord import logging TOKEN = os.environ.get("DISCORD_TOKEN") client = discord.Client() def handle_command(user_id, user_entry, user_chan): print(user_id, user_entry, user_chan) response = "Hum ... I can't acc...
StarcoderdataPython
11213396
import os import sys import random import re import copy import matplotlib import matplotlib.pyplot as plt import pandas as pd import numpy as np import logging import datetime as dt from math import radians, cos, sin, asin, sqrt from datetime import datetime,timedelta from objects.objects import Cluster,Order,Vehicle,...
StarcoderdataPython
1809183
<reponame>bauchter-work/2445_git_repo import Adafruit_BBIO.GPIO as GPIO import Adafruit_BBIO.ADC as ADC ADC.setup() Value = ADC.read("P9_36") #Returns a value from 0 to 1 Voltage = Value*1.8 #converts to a voltage value print "Voltage is: ",Voltage," volts"
StarcoderdataPython
9799757
<filename>api/tests/api_gateway/test_api.py # pylint: disable=missing-class-docstring # pylint: disable=missing-function-docstring import json import os import main import pytest import uuid from aws_lambda_powertools.metrics import MetricUnit from fastapi import HTTPException from unittest.mock import ANY, MagicMock...
StarcoderdataPython
11246254
<gh_stars>0 # Generated by Django 3.2.6 on 2021-09-18 01:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('CollegeApp', '0001_initial'), ] operations = [ migrations.AddField( model_name='college', name='acceptan...
StarcoderdataPython
4598
# Install all examples to connected device(s) import subprocess import sys answer = input("Install all vulkan examples to attached device, this may take some time! (Y/N)").lower() == 'y' if answer: BUILD_ARGUMENTS = "" for arg in sys.argv[1:]: if arg == "-validation": BUILD_ARGUMENTS += "-v...
StarcoderdataPython
6684968
from __future__ import print_function, unicode_literals from argparse import ArgumentParser from code import InteractiveConsole import sys from wsgiref.simple_server import make_server from wsgiref.util import setup_testing_defaults from . import app, init_db, init_environ def main(argv=None): parser = make_arg...
StarcoderdataPython
4809873
<reponame>CogSciUOS/DeepLearningToolbox """Support for parsing of common Deep Learning Toolbox command line options. Intended usage: ``` from argparse import ArgumentParser import dltb.argparse as ToolboxArgparse # ... parser = ArgumentParser(...) # ... add specific arguments ... ToolboxArgparse.add_arguments(parse...
StarcoderdataPython
1691919
<filename>venv/Lib/site-packages/PySide6/examples/macextras/macpasteboardmime/macpasteboardmime.py ############################################################################ ## ## Copyright (C) 2017 The Qt Company Ltd. ## Contact: http://www.qt.io/licensing/ ## ## This file is part of the Qt for Python examples of t...
StarcoderdataPython
11204972
from redis.exceptions import ( ResponseError ) class RedisCluException(Exception): pass class AskError(ResponseError): """ partially keys is slot migrated to another node src node: MIGRATING to dst node get > ASK error ask dst node > ASKING command dst node: IMPORTING from s...
StarcoderdataPython
6651131
<gh_stars>100-1000 from .vtk import VTK, VTKVolume # noqa
StarcoderdataPython
12832211
<reponame>blazejmanczak/AoM-LineMatching<filename>overlay.py<gh_stars>1-10 # Copyright 2020-present, Netherlands Institute for Sound and Vision (<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 L...
StarcoderdataPython
5106377
<gh_stars>0 import re import unittest from unittest.mock import Mock from ats.topology import Device from genie.metaparser.util.exceptions import SchemaEmptyParserError, \ SchemaMissingKeyError from genie.libs.parser.nxos.show_ipv6 import ShowIpv6NeighborsDetailV...
StarcoderdataPython
1626157
"""Sorting utilities for alphanumeric strings.""" import re def _atoi(text): """Convert a string to an int.""" return int(text) if text.isdigit() else text def natural_sort(text): """Given an alphanumeric string, sort using the natural sort algorithm.""" return [_atoi(a) for a in re.split(r"(\d+)", ...
StarcoderdataPython
1974008
<gh_stars>1-10 #!/usr/bin/env python3 import unittest import numpy as np from panda import Panda from panda.tests.safety import libpandasafety_py import panda.tests.safety.common as common from panda.tests.safety.common import CANPackerPanda, make_msg, \ MAX_WRONG_COUNTERS, UNSAFE_...
StarcoderdataPython
333929
# -*- encoding=utf8 -*- from .parser import Parser from huey.djhuey import crontab, db_periodic_task # , db_task, periodic_task from weather_parser.models import City, AirPort from bs4 import BeautifulSoup from LatLon import Latitude, Longitude from cStringIO import StringIO import re import csv import requests s = P...
StarcoderdataPython
4845274
"""Imports""" import webbrowser class Movie(): """Movie class definition.""" def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube): # NOQA """Instantiates the Movie Class.""" self.title = movie_title self.storyline = movie_storyline self.pos...
StarcoderdataPython
3399029
<reponame>Park-Young-Hun/Algorithm from queue import Queue def solution(progresses, speeds): answer = [] q = Queue() # 각각의 기능에 대한 작업소요일을 queue에 넣음. for i in range(len(progresses)): progresses[i] = 100 - progresses[i] if progresses[i] % speeds[i] == 0: q.put(progresses[i] // s...
StarcoderdataPython
1833048
#!/usr/bin/env python3 class heap: @staticmethod def insert(nums, x): # 将元素加入到堆的末尾位置 nums.append(x) idx = len(nums) - 1 while idx != 0: parent_idx = int((idx - 1) / 2) # 如果插入的元素小,则需要和父节点交换位置 if nums[idx] < nums[parent_idx]: nu...
StarcoderdataPython
1932095
from drf_elasticsearch_dsl.tasks import searchIndexUpdateTask, searchIndexDeleteTask from drf_elasticsearch_dsl.connection_handler import connection_handler from django.db.models.signals import post_delete, post_save class CelerySignalProcessor(object): def __init__(self): self.setup() def handle_sa...
StarcoderdataPython
241230
<reponame>pipebio/api-examples from typing import Optional from library.models.sequence_document_kind import SequenceDocumentKind class UploadSummary: id: int sequence_count: Optional[int] sequence_document_kind: Optional[SequenceDocumentKind] def __init__(self, id: int, sequence_count: int = None, ...
StarcoderdataPython
6524490
from baselines.ddpg.memory import RingBuffer, array_min2d import random from collections import namedtuple import numpy as np import sortedcontainers import tensorflow as tf import math from os import path, makedirs class ESMemoryAdapter(object): """Adapter for the baselines DDPG code overwrite options: 'FIFO'...
StarcoderdataPython
1872989
import logging from selvpcclient import base from selvpcclient.util import resource_filter from selvpcclient.exceptions.base import ClientException log = logging.getLogger(__name__) class Subnet(base.Resource): """Represents a subnet.""" def delete(self): """Delete current subnet from domain.""" ...
StarcoderdataPython
1649024
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
StarcoderdataPython
12852279
<gh_stars>0 # Copying <NAME>'s solution https://github.com/hollygrimm/cs294-homework/blob/master/hw1/bc.py # Copy and pasting and merging it into a copy of my behavior_cloner.py code. import argparse import pickle import os import sys import tensorflow.compat.v1 as tf import numpy as np from sklearn.model_selection im...
StarcoderdataPython
8088183
<gh_stars>0 from discord.ext import commands def can_mute(**perms): def predicate(ctx): if ctx.author.guild_permissions.mute_members: return True else: return False return commands.check(predicate) def can_kick(**perms): def predicate(ctx): if ctx.author.gui...
StarcoderdataPython
3248713
from __future__ import print_function import os import sys import shutil import tempfile import pytest from gcpm.cli import cli __ORIG_ARGV__ = sys.argv def test_show_config(): sys.argv = ["gcpm", "show-config", "--config", "./tests/data/gcpm.yml"] cli() sys.argv = __ORIG_ARGV__ assert True def te...
StarcoderdataPython
272635
<reponame>vuhcl/cs110_final_project import math, mmh3 import numpy as np class QuotientFilter: # num_stored (n): the QF must be able to store this many elements # while maintaining the false positive rate. # error_rate (f): the theoretically expected probability of # returning false positives, default ...
StarcoderdataPython
6584427
from UdonPie import UnityEngine from UdonPie.Undefined import * class ParticleSystemShapeTextureChannel: def __new__(cls, arg1=None): ''' :returns: ParticleSystemShapeTextureChannel :rtype: UnityEngine.ParticleSystemShapeTextureChannel ''' pass
StarcoderdataPython
1790109
from django.contrib import admin from .models import Category, Section, Topic, Message from backend.utils.admin import all_fields class CategoryAdmin(admin.ModelAdmin): """Админка категорий""" list_display = ('title', 'id') class SectionAdmin(admin.ModelAdmin): """Админка разделов""" list_display =...
StarcoderdataPython
3511761
<filename>test_project/settings.py """ Django settings for test_project project. Generated by 'django-admin startproject' using Django 2.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/...
StarcoderdataPython
8075943
import json import pytest from GSuiteSecurityAlertCenter import MESSAGES, GSuiteClient, DemistoException from unittest.mock import patch def get_data_from_file(filepath): """ Returns data of specified file. :param filepath: absolute or relative path of file """ with open(filepath) as f: ...
StarcoderdataPython