id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3303651 | <filename>pavement.py<gh_stars>1-10
from collections import OrderedDict
import sys
from importlib import import_module
from paver.easy import task, needs, path, sh, cmdopts, options
from paver.setuputils import setup, find_package_data, install_distutils_tasks
try:
from base_node_rpc.pavement_base import *
except ... | StarcoderdataPython |
4806192 | from .builder import (
PromtailBuilder
)
from .option import (
PromtailOptions
)
from .configfile import (
PromtailConfigFileOptions,
PromtailConfigFile,
)
from .configfileext import (
PromtailConfigFileExt_Kubernetes,
)
__version__ = "0.8.0"
__all__ = [
'PromtailOptions',
'PromtailBuilder... | StarcoderdataPython |
14609 | <gh_stars>0
import math as ma
# note all sizes in m^2
# all costs in pounds
def get_details():
return {'w': get_value("Width:", float),
'h': get_value("Height:", float),
'cost': get_value("Cost per tile:", float),}
def get_value(text = "enter_val", expected_type = None):
while True:... | StarcoderdataPython |
10446 | #!/usr/bin/env python
try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
setup(name='genderizer',
version='0.1.2.3',
license='MIT',
description='Genderizer tries to infer gender information looking at first name and/or making text analysis',
lo... | StarcoderdataPython |
3396369 | # Merge Sorted Array
# You are given two integer arrays nums1 and nums2, sorted in non-decreasing order,
# and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
# Merge nums1 and nums2 into a single array sorted in non-decreasing order.
# The final sorted array should not be ... | StarcoderdataPython |
4837615 | <reponame>jdelrue/digital_me
from jumpscale import j
import inspect
# import imp
import sys
import os
from .GedisCmd import GedisCmd
JSBASE = j.application.jsbase_get_class()
class GedisCmds(JSBASE):
"""
all commands captured in a capnp object, which can be stored in redis or any other keyvaluestor
"""
... | StarcoderdataPython |
130290 | from linode_api4.errors import UnexpectedResponseError
from linode_api4.objects import Base, Property
class AuthorizedApp(Base):
api_endpoint = "/profile/apps/{id}"
properties = {
"id": Property(identifier=True),
"scopes": Property(),
"label": Property(),
"created": Property(i... | StarcoderdataPython |
1724977 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
from warnings import warn
from iminuit.iminuit_warnings import InitialParamWarning
from iminuit import util as mutil
import numpy as np
def pedantic(self, parameters, kwds, errordef):
def w(msg):
w... | StarcoderdataPython |
1782975 | import sys
sys.path.append('.')
import cfg
import async_session
while True:
sess = async_session.AsyncSession(cfg.timeout_read)
sess.open_session()
with sess.clone_session(community='woho') as priv_sess:
to_set = {
async_session.oid_str_to_tuple('1.3.6.1.2.1.1.6.0'): ('f', 's')
... | StarcoderdataPython |
1711989 | """Controls digital outputs added with a 74HC595 shift register.
Description
-----------
A CircuitPython program that interfaces a 74HC595 serial-in parallel-out shift
register IC to add digital outputs to a CircuitPython compatible board.
Circuit
-------
- A 74HC595 shift register IC is connected to the board's SP... | StarcoderdataPython |
3374325 | #!/usr/bin/python
import argparse
from book import Book
# parse some input params
# $booklog <title>: show status of book (if book exists or not, show similar titles to fix misspell)
# -h, --help: show help info
# -n, --note <title>: Edit book notes
# -a, --author <firstname lastname>: author name
# -i, --isbn <numb... | StarcoderdataPython |
1773150 | <reponame>abdessamad14/zellij
"""
Test euclid.py
"""
import itertools
import math
from hypothesis import assume, given
from hypothesis.strategies import lists, integers
import pytest
from zellij.euclid import (
Line, Point, Segment, Bounds, EmptyBounds,
along_the_way, collinear, line_collinear,
Coinciden... | StarcoderdataPython |
3341945 |
from bcg.run_BCG import BCG
from bcg.model_init import Model
import autograd.numpy as np
class Model_l1_ball(Model):
def minimize(self, gradient_at_x=None):
result = np.zeros(self.dimension)
if gradient_at_x is None:
result[0] = 1
else:
i = np.argmax(np.abs(gradie... | StarcoderdataPython |
3397826 | <filename>server/__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import registry
from sqlalchemy.ext.automap import automap_base
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail
from server.config import Config
db = SQLAlch... | StarcoderdataPython |
192407 | import pytest
@pytest.mark.parametrize(
"server_options,port",
[("--debug", 8090), ("--debug --mathjax", 8090), ("--debug", 9090)],
)
@pytest.mark.parametrize("method", ["curl", "stdin"])
def test_math(browser, Server, server_options, port, method):
with Server(server_options, port) as srv:
srv.s... | StarcoderdataPython |
3303981 | # -*- coding: utf-8 -*-
"""
Copyright 2017-2018 <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 ... | StarcoderdataPython |
1740220 | <gh_stars>1000+
# encoding: utf-8
"""
srcap.py
Created by <NAME>
Copyright (c) 2014-2017 Exa Networks. All rights reserved.
"""
from struct import unpack
from exabgp.util import split
from exabgp.bgp.message.update.attribute.bgpls.linkstate import LinkState
from exabgp.bgp.message.update.attribute.bgpls.linkstate i... | StarcoderdataPython |
1635406 | # -*- coding: utf-8 -*-
# @Time : 2018/6/7 下午5:22
# @Author : waitWalker
# @Email : <EMAIL>
# @File : MTTDataBase.py
# @Software: PyCharm
# 数据连接
import pymysql
import time
class MTTDataBase:
error_code = ''
instance = None
# db = None
# cursor = None
timeout = 30
time_count = 0
... | StarcoderdataPython |
3328104 | import json
import requests
from data import *
from url import Url
for url_to_check in urls_to_check:
for i, url in enumerate( url_to_check['urls'] ):
print(url)
for j, child in enumerate( Url(url).get_children() ):
print(f'{i}.{j} - Checking {child}')
i... | StarcoderdataPython |
926 | <gh_stars>0
"""
Enumerator Test
"""
from typing import Any
class is_valid_enum():
"""
Test if a variable is on a list of valid values
"""
__slots__ = ('symbols')
def __init__(self, **kwargs):
"""
-> "type": "enum", "symbols": ["up", "down"]
symbols: list of allowed values ... | StarcoderdataPython |
1683174 | <reponame>jamesramsay100/Fantasy-Premier-League<filename>global_scraper.py
from parsers import *
from cleaners import *
from getters import *
from collector import collect_gw, merge_gw
from understat import parse_epl_data
def parse_data():
""" Parse and store all the data
"""
print("Getting data")
data... | StarcoderdataPython |
72381 | import csv
import math
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import numpy as np
# read the data
csvfile=open("weightedX.csv", 'r')
x = list(csv.reader(csvfile))
csvfile=open("weightedY.csv", 'r')
y = list(csv.reader(csvfile))
m=len(x)
n=1
x3=[]
y2=[]
for i in range(m):
... | StarcoderdataPython |
76585 | """Pareto tail indices plot."""
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba_array
import matplotlib.cm as cm
import numpy as np
from xarray import DataArray
from .plot_utils import (
_scale_fig_size,
get_coords,
color_from_dim,
format_coords_as_labels,
get_plotting_functio... | StarcoderdataPython |
30014 | # Generated by Django 3.0.11 on 2021-01-01 16:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("bpp", "0231_ukryj_status_korekty"),
]
operations = [
migrations.AlterField(
model_name="autor",
name="pseudonim",
... | StarcoderdataPython |
4825466 | <gh_stars>0
"""
.. See the NOTICE file distributed with this work for additional information
regarding copyright ownership.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http:/... | StarcoderdataPython |
1717284 | import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
imge = cv2.VideoCapture(0)
while True:
ret,img = imge.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.... | StarcoderdataPython |
1697281 |
#__________________ Script Python - versão 3.8 _____________________#
# Autor |> <NAME>
# Data |> 05 de Março de 2021
# Paradigma |> Orientado à objetos
# Objetivo |> Interação com usuário, input.
#___________________________________________________________________#
class ReceberNumero:
__num = None
def... | StarcoderdataPython |
3341849 | <gh_stars>0
import sys
def part1(numbers):
blocks = list(numbers)
seenConfigurations = []
iterationcnt = 1
while True:
nextSplitIdx = blocks.index(max(blocks))
banksize = blocks[nextSplitIdx]
blocks[nextSplitIdx] = 0
nextBlock = nextSplitIdx + 1
while banksize > ... | StarcoderdataPython |
3321359 | def is_zero(a):
return all(i == 0 for i in a)
def dot(a, b):
assert len(a) == len(b)
return sum(a[i] * b[i] for i in range(len(a)))
def cross(a, b):
return [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]]
def neg(a):
return [-i for i in a]
def scale(a, n):
return [n ... | StarcoderdataPython |
3312950 | import torch
import torch.nn.functional as F
from torch import nn, optim
from torchvision import models
from utils import get_upsampling_weight
from collections import OrderedDict
class FCN32VGG(nn.Module):
def __init__(self, num_classes=21, pretrained=False):
super(FCN32VGG, self).__init__()
vgg =... | StarcoderdataPython |
1623432 | <reponame>tacosync/skcomws
'''
Socket.IO server for testing
CLI:
python -m watchgod server.main [aiohttp|sanic|tornado|asgi]
Test results:
| connect | disconnect | event | background_task | Ctrl+C
---------+---------+------------+-------+-----------------|--------
aiohttp | O | O ... | StarcoderdataPython |
3302638 | <reponame>steffgrez/fast-jsonrpc
from fast_jsonrpc2.resolver import JSONRPCResolver
from fast_jsonrpc2.version import __version__
| StarcoderdataPython |
1652654 | """Constants for the Todoist component."""
CONF_EXTRA_PROJECTS = "custom_projects"
CONF_PROJECT_DUE_DATE = "due_date_days"
CONF_PROJECT_LABEL_WHITELIST = "labels"
CONF_PROJECT_WHITELIST = "include_projects"
# Calendar Platform: Does this calendar event last all day?
ALL_DAY = "all_day"
# Attribute: All tasks in this p... | StarcoderdataPython |
1799461 | # importing testing framwork
import pytest
# library used to check working virtual environment
import importlib
# importing objects from the jupyter notebook here
from ipynb.fs.full.index import # variable names go here
# format for writing tests
# all functions that are to be run by test suite *must* be prepended wi... | StarcoderdataPython |
1725279 | class Solution:
def maxAncestorDiff(self, root: TreeNode, ancestors = []) -> int:
if root == None:
return 0
curr = 0
if ancestors:
curr = max(abs(root.val - max(ancestors)), abs(root.val - min(ancestors)))
ancestors.append(root.val)
l... | StarcoderdataPython |
153031 | <gh_stars>100-1000
"""
train the XGB_HMM model, return A, B(XGB model), pi
"""
import numpy as np
from XGB_HMM.GMM_HMM import GMM_HMM
from XGB_HMM.re_estimate import re_estimate
from XGB_HMM.predict import self_pred
from XGB_HMM.xgb import self_xgb
def XGB_HMM(O, lengths, verbose=True):
n_states ... | StarcoderdataPython |
4805908 | <reponame>shwnchpl/abrv
import os
from getpass import getuser
from flask import Flask
from . import db
from . import url
def create_app(test_config=None):
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE={
'database': 'abrv... | StarcoderdataPython |
1629945 | import sys
#output and error redirection
sys.stdout = open("./stdout.txt","w+b",0)
sys.stderr = open("./stderr.txt","w+b",0)
import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from... | StarcoderdataPython |
3301408 | <reponame>pdiroot/checkov
from __future__ import annotations
from typing import Any
from checkov.common.checks.base_check_registry import BaseCheckRegistry
from checkov.common.output.report import CheckType
from checkov.common.parsers.json import parse
from checkov.common.parsers.node import DictNode
from checkov.com... | StarcoderdataPython |
3385539 | # from transformers import BertModel, BertTokenizer
from torch import nn
from transformers import BertTokenizer
import torch
from experiment.bert_models.modeling_bert import BertModel, BertConfig
from experiment.bert_utils import BertWrapperModel
from experiment.qa.model import BaseModel
class BertSigmoid(BaseModel):... | StarcoderdataPython |
3297726 | <gh_stars>1-10
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import os.path as osp
import xml.etree.ElementTree as ET
import mmcv
from mmocr.utils import convert_annotations
def collect_files(data_dir):
"""Collect all images and their corresponding groundtruth files.
Args:
... | StarcoderdataPython |
17998 | <filename>days/day01/part2.py<gh_stars>0
from helpers import inputs
def solution(day):
depths = inputs.read_to_list(f"inputs/{day}.txt")
part2_total = 0
for index, depth in enumerate(depths):
if index - 3 >= 0:
current_window = (
int(depth) + int(depths[index - 1]) + in... | StarcoderdataPython |
3238967 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
"""Placeholder."""
import os
from pathlib import Path
from typing import Callable, List
import click
def sm_protocol(
model: str = "model",
output: str = "output",
channels: List[str] = ["train", "test"... | StarcoderdataPython |
1713864 | <reponame>Errare-humanum-est/HeteroGen
# Copyright (c) 2021. <NAME>
# Copyright (c) 2021. University of Edinburgh
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of sourc... | StarcoderdataPython |
124541 | import metrics.evaluation as e
import metrics.evaluation
def get_evaluation(y_test, y_pred):
flat_y_test = [i for subl in y_test for i in subl]
flat_y_pred = [i for subl in y_pred for i in subl]
H,I,D = e.compute_HID(flat_y_test, flat_y_pred)
Precision, Recall, FScore = e.compute_PRF(H,I,D)
evalu... | StarcoderdataPython |
1685009 | <filename>dit/pid/tests/test_imin.py
"""
Tests for dit.pid.imin.
"""
import pytest
from dit.pid.imin import PID_WB
from dit.pid.distributions import bivariates, trivariates
def test_pid_wb1():
"""
Test imin on a generic distribution.
"""
d = bivariates['prob. 1']
pid = PID_WB(d, ((0,), (1,)), (2... | StarcoderdataPython |
1764952 | <reponame>imjal/EventCenterTrack<filename>src/lib/dataset/datasets/prophesee_src/visualize/vis_utils.py
"""
Functions to display events and boxes
Copyright: (c) 2019-2020 Prophesee
"""
from __future__ import print_function
import numpy as np
import cv2
LABELMAP = ["car", "pedestrian"]
def make_binary_histo(events, i... | StarcoderdataPython |
1736190 | #!/usr/bin/python3
'''Send messages to queues in rabbitmq'''
import contextlib
from typing import Iterator
import argparse
import datetime
import pika
@contextlib.contextmanager
def connect(
args: argparse.Namespace
) -> Iterator[pika.adapters.blocking_connection.BlockingChannel]:
'''Connects to rabbi... | StarcoderdataPython |
1672561 | #!/usr/bin/env python
from pyknon.plot import plot2, plot2_bw
from pyknon.simplemusic import inversion
def plot_color():
n1 = [11, 10, 7]
for x in range(12):
plot2(n1, inversion(n1, x), "ex-inversion-plot-{0:02}.ps".format(x))
n2 = [1, 3, 7, 9, 4]
plot2(n2, inversion(n2, 9), "ex-inversion-pl... | StarcoderdataPython |
1600588 | <filename>package/layers/metrics/__init__.py
from .depth_metrics import *
| StarcoderdataPython |
190146 | <reponame>isacasini/SNV_Xia_et_al_2020
# This file contains the following function(s): readtxt, readtxt2df
import pandas as pd
def readtxt(filepathname):
"""Skips a line that starts with “>” and then reads in the rest of the file while removing any new lines (“\n”)"""
sequence = ""
for line in open(filep... | StarcoderdataPython |
150600 | # This script is borrowed from https://github.com/mkocabas/VIBE
# Adhere to their licence to use this script
from psypose.MEVA.meva.dataloaders import Dataset2D
from psypose.MEVA.meva.utils.video_config import PENNACTION_DIR
class PennAction(Dataset2D):
def __init__(self, seqlen, overlap=0.75, debug=False):
... | StarcoderdataPython |
39066 | #!/usr/bin/python3.7
#Author: <NAME>
import sys
import os
import math
import re
import numpy as np
#print('usage: <>.py <file.pdb> \nexecute nsc to generate point-based surface and create tables and if verbose==1 files dotslabel1.xyzrgb dotslabel2.xyzrgb dotslabel3.xyzrgb and dotslabel4.xyzrgb\n')
def pdbsurface(f... | StarcoderdataPython |
3240391 | <reponame>m-holger/qpdf
from collections import defaultdict
from operator import itemgetter
import re
from sphinx import addnodes
from sphinx.directives import ObjectDescription
from sphinx.domains import Domain, Index
from sphinx.roles import XRefRole
from sphinx.util.nodes import make_refnode
# Reference:
# https... | StarcoderdataPython |
1795782 | # -*- coding: utf-8 -*-
# @Author: <NAME>
# @Date: 2019-11-15
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
import codecs
import shutil
import zipfile
import requests
__all__ = [
"wget", "unzip", "rm", "mkdir", "rmdir", "mv"
... | StarcoderdataPython |
152819 | <filename>scripts/alcohol_and_cig_cases.py
alcohol_cases = None
with open('../static/alcohol_cases.txt', 'r') as f:
alcohol_cases = f.readlines()
smoke_cases = None
with open('../static/smoke_cases.txt', 'r') as f:
smoke_cases = f.readlines()
with open('../static/alcohol_and_cig_cases.txt', 'w') as f:
for... | StarcoderdataPython |
4826259 | <gh_stars>0
# -----------------------------------------------------------------------------
# Name: BackupDBWorker.py
# Purpose: Backup observer DB (encrypted only) to an external drive.
#
# Author: <NAME> <<EMAIL>>
#
# Created: Sept 29, 2017
# License: MIT
# ------------------------------------... | StarcoderdataPython |
1704929 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 16 03:18:02 2018
@author: Kazuki
"""
import numpy as np
import pandas as pd
import os
import utils
utils.start(__file__)
#==============================================================================
# setting
month_limit = 12 # max: 96
month_ro... | StarcoderdataPython |
1761963 | # Generated by Django 2.0.7 on 2018-07-21 11:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('catalog', '0004_auto_20180721_1028'),
]
operations = [
migrations.AlterModelOptions(
name='bookinstance',
options={'ordering... | StarcoderdataPython |
1608734 | <filename>myfirst/apps/articles/models.py
import datetime
from django.db import models
from django.utils import timezone
class Article(models.Model):
article_title = models.CharField('article title', max_length = 200)
article_text = models.TextField('article text')
pub_date = models.DateTimeField('publica... | StarcoderdataPython |
169434 | <reponame>Julymusso/IFES
#var
#n, media, cont: int
#i: str
i='s'
cont=0
media=0
while i!='n':
n=int(input('Digite um número: '))
media=media+n
cont=cont+1
i=input("Desejar continuar somando (s) ou deseja encerrar o programa (n)? ")
media=media/cont
print (media)
| StarcoderdataPython |
1658802 | import string
from django.db import models
from django.contrib.postgres.fields import ArrayField
class Icon(models.Model):
name = models.CharField(verbose_name='Nome', max_length=64, unique=True)
tags = ArrayField(models.CharField(max_length=128), blank=True)
slug = models.SlugField(verbose_name='Slug', m... | StarcoderdataPython |
1737357 | print('PAR OU IMPAR')
num = int(input('Digite um número inteiro:'))
if num%2==0:
print('PAR')
else:
print('ÍMPAR')
| StarcoderdataPython |
179959 | d1 = {42: 100}
d2 = {'abc': 'fob'}
d3 = {1e1000: d1}
s = set([frozenset([2,3,4])])
class C(object):
abc = 42
def f(self): pass
cinst = C()
class C2(object):
abc = 42
def __init__(self):
self.oar = 100
self.self = self
def __repr__(self):
return 'myrepr'
... | StarcoderdataPython |
1715667 | import numpy as np
def mean(values, ignore_zeros=False):
used_values = [x for x in values if not ignore_zeros or (ignore_zeros and x != 0)]
return np.mean(used_values) if len(used_values) else 0
| StarcoderdataPython |
192530 | <reponame>gkrish19/SIAM<filename>Software/run.py
import os
os.system('python top_file.py --model_type=DenseNet-BC --dataset=C100+ --saves --logs --renew-logs --train --test')
os.system('python top_file.py --model_type=DenseNet-BC --dataset=C100+ --saves --logs --renew-logs --train --test --quant --act_width=8 --wgt... | StarcoderdataPython |
165145 | """
This is awesome. And needs more documentation.
To bring some light in the big number of classes in this file:
First there are:
* ``SuperForm``
* ``SuperModelForm``
They are the forms that you probably want to use in your own code. They are
direct base classes of ``django.forms.Form`` and ``django.forms.ModelFor... | StarcoderdataPython |
3356988 | import os
#os.environ["CUDA_VISIBLE_DEVICES"]="0"
import numpy as np
import tensorflow as tf
from tensorflow.contrib.rnn import LSTMCell, GRUCell
import sys
import time
from sklearn.metrics import f1_score
import random
class rnn(object):
'''
rnn modular add-on for capturing case-level-context
parame... | StarcoderdataPython |
162869 | <filename>bitcoinlantern/api/connection.py<gh_stars>1-10
from enum import Enum
from rpc.exceptions import BitcoinException
import requests
class BlockExplorers(Enum):
BLOCKEXPLORER = 'https://blockexplorer.com/api/addr/'
class BlockExplorerConnection(object):
def __init__(self, explorer_enum, token=''):
self.expl... | StarcoderdataPython |
104025 | # -*- coding: utf-8 -*-
import time
from sklearn import ensemble
from sklearn import linear_model
from sklearn import naive_bayes
from sklearn import neighbors
from sklearn import neural_network
from sklearn import svm
from sklearn import tree
from sklearn.metrics import f1_score
from sklearn.model_selection import Gri... | StarcoderdataPython |
1750445 | """
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
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, merg... | StarcoderdataPython |
199827 | """
.. module: historical.vpc.differ
:platform: Unix
:copyright: (c) 2017 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. author:: <NAME> <<EMAIL>>
"""
import logging
from raven_python_lambda import RavenLambdaWrapper
from historical.common.dynamodb import process_... | StarcoderdataPython |
1660495 | # Tests if delta calculator is working properly with simple assertion function
from finetuna.calcs import DeltaCalc
from ase.calculators.emt import EMT
import numpy as np
import copy
from ase.build import fcc100, add_adsorbate, molecule
from ase.constraints import FixAtoms
from ase.build import bulk
from ase.utils.eos ... | StarcoderdataPython |
122463 | import numpy as np
import matplotlib.pyplot as plt
from time import time
from numba import cuda
N = 640000
def main():
x = np.linspace(0, 1, N, endpoint=True)
from serial import sArray
start = time()
f = sArray(x)
elapsed = time() - start
print("--- Serial timing: %s seconds ---" % elapsed)
from parallel impo... | StarcoderdataPython |
11405 | <reponame>avijit-chakroborty/ngraph-bridge
# ==============================================================================
# Copyright 2018-2020 Intel Corporation
#
# 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 ... | StarcoderdataPython |
3250939 | <filename>mxnet/tut-gpu.py
# https://gluon-crash-course.mxnet.io/use_gpus.html
from mxnet import nd, gpu, gluon, autograd
from mxnet.gluon import nn
from mxnet.gluon.data.vision import datasets, transforms
from time import time
# allocate data to a gpu
gpu_count = 1
x = nd.ones((3,4), ctx = gpu())
print(x)
if gpu_... | StarcoderdataPython |
1643685 | <filename>examples/name_server_proxy.py
from osbrain import run_agent
from osbrain import run_nameserver
if __name__ == '__main__':
# System deployment
ns = run_nameserver()
run_agent('Agent0')
run_agent('Agent1')
run_agent('Agent2')
# Create a proxy to Agent1 and log a message
agent = ns... | StarcoderdataPython |
4832680 | <reponame>Acidburn0zzz/dfvfs
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the file entry implementation using the tarfile."""
from __future__ import unicode_literals
import unittest
from dfvfs.path import os_path_spec
from dfvfs.path import tar_path_spec
from dfvfs.resolver import context
from dfvfs.vf... | StarcoderdataPython |
1636516 | <filename>moai/export/__init__.py<gh_stars>1-10
from moai.export.single import Exporter as Single
from moai.export.collection import Exporters as Collection
__all__ = [
"Single",
"Collection",
] | StarcoderdataPython |
3315349 | #!/usr/bin/env python
from event_loop.event_loop import EventLoop
__author__ = 'aGn'
__copyright__ = "Copyright 2018, Planet Earth"
if __name__ == "__main__":
print('SNMP Begins')
try:
EventLoop().run_forever()
except KeyboardInterrupt:
import sys
sys.exit(0)
| StarcoderdataPython |
3248937 | <filename>utils/prepare_for_doc_test.py
# coding=utf-8
# Copyright 2022 The HuggingFace Inc. team.
#
# 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/LICEN... | StarcoderdataPython |
1769211 | import sys
sys.path.append("..")
import wingnet as wn
import argparse
import os
import pandas as pd
import cv2 as cv
import matplotlib.pyplot as plt
def load_project(path):
print("loading from {}".format(path))
if path and os.path.exists(path):
project = pd.read_pickle(path)
for img_path in pr... | StarcoderdataPython |
49414 | import sys
import requests
from bs4 import BeautifulSoup
from urllib import request
args = sys.argv[1]
url = args
response = request.urlopen(url)
soup = BeautifulSoup(response, features = "html.parser")
response.close()
print(soup.title.text)
print(soup.pre.text)
| StarcoderdataPython |
1710804 | <reponame>khoih-prog/USBComposite_stm32f1<gh_stars>100-1000
from pywinusb import hid
hid.core.show_hids()
| StarcoderdataPython |
130551 | <reponame>Malavikka/ConvLab-2<gh_stars>100-1000
import os
import zipfile
import torch
from pytorch_pretrained_bert.file_utils import PYTORCH_PRETRAINED_BERT_CACHE
from pytorch_pretrained_bert.modeling import BertForSequenceClassification
from pytorch_pretrained_bert.tokenization import BertTokenizer
from convlab2.pol... | StarcoderdataPython |
1657125 | <reponame>kirillzx/Math-projects
def helix(n):
t = [[0]*n for i in range (n)]
i, j = 0, 0
for k in range(1, n*n+1):
t[i][j]=k
if k == n*n: break
if i<=j+1 and i+j<n-1:
j+=1
elif i<j and i+j>=n-1:
i+=1
elif i>=j and i+j>n-1:
... | StarcoderdataPython |
3368230 | <reponame>Toby-masuku/analysePredict
from . import group_6_module
| StarcoderdataPython |
1628210 | <reponame>ben-hayes/node-hidden-markov-model-tf<filename>test/gaussian.py
import os.path as path
import json
import tensorflow as tf
import tensorflow_probability as tfp
from .tool_generate_data import GenerateData
thisdir = path.dirname(path.realpath(__file__))
# Make data
generator = GenerateData()
states, emissio... | StarcoderdataPython |
3219201 | <gh_stars>0
"""
Authors:
kjmasumo
bowerw2
This is our implementation of the Viterbi algorithm for part of speech tagging.
"""
# Implement the Viterbi algorithm.
# Takes in four parameters: 1) a set of unique tags, 2) the provided sentence as a list, 3) a transition probability
# matrix, and 4) an emission prob... | StarcoderdataPython |
3383365 | import singer_sdk.typing as th
from tap_nhl.schemas.stream_schema_object import StreamSchemaObject
class LiveBoxscoreObject(StreamSchemaObject):
properties = th.PropertiesList(
th.Property("gameId", th.IntegerType),
th.Property("teams", th.ObjectType(
th.Property("away", th.ObjectType(
... | StarcoderdataPython |
149203 | import os
from PIL import Image, ImageFile
from tqdm import tqdm
ImageFile.LOAD_TRUNCATED_IMAGES = True
import torch
from torch.utils.data import Dataset
import torchvision.transforms as transforms
from scene_classification.utils import scan_all_files
class TestDataset(Dataset):
def __init__(self, imgdir, trans... | StarcoderdataPython |
1606826 | <reponame>threefoldtech/jumpscaleX_libs_extra
from Jumpscale import j
# from .CapacityPlanner import CapacityPlanner
JSBASE = j.baseclasses.object
DIR_ITEMS = j.clients.threefold_directory.capacity
class Models:
pass
class FarmerFactory(JSBASE):
def __init__(self):
# self.__jslocation__ = "_j.tool... | StarcoderdataPython |
1768928 | <reponame>ManderaGeneral/generalbrowser
from unittest import TestCase
class Test(TestCase):
def test(self):
pass
| StarcoderdataPython |
3278932 | <filename>src/combinational_element_factory.py
from __future__ import division
import os, math
me = os.path.dirname(__file__)
from block_constants import *
from Element import CombinationalElement
from pymclevel.schematic import MCSchematic
from pymclevel.box import BoundingBox
from pymclevel import alphaMaterials
f... | StarcoderdataPython |
1671488 | from django.db.models import base, Model
from django.utils.translation import get_language
class TranslatableMeta(base.ModelBase):
"""
Metaclass that looks for a special field called __translatable__ which is a dictionary containing keys as the name
of the translatable properties, and the values being lam... | StarcoderdataPython |
119637 | <reponame>fstwn/Cockatoo<filename>modules/networkx/algorithms/tests/test_mixing_degree.py
#!/usr/bin/env python
from nose.tools import *
from nose import SkipTest
import networkx
import networkx.algorithms.mixing as mixing
class TestDegreeMixing(object):
def setUp(self):
self.P4=networkx.path_graph(4... | StarcoderdataPython |
1740378 |
import json
import argparse
from typing import List, Dict
import glob
import os
import pathlib
import pdb
import subprocess
from io import StringIO
import torch
from spacy.tokenizer import Tokenizer
from spacy.lang.en import English
import logging
from tqdm import tqdm
from matplotlib import pyplot as plt
impor... | StarcoderdataPython |
170348 | <filename>rail/likelihood.py
"""
A class to represent a Likelihood
"""
from collections import UserDict
from matplotlib import pyplot as plt
import numpy as np
class Likelihood(UserDict):
"""
A class to represent a Likelihood
"""
def __init__(self, lam: float) -> None:
self.data = {}
... | StarcoderdataPython |
49963 | # Generated by Django 2.0.3 on 2020-01-31 07:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app1', '0003_auto_20200129_0337'),
]
operations = [
migrations.AlterField(
model_name='flight',
name='stripImage',
... | StarcoderdataPython |
164115 | from rest_framework import serializers
from procurebd_api.models import *
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = ProfileUser
#fields = ('name', 'ranking')
fields = '__all__'
class ItemSerializer(serializers.ModelSerializer):
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.