id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
3385499
<reponame>Feng-Yuze/ASP # -*- coding: utf-8 -*- """ Created on Tue Oct 10 @author: jaehyuk """ import numpy as np import scipy.stats as ss import scipy.optimize as sopt from . import normal from . import bsm import pyfeng as pf ''' MC model class for Beta=1 ''' class ModelBsmMC: beta = 1.0 # fixed (not use...
StarcoderdataPython
98903
class Solution: def uniquePaths(self, m: int, n: int) -> int: ans = [1]*n for i in range(1,m): for j in range(1,n): ans[j] = ans[j-1] + ans[j] return ans[-1] if m and n else 0
StarcoderdataPython
3241590
import abc from typing import List, Type from nuplan.common.maps.abstract_map_factory import AbstractMapFactory from nuplan.planning.scenario_builder.abstract_scenario import AbstractScenario from nuplan.planning.scenario_builder.scenario_filter import ScenarioFilter from nuplan.planning.utils.multithreading.worker_po...
StarcoderdataPython
1747
<reponame>kra-ts/falconpy """Internal API endpoint constant library. _______ __ _______ __ __ __ | _ .----.-----.--.--.--.--| | _ | |_.----|__| |--.-----. |. 1___| _| _ | | | | _ | 1___| _| _| | <| -__| |. |___|__| |_____|________|_____|____ |____|__| |...
StarcoderdataPython
1692609
from bs4 import BeautifulSoup from urllib.request import Request, urlopen from urllink import crawl req = Request('https://cornellbotanicgardens.org/explore/gardens/medicinal-herbs/', headers={'User-Agent': 'Mozilla/5.0'}) webpage = urlopen(req).read() testfile = open("html/files/a-web/tid6input.txt", "w") soup = Beau...
StarcoderdataPython
1609331
<reponame>mikapfl/datalad<filename>datalad/cmdline/common_args.py # emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 noet: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the data...
StarcoderdataPython
120211
<gh_stars>1-10 import torch def Spatial_loss(matrix, D): x1 = matrix.view(-1, 4096, 1) Sv = torch.std(x1, dim=0) Xm = x1 - x1.mean(dim=0) C = Xm @ Xm.view(-1, 1, 4096) C = C.mean(dim=0) S = Sv @ Sv.view(1, -1) C = C / S loss = torch.abs(C - (1.0 / (D + 1))) kloss = loss.sum()-loss.t...
StarcoderdataPython
3353726
from dipper.graph.Graph import Graph class Family(): """ Model mereological/part whole relationships Although these relations are more abstract, we often use them to model family relationships (proteins, humans, etc.) The naming of this class may change in the future to better reflect the mea...
StarcoderdataPython
3308677
<gh_stars>1-10 from random import random, seed from typing import List from gsf.dynamic_system.dynamic_systems import DiscreteEventDynamicSystem from examples.example_1.cell import Cell class LinearAutomata(DiscreteEventDynamicSystem): """Linear Automata implementation It has a group of cells, connected bet...
StarcoderdataPython
1693034
# <NAME> # 16-09-2020 # Final assignment for Programming # Project: MyMusic from functions import clearConsole, tryParseInt from termcolor import cprint import sys # Everything what belongs to Menu class Menu: # Sets profile and starts the showMenu function def __init__(self, profile, playlist): self...
StarcoderdataPython
152192
from Maxwell import * from dolfin import * from numpy import * import scipy as Sci import scipy.linalg from math import pi,sin,cos,sqrt import scipy.sparse as sps import scipy.io as save import scipy import pdb from matrix2latex import * print "FEniCS routine to solve Maxwell subproblem \n \n" Mcycle = 10 n = 2 tim...
StarcoderdataPython
34372
<reponame>DennyWeinberg/photoprism import unittest from photoprism import Client class TestClass(unittest.TestCase): def test_upload(): client = Client() client.upload_photo('20210104_223259.jpg', b'TODO', album_names=['Test Album'])
StarcoderdataPython
1666373
<filename>cbuild/filter_logic.py<gh_stars>1-10 minelo = self.get_min_elo() if minelo < 2200: self.ok = False
StarcoderdataPython
3322227
import sys from pathlib import Path def check_if_available(prg, msg): """ Check if the given program is available. If not, then die with the given error message. """ if not Path(prg).is_file(): print(msg, file=sys.stderr) sys.exit(1)
StarcoderdataPython
1785891
max_predicate = lambda a, b: a[1] <= b[1] class Heap: def __init__(self): self.heap = [] def heap_swap(self, a, b): t = self.heap[a] self.heap[a] = self.heap[b] self.heap[b] = t def _heapify(self, heap_size, x, predicate): left = 2 * (x + 1) - 1 right = ...
StarcoderdataPython
1749238
<reponame>chidioguejiofor/airtech-api # Generated by Django 2.2 on 2019-04-08 17:22 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0007_auto_20190408_1436'), ('flight', '0014_auto_20190408_1510'), ('booking', '0005_auto_20190408_1644')...
StarcoderdataPython
18683
<filename>syndata/__init__.py # coding=utf-8 # Author: <NAME> <<EMAIL>> # # License: MIT """ The :mod:`deslib.util` This module includes various utilities. They are divided into three parts: syndata.synthethic_datasets - Provide functions to generate several 2D classification datasets. syndata.plot_tools - Provides...
StarcoderdataPython
174528
<reponame>ngshiheng/six-percent from cryptography.fernet import Fernet def generate_key() -> None: """ Generates a key and save it into a file """ key = Fernet.generate_key() with open("secret.key", "wb") as key_file: key_file.write(key) def load_key() -> bytes: """ Loads the ke...
StarcoderdataPython
4802873
default_app_config = 'media_server.apps.MediaServerConfig'
StarcoderdataPython
3911
from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app __author__ = "<NAME>, <NAME>, and <NAME>" __copyright__ = "Copyright 2013-2015 UKP TU Darmstadt" __credits__ = ["<NAME>", "<NAME>", "<NAME>"] __license__ = "ASL" class Redirector(webapp.RequestHandler): def get(self)...
StarcoderdataPython
1788166
<reponame>kagemeka/python from \ kgmk.dsa.algebra.modular \ .factorial.jit \ import ( factorial, inv_factorial, ) import numpy as np import numba as nb @nb.njit def choose( n: int, r: int, ) -> int: global mod, fact, ifact ok = (0 <= r) & (r <= n) c = fact[n] * ok c = c * ifact[n - r] % mod ret...
StarcoderdataPython
1796691
<reponame>HLOverflow/StockCat import math from datetime import datetime from typing import Union, List, Any import pandas from alpha_vantage.fundamentaldata import FundamentalData from pandas import DataFrame, Series from stock_cat.alpha_vantage_ext.fundamentals_extensions import get_earnings_annual ListTable = List...
StarcoderdataPython
3219775
"""Merge data produced in different shards of extraction. Namely: 1. Trajectories 2. Scene cuts Output: single merged files trajectories.jsonl and scene_changes.json """ from typing import Set import argparse import os import json import glob from utils.utils import load_images_map def is_trajectory_valid(t...
StarcoderdataPython
93582
<filename>tests/test_zero.py import os import sys import json import torch from fmoe.layers import _fmoe_general_global_forward from fmoe import FMoETransformerMLP from test_ddp import _run_distributed class ConstantGate(torch.nn.Module): def __init__(self, d_model, num_expert, world_size, top_k=1): supe...
StarcoderdataPython
3377014
<reponame>szperajacyzolw/streamlit_laundering from boruta import BorutaPy import matplotlib.pyplot as plt import matplotlib.patches as mpatches from sklearn.naive_bayes import BernoulliNB, MultinomialNB from sklearn.preprocessing import FunctionTransformer from sklearn.ensemble import RandomForestClassifier from sklear...
StarcoderdataPython
1769960
from gym_meme.envs.meme_env import MemeEnv import gym_meme.envs
StarcoderdataPython
1609710
<reponame>whatisjasongoldstein/scruffy-video import mock import requests import helpers from .helpers import (get_video_type, get_video_type_and_id, youtube_id, vimeo_id, get_embed_src, call_api, get_image_url) TEST_VIMEO_URL = "https://vimeo.com/22733150" TEST_YOUTUBE_URL_1 = "http://www.youtube.com/watch?v=Sic...
StarcoderdataPython
3359685
import numpy as np from random import shuffle def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X:...
StarcoderdataPython
1601591
<filename>wcoa/migrations/0005_remove_connectpage_date.py # Generated by Django 2.2.3 on 2019-07-25 19:54 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('wcoa', '0004_merge_20190725_1749'), ] operations = [ migrations.RemoveField( m...
StarcoderdataPython
56361
words = [word.upper() for word in open('gettysburg.txt').read().split()] theDictionary = {} for word in words: theDictionary[word] = theDictionary.get(word,0) + 1 print(theDictionary)
StarcoderdataPython
7156
from models.Model import Player, Group, Session, engine
StarcoderdataPython
106732
<filename>Source/Apps/StatusClock.py import logging import time import Geometry.Point as PT import Utilities.Recurrer as AR from PIL import ImageDraw, ImageFont import Apps.BaseApp as BA fontfamily = 'DejaVuSansMono.ttf' boldfontfamily = 'DejaVuSansMono-Bold.ttf' class StatusClockApp(BA.BaseApp): def __init__(...
StarcoderdataPython
183770
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.compose import ColumnTransformer from sklearn.impute import SimpleImputer from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.metrics import mean_squared...
StarcoderdataPython
3253285
<reponame>FAIRDataPipeline/FAIR-CLI<gh_stars>0 #!/usr/bin/python3 # -*- coding: utf-8 -*- """ Versioning ========== Methods for handling semantic versioning and parsing version formats Contents ======== Functions --------- parse_incrementer - parse version increment format """ __date__ = "2021-08-05" import r...
StarcoderdataPython
3218796
<gh_stars>1-10 # -*- coding: utf-8 -*- import tempfile import shutil # __del__形式 # class TempDir: # def __index__(self): # self.name = tempfile.mkdtemp() # # def remove(self): # if self.name is not None: # shutil.rmtree(self.name) # self.name = None # # @property # ...
StarcoderdataPython
1669882
import numpy as np import pandas as pd import matplotlib %matplotlib inline import matplotlib.pyplot as plt import statsmodels.tsa.stattools as ts import statsmodels.api as sm from statsmodels.tsa.stattools import adfuller import ffn import warnings warnings.filterwarnings('ignore') def ind_marker(stock): index_m...
StarcoderdataPython
4842746
<gh_stars>0 """ Round precomputed pixel instance embeddings and evaluate performance. """ import argparse import numpy as np def batch_eval(args): """ :param args: """ if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("dataset_dir", help...
StarcoderdataPython
148749
<filename>tests/test_enasearch.py #!/usr/bin/env python from pprint import pprint import enasearch def cmp(la, lb): """Compare two lists""" return all(s in lb for s in la) and all(s in la for s in lb) def test_get_results(): """Test get_results function""" results = enasearch.get_results(verbose=Fal...
StarcoderdataPython
3366203
<filename>test/defense/ckks/test_core.py def test_sigma(): import numpy as np from aijack.defense import CKKSEncoder M = 8 scale = 1 << 20 encoder = CKKSEncoder(M, scale) b = np.array([1, 2, 3, 4]) p = encoder.sigma_inverse(b) b_reconstructed = encoder.sigma(p) np.testing.assert_a...
StarcoderdataPython
3335162
import math import pylev from .en2kr_dict import disease_dict, species_dict # Use minimum edit distance (Levenshtein distance) to map different strings (e.g., African Swine Fever, africa swine fever, etc.) # into one predefined term (african swine fever) def disease_convert(word): closest_word = ("", math.inf) ...
StarcoderdataPython
3281868
<reponame>nor3th/client-python # coding: utf-8 class StixSightingRelationship: def __init__(self, opencti): self.opencti = opencti self.properties = """ id entity_type parent_types spec_version created_at updated_at ...
StarcoderdataPython
3246365
from django.db import models # Create your models here. from django.db import models from cloudinary.models import CloudinaryField # Create your models here. from django.db import models from django.contrib.auth.models import User # Create your models here. class Project(models.Model): image = CloudinaryField...
StarcoderdataPython
138236
from django.urls import reverse from rest_framework import serializers from redirink.links.models import Link class LinkSerializer(serializers.ModelSerializer): """ Serializer to dict for link. """ user = serializers.HiddenField(default=serializers.CurrentUserDefault()) from_url = serializers.Se...
StarcoderdataPython
1720480
MQTT = { 'enabled': True, 'host': 'mosquitto', } INFLUXDB = { 'enabled': False, 'base_url': 'http://influxdb:8086', # Time when data should be written, even if value has not changed 'write_through_time': 60 * 60, 'database': 'heatpump', 'measurement': 'heatpump', } BINDING = { 'upd...
StarcoderdataPython
3349152
<filename>spharpy/special.py """ Subpackage implementing or wrapping special functions required in the spharpy package. """ from itertools import count import numpy as np import scipy.special as _spspecial from scipy.optimize import brentq def spherical_bessel(n, z, derivative=False): r""" Spherical bessel f...
StarcoderdataPython
3293316
<filename>kiqpo/core/ThisValue.py def ThisValue(): return "this.value"
StarcoderdataPython
3379251
<reponame>coecms/dusqlite #!/usr/bin/env python # # Copyright 2019 <NAME> # # Author: <NAME> <<EMAIL>> # # 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/L...
StarcoderdataPython
3225591
<reponame>fkwai/geolearn import matplotlib.pyplot as plt import numpy as np import pandas as pd sd = np.datetime64('2000-01-01') ed = np.datetime64('2000-12-31') t = pd.date_range(sd, ed) td = t.dayofyear.values-1 fig, ax = plt.subplots(1, 1) nt = td.max() # tLst = ['2000-01-01', '2000-03-01', '2000-06-01', '2000-09-0...
StarcoderdataPython
1733152
from Grove_Fingerprint import Fingerprint import sys import wiringpi2 fp = Fingerprint() if fp.verifyPassword(): print 'Found device.' else: print 'Device not found' sys.exit(0) def getFingerprintIDez(): p = fp.getImage() if p != fp.FINGERPRINT_OK: return -1 p = fp.image2Tz() ...
StarcoderdataPython
154278
from systemcheck.checks.models.checks import Check from systemcheck.models.meta import Base, ChoiceType, Column, ForeignKey, Integer, QtModelMixin, String, qtRelationship, \ relationship, RichString, generic_repr, OperatorMixin, BaseMixin, TableNameMixin from systemcheck.systems.ABAP.models import ActionAbapClientS...
StarcoderdataPython
3201858
import importlib from pydashery import Widget def find_function(search_def): """ Dynamically load the function based on the search definition. :param str search_def: A string to tell us the function to load, e.g. module:funcname or module.path:class.staticmethod :raises Val...
StarcoderdataPython
4808573
from twisted.internet import reactor from twisted.internet.defer import Deferred from twisted.internet.error import AlreadyCalled class TimeOutError(Exception): pass class DeferredWithTimeout(Deferred): """ Deferred with a timeout. If neither the callback nor the errback method is not called within the ...
StarcoderdataPython
1777954
<reponame>thoughteer/edera import datetime import multiprocessing import time import pytest from edera.exceptions import ExcusableError from edera.exceptions import ExcusableMasterSlaveInvocationError from edera.exceptions import MasterSlaveInvocationError from edera.invokers import MultiProcessInvoker from edera.rou...
StarcoderdataPython
4826490
import math import os import re from multiprocessing import Pool from collections import defaultdict import tables import numpy as np from astropy.io import fits from astropy.table import Table from beast.observationmodel.noisemodel.generic_noisemodel import get_noisemodelcat from beast.physicsmodel.grid import SEDGr...
StarcoderdataPython
1742137
""" Know more, visit my Python tutorial page: https://morvanzhou.github.io/tutorials/ My Youtube Channel: https://www.youtube.com/user/MorvanZhou Dependencies: tensorflow: 1.1.0 numpy """ import tensorflow as tf import numpy as np import tensorflow.compat.v1 as tf tf.disable_v2_behavior() tf.set_random_seed(1) np.ran...
StarcoderdataPython
36111
<filename>instances/migrations/0001_initial.py # Generated by Django 2.2.10 on 2020-01-28 07:01 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('computes', '0001_initial'), ] operations = [ ...
StarcoderdataPython
4829042
<gh_stars>0 from paperplane.cli.parser import cli from paperplane.parser.main import parse_and_execute # noqa: F401 def main(): """Entry point for the application script""" cli()
StarcoderdataPython
3228586
import string from collections import defaultdict from collections.abc import Callable, Mapping from functools import partial from typing import Any, Iterable, Optional import parse from arti.fingerprints import Fingerprint from arti.internal.utils import frozendict from arti.partitions import CompositeKey, Composite...
StarcoderdataPython
3297534
from functools import reduce from math import exp, log from random import uniform from datasetloader.Dataset import Dataset def sigmoid(x: float) -> float: return 1 / (1 + exp(-x)) class Neuron: ins: [float] weights: [float] out: float def __init__(self, nb_ins: int): self.weights = [uniform(-2, 2) for _ i...
StarcoderdataPython
1685202
<filename>TagScriptEngine/interface/__init__.py from .adapter import Adapter from .block import Block, verb_required_block __all__ = ("Adapter", "Block", "verb_required_block")
StarcoderdataPython
3252998
<reponame>mhostetter/galois<filename>tests/fields/test_field_trace.py """ A pytest module to test the traces over finite fields. Sage: F = GF(2**5, repr="int") y = [] for x in range(0, F.order()): x = F.fetch_int(x) y.append(x.trace()) print(y) """ import pytest import numpy as np impo...
StarcoderdataPython
4821956
<gh_stars>0 from hestia.service_interface import LazyServiceWrapper from django.conf import settings from conf.option_manager import option_manager from conf.service import ConfService def get_conf_backend(): return settings.CONF_BACKEND or 'conf.cluster_conf_service.ClusterConfService' backend = LazyServiceW...
StarcoderdataPython
4808528
<reponame>gurupratap-matharu/Exercism """Script to find pairs of three numbers in an array whose sum is zero""" import itertools def find_three_sum_pairs(nums): """ Finds unique pairs of three numbers in the array whose sum is zero """ pairs = [] for t in itertools.combinations(nums, 3): ...
StarcoderdataPython
3277991
<gh_stars>1-10 from hypothesis.utils.conventions import not_set def accept(f): def tuples(*args): return f(*args) return tuples
StarcoderdataPython
3293233
<reponame>iroan/Practicing-Federated-Learning import torch from torchvision import models def get_model(name="vgg16", pretrained=True): if name == "resnet18": model = models.resnet18(pretrained=pretrained) elif name == "resnet50": model = models.resnet50(pretrained=pretrained) elif name == "densenet121": m...
StarcoderdataPython
3230299
import os import csv from shopify_csv import ShopifyRow def get_template_rows(): with open( os.path.join( os.getcwd(), "shopify_csv", "tests", "fixtures", "product_template.csv" ), "r", ) as file: reader = csv.reader(file, delimiter=";") return [row for row...
StarcoderdataPython
1751756
import datetime import string from django import forms from django.contrib.auth import ( authenticate, get_user_model, password_validation, ) from django.contrib.auth.forms import _unicode_ci_compare, SetPasswordForm from django.contrib.auth.password_validation import validate_password from django.contrib.auth.tok...
StarcoderdataPython
176833
<reponame>rajatrakesh/CDSW-Demos<filename>basketball-stats/analysis.py from pyspark import SparkContext, SparkConf from pyspark.sql import SQLContext from pyspark.sql.types import * conf = SparkConf().setAppName("basketball-analysis") sc = SparkContext(conf=conf) sqlContext = SQLContext(sc) # #set up dataframes dfP...
StarcoderdataPython
1654437
from django.urls import path from . import views urlpatterns = [ path('class/', views.ClassMessageAPIView.as_view()) # path('', views.ClassesAPIView.as_view()), # path('shedule/', views.SheduleTimeAPIView.as_view()), # path('invite/', views.inviteLinks), # path('join/', views.join), ]
StarcoderdataPython
1620535
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from hwt.code import Or, Switch from hwt.interfaces.std import Handshaked from hwt.interfaces.utils import addClkRstn, propagateClkRstn from hwt.math import log2ceil from hwt.serializer.mode import serializeParamsUniq from hwt.synthesizer.hObjList import HObjList from hwt...
StarcoderdataPython
1647062
<reponame>beny2000/TwitterScienceLiteracyProject<gh_stars>0 import csv class Config: def __init__(self, file): ''' Init method for config class :param file: config file name ''' self.config_file = file def __read(self): ''' Creates csv reader for given co...
StarcoderdataPython
3212409
import numpy as np from .utils import check_dimension, check_dtype, convert_dtype, clip_to_uint def rgb_to_gray(image): check_dimension(image,3) shape=image.shape image= image.astype(np.float64) applied=np.apply_along_axis(lambda x: x[0] *0.299 + x[1]*0.587 + x[2]*0.114,2,image ) return clip...
StarcoderdataPython
1709851
#!/usr/bin/env python # coding: utf-8 """ Synthesizes the results of fits into a single file per harmonic. """ import re import os import math import numpy as np import cycle import sys if len(sys.argv)>1: cycidf = sys.argv[1] else: cycidf = cycle.select() # cycle identifier cycdir = cycle.directory(cycidf) ...
StarcoderdataPython
1617252
<reponame>RaphaelPrevost/Back2Shops<gh_stars>0 #!/usr/bin/env python ############################################################################ # <NAME>, LBNL <EMAIL> ############################################################################ """ script that generates a proxy certificate """ import proxylib imp...
StarcoderdataPython
29030
<gh_stars>0 from models.DecisionTree import DecisionTree class Forest: def __init__(self, hyper_parameters, training_set): """ Inicializa a floresta com suas árvores. :param hyper_parameters: dictionary/hash contendo os hiper parâmetros :param training_set: dataset de treinamento ...
StarcoderdataPython
3332945
import json from redshift_connection import RedshiftConnection def response_formatter(status_code='400', body={'message': 'error'}): api_response = { 'statusCode': status_code, 'headers': { 'Access-Control-Allow-Origin' : '*', 'Access-Control-Allow-Credentials' : True ...
StarcoderdataPython
4809704
<gh_stars>0 #!usr/bin/python # # -*- coding:utf8 -*- class Base: pass class Child(Base): pass # 等价定义, 注意Base后面要加上逗号否则就不是tuple了 SameChild = type('Child', (Base,), {}) # 加上方法 class ChildWithMethod(Base): bar = True def hello(self): print('hello') def hello(self): print('hello') # 等价定义 C...
StarcoderdataPython
3261875
""" Copyright 2012, 2013 UW Information Technology, University of Washington 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 r...
StarcoderdataPython
93914
<reponame>pangolp/pyarweb # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('events', '0002_auto_20170325_2011'), ] operations = [ migrations.AddField( model_name=...
StarcoderdataPython
3365948
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Checks whether a number is in a given range. # # Program ...
StarcoderdataPython
3229758
<gh_stars>0 import os import inject import pytest from hg.core.system import SystemRegistry from hg.core.world import World from hg.game.components.position_component import PositionComponent from hg.game.components.sprite_component import SpriteComponent from hg.gfx.sprite_renderer.renderer import SpriteRenderer fr...
StarcoderdataPython
1679145
import os import yaml import pkg_resources class _ConfigurationItem(object): def __init__(self, val): self._val = val def __getitem__(self, key): val = self._val[key] if isinstance(val, dict): return _ConfigurationItem(val) else: return val def __setitem__(self, key, value): self._val[key] = valu...
StarcoderdataPython
1770927
<gh_stars>0 from flask import request, render_template, redirect import pyshorteners from app import app # from app.controllers import # from db_config import get_collection URL = "http://localhost:5000/" @app.route("/", methods=["GET", "POST"]) def home(): if request.method == "GET": return render_template('...
StarcoderdataPython
1602006
from typing import Optional, Tuple import pandas as pd from scipy.spatial.distance import cdist def get_closest_node_id( coordinates: pd.DataFrame, x: float, y: float, distance="euclidean", x_col: str = "x", y_col: str = "y", id_col: Optional[str] = None, ) -> int: cols = [x_col, y_co...
StarcoderdataPython
23972
<reponame>jdelrue/digital_me from jumpscale import j JSBASE = j.application.jsbase_get_class() class GedisProcessManager(JSBASE): pass
StarcoderdataPython
1676042
<reponame>howawong/openwancha # Generated by Django 3.1 on 2020-10-13 11:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sample', '0002_districtminorwork'), ] operations = [ migrations.AlterField( model_name='districtmino...
StarcoderdataPython
4829639
''' puttin' books on shelves ''' import re from django.db import models from bookwyrm import activitypub from .base_model import BookWyrmModel from .base_model import OrderedCollectionMixin, PrivacyLevels from . import fields class Shelf(OrderedCollectionMixin, BookWyrmModel): ''' a list of books owned by a user...
StarcoderdataPython
169757
<gh_stars>1-10 #!/usr/bin/env python3 """exfi.io.gff3_to_bed.py: exfi submodule to convert a gff3 to bed3 where coordinates are with respect to the transcriptome""" import logging import pandas as pd from exfi.io.bed import BED3_COLS, BED3_DTYPES GFF3_COLS = [ "seqid", "source", "type", "start", "end", "score"...
StarcoderdataPython
1779587
<reponame>jmalinao19/Data-Engineer-NanoDegree from create_AWS_cluster import parse_configFile, from cluster_status import get_cluster_status def delete_cluster(redshift, DWH_CLUSTER_IDENTIFIER): """ Request a deletion for Redshift cluster @type redshift -- @param redshift -- Redshift resource client ...
StarcoderdataPython
1671049
<reponame>almarklein/visvis2<gh_stars>1-10 """ Example that implements a simple custom object and renders it. This example draws a triangle at the appropriate position; the object's transform and camera are taken into account. It also uses the material to set the color. But no geometry is used. It demonstrates: * How...
StarcoderdataPython
1782900
import base64 import json import io import time import picamera import cv2 import numpy import requests n=0 while n<10: stream = io.BytesIO() with picamera.PiCamera() as camera: camera.resolution = (320, 240) camera.capture(stream, format='jpeg') buff = numpy.fromstring(stream.getvalue(), dtype=numpy.uint8)...
StarcoderdataPython
159985
import torch, pytz import torch.nn as nn from torch.utils.data import Dataset, DataLoader import numpy as np import pandas as pd import os, csv # For plotting import matplotlib.pyplot as plt from matplotlib.pyplot import figure import streamlit as st from PIL import Image import Reconstruction_DNN, Recon...
StarcoderdataPython
1697063
<reponame>Ting-Jiang/bioinformaticLearning<filename>learning/rLearn.py #! /usr/bin/python # Project : # Author: <NAME> # Email: print("Hello World! I would like to learn Programming from scratch") # Flow Control temp=False if not temp: print("tempt variable is False") for i in range(10): print(i)
StarcoderdataPython
172526
<gh_stars>1-10 from django.db import models from django_countries.fields import CountryField from django.core.validators import MaxValueValidator, MinValueValidator class Client(models.Model): name = models.CharField(max_length=128) email = models.EmailField() phone = models.CharField(max_length=15) b...
StarcoderdataPython
1755721
''' Created by auto_sdk on 2015.09.07 ''' from aliyun.api.base import RestApi class Mts20140618SubmitJobsRequest(RestApi): def __init__(self,domain='mts.aliyuncs.com',port=80): RestApi.__init__(self,domain, port) self.Input = None self.OutputBucket = None self.OutputLocation = None self.Outputs = N...
StarcoderdataPython
129150
#!/usr/bin/env python3 """Solve subset sum problem.""" import argparse import sys import os import platform from collections import defaultdict from collections import Counter from datetime import datetime as dt from math import log import ctypes __author__ = "<NAME>" __email__ = "<EMAIL>" __version__ = 0.1 # within ...
StarcoderdataPython
1719078
<reponame>alexandru-m-g/hdx-ckan import requests import logging import beaker.cache as bcache import pylons.config as config from datetime import datetime, timedelta from collections import OrderedDict import ckanext.hdx_theme.util.jql_queries as jql_queries bcache.cache_regions.update({ 'hdx_jql_cache': { ...
StarcoderdataPython
3298741
<filename>views.py from django.shortcuts import render from django.views.decorators.csrf import csrf_protect, csrf_exempt # from django.template.context_processors import csrf from hashlib import sha512 import hashlib # Create your views here. def index(request): MERCHANT_KEY = "33y8dMBB" SALT = "HI...
StarcoderdataPython
1701682
'''Faça um programa que, dado um conjunto de N números, determine o menor valor, o maior valor e a soma dos valores.''' conjunto = int(input('Quantos Números terá seu conjunto? ')) menor_valor = maior_valor = soma = 0 for cont in range (1, conjunto+1): num = float(input(f'{cont}º número: ')) soma += num i...
StarcoderdataPython
1625943
"""Loads CartPole-v1 demonstrations and trains BC, GAIL, and AIRL models on that data. """ import pathlib import pickle import tempfile import gym import stable_baselines3 as sb3 from stable_baselines3.common import base_class from stable_baselines3.common.torch_layers import ( BaseFeaturesExtractor, # Combin...
StarcoderdataPython