content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
# Copyright 2015, Pinterest, Inc.
#
# 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 writ... | nilq/baby-python | python |
from datetime import date
import click
@click.group()
def cli():
"Utility for http://b3.com.br datasets"
@cli.command()
@click.option("--date", type=click.DateTime(formats=["%Y-%m-%d"]))
@click.option("--chunk-size", type=int, default=10000)
def download(date, chunk_size):
"""Downloads quotes data"""
if... | nilq/baby-python | python |
import torch
from torchvision.datasets.folder import default_loader
from torch.utils import data
from tqdm import tqdm
import sys
import numpy as np
import struct
class DatasetBin(data.Dataset):
def __init__(self, meta_filename, bin_filename, meta_columns, transform=None, targets_transform=None, loader=default_lo... | nilq/baby-python | python |
import streamlit as st
from pdf2docx import Converter
pdf_file = 'pdf文件路径'
docx_file = '输出word文件的路径'
cv = Converter(pdf_file)
cv.convert(docx_file, start=0, end=None)
cv.close()
st.file_uploader(label, type=None, accept_multiple_files=False, key=None, help=None, on_change=None, args=None, kwargs=None)
st.downl... | nilq/baby-python | python |
import logging
import textwrap
from pathlib import Path
from typing import Optional
import click
from tabulate import tabulate
from bohr import api
from bohr.datamodel.bohrrepo import load_bohr_repo
from bohr.util.logging import verbosity
logger = logging.getLogger(__name__)
@click.group()
def dataset():
pass
... | nilq/baby-python | python |
import requests
import json
from datetime import datetime, timedelta
import logging
bLoadWeatherModelFromFile = False
class WeatherQueryProxy():
def __init__(self, apikey, refreshtimeoutinminutes):
self.queryCache = {}
self.api_key = apikey
self.queryInvalidationTimeout = timede... | nilq/baby-python | python |
#Exercício Python 096: Faça um programa que tenha uma função chamada área(), que receba as dimensões de um terreno retangular (largura e comprimento) e mostre a área do terreno.
#Funções utilizadas no programa principal
def mostraLinha():
print("-" * 30)
def calculoArea (x, y):
area = x * y
print(f"O terr... | nilq/baby-python | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | nilq/baby-python | python |
import re
try:
import json
except ImportError:
import simplejson as json
from rbtools.api.errors import APIError
from rbtools.commands import (Command,
CommandError,
CommandExit,
Option,
Par... | nilq/baby-python | python |
'''
Alena will manage directories
'''
import os
from pathlib import Path
def cleaning_service(pathsToClean, images = False, videos = False):
if images:
if pathsToClean.get('original'):
if Path(os.environ.get('IMAGE_ORIGINAL_LOCAL_PATH') + pathsToClean['original']).i... | nilq/baby-python | python |
from .custom_unet import custom_unet
from .custom_vnet import custom_vnet
from .vanilla_unet import vanilla_unet
from .satellite_unet import satellite_unet
| nilq/baby-python | python |
# Generated by Django 3.1.3 on 2020-12-19 15:03
from django.db import migrations, models
import django.db.models.expressions
class Migration(migrations.Migration):
dependencies = [
('events', '0006_auto_20201215_1622'),
]
operations = [
migrations.RemoveConstraint(
model_nam... | nilq/baby-python | python |
# Create a function named remove_middle which has three parameters named lst, start, and end.
# The function should return a list where all elements in lst with an index between start and end(inclusive) have been removed.
# For example, the following code should return [4, 23, 42] because elements at indices 1, 2, and ... | nilq/baby-python | python |
import pytest
from erp import schema
from erp import forms
from erp.models import Accessibilite
from erp.schema import get_help_text_ui, get_help_text_ui_neg
@pytest.fixture
def form_test():
def _factory(name, value):
instance = Accessibilite(**{name: value})
form = forms.ViewAccessibiliteForm(i... | nilq/baby-python | python |
import logging
import sys
import os
from tasker.master.Master import Master
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO, handlers=[logging.StreamHandler(sys.stdout)])
def supply():
n = 1
while n <= 5:
task = {
"id": "test-{}".format(n),
... | nilq/baby-python | python |
import datetime as dt
from os.path import splitext
def add_ts_to_filename(filepath):
filename, extension = splitext(filepath)
ts = dt.datetime.today().strftime('%Y%m%dT%H%M%S')
filename_with_ts = f"{filename}_{ts}{extension}"
return filename_with_ts
if __name__ == '__main__':
print(add_ts_to_file... | nilq/baby-python | python |
import json
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
j = len(nums) - 1
i = 0
while i < j:
if nums[i] == val and nums[j] != val:
nums[i... | nilq/baby-python | python |
from enum import IntFlag
from .ProcStates import *
class Process:
def __init__(self, n_cores=4096, time_needed=1000, process_id = 0,state = PROC_STATE.WAITING,
scheduled_start_time=0, name="CIFAR" ):
self.n_cores = n_cores
self.needed_time = time_needed
self.process_id = ... | nilq/baby-python | python |
pas = float(input('Quantos Km você irá percorrer'))
pas1 = pas * 0.45
pas2 = pas * 0.5
if pas > 200:
print('Sua passagem saí por R${:.2f}' .format(pas1))
else:
print('Sua passagem saí por R${:.2f}'.format(pas2))
| nilq/baby-python | python |
import json
from http.client import HTTPResponse
from urllib.parse import urlencode
from urllib.request import urlopen
class MeasurementUnit:
def __init__(self, name: str, temperature: str, wind_speed: str):
self.name = name
self.temperature = temperature
self.wind_speed = wind_speed
cla... | nilq/baby-python | python |
from os.path import abspath, dirname, join
from setuptools import find_packages, setup
# Fetches the content from README.md
# This will be used for the "long_description" field.
with open(join(dirname(abspath(__file__)), "README.md"), encoding='utf-8') as f:
README_MD = f.read()
setup(
# The name of your proje... | nilq/baby-python | python |
import random
import numpy as np
from time import sleep
def AgentModel(Observation,actions,reward):
sleep(0.05)
#action = random.choice(actions)
Observation_size = Observation.size()
action_size = len(actions)
qtable = np.zeros((Observation_size, action_size))
return action | nilq/baby-python | python |
#----------------------------------------------------------------------
# Libraries
from PyQt6.QtWidgets import QGridLayout, QDialog, QDialogButtonBox, QLabel, QSizePolicy
from PyQt6.QtGui import QPixmap
from PyQt6.QtCore import Qt
from .QBaseApplication import QBaseApplication
from .QGridWidget import QG... | nilq/baby-python | python |
""" plugin example for autofile template system """
from typing import Iterable, List, Optional
import autofile
# specify which template fields your plugin will provide
FIELDS = {"{foo}": "Returns BAR", "{bar}": "Returns FOO"}
@autofile.hookimpl
def get_template_help() -> Iterable:
"""Specify help text for you... | nilq/baby-python | python |
"""
appends JSON wine records from given data, formats and sort'em,
output is JSON file, contains summary information by built-in parameters
"""
winedata_full = []
avg_wine_price_by_origin = []
ratings_count = []
def string_comb(raw_str):
form_str = ' '.join(
raw_str[1:-1].split()
).replace(
... | nilq/baby-python | python |
#!/usr/bin/env python3
# @generated AUTOGENERATED file. Do not Change!
from dataclasses import dataclass, field as _field
from ...config import custom_scalars, datetime
from gql_client.runtime.variables import encode_variables
from gql import gql, Client
from gql.transport.exceptions import TransportQueryError
from fu... | nilq/baby-python | python |
#!/usr/bin/env python3
# Copyright (c) 2004-present Facebook All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from gql.transport.exceptions import TransportServerError
from psym.common.constant import __version__
from .api.equipment_type impor... | nilq/baby-python | python |
import os
import cv2
import numpy as np
import argparse
from SSRNET_model import SSR_net, SSR_net_general
import sys
import timeit
from moviepy.editor import *
from keras import backend as K
def draw_label(image, point, label, font=cv2.FONT_HERSHEY_SIMPLEX,
font_scale=1, thickness=2):
size = cv2.get... | nilq/baby-python | python |
#!/usr/bin/env python3
import sys
assert_statement = "Requires Python{mjr}.{mnr} or greater".format(
mjr='3',
mnr='4')
assert sys.version_info >= (3, 4), assert_statement
from groupby import main
if __name__ == '__main__':
main()
| nilq/baby-python | python |
import importlib
from contextlib import ContextDecorator
from django.conf import settings
## add those to settings.py
##
## MOCKABLE_NAMES = {
## "MockableClassName": {
## "test": 'path.to.some.ServiceMockError',
## "development": 'path.to.some.ServiceMockOk',
## # "production": 'please.don... | nilq/baby-python | python |
import torch
from torch import nn
from PVANet import PVANet
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class Encoder(nn.Module):
def __init__(self, in_channels, out_channels,feature_size=20):
super(Encoder, self).__init__()
self.cnn = PVANet(in_channels, out_channels)
... | nilq/baby-python | python |
"""
Functions in this file have all been defined in the notebooks.
This file serves to allow subsequent notebooks to import
functionality and reduce code duplication.
"""
import cv2
import numpy as np
import ipyvolume as ipv
def calibrate_cameras() :
""" Calibrates cameras from chessboard images.
Ret... | nilq/baby-python | python |
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
class WebDelegate:
def __init__(self, parser_engine=BeautifulSoup):
#TO-DO: default parser engine은 BeautifulSoup. 필요시 추가.
self.__parser_engine=parser_engine
def get_web_data(self, addr):
req = Request(addr, heade... | nilq/baby-python | python |
from solution import Solution
# MAIN TESTING PROGRAM:
m = 5
n = 5
sln = Solution()
result = sln.unique_paths(m,n)
print('Input:')
print(m)
print(n)
print('Output:')
print(result) | nilq/baby-python | python |
'''
Facebook Hacker Cup 2017
(Qualification Round) problem 2 : https://www.facebook.com/hackercup/problem/169401886867367/
Lazy Loader
'''
import sys
DEBUG = 1
TESTCASE = 'input/lazy_loading.txt'
def maxTrips(a):
a = sorted(a)
trips = 0
while len(a) > 0:
w = a.pop()
k = w
wh... | nilq/baby-python | python |
# coding=utf-8
"""
Copyright 2013 LinkedIn Corp. 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... | nilq/baby-python | python |
"""
Json for config file. Added supports for comments and expandable keywords.
"""
import copy
import json
import os
RECURRENT_OBJECT_TYPES = (dict, list)
# Identifier key to import another json file,
# work as prefix, allowing "INCLUDE_KEY_1", "INCLUDE_KEY_2"...
INCLUDE_KEY = '_include_json'
# There may be perform... | nilq/baby-python | python |
# Module name: user
# from package: smart_scheduler_tools
# Used Modules: basic_structures_definitions, code_plus_section_list_generator,
# code_plus_section_set_filter, subject_list_to_dictionary, dict_from_json
# Description: Its the most fundamental class of the application, it uses all the
# basic struc... | nilq/baby-python | python |
from preprocessor.Text_File import Text_File, Log_File
class Bibtex_File(Text_File):
"""
Examples:
>>> # Instantiation
>>> my_bibtex_file = Bibtex_File('example_data//vu_25_test.bib')
>>> # Invalid formatting of input directory
>>> try:
... # input directory path ... | nilq/baby-python | python |
"""
Copyright 2020 The Johns Hopkins University Applied Physics Laboratory LLC
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
Unles... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
r"""
Hugging Face BERT implementation.
==============
BERT model from hugging face transformers repo.
"""
import torch
from transformers import BertModel, BertForMaskedLM
from caption.models.encoders.encoder_base import Encoder
from caption.tokenizers import BERTTextEncoder
from test_tube i... | nilq/baby-python | python |
from .. import db
Playlist_Songs = db.Table("play_songs", db.Column("playlist_id",
db.Integer, db.ForeignKey('playlist._Playlist__id')),
db.Column("song_id", db.Integer,
db.ForeignKey('song._Song__id'))
... | nilq/baby-python | python |
import re
import numpy as np
def pad_sequences(sequences, maxlen=None, dtype='int32',
padding='pre', truncating='pre', value=0.):
"""Pads sequences to the same length.
# Arguments
sequences: List of lists, where each element is a sequence.
maxlen: Int, maximum length of all se... | nilq/baby-python | python |
#!/usr/bin/env python
import argparse
import glob
import re
import os
import textract
import pyexcel as pe
import email.utils
import olefile as OleFile
from email.parser import Parser as EmailParser
EMAIL_REGEX = re.compile(r"(?i)([a-z0-9._-]{1,}@[a-z0-9-]{1,}\.[a-z]{2,})")
FLAT_FORMATS = ['txt', 'out', 'log', 'csv'... | nilq/baby-python | python |
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
from typing import Sequence, Union, Callable, Any, Set
import warnings
import dace
from dace import Config
import dace.serialize
import dace.library
from dace.sdfg import SDFG, SDFGState
from dace.sdfg import graph, nodes
from dace.properties... | nilq/baby-python | python |
#
# 2018-01-15 by Toomas Mölder
# Some temporary logging (activity includes _tmp_ added for all steps to better understand, what steps take how long and what indexes to create
# TODO: add exception handling
#
from AnalyzerDatabaseManager import AnalyzerDatabaseManager
from models.AveragesByTimeperiodModel import Averag... | nilq/baby-python | python |
import os
import textwrap
from typing import List, Optional
import colorama # type: ignore
from spectacles.logger import GLOBAL_LOGGER as logger, log_sql_error, COLORS
LINE_WIDTH = 80
COLOR_CODE_LENGTH = len(colorama.Fore.RED) + len(colorama.Style.RESET_ALL)
def color(text: str, name: str) -> str:
if os.environ... | nilq/baby-python | python |
# ##### BEGIN MIT LICENSE BLOCK #####
#
# Copyright (c) 2015 - 2017 Pixar
#
# 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 u... | nilq/baby-python | python |
import logging
import warnings
from analyzer import Analyzer
log = logging.getLogger(__name__)
class URLParsing:
def __init__(self, url_link):
self.url_link = url_link
self.tittle = None
self.keywords = None
log.info("set new url {}".format(self.url_link))
self.parsing()
... | nilq/baby-python | python |
"""
Provides the Vault class for secure variable storage.
"""
import base64
import getpass
import json
import os
import subprocess
import tempfile
from simple_automation.vars import Vars
from simple_automation.exceptions import LogicError, MessageError
from simple_automation.utils import choice_yes
class Vault(Vars)... | nilq/baby-python | python |
from .__version__ import __title__, __description__, __url__, __version__
from .__version__ import __author__, __author_email__, __license__
from .__version__ import __copyright__
from .config import Config
from .neuralnet import NeuralNetwork
from .layers import activation, affine, batch_norm, convolution, dropout
f... | nilq/baby-python | python |
try:
from ulab import numpy as np
except:
import numpy as np
dtypes = (np.uint8, np.int8, np.uint16, np.int16, np.float)
print(np.ones(3))
print(np.ones((3,3)))
print(np.eye(3))
print(np.eye(3, M=4))
print(np.eye(3, M=4, k=0))
print(np.eye(3, M=4, k=-1))
print(np.eye(3, M=4, k=-2))
print(np.eye(3, M=4, k=-3)... | nilq/baby-python | python |
from .imdb import AS, IMDb # NOQA
__version__ = "1.0.22"
| nilq/baby-python | python |
from AppKit import *
from PyObjCTools.TestSupport import *
class TestNSUserInterfaceValidationHelper (NSObject):
def action(self): return 1
def tag(self): return 1
def validateUserInterfaceItem_(self, a): return 1
class TestNSUserInterfaceValidation (TestCase):
def testProtocols(self):
self.a... | nilq/baby-python | python |
import PyPDF2
import pytesseract
from pdf2image import convert_from_path
from src.plataform import data_dir_scan as dds
class pdf_extract:
@staticmethod
def get_text_pypdf2(filename):
pdf_reader = PyPDF2.PdfFileReader(pdf_extract.__path_from_filename(filename))
pdf_text = ''
for i i... | nilq/baby-python | python |
"""
Simple water flow example using ANUGA: Water flowing down a channel.
It was called "steep_slope" in an old validation test.
"""
import sys
#------------------------------------------------------------------------------
# Import necessary modules
#--------------------------------------------------------------------... | nilq/baby-python | python |
import numpy as np
def cubic_roots(a, b, c, d):
"""Compute the roots of the cubic polynomial :math:`ax^3 + bx^2 + cx + d`.
:param a: cubic coefficient
:param b: quadratic coefficient
:param c: linear coefficient
:param d: constant
:return: list of three complex roots
This functio... | nilq/baby-python | python |
# Copyright 2017 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | nilq/baby-python | python |
from django.core.paginator import Paginator
from django.db.models import Q
from django.shortcuts import render
from django.utils import timezone
from pokefriend.forms import TrainerRegisterForms, TrainerSearchForms
from pokefriend.models import Trainer
def index(request):
register_form = TrainerRegisterForms()
... | nilq/baby-python | python |
class PBXList(list):
pass
| nilq/baby-python | python |
import collections
import logging
import random
from datetime import datetime
from typing import Iterable, Text, Dict, Any
import attr
import faust
from replay_output_experiment.app import app
from replay_output_experiment.page_views.models import BalanceUpdate, RequestTransfer, DATETIME_BASIC_FORMAT, \
balances... | nilq/baby-python | python |
# print keypad combination
codes = [".;","abc","def","ghi","jkl","mno","pqrs","tu","vwx","yz"]
def gkpc(keypad):
if len(keypad) ==0:
return [""]
key = keypad[0]
rok = keypad[1:]
rres = gkpc(rok)
mres =[]
for word in rres:
for char in codes[int(key)]:
mres.append(cha... | nilq/baby-python | python |
# encoding: utf8
# filename: completion.py
import logging
import transformers
from transformers import AutoConfig, AutoModel, AutoTokenizer, pipeline
from abc import ABC, abstractmethod
from functools import partial
from typing import List
from .corpus import Document
__all__ = ('AbstractCompletor', 'make_co... | nilq/baby-python | python |
number_1 = float(input('Type a number: '))
number_2 = float(input('Type another one: '))
number_3 = float(input('Type the last one, please: '))
if number_1 > number_2 and number_1 > number_3:
if number_2 > number_3:
print(f'{number_1} + {number_2} = {number_1 + number_2}')
else:
print(f'{number... | nilq/baby-python | python |
# -*- encoding: utf-8 -*-
import os
import click
### set environment variable
# os.environ['FLASK_CONFIGURATION'] = "default" # "testing" / "production"
### change environment var to "production" for debugging
# os.environ['FLASK_CONFIGURATION'] = "production"
# from app import app
debug = True
@click.comman... | nilq/baby-python | python |
import sys
import unittest
import testing.postgresql
import psycopg2
import mock
from mock import patch
from eutils import Client
sys.path.append("..")
import crud
import dblib
def handler(postgresql):
with open('data/srss.sql', 'r') as myfile:
data = myfile.read().replace('\n', '')
conn = psycopg2.c... | nilq/baby-python | python |
import datetime as dt
def getDatefromDate(date,delta,strfmt='%Y%m%d'):
if type(date)==str:
date=stringToDate(date,strfmt)
return (date + dt.timedelta(delta)).strftime(strfmt)
def getDateFromToday(delta,strfmt='%Y%m%d'):
""" Returns a string that represents a date n numbers of days from today.
Parameters:
----... | nilq/baby-python | python |
from M2Crypto.EVP import Cipher
from M2Crypto.Rand import rand_bytes
class TestRule3c:
def __init__(self):
self.g_encrypt = 1
self.g_decrypt = 0
self.g_key1 = b"12345678123456781234567812345678"
self.g_key2 = bytes("12345678123456781234567812345678", "utf8")
self.g_iv = b"0... | nilq/baby-python | python |
"""General-purpose test script for image-to-image translation.
Once you have trained your model with train.py, you can use this script to test the model.
It will load a saved model from --checkpoints_dir and save the results to --results_dir.
It first creates model and dataset given the option. It will hard-code some... | nilq/baby-python | python |
from datetime import date
from time import sleep
print('\033[1:31m-=-\033[m' * 10)
print('\033[1m ...ALISTAMENTO MILITAR...\033[m')
print('\033[1:31m-=-\033[m' * 10)
ano = int(input('Em que ano você nasceu? '))
today = date.today().year
dif = today - ano
sleep(2)
print('''\033[1m...PROCESSANDO...AGUARDE...
''... | nilq/baby-python | python |
import zPE.GUI.io_encap as io_encap
from zPE.GUI.zComp.zStrokeParser import KEY_BINDING_RULE_MKUP, parse_key_binding as zSP_PARSE_KEY_BINDING
import os, sys
import pygtk
pygtk.require('2.0')
import gtk
import copy # for deep copy
import pango # for parsing the font
import re ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import unittest
import os
from elfwrapper.elf_wrapper import ElfAddrObj
class TestApp(unittest.TestCase):
def setUp(self):
pass
def test_1(self):
elf = ElfAddrObj(os.path.join(os.getcwd(), r"example/Test.elf"))
with open(r'example\test_var.txtdatafile.txt') ... | nilq/baby-python | python |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""TPS65185: Single chip PMIC for E Ink (R) Vizplex (TM) Enabled Electronic Paper Display"""
__author__ = "ChISL"
__copyright__ = "TBD"
__credits__ = ["Texas Instruments"]
__license__ = "TBD"
__version__ = "0.1"
__maintainer__ = "https://chisl.io"
__email__ ... | nilq/baby-python | python |
import matplotlib
matplotlib.use('Agg')
import os
import argparse
import torch
import numpy as np
import pickle
import sys
sys.path.append('./utils')
from torch import optim
from torch import nn
from torch import multiprocessing
from torch.optim import lr_scheduler
from torch.autograd import Variable
from torch.utils.... | nilq/baby-python | python |
from .duration import Duration
from .numeric import Numeric
from .rate import Rate
from .size import Size
| nilq/baby-python | python |
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
fams = UnwrapElement(IN[0])
ptypes = list()
for fam in fams:
if fam.GetType().ToString() == "Autodesk.Revit.DB.Family":
ptypes.append(fam.FamilyPlacementType)
else: ptypes.append(None)
OUT = ptypes | nilq/baby-python | python |
from sys import stdin, stdout
from operator import itemgetter
cases = int(stdin.readline())
for c in range(cases):
text = stdin.readline().strip().lower()
text = [ch for ch in text if ch.isalpha()]
freq = {}
max_f = 0
for ch in text:
if not ch in freq:
freq[ch] = 1
else:
freq[ch] += 1
... | nilq/baby-python | python |
from temboo.Library.LinkedIn.PeopleAndConnections.GetMemberProfile import GetMemberProfile, GetMemberProfileInputSet, GetMemberProfileResultSet, GetMemberProfileChoreographyExecution
| nilq/baby-python | python |
import time
import asyncio
import concurrent.futures
from functools import partial
def a():
time.sleep(1)
return 'A'
async def b():
await asyncio.sleep(1)
return 'B'
async def c():
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, a)
def show_perf(func):
print... | nilq/baby-python | python |
import logging
def _cancel_pending_orders(client, orders):
pending = [(order['variety'], order['order_id'])
for order in orders if 'OPEN' in order['status']]
# ToDo: if doesn't work in time, try to run it async.
for p in pending:
try:
order_id = client.cancel_order(*p)
... | nilq/baby-python | python |
import appdaemon.plugins.hass.hassapi as hass
import os
import glob
import random
#
# A helper app providing random template selection and rendering.
#
# This app could be used by Smart Assistants to provide some "randomness" in the assistant words.
#
# noinspection PyAttributeOutsideInit
class AssistantTemplate(h... | nilq/baby-python | python |
#!/usr/bin/env python
################################################################
#
# osm.py - Obsidian Settings Manager
# Copyright 2021 Peter Kaminski. Licensed under MIT License.
# https://github.com/peterkaminski/obsidian-settings-manager
#
################################################################
VER... | nilq/baby-python | python |
import os
import argparse
from misc import date_str, get_dir
def model_args():
parser = argparse.ArgumentParser()
# Paths
parser.add_argument('--train_dir',
help='Directory of train data',
default='./data/poetryDB/txt/')
# parser.add_argument('--test_di... | nilq/baby-python | python |
# Copyright 2020 Mark Dickinson. 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | nilq/baby-python | python |
import logging
import os
import sys
import pandas as pd
import re
from collections import OrderedDict
import numpy as np
import argparse
import zipfile
import paramiko
import time
from sqlalchemy.exc import IntegrityError
from dataactcore.models.domainModels import DUNS
from dataactcore.interfaces.db import GlobalDB
f... | nilq/baby-python | python |
import os , csv
# relative path to find the csv file
os.chdir(os.path.abspath(os.path.dirname(__file__)))
path = os.getcwd()
my_path = os.path.join('.', 'Resources', 'budget_data.csv')
#defining our variables
totalMonths = 0
total = 0
averageChange = 0
greatestIncrease = 0
greatestDecrease = 0
#extra variables used ... | nilq/baby-python | python |
import numpy as np
ip_list=[int(x) for x in input().split()]
ip_list=np.asfarray(ip_list)
def listmul(ip_list):
op_list=[]
for i in range(0,len(ip_list)):
temp=1
for j in range(0,len(ip_list)):
if i!=j:
temp=temp*ip_list[j]
op_list.append(temp)
return op_list
op_list = listmul(ip_list)
print(op_list) | nilq/baby-python | python |
from time import time
from typing import Any
from flask import render_template
def login_render(auth_url: str) -> Any:
"""Return login page.
Arguments:
auth_url {str} -- Link to last.fm authorization page.
"""
return render_template("login.html", auth_url=auth_url, timestamp=time... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 7 18:10:42 2020
Small module to allow multiprocessing of the point in polygon problem
@author: Matthew Varnam - The University of Manchester
@email: matthew.varnam(-at-)manchester.ac.uk
"""
#Import numpy for mathematical calculations
import numpy as np
#I... | nilq/baby-python | python |
import sys, os
import librosa
import torch
import numpy as np
from typing import Union, Tuple, List
from collections import defaultdict
import configparser
config = configparser.ConfigParser(allow_no_value=True)
config.read("config.ini")
from vectorizer.model import Model
from vectorizer.utils import chunk_data
from ... | nilq/baby-python | python |
#!/usr/bin/env python3
import re
import pysam
from .most_common import most_common
from .sequence_properties import repeat
cigar_ptn = re.compile(r"[0-9]+[MIDNSHPX=]")
def realn_softclips(
reads, pos, ins_or_del, idl_seq, idl_flanks, decompose_non_indel_read
):
template = make_indel_template(idl_seq, idl_fl... | nilq/baby-python | python |
"""Config namespace."""
from flask_restx import Namespace, Resource, fields # type: ignore
from jsonschema import ValidationError # type: ignore
from configmodel.logic.config import (
create_config,
delete_config,
get_config,
get_configs,
validate_config,
)
api = Namespace("config", descripti... | nilq/baby-python | python |
# coding: utf-8
# In[1]:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# In[2]:
# 载入数据集
mnist = input_data.read_data_sets('./../../datas/mnist/', one_hot=True)
# 输入图片是28*28
n_inputs = 28 # 输入一行,一行有28个数据
max_time = 28 # 一共28行
lstm_size = 100 # 隐层单元
n_classes = 10 # 10个分类
bat... | nilq/baby-python | python |
from framework.types import RequestT
from framework.types import ResponseT
from framework.utils import build_status
from framework.utils import read_static
def handle_image(_request: RequestT) -> ResponseT:
payload = read_static("image.jpg")
status = build_status(200)
headers = {"Content-type": "image/jpe... | nilq/baby-python | python |
import pandas as pd
import googlemaps
import json
from shapely.geometry import shape, Point
with open('static/GEOJSON/USCounties_final.geojson') as f:
geojson1 = json.load(f)
county = geojson1["features"]
with open('static/GEOJSON/ID2.geojson') as f:
geojson = json.load(f)
district = geojson["features"]
pr... | nilq/baby-python | python |
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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 applicab... | nilq/baby-python | python |
import sqlite3
from .utility import exception_info, enquote2
class SQLighter:
def __init__(self, db):
self.connection = sqlite3.connect(db)
self.cursor = self.connection.cursor()
def db_query(self, query, args=None):
with self.connection:
if args is None or args == ():
... | nilq/baby-python | python |
from selfdrive.car import limit_steer_rate
from selfdrive.car.hyundai.hyundaican import create_lkas11, create_lkas12, \
create_1191, create_1156, \
learn_checksum, create_mdps12, create_clu11
from selfdrive.car.hyundai.values imp... | nilq/baby-python | python |
##==========================================================
## 2016.02.09 vsTAAmbk 0.4.1
## Ported from TAAmbk 0.7.0 by Evalyn
## Email: pov@mahou-shoujo.moe
## Thanks (author)kewenyu for help
##==========================================================
## Requirements:
## EEDI2 ... | nilq/baby-python | python |
#!/usr/bin/env python3
from setuptools import setup
setup(
name='asyncpgsa',
version=__import__('asyncpgsa').__version__,
install_requires=[
'asyncpg~=0.9.0',
'sqlalchemy',
],
packages=['asyncpgsa', 'asyncpgsa.testing'],
url='https://github.com/canopytax/asyncpgsa',
license=... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.