id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
17797 | <reponame>chop-dbhi/biorepo-portal<filename>brp/formutils.py
from django import template
from django.forms import widgets
register = template.Library()
@register.inclusion_tag('formfield.html')
def formfield(field):
widget = field.field.widget
type_ = None
if isinstance(widget, widgets.Input):
typ... | StarcoderdataPython |
172233 | <gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
# from distutils.command.install import INSTALL_SCHEMES
from setuptools import setup, find_packages
with open("README.rst") as readme_file:
readme = readme_file.read()
with open("CHANGELOG.rst") as history_file:
history =... | StarcoderdataPython |
1729095 | import sys
sys.path.append('..')
from mtevi.mtevi import *
from mtevi.utils import *
import numpy as np
import torch
import argparse
import os
import math
from BayesianDTI.utils import *
from torch.utils.data import Dataset, DataLoader
from BayesianDTI.datahelper import *
from BayesianDTI.model import *
from BayesianDT... | StarcoderdataPython |
16123 | import os
import sys
import posthoganalytics
from django.apps import AppConfig
from django.conf import settings
from posthog.utils import get_git_branch, get_git_commit, get_machine_id
from posthog.version import VERSION
class PostHogConfig(AppConfig):
name = "posthog"
verbose_name = "PostHog"
def read... | StarcoderdataPython |
113522 | <filename>src/day2.py
# Advent of Code 2021, Day 2
# (c) blu3r4y
from aocd.models import Puzzle
from dotmap import DotMap
from funcy import print_calls
from parse import parse
@print_calls
def part1(instructions):
hor, dep = 0, 0
for e in instructions:
if e.dir == "forward":
hor += e.num
... | StarcoderdataPython |
1604379 | <gh_stars>0
import json
from random import randint
from time import sleep
import uuid
from python_liftbridge import Lift, Message, Stream, ErrStreamExists
def my_random_string(string_length=10):
"""Returns a random string of length string_length."""
random = str(uuid.uuid4())
random = random.upper()
r... | StarcoderdataPython |
31750 | <gh_stars>0
# This code is based on the SOM class library.
#
# Copyright (c) 2001-2021 see AUTHORS.md file
#
# 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 wit... | StarcoderdataPython |
1702192 | from tanim.utils.color import Color
from tanim.utils.config_ops import digest_config
from tanim.core.mobject.vectorized_mobject import VGroup
from tanim.core.mobject.vectorized_mobject import VMobject
from tanim.extention.mobject.geometry import Line
from tanim.extention.mobject.geometry import Rectangle
import tani... | StarcoderdataPython |
3286973 | import abc
from collections import OrderedDict
import numpy as np
from gym.spaces import Box
from rlkit.core.eval_util import create_stats_ordered_dict
from rlkit.envs.wrappers import ProxyEnv
from rlkit.core.serializable import Serializable
from rlkit.core import logger as default_logger
class MultitaskEnv(object,... | StarcoderdataPython |
1731433 | from .explore_handlers import *
| StarcoderdataPython |
1767204 | <reponame>ipattarapong/dbnd<filename>plugins/dbnd-docker/src/dbnd_docker/docker_ctrl.py
from dbnd._core.task_run.task_run_ctrl import TaskRunCtrl
class DockerRunCtrl(TaskRunCtrl):
def docker_run(self):
pass
def on_kill(self):
pass
| StarcoderdataPython |
15206 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time: 2020/5/14 20:41
# @Author: Mecthew
import time
import numpy as np
import pandas as pd
import scipy
from sklearn.svm import LinearSVC
from sklearn.linear_model import logistic
from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import ac... | StarcoderdataPython |
1606631 | <filename>ensemble_classification_wrapper.py
import random
import numpy as np
from scipy import stats
import sys
sys.path.insert(0, "../NumPy-based-Logistic-Regression/")
from numpy_based_0hl_neural_network import NumPyBased0hlNeuralNetwork
sys.path.insert(0, "../NumPy-based-Neural-Network/")
from numpy_based_neural_n... | StarcoderdataPython |
1638141 | <reponame>raphaeldeimel/phastapromep
__all__ = ['_phastapromep']
from ._phastapromep import *
| StarcoderdataPython |
15740 | <filename>trainLib.py
import math
#constants and globals
background = '0'
NORTH = 0
EAST = 1
SOUTH = 2
WEST = 3
dirs = {0 : "NORTH", 1 : "EAST", 2 : "SOUTH", 3 : "WEST"}
class CellElement(): #CellELement Interface for the subclasses
#Subclasses: RegularRoad, Switch, LevelCrossing, Bridge, Station
def setPo... | StarcoderdataPython |
1752380 | # Counter 클래스는 아래와 같이 제너레이터로 변경할 수 있습니다.
# yield 는 iterator 를 추상화 하기 위해 Python 2.2 에 추가되었습니다.
def gen_1_to_5():
yield 1
yield 2
yield 3
yield 4
yield 5
counter = gen_1_to_5()
print(type(counter))
print(next(counter))
print(next(counter))
print(next(counter))
print(next(counter))
print(next(count... | StarcoderdataPython |
1783395 | <filename>example/instagram.py
from justgood import imjustgood
api = imjustgood("YOUR_APIKEY_HERE")
data = api.instagram("the.autobots_corp")
print(data)
# EXAMPLE GET CERTAIN ATTRIBUTES
result = "ID : {}".format(data["result"]["id"])
result += "\nUsername : {}".format(data["result"]["username"])
result += "\nFulln... | StarcoderdataPython |
1672876 | <filename>eviction_tracker/detainer_warrants/judgment_imports.py
from .models import db
from .models import Attorney, Courtroom, Defendant, DetainerWarrant, District, Judge, Hearing, Judgment, Plaintiff, detainer_warrant_defendants
from .util import get_or_create, normalize, open_workbook, dw_rows, district_defaults
fr... | StarcoderdataPython |
3202611 | <reponame>DhruvKinger/Pointer-Controller
'''
This is a sample class for a model. You may choose to use it as-is or make any changes to it.
This has been provided just to give you an idea of how to structure your model class.
'''
import cv2
import numpy as np
from openvino.inference_engine import IECore,IENetwork
clas... | StarcoderdataPython |
172468 | <filename>leetcode/easy/1185-Day_of_week.py
"""
Leetcode #1185
"""
class Solution:
# if we know that 1/1/1971 was Friday
def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
isLeapYear = lambda x: 1 if x % 400 == 0 or (x % 4 == 0 and x % 100 != 0) else 0
months = [31, 28, 31, 3... | StarcoderdataPython |
59113 | <gh_stars>1-10
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader
from .models import *
def index(request):
# latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('core/index.html')
context... | StarcoderdataPython |
4808653 | #!/usr/bin/python
# ex:set fileencoding=utf-8:
from __future__ import unicode_literals
from django import forms
from django.apps import apps
from django.conf import settings
from django.conf.urls import patterns, url, include
from django.contrib.admin.sites import AlreadyRegistered
from django.contrib.admin.sites imp... | StarcoderdataPython |
3307911 | <gh_stars>0
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Disseminat... | StarcoderdataPython |
1779427 | #!/usr/bin/env python
import sys
import os
sys.path.append(os.getcwd())
import cpmsparse.util as util
from cpmsparse.kernels import PatternSparse, CpmSparse
import pandas as pd
import numpy as np
group_id = 'g8788' # event hits: 130
print("We're good to go!")
context, cc = util.init_pycuda()
# Load data
N, x, y... | StarcoderdataPython |
23828 | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... | StarcoderdataPython |
71483 | <filename>pythx/middleware/group_data.py<gh_stars>10-100
"""This module contains a middleware to fill the :code:`groupId`/:code:`groupName`
field."""
import logging
from typing import Dict
from pythx.types import RESPONSE_MODELS, REQUEST_MODELS
from pythx.middleware.base import BaseMiddleware
LOGGER = logging.getLo... | StarcoderdataPython |
1684593 | <reponame>maykinmedia/maykin-email-templates
from django.http import HttpResponse
from django.views.generic import View
from .utils import variable_help_text
class TemplateVariableView(View):
def get(self, request, *args, **kwargs):
variables = variable_help_text(kwargs.get('template_type'))
retu... | StarcoderdataPython |
3343919 | <reponame>LeWeis/captcha-break
# coding=utf-8
from __future__ import print_function
from gen.gen_captcha import gen_dataset, load_templates
import cPickle as pickle
from PIL import Image
import numpy as np
from gen.utils import vec2str
def check_dataset(dataset, labels, index):
data = np.uint8(dataset[index]).resha... | StarcoderdataPython |
3269348 | <filename>tests/scidash/tests/observations.py
"""Observations (experimental facts) used to parameterize tests"""
import os, sys
import quantities as pq
import django
path = os.path.realpath(__file__)
for i in range(4):
path = os.path.split(path)[0]
CW_HOME = path
sys.path.append(CW_HOME)
sys.path.append(os.path.j... | StarcoderdataPython |
3372131 | from keras import layers
from keras import models
from keras.datasets import mnist
from keras.utils import to_categorical
import tensorflow as tf
import os
import contextlib
import datetime
# @contextlib.contextmanager
# def options(options):
# old_opts = tf.config.optimizer.get_experimental_options()
# tf.config.... | StarcoderdataPython |
1669599 | from django.db import models
from django.contrib.auth.models import AbstractUser, UserManager
# Create your models here.
| StarcoderdataPython |
163706 | <reponame>eubr-bigsea/tahiti
# -*- coding: utf-8 -*-}
import logging
import os
import uuid
import requests
from flask import request, current_app, g
from flask_babel import gettext
from flask_restful import Resource
from sqlalchemy import or_
from sqlalchemy.orm import joinedload
from sqlalchemy.sql.elements import an... | StarcoderdataPython |
3218915 | <filename>Chapter4/Aurora/src/test/python/apache/aurora/client/cli/test_diff.py
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | StarcoderdataPython |
156271 | #!/usr/bin/env python3
"""
Command line interface for the Ivaldi IoT scientific sensor client.
"""
# Standard library imports
import argparse
import sys
# Local imports
import ivaldi
import ivaldi.monitor
import ivaldi.link
def generate_arg_parser():
"""
Generate the argument parser for Ivaldi.
Returns... | StarcoderdataPython |
1783280 | # Copyright (C) 2020 Google 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 agreed to in writing, ... | StarcoderdataPython |
184985 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 24 15:53:51 2016
@author: jdorvinen
"""
import numpy as np
def kriebel_dean(w_cm, B, D, W, m, S, T_d, H_b, gamma=0.78):
'''Calculates storm erosion based on the method presented in,
<NAME>., and <NAME>., 'Convolution method for time-dependent
beach-profile ... | StarcoderdataPython |
4840484 | # Common constants and functions for reverting scripts.
import getpass
import base64
import logging
import re
import requests
try:
from lxml import etree
except ImportError:
try:
import xml.etree.cElementTree as etree
except ImportError:
import xml.etree.ElementTree as etree
try:
input ... | StarcoderdataPython |
1766596 | """ Dictionary of standard bond lengths
"""
from phydat.phycon import ANG2BOHR
# Dictionary of A-B single bond lengths
LEN_DCT = {
('H', 'H'): 0.74 * ANG2BOHR,
('H', 'C'): 1.09 * ANG2BOHR,
('H', 'N'): 1.01 * ANG2BOHR,
('H', 'O'): 0.95 * ANG2BOHR,
('H', 'Cl'): 1.275 * ANG2BOHR,
('C', 'C'): 1.5... | StarcoderdataPython |
1754077 | from django.core.exceptions import ValidationError
class HttpError(Exception):
pass
class TrustChainHttpError(HttpError):
pass
class UnknownKid(Exception):
pass
class MissingJwksClaim(ValidationError):
pass
class MissingAuthorityHintsClaim(ValidationError):
pass
class NotDescendant(Valid... | StarcoderdataPython |
188043 | <reponame>yiming107/Pointnet_Pointnet2_pytorch<filename>train_cls.py
"""
Author: Benny
Date: Nov 2019
Modified by: Yiming
Main changes: compatible to train other dataset
"""
from data_utils.ModelNetDataLoader import ModelNetDataLoader
from data_utils.ReplicaDataLoader import ReplicaDataLoader
import argparse
import nu... | StarcoderdataPython |
3223378 | <reponame>Dou-Yu-xuan/deep-learning-visal
import torch
import torch.nn as nn
import torch.nn.functional as F
class _PositionAttentionModule(nn.Module):
""" Position attention module"""
def __init__(self, in_channels, **kwargs):
super(_PositionAttentionModule, self).__init__()
self.con... | StarcoderdataPython |
180941 | <gh_stars>1-10
from django.contrib.syndication.views import Feed
from django.template.defaultfilters import truncatewords_html
from django.utils.safestring import mark_safe
from django.utils.html import strip_tags
from .models import Post
class LatestPostsFeed(Feed):
title = 'Bloggable'
link = ''
descrip... | StarcoderdataPython |
3389632 | <gh_stars>100-1000
from __future__ import unicode_literals
from tests.utils import ConverterTestCase
class StructTestCase(ConverterTestCase):
def test_typedef_primitives(self):
self.assertGeneratedOutput(
"""
typedef unsigned foo1;
typedef unsigned short foo2;
... | StarcoderdataPython |
1684409 | import json
import os
import subprocess
import logging
logger = logging.getLogger('debug')
class ExifTool:
"""
ExifTool class that is used to get song metadata
"""
sentinel = b"{ready}"
def __init__(self, executable="exiftool"):
self.executable = executable
self.running = False
... | StarcoderdataPython |
1637331 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import unicodedata
import epitran
import argparse
def main(code):
epi = epitran.Epitran(code)
for line in sys.stdin: # pointless
line = line.decode('utf-8')
line = unicodedata.normalize('NFD', line.lower())
line = epi.translite... | StarcoderdataPython |
180709 | <filename>packages/w3af/w3af/core/ui/gui/tools/manual_requests.py
"""
manual_requests.py
Copyright 2007 <NAME>
This file is part of w3af, http://w3af.org/ .
w3af 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 v... | StarcoderdataPython |
1799414 | <reponame>super-goose/orbit
import pygame
import math
class Planet:
def __init__(self, surface, color, position, radius, center):
self.radius = radius
self.surface = surface
self.color = color
self.setPosition(position)
self.center = center
self.setOrbitOffset(0)
... | StarcoderdataPython |
97669 | import numpy as np
import redis
import json
import logging
from docopt import docopt
from obnl.core.client import ClientNode
# This doc is used by docopt to make the wrapper callable by command line and gather easily all the given parameters
doc = """>>> IntegrCiTy wrapper command <<<
Usage:
wrapper.py (<host> <n... | StarcoderdataPython |
107271 | '''
Created on Nov 19, 2013
@author: <NAME>
<EMAIL>
Department of Geography, UGA
'''
'''
Create initial table for tweet storing
'''
import dbf
table = dbf.Table("Tweet.dbf","TweetID C(20);TweetText C(200);TweetTime C(30); TweetLat C(30);TweetLon C(30);UserID C(30);UserName C(30);UserLoc C(30); CheckTime C(20)")
... | StarcoderdataPython |
1730688 | <filename>BFM17_POM1D_VrsFnl/src/pom/coupling/ModuleForcing.py
# WARNING THIS IS A TEST VERSION
# (MONTHLY FREQUENCY)
# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# MODEL BFM - Biogeochemical Flux Model
# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=... | StarcoderdataPython |
188053 | <filename>homoeditdistance/demonstration.py<gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Usage demonstration for the homoeditdistance package."""
import sys
import argparse
from homoeditdistance import homoEditDistance, backtrack, assemblePaths
def get_parser():
"""
Returns the argument p... | StarcoderdataPython |
1741439 | import os
import zipfile
import shutil
import walk
def Unpack(set_pack, archive_name):
archive_name = set_pack[0] + "/" + archive_name
z = zipfile.ZipFile(archive_name, 'r')
z.extractall(set_pack[1])
z.close()
def Pack(set_pack, archive_name):
with zipfile.ZipFile(set_pack[0] + "/" + archive_name, 'w... | StarcoderdataPython |
3372492 | <filename>datasets/data-sets/voice-assistant/annotate-data-flows.py<gh_stars>0
#!/usr/bin/env python3
import os
import sys
import json
arguments = len(sys.argv)
src_directory = "."
dst_directory = "../../annotated-data-sets/voice-assistant/"
# read all files in subdirectories
for root, dirs, files in os.walk(src_di... | StarcoderdataPython |
4819843 | from setuptools import setup
from setuptools import find_packages
setup(name='json-test',
packages = find_packages(),
version='0.1',
description='A python library for assisting you in writing tests against a JSON structure.',
url='https://github.com/inkmonk/json-test',
author='Sibi',
... | StarcoderdataPython |
187293 | from osrf_pycommon.process_utils import asyncio
from osrf_pycommon.process_utils.async_execute_process import async_execute_process
from osrf_pycommon.process_utils import get_loop
# allow module to be importable for --cover-inclusive
try:
from osrf_pycommon.process_utils.async_execute_process_trollius import From... | StarcoderdataPython |
116022 | from django import forms
from .models import Job
class JobForm(forms.ModelForm):
class Meta:
model = Job
fields = ('publisher', 'company_name', 'title', 'job_type', 'location', 'description', 'post_until',
'is_active', 'apply_link')
widgets = {
'publisher': f... | StarcoderdataPython |
3249410 | <gh_stars>0
"""QHttp module."""
from PyQt5 import QtCore, QtNetwork
from typing import Union, Optional, cast, Dict, List, Any
from pineboolib.core import decorators
class QHttpRequest(object):
"""QHttpRequest class."""
_valid: bool
_major_ver: int
_minor_ver: int
_values: Dict[str, Any]
_id:... | StarcoderdataPython |
1704596 | <gh_stars>1-10
from transferfile.sftp import Sftp
from transferfile.scp import Scp
from transferfile.ftp import Ftp
from transferfile.rsync import Rsync
class TransferFactory(object):
@classmethod
def create(cls, type, host, username, password=None, port=None, **kwargs):
if type.lower() == "ftp":
... | StarcoderdataPython |
123084 | # -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2019, 2020 <NAME> <<EMAIL>>
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 wi... | StarcoderdataPython |
1728565 | <gh_stars>1-10
import pandas as pd
import numpy as np
'''
This module contains several normalization methods.
See ReadMe.md for usage example.
'''
def zero_one_normalize(df: pd.DataFrame, excluded_colnames: list = None) -> pd.DataFrame:
"""
Applies the MinMaxScaler from the module sklearn.preprocess... | StarcoderdataPython |
3203062 | <gh_stars>1-10
from django.urls import path
# from django.urls import include
from . import views
urlpatterns = [
path('index.html',views.index,name='index'),
path('',views.index,name='index'),
] | StarcoderdataPython |
1713365 | <reponame>jaredlwong/sudoku
"""This solution is a simple bfs with grids being copied using np.array"""
from __future__ import annotations
from typing import FrozenSet
from typing import Iterator
from typing import List
from typing import NewType
from typing import Optional
from typing import Tuple
import time
import... | StarcoderdataPython |
1694599 | <reponame>polymathnexus5/solid-rotary-phone<filename>src/decision_tree.py
from sklearn import datasets
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.preprocessing import LabelEncoder
from keras.utils... | StarcoderdataPython |
4823122 | <reponame>peyang-Celeron/ServerTemplate.py<filename>src/utils/token.py
import os
from secrets import token_bytes
from blake3 import blake3
class Token:
def __init__(self, file):
self.file = file
self.token = None
@property
def loaded(self):
if not os.path.exists(self.file):
... | StarcoderdataPython |
3356266 | #!/usr/bin/env python
# encoding: utf-8
# <NAME>, 2008
# <NAME>, 2008 (ita)
import TaskGen
from TaskGen import taskgen, feature
from Constants import *
TaskGen.declare_chain(
name = 'luac',
rule = '${LUAC} -s -o ${TGT} ${SRC}',
ext_in = '.lua',
ext_out = '.luac',
reentrant = False,
install = 'LUADIR', # env var... | StarcoderdataPython |
1741601 | from django.contrib import admin
from .models import Question, Option
admin.site.register(Question)
admin.site.register(Option)
| StarcoderdataPython |
62551 | import torch
import cv2 as cv
import numpy as np
from sklearn.neighbors import NearestNeighbors
from .model_utils import spread_feature
def optimize_image_mask(image_mask, sp_image, nK=4, th=1e-2):
mask_pts = image_mask.reshape(-1)
xyz_pts = sp_image.reshape(-1, 3)
xyz_pts = xyz_pts[mask_pts > 0.5, :]
... | StarcoderdataPython |
18466 | """from django.contrib import admin
from .models import DemoModel
admin.site.register(DemoModel)"""
| StarcoderdataPython |
3387349 | class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
self.result = []
nums.sort()
visited = [False] * len(nums)
self.dfs(nums, [], visited)
return self.result
def dfs(self, nums, cur, visited):
if len(cur) == len(nums):
... | StarcoderdataPython |
178017 | <filename>interfaces/python/test/nodes_test.py
import ell
def test():
print("nodes_test.test -- TBD")
return 0
| StarcoderdataPython |
127208 | <filename>Episode3/exploits/exploit_got.py
#!/usr/bin/env python2
from pwn import *
ip = "192.168.0.13"
port = 22
user = "pi"
pwd = "<PASSWORD>"
libc = ELF('libc-2.24.so')
gadget_offset = 0xed748
shell = ssh(user, ip, password=<PASSWORD>, port=port)
sh = shell.run('/home/pi/arm/episode3/got_overw')
# fill the arr... | StarcoderdataPython |
1706177 | # The MIT License (MIT)
#
# 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 use, copy, modify, me... | StarcoderdataPython |
3248884 | <gh_stars>0
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.4.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import pandas as pd
import numpy as np
... | StarcoderdataPython |
3338805 | import datetime
from apistar import App, Route, exceptions, types, validators
from apistar_jwt.token import JWT, JWTUser
# Fake user database
USERS_DB = {'id': 1, 'email': '<EMAIL>', 'password': 'password'}
class UserData(types.Type):
email = validators.String()
password = validators.String()
def welcome... | StarcoderdataPython |
117571 | <reponame>spiralgenetics/biograph
# pylint: disable=missing-docstring
from __future__ import print_function
import unittest
import biograph
import biograph.variants as bgexvar
def vcf_assembly(pos, ref, alt, asm_id):
pos = int(pos)-1
if ref and alt and ref[0] == alt[0]:
ref = ref[1:]
alt = al... | StarcoderdataPython |
141728 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# ProDy: A Python Package for Protein Dynamics Analysis
#
# Copyright (C) 2010-2012 <NAME>
#
# This program 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 vers... | StarcoderdataPython |
14788 | # -*- coding: utf-8 -*-
'''
:codeauthor: <NAME> <<EMAIL>>
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase
from tests.support.mock import (
... | StarcoderdataPython |
3320835 | <filename>docs/source/conf.py
# -*- coding: utf-8 -*-
import sys
import os
sys.path.insert(0, os.path.abspath('../../'))
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.coverage',
]
templates_path = ['_templates']
source_suffix = '.rst'
source_encoding = 'utf-8-sig'
master_doc ... | StarcoderdataPython |
1631373 | <filename>app/database.py
import logging
import os
from typing import Optional
import sqlalchemy
from slack_sdk.oauth.installation_store import InstallationStore
from slack_sdk.oauth.installation_store.sqlalchemy import SQLAlchemyInstallationStore
from slack_sdk.oauth.state_store.sqlalchemy import SQLAlchemyOAuthState... | StarcoderdataPython |
3337933 | <reponame>adarshd8127/Hacktoberfest-3
import scipy.integrate as spi
def arc_length(f,a,b,h=0.001,N=1000):
'''Approximate the arc length of y=f(x) from x=a to x=b.
Parameters
----------
f : (vectorized) function of one variable
a,b : numbers defining the interval [a,b]
h : step size to use in d... | StarcoderdataPython |
27 | ##########################################################################
#
# Copyright (c) 2010-2012, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redis... | StarcoderdataPython |
111987 | import numpy as np
from numba import njit, prange
# consav
from consav import linear_interp # for linear interpolation
from consav import golden_section_search # for optimization in 1D
# local modules
import utility
# a. define objective function
@njit
def obj_bellman(c,m,interp_w,par):
""" evaluate bellman equ... | StarcoderdataPython |
170126 | <gh_stars>1-10
"""
Plot accuracy:
python analyze_result.py $path_to_MMI $path_to_peek $path_to_random -l MMI peek random
Plot gain over random:
python analyze_result.py $path_to_MMI $path_to_peek $path_to_random -l MMI peek random --gain-over-random
"""
import argparse
import glob
import numpy ... | StarcoderdataPython |
1646434 | <reponame>microsoft/poultry-cafos
"""
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
Script for running an inference script in parallel over a list of inputs.
We split the actual list of filenames we want to run on into NUM_GPUS different batches,
save those batches to file... | StarcoderdataPython |
1640193 | def rotate_to_first_in_deque_and_pop(input_deque, predicate):
"""
Finds the first item in the deque that satisfies the condition by rotating through the deque using popleft().
Faster than doing a sort on the deque.
"""
for _ in xrange(0, len(input_deque)):
item = input_deque.popleft()
... | StarcoderdataPython |
68555 | from abc import ABC, abstractmethod
class AbstractDisplayService(ABC):
@abstractmethod
def accept_items(self, items):
raise Exception("Not implemented.")
@abstractmethod
def stop(self):
raise Exception("Not implemented.")
| StarcoderdataPython |
1716137 | <gh_stars>0
def countWord(filename, word):
line_count = 0
word_count = 0
with open(filename) as f:
content = f.read()
for line in content.splitlines():
found = line.count(word)
if found:
line_count += 1
word_count += found
return (line_... | StarcoderdataPython |
1624910 |
import arcade
import math
from miscellaneous import Misc
import Constants
class Arrow:
def __init__(self, x1, y1, x2, y2, x3, y3, color):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.x3 = x3
self.y3 = y3
self.color = ... | StarcoderdataPython |
3253593 | <reponame>phungj/MSOE_Comp_Prog_Py
import os
file_path = os.path.join(os.path.dirname(__file__), "sanitized_input.txt")
with open(file_path, 'r') as input:
all_lines = input.readlines()
for i in range(len(all_lines)):
all_lines[i] = all_lines[i].strip("\n")
fields = []
field_ranges = []
index = 0
current_li... | StarcoderdataPython |
3268613 | '''
@author: <NAME>
@summary: Test cases to make sure sequential execution and process based concurrent execution return
the same response.
'''
from tests.test_concurrency_base import TestBaseConcurrency
from batch_requests.concurrent.executor import ProcessBasedExecutor
class TestProcessConcurrency(TestBa... | StarcoderdataPython |
1703891 | <filename>models/DeepFill_Models/unfold_test.py
import torch
import numpy as np
in_a = np.arange(16)
in_a = np.resize(in_a, (4,4))
in_tensor = np.expand_dims(in_a, 0)
in_tensor = np.expand_dims(in_tensor, 0)
print("input: ")
print(in_tensor)
in_t = torch.from_numpy(in_tensor)
all_patches = in_t.unfold(2, 2, 1).unfo... | StarcoderdataPython |
3224296 | #!/usr/bin/env python3
import requests, json
domain = input("Enter the hostname http://")
response = requests.get("http://"+domain)
print(response.json)
print("Status code: "+str(response.status_code))
print("Headers response: ")
for header, value in response.headers.items():
print(header, '-->', value)
pri... | StarcoderdataPython |
4834901 | <reponame>Yuanoung/djg-master
#!/usr/bin/env python
import os, sys, traceback
import unittest
import django.contrib as contrib
try:
set
except NameError:
from sets import Set as set # For Python 2.3
CONTRIB_DIR_NAME = 'django.contrib'
MODEL_TESTS_DIR_NAME = 'modeltests'
REGRESSION_TESTS_DIR_NAME = 'reg... | StarcoderdataPython |
1695526 | <gh_stars>1-10
import os
import subprocess
import pytest
from . import util
class Git:
def __init__(self, repo_dir):
super().__init__()
self.repo_dir = repo_dir
self._run_git('init', self.repo_dir)
# If GPG sign is enabled, committing fails because there is no
# GPG ke... | StarcoderdataPython |
3292071 | text = '[ Статистика ]<br>Система:<br> Процессор:<br>'
for idx, cpu in enumerate(psutil.cpu_percent(interval=1, percpu=True)):
text += '  Ядро №'+str(idx+1)+': '+str(cpu)+'%<br>'
text += '  Температура: '+str(int(open('/sys/class/thermal/thermal_zone0/temp','r').read())/1000)+' °С\n'
mem ... | StarcoderdataPython |
3319969 | #!/usr/bin/env python
#
# MagicaVoxel2MinecraftPi
#
from voxel_util import create_voxel, post_to_chat, ply_to_positions, reset_area
from magicavoxel_axis import axis
from all_clear import clear
from time import sleep
# polygon file format exported from MagicaVoxel
ply_files = ['frog1.ply', 'frog2.ply',... | StarcoderdataPython |
3345740 | # coding=utf-8
# Copyright 2021 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | StarcoderdataPython |
9098 | <gh_stars>0
from binance.client import Client
import PySimpleGUI as sg
api_key = "your_binance_apikey"
secret_key = "your_binance_secretkey"
client = Client(api_key=api_key, api_secret=secret_key)
# price
def get_price(coin):
return round(float(client.get_symbol_ticker(symbol=f"{coin}USDT")['price']), 5)... | StarcoderdataPython |
1661142 | <filename>hyades/determine-cluster-center.py<gh_stars>1-10
"""
Determine cluster center with a radius cut as the position
where the postional membership within the radius cut does not change.
- The radius cut should be large enough to contain substantial number of stars
otherwise it will just depend on the statistical... | StarcoderdataPython |
3300241 | #
# Copyright (c) 2021 kumattau
#
# Use of this source code is governed by a MIT License
#
from .greetings import __doc__, __all__, __version__
from .greetings import *
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.