id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
79099
"""Linked List v2 === CSC148 Winter 2018 === University of Toronto, Computer Science __author__ = '<NAME>' === Module Description === This module contains a linked list implementation. Note that the size can be reduced by using multiple assignment statements. This module was made for lab 4. """ from typing import Opt...
StarcoderdataPython
187983
<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- import os from urllib.request import urlopen from urllib.parse import urlparse import configparser from bs4 import BeautifulSoup from flask import Flask, render_template, make_response from email.utils import formatdate import logging app = Flask(__name__) d...
StarcoderdataPython
138772
# Copyright 2018 The TensorFlow Authors. 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 applica...
StarcoderdataPython
3352444
<gh_stars>1-10 import pytest from pyupgrade import _fix_py3_plus @pytest.mark.parametrize( 's', ( # syntax error 'x = (', # does not inherit from `object` 'class C(B): pass', ), ) def test_fix_classes_noop(s): assert _fix_py3_plus(s, (3,)) == s @pytest.mark.parametri...
StarcoderdataPython
130801
""" Layout components to lay out objects in a grid. """ import math from collections import OrderedDict, namedtuple from functools import partial import numpy as np import param from bokeh.models import Box as BkBox, GridBox as BkGridBox from ..io.model import hold from .base import _col, _row, ListPanel, Panel ...
StarcoderdataPython
4865
""" Data: Temperature and Salinity time series from SIO Scripps Pier Salinity: measured in PSU at the surface (~0.5m) and at depth (~5m) Temp: measured in degrees C at the surface (~0.5m) and at depth (~5m) - Timestamp included beginning in 1990 """ # imports import sys,os import pandas as pd import numpy as...
StarcoderdataPython
3582
import os import numpy as np import pytest import easyidp from easyidp.core.objects import ReconsProject, Points from easyidp.io import metashape module_path = os.path.join(easyidp.__path__[0], "io/tests") def test_init_reconsproject(): attempt1 = ReconsProject("agisoft") assert attempt1.software == "metash...
StarcoderdataPython
17159
# coding: utf-8 """ Grafeas API An API to insert and retrieve annotations on cloud artifacts. # noqa: E501 OpenAPI spec version: v1alpha1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from grafeas.models.deployment_deta...
StarcoderdataPython
21180
#!/bin/python3 # author: <NAME> import tests tests.fix_paths() import yaml from unittest import TestCase from cihpc.cfg.config import global_configuration from cihpc.common.utils import extend_yaml repeat_yaml = ''' foo: !repeat a 5 ''' range_yaml = ''' foo: !range 1 5 bar: !range 1 2 6 ''' sh_yaml = ''' foo: !...
StarcoderdataPython
3369648
import torch import torch.nn as nn import torch.nn.functional as F from mmcv.runner import load_checkpoint from mmedit.models.common import make_layer, pixel_unshuffle from mmedit.models.registry import BACKBONES from mmedit.utils import get_root_logger def get_padding_functions(x, padding=7): """Generate paddin...
StarcoderdataPython
3224298
<filename>src/models/cnn.py<gh_stars>0 import torch import torch.nn as nn import torch.nn.functional as F from src.models.base_torch_model import BaseTorchModel class CNN(BaseTorchModel): def __init__(self, config, vocab): """Initialize the network :param config: :param vocab: obtained ...
StarcoderdataPython
90281
<filename>applications/management/commands/gatherresumes.py from django.core.management.base import BaseCommand, CommandError from applications.models import Application import os import tarfile class Command(BaseCommand): def handle(self, *args, **options): print("Gathering Resumes: This may take a few ...
StarcoderdataPython
3229697
<filename>src/phonology_task_creation.py # Methods for creating phonology tasks import random from random import shuffle import copy # Creates a phoneme inventory for a language def phoneme_inventory(v_min=2, v_max=4, c_min=2, c_max=4, vowels=None, consonants=None): if vowels is None: vowels = ['a', 'e', '...
StarcoderdataPython
30605
<gh_stars>100-1000 import FWCore.ParameterSet.Config as cms # AlCaReco for track based alignment using MinBias events OutALCARECOTkAlMinBias_noDrop = cms.PSet( SelectEvents = cms.untracked.PSet( SelectEvents = cms.vstring('pathALCARECOTkAlMinBias') ), outputCommands = cms.untracked.vstring( ...
StarcoderdataPython
125605
from typing import List, Dict, Callable, Any from ..plugins.panel import PyriWebUIBrowserPanelInfo, PyriWebUIBrowserPanelPluginFactory, PyriWebUIBrowserPanelBase from .. import PyriWebUIBrowser from .welcome_panel import add_welcome_panel from .devices_panel import add_devices_panel from. program_panel import add_progr...
StarcoderdataPython
3029
<reponame>tomaszkingukrol/rest-api-cache-proxy from abc import ABC, abstractclassmethod from model.response import ResponseModel class CacheInterface(ABC): @abstractclassmethod async def get(cls, url: str) -> ResponseModel: pass @abstractclassmethod async def set(cls, url: str, value: ResponseModel,...
StarcoderdataPython
4821955
# -*- coding: utf-8 -*- from django.contrib.auth import authenticate from data.view_classes.custom_view import CustomView import data.models as models class User(CustomView): def get(self): username = self.user.username self.add_response_data('username', username) leagues = [row.league.name for row in m...
StarcoderdataPython
1658536
<reponame>txdywy/flask # -*- coding: utf-8 -*- """ Alancer ~~~~~~~~ An application written with Flask and sqlite3. :copyright: (c) 2015 by <NAME>. :license: BSD, see LICENSE for more details. """ #from gevent import monkey #monkey.patch_all() import time, urllib2 from datetime import datetime from...
StarcoderdataPython
1764443
<filename>ospy/sensors.py # -*- coding: utf-8 -*- __author__ = u'<NAME>' # System imports from threading import Thread, Timer import traceback import logging import traceback import time import datetime import subprocess import os import json # Local imports from ospy.options import options, rain_blocks, program_leve...
StarcoderdataPython
3315660
from django.shortcuts import render, redirect, get_object_or_404 from django.contrib import messages from .models import Image, Comments, Profile from django.db import transaction from django.contrib.auth.models import User from django.http import HttpResponse, HttpResponseRedirect, Http404 from .forms import NewsLette...
StarcoderdataPython
3387142
<reponame>fnp/pylucene # ==================================================================== # 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/LICE...
StarcoderdataPython
3370472
<gh_stars>0 import pathlib import unittest from swiss_tournament.data.player import Player from swiss_tournament.data.result import Result from swiss_tournament.data.round_pairing import RoundPairing from swiss_tournament.data.tournament import Tournament from swiss_tournament.parse.tournament_parser import YamlTourna...
StarcoderdataPython
73355
<gh_stars>1-10 from django.conf.urls import url from django.contrib.auth.decorators import login_required, permission_required from . import views, accounts from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # paymentoption urls url(r'^$', permission_required('banking...
StarcoderdataPython
1642872
<filename>tools/notebooks/create_waymo_masks.py import time import json import datetime import os import tensorflow.compat.v1 as tf import math import glob import numpy as np import itertools import setproctitle import argparse from pathlib import Path tf.enable_eager_execution() from waymo_open_dataset.utils import r...
StarcoderdataPython
1795646
'''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.GL import _types as _cs # End users want this... from OpenGL.raw.GL._types import * from OpenGL.raw.GL import _errors from OpenGL.constant import Constant as _C import ctypes _...
StarcoderdataPython
3245382
<reponame>emilydolson/avida-spatial-tools from avidaspatial import * def test_make_toroidal_weights(): weights = make_toroidal_weights(5, 5) for el in weights.neighbors.values(): assert(len(el) == 4) weights = make_toroidal_weights(15, 10) for el in weights.neighbors.values(): assert(...
StarcoderdataPython
159833
#!/usr/bin/env python3 import numpy as np ############################################################# class Person(): def __init__(self, _id, pos, moveinterval, destiny): self.id = _id self.destiny = destiny self.pos = pos self.moveinterval = moveinterval self.path = np....
StarcoderdataPython
80193
<reponame>jjkeyser/exercism<gh_stars>0 import re class PhoneNumber: def __init__(self, number): self.number = self.clean_number(number) self.area_code = self.number[0:3] def clean_number(self, number): number = re.sub("[^0-9]", "", number) if ( len(number) > 11 ...
StarcoderdataPython
1754962
<reponame>nekron2323/websocket from fastapi import FastAPI, WebSocket, WebSocketDisconnect from fastapi.responses import FileResponse app = FastAPI() CLIENT_FOLDER = '../client' HTML_FILE = '/index.html' client_messages = {} @app.get('/') async def get(): return FileResponse(CLIENT_FOLDER + HTML_FILE) @app.we...
StarcoderdataPython
1768690
# # Copyright (c) 2009-2015, <NAME> # All rights reserved. # # This file is part of Elemental and is under the BSD 2-Clause License, # which can be found in the LICENSE file in the root directory, or at # http://opensource.org/licenses/BSD-2-Clause # import math, El n = 50 # matrix size realRes ...
StarcoderdataPython
3391742
reference_data_path = '../testing_data/obs_for_e3sm_diags/time-series' test_data_path = '../testing_data/test_model_data_for_e3sm_diags/time-series/E3SM_v1' test_name = 'E3SM_v1' # Needed so it can be shown on the plots. results_dir = 'model_ts_vs_obs_ts_results' ref_timeseries_input = True ref_start_yr = 1980 ref_e...
StarcoderdataPython
3238410
<gh_stars>0 import os from pymodm.connection import connect from pymongo import MongoClient # ==== Configuration ==== DB_CONFIG = 'cfg' CN_SEQUENCE = 'sequence' CN_CCXT_CONFIG = 'cxt' # ==== User ==== DB_USER = 'user' CN_USER_AUTH = 'auth' CN_USER_INFO = 'info' # ==== Market ==== DB_MARKET = 'market' CN_NEUTRA...
StarcoderdataPython
3324630
import discord from . import Permission class CreateInstantInvite(Permission): def has_permission(self, user: discord.User, channel: discord.Channel): if isinstance(user, discord.Member): return channel.permissions_for(user).create_instant_invite else: return False clas...
StarcoderdataPython
1608774
#!/software/anaconda3.6/bin/python from mpi4py import MPI import os import pickle from OpSim import OpSim from astropy.coordinates import SkyCoord from astropy import units import numpy as np if __name__ == "__main__": comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() sendbuf = None root = ...
StarcoderdataPython
1715456
<filename>VCFTools_0_1_12b.py from starcluster.clustersetup import ClusterSetup from starcluster.logger import log class VCFToolsInstaller(ClusterSetup): def run(self, nodes, master, user, user_shell, volumes): for node in nodes: log.info("Installing vcftools 0.1.12b on %s" % (node.alias)) node.ssh.execute('w...
StarcoderdataPython
1721396
<filename>wdt/menu/tests/test_get_item.py import uuid from http import HTTPStatus import pytest QUERY = """ query GetItem($id:ID!) { item(id: $id) { id name description photo } } """ @pytest.mark.django_db @pytest.mark.usefixtures("example_data") class TestGetItem: def test_get_valid_item(s...
StarcoderdataPython
1782601
<filename>pterradactyl/terraform/config.py import os import re import json import yaml import phiera from pterradactyl.config import Config from pterradactyl.util import merge_dict, lookup # XXX - this class is too "clever" for its own good. it's hard to follow. class TerraformConfig(object): alias_syntax = re....
StarcoderdataPython
197426
# Copyright (c) 1996-2015 PSERC. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. """Power flow data for IEEE 118 bus test case. """ from numpy import array def case118(): """Power flow data for IEEE 118 bus test case. Please see L{cas...
StarcoderdataPython
91119
<reponame>bodealamu/datamallet import pandas as pd from datamallet.tabular.timeseries import Resampler, RollingWindow d = {'price': [10, 11, 9, 13, 14, 18, 17, 19,10, 11, 9, 13, 14, 18, 17, 19,50, 60, 40, 100, 50, 100, 40,10, 11, 9, 13, 14, 18, 17, 19,10,], 'volume': [50, 60, 40, 100, 50, 100, 40, 50,10, 11, 9, 1...
StarcoderdataPython
3226835
from CommonServerPython import * import traceback SECTIONS_TO_KEEP = ('Threat Hunting', 'Mitigation', 'Remediation', 'Eradication') HEADER_TRANSFORM = {'id': 'Task ID', 'name': 'Task Name', 'state': 'Task State', 'completedDate': 'Completion Time'} ''' COMMAND FUNCTION ''' def add_url_to_tasks(tasks: Dict, workpl...
StarcoderdataPython
1611373
# =============================================================================== # # # # This file has been generated automatically!! Do not change this manually! # # ...
StarcoderdataPython
98224
<reponame>TmsRC/Final_Punto15 import numpy as np import matplotlib.pyplot as plt datos = np.loadtxt("datos.dat").T plt.figure() plt.plot(datos[1],datos[2]) plt.title("Trayectoria") plt.ylabel("Y") plt.xlabel("X") plt.savefig("RubioTomas_final_15.pdf") plt.figure() plt.plot(datos[1],datos[2]) plt.title("Trayectoria")...
StarcoderdataPython
1623388
# Based on code from https://github.com/standupmaths/xmastree2020 # Modified heavily by gentlegiantJGC import argparse import board import neopixel from run_utils import parse_animation_csv, draw_frames # change if your setup has a different number of LEDs NUMBER_OF_LEDS = 500 def load_and_run_csv(csv_path): ...
StarcoderdataPython
3331425
limit = 4 * pow(10, 6) last = 1 before = 0 list_ = [] while (last+before < limit): current = last + before if (current % 2 == 0): print (current) list_.append(current) before = last last = current print("Summe: " + str(sum(list_)))
StarcoderdataPython
3339933
<filename>tests/main.py import os import sys import pytest import datetime class Main(object): """docstring for Main""" def __init__(self, arg): self.arg = arg if not os.path.exists('log'): os.makedirs('log') LOG = 'log/log_{:%Y-%m-%d_%H:%M:%S}.txt'.format(datetime.datetime.now()) CALL = '--resultlog=%s...
StarcoderdataPython
35429
# coding: utf-8 # # k-means with text data # In this assignment you will # * Cluster Wikipedia documents using k-means # * Explore the role of random initialization on the quality of the clustering # * Explore how results differ after changing the number of clusters # * Evaluate clustering, both quantitatively and q...
StarcoderdataPython
23447
# # Jasy - Web Tooling Framework # Copyright 2010-2012 Zynga Inc. # Copyright 2013-2014 <NAME> # import os import jasy import jasy.core.Console as Console from jasy.item.Script import ScriptError from jasy.item.Script import ScriptItem import jasy.script.Resolver as ScriptResolver from jasy.script.Resolver import R...
StarcoderdataPython
1740388
<gh_stars>0 lambda x: x * 2 def myfunc(x): return x * 2 print(myfunc(2)) a = [(3, 4), (5, 6), (7, 8), (2, 1)] a.sort(key=lambda x: x[1]) print(a) myList = [1,4,6,1,7,8,3,2] print(list(map(lambda x: x*3, myList))) print(list(map(lambda x: 'big' if x> 5 else 'small', myList))) print(list(filter(lambda x: x%2 ...
StarcoderdataPython
1687236
<reponame>ronaldseoh/cnnimageretrieval-pytorch import os import pickle import pdb import copy import random import torch import torch.utils.data as data import tqdm from cirtorch.datasets.datahelpers import default_loader, imresize, cid2filename from cirtorch.datasets.genericdataset import ImagesFromList from cirtorc...
StarcoderdataPython
198467
<reponame>solex/presto<gh_stars>0 from copy import deepcopy import simplejson as json from presto.utils.fields import Field, MultipleObjectsField, FormField from presto.utils.exceptions import ValidationError def get_declared_fields(bases, attrs): """ Create a list of Model field instances from the passed in ...
StarcoderdataPython
1707544
from django.urls import path from django.views.decorators.csrf import csrf_exempt from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('practicehome', views.go_pracicehome, name='practicehome'), path('generalinfo',...
StarcoderdataPython
1621308
from __future__ import print_function import boto3 from boto3.dynamodb.conditions import Key, Attr from botocore.exceptions import ClientError import datetime import decimal import inflect import json import os import re import requests print('Loading function') debug = os.getenv('DEBUG', 'false') taco_name = os.get...
StarcoderdataPython
99560
# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors # This software is distributed under the terms and conditions of the 'Apache-2.0' # license which can be found in the file 'LICENSE' in this package distribution # or at 'http://www.apache.org/licenses/LICENSE-2.0'. from setuptools import setup,...
StarcoderdataPython
64518
import bs4 html_str = """ <html> <body> <ul> <li>hello</li> <li>bye</li> <li>welcome</li> </ul> </body> </html> """ bs_obj = bs4.BeautifulSoup(html_str, "html.parser") ul = bs_obj.find("ul") lis = ul.findAll("li") print(lis)
StarcoderdataPython
1785065
<gh_stars>0 from django.urls import path, include from rest_framework.authtoken import views as authtoken_views from apps.users import views urlpatterns = [ path('auth/token/', authtoken_views.obtain_auth_token), path('users/<int:pk>/', views.UserDetail.as_view()), ]
StarcoderdataPython
3208217
<gh_stars>10-100 # -*- coding: utf-8 import torch import torch.nn as nn import torch.nn.functional as F from pytorch_lightning.metrics import MulticlassROC, MulticlassPrecisionRecall from pytorch_lightning.metrics.functional import auc, precision, recall class MultiAUPRC(nn.Module): def __init__(self, num_class...
StarcoderdataPython
1602084
# Copyright (C) 2019 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
StarcoderdataPython
1605651
<reponame>spolu/fuzz1ng import json class Config: def __init__( self, config, ) -> None: self._config = config def get( self, key: str, ): if key not in self._config: raise Exception("Unknown Config key {}".format(key)) ...
StarcoderdataPython
4801948
# $Id: version.py 148 2006-09-22 01:30:23Z quarl $ import subprocess def pipefrom(cmd): return subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0] version = pipefrom(['../build-interceptor-version', '-n'])
StarcoderdataPython
120276
<filename>pantaray/test/test_importance.py import unittest import numpy as np from numpy.random import shuffle from sklearn.datasets import load_digits from sklearn.linear_model import LogisticRegression from sklearn.exceptions import NotFittedError from pantaray.importance_estimation import PCIF class ImportanceT...
StarcoderdataPython
1774139
""" Write a Person class with an instance variable, age, and a constructor that takes an integer, initialAge, as a parameter. The constructor must assign initalAge to age after confirming the argument passed as initailAge is not negative; if a negative argument is passed as initialAge, the constructor should set age to...
StarcoderdataPython
3257548
import pytest @pytest.fixture def user(django_user_model): return django_user_model.objects.create_user(username='TestUser', password='<PASSWORD>') @pytest.fixture def user_client(user, client): client.force_login(user) return client
StarcoderdataPython
1701816
from collections import defaultdict from concurrent.futures import ThreadPoolExecutor from typing import DefaultDict, Dict, Iterable, List, Optional, Union from .constants import SECS_IN_DAY, SECS_IN_HR from .helpers import ConstellationId, get_constellation, get_closest, get_el_az, TimeRangeHolder from .ephemeris imp...
StarcoderdataPython
3257600
<gh_stars>1-10 from ..trie import Trie def test_exist(): word = 'abc' trie = Trie() trie.insert(word) assert word in trie assert 'ab' not in trie assert 'zxy' not in trie def test_match_prefix(): trie = Trie() trie.insert('珍奶') trie.insert('珍奶去冰') assert '珍奶去冰' == trie.match...
StarcoderdataPython
1768579
from binpacking.to_constant_volume import to_constant_volume, csv_to_constant_volume def test_exact_fit(): values = [1, 2, 1] bins = to_constant_volume(values, 2) assert len(bins) == 2
StarcoderdataPython
178867
<gh_stars>0 class Leapx_org(): pass L_obj1 = Leapx_org() L_obj2 = Leapx_org() print (L_obj1) print (L_obj2)
StarcoderdataPython
194777
<filename>model/contact.py class Contact: def __init__(self, firstname, lastname, company, address, telephone, mobile, tel_work, email, email_1, www): self.firstname = firstname self.lastname = lastname self.company = company self.address = address self.telephone = telephone ...
StarcoderdataPython
189671
<reponame>emergent/ProjectEuler #! /usr/bin/env python3 ''' Problem 1 - Project Euler http://projecteuler.net/index.php?section=problems&id=001 ''' def summul(n, x): return int(x * (n // x) * (n // x + 1) / 2) if __name__ == '__main__': N = 1000 - 1 print(summul(N, 3) + summul(N, 5) - summul(N, 3 * 5))
StarcoderdataPython
4821958
<gh_stars>0 from array import array # signed integer a = array('h', (i ** 2 for i in range(1, 7))) mv = memoryview(a) print('memoryview int ', ', '.join([str(i) for i in mv])) oct = mv.cast('B') print('memoryview oct', oct.tolist())
StarcoderdataPython
3269530
<filename>early-returns/double/test_double_vs_guarded.py from double import double from guarded_double import guarded_double assert guarded_double(None) is double(None) is None assert guarded_double(1) == double(1) == 2
StarcoderdataPython
135534
<reponame>bopopescu/phyG # This script allows easy access to Galaxy's database layer via the # Galaxy models. For example: # % python -i scripts/db_shell.py # >>> new_user = User("<EMAIL>") # >>> new_user.set_password # >>> sa_session.add(new_user) # >>> sa_session.commit() # >>> sa_session.query(User).all() # # You c...
StarcoderdataPython
1643541
<gh_stars>0 #!/usr/bin/env python import sys, random import gdax import time from secret_keys import key, b64secret, sbkey, sbsecret, passphrase import traceback from datetime import date import matplotlib.pyplot as plt import numpy as np products = ['ETH-USD', 'BTC-USD', 'LTC-USD'] public_client = gdax.PublicClient...
StarcoderdataPython
3350523
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2019 Baidu.com, Inc. All Rights Reserved # """ requirements: Authors: daisongtai(<EMAIL>) Date: 2019/5/29 6:38 PM """ from __future__ import print_function import re from transformers import BertTokenizer,ElectraTokenizer max_seq_length = 300 # toke...
StarcoderdataPython
38474
import sqlalchemy from .base import Base from .track import Track import model.tracktime class GroupTrack(Base): ''' a link between group and track (association pattern) backrefs group and track (not listed here) To use this first create the group, then group tracks, then tracks and add them to ...
StarcoderdataPython
192638
<gh_stars>1-10 from datetime import date from datetime import datetime from typing import Optional from typing import Union from dateutil.parser import isoparse def parse_datetime(d: Optional[Union[str, date, datetime]]) -> Optional[datetime]: if d is None or d == '': return None if isinstance(d, st...
StarcoderdataPython
1666291
from lost_ds.segmentation.semantic_seg import semantic_segmentation from lost_ds.segmentation.anno_from_seg import segmentation_to_lost
StarcoderdataPython
1615386
""" scheduler """ from .CuBackgroundScheduler import CuBackgroundScheduler from .CuGeventScheduler import CuGeventScheduler
StarcoderdataPython
1664151
import json import requests def to_short_data(index_data): return { "index": index_data['index'], "docs.count": index_data['docs.count'] } url = 'http://localhost:9200/_cat/indices?v' response = requests.get(url, headers={'Accept': 'application/json'}) parsed = json.loads(response.content) sh...
StarcoderdataPython
1612222
from typing import Dict, Any from qcodes.dataset.descriptions.param_spec import ParamSpec class InterDependencies: """ Object containing the ParamSpecs of a given run """ def __init__(self, *paramspecs: ParamSpec) -> None: for paramspec in paramspecs: if not isinstance(paramspec...
StarcoderdataPython
3352489
import os import shutil import tempfile from ConfigParser import RawConfigParser from twisted.trial import unittest from twisted.internet import defer from twisted.internet import reactor import siptrackdlib from siptrackdlib.storage import stsqlite def make_storage(config): return siptrackdlib.storage.load( ...
StarcoderdataPython
1682574
# pygameを読み込む import pygame # sysライブラリを読み込む import sys # pygameのlocalsファイルにあるすべての変数、関数、クラスを読み込む from pygame.locals import * # GUI表示ライブラリtkinterを読み込む import tkinter as tk # os関連の処理をするosライブラリを読み込む import os # snake.pyにあるすべての変数、関数、クラスを読み込む from snake import * # food.pyにあるすべての変数、関数、クラスを読み込む from food import * # background....
StarcoderdataPython
3283183
<gh_stars>0 import random from typing import Any, List def to_string(list_obj: List) -> str: # convert a list to a string return ''.join(list_obj) def to_list(string_obj: str) -> List: # convert a string to list return list(string_obj) def get_random_word() -> str: # return a random shuffle of...
StarcoderdataPython
73001
<reponame>Signal-Kinetics/alexa-apis-for-python<filename>ask-sdk-model-runtime/ask_sdk_model_runtime/lwa/error.py<gh_stars>10-100 # -*- coding: utf-8 -*- # # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights # Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). # You may not use th...
StarcoderdataPython
3339059
from django import forms class ExtensionSearchForm(forms.Form): """Form used to clean up query parameters before sending them to ExtensionSearchFormFilter.""" # Note: consider inheriting from mkt.search.forms.SimpleSearchForm later # when it starts sharing more fields with Webapps and Websites. au...
StarcoderdataPython
1679929
from django import template from memoize import memoize register = template.Library() @memoize(timeout=3600) def get_kind_col(container): kind = container.kind height = kind.layout.get('height', 1.0) envelope = kind.envelope if envelope == 'circle' or height >= 0.75: return 'col-3' else: ...
StarcoderdataPython
1690347
from django.urls import path from . import views urlpatterns = [ path('owner/<int:owner_id>/', views.owner), path('car/', views.Car_List.as_view()), path('car/<int:pk>/', views.One_Car.as_view()), path('owner_create', views.create_view), path('car/<int:pk>/update', views.Car_Update.as_view()), ...
StarcoderdataPython
1714157
<gh_stars>0 from app import app from flask import render_template import rnn print("Starting RNN") RNN = rnn.GruRNN( hid_size=200, trunc=100, emb_size=100, dataset="datasets/all_stories.pkl" ) print("Started RNN") @app.route('/') @app.route('/index') def index(): user = {'nickname': 'Terry'} p...
StarcoderdataPython
19696
<gh_stars>1-10 from .plugin import ProcessTimePlugin
StarcoderdataPython
3232040
<reponame>triangle1984/vk-bot from PIL import Image class Pillowhelper(): def resize_image(input_image_path, size): original_image = Image.open(input_image_path) width, height = original_image.size resized_image = original_image.resize(size) width, height = resized_i...
StarcoderdataPython
50609
# Generated by Django 2.2.4 on 2019-08-11 17:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('alarms_project', '0002_auto_20190811_1841'), ] operations = [ migrations.AlterField( model_name='alarm', name='time'...
StarcoderdataPython
1736788
<filename>sovtoken/sovtoken/messages/fields.py from base58 import b58decode_check from plenum.common.messages.fields import FieldBase, AnyMapField, FixedLengthField, TxnSeqNoField, IterableField from sovtoken.util import decode_address_to_vk_bytes class PublicAddressField(FieldBase): _base_types = (str, ) le...
StarcoderdataPython
89655
<reponame>kotabrog/bootcamp_python from math import sqrt class TinyStatistician: def __init__(self): pass def mean(self, x): if len(x) == 0: return None ret = 0 for value in x: ret += float(value) return ret / float(len(x)) def median(self,...
StarcoderdataPython
1754760
# -*- coding: utf-8 -*- """Build a WSGI application for Bio2BEL Entrez. This module builds a :mod:`Flask` application for interacting with the underlying database. When installing, use the web extra like: .. source-code:: sh pip install bio2bel_entrez[web] """ from .manager import Manager manager = Manager() ...
StarcoderdataPython
128292
<reponame>IsaiahPressman/Kaggle_Santa_2020<filename>benchmark_model.py import base64 import os import pickle import torch # Custom imports import graph_nns as gnn import vectorized_agents as va import vectorized_env as ve DEVICE = torch.device('cuda') RUN_FOLDER = 'a3c/TEMP' MODEL_CHECKPOINT = '140' AGENT_OBS_TYPE =...
StarcoderdataPython
3362321
<reponame>Sunmish/Aegean #! /usr/bin/env python """ Tools for manipulating angles on the surface of a sphere - distance - bearing between two points - translation along a path - paths are either great circles or rhumb lines also angle <-> string conversion tools for Aegean """ __author__ = "<NAME>" import math impo...
StarcoderdataPython
1796570
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired class SignupForm(FlaskForm): username = StringField('username: ', validators=[DataRequired()]) password = StringField('password: ', validators=[DataRequired()]) sfsubmit = SubmitField('S...
StarcoderdataPython
3358565
<reponame>gavincangan/pyro """ Inference algorithms and utilities used in the RSA example models. Adapted from: http://dippl.org/chapters/03-enumeration.html """ from __future__ import absolute_import, division, print_function import collections import six import torch from six.moves import queue import pyro impor...
StarcoderdataPython
97055
<filename>src/pathfinders/pathfinder.py<gh_stars>0 from typing import TYPE_CHECKING, List from math import inf if TYPE_CHECKING: from src.points import Points from pygame import Vector2 class Pathfinder: def __init__(self, points_container: "Points"): self.points_container = points_container ...
StarcoderdataPython
168273
<reponame>allenai/tango from typing import Union import datasets as ds from tango.integrations.datasets import DatasetsFormat from tango.step import Step @Step.register("subset-data") class SubsetData(Step): """ Creates a subset of the data; mostly to be used for testing/debugging. """ DETERMINISTI...
StarcoderdataPython
112376
import numpy as np from scipy.io import loadmat from tqdm import tqdm from cmfsapy.dimension.fsa import ml_dims load_path = "../benchmark_data/manifold_data/" save_path = "./" datasets = [1, 2, 3, 4, 5, 6, 7, 9, 101, 102, 103, 104, 11, 12, 13] D = [11, 5, 6, 8, 3, 36, 3, 20, 11, 18, 25, 71, 3, 20, 13] intdims = [10...
StarcoderdataPython