id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
4879830
import logging from typing import List import numpy from cephlib.units import unit_conversion_coef_f from cephlib.plot import PlotParams, provide_plot from .resources import IOSummary logger = logging.getLogger("wally") @provide_plot(eng=False, no_legend=True, grid='y', style_name='ioqd', noadjust=True) def io_c...
StarcoderdataPython
11240796
<filename>arithmetic/views/back.py import asyncio import random from datetime import datetime import time from ..constants import * async def make_progression(n: int, d: float, n1: int, interval: float) -> dict: start_time = time.monotonic() if use_print: print('---------------------------------------...
StarcoderdataPython
11287959
<reponame>Elektron-blip/Circuit_Calculator_Alpha<gh_stars>1-10 from Modules.unifier import test
StarcoderdataPython
3371810
<reponame>Curiosio/srtm.py import gpxpy as mod_gpxpy # type: ignore import cartesius.main as mod_cartesius # type: ignore import cartesius.charts as mod_charts # type: ignore import cartesius.elements as mod_elements # type: ignore import logging as mod_logging import srtm as mod_srtm from typing import * mod_logging...
StarcoderdataPython
11348906
import unittest from data_hub_call import Data_hub_call import datetime class TestGetDateTime(unittest.TestCase): """ Our basic test class """ def test_getDateTime(self): """ The actual test. Any method which starts with ``test_`` will considered as a test case. """ ...
StarcoderdataPython
329584
<gh_stars>1-10 from pymesh.TestCase import TestCase from pymesh.meshutils import generate_box_mesh from pymesh import minkowski_sum, detect_self_intersection import numpy as np class MinkowskiSumTest(TestCase): def test_simple(self): input_mesh = generate_box_mesh( np.array([0, 0, 0]), np....
StarcoderdataPython
8136143
<reponame>Hamng/python-sources # -*- coding: utf-8 -*- """ Created on Sat Feb 23 20:58:30 2019 @author: Ham HackerRanch Challenge: itertools.product() Task You are given a two lists A and B. Your task is to compute their cartesian product X. Example A = [1, 2] B = [3, 4] AxB = [(1, 3), (1, 4), ...
StarcoderdataPython
8157486
from svgwrite import Drawing from svgwrite.container import Group from objects import Renderable import math class PopEye(Renderable): def __init__(self, radius: float, pupil_radius: float = .3, pupil_rho: float = 0, pupil_phi: float = 0) -> None: self.radius = radius self.pupil_radius = pupil_rad...
StarcoderdataPython
395196
<reponame>elias-1/NiftyNet # -*- coding: utf-8 -*- # Copyright 2018 The Sonnet Authors. All Rights Reserved. # Modifications copyright 2018 The NiftyNet 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...
StarcoderdataPython
9793633
<reponame>HeitorBoschirolli/sigback import numpy as np import random import os from skimage import img_as_float64 from skimage.transform import rescale from skimage.io import imread, imsave from sigback.processing import color, transform def blend(sig, sig_barycenter, doc, doc_center, keep_size=False): if (sig.s...
StarcoderdataPython
91631
<filename>BN_checks.py # -*- coding: utf-8 -*- """ Created on Sun Oct 4 12:42:07 2020 @author: claud """ import pandas as pd import numpy as np from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score, recall_score, f1_score fi...
StarcoderdataPython
3276269
<reponame>WorkAroundOnline/python-workaround class Task: def __init__(self, external_url=None, iframe_url=None, description=None): self.external_url = external_url self.iframe_url = iframe_url self.description = description self.status = 'local' def cancel(self): if self...
StarcoderdataPython
6550965
<filename>dataprep/masks_to_box.py<gh_stars>1-10 """ Converts segmentation masks of different types from different folders to YOLO format bounding boxes. """ import os import sys import cv2 from tqdm import tqdm from skimage.measure import label, regionprops if __name__ == "__main__": GT_PATH = sys.argv[1] ...
StarcoderdataPython
6630857
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_graphql import GraphQLView from graphene_sqlalchemy import SQLAlchemyObjectType import graphene app = Flask(__name__) SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://test:test@192.168.1.2:3306/study?charset=utf8' app.config['SQLALCHEMY_DATABASE_URI'...
StarcoderdataPython
5112151
#! /n/local_linux/epd/bin/python2.7 # # This script will not run with /usr/local/bin/python -> python3.2 # for linux /n/local_linux/python2.5.1/bin/python # # default is now vers 3 in /usr/bin/python # for linux /n/local_linux/python2.5.1/bin/python # for mac /usr/bin/env python # for lanl machines /usr/bin/env py...
StarcoderdataPython
9785427
import os import time import atexit import termios, fcntl, sys, os import select def init(): fd = sys.stdin.fileno() # save old state flags_save = fcntl.fcntl(fd, fcntl.F_GETFL) attrs_save = termios.tcgetattr(fd) # make raw - the way to do this comes from the termios(3) man page. attrs = list(a...
StarcoderdataPython
4856573
<reponame>ChristianofTruth/nba_hustle_stats #!/usr/bin/env python # coding: utf-8 import dash from dash.dependencies import Input, Output import dash_core_components as dcc import dash_html_components as html import plotly.figure_factory as ff import plotly.graph_objs as go import plotly.offline as py import plotly.ex...
StarcoderdataPython
71194
# local imports import xmatters import config # python3 package imports import logging import base64 import json from logging.handlers import RotatingFileHandler import urllib.parse import datetime import csv # main process def main() -> object: """ 1. Query for all events where a form property is set to...
StarcoderdataPython
11205077
<filename>portfolio/Mahbubur_Rahman/admin.py from django.contrib import admin from .models import Home, About, Profile, Category, Skills, Portfolio # Home admin.site.register(Home) # About class ProfileInline(admin.TabularInline): model = Profile extra = 1 @admin.register(About) class AboutAdmin(admin.Mode...
StarcoderdataPython
3246796
#1. Дана последовательность натуральных чисел a1, a2, ..., an. Создать массив из четных чисел этой последовательности. Если таких чисел нет, то вывести сообщение об этом факте. #2. Дана последовательность целых чисел a1,.a2, ..., an, Указать все пары элементов массива, для которых сумма равна n. #3. Даны две последоват...
StarcoderdataPython
4863387
from typing import Dict from code.front_end.our_ast import * import itertools as itl from collections import OrderedDict class SemanticAnalysisError(Exception): #Esception que voy a utilizar para detectar los errores semanticos, recive una lista de strings con los problemas y en su __str__ los imprime ...
StarcoderdataPython
4993691
class Solution: def minOperations(self, n): return n*(n//2) - (n//2) * (n//2)
StarcoderdataPython
1655017
<reponame>Rhinrei/stepik_python_selenium import math, time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def calc(x): return str(math.log(abs(12*math.sin(int(x)))))...
StarcoderdataPython
8158394
# Dependencies import numpy as np import pandas as pd import networkx as nx # Define function for getting word map to integer def map_words(words): # Get unique lemmas unique_words = words.groupby(by=['text', 'pos']).size().reset_index(name='counts') unique_words.sort_values(by='counts', ascending=False, ...
StarcoderdataPython
5160539
from app.models import db, Instruction # Adds a demo location, you can add other locations here if you want def seed_instructions(): db.session.bulk_insert_mappings(Instruction, [ { "recipeId"...
StarcoderdataPython
1975503
<filename>api.py from flask import Flask, jsonify, request, make_response from flask_restplus import Api, Resource, reqparse from functools import cache, wraps from flask_caching import Cache from functools import wraps from json import loads import mysql.connector import logging import urllib import jwt # Flask app =...
StarcoderdataPython
9695477
<filename>notebooks/GraphDrawing.py #%% import pylab import networkx as nx import numpy as np #%% g05_60 = np.loadtxt("data/g05_60.0", skiprows=0, dtype=np.int32) g05_100 = np.loadtxt("data/g05_100.0", skiprows=0, dtype=np.int32) G60 = nx.convert.from_edgelist( [(g05_60[i, 0] - 1, g05_60[i, 1] - 1) for i in range...
StarcoderdataPython
367101
<gh_stars>1-10 # -*- coding: utf-8 -*- # Merge the coverage tracks created in the "gatk_cov" steps. import os from snakemake.shell import shell # Create file with GATK sample_interval_summary output files # used in `--GATKdepthsList` work_dir = os.getcwd() list_path = os.path.join(os.path.dirname(str(snakemake.outpu...
StarcoderdataPython
1948776
class Route: def __init__(self): self.id=-1 self.prefix="" self.neighbor="" self.next_hop="" self.as_path=[] self.communities=[] self.type="" def aspath_length(as_path): return len(as_path) def get_advertised_as(as_path): return as_pat...
StarcoderdataPython
11256715
<filename>pyutil_json/__init__.py<gh_stars>0 # -*- coding: utf-8 -*- from rapidjson import dumps from rapidjson import dump from rapidjson import loads from rapidjson import load from .util import json_dumps_ne as dumps_ne from .util import json_dumps_e as dumps_e from .util import json_loads_ne as loads_ne from .uti...
StarcoderdataPython
8060928
<gh_stars>0 ''' This module as handler deal with command received from manager.py So most of function don't have to return, just using logging. ''' import logging import json import manager import socket import random import sqlite3 import os import sys import mgr_core # 当前目录 __CURRENT_DIR__ = os.path....
StarcoderdataPython
11370704
""" Transforms data into the final output data """ import json import logging LOGGER = logging.getLogger(__name__) def transform(data): """ Applies simple transformation to the data Expects data: raw_data = { "intValue": "42", "floatValue": "3.14159265358979", "...
StarcoderdataPython
9623350
import time import random MIN_ANSWER = 1 MAX_ANSWER = 100 def ask_for_number(): try: answer = int(input(f"Guess a number between {MIN_ANSWER} and {MAX_ANSWER}: ")) return answer except: print("You have to enter an integer number, please try again.") return ask_for_number() def make_a_gues...
StarcoderdataPython
9765107
"""empty message Revision ID: f5d6fb482e96 Revises: <PASSWORD> Create Date: 2019-10-06 15:30:23.797756 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'f<PASSWORD>' down_revision = 'c<PASSWORD>' branch_labels = None depends_on = None def upgrade(): # ### ...
StarcoderdataPython
1923737
<filename>Python/subcontiguous_array.py a = [-2, 3, -16, 100, -4, 51] n = len(a) m = [0]*(n+1) if a[0]>0: m[0] = a[0] # makes negative values eq to 0 max_val = -1 for i in range(1,n): if m[i-1] + a[i] > m[i]: m[i] = m[i-1] + a[i] #uses prefix sum max_val = max(max_val,m[i]) ...
StarcoderdataPython
1870807
import os DFL_DATA_PATH = os.path.join(os.environ['HOME'], 'VisualSearch') DFL_CONFIG = 'resnet50_focal_%d_ap' DFL_DEVICE = 0 if __name__ == '__main__': print('DATA_PATH {}'.format(DFL_DATA_PATH)) print('CONFIG {}'.format(DFL_CONFIG)) print('DEVICE {}'.format(DFL_DEVICE))
StarcoderdataPython
3402184
<gh_stars>10-100 import datetime import logging import ckan.authz as new_authz import ckan.logic as logic import ckan.logic.auth.update as core_auth_update from ckan.common import _ from ckanext.hdx_users.helpers.reset_password import ResetKeyHelper log = logging.getLogger(__name__) ## ORGS def hdx_send_new_org_req...
StarcoderdataPython
5181721
<reponame>kongo09/hass-dell-printer from typing import Callable, Any, Dict from custom_components.dell_printer import DellDataUpdateCoordinator, DellPrinterEntity from homeassistant.components.binary_sensor import BinarySensorEntity from homeassistant.helpers.entity import EntityCategory from homeassistant.helpers.typi...
StarcoderdataPython
8082474
<filename>network/norm.py<gh_stars>10-100 import torch.nn as nn import functools class InstanceNorm(nn.GroupNorm): def __init__(self, channels): super().__init__(channels, channels) class LayerNorm(nn.GroupNorm): def __init__(self, channels): super().__init__(1, channels) def get_norm_layer(n...
StarcoderdataPython
92699
<filename>emiz/weather/avwx/exc.py # coding=utf-8 """ Exceptions for AVWX package """ class AVWXError(Exception): """Base AVWX exception""" class AVWXRequestFailedError(AVWXError): """Raised when request failed""" class StationNotFound(AVWXError): """ Raised when a ICAO station isn't found """...
StarcoderdataPython
3380359
import string from subprocess import call import csv import sys from os.path import * #################################################################### # # COMMON FUNCTIONS # #################################################################### def read_table_from_csv(file_name, header_starts=["##hdr", "## hdr"]...
StarcoderdataPython
210502
import argparse import collections import math import os import sys import matplotlib.pyplot as plt from pwdmodels import model, pcfg, backoff, ngram_chain def gen_guess_crack(estimations: [int], upper_bound): estimations.sort() gc_pairs = {} for idx, est in enumerate(estimations): if est < uppe...
StarcoderdataPython
3330632
<reponame>chameleon-hpc/chameleon-scripts import os, sys import numpy as np import statistics as st import matplotlib.pyplot as plt F_SIZE = 16 plt.rc('font', size=F_SIZE) # controls default text sizes plt.rc('axes', titlesize=F_SIZE) # fontsize of the axes title plt.rc('axes', labelsize=F_SIZE) ...
StarcoderdataPython
1732094
<gh_stars>1-10 # Python - 3.6.0 remove_exclamation_marks = lambda s: s.replace('!', '')
StarcoderdataPython
1626416
<reponame>westerncapelabs/django-wcl-skel<filename>{{cookiecutter.repo_name}}/{{cookiecutter.app_name}}/urls.py from django.conf.urls import url, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'user', views.UserViewSet) router.register(r'group', views.G...
StarcoderdataPython
9680286
<filename>molsysmt/element/group/terminal_capping/is_terminal_capping.py<gh_stars>0 from .names import names def is_terminal_capping(name): return (name in names)
StarcoderdataPython
12831536
# Write functions for sending email here. from core.models import Bibtex from django.contrib.auth.decorators import login_required from django.core.mail import send_mail from django.template.loader import get_template from notification.const import address @login_required def send_email_test(): # 件名 subject =...
StarcoderdataPython
4823514
__all__ = [ 'suggest_filename', 'template_to_filepath', ] import re from pathlib import Path import more_itertools from .constants import CHARACTER_REPLACEMENTS, TEMPLATE_PATTERNS from .utils import list_to_single_value def _replace_invalid_characters(filepath): for char in CHARACTER_REPLACEMENTS: filepath = ...
StarcoderdataPython
3473514
<reponame>sebtelko/pulumi-azure-native # coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** 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, ...
StarcoderdataPython
1833685
<filename>iron/utilities/stitch_mate_pair_alignments.py #!/usr/bin/python import sys,argparse, re from subprocess import Popen, PIPE from SamBasics import MultiEntrySamReader, SAMtoPSLconversionFactory, PSLtoSAMconversionFactory from PSLBasics import PSL from SequenceBasics import rc, read_fasta_into_hash from multipro...
StarcoderdataPython
3462167
<reponame>mbrner/funfolding<filename>funfolding/pipeline/_pipeline.py #!/usr/bin/env python # -*- coding: utf-8 -*- import logging import numpy as np def sample_distribution(weights, max_w=None, random_state=None): logging.debug('Running sample_distribution with max_w={}'.format(max_w)) if not isinstance(ran...
StarcoderdataPython
11224571
<reponame>mateusjustino/cursos<filename>cursoemvideo/python/exercicio/114(siteEstaAcessivel).py<gh_stars>0 from urllib import request site = str(input('Digite um site: ')) try: site1 = request.urlopen('https://www.'+site+'/') except request.URLError: print('O Site não está acessível no momento') else: print...
StarcoderdataPython
6467899
<reponame>d471061c/TimeTracker from flask import jsonify, request, Blueprint from flask_jwt import jwt_required, current_identity from application import db from ..models.project import Project from ..models.task import Task from ..utils.validation import validate_json project_api = Blueprint('project_api', __name__)...
StarcoderdataPython
5025065
N = int(raw_input()) num = [int(i) for i in raw_input().split()] if N != len(num): print 'Not matching' print sorted(list(set(num)))[-2]
StarcoderdataPython
1774886
<filename>data/test_waypoints_show.py<gh_stars>1-10 #!/usr/bin/env python import os import csv import tf import numpy as np import matplotlib.pyplot as plt """ self.lights.len=8 lights[0] : [1172.183, 1186.299], lights[1] : [1584.065, 1156.953], lights[2] : [2126.353, 1550.636], lights[3] : [2178.291, 1819.328], lig...
StarcoderdataPython
254870
<reponame>FranGarciaLopez/quizer-api from lib.response_parser import Response_Parser from lib.db import Db class UserTests: def __init__(self, conn): self.conn = conn def post(self, user_id, test_id): sql_statement = "INSERT INTO user_tests (user_id, test_id) VALUES ('{0}','{1}')".format(user_...
StarcoderdataPython
3276490
<reponame>bresilla/cansim import can import cantools import os import roslibpy import sys import time from kivy.app import App from kivy.uix.widget import Widget from kivy.lang.builder import Builder from kivy.clock import Clock clock = 0.5 quality = 0 capacity = 0 emergency = False cameras = True client = roslibpy...
StarcoderdataPython
3536006
<gh_stars>10-100 from pyradioconfig.parts.ocelot.calculators.calc_misc import CALC_Misc_ocelot class Calc_Misc_Sol(CALC_Misc_ocelot): def calc_misc_Ocelot(self, model): pass def calc_misc_Sol(self, model): """ These aren't really calculating right now. Just using defaults or forced v...
StarcoderdataPython
8060368
<gh_stars>1-10 """A system for defining and representing bit fields. A common use-case for this module is defining SpiNNaker routing keys based on hierarchical bit-fields. See the :py:class:`.BitField` class. """ from six import iteritems from collections import OrderedDict from math import log class BitField(ob...
StarcoderdataPython
5021118
<reponame>dfjxs/dfvfs # -*- coding: utf-8 -*- """Helper functions for Logical Volume Manager (LVM) support.""" def LVMPathSpecGetVolumeIndex(path_spec): """Retrieves the volume index from the path specification. Args: path_spec (PathSpec): path specification. Returns: int: volume index or None if not ...
StarcoderdataPython
6519621
<reponame>nivlekp/abjad-ext-nauert import abjadext.nauert def test_WeightedSearchTree___init___01(): abjadext.nauert.WeightedSearchTree()
StarcoderdataPython
11279355
<reponame>JunhoPark0314/few-shot-object-detection from .defaults import DefaultPredictor, DefaultTrainer, default_argument_parser, default_setup, DefaultBankTrainer from .train_loop_wi_bank import BankTrainer from .hooks import *
StarcoderdataPython
6555348
#!/usr/bin/env python3 import pandas as pd import numpy as np import statsmodels.formula.api as smf # --- (BOBA_CONFIG) { "graph": [ "B1->C", "B2->C", "C->D1->F1", "C->D2->F1", "C->F2" ], "decisions": [ {"var": "sample_size", "options": [1284, 2568]}, {"var": "rt", "options": ["adjus...
StarcoderdataPython
12824732
<reponame>yuguiyang/python_demo # -*- coding: utf-8 -*- """ Created on Thu Aug 10 16:24:02 2017 @author: hexo """ import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties #引用Windows中的字体 font_set = FontProperties(fname=r'C:\Windows\Fonts\simsun.ttc', size=15) plt.figure(u'中文') plt.plot([...
StarcoderdataPython
6548792
<gh_stars>0 #!/usr/bin python # coding: utf8 import psycopg2 conn = psycopg2.connect("dbname='scp'\ user='scp'\ host='localhost'\ password='<PASSWORD>'") c = conn.cursor() query = """ INSERT INTO servicos_cid (cid_id, descricao) VALUES ('A00.0', 'Cólera devida a Vibrio 01, biótipo '), ('A00.1'...
StarcoderdataPython
1960410
input = """36000000""" # number of presents for a house = sum(house number distinct factors including itself and 1) * 10 import math def num_presents(h): sum_factors = set() for i in range(1, math.floor(math.sqrt(h)) + 1): if h % i == 0: sum_factors.add(i) sum_factors.add(int(...
StarcoderdataPython
12808284
import ssl from datetime import timezone from typing import Any, Dict, Tuple, List, Optional from dateparser import parse from mailparser import parse_from_bytes from imap_tools import OR from imapclient import IMAPClient import demistomock as demisto from CommonServerPython import * class Email(object): def __...
StarcoderdataPython
3595910
from typing import Optional, List import uuid, datetime from pydantic import BaseModel, Field class SubTask(BaseModel): subname: str = Field(...) completed: bool = False class TaskModel(BaseModel): id: str = Field(default_factory=uuid.uuid4, alias="_id") name: str = Field(...) description: str = ...
StarcoderdataPython
159548
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ------------------------------------------------- @ Author : Max_Pengjb @ date : 2018/9/23 22:37 @ IDE : PyCharm @ GitHub : https://github.com/JackyPJB @ Contact : <EMAIL> ----------------------------...
StarcoderdataPython
5150991
<filename>nnAvicaching_find_rewards.py #!/usr/bin/env python # ============================================================================= # nnAvicaching_find_rewards.py # Author: <NAME> -- github: @anmolkabra # Project: Solving the Avicaching Game Faster and Better (Summer 2017) # ----------------------------------...
StarcoderdataPython
9774903
<filename>lib/examle1.py import pandas import numpy from sklearn.model_selection import train_test_split column_names = ["Sample code number", "Clump Thickness", "Uniformity of of Cell Size", "Uniformity of Cell Shape", "Marginal Adhesion", "Single Epithelial Cell Size", "Bare Nuclei", "Bland Chromatin", "Norm...
StarcoderdataPython
9656798
<filename>Simple_CenterNet/nets/hourglass.py import numpy as np import torch import torch.nn as nn class convolution(nn.Module): def __init__(self, k, inp_dim, out_dim, stride=1, with_bn=True): super(convolution, self).__init__() pad = (k - 1) // 2 self.conv = nn.Conv2d(inp_dim, ...
StarcoderdataPython
3599333
<gh_stars>0 import sys import cv2 import os os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' output_path = './graded_images/' from SingleDetectionAndRecognition import classify arguments = len(sys.argv) if arguments == 2: _, path = sys.argv image = cv2.imread(os.path.join(path)) out_image = classify(image) ...
StarcoderdataPython
3528492
""" (c) RIKEN 2015. All rights reserved. Author: <NAME> This software is released under the new BSD License; see LICENSE. """ from yamtbx.dataproc.command_line.pilatus_for_crystfel import make_geom_decomposed_for_raw from yamtbx.dataproc.XIO import XIO from yamtbx.dataproc import crystfel from yamtbx.dataproc.crystfe...
StarcoderdataPython
3224767
import swiftclient from django.db import models from django.conf import settings import django_filters from rest_framework.filters import FilterSet from feeds.models import Feed, FeedFile from .fields import CPUField, MemoryField # API types TYPE_CHOICES = [("string", "String values"), ("float", "Float values"), ...
StarcoderdataPython
12819588
# -*- coding: utf-8 -*- """Top-level package for git-code-counter.""" __author__ = """git-code-counter""" __email__ = '<EMAIL>' __version__ = '0.1.0'
StarcoderdataPython
3259928
<reponame>jhkloss/libg3n_frontend<filename>config/module_config.py<gh_stars>0 from libg3n.modules.java.java_library import JavaLibrary from libg3n.modules.python.python_library import PythonLibrary from libg3n.modules.java.java_config import JavaConfig from libg3n.modules.python.python_config import PythonConfig MOD...
StarcoderdataPython
8060905
import sys import os import time import logging from multiprocessing import Manager from ruuvitag_sensor.data_formats import DataFormats from ruuvitag_sensor.decoder import get_decoder, parse_mac log = logging.getLogger(__name__) if os.environ.get('RUUVI_BLE_ADAPTER') == 'Bleson': from ruuvitag_sensor.adapters....
StarcoderdataPython
6699343
<reponame>donaldsa18/VindictusDyeFinder import cv2 import win32con import win32gui import win32ui import win32api import numpy as np class RGBFinder: def __init__(self, gui=None): self.top = 268 self.left = 649 self.w = 907 - 651 # 904-651 self.h = 524 - 268 # 498-268+37 self.x = 0 self.y = 0 self.vi...
StarcoderdataPython
3527484
<reponame>daninge98/shilling from web3 import Web3, HTTPProvider import time import setup as s import json import os import siaproof as sia import pickle import datetime w3 = Web3(HTTPProvider('http://127.0.0.1:7545')) IS_OUTSOURCING_PROOFS = False import sys sys.path.append('./posw') from posw.posw import * from po...
StarcoderdataPython
1622655
from proxy_parse import ProxyParser from proxy_parse.spiders import HideMySpider def test_proxy_parser(): proxy_parser = ProxyParser(scrapy_spiders=[HideMySpider]) result = proxy_parser.parse() assert type(result) is list assert all(type(proxy) is str and ":" in proxy for proxy in result)
StarcoderdataPython
6618526
<filename>Python/Dynamic_Programming/fibonacci_best.py # Calculating Nth Fibonacci Number (Best Method) # Time -> O(N) # Space -> O(3) def fibonacci_best(n: int) -> int: val1, val2 = 0, 1 for _ in range(n): val3 = 0 val2 += val1 val3 += val1 val1 = val2 val2 = val3 ...
StarcoderdataPython
8124903
<reponame>NeonOcean/Environment<gh_stars>1-10 from situations.situation import Situation from venues.scheduling_zone_director import SchedulingZoneDirector import services class GoDancingZoneDirector(SchedulingZoneDirector): INSTANCE_TUNABLES = {'go_dancing_background_situation': Situation.TunableReference(descrip...
StarcoderdataPython
9740523
<gh_stars>10-100 import argparse import numpy as np from gensim.models import KeyedVectors from gensim.models import Word2Vec from gensim.models.word2vec import LineSentence import time from nltk.corpus import words import re import sys, os sys.path.insert(0, os.path.abspath(".")) from embed.embed_helper import train_w...
StarcoderdataPython
12851609
<reponame>cs-fullstack-2019-spring/django-authentication-cw-bettyjware11 from django.shortcuts import render from django.shortcuts import HttpResponse from .forms import FoodFitnessForm from django.contrib.auth.models import User # function to test with def index(request): return HttpResponse("You made it.") # ...
StarcoderdataPython
4927243
import torch.nn as nn import torch class SignMseLoss(nn.Module): def __init__(self, weight_rate=1): super().__init__() self.weight = weight_rate def forward(self, input, target): target[target < 0.5] = 0 input[target < 0.5] = 0 return ((input - target) ** 2).sum() / in...
StarcoderdataPython
8121758
# Copyright 2019 Google 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 required by applicable law or agreed to in writing,...
StarcoderdataPython
4943156
# coding: utf-8 import numpy import chainer import chainer.functions as F import chainer.links as L from PIL import Image """ Convolution: out_size = (in_size + pad * 2 - ksize) / stride + 1 Inception: out_channels = out1 + out3 + out33 + proj_pool(default: in_channels) out_size = Convolution2d(ksize=3, pad=1, ...
StarcoderdataPython
1683385
import sys , pygame def check_keydown_events(event,ai_settings,screen,character_A): if event.key == pygame.K_RIGHT: character_A.moving_right = True elif event.key == pygame.K_LEFT: character_A.moving_left = True def check_keyup_events(event,character_A): ...
StarcoderdataPython
11370074
import pandas as pd from autoscalingsim.utils.utilization import EntityUtilization from autoscalingsim.utils.df_convenience import convert_to_class waiting_time_metric_name = 'waiting_time' waiting_requests_count_metric_name = 'waiting_requests_count' class BufferUtilization(EntityUtilization): metrics = [ wait...
StarcoderdataPython
3365829
#!/usr/bin/env python import bcc import time import collections import datetime import os import signal import errno import json try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse import threading import socket import BaseHTTPServer import SocketServer import string import...
StarcoderdataPython
3496113
#!/usr/bin/python import sys, os, operator, smtplib, re from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def send_email(addr, subject, msg_body): email_subject = subject from_addr="<EMAIL>" to_addr = [addr, '<EMAIL>'] msg = MIMEMultipart() msg['From'] = 'Confer Team <...
StarcoderdataPython
189547
# Python 2 and 3: # To make Py2 code safer (more like Py3) by preventing # implicit relative imports, you can also add this to the top: # from __future__ import absolute_import # from transformations import quaternion_from_euler, quaternion_matrix, euler_matrix # from transformations import euler_matrix try: ...
StarcoderdataPython
1948604
from mxnet import nd, autograd import random from time import time num_inputs = 2 num_examples = 1000 true_w = [2, -3.4] true_b = 4.2 features = nd.random.normal(scale=1, shape=(num_examples, num_inputs)) labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b labels += nd.random.normal(scale=0.01, s...
StarcoderdataPython
9666793
#!/usr/bin/env python # program runs in the background, scanning for bluetooth devices # at a regular interval. # uses the following shell utility # hcitool inq --flush outputs: # Inquiring... # 60:FB:42:82:2E:7B clock offset: 0x5129 class: 0x38010c # 60:FB:42:82:2E:7B clock offset: 0x5129 class: 0x38010c # .....
StarcoderdataPython
396929
<reponame>JasperSnoek/basenji<filename>bin/basenji_hdf5_genes.py<gh_stars>1-10 #!/usr/bin/env python # Copyright 2017 Calico 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:...
StarcoderdataPython
1943999
<filename>var/spack/repos/builtin/packages/libszip/package.py # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Libszip(AutotoolsPackage): "...
StarcoderdataPython
11244173
""" Dans_Diffraction Examples Calculate exchange path between magnetic atoms """ import sys,os import numpy as np import matplotlib.pyplot as plt # Plotting cf = os.path.dirname(__file__) sys.path.insert(0,os.path.join(cf,'..')) import Dans_Diffraction as dif f = cf+'/../Dans_Diffraction/Structures/Sr3LiRuO6_C2\'c\'....
StarcoderdataPython
4990595
# Generated by Django 3.2.4 on 2021-07-13 23:57 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('dashboard', '0002_auto_20210713_1642'), ] operations = [ migrations.AlterField( model_name='rep...
StarcoderdataPython
1842927
<gh_stars>0 # Copyright 2022 Recruit Co., Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
StarcoderdataPython