id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
175430
import re class RegexPattern(object): def __init__(self, regex, handler, default_kwargs={}): self.regex = re.compile(regex, re.UNICODE) self.callback = handler self.default_kwargs = default_kwargs def resolve(self, line): match = self.regex.search(line) if match: ...
StarcoderdataPython
3211217
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Classes and utilites to keep track of files associated to an analysis. The main class is `FileArchive`, which keep track of all the files associated to an analysis. The `FileHandle` helper class encapsulates information on a particular file. """ from...
StarcoderdataPython
3340806
""" Deskews file after getting skew angle """ import optparse import numpy as np import matplotlib.pyplot as plt from .skew_detect import SkewDetect from skimage import io from skimage.transform import rotate class Deskew: def __init__( self, input_numpy=None, output_numpy=False, input_file=None, dis...
StarcoderdataPython
1722963
from setuptools import setup setup(name='monitor_manager', url='https://github.com/carlos-devworks/monitor_manager', project_urls={ 'Documentation': 'https://carlos-devworks.github.io/monitor_manager', }, license='MIT', author='carlos.devworks', author_email='<EMAIL>', pac...
StarcoderdataPython
34651
<reponame>ronbeltran/webapp2-bedrock import os import webapp2 import jinja2 import config from app.utils.compressor import WEBASSETS_ENV JINJA_ENV = jinja2.Environment( autoescape=lambda x: True, extensions=['jinja2.ext.autoescape', 'webassets.ext.jinja2.AssetsExtension'], loader=jinja2....
StarcoderdataPython
3230123
<reponame>grillazz/fastapi-mongodb import pytest from fastapi import status from httpx import AsyncClient @pytest.mark.anyio async def test_health_check(client: AsyncClient): response = await client.get("/health-check") assert response.status_code == status.HTTP_200_OK assert response.json()["version"] ==...
StarcoderdataPython
3361839
from mmdet.datasets.builder import build_dataloader from .builder import DATASETS, build_dataset from .custom_3d import Custom3DDataset from .dataset_wrappers import MultiViewMixin from .kitti_dataset import KittiDataset from .kitti_monocular_dataset import KittiMultiViewDataset, KittiStereoDataset from .lyft_dataset i...
StarcoderdataPython
1613407
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import unittest import webapp2 import webtest from google.appengine.ext import ndb from google.appengine.ext import testbed from dashboard.pin...
StarcoderdataPython
1744825
""" MIT License Copyright (c) 2019 lukeciel 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, dist...
StarcoderdataPython
17408
from bs4 import BeautifulSoup as soup from urllib.request import Request, urlopen from datetime import date import math import openpyxl import pandas as pd fname = 'https://www.governing.com/gov-data/census/state-minority-population-data-estimates.html' req = Request(fname, headers={'User-Agent': 'Mozilla/5.0'}) webpa...
StarcoderdataPython
183675
# Generated by Django 4.0.2 on 2022-03-05 10:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('instructors', '0015_remove_user_avatar_user_avatar_url_and_more'), ] operations = [ migrations.AddField( model_name='user', ...
StarcoderdataPython
4814922
from datetime import datetime, date from dateutil.relativedelta import relativedelta import json import math import requests from typing import Any, List, Optional, Dict from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response from app.core.config import settings from app import crud, schemas ...
StarcoderdataPython
3234470
<gh_stars>0 File = open("KeySender.txt", "r+") File2 = open("KeyHexed.txt", "w+") counter = 0 revcount = 7 value = 0 while True: char = File.read(1) if not char : break elif char: try: a = int(char[0]) if counter % 8 == 0: if value != 0: ...
StarcoderdataPython
1654769
<reponame>vanSultan/anal_dev_algo from math import sin from random import random, normalvariate from typing import Callable, Tuple, List from vector_2d import Vector def function_1(x: float) -> float: # [0, 1] return x ** 3 def function_2(x: float) -> float: # [0, 1] return abs(x - 0.2) def funct...
StarcoderdataPython
25880
"""A tool for modeling composite beams and aircraft wings. ``Aerodynamics`` This module provides the aerodynamics models used within AeroComBAT ``AircraftParts`` This module provides a full-fledged wing object that can be used to determine if a design is both statically adequate as well as stable. ``...
StarcoderdataPython
152163
import pandas import pandas._period import pandas._sparse import pandas._testing import pandas.algos import pandas.hashtable import pandas.index import pandas.json import pandas.lib import pandas.msgpack import pandas.parser import pandas.tslib import sys if sys.version_info >= (2, 7): import pandas.io.excel prin...
StarcoderdataPython
1727391
<filename>Week_2(Sensors and Actuators)/Python Codes/qstp_q2.py #THE PROGRAMS ASKS FOR THE INFECTED HOUSES CORDINATES AND THENGIVES BACK THE HOUSES THAT ARE PRONE TO INFECTION BY A SIMPLE ALORITHM #PROVIDE INPUTS AS ASKED AND WATCH OUT FOR THE COORDINATES TO BE FROM 0-9 0-9 import numpy as np #------------------------...
StarcoderdataPython
9732
<filename>divsum_stats.py<gh_stars>0 #!/usr/bin/python import sys from subprocess import call print "divsum_count.py ListOfDivsumFiles\n" try: files = sys.argv[1] except: files = raw_input("Introduce RepeatMasker's list of Divsum files with library size (tab separated): ") files = open(files).readlines() to...
StarcoderdataPython
3201647
<gh_stars>100-1000 # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. from typing import TYPE_CHECKING if TYPE_CHECKING: from cdm.resolvedmodel import ResolvedTraitSet class RelationshipInfo: def __init_...
StarcoderdataPython
10399
<reponame>cl9200/nbase-arc<gh_stars>0 # # Copyright 2015 N<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 app...
StarcoderdataPython
1787559
import scrapy # from tutorial.items import ReviewItem from scrapy_splash import SplashRequest class ReviewSpider(scrapy.Spider): name = 'review' def start_requests(self): url = 'https://kr.iherb.com/pr/21st-century-calcium-magnesium-zinc-d3-90-tablets/10695' product_urls = [ 'http...
StarcoderdataPython
3323868
<filename>ontology/neural_network/sherlock/listify_length_k18.py #!/bin/python import listify_length listify_length.optimize_list_len(18)
StarcoderdataPython
148615
<gh_stars>0 """ FBDTools library - icecream package This module contains useful functions to compute and aggregate predictions and target values. """ from typing import Any, Callable, List, Tuple, Union import numpy as np import pandas as pd from sklearn.cluster import KMeans from .config import options from .discre...
StarcoderdataPython
4839692
<gh_stars>1-10 import os import pytest import kapre from kapre import backend as KPB from tensorflow.keras import backend as K import numpy as np TOL = 1e-5 def test_amplitude_to_decibel(): """test for backend_keras.amplitude_to_decibel""" from kapre.backend_keras import amplitude_to_decibel x = np.arra...
StarcoderdataPython
3270539
#!/usr/bin/env python3 import numpy as np result = 0 input = np.loadtxt('day04/input.txt',dtype=int,max_rows=1,delimiter=',') boards = np.loadtxt('day04/input.txt',skiprows=1,dtype=int) boards = np.array_split(boards,len(boards)/5) old_boards = [] def game_loop(): for draw in input: for board in boards: if ha...
StarcoderdataPython
196112
# Copyright (c) 2021 <NAME> # # 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, distribute, ...
StarcoderdataPython
1647783
<gh_stars>1-10 import os import time time.sleep(2) def mount_sdb1(): os.system("sudo mount /dev/sdb1 /mnt" ) def mount_sdb2(): os.system("sudo mount /dev/sdb2 /mnt") os.system("sudo fdisk -l") print("fdisk command run") if True: mount_sdb1() print("sdb1 has mount") else: mount_sdb2() print("sdb2 has mount")...
StarcoderdataPython
183029
<reponame>peleg525/Ourlogger<gh_stars>0 from Ourlogger.Ourlogger import logger
StarcoderdataPython
3301935
<reponame>kwonhyeokmin/ImageSimilarity from tensorflow.keras.datasets import mnist import tensorflow as tf from functools import partial import itertools import numpy as np import time from model import create_model import os import os.path as osp from pathlib import Path import logging logger = logging.getLogger() lo...
StarcoderdataPython
3310080
from core.himesis import Himesis, HimesisPreConditionPatternLHS import cPickle as pickle from uuid import UUID class HFindTwoApplyElementsWithTraceLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HFindTwoApplyElementsWithTraceLHS. ...
StarcoderdataPython
3235553
<reponame>billboggs/elasticsearch-HQ """ .. module:: status .. moduleauthor:: <NAME> <<EMAIL>> """ import json from urllib.parse import unquote_plus from flask import current_app, url_for from flask_restful import Resource from elastichq.service import HQService from . import api from ..common.api_response import AP...
StarcoderdataPython
174059
# Generated by Django 2.1.2 on 2018-12-13 21:21 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('experience', '0013_auto_20181213_1610'), ] operations = [ ]
StarcoderdataPython
117699
<gh_stars>10-100 from itertools import count from operator import mul from functools import reduce grid = [line.strip() for line in open("inputs/03.txt").readlines()] traverse = lambda right, down: sum(grid[y][x % len(grid[0])] == '#' for (x, y) in zip(count(0, right), ...
StarcoderdataPython
3225941
""" Forward-compatibility support for Python 2.4 and earlier """ # from jaraco.compat 1.2 try: from functools import wraps except ImportError: def wraps(func): "Just return the function unwrapped" return lambda x: x try: import hashlib except ImportError: from setuptools._backport imp...
StarcoderdataPython
45347
<filename>board_app/migrations/0004_alter_boardmodel_snsimage.py # Generated by Django 3.2.3 on 2021-08-01 12:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('board_app', '0003_alter_boardmodel_snsimage'), ] operations = [ migrations....
StarcoderdataPython
84102
""" Connection module. """ from lib import connect DB = connect()
StarcoderdataPython
1769903
from django.conf.urls import url from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.network, name = 'network'), ]
StarcoderdataPython
104825
<filename>astropynamic/time.py import datetime from astropynamic import dates def julian_date(dt=None, year=None, month=1, day=1, hour=0, minute=0, second=0, modified=True): r""" Calculates the Julian date or modified Julian date (if specified). Parameters ---------- dt : datetime, default None ...
StarcoderdataPython
1676919
<reponame>deadsnakes/python3.2<filename>Lib/test/test_super.py """Unit tests for new super() implementation.""" import sys import unittest from test import support class A: def f(self): return 'A' @classmethod def cm(cls): return (cls, 'A') class B(A): def f(self): return sup...
StarcoderdataPython
3395881
<gh_stars>1-10 # -*- coding: utf-8 -*- """Collection of functions for the manipulation of time series.""" from __future__ import absolute_import, division, print_function import warnings import mando import pandas as pd import typic from mando.rst_text_formatter import RSTHelpFormatter from scipy.stats import t fro...
StarcoderdataPython
3301075
<filename>stacker/commands/stacker/destroy.py<gh_stars>1-10 """Destroys CloudFormation stacks based on the given config. Stacker will determine the order in which stacks should be destroyed based on any manual requirements they specify or output values they rely on from other stacks. """ from __future__ import print_...
StarcoderdataPython
1611183
<reponame>tarunchhabra26/PythonPlayground from __future__ import division, print_function from random import * RANGES = [(0, 10), (0, 10), (1, 5), (0, 6), (1, 5), (0, 10)] def mws(m): """ Driver method for MaxWalkSat :param m: instance of model :return: None """ print("Running max walk sat fo...
StarcoderdataPython
3249082
<reponame>ameen-a/Stock-Predictor-9000 # # Created by <NAME> # *** author cannot guarantee effectiveness of this stock prediction program *** # * however if a profit is made, the author requests 80% * # # ================================ IMPORTS ==============================...
StarcoderdataPython
104049
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' surface2stations.py Extract synthetics at given stations from a NetCDF database of surface wavefield created by AxiSEM3D (named axisem3d_surface.nc by the solver) and save them into a NetCDF waveform database (same as the built-in NetCDF output axisem3d_synthetics.nc)...
StarcoderdataPython
1743995
<gh_stars>0 import pandas as pd import numpy as np df_train = pd.read_csv("trainset2-15.csv") X = df_train.iloc[:, 0:-1].values y = df_train.iloc[:, -1].values w = np.array([1.6441,2.0457]) y_pred = np.dot(X, w) print(y_pred) # Visualizing from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt fig...
StarcoderdataPython
1656136
<filename>Seminar1/pwned_v2.py # https://haveibeenpwned.com/API/v2 import pwnedpasswords import requests import hashlib import matplotlib.pyplot as plt def load_passwords(file_name: str) -> dict: """ Function that loads most common passwords to memory. """ with open(file_name, 'r') as f: ...
StarcoderdataPython
3324187
from django.db import models # Create your models here. class Folder(models.Model): path = models.CharField(max_length=8192, primary_key=True) email = models.EmailField() child_of_path = models.CharField(max_length=8192) class SubTask(models.Model): task_id = models.IntegerField() title = model...
StarcoderdataPython
3380175
<gh_stars>0 """ .. module:: pdb :synopsis: This module implements functions for PDB files manipulation. """ # Third-party modules import os import logging from Bio.PDB.PDBIO import PDBIO from Bio.PDB import Dice from Bio.PDB import Select # Set logging info logging.basicConfig(filename='flex.log', filemode='w', ...
StarcoderdataPython
1719655
from config import opt import torch import math from copy import deepcopy import types from torch import nn import torchvision from torchvision.models.detection.anchor_utils import AnchorGenerator from torchvision.models.detection.rpn import RPNHead from torchvision.models.detection.retinanet import RetinaNetHead from ...
StarcoderdataPython
3297935
class failed_login(Exception): """ This exception is raised when a user fails to log in. """ pass class disallowed_url_input(Exception): """ This exception is raised when a user tries to send a message with an url (outside of KoGaMa Domains). """ pass class too_many_requests(Exception): """ This e...
StarcoderdataPython
45827
<filename>tests/utils.py # -*- coding: utf-8 -*- from matchpy.expressions.constraints import Constraint from matchpy.expressions.substitution import Substitution from matchpy.expressions.expressions import Pattern class MockConstraint(Constraint): def __init__(self, return_value, *variables, renaming=None)...
StarcoderdataPython
46472
<gh_stars>1-10 #!/usr/bin/env python """This is the unit test module for the causal matrix module. """ import pandas as pd import numpy as np from podspy.structure import CausalMatrix class TestCausalMatrix: def test_build_from_logtable(self, simple_log_table): # sort activities cmat = Causal...
StarcoderdataPython
88666
import numpy import matplotlib.pylab as plt class LinearHeadHead(object): """ Solves the system: \div \frac{\rho}{\mu} k \grad (p + \rho g z) = 0 on the domain [x_0, x_1] \cross [z_0,z_1] Boundary conditions are given by: h(x_0,z,t) = h_0 [m] => p(x_0,z,t)=(h_0-z) \rho g h(x_1,...
StarcoderdataPython
1654459
import unittest from rfb_mc.component.eamp.eamp_edge_scheduler import EampEdgeScheduler from rfb_mc.test.component.eamp.eamp_edge_scheduler import EampEdgeSchedulerTestCaseBase class TestEampEdgeScheduler(unittest.TestCase, EampEdgeSchedulerTestCaseBase): def get_test_case(self): return self def get_...
StarcoderdataPython
1633701
from datetime import date, timedelta from unittest.mock import PropertyMock, patch import pytest from django.core.exceptions import ValidationError from cdhweb.pages.models import ( DateRange, DisplayUrlMixin, ExternalAttachment, LocalAttachment, RelatedLinkType, ) class TestRelatedLinkType: ...
StarcoderdataPython
1620745
<filename>PokerRL/game/PokerEnvStateDictEnums.py<gh_stars>10-100 # Copyright (c) 2019 <NAME> """ Enum keys to PokerEnv's state_dict objects. """ class EnvDictIdxs: current_round = "current_round" side_pots = "side_pots" main_pot = "main_pot" board_2d = "board_2d" last_action = "last_action" ...
StarcoderdataPython
1707380
<gh_stars>1-10 """ API that allows to retrieve user's messages """ import traceback import json from decimal import Decimal from flask import Blueprint, request, make_response, jsonify, abort from lifoid.logging.mixin import ServiceLogger from lifoid.message.repository import MessageRepository from lifoid.utils.asdict ...
StarcoderdataPython
1681592
<reponame>UdayanSinha/Code_Blocks import serial from time import sleep #setup serial comm port="/dev/ttyACM0" #serial port serial_arduino=serial.Serial(port, 9600) #start serial comm@9600bps serial_arduino.flushInput() #clear i/p buffer try: while True: if(serial_arduino.i...
StarcoderdataPython
1772423
# -*- coding: utf-8 -*- # Copyright 2016 Resonai Ltd. 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 requir...
StarcoderdataPython
3267226
""" The MIT License (MIT) Copyright (c) 2020-Current Skelmis 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, mer...
StarcoderdataPython
3359219
import argparse from pdm.cli.commands.base import BaseCommand from pdm.project import Project class Command(BaseCommand): """Generate completion scripts for the given shell""" arguments = [] def add_arguments(self, parser: argparse.ArgumentParser) -> None: parser.add_argument( "shel...
StarcoderdataPython
1796572
<reponame>lixinyu2001/eesen-pytorch-thchs30 import os import argparse import json import torch from torch import nn, autograd import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.nn.utils import clip_grad_value_ from dataset import KaldiFeatureLabelReader from model import Net ...
StarcoderdataPython
192373
<reponame>RobotLocomotion/drake-python3.7 """ Provides a unittest for high-level deprecation testing API (``catch_drake_warnings``), relevant to deprecations in pybind11 bindings of C++ API. For more details, please review the following documentation: - https://drake.mit.edu/code_review_checklist.html - https://drake...
StarcoderdataPython
3286893
# data TRAINING_DATA_FILE = 'houseprice.csv' PIPELINE_NAME = 'lasso_regression' TARGET = 'SalePrice' # input variables FEATURES = ['MSSubClass', 'MSZoning', 'Neighborhood', 'OverallQual', 'OverallCond', 'YearRemodAdd', 'RoofStyle', 'MasVnrType', 'BsmtQual', 'BsmtExposure', 'Heati...
StarcoderdataPython
1691695
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from pywt import WaveletPacket2D import pywt.data arr = pywt.data.aero() wp2 = WaveletPacket2D(arr, 'db2', 'symmetric', maxlevel=2) # Show original figure plt.imshow(arr, interpolation="nearest", cmap=plt.cm.gray) pa...
StarcoderdataPython
1753049
<gh_stars>0 # -*- coding: utf-8 -*- """ Test module for the Scraper against Finn.no housing search """ __author__ = '<NAME>' __email__ = '<EMAIL>' from uuid import UUID import pytest as pt from source.app import Finn from source.util import TrackingError class TestFinn: """ Test cases for the Finn scrap...
StarcoderdataPython
3212895
"""Algorithms for sorting session requests.""" import random from abc import ABC, abstractmethod from typing import List from serving_dataclasses import SessionRequest from serving_system import ServingSystem class RequestSorter(ABC): """Defines the interface for request sorting algorithms.""" @abstractmeth...
StarcoderdataPython
1713441
from convoy.convoy import Convoy
StarcoderdataPython
1640280
<reponame>KorKite/tf_alloc # __init__.py # Copyright (C) 2022 (<EMAIL>) and contributors # <NAME> # github.com/korkite try: import tensorflow as tf except: raise ModuleNotFoundError("You must install tensorflow for your environment first. This package doesn't contain tensorflow installation.") __version__ = ...
StarcoderdataPython
3222357
import numpy as np import pandas as pd from flask import Flask, request, render_template import joblib #Creating the flask app app = Flask(__name__) model = joblib.load("Loan_Predictor.pkl") @app.route('/') def home(): return render_template('Loan_App_Template.html') @app.route('/predict', methods...
StarcoderdataPython
85363
import pytest from challenges.queue_with_stacks.queue_with_stacks import PseudoQueue, Stack, Node, InvalidOperationError def test_dequeue_from_example(): pq = PseudoQueue() pq.enqueue(5) pq.enqueue(3) pq.enqueue(1) actual = pq.dequeue() expected = 5 assert actual == expected
StarcoderdataPython
1629196
from collections import namedtuple """ FacegramThread holds thread related data """ FacegramThread = namedtuple("FacegramThread", "facebookID telegramChatId telegramUsername isGroup") """ FacegramUser holds telegram user related information """ FacegramUser = namedtuple("FacegramUser", "userId accessHash")
StarcoderdataPython
187764
<reponame>noqqe/rvo<gh_stars>10-100 import click import rvo.db as db import rvo.utils as utils @click.command(short_help="Verifys the connection to the database", help=""" Verifys the connection to the database and checks read/write access """) @click.pass...
StarcoderdataPython
1756127
import os import sys import collections if sys.version_info[0] == 2: import xml.etree.cElementTree as ET else: import xml.etree.ElementTree as ET from PIL import Image import torch import torchvision import cv2 import numpy as np import random import pathlib def resize_bbox(bbox,scale_transform): min_x, m...
StarcoderdataPython
3328220
<gh_stars>0 from django.http import HttpResponse from django.shortcuts import render import operator def homepage(request): #return HttpResponse('hello') return render(request, 'home.html',{'Hithere': 'this is me'}) def eggs(request): #return HttpResponse('Eggs are great!') return HttpResponse('<h1>egg...
StarcoderdataPython
3256252
<gh_stars>1-10 #!/usr/bin/env python # Copyright 2021 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 ap...
StarcoderdataPython
3331891
<reponame>shoaibur/SWE<filename>Interview-Preparation/Amazon/treesgraphs-word-ladder-ii.py class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: out = [] wordSet = set(wordList) q = collections.deque() q.append(([beginWo...
StarcoderdataPython
3385898
<reponame>Shanksum/eyevis-tool<filename>csv/csvparser.py import csv import os from shutil import copyfile from PIL import Image class CSVParser: eyevido_ds = dict() id_mapping = dict() merged_mouse_data = [] merged_gaze_data = [] def csv_import(self): # print('import started') pat...
StarcoderdataPython
1778791
<reponame>idc9/yaglm from time import time from warnings import warn from yaglm.solver.base import GlmSolverWithPath from yaglm.autoassign import autoassign from yaglm.utils import is_multi_response, get_shapes_from, clip_zero from yaglm.config.penalty_utils import get_flavor_kind from yaglm.config.penalty import NoPe...
StarcoderdataPython
3223690
''' Determine yelp id for businesses by phone number. Use the last file written with the yelp_id.py script. Run yelp_id again on the results to pick up itmes that have a phone number but no yelp id. Then manually reconcile. 20160625 <NAME> ''' import json import re import pandas as pd from yelpapi import YelpAPI #d...
StarcoderdataPython
25970
"""Finance Database view""" __docformat__ = "numpy" import os import pandas as pd from tabulate import tabulate from gamestonk_terminal import feature_flags as gtff from gamestonk_terminal.etf import financedatabase_model from gamestonk_terminal.helper_funcs import export_data def display_etf_by_name( name: str,...
StarcoderdataPython
3392925
<reponame>ludwiglierhammer/pyhomogenize<filename>pyhomogenize/operators/showvar.py import pyhomogenize as pyh help=""" showvar : Print variable names. At first, merge files if needed. usage: pyhomogenize showvar -i ifile1 [ifile2 [ifileN]] """ def start(args): file = pyh.netcdf_basics(args.input_files) n...
StarcoderdataPython
74213
<reponame>SilentByte/healthcam<filename>PiCode/src/maskcam/settings.py<gh_stars>1-10 from knobs import Knob from socket import gethostname # Knobs are basically wrappers for os.getenvs that have some niceties CAMERA_NUMBER = Knob(env_name="CAMERA_NUMBER", default=0, description="Raspberry Pi ca...
StarcoderdataPython
1734093
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A screenshot utility, particularly meant for keyboard focused environments Save as whatever you want the command to be named, somewhere in PATH bindsym --release Print exect --nostartup-id grapy.py """ import os from subprocess import Popen, PIPE from tempfile import ...
StarcoderdataPython
113735
<filename>models/encoder.py import torch.nn as nn from models.attention import MultiHeadAttention from models.positionwise import PositionWiseFeedForward from models.ops import create_positional_encoding, create_source_mask, create_position_vector class EncoderLayer(nn.Module): def __init__(self, params): ...
StarcoderdataPython
3322906
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'FileNode' db.create_table('media_tree_filenode', ( ('id', self.gf('django.db.m...
StarcoderdataPython
3389469
<gh_stars>1-10 #%% import random import matplotlib.pyplot as plt import seaborn as sns import tensorflow as tf import tensorflow.keras as keras from itertools import product import pandas as pd import numpy as np import pickle import matplotlib from sklearn.model_selection import StratifiedKFold from math import log2,...
StarcoderdataPython
3334810
from django.template import Library from article.models import Article from django.core.cache import cache CACHE_TIMEOUT=60*10 register = Library() @register.assignment_tag def get_latest_article(number): cache_key='cache_latestarticles'+str(number) latestarticles=cache.get('cache_latestarticles') if lates...
StarcoderdataPython
1748815
#!/usr/bin/env python """ Copyright 2012 endolith at gmail com Copyright 2009 <NAME> at gmail com Translation and modification of http://www.mathworks.com/matlabcentral/fileexchange/26026-bipolar-colormap Based on <NAME>'s hand-crafted colormap for cortical visualisation """ from __future__ import division import s...
StarcoderdataPython
1633769
import unittest import pymysql.cursors # Not a Python dev, this is probably pretty ugly class TestDjConventions(unittest.TestCase): @classmethod def setUpClass(cls): cls.conn = pymysql.connect( host="localhost", user="user", password="password", db="heli...
StarcoderdataPython
43660
<reponame>felixcheruiyot/zazi-core-banking import logging from decimal import Decimal as D from django.utils import timezone from zazi.core import json from .enums import LoanTransactionType from . import utils as api #-------------- logger = logging.getLogger(__name__) #-------------- def process_loan_transac...
StarcoderdataPython
1771780
<reponame>PerformLine/webfriend from __future__ import absolute_import import os from sys import platform def locate_browser_process(): names = [] if os.getenv('WEBFRIEND_BROWSER'): names += os.getenv('WEBFRIEND_BROWSER').split(':') if platform.startswith('linux'): names += [ ...
StarcoderdataPython
40400
from io import StringIO from hypothesis import given, strategies from intentionally_blank import api def test_format_empty_with_empty_string(): with StringIO() as in_file, StringIO() as out_file: api.format_from_file_to_file(in_file, out_file, format_names=["identity"]) assert len(out_file.getva...
StarcoderdataPython
3307020
from datetime import date atual = date.today().year ano = int(input('Qual o ano do seu nascimento?')) idade = atual - ano print(f'O atleta tem {idade} anos. Sua categoria é:') if idade <= 9: print('Mirim') elif 9 < idade <= 14: print('Infantil') elif 14 < idade <=19: print('Junior') elif 19 < idade <= 20: ...
StarcoderdataPython
1686081
<reponame>sapristi/mopidy-bookmarks import tornado.websocket import tornado.ioloop import tornado.escape import tornado.web import logging import functools import pykka from mopidy.internal import jsonrpc from mopidy import models from mopidy.http.handlers import ( WebSocketHandler as MopidyWebSocketHandler, ...
StarcoderdataPython
3276700
"""This module controls everything to do with storing, editing, displaying, and destroying shortcuts (or aliases) to tags.""" import sys import argparse from typing import Tuple, List from halo import Halo # extremely important from inputfuncs.input_reader import ( read_lines_into_dict ) def create_tag_shortc...
StarcoderdataPython
26965
<gh_stars>1-10 from .spaceloads import *
StarcoderdataPython
121812
<filename>py_controls/MemoryManager.py # -*- coding: utf-8 -*- """ Created on Fri Dec 30 15:52:43 2016 @author: robin """ import json from enum import Enum #testing possible enums for readability...(not implemeted) class NrH(Enum): #human data formtat for Json name = 0 human = 1 job = 2 ...
StarcoderdataPython
1720945
<reponame>diego-marcelino/valora-quiz<filename>quiz/users/tests/test_models.py from django.db.utils import IntegrityError import pytest from quiz.users.models import User pytestmark = pytest.mark.django_db @pytest.mark.parametrize('attr', ['name', 'username', 'role']) def test_user_has_attributes(user: User, attr)...
StarcoderdataPython
3246825
<reponame>Saicharan67/Interview-Coding-Questions # Python Program for Floyd Warshall Algorithm # Number of vertices in the graph V = 4 # Define infinity as the large # enough value. This value will be # used for vertices not connected to each other INF = 99999 # Solves all pair shortest path # via Floyd Warshall Alg...
StarcoderdataPython