id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1787742
from challenges.data_structure.stacks_and_queues.stacks_and_queues import * import pytest import unittest ''' Stack tests for ''' def test_push(stack_test): excpected = "three\ntwo\none" actual = f"{stack_test}" assert excpected == actual def test_push_to_empty(): stack = Stack() stack.push("one...
StarcoderdataPython
60900
<filename>board/widgets.py from rakmai.widgets import ( SummernoteBs4Widget, SummernoteLiteWidget ) class MessageSummernoteBs4Widget(SummernoteBs4Widget): class Media: js = ( 'js/board/message-summernote-ajax.js', ) class MessageAdminSummernoteLiteWidget(SummernoteLiteWidget): ...
StarcoderdataPython
4825097
from NERTranserLearning.Experiment import Experiment class ExperimentTransferTddTraining(Experiment): """ Contains the configurations of the transfer learning training on various data-sets for both Elmo and naive embeddings with TDD output layer. It's crucial the training will run in a sequential ord...
StarcoderdataPython
1616432
#------------------------------------------------------------------------------- # Name: module2 # Purpose: # # Author: user # # Created: 28/03/2019 # Copyright: (c) user 2019 # Licence: <your licence> #------------------------------------------------------------------------------- num...
StarcoderdataPython
1641120
<filename>examples/plot_interpolate_bad_channels.py<gh_stars>1-10 """ ================================================ Interpolate bad channels using spherical splines ================================================ This example shows how to interpolate bad EEG channels using spherical splines as described in [1]. R...
StarcoderdataPython
114612
# -*- coding: utf-8 -*- """コントローラ 本ライブラリにおけるコントローラとは人間に代わってアクション選択を行うプログラムを指す。 """ import random class Randomizer(object): """選択可能なアクションからランダムに選択を行うコントローラ """ def __init__(self, params): """初期化 @param params: dict パラメータ 'actions': 選択可能なアクションの数 'seed': 乱数シード ...
StarcoderdataPython
1748807
import os import datetime # change your parent dir accordingly try: directory = "ExDirFiles" parent_dir = "E:/GitHub/1) Git_Tutorials_Repo_Projects/core-python/Core_Python/" path = os.path.join(parent_dir,directory) ''' mode is set to '0o666' which allowed both read and write functionality for the ...
StarcoderdataPython
3245055
# -*- coding: utf-8 -*- """ Solution to Project Euler problem 346 Author: <NAME> https://github.com/jaimeliew1/Project_Euler_Solutions """ ''' x = 1111_2 is a 4 digit number in base 2 consisting of only ones. x = 2^0 + 2^1 + 2^2 + 2^3 = 15 y = 111...111_b is an n digit number in base b consisting of only ones. y = b^...
StarcoderdataPython
3302286
<filename>python/flowdec/__init__.py import os.path as osp pkg_dir = osp.abspath(osp.dirname(__file__)) data_dir = osp.normpath(osp.join(pkg_dir, 'datasets')) tf_graph_dir = osp.normpath(osp.join(pkg_dir, '../../tensorflow'))
StarcoderdataPython
1743772
<filename>commands/cmdsets/standard.py """ Basic starting cmdsets for characters. Each of these cmdsets attempts to represent some aspect of how characters function, so that different conditions on characters can extend/modify/remove functionality from them without explicitly calling individual commands. """ import tr...
StarcoderdataPython
1611903
<reponame>Christian-B/my_spinnaker from collections import namedtuple import time from typing import NamedTuple class Foo(object): __slots__ = ("alpha", "beta", "gamma") def __init__(self, alpha, beta, gamma): self.alpha = alpha self.beta = beta self.gamma = gamma Bar = namedtuple('...
StarcoderdataPython
169056
from ctypes import util from typing import List from ._augment import Augment from ._augment_groups import AugmentGroups from effect import * from effect import EffectTypes as ET from util import many_effs_with_same_amount GROUP = AugmentGroups.TRIA CONFLICT = (GROUP,) augments: List[Augment] = [] _primary_names =...
StarcoderdataPython
3300184
''' You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Note: You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. Example 1: Given input matrix = [ [1,2,3], [4,...
StarcoderdataPython
1638860
<filename>visualizer/visualizer.py # TODO 1. Implement parent visualizer class # TODO 2. Integrate to GUI import cv2 import numpy as np import re import enum from jcr.rnn import JcrGRU from jcr.trainer import load_checkpoint from jcr.evaluator import evaluate_frame from utils.misc import get_folders_and_files from ut...
StarcoderdataPython
1783661
""" Install Module """ # Django from django.core.management import execute_from_command_line # local Django from app.modules.util.helpers import Helpers from app.modules.entity.option_entity import Option_Entity from app.modules.entity.user_entity import User_Entity class Install(): __option_entity = None ...
StarcoderdataPython
1786085
desc = "Windows based eth0 interface file template for private cloud" data = """@echo off echo ############################################################################## echo # # echo # FIRST BOOT SETUP ...
StarcoderdataPython
3279990
<reponame>askprash/pyCycle import sys import openmdao.api as om import pycycle.api as pyc class WetTurbojet(pyc.Cycle): def initialize(self): self.options.declare('design', default=True, desc='Switch between on-design and off-design calculation.') def setup(self): ...
StarcoderdataPython
1688238
<gh_stars>0 from rest_framework.viewsets import ModelViewSet from api.serializers.application_form import ApplicationFormSerializer, \ ApplicationFormCreateSerializer from api.models.go_electric_rebate_application import GoElectricRebateApplication class ApplicationFormViewset(ModelViewSet): queryset = GoElec...
StarcoderdataPython
158214
<gh_stars>0 import random def random_mirror(data_numpy): # TODO random!!! if random.random() < 0.5: data_numpy[0] = - data_numpy[0] return data_numpy def augment(data_numpy): data_numpy = random_mirror(data_numpy) return data_numpy
StarcoderdataPython
57245
<reponame>ohpauleez/aupy #!/usr/bin/env python from __future__ import with_statement import time import sys from SocketServer import ThreadingMixIn, TCPServer, StreamRequestHandler #import pydysh from aupy2 import Utility class Master(object): def __init__(self): self.master_server = None super(Master, self).__i...
StarcoderdataPython
3376673
from neural.loss.naive_entropy import NaiveEntropy from neural.loss.mse import MeanSquaredError __all__ = ['NaiveEntropy', 'MeanSquaredError']
StarcoderdataPython
3385671
<reponame>mlin/sqlite_zstd_vfs #!/usr/bin/env python3 import sys import os import subprocess import contextlib import time import sqlite3 import argparse import json HERE = os.path.dirname(__file__) BUILD = os.path.abspath(os.path.join(HERE, "..", "build")) DB_URL = "https://github.com/mlin/sqlite_web_vfs/releases/do...
StarcoderdataPython
3377342
""" Tests for `kolibri` module. """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import unittest import mock import kolibri from kolibri.utils import version #: Because we don't want to call the original (decorated function), it uses #: caching...
StarcoderdataPython
3338085
from io import BytesIO from PIL import Image from django.core.files import File def get_image_file(name='test.png', ext='png', size=(50, 50), color=(256, 0, 0)): file_obj = BytesIO() image = Image.new("RGB", size=size, color=color) image.save(file_obj, ext) file_obj.seek(0) return File(file_obj, ...
StarcoderdataPython
163751
# Copyright (C)2016, International Business Machines Corporation # All rights reserved. import testutils as tt import shutil import sys def test_execution(name, python_command): '''Execute the test case''' #tt.assert_pass(err != 0, stdout, stderr) print "Execute scenario ContentRankingSample" tt.run_checked(['out...
StarcoderdataPython
23369
""" stanCode Breakout Project Adapted from <NAME>'s Breakout by <NAME>, <NAME>, <NAME>, and <NAME> File: breakoutgraphics.py Name: <NAME> ------------------------- This python file will create a class named BreakoutGraphics for the break out game. This class will contain the building block for creating that game. """...
StarcoderdataPython
3390005
<gh_stars>0 from .transaction import * from .investor import * from .ROICalculator import *
StarcoderdataPython
51617
import numpy as np from scipy.spatial.distance import pdist, squareform from scipy import exp from scipy.linalg import eigh def rbf_kernel_pca(X, gamma, n_components): """ RBF kernel PCA implementation. Parameters ------------ X: {NumPy ndarray}, shape = [n_samples, n_features] gamma: float ...
StarcoderdataPython
3291269
<filename>plexapi/media.py<gh_stars>0 # -*- coding: utf-8 -*- import xml from urllib.parse import quote_plus from plexapi import log, settings, utils from plexapi.base import PlexObject from plexapi.exceptions import BadRequest from plexapi.utils import cast @utils.registerPlexObject class Media(PlexObject): ""...
StarcoderdataPython
83027
""" Useful tools when working with Figura configs. """ import os from .settings import get_setting from .errors import ConfigError, ConfigParsingError, ConfigValueError from .path import to_figura_path from .container import ConfigContainer from .parser import ConfigParser from .importutils import is_impor...
StarcoderdataPython
3294326
<gh_stars>0 import pygame import random, math from entities.entity import Entity class Chaser(Entity): def __init__(self, x=0, y=0) -> None: super().__init__(x=x, y=y) self.mode = 'chase' self.mode_ticker = 0 self.switch_readiness = 100 self.goal = [0, 0] #to introd...
StarcoderdataPython
162957
<filename>test_plugins/BondingTest.py<gh_stars>0 import os import requests import tempfile import nanome from nanome.util import Logs import sys import time NAME = "<NAME>" DESCRIPTION = "Tests add_bonds." CATEGORY = "testing" HAS_ADVANCED_OPTIONS = False class BondingTest(nanome.PluginInstance): def start(self)...
StarcoderdataPython
139961
<reponame>timwoj/tlmbot import os import sqlite3 import sys import unittest from furl import furl from urllib.parse import urlparse,parse_qs from datetime import datetime def connect(path, read_only): full_path = path if read_only: full_path = f'file:{path}?mode=ro' conn = None try: ...
StarcoderdataPython
3226180
<filename>jni-build/jni/include/tensorflow/python/summary/summary.py # Copyright 2016 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...
StarcoderdataPython
1790306
<reponame>stay-whimsical/screamchess """ Code used to play various sounds, blink LEDs, and manage the media generally. """ import random import sound from chess.models import King, Rook, Bishop, Knight, Queen, Pawn sound.create_sound_bank() def test_sound(gamestate, events): try: sound.play_sound(_rand...
StarcoderdataPython
1739153
from pyramid.config import Configurator def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('measure', '/measure') config.add_route('measuredata', ...
StarcoderdataPython
1752340
<gh_stars>0 import pickle import re import sys import time import pytest from loguru import logger from .conftest import default_threading_excepthook class NotPicklable: def __getstate__(self): raise pickle.PicklingError("You shall not serialize me!") def __setstate__(self, state): pass c...
StarcoderdataPython
122811
<reponame>TristenSeth/campy import namesurferentry class NameSurferDatabase: """In this case, we'll oblige the OOP design and initialize from a filename.""" def __init__(self, filename): self._lookup = {} with open(filename) as f: for line in f: entry = namesurferen...
StarcoderdataPython
177540
import math import time #compute \pi using formula shown below: #\pi=\int_{0}^{1}\frac{4}{1+x^2}dx \sim =\frac{1}{n}\sum_{i=0}^{n-1}\frac{4}{1+(\frac{i+0.5}{n})^2} # def compute_pi(num_step): h=1.0/num_step s=0.0 for i in range(num_step): x=h*(i+0.5) s+=4.0/(1.0+x**2) return s*h def mai...
StarcoderdataPython
106886
# -*- coding: utf-8 -*- """ Created Nov 2018 @author: henss """ # import built in libarys import os from urllib.request import urlretrieve, urlopen # import 3rd party libarys from bs4 import BeautifulSoup # import local libarys # define classes and functions class Weblink(): """ Class ...
StarcoderdataPython
3374618
from django import forms from django.core.exceptions import FieldDoesNotExist from django.http import HttpResponseRedirect from django.views.generic.edit import FormMixin class AssignUserMixin(FormMixin): def form_valid(self, form: forms.ModelForm) -> HttpResponseRedirect: instance = form.save(commit=Fals...
StarcoderdataPython
4702
<reponame>JamesWang007/Open3D-PointNet<gh_stars>100-1000 #!/usr/bin/env python3 # Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma de # Barcelona (UAB). # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. """Download big fil...
StarcoderdataPython
3281619
<reponame>wqu-bom/pybufrkit """ pybufrkit.script ~~~~~~~~~~~~~~~~ """ from __future__ import absolute_import from __future__ import print_function import functools import ast from pybufrkit.dataquery import QueryResult from pybufrkit.query import BufrMessageQuerent __all__ = ['process_embedded_query_expr', 'ScriptRu...
StarcoderdataPython
1693039
""" Plugin for getting data from sheet and generate pdf from it """ import json import os import os.path import calendar import time from datetime import datetime from urllib.parse import urlencode import gspread from gspread.exceptions import SpreadsheetNotFound import requests from requests.auth import HTTPDigestAuth...
StarcoderdataPython
3377319
<gh_stars>0 from datetime import date from time import sleep idade = date.today().year - int(input('Em que ano você nasceu: ')) #idade == ano atual - ano de nascimento print('Analisando dados...') sleep(1) print('Determinando sua categoria...') sleep(2) if idade <= 9: print('Você tem {} anos \nCategoria: MIRIM'.for...
StarcoderdataPython
1774090
<reponame>rachelaus/capstone import pytest import json from scripts import update_snippets from capdb.models import Snippet @pytest.mark.django_db(databases=['capdb']) def test_map_numbers(case_factory, jurisdiction): [case_factory(jurisdiction=jurisdiction) for i in range(3)] update_snippets.update_map_number...
StarcoderdataPython
3282298
import mock import time from copy import deepcopy from unittest import TestCase from authlib.common.urls import url_encode from authlib.integrations.httpx_client import ( OAuthError, OAuth2Client, ) from tests.py3.utils import MockDispatch class OAuth2ClientTest(TestCase): def setUp(self): self.to...
StarcoderdataPython
1770482
import os import time import datetime import shutil from shared.logger_factory import LoggerFactory from shared.utils import read_data_from_json, write_data_to_json ROOT_DIR = os.environ['ROOT_DIR'] class DataManager: """ Class that collects the enhanced data from the scraping process, manages backups and compos...
StarcoderdataPython
188303
from bs4 import BeautifulSoup import requests import time import json import os.path import concurrent.futures from kivymd.uix.card import MDCardSwipe from kivy.properties import StringProperty from kivymd.utils import asynckivy #make this asynchronous class SwipeStockItem(MDCardSwipe): sCode=StringProperty() ...
StarcoderdataPython
3303482
import json from django.http import HttpResponse from datetime import datetime import json def hello_world(request): now = datetime.now().strftime("%b, %dth, %Y - %H, %M hrs") return HttpResponse(f'Oh, hi! current server time is {str(now)}') def hi(request): # numbers = (request.GET["numbers"].split(","))...
StarcoderdataPython
127869
import numpy as np import pandas as pd from scipy import interpolate from astropy.cosmology import LambdaCDM import Corrfunc from Corrfunc.utils import convert_rp_pi_counts_to_wp from Corrfunc.mocks.DDrppi_mocks import DDrppi_mocks from astropy.cosmology import LambdaCDM import time import plotter def main(): #...
StarcoderdataPython
1631126
<gh_stars>1-10 import numpy as np import am_sim as ams from utilities.dataset_interface import load_all_datasets # only executed in the main process, not in child processes if __name__ == '__main__': # setup numpy random seed for reproducibility np.random.seed(1) # initial value of model parameters ...
StarcoderdataPython
151860
<reponame>kingjr/jr-tools import numpy as np from numpy.testing import assert_equal, assert_array_almost_equal from .. import align_signals from .. import fast_mannwhitneyu def test_align_signal(): a = np.asarray(np.random.rand(1000) > .9, float) for pad in [10, 11, 0]: b = np.hstack((np.zeros(pad), a...
StarcoderdataPython
1794643
<reponame>jasmineyadeta/PythonPractice # function to find average marks def find_average_marks(marks): sum_of_marks = sum(marks) total_subjects = len(marks) average_mark = sum_of_marks/total_subjects return average_mark # function to calculate grade and return it def grading_scale(average_mark): if...
StarcoderdataPython
73994
import re def Remove_Duplicates(Test_string): Pattern = r"\b(\w+)(?:\W\1\b)+" return re.sub(Pattern, r"\1", Test_string, flags=re.IGNORECASE) Test_string1 = "Good bye bye world world" Test_string2 = "Ram went went to to his home" Test_string3 = "Hello hello world world" print(Remove_Duplicates(Te...
StarcoderdataPython
3264905
import os import json import yaml import logging import click import re from .project import Project from .plugin import PluginType, Plugin from .plugin.factory import plugin_factory from .config_service import ConfigService from .utils import setting_env class ProjectAddCustomService: def __init__(self, project...
StarcoderdataPython
1617256
import yaml class File: def __init__(self, url): self._url = url @property def yaml_dict(self): with open(self._url, 'r') as stream: try: config_dict = yaml.safe_load(stream) return config_dict except yaml.YAMLError as exc: ...
StarcoderdataPython
1768049
# # copyright (c) 2010 <NAME> <<EMAIL>> # from BuildSystem.AutoToolsBuildSystem import * from Package.PackageBase import * from Packager.TypePackager import * from Source.MultiSource import * class AutoToolsPackageBase(PackageBase, MultiSource, AutoToolsBuildSystem, TypePackager): """provides a base class for aut...
StarcoderdataPython
3310211
<reponame>Expert37/python_lesson_3 # кортежи - это тот же самый список, только не изменяемый # те же самые объекты, которые хранятся в списке. Если они будут храниться в кортеже, то доступ к ним будет гораздо быстрее и они будут занимать меньше памяти # кортежи задаются (). Доступ, срезы - всё как в списках. # Иниц...
StarcoderdataPython
1608142
class Solution: def removeStones(self, stones): """ :type stones: List[List[int]] :rtype: int """ parent = {} def find(x): if x != parent[x]: parent[x] = find(parent[x]) return parent[x] def union(x, y): pare...
StarcoderdataPython
72960
<filename>scripts/prepare_data_multi_process.py import redis import json import h5py import pickle import numpy as np import random import jieba import multiprocessing word2idx, idx2word ,allwords, corpus = None, None,{},[] DUMP_FILE = 'data/basic_data_700k_v2.pkl' check_sample_size = 10 TF_THRES = 5 DF_THRES = 2 ...
StarcoderdataPython
101416
<gh_stars>10-100 #!/usr/bin/env python3 import os import sys import time import numpy as np import simpleaudio as sa class Player: def __init__(self, volume: float = 0.3, mute_output: bool = False): if volume < 0 or volume > 1: raise ValueError("Volume must be a float between...
StarcoderdataPython
1759484
<reponame>AkasDutta/veros from veros.core import friction from veros.pyom_compat import get_random_state from test_base import compare_state TEST_SETTINGS = dict( nx=70, ny=60, nz=50, dt_tracer=3600, dt_mom=3600, enable_cyclic_x=True, enable_conserve_energy=True, enable_bottom_frictio...
StarcoderdataPython
36669
<gh_stars>0 # -*- coding: utf-8 -*- # FOGLAMP_BEGIN # See: http://foglamp.readthedocs.io/ # FOGLAMP_END """HTTP Listener handler for sensor readings""" import asyncio import copy import sys from aiohttp import web from foglamp.common import logger from foglamp.common.web import middleware from foglamp.plugins.commo...
StarcoderdataPython
1606685
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup try: from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup() except ImportError: # extract information from package.xml manually when catkin_pkg is unava...
StarcoderdataPython
1601623
"""XML Utilities""" import xml.etree.ElementTree as ET def quote(tag): """ Turn a namespace prefixed tag name into a Clark-notation qualified tag name for lxml. For example, ``qn('p:cSld')`` returns ``'{http://schemas.../main}cSld'``. Source: https://github.com/python-openxml/python-docx/ """...
StarcoderdataPython
3316886
<gh_stars>1-10 from flask import render_template, Blueprint, redirect from app.models import card from app.forms import card_form from flask_user import roles_accepted, login_required cards_blueprint = Blueprint('cards', __name__) @cards_blueprint.route('/') def index(): cards = card.query.all() return rende...
StarcoderdataPython
3253974
<reponame>sixhobbits/nps-sample-data import random from collections import Counter from datetime import datetime from datetime import timedelta # some NPS score weightings that lead to an NPS of around 70 BASE_WEIGHTS = [0.05, 0.045, 0.002, 0.002, 0.002, 0.01, 0.029, 0.05, 0.06, 0.3, 0.45] # all possible NPS...
StarcoderdataPython
1719788
try: file = open('eeee','r+') except Exception as e: print('There is no file named as eeee') response = input("do you want to create a eeee file?(y/n) ") if response == 'y': file = open('eeee','w') else: pass else: file.write('hahahaha') file.close()
StarcoderdataPython
134858
<gh_stars>0 #!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': s = input() the_letters = {} total = len(s) for character in s: if character in the_letters: continue else: the_letters[character] = s.count(character) frequencies = sor...
StarcoderdataPython
3328772
#!/usr/bin/env python3 # The Expat License # # Copyright (c) 2017, <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 the rights # to ...
StarcoderdataPython
151019
# coding=utf-8 # Copyright (c) 2016-2018, F5 Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
StarcoderdataPython
3203198
<gh_stars>10-100 # Copyright 2016 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
StarcoderdataPython
72040
"""Forward and back projector for PET data reconstruction""" __author__ = "<NAME>" __copyright__ = "Copyright 2018" #------------------------------------------------------------------------------ import numpy as np import sys import os import logging import petprj from niftypet.nipet.img import mmrimg from nif...
StarcoderdataPython
4824551
from .case import Case from .abstract import Point, Form from . import colors import numpy as np import shelve from pygame.locals import * class Painter: def __init__(self, *args, **kwargs): """Create a painter.""" self.paints = [Board(), Paint(*args, **kwargs)] self.paint_brush = PaintB...
StarcoderdataPython
4828025
<gh_stars>0 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader def get_device(): if torch.cuda.is_available(): device = torch.device('cuda:0') else: device = torch.device('cpu') # don't have GPU return devi...
StarcoderdataPython
103252
import os import numpy as np from data.dataset import VoxelizationDataset, DatasetPhase class S3DISDataset(VoxelizationDataset): category = ['wall', 'floor', 'beam', 'chair', 'sofa', 'table', 'door', 'window', 'bookcase', 'column', 'clutter', 'ceiling', 'board'] CLIP_SIZE = None CLIP_BOUND...
StarcoderdataPython
62590
from typing import Generator import pytest from fastapi.testclient import TestClient from app.main import app @pytest.fixture(scope="module") def test_data(): sample_data = {"user_handle": 1} return sample_data @pytest.fixture() def client() -> Generator: with TestClient(app) as _client: yield...
StarcoderdataPython
4840196
<gh_stars>10-100 #! /usr/bin/python3 from Parser import Parser from Commands import Commands from Data import Data from Code import Code from Resolver import Resolver from Configuration import Configuration from Generator import Generator from Operators import Operato...
StarcoderdataPython
74135
from .quantum_register import QuantumRegister from .classical_register import ClassicalRegister import qsy.gates as gates __version__ = '0.4.4'
StarcoderdataPython
3215572
from pdb import set_trace as breakpoint class Dog(): def __init__(self, name, age, housebroke): self.name = name self.age = age self.housebroke = housebroke def is_housebroke(self): if self.housebroke == True: print(f'{self.name} is housebroken!') else: ...
StarcoderdataPython
9407
# Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team licenses this file to you under the # Apache License, Version 2.0 (the "License"); you may not u...
StarcoderdataPython
3251288
<reponame>carlosparaciari/ArXivBot #!/usr/bin/env python import psycopg2 import os import yaml import sys # This script will create a new user and database, and will create the tables # needed for ArXivBot to work in this database. The tables are the following: # # 1. - Name : preferences # - Columns : (...
StarcoderdataPython
3371082
<reponame>domenicodigangi/GraphsData # Script to uniformly aggregate all streaming graphs data available into discrete time sequences of networks #%% Import packages import os import pandas as pd import networkx as nx import numpy as np #%% load all datasets all_df = [] load_direct = "./raw_data_files/" files = os.li...
StarcoderdataPython
88652
<gh_stars>0 from modules.lib.alarm_condition import AlarmCondition from modules.lib.alarm_condition_parser import parse_alarm_condition import json def alarm_condition_from_params(params, key): try: alarm_condition = params[key]['alarms'] if alarm_condition is None: return None ...
StarcoderdataPython
1686449
import torch import torch.optim from torch import nn from utils import * from model import * from load_data import trainloader, testloader def get_noise(n, size): ''' out (n, size, 1, 1) noise vector ''' return torch.randn(n, size, 1, 1).to(device) def weights_init(m): classname = m.__class__.__...
StarcoderdataPython
1646719
# -*- coding: utf-8 -*- """ PyThaiNLP package installation and data tools """ import os import subprocess import sys import pythainlp PYTHAINLP_DATA_DIR = "pythainlp-data" def install_package(package): """ Install package using pip Use with caution. User may not like their system to be installed wit...
StarcoderdataPython
1613855
<reponame>alemr214/curso-python-desde-cero<gh_stars>0 import sqlite3 conexion = sqlite3.connect("GestionProductos.db") miCursor = conexion.cursor() miCursor.execute(""" CREATE TABLE IF NOT EXISTS PRODUCTOS ( codigo_articulo VARCHAR(4) PRIMARY KEY, nombre_articulo VARCHAR(50), precio INTEGE...
StarcoderdataPython
3372503
from .generator import Generator from . import _version __version__ = _version.get_versions()['version']
StarcoderdataPython
143556
import os import io import json import trimesh import random import matplotlib.pyplot as plt import numpy as np import cv2 import torch def load_bop_meshes(model_path, obj_ids="all"): """ Returns: meshes: list[Trimesh] objID2clsID: dict, objID (original) --> i (0-indexed) """ # load m...
StarcoderdataPython
4833583
<gh_stars>100-1000 # -*- coding: utf-8 -*- import io import os from .specs import pipelines from .manager import execute_pipeline VERSION_FILE = os.path.join(os.path.dirname(__file__), 'VERSION') __version__ = io.open(VERSION_FILE, encoding='utf-8').readline().strip()
StarcoderdataPython
45187
<reponame>genestack/python-client #!python # -*- coding: utf-8 -*- from __future__ import print_function from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from future import standard_library standard_library.install_aliases() from builtins import input from...
StarcoderdataPython
1708014
# Generated by Django 3.1.2 on 2020-10-24 22:22 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ('cards', '0003_card_user'), ] operations = [ migrations.AlterField( ...
StarcoderdataPython
1660716
import unittest from main import tilingCost class TestTiles(unittest.TestCase): def test_Cost_of_tiles_1(self): self.assertEqual(1_700, tilingCost(4, 5, cost=25)) def test_Cost_of_tiles_2(self): self.assertEqual(2_100, tilingCost(3, 7, cost=40)) def test_Cost_of_tiles_3(self): self.assertEqual...
StarcoderdataPython
1697182
<reponame>chudur-budur/visualization<gh_stars>0 """scatter.py -- A customized scatter plotting module. This module provides a customized scatter plotting functions for high-dimensional Pareto-optimal fronts. It also provides different relevant parameters, tools and utilities. Copyright (C) 2016 C...
StarcoderdataPython
3375536
from array import array from random import random from math import sin import arcade import imgui from imflo.node import Node from imflo.pin import Input class MeterNode(Node): def __init__(self, page): super().__init__(page) self.values = array('f', [sin(x * 0.1) for x in range(100)]) se...
StarcoderdataPython
3245565
import vdomr as vd import spiketoolkit as st import spikeextractors as se from .unitwaveformswidget import UnitWaveformsWidget from .correlogramswidget import CorrelogramsWidget from .timeserieswidget import TimeseriesWidget class ButtonList(vd.Component): def __init__(self,data): vd.Component.__init__(sel...
StarcoderdataPython
1707449
# -*- coding: utf-8 -*- # Copyright (c) 2015, Dataent Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import os from six import iteritems import logging from werkzeug.wrappers import Request from werkzeug.local import LocalManager from werkzeug.exceptions...
StarcoderdataPython
8820
from typing import (Any, Union, Type) # noqa: F401 from ..keys.datatypes import ( LazyBackend, PublicKey, PrivateKey, Signature, ) from eth_keys.exceptions import ( ValidationError, ) from eth_keys.validation import ( validate_message_hash, ) # These must be aliased due to a scoping issue in...
StarcoderdataPython
1636553
import pathlib import tempfile from flask import Flask from flask_restful import Resource, Api, reqparse from werkzeug.datastructures import FileStorage from predict import predict app = Flask(__name__) api = Api(app) ALLOWED_EXTENSIONS = ['.jpeg'] class ClassifyImage(Resource): def post(self): """ ...
StarcoderdataPython