id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3225314
import django_filters from cards import models class CardFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') created_at = django_filters.DateTimeFilter(field_name="created_at", ) modified_at = django_filters.DateTimeFilter(field_name="modified_at") ordering = ...
StarcoderdataPython
3313991
import os import json from mlb_utils import get_player_line, get_team_line_attributes, match_in_candidate_innings from mlb_utils import get_inning_side_entities from mlb_utils import get_all_paragraph_plans from mlb_utils import get_ents, get_ordinal_adjective_map, get_inning, sort_files_key, filter_summaries, \ ex...
StarcoderdataPython
1737974
<filename>code/tests/unit/api/test_health.py from http import HTTPStatus from pytest import fixture from .utils import get_headers def routes(): yield '/health' @fixture(scope='module', params=routes(), ids=lambda route: f'POST {route}') def route(request): return request.param def test_health_call_succ...
StarcoderdataPython
1645519
<gh_stars>0 #!/usr/bin/python import sys import os import re import scipy.stats as stats from matplotlib.pyplot import * from numpy import * # Goal: follow the average bandwidth of all nodes over time if len(sys.argv) == 1: print "Goal: Give the cdf of the average bandwidth of each node during the overall session...
StarcoderdataPython
3360329
from unittest import TestCase from mock import patch, Mock import torchbearer from torchbearer import Trial from torchbearer.callbacks.checkpointers import _Checkpointer, ModelCheckpoint, MostRecent, Interval, Best import warnings class TestCheckpointer(TestCase): @patch('os.makedirs') def test_make_dirs(self...
StarcoderdataPython
18846
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from devices.v1beta1 import DevicesService_Beta1_pb2 as devices_dot_v1beta1_dot_DevicesService__Beta1__pb2 class DevicesStub(object): """Specifies the devices service, which enables managed devices to check-in, authorize themselves, ...
StarcoderdataPython
120816
<filename>examples/basic_bot.py<gh_stars>0 # This example requires the 'members' privileged intent to use the Member converter # and the 'message_content' privileged intent for prefixed commands. import random import discord from discord.ext import commands description = """ An example bot to showcase the discord.ex...
StarcoderdataPython
1672762
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import datetime def get_log_name(file_path): time = file_path.split("/")[-1].split(".")[0].split("-")[2:4] return time[0] + "-" + time[1] def current_date_time(): return datetime.datetime.today().strftime("%Y.%m.%d %H:%M") def format_date_time(t): retu...
StarcoderdataPython
1765068
# -*- coding: utf-8 -*- # # Copyright 2018 - Swiss Data Science Center (SDSC) # A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and # Eidgenössische Technische Hochschule Zürich (ETHZ). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compli...
StarcoderdataPython
3213592
<gh_stars>10-100 from django import forms from phonenumber_field.formfields import PhoneNumberField class AreaCodeForm(forms.Form): """Form for specifying the area code when searching for available numbers""" area_code = forms.CharField(min_length=3, max_length=3, required=False) class PurchaseNumberForm(fo...
StarcoderdataPython
4832958
<reponame>jhertz/autovod # python youtube uploader # written by jhertz # large chunk of code borrowed from https://developers.google.com/youtube/v3/guides/uploading_a_video # needs client_secrets.json for youtube API creds import httplib import httplib2 import os import random import sys import time import un...
StarcoderdataPython
168481
import sys from decorator import decorator from fabric.api import env, hide, parallel, run, settings from fabric.tasks import execute env.shell = '/bin/bash -l -c -o pipefail' env.keepalive = 60 env.timeout = 60 def parallel_task(server_side=True): @decorator def _parallel_task(task, *args, **kargs): ...
StarcoderdataPython
3319853
import os.path # Write a function rainfallChart that displays this data as a textual bar chart using # one asterisk for each mm of rainfall; e.g., given the above data the output should be: # Portsmouth ******** # London ***** # Southampton ************ def rainfallChart(): structur...
StarcoderdataPython
3344830
<reponame>jahmelharris/spireader #!/usr/bin/env /usr/bin/python from memoryreader import app app.run(host="0.0.0.0")
StarcoderdataPython
82319
#!/usr/bin/python3 # lltapes.py - Uses BeautifulSoup and requests to parse and download episodes # from lovelinetapes. import re import sys import os import logging import argparse # for multi-threading from queue import Queue from threading import Thread import requests from bs4 import BeautifulSoup U...
StarcoderdataPython
3276664
<reponame>easyopsapis/easyops-api-python # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: fail_instance.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf impo...
StarcoderdataPython
1716699
import numpy as np import tvm from tvm.contrib import graph_runtime import topi.testing import nnvm.symbol as sym import nnvm.compiler from nnvm.testing.config import ctx_list from nnvm.testing.check_computation import check_function def test_check_function(): # test the testing function x = sym.Variable("x")...
StarcoderdataPython
1785346
from dlkp.models import KeyphraseTagger from dlkp.extraction import ( KEDataArguments, KEModelArguments, KETrainingArguments, ) model_name = "bloomberg/KBIR" print("Training: ", model_name) training_args = KETrainingArguments( output_dir=f"/data/models/keyphrase/dlkp/inspec/extraction/{model_name}/fin...
StarcoderdataPython
1671708
# run bear example with knn_k at different values import os cmd = 'python3 ../kgc.py bear.csv ' for i in range(10, 1111, 10): c = cmd + str(i) + ' 1 > bear_' + str(i) + '.txt' print(c) # a = os.system(cmd)
StarcoderdataPython
68268
<reponame>carterbancroft/cryptopals # https://cryptopals.com/sets/1/challenges/3 from binascii import unhexlify def do_it(hex_str): unhexlified = unhexlify(hex_str) common = 'ETAOIN SHRDLU' current_high_score = 0 current_high_string = '' key = '' for i in range(127): data = [i ^ cha...
StarcoderdataPython
139736
DEFAULT_ENV_NAME = "CartPole-v1" DEFAULT_ALGORITHM = "random" DEFAULT_MAX_EPISODES = 1000 DEFAULT_LEARNING_RATE = 0.001 DEFAULT_GAMMA = 0.95 DEFAULT_UPDATE_FREQUENCY = 20
StarcoderdataPython
3335102
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # xarray-simlab documentation build configuration file, created by # sphinx-quickstart on Sun Jun 11 14:04:24 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in thi...
StarcoderdataPython
126524
""" Contains utility funcion to work with falcon POST data requests. """ import json import falcon def req_to_dict(req): """Exctract POST request params as a json.""" try: raw_json = req.stream.read() except Exception as ex: raise falcon.HTTPError(falcon.HTTP_400, 'Error', ex.message) ...
StarcoderdataPython
1623422
import importlib from hydroDL.master import basins from hydroDL.app import waterQuality from hydroDL import kPath from hydroDL.model import trainTS from hydroDL.data import gageII, usgs from hydroDL.post import axplot, figplot import torch import os import json import numpy as np import pandas as pd import matplotlib....
StarcoderdataPython
3228817
<reponame>LanceaKing/kaldi<filename>egs/iam/v2/local/gen_topo.py #!/usr/bin/env python # Copyright 2017 (author: <NAME>) # Generate a topology file. This allows control of the number of states in the # non-silence HMMs, and in the silence HMMs. This is a modified version of # 'utils/gen_topo.pl'. The difference is t...
StarcoderdataPython
1768240
""" This module contains tests for tofu.geom in its structured version """ # External modules import os import numpy as np import matplotlib.pyplot as plt import warnings as warn # Importing package tofu.geom import tofu as tf from tofu import __version__ _here = os.path.abspath(os.path.dirname(__file__)) VerbHe...
StarcoderdataPython
194436
# -*- coding: utf-8 -*- """ Created on Fri Mar 5 09:08:54 2021 根据research_field_0304v2.csv 对一个公司-->所在行业的所有公司研究领域求交集 """ import csv import pandas as pd #先把一家公司所有年份研究领域合并 def get_field_list(orgpath,outpath): orgdf = pd.read_csv(orgpath,dtype=str) orgdf['stock_code'] = orgdf['stock_code'].astype(str).str.zfi...
StarcoderdataPython
3381806
<reponame>Dowell-Lab/DAStk #!/usr/bin/env python # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path....
StarcoderdataPython
80047
import os import sys if len(sys.argv) >= 2: for i in sys.argv[1:]: os.system(f'type nul > {i}') else: print('Pass parameters for creating files. E.g. touch file.py file2.pyw')
StarcoderdataPython
3306276
import sys from data_dense import iter_data def build_dictionary(translation_file,uniq_tokens): vocabulary=set() with open(uniq_tokens) as f: for line in f: line=line.strip().lower() vocabulary.add(line) ttable={} f=open(translation_file) for line in f: f,...
StarcoderdataPython
149221
<filename>cube.py import random from piece import Piece from anim import Anim from stack import Stack from timer import Timer class Cube: """Handles rendering and updating of the cube. Args: colors (:obj:`list` of int): Color scheme in `FBUDLR` order. sz (int, optional): Size of each cube pie...
StarcoderdataPython
123356
from uuid import uuid4 from datetime import datetime from mongoengine import Document,DateField, StringField, BooleanField, EmailField class UserAccount(Document): username = StringField(required=True, min_length=3) email = EmailField(required=True, unique=True) gender = StringField(choices=("male", "fema...
StarcoderdataPython
18226
import datetime from dateutil.parser import parse from mongoengine import DateTimeField, FileField from mongoengine.connection import DEFAULT_CONNECTION_NAME #from mongoengine.python_support import str_types from six import string_types as str_types import io from django.conf import settings if settings.FILE_DB == se...
StarcoderdataPython
1719218
<reponame>thehapax/encrypt-config import configparser """ an idea of future config file format Simple Arb : A <-> B Triangular arb : A -> B -> C """ simple_arb = ['strategy-type', 'exchange_name', 'api_key', 'secret', 'fund-password'] triangular_arb = ['strategy-type', 'Exchange_Name_A', 'api_key_A', 'secret-A', ...
StarcoderdataPython
1613332
<gh_stars>0 from efficientnet_pytorch import EfficientNet import numpy as np import json from PIL import Image import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler from torchvision import transforms import matplotlib.pyplot as plt import time import os import c...
StarcoderdataPython
1619118
<reponame>staghouse/mtgjson<filename>mtgjson5/utils.py """ MTGJSON simple utilities """ import collections import hashlib import inspect import itertools import json import logging import os import pathlib import time from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union import gevent.pool imp...
StarcoderdataPython
1720928
<gh_stars>1-10 import argparse import torch import os import json import pickle from nltk.tokenize import sent_tokenize import nltk nltk.download('punkt') import datasets from tqdm import tqdm import numpy as np import random def set_seed(seed): random.seed(seed) np.random.seed(seed) torch....
StarcoderdataPython
3202717
from .messages import Message
StarcoderdataPython
3201082
<filename>Algoritmos de Escalonamento/Escalonador por prioridade/main.py<gh_stars>0 from manager import ProcessScheduler from process import Process from creator import creator from time import sleep ''' @author: <NAME> Implementation of the priority scheduling algorithm. The algorithm is preemptive and so...
StarcoderdataPython
1788669
#!/usr/bin/python # -*- coding: utf-8 -*- # --------------------------------------------------------------------- # Copyright (c) 2012 <NAME>. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # ...
StarcoderdataPython
1750137
# Generated by Django 2.0.4 on 2018-04-17 11:38 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('core', '0006_auto_20180417_1337'), ] operations = [ migrations.AlterField( model_name='activityjour...
StarcoderdataPython
1788050
<reponame>icemac/icemac.addressbook<filename>src/icemac/addressbook/browser/search/interfaces.py import z3c.menu.ready2go import zope.interface import zope.viewlet.interfaces class ISearchMenu(z3c.menu.ready2go.ISiteMenu): """Search menu.""" class ISearchForm(zope.viewlet.interfaces.IViewletManager): """Sea...
StarcoderdataPython
179717
<gh_stars>0 # Copyright 2017 Mycroft AI 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 ...
StarcoderdataPython
1694048
<gh_stars>100-1000 # Copyright 2019 Xiaomi, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
StarcoderdataPython
1673950
<reponame>itsMo07/tweepy import unittest from unittest.case import skip from mock import MagicMock, patch from .config import create_auth from .test_utils import mock_tweet from tweepy.api import API from tweepy.auth import OAuthHandler from tweepy.models import Status from tweepy.streaming import Stream, StreamListe...
StarcoderdataPython
1688756
<filename>Parser-hybrid/nparser/bucket.py #!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2016 <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.or...
StarcoderdataPython
3234988
# Copyright 2020 DeepMind Technologies Limited. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
StarcoderdataPython
3254526
<filename>notebooks/_solutions/pandas_07_reshaping_data22.py df['Underaged'] = df['Age'] <= 18
StarcoderdataPython
1622379
<reponame>renderbus/rayvision_utils """Exception."""
StarcoderdataPython
1689975
<reponame>wavestoweather/enstools import os import logging import bz2 import six import xarray import numpy as np from numba import jit import dask from shutil import copyfileobj if six.PY3: from urllib.request import urlretrieve, urlopen else: from urllib import urlretrieve def download(url, destination, u...
StarcoderdataPython
1647941
<reponame>mishelshaji/py-2-ecommerce from django.urls import path from .views import * urlpatterns = [ path('login/', user_login, name='accounts_login'), path('register/', register, name='accounts_register'), ]
StarcoderdataPython
77760
<reponame>rmayherr/python<filename>movie.py #!/usr/bin/python import glob, sys, subprocess import time wfiles = {} wfilecontent = [] wfilename = "" wfilecache = [] #Set colored messages def printColored(msg, color="red"): if color == "red": print('\x1b[1;37;41m' + msg + '\x1b[0m') time.sleep(2) ...
StarcoderdataPython
159515
<filename>configs/kd/cifar100/kd_resnet18_resnet50_cifar100_adaptivenst_logits.py _base_ = './kd_resnet18_resnet50_cifar100_equal.py' # model settings model = dict( adaptive=True, adaptation = dict(out_channels=[256, 512, 1024, 2048], in_channels=[64, 128, 256, 512]), distill_losses=[ dict(type='NST...
StarcoderdataPython
1790431
<reponame>psbsgic/rabbitai from abc import ABC, abstractmethod from typing import Any class BaseCommand(ABC): """命令抽象基类,定义方法:run、validate。""" @abstractmethod def run(self) -> Any: """ 执行该命令。如果失败触发异常, :raises: CommandException。 """ @abstractmethod def validate(self...
StarcoderdataPython
1646507
<reponame>1bod/ProjetJukebox<filename>main.py<gh_stars>0 """Module principal du Projet monstercat media player""" # Le module pygame est utilisé pour la lecture des musiques en format mp3 # En effet, l'api monstercat ne founit pas les fichiers audio au format mp3 # winsound.PlaySound ne fonctionne pas avec les f...
StarcoderdataPython
3338958
<reponame>Benoit3/RaspPowerHat<gh_stars>0 import signal class stopManager: stop_now = False def __init__(self): signal.signal(signal.SIGINT, self.stopTest) signal.signal(signal.SIGTERM, self.stopTest) def stopTest(self,signum,frame): self.stop_now = True
StarcoderdataPython
1747200
<filename>venv/Lib/site-packages/markdown_it/extensions/amsmath.py from mdit_py_plugins.amsmath import * # noqa: F401,F403 import warnings warnings.warn( "`markdown_it.extensions` is deprecated, import from `mdit_py_plugins` instead", DeprecationWarning, stacklevel=2, )
StarcoderdataPython
4842420
<gh_stars>1-10 import tornado.web import tornado.httpclient class MainHandler(tornado.web.RequestHandler): def get(self): items = ["Item 1", "Item 2", "Item 3"] self.render("index.html", title="My title", items=items) class AsyncHandler(tornado.web.RequestHandler): @tornado.web.asynchronou...
StarcoderdataPython
3298514
import json def lambda_handler(event, context): response = { "statusCode": 200, "headers": { "content-type": "application/json" } } response_body = { "verification": event['headers']['X-Okta-Verification-Challenge'] } response['body'] = json.dumps(resp...
StarcoderdataPython
3396338
from .model import Artifact, ArtifactRef, Git, Run, RunStatus from ._api_client.dto import ArtifactDto, ArtifactRefDto, GitDto, ExperimentRefDto, RunDto, StatusDto from typing import List, Optional def dto_to_artifact(artifact_dto: ArtifactDto) -> Artifact: return Artifact( created_at=artifact_dto.create...
StarcoderdataPython
1741796
""" SNMPv3: auth SHA, privacy AES128 ++++++++++++++++++++++++++++++++ Send SNMP GET request using the following options: * with SNMPv3, user 'usr-sha-aes', SHA authentication, AES128 encryption * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for SNMPv2-MIB::sysDescr.0 MIB object Available authentication pro...
StarcoderdataPython
59220
#!/usr/bin/env python import webapp2 from google.appengine.api import app_identity from google.appengine.api import mail from conference import ConferenceApi from google.appengine.api import app_identity from google.appengine.api import mail from google.appengine.api import memcache from google.appengine.ext import ndb...
StarcoderdataPython
73091
# Copyright Pincer 2021-Present # Full MIT License can be found in `LICENSE` at the project root. from dataclasses import dataclass from typing import Optional @dataclass class GatewayConfig: """This file is to make maintaining the library its gateway configuration easier. """ socket_base_url: str = ...
StarcoderdataPython
1650218
<filename>samples/python-azurefunction/SendMessageToKafka/__init__.py import logging import json import azure.functions as func def main(args, messages: func.Out[bytes]) -> None: logging.info('Python processed a SendMessageToKafka request from the Dapr Runtime.') messages.set(json.dumps({"data": args}))
StarcoderdataPython
164139
from concurrent.futures import ProcessPoolExecutor from functools import partial from .funcs import process_csv_line, process_raw_speech_text def process_line(this_line, do_stemming=False, remove_stopwords=False): """ Given a line from the CSV file, gets the stemmed tokens. """ speech = process_csv_li...
StarcoderdataPython
3319698
#class Document:
StarcoderdataPython
80545
<reponame>tfpk/memtree from .utils import get_output def test_get_type(): INPUT = """ print(gdb_get_type('i')) print(gdb_get_type('a')) print(gdb_get_type('struct_instance')) print(gdb_get_type('union_instance')) print(gdb_get_type('*(union_instance->z)')) print(gdb_get_type('union_instance->z')) print(gdb_get_typ...
StarcoderdataPython
1717607
""" Create the input file to simulate the an Keken et al. (1997) model """ import numpy as np import matplotlib.pyplot as plt Nx = 81 Nz = 81 Lx = 92.42 Lz = 100.0 xn = np.linspace(0, Lx, Nx) liton = -0.8 * Lz + 0.02 * Lz * np.cos(np.pi * xn / Lx) liton = liton * 1000 # Create the interface file layer_propertie...
StarcoderdataPython
1609556
<reponame>DaPulse/redash from __future__ import absolute_import import logging import os import sys import redis from flask_mail import Mail from flask_limiter import Limiter from flask_limiter.util import get_ipaddr from flask_migrate import Migrate from statsd import StatsClient from . import settings from .app imp...
StarcoderdataPython
3391367
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (division, print_function, absolute_import, unicode_literals) import numpy as np from radial import orbit, dataset, rv_model, prior import scipy.signal as ss import matplotlib.pyplot as plt import matplotlib.markers as mrk im...
StarcoderdataPython
4828711
<reponame>Sunil-Rathore/golem<gh_stars>100-1000 class ResultsEnum: PENDING = 'pending' RUNNING = 'running' FAILURE = 'failure' ERROR = 'error' CODE_ERROR = 'code error' SUCCESS = 'success' STOPPED = 'stopped' NOT_RUN = 'not run' SKIPPED = 'skipped'
StarcoderdataPython
1642748
<reponame>connorkeevill/CM20257-housemates # Generated by Django 3.1.7 on 2021-03-16 22:56 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('app', '0014_auto_20210316_1331'), ('app', '0015_auto_20210315_1546'), ] operations = [ ]
StarcoderdataPython
1654129
''' Given a square matrix, calculate the absolute difference between the sums of its diagonals. Sample Input: 11 2 4 4 5 6 10 8 -12 Return the absolute difference between the sums of the matrix's two diagonals as a single integer. Sample Output: 15 ''' def diagonalDifference(arr): l = len(arr) primar...
StarcoderdataPython
178272
# -*- coding: utf-8 -*- from __future__ import unicode_literals import random from django.apps import apps from django.contrib.contenttypes.models import ContentType from django.db.models import Max from django_sample_generator import fields, generator from .models import Comment from .utils import update_comments_h...
StarcoderdataPython
168580
<gh_stars>0 # @Time: 10/28/2021 # @Author: lnblanke # @Email: <EMAIL> # @File: __init__.py from .GradBoost import GradBoost
StarcoderdataPython
1640976
<gh_stars>1-10 from .google_language_model import Google1BillionWordsLanguageModel from .gpt2 import GPT2 from .language_model_constraint import LanguageModelConstraint
StarcoderdataPython
1740844
<reponame>dbmi-pitt/DIKB-Evidence-analytics<filename>new-SQL-simple-DIKB-web/test.py import os,sys, string, cgi from time import time, strftime, localtime import sys sys.path = sys.path + ['.'] from mysql_tool import * from DIKB_Load import load_ev_from_db from sqlalchemy import func from sqlalchemy.orm.exc import N...
StarcoderdataPython
103904
import logging class Logger: config = { 'level': 'DEBUG', 'stdout': True } def __init__(self, name='logger', config=config): self.logger = logging.getLogger(name) level = logging.getLevelName(config.get('level', 'DEBUG')) self.logger.setLevel(level) defau...
StarcoderdataPython
31916
<reponame>sbaktha/MPNet import torch import torch.utils.data as data import os import pickle import numpy as np import nltk from PIL import Image import os.path import random from torch.autograd import Variable import torch.nn as nn import math # Environment Encoder class Encoder(nn.Module): def __init__(self): su...
StarcoderdataPython
1746956
<filename>tests/test_session.py import unittest import numpy as np from io import BytesIO import h5py from exetera.core import session from exetera.core import fields from exetera.core import dataframe from exetera.core import persistence as per from exetera.core import utils from exetera.core import field_importers...
StarcoderdataPython
170757
from os.path import join, dirname from client import app def fread(fn): with open(join(dirname(__file__), fn), 'r') as f: return f.read().decode("utf-8") app.config["OAUTH_CREDENTIALS"] = { u"rsa_key": fread("mykey.pem"), u"signature_method": u"RSA-SHA1", "signature_type": "body" } app.config...
StarcoderdataPython
3365500
<gh_stars>1-10 import itertools import numpy as np from multiprocessing.dummy import Pool from multiprocessing import cpu_count from scipy.sparse import csr_matrix from scipy.spatial.distance import cdist from somnium.codebook import Codebook from somnium.normalization import NormalizerFactory from somnium.neighborh...
StarcoderdataPython
3385422
<gh_stars>0 import csv from hedger import utils class CsvReader: def __init__(self, path, cast_numeric=True): self._path = path self._file = None self._reader = None self._cast_numeric = cast_numeric def __enter__(self): self._file = open(self._path, 'r', newline='') ...
StarcoderdataPython
19878
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 27 23:58:37 2020 @author: manal """ import numpy as np import GPy from GPy.kern.src.stationary import Stationary class Cosine_prod(Stationary): """ Cosine kernel: Product of 1D Cosine kernels .. math:: &k(x,x')_i = ...
StarcoderdataPython
3333237
""" train_xcept.py Train the Xception network to classify HV towers and substations Modified on: 3/24/2020 by <NAME> (<EMAIL>) """ import os from os import path as op from functools import partial from datetime import datetime as dt import pickle import pprint import numpy as np # import tensorflow as tf from tenso...
StarcoderdataPython
3325612
<reponame>neelabalan/mtodo<filename>mtodo/app.py import requests import json from mtodo.util import handle_request_exception from mtodo.logger import Logger logger = Logger.get_logger( logpath = '/tmp/mtodo-logs.log' ) class TodoApi: def __init__( self, access_token ): self.access_token = access_token ...
StarcoderdataPython
94694
from __future__ import division from utils.utils import * from utils.datasets import * from PIL import Image import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib.ticker import NullLocator def plot_box_images(imgs, img_detections, classes, savePath, img_size=416): """ imgs: l...
StarcoderdataPython
1651717
<filename>spirit/views/topic_private.py<gh_stars>1-10 #-*- coding: utf-8 -*- from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.contrib.auth import get_user_model from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorator...
StarcoderdataPython
1650502
<filename>tests/api/test_payments_create.py<gh_stars>1-10 from allure import title, description, suite, parent_suite from data import API_PAYMENTS_SUCCESS, DATA_AMOUNT_PAYMENTS_SUCCESS, DATA_PAYMENTS_TIMESTAMP, \ API_POST_METHOD_NOT_ALLOWED, API_AUTH_TOKEN_EMPTY, AUTH_DATA_FAIL_NOT_FOUND_ID, AUTH_DATA_LENGTH_TOKEN...
StarcoderdataPython
1643938
from urlparse import urlparse class Session(object): """ Contains the components needed to communicate with the Ingenico ePayments platform. :param api_endpoint: the address of the target server as a string or ParseResult object """ def __init__(self, api_endpoint, connection, authenticator, ...
StarcoderdataPython
3351272
import os import sys from datetime import datetime from google.cloud import logging try: logger = logging.Client().logger("trader") except Exception: logger = None def tlog(msg: str) -> None: try: calling_fn = f"[{sys._getframe(1).f_code.co_name}()]" except Exception: calling_fn = ""...
StarcoderdataPython
1797145
<reponame>mwk0408/codewars_solutions from datetime import datetime def what_day_of_the_week(year, month, date): return datetime(year, month, date).strftime('%A')
StarcoderdataPython
3264375
import os import sys from functools import partial import matplotlib matplotlib.use('Agg') import numpy as np import elfi from elfie.bolfi_extensions import BolfiParams, BolfiFactory from elfie.inference import inference_experiment, get_sample_pool from elfie.mpi import mpi_main from elfie.reporting import run_and_r...
StarcoderdataPython
4837985
<filename>test/test_cloudwatch_metric_connector.py # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import importlib from mock import MagicMock, patch from src import utils DEFAULT_NAMESPACE = 'Greengrass' DEFAULT_METRIC_NAME = 'Count' DEFAULT_METRIC_VALUE = ...
StarcoderdataPython
1737387
# coding: utf-8 import os from multiprocessing import cpu_count site_name = '基于ORB的图像搜索引擎' # 网站标题 project_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) cpu_count = cpu_count() upload_image_path = os.path.join(project_path, 'static/uploads/') # 上传图片保存地址 dataset_db_path = os.path.join(pr...
StarcoderdataPython
1647750
<filename>netaccess.py #!/usr/bin/env python3 import selenium import selenium.webdriver from selenium.webdriver.firefox.options import Options import time #--------------------------------firefox--------------------------------- firefox_options = Options() firefox_options.add_argument("--headless") #Comment this to s...
StarcoderdataPython
3285
#!/usr/bin/env python3 import math try: # from PDFPageDetailedAggregator: from pdfminer.pdfdocument import PDFDocument, PDFNoOutlines from pdfminer.pdfparser import PDFParser from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import PDFPageAggregator ...
StarcoderdataPython
3358554
<filename>IPython/core/macro.py """Support for interactive macros in IPython""" #***************************************************************************** # Copyright (C) 2001-2005 <NAME> <<EMAIL>> # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed a...
StarcoderdataPython
3229348
<reponame>olgamelnichuk/NGSPyEasy<gh_stars>1-10 #!/usr/bin/env python ### # Copyright 2015, EMBL-EBI # # 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/LIC...
StarcoderdataPython
1730099
class GlobalState(object): def __init__(self): self.props = {} def set_prop(self, key, value): self.props[key] = value def get_prop(self, key): return self.props[key] GLOBALSTATE = GlobalState()
StarcoderdataPython