id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
8114545
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class CloudbusTotalOdItem(object): def __init__(self): self._code = None self._message = None self._totalod = None self._weekend_od = None self._workday_od = Non...
StarcoderdataPython
206389
n = float(input('Digite o 1º numero: ')) n1 = float(input('Digite o 2º numero: ')) n2 = 0 while n2 != 5: print(''' [1] somar [2] Multiplicar [3] Maior [4] Novos numeros [5] Sair do programa''') n2 = int(input('Sua opção: ')) if n2 == 1: n3 = n + n1 print(f'A soma entre {n} + {n1} é ...
StarcoderdataPython
1959209
<filename>friendly-asyncio/6-aiohttp-server.py<gh_stars>10-100 import asyncio import random from aiohttp import web routes = web.RouteTableDef() @routes.get(r"/randint/{number:\d+}") async def randint(request): try: number = int(request.match_info["number"]) except Exception: number = 20 ...
StarcoderdataPython
11217137
<reponame>mdw771/tomosim # -*- coding: utf-8 -*- """ This script works for foam phantom. Plot snr_intrinsic and fidelity against truncation ratio. Will read already-generated data. Use foam_eff_ratio if not exists. """ import numpy as np import glob import dxchange import matplotlib.pyplot as plt import tomopy import...
StarcoderdataPython
12839151
from __future__ import absolute_import, division, print_function from cfn_model.model.ModelElement import ModelElement class EC2NetworkInterface(ModelElement): """ Ec2 network interface model lement """ def __init__(self, cfn_model): """ Initialize :param cfn_model: ""...
StarcoderdataPython
1788767
"Unit test for the game-board class" import unittest from .board import * def place_stone(board, color, x, y): board[x,y] = color class TestBoard(unittest.TestCase): def test_creation(self): width = 20 height = 40 board = Board(height, width) self.assertEqual(board.shape, (he...
StarcoderdataPython
9650606
import sys from asyncio import AbstractEventLoop, get_event_loop_policy from typing import List, Optional, Union from unittest.mock import MagicMock, Mock, patch if sys.version_info >= (3, 8): from unittest.mock import AsyncMock else: class AsyncMock(MagicMock): async def __call__(self, *args, **kwarg...
StarcoderdataPython
5195872
<gh_stars>1-10 # -*- coding: utf-8 -*- """ test.t_utils.test_file ~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2014 by the RootForum.org team, see AUTHORS. :license: MIT License, see LICENSE for details. """ import os import tempfile from unittest import TestCase, skipUnless, skipIf import sys from mag...
StarcoderdataPython
6636133
<gh_stars>0 from django.contrib import admin from .models import Link, Node admin.site.register(Node) admin.site.register(Link)
StarcoderdataPython
4940868
<reponame>LikimiaD/HackerRank<gh_stars>0 from itertools import product print(*product(map(int, input().split(' ')), map(int, input().split(' '))))
StarcoderdataPython
9645722
# purchase/urls.py from django.urls import path from . import views app_name = "purchase" urlpatterns = [ path('', views.PurchaseView.as_view(), name='home'), path('invoice/<int:invoice_id>', views.InvoiceView.as_view(), name='invoice'), ]
StarcoderdataPython
16756
from typing import Tuple import torch class RunningMeanStd: """ Utility Function to compute a running mean and variance calculator :param epsilon: Small number to prevent division by zero for calculations :param shape: Shape of the RMS object :type epsilon: float :type shape: Tuple """ ...
StarcoderdataPython
1608179
# <NAME> # GUI class from Tkinter import * import TTT_game import TTT_AI ##################### """The Class to Create an App.""" class TTT(object): def __init__(self, master): ''' Initializes the variables for the game and tkinter window. Pre: The Tkinter master is supplied. Post: Game a...
StarcoderdataPython
5158800
<reponame>ericjwhitney/pyavia #!/usr/bin/env python3 # Examples of stress concentration factor along the bore of straight or # countersunk holes. Reproduces results of NASA-TP-3192 Figure 4, 7(a) and # 7(b) # Written by: <NAME> Last updated: 9 April 2020 import numpy as np import matplotlib.pyplot as plt from pya...
StarcoderdataPython
44966
import json import os from eg import config from eg import substitute from eg import util from mock import Mock from mock import patch PATH_UNSQUEEZED_FILE = os.path.join( 'test', 'assets', 'pwd_unsqueezed.md' ) PATH_SQUEEZED_FILE = os.path.join( 'test', 'assets', 'pwd_squeezed.md' ) def _cr...
StarcoderdataPython
1990628
from fastapi import APIRouter from app.schemas import UserCreate, UserUpdate from app.models import User user_router = APIRouter( prefix="/user", tags=["user"], responses={404: {"description": "Not found"}}, ) @user_router.get("/by_id") async def user_find_by_id(id: int): user = await User.find_by_id(id=id) ...
StarcoderdataPython
11250634
<filename>resources/models/commons/errors/computersRouteErrors.py<gh_stars>0 #encoding utf-8 #__author__ = <NAME>, <EMAIL> #Python3 __author__ = '<NAME>' from datetime import datetime from resources.models.commons.database_manager import Database from resources.models.commons.mysql_manager import Gera_query class Er...
StarcoderdataPython
6582382
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-07 11:33 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Creat...
StarcoderdataPython
4866004
<gh_stars>1-10 ''' This program plots the lengths of source input and target pairs. The intention is for one to use this to help determine bucket sizes. Maybe in the future I will implement a clustering algorithm to autonomously find bucket sizes ''' import os import matplotlib.mlab as mlab import matplotlib.pyplo...
StarcoderdataPython
3457897
<filename>supervisely/visualize/src/ui/input_data.py import os import supervisely_lib as sly import sly_globals as g from sly_visualize_progress import get_progress_cb, reset_progress, init_progress import cv2 import ffmpeg progress_index = 1 object_ann_info = None def init(data, state): data["projectId"] =...
StarcoderdataPython
8171343
<gh_stars>100-1000 """ Exploration policy for permutation invariant environments """ from ..base_classes import Policy import itertools import random import copy import numpy as np class LongerExplorationPolicy(Policy): """Simple alternative to :math:`\epsilon`-greedy that can explore more efficiently for a ...
StarcoderdataPython
11302286
import FWCore.ParameterSet.Config as cms from RecoParticleFlow.PFClusterProducer.particleFlowClusterECAL_cff import * particleFlowClusterOOTECAL = particleFlowClusterECAL.clone() particleFlowClusterOOTECAL.inputECAL = cms.InputTag("particleFlowClusterOOTECALUncorrected") from Configuration.Eras.Modifier_run2_miniAOD_...
StarcoderdataPython
8029071
<reponame>Shaikh-Nabeel/HackerRankAlgorithms """ You are given a list of N people who are attending ACM-ICPC World Finals. Each of them are either well versed in a topic or they are not. Find out the maximum number of topics a 2-person team can know. And also find out how many teams can know that maximum number of topi...
StarcoderdataPython
211015
import operator from functools import reduce from django.shortcuts import get_object_or_404, render from django.db.models import Q from django.urls import reverse from django.http import HttpResponseRedirect from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from .forms import RoomPostForm from .m...
StarcoderdataPython
6592327
<reponame>Cladett/rlman from dVRL_simulator.vrep.vrepObject import vrepObject import numpy as np from numpy.linalg import inv class camera(vrepObject): def __init__(self, clientID, rgb=True): super(camera, self).__init__(clientID) self.camera_handle = self.getHandle('Vision_Sensor') self.r...
StarcoderdataPython
190045
<reponame>Aditya-aot/ION from django import forms from django.forms import ModelForm from .models import stock_port , crypto_port class stock_port_form(ModelForm) : name = forms.CharField(label='',widget=forms.TextInput(attrs={"placholder":"write here"})) price = forms.CharField(label='',widget=forms.TextInput...
StarcoderdataPython
12846038
<gh_stars>0 import numpy as np from ..core.derivative import Derivative class AsianCallOption(Derivative): def __init__(self, S, K, T, r, sigma, steps, **kwargs): super().__init__(S_0=S, T=T, r=r, sigma=sigma, steps=steps, **kwargs) self.S = S self.K = K self.T = T ...
StarcoderdataPython
11360124
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2022- <NAME> # # Distributed under the terms of the MIT License # (see wavespin/__init__.py for details) # ----------------------------------------------------------------------------- import numpy as...
StarcoderdataPython
4890080
<reponame>simonbray/parsec from __future__ import absolute_import import os import sys import click import json from .io import error from .config import read_global_config, global_config_path, set_global_config_path # noqa, ditto from .galaxy import get_galaxy_instance, get_toolshed_instance from parsec import __ver...
StarcoderdataPython
4938101
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: fl_comm_libs/proto/co_proxy.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from...
StarcoderdataPython
8114886
from .is_pytraj_Topology import is_pytraj_Topology from .extract import extract from .add import add from .append_structures import append_structures from .get import * from .set import * from .to_molsysmt_Topology import to_molsysmt_Topology
StarcoderdataPython
6440477
from django.urls import path from . import views app_name = 'showcase' urlpatterns = [ path('', views.home, name='home'), ]
StarcoderdataPython
8040616
<reponame>pulumi/pulumi-azure-nextgen<filename>sdk/python/pulumi_azure_nextgen/cdn/route.py<gh_stars>10-100 # coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi...
StarcoderdataPython
5045257
import os from twisted.python import filepath from twisted.trial import unittest from .. import database from ..database import get_db, TARGET_VERSION, dump_db, DBError class Get(unittest.TestCase): def test_create_default(self): db_url = ":memory:" db = get_db(db_url) rows = db.execute("SE...
StarcoderdataPython
1795201
<reponame>custa/python-skeleton import requests url = 'https://api.github.com/users/octocat' try: r = requests.get(url) if 200 != r.status_code: print("{}".format(r.content)) except Exception as e: print("{}".format(e))
StarcoderdataPython
9684241
<reponame>mudam/python-erply-api import json data = json.dumps({'status': {'recordsTotal': 0, 'request': 'getSalesReport', 'generationTime': 0.13462495803833, 'recordsInResponse': 0, 'requestUnixTime': 1469040297, 'errorCode': 1016, 'errorField': 'dateStart', 'responseStatus': 'error'}, 'records': None})
StarcoderdataPython
8079499
class VeristandError(Exception): """ The base class for all VeriStandErrors. Note: This class generates a :class:`VeristandError` if a more specific error cannot be determined. """ pass class TranslateError(VeristandError): """Raised if a Python function fails to translate to a VeriStand r...
StarcoderdataPython
12859085
<filename>serializers_test/avro_avg.py import avro.schema import json import fastavro SCHEMA = { "namespace": "avg_obj", "type": "record", "name": "Meme", "fields": [ {"name": "user", "type": { "type": "record", "name": "PostUser", "fields": [ ...
StarcoderdataPython
11340172
<reponame>willynpi/django-tutorial-for-programmers<gh_stars>100-1000 import logging from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.http import Http404, HttpResponse, HttpResponseForbidden from django.shortcuts import redirect, render from django.views...
StarcoderdataPython
3300738
import errno import os import shutil __author__ = '<NAME>' __all__ = ['mkdir_p', 'remove_childreen'] def mkdir_p(path): ''' Recursively creates the directories in a given path Equivalent to batch cmd mkdir -p. Parameters ---------- path : str Path to the final directory to create. ...
StarcoderdataPython
9677849
<filename>sdk/python/pulumi_azure_nextgen/vmwarecloudsimple/v20190401/__init__.py # coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** # Export this package's modules as members: from .dedicated_cloud_nod...
StarcoderdataPython
5086171
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_script import Manager from flask_migrate import Migrate, MigrateCommand app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/flask1' # db = SQLAlchemy(app) from api import app, db migrate = Migrate(app, db) ma...
StarcoderdataPython
9734058
""" The :mod:`ramp_database.model` defines the database structure which is used for the RAMP events. """ from .base import * # noqa from .user import * # noqa from .fold import * # noqa from .team import * # noqa from .score import * # noqa from .event import * # noqa from .problem import * # noqa from .workflo...
StarcoderdataPython
3328063
<reponame>BatedUrGonnaDie/salty_bot #! /usr/bin/env python3.7 import modules.apis.api_base as api class NewbsAPI(api.API): def __init__(self, headers=None, cookies=None): super(NewbsAPI, self).__init__("https://leagueofnewbs.com/api", headers=headers, cookies=cookies) def add_textutil(self, channel...
StarcoderdataPython
8185341
""" Radial distribution function related describers """ from ._rdf import RadialDistributionFunction # noqa __all__ = ["RadialDistributionFunction"]
StarcoderdataPython
279483
<gh_stars>10-100 import numpy as np import torch import torch from functools import partial from dataset_specifications.dataset import Dataset class WmixSet(Dataset): def __init__(self, n_comp): super().__init__() self.n_samples = { "train": 50000, "val": 5000, ...
StarcoderdataPython
57270
import torch import torch.nn as nn from lightconvpoint.nn.deprecated.module import Module as LCPModule from lightconvpoint.nn.deprecated.convolutions import FKAConv from lightconvpoint.nn.deprecated.pooling import max_pool from lightconvpoint.spatial.deprecated import sampling_quantized, knn, upsample_nearest from ligh...
StarcoderdataPython
4926614
import uuid from typing import Dict, List, Union from superai.data_program.base import DataProgramBase # TODO: refactor api and add to client mixin class TaskInstance(DataProgramBase): def __init__( self, task_template_id: Union[int, float], quality=None, cost=None, latenc...
StarcoderdataPython
9775746
<gh_stars>0 import numpy as np import pandas as pd import statsmodels.api as sm # import class import heat.modeling # TODO create a dummy paraheat object from dummy data for testing purposes # rng = np.random.default_rng() # df = pd.DataFrame(rng.integers(0, 100, size=(100, 5)), columns=list('ABCDE')) # for now use ...
StarcoderdataPython
9618556
"""Выбор аэродромов для миссии В миссии у сторон по 3 фронтовых филда и по 4 тыловых. Фронтовые (по 3) выбираются по алгоритму: * Все аэродромы фильтруются по нахождению в прифронтовой зоне * Полученный список сортируется по общему количеству самолётов * Из списка берутся первый, последний и случайный аэродром Тыловы...
StarcoderdataPython
1713806
<gh_stars>1-10 # stdlib import yaml import os.path # local module from .factory_loader import FactoryLoader __all__ = ['loadyaml'] def loadyaml( path ): """ Load a YAML file at :path: that contains Table and View definitions. Returns a <dict> of item-name anditem-class definition. If you want to import t...
StarcoderdataPython
11266015
# -*- coding: utf-8 -*- from openprocurement.auctions.core.tests.base import snitch from openprocurement.auctions.core.tests.blanks.complaint_blanks import ( # AuctionComplaintResourceTest create_auction_complaint_invalid, create_auction_complaint, patch_auction_complaint, review_auction_complaint, ...
StarcoderdataPython
12859949
# # @lc app=leetcode id=206 lang=python3 # # [206] Reverse Linked List # # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: def iterative(head): ...
StarcoderdataPython
3444760
from django.db import models # Create your models here. class Disease(models.Model): code = models.CharField(max_length=4) name = models.CharField(max_length=120) description = models.TextField() medication = models.TextField(blank=True) source = models.CharField(max_length=120,default="Kementerian...
StarcoderdataPython
4844955
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'tanchao' import sys with open(sys.argv[1], 'r') as test_cases: for test in test_cases: test = test.strip() if test: # remove ending code '\n' and not empty string print 'todo'
StarcoderdataPython
4827398
<reponame>willhardy/Adjax # -*- coding: UTF-8 -*- from utils import get_key, JsonResponse, get_template_include_key, named_key from django.contrib import messages from django.core import urlresolvers from django.template.context import RequestContext from django.template.loader import render_to_string from pprint impo...
StarcoderdataPython
4807013
<reponame>Kitware/paraview-visualizer from paraview import simple def initialize(server): state, ctrl = server.state, server.controller @state.change("active_controls") def update_active_panel(active_controls, **kwargs): state.drawer_visibility = active_controls is not None @ctrl.add("on_act...
StarcoderdataPython
9787406
<reponame>FatiahBalo/python-ds """ Bubble Sort worst time complexity occurs when array is reverse sorted - O(n^2) Best time scenario is when array is already sorted - O(n) """ def bubble_sort(array): n = len(array) for i in range(n): for j in range(0, n-i-1): if array[j] > array[j+1]: ...
StarcoderdataPython
8087410
<filename>NASA SPACEAPPS CHALLENGE/Solution/Software part/Astronomical Data and Python Libraries/Astropy/astropy-1.1.2/astropy/utils/compat/fractions.py # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Handles backports of the standard library's `fractions.py`. The fractions module in 2.6 does not h...
StarcoderdataPython
12860137
from NERDA.models import NERDA from NERDA.datasets import get_conll_data, get_dane_data from transformers import AutoTokenizer trans = 'bert-base-multilingual-uncased' tokenizer = AutoTokenizer.from_pretrained(trans, do_lower_case = True) data = get_dane_data('train') sents = data.get('sentences') out = [] for sent ...
StarcoderdataPython
6601489
import numpy as np def multi_dot(*vectors): """ Pairwise vectors product. Args: vectors: tuple of numpy.array with len(shape) = 1 Returns: numpy.ndarray """ if len(vectors) == 1: return vectors[0] vec_dot = np.dot(np.expand_dims(vectors[0], -1), np.expand_dims(vectors[...
StarcoderdataPython
24320
"""Class implementation for the stop_propagation interface. """ from apysc._type.variable_name_interface import VariableNameInterface class StopPropagationInterface(VariableNameInterface): def stop_propagation(self) -> None: """ Stop event propagation. """ import apys...
StarcoderdataPython
1806853
<filename>nlpaug/augmenter/spectrogram/spectrogram_augmenter.py import numpy as np from nlpaug.util import Method from nlpaug import Augmenter class SpectrogramAugmenter(Augmenter): def __init__(self, action, name='Spectrogram_Aug', aug_min=1, aug_p=0.3, verbose=0): super(SpectrogramAugmenter, self).__in...
StarcoderdataPython
8194771
a asdgsdg asdg
StarcoderdataPython
1786725
import typer app = typer.Typer() @app.command() def hellow(name: str, d: int, state:bool = True): print(f"halo {name} {d}") if state==True: print(f"iq {d}") @app.command() def bye(): print("bye") if __name__ == "__main__": app()
StarcoderdataPython
1849981
<gh_stars>0 import speech_recognition as sr class AudioUtils: """ author: <NAME> This class will provide certain audio functionality, like: - doing speech to text """ @staticmethod def record_caption(): r = sr.Recognizer() with sr.Microphone() as source: ...
StarcoderdataPython
3579877
<reponame>turlodales/vimr import argparse import pathlib import shutil from builder import Builder from config import Config from deps import ag, pcre, xz from deps.ag import AgBuilder DEPS_FILE_NAME = ".deps" PACKAGE_NAME = "vimr-deps" def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() ...
StarcoderdataPython
341240
<gh_stars>1-10 # Copyright 2021 Huawei Technologies Co., Ltd # # 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 l...
StarcoderdataPython
1734060
#%% from functools import partial import jax import jax.numpy as np from jax import random, vmap, jit, grad from jax.experimental import stax, optimizers from jax.experimental.stax import Dense, Relu import matplotlib.pyplot as plt from tqdm.notebook import tqdm #%% # Use stax to set up network initialization and ...
StarcoderdataPython
3348491
import os import ctypes import multiprocessing import logging log = logging.getLogger(__name__) FILE_DIR = os.path.dirname(os.path.abspath(__file__)) SRC_PORT = 20130 DST_PORT = 20130 PACKET_RX_RING = 5 PACKET_TX_RING = 13 class Ring(ctypes.Structure): pass class BandwidthController(multiprocessing.Process): ...
StarcoderdataPython
3594738
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unit tests for update_perf_expectations.""" import copy from StringIO import StringIO import unittest import make_expectations as...
StarcoderdataPython
8158985
def add_destination(): distenationName = input("Название пункта назначения? ") number = input("Номер поезда? ") my_string = str(input('Время отправления(yyyy-mm-dd hh:mm): ')) departureTime = datetime.strptime(my_string, "%Y-%m-%d %H:%M") schedule = { 'distenationName': distenationNam...
StarcoderdataPython
12817611
<reponame>kiyoon/camera-tools #!/usr/bin/env python3 import argparse class Formatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter): pass parser = argparse.ArgumentParser( description='''Read EXIF data Author: <NAME> (<EMAIL>)''', formatter_class=Formatter) parser....
StarcoderdataPython
5154951
<reponame>fehija/MLb-LDLr<gh_stars>0 GCODE = { "GCT":"Ala", "GCC":"Ala", "GCA":"Ala", "GCG":"Ala", "CGT":"Arg", "CGC":"Arg", "CGA":"Arg", "CGG":"Arg", "AGA":"Arg", "AGG":"Arg", "AAT":"Asn", "AAC":"Asn", "GAT":"Asp", "GAC":"Asp", "TGT":"Cys", "TGC":"Cys", "CAA":"Gln", "CAG":"Gln", "GAA":"Glu", "GAG":...
StarcoderdataPython
12811092
<filename>imperative/python/megengine/utils/naming.py # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # ...
StarcoderdataPython
5164994
from opendr.planning.end_to_end_planning.e2e_planning_learner import EndToEndPlanningRLLearner from opendr.planning.end_to_end_planning.envs.agi_env import AgiEnv __all__ = ['EndToEndPlanningRLLearner', 'AgiEnv']
StarcoderdataPython
5024004
<filename>pneumo/utils/augmentations.py import torch from torchvision import transforms import torchvision.transforms.functional as TF from PIL import ImageOps, ImageEnhance, Image import random import math """ Transforamtions that we can apply on an image and the range of magnitude: Rotate Flip Mirror Equalize Sol...
StarcoderdataPython
3388405
<filename>src/plot_hourly_bar_graph.py import matplotlib.pyplot as plt import matplotlib.pylab as pylab from dateutil.parser import parse import datetime import csv import numpy import os import copy class CountReading: def __init__(self, timestamp, count): self.timestamp = timestamp self.count = ...
StarcoderdataPython
3520575
import os def deletenull(label_path): files = os.listdir(label_path) for file in files: if os.path.getsize(label_path + "/" + file) == 0: os.remove(label_path + "/" + file) if __name__ == '__main__': deletenull("Westlife/labels_with_ids")
StarcoderdataPython
1847666
import os import requests from tqdm import tqdm FILE_NAME = 'data.xml.bz2' FINAL_FILE_NAME = 'data.xml' def needs_to_download(): if os.path.exists(FILE_NAME) and os.path.getsize(FILE_NAME) > 0: return False if os.path.exists(FINAL_FILE_NAME) and os.path.getsize(FINAL_FILE_NAME) > 0: return...
StarcoderdataPython
6491532
from csv import reader, writer with open("fighters_new.csv", "w") as file: csv_writer = writer(file) csv_writer.writerow(["Character", "Move"]) csv_writer.writerow(["Ryu", "Hadouken"]) with open('fighters.csv') as file: csv_reader = reader(file) #fighters = [[s.upper() for s in row] for row in ...
StarcoderdataPython
222795
from server import db from server.model import BaseModel, PermissionBaseModel class Framework(db.Model, PermissionBaseModel, BaseModel): __tablename__ = "framework" id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(64), unique=True, nullable=False) url = db.Column(db.String(25...
StarcoderdataPython
4803552
<gh_stars>0 """ version which can be consumed from within the module """ VERSION_STR = "0.0.4" DESCRIPTION = "pymultienv is a command to help you deal with multiple python environments" APP_NAME = "pymultienv" LOGGER_NAME = "pymultienv"
StarcoderdataPython
6560191
<reponame>ferag/keystone<filename>keystone/trust/core.py # Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-...
StarcoderdataPython
11333506
<reponame>mmathys/bagua # TODO: @shjwudp merge with service module import copy import os import re import time from pssh.clients import ParallelSSHClient from pssh.exceptions import Timeout from .bayesian_optimizer import ( IntParam, BayesianOptimizer, ) def sysperf(host_list, nproc_per_node, ssh_port, env:...
StarcoderdataPython
8135035
#!/usr/bin/env python import os from urlparse import urlunparse # MySQL server configuration mysql_host = "localhost" mysql_user = "root" mysql_password = "<PASSWORD>" mysql_db = "yagra" # Length in bytes of the password for cookie random_password_length = 32 # The time in seconds password cookies expire random_p...
StarcoderdataPython
3207118
from tamtam import Bot, Dispatcher, run_poller from tamtam.types import Message, BotStarted from tamtam.dispatcher.filters import MessageFilters bot = Bot("put token") dp = Dispatcher(bot) @dp.bot_started() async def new_user(upd: BotStarted): await upd.respond(f"Hello! {upd.user.name}.\nNice to see you!") @d...
StarcoderdataPython
5010122
import numpy import matplotlib fig = plt.figure(figsize=(6,5)) left, bottom, width, height = 0.1, 0.1, 0.8, 0.8 ax = fig.add_axes([left, bottom, width, height]) start, stop, n_values = -2, 2, 800 x_vals = np.linspace(start, stop, n_values) y_vals = np.linspace(start, stop, n_values) X, Y = np.meshgrid(x_vals, y_val...
StarcoderdataPython
6646681
# Generated by Django 3.0.3 on 2020-04-21 10:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('quickbooks_online', '0002_cheque_chequelineitem_creditcardpurchase_creditcardpurchaselineitem_journalentry_journalentrylineite'), ] operations = [ ...
StarcoderdataPython
69238
<filename>api/users/migrations/0007_govuser_default_queue.py # Generated by Django 2.2.11 on 2020-04-29 15:24 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ("users", "0006_auto_20200424_1136"), ] operations = [ migrations.Ad...
StarcoderdataPython
5117329
from math import inf from hypothesis import assume, given from hypothesis.strategies import composite, integers, lists, permutations from algorithms.structures.tree.avl_tree import AVLTree from algorithms.structures.tree.binary_search_tree import BinarySearchTree from algorithms.structures.tree.red_black_tree import ...
StarcoderdataPython
12843438
<reponame>Tallisado/DbBot<gh_stars>1-10 from os.path import exists from sys import argv from dbbot import CommandLineOptions class WriterOptions(CommandLineOptions): @property def output_file_path(self): return self._options.output_file_path def _add_parser_options(self): super(WriterOp...
StarcoderdataPython
3267093
import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.lines import Line2D def customlegend(ax, labels: "List[String]", colors : "List of color names", ncol = 1, fontsize = 6, linewidth = 4, framealpha = 0, loc = "best", fontweight = "bold", columnspacing = 0, **kwar...
StarcoderdataPython
1684428
<gh_stars>1-10 # -*- coding: utf-8 -*- """Yo helpers package.""" import datetime import json import sys import grequests import requests from flask import current_app, g, request from mongoengine import DoesNotExist from requests.exceptions import RequestException, Timeout from .queries import (clear_get_favorite_yo...
StarcoderdataPython
3446495
<reponame>z727354123/pyCharmTest class Person: def __init__(self): self.items = [1, 2, 3, 4, 5, 6, 7, 8] def __setitem__(self, key, value): print("set", key, value) self.items[key] = value def __getitem__(self, key): print(key) return self.items[key] p = Person() ...
StarcoderdataPython
5104137
<reponame>konstdimasik/python_code # Напишите программу, которая считывает строку с числом nn, которое # задаёт количество чисел, которые нужно считать. Далее считывает n строк # с числами x_i, по одному числу в каждой строке. Итого будет n+1n+1 строк. # # При считывании числа x_i программа должна на отдельной строке в...
StarcoderdataPython
8164970
<gh_stars>0 import pytest from hello.world_world import hello_world def test_hello_world(): hello_world()
StarcoderdataPython
3285710
<reponame>Esequiel378/proxy-randomizer<filename>proxy_randomizer/utils.py """utils to consume from modules""" # built in modules import unicodedata # type hint from typing import Dict, List, Optional # third party modules import requests from bs4 import BeautifulSoup # local modules from proxy_randomizer.proxy impo...
StarcoderdataPython
6685307
<reponame>arthurMll/TAPI import connexion import six from tapi_server.models.inline_object24 import InlineObject24 # noqa: E501 from tapi_server.models.inline_object32 import InlineObject32 # noqa: E501 from tapi_server.models.tapi_common_bandwidth_profile import TapiCommonBandwidthProfile # noqa: E501 from tapi_se...
StarcoderdataPython
3441041
class Solution: def VerifySquenceOfBST(self, sequence): if sequence == []: return False length = len(sequence) root = sequence[-1] for i in range(length): if sequence[i] > root: break for j in range(i, length): if sequenc...
StarcoderdataPython