id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1726359
import numpy as np import glob import random import torch import torch.utils.data from analyzer.data.utils.data_raw import * from analyzer.data.utils.data_misc import * from analyzer.data.augmentation import Augmentor class PairDataset(): ''' This Dataloader will prepare sample that are pairs for feeding the c...
StarcoderdataPython
4806459
from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient class RegisterUserTestCase(TestCase): def setUp(self): self.data = {'username': 'apiuser', 'email': '<EMAIL>', 'password': '<PASSWORD>', 'password2': '<PASSWORD>'} ...
StarcoderdataPython
1723520
class Solution: # O(n) time | O(1) space - where n is the length of the input array def findMaxConsecutiveOnes(self, nums: List[int]) -> int: maxCount = currentMax = 0 for num in nums: if num == 1: currentMax += 1 else: maxCount = max(maxC...
StarcoderdataPython
70666
#! /usr/bin/env python # from distutils.core import setup from ginga.version import version import os def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "ginga", version = version, author = "<NAME>", author_email = "<EMAIL>", description = ("An as...
StarcoderdataPython
1799809
import datetime def date_now(): return datetime.datetime.now().strftime('%m月%d日') def statement_head(ws, cust_info, pur_comment=''): ws.merge_cells('C2:D2') ws.merge_cells('F2:G2') cust_title = cust_info.cust_location + cust_info.cust_name + pur_comment data_list = [['', '', '', cust_title, '发货单...
StarcoderdataPython
3386062
# Basic testing for numbers import cake INTEGER_TEST = 10 def TestBase(): num = cake.Number(INTEGER_TEST) print(num, num.value, num.type) assert num(10)(10) == 1000, "Chaining result for 10 * 10 * 10 didn't return 1000" print('Passed chaining test') assert num / 10 * 10 + 10 == 20, "Failed...
StarcoderdataPython
1610907
<gh_stars>1-10 """ Copyright: MAXON Computer GmbH Author: <NAME> Description: - Imports STP/STEP with custom settings. Class/method highlighted: - c4d.plugins.FindPlugin() - MSG_RETRIEVEPRIVATEDATA - c4d.documents.MergeDocument() Documentation links: - https://developers.maxon.net/docs/Cinema4DP...
StarcoderdataPython
3396256
import re from math import exp import random _error_threshold = 0.0001 class HMMException(Exception): def __init__(self, msg = ""): self.msg = msg def __str__(self): return self.msg _blank = re.compile("^\s*\n$") def _next_line(fp): """Return the next line of fp that is not either em...
StarcoderdataPython
58716
<filename>cve-manager/cve_manager/tests/test_callback/test_set_repo_callback.py<gh_stars>0 #!/usr/bin/python3 # ****************************************************************************** # Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved. # licensed under the Mulan PSL v2. # You can use th...
StarcoderdataPython
1769056
<gh_stars>0 import lightgbm as lgb import pandas as pd import argparse import numpy as np def get_input_data(start_idx, end_idx): df = pd.read_csv("winequality-white.csv", sep=";") predict_col = "quality" df = df.drop(predict_col, axis=1) return df.iloc[start_idx:(end_idx+1)] def predict(data): ...
StarcoderdataPython
3300455
import yaml import os from collections import defaultdict from cumulusci.tasks.salesforce import BaseSalesforceApiTask from cumulusci.core.utils import process_list_arg, process_bool_arg from cumulusci.core.exceptions import TaskOptionsError, CumulusCIException class SetTDTMHandlerStatus(BaseSalesforceApiTask): ...
StarcoderdataPython
1781541
import binascii from rex.exploit.shellcode import Shellcode class LinuxARMBinsh(Shellcode): # TODO: should be 'linux' once CLE can identify linux files supported_platforms = ["unix"] arches = ["ARMEL"] name = "binsh" asm = """ add r0, pc, #0xc mov r2, #0 push {r0, r2} mov r1, sp """ code = ...
StarcoderdataPython
3342139
def productSum(array, multiplier = 1): sum = 0 for item in array: if isinstance(item, int): sum += item #add to sum when int else: sum += productSum(item, multiplier+1) #recursive call and increment multiplier return sum * multiplier
StarcoderdataPython
1780096
<filename>notebooks/few-bit-backward/memory-usage-operation-only.py # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.11.0 # kernelspec: # display_name: Python 3 (ipykernel) # language: python #...
StarcoderdataPython
1650712
<reponame>vavalto/GenoSense<filename>GenoSense/app/src/utils/sandbox_bed.py<gh_stars>0 # from pybedtools import BedTool import numpy as np import os from functools import reduce # import timeit # from multiprocessing import Pool import pickle result_list = [] def log_result(result): # This is called whenever foo_p...
StarcoderdataPython
3211335
<gh_stars>0 tz_str = None sep = ' -- ' testFunctions = True import datetime as dt class time: def now(tz_str): tz_now = dt.datetime.now(tz_str) return tz_now def timestamp(): rightnow = time.now(tz_str) stamp = str(rightnow)# + ' // TZ: ' + str(tz_str) return stamp class logger: sep = ':' ...
StarcoderdataPython
42923
<reponame>Edlward/foc_esc<gh_stars>10-100 import math import constants class Simulator(object): def __init__ (self): self.bemfa = 0.0 self.bemfb = 0.0 self.va = 0.0 self.vb = 0.0 self.kp = constants.KP_EST_RPM self.ki = constants.KI_EST_RPM self.ls = 0.035 ...
StarcoderdataPython
40749
<filename>blog_project/routes/art_route.py from flask import request, session from models.models import Article, ArticleContent from models.result import ResultResp from services import art_services def insert_article(): try: params = request.json art_services.insert_article(Article(None, params['t...
StarcoderdataPython
1792896
from datetime import datetime import functools import os import time import sys from schedule import run_all # to import local fuctions sys.path.insert(0, '../tools') import schedule from extract.earnings import extract_earnings from extract.fundamentals import update_fundamental_dates, extract_fundamentals from ext...
StarcoderdataPython
140552
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. """ An example showing how to include context correlation information in logging telemetry. """ import os import logging from opentelemetry import trace from opentelemetry.sdk._logs import ( LogEmitterProvider, OTLPHa...
StarcoderdataPython
3263054
import typing from datetime import datetime from pyrunehistory.domain.models.account import Account from pyrunehistory.highscores import HighScores class Accounts: def __init__(self, client: 'pyrunehistory.client.Client'): self.client = client def get_accounts(self, runs_unchanged_min: int = None, ...
StarcoderdataPython
70185
summultiples = 0 for i in range(1000): if i % 3 == 0 or i % 5 == 0: summultiples += i print(summultiples)
StarcoderdataPython
3242737
import discord import os from data.keep_alive import keep_alive from discord.ext import commands client = commands.Bot(command_prefix = "#", case_insensitive=True) client.remove_command("help") @client.event async def on_member_join(ctx,member): await ctx.send( f'Hi {member.name}, welcome to cul-Ahem server') ...
StarcoderdataPython
1762233
<gh_stars>1-10 from platypus import NSGAII, Problem, Real from Library.DataClass import * from Library.RiskCalc import * def calc_total_value(universe: Universe, weights: [float]): total = 0 for i in range(universe.count): total += universe.universe_set[i].last_price * weights[i] return total cla...
StarcoderdataPython
1640454
import inspect from enum import Enum from typing import ( Any, AnyStr, ClassVar, Dict, List, Literal, Optional, Tuple, Type, Union, get_args, get_origin ) from typing_extensions import Annotated from ...errors import CommandSetupError from ...models import InteractionChannel, InteractionMember, InteractionUse...
StarcoderdataPython
180125
<reponame>betoesquivel/PyData29-DataAnalyticsWithAWSLambda<filename>numpy/version.py<gh_stars>10-100 # THIS FILE IS GENERATED FROM NUMPY SETUP.PY short_version = '1.10.4' version = '1.10.4' full_version = '1.10.4' git_revision = '<PASSWORD>' release = True if not release: version = full_version
StarcoderdataPython
96112
<reponame>rsdoherty/azure-sdk-for-python from .proxy_testcase_async import RecordedByProxyAsync __all__ = ["RecordedByProxyAsync"]
StarcoderdataPython
3200932
<gh_stars>0 #!/usr/bin/env python3 from random import shuffle import time import logging import pickle import numpy as np # ------------------------------------------------------------------------------ # Configuration # ------------------------------------------------------------------------------ INPUT_NEURONS = 768 ...
StarcoderdataPython
1609391
# -*- coding: utf-8 -*- """ Created on Tue Dec 17 14:28:30 2019 @author: Timothe """ #%% from HirisSeqReader import Foldersearch, QuickRegexp, Repair_HIRIS from termcolor import colored import sys import os import logging from datetime import datetime import tkinter as tk from tkinter import filedialog from distutil...
StarcoderdataPython
4842133
<reponame>albertz/music-player from PyObjCTools.TestSupport import * import Quartz try: unicode except NameError: unicode = str class TestCVPixelBufferIOSurface (TestCase): @min_os_level('10.6') def testConstants10_6(self): self.assertIsInstance(Quartz.kCVPixelBufferIOSurfaceOpenGLTextureCom...
StarcoderdataPython
1693395
from fics import FiniteInverseCategory as fic from networkx import MultiDiGraph import sys def Glob(n): Glob = MultiDiGraph() s_morphisms = [('X'+str(m+1),'X'+str(m),'s'+str(m)) for m in range(n)] t_morphisms = [('X'+str(m+1),'X'+str(m),'t'+str(m)) for m in range(n)] morphisms = s_morphisms + t_morphis...
StarcoderdataPython
1751976
import aioboto3 import datetime import aiohttp import attr from envs import env from jose import jwt, JWTError from .aws_srp import AWSSRP from .exceptions import TokenVerificationException from .userobj import UserObj from .groupobj import GroupObj from .utils import dict_to_cognito @attr.s class Cognito(object): ...
StarcoderdataPython
3252822
<filename>example/requirements/ifcopenshell/ifcopenshell/template.py ############################################################################### # # # This file is part of IfcOpenShell. # # ...
StarcoderdataPython
196408
# defines the database schema # import datetime import psycopg2 as pg from dotenv import load_dotenv import os load_dotenv() creds = { 'user': os.environ.get('USER'), 'password': os.environ.get('PASSWORD'), 'host': os.environ.get('HOST'), 'dbname': os.environ.get('DATABASE'), 'port': os.environ.get('PORT')...
StarcoderdataPython
1736709
<reponame>roybens/neuroGPU # -*- coding: utf-8 -*- """ Created on Wed Jun 19 10:30:07 2019 @author: bensr """ import pickle import matplotlib.pyplot as plt import neuron as nrn import os import subprocess import shutil import time from NeuroGPUFromPkl import run_params_with_pkl from deap import base, creator, tools, ...
StarcoderdataPython
1657056
import torch import copy import numpy as np from typing import Union, Tuple from codebook import Codebook from psf import PSF class ISTDeco: ''' ISTDECO - Deconvovles 1D or 2D spatial transcriptomic data Parameters ---------- Y : float Input image data of shape (rounds, channels, height, ...
StarcoderdataPython
75801
from typing import Optional, List, Callable, Tuple, Iterable from fedot.core.log import default_log, Log ConditionType = Callable[[], bool] ConditionEntryType = Tuple[ConditionType, Optional[str]] class GroupedCondition: """Represents sequence of ordinary conditions with logging. All composed conditions are...
StarcoderdataPython
1647053
# twitter sentiment analysis # (c) <NAME>, The Medusa's Cave Blog 2012 # Description: This file performs simple sentiment analysis on global twitter feeds # Later versions may improve on the sentiment analysis algorithm import os, sys, time; # import standard libraries from twython import Twython; ...
StarcoderdataPython
1771306
<reponame>manuelprogramming/OSA<filename>plugins/analyser/load_ref.py from dataclasses import dataclass import numpy as np from osa import factory from handlers.result import BaseResult from handlers.ref import load_ref_data @dataclass class LoadRef: """ Loads the saved reference data """ command: s...
StarcoderdataPython
1658245
<gh_stars>1-10 from __future__ import annotations import os from dataclasses import dataclass from dataclasses import field from typing import List from typing import Optional from typing import TYPE_CHECKING from typing import TypeVar from typing import Union import pydantic import cptk.constants import cptk.scrape...
StarcoderdataPython
3367419
<filename>src/kbqa/scripts/gen_linkings.py # -*- coding:utf-8 -*- """ Implementation of entity linking Goal: Entity/Type/Time linking based on n-grams. Note: all linking procedure ignore cases. """ import re import codecs import json import pickle import argparse from stanfordcorenlp import StanfordCoreNLP from src.kbq...
StarcoderdataPython
190928
import re #re.match方法 list = "abcdefghijklmn" m = re.match('abc',list) #print(m) print("match result: ", m.span()) print("start position:", m.start()) print("end position: ", m.end()) print() list1="Fat cats are smarter than dogs" m1 = re.match(r'(.*) are (.*?) dogs',list1) #print (m1) print('match whole sentence:'...
StarcoderdataPython
1655934
<gh_stars>0 import asyncio import logging import random from typing import Literal import discord from redbot.core import Config, bank, checks, commands from redbot.core.utils import menus log = logging.getLogger('red.jojo.collectables') class Collectables(commands.Cog): def __init__(self, bot): self.bo...
StarcoderdataPython
3381888
import komand from .schema import DeleteAnalysisInput, DeleteAnalysisOutput, Input, Output # Custom imports below class DeleteAnalysis(komand.Action): def __init__(self): super(self.__class__, self).__init__( name='delete_analysis', description='Delete an analysis', ...
StarcoderdataPython
41855
from django import forms from .models import FeedBackModel class FeedBackForms(forms.ModelForm): class Meta: model = FeedBackModel fields = ('name', 'last_name', 'subject', 'text')
StarcoderdataPython
1614383
# _________________________________________________________________________ # # WST: the Water Security Toolkit # Copyright (c) 2012 Sandia Corporation. # This software is distributed under the BSD License. # Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, # the U.S. Government retains cert...
StarcoderdataPython
3314408
<filename>processing/scripts/bdot_dl.py import argparse from datetime import datetime, timezone import urllib.request import urllib.error import shutil from os import path BASE_URL = 'https://integracja.gugik.gov.pl/PRG/pobierz.php?bdot10k&teryt=' def download_file(url: str, file_path: str): print(datetime.now(...
StarcoderdataPython
131745
<gh_stars>0 class Problem: def __init__(self, n, m): self.n = n self.m = m self.answer = [0 for _ in range(m)] self.used = [False for _ in range(n)] def printAnswer(self): for number in self.answer: print(number,end=' ') print() def makeAnswer(se...
StarcoderdataPython
3374987
<gh_stars>1-10 import threading import rospy from sensor_msgs.msg import JointState class AxesSubscriber: def __init__(self): self.lock = threading.Lock() self.last_msg_seq = -1 self.name = [] self.position = [] self.velocity = [] self.effort = [] self.thre...
StarcoderdataPython
1753715
<gh_stars>100-1000 import FWCore.ParameterSet.Config as cms #demo = cms.EDAnalyzer('L1TScalers' #) from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer l1tscalers = DQMEDAnalyzer('L1TScalersSCAL', #l1GtData = cms.InputTag("l1GtUnpack","","HLT"), #dqmFolder = cms.untracked.str...
StarcoderdataPython
3378510
from mycroft import MycroftSkill, intent_file_handler from . import reddit from typing import Any from pathlib import Path def get_data_type(data_type: str) -> Any: if data_type in ["video", "videos", "film", "films", "movie", "movies"]: return reddit.Reddit.DataTypes.VIDEO elif data_type in ["image", ...
StarcoderdataPython
3361586
<gh_stars>1-10 import argparse import logging import signal import sys from enum import Enum, unique from multiprocessing import Event from common.nlp import create_nlp_instance, SpacyPreprocessor from config.armchair_expert import ARMCHAIR_EXPERT_LOGLEVEL from config.ml import USE_GPU, STRUCTURE_MODEL_PATH, MARKOV_DB...
StarcoderdataPython
3244363
<reponame>jsam356/CAP2 import luigi from os.path import join, dirname from glob import glob import subprocess from ....pipeline.utils.cap_task import CapDbTask from ....pipeline.config import PipelineConfig from ....pipeline.utils.conda import CondaPackage GENOME_FASTA = join( dirname(__file__), 'genomes', ...
StarcoderdataPython
3246080
<reponame>yoosan/i3d-tensorflow """Utilities for building Inflated 3D ConvNets """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import collections from snets.scopes import * slim = tf.contrib.slim @add_arg_scope def unit3D(inputs...
StarcoderdataPython
69780
""" Concrete Syntax Tree for Python 3.6+ source code """ from cdd.cst_utils import cst_parser, cst_scanner def cst_parse(source): """ Parse Python source lines into a Concrete Syntax Tree :param source: Python source code :type source: ```str``` :return: List of `namedtuple`s with at least ("li...
StarcoderdataPython
3280942
# 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
176841
<filename>ws/ed.py import logging import traceback import io import argparse as argparse from cryptography.fernet import Fernet #create logger logger = logging.getLogger('encrypt') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages fh = logging.FileHandler('encrypt.log') fh.setLevel(lo...
StarcoderdataPython
3289697
<filename>addons/base_address_extended/tests/test_street_fields.py # -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models from odoo.tests.common import SavepointCase class TestStreetFields(SavepointCase): @classmethod def setUpClass(cls): ...
StarcoderdataPython
61089
<reponame>Lockon2000/Udacity def ceaser(message): ciphered = "" for c in message: if c.isalpha(): if c.isupper(): upper = True else: upper = False c = c.upper() place = ord(c) if place+13 > 90: ...
StarcoderdataPython
3351685
from app import app, db with app.app_context(): db.create_all()
StarcoderdataPython
3218389
<filename>CSGraphQLAPIDeployScripts/websphere/Jython/setFederatedRealmName.py<gh_stars>0 #/* # IBM Confidential # OCO Source Materials # 5737-I23 # Copyright IBM Corp. 2021 # The source code for this program is not published or otherwise divested of its trade secrets, irrespective of what has been deposited with the U....
StarcoderdataPython
142357
#----------------------------------------------------- # Mimas: conference submission and review system # (c) <NAME> 2016-2020 http://www.allankelly.net # Licensed under MIT License, see LICENSE file # ----------------------------------------------------- # system imports # framework imports import logging from googl...
StarcoderdataPython
1702003
<gh_stars>0 from functools import wraps def logged(prefix=None, message=None): def decorate(func): logmsg = message if message else func.__name__ @wraps(func) def wrapper(*args, **kwargs): if args[0].verbose: if kwargs.get('leds'): if set(ar...
StarcoderdataPython
52046
<reponame>jamesssooi/font-cli<gh_stars>10-100 '''fonty.commands.list.py: Command-line interface to list user installed fonts.''' import sys import timeit from functools import reduce from itertools import zip_longest import click from ansiwrap import ansilen from termcolor import colored from fonty.models.manifest imp...
StarcoderdataPython
3374989
<filename>pytorch_gleam/inference/__init__.py<gh_stars>0 from pytorch_gleam.inference.consistency import ConsistencyInference from pytorch_gleam.inference.consistency import CountConsistencyInference from pytorch_gleam.inference.consistency import ScoreConsistencyInference from pytorch_gleam.inference.consistency impo...
StarcoderdataPython
57983
from tests.unit import base from src import database class AppActiveRepositoryTest(base.TestCase): def test_has_db(self): self.assertTrue(hasattr(database.AppActiveRepository, 'db')) def test_has_db_default_none(self): # TODO: How to test this? Because the import of initialize on test base m...
StarcoderdataPython
1770821
<filename>text-mining.py #!/usr/bin/python #import the necessary modules import sys import pymongo import json import ConfigParser #import the necessary methods from tweepy library from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream class StdOutListener(StreamListene...
StarcoderdataPython
1652889
# functools.partial has dict attrs import functools p = functools.partial(list) p.__dict__ = dict(a=3) print p.a class P(functools.partial): pass p = P(list) p.__dict__ = dict(a=7)
StarcoderdataPython
1775381
<filename>main_page.py<gh_stars>0 # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'main_page.ui' # # Created by: PyQt5 UI code generator 5.12.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets import numpy as np import os import face_reco...
StarcoderdataPython
3323148
<reponame>zs7779/SAN<filename>lib/datasets/CycleDataset.py ############################################################## ### Copyright (c) 2018-present, <NAME> ### ### Modified from PyTorch Cycle-GAN ### ### Style Aggregated Network for Facial Landmark Detection ### ### Computer V...
StarcoderdataPython
3336641
<gh_stars>0 #!/bin/python3 import sys S = input().strip() try: a = int(S) print(a) except ValueError: print("Bad String")
StarcoderdataPython
1734427
<gh_stars>0 import sqlalchemy as sa from framework import DateTimeAware # SQLAlchemy class TimeStampMixin: """ Timestamping mixin""" created_at = sa.Column(sa.DateTime(timezone=True), default=DateTimeAware.utcnow) created_at._creation_order = 9998 # 列作成の優先順位 updated_at = sa.Column( sa.DateT...
StarcoderdataPython
3218763
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Author: lionel import collections import tensorflow as tf def load_data(filename, sep=' ', sep1=',', isCharacter=False): label_list = [] features_list = [] with tf.gfile.GFile(filename, 'r') as f: for line in f.readlines(): fields = line...
StarcoderdataPython
1639228
<reponame>ISISComputingGroup/EPICS-DeviceEmulator<filename>lewis_emulators/neocera_ltc21/states.py from lewis.core.statemachine import State from lewis.core import approaches from .constants import HEATER_INDEX class OffState(State): """ Device is in off state. It does not display the temperature on the...
StarcoderdataPython
1688725
<reponame>e-km0d/surface from PySide2.QtWidgets import * class Home(QWidget): """ TODO: Document """ def __init__(self): """ TODO: Document """ super(Home, self).__init__()
StarcoderdataPython
9538
<reponame>AleksaLuka/Axelrod import axelrod as axl from .test_player import TestPlayer C, D = axl.Action.C, axl.Action.D class TestMyStrategy(TestPlayer): name = "MyStrategy" player = axl.mystrategy expected_classifier = { "memory_depth": 1, "stochastic": False, "long_run_time": ...
StarcoderdataPython
4812108
from .backend import app as backend from .frontend import app as frontend
StarcoderdataPython
1730771
import sys header=""" \\begin{table}[h] \\centering {\\small \\begin{tabular}{|p{0.18\\linewidth}|p{0.2\\linewidth}|p{0.5\\linewidth}|} \\hline""" footer=""" \\end{tabular} } \\caption{} \\label{} \\end{table}""" # read data data={} theme=None category=None with open(sys.argv[1]) as f: lines = f.readlines() ...
StarcoderdataPython
3338780
from __future__ import annotations import moviepy.video.fx.crop as crop_fx from matplotlib.colors import to_rgb from sauronlab.core.core_imports import * from sauronlab.extras.video_core import VideoCore from sauronlab.model.cache_interfaces import ASauronxVideo from sauronlab.model.roi_tools import * from sauronlab....
StarcoderdataPython
1770548
from collections import OrderedDict from io import BytesIO from os.path import basename import arrow from dropbox.client import DropboxClient, ErrorResponse from wsgidav.dav_error import DAVError, HTTP_NOT_FOUND, HTTP_INTERNAL_ERROR from wsgidav.dav_provider import DAVProvider, _DAVResource from wsgidav.util import jo...
StarcoderdataPython
1653006
<gh_stars>0 ''' Set of helper apps to help with flask ''' from flask import render_template, Flask, request, url_for, jsonify, flash, make_response import uuid from helper import helper from kraken_db import kraken_post_record, post_bigquery_log menu = [ { "name": "New record", "url": "/new?format=html"}, {...
StarcoderdataPython
103600
<gh_stars>1-10 import datetime from django.contrib.auth import get_user_model from django.db import IntegrityError from django.test import TestCase from model_mommy import mommy from sgce.certificates.models import Participant, Template, Certificate from sgce.core.models import Event class CertificateModelTest(Test...
StarcoderdataPython
183312
# -*- coding: utf-8 -*- from django import forms from django.db import models class LibraryFormField(forms.ModelChoiceField): pass class GalleryFormField(LibraryFormField): pass class LibraryField(models.ForeignKey): description = "Attachments" def __init__(self, to='django_attachments.Library', *args, **kwa...
StarcoderdataPython
4830947
import pytest from common.filters import type_choices from common.tests.factories import TestModel2Factory from common.tests.models import TestModel2 pytestmark = pytest.mark.django_db @pytest.fixture(params=(0, 1, 10)) def choice_inputs(request): return [TestModel2Factory() for _ in range(request.param)] def...
StarcoderdataPython
3309498
import logging from typing import Callable from os import devnull import pytest from scanner.transports.ssh import ExecResult from scanner.types import BaseTransport logging.basicConfig(stream=open(devnull, 'w')) class DummyUnixTransport(BaseTransport): def __init__(self, text: str, *args, **kwargs) -> None: ...
StarcoderdataPython
130891
from __future__ import print_function from __future__ import absolute_import from future.utils import listvalues from builtins import object import collections import hashlib import os import re import threading import functools import copy from ._ranges import locators_and_ranges, Range from .arvfile import StreamFil...
StarcoderdataPython
1732146
<gh_stars>0 # Generated by Django 3.1 on 2020-09-01 14:52 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('app', '0001_initial'), ] operations = [ migrations.RenameModel( old_name='Pattern', new_name='CodeSn...
StarcoderdataPython
1629664
<gh_stars>1-10 from django.shortcuts import render from django.utils.safestring import mark_safe from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponseRedirect, HttpResponse from django.core.files.storage import FileSystemStorage from .models import * import json, uuid def lecture(r...
StarcoderdataPython
1655825
''' Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1...
StarcoderdataPython
1716877
# Implement Queue using Stacks: https://leetcode.com/problems/implement-queue-using-stacks/ # Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty). # Implement the MyQueue class: # void push(int x)...
StarcoderdataPython
3320928
<gh_stars>1-10 import numpy as np from nlpaug.augmenter.spectrogram import SpectrogramAugmenter from nlpaug.util import Action, Logger import nlpaug.model.spectrogram as nms class FrequencyMaskingAug(SpectrogramAugmenter): """ Augmenter that mask spectrogram based on frequency by random values. :param t...
StarcoderdataPython
1627537
<filename>helpers.py # -*- coding: utf-8 -*- from __future__ import print_function from __future__ import division from six.moves import xrange from sys import exit from multiprocessing import Pool import numpy as np import scipy import math def normalizer(myvector): mysum = 0. for myvalue in myvector: ...
StarcoderdataPython
1725448
from spam_handling import * @spam_check(name="Spam test 1", all=False, sites=set(("codegolf.stackexchange.com",)), max_rep=10) def spam_test_1(post): if len(post.body) > 100: return "Post length is greater than 100" else: return "" regex_spam_check(r"\bvashikaran\Wspecialist\b", name="Bad ke...
StarcoderdataPython
28432
<reponame>seignovert/pyvims<gh_stars>1-10 """Test VIMS image module.""" from numpy.testing import assert_array_almost_equal as assert_array from pytest import approx, fixture, raises from pyvims import VIMS from pyvims.errors import VIMSError @fixture def img_id(): """Testing image ID.""" return '173145641...
StarcoderdataPython
3225086
<reponame>open-pulse/OpenPulse from PyQt5.QtWidgets import QLineEdit, QDialog, QFileDialog, QWidget, QTreeWidget, QToolButton, QRadioButton, QMessageBox, QTreeWidgetItem, QTabWidget, QLabel, QCheckBox, QPushButton, QSpinBox from os.path import basename from PyQt5.QtGui import QIcon from PyQt5.QtGui import QColor, QBrus...
StarcoderdataPython
3253550
<gh_stars>10-100 """Global fixtures for custom integration.""" import pytest_socket def enable_external_sockets(): pytest_socket.socket_allow_hosts(["api.octopus.energy"]) pytest_socket.enable_socket()
StarcoderdataPython
1654101
<gh_stars>0 from muse.algorithms.sorting import BubbleSort from muse.algorithms.sorting import InsertionSort from muse.algorithms.sorting import MergeSort from muse.algorithms.sorting import QuickSort from muse.algorithms.sorting import SelectionSort def bubbleSort(arr: list) -> None: BubbleSort.sort(arr) def ins...
StarcoderdataPython
3292032
from conf.feature import * QUERY_DIM = 6 MODEL_CONFIG = {"UNet": {"with_bn0" : True, "input_channels_num" : CHANNELS_NUM, "input_size" : WINDOW_SIZE // 2, "blocks_num" : 5, "condition_dim" : QUERY_DIM, "output_dim" : CHANNELS_NUM, }, "QueryNet": {"blocks_num" : 2, "input_size" : WINDOW_SIZE /...
StarcoderdataPython
3270582
<filename>tunepy2/interfaces/abstract_convergence_criterion.py<gh_stars>0 from abc import ABC, abstractmethod from tunepy2 import Genome class AbstractConvergenceCriterion(ABC): """Interface for algorithms that declare convergence of an optimizer""" @abstractmethod def converged(self, old_candidate: Gen...
StarcoderdataPython
1684328
#!/usr/bin/env python3 # # Copyright 2018 Dynatrace LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
StarcoderdataPython