id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3325431 | <gh_stars>10-100
# from datetime import date
from django import template
# from django.conf import settings
# from demo.models import PersonPage, BlogPage, EventPage, Advert, Page
register = template.Library()
@register.assignment_tag(takes_context=True)
def get_site_root(context):
"""
Gets the root page for... | StarcoderdataPython |
3261218 | """ Prediction models.
"""
import typing as t
import numpy as np
import tensorflow as tf
import embed
import data
import op
import nn
from nn.base import Model, WeightedSoftmaxCrossEntropyMixin
from util.log import exec_log as log
from util.debug import *
class ESIM(WeightedSoftmaxCrossEntropyMixin, Model):
... | StarcoderdataPython |
1748377 | #!/usr/bin/python3
"""
Given a non-empty array containing only positive integers, find if the array can
be partitioned into two subsets such that the sum of elements in both subsets is
equal.
"""
from collections import defaultdict
class Solution:
def canPartition(self, nums):
"""
0/1 Knapsack pro... | StarcoderdataPython |
1712021 | <reponame>swapnilsparsh/HacktoberFest2020
# pass list in a function
def count(lst):
even = 0
odd = 0
for i in lst:
if i % 2 == 0:
even += 1
else:
odd += 1
return even,odd
lst = []
for i in range(1,6):
app = int(input("Enter the "+ str(i)+ " no. "))
lst.... | StarcoderdataPython |
194162 | <reponame>Joeffison/MachineLearningBuilder
# -*- coding: utf-8 -*-
template_model_creation = """import pandas as pd
from sklearn.model_selection import train_test_split
{model_import} as ChosenMLAlgorithm
from sklearn.metrics import accuracy_score, confusion_matrix
import pickle
csv_file = "{csv_file}"
model_file =... | StarcoderdataPython |
3349255 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 24 19:08:52 2021
@author: majdi
"""
import os
import sys
import subprocess
from setuptools import setup, find_packages
from distutils.version import LooseVersion
from neorl.version import version
import warnings
warnings.filterwarnings("ignore", category=De... | StarcoderdataPython |
3315047 | <reponame>g10f/sso<filename>apps/smart_selects/form_fields.py<gh_stars>1-10
from django.apps import apps
from django.forms import ChoiceField
from django.forms.models import ModelChoiceField
from smart_selects.widgets import ChainedSelect
class ChainedModelChoiceField(ModelChoiceField):
def __init__(self, app_nam... | StarcoderdataPython |
3286165 | <reponame>TomMakkink/transformers-for-rl<gh_stars>1-10
# import math
# import random
#
# import numpy as np
# import torch
# import torch.nn.functional as F
# import torch.optim as optim
#
# from agents.agent import Agent
# from agents.replay_buffer import ReplayBuffer
# from configs.dqn_config import dqn_config
# from... | StarcoderdataPython |
3356981 | <filename>website/web/__init__.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import base64
from zipfile import ZipFile, ZIP_DEFLATED
from io import BytesIO
import os
from pathlib import Path
from datetime import datetime, timedelta
import json
import http
import calendar
from flask import Flask, render_template, ... | StarcoderdataPython |
3350666 | """
:mod:`zsl.application.modules.cache_module`
-------------------------------------------
"""
from __future__ import unicode_literals
import logging
from injector import Binder, Module, singleton
from zsl.cache.cache_module import CacheModule
from zsl.cache.id_helper import IdHelper
from zsl.cache.redis_cache_modu... | StarcoderdataPython |
1645542 | from typing import Tuple
import torch
from torch_nlp_utils.common import Registrable
from vae_lm.models.base.torch_module import TorchModule
class Flow(TorchModule, Registrable):
"""Generic Class for Generative Flow."""
def forward(
self, z: torch.Tensor, mask: torch.Tensor = None
) -> Tuple[torc... | StarcoderdataPython |
1761416 | <reponame>xinglun/TestFramework<filename>sutie/common/test_menu.py<gh_stars>0
import pytest
import allure
from util.common.login import login
from util.yaml.yaml_util import YamlUtil
from util.request.requestSend import send_request
class TestMenu:
@allure.description("menu test")
@allure.severity("normal") # b... | StarcoderdataPython |
127716 | # Copyright 2019 Indiana Biosciences Research Institute (IBRI)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | StarcoderdataPython |
172784 | # x = n^2 + an + b; |a| < 1000 and |b| < 1000
# b has to be odd, positive and prime as we are testing consecutive values for n
# a has to be negative otherwise the difference between consecutive x's will be huge!
def is_prime(num) :
if (num <= 1) :
return False
if (num <= 3) :
return True... | StarcoderdataPython |
1687401 | <gh_stars>10-100
import asyncio
from pprint import pprint
from aiohttp import ClientSession, TCPConnector
async def fetch_url(session, url):
"""return html body of url"""
async with session.get(url, timeout=60 * 60) as response:
return await response.text()
async def fetch_all_urls(session, urls):
... | StarcoderdataPython |
1685644 | """
Copyright 2008-2009 <NAME>
This file is part of PyCAM.
PyCAM is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PyCAM is distributed in t... | StarcoderdataPython |
1722379 | <filename>main.py<gh_stars>0
import string
while True:
user_inp = str(input("Enter Password: "))
s1 = string.ascii_lowercase
s2 = string.ascii_uppercase
s3 = string.digits
s4 = string.punctuation
if s1[0:2] and s2[0:2] and s3[0:2] and s4[0:2] in user_inp:
print("Password Strong!... | StarcoderdataPython |
157090 | import numpy as np
class NeuralNetwork:
def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate,
weights_input_to_hidden=None, weights_hidden_to_output=None):
self.input_nodes = input_nodes
self.hidden_nodes = hidden_nodes
self.output_nodes = output_nodes
... | StarcoderdataPython |
1709695 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-11-6 23:21:21
# @Author : poplar. (<EMAIL>)
# @Link : http://white-poplar.github.io
# @Version : $Id$
import traceback
import lib.Tool
from Action import Action
import time
import threading
def main():
print("当前时间", time.strftime('%Y-%m-%d %H:%M... | StarcoderdataPython |
3330299 | <reponame>ChaoTzuYin/AutoPPT
# -*- coding: utf-8 -*-
"""
@author: ChaoTzuYin
"""
from pptx import Presentation
import numpy as np
import io
from PIL import Image
import copy
class info_keeper():
def __init__(self, slide_idx, shape_idx, left, top, width, height):
self.slide_idx = slide_idx
self.... | StarcoderdataPython |
3310272 | <reponame>teald/vplanet<filename>tests/IoHeat/test_IoHeat.py
from benchmark import Benchmark, benchmark
import astropy.units as u
import pytest
@benchmark(
{
"log.initial.io.PowerEqtide": {
"value": 9.380954e13,
"unit": u.kg * u.m ** 2 / u.sec ** 3,
},
"log.initial.... | StarcoderdataPython |
154185 | def aumentar(preco=0, taxa=0, formatado=False):
res = preco + (preco * taxa / 100)
return res if formatado is False else moeda(res)
def diminuir(preco=0, taxa=0, formatado=False):
res = preco - (preco * taxa / 100)
return res if formatado is False else moeda(res)
def dobro(preco=0, formatado=False):... | StarcoderdataPython |
12861 | <filename>python/moderation_text_token_demo.py
# -*- coding:utf-8 -*-
from moderation_sdk.gettoken import get_token
from moderation_sdk.moderation_text import moderation_text
from moderation_sdk.utils import init_global_env
if __name__ == '__main__':
# Services currently support North China-Beijing(cn-north-4),Chi... | StarcoderdataPython |
1661933 | """Emulates a Philips Wake-up Light / sunrise.
This cycles through a sequence of RGB tuples and then
linearily interpolates them in HSV color space as time
proceeds.
The routine can be triggered a service `pyscript.wake_up_light`.
The sequence is canceled by turning the light on and off.
"""
import sys
sys.path.appe... | StarcoderdataPython |
1725657 | from blockchain_users_generator import generator as blockchain_users_generator
users = blockchain_users_generator.generate(1000)
users_dict = [user.to_dict() for user in users]
print("\n\n------model------\n", users[0])
print("\n\n------dict-------\n", users_dict[0]) | StarcoderdataPython |
163444 | # pylint: disable=C0303
import os
import numpy as np
import h5py
import matplotlib.pyplot as plt
from math import sqrt
from array import array
from copy import deepcopy
import pickle
import time
from keras.models import load_model
from collections import namedtuple
from sklearn import utils
from keras.utils import to_... | StarcoderdataPython |
1731893 | <reponame>letuananh/pyinkscape
import logging
import platform
import subprocess
from pathlib import Path
WIN_EXE_POTENTIAL_PATHS = [
"C:\\Program Files\\Inkscape\\inkscape.exe",
"C:\\Program Files\\Inkscape\\bin\\inkscape.exe"
]
if platform.system() == "Windows":
INKSCAPE_PATH = None
for _potential_pat... | StarcoderdataPython |
1774449 | class Solution:
def minFallingPathSum(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
rows = len(A)
if rows == 0:
return 0
cols = len(A[0])
if cols == 0:
return 0
if rows == 1:
return min(A[0])
... | StarcoderdataPython |
4816146 | <filename>Homework/2019/Task1/6/code/hyperparams.py<gh_stars>0
# -*- coding: utf-8 -*-
#/usr/bin/python2
'''
By <NAME>. <EMAIL>.
www.github.com/kyubyong/neural_chinese_transliterator
'''
class Hyperparams:
'''Hyper parameters'''
isqwerty = True # If False, 10 keyboard layout is assumed.
... | StarcoderdataPython |
3213936 | <reponame>nbeaver/fonts_with_chars<filename>fonts_with_chars.py
#! /usr/bin/env python3
import argparse
import fontconfig
def get_fonts_with_chars(chars):
for font_file in fontconfig.query():
font = fontconfig.FcFont(font_file)
if all([font.has_char(char) for char in chars]):
yield fon... | StarcoderdataPython |
3276925 | <reponame>joshbaptiste/media_cache_cluster
import os
import configparser
import psutil
import scanner
def parseConfig(configFile):
""" Parses config file """
options = []
config = configparser.ConfigParser()
config.read(configFile)
if config.has_section('global'):
sections = config.sectio... | StarcoderdataPython |
198640 | from django.conf import settings
# Port used to communicate with Discord Proxy
DISCORDNOTIFY_DISCORDPROXY_PORT = getattr(
settings, "DISCORDNOTIFY_DISCORDPROXY_PORT", 50051
)
# When set to True, only superusers will be get their notifications forwarded
DISCORDNOTIFY_SUPERUSER_ONLY = getattr(settings, "DISCORDNOTI... | StarcoderdataPython |
127725 | #
# littletable_demo.py
#
# Copyright 2010, <NAME>
#
from __future__ import print_function
from littletable import Table
from collections import namedtuple
import sys
Customer = namedtuple("Customer", "id name")
CatalogItem = namedtuple("CatalogItem", "sku descr unitofmeas unitprice")
customers = Table("customers")
... | StarcoderdataPython |
3310931 | <gh_stars>0
import logging
from models.datamodel import DataModel
from models.datamodel import TextDataRow
import fileutils
import time
import csv_formatter
from collections import Counter
from enum import Enum
from nltk.stem.snowball import SnowballStemmer
logger = logging.getLogger()
class ProcessMode(Enum):
... | StarcoderdataPython |
1778560 | import pandas as pd
import numpy as np
file = pd.read_csv('Non_US_Cities.csv')
for country in file.Country.unique():
print(country)
temp = file[file.Country == country]
master = pd.DataFrame()
for i, row in temp.iterrows():
print(row.City)
df = pd.read_csv(row['Reviews Link'... | StarcoderdataPython |
35787 | <reponame>MarshallRawson/NaviGator<filename>mission_control/navigator_missions/navigator_missions/start_gate_marshall.py
#!/usr/bin/env python
from __future__ import division
import txros
import numpy as np
import mil_tools
from mil_misc_tools.text_effects import fprint
from navigator import Navigator
import math
from ... | StarcoderdataPython |
3353878 | <reponame>mverleg/django_misc
import settings
from django.http import HttpResponseRedirect
def secure_redirect(request, url = None):
"""
turns a request into a securified redirect
"""
if url is None:
url = request.build_absolute_uri(request.get_full_path())
url = request.build_absolute_uri(url)
url = url.re... | StarcoderdataPython |
187071 | <gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""bibgrep: Grep for bib(la)tex files.
To get all articles where the author contains 'Johnson' and the article is from
2010 or beyond:
>>> bibgrep --entry="article" --field="author~Johnson" --field="year>=2010"
The key, entry and field arguments take str... | StarcoderdataPython |
3277576 | <gh_stars>10-100
import argparse
import torch
from copy import deepcopy
from pprint import pprint
try:
from apex.parallel import DistributedDataParallel as DDP
except ImportError:
pass
from torch.nn.parallel import DistributedDataParallel as torch_DDP
from zerovl.core import init_device, cfg, update_cfg
from... | StarcoderdataPython |
3246499 | s = 9
print(f'O valor da variável s é {s}') | StarcoderdataPython |
102233 | #%%
from user_agents import parse
user_agent = "Mozilla/5.0 (Linux; Android 10; SM-N960F Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/78.0.3904.62 XWEB/2889 MMWEBSDK/20210902 Mobile Safari/537.36 MMWEBID/1696 MicroMessenger/8.0.15.2001(0x28000F41) Process/to"
ua = parse(user_a... | StarcoderdataPython |
43969 | import time
from tasks.capp import app
from others.affine_applications import MoveApps
@app.task(name="sdc.move11", bind=True)
def task_1(self, x):
time.sleep(1)
return MoveApps(":move", x).foo()
@app.task(name="sdc.move12", bind=True)
def task_2(self, x):
return MoveApps(":move", x + 1).foo()
| StarcoderdataPython |
1716155 | <reponame>umarcor/litex<filename>test/test_led.py
#
# This file is part of LiteX.
#
# Copyright (c) 2022 <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-2-Clause
import unittest
from migen import *
from litex.soc.cores.led import WS2812
class TestWS2812(unittest.TestCase):
test_clk_freqs = [75e6, 50e6, 25e6]
... | StarcoderdataPython |
482 | <filename>hypnettorch/data/timeseries/preprocess_audioset.py
#!/usr/bin/env python3
# Copyright 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
#
# http://www.apache.org/licens... | StarcoderdataPython |
1727732 | import gemmi
import unittest
from swamp.utils import *
from conkit.core import ContactMap, Contact
class UtilsTestCase(unittest.TestCase):
def test_1(self):
contact_map = ContactMap("test")
contact_map.add(Contact(1, 4, 1.0))
contact_map.add(Contact(2, 4, 1.0))
contact_map.add(Con... | StarcoderdataPython |
159829 | <reponame>petrLorenc/Labelling-Tool<filename>app/modules/loader/model_utils.py
import numpy as np
import torch
class ModelUtils:
"""
Group of function to help work with embeddings and models.
"""
@staticmethod
def load_glove_mapping(path):
"""
creates a dictionary mapping words t... | StarcoderdataPython |
3301493 | <gh_stars>1-10
#!/usr/bin/env python
__tempdir__ = '/tmp'
| StarcoderdataPython |
4806918 | <filename>src/main.py
import src.preprocessing.preprocessing as prep
import src.classification.classification as classification
if __name__ == '__main__':
# Apply preprocessing steps and generate features then save
prep.main()
# Run classification algorithms to predict kinship relations
classificatio... | StarcoderdataPython |
1703473 | <filename>book/book/items.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from scrapy import Item, Field
class Subject(Item):
douban_id = Field()
type = Field()
class Meta(Item):
douban_id = Field()
slug = Field()
name = Field()
sub_name = Field()
alt_name = Field()
cover = Field()... | StarcoderdataPython |
3306129 | <gh_stars>0
# Import system libraries
import os
import sys
# Import 3rd party libraries
import pytest
# Import custom libraries
sys.path.append(os.path.join(os.path.dirname(__file__), "../../../"))
import lib.common.type_validator as type_validator
class TestBaseValidator(object):
def test_base_validator_is_no... | StarcoderdataPython |
118725 | #!/usr/bin/env python3
from functools import lru_cache
from typing import NamedTuple, Dict, Any
from datetime import datetime
from pathlib import Path
import json
import pytz
from mycfg import paths
# TODO Json type?
# TODO memoised properties?
# TODO lazy mode and eager mode?
# lazy is a bit nicer in terms of more ... | StarcoderdataPython |
61594 | #Enquiry Form
name=input('Enter your First Name ')
Class=int(input('Enter your class '))
school=input('Enter your school name ')
address=input('Enter your Address ')
number=int(input('Enter your phone number '))
#print("Name- ",name,"Class- ",Class,"School- ",school,"Address- ",address,"Phone Number- ",number,sep='\n')... | StarcoderdataPython |
1619777 | nome = str(input('Insira um nome aqui: ')).strip().upper()
noma = nome.split()
nom1 = 'SILVA' in noma
print('A pessoa tem o nome Silva?: {}'.format(nom1))
| StarcoderdataPython |
1757917 | import aiohttp
import asyncio
import json
# global dict settings
urls = {
"shezheng": "http://",
"shehuang": 'http://',
}
# NOTE: can be remove in productive code
# this is ok too
# form = aiohttp.FormData()
# form.add_field('image',
# open('/home/mory/data/face_test/10.jpg', 'rb'),
# ... | StarcoderdataPython |
3347221 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2017-12-25 14:41
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0004_auto_20170105_... | StarcoderdataPython |
135839 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | StarcoderdataPython |
112462 | # Generated by Django 4.0.1 on 2022-04-07 01:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('model_api', '0005_remove_order_datetimecreated_alter_order__id_and_more'),
]
operations = [
migrations.AddField(
model_name='ord... | StarcoderdataPython |
1707483 | #!/usr/bin/env python
"""
The mosaic QGraphicsView. This is QGraphicsView in the mosaic
UI tab.
Hazen 10/18
"""
import os
from PyQt5 import QtCore, QtGui, QtWidgets
#import storm_control.steve.qtMultifieldView as multiView
import storm_control.steve.coord as coord
import storm_control.steve.steveItems as steveItems
... | StarcoderdataPython |
1674048 | from typing import Callable, Optional
import torch
from torch import nn
import constants
from rl_multi_agent import MultiAgent
from rl_multi_agent.experiments.experiment import ExperimentConfig
from rl_multi_agent.furnmove_episode_samplers import FurnMoveEpisodeSampler
from rl_multi_agent.furnmove_episodes import Fur... | StarcoderdataPython |
3228474 | <gh_stars>1-10
#
# Copyright 2012 <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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | StarcoderdataPython |
3357407 | #! /usr/bin/env python
# run this test against an instance of uwsgi for websockets
from nose import tools
import threading
from websocket import create_connection
class WebsocketClient(threading.Thread):
"""Simulate a websocket client"""
def __init__(self, websocket_url):
self.websocket_url = websocke... | StarcoderdataPython |
3210752 | import os
from os import path
from os.path import join
import sys
import json
import printj
import pyjeasy.file_utils as f
import cv2
from tqdm import tqdm
PATH = "/home/jitesh/sekisui/bolt/hexagon_bolts"
OUTPUT_PATH = "/home/jitesh/sekisui/bolt/cropped_hexagon_bolts"
f.make_dir_if_not_exists(OUTPUT_PATH)
json_list =... | StarcoderdataPython |
3217935 | <reponame>alirezaghey/leetcode-solutions
from functools import cache
class Solution:
# iterative solution
# TC: O(n)
# SC: O(1)
def numTilings(self, n: int) -> int:
dp = [1,1,2]
if n <= 2:
return dp[n]
MOD = 1_000_000_007
for _ in range(2, n):
... | StarcoderdataPython |
164515 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import httpretty
from pyfakefs import fake_filesystem_unittest
from click import UsageError, ClickException
from mock import Mock, MagicMock, patch
from requests.exceptions import SSLError
from cloudshell.rest.api import FeatureUnavailable
from shellfoundry.c... | StarcoderdataPython |
3316734 | from .csv_rule import CSVRule
from flask import Flask
app = Flask(__name__)
class limitAcuityRule(CSVRule):
# def __init__(self, name_in_csv, node_id):
# super().__init__(name_in_csv, node_id)
def __init__(self, name_in_csv, allowed_acuity, node_id):
super().__init__(name_in_csv, node_id)
... | StarcoderdataPython |
112905 | """
AlexNet 模型
本模型默认总参数量[参考基准:cifar10]:
Total params: 24,769,290
Trainable params: 24,768,586
Non-trainable params: 704
本模型默认总参数量[参考基准:ImageNet]:
Total params: 62,379,752
Trainable params: 62,379,048
Non-trainable params: 704
"""
from hat.models.advanc... | StarcoderdataPython |
1659430 | #!/usr/bin/python
import time
for x in xrange(0,10):
print x
time.sleep(2);
| StarcoderdataPython |
3336778 | # ==============================================================================
# Copyright 2020 Google LLC
#
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/li... | StarcoderdataPython |
53117 | <reponame>zhigangjiang/LGT-Net
"""
@Date: 2021/07/18
@description:
"""
import os
import models
import torch.distributed as dist
import torch
from torch.nn import init
from torch.optim import lr_scheduler
from utils.time_watch import TimeWatch
from models.other.optimizer import build_optimizer
from models.other.criter... | StarcoderdataPython |
50875 | #!/usr/bin/env python
import yaml
from pprint import pprint as pp
from napalm import get_network_driver
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
# Read YAML file
with open("my_devices.yml", 'r') as strea... | StarcoderdataPython |
147905 | from .__init__ import *
from ..__init__ import Generator
def percentageFunc(maxValue=99, maxpercentage=99):
a = random.randint(1, maxpercentage)
b = random.randint(1, maxValue)
problem = f"What is {a}% of {b}?"
percentage = a / 100 * b
formatted_float = "{:.2f}".format(percentage)
solution = f... | StarcoderdataPython |
3378082 | from jupyter_client import KernelManager
import queue
from jupyter_client.manager import run_kernel
class MyKernel():
def __init__():
kernel = KernelManager()
kernel.start_kernel()
client = = km.client()
def run_code(self, code):
print("executing code: " + code)
... | StarcoderdataPython |
43995 | #!/usr/bin/python3
# ==================================================
"""
File: RMedian - Unittest - Phase 1
Author: <NAME>
"""
# ==================================================
# Import
import math
import random
import pytest
# ==================================================
# Phase 1
def phase1(X, k, d):... | StarcoderdataPython |
1784617 | from flask_wtf import FlaskForm
from wtforms import TextField
from wtforms.validators import Required, Email, Length
from app.jobs.models import Jobs
from app import db
class RegisterJobsForm(FlaskForm):
name = TextField(validators=[Required()])
address = TextField()
| StarcoderdataPython |
3389412 | import json
from jwkest import BadSignature
from jwkest.jwk import SYMKey
from jwkest.jws import NoSuitableSigningKeys
from jwkest.jwt import JWT
from oic.oic import OIDCONF_PATTERN
from oic.oic.message import IdToken, ProviderConfigurationResponse
from oic.utils.keyio import KeyJar, KeyBundle
import requests
class... | StarcoderdataPython |
3343419 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import print_function
import os.path as op
import sys
import logging
import string
from collections import defaultdict
from itertools import product, combinations
from jcvi.formats.blast import BlastLine
from jcvi.formats.fasta import Fasta
fr... | StarcoderdataPython |
1796817 | import os
from biicode.client.dev.cmake.cmaketool import CMakeTool
from biicode.common.model.blob import Blob
from biicode.common.utils.file_utils import save_blob_if_modified, save, load_resource
from biicode.client.dev.cpp import DEV_CPP_DIR
default_cmake = """
ADD_BII_TARGETS()
###################################... | StarcoderdataPython |
3319841 | <gh_stars>1-10
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; wi... | StarcoderdataPython |
15146 | <gh_stars>100-1000
# Copyright 2016-present CERN – European Organization for Nuclear Research
#
# 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... | StarcoderdataPython |
183557 | # simple benchmark
from generator import *
import time
# number of simulated photons
N = int(5E7)
t1 = time.time()
spectrum = Etalon()
spectrograph = MaroonX()
generate_rv_series(spectrograph, spectrum, [0.], photons_per_spectrum=N)
t2 = time.time()
print("Total time for tracing: {:.2f} s".format(t2-t1))
print("Simul... | StarcoderdataPython |
3335053 | """An implementation of SegNet (and Bayesian alternative)."""
from keras.applications.vgg16 import VGG16
from keras.layers import Activation
from keras.layers import BatchNormalization
from keras.layers import Conv2D
from keras.layers import Dropout
from keras.layers import Input
from keras.layers import Lambda
from ke... | StarcoderdataPython |
32666 | import pytest
@pytest.mark.parametrize("cli_options", [
('-k', 'notestdeselect',),
])
def test_autoexecute_yml_keywords_skipped(testdir, cli_options):
yml_file = testdir.makefile(".yml", """
---
markers:
- marker1
- marker2
---
- provider: python
type: assert
expression: "1"
""")
assert yml_fi... | StarcoderdataPython |
3392125 | import itertools
import logging
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from sklearn import metrics
from torch.utils.data import DataLoader, Dataset
from torchvision import models
from model import CompatModel
from polyvore_dataset import Cat... | StarcoderdataPython |
4812740 | """ Common tools """
__version__ = "2.0.0"
from .config import Config, parse_config # noqa
from .errors import Error, InvalidConfig # noqa
from .executor import Task, run_sequence, ExecutorFailed # noqa
from .groups import GroupList, Group # noqa
from .groups import GroupNotFound, UnknownElement as UnknownGroupEl... | StarcoderdataPython |
41401 | <reponame>prachir1501/NeuralDater<filename>helper.py<gh_stars>10-100
import numpy as np, sys, unicodedata, requests, os, random, pdb, requests, json, gensim
import matplotlib.pyplot as plt, uuid, time, argparse, pickle, operator
import logging, logging.config, itertools, pathlib
import scipy.sparse as sp
from collecti... | StarcoderdataPython |
1667492 | <filename>ddi_search_engine/Bio/config/FormatRegistry.py
# Copyright 2002 by <NAME>, <NAME>. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
# This is based on some older code b... | StarcoderdataPython |
138882 | import unittest
from models.readingtip import ReadingTip
from models.tag import Tag
from models.user import User
class TestReadingTip(unittest.TestCase):
def setUp(self):
self.user = User("maija", "jahph5Ie")
def test_constructor_sets_fields_correctly(self):
tags = [Tag("kirjat"), Tag("maksull... | StarcoderdataPython |
1760230 | # Generated by Django 2.2.2 on 2019-06-26 14:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('favouritesapi', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='category',
name='category_count',... | StarcoderdataPython |
3384787 | from rest_framework.response import Response
from rest_framework import views
from .utils import searcher
class SearchView(views.APIView):
def get(self, request, format=None):
query_str = request.query_params.get('q', None)
if not query_str:
return Response(status=400, data=dict(me... | StarcoderdataPython |
1626588 | <filename>AtC_Beg_Con_071-080/ABC078/B.py<gh_stars>0
x, y, z = map(int, input().split())
i = 0
while x - (y + z) * i > 0:
i += 1
t = x - (y + z) * (i - 1)
if t >= z:
print(i - 1)
else:
print(i - 2) | StarcoderdataPython |
157724 | <filename>libweasyl/libweasyl/alembic/versions/8e98a1be126e_add_index_on_submission_popularity_score.py
"""Add index on submission popularity score
Revision ID: 8e98a1be126e
Revises: <PASSWORD>
Create Date: 2019-10-24 17:06:22.092041
"""
# revision identifiers, used by Alembic.
revision = '8e98a1be126e'
down_revisio... | StarcoderdataPython |
1754138 | # Copyright (c) 2019-2020 <NAME>
# License: MIT License
# Created 2019-02-15
from typing import TYPE_CHECKING, Tuple, Sequence, Iterable, cast, List, Union
import array
import copy
from contextlib import contextmanager
from ezdxf.math import Vector, Matrix44
from ezdxf.math.transformtools import OCSTransform, NonUnifor... | StarcoderdataPython |
168191 | <filename>gen2-custom-models/concat.py
import numpy as np
import cv2
import depthai as dai
SHAPE = 300
p = dai.Pipeline()
p.setOpenVINOVersion(dai.OpenVINO.VERSION_2021_4)
camRgb = p.create(dai.node.ColorCamera)
camRgb.setPreviewSize(SHAPE, SHAPE)
camRgb.setInterleaved(False)
camRgb.setColorOrder(dai.Col... | StarcoderdataPython |
1687575 | <gh_stars>0
import sys
import json
from df import df_worklist, ANALYSES, fmt, interp
from form_blocks import form_blocks
import cfg
from cfg_to_code import cfg_to_code
from util import fresh
def br_removal(blocks):
in_, out = df_worklist(blocks, ANALYSES['cprop'])
# overwirte blocks
preds, succs = cfg.edge... | StarcoderdataPython |
4457 | from ._movement import Movement
from .path import MovementPath
from .paths import MovementPaths
| StarcoderdataPython |
162793 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 0.5.0.5149 (http://hl7.org/fhir/StructureDefinition/SearchParameter) on 2015-07-06.
# 2015, SMART Health IT.
from . import contactpoint
from . import domainresource
from . import fhirdate
from . import fhirelement
class SearchParameter(domainre... | StarcoderdataPython |
1649213 | <reponame>LeeDongGeon1996/Stock.Indicators.Python<filename>stock_indicators/indicators/adx.py
from typing import Iterable, Optional, TypeVar
from stock_indicators._cslib import CsIndicator
from stock_indicators._cstypes import List as CsList
from stock_indicators.indicators.common.helpers import RemoveWarmupMixin
from... | StarcoderdataPython |
93811 | #!/usr/bin/python3.4
# -*-coding:Utf-8 -*
'''module to manage Rendering Options'''
import xml.etree.ElementTree as xmlMod
import os
class Options:
'''class to manage Rendering Options'''
RGBA_AVAILABLE = ['IRIS', 'PNG', 'JPEG2000', 'TARGA', 'DPX', 'OPEN_EXR_MULTILAYER', 'OPEN_EXR', 'HDR' ]
def __init__(self, xm... | StarcoderdataPython |
66383 |
# XXX depends on internet connectivity, so not run as part of standard tests
from __future__ import absolute_import, division, print_function
def exercise():
from mmtbx.wwpdb import rcsb_web_services
lysozyme = """<KEY>"""
homologs = rcsb_web_services.sequence_search(lysozyme, d_max=2.0)
assert (len(homologs... | StarcoderdataPython |
1746092 | import requests
import json
import ConfigParser
class LabelManager:
def __init__(self, config):
"""
:param ConfigParser.RawConfigParser config: read config file
"""
self.nextcloudBaseUrl = 'https://api.github.com/repos/nextcloud/'
config.read('github.cfg')
self.aut... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.