id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1755327
<gh_stars>1-10 # Copyright (C) 2017-2019 New York University, # University at Buffalo, # Illinois Institute of Technology. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obta...
StarcoderdataPython
3356402
<gh_stars>1-10 from rest_framework import serializers from rest_framework_gis import serializers from rest_framework.serializers import CharField from origin_destination_api.models import OriginDestination, ResidenceAreaCharacteristics, WorkplaceAreaCharacteristics, Xwalk class OriginDestinationSerializer(serializer...
StarcoderdataPython
1799836
<reponame>josuerojasq/netacad_python #El método "islower()" es una variante de "isalpha()" - solo acepta letras minúsculas. print("Moooo".islower()) print('moooo'.islower())
StarcoderdataPython
3237210
<reponame>dk107dk/cdocs<filename>setup.py import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="cdocs", version="0.0.38", author="<NAME>", author_email="<EMAIL>", description="Cdocs is a super simple contextual help library", long_descrip...
StarcoderdataPython
1761105
# $ pip install pypdf2 # http://note.mokuzine.net/python-pdf-split/ # https://docs.python.jp/3/library/pathlib.html # https://qiita.com/amowwee/items/e63b3610ea750f7dba1b # https://blanktar.jp/blog/2015/07/python-pathlib.html import pathlib from PyPDF2 import PdfFileWriter, PdfFileReader def main(): split('ap') ...
StarcoderdataPython
1794486
import hashlib import struct from collections import OrderedDict from typing import IO, Any, Optional, Iterable, Mapping, Dict, \ NamedTuple, ClassVar, TypeVar, Type from pymap.mailbox import MailboxSnapshot from .io import FileWriteable __all__ = ['Record', 'UidList'] _UDT = TypeVar('_UDT', bound='UidList') ...
StarcoderdataPython
4834770
<filename>sample.py<gh_stars>0 #!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np c = np.array([[1,2,3,4],[5,6,7,8],[9,8,7,6]],int) type(c) # In[2]: c # In[3]: c[1,1] # In[4]: c[2,3] # In[5]: c[2,0] # In[6]: k=c.reshape(4,3) # In[7]: k # In[8]: c.ndim # In[10]: c.shape ...
StarcoderdataPython
144683
import numpy as np import matplotlib.pyplot as plt from math import sqrt, copysign from scipy.optimize import brenth from scipy.optimize import fsolve,fmin_l_bfgs_b,fmin_cg,fminbound """ sign of the number """ def sign(x): if x==0: return 0 else: return copysign(1,x) """ if function f can't b...
StarcoderdataPython
3373620
<gh_stars>1-10 import io import pathlib import numpy as np import yaml from matplotlib import pyplot import functools import inspect import warnings def yaml_load(s: str): return yaml.load(s, Loader=yaml.BaseLoader) def yaml_dump(obj: any): return yaml.dump(obj, default_flow_style=False) def overlay_ima...
StarcoderdataPython
1723890
from germanium.static import * from germanium.locators import StaticElementLocator from behave import * from features.steps.asserts import * use_step_matcher("re") @step(u'I search using S for (?P<locator>.*)') def step_impl(context, locator): print("Search for locator: %s" % locator) S(locator).exists() ...
StarcoderdataPython
3342121
def is_associate_or_consultant_to_pipeline(user, pipeline): """Check if a user is an assocaite or consulant of a pipeline record. """ # if user no employee assigned, then not allowed employee = getattr(user, 'as_employee', None) if not employee: return False associate_id = pipeline....
StarcoderdataPython
195410
# MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # 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, ...
StarcoderdataPython
1653864
<gh_stars>1-10 from six import raise_from import numpy as np def assert_close(a, b, atol=1.e-8): try: assert np.allclose([a], [b], atol=atol) except AssertionError as e: raise_from(AssertionError('expected %s to be close to %s (atol=%s)' % (a, b, atol)), e) def assert_all_close(a, b, atol=1...
StarcoderdataPython
3336752
'''Defines the parameters we will use in the model''' from numpy import array, arange, concatenate, diag, linspace, ones, where, zeros from pandas import read_excel, read_csv from scipy.integrate import solve_ivp from model.preprocessing import ( make_aggregator, aggregate_contact_matrix, aggregate_vector_quan...
StarcoderdataPython
176047
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may ...
StarcoderdataPython
93792
def solution(A,B,K): count = 0 for i in range(A,B): if(i%K==0): count += 1 #print(count) return count solution(6,11,2)
StarcoderdataPython
1751444
import asyncio import json import pytest from aiohttp import web from aiovalidator import ( IntegerField, middleware_exception, validator_factory, abort) @asyncio.coroutine def foo_validator_async(value): return value * 2 def foo_default_async(value): @asyncio.coroutine def default(): ...
StarcoderdataPython
125315
from countryinfo import countries import json from urllib.parse import quote,unquote import requests from time import sleep from bs4 import BeautifulSoup import re def recode_countryinfo(): """some entres are utf-encoded - to clean that you can use this code... Result is stored in data.json, so you can copy d...
StarcoderdataPython
45213
# Based on: https://towardsdatascience.com/clustering-the-us-population-observation-weighted-k-means-f4d58b370002 import random import numpy as np import scipy.spatial def distance(p1,p2): return np.linalg.norm(p1,p2) def cluster_centroids(data,weights, clusters, k): results=[] for i in range(k): results....
StarcoderdataPython
25873
<filename>score/models.py<gh_stars>1-10 from django.db import models from django.contrib.auth.models import User from solo.models import SingletonModel class Division(models.Model): nom = models.CharField(max_length=30) def __str__(self): return self.nom class Equipe(models.Model): nom = models...
StarcoderdataPython
3397516
<reponame>coveooss/coveo-python-oss<filename>coveo-systools/coveo_systools/streams.py import re # 7-bit and 8-bit C1 ANSI sequences (note: this is a bytes regex, not str) # We use this to filter out ANSI codes from console outputs # Source: https://stackoverflow.com/a/14693789/1741414 ANSI_ESCAPE_8BIT = re.compile( ...
StarcoderdataPython
3254737
<reponame>hkotaro1215/invest """GLOBIO InVEST Model.""" from __future__ import absolute_import import os import logging import collections import csv import uuid from osgeo import gdal from osgeo import ogr from osgeo import osr import numpy import natcap.invest.pygeoprocessing_0_3_3 from . import utils from . import...
StarcoderdataPython
1659152
import os PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) SECRET_KEY = "pm=6+$d7--sl1rpmu7x*(72(=le!4lp-v-8tv993(+$7ak((&amp;x" MANAGERS = ADMINS = [] SITE_ID = 1 USE_I18N = True USE_L10N = True TIME_ZONE = "America/Chicago" LANGUAGE_CODE = "en-us" # These are for ...
StarcoderdataPython
168403
# -*- coding: utf-8 -*- """ feedjack <NAME> fjcloud.py """ import math from feedjack import fjlib from feedjack import fjcache def getsteps(levels, tagmax): """ Returns a list with the max number of posts per "tagcloud level" """ ntw = levels if ntw < 2: ntw = 2 steps = [(stp, 1 + (stp ...
StarcoderdataPython
1733055
from rest_framework import serializers from core.models.insurer import Insurer class InsurerSerializer(serializers.ModelSerializer): class Meta: model = Insurer fields = ('id', 'name', 'is_active')
StarcoderdataPython
1634938
# Copyright (c) Facebook, Inc. 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. #!/usr/bin/env python3 import numpy as np import unittest import faiss import tempfile import os import io import sys import warnings from mu...
StarcoderdataPython
1636980
import os import sys STRICTDOC_ROOT_PATH = os.path.abspath( os.path.join(__file__, "../../../../strictdoc") ) assert os.path.exists(STRICTDOC_ROOT_PATH), "does not exist: {}".format( STRICTDOC_ROOT_PATH ) sys.path.append(STRICTDOC_ROOT_PATH)
StarcoderdataPython
159493
<reponame>NiceCircuits/pcbLibraryManager<filename>src/pcbLibraryManager/footprints/footprintSmdQuad.py # -*- coding: utf-8 -*- """ Created on Mon Aug 3 06:52:50 2015 @author: piotr at nicecircuits.com """ from libraryManager.footprint import footprint from libraryManager.footprintPrimitive import * from libraryManag...
StarcoderdataPython
3337593
mff_auto = "0.9.5" mff = "7.5.1" updater = "1.1.0"
StarcoderdataPython
77215
import torch import torch.nn as nn # from torchsummary import summary # from lib.medzoo.BaseModelClass import BaseModel """ Implementation od DenseVoxelNet based on https://arxiv.org/abs/1708.00573 Hyperparameters used: batch size = 3 weight decay = 0.0005 momentum = 0.9 lr = 0.05 """ def init_weights(m): """ ...
StarcoderdataPython
20431
# -*- test-case-name: vumi.blinkenlights.tests.test_metrics_workers -*- import time import random import hashlib from datetime import datetime from twisted.python import log from twisted.internet.defer import inlineCallbacks, Deferred from twisted.internet import reactor from twisted.internet.task import LoopingCall ...
StarcoderdataPython
140233
<reponame>knownstranger03/Human_Pose_Estimation from keras.preprocessing.image import ImageDataGenerator import numpy as np, pandas as pd, sklearn from sklearn.preprocessing import OneHotEncoder from sklearn.model_selection import train_test_split def prep(): generator=ImageDataGenerator(validation_split=0.10) ...
StarcoderdataPython
3315578
<gh_stars>10-100 from __future__ import print_function import unittest import numpy as np import sqaod as sq import sqaod.common as common from .example_problems import * class TestDenseGraphFormulasBase : def __init__(self, pkg, dtype) : self.pkg = pkg self.dtype = dtype self.epu = 1.e-6...
StarcoderdataPython
1658608
from pandas import DataFrame, Series def set_value_where(data, columns, value, where): """ :type data: DataFrame :type columns: str :type where: Series :rtype: DataFrame """ data.set_value(index=data[where].index, col=columns, value=value) return data
StarcoderdataPython
3263970
import os import asyncio from PIL import Image from concurrent.futures import ThreadPoolExecutor from hoshino import Service, priv from hoshino.typing import HoshinoBot, CQEvent, MessageSegment, CommandSession from hoshino.util import FreqLimiter, DailyNumberLimiter, pic2b64 from .src.generator import genImage from ....
StarcoderdataPython
3261317
<filename>benchmarks/digis/lamp/driver/lifx.py from digi import logger from lifxlan import LifxLAN def put(dev, power, color): # TBD: in a single call dev.set_power(power) dev.set_color(color) def get(dev, retry=3): for _ in range(retry): try: status = { "power": ...
StarcoderdataPython
4814561
# coding: utf-8 """ NamSor API v2 NamSor API v2 : enpoints to process personal names (gender, cultural origin or ethnicity) in all alphabets or languages. Use GET methods for small tests, but prefer POST methods for higher throughput (batch processing of up to 100 names at a time). Need something you can't fi...
StarcoderdataPython
3385867
<filename>TextCNN/config.py import torch class Config(object): """Base configuration class.""" #训练文件夹位置 train_dir = "data/train" #评估文件夹位置 eval_dir = "data/eval" #模型的保存位置 save_path='model/' #是否使用gpu cuda = True #训练的epoch epochs = 2 batch_size = 64 #学习率 learning_ra...
StarcoderdataPython
122827
<filename>scripts/framework-applications/export-framework-applicant-details.py #!/usr/bin/env python """Export supplier "about you" information for suppliers who applied to a framework. This report includes registered company information and contact details. Usage: scripts/framework-applications/export-framewor...
StarcoderdataPython
4826822
########################################################################## # # Copyright (c) 2008, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistribu...
StarcoderdataPython
1614350
from django.urls import path from .views import (GenPubAddrView, TorrentFileView, BypassPaymentReceivedView, PaymentReceivedView, Pdp2ActivationStatusView, TorrentFileInfoView, PaymentView, PubAddrsListView, SendPdp2Data, ChangePubKey, WalletNotificationView, BlockNotificationVi...
StarcoderdataPython
3386737
<reponame>duskforge/nodzz """Configuration management tools. While ``nodzz`` have the instruments to implement, manage and configure any behavior tree via pure Python API, this is of course not the most convenient way to manage behavior trees based projects. ``nodzz`` provides config based behavior tree management too...
StarcoderdataPython
1676571
<filename>smooth_rf/tests/test_pytorch_prep.py import numpy as np import pandas as pd import scipy.sparse import sparse import sklearn from sklearn.ensemble import RandomForestRegressor from collections import Counter import sys, os import smooth_rf def test_create_Gamma_eta_tree_more_regression(): """ test f...
StarcoderdataPython
4818965
<filename>omfgene.py #!/usr/bin/env python """ omfgene.py Queries Snaptron's discordex for evidence of gene fusions across TCGA. Reports incidence of fusion at a given evidence level. """
StarcoderdataPython
75746
<gh_stars>100-1000 #!/usr/bin/env python # # BSD LICENSE # # Copyright(c) 2010-2014 Intel Corporation. All rights reserved. # Copyright(c) 2017 Cavium, Inc. All rights reserved. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provi...
StarcoderdataPython
76394
# Copyright (c) 2021 The Ensaio Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause # # This code is part of the Fatiando a Terra project (https://www.fatiando.org) # # Import functions/classes to make the public API from ._fetchers import ( fetch_alps_gps,...
StarcoderdataPython
3388600
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2019-03-18 15:46 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('variableServer', '0003_auto_20180710_1657'), ] operations = [ m...
StarcoderdataPython
4819094
<reponame>NyanKiyoshi/CryptoPaste<filename>cryptopaste/utils.py<gh_stars>1-10 # -*- coding: utf-8 -*- # ==== CryptoPaste # AUTHOR: NyanKiyoshi # COPYRIGHT: 2015 - NyanKiyoshi # URL: https://github.com/NyanKiyoshi/CryptoPaste/ # LICENSE: https://github.com/NyanKiyoshi/CryptoPaste/master/LICENSE # # This file is part of ...
StarcoderdataPython
1773041
import gym import sonnet as snt import tensorflow as tf import numpy as np from ray.rllib.models.tf.tf_modelv2 import TFModelV2 def build_logits(action_space, latent_vec): if isinstance(action_space, gym.spaces.Discrete): return snt.Linear(output_size=action_space.n, initializers...
StarcoderdataPython
1619717
#!/usr/bin/python # testdoc.py [-d] [-r] file import sys import os, os.path import doctest import warnings from doctest_tools import setpath debug = False warnings.simplefilter('default') def import_module(modulepath, remove_first_path = False, full = True): r"""Imports the module indicated by modulepath. ...
StarcoderdataPython
1759697
#import matplotlib.pyplot as plt def append_history(history, h): ''' This function appends the statistics over epochs ''' try: history.history['loss'] = history.history['loss'] + h.history['loss'] history.history['val_loss'] = history.history['val_loss'] + h.history['val_loss'] his...
StarcoderdataPython
1723519
<reponame>malja/check_miner<filename>check_miner.py import requests import psutil import dns.resolver import smtplib from threading import Timer import subprocess from datetime import datetime PROCESS_NAME = "EthDcrMiner64.exe" MINER_ADDRESS = "" PATH_TO_EXECUTABLE = "" INTERVAL = 60*60 EMAIL_FROM = "" EMAIL_TO = "" ...
StarcoderdataPython
194853
# -*- coding: utf-8 -*- import django from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.http import HttpResponse import django.views.static import example.testapp.views admin.autodiscover() def handle404(request): return HttpResponse('404') de...
StarcoderdataPython
51776
#!/usr/bin/env python3 import os import sys import json import configparser import logging import logging.config import traceback # install required package if in docker if os.geteuid() == 0: import pkgutil import subprocess required_pkgs = ["pytz"] for pkg in required_pkgs: if not pkgutil.fin...
StarcoderdataPython
111175
<filename>components/Actuators/HighLevel/turretCalibrate.py from magicbot import StateMachine, feedback, state from rev import SparkMaxLimitSwitch from components.Actuators.LowLevel.turretThreshold import TurretThreshold from networktables import NetworkTables as networktable class CalibrateTurret(StateMachine): c...
StarcoderdataPython
3361987
<gh_stars>0 #referred https://github.com/mammothb/symspellpy import os from collections import Counter from symspellpy.symspellpy import SymSpell, Verbosity # import the module import pickle as pkl def read_qspell(): file='../corpus-webis-qspell-17.csv' data=[] valid=[] lens=[] with open(file) as...
StarcoderdataPython
67762
# -*- coding: utf-8 -*- """USN change journal records.""" import os from dtformats import data_format class USNRecords(data_format.BinaryDataFile): """USN change journal records.""" # Using a class constant significantly speeds up the time required to load # the dtFabric definition file. _FABRIC = data_for...
StarcoderdataPython
3228885
<gh_stars>0 import os import os.path import pyndows from pyndows.testing import samba_mock, SMBConnectionMock class DateTimeMock: @staticmethod def utcnow(): class UTCDateTimeMock: @staticmethod def isoformat(): return "2018-10-11T15:05:05.663979" retu...
StarcoderdataPython
1622704
<reponame>cyphyhouse/KoordLanguage from src.harness.agentThread import AgentThread class Task: def __init__(self): self.loc = None self.assignId = None self.taskId = None class DefaultName(AgentThread): def __init__(self, config, motion_config): super(DefaultName, self).__...
StarcoderdataPython
1658511
""" Migration script to add the post_job_action_association table. """ import logging from sqlalchemy import ( Column, ForeignKey, Integer, MetaData, Table, ) from galaxy.model.migrate.versions.util import ( create_table, drop_table, ) log = logging.getLogger(__name__) metadata = MetaDat...
StarcoderdataPython
1743577
<reponame>cys3c/viper-shell #!/usr/bin/python #import commands #import shutil import socket import subprocess import os import platform import sys # In the transfer function, we first check if the file exists in the first place, if not we will notify the attacker # otherwise, we will create a loop where each time we ...
StarcoderdataPython
3226972
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2015, Ansible Project # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
StarcoderdataPython
1705684
#------------------------------------------------------------------------------# # Copyright 2018 <NAME>. All rights reserved. Use of this source # # code is governed by a MIT license that can be found in the LICENSE file. # #------------------------------------------------------------------------------# """ bet...
StarcoderdataPython
3276322
<filename>tests/conftest.py import pytest from pytest_factoryboy import register from wagtail.core.models import Site from .factories import BlogPageFactory register(BlogPageFactory) @pytest.fixture def home(): # Root page is created by Wagtail migrations. return Site.objects.first().root_page
StarcoderdataPython
3318665
<reponame>APrioriInvestments/typed_python # Copyright 2017-2019 typed_python Authors # # 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...
StarcoderdataPython
4835056
<gh_stars>10-100 #!/usr/bin/python import logging logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy.all import * if len(sys.argv) != 2: print "Usage - ./pinger.py [filename]" print "Example - ./pinger.py iplist.txt" print "Example will perform an ICMP ping scan of the IP addresses listed in ipl...
StarcoderdataPython
1799043
from datetime import datetime from capslock import run_multiple_times @run_multiple_times(times=10) def current_time(): now = datetime.now() return now.strftime("%H:%M:%S.%f") if __name__ == '__main__': print(current_time())
StarcoderdataPython
158813
from time import sleep from common.servicechain.config import ConfigSvcChain from common.servicechain.verify import VerifySvcChain from common.servicechain.mirror.verify import VerifySvcMirror from common.servicechain.mirror.config import ConfigSvcMirror from tcutils.util import get_random_cidr from tcutils.util import...
StarcoderdataPython
3292857
from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from django.conf import settings from .models import Profile __all__ = ( 'create_user_profile', 'save_user_profile', ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_user_profile(sender, instan...
StarcoderdataPython
32830
<reponame>fengjixuchui/scapula<filename>scapula/transform/encoded_rt_to_r9.py import shoulder class EncodedRtToR9(shoulder.transform.abstract_transform.AbstractTransform): @property def description(self): d = "changing src/dest register for encoded accessors from r0 to r9" return d def do...
StarcoderdataPython
1733634
from pathlib import Path from tqdm import tqdm import tensorflow as tf from modules.esrgan import rrdb_net from modules.lr_scheduler import MultiStepLR from modules.data import load_dataset from modules.losses import get_pixel_loss HAS_WANDB_ACCOUNT = True PROJECT = 'esrgan-tf2' import wandb if not HAS_WAND...
StarcoderdataPython
3384715
<filename>code/FeatureExtractionMode/BOW/BOW4vec.py from .kmer_bow import km_bow from .mismatch_bow import mismatch_bow from .subsequence_bow import subsequence_bow from .tng_bow import tng_bow from .dr_bow import dr_bow from .dt_bow import dt_bow from ..utils.utils_write import vectors2files from ..utils.utils_const i...
StarcoderdataPython
1722509
<gh_stars>0 #Generate Fibonacci series of N terms n=int(input("Enter The Limit:")) f=0 s=1 if n<=0: print("The requested series is",f) else: print(f) print(s) for x in range(2,n): next=f+s print(next)...
StarcoderdataPython
1624667
<gh_stars>10-100 import tvm import sys from .schedule_state import RealScheduleState from .utils import tile_axes, reorder_spatial_and_reduce_axes, get_need_tile, get_factors from ..utils import ERROR, ASSERT, to_int, REFUSE def schedule_cuda_allreduce(op, op_to_id, op_to_state, sch, tensors, subgraph, multi_entity, ...
StarcoderdataPython
35909
# -*- coding: utf-8 -*- # Copyright 2015 Mirantis, 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 requir...
StarcoderdataPython
3340340
#! /usr/bin/python3 # -*- coding: utf-8 -*- __author__ = '<NAME>' __copyright__ = 'Copyright 2020, cmspy' __credits__ = ['<NAME>'] __maintainer__ = 'Alan' __email__ = '<EMAIL>' __status__ = 'Production' __all__ = [ 'to_skycoord', 'radec2lmn' ] import numpy as np from astropy.coordinates import ( SkyCoor...
StarcoderdataPython
48953
<reponame>WatsonWangZh/CodingPractice # There are n cities connected by m flights. # Each flight starts from city u and arrives at v with a price w. # Now given all the cities and flights, # together with starting city src and the destination dst, # your task is to find the cheapest price from src to dst with up to ...
StarcoderdataPython
15782
#!/usr/bin/env python import rospy from geometry_msgs.msg import Twist, TransformStamped from std_msgs.msg import String from enum import Enum import tf2_ros import math class mission_states(Enum): STOP = -1 SUBMERGE = 0 MOVE_TO_GATE = 1 MOVE_THROUGH_GATE = 2 def checkTolerance(current, wanted): t...
StarcoderdataPython
11193
<reponame>hurschler/pig-face-recognition import logging.config import util.logger_init import numpy as np import tensorflow as tf from sklearn.metrics import confusion_matrix from util.tensorboard_util import plot_confusion_matrix, plot_to_image from tensorflow.python.keras.callbacks_v1 import TensorBoard from keras im...
StarcoderdataPython
1634431
<gh_stars>1-10 import string def ceaser(plaintext, shift, mode='encode'): ''' Ceaser cipher encoder and decoder. :param plaintext: bytes :param shift: int, Number of characters to shift by. :param mode: 'encode' from plain to cipher, 'decode' from cipher to plain. :return: bytes ''' if...
StarcoderdataPython
3258568
<filename>bioprocs/tabix.py from pyppl import Proc, Box #from .utils import helpers, runcmd from . import params """ @name: pTabix @description: Use tabix to extract information. @input: `infile`: a local or remote file `region`: a region or a file containing regions @output: `outfile:file`: The information extra...
StarcoderdataPython
4840406
<filename>vinplots/_style/__init__.py<gh_stars>0 from ._funcs._modify_axis_spines import _modify_axis_spines as modify_spines
StarcoderdataPython
1676752
""" The API basically only provides one class. You can create a :class:`Script` and use its methods. Additionally you can add a debug function with :func:`set_debug_function`. Alternatively, if you don't need a custom function and are happy with printing debug messages to stdout, simply call :func:`set_debug_function`...
StarcoderdataPython
1671766
<filename>src/sage/geometry/polyhedron/face.py """ A class to keep information about faces of a polyhedron This module gives you a tool to work with the faces of a polyhedron and their relative position. First, you need to find the faces. To get the faces in a particular dimension, use the :meth:`~sage.geometry.polyhe...
StarcoderdataPython
3384308
""" PageFactory uses the factory design pattern. get_page_object() returns the appropriate page object. Add elif clauses as and when you implement new pages. Pages implemented so far: 1. Temperature main page 2. Moisturizer page 3. Sunscreens Page 4. Cart Page 5. Payment Gateway Page """ from page_objects.temperature...
StarcoderdataPython
3234077
<gh_stars>1-10 ################################################################################################################ # # Copyright 2022 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 ...
StarcoderdataPython
3252750
from dataclasses import dataclass from typing import Optional import numpy as np import pandas as pd from .meta import GRMMeta @dataclass() class GRMInputs: meta: GRMMeta response_array: np.ndarray level_array: Optional[np.ndarray] = None @classmethod def from_df(cls, response_d...
StarcoderdataPython
3326413
<reponame>mullzhang/genqubo import numpy as np import numpy.random from dimod.binary_quadratic_model import BinaryQuadraticModel from dimod.decorators import graph_argument @graph_argument('graph') def normal(graph, vartype, loc=0.0, scale=1.0, cls=BinaryQuadraticModel, seed=None, zero_lbias=False): "...
StarcoderdataPython
88005
import csv import os import pcbnew import re import wx from decimal import Decimal, getcontext from pathlib import Path ref_ignore = ["TP", "T", "NT", "REF**", "G", "H"] # original rotation db from: # https://github.com/matthewlai/JLCKicadTools/blob/master/jlc_kicad_tools/cpl_rotations_db.csv rotations = { "^SOT-...
StarcoderdataPython
3278470
import re from rest_framework import generics from rest_framework import permissions from rest_framework import exceptions from rest_framework import status from rest_framework.response import Response from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User from django.db.models imp...
StarcoderdataPython
1707876
#!/usr/bin/env python import s3dict import unittest import os import sys class TestS3Dict(unittest.TestCase): def setUp(self): self.basedir = os.path.dirname(__file__) def testRead(self): foodict = s3dict.open(os.path.join(self.basedir, "test", "foo.dict")) self.assert_('AH' in foodic...
StarcoderdataPython
3338561
<gh_stars>0 import timeit from datetime import datetime import socket import os import glob from tqdm import tqdm import numpy as np import matplotlib.pyplot as plt import torch from tensorboardX import SummaryWriter from torch import nn, optim from torch.utils.data import DataLoader from torch.autograd import Variable...
StarcoderdataPython
80145
<reponame>Mr-TelegramBot/python-tdlib from ..factory import Type class chatReportReasonViolence(Type): pass
StarcoderdataPython
3353351
<reponame>Kaushal-Dhungel/djangocms-icon from django import forms from .fields import IconField from .models import Icon class IconForm(forms.ModelForm): icon = IconField(required=True) class Meta: model = Icon fields = ('label', 'icon', 'template', 'attributes',)
StarcoderdataPython
3383551
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
StarcoderdataPython
1772542
# -*- coding: utf-8 -*- import logging from dbaas_credentials.models import CredentialType from util import get_credentials_for from util import full_stack from dbaas_cloudstack.models import HostAttr from dbaas_cloudstack.models import DatabaseInfraAttr from dbaas_cloudstack.provider import CloudStackProvider from wor...
StarcoderdataPython
3362757
<reponame>xiaoandx/learningCode # 创建一个保存满足水仙花数的列表 numberList = list(); # 循环判断每个数是否满足 for number in range(100, 1000, 1): a = number // 100; b = (number // 10) % 10; c = (number % 100) % 10; if a ** 3 + b ** 3 + c ** 3 == number: numberList.append(number); # 按照格式输出满足的数 print("所有的3位水仙花数:", end=" ...
StarcoderdataPython
34267
<gh_stars>1-10 # Credits to https://stackoverflow.com/a/56944256/9470078 # I wanted a colored logger without dependencies, so here it is! import logging class ColoredFormatter(logging.Formatter): grey = "\x1b[38;20m" yellow = "\x1b[33;20m" red = "\x1b[31;20m" blue = "\x1b[34;20m" bold_red = "\x1b[...
StarcoderdataPython
4814526
<filename>fastapi_sessions/backends/session_backend.py<gh_stars>10-100 """Generic backend code.""" from abc import ABC, abstractmethod from typing import Generic, Optional, TypeVar from fastapi_sessions.frontends.session_frontend import ID from pydantic.main import BaseModel SessionModel = TypeVar("SessionModel", bou...
StarcoderdataPython
3297232
<reponame>vijaykumawat256/Prompt-Summarization def two_decimal_places(n):
StarcoderdataPython