id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
157955
import time from unittest import TestCase from fsmodels.models import Field, ValidationError def generic_validator(x): return x == 1, {'detail': 'x must be 1.'} class TestField(TestCase): def test___init__(self): # no required fields f = Field() with self.assertRaises((Validation...
StarcoderdataPython
1712136
<reponame>JayMonari/py-personal def square_of_sum(number: int) -> int: return sum([n for n in range(1, number + 1)]) ** 2 def sum_of_squares(number: int) -> int: return sum([n**2 for n in range(1, number + 1)]) def difference_of_squares(number): return square_of_sum(number) - sum_of_squares(number)
StarcoderdataPython
75414
<reponame>mattn/vint<gh_stars>1-10 import re from vint.ast.node_type import NodeType from vint.linting.level import Level from vint.linting.policy.abstract_policy import AbstractPolicy from vint.linting.policy_loader import register_policy from vint.linting.policy.autocmd_event import AutoCmdEvents @register_policy c...
StarcoderdataPython
3368443
<filename>baseCoverter.py<gh_stars>0 import random def convertQues(rng): # num = random.randint(0, rng) num = rng modes = ["hex", "bin"] mode = random.choice(modes) wrongAnswer = True if mode == "hex": while wrongAnswer: inp = input(f"What is hex {hex(num)[2:]} in decimal:...
StarcoderdataPython
78801
<reponame>jetannenbaum/micropython_ir # sony.py Encoder for IR remote control using synchronous code # Sony SIRC protocol. # Author: <NAME> # Copyright <NAME> 2020 Released under the MIT license from micropython import const from ir_tx import IR class SONY_ABC(IR): def __init__(self, pin, bits, freq, verbose): ...
StarcoderdataPython
3379885
from typing import List, Tuple import numpy as np from pyrep.objects.shape import Shape from pyrep.objects.joint import Joint from pyrep.objects.object import Object from rlbench.backend.task import Task from rlbench.backend.conditions import JointCondition class OpenDoor(Task): def init_task(self) -> None: ...
StarcoderdataPython
154887
<reponame>saurabsa/azure-cli-old # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -----------------------------------...
StarcoderdataPython
192541
<filename>beagle/header/mpu_accel_fsr_t.py<gh_stars>0 ACCEL_FSR_2G = 0 ACCEL_FSR_4G = 1 ACCEL_FSR_8G = 2 ACCEL_FSR_16G = 3
StarcoderdataPython
3272806
<filename>python/testData/completion/tupleParameterNamesNotSuggested.py def func((foo, bar), baz): pass func(b<caret>)
StarcoderdataPython
3267946
<reponame>TejasAvinashShetty/krotov<gh_stars>0 r"""Routines for `check_convergence` in :func:`krotov.optimize.optimize_pulses` A `check_convergence` function may be used to determine whether an optimization is converged, and thus can be stopped before the maximum number of iterations (`iter_stop`) is reached. A functi...
StarcoderdataPython
1614332
import time from typing import Any, List, Union from urllib.parse import urlparse import pymemcache from freiner.errors import FreinerConfigurationError from freiner.types import Host MemcachedClient = Union[pymemcache.Client, pymemcache.PooledClient, pymemcache.HashClient] class MemcachedStorage: """ Rat...
StarcoderdataPython
3366115
""" ID: fufa0001 LANG: PYTHON3 TASK: ride """ import string fin = open ('ride.in', 'r') fout = open ('ride.out', 'w') ufo,group = fin.read().splitlines() ufo = ufo.strip() group = group.strip() ufo_num = 1 for char in ufo: #print(f"{char}: {string.ascii_uppercase.index(char)}") ufo_num *= string.ascii_uppercase...
StarcoderdataPython
3203174
<filename>caiotte/items.py # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class ScholarItem(scrapy.Item): username = scrapy.Field() name = scrapy.Field() email = scrapy.Fi...
StarcoderdataPython
130956
from typing import Union, Tuple from duration import Duration class Transition: # Initialization and instance variables def __init__(self, source: str, destination: str, sgate: str = None, dgate: str = None, distribution: Union[dict, int] = 0) -> None: self.source = source self.source_gate = s...
StarcoderdataPython
39256
<gh_stars>100-1000 import math import numpy as np from keras import backend as K from keras.layers import Conv2D, Concatenate, Activation, Add from keras.engine import InputSpec def logsoftmax(x): ''' Numerically stable log(softmax(x)) ''' m = K.max(x, axis=-1, keepdims=True) return x - m - K.log(K.sum(...
StarcoderdataPython
3362673
<reponame>ramyasaimullapudi/WolfTrackPlus class User: """ This class is a controller for the user database. It inherits properties from flask_restful.Resource """ def get(self, email, password): """ gets defails of the specific user :param email: email of the user :param...
StarcoderdataPython
3358352
<reponame>dmoiseenko/kon-config<gh_stars>0 import yaml def create_yaml_file_by_dictionary(file_path, dictionary): with open(file_path, "w") as outfile: yaml.dump(dictionary, outfile, default_flow_style=False) def read_yaml_file_to_dictionary(file_path): with open(file_path) as file: y = yaml...
StarcoderdataPython
19498
<gh_stars>1-10 from datetime import datetime from kivy.app import App from kivy.factory import Factory from kivy.lang import Builder from kivy.clock import Clock from kivy.uix.button import Button from electrum.gui.kivy.i18n import _ from electrum.bitcoin import Token from electrum.util import parse_token_URI, Inval...
StarcoderdataPython
109523
<reponame>monkeyman79/dfsimage """This module contains MMBEntry class.""" from typing import Protocol, IO, Union from .consts import MMB_INDEX_ENTRY_SIZE from .consts import MMB_STATUS_OFFSET, MMB_STATUS_LOCKED, MMB_STATUS_UNLOCKED from .consts import MMB_STATUS_UNINITIALIZED, MMB_STATUS_UNINITIALIZED_MASK from .enu...
StarcoderdataPython
152872
<gh_stars>0 from .hk_print import HKPrint, HKPrintTheme print = HKPrint()
StarcoderdataPython
1674608
import gym import tensorflow as tf import spinup import numpy as np #making environment lambda function env = lambda : gym.make("quadrotor_14d_env:DiffDriveEnv-v0") #vpg # spinup.vpg( # env, # ac_kwargs={"hidden_sizes":(64,2)}, # seed = np.random.randint(100), # steps_per_epoch=1250, # epochs=2500...
StarcoderdataPython
1765207
<filename>test/test_warn_messages.py #! /usr/bin/python #-*- coding: utf-8 -*- from __future__ import print_function import sys import os import re import argparse import datetime import pybern.products.bernbpe as bpe stop = datetime.datetime.now(tz=datetime.timezone.utc) start = stop - datetime.timedelta(days=5) cam...
StarcoderdataPython
1715704
<reponame>divyquartic/QuarticSDK<filename>tests/features/tag_list_data_flow/__init__.py import pandas as pd import pytest from unittest import mock from aloe import step, world from quartic_sdk import APIClient from quartic_sdk.core.entities import Tag, Asset from quartic_sdk.core.entity_helpers.entity_list import En...
StarcoderdataPython
176711
from sub_capture_tool import SubCaptureTool import numpy import cv2 import time time.sleep(3) sct = SubCaptureTool() j = 0 for i in range(60): time.sleep(1) for seg in sct.capture(): gray = cv2.cvtColor(seg, cv2.COLOR_RGB2GRAY) gray, img_bin = cv2.threshold(gray,128,255, cv2.THRESH_BINARY | cv2...
StarcoderdataPython
1612141
from argon2 import PasswordHasher from argon2.exceptions import VerifyMismatchError def encrypt_password(password): return PasswordHasher().hash(password) def verify_password(password, hash): try: return PasswordHasher().verify(hash, password) except VerifyMismatchError: return False
StarcoderdataPython
4815817
import os from models.Player import Player def get_players(data): players = [] for playerxml in data.iter('player'): player = Player(playerxml.attrib) players.append(player) return players
StarcoderdataPython
1741985
import django from django.contrib.contenttypes.models import ContentType from fluent_contents.models import ContentItem from fluent_contents.tests.utils import AppTestCase class ModelTests(AppTestCase): """ Testing the data model. """ def test_stale_model_str(self): """ No matter wha...
StarcoderdataPython
3362776
<filename>python/packages/pybind_nisar/workflows/runconfig.py<gh_stars>10-100 ''' base class for processing and validating args ''' import os import journal from ruamel.yaml import YAML import yamale import numpy as np import pybind_isce3 as isce from pybind_nisar.products.readers import SLC from pybind_nisar.workfl...
StarcoderdataPython
1600681
<gh_stars>0 """ MIT License Copyright (c) 2021-present VincentRPS Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify...
StarcoderdataPython
177376
<gh_stars>0 import locale import os from enum import Enum from typing import List, Tuple from qtpy.QtCore import QEvent, Qt from qtpy.QtGui import QKeyEvent, QResizeEvent from qtpy.QtWidgets import ( QApplication, QBoxLayout, QCheckBox, QComboBox, QHBoxLayout, QLabel, QMessageBox, QPush...
StarcoderdataPython
27347
<gh_stars>1-10 # -*- coding: utf-8 -*- """ CSV related help functions """ from __future__ import unicode_literals oldstr = str from builtins import str import csv import io import six from catatom2osm.config import eol, encoding, delimiter def dict2csv(csv_path, a_dict, sort=None): """ Writes a dictionary to...
StarcoderdataPython
503
<filename>tests/bugs/core_6266_test.py #coding:utf-8 # # id: bugs.core_6266 # title: Deleting records from MON$ATTACHMENTS using ORDER BY clause doesn't close the corresponding attachments # decription: # Old title: Don't close attach while deleting record from MON$ATTACHMENTS usin...
StarcoderdataPython
3255294
<filename>main.py import sys import kspdatareader TEST_FILE = 'persistent.sfs' def main(): with open(TEST_FILE) as infile: reader = kspdatareader.KSPDataReader() reader.process_lines(infile.readlines()) if __name__ == '__main__': sys.exit(main())
StarcoderdataPython
1673420
<gh_stars>10-100 #import sys # sys.path.insert(0, '/content/gdrive/MyDrive/Tese/code') # for colab from src.classification_scripts.SupConLoss.train_supcon import FineTuneSupCon from src.classification_scripts.ALS.train_ALSingle import FineTuneALS from src.classification_scripts.cross_entropy.train_ce import FineTuneC...
StarcoderdataPython
1685030
<filename>src/dwell/climate/__init__.py from .gridding import *
StarcoderdataPython
1761559
<filename>tryalgo/knuth_morris_pratt.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- # Find a substring by Knuth-Morris-Pratt # <NAME> et <NAME> - 2014-2018 # inspired by a code from <NAME> # snip{ def knuth_morris_pratt(s, t): """Find a substring by Knuth-Morris-Pratt :param s: the haystack string :pa...
StarcoderdataPython
24720
import logging logging.basicConfig(level=logging.INFO) from flask import Flask from application.config import Config app = Flask(__name__) app.config.from_object(Config) from application.models.classifiers.CNNClassifier import CNNClassifier from application.models.classifiers.MLPClassifier import MLPClassifier fro...
StarcoderdataPython
1668327
from reducer import Reducer from bounder import Bounder from normalizer import Normalizer from gridifier import Gridifier from pB_approximator import pB_Approximator from trimmer import Trimmer from balancer import Balancer from squeezer import Squeezer from corrector import Corrector import numpy as np import tensor...
StarcoderdataPython
1703274
from . import tools from .capacity import Capacity from .dataset import Dataset from .datasource import Datasource from .report import Report from .tenant import Tenant from .token import Token from .workspace import Workspace
StarcoderdataPython
3360225
import torch, sys, os, pdb import numpy as np from PIL import Image from scipy.spatial import Delaunay sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) from .aligned_reid_utils import load_state_dict from models.yolo_models import Darknet from .featurepointnet_model_util import ...
StarcoderdataPython
1751646
<reponame>ian-r-rose/visualization<filename>docker/src/clawpack-5.3.1/riemann/src/__init__.py<gh_stars>10-100 #!/usr/bin/env python # encoding: utf-8 """ Wave propagation Riemann solvers implemented in Python and Fortran. """ rp_solver_list_1d = [] rp_solver_list_2d = [] rp_solver_list_3d = [] # Import 1d Riemann sol...
StarcoderdataPython
132091
import xmlrpc.client s = xmlrpc.client.ServerProxy('http://localhost:9000') print("Available Methods:") print(s.system.listMethods()) s.mouseClick("mainWindow/Button_1") s.wait(200) s.mouseClick("mainWindow/Button_2") s.wait(200) s.mouseClick("mainWindow/Button_2") s.wait(200) s.mouseClick("mainWindow/Button_2") s.wai...
StarcoderdataPython
3340214
<filename>tests/accepted_test.py<gh_stars>1-10 from src.spotlight.errors import ACCEPTED_ERROR from .validator_test import ValidatorTest class AcceptedTest(ValidatorTest): def test_accepted_rule_with_invalid_values_expect_error(self): rules = { "tos1": "accepted", "tos2": "accepted...
StarcoderdataPython
124790
from django.http import HttpResponse from django.shortcuts import render, redirect from RoomsManagement.models import * from .models import * from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.urls import reverse from django.contrib import messages from ....
StarcoderdataPython
3214957
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Copyright © Spyder Project Contributors # # Licensed under the terms of the MIT License # ---------------------------------------------------------------------------- """CompletionPlugin tests.""" # Standard libra...
StarcoderdataPython
129275
# -*- coding: utf-8 -*- # # <NAME> <<EMAIL>> # parasim # (c) 1998-2022 all rights reserved # # the package import hello # declaration class Greet(hello.command, family='hello.cli.greet'): """ This is the base class for command that greet my friends N.B.: This command is not directly usable since it doe...
StarcoderdataPython
3278792
<reponame>lalapapauhuh/Python<filename>Turtle/folha.py import turtle wn = turtle.Screen() wn.bgcolor('LightGrey') risco = turtle.Turtle() risco.color('DimGrey') risco.pensize(12) for size in range(1,31,1): risco.forward(size) risco.right(26) risco.left(160) risco.forward(50) ris...
StarcoderdataPython
15548
<reponame>ICT4H/dcs-web<gh_stars>1-10 from unittest import TestCase from mock import patch, MagicMock from mangrove.datastore.database import DatabaseManager from datawinners.questionnaire.library import QuestionnaireLibrary class TestQuestionnaireTemplate(TestCase): def test_get_category_to_doc_mappings(self):...
StarcoderdataPython
3211565
sm.lockUI() FANZY = 1500010 sm.removeEscapeButton() sm.flipDialoguePlayerAsSpeaker() sm.sendNext("#bBleh! I almost drowned!#k") sm.setSpeakerID(FANZY) sm.sendSay("There must be some kind of enchantment to keep people from swimming across.") sm.flipDialoguePlayerAsSpeaker() sm.sendSay("#bYou could have told me that ...
StarcoderdataPython
3281776
<filename>app/api/profile_endpoint.py from typing import List, Optional from fastapi import APIRouter from fastapi import HTTPException, Depends from fastapi.responses import Response from tracardi.service.storage.driver import storage from tracardi.service.storage.factory import StorageFor from .auth.authentication ...
StarcoderdataPython
83178
# -*- coding: utf-8 -*- """ Created on Tue Mar 22 11:53:09 2022 @author: Oliver """ import numpy as np from matplotlib import pyplot as plt import cv2 as cv from PIL import Image from PIL.ImageOps import grayscale from .pattern_tools import patchmaker, align_pattern, microns_into_pattern def histogram_patches(patch...
StarcoderdataPython
1761143
#!/usr/bin/env python #coding:utf-8 # Author: mozman --<<EMAIL>> # Purpose: test hyperlink object # Created: 09.10.2010 # Copyright (C) 2010, <NAME> # License: GPLv3 import sys import unittest from svgwrite.container import Hyperlink class TestHyperlink(unittest.TestCase): def test_constructor(s...
StarcoderdataPython
3357141
<reponame>Orig5826/Basics # -*- coding: utf_8 -*- """ urllib.request """ import urllib.request import re def getHtml(url, code="utf8"): response = urllib.request.urlopen(url) html = response.read().decode("utf8") return html def getInfo(): url = "http://www.juzimi.com/" html = getHtml(url) ...
StarcoderdataPython
3232539
<reponame>PiotrJTomaszewski/InternetRadioReciever from mpd import MPDClient, base import threading DEBUG_MODE = True class SeriousConnectionError(BaseException): def __init__(self, arg): self.strerror = arg self.args = {arg} def reconnect_on_failure(client): def decorator(func): def...
StarcoderdataPython
1693674
<gh_stars>10-100 import unittest import pytest from dpipe.im.axes import * class TextBroadcastToAxes(unittest.TestCase): def test_exceptions(self): with self.assertRaises(ValueError): broadcast_to_axis(None, [1], [1, 2], [1, 2, 3]) with self.assertRaises(ValueError): broa...
StarcoderdataPython
4835543
<reponame>btjanaka/competitive-programming-solutions<filename>leetcode/452.py # Author: btjanaka (<NAME>) # Problem: (LeetCode) 452 # Title: Minimum Number of Arrows to Burst Balloons # Link: https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/ # Idea: Represent the horizontal coordinates as a seri...
StarcoderdataPython
1684751
<filename>lib/galaxy/tool_util/linters/help.py """This module contains a linting function for a tool's help.""" from galaxy.util import ( rst_to_html, unicodify, ) def lint_help(tool_xml, lint_ctx): """Ensure tool contains exactly one valid RST help block.""" # determine node to report for general pro...
StarcoderdataPython
182347
<filename>public/cantusdata/management/commands/import_data.py from django.core.management.base import BaseCommand from django.db import transaction from optparse import make_option from cantusdata.models.chant import Chant from cantusdata.models.folio import Folio from cantusdata.models.concordance import Concordance ...
StarcoderdataPython
28634
""" ================== welly ================== """ from .project import Project from .well import Well from .header import Header from .curve import Curve from .synthetic import Synthetic from .location import Location from .crs import CRS from . import tools from . import quality def read_las(path, **kwargs): "...
StarcoderdataPython
198312
<reponame>462630221/optimizer # SPDX-License-Identifier: Apache-2.0 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from collections import OrderedDict from typing import Sequence, Text, Any, Tuple, List, Callable, Op...
StarcoderdataPython
3207575
<reponame>StevenCollins/pro-ve-pro<gh_stars>0 #!/usr/bin/env python3 # To run this you probably need to: # pip install pyvesync # pip install python-dotenv import os import json from http.server import BaseHTTPRequestHandler, HTTPServer from pyvesync import VeSync from dotenv import load_dotenv load_dotenv() # Setu...
StarcoderdataPython
89835
import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms import argparse, time, sys, os, cv2 import numpy as np from dataloader import AlzhDataset import tensorboard_logger as tb_logger from PIL import Image from utils import AverageMeter, accuracy, adjust_learning_rate from net...
StarcoderdataPython
114431
<filename>src/tools.py<gh_stars>1-10 """ File: tools.py Authors: <NAME> & <NAME> Copyright (c) 2020 <NAME> & <NAME> The MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without ...
StarcoderdataPython
3228974
<reponame>young43/ISCC_2020 #!/usr/bin/env python import cv2 import threading # import Queue as que import time import numpy as np # import roslib import sys # import rospy import importlib # import cPickle # import genpy.message # from rospy import ROSException # import sensor_msgs.msg # import actionlib # import ro...
StarcoderdataPython
132057
<reponame>CorvusEtiam/financemgr<gh_stars>0 from setuptools import setup setup( name = "financemgr", version = "1.0.0", packages = ['financemgr'], install_requires = ["sqlalchemy"] )
StarcoderdataPython
1631732
# Copyright 2013-2021 Aerospike, Inc. # # 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 to in writ...
StarcoderdataPython
3300363
import os, csv #dictionary function designed to read .csv file from a provided address and given an array to store the values def RCSV(address): csv_reader = csv.DictReader(open(address, 'r'), delimiter=',', quotechar='"') headers = csv_reader.fieldnames input=[] for line in csv_reader: for i in range(len(csv...
StarcoderdataPython
1790059
# -*- coding:UTF-8 -*- ## # | file : main.py # | version : V1.0 # | date : 2017-12-08 # | function : 1.5inch OLED # # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documnetation files (the "Software"), t...
StarcoderdataPython
1725478
from .visualize import ( hyperopt_viz, compare_performance_viz, learning_curves_viz, )
StarcoderdataPython
1735293
<reponame>MarcinStachowiak/CIFAR-10_challange import cifar10_manager import dim_reduction_service import image_service import inceptionv3_manager import metrics_service from classification_service import EnsembleVotingModel from classification_service import NeuralNetworkModel from feature_service import FearureImageEx...
StarcoderdataPython
3393730
""" This module produces the strain versus strain rate populations, with bivariate histograms. Example: > cd ~/sibl/cli/process/exodus > conda activate siblenv > python visualization.py """ import os import numpy as np import matplotlib.pyplot as plt from matplotlib import rc # import pandas as pd impo...
StarcoderdataPython
3259395
<reponame>xjh093/LearnPythonTheHardWay<filename>pdf/examples/ex4.py #! /usr/bin/python3 # p25 cars = 100 space_in_a_car = 4.0 drivers = 30 passengers = 90 cars_not_driver = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_a_car average_passengers_per_car = passengers / cars_driven print(...
StarcoderdataPython
3228575
<filename>nlp_utils/Augmentation/SequenceAugmentation.py from typing import List from itertools import compress from .BaseAugmentation import MixinAugmentation class _RandomTruncate(MixinAugmentation): def __init__(self, min_length: int = 128, max_length: int = 256, random_seed: int = 42, threshold: float = .5): ...
StarcoderdataPython
3289699
import asgineer @asgineer.to_asgi async def app(request): if request.method == "GET": if request.path == "/": return "" if request.path.startswith("/user/"): return await output_second_param(request.path) elif request.method == "POST": return "" else: ...
StarcoderdataPython
61759
<reponame>anyboby/ConstrainedMBPO import numpy as np from softlearning.policies.safe_utils.mpi_tools import mpi_statistics_scalar from softlearning.policies.safe_utils.utils import * from softlearning.replay_pools.cpobuffer import CPOBuffer import scipy.signal class ModelBuffer(CPOBuffer): def __init__(self, bat...
StarcoderdataPython
3292810
from mountequist.responses.httpis import HttpIs from mountequist.responses.proxy import Proxy
StarcoderdataPython
3208153
<filename>watson/analyze_tone.py import requests import json def analyze_tone(text): usern = '<PASSWORD>' passw = '<PASSWORD>' #watsonUrl = 'https://gateway.watsonplatform.net/tone-analyzer-beta/api/v3/tone?version=2016-05-18' watsonUrl='https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?ve...
StarcoderdataPython
119515
import pandas as pd from pathlib import Path def process_files(input_dir, output_dir, record_name): img_dir = output_dir / 'images' labels_dir = output_dir / 'labels' record_path = output_dir / record_name class_path = output_dir / 'classes.names' img_dir.mkdir(exist_ok=True) labels_dir.mkdi...
StarcoderdataPython
30007
"""Tools for working with Cryptopunk NFTs; this includes utilities for data analysis and image preparation for training machine learning models using Cryptopunks as training data. Functions: get_punk(id) pixel_to_img(pixel_str, dim) flatten(img) unflatten(img) sort_dict_by_function_of_value(d, f) ...
StarcoderdataPython
3332124
<filename>AdventOfCode2021/Day14/Day14.py<gh_stars>0 def part1(): code = open("input.txt").read().split("\n\n")[0] keys = {i.split(" -> ")[0]:i.split(" -> ")[1] for i in open("input.txt").read().split("\n\n")[1].split("\n")} string = {} for i in range(0,len(code)-1): string[code[i]+code[i+1]] =...
StarcoderdataPython
3247929
<gh_stars>10-100 import os from pkg_resources import resource_filename MISSING_LIBRARY_ERROR = """ Could not find the kaldi-io shared object (libtf_kaldi_io.so) on the system search paths, on paths specified in the LD_LIBRARY_PATH environment variable, or by importing package data from the 'tf_kaldi_io' package. Plea...
StarcoderdataPython
986
<reponame>HaidongHe/rqalpha # -*- coding: utf-8 -*- # 版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”) # # 除非遵守当前许可,否则不得使用本软件。 # # * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件): # 遵守 Apache License 2.0(下称“Apache 2.0 许可”),您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。 # 除非法律有要求或以...
StarcoderdataPython
3327042
from time import time def bouquets(narcissus_price, tulip_price, rose_price, summ): count = 0 args = sorted([narcissus_price, tulip_price, rose_price]) amounts = { 'cheap': [None, args[0]], 'medium': [None, args[1]], 'expensive': [None, args[2]] } del args for i in range(1, int(summ // amounts['cheap'][1...
StarcoderdataPython
3275866
<reponame>hust201010701/OneKeyUploadImage from qiniu import * import qiniu.config from win32con import * import win32clipboard import ctypes from ctypes.wintypes import * import sys import time import os from PIL import Image from qiniu.services.storage.upload_progress_recorder import UploadProgressRecorder class BITM...
StarcoderdataPython
158030
''' Exercise 1: 1. Write a recursive function print_all(numbers) that prints all the elements of list of integers, one per line (use no while loops or for loops). The parameters numbers to the function is a list of int. 2. Same problem as the last one but prints out the elements in reverse order. ''' #printing all in...
StarcoderdataPython
1737955
<reponame>yellowb/ml-sample import heapq """ self encapsulated priority queue """ class PriorityQueue: def __init__(self): self._queue = [] self._count = 0 def _push(self, priority, item): heapq.heappush(self._queue, (-priority, self._count, item)) # the first...
StarcoderdataPython
1789364
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import uu...
StarcoderdataPython
3221346
from time import time from multiprocessing.pool import Pool NUM_LIMIT = 1000000 start_time = time() def cal_uv(i): print(i) result_list =[] for u in range(1, i): v = i/u if v < 1: continue if not (u+v) % 4: z_4 = 3*v-u if z_4> 0 and not z_4 % 4...
StarcoderdataPython
40987
<reponame>mampilly/backend-global<gh_stars>0 '''Rate limiting via Redis''' import logging from datetime import timedelta from redis import Redis from app.core.database.cache import get_redis_connection from app.exceptions.application_exception import exception def rate_request(key, limit, period): """Rate request...
StarcoderdataPython
82929
<filename>python/controller.py<gh_stars>0 from distutils.log import debug from threading import Thread from flask import Flask, jsonify, send_file from time import sleep from dataclasses import dataclass, field from datetime import datetime, timedelta import serial import uuid from collections import deque import sys i...
StarcoderdataPython
181601
<filename>weasel/widgets/image_sliders.py __all__ = ['ImageSliders'] import pandas as pd from PyQt5.QtCore import Qt, pyqtSignal from PyQt5.QtWidgets import ( QWidget, QHBoxLayout, QPushButton, ) from PyQt5.QtGui import QIcon from .. import widgets as widgets class ImageSliders(QWidget): """Widget with...
StarcoderdataPython
1633092
import itertools from typing import List, Iterable from bispy.utilities.graph_entities import _Vertex, _QBlock # check if the given partition is stable with respect to the given block, or if # it's stable if the block isn't given def is_stable_vertexes_partition(partition: List[List[_Vertex]]) -> bool: """Checks ...
StarcoderdataPython
1788800
#!/usr/bin/env python3 import os import sys import MySQLdb def database_check(): dbname = os.environ.get('MYSQL_DATABASE') user = os.environ.get('MYSQL_USER') password = os.environ.get('MYSQL_PASSWORD') host = "db" port = 3306 print("HOST: {host}:{port}, DB: {dbname}, USER: {user}".format( ...
StarcoderdataPython
1785351
<filename>dominion/tasks.py # Copyright 2020 <NAME>. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required...
StarcoderdataPython
1717078
#!/usr/bin/env python def bubble_sort(iterable): """Sorts the iterable. Bubble sort is a simple, comparison sorting algorithm that iterates through a collection, compares adjacent items, and swaps them if they are in the wrong order. Iterations through the collection are repeated until no swaps are needed....
StarcoderdataPython
3250314
#! /usr/bin/env python # # The file 'command_line_options.py' in $QUEX_PATH/doc generates documentation # for the command line options. This file double-checks whether the content # of the generated files is consistent with the current setup. # # (C) <NAME> #_____________________________________________________________...
StarcoderdataPython
1606370
# standard from threading import Event # internal from src import settings from .base import BaseWidget from src.apps import InvoiceApp, CustomerApp, CallApp # pyqt from PyQt5.QtWidgets import QHBoxLayout, QPushButton, QLabel from PyQt5.QtCore import Qt, QObject, QThread, pyqtSignal ########## # Engine # ########## c...
StarcoderdataPython
3383436
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def go_back(apps, schema_editor): Provider = apps.get_model("core", "Provider") ProviderTrait = apps.get_model("core", "Trait") for provider in Provider.objects.all(): if provider.dns_server_i...
StarcoderdataPython
99650
""" Experiments to unconver the true nature of coroutines. One goal is to be able to operate coroutines without an event loop (or some kind of stub of an event loop) Other goals are to be able to serialize coroutines, move them between processes and threads, implement advanced error handling (could we back one up a...
StarcoderdataPython
114727
<gh_stars>1-10 import matplotlib.pyplot as plt import numpy as np from comb_step_ramp import comb_step_ramp t = np.arange(-10, 10,0.01) 'TIME SCALING BY t/2' x=[] comb_step_ramp(t/2,x) plt.subplot(2,2,1) plt.step(t,x) plt.axhline(0, color='black') plt.axvline(0, color='black') plt.xlabel('time') plt.yl...
StarcoderdataPython