id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
199762
<filename>cmp3103m-code-fragments/scripts/receiver.py # -*- coding: utf-8 -*- """ Created on Wed Jan 28 15:40:31 2015 @author: lcas """ import rospy from sensor_msgs.msg import LaserScan from geometry_msgs.msg import Twist class Receiver: def __init__(self): rospy.init_node('receiver') self.sub...
StarcoderdataPython
3327585
from uranium import current_build import os current_build.packages.install("uranium-plus[vscode]") import uranium_plus current_build.config.update({"uranium-plus": {"module": "vcver"}}) uranium_plus.bootstrap(current_build)
StarcoderdataPython
1601192
<reponame>geertj/python-rest # # This file is part of Python-REST. Python-REST is free software that is # made available under the MIT license. Consult the file "LICENSE" that is # distributed together with this file for the exact licensing terms. # # Python-REST is copyright (c) 2010 by the Python-REST authors. See th...
StarcoderdataPython
3321511
<filename>CursoEmVideo/pythonProject/ex018.py #calculo do seno cosseno e tangente de um angulo import math n = float(input('Digite o valor do ângulo: ')) sen = math.sin(math.radians(n)) cos = math.cos(math.radians(n)) tang =math.tan(math.radians(n)) print('O ângulo de {:.2f} graus tem: \n Seno: {:.2f}\n Cosseno {:.2f}\...
StarcoderdataPython
1761669
import re def check_exception(word): # Checa se a palavra corresponde a uma exceção (artigo, preposição ou conjunção) exceptionsPort = ['o', 'os', 'a', 'as', 'um', 'uns', 'uma', 'umas', 'ao', 'aos', 'à', 'às', 'do', 'dos', 'da', 'das', 'dum', 'duns', 'duma', 'dumas', 'no', 'nos', 'na', 'nas', 'num', 'nuns', 'numa', '...
StarcoderdataPython
158230
<gh_stars>100-1000 # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. class ChoiceFactoryOptions: def __init__( self, inline_separator: str = None, inline_or: str = None, inline_or_more: str = None, include_numbers: bool = None, ...
StarcoderdataPython
90948
import datetime import base64 from tornado.web import RequestHandler from tornado import gen from bson.objectid import ObjectId class Handler(RequestHandler): @gen.coroutine def post(self, _id): """提交代码""" try: #if self.request.remote_ip != "192.168.3.11": # raise Ru...
StarcoderdataPython
1638326
<filename>docs/autodoc.py # Copyright (c) AIRBUS and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import ast import importlib import inspect import json import logging import os import pkgutil import re import sys import url...
StarcoderdataPython
126735
<filename>terrascript/local/__init__.py # terrascript/local/__init__.py import terrascript class local(terrascript.Provider): pass
StarcoderdataPython
1650202
<filename>get_logits.py import numpy as np from tqdm import tqdm import sys # use non standard flow_from_directory from utils.image_preprocessing_v1 import ImageDataGenerator # it outputs not only x_batch and y_batch but also image names from keras.models import Model from models.xception import Xception, preprocess_...
StarcoderdataPython
1741062
from codewars.game_of_life import get_generation def test_game_of_life() -> None: start = [[1, 0, 0], [0, 1, 1], [1, 1, 0]] end = [[0, 1, 0], [0, 0, 1], [1, 1, 1]] assert get_generation(start, 1) == end
StarcoderdataPython
1787962
from setuptools import setup setup(name='commute_logger', description='A python based logger for recording commute times using Google Directions API', url='https://github.com/nakulbende/Commute_logger', author='<NAME>', author_email='<EMAIL>', license='MIT, Copyright (c) 2021 <NAME>', ...
StarcoderdataPython
1757549
<filename>executor.py #!/usr/bin/env python from py2neo import Graph, Path import time import argparse letters = "<KEY>" def connect(url): print "URL: {}".format(url) return Graph(url) def get_statements_count(node_type="Organisation"): """ Generate the Cypher statements required to count the number of ...
StarcoderdataPython
3254922
<reponame>shuigedeng/taotao-cloud-paren<filename>taotao-cloud-python/taotao-cloud-oldboy/day73-cmdb/day73/src/package.py # from .plugins.disk import DiskPlugin # from .plugins.mem import MemPlugin # from .plugins.nic import NicPlugin from conf import settings def pack(): # obj1 = DiskPlugin() # disk_info = obj...
StarcoderdataPython
3267189
<filename>test_thermal/test_SuperAdmin/test_ClientManagement/test_update.py from seleniumbase import BaseCase from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from parameterized import parameterized import pytest from test_thermal.test_SuperAdmin.SysAdminBase import SysAdminBa...
StarcoderdataPython
17961
from collections import namedtuple from dagster import check from dagster.config.config_type import ConfigType, ConfigTypeKind from dagster.config.field import Field from dagster.core.serdes import whitelist_for_serdes @whitelist_for_serdes class NonGenericTypeRefMeta(namedtuple('_NonGenericTypeRefMeta', 'key')): ...
StarcoderdataPython
1788247
def find_index(nodes, x, y): for index, item in enumerate(nodes): if item["coord"][0] == x and item["coord"][1] == y: return index return -1 def tile_input(risk_nodes, x=5, y=5): tiled = tile_x(risk_nodes, x) tiled = tile_x([list(x) for x in zip(*tiled)], y) return [list(x) for...
StarcoderdataPython
4827283
""" A generic function for generating context processors, and a processor which adds media-specific settings to each ``RequestContext``. """ def settings_processor(*settings_list): """ Generates and returns a context processor function which will read the values of all the settings passed in and return t...
StarcoderdataPython
4803552
<gh_stars>0 """ version which can be consumed from within the module """ VERSION_STR = "0.0.4" DESCRIPTION = "pymultienv is a command to help you deal with multiple python environments" APP_NAME = "pymultienv" LOGGER_NAME = "pymultienv"
StarcoderdataPython
18908
<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Furthest point sampling Original author: <NAME> Modified by <NAME> All Rights Reserved. 2017. Modified by <NAME> (2020) """ import os import sys import tensorflow as tf from tensorflow.python.framework import ops BASE_DIR = os.path.dirname(os.path.ab...
StarcoderdataPython
53050
<filename>whattowatch/core/models.py from tabnanny import verbose from embed_video.fields import EmbedVideoField from core.utils import get_file_path from django.db import models from pydoc import describe CHOICES_RATTING = [ (0, "L"), (10, "10"), (12, "12"), (14, "14"), (16, "16"), (18, "18"),...
StarcoderdataPython
3324410
#This class is designed to calculate where edges should be between nodes class EdgeCalculator: #@param commit: list of all the commits from the log def __init__(self,commits,programmers): self.commitlist = commits self.programmerslist = programmers #function that calculates which n...
StarcoderdataPython
4814136
#!/usr/bin/env python # -*- coding: utf-8 -*- import shutil import logging import tarfile import requests from tqdm import tqdm def ncbi(path, filename, base_url='https://ftp.ncbi.nlm.nih.gov/'): """Download a file from the NCBI ftp using https Arguments: path (string): base path to the file ...
StarcoderdataPython
3277064
<gh_stars>1-10 #!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import pandas as pd import scipy import scipy.linalg import matplotlib.pyplot as plt import sklearn.metrics import sklearn.neighbors import time import torch from torch import nn import torch.nn.functional as F from torch.utils.data im...
StarcoderdataPython
36917
<reponame>imamol/license_automation import requests from bs4 import BeautifulSoup def verfiy_package_names(): with open('final_output/remaining_list.csv') as file: orig_packages = file.readlines() bad_count = 0 good_count = 0 count = 0 dict_packages = {} ...
StarcoderdataPython
3379104
<filename>research/cv/AttentionCluster/src/datasets/mnist_sampler.py<gh_stars>10-100 # Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://w...
StarcoderdataPython
3227583
""" We can assess the parameter space around the optimum solution found using ``maxsmooth`` with the param_plotter() function. This can help us identify how well a problem can be solved using the sign sampling approach employed by ``maxsmooth`` or simply be used to identify correlations between the foreground parameter...
StarcoderdataPython
3394331
<filename>model/condition.py #!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 4.0.1-9346c8cc45 (http://hl7.org/fhir/StructureDefinition/Condition) on 2020-02-03. # 2020, SMART Health IT. import sys from dataclasses import dataclass, field from typing import ClassVar, Optional, List from .age imp...
StarcoderdataPython
3241285
""" Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N - h papers have no more...
StarcoderdataPython
1787319
<filename>eit_model/greit.py<gh_stars>0 import copy import logging import numpy as np from eit_model.data import EITImage logger = logging.getLogger(__name__) def greit_filter(image: EITImage, threshold: float = None, div:float=4.0) -> EITImage: image_n = copy.deepcopy(image) image_n.data = image.data....
StarcoderdataPython
3388182
<reponame>Facunditenn/silla_cdp<filename>src/cdp_gui.py # Modulo de interfaz de usuario # Por ahora, estan solo las funciones necesarias para que no tire error, hasta tener lvgl andando def show_calib_instructions(which: str): print(which) def update_sensor_state(): pass
StarcoderdataPython
1716229
from floodsystem.station import MonitoringStation #2B (2) def stations_level_over_threshold(stations, tol): """a function that returns a list of tuples containing stations eith water levels over threshold and their relative water level """ stations_over = [] #creates empty list fot stations over threshol...
StarcoderdataPython
137376
<reponame>grutts/siri from dataclasses import dataclass, field from decimal import Decimal from typing import List, Optional __NAMESPACE__ = "http://www.siri.org.uk/siri" @dataclass class LocationStructure: """Type for gepspatial Position of a point. May be expressed in concrete WGS 84 Coordinates or any gm...
StarcoderdataPython
1736986
<gh_stars>0 from django import http from django.core.exceptions import PermissionDenied from django.db.models import Prefetch, Q from django.db.transaction import non_atomic_requests from django.shortcuts import get_object_or_404, redirect from django.utils.encoding import force_text from django.utils.translation impor...
StarcoderdataPython
3323514
<filename>Scripts/rom_generation.py # Script to generate the contents of the ROM IC that contains the engine's # predetermined move in response to the current game state. # # Board Cell Numbering: # 0 | 1 | 2 # ---+---+--- # 3 | 4 | 5 # ---+---+--- # 6 | 7 | 8 # # The Engine is always player 2. # # ROM Add...
StarcoderdataPython
1760798
<filename>Exercicios/mundo3-exercicios-72/ex098-correcao.py<gh_stars>0 # Faca um programa que tenha uma funcao # chamda contador(), que receba tres # parametros: inicio, fim e passo e realize a contagem. # Seu programa tem que realizar tres # contagens atraves da funcao criada: # A - De 1 ateh 10, de 1 em 1 # B - De 10...
StarcoderdataPython
1602310
from __future__ import absolute_import from __future__ import unicode_literals import os.path import pre_commit.constants as C from pre_commit.runner import Runner from testing.fixtures import git_dir from testing.util import cwd def test_init_has_no_side_effects(tmpdir): current_wd = os.getcwd() runner = R...
StarcoderdataPython
4836801
#!/usr/bin/env python3 import sys import os import re import argparse import pathlib import pandas as pd def main(args): ####################################################################### # Get arguments ####################################################################### input_file_paths = ...
StarcoderdataPython
1699538
<reponame>SKA-ScienceDataProcessor/integration-prototype # -*- coding: utf-8 -*- """Implements a simple test imaging pipeline using Spark and the OSKAR imager. This pipeline makes dirty images from all Measurement Sets in a specified directory, the name of which is given on the command line. Usage: spark-submit spark...
StarcoderdataPython
1779089
from pathlib import Path import re from setuptools import setup _DIR = Path(__file__).parent with (_DIR / "src/flynt/__init__.py").open() as f: version = re.search('__version__ = "(.*?)"', f.read()).group(1) def get_requirements(): with (_DIR / "requirements.txt").open() as f: return f.read() set...
StarcoderdataPython
70469
import pandas as pd import numpy as np from sklearn import model_selection from sklearn import preprocessing if __name__ == "__main__": df = pd.read_csv("data.csv") df["kfold"] = -1 d = {"downdog": 0, "goddess": 1, "plank": 2, "tree": 3, "warrior2": 4} df["y"] = df["y"].map(d) df = df.sa...
StarcoderdataPython
4819749
<gh_stars>1-10 # 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 by applicable l...
StarcoderdataPython
1726556
"""Class Validators.""" from marshmallow import fields, Schema from marshmallow.validate import OneOf from ..enums import * from ..models.BaseSchema import BaseSchema class FeedbackValidator: class getAttributes(BaseSchema): company_id = fields.Str(required=False) applicatio...
StarcoderdataPython
52992
from marshmallow import fields, validate from marshmallow_enum import EnumField from bigeye.models.base import ma from bigeye.models.user import UserRoles from bigeye.models.challenge import ChallengeDifficulty class ChallengeCategorySchema(ma.Schema): id = fields.Integer(dump_only=True) name = fields.String...
StarcoderdataPython
1634852
# -*- coding: future_fstrings -*- # Friendly Telegram (telegram userbot) # Copyright (C) 2018-2020 The Authors # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either vers...
StarcoderdataPython
3237780
<gh_stars>0 from warnings import warn import numpy as np import matplotlib.image as mimage from matplotlib.colors import to_rgba_array from ..utils import resolution from ..coords import coord_cartesian from ..doctools import document from ..exceptions import PlotnineError, PlotnineWarning from .geom import geom @d...
StarcoderdataPython
188273
# Generated by the protocol buffer compiler. DO NOT EDIT! # sources: proto/error/v1/error.proto # plugin: python-betterproto from dataclasses import dataclass from typing import Dict import betterproto from betterproto.grpc.grpclib_server import ServiceBase @dataclass(eq=False, repr=False) class ErrorScope(betterpr...
StarcoderdataPython
3270318
<filename>kernel/table.py<gh_stars>10-100 '''The object file of "table.c" contains most kernel data. Variables that are declared in the *.h files appear with EXTERN in front of them, as in EXTERN int x; Normally EXTERN is defined as extern, so when they are included in another file, no storage is allocated. If EXTER...
StarcoderdataPython
3342687
<filename>dataPrepare.py import os, sys, datetime import cv2 as cv import argparse import youtube_dl from lib.data import video # ------------------------------------parameters------------------------------# parser = argparse.ArgumentParser(description='Process parameters.', formatter_class=argparse.Argumen...
StarcoderdataPython
3396759
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class FluentCommentsApp(AppConfig): name = "fluent_comments" verbose_name = _("Comments") def ready(self): # This installs the comment_will_be_posted signal import fluent_comments.receivers # noqa
StarcoderdataPython
1696879
<filename>lyman/tests/test_surface.py import nibabel as nib import pytest from .. import surface class TestSurfaceMeasure(object): def test_surface_measure_neighbors(self, meshdata): sm = surface.SurfaceMeasure(meshdata["verts"], meshdata["faces"]) for v, v_n in sm.neighbors.items(): ...
StarcoderdataPython
1635443
<gh_stars>1-10 # This file gets the information of the games you have collected previously on games.py # The program runs using 'scrapy runspider analyze.py' # This file should take around 2 hours to completed # This file is NOT a final build, expect MANY bugs, especially skipping games crawl. # You bear all respon...
StarcoderdataPython
1618843
#problem statement::Use The Function name,return type and argument as: #int findValue(a,b) #The function must return 1 if the second number b is the last digits of a,else return 0 #sample input a=12344 b=344 #sample output yes def findValue(a,b): if [len(a)-len(b):] == b: return 1 else: return...
StarcoderdataPython
3349495
""" Step module """ import time class Step(object): """ Base Step class. All steps inherit from this class. """ def __call__(self): """ Executes a step. Returns: run results """ return self.run() def run(self): """ Executes a ...
StarcoderdataPython
3202093
# -*- coding: utf-8 -*- """ Created on Mon Apr 6 10:34:01 2020 @author: skjerns """ import config as cfg import ospath import sleep_utils from tqdm import tqdm import numpy as np folder = cfg.folder_edf files = ospath.list_files(folder, exts=['hypno']) hypnos = {} for file in tqdm(files): hypno = sleep_utils.r...
StarcoderdataPython
136443
"""``runway gen-sample`` command group.""" # docs: file://./../../../../docs/source/commands.rst import click from ... import options from ._cdk_csharp import cdk_csharp from ._cdk_py import cdk_py from ._cdk_tsc import cdk_tsc from ._cfn import cfn from ._cfngin import cfngin from ._k8s_cfn_repo import k8s_cfn_repo f...
StarcoderdataPython
18719
<gh_stars>0 import sys from mrs_utils import misc_utils, vis_utils from mrs_utils import eval_utils import os from skimage import io import numpy as np import matplotlib.pyplot as plt # Creat object scorer class osc = eval_utils.ObjectScorer(min_th=0.5, link_r=20, eps=2) # Define the source data_dir = '/scratch/sr36...
StarcoderdataPython
163828
import easygui as g import os #先打开第一个文件,显示并提取文件内容 file = g.fileopenbox(title='文件选择', msg='请选择你要打开的第一个文件文件', default='./*.txt', filetypes=['.txt', 'txt文档']) file_name = os.path.basename(file) with open(file,encoding='utf-8')as f1: content = f1.read() file_content = g.textbox(title='显示文件内容', msg='文件【%s】的内容显示如下' % fi...
StarcoderdataPython
3284246
from stellar_sdk import Asset from stellar_sdk.call_builder.offers_call_builder import OffersCallBuilder from tests.call_builder import horizon_url, client class TestOffersCallBuilder: def test_init(self): builder = OffersCallBuilder(horizon_url, client) assert builder.endpoint == "offers" ...
StarcoderdataPython
3263485
<filename>currencies/management/commands/_exchangeratesapi_client.py import decimal import requests __version__ = '0.1.0' __author__ = '<NAME>' __license__ = 'MIT' __copyright__ = 'Copyright 2021 Ward and Partners' # https://exchangeratesapi.io/documentation/ class ExchangeRatesApiClientException(request...
StarcoderdataPython
170519
import eventlet eventlet.monkey_patch(socket=True, select=True, time=True) import sys import time from oslo_config import cfg from oslo_log import log as logging import oslo_messaging as messaging from oslo_service import service as common_service from oslo_utils import excutils from neutron._i18n import _ from neut...
StarcoderdataPython
194860
import subprocess, re, os import gzip, shutil from smsgateway.config import * def _logging_namer(name): return name + ".gz" def _logging_rotater(source, dest): with open(source, "rb") as sf: # data = sf.read() # compressed = zlib.compress(data, 9) with gzip.open(dest, 'wb') as df: ...
StarcoderdataPython
58856
<reponame>sunbit/aioclustermanager<filename>aioclustermanager/nomad/__init__.py from aioclustermanager.nomad.caller import NomadCaller import aiohttp import asyncio class NomadContextManager: def __init__(self, environment, loop=None): self.environment = environment if loop is None: s...
StarcoderdataPython
97417
<reponame>SourceDoctor/puppet-librenms #!/usr/bin/python3 # Copyright(C) 2009 <NAME> # # 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 Foundation; either version 2 # of the License, or(at your option) any ...
StarcoderdataPython
3307204
<reponame>jiaruonan/transferlearning from torchvision import datasets, transforms import torch import numpy as np from torchvision import transforms import os from PIL import Image, ImageOps class ResizeImage(): def __init__(self, size): if isinstance(size, int): self.size = (int(size), int...
StarcoderdataPython
1627117
<gh_stars>0 """ A GUI for multi-processing logging using ZMQ Code is adapted from https://github.com/zeromq/pyzmq/blob/master/examples/logger/zmqlogger.py <NAME> <<EMAIL>> """ #%% Import packages import logging import os import signal import time import argparse import re from qtpy import QtGui from qtpy import Qt...
StarcoderdataPython
3254393
import numpy as np import theano import theano.tensor as T from sklearn import datasets, preprocessing from sklearn.model_selection import train_test_split from neupy import algorithms, layers from neupy.utils import asfloat from neupy.algorithms.gd.lev_marq import compute_jacobian from base import BaseTestCase cla...
StarcoderdataPython
1635239
import pytest from unittest.mock import Mock from datetime import datetime as dt from src.reporting.report import Driver from tests.test_report import TestDriver @pytest.fixture(scope='class') def fixture_create_drivers(): """ Creates mocked instances of Driver. """ abbreviations = ['DRR', 'SVF', 'BHS...
StarcoderdataPython
18001
<gh_stars>1-10 import numpy as np import pandas as pd import ipywidgets as widgets import matplotlib.pyplot as plt from skimage.measure import label, regionprops, regionprops_table from skimage.color import label2rgb def Wav_2_Im(im, wn): ''' Input a 3-D datacube and outputs a normalized slice at one wavenumber. ...
StarcoderdataPython
4826506
<reponame>Wang-TaoTao/meiduo_admin_project<filename>meiduo_mall/apps/users/utils.py import re from django.contrib.auth.backends import ModelBackend from apps.users.models import User class UsernameMobileModelBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): ...
StarcoderdataPython
1782157
<gh_stars>1-10 import torch import torch.nn as nn from torch.utils.tensorboard import SummaryWriter writer = SummaryWriter('runs/lgbm') def idx2onehot(idx, n): assert torch.max(idx).item() < n if idx.dim() == 1: idx = idx.unsqueeze(1) onehot = torch.zeros(idx.size(0), n) onehot.sc...
StarcoderdataPython
197510
######################################################################## # # Date: Sept 2012 Author: <NAME> # # <EMAIL> # # The Scripps Research Institute (TSRI) # Molecular Graphics Lab # La Jolla, CA 92037, USA # # Copyright: <NAME> and TSRI # #################################################...
StarcoderdataPython
1703507
# Credit to @danijar and @alexlee-gk on github # https://github.com/tensorflow/tensorboard/issues/39#issuecomment-568917607 import numpy as np import tensorflow as tf def video_summary(name, video, step=None, fps=20): name = tf.constant(name).numpy().decode('utf-8') video = np.array(video) if video.dtype in (n...
StarcoderdataPython
121141
<gh_stars>0 #!/usr/bin/env python3 # # Copyright 2018 <NAME> <<EMAIL>> # # 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,...
StarcoderdataPython
3273962
modes = ["RGB8", "HSVF32", "HLSF32"] strand_modes = ["RGB8", "BGR8"]
StarcoderdataPython
3376301
<reponame>gkovacs/python-getsecret import yaml from os.path import expanduser, isfile import os def getsecret(key, default=None): environ_value = os.environ.get(key) if environ_value is not None: return environ_value secrets = {} if isfile('.getsecret.yaml'): secrets = yaml.load(open('.getsecret.yaml')...
StarcoderdataPython
3269246
import argparse import torch from torch.autograd import Variable from torchvision import transforms, models import torch.nn.functional as F import numpy as np from PIL import Image import json import os import random from checkpoint import load_checkpoint, category_names def parse_args(): parser = argparse.Arg...
StarcoderdataPython
3397902
<reponame>binfiles/binfiles.net import copy import hashlib import json import os from os import path # Describe all sizes of files we need to create dataFileSizes = [1048576, 10485760, 104857600, 524288000, 1048576000] # Describe the hash types we'll be generating hashFileTypes = ["sha256", "sha1", "md5"] # Setup th...
StarcoderdataPython
1743198
<reponame>viksrivat/aws-sam-cli<gh_stars>1-10 from .integ_base import IntegBase, TelemetryServer class TestTelemetryContract(IntegBase): """ Validates the basic tenets/contract Telemetry module needs to adhere to """ def test_must_not_send_metrics_if_disabled_using_envvar(self): """ ...
StarcoderdataPython
3324874
<filename>30stats.py #!/usr/bin/env python3 # Write a program that computes typical stats # Count, Min, Max, Mean, Std. Dev, Median # No, you cannot import the stats library! import sys import math #args = [float(x) for x in sys.argv[1:]] #print(args) args = [] for x in sys.argv[1:]: args.append(float(x)) print(...
StarcoderdataPython
70649
import sys import numpy as np from cv2 import BRISK_create from cv2.xfeatures2d import FREAK_create from numpy import histogramdd from skimage.color import rgb2lab, rgb2hsv from skimage.feature import local_binary_pattern, greycoprops, greycomatrix from sklearn.base import TransformerMixin from sklearn.cluster import ...
StarcoderdataPython
3397665
import pytest @pytest.fixture def other(): assert 0 def test_setup_fails(something, other): pass def test_call_fails(something): assert 1 def test_fail2(): assert 1
StarcoderdataPython
1758209
<filename>utilities.py import torch import scipy.io import h5py import csv import operator import itertools import numpy as np import torch.nn as nn import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib.gridspec import SubplotSpec from matplotlib.ticker import MaxNLocator from functools import reduce...
StarcoderdataPython
34877
<filename>backend/tests/test_response.py """ Not tested as they seemed obvious: - "SleepTime": 31045, // Total amount of time sleeping including nocturnal awakenings (sleepOffset - sleepOnset) - "WASO": 3932, // Total amount of time passed in nocturnal awakenings. It is the total time passed in non-wake stage ...
StarcoderdataPython
69270
# -*- coding: utf-8 -*- import torch # Internal imports from .flow import Flow from .layers import Conv2dZeros, GaussianDiag class ReverseFlow(Flow): """ Reverse flow layer as defined in Density estimation using Real NVP - Dinh et al. (2016) (https://arxiv.org/pdf/1605.08803). """ def __init...
StarcoderdataPython
3356861
<filename>word_vectorizer/exceptions/__init__.py """Exceptions that can be launched when using this package""" from .not_existing_model_exception import NotExistingModelException from .not_known_technology_exception import NotKnownTechnologyException from .not_understood_url_exception import NotUnderstoodURLException f...
StarcoderdataPython
39170
<gh_stars>1-10 import tensorflow as tf import tensorflow.keras.backend as K from tensorflow.keras.models import Model from tensorflow.keras.layers import (Input, Dropout, BatchNormalization, Activation, Dense, Concatenate, Conv2D, Conv2DTrans...
StarcoderdataPython
191835
<reponame>taciturn-pachyderm/python-homegrown-tools from setuptools import setup, find_packages from os import getenv try: with open('requirements.txt') as r: requirements = r.readlines() except: requirements = [] try: from __package__ import * except: package_name = getenv("PACKAGE_N...
StarcoderdataPython
1741975
<filename>main.py from utils.args import get_args from tasks.common import run_task import time from datetime import timedelta def main(): # parse configuration args = get_args() # start timer start = time.time() # start of task run_task(args) # end of task # end timer end = tim...
StarcoderdataPython
10284
<gh_stars>0 #!/usr/bin/env python2.7 import unittest import canning class TestNop(unittest.TestCase): def test_nop(self): canning.NopTeeFd.write("asdf") class TestSlice(unittest.TestCase): REPORT = "20130505T065614Z-VN-AS24173-dns_consistency-no_report_id-0.1.0-probe.yaml" @staticmethod d...
StarcoderdataPython
1634290
from __future__ import absolute_import from __future__ import print_function import numpy as npy import random as random import matplotlib.pyplot as plt import time from nuts import nuts6, NutsSampler_fn_wrapper import hydra import autograd.numpy as np import autograd.numpy.random as npr from autograd import grad, ele...
StarcoderdataPython
3267457
# -*- coding: utf-8 -*- __author__ = '<NAME>' import numpy as np def log_nb_clusters_to_np_int_type(log_nb_clusters: int) -> type: # Considering that the cluster indices start from zero if log_nb_clusters <= 8: return np.uint8 elif log_nb_clusters <= 16: return np.uint16 elif log_nb_c...
StarcoderdataPython
104027
import loja_funcoes_auxiliares as aux def adicionar_produto_carrinho(estoque, carrinho): """ Adiciona um produto do estoque ao carrinho (se nao estiver adicionado ainda) :param estoque: lista com o estoque mais atualizado :param carrinho: lista com carrinho de compras mais atualizado :retu...
StarcoderdataPython
186555
<gh_stars>0 """ Stack some small standard size pcb 'modules' Stacking headers result in a spacing of ~12.8mm I have some 30x70x1.6mm PCBs with M2 corner holes, 66x26mm I want to put a connector at one end, so at the other end I need some support. """ from solid import * from solid.utils import * import util, body, ey...
StarcoderdataPython
3307123
<filename>pau/views/mixins.py import logging from django.http import HttpResponseRedirect from paucore.utils.web import smart_reverse from paucore.web.views import ViewMiddleware, EarlyReturn logger = logging.getLogger(__name__) class OAuthLoginRequiredViewMixin(ViewMiddleware): requires_auth = True def p...
StarcoderdataPython
57620
<reponame>egsui/stanCode_Projects """ File: anagram.py Name: <NAME> ---------------------------------- This program recursively finds all the anagram(s) for the word input by user and terminates when the input string matches the EXIT constant defined at line 19 If you correctly implement this program, you should see t...
StarcoderdataPython
175460
import urllib.request import json import time import os.path import sys import datetime import twitter def getJSONFromUrl(fetch_url): #Fetch json data from the url with urllib.request.urlopen(fetch_url, timeout=1) as url: data = json.loads(url.read().decode()) return data de...
StarcoderdataPython
3264712
import lab as B import matplotlib.pyplot as plt import neuralprocesses.torch as nps import stheno import torch from wbml.plot import tweak __all__ = ["visualise"] def visualise(model, gen, *, path, config, predict=nps.predict): """Plot the prediction for the first element of a batch.""" if config["dim_x"] ==...
StarcoderdataPython
1755293
import requests import pandas as pd import re import datetime as dt from bs4 import BeautifulSoup as bs # comprehend list for years years = [str(2000 + i) for i in range(5,19)] this_year = '2019' # print(years) # multiple functions for cleaning data # regex for finding round names pattern = re.compile("^(Round|Week|S...
StarcoderdataPython
94505
#converts the pixel bytes to binary def decToBin(dec): secret_bin = [] for i in dec: secret_bin.append(f'{i:08b}') return secret_bin #gets the last 2 LSB of each byte def get2LSB(secret_bin): last2 = [] for i in secret_bin: for j in i[6:8]: last2.append(j...
StarcoderdataPython