id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
12809052
<reponame>hemo650/Ezy-Sort from .runner import ColourTextTestRunner class ColourRunnerMixin(object): test_runner = ColourTextTestRunner def __init__(self, *args, **kwargs): self.no_colour = kwargs.get('no_color', False) super(ColourRunnerMixin, self).__init__(*args, **kwargs) def run_sui...
StarcoderdataPython
5145754
"""Extract/pre-process data.""" import pandas as pd import logging log = logging.getLogger(__name__) class PreProcess(): """Preprocess data.""" def __init__(self): self.frame = pd.DataFrame() def csv_to_df(self, file): """ Set the dict to a dataframe. Args: ----...
StarcoderdataPython
1791985
#!/usr/bin/env python3 # ================== i18n.py ===================== # It localizes website elements. # Hook type: pre_build (modifies config file) # Configuration: # Create a i18n.yaml file in your project root. Look at i18n.yaml and i18n.example.yaml # to get a feel for the structure. # Add the correct id to...
StarcoderdataPython
1971165
<reponame>ulikoehler/ODBPy<filename>ODBPy/Profile.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Parser for the ODB++ PCB profile file """ import os.path from collections import namedtuple from .LineRecordParser import * from .SurfaceParser import * from .PolygonParser import * from .Decoder import * from .Treei...
StarcoderdataPython
6416740
import re import warnings from optparse import make_option from django.core.management.commands.inspectdb import Command as InspectDBCommand from django.db import connections, DEFAULT_DB_ALIAS from salesforce.backend import introspection as sf_introspection import django import salesforce class Command(InspectDBComman...
StarcoderdataPython
6697269
<reponame>sosolidkk/manga-unifier<gh_stars>1-10 from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.reverse import reverse from rest_framework.test import APIClient, APITransactionTestCase from tests.factories.user import UserFactory class CreateTokenForUserTest(API...
StarcoderdataPython
1820000
<filename>src/const_performance.py # -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <codecell> #!/usr/bin/env python # #The MIT CorrelX Correlator # #https://github.com/MITHaystack/CorrelX #Contact: <EMAIL> #Project leads: <NAME>, <NAME> Project developer: <NAME> # #Copyright 2017 MIT Haystack Observatory # #Perm...
StarcoderdataPython
4971403
import unittest import zserio from testutils import getZserioApi class OptionalBit31RangeCheckTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.api = getZserioApi(__file__, "with_range_check_code.zs", extraArgs=["-withRangeCheckCode"]).optional_bit31_range_c...
StarcoderdataPython
5155944
<filename>BOJ/19000~19999/19600~19699/19504.py X=[] Y=[] for i in range(int(input())): a,b=map(int,input().split(',')) X.append(a) Y.append(b) print(f"{min(X)-1},{min(Y)-1}") print(f"{max(X)+1},{max(Y)+1}")
StarcoderdataPython
114581
<gh_stars>1-10 #!/usr/bin/env python #=========================================================================== # # DOWNLOAD aircraft data in IWG1 format # #=========================================================================== import os import sys from stat import * import time import datetime from datetime i...
StarcoderdataPython
371405
"""add an output_type field Revision ID: 5720713911df Revises: 10dea94d2dc1 Create Date: 2018-05-24 12:05:10.226540 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '5720713911df' down_revision = '10dea94d2dc1' branch_labels = None depends_on = None from sqlal...
StarcoderdataPython
1954975
<reponame>HelmchenLabSoftware/mesostat-dev<gh_stars>0 import pandas as pd import itertools ############################ # Display ############################ def pd_print_all(df): with pd.option_context('display.max_rows', None, 'display.max_columns', None): # more options can be specified also print(d...
StarcoderdataPython
145369
<filename>dev/mlsqltestssupport/aliyun/upload_release.py # -*- coding: utf-8 -*- import os import mlsqltestssupport.aliyun.config as config if not os.environ['MLSQL_RELEASE_TAR']: raise ValueError('MLSQL_RELEASE_TAR should be configured') fileName = os.environ['MLSQL_RELEASE_TAR'] bucket = config.ossClient() b...
StarcoderdataPython
1957621
<filename>flask_blog/api/views.py from flask import Blueprint, jsonify from flask_blog.auth.decorators import requires_basic_auth api = Blueprint('api', __name__) @api.route('/hello-world', methods=['GET']) @requires_basic_auth def login(): return jsonify({'message': 'Hello World!'})
StarcoderdataPython
3266463
#!/usr/bin/env python3 import sys import argparse from Bio import SeqIO from gffpal.gff import GFFRecord, Strand from gffpal.attributes import GFFAttributes def cli(prog, args): parser = argparse.ArgumentParser( prog=prog, description=""" Converts a tab-separated blast-like file to a GFF3. ...
StarcoderdataPython
11245151
from math import sin, cos, tan, atan, sqrt, radians imgw = 1920 imgh = 1080 a = radians(42.5) # camera vertical view angle +/-3 b = radians(69.4) # camera horizontal view angle +/-3 aGAO = radians(39) # camera optical angle (to z-axis) AO = 80 # distance from camera to ground CO = tan(aGAO - a/2)*AO AC = sqrt(AO*AO...
StarcoderdataPython
9730253
from django.contrib.messages.views import SuccessMessageMixin from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from django.views import generic from braces.views import LoginRequiredMixin from .forms import FeedbackForm from .models import Feedback class FeedbackCreate(LoginRe...
StarcoderdataPython
3538639
# coding: utf-8 import sys #from AppTestStringObjectWithDict def test_format_item_dict(): d = {'i': 23} assert 'a23b' == 'a%(i)sb' % d assert '23b' == '%(i)sb' % d assert 'a23' == 'a%(i)s' % d assert '23' == '%(i)s' % d def test_format_two_items(): d = {'i': 23, 'j': 42} assert 'a23b42c' =...
StarcoderdataPython
3574640
import json from typing import Optional import PySide6.QtWidgets from PySide6 import QtWidgets, QtCore, QtGui from PySide6.QtCore import SIGNAL, QPoint from PySide6.QtGui import QStandardItemModel, QStandardItem, QIcon from PySide6.QtWidgets import QLineEdit, QFormLayout, QPushButton, QHBoxLayout, QListView import sr...
StarcoderdataPython
11273479
# Copyright 2019 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
StarcoderdataPython
11214059
<filename>twitchAPI/types.py # Copyright (c) 2020. Lena "Teekeks" During <<EMAIL>> from enum import Enum class AnalyticsReportType(Enum): """Enum of all Analytics report types :var V1: :var V2: """ V1 = 'overview_v1' V2 = 'overview_v2' class AuthScope(Enum): """Enum of Authentication ...
StarcoderdataPython
1712761
<filename>mc/bookmarks/bookmarksexport/HtmlExporter.py<gh_stars>1-10 from .BookmarksExporter import BookmarksExporter from PyQt5.Qt import QDir from mc.common.globalvars import gVar from ..BookmarkItem import BookmarkItem from traceback import print_exc class HtmlExporter(BookmarksExporter): def __init__(self, par...
StarcoderdataPython
1809194
# Copyright 2017-2020 The GPflow Contributors. 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 appli...
StarcoderdataPython
8047414
<gh_stars>0 def solution(n): result = '' while n > 0: n, mod = divmod(n, 3) if mod == 0: n -= 1 mod = 3 result += str(mod) result = result.replace('3', '4') return result[::-1]
StarcoderdataPython
6480045
<reponame>Seniorcaptain/Scraper<filename>main.py<gh_stars>0 # import what we need import pandas as pd import requests_html session = requests_html.HTMLSession() # use session to get the page r = session.get('https://kenyanwallstreet.com/') r = session.get('https://www.businessdailyafrica.com/') # r =session.get(' htt...
StarcoderdataPython
3554897
<reponame>SGC-Tlaxcala/cerebro # Generated by Django 3.2.5 on 2021-07-24 00:46 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('productividad', '0007_auto_20190613_1548'), ] operations = [ migrations.Crea...
StarcoderdataPython
4996450
from django.forms import ModelForm from .models import * class TagForm(ModelForm): class Meta: model = Tag fields = '__all__' class CorpusForm(ModelForm): class Meta: model = Corpus fields = '__all__' class ArticleForm(ModelForm): class Meta: model = Article ...
StarcoderdataPython
1927441
BINARY_FNAME_TEMPLATE = "{version}-{platform}-{architecture}"
StarcoderdataPython
4894721
from flask_login import UserMixin from app.db_instance import db class UserProfile(db.Model): user_id = db.Column(db.String(36), primary_key=True) role_id = db.Column(db.Integer, unique=False, nullable=False) department_id = db.Column(db.Integer, unique=False, nullable=False) # Nullables: first_...
StarcoderdataPython
11228910
<filename>In Class Projects/In Class Examples Spring 2019/Section 8/schoolCountyDoubleIndexInClass.py import pandas as pd import os import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages data = pd.read_csv("schoolDataRealExpenditures.csv", index_col = ["County","Year"]...
StarcoderdataPython
1781393
<gh_stars>0 from __future__ import print_function from future.standard_library import install_aliases install_aliases() from urllib.parse import urlparse, urlencode from urllib.request import urlopen, Request from urllib.error import HTTPError import json import os import wolframalpha import wikipedia i...
StarcoderdataPython
11335460
<gh_stars>0 key_to_command = { "w": b"\x01", "s": b"\x02", "a": b"\x03", "d": b"\x04", "turbo_on": b"\x05", "turbo_off": b"\x06", "f": b"\x07", } command_to_key = {v: k for k, v in key_to_command.items()}
StarcoderdataPython
8025290
<gh_stars>1-10 """This module implements a distributed database as an example usage of the piChain package. It's a key-value storage that can handle keys and values that are arbitrary byte arrays. Supported operations are put(key,value), get(key) and delete(key). note: If you want to delete the local database and the ...
StarcoderdataPython
6530606
from scipy.constants import mu_0, epsilon_0 from . import TDEM from . import FDEM from . import NSEM from . import Static from . import Base from . import Analytics from . import Utils
StarcoderdataPython
4931234
#! /usr/bin/env python ## @file Pet_behaviours.py # @brief Pet state machine # # Details: This component handles the user interface of the project # ## Library declaration import rospy from std_srvs.srv import * import random ## Variable definition random_timer=0 # variable to make chronologically randomic the choic...
StarcoderdataPython
11277301
<reponame>euseand/RSS_Reader<gh_stars>0 import argparse import json from datetime import datetime from .rss_parser import RssParser current_version = 0.42 def main(): """ This function contains all utility features realisation :return: None """ parser = argparse.ArgumentParser(description='Brand ...
StarcoderdataPython
9688870
<gh_stars>1-10 from quo import echo, Console from quo.padding import Padding console = Console() test = Padding("Hello", (2, 4), style="on blue", expand=False) console.echo(test, fg="red")
StarcoderdataPython
11374220
# encoding: utf-8 """ @author: <NAME> @time: 2021/06/20 14:49 @desc: """ from networks.head.yolo_head import YoloHead from networks.head.rcnn_head.rcnn_head import RcnnHead head_dict = { 'yolohead': YoloHead, 'rcnnhead': RcnnHead, } def build_head(cfg): _cfg = cfg.copy() type_name = _cfg.pop('name')...
StarcoderdataPython
11262640
# Copyright (c) 2022 PaddlePaddle Authors. 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 appli...
StarcoderdataPython
1699892
<filename>teamcity-ldap-sync.py import argparse import json import requests import random from ldap3 import Server, Connection, SUBTREE, ALL try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse try: import configparser except ImportError: import ConfigParser as conf...
StarcoderdataPython
4992114
<filename>Python_Scripts_for_extracting_named_events/_main_.py """ @author: alex """ from load_wp_term_relationships import load_wp_term_relationships from load_wp_term_taxonomy_and_wp_terms import merge_wp_term_taxonomy_and_read_wp_terms from make_relationships_events import make_associations_between_dfs from make_lo...
StarcoderdataPython
6492153
<filename>tmp/even.py # -*- coding: utf-8 -*- # 回调函数1 # 生成一个2k形式的偶数 def double(x): return x * 2 # 回调函数2 # 生成一个4k形式的偶数 def quadruple(x): return x * 4
StarcoderdataPython
1974520
"""Test funsies cleaning.""" # std from signal import SIGKILL import time # funsies import funsies as f def test_cleanup() -> None: """Test truncation.""" # std import os def kill_self(*inp: bytes) -> bytes: pid = os.getpid() os.kill(pid, SIGKILL) time.sleep(2.0) retu...
StarcoderdataPython
9713075
""" Module containing the `~halotools.mock_observables.surface_density_in_annulus` and `~halotools.mock_observables.surface_density_in_cylinder` functions used to calculate galaxy-galaxy lensing. """ from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np from .mass_in_cy...
StarcoderdataPython
5148604
import os import sys import cppimport.config def check_contains_cppimport(filepath): with open(filepath, "r") as f: return "cppimport" in f.readline() def find_file_in_folders(filename, paths, opt_in): for d in paths: if not os.path.exists(d): continue if os.path.isfile...
StarcoderdataPython
9651248
<reponame>vmthunder/nova # Copyright 2013 Cloudbase Solutions Srl # 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/LI...
StarcoderdataPython
5128229
<gh_stars>10-100 #!/usr/bin/python # -*- coding: utf-8 -*- import httplib2 as http import httplib import re from urlparse import urlparse import pprint import urllib2 class streamscrobbler: def parse_headers(self, response): headers = {} int = 0 while True: line = response.read...
StarcoderdataPython
4837205
import cv2 import os import sys from string import Template # first argument is the haarcascades path face_cascade_path = sys.argv[1] face_cascade = cv2.CascadeClassifier(os.path.expanduser(face_cascade_path)) scale_factor = 1.1 min_neighbors = 3 min_size = (30, 30) flags = cv2.cv.CV_HAAR_SCALE_IMAGE for infname in ...
StarcoderdataPython
1853230
import sys input = sys.stdin.readline a, b = map(int, input().split()) if a == 1: a += 13 if b == 1: b += 13 if a > b: ans = "Alice" elif a == b: ans = "Draw" else: ans = "Bob" print(ans)
StarcoderdataPython
9656899
<reponame>tkettu/AdventOfCode2017<filename>milliseconds2/milliseconds21.py import sys def difference_bw_largest_adn_smallest(line): s = line.split() nums = [int(i) for i in s] ma, mi = max(nums), min(nums) return (ma - mi) def checksum(nums): cs = 0 while (True): line = nums.readlin...
StarcoderdataPython
3350510
import csv import time import datetime from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By begin_year = 1975 end_year ...
StarcoderdataPython
6619924
<gh_stars>0 from pyspark.mllib.tree import RandomForest from pyspark import SparkContext, SparkConf from pyspark.mllib.regression import LabeledPoint from pyspark.mllib.linalg import Vectors import logging import time, os, sys import re def union(line): predic = line[0] values = line[1] #if(predic == u'1.0...
StarcoderdataPython
1915053
#sort lst = [1,3,5,10,9,8,7,6,4,2] print ('sort={}'.format(lst.sort())) print ('sort={}'.format(lst)) #sorted lst = [1,3,5,10,9,8,7,6,4,2] print ('sorted={}'.format(sorted(lst))) print (lst)
StarcoderdataPython
11342572
import cx_Oracle from database_connections import password_encryption from database_connections.DatabaseConnection import DatabaseConnection def get_DatabaseConnection( **kwargs ): '''returns the class instance of the said object''' return Oracle( **kwargs ) class Oracle( DatabaseConnection ): '''To run...
StarcoderdataPython
6531943
<reponame>rscohn2/sensepy # SPDX-FileCopyrightText: 2020 <NAME> # # SPDX-License-Identifier: MIT import logging import sys import yaml from zignalz import cli logger = logging.getLogger(__name__) class Config: def __init__(self): self.data = None def sensor_name(self, device_id, sensor_id): ...
StarcoderdataPython
295150
"""Tests for user client API""" # pylint: disable=unused-argument import json import pytest def test_list_users(api_client): """Test list users for correct request""" resp = api_client.users.list() assert resp.status_code == 200 assert resp.json() == [{ "id": 39, "username": "01BQRHXR...
StarcoderdataPython
11392026
<filename>Software/lora_callback.py def lora_cb(lora): events = lora.events() if events & LoRa.RX_PACKET_EVENT: print('Lora packet received') data = s.recv(64) print(data) if events & LoRa.TX_PACKET_EVENT: print('Lora packet sent') lora.callback(trigger=(LoRa.RX_PACKET_EVENT...
StarcoderdataPython
5134508
# -*- coding: utf-8 -*- """ Created on Mon Jan 13 01:29:08 2020 @author: MMOHTASHIM """ import pickle import numpy from tensorflow import keras from tensorflow.keras.applications.mobilenet import MobileNet import argparse from tensorflow.keras.layers import Input from tensorflow.keras.models import Model import os f...
StarcoderdataPython
4847619
from aacharts.aaenum.AAEnum import * from aacharts.aaoptionsmodel.AAScrollablePlotArea import AAScrollablePlotArea from aacharts.aaoptionsmodel.AAStyle import AAStyle from aacharts.aaoptionsmodel.AAStyle import AAStyle from aacharts.aaenum.AAEnum import * from aacharts.aaoptionsmodel.AAYAxis import AAYAxis from aachart...
StarcoderdataPython
1681242
import os import sys import json from time import sleep from importlib import import_module from helper import bold_str, sprintf, cursorUpLines, setupFiles # Default configuration file dfltCfgFile = "config_dflt.py" # Import default configuration file. # Not using `import config_dflt` because of printing option (`net...
StarcoderdataPython
11248651
import os import json from datetime import datetime as dt from flask import request, send_file from werkzeug.utils import secure_filename from taky.dps import app def url_for(f_hash): """ Returns the URL for the given hash """ return f"{request.host_url}Marti/sync/content?hash={f_hash}" def get_me...
StarcoderdataPython
3568723
""" # rebotes.py # Ejercicio 1.5 @author: <NAME> """ # Ejercicio altura = 100 toca_piso = 1 rebota = (100*.6) #solicito que imprima al menos 10 veces los rebotes while toca_piso <= 10: print(round(rebota, ndigits=4)) toca_piso = toca_piso + 1 rebota = rebota * 0.6 """ resultado: 60.0 36.0 ...
StarcoderdataPython
6949
<filename>setup.py<gh_stars>1-10 import os, os.path import subprocess from distutils.core import setup from py2exe.build_exe import py2exe PROGRAM_NAME = 'icom_app' PROGRAM_DESC = 'simple icom app' NSIS_SCRIPT_TEMPLATE = r""" !define py2exeOutputDirectory '{output_dir}\' !define exe '{program_name}.exe' ...
StarcoderdataPython
4806263
<filename>client/python/easemlclient/easemlclient/model/type.py """ Implementation of the `ApiType` class. """ import requests from copy import deepcopy from enum import Enum from typing import Dict, Any, TypeVar, Generic, Optional, Tuple, List, Type from .core import Connection T = TypeVar('T', bound='ApiType') cl...
StarcoderdataPython
3541713
<gh_stars>0 ''' from math import hypot a = float(input('Digite o valor de um cateto: ')) b = float(input('Digite o valor de outro cateto: ')) print('A hipotenusa dos catetos {} e {} é igual a {:.2f}: '.format(a, b, hypot(a, b))) ''' # ou from math import sqrt a = float(input('Digite o valor de um cateto: ')) b = floa...
StarcoderdataPython
8104391
<reponame>mail2nsrajesh/networking-bagpipe # Copyright (c) 2016 Orange. # 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/licen...
StarcoderdataPython
1880364
from yargy import ( rule, or_, Parser, ) from yargy.pipelines import pipeline from yargy.predicates import ( type, in_, normalized, ) from yargy.interpretation import ( fact ) from natasha.grammars import date, addr from .helpers import select_span_tokens, ID_TOKENIZER, show_matches, TOKENIZER, load...
StarcoderdataPython
4842151
"""Shared constants for IPv4 and IPv6.""" # Protocol numbers - http://www.iana.org/assignments/protocol-numbers IP_PROTO_IP = 0 # dummy for IP IP_PROTO_HOPOPTS = IP_PROTO_IP # IPv6 hop-by-hop options IP_PROTO_ICMP = 1 # ICMP IP_PROTO_IGMP = 2 # IGMP IP_PROTO_GGP = 3 # gateway-gateway protocol IP_PROTO_IPIP = 4 #...
StarcoderdataPython
12815454
<filename>magi/agents/sac/config.py """Soft Actor-Critic agent parameters.""" import dataclasses from typing import Optional from acme import specs from acme.adders import reverb as adders_reverb import numpy as np def target_entropy_from_env_spec(env_spec: specs.EnvironmentSpec) -> float: """Compute the heurist...
StarcoderdataPython
3435258
''' Copyright (c) 2008 <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, copy, modify, merge, publish...
StarcoderdataPython
112680
# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. # # 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 applica...
StarcoderdataPython
5074789
import sys import json import os.path import datetime from dagon import batch from dagon import Workflow from dagon.docker_task import DockerTask # Check if this is the main if __name__ == '__main__': config={ "scratch_dir_base":"/tmp/test/", "remove_dir":False } # Create the orchestration workflow ...
StarcoderdataPython
6618877
if __name__ == '__main__': file = open('f2_l-d_kp_20_878.txt', 'r') linesfile = file.readlines() resulttoken0 = [] resulttoken1 = [] for x in linesfile: resulttoken0.append(int(x.split()[0])) resulttoken1.append(int(x.split()[1])) file.close() print('column 0 ( values )...
StarcoderdataPython
6446059
<filename>APP/TextSummarization/text_summarization.py #!/usr/bin/env python # -*- coding: UTF-8 -*- '''================================================= @IDE :PyCharm @Author :LuckyHuibo @Date :2019/10/16 22:35 @Desc : ==================================================''' if __name__ == "__main__": pass
StarcoderdataPython
9707957
<reponame>petchat/senz.dev.dashboard __author__ = 'heamon7' SECRET_KEY = 'this is senz dashboard'
StarcoderdataPython
1883880
def horas_dias(h): return h/24 x=float(input("Numero de Horas: ")) print(horas_dias(x))
StarcoderdataPython
11201498
import time from typing import Any, Callable, ClassVar, Dict, Optional, List from dataclasses import dataclass, field import pystan from stanpyro.dppl import PyroModel from stannumpyro.dppl import NumPyroModel from scipy.stats import entropy, ks_2samp import numpy as np from jax import numpy as jnp import jax.random ...
StarcoderdataPython
9617419
<gh_stars>0 import cv2 vidcap = cv2.VideoCapture('livevideo.mp4') success,image = vidcap.read() count = 0 success = True while success: success,image = vidcap.read() print('Read a new frame: ', success) if count % 50 == 0: cv2.imwrite("imgs/frame%d.jpg" % count, image) pass # save frame as JPEG file...
StarcoderdataPython
5029682
import copy from typing import Callable, Dict, List, Optional, Tuple from . import asciiart class Action: """ Generic action class for updating the game state. """ def __init__(self, fn: Callable[["QuarantineStatus"], Optional[str]]): self._fn: Callable[["QuarantineStatus"], Optional[str]] =...
StarcoderdataPython
169014
<filename>lcls_live/bmad/tools.py from lcls_live.klystron import Klystron, existing_LCLS_klystrons, unusable_faults from lcls_live import Collimator from math import isnan, sqrt import pandas def bmad_klystron_lines(klystron): ''' Form Bmad lines to set klystron overlays. ''' k = klystron kname ...
StarcoderdataPython
4955212
<gh_stars>0 #%% import argparse import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import os import numpy as np import json from torch import alpha_dropout import cv2 import torch import torchvision.transforms as transforms ###################DTDmax######################...
StarcoderdataPython
11319969
def validateStackSequences(pushed: list[int], popped: list[int]) -> bool: stack = [] popped = popped[::-1] for p in pushed: stack.append(p) while stack and popped and stack[-1] == popped[-1]: stack.pop() popped.pop() return len(popped) == 0
StarcoderdataPython
9771328
import pytest from symspellpy import Verbosity ENTRIES = ["baked", "ax", "lake", "", "slaked"] class TestSymSpellPyEdgeCases: @pytest.mark.parametrize("symspell_long_entry", [ENTRIES], indirect=True) def test_empty_string_has_all_short_deletes(self, symspell_long_entry): sym_spell, entries...
StarcoderdataPython
3254729
<gh_stars>1-10 import math with open("input.txt") as fp: matrix = [i.strip() for i in fp.readlines()] height = len(matrix) width = len(matrix[0]) row = 0 col = 0 def findTrees(matrix, height, width, row, col, rowJump, colJump): trees = 0 while row < height and col <= width: if matrix[row][col]...
StarcoderdataPython
11298044
<filename>contrib/Research/nlp/bert/BERT_tf_Soapeggpain/script/e2e_func_node/tools/performance/performanceAnalysis/drawexcel.py # -*- coding: UTF-8 -*- import os import xlsxwriter import numpy as np """ draw excel picture """ EXCEL_FILE = None EXCEL_SHEET = None DEFAULT_COL_LEN = 12 FIRST_ROW_NUM = 0 DATA_START_ROW_N...
StarcoderdataPython
1781627
#!/usr/bin/python2 import __init__ from utils.log import FALOG import time import pika import sys import json class Server(object): def __init__(self, exchange, binding_keys, exchange_type, username = 'network_monitor', passwd = '<PASSWORD>', vhost = 'network_monitor', host = '192.168.122.1', port ...
StarcoderdataPython
8022643
import pandas as pd from torch.utils.data import Dataset, DataLoader import torch # Create my own dataset class that reads data from csv, partitions it. class ForexDataset(Dataset): def __init__(self, csv_file, num_steps=20, train=True, train_size=0.8): super(ForexDataset, self).__init__() df = pd.read_csv(csv_fi...
StarcoderdataPython
6599741
<reponame>mstypulk/qiskit-terra # -*- coding: utf-8 -*- # Copyright 2019, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. """ Persistent value. """ from qiskit.pulse.channels import OutputChannel from qiskit.pulse....
StarcoderdataPython
1868447
from typing import List from app.models import Category from fastack import ModelController from fastack_sqlmodel.globals import db from fastack_sqlmodel.session import Session from fastapi import Request, Response from pydantic import BaseModel, conint, constr from sqlalchemy.sql.elements import and_ class BodyCate...
StarcoderdataPython
6529599
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 17 18:19:37 2019 @author: matthew """ #%% def dem_and_temporal_source_figure(sources, sources_mask, fig_kwargs, dem = None, temporal_data = None, fig_title = None): """ Given sources recovered by a blind signal separation method (e.g. PCA or I...
StarcoderdataPython
4811238
from xml.dom import minidom import urllib GEOCODER="http://ws.geonames.org/search?q=%s" from math import * def haversine(co1, co2): lon1, lat1 = co1 lon2, lat2 = co2 # convert to radians lon1 = lon1 * pi / 180 lon2 = lon2 * pi / 180 lat1 = lat1 * pi / 180 lat2 = lat2 * pi / 180 # haversine formula ...
StarcoderdataPython
3550836
<filename>futu/common/pb/Trd_GetFunds_pb2.py # Generated by the protocol buffer compiler. DO NOT EDIT! # source: Trd_GetFunds.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _messag...
StarcoderdataPython
1891239
from typing import IO def _calculate_log2_num_bytes(value: int) -> int: """ Determine the number of bytes required to encode the input value. Artificially limited to max of 8 bytes to be compliant :param value: :return: The calculate the number of bytes """ for log2_num_bytes in range(4)...
StarcoderdataPython
105873
<reponame>xiaolao/PaddleX # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. # # 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 # # ...
StarcoderdataPython
1882111
#from server import mycrt import pytest import unittest import requests import json #from mycrt import application from .context import * """ if __name__ == '__main__': if __package__ is None: import sys from os import path sys.path.append( path.dirname( path.dirname( path.abspath(__file_...
StarcoderdataPython
1738329
<filename>colcon_hardware_acceleration/subverb/hypervisor.py # Copyright 2022 <NAME> # Licensed under the Apache License, Version 2.0 import os import sys import errno from pathlib import Path from colcon_core.plugin_system import satisfies_version from colcon_hardware_acceleration.subverb import ( AccelerationSu...
StarcoderdataPython
1720361
# -*- coding: utf-8 -*- # # Copyright (C) 2016-2017 <NAME> # # 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
189983
<gh_stars>0 from .node import NodeModelBase
StarcoderdataPython
79815
import functools from typing import Optional, Sequence from fvcore.common.registry import Registry as _Registry from tabulate import tabulate class Registry(_Registry): """Extension of fvcore's registry that supports aliases.""" _ALIAS_KEYWORDS = ("_aliases", "_ALIASES") def __init__(self, name: str): ...
StarcoderdataPython
384009
age = int(input()) def drinks(drink): print(f"drink {drink}") if age <= 14: drinks("toddy") elif age <= 18: drinks("coke") elif age <= 21: drinks("beer") else: drinks("whisky")
StarcoderdataPython