text string | size int64 | token_count int64 |
|---|---|---|
"""Covers import of data downloaded from the
`Meadows online behavior platform <https://meadows-research.com/>`_.
For information on available file types see the meadows
`documentation on downloads <https://meadows-research.com/documentation\
/researcher/downloads/>`_.
"""
from os.path import basename
import numpy
fr... | 3,785 | 1,144 |
from ..common import WQXException
from .SimpleContent import (
BinaryObjectFileName,
BinaryObjectFileTypeCode
)
from yattag import Doc
class AttachedBinaryObject:
"""Reference document, image, photo, GIS data layer, laboratory material or other electronic object attached within a data exchange, as well as inform... | 2,406 | 618 |
import os
import importlib
import pathlib
from tools.Aspect import ModuleAspectizer
path = os.getcwd()
dir_list = os.listdir(path)
print(dir_list)
aspect = ModuleAspectizer()
print('new')
exceptions = ['pyplot.py', 'setup.py', 'bootstrap.py', 'instrument.py',
'windows.py','pybloom.py', 'switcher.py','ma... | 1,185 | 372 |
import json
import os
import codecs
from capitalization_train.puls_util import (separate_title_from_body,
extract_and_capitalize_headlines_from_corpus,
get_input_example,
get_doc_ids_from_... | 3,564 | 1,376 |
import flask
from flask import request, jsonify
from flask_cors import CORS
import math
from wasmer import engine, Store, Module, Instance
app = flask.Flask(__name__)
CORS(app)
@app.route('/add', methods=['POST'])
def add():
store = Store()
# Let's compile the module to be able to execute it!
module = Module... | 906 | 328 |
import unittest
import torch
from torchvision.models.resnet import BasicBlock, Bottleneck
from nuscenes.prediction.models.backbone import ResNetBackbone, MobileNetBackbone
class TestBackBones(unittest.TestCase):
def count_layers(self, model):
if isinstance(model[4][0], BasicBlock):
n_convs ... | 1,815 | 698 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @File : Qrbar_test.py
import cv2
import numpy as np
from pyzbar.pyzbar import decode
img = cv2.imread('qrcode.png')
for barcode in decode(img):
print(barcode.data.decode('utf-8'))
print(barcode.data)
pts = np.array([barcode.polygon], np.int32)
pts = pts.... | 379 | 161 |
import os
import requests
import time
c = get_config() # noqa: F821
c.ServerApp.ip = "0.0.0.0"
c.ServerApp.port = 8888
c.ServerApp.open_browser = False
def get_gooogle_instance_attribute(attribute_name):
try:
response = requests.get(
f'http://metadata.google.internal/computeMetadata/v1/in... | 1,336 | 439 |
'''
@Author: Jiangtao
@Date: 2020-02-25 16:13:42
@LastEditors: Jiangtao
@LastEditTime: 2020-07-06 14:01:11
@Description:
'''
import numpy as np
np.set_printoptions(threshold=np.inf)
import torch
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def mixup_data(x, y, dev... | 1,346 | 608 |
#Среднее гармоническое
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def harmid(*args):
if args and 0 not in args:
a = 0
for item in args:
a += 1 / item
return len(args) / a
else:
return None
if __name__ == "__main__":
print(harmid())
print(harmi... | 376 | 174 |
import argparse
import sys
import datetime
import json
import logging
import re
import random
import requests
import shutil
from pyquery import PyQuery as pq
def main(username, password):
logging.basicConfig(filename='logging.log', level=logging.DEBUG)
session = requests.session()
uid, dtsg = login(ses... | 1,187 | 374 |
#!/usr/bin/env python
"""
"""
from __future__ import print_function
import argparse
import sys
from . import common
from . import helper
from . import vcs_tool
PARAMS = {}
PARAMS['this_script'] = common.get_script_name_from_filename(__file__)
def setup_and_dispatch():
parser = argparse.ArgumentParser(
... | 1,347 | 426 |
from django.db import models
# from themall.models import Customer
# Create your models here.
class Seller(models.Model):
email = models.OneToOneField('themall.Customer', on_delete=models.CASCADE, to_field='email')
store_name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
descrip... | 411 | 147 |
# Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
# For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
import time
import pytest
from harness import log
from harness.dom_parser_utils import *
from harness.interface.defs import key_codes
from bt_fixtures import *
@pytest.mark.rt1051
@pyte... | 2,392 | 834 |
import smtplib, ssl, os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from .html_template import emailHtml
from .text_template import emailText
port = 465
context = ssl.create_default_context()
def sendEmail(emailData):
adminUser = os.getenv("ADMIN_USERNAME")
password =... | 1,147 | 366 |
# 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, software
# distributed under t... | 2,606 | 741 |
#!/usr/bin/python3
from tornado import ioloop, web
from tornado.options import define, options, parse_command_line
from manifest import ManifestHandler
from segment import SegmentHandler
app = web.Application([
(r'/segment/.*',SegmentHandler),
(r'/manifest/.*',ManifestHandler),
])
if __name__ == "__main__":
... | 664 | 218 |
import os
for root, dirs, files in os.walk("/Users/coco/Documents/GitHub/pingcap-upstream/docs-cn", topdown=True):
#for root, dirs, files in os.walk("/Users/coco/Documents/GitHub/python-side-projects/cofile", topdown=True):
for name in files:
if '.md' in name: # Check all markdown files
filep... | 488 | 158 |
import requests
import os
import json
import datetime
'''
Pulls a dbml file from the API. User must manually add the file id, found in the 'response_ids.json' file generated from dbml_post_to_api.py
'''
url='http://ec2-54-167-67-34.compute-1.amazonaws.com/api/dbmls' #url of the API
id = '6192b1f31c2a512293f... | 499 | 205 |
import os
from fabric.api import local, lcd
def clean():
with lcd(os.path.dirname(__file__)):
local("python3.6 setup.py clean --all")
local("find . | grep -E \"(__pycache__|\.pyc$)\" | xargs rm -rf")
def make():
local("python3.6 setup.py bdist_wheel")
def deploy():
test()
make()
... | 400 | 145 |
from openpyxl import load_workbook
def getRowCount(file):
wb = load_workbook(file)
sheet = wb.active
return sheet.max_row
def getColumnCount(file):
wb = load_workbook(file)
sheet = wb.active
return sheet.max_column
def getCellData(file, cell):
wb = load_workbook(file)
sheet = wb.acti... | 544 | 202 |
# List of tables that should be routed to this app.
# Note that this is not intended to be a complete list of the available tables.
TABLE_NAMES = (
'lemma',
'inflection',
'aspect_pair',
)
| 200 | 61 |
import argparse
from differential.plugins.base import Base
class Gazelle(Base):
@classmethod
def get_aliases(cls):
return "gz",
@classmethod
def get_help(cls):
return "Gazelle插件,适用于未经过大规模结构改动的Gazelle站点"
@classmethod
def add_parser(cls, parser: argparse.ArgumentParser) -> arg... | 399 | 140 |
[
{
'date': '2014-01-01',
'description': 'Yılbaşı',
'locale': 'tr-TR',
'notes': '',
'region': '',
'type': 'NF'
},
{
'date': '2014-04-23',
'description': 'Ulusal Egemenlik ve Çocuk Bayramı',
'locale': 'tr-TR',
'notes': '',
... | 2,398 | 931 |
# pommerman/cli/run_battle.py
# pommerman/agents/TensorFlowAgent/pit.py
import atexit
from datetime import datetime
import os
import random
import sys
import time
import argparse
import numpy as np
from pommerman import helpers, make
from TensorFlowAgent import TensorFlowAgent
from pommerman import utility
import ... | 2,512 | 838 |
import numpy as np
import tensorflow as tf
import unittest
from xcenternet.model.evaluation.overlap import compute_overlap
from xcenternet.model.evaluation.mean_average_precision import MAP
class TestMeanAveragePrecision(unittest.TestCase):
def setUp(self):
self.map_bboxes = np.array(
[
... | 4,645 | 1,883 |
# Copyright 2017 The Sonnet Authors. 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/licenses/LICENSE-2.0
#
# Unless required by applicable l... | 3,063 | 1,034 |
#!/usr/bin/env python
import rospy
from reflex_msgs.msg import HandCommand
from time import sleep
from reflex_base_services import *
class ReFlex_Polling(ReFlex):
def __init__(self):
super(ReFlex_Polling, self).__init__()
def callback(data):
# data is a HandCommand variable... | 714 | 241 |
import os.path
from typing import Sequence, Optional, Dict
import numpy as np
import pandas as pd
from nk_sent2vec import Sent2Vec as _Sent2Vec
from d3m import container, utils
from d3m.primitive_interfaces.transformer import TransformerPrimitiveBase
from d3m.primitive_interfaces.base import CallResult
from d3m.contai... | 7,630 | 2,180 |
import pytest
from helpers.cluster import ClickHouseCluster
cluster = ClickHouseCluster(__file__)
instance = cluster.add_instance('instance', stay_alive=True)
@pytest.fixture(scope="module", autouse=True)
def started_cluster():
try:
cluster.start()
yield cluster
finally:
cluster.shut... | 1,173 | 401 |
# -*- coding: utf-8 -*-
# This software and supporting documentation are distributed by
# Institut Federatif de Recherche 49
# CEA/NeuroSpin, Batiment 145,
# 91191 Gif-sur-Yvette cedex
# France
#
# This software is governed by the CeCILL-B license under
# French law and abiding by the rules of dis... | 7,694 | 2,000 |
import random
import pytest
from model.contact import Contact
def test_delete_some_contact(app, db, check_ui):
if len(db.get_group_list()) == 0:
app.contact.create(Contact(firstname="del_test"))
with pytest.allure.step('Get contact list'):
old_contacts = db.get_contact_list()
with pytest... | 1,000 | 291 |
from operator import itemgetter
import pandas as pd
import slate
from slate.integrations.common import b_id, DUMMY_METRICS, DUMMY_INDICATORS
try:
import backtesting
except ImportError:
pass
class BacktestingPy:
slate: 'slate.Slate'
api: 'slate.api.API'
def __init__(self, slate, api):
s... | 3,513 | 1,080 |
nome = []
temp = []
pesoMaior = pesoMenor = 0
count = 1
while True:
temp.append(str(input('Nome: ')))
temp.append(float(input('Peso: ')))
if count == 1:
pesoMaior = pesoMenor = temp[1]
else:
if temp[1] >= pesoMaior:
pesoMaior = temp[1]
elif temp[1] <= pesoMenor:
... | 1,029 | 397 |
"""
Run inference N times on the provided model given set of hyperparameters. Has
the option to inject noise into the test set.
"""
import os
import shutil
import re
import clize
import mlflow
import tensorflow as tf
from clize.parameters import multi
from ml_intuition.data.io import load_processed_h5
from ml_intuit... | 8,685 | 2,381 |
import json
import os
import numpy
import pandas as pd
from quantlaw.utils.beautiful_soup import create_soup
from quantlaw.utils.files import ensure_exists
from quantlaw.utils.pipeline import PipelineStep
from statics import (
DE_REFERENCE_PARSED_PATH,
DE_REG_AUTHORITY_EDGELIST_PATH,
DE_REG_CROSSREFERENCE... | 3,629 | 1,191 |
from subprocess import check_output
def main():
output = check_output(["hello-world"]).decode("utf-8").strip()
if not output == "Hello, world!":
raise Exception(output)
print("SUCCESS")
if __name__ == '__main__':
main()
| 248 | 80 |
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
import select_data as sd
'''
See paper: Sensors 2018, 18(4), 1055; https://doi.org/10.3390/s18041055
"Divide and Conquer-Base... | 5,567 | 2,107 |
# ============================================================================
#
# Copyright (c) 2007-2010 Integral Technology Solutions Pty Ltd,
# All Rights Reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL... | 22,060 | 5,799 |
from moment_plots import *
np.random.seed(1)
ts = test_series(500) * 10
# ts[::100] = 20
s = ts.cumsum()
fig, axes = plt.subplots(3, 1, figsize=(8, 10), sharex=True)
ax0, ax1, ax2 = axes
ax0.plot(s.index, s.values)
ax0.set_title('time series')
ax1.plot(s.index, m.ewma(s, span=50, min_periods=1).values, color='b... | 836 | 391 |
import sys
# import the GameState of the game
from Game.GameStateConnect4 import GameState
# import all agents
from Agents.MCTS import MCTSTree
from Agents.Random import RandomAgent
from Agents.AlphaBeta import AlphaBetaAgent
# creates the board string for connect4 (full of zeros)
start_board_list = ["000000 ... | 3,564 | 1,034 |
import os
from time import sleep
import aiohttp
from aiotg import Bot
CLEVERBOT = "https://www.cleverbot.com/getreply?key={key}&input={q}"
APERTIUM = 'http://batisteo.eu:2737/translate?markUnknown=no&q={q}&langpair={pair}'
CLEVERBOT_TOKEN = os.environ['CLEVERBOT_TOKEN']
bot = Bot(api_token=os.environ['BOT_TOKEN'])
... | 990 | 390 |
# (c) Copyright IBM Corp. 2010, 2018. All Rights Reserved.
import pkg_resources
try:
__version__ = pkg_resources.get_distribution(__name__).version
except pkg_resources.DistributionNotFound:
__version__ = None
from .actions_component import ResilientComponent
from .action_message import ActionMessageBase, Act... | 702 | 194 |
"""The transforms module contains all the transforms that can be added to the
simulation of a model. These transforms are applied after the simulation,
to incorporate nonlinear effects.
"""
import numpy as np
from pandas import DataFrame
class ThresholdTransform:
"""ThresholdTransform lowers the simulation whe... | 2,838 | 847 |
import string
from ..datasets import Dataset
uppercase_ascii_letters = Dataset("uppercase_letter", None, string.ascii_uppercase)
lowercase_ascii_letters = Dataset("lowercase_letter", None, string.ascii_lowercase)
ascii_letters = Dataset("letter", None, string.ascii_letters)
digits = Dataset("digit", None, string.dig... | 382 | 129 |
'''
HackerLand Enterprise is adopting a new viral advertising strategy. When they launch a new product, they advertise it to exactly people on social media.
On the first day, half of those people (i.e., ) like the advertisement and each shares it with of their friends. At the beginning of the second day, people re... | 1,732 | 511 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: zss_debug.proto
from google.protobuf import descriptor_pb2
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import reflection as _reflection
from google.protobuf import message as _message
from google.protobuf impo... | 33,413 | 12,398 |
import os
import subprocess
import tempfile
try:
from PyQt5.QtCore import QBuffer, QIODevice, Qt
from PyQt5.QtGui import QImage
except ImportError:
from PySide2.QtCore import QBuffer, QIODevice, Qt
from PySide2.QtGui import QImage
from .texture_format import TextureFormat
def imageToBytes(image):
... | 1,055 | 354 |
##########################################################################
# PyPipe - Copyright (C) AGrigis, 2017
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for details.
####... | 4,324 | 1,177 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 02/06/17 at 2:24 PM
@author: neil
Program description here
Version 0.0.0
"""
from . import constants
from . import utils
from astropy import units as u
# =============================================================================
# Define variables
#... | 7,945 | 2,136 |
from ._process import process_pipeline
__all__ = ["process_pipeline"]
| 71 | 23 |
##~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~##
## ##
## This file forms part of the Underworld geophysics modelling application. ##
## ... | 7,626 | 2,321 |
from .utils import skip_projects_except
@skip_projects_except(["test"])
def test_test(ape_cli, runner):
# test cases implicitly test built-in isolation
result = runner.invoke(ape_cli, ["test"])
assert result.exit_code == 0, result.output
@skip_projects_except(["test"])
def test_test_isolation_disabled(a... | 589 | 180 |
# Necro(ネクロ)
# sidmishra94540@gmail.com
def binaryGenerator(n):
pad = [0]*n
res = []
for _ in range(2**n):
num = list(map(int, bin(_)[2:]))
num = pad[:n-len(num)]+num
res.append(num)
return res
if __name__ == '__main__':
print(binaryGenerator(int(input()))) | 302 | 122 |
# Copyright (c) The InferLO authors. All rights reserved.
# Licensed under the Apache License, Version 2.0 - see LICENSE.
from inferlo.testing import ExperimentRunner
def test_run_experiment():
def my_experiment(x=0):
return {"square": x * x, "cube": x * x * x}
runner = ExperimentRunner()
result... | 403 | 134 |
"""
Module implements simple ORM for SQLite.
Module excludes using many-to-many and one-to-many relationships.
Trying to save the same object (update) with another aggregated object
will rewrite old object!
"""
import os
import sqlite3
from array import array
from inspect import *
import builtins
import sys
import lo... | 36,688 | 10,552 |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""This mo... | 4,480 | 1,067 |
import csv
import six
from collections import defaultdict, Counter
from itertools import izip, islice
from geodata.text.tokenize import tokenize, token_types
from geodata.encoding import safe_encode
class FrequentPhraseExtractor(object):
'''
Extract common multi-word phrases from a file/iterator using the
... | 3,833 | 1,243 |
from scipy.signal import oaconvolve
from pyfar import Signal
# Class to generate ref-Objects, that can bei part of the MeasurementChain
class Device(object):
"""Class for device in MeasurementChain.
This class holds methods and properties of a device in the
'MeasurementChain' class. A device can be e.g.,... | 10,093 | 2,571 |
from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="algorithms",
version="0.1",
description="Implements a few optimisation algorithms",
long_description=long_description,
long_description_content_type="text/markdown",
ur... | 482 | 153 |
import pandas as pd
import dimensionality_reduction_functions as dim_red
from plotting_functions import colored_line_plot, colored_line_and_scatter_plot, colored_line_plot_projected_data
# Number of PCA components
ndim = 3
####################################### EXAMPLE 4: CYCLOPROPYLIDENE BIFURCATION ###############... | 3,980 | 1,686 |
import asyncio
import json
from unittest import TestCase
from aioresponses import aioresponses
import hummingbot.connector.exchange.bitfinex.bitfinex_utils as utils
from hummingbot.connector.exchange.bitfinex import BITFINEX_REST_URL
from hummingbot.connector.exchange.bitfinex.bitfinex_api_order_book_data_source impo... | 2,381 | 825 |
'''
This code compares the loc and iloc in pandas dataframe
'''
__author__ = "Tushar SEth"
__email__ = "tusharseth93@gmail.com"
import pandas as pd
import timeit
df_test = pd.DataFrame()
tlist = []
tlist2 = []
################ this code creates a dataframe df_test ##################
###############with two column... | 2,445 | 720 |
"""
Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина). Значения данных
атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными. Определить метод расчета
массы асфальта, необходимого для покрытия всего дорожного полотна. Использовать формулу... | 900 | 362 |
from functools import total_ordering
from random import shuffle
class Player:
def __init__(self, name):
self.name = name
self.hand = []
def __str__(self):
return self.name
def play(self):
return self.hand.pop()
def receive(self, cards):
for card in cards:
... | 2,897 | 926 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
cz2 = (0.7, 0.7, 0.7)
cz = (0.3, 0.3, 0.3)
cy = (0.7, 0.4, 0.12)
ci = (0.1, 0.3, 0.5)
ct = (0.7, 0.2, 0.1)
ax = plt.figure(figsize=(5,4)).gca()
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.yaxis.grid(True)
ax.set_... | 1,191 | 700 |
'''OpenGL extension ATI.pn_triangles
Overview (from the spec)
ATI_pn_triangles provides a path for enabling the GL to internally
tessellate input geometry into curved patches. The extension allows the
user to tune the amount of tessellation to be performed on each triangle as
a global state value. The inten... | 3,079 | 1,234 |
import os
import numpy as np
from setuptools import setup, find_packages, Extension
NAME = 'toad'
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__))
VERSION_FILE = os.path.join(CURRENT_PATH, NAME, 'version.py')
def get_version():
ns = {}
with open(VERSION_FILE) as f:
exec(f.read(), ns)
r... | 2,325 | 741 |
import torch
import tvm
from tvm import autotvm
from tvm import relay
from tvm.contrib import download
from tvm.contrib.debugger import debug_runtime
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import argparse
import os
from os.path import join, isfile
import sys
import json, requests
fro... | 9,071 | 2,952 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
DataWorkshop: application to handle data, e.g. generated from imageviewer
Author: Tong Zhang
Created: Sep. 23rd, 2015
"""
from ...utils import datautils
from ...utils import miscutils
from ...utils import funutils
from ...utils import resutils
import wx
import wx.lib... | 2,061 | 706 |
"""Authorization token handling."""
import logging
from functools import wraps
from flask import g, request
from requests import get
from pydantic.error_wrappers import ValidationError
from bayesian.utility.user_utils import get_user, UserException, UserNotFoundException
from bayesian.utility.v2.sa_models import Header... | 2,953 | 821 |
tcase = int(input())
while(tcase):
str= input() [::-1]
print(int(str))
tcase -= 1 | 96 | 43 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: atekawade
"""
from setuptools import setup, find_packages
setup(
# Needed to silence warnings (and to be a worthwhile package)
name='tomo_encoders',
url='https://github.com/aniketkt/TomoEncoders',
author='Aniket Tekawade',
author_email='a... | 1,082 | 379 |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021, CloudBlue
# All rights reserved.
#
import pathlib
from datetime import date
from tempfile import NamedTemporaryFile
from collections import namedtuple
import math
import copy
from connect.client import R
from plotly import graph_objects as go
from ..utils import (
c... | 17,328 | 5,314 |
symbols = []
exports = [{'type': 'function', 'name': 'AmdPowerXpressRequestHighPerformance', 'address': '0x7ff66dd14004'}, {'type': 'function', 'name': 'NvOptimusEnablement', 'address': '0x7ff66dd14000'}] | 204 | 81 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Copyright (c) 2015 Uwe Köckemann <uwe.kockemann@oru.se>
#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 l... | 7,728 | 2,928 |
import time
from signal import pause
import logging
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
logger = logging.getLogger(__name__)
map_edge_parse = {'falling':GPIO.FALLING, 'rising':GPIO.RISING, 'both':GPIO.BOTH}
map_pull_parse = {'pull_up':GPIO.PUD_UP, 'pull_down':GPIO.PUD_DOWN, 'pull_off':GPIO.PUD_OFF}
map_edg... | 6,979 | 2,270 |
#!/usr/bin/python
"""A command-line interface to pyatdl, yet another to-do list.
The most important command is 'help'.
The key notions are Action, Context, Folder, and Project. The commands use the
filesystem idiom. Actions and Contexts are like regular files. Projects and
Folders are like directories.
This was the... | 10,308 | 3,350 |
from setuptools import setup
setup(name='gtkpass',
version='0.2.7',
description='A GTK+ 3 program for the standard unix password manager',
url='http://github.com/raghavsub/gtkpass',
author='Raghav Subramaniam',
author_email='raghavs511@gmail.com',
license='MIT',
packages=['gtk... | 426 | 142 |
from flask_restplus import Resource, fields, Namespace
from restApi.models.rides import Rides
from restApi.helpers.ride_helpers import RideParser
from .auth import token_required
Ride_object = Rides()
ride_api = Namespace("rides", description="this are routes that allow users to create get or delete a ride")
ride_of... | 2,556 | 761 |
import pytest
import time
from .utils import (
init_app, init_db, clean_db,
add_flow, add_run, add_step, add_task, add_artifact,
_test_list_resources, _test_single_resource, add_metadata, get_heartbeat_ts
)
pytestmark = [pytest.mark.integration_tests]
# Fixtures begin
@pytest.fixture
def cli(loop, aiohtt... | 27,827 | 9,964 |
import datetime
import fastapi
import pymongo
import pymongo.errors
import pymongo.results
from apps.common.enums import CodeAudiences
from apps.common.handlers import PasswordsHandler, TokensHandler
from fastapi_mongodb.exceptions import HandlerException, RepositoryException
from fastapi_mongodb.handlers... | 2,033 | 616 |
import torch
from torch.optim import lr_scheduler
from tqdm import tqdm
from torchsummary import summary
from torch.utils.tensorboard import SummaryWriter
from apex import amp
from loss import dice
from pathlib import Path
from data import CaseDataset, load_case, save_pred, \
orient_crop_case, regions_crop_case, re... | 25,971 | 7,782 |
""" Helper methods constant across all workers """
import requests, datetime, time
import sqlalchemy as s
import pandas as pd
def connect_to_broker(self, logging):
connected = False
for i in range(5):
try:
logging.info("attempt {}".format(i))
if i > 0:
time.sleep... | 8,285 | 2,496 |
# 006 - Faça um programa que peça o raio de um círculo, calcule e mostre sua área.
print(f'Área: {3.14 * pow(float(input("Raio círculo: ")), 2)}') | 147 | 65 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 09 22:25:07 2019
@author: arnaudhub
"""
#import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.sql import text
import configparser,os
from urllib import parse
#import sql.connector
config = configparser.ConfigParser()
config.re... | 16,034 | 6,853 |
from multiml import logger
from multiml.task.pytorch import PytorchASNGNASTask
from multiml.task.pytorch import PytorchASNGNASBlockTask
from . import PytorchConnectionRandomSearchAgent
from multiml.task.pytorch.datasets import StoreGateDataset, NumpyDataset
import numpy as np
class PytorchASNGNASAgent(PytorchConnect... | 10,002 | 3,215 |
import os
import pytest
from petisco import FlaskApplication
SWAGGER_DIR = os.path.dirname(os.path.abspath(__file__)) + "/application/"
app = FlaskApplication(application_name="petisco", swagger_dir=SWAGGER_DIR).get_app()
@pytest.fixture
def client():
with app.app.test_client() as c:
yield c
@pytest... | 393 | 142 |
from rest_framework import status
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from ..models import User
from ..token import account_activation_token
# local import
from authors.base_test_config import TestConfiguration
class TestRe... | 6,136 | 1,745 |
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from flask import Blueprint, jsonify, request, flash, redirect, render_template
from web_app.models import User
from web_app.statsmodels import load_model
from web_app.services.basilica_service import connection as basilica_con... | 2,192 | 767 |
#
# Tests for the standard parameters
#
import pybamm
import unittest
class TestGeometricParameters(unittest.TestCase):
def test_macroscale_parameters(self):
geo = pybamm.geometric_parameters
L_n = geo.L_n
L_s = geo.L_s
L_p = geo.L_p
L_x = geo.L_x
l_n = geo.l_n
... | 1,399 | 510 |
import argparse
import os
import pyprind
import utils
import treetk
import treetk.rstdt
def main(args):
"""
We use n-ary ctrees (ie., *.labeled.nary.ctree) to generate dtrees.
Morey et al. (2018) demonstrate that scores evaluated on these dtrees are superficially lower than those on right-heavy binarize... | 1,860 | 633 |
# vinyl.py
import os
import discord
from discord import voice_client
from audio_source import AudioSource
from audio_controller import AudioController
import yt_dlp
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
# Suppress unnecessary bug reports
yt_dl... | 4,507 | 1,349 |
"""Tests for AchromLens component."""
# stdlib
import logging
# external
import pytest
# project
from payload_designer.components import lenses
LOG = logging.getLogger(__name__)
def test_focal_length_1():
"""Test AchromLens.focal_length_1()"""
f_eq = 50
V_1 = 0.016
V_2 = 0.028
doublet = lense... | 1,106 | 523 |
#!/usr/bin/env python
import matplotlib.pyplot as pl
import numpy as np
p = np.random.rand(5000, 2) * 4 - 2
inner = np.sum(p ** 2, axis=1) <= 4
pl.figure(figsize=(10, 10))
pl.plot(p[inner, 0], p[inner, 1], 'bo')
pl.plot(p[~inner, 0], p[~inner, 1], 'rD')
pi_estimate = np.sum(inner) / 5000 * 4
print('the estimated pi ... | 486 | 230 |
from contextlib import closing
import h5py
import numpy as np
def save_h5(outfile, dictionary):
""" Saves passed dictionary to an h5 file
Parameters
----------
outfile : string
Name of output h5 file
dictionary : dictionary
Dictionary that will be saved
"""
def save_layer(... | 1,949 | 555 |
from math import sqrt
def is_prime_number(number):
# we only need to loop from 2 to square root of number
# https://stackoverflow.com/a/5811176/4388776
for i in range(2, int(sqrt(number)) + 1):
if number % i == 0:
return False
return True
def get_nth_prime(n):
count = 0
n... | 526 | 181 |
# -*- coding: utf-8 -*-
""" Helper functions for VariationalModel class """
from __future__ import print_function
from __future__ import division
import math
import random
import tensorflow as tf
from tensorflow.contrib.legacy_seq2seq.python.ops import seq2seq as s2s
def linearOutcomePrediction(zs, pa... | 11,582 | 4,679 |
# load modules
from abc import ABCMeta, abstractmethod
from typing import List
from src.Domain.Song import Song, SongHash, Url
# definition
class ISongFactory(metaclass=ABCMeta):
# URLからSongインスタンスのリストを生成する
@abstractmethod
def generateByUrl(self, url: Url) -> List[Song]:
pass
# hash値からSongイン... | 417 | 155 |
"""empty message
Revision ID: b9ab1a9a2113
Revises:
Create Date: 2021-11-28 22:41:01.160642
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b9ab1a9a2113'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... | 1,164 | 424 |