content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
# Author: Steven C. Dang
# Class for most common operations with TA2
import logging
import grpc
from os import path
from google.protobuf.json_format import MessageToJson
import pandas as pd
# D3M TA2 API imports
from .api_v3 import core_pb2, core_pb2_grpc
from .api_v3 import value_pb2
from .api_v3 import problem_pb... | nilq/baby-python | python |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
import MySQLdb
import requests
from lxml import etree,html
import re
from datetime import date,datetime
from time import sleep, time
import simplejson
import concurrent.futures
from concurrent.futures import ProcessPoolExecutor, as_completed
from tqdm import tqdm
from seleniu... | nilq/baby-python | python |
import numpy as np
from math import radians
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
def wind_rose(df, wd, nbins=16, xticks=8, plot=111, wind=True, ylim=False, yaxis=False, yticks=False):
"""
Return a wind rose.
Parameters
----------
df : DataFrame
The pandas Dat... | nilq/baby-python | python |
import pytest
import pystiche_papers.johnson_alahi_li_2016 as paper
@pytest.fixture(scope="package")
def styles():
return (
"composition_vii",
"feathers",
"la_muse",
"mosaic",
"starry_night",
"the_scream",
"udnie",
"the_wave",
)
@pytest.fixtur... | nilq/baby-python | python |
a = "Paul Sinatra"
print(a.count("a"))
print(a.count("a",0,10))
print(a.endswith("tra"))
print(a.endswith("ul",1,8))
print(a.find("a"))
print(a.find("a",2,10))
print(len(a))
print(a.lower())
print(max(a))
print(min(a))
print(a.replace("a","b"))
print(a.split(" "))
print(a.strip())
print(a.upper()) | nilq/baby-python | python |
"""Token constants."""
# Auto-generated by Tools/scripts/generate_token.py
__all__ = ['tok_name', 'ISTERMINAL', 'ISNONTERMINAL', 'ISEOF']
ENDMARKER = 0
NAME = 1
NUMBER = 2
STRING = 3
NEWLINE = 4
INDENT = 5
DEDENT = 6
LPAR = 7
RPAR = 8
LSQB = 9
RSQB = 10
COLON = 11
COMMA = 12
SEMI = 13
PLUS = 14
MINUS = 15
STAR = 16
S... | nilq/baby-python | python |
from django.contrib.auth.models import User
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.parsers import JSONParser
from rest_framework.permissions import IsAuthenticated
from rest_framework.renderers import DocumentationRen... | nilq/baby-python | python |
from __future__ import print_function
import os
import sys
import curses
import txtsh.log as log
class Cursor(object):
def __init__(self):
self.y = 4
self.x = 0
self.up_limit = 4
self.down_limit = 4
def display(self):
curses.setsyx(self.y, self.x)
curses.do... | nilq/baby-python | python |
#!/usr/bin/pypy
from sys import *
from random import *
T, n, p, K0 = map(int, argv[1:]);
print T
for i in xrange(T):
E = []
mark = []
for i in xrange(2, n * p / 100 + 1):
E.append((randint(1, i - 1), i))
mark.append(0)
for i in xrange(n * p / 100 + 1, n + 1):
j = randrange(0, ... | nilq/baby-python | python |
"""
devl.py -- The more cross-platform makefile substitute with setup tools
Usage
=====
For first-time setup of this file, type 'python devl.py'
How to Add Functionality
========================
User Variables
--------------
To add a new user variable, you should
- Update the ``user_variables`` dict in this modul... | nilq/baby-python | python |
# Copyright 2021 Ash Hellwig <ash@ashwigltd.com> (https://ash.ashwigltd.com)
#
# 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 requ... | nilq/baby-python | python |
"""Init module."""
from . import contypes, exceptions, models, repository, service
from .controller import controller
__all__ = [
"controller",
"contypes",
"exceptions",
"models",
"repository",
"service",
]
| nilq/baby-python | python |
import argparse
def str2bool(v):
return v.lower() in ("yes", "y", "true", "t", "1")
parser = argparse.ArgumentParser(description="test global argument parser")
# script parameters
parser.add_argument('-g', '--GT_PATH', default='gt/gt.zip', help="Path of the Ground Truth file.")
parser.add_argument('-s',... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.dagrun_operator import TriggerDagRunOperator
default_args = {'owner': 'afroot05', 'retries': 2, 'retry_delay': timedelta(minutes... | nilq/baby-python | python |
from pointing.envs import SimplePointingTask
from pointing.users import CarefulPointer
from pointing.assistants import ConstantCDGain, BIGGain
from coopihc.bundle import PlayNone, PlayAssistant
import matplotlib.pyplot as plt
# ===================== First example =====================
# task = SimplePointingTask(gr... | nilq/baby-python | python |
from os.path import join
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import argparse
from repro_lap_reg.load_param_seq_results import load_param_seq_results
from repro_lap_reg.viz_seq import plot_param_vs_metric_by_model
from repro_lap_reg.viz_utils import savefig
from repro_lap_reg.util... | nilq/baby-python | python |
from collections import Counter
from dataclasses import dataclass
from itertools import zip_longest
@dataclass
class Point:
x: int
y: int
def __hash__(self):
return hash((self.x, self.y))
@dataclass
class Segment:
a: Point
b: Point
def orthogonal(self):
return self.a.x == self.b.x or self.a.y ==... | nilq/baby-python | python |
# Config
# If you know what your doing, feel free to edit the code.
# Bot Token
# Token of the Bot which you want to use.
TOKEN = ""
# Log File
# Where all the logs of everything are stored.
# Default: "logs.txt"
LOG_FILE = "logs.txt"
# File where the codes are stored.
# Codes are given out by lines, so... | nilq/baby-python | python |
import discord
from discord.ext import commands
class ListMyGames(commands.Cog):
def __init__(self, client):
self.client = client
self.db = self.client.firestoreDb
@commands.command(brief="Lists games you have already acquired")
async def listmygames(self, ctx):
await ctx.author.s... | nilq/baby-python | python |
# Validating phone numbers
# Problem Link: https://www.hackerrank.com/challenges/validating-the-phone-number/problem
import re
for _ in range(int(input())):
print("YES" if re.match("^[789]\d{9}$", input()) else "NO")
| nilq/baby-python | python |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import time
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB, BernoulliNB, MultinomialNB
names=['AGE','TB','DB','TP','Albumin','A/G','sgpt','sgot','ALKPHOS','GENDER']
dataset=pd.read_csv("Indian Liver ... | nilq/baby-python | python |
"""
taskcat python module
"""
from ._cfn.stack import Stack # noqa: F401
from ._cfn.template import Template # noqa: F401
from ._cli import main # noqa: F401
from ._config import Config # noqa: F401
__all__ = ["Stack", "Template", "Config", "main"]
| nilq/baby-python | python |
# Copyright 2016 The Johns Hopkins University Applied Physics Laboratory
#
# 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 os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-emailuser',
version='0.0.1',
packages=['... | nilq/baby-python | python |
"""Top-level package for explainy."""
__author__ = """Mauro Luzzatto"""
__email__ = "mauroluzzatto@hotmail.com"
__version__ = '0.1.14'
| nilq/baby-python | python |
__version__ = "0.0.1"
__required_biorbd_min_version__ = "1.2.8"
| nilq/baby-python | python |
# Import library
import sys
import rohub
import os
sys.path.insert(0, os.path.join(os.getcwd(), 'misc', 'rohub'))
import config
# Authenticate
rohub.login(username=config.username, password=config.password)
# metadata
metadata_contribution = {
'environment': 'agriculture',
'topic': 'exploration',
'filenam... | nilq/baby-python | python |
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
"""Very simple inter-object notification s... | nilq/baby-python | python |
import os
import pathlib
import shutil
from typing import List
from gaas.applications.image_coloring.config import \
ANIME_SKETCH_COLORIZATION_DATASET_DATASET_ID
from gaas.applications.image_coloring.dataset import \
AnimeSketchColorizationDatasetGenerator
from gaas.applications.image_coloring.utils.locations ... | nilq/baby-python | python |
from . import extract | nilq/baby-python | python |
from typing import Dict, Any
from typing import Tuple
class DataBuffer:
"""
Databuffer with rollover
"""
def __init__(self, cols, size):
self.size = size
self.entries = [None for i in range(size)]
self.counter = 0
self.cols = cols
self.col_to_idx = {c: idx for... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-02-18 18:58
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0025_auto_20190217_2026'),
]
operations = [
migrations.AddFiel... | nilq/baby-python | python |
__all__ = ["battleground", "bridge", "forest", "mountains", "store"]
| nilq/baby-python | python |
################################################################################
# Peach - Computational Intelligence for Python
# Jose Alexandre Nalon
#
# This file: fuzzy/control.py
# Fuzzy based controllers, or fuzzy inference systems
################################################################################
... | nilq/baby-python | python |
import this # => display the Zen of Py
# 1. Any python file can be imported as module
# to load from another module:
import sys
sys.path += ["path_to_folder"] # and import MyModule
if __name__ == "__main__":
pass # this code will exec only if the script is ran. if loaded as module, it will not run
# PACKAGES
# ... | nilq/baby-python | python |
import math
import itertools
import functools
import multiprocessing
import asyncio
import uuid
import numpy as np
import pymatgen as pmg
import lammps
from lammps.potential import (
write_table_pair_potential,
write_tersoff_potential,
write_stillinger_weber_potential,
write_gao_weber_potential,
w... | nilq/baby-python | python |
# Generated by Django 2.0.5 on 2018-09-11 16:17
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("barriers", "0007_auto_20180905_1553")]
operations = [
migrations.RemoveField(model_name="barrierstatus", name="barrier"),
migrations.RemoveField(model_na... | nilq/baby-python | python |
### extends 'class_empty.py'
### block ClassImports
# NOTICE: Do not edit anything here, it is generated code
from . import gxapi_cy
from geosoft.gxapi import GXContext, float_ref, int_ref, str_ref
### endblock ClassImports
### block Header
# NOTICE: The code generator will not replace the code in this block
### end... | nilq/baby-python | python |
from contextlib import nullcontext as expectation_of_no_exceptions_raised
import pytest
from _config.combo.cookie_banner import JYLLANDSPOSTEN_ACCEPT_COOKIES
from _config.combo.log_in import (AMAZON_LOGIN_CREDENTIALS, AMAZON_LOGIN_FORM, JYLLANDSPOSTEN_LOGIN_CREDENTIALS,
JYLLANDSPOSTEN... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import copy
import solutions.utils as utils
class CoProcessor:
def __init__(self, debug=True):
self._registers = {c: 0 for c in 'abcdefgh'}
self._pc = 0
self._mul_counter = 0
self._debug = debug
self._states = set()
... | nilq/baby-python | python |
"""
Object Co-segmentation Datasets
author - Sayan Goswami
email - sayan.goswami.106@gmail.com
"""
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
from torchvision.datasets import ImageFolder, DatasetFolder
from torchvision.transforms import ToTensor
class DatasetABC(Dataset):
""... | nilq/baby-python | python |
""" This simulation is adapted from main for Bayesian inference analysis """
from scipy.signal import find_peaks
import matplotlib.pyplot as plt
import plotter
import network
import os
import pickle
import numpy as np
# %%markdown
#
# %%
# do not use spatial convolution (set kernels supe small)
no_spatial_conv = Tru... | nilq/baby-python | python |
"""
Core functions.
"""
import numpy as np
import warnings
from scipy.optimize import brentq, fsolve
from scipy.stats import ttest_ind, ttest_1samp
from fractions import Fraction
from .utils import get_prng, potential_outcomes, permute
def corr(x, y, alternative='greater', reps=10**4, seed=None, plus1=True):
r... | nilq/baby-python | python |
"""ETS Prediction View"""
__docformat__ = "numpy"
import datetime
import os
import warnings
from typing import Union
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import pandas as pd
from pandas.plotting import register_matplotlib_converters
from gamestonk_terminal import feat... | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This file is part of pyunicorn.
# Copyright (C) 2008--2019 Jonathan F. Donges and pyunicorn authors
# URL: <http://www.pik-potsdam.de/members/donges/software>
# License: BSD (3-clause)
#
# Please acknowledge and cite the use of this software and its authors
# when results a... | nilq/baby-python | python |
class AppriseNotificationFailure(Exception):
# Apprise returns false if something goes wrong
# they do not have Exception objects, so we're creating a catch all here
pass
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2019 Lorenzo
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, ... | nilq/baby-python | python |
# 文字列
import keyword
from importlib import import_module
import re
import string
'''
[文字列モジュール|string[|モジュール]]をインポートする
@prefix(sub;部分文字列)
@alt(先頭|最初|左[側|端])
@alt(末尾|最後|後ろ|右[側|端])
@alt(左側|左)
@alt(右側|右)
'''
string = import_module('string')
keyword = import_module('keyword')
s = 'ABC abc 123' # 文字列 s, s2, s3
s2 = 'a... | nilq/baby-python | python |
""" Functions for running the PEPR model defined in the
--Univeral visitation law of human mobility-- paper
(https://www.nature.com/articles/s41586-021-03480-9).
"""
import random
import time
import itertools as it
import matplotlib.pyplot as plt
import numpy as np
def levy_flight(num_steps: int,... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from authomatic import providers
class MozillaPersona(providers.AuthenticationProvider):
pass
| nilq/baby-python | python |
import requests
from kong.api import API
class Connection:
def __init__(self, url='http://localhost:8001'):
self.url = url
def _get(self, path='', **request_args):
return requests.get(self.url + path, **request_args)
def _post(self, path='', **request_args):
return requests.pos... | nilq/baby-python | python |
from discoPy.rest.base_request.base_request import BaseRequestAPI
class StageData(BaseRequestAPI):
'''Contains a collection of stage related methods.'''
def __init__(self, token: str, url: str=None):
super().__init__(token, url)
def create_stage_instance(self, channel_id, topic: str, privacy_leve... | nilq/baby-python | python |
#!/usr/bin/env python3
# Python fizzbuzz implementation
for num in range(1, 25):
#check if number is divisible by both 3 and 5
if num % 3 == 0 and num % 5 == 0:
print("FizzBuzz")
#check if number divisible by 3
elif num % 3 == 0:
print("Fizz")
# check if number is divisible... | nilq/baby-python | python |
import re
from dataclasses import dataclass
from typing import List, Tuple, Optional
import attr
from new.data_aggregation.utils import MethodSignature
@dataclass(frozen=True)
class Scope:
name: Optional[str] = None # attr.attrib()
bounds: Optional[Tuple[int, int]] = None # attr.attrib()
type: Optiona... | nilq/baby-python | python |
# test function dot
def projCappedSimplex():
import numpy as np
from limetr.utils import projCappedSimplex
ok = True
# setup test problem
# -------------------------------------------------------------------------
w = np.ones(10)
sum_w = 9.0
tr_w = np.repeat(0.9, 10)
my_w = projC... | nilq/baby-python | python |
# Author: Mikita Sazanovich
import argparse
import itertools
import os
import sys
import numpy as np
import tensorflow as tf
sys.path.append('../')
from deepq import StatePotentialRewardShaper, Estimator, StatePreprocessor, PrioritizedReplayBuffer
from deepq import get_last_episode
from dotaenv import DotaEnvironme... | nilq/baby-python | python |
from pptx import Presentation
from pptx.chart.data import CategoryChartData
from pptx.enum.chart import XL_CHART_TYPE
from pptx.util import Inches
class Present():
def test_pptx(self):
# create presentation with 1 slide ------
prs = Presentation()
slide = prs.slides.add_slide(prs.slide_lay... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 25 13:08:47 2019
@author: Mario
"""
import subprocess, sys
if __name__ == "__main__":
#########################################
###### DISTRIBUTED COMPUTING SETUP ######
#########################################
rescanNetwork = True
if rescanNet... | nilq/baby-python | python |
import argparse
import configparser
import json
import os
import sys
import time
import requests
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from util import logger
class ConversationScraper:
"""Scraper that retrieves, process and stores all messages belonging to a specific Facebook conversat... | nilq/baby-python | python |
import sys
import timeit
import zmq
from kombu import Connection
from timer import Timer
TOTAL_MESSAGES = int(sys.argv[1])
amqp_timer = Timer()
zmq_timer = Timer()
def log(msg):
pass
# print(msg)
def main():
context = zmq.Context()
sockets = {}
with Connection("amqp://guest:guest@127.0.0.1:... | 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 |
# import psycopg2
# import os
# import csv
# class PostgreSQL:
# def __init__(self, host, port, username, password, database):
# self.host = host
# self.port = port
# self.username = username
# self.password = password
# self.database = database
# se... | nilq/baby-python | python |
from __future__ import print_function, absolute_import
import numpy as np
import torch
from torch.utils.data import Dataset
from functools import reduce
#####################################
# data loader with four output
#####################################
class PoseDataSet(Dataset):
def __init__(self, poses_... | nilq/baby-python | python |
import os
import pandas as pd
from base import BaseFeature
from google.cloud import storage, bigquery
from google.cloud import bigquery_storage_v1beta1
from encoding_func import target_encoding
class TargetEncodingResponseTimeDiff(BaseFeature):
def import_columns(self):
return [
"1"
]
... | nilq/baby-python | python |
import numpy as np
from math import pi
'''
Class to calculate the inverse kinematics for the stewart platform.
Needs pose and twist input to calculate leg length and velocity
All length-units is written in meters [m]
'''
class InverseKinematics(object):
def __init__(self):
# minimum po... | nilq/baby-python | python |
import torch.nn as nn
from typing import Optional, Union, List
from .model_config import MODEL_CONFIG
from .decoder.deeplabv3plus import DeepLabV3PlusDecoder
from .get_encoder import build_encoder
from .base_model import SegmentationModel
from .lib import SynchronizedBatchNorm2d
BatchNorm2d = SynchronizedBatchNorm2d
... | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import argparse
def load():
"""
Description
Returns
Arguments object.
"""
parser = argparse.ArgumentParser(description="Program description",
formatter_class=argparse.ArgumentDefaultsHelpFormatter
... | nilq/baby-python | python |
from .model import Model
class Datacenters(Model):
pass
| nilq/baby-python | python |
import threading
import typing as tp
from contextlib import contextmanager
from dataclasses import dataclass
from treex import types
@dataclass
class _Context(threading.local):
call_info: tp.Optional[tp.Dict["Module", tp.Tuple[types.Inputs, tp.Any]]] = None
def __enter__(self):
global _CONTEXT
... | nilq/baby-python | python |
"""empty message
Revision ID: b1f6e283b530
Revises:
Create Date: 2021-06-15 12:34:40.497836
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b1f6e283b530'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... | nilq/baby-python | python |
from pymatgen.electronic_structure.core import Spin, Orbital
from pymatgen.io.vasp.outputs import BSVasprun, Eigenval
from pymatgen.io.vasp.inputs import Kpoints, Poscar, Incar
from pymatgen.symmetry.bandstructure import HighSymmKpath
from vaspvis.unfold import unfold, make_kpath, removeDuplicateKpoints
from pymatgen.c... | nilq/baby-python | python |
#!/usr/bin/env python
# mainly taken from https://github.com/rochaporto/collectd-openstack
import collectd
import datetime
import traceback
class Base(object):
def __init__(self):
self.username = 'admin'
self.password = 'admin'
self.verbose = False
self.debug = False
self.... | nilq/baby-python | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import numpy as np
import tensorflow as tf
import cv2
from utils.misc import get_center
Rectangle = collections.namedtuple('Rectangle', ['x', 'y', 'width', 'height'])
def get_gauss_filter... | nilq/baby-python | python |
import matplotlib.pyplot as plt
import numpy as np
import wave
import sys
import statistics
########################################
# INPUT PARAMETER #
########################################
bpm = 136
offsetms = 0 # offset for beat grid in ms. Moves the beat grid to the right and is used to al... | nilq/baby-python | python |
class Solution:
def mctFromLeafValues(self, arr: List[int]) -> int:
"""
[6,2,4]
l
r
k
[12,24] [24, 8]
[36] [32]
[6,2,4,1]
l r
k
[12,24, 6] [8]
... | nilq/baby-python | python |
screen = None
window = None
class Game():
scene = 'title'
state = ''
interaction = -1
interaction_level = -1
class Cursor():
menu = 0
class Camera():
position = [-6, -40]
class Field():
location = 'home'
player_position = [1, 1]
player_face = 'D'
class Player():
inventory =... | nilq/baby-python | python |
# Electrum - Lightweight Bitcoin Client
# Copyright (c) 2012 Thomas Voegtlin
#
# 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 t... | nilq/baby-python | python |
from datalabframework import params, project
import os
from textwrap import dedent
import pytest
from testfixtures import TempDirectory
@pytest.fixture()
def dir():
with TempDirectory() as dir:
original_dir = os.getcwd()
os.chdir(dir.path)
p = project.Config()
p.__class__._insta... | nilq/baby-python | python |
import os,time,requests,re
from time import sleep
id=[]
def search(url):
global id
sleep(2)
req=requests.get(url).text
usr=re.findall(r'<td class="bz ca"><a href="(.*?)"><div class="cb"><div class="cc">(.*?)</div></div>',req)
for user in usr:
username=user[0].replace("/","")
if 'prof... | nilq/baby-python | python |
import logging
import json
class Logger:
def __init__(self):
pass
@staticmethod
def log(info_type, message):
try:
uid = json.loads(str(message[0]))['result']
if len(uid) == 16:
uid_file = open('./chaostoolbox/data/log/uid.log','a')
ui... | nilq/baby-python | python |
import os
import glob
import re
path = '\Documents\python\C++Examples'
gramHash = {}
for filename in glob.glob('*.cpp'):
outFile = open('KnownCPP.txt', 'a')
fileOpen = open(filename, 'r', encoding='utf8', errors='ignore')
fileString = ""
for line in fileOpen:
# Removes non ASCII characters
lin... | nilq/baby-python | python |
import torch
from ncc.modules.decoders.ncc_incremental_decoder import NccIncrementalDecoder
class SequenceCompletor(object):
def __init__(
self,
retain_dropout=False,
):
"""Generates translations of a given source sentence.
Args:
retain_dropout (bool, optional): u... | nilq/baby-python | python |
from django.forms import ModelForm
from django.test import TestCase
from .models import JSONNotRequiredModel
class JSONModelFormTest(TestCase):
def setUp(self):
class JSONNotRequiredForm(ModelForm):
class Meta:
model = JSONNotRequiredModel
fields = '__all__'
... | nilq/baby-python | python |
import collections
class Equalizer:
def __init__(self, levels: list):
_dict = collections.defaultdict(int)
_dict.update(levels)
_dict = [{"band": i, "gain": _dict[i]} for i in range(15)]
self.eq = _dict
self.raw = levels
@classmethod
def build(cls, *, levels: li... | nilq/baby-python | python |
# Copyright 2019-2020 SURF.
# 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, soft... | nilq/baby-python | python |
import sys,os
import traceback
import time
import shutil
import json
import requests
from selenium import webdriver
from PIL import Image
class ScriptError (Exception):
pass
def iw (webhook:str, message:str):
"""
post message to slack channel
"""
data = json.dumps({
'text' : message
})
... | nilq/baby-python | python |
import json
from time import sleep
try:
from typing import Optional, Tuple
except ImportError:
pass
from google_play_scraper import Sort
from google_play_scraper.constants.element import ElementSpecs
from google_play_scraper.constants.regex import Regex
from google_play_scraper.constants.request import Format... | nilq/baby-python | python |
from ..sql_helper import SQLHelper
from shapely import wkb
from shapely.geometry import Polygon
from .filtering import filtering_objects
def generate_rectangle_information(form):
"""
Функция для генерации информации по области
:param form: форма из POST запроса с координатами области (прямоугольника) и 6 ... | nilq/baby-python | python |
from enum import Enum, unique
@unique
class MeboCommands(Enum):
READERS = "READERS"
FACTORY = "FACTORY"
BAT = "BAT"
WHEEL_LEFT_FORWARD = "WHEEL_LEFT_FORWARD"
WHEEL_LEFT_BACKWARD = "WHEEL_LEFT_BACKWARD"
WHEEL_RIGHT_FORWARD = "WHEEL_RIGHT_FORWARD"
WHEEL_RIGHT_BACKWARD = "WHEEL_RIGHT_BACKWAR... | nilq/baby-python | python |
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Final, Dict, Optional, final, List, Any
from ftplib import FTP_TLS
from functools import cached_property
import ssl
import os
class FTPClient(ABC):
HOSTS: Final[Dict[str, Optional[str]]] = {
'main': 'ree... | nilq/baby-python | python |
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
name = 'toyui'
namespace = 'toy'
export = 'TOY_UI_EXPORT'
subdir = 'toyui'
dependencies = ['toyobj']
rootdir = dir_path
basetypes = [] | nilq/baby-python | python |
# This is a script that calculates WER of different decades in vks_kotus_sample.json.
# There are currently some decades not analysed, as we got sufficient picture when
# we just ensured that there are no excessive gaps of several decades.
# Also the current corpus is temporally relatively limited, so this is a minor ... | nilq/baby-python | python |
# ---------------------------------------------------------------------
# Vendor: Zyxel
# OS: ZyNOS_EE
# ---------------------------------------------------------------------
# Copyright (C) 2007-2011 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : qichun tang
# @Date : 2020-12-15
# @Contact : qichun.tang@bupt.edu.cn
import hashlib
from copy import deepcopy
from typing import Union, Dict, Any
import numpy as np
from ConfigSpace import Configuration
from scipy.sparse import issparse
def get_hash_o... | nilq/baby-python | python |
import unittest
from etl import sources
from unittest.mock import patch, MagicMock
class TestODKSource(unittest.TestCase):
def test_fix_odk_sunmission(self):
""" Testing fix odk submission"""
data = {
"@a": "a",
"b": "b",
"orx:meta": "should_not_be_there"
... | nilq/baby-python | python |
"""Tests for driver.py"""
import pytest
import pandas as pd
from pandas.testing import assert_frame_equal
from timeflux.core.io import Port
def test_nexus():
assert True
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
from .file_read_backwards import FileReadBackwards # noqa: F401
__author__ = """Robin Robin"""
__email__ = 'robin81@gmail.com'
__version__ = '1.1.2'
__github__ = 'https://github.com/robin81/file_read_backwards'
| nilq/baby-python | python |
import numpy as np
class Stats(list):
def __init__(self,list):
self.list = list
self.length = len(list)
self.mean = sum(list)/self.length
#If list is even
if self.length % 2 == 0:
self.medianEven = median(list)
else:
self.medianOdd = median(l... | nilq/baby-python | python |
expected_output = {
'vll': {
'MY-QINQ-VLL-LOCAL': {
'vll_id': 4,
'ifl_id': '4096',
'state': 'UP',
'endpoint': {
1: {
'type': 'tagged',
'outer_vlan_id': 100,
'inner_vlan_id': 45,
'interface': 'ethernet2/1',
'cos': '--'
},
... | nilq/baby-python | python |
""" Given an array A of strings made only from lowercase letters, return a list
of all characters that show up in all strings within the list (including
duplicates). For example, if a character occurs 3 times in all strings but
not 4 times, you need to include that character three times in the final
answe... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.