id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
10423
import os from functools import partial from io import BytesIO import numpy as np import PIL.Image import scipy.misc import tensorflow as tf graph = tf.Graph() sess = tf.InteractiveSession(graph=graph) model_fn = "./models/tensorflow_inception_graph.pb" with tf.gfile.FastGFile(model_fn, 'rb') as f: graph_def = tf...
StarcoderdataPython
197262
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. 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
3390222
import sys sys.setdefaultencoding('utf8')
StarcoderdataPython
11245847
<gh_stars>0 """Initial migration. Revision ID: <PASSWORD> Revises: Create Date: 2020-07-23 23:48:54.534407 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<PASSWORD>' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### comman...
StarcoderdataPython
86329
from Experiment import * from iGIF_NP import * from AEC_Badel import * from Tools import * from Filter_Rect_LogSpaced import * import matplotlib.pyplot as plt import numpy as np import copy import os R_X = {} # List separate experiments in separate folder data_folders_for_separate_experiments = ['seventh_set'...
StarcoderdataPython
8092238
from valor import Valor from discord.ext.commands import Context from util import ErrorEmbed, LongTextEmbed, LongFieldEmbed, guild_name_from_tag import random from datetime import datetime import requests from sql import ValorSQL from commands.common import get_uuid, from_uuid async def _register_leaderboard(valor: Va...
StarcoderdataPython
1853170
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Smartpi Consumption Kalkulator | smartpick.py by rbckman ''' import os import time import requests import code import re from datetime import datetime from datetime import timedelta import argparse from calendar import monthrange def getargs(): parser = argparse.A...
StarcoderdataPython
5178920
<gh_stars>0 #!/usr/bin/env python3 # vim: ts=4 sts=4 et sw=4 from .lexer import tokens, column from .common import ProcyonSyntaxError from .ast import (Node, Value, Ident, BinaryOp, UnaryOp, Function, Conditional, While, FunctionCall, ControlFlowStatement, Comparison, ComparisonOp) # # Procyon pars...
StarcoderdataPython
290608
import unittest from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Structure from pymatgen.core.tensors import Tensor from pymatgen.analysis.elasticity.strain import Strain, Deformation, \ convert_strain_to_deformation, DeformedStructureSet from pymatgen.util.testing import PymatgenTest ...
StarcoderdataPython
4954162
<gh_stars>1-10 # -*- coding: utf-8 -*- import os try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup, find_packages def read(fname): try: with open(os.path.join(os.path.dirname(__file__), fname), "r") as fp: return fp.read().strip() ...
StarcoderdataPython
9732618
import math import pandas as pd import re import sys def read_data(): frame = pd.read_excel('list_one.xls', skiprows=3, header=0) currencies = {} for row in frame.itertuples(): if row._3 in currencies: currencies[row._3]['standards_entities'].append(row.ENTITY) else: ...
StarcoderdataPython
8149425
from collections import ( defaultdict, ) from concurrent.futures.thread import ( ThreadPoolExecutor, ) from itertools import ( groupby, ) import json import logging from operator import ( itemgetter, ) import time from typing import ( Any, ClassVar, Dict, List, Optional, Sequence...
StarcoderdataPython
3526248
<reponame>jeikabu/lumberyard<filename>dev/Tools/Python/2.7.13/mac/Python.framework/Versions/2.7/lib/python2.7/site-packages/pyxb/bundles/wssplat/wsrf_br.py from pyxb.bundles.wssplat.raw.wsrf_br import *
StarcoderdataPython
1981510
import tensorflow as tf from webdnn.frontend.tensorflow.converter import TensorFlowConverter @TensorFlowConverter.register_handler("AllCandidateSampler") def all_candidate_sampler_handler(converter: TensorFlowConverter, tf_op: "tf.Operation"): raise NotImplementedError(f"[TensorFlowConverter] {tf_op.type} is not...
StarcoderdataPython
5198881
# -*- coding: utf-8 -*- """Objec-oriented representation of a chessboard. This module contains code that represents a chessboard in an object-oriented style. Example: >>> board = Board() >>> board.show() ♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜ ♟︎ ♟︎ ♟︎ ♟︎ ♟︎ ♟︎ ♟︎ ♟︎ ⊡ ⊡ ⊡ ⊡ ⊡ ⊡ ⊡ ⊡ ⊡ ⊡ ⊡ ⊡ ⊡ ⊡ ⊡ ⊡ ⊡ ⊡ ⊡ ⊡ ⊡ ⊡ ⊡...
StarcoderdataPython
5047027
import os import numpy as np from scripts.datautils import MatchedTestSet from train_multimodal_latentodegru_sync import getConfig, visualize_embedding from sklearn.decomposition import PCA from sklearn.manifold import TSNE import matplotlib matplotlib.rcParams.update({'font.size': 14}) import matplotlib.pyplot as...
StarcoderdataPython
12819792
<filename>apollo/Scraper/download_comments.py<gh_stars>0 import json import time import requests from apollo.Scraper.config import ( USER_AGENT, YOUTUBE_COMMENTS_AJAX_URL_NEW, YOUTUBE_COMMENTS_AJAX_URL_OLD, YOUTUBE_VIDEO_URL, ) from apollo.Scraper.extract import extract_comments, extract_reply_cids fro...
StarcoderdataPython
9652046
<gh_stars>0 # Copyright 2015 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. from benchmarks import silk_flags import page_sets from telemetry import benchmark from telemetry.core.platform import tracing_category_filter fro...
StarcoderdataPython
371727
<reponame>m09/mloncode from pathlib import Path from pytest import fixture from mloncode.parsing.java_parser import JavaParser from mloncode.parsing.parser import Nodes @fixture(scope="session") def nodes() -> Nodes: parser = JavaParser() return parser.parse(Path(__file__).parent / "data", Path("Test.java")...
StarcoderdataPython
12816427
<gh_stars>10-100 __all__ = [ "db" ] from . import * # noqa
StarcoderdataPython
6455762
from django.contrib import admin from .models import BackupJob, BackgroundTask, DiskWipe, DiskCheck, VirusScan, DiskClone admin.site.register(BackupJob) admin.site.register(BackgroundTask) admin.site.register(DiskWipe) admin.site.register(DiskCheck) admin.site.register(VirusScan) admin.site.register(DiskClone)
StarcoderdataPython
6692876
import os import pytest import time import mock from collections import namedtuple import boto3 import botocore import numpy as np from click.testing import CliRunner from sklearn.linear_model import LogisticRegression import mlflow import mlflow.pyfunc import mlflow.sklearn import mlflow.sagemaker as mfs import mlfl...
StarcoderdataPython
8161186
# Author: <NAME> <<EMAIL>> # # (c) 2012 # Modified by: <NAME> <<EMAIL>> # # License: MIT from __future__ import division import re import sys from arabic_reshaper import arabic_reshaper from bidi.algorithm import get_display import warnings from random import Random import os from operator import itemgetter from word...
StarcoderdataPython
5136489
import inspect import struct import datetime def snapshot_protobuf_serializer(thought): return thought.snapshot.SerializeToString() class Thought: """ Encapsulates everything about a mindshot, The client and the server agree on this as the de-facto data-model of a thought.1 The brain sample may c...
StarcoderdataPython
9616842
<reponame>qwikintelligence/building-blocks import pathlib import utils_jsonl as ul import utils_jsont as ut from argparse import ArgumentParser from typeguard import typechecked @typechecked def convert_jsonl_to_jsont(jsonl_in: pathlib.Path, jsont_out: pathlib.Path) -> None: """ Converts a `JSONL` file into a ...
StarcoderdataPython
1884591
<filename>axonius_api_client/cli/grp_system/grp_users/cmd_delete.py<gh_stars>10-100 # -*- coding: utf-8 -*- """Command line interface for Axonius API Client.""" from ...context import CONTEXT_SETTINGS, click from ...options import AUTH, add_options USER_NAME = click.option( "--name", "-n", "name", help...
StarcoderdataPython
180343
"""Test the 'services.py' module.""" from graphviz import Digraph from stochastic_service_composition.rendering import service_to_graphviz from stochastic_service_composition.services import Service, build_system_service class TestInitialization: """Test class to test initialization and getters.""" @classme...
StarcoderdataPython
211476
<reponame>slmjy/oci-ansible-collection<gh_stars>100-1000 #!/usr/bin/python # Copyright (c) 2020, 2021 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/g...
StarcoderdataPython
1883809
<gh_stars>1-10 # E-COMMERCE CMR # # Beginning of a e-commerce CMR where we apply different discounts to each # product category (pants-10%, sweaters-5%, t-shirts-20%) and pick them up and VAT # and campaign info from a list (dynamically) # # You first ask what type of product it is and then it # prints out the price ...
StarcoderdataPython
1763351
<reponame>combinators/templating @(clsName: Python, text: Python, body: Python, bodyTight: Python) class @{clsName}(object): def __init__(self): @body.indentExceptFirst.indentExceptFirst def test(self): @bodyTight.indent.indent if __name__ == "__main__": x = new @{clsName}() print(@text) p...
StarcoderdataPython
1630029
from discord.ext import commands from config import getarg from cogregister import commandregister, eventregister # Creates two types of bots based on the value of the --no-auto-sharding flag if getarg('no_auto_sharding'): bot = commands.Bot else: bot = commands.AutoShardedBot # Initialize method into bot ob...
StarcoderdataPython
1704803
<reponame>gigincg/care<filename>care/facility/migrations/0021_auto_20200324_0756.py # Generated by Django 2.2.11 on 2020-03-24 07:56 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('facility', '0020_auto_20200323_1029'), ...
StarcoderdataPython
3377359
<gh_stars>1-10 # -*- coding: utf-8 -*- from south.utils import datetime_utils as 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 'Provisioner' db.create_table(u'ssdfrontend...
StarcoderdataPython
5078908
#!/usr/bin/env python from __future__ import with_statement from collections import defaultdict import wget import requests import sys import gzip import itertools """ DESCRIPTION: Program to download and create the 'geneset' file for input into Gowinda for the species Aedes aegypti from the uniprot and BioMart (Vect...
StarcoderdataPython
4832720
<gh_stars>100-1000 box_width = 350 id_lables = ["white", "blue", "black", "red", "green", "multi", "colorless", "lands"] html_prepend = """<!DOCTYPE html> <head> <style> ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; } li { float: left; } li a { ...
StarcoderdataPython
5038018
from flask import current_app from zeus import factories def test_time_aggregate( client, default_login, default_repo, default_repo_access, default_source ): factories.BuildFactory(source=default_source, passed=True) resp = client.get( "/api/repos/{}/stats?aggregate=time&points=30&resolution=1d&...
StarcoderdataPython
6481903
<reponame>Sam-Gao-Xin/Courses- """ Tabular data as nested dictionaries. """ # Top 10 software products with the most vulnerabilities in 2017 # (through August). From www.cvedetails.com. vulnerabilities2017 = { 'Android': {'vendor': 'Google', 'type': 'Operating System', 'number': 56...
StarcoderdataPython
3501655
# -*- coding: utf-8 -*- """ Created on Sat Nov 17 21:08:37 2018 文本文件切分工具 将一个大的文本文件等分成指定个数的小文件 @author: zyb_as """ import time def calculateRowNum(filename, encoding = 'utf-8'): """ calculate the total number of the txt file filename: encoding """ cnt = 0 for line in open(filename, encodi...
StarcoderdataPython
6571264
<filename>core/pycopia/ssmtpd.py<gh_stars>10-100 #!/usr/bin/python2.7 # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # 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 ...
StarcoderdataPython
3233310
import json from passlib.context import CryptContext import psycopg2 import sys import DB_manager def new_user(email, password): #Non-encrypting information email = email.lower() try: conn = psycopg2.connect(host = DB_manager.get_hostname(), database = DB_manager.get_database(), ...
StarcoderdataPython
11248622
from django.contrib import admin from .models import Venda, ItemDoPedido from .actions import nfe_emitida, nfe_nao_emitida class ItemPedidoInLine(admin.TabularInline): model = ItemDoPedido extra = 1 # class ItemPedidoInLine(admin.StackedInline): # model = ItemDoPedi do # extra = 1 class VendaAd...
StarcoderdataPython
3476808
from datetime import datetime, timedelta from bisect import bisect_right import math # table of UTC leap second insertions since 1980 (http://hpiers.obspm.fr/eop-pc/index.php?index=TAI-UTC_tab&lang=en) _LEAPSECONDS = [ (datetime(1980, 1, 1).timestamp(), timedelta(seconds=19)), (datetime(1981, 7, 1).timestamp()...
StarcoderdataPython
1655104
# author: <NAME> (nxkennedy) import csv import os import time import sqlite3 rootdir = os.getcwd() components = [] reports = [] dbname = 'db-' + time.strftime("%Y%m%d-%H%M%S") + '.db' def normalize(infile): filename = os.path.basename(infile) info = filename.split(' ') s_id = info[2] s_type =...
StarcoderdataPython
5012746
<gh_stars>1-10 ''' Copyright (c) 2019-2020, <NAME>. All rights reserved. e-mail: <EMAIL> Released under the MIT license. https://opensource.org/licenses/mit-license.php Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation f...
StarcoderdataPython
3264808
<gh_stars>0 import sys from .io import read_pairs, read_sequence, read_scoring_matrix, write_alignment, write_optimal_matrix from .alignment import smith_waterman, smith_waterman_len_adj, smith_waterman_alignment, optimize_scoring_matrix # Some quick stuff to make sure the program is called correctly if sys.argv[1] !=...
StarcoderdataPython
4847828
<gh_stars>10-100 import numpy as np from scipy import optimize import time def f(x, sigma, q): Linvx = (sigma**2)*np.log((np.exp(x)-(1-q))/q) + 0.5 ALinvx = (1/np.sqrt(2*np.pi*sigma**2))*((1-q)*np.exp(-Linvx*Linvx/(2*sigma**2)) + q*np.exp(-(Linvx-1)*(Linvx-1)/(2*sigma**2))) dLinvx = sigma**2*np.exp(...
StarcoderdataPython
3311995
<filename>modules/sfp_abusix.py # -*- coding: utf-8 -*- # ------------------------------------------------------------------------------- # Name: sfp_abusix # Purpose: SpiderFoot plug-in for looking up whether IPs/Netblocks/Domains # appear in the Abusix Mail Intelligence blacklist. # # Author: ...
StarcoderdataPython
6664116
<reponame>brando90/pytorch-meta import logging def main(args): logging.basicConfig(level=logging.INFO if args.verbose else logging.WARNING) with open('README.md', encoding='utf-8') as f: long_description = f.read() with open('docs/index.md', 'w') as f: f.write(long_description) if __name...
StarcoderdataPython
6593764
<gh_stars>1-10 # -*- coding: utf-8 -*- """ Created on Tue Aug 28 21:12:23 2018 @author: limingfan """ import os import time import json import logging class SettingsBaseboard(object): """ """ def __init__(self): """ """ self.str_datetime = time.strftime("%Y_%...
StarcoderdataPython
3460389
<reponame>ShubhamThakre/datahub<filename>metadata-ingestion/src/datahub/ingestion/source/sql/hana.py from typing import Dict import pydantic from datahub.ingestion.api.common import PipelineContext from datahub.ingestion.api.decorators import ( SourceCapability, SupportStatus, capability, config_class...
StarcoderdataPython
11396064
import os import json from fabric.contrib.files import sed from fabric.context_managers import cd from fabric.api import env, sudo, run PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(PROJECT_DIR) # Load deploy settings in deploy.json with open(os.path.join(PROJECT_DIR, 'deploy.js...
StarcoderdataPython
6463495
import string def del_punct(text_data): tokens = text_data.split() # delete punctuation symbols tokens = [i for i in tokens if ( i not in string.punctuation )] return " ".join( tokens )
StarcoderdataPython
11298083
<filename>read_write_list2file.py<gh_stars>0 # -*- coding: utf-8 -*- # @Author: <NAME> # @Date: 2018-10-15 17:31:55 # @Last Modified by: <NAME> # @Last Modified time: 2018-10-15 18:18:22 def list_to_file(filename, list): with open(filename, 'w', encoding='utf-8') as f: for ele in list: f.write('%s\n' % str(...
StarcoderdataPython
45093
# -*- coding: utf-8 -*- import requests import os from lxml import etree try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse try: from .xmlns import strip_xmlns from .service import Service from .embedded_device import EmbeddedDevice from .instance_singlet...
StarcoderdataPython
6595729
"""Dit bestand stelt een URL samen die de gebruiker kan bezoeken om zijn route te bekijken / gebruiken.""" def createMapsURL(route): """Deze functie maakt een URL waarmee de gebruiker meteen de route in google maps kan bekijken, Voorbeeld: https://www.google.com/maps/dir/?api=1&origin=27+Julianalaan+Bilthoven...
StarcoderdataPython
3453119
<reponame>DavidFellner/Malfunctions_in_LV_grid_datase<filename>raw_data_generation/grid_preparation.py import pflib.pf as pf import pandas as pd import numpy as np import os import importlib from experiment_config import experiment_path, chosen_experiment spec = importlib.util.spec_from_file_location(chosen_experiment...
StarcoderdataPython
1924262
<reponame>vladvasiliu/UpdateEC2DNS<filename>update_ec2_dns_function/update_ec2_dns/gandi.py<gh_stars>0 from enum import Enum from typing import List, Optional from urllib.parse import urljoin import validators from pydantic import BaseModel, conint, validator, root_validator import requests from requests.auth import A...
StarcoderdataPython
8193834
<reponame>DZDL/aicleaner<gh_stars>1-10 import librosa import soundfile as sf # Get example audio file filename = librosa.ex('trumpet') data, samplerate = sf.read(filename, dtype='float32') print(data) print(data.shape) data = data.T print(data) print(data.shape) data_22k = librosa.resample(data, samplerate, 8000) pri...
StarcoderdataPython
270049
<gh_stars>100-1000 # Generated by Django 2.1.7 on 2020-01-23 22:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('clist', '0023_auto_20191209_0955'), ] operations = [ migrations.AddField( model_name='resource', ...
StarcoderdataPython
1680118
<gh_stars>0 ''' - Augmentation - Sequence (Time Series data) - Single Value Regression. ''' from typing import ( Sequence, ) import numpy as np class AugSeqRegSingle: def __init__( self, data: np.ndarray, seq_len: int, delay: int=0, ): self.data = data self.seq_len = seq_len ...
StarcoderdataPython
12845906
"""Input/output functions.""" import astropy.io.fits as fits from astropy.table import Table import numpy as np import astropy.units as u from astropy.coordinates import ( EarthLocation, AltAz, Angle, ICRS, GCRS, SkyCoord, get_sun, ) import os from astropy.time import Time import warnings fr...
StarcoderdataPython
1713601
<filename>userBased_filtering_recommend.py import pandas as pd import numpy as np from sklearn.metrics.pairwise import cosine_similarity import sklearn.utils from helper_functions import movieId_to_title def user_based_filtering_recommend(new_user,user_movies_ids,movies_num,n_neighbor,movies_ratings): """ This fu...
StarcoderdataPython
3583322
def fib_recursive(n): """ Returns the Finabocci's value for 'n' using recursion. Args: n (int): number of interactions. Returns: int: Fibonacci's value. """ if n == 0 or n == 1: return 1 else: return fib_recursive(n-1) + fib_recursive(n-2) def fib_dictio...
StarcoderdataPython
3416071
<gh_stars>0 class Solution: def calculate(self, s: str) -> int: if not s: return 0 priority = {'+': 0, '-': 0, '*': 1, '/': 1} def operate(n1, n2, operator) -> int: if operator == '+': return n1 + n2 if operator == '-': ...
StarcoderdataPython
5113946
<reponame>tcv-geo/connectedhomeip<gh_stars>0 #!/usr/bin/env python # Copyright (c) 2022 Project CHIP Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licens...
StarcoderdataPython
108246
<filename>zcrmsdk/src/com/zoho/api/authenticator/store/__init__.py from .db_store import DBStore from .file_store import FileStore from .token_store import TokenStore
StarcoderdataPython
132574
<gh_stars>1-10 from app.quiz import quiz_blueprint as quiz from flask import render_template @quiz.route('/start/<code>') def quiz_homepage(code): return render_template('quiz/index.html') @quiz.route('/') def index_quiz(): return render_template('quiz/landing-page.html')
StarcoderdataPython
208322
<reponame>xinli8287/mastering_azureml from keras.callbacks import Callback import numpy as np class AzureMlKerasCallback(Callback): def __init__(self, run): super(AzureMlKerasCallback, self).__init__() self.run = run def on_epoch_end(self, epoch, logs=None): logs = logs or {} ...
StarcoderdataPython
9737097
<filename>ipfshttpclient/client/swarm.py from . import base class FiltersSection(base.SectionBase): @base.returns_single_item(base.ResponseBase) def add(self, address, *addresses, **kwargs): """Adds a given multiaddr filter to the filter list. This will add an address filter to the daemons swarm. Filters appli...
StarcoderdataPython
3510026
from django.db.models.signals import post_save from django.dispatch import receiver from cvat.apps.engine.models import Job, StatusChoice, Project, Task from cvat.apps.training.jobs import ( create_training_project_job, upload_images_job, upload_annotation_to_training_project_job, ) @receiver(post_save, ...
StarcoderdataPython
127251
# -*- coding: utf-8 -*- """ Created on Sat Oct 10 13:01:49 2020 @author: saksh """ import numpy as np np.random.seed(1337) import tensorflow as tf import pandas as pd from statsmodels.tsa.api import VAR from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.svm import SVR from s...
StarcoderdataPython
11255708
<reponame>cortizbon/code_forces n = int(input('Número de bebidas: ')) datos = [int(i) for i in input('% de naranja: ').split(' ')] res = sum(datos)/(n*100) print(res*100)
StarcoderdataPython
78784
<filename>certificate_engine/tests/test_rsa_key.py import arrow from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives.serialization.pkcs12 import load_pkcs12 from django.db.models import signals from django.test import TestCase from django.utils import timezone from factory.djang...
StarcoderdataPython
5021896
# Python3 code to linearly search x in arr[]. # If x is present then return its location, # otherwise return -1 def search(arr, n, x): for i in range(0, n): if (arr[i] == x): return i return -1 # Driver Code arr = [2, 3, 4, 10, 40] x = 10 n = len(arr) # Function call result = sea...
StarcoderdataPython
8136525
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, Sequence from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, scoped_session, sessionmaker PRODUCTS = [ { 'title': 'MacBook Air', 'price_rub': 80000,...
StarcoderdataPython
352233
<gh_stars>1-10 from flask import Flask from routes.login import login_b from routes.register import register_b from routes.main import main_b from routes.logout import logout_b import routes.auth as auth app = Flask(__name__) app.register_blueprint(main_b) app.register_blueprint(login_b) app.register_bluep...
StarcoderdataPython
6425633
<reponame>armysick/beagle import os import pytest from beagle.web import create_app from beagle.web.server import db as _db import tempfile TESTDB = "test_project.db" TESTDB_PATH = f"{tempfile.gettempdir()}/{TESTDB}" TEST_DATABASE_URI = "sqlite:///" + TESTDB_PATH @pytest.fixture(scope="session") def app(request): ...
StarcoderdataPython
9613654
import urllib.request,json from .models import Sources,Article # News = news.Sources # Article = article.Article # Getting api key api_key = None #Getting the news base url base_url = None article_base_url = None def configure_request(app): global api_key,base_url,article_base_url api_key = app.conf...
StarcoderdataPython
3317624
import tools import config import numpy as np class Match(): def __init__(self, _match): """Takes match message as _match from exchange """ self.matchId = _match["id"] self.linkId = _match["linkid"] self.longPosition = 0 self.shortPosition = 0 strike_map = { "game":"spread", ...
StarcoderdataPython
11312847
""" CARPI OBD II DAEMON (C) 2018, Raphael "rGunti" Guntersweiler Licensed under MIT """ from logging import Logger from time import sleep from carpicommons.log import logger from daemoncommons.daemon import Daemon from obd import OBD, Async, commands, OBDResponse, Unit from obd.codes import FUEL_STATUS from redisdatab...
StarcoderdataPython
4932263
from setuptools import setup setup( name='maps', version='5.1.1', description='Maps: flavors of Python dictionaries', url='https://github.com/pcattori/maps', author='<NAME>', author_email='<EMAIL>', license='MIT', packages=['maps'], test_suite='tests', extras_require={'dev': ['c...
StarcoderdataPython
92375
""" Bridging Composite and Real: Towards End-to-end Deep Image Matting [IJCV-2021] Dataset processing. Copyright (c) 2021, <NAME> (<EMAIL>) Licensed under the MIT License (see LICENSE for details) Github repo: https://github.com/JizhiziLi/GFM Paper link (Arxiv): https://arxiv.org/abs/2010.16188 """ from config impor...
StarcoderdataPython
8011077
<gh_stars>0 import pyxel from utils import Vec, ColPal, Rect import music from constants import (WINDOW_WIDTH, WINDOW_HEIGHT, CAPTION, FPS, ANIM_FPS, COLKEY, DEBUG) class Player: """playable character""" global COLKEY # === CLASS VARIABLE...
StarcoderdataPython
3534242
'''csv2db.py - upload table to database ==================================== :Tags: Python Purpose ------- create a table from a csv separated file and load data into it. This module supports backends for postgres and sqlite3. Column types are auto-detected. Read a table from stdin and create an sqlite3 database. ...
StarcoderdataPython
3584766
import os class Config(object): DEBUG = False SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/publictitles' class TestConfig(DevelopmentConfig): TESTING = True SQLALCHEMY_DATABASE_URI = "s...
StarcoderdataPython
6702884
import numpy as np from scipy.special import expit from math import ceil # Given a predicate's semantic function, calculate a distribution over entity vectors, # approximating the posterior distribution over entities, given that the predicate is true ### Initialisation def get_semfunc(pred_wei, pred_bias): """ ...
StarcoderdataPython
191638
<gh_stars>10-100 import os import unittest from unittest import mock from image_quantizer import quantizer class ImageQuantizerTestCase(unittest.TestCase): def _get_image_path(self, filename): return os.path.join(os.path.dirname(__file__), 'fixtures', filename) def test_quantize(self): q = ...
StarcoderdataPython
6530318
import ScintillaConstants import Utils def generate_handler_name(state): return 'handle_' + state[4:].lower() class DispatchHandler: def __init__(self, state_prefix): self.handlers = {} if state_prefix is not None: for constant in Utils.list_states(state_prefix): ...
StarcoderdataPython
57915
class AminoAcid: def __init__(self,name='AA'): self.name = name self.name3L = '' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # ...
StarcoderdataPython
3257138
from __future__ import annotations import numpy as np import pandas as pd import torch from torch.nn import Module, Embedding, Linear, RNNCell, CrossEntropyLoss from torch.nn.functional import softmax, relu, dropout from torch.optim import Adam from nlp_pytorch.data.base_dataset import SplitDataset from nlp_pytorch.d...
StarcoderdataPython
3575950
from flask_sqlalchemy import SQLAlchemy from datetime import datetime from flask_admin.contrib import sqla from flask_login import current_user # User Class # db = SQLAlchemy() class User(db.Model): __tablename__ = "users" id = db.Column('user_id', db.Integer, primary_key=True) username = db.Column('usern...
StarcoderdataPython
8081914
# import necessary libraries from flask import Flask, render_template, redirect from flask_pymongo import PyMongo import scrape_mars # create instance of Flask app app = Flask(__name__) mongo = PyMongo(app, uri="mongodb://localhost:27017/mars_app") # create route that renders index.html template and finds documents ...
StarcoderdataPython
9712296
#! /usr/bin/env py.test # -*- coding: utf-8 -*- # Copyright (c) 2007-2009 PediaPress GmbH # See README.txt for additional licensing information. from mwlib import uparser from mwlib import parser parse = uparser.simpleparse def test_rot13(): r=parse(u"""<rot13>test</rot13>""") # grfg txt = [x.caption for...
StarcoderdataPython
3469921
import math while True: try: n, l, c = map(int, input().split()) story = input() if len(story.split()) == n: count = 0 x = 0 y = 0 for i in range(len(story)): if y <= c: y += 1 if ...
StarcoderdataPython
356594
# coding=utf-8 # Copyright 2019 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
StarcoderdataPython
5006499
from collections import deque import statvent import statvent.stats def test_incr_increments_the_given_stat_value(): statvent.stats._stats['foo'] = 100 statvent.incr('foo') assert statvent.stats._stats['foo'] == 101 def test_incr_by_a_value_increments_by_that_value(): statvent.stats._stats['bar'] = ...
StarcoderdataPython
1823444
import ipydatawidgets import ipywidgets from ipywidgets import interact, interactive, fixed, interact_manual import ivvv.img_prep import numpy import traitlets @ipywidgets.register class VolumeWidget(ipywidgets.DOMWidget): _view_name = traitlets.Unicode("VolumeWidgetView").tag(sync=True) _view_module = trait...
StarcoderdataPython
6680150
<gh_stars>10-100 #!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2015-2016 by <NAME> # gaik (dot) tamazian (at) gmail (dot) com import logging import pyfaidx import random import string from bioformats.blast import BlastTab from chromosomer.exception import MapError from chromosomer.exception import Ali...
StarcoderdataPython
6657022
from django.http.response import JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from MTQCApp.commprotocol.server_response import SUCCESS, WRONG_JSON, ServerResponse from .services import user_service from .services import project_service # Create your v...
StarcoderdataPython
6626107
<filename>cloud_ml_sdk/cloud_ml_sdk/models/quota.py # Copyright 2017 Xiaomi, 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...
StarcoderdataPython