id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
4844470
import numpy as np from scipy.signal import find_peaks from .utils import compute_probs from .utils import probs2cfs def pick_arrivals(cf): prom = cf.max() #mad = median_abs_deviation(cf) median = np.median(cf) mad = np.median(abs(cf-median)) for i in range(2): #prom /= 2 peaks, pr...
StarcoderdataPython
3303396
""" CISCO SAMPLE CODE LICENSE Version 1.0 Copyright (c) 2020 Cisco and/or its affiliates These terms govern this Cisco example or demo source code and its associated documentation (together, the "Sample Code"). By downloading, copyi...
StarcoderdataPython
8190191
import pyglet #from sketches.OrthoWindow import OrthoWindow as MainWindow #from sketches.ChunkWindow import ChunkWindow as MainWindow #from sketches.ProjectionWindow import ProjectionWindow as MainWindow from sketches.WorldWindow import WorldWindow as MainWindow #from sketches.RenderGraphTestWindow import RenderGraphT...
StarcoderdataPython
1883868
# -*- coding: utf-8 -*- # # <NAME> <<EMAIL>> # (c) 1998-2022 all rights reserved # framework import merlin # the GNU compiler suite class Suite(merlin.component, family="merlin.compilers.gnu", implements=merlin.protocols.compiler): """ The GNU compiler suite """ # end of file
StarcoderdataPython
3492533
<gh_stars>0 import time import importlib from pip._internal import main as pipmain import data.global_variables as global_var # FUNCTION - Installs the given Module in Python def install(package): pipmain(['install', package]) # Reads Requirements from Requirements.txt def read_requirements(): with open(glo...
StarcoderdataPython
266350
# -*- coding: utf-8 -*- import json import os from urlparse import urljoin import requests import rethinkdb as r from requests.auth import HTTPDigestAuth from requests.packages.urllib3.exceptions import (InsecureRequestWarning, SNIMissingWarning, InsecurePlatformWarning) requests.package...
StarcoderdataPython
51279
import gym import gym_sokoban import torch import numpy as np import random import time from utilities.channelConverter import hwc2chw from experts.utils import get_distance from external_actions import get_astar_action import warnings warnings.simplefilter("ignore", UserWarning) def test_the_agent(agent, data_path...
StarcoderdataPython
1775762
default_app_config='accounting.apps.AccountingConfig'
StarcoderdataPython
11395132
<gh_stars>10-100 # Main interface to the SmugMug web service. from . import smugmug_oauth import base64 import collections import hashlib import heapq import io import json import math import os import re import requests import threading import time API_ROOT = 'https://api.smugmug.com' API_UPLOAD = 'https://upload.s...
StarcoderdataPython
9693530
from . import BaseExtractor class Layarkaca21(BaseExtractor): tag = "movie" host = "http://149.56.24.226/" def extract_meta(self, id: str) -> dict: """ Ambil semua metadata dari halaman web Args: id: type 'str' """ raw = self.session.get(f"{self.hos...
StarcoderdataPython
1948011
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from ... import TestUnitBase class TestVBAExtractor(TestUnitBase): def test_maldoc(self): data = self.download_sample('4bdc8e660ff4fb05e5b6c0a2dd70c537817f46ac3270d779fdddc8e459829c08') unit = self.load() code = list(data | unit) self...
StarcoderdataPython
8103600
import numpy as np from scipy.stats import rankdata from functools import partial from nptyping import Array from sklearn.metrics import pairwise_distances from sklearn.base import BaseEstimator, TransformerMixin class BoostedSURF(BaseEstimator, TransformerMixin): """sklearn compatible implementation of the boost...
StarcoderdataPython
1931358
#!/usr/bin/env python2 import json import thread import psycopg2 import websocket import api import config def on_message(ws, message): #print(message) j = json.loads(message) try: #print j["params"][1][0][0]["id"] id_ = j["params"][1][0][0]["id"] #print id_[:4] if id_[:4...
StarcoderdataPython
217197
<gh_stars>0 """ Module with functionalities for blocking based on a dictionary of records, where a blocking function must return a dictionary with block identifiers as keys and values being sets or lists of record identifiers in that block. """ # ===========================================================...
StarcoderdataPython
6443414
<gh_stars>0 # coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload fr...
StarcoderdataPython
5153514
# PYTHONPATH must be set to openschc/src import binascii import pprint """ This is a no_compression test, ie the packet is sent no compressed with a aligned ruleID of 8 bits. """ from gen_rulemanager import RuleManager from compr_parser import Parser from compr_core import Compressor enable_debug_pr...
StarcoderdataPython
364231
<reponame>laetitia123/akikatest<gh_stars>0 from __future__ import unicode_literals from django.db import models from django.utils import timezone import datetime as dt class Akika(models.Model): title = models.CharField(max_length=60) post = models.TextField() pub_date = models.DateTimeField(auto_now_ad...
StarcoderdataPython
5199361
<filename>main.py import sys sys.path.append('./lib') import _G, const, util, Input def start(): util.init() if _G.AppHwnd == 0: print("App not found, aborting") return exit() util.activate_window(_G.AppHwnd) while _G.Flags['running']: main_loop() def main_loop(): util.uwait(_G.UpdateDuratio...
StarcoderdataPython
11392901
import py, sys from pypy.interpreter.astcompiler import codegen, astbuilder, symtable, optimize from pypy.interpreter.pyparser import pyparse from pypy.interpreter.pyparser.test import expressions from pypy.interpreter.pycode import PyCode from pypy.interpreter.pyparser.error import SyntaxError, IndentationError from p...
StarcoderdataPython
6634844
import json import subprocess import csv import operator import ld_helpers import pprint import mpu_helpers DEFAULT_RAM_SECTIONS = ['.data', '.bss', '._user_heap_stack', '.stack', '.hexbox_rt_ram'] DEFAULT_FLASH_SECTIONS = ['.isr_vector', '.rodata', '.ARM.extab', '.A...
StarcoderdataPython
9691271
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the License); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, sof...
StarcoderdataPython
5153702
<filename>screen/screen.py from screens.call_screen import CallScreen from screens.inital_call_screen import InitialCallScreen from screens.middle_screen import MiddleScreen class Screen(object): """Class that represents the screen itself and instantiates all subscreens""" def __init__(self): self.in...
StarcoderdataPython
1858965
<reponame>weeb-poly/syncplay-proxy<filename>syncplay/ep_proxy.py import os import logging from twisted.internet.endpoints import TCP4ServerEndpoint, SSL4ServerEndpoint from syncplay.server import SyncplayProxyWSFactory from syncplay.server import SyncplayProxyTCPFactory from twisted.internet import reactor # from a...
StarcoderdataPython
1932063
<filename>spotjuk/src/schemas/create_database.py import os os.remove('../database.db') import sqlite3 conn = sqlite3.connect('../database.db') cursor = conn.cursor() cursor.execute(""" CREATE TABLE categories ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, categorie VARCHAR(20) NOT NULL, cover VARCHAR(...
StarcoderdataPython
8145045
import datetime from Bearing import Bearing class Sensors(): def __init__(self): self.setAllValues() ############################################ getter --> def getWindDirection(self): return self.__windDirection def getCompassBearing(self): return self.__compassCourse def ge...
StarcoderdataPython
233917
n1 = int(input('Input an integer number: ')) n2 = int(input('Input another integer number: ')) print('The sum between {} and {} is equal to: {}'.format(n1, n2, n1 + n2))
StarcoderdataPython
106936
#! /opt/conda/bin/python3 """ File containing keras callback class to collect runstats of the training process """ # Copyright 2018 FAU-iPAT (http://ipat.uni-erlangen.de/) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may ob...
StarcoderdataPython
1843524
from dagster import solid from dagster.core.execution.context.compute import AbstractComputeExecutionContext from hca_manage.check import CheckManager from hca_manage.common import ProblemCount from hca_orchestration.contrib.dagster import short_run_id @solid( required_resource_keys={'data_repo_client', 'hca_dat...
StarcoderdataPython
133489
''' We'll put utility functions here - timing decorators, exiting functions, and maths stuff are here atm. <NAME> 28/10/2019 ''' #------------------------------------------------------------------ import time from math import sqrt import sys from ast import literal_eval as lit import random from pathlib import Path ...
StarcoderdataPython
3500024
''' CLI entry-point for salt-api ''' # Import python libs import sys import logging # Import salt libs import salt.utils.verify from salt.utils.parsers import ( ConfigDirMixIn, DaemonMixIn, LogLevelMixIn, MergeConfigMixIn, OptionParser, OptionParserMeta, PidfileMixin) # Import salt-api lib...
StarcoderdataPython
12808033
<reponame>hellysmile/aiohttp_request import contextvars import typing from functools import partial from aiohttp import web from werkzeug.local import LocalProxy __version__ = '0.0.1' ctx = contextvars.ContextVar('request') # type: contextvars.ContextVar class ThreadContext: __slots__ = ('_ctx', '_fn') ...
StarcoderdataPython
380311
<filename>she-process.py #!/usr/bin/env python # coding: utf-8 # In[1]: # pip install pandas openpyxl jinja2 faker import pandas as pd import pathlib from jinja2 import Template from faker import Faker import sys # In[2]: df_names = pd.read_csv('out.csv') # print(df_names[:4]) names = df_names['en'].sample(n=1, ...
StarcoderdataPython
3562866
<gh_stars>0 # Copyright 2018-2019 <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 law or agreed to ...
StarcoderdataPython
1788524
<filename>routemaster/logging/__init__.py """Logging plugin subsystem.""" from routemaster.logging.base import BaseLogger from routemaster.logging.plugins import ( PluginConfigurationException, register_loggers, ) from routemaster.logging.split_logger import SplitLogger from routemaster.logging.python_logger i...
StarcoderdataPython
265428
# Runners group runners = ['harry', 'ron', 'harmoine'] our_group = ['mukul'] while runners: athlete = runners.pop() print("Adding user: " + athlete.title()) our_group.append(athlete) print("That's our group:- ") for our_group in our_group: print(our_group.title() + " from harry potter!") Dream_vacatio...
StarcoderdataPython
331416
<reponame>itzpc/Google-MLCC-NITJ def main(): choice='z' if choice == 'a': print("You chose 'a'.") elif choice == 'b': print("You chose 'b'.") elif choice == 'c': print("You chose 'c'.") else: print("Invalid choice.") if __name__ == '__main__': main()
StarcoderdataPython
6401396
from pyppeteer import launch async def screengrab(url): browser = await launch({"slowMo": 5}, args=["--no-sandbox"]) page = await browser.newPage() await page.setViewport( {"width": 1920, "height": 1080, "deviceScaleFactor": 1} ) await page.goto(url, waitUntil="networkidle2") await pag...
StarcoderdataPython
6699701
from typing import List, Iterator import os import logging from ..module import SafeFilenameModule logger = logging.getLogger(__name__) class PackageScanner: """ Scans a package for all the Python modules within it. Usage: package = SafeFilenameModule('mypackage', '/path/to/mypackage/__init__....
StarcoderdataPython
1629836
from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient from core.models import Recipe, Tag, Ingredient from recipe.serializers import RecipeSerializer, RecipeDetailSerializer RECIPES_...
StarcoderdataPython
11348466
def console(outfile,highlighter): with open(outfile, 'r') as fin: for line in fin: print(line) for word in line.split(): if 'TAB' in word: highlighter
StarcoderdataPython
1808627
from datetime import datetime from functools import lru_cache from houdini.data import db class Penguin(db.Model): __tablename__ = 'penguin' id = db.Column(db.Integer, primary_key=True, server_default=db.text("nextval('\"penguin_id_seq\"'::regclass)")) username = db.Column(db.String(12), nullable=False,...
StarcoderdataPython
11258102
# Generated by Django 2.0.4 on 2018-05-10 05:01 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Lock', fields=[ ('id', models.AutoField(aut...
StarcoderdataPython
378929
import inspect import pytest from botocore.stub import Stubber from AwAws.SharedResources.parameters import Parameters # set up some simple responses from SSM @pytest.fixture def ssm_get_response(): response = { 'Parameter': { 'Type': 'String', 'Name': '/alpha/hostname', ...
StarcoderdataPython
5061447
<reponame>mn3711698/wrobot # -*- coding: utf-8 -*- ############################################################################## # Author:QQ173782910 ############################################################################## """admin/vi/BASE_TPL.py""" from basic.VIEW_TOOL import cVIEWS class cBASE_TPL(cVIEWS): ...
StarcoderdataPython
11367086
<reponame>MatthewTsan/Leetcode # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: if n == 0 or not head: return head ...
StarcoderdataPython
6611489
# -*- coding: utf-8 -*- from conans import ConanFile, CMake, tools import os class KhronosOpenCLCLHPPConan(ConanFile): name = "khronos-opencl-clhpp" version = "20190207" description = "OpenCL Host API C++ bindings" topics = ("conan", "opencl", "header-only", "opencl-headers", "clhpp", "khronos") ...
StarcoderdataPython
6481739
<gh_stars>0 from objects import experiments, outputtable, computationalresource import json import itertools import copy import os import lxml.etree as etree import sqlite3 as lite import sys import subprocess import datetime import time modelsAndAlgorithmNames_global = [] baseParamsDict_global = {} computationalResou...
StarcoderdataPython
1946747
<filename>doc/week1/w1d3/json.py import urllib import simplejson as json # sudo pip install simplejson url = "http://www.boldsystems.org/index.php/API_Tax/TaxonSearch?taxName=Danaus" response = urllib.urlopen(url) data = json.loads(response.read()) if data['top_matched_names']: for name in data['top_matched_names']: ...
StarcoderdataPython
1832350
def print_left_perimeter(root): while root != None: curr_val = root.data if root.left != None: root = root.left elif root.right != None: root = root.right else: # leaf node break print(str(curr_val) + " ") def print_right_perimeter(root):...
StarcoderdataPython
4862425
#!/usr/bin/python # # Copyright 2010 Google Inc. 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 b...
StarcoderdataPython
11365847
from collections import defaultdict class Solution: def canPair(self, arr, k): # Code here for i in range(len(arr)): arr[i] = arr[i] % k dict_1 = defaultdict(lambda: 0) # print(arr) for i in arr: if i == 0: if dict_1[i] > 0: ...
StarcoderdataPython
295133
# RUN: test-parser.sh %s # RUN: test-output.sh %s x = 1 # PARSER-LABEL:x = 1i y = 2 # PARSER-NEXT:y = 2i print("Start") # PARSER-NEXT:print("Start") # OUTPUT-LABEL: Start if x == 1: # PARSER-NEXT:if (x == 1i): if y == 3: # PARSER-NEXT: if ...
StarcoderdataPython
5029193
<reponame>mfleming99/COVID-QA<filename>covid_nlp/language/ms_translate.py # -*- coding: utf-8 -*- import os, requests, uuid, json import sys import pandas as pd class MSTranslator(): def __init__(self, key = None, endpoint = None, lang = None): if key: self.azure_key = key else: ...
StarcoderdataPython
9720246
<filename>model/data_analysis.py import csv import argparse from matplotlib import pyplot as plt import numpy as np # Script that created a histogram of the years that citation come from. This can be used for data analysis of a test # set # The examples must be labeled with a "Year" column # Usage: python3 data_analys...
StarcoderdataPython
6454987
<reponame>xiangshiyin/coding-challenge class Solution: def isValidSerialization(self, preorder: str) -> bool: nodes = preorder.split(',') slots = 1 for node in nodes: slots -= 1 if slots < 0: return False if node.i...
StarcoderdataPython
8153478
class Робочи_дни(): def Pon(pon): print(""" Урок : Година : Оцынка Физика 08:00 8 Инф.мат 08:50 10 Укр.лит 09:30 11 Укр.мова 10:15 5 Химия 12:00 7 """) def Viv(der): print(""" Урок : Година : Оцынка Фыз.кул ...
StarcoderdataPython
393786
<filename>plugins/rapid7_insightops/komand_rapid7_insightops/connection/connection.py import komand from .schema import ConnectionSchema # Custom imports below class Connection(komand.Connection): def __init__(self): super(self.__class__, self).__init__(input=ConnectionSchema()) self.api_key = No...
StarcoderdataPython
1630267
<filename>registry/app.py """The app module, containing the app factory function.""" import logging import sys from flask import Flask, render_template from registry import batch, commands, donor, public, user from registry.extensions import ( bcrypt, csrf_protect, db, debug_toolbar, login_manager...
StarcoderdataPython
1676630
#!/usr/bin/env python class SkipObject: def __init__(self, wrapped): self.wrapped = wrapped return def __iter__(self): return SkipIterator(self.wrapped) class SkipIterator: def __init__(self, wrapped): self.wrapped = wrapped self.offset = 0 def __next__(self): ...
StarcoderdataPython
11341566
from direct.showbase.PythonUtil import POD class QuestRewardStruct(POD): DataSet = {'rewardType': None,'amount': None,'questId': None}
StarcoderdataPython
11254869
<reponame>probcomp/hierarchical-irm # Copyright 2021 MIT Probabilistic Computing Project # Apache License, Version 2.0, refer to LICENSE.txt from scipy.io import loadmat # Animals as a single binary relation" # has: Animals x Features -> {0,1} x = loadmat('50animalbindat.mat') features = [y[0][0] for y in x['featur...
StarcoderdataPython
6492559
<reponame>linuxfood/pyobjc-framework-Cocoa-test<filename>PyObjCTest/test_nswindowrestoration.py import AppKit import objc from PyObjCTools.TestSupport import TestCase, min_os_level class RestorationHelper(AppKit.NSObject): def restoreWindowWithIdentifier_state_completionHandler_(self, a, b, c): pass cla...
StarcoderdataPython
9740554
import webbrowser, os import json import boto3 import io from io import BytesIO import sys file_name = sys.argv[1] # get the results client = boto3.client( service_name='textract', region_name= 'us-east-1' ) def get_table_html_results(file_name): with open(file_name, 'rb') as file: img...
StarcoderdataPython
4904260
# Generated by Django 3.2.9 on 2021-11-16 11:17 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('academicInfo', '0001_initial'), ('faculty', '0001_initial'), ('student', '0001_initial')...
StarcoderdataPython
5010732
<filename>tests/actions/test_store_metric_action.py from great_expectations.core import ExpectationSuiteValidationResult, ExpectationValidationResult, \ ExpectationConfiguration from great_expectations.core.metric import ValidationMetricIdentifier from great_expectations.data_context.types.resource_identifiers impo...
StarcoderdataPython
8067855
<reponame>usrl-uofsc/WaterSampling import RPi.GPIO as GPIO from time import sleep class Bottle: # init function takes in values for the arguments. def __init__(self, pin): self.pin = pin self.__isfull = False GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(sel...
StarcoderdataPython
3376686
import argparse from google_drive_backup import GoogleDriveBackupCreator parser = argparse.ArgumentParser() parser.add_argument("dir", help="Directory name to backup") args = parser.parse_args() gdrive_backup_creator = GoogleDriveBackupCreator() gdrive_backup_creator.backup(args.dir)
StarcoderdataPython
5113060
""" """ import json import os from openeo_odc.map_to_odc import map_to_odc from openeo_pg_parser.translate import translate_process_graph from openeo_pg_parser.validate import validate_processes def test_job(): """Create a xarray/opendatacube job based on an openEO process graph.""" # Set input parameters ...
StarcoderdataPython
11317254
# import libraries here import numpy as np import cv2 def count_blood_cells(image_path): """ Procedura prima putanju do fotografije i vraca broj crvenih krvnih zrnaca, belih krvnih zrnaca i informaciju da li pacijent ima leukemiju ili ne, na osnovu odnosa broja krvnih zrnaca Ova procedura se poziva a...
StarcoderdataPython
159632
<filename>python/StringCalculator/StringCalculator.py class StringCalculator: def __init__(self): self.string = '' self.list_of_numbers = [] self.delimiter = ',' def add(self, string_of_numbers): self.validate_input(string_of_numbers) self.process_delimiter() ...
StarcoderdataPython
1804904
#****************************************************************************** # (C) 2018, <NAME>, Austria * # * # The Space Python Library is free software; you can redistribute it and/or * # m...
StarcoderdataPython
6425952
<reponame>jalmquist/aleph """collection languages Revision ID: <KEY> Revises: 9<PASSWORD> Create Date: 2017-06-14 10:13:23.270229 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '9be0f89c9088' ...
StarcoderdataPython
5043660
# Generated by Django 3.0.8 on 2020-09-02 18:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalog', '0008_auto_20200902_1625'), ] operations = [ migrations.AlterField( model_name='author', name='date_of_bir...
StarcoderdataPython
34669
# Copyright (c) 2018 The Regents of the University of Michigan # and the University of Pennsylvania # # 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 li...
StarcoderdataPython
8141383
#!/usr/bin/env python from nodes import RootNode, FilterNode, HamlNode, create_node from optparse import OptionParser import sys VALID_EXTENSIONS=['haml', 'hamlpy'] class Compiler: def process(self, raw_text, options=None): split_text = raw_text.split('\n') return self.process_lines(split_text, op...
StarcoderdataPython
149651
<gh_stars>1-10 import boto3 def fetchDynamoClient(peer): kwargs = _getClientConfig(peer) dynamodb = boto3.resource('dynamodb', **kwargs) return dynamodb.Table(peer['name']) def fetchKinesisClient(peer): kwargs = _getClientConfig(peer) return boto3.client('kinesis', **kwargs) def fetchSSMClient(pe...
StarcoderdataPython
1892120
<filename>aws_networkacl.py #!/usr/bin/env python import jmespath import argparse import csv import sys from terminaltables import SingleTable from aws_queries import query, NETWORKACL from aws_info import vpc_info def network_acls(environment,table_flag=False): field_names = ['Environment','ID','Name','VPC(ID/Na...
StarcoderdataPython
9758014
<reponame>dbobrenko/AsynQ-Learning from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import random import threading as th import time from datetime import datetime from six.moves import range # pylint: disable=redefined-builtin import numpy as np i...
StarcoderdataPython
8121358
import networkx as nx import topology as tp import matplotlib.pyplot as plt import selection def greedy_partition(g, max_hop, max_cluster_size, node_sequence): unvisited_nodes = list(g.nodes()) cluster_id = 1 cluster_dict = {} ndcount = 0 while len(unvisited_nodes) > 0: stnode ...
StarcoderdataPython
46733
import argparse import copy import datetime import re import shlex from typing import Union import time import discord from discord.ext import commands class Arguments(argparse.ArgumentParser): def error(self, message): raise RuntimeError(message) def setup(bot): bot.add_cog(Moderation(bot)) def ...
StarcoderdataPython
1946494
# -*- coding:utf-8 -*- import urllib.request import urllib.parse import http.cookiejar from bs4 import BeautifulSoup def test_bs(): response = urllib.request.urlopen('http://www.shanbay.com/team/members/') page_html = response.read() soup = BeautifulSoup(page_html) pre = soup.prettify() print(pr...
StarcoderdataPython
3544429
<gh_stars>0 import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library from time import sleep # Import the sleep function from the time module GPIO.setwarnings(False) # Ignore warning for now GPIO.setmode(GPIO.BOARD) # Use physical pin numbering GPIO.setup(12, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(22, GP...
StarcoderdataPython
9717891
<filename>src/fleetctrl/planning/VehiclePlan.py # -------------------------------------------------------------------------------------------------------------------- # # standard distribution imports # ----------------------------- import logging from os import startfile # additional module imports (> requirements) #...
StarcoderdataPython
1768919
<reponame>frangiz/AdventOfCode2018 """--- Day 10: The Stars Align ---""" import helpers class Point(): def __init__(self, x, y, dx, dy): self.x = x self.y = y self.dx = dx self.dy = dy def __repr__(self): return '({}, {} -> {}, {})'.format(self.x, self.y, self.dx, self...
StarcoderdataPython
8010734
<filename>DataGenerators/prepare_dataset.py # this file is used to convert '.mat' files to one '.npz' file # for human3.6m dataset, it also select the 17 joints from the whole 32 # input: some '.mat' files in './data/NAME/' # output: one '.npz' file in same path import numpy as np import os from scipy.io import loadm...
StarcoderdataPython
5151038
<reponame>slegroux/NeMo # Copyright (c) 2021, NVIDIA CORPORATION. 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 # # ...
StarcoderdataPython
6570606
from io import BytesIO from sys import version_info from unittest import TestCase from xml.etree import ElementTree import datetime import pytest from pyclarity_lims.constants import nsmap from pyclarity_lims.descriptors import StringDescriptor, StringAttributeDescriptor, StringListDescriptor, \ StringDictionaryD...
StarcoderdataPython
86028
import json import os from . import jsonencoder class Objects: def __init__(self, path: str): self.path = os.path.abspath(path) os.makedirs(os.path.join(self.path, "objects"), exist_ok=True) self.encoder = jsonencoder.Encoder() def save_object(self, object_name, object_instance): ...
StarcoderdataPython
1629231
from cumulusci.core.utils import process_bool_arg, process_list_arg from cumulusci.tasks.bulkdata.step import ( DataOperationType, DataOperationStatus, DataApi, get_query_operation, get_dml_operation, ) from cumulusci.tasks.salesforce import BaseSalesforceApiTask from cumulusci.core.exceptions impor...
StarcoderdataPython
6483269
import sys if len(sys.argv) != 2: print('Usage:\npython3 <TLD list>') sys.exit() tld = [] all_tld = [] not_tld = [] for line in open(sys.argv[1]): i = line.find('//') if i >= 0: line = line[:i] line = line.strip() if '.' not in line: continue if line.startswith('!'): not_tld.append(line[1:...
StarcoderdataPython
5150456
""" Quantiphyse - Widgets for data simulation Copyright (c) 2013-2020 University of Oxford 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 re...
StarcoderdataPython
4870341
import numpy as np import pandas as pd import torch class SessionDataset: def __init__(self, sep='\t', session_key='SessionId', item_key='ItemId', time_key='TimeStamp', user_key='UserId', mode='train', train_data=None, test_data=None, n_samples=-1, itemmap=None, time_sort=False, print_info=True):...
StarcoderdataPython
127809
import requests import json from constants import getConstants # get constants constants = getConstants() def api_request(method, url, header=None, data=None, response_type='json'): response = requests.request(method, url, headers=header, data=data) if response_type == 'json': try: respons...
StarcoderdataPython
3500144
<gh_stars>10-100 import numpy as np import torch import scipy _eps = 1.0e-5 class FIDScheduler(object): def __init__(self,args): self.freq_fid = 2000 # args.freq_fid self.oldest_fid_iter = 20000 # args.oldest_fid_iter self.num_old_fids = int(self.oldest_fid_iter/self.freq_fid) +1 se...
StarcoderdataPython
6432969
<filename>utils/convert_fregene_vcf.py import argparse import random import numpy as np format_header = "##fileformat=VCFv4.1" header_left = "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT" def generate_vcf(flname, positions, diploids): n_sites = len(positions) n_individuals = len(diploids) posit...
StarcoderdataPython
6492676
<filename>test_linear.py from ANN import ANN from PSO import PSO import time #data = 'Data/1in_linear.txt' #data = 'Data/1in_cubic.txt' data = 'Data/1in_sine.txt' #data = 'Data/1in_tanh.txt' #data = 'Data/2in_xor.txt' input_size = 1 ann = ANN(input_size, [12,1]) pso = PSO(50, 10, 0.9, 0.4, 2.5, 0, 1.5, 1, ann, 1000...
StarcoderdataPython
11292035
import os, sys, glob from os.path import dirname, join, abspath sys.path.insert(0, abspath(join(dirname(__file__), '..'))) import argparse import pandas as pd import numpy as np from Utils.Funcs import printProgressBar, loadFromJson from DataClasses import Annotation, classToDic import json import array import math imp...
StarcoderdataPython
1609934
<reponame>vmware/distributed-apps-platform # Copyright (c) 2020-2021 VMware, Inc. All Rights Reserved. # SPDX-License-Identifier: BSD-2 License # The full license information can be found in LICENSE.txt # in the root directory of this project. __version__='1.0.1'
StarcoderdataPython
11267575
# -*- coding: utf-8 -*- # flake8: noqa """Installation script.""" #------------------------------------------------------------------------------ # Imports #------------------------------------------------------------------------------ import os import os.path as op from pathlib import Path import re from setuptoo...
StarcoderdataPython
4957995
<gh_stars>1-10 import mysql.connector as sql from SearchUtility_Backend.SearchUtilityLogger import SearchUtilityLogger class MySQLCommands: @staticmethod def CreateDataBase(): return "CREATE DATABASE IF NOT EXISTS SearchUtility" @staticmethod def UseDataBase(): return "US...
StarcoderdataPython