id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
173243
import os import re from django.conf import settings from statsd.defaults.django import statsd DATADOG_METRICS = False DATADOG_TAGS = None if settings.DATADOG_API_KEY: from datadog import initialize options = { 'api_key': settings.DATADOG_API_KEY, 'app_key': settings.DATADOG_APP_KEY } ...
StarcoderdataPython
3339451
# -*- coding: utf-8 -*- from __future__ import ( absolute_import, division, print_function, unicode_literals, ) import unittest from unittest import TestCase class DataTest(TestCase): """Obey the testing goat.""" def test_something(self): """A testing template -- make to update tests...
StarcoderdataPython
160296
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def add(self, data): if self.head is None: self.head = Node(data) else: temp = self.head self.head = N...
StarcoderdataPython
1787440
"""Unit tests for agent factory. """ import unittest from parameterized import parameterized from stock_trading_backend.agent import create_agent, FollowingFeatureAgent from stock_trading_backend.util import read_config_file class TestAgentFactory(unittest.TestCase): """Unit tests for agent factory. """ ...
StarcoderdataPython
3361716
<filename>lib/p5/pvector.py class PVector(object): def __init__(self, x, y, z=0): self.x = x self.y = y self.z = z def add(self, *args): x, y, z = (args[0].x, args[0].y, args[0].z) if len(args) == 1 else args self.x += x self.y += y self.z += z de...
StarcoderdataPython
198786
<filename>src/common.py import os import sys import logging import logging.handlers import configparser import hashlib import subprocess DONE = "done" SYSTEM_CONF_FILE="DisNOTE.ini" SEG_TMP_AUDIO_LENGTH="seg_tmp_audio_length" IS_RECOGNIZE_NOIZE="is_recognize_noize" def getVersion(): return "v2.1.1" # 無音検出時に作るテンポラリフ...
StarcoderdataPython
122225
from setuptools import setup setup( name='beets-mpdadd', version='0.2', description='beets plugin that adds query results to the current MPD playlist', author='<NAME>', author_email='<EMAIL>', license='MIT', platforms='ALL', packages=['beetsplug'], install_requires=['beets', 'python...
StarcoderdataPython
1733154
<gh_stars>1-10 import re class DigestConfig: def __init__(self): self._digest_pattern = "[KR]" # Trypsin/P = "([KR](?=[^P]))", AspN = "\w(?=D)" self.digest_pattern = self._digest_pattern self.min_len = 7 self.max_len = 30 self.max_miss_cleave = 2 self.cleave_type = "...
StarcoderdataPython
4840497
<reponame>iBalag/claimant from datetime import datetime, timedelta from typing import List, Optional from aiogram import types from aiogram.dispatcher import FSMContext from aiogram.types import ReplyKeyboardMarkup, ReplyKeyboardRemove, InlineKeyboardButton, \ InlineKeyboardMarkup from common import calc_oof_prof...
StarcoderdataPython
3298576
<reponame>AlexRogalskiy/DevArtifacts<filename>master/kismet-2018-08-BETA1/kismet-2018-08-BETA1/capture_freaklabs_zigbee/KismetCaptureFreaklabsZigbee/__init__.py<gh_stars>1-10 #!/usr/bin/env python2 """ freaklabs zigbee sniffer source accepts standard source hop options accepts additional options: device=/path/to/ser...
StarcoderdataPython
105484
import logging import click import obelisk from pathlib import Path logger = logging.getLogger(__name__) @click.command() @click.option("-c", "--convert", is_flag=True, help="convert file (currently the only mode)") @click.option("-i", "--input", prompt="Input filepath: ", help="Input f...
StarcoderdataPython
8432
<gh_stars>0 """ Copyright 2017-2018 yhenon (https://github.com/yhenon/) Copyright 2017-2018 Fizyr (https://fizyr.com) 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/licen...
StarcoderdataPython
3397804
# Symbol symbol_out = open('random6.txt','w') symbol = '!@#$%^&*()-+{}|:"<>?[]\;\',./' line_length = 20 text_length = 20000 output = '' index = 0 for i in range(text_length) : for j in range(line_length) : index %= len(symbol) output += symbol[index] index += 1 output += ...
StarcoderdataPython
1610010
<filename>murano/dsl/constants.py<gh_stars>1-10 # Copyright (c) 2014 Mirantis, 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/LICE...
StarcoderdataPython
1603058
from django.db.models import Value, F, TextField from django.db.models.functions import Concat from sphinxql import indexes, fields from .models import Document class DocumentIndex(indexes.Index): name = fields.Text(Concat(F('type__name'), Value(' '), F('number'), output_field=TextF...
StarcoderdataPython
1635849
import random randNum = random.randint(1, 9) while True: guess = int(input("Guess the number (1~9) ")) if guess < randNum: print("Your guessed is too low.") elif guess > randNum: print("Your guessed is too high.") else: print("You've guessed it right!") break # print(str...
StarcoderdataPython
1606524
<filename>main.py<gh_stars>0 print("git is my vcs of choice") # its wow!!
StarcoderdataPython
165235
<reponame>OrangutanGaming/Nexus-Stats-py<filename>nexus_stats/API.py import requests from nexus_stats.profile import Profile from nexus_stats.exceptions import * class Requester(): """Represents a connection to the API. This class is used to get data from the API and return useful information. A fe...
StarcoderdataPython
23953
<reponame>maralla/validator.vim # -*- coding: utf-8 -*- from validator import Validator class VimVint(Validator): __filetype__ = 'vim' checker = 'vint' args = '-w --no-color' regex = r""" .+?: (?P<lnum>\d+): (?P<col>\d+): \s(?P<text>.+)"""
StarcoderdataPython
3256954
from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * from fe import * from upload import * from login import * from pathlib import Path import sys, os, sqlite3, datetime from shutil import rmtree from apscheduler.schedulers.qt import QtScheduler import datetime class MainApp(QMainWind...
StarcoderdataPython
3327113
# {'posCelula':posCelula, 'dimX':quantX, 'dimY':quantY} #regras: # quaisquer celulas com menos de 2 vizinhos, morre OK # quaisquer celulas com 2 ou 3 vizinhos vive na proxima geração # quaisquer celulas com mais de 3 vizinhos, morre OK # quaisquer casas com 3 vizinhos vivos, torna-se viva na próxima geração ...
StarcoderdataPython
1693261
<gh_stars>0 #!/usr/bin/python3 """ Library for Casambi Cloud api. Request api_key at: https://developer.casambi.com/ """ import uuid import json import logging import datetime import socket from pprint import pformat from typing import Tuple from colorsys import rgb_to_hsv import requests import websocket _LOGGER = ...
StarcoderdataPython
1708005
import cv2 import numpy import math from .cluster import Clusters, Cluster CV_HARRIS_CORNER_THRESHOLD = 10e-03 MIN_CORNER_CLUSTER = 1 def init_harris_corners_and_cluster(monochrome_pil_img, polar_side_maximums, polar_side_minimums, origin): harris_img = cv2.cornerHarris(numpy.array(monochrome_pil_img), 3, 3, 0.04...
StarcoderdataPython
1643327
"""ShuffleNet (https://arxiv.org/abs/1707.01083)""" import collections import torch from .model import Model from .modules import Add, Conv2dAct, ChannelShuffle, Conv2dBN class ShuffleNet(Model): FIRST_STAGE_CHANNELS = {1: 144, 2: 200, 3: 240, 4: 272, 8: 384} class BasicBlock(torch.nn.Module): def __...
StarcoderdataPython
161878
<filename>snoop/data/management/commands/runworkers.py """Entrypoint for worker process. Starts up a variable number of worker processes with Celery, depending on settings and available CPU count. """ import os import logging import subprocess from django.conf import settings from django.core.management.base import ...
StarcoderdataPython
1705583
import tensorflow as tf from utils import RNN # one byte input, 256 possiblities for 1 hot encoding SIZE_IN = 8 SEQ_LEN = 10 BATCH_SIZE = 10 cell = RNN(128, (SIZE_IN, 8,), (SIZE_IN,8,)) out_state, logits = Y_ = tf.placeholder(tf.float32, shape=(None,SIZE_IN,8,), name="Y_") cost = tf.nn.softmax_cross_entropy_with_...
StarcoderdataPython
1723593
# coding: utf-8 """ Trakerr Client API Get your application events and errors to Trakerr via the *Trakerr API*. 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://...
StarcoderdataPython
4807230
<gh_stars>0 from ryanair.ryanair import Ryanair from ryanair.Dates import departuredates, returndates
StarcoderdataPython
3295153
import unittest import torch import numpy as np import numpy.testing as npt from torch_points_kernels import grouping_operation class TestGroup(unittest.TestCase): # input: points(b, c, n) idx(b, npoints, nsample) # output: out(b, c, npoints, nsample) def test_simple(self): features = torch.tenso...
StarcoderdataPython
3238555
<reponame>vahtras/util import numpy class BlockDiagonalMatrix: """ Blocked matrix class based on lists of full matrices """ def __init__(self, nrow, ncol): """ Constructur of the class.""" assert len(nrow) == len(ncol) from . import full self.nblocks = len(nrow) ...
StarcoderdataPython
72506
# -*- coding: utf8 -*- # # Copyright (c) 2006-2016 <NAME> # Copyright (c) 2014 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation t...
StarcoderdataPython
3222798
rom = input() dic = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} res = 0 tmp = pre = dic[rom[0]] for cur in rom[1:]: if dic[cur] == pre: tmp += dic[cur] elif dic[cur] > pre: tmp = dic[cur] - tmp elif dic[cur] < pre: res += tmp tmp = dic[cur] pre = dic[cur] r...
StarcoderdataPython
140435
"""Simple demo primarily for verifying the development environment.""" from gears import core from gears import draw def main(): node = draw.primitives.Triangle((200, 200), (100, 400)) node = draw.transforms.Translation(node, 300, 200) # also we should try to see if triangle works when we # put the ve...
StarcoderdataPython
4841971
<gh_stars>0 import pkgutil import os, sys import os.path import glob import roadrunner def getData(resource): """ get the contents of a testing resource file. """ return pkgutil.get_data(__name__, resource).decode("utf8") def abspath(resource): # current dir of package d = os.path.dirname(__...
StarcoderdataPython
1701462
#! python3 import sys, PyQt5 from PyQt5.QtWidgets import QMainWindow, QAction, QMenu, QApplication class Example(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): menubar = self.menuBar() fileMenu = menubar.addMenu('File')...
StarcoderdataPython
1757872
# Copyright (c) 2020, <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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
StarcoderdataPython
8657
#! /usr/bin/env python import rospy from nav_msgs.msg import Odometry class OdomTopicReader(object): def __init__(self, topic_name = '/odom'): self._topic_name = topic_name self._sub = rospy.Subscriber(self._topic_name, Odometry, self.topic_callback) self._odomdata = Odometry() def to...
StarcoderdataPython
4839274
"""Support for the GIOS service.""" from homeassistant.components.air_quality import ( ATTR_CO, ATTR_NO2, ATTR_OZONE, ATTR_PM_2_5, ATTR_PM_10, ATTR_SO2, AirQualityEntity, ) from homeassistant.const import CONF_NAME from .const import ATTR_STATION, DATA_CLIENT, DEFAULT_SCAN_INTERVAL, DOMAIN,...
StarcoderdataPython
4825641
# encoding: utf-8 ''' @author: <NAME> @contact: <EMAIL> @software: nef @file: app_recon_full.py @date: 5/13/2019 @desc: ''' import click import srfnef as nef import os import pypandoc import tensorflow as tf @click.command() @click.argument('json_path', type = click.Path(exists = True)) @click.option('--outdir', '-o'...
StarcoderdataPython
3300260
<gh_stars>0 def network_connections(data): return [ { 'origin': data['vendorInformation']['provider'], 'related': { 'type': 'domain', 'value': connection['destinationDomain'] }, 'relation': 'Connected_To', 'source': ...
StarcoderdataPython
3306585
import numpy as np from enum import Enum from random import randint MAX_GENERATION = 1000 POPULATION_SIZE = 20 CHROMOSOME_LENGTH = 20 NUMBER_OF_SELECTED_CHROMOSOME = 3 INCREMENT_RANGE_FOR_CHROMOSOME_LENGTH = 50 INCREMENT_SIZE_FOR_CHROMOSOME_LENGTH = 5 goal = np.array([[1, 2, 3], [8, 9, 4], [7, 6, 5]]) initial = np.a...
StarcoderdataPython
180640
<reponame>Zhenye-Na/leetcode # # @lc app=leetcode id=25 lang=python3 # # [25] Reverse Nodes in k-Group # # https://leetcode.com/problems/reverse-nodes-in-k-group/description/ # # algorithms # Hard (46.35%) # Likes: 4377 # Dislikes: 423 # Total Accepted: 383.3K # Total Submissions: 813.3K # Testcase Example: '[1,...
StarcoderdataPython
1665996
<reponame>Hardikris/moodlepy<filename>moodle/core/webservice/advanced_feature.py from moodle.attr import dataclass @dataclass class AdvancedFeatures: name: str value: int def __str__(self) -> str: return self.name
StarcoderdataPython
3383984
<filename>test/tests/polymorphism_small.py class Union(object): def __init__(self, subs): self.subs = subs def score(self): t = 0 for s in self.subs: t += s.score() t /= len(self.subs) ** 2.0 return t class Simple(object): def score(self): return...
StarcoderdataPython
6933
<reponame>mklew/quickstart-data-lake-qubole<filename>assets/utils/config.py from configparser import ConfigParser CONFIG_INT_KEYS = { 'hadoop_max_nodes_count', 'hadoop_ebs_volumes_count', 'hadoop_ebs_volume_size', 'spark_max_nodes_count', 'spark_ebs_volumes_count', 'spark_ebs_volume_size' } d...
StarcoderdataPython
3330811
#!/usr/bin/env python #from distutils.core import setup import re, uuid from setuptools import setup, find_packages from pip.req import parse_requirements install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1()) reqs = [str(req.req) for req in install_reqs] setup(name="GeoTweet", version="0.1...
StarcoderdataPython
178028
# --- # jupyter: # jupytext: # cell_metadata_filter: ExecuteTime # formats: ipynb,py # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.3.0 # kernelspec: # display_name: Python 3 # language: python # name: python...
StarcoderdataPython
3378371
import argparse import pandas as pd import numpy as np import re import nltk from sklearn.preprocessing import LabelEncoder from sklearn import utils from ..utils import serialize, deserialize from .tokenization import tokenize_articles, nan_to_str, convert_tokens_to_int, get_words_freq from gensim.models.doc2vec im...
StarcoderdataPython
126153
<reponame>ralcabes/EventManager<filename>eventmanager/tasks/urls.py<gh_stars>1-10 from . import views from django.conf.urls import url from django.contrib.auth import views as auth_views from django.urls import path urlpatterns = [ path( 'events/<slug:slug>/task/<task>/delete/', views.delete_task...
StarcoderdataPython
58590
<reponame>KevinKnott/Coding-Review # Search in Rotated Sorted Array: https://leetcode.com/problems/search-in-rotated-sorted-array/ # There is an integer array nums sorted in ascending order (with distinct values). # Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.leng...
StarcoderdataPython
1774609
from functools import cached_property from typing import Union from wtforms import StringField from app.forms.field_handlers.field_handler import FieldHandler from app.forms.validators import MobileNumberCheck, ResponseRequired MobileNumberValidatorTypes = list[Union[ResponseRequired, MobileNumberCheck]] class Mob...
StarcoderdataPython
3358819
from ._base import Base from loguru import logger from os import path import subprocess, os, platform class Edit(Base): """Edit. Opens the default editor (run `echo $EDITOR`) to edit the package file. Usage: gitget edit [global options] Examples: gitget edit """ def run(self): ...
StarcoderdataPython
37679
import requests import json from datetime import datetime headers = {"Content-type": "application/json", "Accept": "text/plain"} def addUser(): url = "http://10.194.223.134:5000/add_user" data = {"username": "test_user"} requests.post(url, data=json.dumps(data), headers=headers) def addMessage(): url...
StarcoderdataPython
1679738
<reponame>bquirin/-Rightmove-webscraper import requests from bs4 import BeautifulSoup import csv def get_page(url): response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") if not response.ok: print(f"Server responded with {response.status_code}") return soup def get_d...
StarcoderdataPython
3258356
<filename>threeML/utils/string_utils.py def dash_separated_string_to_tuple(arg): """ turn a dash separated string into a tuple :param arg: a dash separated string "a-b" :return: (a,b) """ return arg.replace(" ", "").split("-")
StarcoderdataPython
1693909
<reponame>eventable/CalendarServer<filename>txdav/common/datastore/file.py # -*- test-case-name: txdav.caldav.datastore.test.test_file -*- ## # Copyright (c) 2010-2015 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance wit...
StarcoderdataPython
1633182
<filename>2020/python/day2.py import sys import common def get_filename(): filename = sys.argv[0] filename = filename.split("/")[-1] filename = filename.split(".")[0] return filename data = common.get_file_contents("data/{}_input.txt".format(get_filename())) def check_password(line): # break ou...
StarcoderdataPython
153716
<gh_stars>1-10 # Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from libs.structured_object import StructuredObject class IntRange(StructuredObject): """Represents a generic integer range to include an ...
StarcoderdataPython
1743723
<filename>demo/tests/unit/mock.py from uuid import uuid4 class MockContext(object): def __init__(self, function_name): self.function_name = function_name self.function_version = "v$LATEST" self.memory_limit_in_mb = 512 self.invoked_function_arn = f"arn:aws:lambda:us-east-1:ACCOUNT:...
StarcoderdataPython
3215935
# encoding: utf-8 import json import logging import ckan.plugins as p try: # CKAN 2.7 and later from ckan.common import config except ImportError: # CKAN 2.6 and earlier from pylons import config log = logging.getLogger(__name__) ignore_empty = p.toolkit.get_validator('ignore_empty') DEFAULT_AGS_FO...
StarcoderdataPython
3332784
<reponame>AlphaMycelium/pathfinder.vim from heapdict import heapdict from pathfinder.server.motions.find import FindMotionGenerator from pathfinder.server.motions.search import SearchMotionGenerator from pathfinder.server.motions.simple import SimpleMotionGenerator from pathfinder.server.node import Node class Dijks...
StarcoderdataPython
4837782
import pytest import numpy as np import torch import model import test @pytest.fixture(params=[4096, 4096*10]) def nb_timesteps(request): return int(request.param) @pytest.fixture(params=[1, 2, 3]) def nb_channels(request): return request.param @pytest.fixture(params=[1, 2, 16]) def nb_samples(request): ...
StarcoderdataPython
1646153
<filename>Game/__init__.py import Game.main import Game.bird import Game.utils __all__ = ( main.__all__, bird.__all__, utils.__all__, )
StarcoderdataPython
24626
from django.views.generic import ListView, CreateView, UpdateView from django.utils.decorators import method_decorator from django.contrib.admin.views.decorators import staff_member_required from django.shortcuts import get_object_or_404, redirect, reverse from django.urls import reverse_lazy from django.contrib import...
StarcoderdataPython
1777524
<gh_stars>1-10 import os import pybind11 import subprocess import sys from setuptools import setup, Extension from setuptools.command.build_ext import build_ext with open("parametric_plasma_source/__init__.py", "r") as f: for line in f.readlines(): if "__version__" in line: version = line.spl...
StarcoderdataPython
3390772
import os from flask_restful import Resource, reqparse script_dir = os.path.dirname(__file__) parser = reqparse.RequestParser() class ReviewsController(Resource): def post(self): parser.add_argument('text', type=str, required=True, help='Error when parsing review text') parser.add_argument('res...
StarcoderdataPython
1646126
<reponame>robtucker/pyspark-tooling # import pytest from pyspark_tooling import plan from tests import base # @pytest.mark.focus class TestPlanUtils(base.BaseTest): def test_parse_plan(self): with open("./tests/sample_plan.txt") as f: txt = f.read() res = plan.parse_plan(txt) ...
StarcoderdataPython
1665496
<filename>create_data.py import collections import tensorflow as tf from prepro_utils import preprocess_text, partial, encode_ids, encode_pieces import sentencepiece as spm SEG_ID_A = 0 SEG_ID_B = 1 SEG_ID_CLS = 2 SEG_ID_SEP = 3 SEG_ID_PAD = 4 special_symbols = { "<unk>": 0, "<s>": 1, "</s>": 2, "<cl...
StarcoderdataPython
1630183
<gh_stars>0 import pytest from text_emb.text_embedding import Fasttext, BOW, Tfidf from util import ProtestDataset_txtfts_2, Lighting import os import torchvision.transforms as transforms from easyocr.joint_model import Sentence_model from torch.utils.data import Dataset, DataLoader import torch from train.collate_fn i...
StarcoderdataPython
3270637
""" PROBLEM STATEMENT design a data structure known as a Least Recently Used (LRU) cache. An LRU cache is a type of cache in which we remove the least recently used entry when the cache memory reaches its limit. For the current problem, consider both get and set operations as an use operation. You...
StarcoderdataPython
1663915
<gh_stars>1-10 #INPUT PARAMETERS ***************************************************** import matplotlib.pyplot as plt import numpy as np import math import scipy from SSFM import SSFM_FD from numpy.fft import fftshift, ifftshift c = 299792.458 #%speed of ligth nm/ps #% Input Field Paramenters tfwhm...
StarcoderdataPython
1685109
<reponame>OuyangChao/Paddle<filename>python/paddle/fluid/tests/unittests/test_cross_entropy_loss.py<gh_stars>1-10 # Copyright (c) 2020 PaddlePaddle 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 m...
StarcoderdataPython
115524
import copy import torch from corgie import constants, exceptions from corgie.log import logger as corgie_logger from corgie.boundingcube import BoundingCube from corgie.layers.base import register_layer_type, BaseLayerType from corgie import helpers class VolumetricLayer(BaseLayerType): def __init__(self, data...
StarcoderdataPython
3280584
import sys import signal import crontab_jobs default_app_config = 'dataloaderinterface.apps.DataloaderinterfaceConfig' def on_dataloaderinterface_shutdown(*args): from django.conf import settings crontab_jobs.stop_jobs() sys.exit(0) signal.signal(signal.SIGINT, on_dataloaderinterface_shutdown) signal.s...
StarcoderdataPython
3217539
<reponame>base4sistemas/pyescpos-cli # -*- coding: utf-8 -*- # # escpostools/commands/cmd_test.py # # Copyright 2018 Base4 Sistemas Ltda ME # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #...
StarcoderdataPython
173585
<gh_stars>1-10 # -*- coding: utf-8 -*- """ updater handlers movie poster module. """ from charma.updater.decorators import updater from charma.updater.enumerations import UpdaterCategoryEnum from charma.updater.handlers.base import UpdaterBase from charma.updater.handlers.mixin import ImageFetcherMixin class MoviePo...
StarcoderdataPython
1661393
<reponame>chanzuckerberg/aspen import json import requests from botocore.client import ClientError from aspen.database.models import CanSee, DataType from aspen.test_infra.models.phylo_tree import phylorun_factory, phylotree_factory from aspen.test_infra.models.sample import sample_factory from aspen.test_infra.model...
StarcoderdataPython
1710948
<reponame>FelixSchwarz/pycerberus # -*- coding: UTF-8 -*- # This file is a part of pycerberus. # The source code contained in this file is licensed under the MIT license. # See LICENSE.txt in the main project directory, for more information. # SPDX-License-Identifier: MIT from __future__ import absolute_import, print_...
StarcoderdataPython
1764013
<reponame>thomassutter/MoPoE<filename>celeba/flags.py import argparse from utils.BaseFlags import parser as parser # DATASET NAME parser.add_argument('--dataset', type=str, default='CelebA', help="name of the dataset") # add arguments parser.add_argument('--style_img_dim', type=int, default=32, help="dimension of va...
StarcoderdataPython
4801993
#-*- coding: utf-8 -*- from django.contrib import admin class PrimitivePermissionAwareModelAdmin(admin.ModelAdmin): def has_add_permission(self, request): # we don't have a "add" permission... but all adding is handled # by special methods that go around these permissions anyway # TODO: re...
StarcoderdataPython
120222
# -*- coding: utf-8 -*- """ Routes for the restfulapi addon. """ from framework.routing import Rule, json_renderer from . import views widget_routes = { 'rules': [ Rule( [ '/project/<pid>/restfulapi/download/' ], 'post', views.restfulapi_dow...
StarcoderdataPython
1688550
# -*- coding: utf-8 -*- """ Adagrad learning algorithm. For a nice explanation of the algorithm, see: http://sebastianruder.com/optimizing-gradient-descent/index.html#adagrad Adagrad [1] is an algorithm for gradient-based optimization that adapts the learning rate to the parameters, performing larger updates for infr...
StarcoderdataPython
3223434
<reponame>daadaada/triton<filename>python/triton/ops/blocksparse/matmul.py import triton import triton._C.libtriton as libtriton import torch import os import math src = triton.read(os.path.join(os.path.dirname(__file__), 'matmul.c')) ############## # MAIN API # ############## class _matmul(torch.autograd.Function)...
StarcoderdataPython
1776613
# -*- coding: utf-8 -*- ############################################################################### # Author: (C) 2012 <NAME> # Module: apps # Description: Django project applications module ###############################################################################
StarcoderdataPython
1730598
catlog = [ "coordinate_tol", "distance_tol", "angle2_tol", "angle_tol", "area_tol", "setting_tol", ]
StarcoderdataPython
120282
import asyncio import os import textwrap import urllib from typing import Tuple import caproto.server from .archstats import Archstats SUPPORTED_DATABASE_BACKENDS = {'elastic', } def get_archiver_url() -> str: """Get the archiver appliance interface URL from the environment.""" archiver_url = os.environ.ge...
StarcoderdataPython
3200725
import luigi as luigi import pandas as pd import numpy as np from visualization_tasks.PlotColumnEqualsData import PlotColumnEqualsData from visualization_tasks.Visualizer import Visualizer from data_tasks.MergeRetroSheetData import MergeRetroSheetData class GroupBy(luigi.Task): year = luigi.YearParameter() co...
StarcoderdataPython
3270472
<reponame>CRaNkXD/PyMoneyOrga import unittest import time from timeit import default_timer as timer import timeit from PyMoneyOrga.database.database_sqlite import DatabaseSqlite class TestDatabaseSqlite(unittest.TestCase): def setUp(self): self.database = DatabaseSqlite(url="sqlite:///pymoneyorga.sqlite.t...
StarcoderdataPython
111272
<gh_stars>10-100 import dash_html_components as html import dash_core_components as dcc import dash_bootstrap_components as dbc from plotly.subplots import make_subplots class blocktimeViewClass: def getBlocktimeContent(self, data, bgImage): content = [dbc.Modal([dbc.ModalHeader("Info Block Time"), ...
StarcoderdataPython
3244357
<filename>giggleliu/tba/lattice/fs.py #!/usr/bin/python ''' Fermi surface related utilities. ''' from numpy import * from numpy.linalg import norm from matplotlib.pyplot import * from path import path_k,KPath from utils import bisect __all__=['FermiPiece','FermiSurface','FSHandler'] class FermiPiece(KPath): ''' ...
StarcoderdataPython
1733465
<filename>data/train/python/ded893a797f56ef047775641755622fb7a2aa591produce_auth.py<gh_stars>10-100 #!/usr/bin/env python from Broker.Messages import Message, Publish, Authentication from Broker.Transport import TCP, UDP, SSL from Broker.Codecs import Protobuf as Codec #auto codec selection (thrift or protobuf if thri...
StarcoderdataPython
183084
import json import argparse import string import calendar import re from datetime import date def remove_punctuation(text): exclude = set(string.punctuation) return ''.join(ch for ch in text if ch not in exclude) def cleanup_documents(documents): dashCharacters = ["-", "\u00ad", "\u2010", "\u2011", "\u2012", "\u20...
StarcoderdataPython
1689270
"""Copyright © 2020-present, Swisscom (Schweiz) AG. All rights reserved. Loss Class for all the losses of the MAMO framework. Typical usage example: foo = Loss() bar = foo.compute_loss() """ from abc import ABC, abstractmethod class Loss(ABC): """ Loss class that will be specific for models / datasets ...
StarcoderdataPython
1666658
<filename>gentrl/decoder.py #import torch #import torch.nn as nn #import torch.nn.functional as F import tensorflow as tf from tensorflow.keras import layers from gentrl.tokenizer import get_vocab_size, encode, decode class DilConvDecoder(layers.Layer): ''' Class for autoregressive model that works in WaveNe...
StarcoderdataPython
3354975
<gh_stars>10-100 import torch import torch.nn as nn import math device = 'cuda' if torch.cuda.is_available() else 'cpu' class DNN(nn.Module): """Deep Neural Network""" def __init__(self, input_size, hidden_size, output_size): super(DNN, self).__init__() self.main = nn.Sequentia...
StarcoderdataPython
3220745
#!/usr/bin/env python3 """ Copyright 2017 Brocade Communications Systems, 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 also obtain a copy of the License at http://www.apache.org/licenses/LICENSE...
StarcoderdataPython
3379021
<gh_stars>0 #!/usr/bin/env python import os from setuptools import setup from marktime import version as module_version readme_path = os.path.join(os.path.dirname(__file__), 'README.rst') setup( name='marktime', version=module_version, py_modules=['marktime'], description='Python timer module for h...
StarcoderdataPython
1692545
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # PNA Aggregators ------------------------------------------------------------------------------ EPS = 1e-5 def aggregate_mean(h): return torch.mean(h, dim=1) def aggregate_max(h): return torch.max(h, dim=1)[0] def agg...
StarcoderdataPython
132910
<reponame>18F/federalist-garden-build-py import os from invoke import MockContext, Result from tasks import clone_repo, push_repo_remote class TestCloneRepo(): def test_it_is_callable(self): os.environ['GITHUB_TOKEN'] = 'fake_token' ctx = MockContext(run=Result('git clone result')) clone...
StarcoderdataPython
3329578
''' script que aprensenta o quanto você pode comprar com base na sua quantia atual ''' real = float(input('Dinheiro Atual na Carteira? R$')) dolar = real / 5.51 euro = real / 6.37 libra = real / 7.53 franco = real / 5.97 print(f'você tem R${real:.2f}') print(f'pode comprar até US${dolar:.2f}') print(f'pode comprar ...
StarcoderdataPython