id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
11339599
<gh_stars>0 import asyncio from collections import deque def split_into_even_size(lst, size): return [lst[i:i + size] for i in range(0, len(lst), size)] import datetime class ExpiredSet: def __init__(self, seconds, max_seconds=None): self.container = {} self.max_seconds = max_seconds def ...
StarcoderdataPython
6684893
#stylus.py #(c) <NAME>, Smith-Kettlewell Eye Research Institute #code to support stylus, including markers printed on it import numpy as np import cv2 def detectMarkers_clean(gray, dictionary, parameters): #call aruco.detectMarkers but clean up the returned corners and ids #corners: multi-array of dimension n x 4 x...
StarcoderdataPython
8144341
#!/usr/bin/pyhon3 #coding:utf-8 #引入开发包 import requests import os from bs4 import BeautifulSoup url='http://www.qiushu.cc/t/76675/23617439.html' #请求头,模拟浏览器 req_header={ 'Accept':'*/*', 'Accept-Encoding':'gzip, deflate', 'Accept-Language':'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2', 'Con...
StarcoderdataPython
9624291
class SimulationParameters(object): def __init__( self, simulation_time: float, packet_length: int, generation_constant: float, queue_constant: float, lambda_on: float, lambda_off: float, streams_number: int, dropped_streams: int, ): ...
StarcoderdataPython
150830
<filename>AVM + DELTA.py # Monte Carlo Valuation of a European Option in a Black-Scholes World # With implementation of Antithetic and Delta-based control variate method # by <NAME> # 10/31/2016 from math import * import numpy as np import random from scipy.stats import norm # Computation of Black-Scholes ...
StarcoderdataPython
3337556
#!/usr/bin/env python3 # Copyright 2019 <NAME> # 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, merge, pub...
StarcoderdataPython
6652885
import collections import operator import bytewax from bytewax import inp # You can define your own functions which add groupings of steps to a # dataflow. This allows you to repeat a pattern of steps easily. def calc_counts(flow): """Add steps to this flow which counts the frequencies of input items and emi...
StarcoderdataPython
5112492
<gh_stars>1-10 import os, sys from datetime import datetime import time import random import inspect import platform import getpass import socket import inspect from distutils.dir_util import copy_tree class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instan...
StarcoderdataPython
9716992
<gh_stars>10-100 # -*- coding: utf8 -*- """ Constants for modules """ __author__ = 'sergey' COMPRESSION_SUPPORTED=('lzo', 'zlib', 'bz2', 'xz', 'snappy', 'lz4', 'lz4h', 'lz4r07', 'quicklz', 'quicklzf', 'quicklzm', 'quicklzb', 'brotli', ...
StarcoderdataPython
5095571
#!/usr/bin/env python """Application controller for RAxML (v7.0.3). WARNING: Because of the use of the -x option, this version is no longer compatible with RAxML version VI. """ from cogent.app.parameters import FlagParameter, ValuedParameter, FilePath from cogent.app.util import CommandLineApplication, ResultPath, ge...
StarcoderdataPython
5123437
<reponame>MichaelTROEHLER/datadog-api-client-python<filename>tests/v1/test_synthetics_trigger_ci_tests_response_results.py<gh_stars>0 # coding: utf-8 # Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. # This product includes software developed at Datadog (https...
StarcoderdataPython
1926422
<reponame>ormsbya/ProteomicsUtils """ Generates plots of the TPE reactivity (according to Log2 Cys/NonCys) for all peptides corresponding to a given protein across samples e.g. denaturation curve or time intervals. """ import os, sys from ProteomicsUtils.LoggerConfig import logger_config from ProteomicsUtils import St...
StarcoderdataPython
8049689
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import time from loguru import logger class Moment: def __init__(self, unix_timestamp: int = None, format_time: str = None): self.unix_timestamp = unix_timestamp or int(time.time()) self.format_time = format_time or '%Y-%m-%d %H:%M:%S'...
StarcoderdataPython
6569453
<gh_stars>100-1000 # coding=utf-8 # Copyright 2019 Google LLC. # # 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 applic...
StarcoderdataPython
9662794
<reponame>roeselfa/FeatureLearningBasedDistanceMetrics<gh_stars>1-10 import AdvancedBA as ba import matplotlib.pylab as plt import seaborn as sns from pm4py.objects.log.adapters.pandas import csv_import_adapter from pm4py.objects.conversion.log import factory as conversion_factory from pm4py.util import constants plt....
StarcoderdataPython
6475568
<reponame>EVEprosper/ProsperDatareader """prosper.datareader.news: utilities for looking at news data""" import pandas as pd import prosper.datareader.robinhood as robinhood # TODO: simplify import import prosper.datareader.yahoo as yahoo import prosper.datareader.intrinio as intrinio import prosper.datareader.excep...
StarcoderdataPython
9789463
<reponame>qgoestch/sinecity_testcases # -*- coding: utf-8 -*- ## # \file errors_calc2_modes.py # \title Calculation of the errors and norms for the case2: # modes in 2D square box. # \author <NAME> # \version 0.1 # \license BSD 3-Clause License # \inst UMRAE (Ifsttar Nantes), LAUM (Le Mans Univ...
StarcoderdataPython
1784483
<gh_stars>0 # -*- coding: utf-8 -*- """Application configuration.""" import os, datetime import simplekv.memory class Config(object): """Base configuration.""" #SECRET_KEY = os.environ.get('MYFLASKAPP_SECRET', 'secret-key') # TODO: Change me SECRET_KEY = '<KEY>' #csrf EMAIL_KEY = '<KEY>' # email veri...
StarcoderdataPython
5167109
botnick = "botsnamehere" # twitch username the bot will use trustedppl = ["trusted user", "another trusted user"] # NO spaces in the username # the people you trust to use certain commands channeltojoin = "yourchannelnamehere" #the twitch channel to join oa = "oauth:abc123abc123" # your oauth key for the user you ch...
StarcoderdataPython
3266896
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import sys import platform if platform.system() == 'Darwin': sys.path.append("../Resources/lib/python2.7/site-packages/") import sip # Tell qt to return python string instead of QString # These are only needed for Python v2 but are harmless for Python v3. sip.setapi...
StarcoderdataPython
6636223
from twisted.internet import reactor from twisted.web.server import Site from webservices.async import provider_for_twisted from webservices.models import Provider API_KEYS = { 'pubkey': 'privkey', # your keys here } class HelloProvider(Provider): def get_private_key(self, public_key): return API_...
StarcoderdataPython
3215526
<gh_stars>0 import json import os import torch class TimeDistributed(torch.nn.Module): """ Time distributed wrapper compatible with linear/dense pytorch layer modules""" def __init__(self, module, batch_first=True): super(TimeDistributed, self).__init__() self.module = module self.ba...
StarcoderdataPython
5050900
<reponame>lordjabez/temperature-collector<filename>lambdas/temperature-collector/weather.py<gh_stars>1-10 import logging import requests _weather_url = 'https://api.openweathermap.org/data/2.5/weather' _log = logging.getLogger(__name__) def get_temperature(config, lat, lon): api_key = config['openWeatherApiKe...
StarcoderdataPython
11342183
<filename>CIM15/IEC61970/Informative/InfCustomers/PowerQualityPricing.py # Copyright (C) 2010-2011 <NAME> # # 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 with...
StarcoderdataPython
6510432
import json import random import pytest from src import es_handler @pytest.fixture() def es_cleared(): # setup es = es_handler.connect_elasticsearch() es.indices.delete(index='test_index', ignore=[400, 404]) yield # cleanup after test execution es.indices.delete(index='test_index', ignore=[40...
StarcoderdataPython
9662720
import logging import paramiko import string from time import sleep from ocs_ci.ocs.exceptions import CommandFailed, TimeoutException log = logging class WinNode(object): def __init__(self, **kw): self.login = "Administrator" self.password = "<PASSWORD>" self.ip_address = kw['ip_address...
StarcoderdataPython
6664511
from django.contrib import admin from django import forms from .models import Pathogen, Original_host, Origin_pathogen, NCBI_nodes, Changelog, Table_descriptions import json class PathogenForm(forms.ModelForm): class Meta: fields = [] model = Pathogen def __init__(self, *args, **kwargs): ...
StarcoderdataPython
11210822
<reponame>ekmixon/gamechanger-ml """ usage: python predict_table.py [-h] -m MODEL_PATH -d DATA_PATH [-b BATCH_SIZE] [-l MAX_SEQ_LEN] -g GLOB [-o OUTPUT_CSV] -a AGENCIES_PATH [-r] Binary classification of each sentence in the files matching the 'glob' in dat...
StarcoderdataPython
103590
<reponame>rodmidde/pandoc-astah-include #!/usr/bin/env python """ Astah filter to process code blocks with class "ashah" into images. Needs `astah-community.jar and dependencies`. """ import os import shutil from subprocess import call from pandocfilters import toJSONFilter, Para, Image, get_caption def get_file...
StarcoderdataPython
1684323
import random def eightball(): # https://en.wikipedia.org/wiki/Magic_8-Ball#Possible_answers return random.choice(("It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply...
StarcoderdataPython
12864804
# -*- coding: utf-8 -*- """Constants for building the biological network explorer's transformations toolbox.""" from typing import List, Tuple from pybel.struct.pipeline.decorators import mapped # Default NetworkX explorer toolbox functions (name, button text, description) _explorer_toolbox = ( ('collapse_to_ge...
StarcoderdataPython
1807802
<reponame>borislavstoychev/nails_project from django.urls import path from nails_project.schedule import views urlpatterns = [ path('', views.ScheduleListView.as_view(), name='schedule view'), path('create-schedule/', views.ScheduleCreateView.as_view(), name='schedule create'), path('schedule-delete/<int...
StarcoderdataPython
6554458
<filename>weibo/test_weibo.py # -*- coding:utf-8 -*- # 微博热搜主页 : https://m.weibo.cn/p/102803_ctg1_8999_-_ctg1_8999_home # 微博热搜主页的数据 : https://m.weibo.cn/api/container/getIndex?containerid=102803_ctg1_8999_-_ctg1_8999_home&page={} # 微博热搜博主发表微博的数据 : https://m.weibo.cn/api/container/getIndex?uid={}&luicode=10000011&lfid=...
StarcoderdataPython
1652710
<filename>quantities/volume.py from .quantity_type import QuantityType from .quantity import Quantity from .units import Unit from .area import AreaType from .length import LengthType class cubic_meter(Unit): profile = { "name":"cubic meter", "symbol":"", "express_by_SI_base":"m+3", ...
StarcoderdataPython
6484066
import tensorflow as tf from os.path import join, exists from .preprocess import ZaloDatasetProcessor from .modeling import BertClassifierModel from bert import tokenization import kashgari from kashgari.tasks.classification import BiGRU_Model from kashgari.embeddings import BERTEmbedding, TransformerEmbedding from kas...
StarcoderdataPython
11309616
import time import numpy as np from cechmate import phat_diagrams, Alpha, Rips def test_phat_diagrams(): t = np.linspace(0, 2 * np.pi, 40) X = np.zeros((len(t), 2)) X[:, 0] = np.cos(t) X[:, 1] = np.sin(t) np.random.seed(10) X += 0.2 * np.random.randn(len(t), 2) rips = Rips(1).build(X) ...
StarcoderdataPython
276766
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import argparse from sccl.language import * from sccl.topologies import * from sccl.language.collectives import Collective class ReduceGather(Collective): def __init__(self, num_ranks, chunk_factor, inplace, groups): Collective.__in...
StarcoderdataPython
6421402
""" Constants Module """ class Constants(): INCIDENT_UPDATE_STATUSES = { "investigating": "Investigating", "identified": "Identified", "monitoring": "Monitoring", "update": "Update", "resolved": "Resolved", } COMPONENT_STATUSES = { "operational": "Operatio...
StarcoderdataPython
6695929
import os import random import itertools import numpy as np import collections import matplotlib.pyplot as plt from collections import Counter from itertools import chain from bisect import bisect_right, bisect_left from reclist.current import current def statistics(x_train, y_train, x_test, y_test, y_pred): trai...
StarcoderdataPython
6609496
<filename>code/test_poly_time.py<gh_stars>0 from os import urandom from pyspark import SparkConf, SparkContext, StorageLevel from time import time from base.algebra import * from base.ntt import fast_coset_divide, fast_coset_evaluate, fast_multiply from base.univariate import Polynomial from rdd.rdd_poly import ( ...
StarcoderdataPython
1790843
import asyncio import logging import os import threading from time import sleep from unittest.mock import MagicMock from dotenv import load_dotenv from Collectors.EdgeOS.Collector import EdgeOSCollector from Collectors.Environment.Collector import EnvironmentCollector from DB.InfluxDBCloud import InfluxDBCloud _loop...
StarcoderdataPython
8183011
<gh_stars>1-10 from typing import List def find_line(lines: List[str], keyword: str, fallback: str = '') -> str: for line in lines: if line.startswith(keyword): return line.replace('\n', '') return fallback def find_value(line: str, delimiter: s...
StarcoderdataPython
9365
#!/usr/bin/env python3 """ Description: Python script to append the common columns in one sheet from another sheet using fuzzy matching. """ import pip def import_or_install(package): try: __import__(package) except ImportError: pip.main(['install', package]) import os import sys im...
StarcoderdataPython
6599046
from mysql.connector.pooling import MySQLConnectionPool as MariaDBConnectionPool from undine.database import Database from undine.utils.exception import UndineException import mysql.connector as mariadb class MariaDbConnector(Database): _DEFAULT_HOST = 'localhost' _DEFAULT_DATABASE = 'undine' _DEFAULT_US...
StarcoderdataPython
350251
__author__ = '<NAME>, <EMAIL>' from innermemetic import InnerMemeticSearch from inversememetic import InverseMemeticSearch class InnerInverseMemeticSearch(InnerMemeticSearch, InverseMemeticSearch): """ inverse of inner memetic search""" def _learnStep(self): self.switchMutations() ...
StarcoderdataPython
5186490
"""Provide an easy interface for loading data into L{DataFrame}s for Spark. """ # # 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 fil...
StarcoderdataPython
4963739
<gh_stars>0 ''' Author: <NAME> Date: Dec 29 2016 Description: Script that runs in the background. Shuts down the pi when a GPIO pin goes low ''' import time import RPi.GPIO as GPIO import os # global vars TIME_DELAY = 500 BUT_PIN = 21 # setup helper function for event callback def shutdown(c): os.system("sudo s...
StarcoderdataPython
6414277
import datetime import random import math import pandas as pd import DataGenUtil from faker import Faker SUBJECTS = ['Math - Algebra', 'Math - Geometry', 'English Language', 'History - World History', 'Science Biology', 'Health', 'Technology - Programming', 'Physical Education', 'Art', 'Music'] ...
StarcoderdataPython
6652494
<filename>sklearn_wrapper/modules/Outputer.py<gh_stars>1-10 import importlib from logging import getLogger import numpy as np import pandas as pd logger = getLogger('predict').getChild('Outputer') if 'ConfigReader' not in globals(): from .ConfigReader import ConfigReader if 'LikeWrapper' not in globals(): f...
StarcoderdataPython
9639726
OMICSDI = { 'base_url': "https://www.omicsdi.org/ws/dataset/search?", 'omicsdi_api_url': "https://www.omicsdi.org/ws/dataset/{}/{}.json", 'metabolights': { 'query': "repository:\"Metabolights\"", 'dataset_url': "http://www.ebi.ac.uk/metabolights/{}", 'omicsdi_url': "https://www.omicsdi.org/dataset/met...
StarcoderdataPython
6653944
# # Copyright (c) 2021 Arm Limited and Contributors. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # """Tests for the HostRegistry class.""" import unittest from htrun.host_tests_registry import HostRegistry from htrun import BaseHostTest class HostRegistryTestCase(unittest.TestCase): class HostTest...
StarcoderdataPython
368717
<filename>transforms.py from albumentations import ( Compose, OneOf, CenterCrop, GaussNoise, Normalize, HorizontalFlip, Resize, Rotate, JpegCompression, ChannelShuffle, InvertImg, RandomBrightnessContrast, RGBShift, RandomGamma, HueSaturationValue, Multipl...
StarcoderdataPython
6402553
<reponame>Sirrah91/Asteroid-spectra<gh_stars>0 # Parameters for the data collection # Only spectra within this range will be processes lambda_min = 450 # Minimum value of lambda; nm lambda_max = 2450 # Maximum value of lambda; nm resolution_max = 15 # Maximum acceptable step in wavelength resolution; nm denoise =...
StarcoderdataPython
3470860
# -*- coding: utf-8 -*- """ Created on Tue Jul 5 18:05:41 2016 @author: Olivier """ import numpy as np class basisTab: m = np.array( [ ["date", 0, "varchar", 1], ["calories", 0, "int", 0], ["gsr", 0, "int", 0], ["hearrate", 0, "int", 0], ["ski...
StarcoderdataPython
9648470
<reponame>autorouting/main # THIS IS THE CODE THAT CONSTANTLY RUNS IN THE BACKGROUND ON THE SERVER. import sys import time import pickle import networkx as nx import osmnx as ox import serialize import socket import concurrent.futures # Load network into memory G = pickle.load(open('graph', 'rb')) def generate_dista...
StarcoderdataPython
5096800
<filename>choosemybeer.py #!/usr/bin/env python ############################################################# # # # ChooseMyBeer - find the keg that's right for you # # written by <NAME> (<EMAIL>) # # ...
StarcoderdataPython
94572
<filename>curso em video/python/mundo 2/ex 067.py<gh_stars>0 #num1 = int(input('qual tabuada você deseja?')) #num2 = 1 #while True: # if num1 <= 0: # break # print(f'{num2} X {num1} ={num2*num1}') # num2 += 1 # if num2>=11: # num1 = int(input('qual tabuada você deseja?')) # num2 = 1 #pr...
StarcoderdataPython
6441242
# coding: utf-8 from fabkit import task, serial from fablib.mysql import MySQL @task def setup(): mysql = MySQL() mysql.setup() return {'status': 1} @task @serial def setup_replication(): mysql = MySQL() mysql.setup_replication() return {'status': 1}
StarcoderdataPython
3578080
<reponame>eHealthAfrica/aether #!/usr/bin/env python # Copyright (C) 2019 by eHealth Africa : http://www.eHealthAfrica.org # # See the NOTICE file distributed with this work for additional information # regarding copyright ownership. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use...
StarcoderdataPython
11221535
<reponame>borisdayma/wav2vec-toolkit import os import sys import textwrap import pkg_resources BASE_PATH = "wav2vec_toolkit" LANG_PATH = "languages" LANG_MODULE_REQUIREMENTS = ["normalizer.py", "README.md", "requirements.txt"] def get_file_path(name: str): return os.path.abspath(os.path.join(os.path.dirname(__...
StarcoderdataPython
1938063
<gh_stars>0 # Copyright 2020 Google LLC # # 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 i...
StarcoderdataPython
9680266
#!/usr/bin/env python3 import base import numpy as np def tasks(): return [ ScoreMeanStd(), ] class ScoreMeanStd(base.Task): """ Calculates mean and standard averages of the number of mutations, hse score and dom score. A comparison is made between hse/dom scores of positions with an...
StarcoderdataPython
31142
<gh_stars>0 """ Reads (article_id, [tokens]) from tokens.pickle and writes: (article_id, w2v) (article_id, bow) """ import json import sys import os import pickle import psycopg2 from multiprocessing.pool import Pool import numpy as np import zlib # from gensim.models import Word2Vec from gensim.models import Word2Ve...
StarcoderdataPython
6652246
import datetime from pathlib import Path import tempfile import logging import sys from rich.logging import RichHandler LOGGER_FORMAT = '%(asctime)s - ' \ '%(module)s.%(funcName)s - ' \ '(%(levelname)s): %(message)s' FORMATTER = logging.Formatter(LOGGER_FORMAT) def get_console_handle...
StarcoderdataPython
23062
import itertools def next_step(board, i, j): xMin = max(0, j - 1) xMax = min(board.shape[1] - 1, j +1) yMin = max(0, i - 1) yMax = min(board.shape[0] - 1, i +1) iteration = list(itertools.product(range(yMin, yMax + 1), range(xMin, xMax+1))) iteration.remove((i,j)) sum = 0; for (k, m) i...
StarcoderdataPython
4847041
<gh_stars>100-1000 from __future__ import unicode_literals from django.core.exceptions import ObjectDoesNotExist, PermissionDenied from django.db.models import Q from django.utils import six from djblets.webapi.errors import DOES_NOT_EXIST, WebAPIError from djblets.webapi.fields import (BooleanFieldType, ...
StarcoderdataPython
360545
<gh_stars>0 """ Написать программу, которая выведет на экран все числа от 1 до 100 которые кратные n (n вводится с клавиатуры). """ n = int(input("Enter number: ")) for x in range(1, 101): if x % n ==0: print(x)
StarcoderdataPython
8041472
import numpy as np # scipy.stats.cramervonmises # Suponha que desejamos testar se os dados gerados por # scipy.stats.norm.rvs foram, de fato, extraídos da # distribuição normal padrão. Escolhemos um nível de # significância alfa = 0,05. from scipy import stats rng = np.random.default_rng() x = stats.norm.rvs(size=50...
StarcoderdataPython
6655020
import numpy as np from gym.spaces import Box, Dict from multiworld.core.multitask_env import MultitaskEnv from multiworld.envs.env_util import ( get_stat_in_paths, create_stats_ordered_dict, ) import railrl.torch.pytorch_util as ptu from railrl.envs.wrappers import ProxyEnv from railrl.torch.core import PyTor...
StarcoderdataPython
215855
"""Samples are print to stdout""" import random import argparse from pathlib import Path SOURCES = { "Random@0.1": "_baseline_random_10", "Head@0.1": "_baseline_head_10", "TextRank@0.1": "_original_10", "BM25+eps.25@0.1": "_bm25pluseps025_10", "USE-base@0.1": "_use_base_10", "USE-large@0.1": "_...
StarcoderdataPython
384163
import datetime, pytz import time import sys from pyspark.sql import SparkSession from pyspark.sql.functions import regexp_replace from pyspark.sql.functions import split from pyspark.sql.functions import udf from pyspark.sql.types import * import matplotlib.pyplot as plt import sys,tweepy,csv,re from textblob import T...
StarcoderdataPython
4988948
<gh_stars>1-10 import pandas as pd import os import tqdm import networkx as nx import mxnet as mx import torch import numpy as np import json from mmdet.ops.nms.nms_wrapper import nms def soft_bbox_vote(det, vote_thresh, score_thresh=0.01): if det.shape[0] <= 1: return det order = det[:, 4].ravel().arg...
StarcoderdataPython
3504992
import numpy as np import tensorflow as tf from spektral.data.utils import ( batch_generator, collate_labels_disjoint, get_spec, prepend_none, sp_matrices_to_sp_tensors, to_batch, to_disjoint, to_mixed, to_tf_signature, ) version = tf.__version__.split(".") major, minor = int(versi...
StarcoderdataPython
3428281
__author__ = 'rv' from net.asserter.crawler.economic_indicator import YahooFinance if __name__ == "__main__": print("Hello") # yahoo_finance = yahoo_finance() # economic_indicators.cec(from_yahoo=True,is_save=True)
StarcoderdataPython
4906544
#Faça um programa que tenha uma função chamada escreva(), que receba um texto qualquer como parâmetro e mostre uma #mensagem com tamanho adaptável. def txt(msg): print('-' * len(msg)) print(msg) print('-' * len(msg)) txt('Oi') txt('Como você está?') txt('Obrigado!')
StarcoderdataPython
3321093
from datetime import date trab = dict() trab['nome'] = str(input('Nome: ').strip().title()) trab['Ano de Nascimento'] = int(input('Ano de nascimento: ')) idade = date.today().year - trab['Ano de Nascimento'] trab['ctps'] = int(input('Carteira de trabalho(0 se não tiver): ')) print('-=+' * 20) if trab['ctps'] == 0: ...
StarcoderdataPython
1917682
#!/usr/bin/env python from setuptools import setup,find_packages import sys from setuptools.command.test import test as TestCommand class PyTest(TestCommand): user_options = [('pytest-args=', 'a', "Arguments to pass to pytest")] def initialize_options(self): TestCommand.initialize_options(self) ...
StarcoderdataPython
6567435
from pyspark import SparkConf, SparkContext def loadMovieNames(): movieNames = {} skip_first = True with open("ml-latest/movies.csv") as f: for line in f: if skip_first: skip_first = False continue fields = line.split(",") movieNam...
StarcoderdataPython
1848798
#!/usr/bin/env python # -*- coding: utf-8 -*- from pathlib import Path import typer from toolz import pipe import snappycli.auth as auth import snappycli.client as client app = typer.Typer() def exception_handler(func): def inner_func(*args, **kwargs): try: return func(*args, **kwargs) ...
StarcoderdataPython
3405190
from src.config.logger import AppLogger from src.helpers.file_handler import FileHandler import pandas as pd import category_encoders as ce class CategoricalDataEncoder(AppLogger): encoder_cols = ['sex', 'smoker', 'region'] def __init__(self, dataset: pd.DataFrame(), train=False): super(Categor...
StarcoderdataPython
1793699
import logging import uuid import datetime from six.moves import http_client from flask import request, g, abort, url_for, jsonify from flask.views import MethodView import marshmallow as ma from flask_restx import reqparse from flask_smorest import Blueprint from drift.core.extensions.urlregistry import Endpoints f...
StarcoderdataPython
5020074
# BSD 2-Clause License # # Copyright (c) 2021, Hewlett Packard Enterprise # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright noti...
StarcoderdataPython
11258339
import errno import socket from ..util.connection import create_connection from ..util.ssl_ import ssl_wrap_socket from ..util import selectors from .. import util from ._common import DEFAULT_SELECTOR, is_readable, LoopAbort __all__ = ["SyncBackend"] BUFSIZE = 65536 class SyncBackend(object): def connect(self...
StarcoderdataPython
150056
<gh_stars>1-10 MAX_PREFIX_LEN = 60 EXCEPTION_PREFIXES = { "1. Une attestation de la maîtrise foncière sur l'emprise de ": None, "2. Un plan de l'exploitation à une échelle adaptée à la supe": None, '3. Une note succincte indiquant la nature de la substance ex': None, '4. Pour les carrières visées à la r...
StarcoderdataPython
4897293
#!/usr/bin/env python # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Generate djvused input for book metadata # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ from collections import namedtuple import re import itertools import sys import io BookMark = namedtuple('BookMark', ['titl...
StarcoderdataPython
3252646
import tensorflow as tf import argparse import os import statistics as stat from models.utils import plot_test_images, plot_images, print_metrics from models.espcn.model_espcn import ESPCN as espcn from models.evsrnet.model_evsrnet import EVSRNet from models.rtsrgan.model_generator import G_RTSRGAN as g_rtsrgan f...
StarcoderdataPython
4807885
<reponame>knutsonchris/stacki # @copyright@ # Copyright (c) 2006 - 2019 Teradata # All rights reserved. Stacki(r) v5.x stacki.com # https://github.com/Teradata/stacki/blob/master/LICENSE.txt # @copyright@ # # @rocks@ # Copyright (c) 2000 - 2010 The Regents of the University of California # All rights reserved. Rocks(r)...
StarcoderdataPython
11372627
import abc import enum import typing as t import weakref from pathlib import Path from nr.caching.api import KeyDoesNotExist from nr.preconditions import check_instance_of, check_not_none import craftr from craftr.core.property import HavingProperties, collect_properties from craftr.core.configurable import Closure ...
StarcoderdataPython
8013989
import itertools def longestWPI(hours: list[int]) -> int: prefix = list(itertools.accumulate([1 if h > 8 else -1 for h in hours]))[::-1] indexes = { c: i for i, c in enumerate(prefix) } highest = 0 for i, v in enumerate(prefix): if v > 0: highest = max(highest, len(prefix) - i) ...
StarcoderdataPython
8178305
from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.db import models class Pigeon(models.Model): """ A pigeon is a message that will be delivered to a number of users """ # Reference ...
StarcoderdataPython
1806481
# This code is taken from https://github.com/open-mmlab/mmediting # Modified by <NAME> import torch import torch.nn as nn from mmcv.parallel import MODULE_WRAPPERS, MMDistributedDataParallel from mmcv.parallel.scatter_gather import scatter_kwargs from torch.cuda._utils import _get_device_index @MODULE_WRAPPERS.regis...
StarcoderdataPython
6478438
<filename>stubs.min/System/Windows/__init___parts/StaticResourceExtension.py class StaticResourceExtension(MarkupExtension): """ Implements a markup extension that supports static (XAML load time) resource references made from XAML. StaticResourceExtension(resourceKey: object) StaticResourceExtension() ...
StarcoderdataPython
1914311
<filename>e2e/cfgs/gen_single_im_cfgs.py import os import yaml def gen_e2e_single(base_cfg_fname, yaml_out_dir, dataset, model_depth, model_type, data_type, data_loader, yaml_out_fname=None): with open(base_cfg_fname, 'r') as f: cfg = yaml.safe_load...
StarcoderdataPython
3258909
<gh_stars>0 from typing import Sequence from numbers import Number from tabulate import tabulate class Matrix(Sequence): def __init__(self, matrix: Sequence[Sequence[float]]): assert (isinstance(matrix, Sequence) and isinstance(matrix, Sequence)), "Wrong data" self.__matrix = [[flo...
StarcoderdataPython
8096102
from django.urls import path from . import views app_name = 'restrito' urlpatterns = [ path('', views.home, name='home'), path('matriculas/', views.matricula_lista, name="matricula_lista"), path('matriculas/solicitar/', views.matricula_solicitar, name="matricula_solicitar"), path('matriculas/solicitar...
StarcoderdataPython
5109289
<filename>plugins/xlsimg/xlsimg.py import os class Excel2imgPlugin(object): def __init__(self, preprocessor): self.pp = preprocessor self.token = "<PASSWORD>" self.pp.register_plugin(self) def process(self, code, fname, sheet="", range="", title=None, div_style=None): """ ...
StarcoderdataPython
9670213
from .const import * __all__ = ['INSERT_USER','GET_USER','GET_USERS','INIT_DATABASE','GET_PRMS']
StarcoderdataPython
3333088
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
StarcoderdataPython
6630433
import sys f = open(sys.argv[1],mode = 'rt', encoding='utf-8') for line in f: sys.stdout.write(line) f.close()
StarcoderdataPython
6455167
from flask import Blueprint # # @author: andy # from .measure_service import profiling_service profiler_blueprint = Blueprint("profiler", __name__) @profiler_blueprint.route("/profiler", methods=["GET"]) def index(): return profiling_service.as_html()
StarcoderdataPython