content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import torch
class ModelPipeline:
def __init__(self, preprocessor, model, return_numpy=True):
self.preprocessor = preprocessor
self.model = model
self.return_numpy = return_numpy
def __call__(self, *args, **kwargs):
inputs = self.preprocessor(*args, **kwargs)
if isinst... | nilq/baby-python | python |
#!/Users/rblount/.pyenv/versions/AdOfCode/bin/python
import sys
import os
import numpy as np
from TerminalColors import BRED, BGREEN, ENDCOLOR
from AOC import AOC
testing = False
days = 100
def parse_input(data_input: list):
array = np.genfromtxt(data_input, dtype=int, delimiter=1)
return array
def prin... | nilq/baby-python | python |
from .realtime import interface, urlib
################################################################
## Simulated robot implementation
################################################################
class SimConnection:
"""Implements functionality to read simulated robot state (arm and F/T sensor) and command ... | nilq/baby-python | python |
import sys
import time
from networktables import NetworkTables
import logging
logging.basicConfig(level=logging.DEBUG)
NetworkTables.initialize(server = "localhost")
sd = NetworkTables.getTable("/vision")
while True:
try:
x = sd.getNumberArray('centerX')
width = sd.getNumberArray('width')
... | nilq/baby-python | python |
# Generated by Django 3.0.5 on 2020-09-02 22:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0020_auto_20200903_0339'),
]
operations = [
migrations.AlterField(
model_name='questiontable',
name='count1... | nilq/baby-python | python |
from django.apps import AppConfig
class HarvesterConfig(AppConfig):
default_auto_field = 'django.db.models.AutoField'
name = 'harvester'
| nilq/baby-python | python |
#!/usr/bin/env python3.7
"""
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE and README.md files for licensing instructions.
The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent
"""
import json
import os
from typing import Uni... | nilq/baby-python | python |
"""ssoadmin module initialization; sets value for base decorator."""
from .models import ssoadmin_backends
from ..core.models import base_decorator
mock_ssoadmin = base_decorator(ssoadmin_backends)
| nilq/baby-python | python |
import unittest
from page.thread_page import Page
import time
class threadDemo(unittest.TestCase):
def __repr__(self):
return 'appdemo'
@classmethod
def setUpClass(cls):
cls.page = Page()
def test_a_thread(self):
time.sleep(6)
self.page.login_btn()
time.sleep(... | nilq/baby-python | python |
import falcon
from falcon.testing import TestResource as ResourceMock
from tests import RestTestBase
from monitorrent.rest import no_auth, AuthMiddleware
def is_auth_enabled():
return False
class TestAuthMiddleware(RestTestBase):
def setUp(self, disable_auth=False):
super(TestAuthMiddleware, self).s... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from std_msgs.msg import String, Bool
from burger_war_dev.msg import war_state
from actionlib_msgs.msg import GoalStatusArray
class StateControlBot():
def __init__(self):
self.pub = rospy.Publisher("main_state",String, queue_size=10)
self.s... | nilq/baby-python | python |
valor1 = 0
acumu1 = 0
valor2 = 10
acumu2 = 10
while valor <= 8:
print(acumulador, valor1)
else:
print('terminou o laço') | nilq/baby-python | python |
from ._pyg_decoders import (
LogSoftmaxDecoderMaintainer,
SumPoolMLPDecoderMaintainer,
DiffPoolDecoderMaintainer,
DotProductLinkPredictionDecoderMaintainer
)
| nilq/baby-python | python |
import random
def sort_by_length(words):
t = []
for word in words:
t.append((len(word), word))
t = t[::-1]
res = []
for length, word in t:
res.append(word)
return res
def sort_by_length_random(words):
"""Modify this example so that words with the same length appear in ran... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
# fix sys path so we don't need to setup PYTHONPATH
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
os.environ['DJANGO_SETTINGS_MODULE'] = 'userena.runtests.settings'
import django
if django.VERSION >= (1, 7, 0):
# starting from 1.... | nilq/baby-python | python |
import pytest
from omniscient.utils.query_graph_utils import QueryGraphUtils
@pytest.fixture(scope="class")
def setup():
sparql = """
PREFIX ns: <http://rdf.freebase.com/ns/>
SELECT DISTINCT ?x
WHERE {
FILTER (?x != ?c)
FILTER (!isLiteral(?x) OR lang(?x) = '' OR langMatches(lang(?... | nilq/baby-python | python |
A = ['C', 'D', "E", "F", "G"]
B = [3, 0, 4, 1, 2]
def sort(A, B):
t = zip(A,B)
t = sorted(t, key=lambda x: x[1])
A, B = zip(*t)
return A
print sort(A,B) | nilq/baby-python | python |
""""""
# Standard library modules.
import os
# Third party modules.
import pytest
import pyxray
# Local modules.
from pymontecarlo_penepma.importer import PenepmaImporter
# Globals and constants variables.
@pytest.fixture
def importer():
return PenepmaImporter()
@pytest.mark.asyncio
async def test_import(ev... | nilq/baby-python | python |
import os
import streamlit as st
import pandas as pd
import plotly.express as px
from PIL import Image
favicon = Image.open("media/favicon.ico")
st.set_page_config(
page_title = "AICS Results",
page_icon = favicon,
menu_items={
'Get Help': 'https://github.com/All-IISER-Cubing-Society/Results',
... | nilq/baby-python | python |
"""
Create a movie
==============
This example shows how to create a movie, which is only possible if `ffmpeg` is
installed in a standard location.
"""
from pde import UnitGrid, ScalarField, DiffusionPDE, MemoryStorage, movie_scalar
grid = UnitGrid([16, 16]) # generate grid
state = ScalarFi... | nilq/baby-python | python |
import warnings
warnings.simplefilter('ignore')
import pytest
import numpy as np
import keras
from hand_classifier.hand_cnn import HandCNN
@pytest.mark.parametrize("img_shape, target_shape", [((512, 512, 3), (224, 224, 3)), ((820, 430, 3), (96, 96, 3)), ((400, 800, 3), (114, 114, 3))])
def test_preprocessing(img_sha... | nilq/baby-python | python |
from flask import Blueprint
main=Blueprint("main",__name__)
from .views import * | nilq/baby-python | python |
# # scan_test.py
# # Author: Thomas MINIER - MIT License 2017-2018
# from query_engine.sage_engine import SageEngine
# from query_engine.iterators.scan import ScanIterator
# from query_engine.iterators.union import BagUnionIterator, RandomBagUnionIterator
# from database.hdt_file_connector import HDTFileConnector
#
# h... | nilq/baby-python | python |
# Copyright 2018 Sabino Miranda Jimenez
# 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 w... | nilq/baby-python | python |
from ._helpers import export_data, ExportScope
from . import orders, nested_orders
| nilq/baby-python | python |
RESNET = "resnet"
XCEPTION = "xception"
INCEPTIONV3 = "inceptionv3"
VGG16 = "vgg16"
IMAGENET = "imagenet"
CONFIG_FILE = "config.json"
MODEL_INFO_FILE = "model_info.json"
SCORING = "scoring"
RETRAINING = "retraining"
BEFORE_TRAIN = "before_train"
RETRAINED_SUFFIX="_retrained"
CUSTOM_TOP_SUFFIX = "_customtop"
RETRAINED =... | nilq/baby-python | python |
import datetime
from dateutil import tz
def identity(x):
'''return the input value'''
return x
def local_timestamp(ts):
'''return a dst aware `datetime` object from `ts`'''
return datetime.datetime.fromtimestamp(ts, tz.tzlocal())
def strftime(ts):
if ts is None:
return 'None'
if ... | nilq/baby-python | python |
"""
Copyright (c) 2018-2021 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 a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... | nilq/baby-python | python |
"""
This module details user input api
"""
import time
from queue import Queue, Empty
from pubsub import pub
from fixate.config import RESOURCES
from collections import OrderedDict
USER_YES_NO = ("YES", "NO")
USER_RETRY_ABORT_FAIL = ("RETRY", "ABORT", "FAIL")
def _user_req_input(msg, target=None, attempts=5, **kwarg... | nilq/baby-python | python |
"""
NOTE: Здесь можно описывать и другие аспекты, которые идут параллельно основному использованию.
Если слишком длинно - можно и ссылками на офиц. доку
"""
def example_1():
pass
if __name__ == "__main__":
example_1() | nilq/baby-python | python |
import os.path
from data.base_dataset import BaseDataset, get_transforms_reid, get_transforms_LR_reid, get_transforms_norm_reid
from data.image_folder import make_reid_dataset
from PIL import Image
from scipy.io import loadmat
import numpy as np
class SingleMarketDataset(BaseDataset):
@staticmethod
def modify... | nilq/baby-python | python |
from pm4pymdl.algo.mvp.utils import succint_mdl_to_exploded_mdl, clean_objtypes
import pandas as pd
def preprocess(df, parameters=None):
if parameters is None:
parameters = {}
conversion_needed = False
try:
if df.type == "succint":
conversion_needed = True
except:
... | nilq/baby-python | python |
#!/usr/bin/env python
# coding: utf-8
import numpy as np
import torchvision
import torch
import matplotlib.pyplot as plt
from pathlib import Path
import logging
import time
import pickle
from sklearn.model_selection import train_test_split
from torch.utils.data import TensorDataset, DataLoader
from torch.utils.da... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# Meta-info
Author: Nelson Brochado
Created: 08/10/2017
Updated: 02/04/2018
# Description
Unit tests for the functions in the ands.algorithms.numerical.barycentric
module.
"""
import unittest
from ands.algorithms.numerical.barycentric import barycentric, compu... | nilq/baby-python | python |
# -*- coding=utf-8 -*-
__all__ = [
'tiny_imagenet',
'imagewoof2',
'imagenette2'
]
import os
import torch
import torchvision
_default_batch_size = 32
_default_num_workers = 4
def _transform(train=True):
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
if train:
return torchvi... | nilq/baby-python | python |
#!/usr/bin/python
import util
TAG_LIST_1 = ['keyspace', 'shard', 'type']
TAG_LIST_2 = ['type']
TAG_LIST_3 = ['method', 'keyspace', 'shard', 'type']
TAG_LIST_4 = ['method', 'keyspace', 'type']
def process_data(json_data):
epoch_time = util.get_epoch_time()
util.create_metric(epoch_time, "vitess.healthcheck... | nilq/baby-python | python |
import requests
import os
API_URL = 'http://127.0.0.1:8000/api/devices/devicetype/1/'
API_KEY = os.environ['TESTAUTH']
headers = {'Authorization': f'Token {API_KEY}'}
r = requests.delete(API_URL, headers=headers)
print(r.status_code)
| nilq/baby-python | python |
from django.test import TestCase
class AnalyzerTasksTestCase(TestCase):
@classmethod
def setUpTestData(cls):
pass
| nilq/baby-python | python |
#!/usr/bin/env python
import sys,argparse
import numpy
import os
import time, datetime
import h5py
import scipy.misc
import configobj
def get_valid_stacks(f_names):
f_names_valid = []
for fn in f_names:
with h5py.File(fn,"r") as f:
if "mean" in f.keys():
f_names_valid.append... | nilq/baby-python | python |
#coding=utf-8
# Copyright (c) 2018 Baidu, 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/licenses/LICENSE-2.0
#
# Unless required ... | nilq/baby-python | python |
import json
import requests
import code
class Demand():
def __init__(self, region='ap-southeast-1', instanceType='m4.large', operatingSystem='Linux'):
self.url = 'https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/{}/index.json'.format(region)
self.instanceType = instanceTyp... | nilq/baby-python | python |
"""
Our exception hierarchy:
* HTTPError
x RequestError
+ TransportError
- TimeoutException
· ConnectTimeout
· ReadTimeout
· WriteTimeout
· PoolTimeout
- NetworkError
· ConnectError
· ReadError
· WriteError
· CloseError
- ProtocolE... | nilq/baby-python | python |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | nilq/baby-python | python |
"""
GMail! Woo!
"""
__title__ = 'gmail'
__version__ = '0.1'
__author__ = 'Charlie Guo'
__build__ = 0x0001
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2013 Charlie Guo'
from gmail import Gmail
from mailbox import Mailbox
from message import Message
from utils import login, authenticate
| nilq/baby-python | python |
import pytest
from pype import *
from timeseries import *
__author__ = "Mynti207"
__copyright__ = "Mynti207"
__license__ = "mit"
def test_lexer():
# sample data
data = '''
3 + 4 * 10
+ -20 *2
'''
# pass data to lexer and tokenize
lexer.input(data)
for tok in lexer:
assert ... | nilq/baby-python | python |
# -*- coding:utf-8; -*-
class SolutionV1:
def letterCombinations(self, digits):
# 1. 定义一个集合存储最后的字符串
result = []
# 2. 然后定义一个递归函数,来生成符合条件的字符串
# 递归函数的参数如何定义:
# i 表示递归层数,虽然不知道i此时到底什么意思。
# digits表示要传递的数字字符,因为生成数字对应的字母字符串肯定是离不开这个参数的
def helper(i, digits, s):
... | nilq/baby-python | python |
##
## This file is part of the libsigrok project.
##
## Copyright (C) 2013 Martin Ling <martin-sigrok@earth.li>
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the Lice... | nilq/baby-python | python |
import os
import shutil
import audeer
import audformat
import audiofile as af
import pandas as pd
src_dir = 'src'
build_dir = audeer.mkdir('build')
# Prepare functions for getting information from file names
def parse_names(names, from_i, to_i, is_number=False, mapping=None):
for name in names:
key = n... | nilq/baby-python | python |
X_raw_0 = [
[0, 0.1, 0, 0, 0],
[0.1, 0, 0.1, 0, 0.1],
[0, 0.1, 0, 0.1, 0],
[0, 0, 0.1, 0, 0],
[0, 0.1, 0, 0, 0]
]
node_info_0 = [
{
'min_load': 0,
'max_load': 30,
'min_power': 0,
'max_power': 15,
'load_coeff': 10,
'load_ref': 20,
'power_co... | nilq/baby-python | python |
from typing import List
from pydantic import BaseModel, Field
__all__ = [
"ArticleRankDTO",
]
class ArticleRankDTO(BaseModel):
articleTitle: str = Field(
... ,
description = "文章标题"
)
viewCount: int = Field(
... ,
description = "文章浏览量"
... | nilq/baby-python | python |
# ===========================================================================
# Copyright 2013 University of Limerick
#
# This file is part of DREAM.
#
# DREAM is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Founda... | nilq/baby-python | python |
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2015 Toshio Kuratomi <tkuratomi@ansible.com>
# (c) 2017, Peter Sprygada <psprygad@redhat.com>
# (c) 2017 Ansible Project
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import fcntl
import gettext
import os
import ... | nilq/baby-python | python |
#!/usr/bin/env python3
#encoding=utf-8
#-----------------------------------------
# Usage: python3 4-getattr-builtins.py
# Description: compare __getattr__ and __getattribute__
#-----------------------------------------
class GetAttr:
eggs = 88 # eggs stored on class, spam on instance
def __init__(self... | nilq/baby-python | python |
# Exercício Python 024
# Leia o nome de uma cidade. Começa com 'SANTO'
cidade = str(input('Digite o nome de uma cidade: ')).strip()
minusculo = cidade.lower()
santo = 'santo'in minusculo[0:5]
print(santo)
# outra forma
print(cidade[:5].lower() == 'santo')
| nilq/baby-python | python |
import numpy
import pytest
import helpers
import meshio
@pytest.mark.parametrize(
"mesh",
[
helpers.tri_mesh,
helpers.tri_mesh_2d,
helpers.tet_mesh,
helpers.add_cell_data(helpers.tri_mesh, 1, dtype=float),
helpers.add_cell_data(helpers.tri_mesh, 1, dtype=numpy.int32),
... | nilq/baby-python | python |
"""
LINK: https://leetcode.com/problems/factorial-trailing-zeroes/
Given an integer n, return the number of trailing zeroes in n!.
Follow up: Could you write a solution that works in logarithmic time complexity?
Example 1:
Input: n = 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: n = 5
Outpu... | nilq/baby-python | python |
from generators import *
from laws import (monoid_laws, functor_laws, applicative_laws, monad_laws, trans_laws)
from fplib.maybe import Maybe
from fplib.transformer import trans
from fplib.ident_t import IdT
T = trans(IdT, Maybe)
def cmpidt(idt0, idt1):
return idt0.unwrap == idt1.unwrap
def test_idt_functor()... | nilq/baby-python | python |
"""
Energy level and transitions classes
"""
import numpy as np
import astropy.units as u
import astropy.constants as const
from fiasco.util import vectorize_where
__all__ = ['Level', 'Transitions']
class Level(object):
def __init__(self, index, elvlc):
self._index = index
self._elvlc = elvlc
... | nilq/baby-python | python |
"""
# -*- coding: utf-8 -*-
__author__ = "Akash"
__email__ = "akashjio6666@gmail.com"
__version__ = 1.0.0"
__copyright__ = "Copyright (c) 2004-2020 Leonard Richardson"
# Use of this source code is governed by the MIT license.
__license__ = "MIT"
Description:
Py-Insta Is A Python Library
... | nilq/baby-python | python |
import scrython
import time
query = input("Type the name of the set: ")
time.sleep(0.05)
sets = scrython.sets.Sets()
for i in range(sets.data_length()):
if sets.set_name(i) == query:
print("Set code:", sets.set_code(i).upper())
break
else:
continue
| nilq/baby-python | python |
import json
import binascii
import struct
import random
from io import BytesIO
import sys
from operator import itemgetter
class Item():
def __init__(self, name, index, quantity, rate):
self.name = name
self.index = index
self.quantity = quantity
self.rate = rate
def __repr__(self):
return ... | nilq/baby-python | python |
import os
from pytest import fixture
from zpz.filesys.path import relative_path
from zpz.spark import PySparkSession, ScalaSparkSession, SparkSession, SparkSessionError
livy_server_url = None
@fixture(scope='module')
def pysession():
return PySparkSession(livy_server_url)
@fixture(scope='module')
def scalases... | nilq/baby-python | python |
from benchbuild.projects.benchbuild.group import BenchBuildGroup
from benchbuild.utils.wrapping import wrap
from benchbuild.settings import CFG
from benchbuild.utils.compiler import lt_clang, lt_clang_cxx
from benchbuild.utils.downloader import Git
from benchbuild.utils.run import run
from benchbuild.utils.versions imp... | nilq/baby-python | python |
# Elaine Laguerta (github: @elaguerta)
# LBNL GIG
# File created: 28 May 2021
# Smell tests to verify Solution API functions
from gigpower.solution import Solution
from gigpower.solution_dss import SolutionDSS
from gigpower.solution_fbs import SolutionFBS
from gigpower.solution_nr3 import SolutionNR3
from gigpower.ut... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Django Models documentation build configuration file, created by
# sphinx-quickstart on Wed Nov 29 06:50:23 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in thi... | nilq/baby-python | python |
load("@bazel_tools//tools/jdk:toolchain_utils.bzl", "find_java_runtime_toolchain", "find_java_toolchain")
def _proto_path(proto):
"""
The proto path is not really a file path
It's the path to the proto that was seen when the descriptor file was generated.
"""
path = proto.path
root = proto.root... | nilq/baby-python | python |
"""
Methods for working with releases, including the releaseObject class
definition live here.
"""
# standard library imports
from datetime import datetime, timedelta
import json
# second party imports
from bson import json_util
from bson.objectid import ObjectId
import flask
import pymongo
# local imports
f... | nilq/baby-python | python |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
import os
import sys
import signal
import time
from datetime import datetime
from datetime import timedelta
# import cv2 as cv
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt # 导入模块 matplotlib.pyplot,并简写成 plt
import numpy as np # 导入... | nilq/baby-python | python |
"""
Class to represent the results of a prediction.
"""
import codecs
import logging
import os
import warnings
from numpy import ndarray
from sklearn.exceptions import UndefinedMetricWarning
from sklearn.metrics import \
confusion_matrix, \
recall_score, \
precision_score, \
f1_score, \
accuracy_sc... | nilq/baby-python | python |
import server_socket
import threading
class Microphone(object):
def __init__(self, host, port, steer):
self.steer = steer
self.socket = server_socket.Server(host, port)
self.client = self.socket.Get_Client()
def Recv(self) :
while True :
# 스레드를 돌면서 s... | nilq/baby-python | python |
#!/usr/bin/env python2
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""This simulates a real job by producing a lot of output."""
from __future__ import print_function
__author__ = 'asharif@google.com (Ahmad Sharif)'
import time
def Main():
"""The main function."""
for j in range(10):
for i in rang... | nilq/baby-python | python |
############## Configurator for command line programs
#### tests
# 2016 Portia Frances Limited for UBS
# Author: Thomas Haederle
import logging
logger = logging.getLogger(__name__)
import pytest
#from nose.tools import *
from configurator import Configurator
def test_configurator_initialize():
conf = Configurat... | nilq/baby-python | python |
def signed8(b):
if b > 127:
return -256 + b
else:
return b
def signed16(v):
v &= 0xFFFF
if v > 0x7FFF:
return - 0x10000 + v
else:
return v
def signed24(v):
v &= 0xFFFFFF
if v > 0x7FFFFF:
return - 0x1000000 + v
else:
return v
def read_... | nilq/baby-python | python |
# import geopandas
# from utils.common import load_shape
# from pathlib import Path
# import sys
# sys.path.append(str(Path(__file__).parent.parent))
# from configs import server_config
# # from shapely.geometry import shape
# from db_connection import DBConnection
# from alchemy import Eez
# import shapely.geometry as... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
__all__ = ("main",)
def main():
from lyricli.console import main
main()
if __name__ == "__main__":
main() | nilq/baby-python | python |
import nextcord
from util.mongo import Document
class afk_utils:
def __init__(self, bot):
self.db = bot.db
self.afk_db = Document(self.db, "afk_user_db")
async def create_afk(self, user, guild_id, reason):
dict = {
"_id" : user.id,
"guild_id" : guild_id... | nilq/baby-python | python |
from .core.serializers import *
| nilq/baby-python | python |
# firstline
# Foo header content
# Foo foo foo foo foo foo foo foo foo foo foo foo foo
# Foo foo foo foo foo foo foo foo foo foo foo foo foo
# Foo foo foo foo foo foo foo foo foo foo foo foo foo
# Foo foo foo foo foo foo foo foo foo foo foo foo foo
# Foo foo foo foo foo foo foo foo foo foo foo foo foo
# Foo foo foo fo... | nilq/baby-python | python |
from app.schemas.game_schema import Positions, Action
from .action_handler import ActionHandler
class MoveActionHandler(ActionHandler):
@property
def activity_text(self):
return f"{self.player} moved"
def execute(self):
move_where = self.payload.move_where
player_position = self.g... | nilq/baby-python | python |
import logging
import os
import re
from scanapi.errors import BadConfigurationError
from scanapi.evaluators.code_evaluator import CodeEvaluator
logger = logging.getLogger(__name__)
class StringEvaluator:
variable_pattern = re.compile(
r"(?P<something_before>\w*)(?P<start>\${)(?P<variable>[\w|-]*)(?P<end... | nilq/baby-python | python |
"""
A small tool to resize all Frames in a ByteBlower GUI project.
"""
import sys
import lxml.etree as ET
import random
if len(sys.argv) != 4:
print('Expected 2 arguments: <src bbp> <target bpp> <new frame size>')
sys.exit(-1)
filename = sys.argv[1]
target_name = sys.argv[2]
try:
new_size = int(sys.a... | nilq/baby-python | python |
# This Source Code Form is subject to the terms of the MIT
# License. If a copy of the same was not distributed with this
# file, You can obtain one at
# https://github.com/akhilpandey95/altpred/blob/master/LICENSE.
import sys
import json
import certifi
import urllib3
import requests
import numpy as np
import pandas a... | nilq/baby-python | python |
#!/usr/bin/env python
import os, sys, json, re, shutil
from utils.queryBuilder import postQuery
def prep_inputs(ml_dir, ctx_file, in_file):
# get context
with open(ctx_file) as f:
j = json.load(f)
# get kwargs
kwargs = j #mstarch - with containerization, "kwargs" are in context at top level... | nilq/baby-python | python |
#Faça um programa que leia nome e peso de várias pessoas, guardando
#tudo em uma lista. No final mostre:
#A)- Quantas pessoas foram cadatradas
#B)- Uma listagem com as pessoas mais pesadas
#C)- Uma listagem com as pessoas mais leves
temp = []
pessoas = []
mai = men = 0
while True:
temp.append(str(input('Nome: ')))... | nilq/baby-python | python |
# -*- coding: utf-8 -*_
#
# Copyright (c) 2020, Pureport, Inc.
# All Rights Reserved
"""
The credentials module handles loading, parsing and returning a valid
object that can be passed into a :class:`pureport.session.Session`
instance to authenticate to the Pureport API. This module will search
for credentials in wel... | nilq/baby-python | python |
import sublime, sublime_plugin
import winreg, subprocess
import re
from os import path
CONEMU = "C:\\Program Files\\ConEmu\\ConEmu64.exe"
CONEMUC = "C:\\Program Files\\ConEmu\\ConEmu\\ConEmuC64.exe"
try: # can we find ConEmu from App Paths?
apps = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\W... | nilq/baby-python | python |
"""
Created on Sat Mar 09 16:33:01 2020
@author: Pieter Cawood
"""
from mesa import Model
from mesa.time import RandomActivation
from mesa.space import MultiGrid
from mesa.datacollection import DataCollector
from mesa_agents import Parking, Wall, Space, Robot
from ta_world import MAPNODETYPES
class ... | nilq/baby-python | python |
'''
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:
What should we return when needle is an empty... | nilq/baby-python | python |
import requests
from bs4 import BeautifulSoup as bs
import pandas as pd
players_image_urls = []
url = 'https://www.pro-football-reference.com/players/'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0'}
page = requests.get(url,headers=headers, timeout=2, allow_r... | nilq/baby-python | python |
import pytest
from ethdata import ethdata
class TestAccountSetters(object):
def test_setter_1_address(self):
my_account = ethdata.Account("0x1cB424cB77B19143825004d0bd0a4BEE2c5e91A8")
assert my_account.address == "0x1cb424cb77b19143825004d0bd0a4bee2c5e91a8"
with pytest.raises(ValueError):
... | nilq/baby-python | python |
import struct
from binascii import b2a_hex, a2b_hex
from pymodbus.exceptions import ModbusIOException
from pymodbus.utilities import checkLRC, computeLRC
from pymodbus.framer import ModbusFramer, FRAME_HEADER, BYTE_ORDER
ASCII_FRAME_HEADER = BYTE_ORDER + FRAME_HEADER
# ----------------------------------------------... | nilq/baby-python | python |
#
# Copyright (c) nexB Inc. and others.
# SPDX-License-Identifier: Apache-2.0
#
# Visit https://aboutcode.org and https://github.com/nexB/ for support and download.
# ScanCode is a trademark of nexB Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... | nilq/baby-python | python |
b='You Yi Xue Sa Xu Li Li Yuan Dui Huo Sha Leng Pou Hu Guo Bu Rui Wei Sou An Yu Xiang Heng Yang Xiao Yao Fan Bi Ci Heng Tao Liu Fei Zhu Tou Xi Zan Yi Dou Yuan Jiu Zai Bo Ti Ying Tou Yi Nian Shao Ben Gou Ban Mo Gai En She Caan Zhi Yang Jian Yuan Shui Ti Wei Xun Zhi Yi Ren Shi Hu Ne Ye Jian Sui Ying Bao Hu Hu Ye Yang Li... | nilq/baby-python | python |
import json
from rest_framework.test import APITestCase
from django.urls import reverse
from rest_framework import status
from django.contrib.auth import get_user_model
from authors.apps.articles.models import Articles
from authors.apps.profiles.models import Profile
class TestGetEndpoint(APITestCase):
def set... | nilq/baby-python | python |
from sympy import Wild, Indexed
from contextlib import contextmanager
class DestructuringError(ValueError):
'''
Represent an error due to the impossibility to destructure a given term.
At the present, we neither provide meaningful error messages nor objects
related to the context in which this excep... | nilq/baby-python | python |
"""
**download.py**
A commandline utility to retrieve test data from
https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/ for use in evaluating
LSAnamoly.
**usage**: download.py [-h] --params YML_PARAMS --data-dir DATA_DIR
[--sc-url SC_URL] [--mc-url MC_URL]
Retrieve datasets for LsAnomaly evaluation. By def... | nilq/baby-python | python |
#!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
from queries import SparqlQuery
class event_precis(SparqlQuery):
"""
"""
def __init__(self, *args, **kwargs):
super(event_precis, self).__init__(*args, **kwargs)
self.query_title = 'Get event precis'
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright 2021 the HERA Project
# Licensed under the MIT License
import pytest
import glob
from pyuvdata import UVData
from pyuvdata import UVCal
from ..data import DATA_PATH
from .. import chunker
from hera_qm.utils import apply_yaml_flags
import numpy as np
import sys
def test_chunk_data_... | nilq/baby-python | python |
import argparse
import codecs
import json
import math
import os.path
import numpy as np
import tensorflow as tf
__all__ = ["create_default_hyperparams", "load_hyperparams",
"generate_search_lookup", "search_hyperparams", "create_hyperparams_file"]
def create_default_hyperparams(config_type):
"""create... | nilq/baby-python | python |
from fractions import Fraction
def isPointinPolygon(pointlist, rangelist):#射线法先判断点是否在大多边形里面
# 判断是否在外包矩形内,如果不在,直接返回false
xlist = []#装大多边形的点的横坐标
ylist = []#装大多边形的点的纵坐标
for i in range(len(rangelist)-1):
xlist.append(rangelist[i][0])
ylist.append(rangelist[i][1])
maxx = max(xlist)
m... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.