id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
8121810 | <filename>campus_app/migrations/0005_auto_20190706_1912.py
# Generated by Django 2.2.2 on 2019-07-06 22:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('campus_app', '0004_delete_usuario'),
]
operations = [
migrations.AlterField(
... | StarcoderdataPython |
1633041 | # -*- coding: utf-8 -*-
"""
@author: LiuXin
@contact: <EMAIL>
@Created on: DATE{TIME}
"""
from __future__ import print_function, division
import os
from PIL import Image
import numpy as np
import torch
from torch.utils.data import Dataset
from mypath import Path
from torchvision import transforms
from dataloader.transf... | StarcoderdataPython |
3354268 | <filename>temp.py
import numpy as np
import holoviews as hv
import pandas as pd
hv.extension('matplotlib')
# hv.notebook_extension('plotly')
vdata = pd.read_csv("./votingdata.csv")
vdata['log_DiffAdd'] = np.log(vdata.DiffAdd)
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
import random
# pyplot... | StarcoderdataPython |
185554 | <gh_stars>10-100
import theano.tensor as T
from pylearn2.utils import wraps
from pylearn2.models.mlp import Layer
from pylearn2.models.mlp import PretrainedLayer
class PretrainedLayerWeight(PretrainedLayer):
@wraps(Layer.get_weight_decay)
def get_weight_decay(self, coeff):
if isinstance(coeff, str):... | StarcoderdataPython |
6696998 | import rubrik_cdm
rubrik = rubrik_cdm.Connect()
subnets = rubrik.set_esxi_subnets(["192.168.2.10/24","10.255.0.2/16"])
| StarcoderdataPython |
8057453 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Find the global maximum on ackley function
'''
from math import sin, cos, pi, pow, exp
import math
from gaft import GAEngine
from gaft.components import BinaryIndividual
from gaft.components import Population
from gaft.operators import TournamentSelectio... | StarcoderdataPython |
11299118 | <reponame>RenolY2/mkdd-track-editor
import traceback
import os
from time import sleep
from timeit import default_timer
from io import StringIO
from math import sin, cos, atan2, radians, degrees, pi, tan
import json
from OpenGL.GL import *
from OpenGL.GLU import *
from PyQt5.QtGui import QMouseEvent, QWheelEvent, QPai... | StarcoderdataPython |
9653410 | import os
from rich.logging import RichHandler
def configure_logger() -> None:
"""
Configure the loguru configuration with Rich.
:return:
"""
if "LOGURU_LEVEL" not in os.environ:
os.environ["LOGURU_LEVEL"] = "INFO"
from loguru import logger
logger.configure(
handlers=[{"... | StarcoderdataPython |
4968902 | import json
from redata import settings
from redata.grafana.utils import load_json_data, update_home_panel_element
from grafana_api.grafana_face import GrafanaFace
from redata.grafana.panels.base import HomeLastDayTraffic, HomeLastModifiedTime, HomeAlerts
import math
def load_json_data(file_name):
with open(file_n... | StarcoderdataPython |
6432867 | <filename>Python/leetcode.055.jump-game.py
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
x = len(nums)
if x == 0: return False
i = 0
rightb = 0
while i <= rightb:
rightb = max(rightb, nu... | StarcoderdataPython |
11344718 | <reponame>peppocola/Screening-COVID19
import os
import re
import argparse
import pandas as pd
import numpy as np
from tqdm import tqdm
from PIL import Image as pil
if __name__ == '__main__':
# Usage example:
# python covidx/ct/seq_preprocessing.py /hdd/Datasets/covidx-ct/train_COVIDx_CT-2A.txt /hdd/Dataset... | StarcoderdataPython |
12851459 | <reponame>mbodenhamer/yatr
__version__ = '0.0.11b'
from .base import *
from .context import *
from .task import *
from .env import *
from .parse import *
| StarcoderdataPython |
5002450 | <reponame>lucashenrs/acelerapython-codenation<filename>semana-3/test_main.py
from main import get_temperature
import pytest
from unittest.mock import patch
temp_imputs = [
(62, -14.235004, -51.92528, 16),
]
@patch('main.requests.get')
@pytest.mark.parametrize("temp_farenheit_input, lat, lng, \
... | StarcoderdataPython |
4964035 | import functools
import heapq
__all__ = ['iterunion']
def iterunion(concepts, sortkey, next_concepts):
heap = [(sortkey(c), c) for c in concepts]
heapq.heapify(heap)
push = functools.partial(heapq.heappush, heap)
pop = functools.partial(heapq.heappop, heap)
seen = -1
while heap:
in... | StarcoderdataPython |
3297842 | # Copyright (c) 2021 OpenKS Authors, DCD Research Lab, Zhejiang University.
# All Rights Reserved.
import logging
import torch
import torch.nn as nn
from ...model import TorchModel
logger = logging.getLogger(__name__)
@TorchModel.register("question-embedding", "PyTorch")
class QuestionEmbedding(TorchModel):
def __... | StarcoderdataPython |
8158100 | <reponame>m-m-git/transparentwindow
from ctypes import POINTER
from ctypes import WINFUNCTYPE
from ctypes import c_int
from ctypes import c_int64
from ctypes import c_void_p
from ctypes import windll
from ctypes.wintypes import ATOM
from ctypes.wintypes import BOOL
from ctypes.wintypes import DWORD
from ctypes.wintypes... | StarcoderdataPython |
9725177 | WHITESPACE_STR = ' \t\n\r'
def parse_array(s, _w=WHITESPACE_STR, _sep=","):
array = None
stack = []
accumulator = ""
closed_flag = False
sep_flag = False
whitespace_flag = False
started_flag = False
for ch in s:
if ch in _w:
whitespace_flag = True
contin... | StarcoderdataPython |
6551255 | <reponame>dkuspawono/cloudmarker<filename>cloudmarker/test/test_main.py
"""Tests for package execution."""
import unittest
from unittest import mock
class MainTest(unittest.TestCase):
"""Tests for package execution."""
@mock.patch('sys.argv', ['cloudmarker', '-c', '-n'])
def test_main(self):
# ... | StarcoderdataPython |
3413981 | <reponame>jerenner/stempy
import sys
from pathlib import Path
import click
import stempy.io as stio
import stempy.image as stim
@click.command()
@click.option('-i', '--input-path', help='HDF5 file containing the electron counts',
type=click.Path(exists=True, dir_okay=False), default=None, show_default... | StarcoderdataPython |
6691246 | from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, username, password):
if not username:
raise ValueError('User must have a username')
user = self.model(username=username)
... | StarcoderdataPython |
6425222 | <filename>my_games/snake/lib/model/snake.py<gh_stars>0
from lib.model.game_model_list import GameModelList
# game snake for holding block game objects
# - manages block color draw
# - manages block collidable property
# - manages additions and removals of game blocks (simulate snake movement)
class Snake(GameMod... | StarcoderdataPython |
1977161 | <filename>madelon/main.py<gh_stars>10-100
# python spearmint_sync.py --method=GPEIOptChooser madelon_sofia_vw_rbf
import sys, subprocess, re, os
from math import exp
def get_validation_loss( data ):
pattern = 'error: ([0-9.]+)'
matches = re.search( pattern, data )
validation_loss = float( matches.group( 1 ))
ret... | StarcoderdataPython |
3373279 | import sys
from pysam import VariantFile
def main():
vcfpath = sys.argv[1]
vcf = VariantFile(vcfpath)
print('\n'.join(str(vcf.header).split('\n'))[:-1])
hgnones = {0: 0, 1: 0, 2: 0}
nanones = {0: 0, 1: 0, 2: 0}
for record in vcf.fetch():
hg1, hg2 = record.samples["HG00733"]["GT"]
... | StarcoderdataPython |
1683383 | <reponame>CharleeSF/brian2
"""
<NAME> (2013). Sharpness of spike initiation in neurons explained by compartmentalization.
PLoS Comp Biol, doi: 10.1371/journal.pcbi.1003338.
Fig. 3C-F. Kink with Nav1.6 and Nav1.2
"""
from brian2 import *
from params import *
defaultclock.dt = 0.01*ms
# Morphology
morpho = Soma(50*um)... | StarcoderdataPython |
226436 | <filename>Aeneas/aeneas/aeneas/ttswrappers/espeakngttswrapper.py
#!/usr/bin/env python
# coding=utf-8
# aeneas is a Python/C library and a set of tools
# to automagically synchronize audio and text (aka forced alignment)
#
# Copyright (C) 2012-2013, <NAME> (www.albertopettarin.it)
# Copyright (C) 2013-2015, ReadBeyond... | StarcoderdataPython |
1985324 | #!/usr/bin/env python3
import numpy as np
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, GlobalAveragePooling2D, Flatten, Dropout
from keras.layers.merge import concatenate
from keras.models import Model
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, TensorBoard
# import t... | StarcoderdataPython |
3364112 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: Alfons
@contact: <EMAIL>
@file: 07-04-singledispatch.py
@time: 18-2-28 下午8:40
@version: v1.0
"""
from functools import singledispatch
import html
# 单分派泛函数,实现重载
@singledispatch
def htmlize(obj):
content = html.escape(repr(obj))
return "<pre>%s</pre>" % cont... | StarcoderdataPython |
9741660 | # firmware to play back TASes at high speed by just streaming in latches.
# includes APU frequency adjustments too.
# notational notes:
# boneless is a word-based architecture, it has no concept of the 8 bit byte.
# but we do, so we have to define what a word means.
# * a "word" is a 16 bit unsigned integer, transmitt... | StarcoderdataPython |
4881385 | # Copyright © 2019 Province of British Columbia
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | StarcoderdataPython |
1884439 |
#Loop Through a List
#You can loop through the list items by using a for loop:
#Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
thislist = [1, 2, 3]
for x in thislist:
print(x)
#Learn more about for loops in our Python For Loops Chapter.
#Loop T... | StarcoderdataPython |
1832825 | import torch
import torch.nn as nn
import torch.nn.parallel
from miscc.config import cfg
from torch.autograd import Variable
def conv3_1d(in_planes, out_planes, stride=1, padding=False):
"3 convolution without padding"
return nn.Conv1d(in_planes, out_planes, kernel_size=3, stride=stride,
p... | StarcoderdataPython |
6509776 | # Custom Bot Message by @Hageru-Ray
from discord.ext import commands
import discord
class Say(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@commands.cooldown(1, 30, commands.BucketType.user)
async def say(self, ctx, *, message):
embed = discord.... | StarcoderdataPython |
3231325 | <reponame>JohnKarima/hood<filename>hoodapp/migrations/0008_auto_20201031_1609.py
# Generated by Django 3.1.2 on 2020-10-31 16:09
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('hoodapp', '0007_auto_20201031_1459'),
]... | StarcoderdataPython |
9624029 | <filename>solution/input_module.py
'''
InputModule
Contains the necessary code to process the user
input
Author: <NAME>
'''
valid_characters = [
'*', # Space
'#' # Wall
]
class InputModule:
'''
InputModule class that is going to contain
the method to process an input
'''
def is_valid(se... | StarcoderdataPython |
6541428 | <reponame>rohitsinha54/Learning-Python
#!/usr/bin/env python
"""selectionsort.py: Program to implement selection sort"""
__author__ = '<NAME>'
def selection_sort(alist):
for i in range(len(alist) - 1, 0, -1):
max_position = 0
for j in range(1, i+1):
if alist[j] > alist[max_position]:... | StarcoderdataPython |
3439810 | <reponame>google/vizier
"""Tests for vizier.pyvizier.oss.metadata_util."""
from vizier._src.pyvizier.oss import metadata_util
from vizier.service import study_pb2
from absl.testing import absltest
class MetadataUtilTest(absltest.TestCase):
def test_get(self):
meta_trial = study_pb2.Trial(id='meta_trial')
... | StarcoderdataPython |
4895350 | # Copyright 2015, Aiven, https://aiven.io/
#
# This file is under the Apache License, Version 2.0.
# See the file `LICENSE` for details.
from . import journalpump
journalpump.JournalPump.run_exit()
| StarcoderdataPython |
160324 | <gh_stars>1-10
import datetime
class ParamCheck():
"""
パラメータチェックを実施するクラス。
"""
def __init__(self):
"""
初期化を実施する。
"""
pass
def check_required(self, columns, column_name):
"""
必須チェックを実施する。
Parameters
----------
... | StarcoderdataPython |
8080088 | """
In this Bite we'd like you to loop over the characters in the large
block of text (the most important text for any Python programmer:
The Zen of Python!)
Within this loop you'll perform the following actions:
Replace all vowels (aeiou) with stars (*), do this case insensitively.
Count the number of replacements... | StarcoderdataPython |
5199669 | <filename>modulestf/render.py
import glob
import json
import os
import re
import shutil
from pprint import pformat, pprint
from cookiecutter.exceptions import NonTemplatedInputDirException
from cookiecutter.main import cookiecutter
from modulestf.const import *
from modulestf.logger import setup_logging
from modulestf... | StarcoderdataPython |
321655 | # Requires python3 to work since, python 3< does not implement %z.
import sys
import os
import json
from datetime import datetime
import pytz
from subprocess import Popen, PIPE, STDOUT
class Version(object):
def __init__(self, version):
v = version
if v.startswith('v'):
v = v[1:].spli... | StarcoderdataPython |
5133782 | <reponame>jsevo/taxumap
# Authors: <NAME> <<EMAIL>>, <NAME> <<EMAIL>>
# License: MIT
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="taxumap",
version="0.1",
description="UMAP visualization for microbiota compositions with taxonomic structure."... | StarcoderdataPython |
5098934 | <reponame>LiYuzhu12138/3D-DART-server
#!/usr/bin/env python2.7
USAGE = """
==========================================================================================
Author: <NAME>, Department of NMR spectroscopy, Bijvoet Center
for Biomolecular Research, Utrecht university, The Netherlands
Copyright (C): 20... | StarcoderdataPython |
1893148 | """
Abstract Class for using datatables package with server side processing option in Django project.
"""
from .utils.data_type_ensure import ensure
from .utils.enum import TripleEnum
from collections import OrderedDict, defaultdict
from typing import (
Tuple, Any, Dict
)
from rest_framework.serializers import Mode... | StarcoderdataPython |
1989910 | <gh_stars>0
import numpy as np
class TrainTestSplitter:
def __init__(self, data_dict, user_ratings_count_threshold, percent):
self.books = data_dict['books']
self.users = data_dict['users']
self.ratings = data_dict['ratings']
self.user_ratings_count_threshold = user_ratings_count... | StarcoderdataPython |
3210380 | import numpy as np
import pandas as pd
from datetime import date
import os
print("Reading clean data")
data = pd.read_csv('../clean/all_clean_data.csv', encoding='utf-8', dtype=str)
if not os.path.exists('../clean/macro'):
os.mkdir('../clean/macro')
def update_visa_class(x):
if pd.to_datetime(x).year<2007:
... | StarcoderdataPython |
5167690 | <filename>Adobe_CSV.py
import sys
import argparse
import csv
#TODO
#@V1.1
#@Date 2/13/2020
#@Author mlizbeth
#sort/diff switches?
file_headers = ["Identity Type", "Username", "Domain", "Email", "First Name", "Last Name", "Country Code", "Product Configurations", "Admin Roles", "Product Configurations Administered",
... | StarcoderdataPython |
6519152 | """
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
"""
# Definiti... | StarcoderdataPython |
11244810 | <gh_stars>100-1000
import torch
import torch.utils.data as data
import numpy as np
import os
import sys
import subprocess
import shlex
import pickle
from .data_utils import grid_subsampling
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
def pc_normalize(pc):
# Center a... | StarcoderdataPython |
11361694 | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
a=[]
x={}
for i in set(words):
x[i]=words.count(i)
a = sorted(x, key=lambda i: (-x[i], i))
return a[:k]
| StarcoderdataPython |
4994270 | from crawler.crawler import get_recursive_urls
from data.collect import collect_data
import argparse
from urllib.parse import urlparse
import json
from subprocess import Popen
from utils.utils import eprint, add_auth, dsum, dstd
import os
def get_domain(url):
parsed = urlparse(url)
return parsed.scheme + '://... | StarcoderdataPython |
3500702 | """Utility stuff that fitted nowhere else."""
from .dict2arr import (
dict2arr,
dict2arrlabels,
io_dict2arr,
)
from .read_sample import (
read_sample,
)
from .event_ixs import (
EventIxs,
)
from .par_trafo import (
ParTrafoBase,
ParTrafo,
)
from .log import (
log_samples,
)
| StarcoderdataPython |
3549693 |
from jk_hwriter import HWriter
from .htmlgeneral import *
class HTMLRawText(object):
def __init__(self, textOrTextList):
if isinstance(textOrTextList, str):
self.texts1 = [ textOrTextList ]
else:
self.texts1 = list(textOrTextList)
self.texts2 = []
#
def __call__(self, **attrs):
self.texts1.app... | StarcoderdataPython |
6640492 | <reponame>Harald-R/aw_nas
import torch
import torch.nn.functional as F
from aw_nas.objective.detection_utils.base import Losses
from aw_nas.utils import box_utils, getLogger
__all__ = ["MultiBoxLoss", "FocalLoss"]
class MultiBoxLoss(Losses):
NAME = "multibox_loss"
"""SSD Weighted Loss Function
Objectiv... | StarcoderdataPython |
8017213 | import os, random, json
import numpy as np
from scipy import stats
import util
SEQ_SIZE = 8
NUM_TO_GEN = 20
MODEL_DIR = 'trained_all/'
PARSED_DIR = 'parsed_all/'
MAKE_STATEFUL = False
IS_REVERSE = True
#Load titles
title_words, title_word_to_ix = util.load_title_dict(PARSED_DIR)
title_dict_size = len(title_words)
tit... | StarcoderdataPython |
11212754 | <reponame>KayanOkagawa/Cursoemvideo-Python3-Exercicios
def interface(conect):
from time import sleep
while True:
print('-=' * 20)
print('MENU PRINCIPAL')
print('-=' * 20)
print("""
1 - Lista Usuarios;
2 - Cadastra Usuarios;
3 - Sair
""")
print('-=' * 20)
... | StarcoderdataPython |
11206506 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 27 22:12:24 2021
@author: leonl42
print useful statistics about the data
"""
import numpy as np
import matplotlib as plt
from scripts.util import get_freq_dist, PANDAS_DTYPE,COLUMN_LABEL,COLUMN_HASHTAGS, COLUMN_TIMEDELTAS,SUFFIX_POST,COLUMN_TWEET... | StarcoderdataPython |
5073301 | <filename>NumpyTutorial/Questions on Numpy Indexing.py
import numpy as np
#Questions on NumPy Indexing
#Replace NumPy array elements that doesn’t satisfy the given condition
#where Return elements chosen from x or y depending on condition.
x = np.array([[45.42436315, 52.48558583, 10.32924763],
[5.74... | StarcoderdataPython |
6480949 | from flask import Blueprint
from .views import ComputeSimilarityAPI, IndexContributionAPI, SetupSimilarityAPI
similarity_blueprint = Blueprint("similarity", __name__)
similarity_blueprint.add_url_rule('/similar/<contribution_id>/',
view_func=ComputeSimilarityAPI.as_view('compute_simi... | StarcoderdataPython |
33715 | import dingus.codec
import utils
import transaction
class BlockHeader(object):
VERSION = 0
def __init__(
self,
) -> None:
raise NotImplementedError
class Block(object):
VERSION = 0
def __init__(
self,
header: BlockHeader,
payload: list[transaction.Trans... | StarcoderdataPython |
4843673 | import heapq
import os
from typing import List, TypeVar
import numpy as np
_GridItem = TypeVar('_GridItem')
def tile(
h: int,
w: int,
sub_grids: List[List[List[_GridItem]]]
) -> List[List[_GridItem]]:
tiled_grid: List[List[_GridItem]] = []
for _ in range(h):
tile_row = sub_grids[:w]
... | StarcoderdataPython |
6524312 | from rest_framework.permissions import BasePermission
from .models import Itemlist
class IsOwner(BasePermission):
"""Custom permission class to allow itemlist owners to edit them."""
def has_object_permission(self, request, view, obj):
"""Return True if permission is granted to the itemlist owner."""... | StarcoderdataPython |
1981738 | <reponame>terminalkitten/pdfmate<gh_stars>1-10
# -*- coding: utf-8 -*-
import asyncio
import io
import re
from tempfile import NamedTemporaryFile
from typing import BinaryIO, Dict, NoReturn, Union
from PyPDF2 import PdfFileMerger
from pyppeteer import errors, launch
from .configuration import DEFAULT_CONFIG
from .err... | StarcoderdataPython |
374019 | <gh_stars>0
# coding=utf-8
import json
import requests
from globalvars import GlobalVars
import threading
# noinspection PyPackageRequirements
import websocket
from collections import Iterable
from datetime import datetime, timedelta
from glob import glob
import sys
import traceback
import time
import os
import datahan... | StarcoderdataPython |
1759485 | # -*- coding: utf-8 -*-
import sqlite3
import argparse
from urllib.request import Request, urlopen
import csv
import re
import xml.etree.ElementTree as ET
from typing import List, Dict
import collections
import json
# BLASTの結果のtextファイル名をパラメータから取得
# $ python m2o.py <file path> のようにBLASTのformat 6 outputファイルを引数にしてスクリプトを... | StarcoderdataPython |
7222 | <gh_stars>1-10
from seeker.models import Building, Classroom, Time
import json
import os
os.chdir('../data')
fileList = os.listdir()
#loops through each json file
for jsonfile in fileList:
#opens the jsonfile and loads the data
f = open(jsonfile, 'r')
data = f.read()
jsondata = json.loads(data)
#c... | StarcoderdataPython |
6415826 | <gh_stars>10-100
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth import get_user_model
from django.test import TestCase
from comment.models import Comment
from blog.models import Blog
# Create your tests here.
class CommentTest(TestCase):
def setUp(self) -> None:
sel... | StarcoderdataPython |
9765447 | <reponame>K-Mike/ml_package
# -*- coding: utf-8 -*-
from __future__ import print_function
from ._version import get_versions
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__version__ = get_versions()['version']
del get_versions
# Project from http://confusable-homoglyphs.readthedocs.io/en/latest/apidocumentation.html
#... | StarcoderdataPython |
6567205 | <reponame>nickerso/opencmiss-libcellml<gh_stars>1-10
import os
from omniidl import idlvisitor, output, idlast
import jnutils
import string
class NativeStubVisitor (idlvisitor.AstVisitor):
def __init__(self):
self.mangleParts = ['Java', 'pjm2pcm']
self.inameParts = []
self.mangled = ''
... | StarcoderdataPython |
1983755 | from collections import deque
price_per_bullet = int(input())
barrel_size = int(input())
bull = list(map(int, input().split()))
bullets = deque(bull[::-1])
locks = deque(list(map(int, input().split())))
intelligence_value = int(input())
total_money = 0
local_barrel = int(barrel_size)
while bullets and locks:
c... | StarcoderdataPython |
3363362 | #############
## SETUP ##
#############
import itertools
def setup(file):
with open(file) as f:
data = [int(val) for val in f.read().splitlines()]
return data
class RollingSum:
def __init__(self, start):
self._values = start
self._sums = [None] * (len(start) - 1)
for i in... | StarcoderdataPython |
3545005 | <reponame>elifesciences/elife-bot
import unittest
from mock import mock, patch
import activity.activity_ScheduleDownstream as activity_module
from activity.activity_ScheduleDownstream import (
activity_ScheduleDownstream as activity_object,
)
from provider import article, lax_provider
import tests.activity.settings... | StarcoderdataPython |
4835260 | <reponame>Rafilek/backend-app-api-one<filename>app/app/calc.py
def add(x, y):
""" test function """
return x + y
| StarcoderdataPython |
4981640 | from .create_package import CreatePackage | StarcoderdataPython |
6490765 | <filename>Opt_DM_GUI5.py
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 27 14:29:46 2019
@author: 028375
"""
from __future__ import unicode_literals, division
try:
import tkinter as tk
import tkinter.messagebox as msbox
except ImportError:
import Tkinter as tk
import tkMessageBox as msbox
impor... | StarcoderdataPython |
5061676 | <filename>src/client/pytriloquist/gui/app.py
import appuifw as ui
from pytriloquist import Const
from pytriloquist.btclient import BluetoothError
from pytriloquist.gui import Dialog
class ApplicationsDialog(Dialog):
"""
Dialog used to manage applications.
"""
def __init__(self, app, parent):
... | StarcoderdataPython |
53396 | <filename>transformer/__init__.py
import transformer.Beam
import transformer.Constants
import transformer.Layers
import transformer.Models
import transformer.Modules
import transformer.Optim
import transformer.SubLayers
import transformer.Translator
__all__ = [
transformer.Constants, transformer.Modules, transform... | StarcoderdataPython |
11270552 | <reponame>cherry-wb/googleads-python-lib
#!/usr/bin/python
#
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/l... | StarcoderdataPython |
3440154 | <reponame>neelkarma/xkcd-cli
from .cli.main import main
main()
| StarcoderdataPython |
5050313 | <filename>config.py
import os
import sys
class Env:
_errors = []
@staticmethod
def get_errors():
return Env._errors
@staticmethod
def _get_default(env, default, required):
if required:
Env._errors.append("'$" + env + "' is not defined in the environment variables!")
... | StarcoderdataPython |
4871976 | import json
import os
import re
from typing import Any, Dict, Optional
import pandas as pd
from pandas import DataFrame
import geopandas as gpd
from network_wrangler import ProjectCard
from network_wrangler import RoadwayNetwork
from .transit import CubeTransit, StandardTransit
from .logger import WranglerLogger
fro... | StarcoderdataPython |
1736480 | <reponame>Mehi335/testreport.py
# Imports all (*) classes,
# atributes, and methods of tkinter into the
# current workspace
import tkinter as tk
#import tkinter.messagebox as messagebox
def il_get_value():
# ***********************************
# Creates an instance of the class tkinter.Tk.
# This creates ... | StarcoderdataPython |
212132 | from enum import Enum
from typing import Optional, Union, Dict, Any, List
try:
from typing_extensions import TypedDict
except ImportError:
from typing import TypedDict
class HttpCredentials(TypedDict):
username: str
password: str
class _GeoCoordinated(TypedDict):
longitude: float
latitude:... | StarcoderdataPython |
3511827 | <reponame>playbase/DDOS-Attack<filename>web-app/app.py
import pandas as pd
from flask import Flask, request, jsonify, render_template
import joblib
app = Flask(__name__)
model = joblib.load(open('model.pkl', 'rb'))
@app.route('/')
def home():
return render_template('index.html')
@app.route('/predict... | StarcoderdataPython |
100762 | <gh_stars>1-10
from Callable import Callable
from Environment import Environment
class FunctionCallable(Callable):
def __init__(self, declaration):
self.declaration = declaration
def arity(self):
return len(self.declaration.params)
def call(self, interpreter, arguments):
environme... | StarcoderdataPython |
4874829 | from __future__ import annotations
class ExperimentConflictError(Exception):
"""experiment conflict error"""
class ExperimentNotFoundError(Exception):
"""experiment not found error"""
class WorkerNotFoundError(Exception):
"""worker not found error"""
class GitError(Exception):
"""git error"""
... | StarcoderdataPython |
305342 | <reponame>LaudateCorpus1/labmanager-unit-vsphere<gh_stars>1-10
from web.settings import Settings as settings
import asyncio
import logging
import sys
import datetime
import time
import base64
import hashlib
from sanic.response import json as sanicjson
import ldap
logger = logging.getLogger()
def get_ldap_connection(... | StarcoderdataPython |
6443765 | # -*- coding: utf-8 -*-
import unittest
from lunar_python import SolarSeason
class SolarSeasonTest(unittest.TestCase):
def test(self):
season = SolarSeason.fromYm(2019, 5)
self.assertEqual("2019.2", season.toString())
self.assertEqual("2019年2季度", season.toFullString())
self.assert... | StarcoderdataPython |
4999849 | <filename>pvlib/tools.py
"""
Collection of functions used in pvlib_python
"""
import datetime as dt
import numpy as np
import pandas as pd
import pytz
import warnings
def cosd(angle):
"""
Cosine with angle input in degrees
Parameters
----------
angle : float or array-like
Angle in degree... | StarcoderdataPython |
4993945 | import sys, os,pathlib
current_file_path = pathlib.Path(__file__).parent.absolute()
sys.path.insert(1,'/Users/matin/Downloads/testProjs/RTvisalize')
from realtime import monitor
settings = {
"Cell count": {
"graph_dir" : "cell_count.csv",
"graph_type" : 'lines',
"graph_size" : 8... | StarcoderdataPython |
1727220 | <reponame>pedrodaniel10/ALC
#!/usr/bin/env python3
# File: chk.py
# Author: mikolas
# Created on: Fri Oct 11 14:18:32 WEST 2019
# Copyright (C) 2019, <NAME>
import sys
def err(msg):
print("ERROR:", msg)
exit(1)
def parse_samples(f):
nms = None
samples = []
for l in f:
s = l.rstrip().spli... | StarcoderdataPython |
8169738 | from __future__ import division
import os
import cv2
import numpy as np
import pickle
import time
from kentaroy47.config import Config as config
from keras import backend as K
from keras.layers import Input
from keras.models import Model
import kentaroy47.roi_helpers as roi_helpers
import argparse
import os
import kent... | StarcoderdataPython |
1627851 | <reponame>ShinyShoes12/1_ImgClassfication
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
"""This script is for users having colab pro ver.
If you are colab free user, execute untill NOTICE HERE ~ index and go to other script."""
# # 1) **Preparing Datas**
#
#
#
# ## Check out : Gpu/Ram
# In[ ]:
## 할당된 GPU ... | StarcoderdataPython |
6638554 | <filename>src/export_excel.py
# -*- coding: utf-8 -*-
import json
import os
import re
import sys
from datetime import datetime, date
from decimal import Decimal
from getopt import getopt, GetoptError
from openpyxl import Workbook, load_workbook
from openpyxl.styles import PatternFill, Font
from openpyxl.utils import ... | StarcoderdataPython |
1639691 | #!/usr/bin/env python
from __future__ import print_function
import re
import argparse
import logging
from xigt.codecs import xigtxml
from xigt import XigtCorpus, Igt, xigtpath as xp
def run(args):
xc = xigtxml.load(args.infile)
if args.igt_key:
logging.info('Sorting %s IGTs' % args.infile)
xc... | StarcoderdataPython |
133604 | # -*- coding: utf-8 -*-
"""
Conversion between Dialog-2010 (http://ru-eval.ru/) and aot.ru tags.
Dialog-2010 tags are less detailed than aot tags so aot -> dialog2010
conversion discards information.
"""
from __future__ import absolute_import, unicode_literals
import itertools
from russian_tagsets import converters
fr... | StarcoderdataPython |
4836573 | <gh_stars>1-10
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module implements various transmuter classes.
Transmuters are essentially classes that generate TransformedStructures from
various data sources. They enable the high-throughput generati... | StarcoderdataPython |
6427456 | #!/usr/bin/env python
# coding=utf-8
from handlers.kbeServer.Editor.Interface import interface_res
def ResVersionResponse(DB, subCode, uid, data):
if subCode == 10:
return interface_res.GetUpdateVersion(DB,uid, data)
elif subCode == 11:
return interface_res.AnlyzeCode(DB,uid, data)
elif s... | StarcoderdataPython |
12803868 | import logging
import os
from dockerfile_parse.constants import DOCKERFILE_FILENAME
from checkov.common.output.record import Record
from checkov.common.output.report import Report
from checkov.common.runners.base_runner import BaseRunner, filter_ignored_directories
from checkov.dockerfile.parser import parse, collect_... | StarcoderdataPython |
1647737 | # Copyright 2020 The Trieste Contributors
#
# 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.