id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3222786
def showBits(n): l=[] for i in range (32): r=n%2 l.append(r) n //=2 l.reverse() return l
StarcoderdataPython
3356913
<reponame>ejuarez007/IncidentesVialesCDMX<filename>Classes.py import pandas as pd from dataclasses import dataclass from decorators import open_close_connection @dataclass class Datos(): path:str def read_data(self,sep=","): data = pd.read_csv(self.path, sep=sep) return data ...
StarcoderdataPython
3348230
<filename>pdf_manager/core/main.py import argparse import sys from typing import List from colorama import init from pdf_manager.budget import create_budget from pdf_manager.concat import concat_pdfs _LS = List[str] __all__ = ['main'] def _parse_args(args: _LS = None) -> argparse.Namespace: """ArgumentParser d...
StarcoderdataPython
1636037
import unittest from program.hr import ( payroll_system, get_policy, calculate_payroll, DisabilityPolicy, ) from program.employees import employee_database class TestHr(unittest.TestCase): employee_db = employee_database employee_list = employee_db.employees() system = payroll_system ...
StarcoderdataPython
86500
import unittest.mock as mock from urllib.parse import quote as param_encoder from django.urls import reverse from django.core.exceptions import ImproperlyConfigured from rest_framework import status from api.models import PublicDataset, Workspace, Resource from api.tests.base import BaseAPITestCase from api.tests impo...
StarcoderdataPython
33729
import os import subprocess class TestTasks: """ Test that the tasks work with invoke. """ CMD_KWARGS = dict( capture_output=True, encoding="utf-8", shell=True, env=os.environ.copy(), ) def test_unapproved_licenses(self): """ Should emit table of unapproved lic...
StarcoderdataPython
72205
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, ...
StarcoderdataPython
3283519
<gh_stars>0 # -*- coding: utf-8 -*- from __future__ import division import os import sys from setuptools import setup DIR = os.path.abspath(os.path.dirname(__file__)) sys.path.append(os.path.join(DIR, "extern", "pybind11")) from pybind11.setup_helpers import ParallelCompile, Pybind11Extension # noqa: E402 del sys...
StarcoderdataPython
3236444
<gh_stars>10-100 from pyamf.adapters import register_adapter def when_imported(mod): """ This function is called immediately after mymodule has been imported. It configures PyAMF to encode a list when an instance of mymodule.CustomClass is encountered. """ import pyamf pyamf.add_type(mod....
StarcoderdataPython
4843020
from django.core.management.base import BaseCommand from django.core.management import call_command from django.core.mail.message import EmailMessage from django.conf import settings from wildlifelicensing.apps.returns.models import Return import datetime from zipfile import ZipFile import os class Command(BaseComman...
StarcoderdataPython
44485
from flask import url_for from tests.conftest import normalize_spaces def test_set_inbound_sms_sets_a_number_for_service( logged_in_client, mock_add_sms_sender, multiple_available_inbound_numbers, service_one, fake_uuid, mock_no_inbound_number_for_service, mocker ): mocker.patch('app....
StarcoderdataPython
38903
#45-crie um programa que faça o computador jogar jokenpo com voce. print('=====JOKENPO=====') print('') from random import randint from time import sleep itens = ('pedra','papel','tesoura') computador = randint(0, 2) print('''FAÇA SUA ESCOLHA [ 0 ] pedra [ 1 ] papel [ 2 ] tesoura ''') jogador = int(input('Qual a sua j...
StarcoderdataPython
198984
from validation.types.type_validation import ( ValidationType, ValidationTypeError ) from uontypes.scalars.uon_uint import UonUint class UintTypeValidation(ValidationType): def validate_type(self, input_): if (not isinstance(input_, UonUint)): raise ValidationTypeError("The following inpu...
StarcoderdataPython
3288912
# Generated by Django 4.0 on 2022-03-20 13:41 import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.CreateModel( ...
StarcoderdataPython
126097
<gh_stars>0 # https://zulko.github.io/moviepy/examples/star_worms.html
StarcoderdataPython
1659207
<filename>Main.py import YellScraper scraper = YellScraper.Scraper() scraper.setKeyword('Restaurant') scraper.setLocation('Old+Street%2C+ec1v') scraper.start() print 'Done... Exiting'
StarcoderdataPython
3211518
<gh_stars>1-10 from http.server import BaseHTTPRequestHandler, HTTPServer from json import * port = 8081 class TestServer(BaseHTTPRequestHandler): def _set_headers(self): self.send_response(200) self.send_header('Content-type', 'text/json') self.end_headers() @staticmethod def is...
StarcoderdataPython
22116
"""Some debugging functions for working with the Scrapy engine""" # used in global tests code from time import time # noqa: F401 def get_engine_status(engine): """Return a report of the current engine status""" tests = [ "time()-engine.start_time", "engine.has_capacity()", "len(engin...
StarcoderdataPython
3225577
# -*- coding: utf-8 -*- """ Survey_traverseAdjustment.py *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU ...
StarcoderdataPython
135821
"""The Media Source implementation for the Jellyfin integration.""" from __future__ import annotations import logging import mimetypes from typing import Any import urllib.parse from jellyfin_apiclient_python.api import jellyfin_url from jellyfin_apiclient_python.client import JellyfinClient from homeassistant.compo...
StarcoderdataPython
182506
<gh_stars>0 import sys import math points = [] with open(sys.argv[1], 'r') as infile: for line in infile: line = line.strip().split(',') points.append(str(line[0]) + "," + str(line[1]) + "," + str(line[2])) with open(sys.argv[2], 'w') as outfile: with open(sys.argv[3], 'w') as edg...
StarcoderdataPython
3393766
from typing import Dict, List, Tuple import numpy as np import pandas as pd from tqdm import tqdm from data.dataset import train, test, books def baseline_model() -> Tuple[Dict[int, List], Dict[int, List]]: global train, test sol = test.groupby(["user_id"])["book_id"].agg({"unique"}).reset_index() gt = ...
StarcoderdataPython
1705776
<reponame>miladgharibi/PicoSchool<filename>account/views.py from django.contrib import ( auth, messages, ) from django.contrib.auth.decorators import login_required from django.contrib.auth.views import PasswordChangeView from django.shortcuts import ( render, redirect, ) from django.urls import reverse...
StarcoderdataPython
64414
<filename>learn2learn/_version.py __version__ = '0.0.5.1'
StarcoderdataPython
4822004
from django.conf.urls.defaults import * urlpatterns = patterns('aquaticore.databases.views', (r'^$', 'index'), (r'^(?P<database_id>\d+)/$', 'detail'), )
StarcoderdataPython
118449
<filename>pypospack/task/tasks_lammps/elastic_calculation.py import os from collections import OrderedDict import pypospack.potential as potential from pypospack.task.lammps import LammpsSimulationError, LammpsSimulation class LammpsElasticCalculation(LammpsSimulation): """ Class for LAMMPS elastic calculation ...
StarcoderdataPython
41122
<filename>udp-client.py<gh_stars>0 import socket, traceback host = '255.255.255.255' # Bind to all interfaces port = 2081 print "Creating socker on port: ", port s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #print "Setting REUSEADDR option" #s.setsockopt(socket.SOL_SOCKET, socke...
StarcoderdataPython
52765
import pytest import sys sys.path.append(".") sys.path.append("../.") from boxdetect import config from boxdetect import pipelines def test_save_load_config(capsys): cfg = config.PipelinesConfig() cfg.morph_kernels_thickness = 10 cfg.save_yaml('test_cfg.yaml') cfg2 = config.PipelinesConfig('test_cfg.y...
StarcoderdataPython
122037
import logging from configparser import ConfigParser from os import path, listdir LOGGER = logging.getLogger('gullveig') def priority_sort_files(k: str): first = 0 second = k if '-' not in k: return first, second parts = k.split('-', 2) # noinspection PyBroadException try: ...
StarcoderdataPython
1611384
#To input username&pass and check if it's correct. Q22 #Made by INS, Using dictionary for faster credential check. d={} while True: x=raw_input("Enter a user name : ") y=raw_input("Enter a password : ") d[x]=y cont=raw_input("Do you want to add more usernames? [y/n] ") if cont=='y': ...
StarcoderdataPython
1737889
import json import logging import pathlib import subprocess import sys from manubot.cite.citekey import ( citekey_to_csl_item, standardize_citekey, is_valid_citekey, ) from manubot.pandoc.util import get_pandoc_info from manubot.util import shlex_join # For manubot cite, infer --format from --output file...
StarcoderdataPython
1660155
combo_list = [] one_list = [4,5] combo_list.extend(one_list) combo_list #Output """ [4,5] """
StarcoderdataPython
190391
<filename>scripts/strelka-2.9.2.centos6_x86_64/lib/python/makeRunScript.py # # Strelka - Small Variant Caller # Copyright (c) 2009-2018 Illumina, Inc. # # This program 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 Found...
StarcoderdataPython
1752118
<reponame>lorddaedra/django-magiclink<gh_stars>0 from __future__ import annotations from django.urls import path from .views import LoginSentView, LoginVerifyView, LoginView, LogoutView, SignupView app_name = "magiclinks" urlpatterns = [ path('login/', LoginView.as_view(), name='login'), path('login/sent/',...
StarcoderdataPython
3245944
import os from pathlib import Path import pytest from s3fetch import __version__ from s3fetch.command import S3Fetch from s3fetch.exceptions import DirectoryDoesNotExistError, NoObjectsFoundError @pytest.fixture(scope="function") def aws_credentials(): """Mocked AWS Credentials for moto.""" os.environ["AWS_A...
StarcoderdataPython
109377
<filename>evennia/contrib/tutorials/batchprocessor/__init__.py """ Batch processing examples - Griatch 2012 """
StarcoderdataPython
3385438
# # This file is part of PyFOPPL, an implementation of a First Order Probabilistic Programming Language in Python. # # License: MIT (see LICENSE.txt) # # 21. Feb 2018, <NAME> # 20. Mar 2018, <NAME> # from ..fe_clojure import ppl_clojure_forms as clj from ..ppl_ast import * from .ppl_clojure_lexer import ClojureLexer fr...
StarcoderdataPython
3215420
<gh_stars>10-100 # Copyright (c) 2018 Ansible by Red Hat # All Rights Reserved. class _AwxTaskError(): def build_exception(self, task, message=None): if message is None: message = "Execution error running {}".format(task.log_format) e = Exception(message) e.task = task ...
StarcoderdataPython
1783397
from oauth2client.client import OAuth2WebServerFlow import httplib2 import json class Oauth2Client(object): """client for interacting with google oauth 2, as google openid connect is supported under oauth2""" def __init__(self, settings, logger, HTTP_PROXY=None): self.logger = logger self...
StarcoderdataPython
3218153
<reponame>ZwCreatePhoton/htmlmth import htmlmth.mods.http from . import TransformFunction, http_payload_to_tfarg_function def _generate_encode_chunked_equisize(*args, **kwargs): chunksize = kwargs.get("chunksize", 256) assert(chunksize > 0) return TransformFunction("", "ch...
StarcoderdataPython
77953
<reponame>Furzoom/learnpython<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- # type(a) == type(b) - whether value of type(a) is equivalent to value of type(b) # type(a) is type(b) - whether type(a) and type(b) have same type
StarcoderdataPython
3252066
<reponame>nexus-lab/relf-server #!/usr/bin/env python """Benchmark tests for the Cloud Bigtable data store.""" from grr.lib import flags from grr.server import data_store_test from grr.server.data_stores import cloud_bigtable_data_store_test from grr.test_lib import test_lib class CloudBigtableDataStoreBenchmarks( ...
StarcoderdataPython
3272253
<filename>Netflix/em.py """Mixture model for matrix completion""" from typing import Tuple import numpy as np from scipy.special import logsumexp from common import GaussianMixture def log_gaussian(x: np.ndarray, mean: np.ndarray, var: float) -> float: """Computes the log probablity of vector x under a normal dist...
StarcoderdataPython
8185
<gh_stars>0 def calc_fitness(pop): from to_decimal import to_decimal from math import sin, sqrt for index, elem in enumerate(pop): # só atribui a fitness a cromossomos que ainda não possuem fitness # print(elem[0], elem[1]) x = to_decimal(elem[0]) y = to_decimal(elem[1]) ...
StarcoderdataPython
3271634
<reponame>WillemRvX/ethelease #!/usr/bin/env python import os from time import sleep from ethelease.commons.utils import ENV, LOGGER from ethelease.cronos.utils import eval_cron from ethelease.k8s.ops import pod_launch_n_mgmt, K8sPodConf from ethelease.workflow.commons.utils import Valuables, scheds, scheduler FAMIL...
StarcoderdataPython
1705281
<gh_stars>1-10 import unittest import os import sys lib_path = os.path.abspath('../') sys.path.append(lib_path) try: from Comodo.TV import * # @UnusedWildImport except ImportError, erro: from trunk.Comodo.TV import * # @UnusedWildImport class TesteTV(unittest.TestCase): def setUp(self): self.tv1...
StarcoderdataPython
1684744
# SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD # SPDX-License-Identifier: CC0-1.0 import pytest from pytest_embedded import Dut def deepsleep_test(dut: Dut, case_name: str) -> None: dut.expect_exact('Press ENTER to see the list of tests') dut.write(case_name) reset_reason = 'DEEP...
StarcoderdataPython
3375359
<gh_stars>0 import logging import numpy as np from demotivational_policy_descent.agents.agent_interface import AgentInterface class Dummy(AgentInterface): def __init__(self, env, player_id=1): super().__init__(env=env, player_id=player_id) self.reset() # Call reset here to avoid code duplicatio...
StarcoderdataPython
1739302
import io from twisted.internet import reactor from ygo.card import Card from ygo.duel_reader import DuelReader from ygo.parsers.duel_parser import DuelParser from ygo.utils import process_duel def msg_select_option(self, data): data = io.BytesIO(data[1:]) player = self.read_u8(data) size = self.read_u8(...
StarcoderdataPython
127692
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitR04c_CompleteLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitR04c_CompleteLHS """ # Flag this instance as compiled now self.is_compiled = True sup...
StarcoderdataPython
3257317
""" Decorators to extend workflow functions """ from functools import wraps from .util import find_on_path from .provenance import BINARY_PROVENANCE as bin_provenance_registry class requires(object): """Convenience wrapper for tracking binaries used to perform tasks """ def __init__(self, binaries=list(...
StarcoderdataPython
1602866
# # Copyright (c) 2020, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
StarcoderdataPython
1707795
""" SGA.html ======== Code to generate HTML output for the various stages of the SGA analysis. """ import os import numpy as np def get_layer(onegal): if onegal['DR'] == 'dr6': layer = 'mzls+bass-dr6' elif onegal['DR'] == 'dr7': layer = 'decals-dr5' else: print('Unrecognized data ...
StarcoderdataPython
4823099
<reponame>BattleCisco/AAshe import traceback import aiohttp import sqlite3 import asyncio regions = [ "BR1", "EUN1", "EUW1", "JP1", "KR", "LA1", "LA2", "NA1", "OC1", "TR1", "RU", "PBE1"] class Config: api_key = None calls = 0 sql_cache = True conn = None def __init__(self): pass @classmetho...
StarcoderdataPython
1750889
<gh_stars>10-100 #!/usr/bin/env python """ Unit tests for M2Crypto.BN. Copyright (c) 2005 Open Source Applications Foundation. All rights reserved. """ import re import warnings from M2Crypto import BN, Rand from tests import unittest loops = 16 class BNTestCase(unittest.TestCase): def test_rand(self): ...
StarcoderdataPython
3267748
<filename>model/models/feat.py import torch import torch.nn as nn import numpy as np import torch.nn.functional as F from model.models import FewShotModel def conv3x3(in_channels, out_channels, stride=1): return nn.Conv1d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bi...
StarcoderdataPython
3321366
# -*- coding: utf-8 -*- # Copyright (c) 2016 - 2018 Ericsson AB # # 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 appl...
StarcoderdataPython
189081
from test.unit.extraction.gaussian_parser_test import * from test.unit.extraction.extraction_test import * from test.unit.glassware_test import * from test.unit.datawork_test import * from test.unit.writer_test import * from test.unit.tesliper_test import * if __name__ == '__main__': unittest.main()
StarcoderdataPython
184026
<gh_stars>0 import numpy as np import pandas as pd def extract_table(input_file, cancer_type): Cancer_type = cancer_type data = pd.read_csv(input_file) columns = data.columns selected_col = ['Mutation type', 'Trinucleotide'] for c in columns: if Cancer_type in c: selected_col.a...
StarcoderdataPython
168255
<gh_stars>1-10 class Player(object): INIT_STATE = 0x00 ENTERED_STATE = 0x01 READY_STATE = 0x02 def __init__(self): #0 1 logined 2 entered self.state = self.INIT_STATE #hex self.peerid = -1 self.character = None self.qobject = None self.active = False self.aoilist = [] self.sendmsgs = []
StarcoderdataPython
1686373
# coding=utf-8 # Module magneto_bold_16 # generated from Magneto 11.25pt name = "<NAME>" start_char = '!' end_char = chr(127) char_height = 16 space_width = 8 gap_width = 2 bitmaps = ( # @0 '!' (6 pixels wide) 0x00, # 0x1C, # OOO 0x38, # OOO 0x38, # OOO 0x30, # O...
StarcoderdataPython
1757564
<filename>amfeti/preconditioners/k_preconditioners.py<gh_stars>10-100 # # Copyright (c) 2020 TECHNICAL UNIVERSITY OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS, # BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, <EMAIL>. # # Distributed under 3-Clause BSD license. See LICENSE file for ...
StarcoderdataPython
134397
<filename>scihub2pdf/libgen.py from __future__ import unicode_literals, print_function, absolute_import import logging import requests from lxml import html from lxml.etree import ParserError from tool import norm_url, download_pdf logger = logging.getLogger("scihub") class LibGen(object): def __init__(self, ...
StarcoderdataPython
1760217
## Generate the dataset, save the data and a plot of it as well import numpy as np import skfuzzy as fuzz import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from skfuzzy import control as ctrl import scipy.io # Set for reproducibility np.random.seed(seed=123) loc_risk =...
StarcoderdataPython
188802
<filename>pdf_merge.py # pdf_merging.py import os from PyPDF2 import PdfFileReader, PdfFileWriter def merge_pdfs(dir_path, output): pdf_writer = PdfFileWriter() paths = os.listdir(dir_path) #print("Looking in",paths,"for PDFs") #checks if existing merged.pdf exists, if so deletes it if os....
StarcoderdataPython
1609530
<reponame>angelaaaateng/awesome-panel """This module implements the Page Model""" import param # from awesome_panel.application.models.author import Author from package.awesome_panel.application.models.author import Author from package.awesome_panel.utils import OrderByNameMixin class Page(OrderByNameMixin, pa...
StarcoderdataPython
3396585
<reponame>ChuanleiGuo/AlgorithmsPlayground class Solution(object): def topKFrequent(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ buckets = [[] for _ in range(len(nums) + 1)] frequency_dict = {} for num in nums: ...
StarcoderdataPython
27900
#!/usr/bin/python3 import numpy as np def meeting_planes(a1, b1, c1, a2, b2, c2, a3, b3, c3): return [] def main(): a1=1 b1=4 c1=5 a2=3 b2=2 c2=1 a3=2 b3=4 c3=1 x, y, z = meeting_planes(a1, b1, c1, a2, b2, c2, a3, b3, c3) print(f"Planes meet at x={x}, y={y} and z={z}"...
StarcoderdataPython
4807481
<gh_stars>0 import os import os.path import subprocess import yaml from crontab import CronTab import wakeup.config as config import wakeup.util as util from wakeup.schedule import Schedule, parse_schedule from wakeup.constants import CONFIG_FILE_NAME, ALARM_SCRIPT_NAME def schedule(args): alarm_schedule = pars...
StarcoderdataPython
3380810
#!/usr/bin/env python3 try: from pip.req import parse_requirements # pip 9.x except ImportError: from pip._internal.req import parse_requirements # pip 10.x from setuptools import find_packages, setup from app.util import autoversioning version = autoversioning.get_version() # bdist_pex runs in a temp dir...
StarcoderdataPython
1675893
from django.shortcuts import render from rest_framework import viewsets, filters import django_filters from . import models from . import serializers class TeamViewSet(viewsets.ModelViewSet): queryset = models.Team.objects.all() serializer_class = serializers.TeamSerializer filter_backends = (filters.Dj...
StarcoderdataPython
9355
<filename>code/send.py import sys import time from datetime import datetime from bot import FbMessengerBot if __name__ == "__main__": if len(sys.argv) < 3: print("No email or password provided") else: bot = FbMessengerBot(sys.argv[1], sys.argv[2]) with open("users.txt", "r") as file: ...
StarcoderdataPython
133882
# coding: utf-8 """Test the /files/ handler.""" import io import os from unicodedata import normalize pjoin = os.path.join import requests import json from nbformat import write from nbformat.v4 import (new_notebook, new_markdown_cell, new_code_cell, new_o...
StarcoderdataPython
3278997
<gh_stars>0 #!\usr\bin\python """ File: unstable_ODE.py Copyright (c) 2016 <NAME> License: MIT Excercise C.4: Implements the derivative of an unstable function u_k to test how well the Euler method approximates it given different initial conditions for alpha, and delta t """ import numpy as np import sympy as sp i...
StarcoderdataPython
3375445
import torch.nn.functional as F import torch.nn as nn import torch """ 这个是把PICK对应论文中的GraphModel中的Graph Learning的代码, 看起来忒费劲,我就笨方法,一行行肢解后,打印出来看、理解: 我理解就是 - 降维 - 做softmax算每个节点和彼此之间的关系权重 - 然后计算loss: ''' \mathcal{L}_{GL}=\frac{1}{N}\sum_{i,j=1}^N exp(A_{ij}+\eta \Vert v_i...
StarcoderdataPython
42621
<filename>main.py import wikipedia import webbrowser def getPage(): # 1 means number of random articles random_article = wikipedia.random(1) # print to the user the choice of random article print("The random generated wikipedia article is " + random_article) # User input to view the page or not choice = ...
StarcoderdataPython
3289035
<reponame>Ida-Ida/hecktor-2020 import torch from torch import nn from torch.nn import functional as F class BasicConv3d(nn.Module): def __init__(self, in_channels, out_channels, **kwargs): super(BasicConv3d, self).__init__() self.conv = nn.Conv3d(in_channels, out_channels, bias=False, **kwargs) ...
StarcoderdataPython
1679652
''' Created on Dec, 2016 @author: hugo ''' from __future__ import absolute_import import os import re from random import shuffle import numpy as np from collections import Counter, defaultdict from ..preprocessing.preprocessing import build_vocab, generate_bow, count_words from ..utils.io_utils import dump_json cl...
StarcoderdataPython
3281630
from game import i2c import gevent from gevent.wsgi import WSGIServer from threading import Thread from game.game import Game go = Game("piet","pol","normal","subtile") gameRunning = False import webBack import MySQLdb import time def startServer(): server = WSGIServer(("", 5000), webBack.app) server.serve_forever...
StarcoderdataPython
3377083
from django.urls import path from . import views urlpatterns = [ path('signup/', views.signup), path('check_duplication/', views.check_duplication), path('delete/', views.delete), ]
StarcoderdataPython
1723408
#!/usr/bin/env python3 #-m pip3 install pypdf2 import os from PyPDF2 import PdfFileWriter, PdfFileReader import argparse def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--in', type=str, nargs='+', dest='pdfs_to_merge', required=True, help='List of pdf fragments to merge') parser...
StarcoderdataPython
3203785
<gh_stars>0 ## @defgroup Methods-Weights-Correlations-Propulsion Propulsion # Contains some methods for calculating different propulsion system weights # @ingroup Methods-Weights-Correlations from .air_cooled_motor import air_cooled_motor from .engine_jet import engine...
StarcoderdataPython
1648333
<filename>Python/ILoveYou.py # Language: Python # Level: 8kyu # Name of Problem: I love you, a little , a lot, passionately ... not at all # Instructions: Who remembers back to their time in the schoolyard, when girls would take a flower and tear its petals, saying each of the following phrases each time a petal was t...
StarcoderdataPython
3387983
import math def funcion_factorial(n: int ): """El factorial de un numero. Parameters ---------- n : int Numero entero `n`. Returns ------- int Retorna el factorial del numero `n` """ facto= 1 for i in range(1,n+1): facto = facto * i return fact...
StarcoderdataPython
3358510
<filename>reader.py<gh_stars>0 #Based on script by <NAME> @alexram1313 #https://github.com/alexram1313/text-to-speech-sample import simpleaudio as sa import re import _thread import time from pydub import AudioSegment from pydub.playback import play class TextToSpeech: CHUNK = 1024 #apparently you can bot...
StarcoderdataPython
105432
"""This module implements uploading videos on YouTube via Selenium using metadata JSON file to extract its title, description etc.""" from typing import DefaultDict, Optional from selenium_firefox.firefox import Firefox, By, Keys from collections import defaultdict import json import time from youtube_uploader_sel...
StarcoderdataPython
1662258
# V0 # V1 # https://blog.csdn.net/fuxuemingzhu/article/details/82820204 # IDEA : GREEDY class MyCalendarTwo(object): def __init__(self): # every booked interval self.booked = list() # every overlap interval self.overlaped = list() def book(self, start, end): """ ...
StarcoderdataPython
126991
from __future__ import annotations from dataclasses import dataclass from typing import Sequence, Tuple, Optional, List, Dict, Any, Iterable import logging from pathlib import Path import os from concurrent.futures import ThreadPoolExecutor from requests import HTTPError from catpy.applications import CatmaidClientApp...
StarcoderdataPython
167107
""" Author: michealowen Last edited: 2019.11.1,Friday LASSO回归算法,使用波士顿房价数据集 在损失函数中加入L1正则项,后验概率的符合拉普拉斯分布 """ #encoding=UTF-8 import numpy as np import pandas as pd from sklearn import datasets from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split class ridgeRegression: ''' ...
StarcoderdataPython
1681828
<reponame>kozhevnikov-peter/curve-dao-contracts import brownie WEEK = 86400 * 7 YEAR = 365 * 86400 ZERO_ADDRESS = "0x0000000000000000000000000000000000000000" def test_burn(accounts, token): balance = token.balanceOf(accounts[0]) initial_supply = token.totalSupply() token.burn(31337, {'from': accounts[0]...
StarcoderdataPython
1716067
<gh_stars>1-10 #! python3 """ Generate JSON configuration files for the Tethys simulation code. This script generates experimental settings with a constant p and m, as well as a fixed number of iterations. Other parameters, such as the generation method of the list (more precisely the lists' length), the initial orien...
StarcoderdataPython
155605
<reponame>Vinson-sheep/DRL-Algorithms-with-Pytorch-for-Beginners-<filename>Char10 TD3/TD3.py import os import numpy as np import copy import gym import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from tensorboardX import SummaryWriter from buffer import ReplayBuffer ''' Twin...
StarcoderdataPython
4813534
<reponame>yehuohan/ln-ss<filename>test/fourier-FT-test.py #!/usr/bin/env python3 import sys,os sys.path.append(os.getcwd() + '/../') import lnss.fourier as fourier import numpy as np import scipy as sp import sympy as sy from sympy import Piecewise, integrate, fourier_series, symbols, DiracDelta from sympy import Sum...
StarcoderdataPython
3337566
from urllib import parse from ..utils.collections import flatten from ..exceptions import RouteNotFoundException, MethodNotAllowedException class Router: http_methods = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"] def __init__(self, *routes, module_location=None): self.routes = flatt...
StarcoderdataPython
3271028
<gh_stars>0 """ 给出二叉 搜索 树的根节点, 该树的节点值各不相同, 请你将其转换为累加树(Greater Sum Tree) 使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。 提醒一下,二叉搜索树满足下列约束条件: 节点的左子树仅包含键 小于 节点键的节点。 节点的右子树仅包含键 大于 节点键的节点。 左右子树也必须是二叉搜索树。 """ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left ...
StarcoderdataPython
3212107
<filename>Db_connection.py import sqlite3 from datetime import datetime as datetime #this file contains methods for inserting sensor data into an sqlite database, import this to another file to use the functions. #running this file wil create the database and table for storing the sensordata conn=sqlite3.connec...
StarcoderdataPython
3286980
<reponame>RideGreg/LeetCode # Time: O(n) # Space: O(h) # 951 # For a binary tree T, we define a flip operation as follows: choose any node, swap the left and right child subtrees. # # A binary tree X is flip equivalent to a binary tree Y iff we can make X equal to Y after some number of flip operations. # # Write a f...
StarcoderdataPython
1668802
<reponame>xram64/AdventOfCode2021<filename>day03/day03.py<gh_stars>1-10 ## Advent of Code 2021: Day 3 ## https://adventofcode.com/2021/day/3 ## <NAME> | github.com/xram64 ## Answers: [Part 1]: 3633500, [Part 2]: 4550283 import sys # Return most commonly-found bit, breaking ties in favor of '1' def get_most_common_bit...
StarcoderdataPython
4825723
#!/usr/bin/python3 # -*- coding: utf-8 -*- import sys import os from lxml import html from lxml import etree from lxml.html.clean import Cleaner def usage(): str = """ Usage: Importe les fichiers depuis une archive IMS de Moodle de Lille3... Nettoie le HTML en enlevant les attributs de style Réécrit les...
StarcoderdataPython
3269749
<filename>example8_dict.py # -*- coding: utf-8 -*- # An empty dict a = {} # Result: None print a.get("abc") # Add a value to the dict a["abc"] = 5 # Result: 5 print a.get("abc") # Add another value a[16] = "A text" # Result: A text print a.get(16) # The whole dict {16: 'A text', 'abc': 5} print a # You can add ...
StarcoderdataPython