content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
class ControlConfiguration(object):
def __init__(self, control_horizon, prediction_horizon, min_diff=1e-3, max_diff=0.15, diff_decay=0.8):
self.control_horizon = control_horizon
self.prediction_horizon = prediction_horizon
self.min_diff = min_diff
self.max_diff = max_diff
s... | nilq/baby-python | python |
from flexitext.utils import listify
class Parser:
def __init__(self, tokens):
self.tokens = tokens
self.current = 0
def at_end(self):
return self.peek().kind == "EOF"
def advance(self):
self.current += 1
return self.tokens[self.current - 1]
def peek(self):
... | nilq/baby-python | python |
import argparse
import polyscope as ps
import pickle
import os
import numpy as np
from mmcv import Config, DictAction
from mmdet3d.datasets import build_dataloader, build_dataset
def parse_args():
parser = argparse.ArgumentParser(
description='Visualize Results')
parser.add_argument('config', help='t... | nilq/baby-python | python |
from flask.ext.mail import Mail, Message
from run import mail
def sendUserEmail(to, message):
header = 'Allez Viens User Contacted You'
sendEmail([to], header, message)
def sendValidationEmail(to, url):
header = 'Allez Viens Validation'
body = "Please click <a href='" + url + "'>this link</a> to validate and edit... | nilq/baby-python | python |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: data/exercise_route2.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflect... | nilq/baby-python | python |
# Created by MechAviv
# Quest ID :: 32707
# [FriendStory] Student From Another World
sm.setIntroBoxChat(1530000)
sm.setSpeakerType(3)
sm.sendNext("Hello? Hello?\r\n\r\nOkay, the magician guy said he teleported the phone to someone who can help. So, um, hi? Can you help me, maybe?")
sm.setIntroBoxChat(1530000)
sm.set... | nilq/baby-python | python |
# original: https://github.com/yukuku/telebot
# modified by: Bak Yeon O @ http://bakyeono.net
# description: http://bakyeono.net/post/2015-08-24-using-telegram-bot-api.html
# github: https://github.com/bakyeono/using-telegram-bot-api
#
# 구글 앱 엔진 라이브러리 로드
from google.appengine.api import urlfetch
from google.a... | nilq/baby-python | python |
from . import overworld
from . import dungeon1
from . import dungeon2
from . import dungeon3
from . import dungeon4
from . import dungeon5
from . import dungeon6
from . import dungeon7
from . import dungeon8
from . import dungeonColor
from .requirements import AND, OR, COUNT, FOUND
from .location import Loca... | nilq/baby-python | python |
'''
This object reads PCL files and prepare the microarray data as training set to DAs.
The input training vector can either be a gene's expression value over all sampels, or one
microarray sample with all genes' expression value. To feed into DAs, the
standard input dataset is a two-dimensional array with each row a... | nilq/baby-python | python |
from setuptools import setup
setup(
name='budget',
version='1.2.2',
packages=['budget'],
entry_points={
'console_scripts': [
'budget=budget.__main__:main'
]
})
| nilq/baby-python | python |
from Jumpscale import j
def main(self):
"""
to run:
kosmos 'j.data.types.test(name="iprange")'
"""
ipv4 = j.data.types.get("iprange", default="192.168.0.0/28")
assert ipv4.default_get() == "192.168.0.0/28"
assert ipv4.check("192.168.23.255/28") == True
assert ipv4.check("192.168.23.3... | nilq/baby-python | python |
from typing import Optional
from pydantic import BaseModel, Field
class CodePayload(BaseModel):
id: str = Field(..., max_length=8)
code: str
description: Optional[str] = None
| nilq/baby-python | python |
# -------------------------------------------------------------
# BASE: Simple script to score points for the facebook CTF
# -------------------------------------------------------------
#
# Written by Javier (@javutin)
import time
import json
import hashlib
import logging
from BaseHTTPServer import HTTPServer, BaseHT... | nilq/baby-python | python |
from collections import defaultdict
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from symposion.proposals.kinds import get_kind_slugs, get_proposal_model
from email_log.models import Email
from pycon.models import PyConP... | nilq/baby-python | python |
# -*- coding: UTF-8 -*-
import fnmatch
import logging
import re
import subprocess
import uuid
from threading import Thread
from .decorators import side_effecting
from .utils import create_sha1sum_file
class Action:
"""Абстрактный класс действия.
Attributes:
name: Строка, уникальное имя действия.
... | nilq/baby-python | python |
"""Update invoice check constraint
Revision ID: 49e1c8c65f59
Revises: c45d12536d7e
Create Date: 2017-03-31 02:09:55.488859
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '49e1c8c65f59'
down_revision = 'c45d12536d7e'
branch_labels = None
depends_on = None
def... | nilq/baby-python | python |
# Copyright (c) 2015 Mirantis 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 converter import Parser, Converter
test_cases = [
# LENGTH
"100 kmeter nfeet",
"1 nauticalmile meter",
"1 microleague millifoot",
"13 dlea Mft",
"1 ft fur",
"100 kilometer dafeet",
"1 ft m",
"17 kilord Gin"
# DATA
"10 kbyte Mb",
"8 bit byte",
"100 GiB Mibit",
... | nilq/baby-python | python |
#
# The script providing implementation of structures and functions used in
# the Novelty Search method.
#
from functools import total_ordering
# how many nearest neighbors to consider for calculating novelty score?
KNN = 15
# the maximal novelty archive size
MAXNoveltyArchiveSize = 1000
@total_ordering
class Novelt... | nilq/baby-python | python |
from timeit import default_timer as timer
# from datahelpers.data_helper_ml_mulmol6_OnTheFly import DataHelperMulMol6
from datahelpers.data_helper_ml_normal import DataHelperMLNormal
from datahelpers.data_helper_ml_2chan import DataHelperML2CH
from datahelpers.data_helper_ml_mulmol6_OnTheFly import DataHelperMLFly
from... | nilq/baby-python | python |
#! /usr/bin/python
# transaction_csv_cleanup.py
# for Python 3
# Searches specified folder or default download folder for exported
# bank transaction file (.csv format) & adjusts format for YNAB import
# CHANGELOG
# 2017-09-29
# ~ Merged in parameters from https://www.reddit.com/user/FinibusBonorum
# ~ ... | nilq/baby-python | python |
# ***************************************************
# SERVO test for duty cycle range
#
# ProtoStax Air Quality Monitor.
# using Raspberry Pi A+, Micro Servo SG92R, RGB LED and ProtoStax Enclosure for Raspberry Pi
# --> https://www.protostax.com/products/protostax-for-raspberry-pi-a
# You can also use
# -... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore, Qt
class QRoundProgressBar(QtGui.QWidget):
StyleDonut = 1
StylePie = 2
StyleLine = 3
PositionLeft = 180
PositionTop = 90
PositionRight = 0
PositionBottom = -90
UF_VALUE = 1
UF_PERCENT = 2
UF_MAX = 4
def __init__(se... | nilq/baby-python | python |
from .parser import MopacParser
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
""".. moduleauthor:: Artur Lissin"""
from bann.b_container.states.framework.pytorch.lr_scheduler_param import LrSchAlgWr, \
create_lr_sch_json_param_output
from bann.b_container.functions.pytorch.init_framework_fun import InitNetArgs
from bann.b_container.states.framework.pytorch.optim_param... | nilq/baby-python | python |
from setuptools import setup, find_packages
setup(name='pyfdam',
version='0.1',
description='Code for fitting impedance data and simulating discharge experiments',
url='http://github.com/muhammadhasyim/pyfdam',
author='Muhammad R. Hasyim',
author_email='muhammad_hasyim@berkeley.edu',
... | nilq/baby-python | python |
# from __future__ import print_function, division
from tensorflow.keras.layers import Input, Dense, Flatten, Dropout, UpSampling2D, Conv2D
from tensorflow.keras.layers import BatchNormalization, Activation, ZeroPadding2D, LeakyReLU, MaxPooling2D
from tensorflow.keras.models import Sequential, Model
from tensorflow.ker... | nilq/baby-python | python |
# Generated by Django 3.1.1 on 2020-11-06 15:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('devices', '0006_auto_20201105_1843'),
]
operations = [
migrations.AlterField(
model_name='modbu... | nilq/baby-python | python |
''' sample dream '''
from dreamer import Dream
if __name__ == "__main__":
dream = Dream(dream_type='sex')
for i in range(10):
print dream.dream()
| nilq/baby-python | python |
"""
/******************************************************************************
This source file is part of the Avogadro project.
This source code is released under the New BSD License, (the "License").
******************************************************************************/
"""
import argparse
import ... | nilq/baby-python | python |
import os
import pickle
if __name__ == '__main__':
data_tag = 'tw_mm_s4' # 'tw_mm_s1' || 'tw_mm_imagenet_s2' || 'tw_mm_daily_s2'
data_dir = '../data/{}'.format(data_tag)
for data_tag in ['train', 'valid', 'test']:
print('\nComputing url map for %s' % data_tag)
src_fn = os.path.join(data_di... | nilq/baby-python | python |
import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
pfjetEfficiency = DQMEDHarvester("DQMGenericClient",
subDirs = cms.untracked.vstring("HLT/JME/*"),
verbose = cms.untracked.uint32(0), # Set to 2 for all messages
resolution = cms.vstring(),
... | nilq/baby-python | python |
class solution:
def capital(self,word):
count = 0
for i in range(len(word)):
if word[i] >= chr(65) and word[i] > chr(91):
count = count+1
if count == len(word):
return True
elif count == 0:
return True
... | nilq/baby-python | python |
import numpy as np
from Bio.Seq import Seq
from .biotables import COMPLEMENTS, CODONS_SEQUENCES
def complement(dna_sequence):
"""Return the complement of the DNA sequence.
For instance ``complement("ATGCCG")`` returns ``"TACGGC"``.
Uses Biopython for speed.
"""
if hasattr(dna_sequence, "comple... | nilq/baby-python | python |
#
# Generated with WinchBlueprint
from dmt.blueprint import Blueprint
from dmt.dimension import Dimension
from dmt.attribute import Attribute
from dmt.enum_attribute import EnumAttribute
from dmt.blueprint_attribute import BlueprintAttribute
from sima.sima.blueprints.namedobject import NamedObjectBlueprint
class Winc... | nilq/baby-python | python |
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import torchvision
from torchvision import transforms
def process_image(image_path):
''' Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array
'''
# Process a PIL image for use in a PyTorch mode... | nilq/baby-python | python |
from urllib.parse import urlparse
from wal_e.blobstore import wabs
from wal_e.operator.backup import Backup
class WABSBackup(Backup):
"""
A performs Windows Azure Blob Service uploads to of PostgreSQL WAL files
and clusters
"""
def __init__(self, layout, creds, gpg_key_id):
super(WABSBac... | nilq/baby-python | python |
# ------------------------------------------------------------------------------------
# Comparision Operators in Python
# ------------------------------------------------------------------------------------
# So basically there are 6 Comparison Operators in Python , let us learn them one by one .
# Note : One more th... | nilq/baby-python | python |
from game_parser import read_lines
from grid import grid_to_string
from player import Player
from cells import Start, End, Air, Fire, Water, Teleport, Wall
class Game:
def __init__(self, filename):
self.grid = read_lines(filename)
self.position = self.start_position(self.grid)
self.player = ... | nilq/baby-python | python |
# import the necessary packages
import cv2
import math
import numpy as np
# canny edge method, not currently used
def find_edges(image):
grey = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # convert to greyscale
grey = cv2.GaussianBlur(grey, (17, 17), 0) # blur
grey = cv2.bilateralFilter(grey, 9, 75, 75) # what... | nilq/baby-python | python |
from ...doc import *
cudaRT_thread = [
# 4.2. Thread Management [DEPRECATED]
func_decl( [ "cudaThreadExit" ] ),
func_decl( [ "cudaThreadGetCacheConfig" ],
[ parm_def('pCacheConfig', [MEMORY_HOST, SCALAR], INOUT_OUT ) ] ),
func_decl( [ "cudaThreadGetLimit" ],
[ parm_def('pValue', [MEMORY... | nilq/baby-python | python |
import torch
import torch.nn as nn
import numpy as np
import itertools
import logging
from crowd_sim.envs.policy.policy import Policy
from crowd_sim.envs.utils.action import ActionRot, ActionXY
from crowd_sim.envs.utils.state import ObservableState, FullState
def mlp(input_dim, mlp_dims, last_relu=False):
layers ... | nilq/baby-python | python |
from snovault import upgrade_step
@upgrade_step('award', '', '2')
def award_0_2(value, system):
# http://redmine.encodedcc.org/issues/1295
# http://redmine.encodedcc.org/issues/1307
rfa_mapping = ['ENCODE2', 'ENCODE2-Mouse']
if value['rfa'] in rfa_mapping:
value['status'] = 'disabled'
else... | nilq/baby-python | python |
# example based on code from numpy library:
# https://github.com/numpy/numpy/blob/master/numpy/matlib.py
# https://github.com/numpy/numpy/blob/master/numpy/fft/fftpack.c
def ones(shape, dtype=None, order='C'):
# ...
static void radb3(int ido, int l1, const Treal cc[], Treal ch[],
const Treal wa1... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
------------------------------------------------... | nilq/baby-python | python |
#codeing utf-8
class Solution(object):
def longest_common_subsequence(self,s):
lens = len(s)
if lens <= 1 :
return s
sleft,sright = 0,0
dp=[[0 for i in range(lens)] for j in range(lens)]
for i in range(1,lens):
dp[i][i] = True
dp[i][i-1] = ... | nilq/baby-python | python |
#!/bin/python3
import sys
def isBalanced(s):
# Complete this function
str_len = len(s)
if((str_len < 2) or (str_len % 2 != 0)):
return "NO"
brackets_map = {')':'(', ']':'[', '}':'{'}
open_brckts = {'{','(','['}
stack = list()
bracket = ""
is_balanced = True
for i in ra... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 13 16:31:11 2014
@author: jc3e13
This module contains functions for investigating internal gravity waves.
All functions take angular frequency and wavenumber. Angular wavenumber is 2 pi
divided by the wavelength and angular frequency is 2 pi divided by the period.
"""
i... | nilq/baby-python | python |
import json
import random
from copy import deepcopy
from datetime import datetime
from flask import Markup
from flask import Response, current_app, flash, redirect, url_for
from flask_admin.actions import action
from quokka.utils.text import slugify
class PublishAction(object):
@action(
'toggle_publish... | nilq/baby-python | python |
import json
from dmscreen.data.data_loader import get_class_id
def ParseData():
f = open('dmscreen/data/allSpells.json',)
data = json.load(f)
id_ = 0
for i in data["allSpells"]:
classes = []
for s in i["classes"].split(", "):
classes.append(get_class_id(s))
i["cl... | nilq/baby-python | python |
# BOT TOKEN
TOKEN = ""
| nilq/baby-python | python |
import urllib.request
import zipfile
from os import remove, rename, listdir, path
from shutil import rmtree
import re
INVALID = re.compile(r'-.*', re.MULTILINE)
def download_deps(deps, libFolder):
for zipUrl in deps:
print('downloading from '+zipUrl)
urllib.request.urlretrieve(zipUrl, 'temp.zip')
... | nilq/baby-python | python |
# Copyright 2018: Red Hat 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... | nilq/baby-python | python |
from django.views.generic.list import ListView
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect, render
from oppgavegen.models import Set, Chapter, Level
from oppgavegen.views.mixins import LoginRequiredMixin
from oppgavegen.view_logic.current_work impo... | nilq/baby-python | python |
import argparse
import fsspec
import fv3config
def _parse_write_run_directory_args():
parser = argparse.ArgumentParser("write_run_directory")
parser.add_argument(
"config", help="URI to fv3config yaml file. Supports any path used by fsspec."
)
parser.add_argument(
"rundir", help="Desi... | nilq/baby-python | python |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
f... | nilq/baby-python | python |
#!/usr/bin/env python
import rospy
# from vanttec_uuv.msg import ThrustControl
from geometry_msgs.msg import Twist
thrust_pub = rospy.Publisher("/uuv_desired_velocity", Twist, queue_size=1000)
def remap_vel(src_vel):
des_vel = Twist()
des_vel.linear.x = src_vel.linear.x
des_vel.linear.y = -src_vel.linear... | nilq/baby-python | python |
import sys
import os
import math
"""
Notes
- The trick here is to split the right hand side (RHS) of the equation into two
fractions i.e. x = -b/2/a +/- math.sqrt(discriminant)/2/a
- The discriminant is >= 0 for real roots and < 0 for imaginary roots
- For real roots: x1,2 = -b/2/a +/- math.sqrt(discriminant)/2/a as... | nilq/baby-python | python |
from a10sdk.common.A10BaseClass import A10BaseClass
class HostList(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param dns_host: {"minLength": 1, "maxLength": 31, "type": "string", "description": "DNS remote host", "format": "string"}
:param ipv4_mask: {"type": "s... | nilq/baby-python | python |
from ddb.__main__ import register_default_caches, clear_caches
from ddb.command import LifecycleCommand
from ddb.config import config
from ddb.event import bus
from ddb.phase import DefaultPhase, phases
def test_lifecycle():
register_default_caches()
phases.register(DefaultPhase("step1"))
phases.register... | nilq/baby-python | python |
from pyserialization.serializable import Serializable
from pyserialization.serialint import SerialU32
from pyserialization.seriallist import serial_list
from pyserialization.serialstring import SerialAsciiString
from operator import mul
import functools
import numpy as np
class _IntList(serial_list(SerialU32)):
... | nilq/baby-python | python |
from django.db import models
import a2s
SERVER_TYPES = (
(68, 'Dedicated'),
(100, 'Dedicated'),
(108, 'Non-dedicated'),
(112, 'SourceTV'),
)
PLATFORMS = (
(76, 'Linux'),
(108, 'Linux'),
(109, 'Mac OS X'),
(111, 'Mac OS X'),
(119, 'Windows')
)
class Server(models.Model):
title... | nilq/baby-python | python |
from canoser import Struct, Uint8, bytes_to_int_list, hex_to_int_list
from libra.transaction.transaction_argument import TransactionArgument, normalize_public_key
from libra.bytecode import bytecodes
from libra.account_address import Address
class Script(Struct):
_fields = [
('code', [Uint8]),
... | nilq/baby-python | python |
'''
@brief Encoder for Packet data
This encoder takes in PktData objects, serializes them, and sends the results
to all registered senders.
Serialized Packet format:
+--------------------------------+ -
| Header = "A5A5 " | |
| (5 byte string) | |
... | nilq/baby-python | python |
import asyncio
import logging
from kubernetes import client, config, watch
#def main():
logger = logging.getLogger('k8s_events')
logger.setLevel(logging.DEBUG)
config.load_kube_config()
v1 = client.CoreV1Api()
v1ext = client.ExtensionsV1beta1Api()
async def pods():
w = watch.Watch()
for event in w.stream(... | nilq/baby-python | python |
from utils import *
import torch.optim as optim
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
Seq_len, X_train = read_txt('./data/data.txt')
Embedding_matrix = pretrained_embedding_layer(w2v_m, w2i)
vocab_size = len(w2i)
n_hidden = 16
embedding_dim = 300
class LM_Dataset(Dataset)... | nilq/baby-python | python |
import io
import random
import picamera
def motion_detected():
# Randomly return True (like a fake motion detection routine)
return random.randint(0, 10) == 0
camera = picamera.PiCamera()
stream = picamera.PiCameraCircularIO(camera, seconds=20)
camera.start_recording(stream, format='h264')
try:
while True... | nilq/baby-python | python |
import argparse
import webbrowser
import json
import traceback
import socket
import threading
import signal
import os
from pathlib import Path
from lyrebird import log
from lyrebird import application
from lyrebird.config import Rescource, ConfigManager
from lyrebird.mock.mock_server import LyrebirdMockServer
from lyre... | nilq/baby-python | python |
""" Decorator module.
Contains various decorators for hook callbacks.
"""
class BaseDecorator:
""" Base class for decorators in Eris. """
# The interface for hooks means that events will always be the first argument, anything else
# will be passed as payloads for the events.
_EVENT_OFFSET: int = 1
| nilq/baby-python | python |
# -*- coding: UTF-8 -*-
import enum
class MealEnum(enum.Enum):
BREAKFAST = "Breakfast"
MORNING_SNACK = "Morning snack"
LUNCH = "Lunch"
AFTERNOON_SNACK = "Afternoon snack"
DINNER = "Dinner" | nilq/baby-python | python |
from gutenberg.query import get_etexts
from gutenberg.query import get_metadata
from gutenberg.acquire import load_etext
from gutenberg.cleanup import strip_headers
from gutenberg.query import list_supported_metadatas
from gutenberg.acquire import set_metadata_cache
from gutenberg.acquire.metadata import SqliteMetad... | nilq/baby-python | python |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver import FirefoxOptions
import json, config, tracebac... | nilq/baby-python | python |
# Copyright (c) 2012, Johan Rydberg
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, di... | nilq/baby-python | python |
#!/usr/bin/env python
#3. Use Pexpect to retrieve the output of 'show ip int brief' from pynet-rtr2.
import pexpect, getpass, sys, time, re
def main():
ip_addr = '184.105.247.71'
username = 'pyclass'
password = getpass.getpass()
cmd = 'show ip int brief'
ssh_conn = pexpect.spawn('ssh {}@{}'.format(... | nilq/baby-python | python |
"""
********************************************************************************
post_processing
********************************************************************************
Polyline simplification
=======================
.. autosummary::
:toctree: generated/
:nosignatures:
simplify_paths_rdp
So... | nilq/baby-python | python |
#!/usr/bin/env python2.7
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import json
import logging
import os
import pprint
import sys
import time
LOG = logging.getLogger()
LOG.setLevel(logging.DEBUG) # For now, let Handlers control t... | nilq/baby-python | python |
import json
import asyncio
from os import environ
from functools import partial
from aiohttp import ClientSession, ClientConnectionError
from pyee import AsyncIOEventEmitter
from aiohttp_sse_client.client import EventSource
DEFAULT_STREAM_URL = 'https://stream.flowdock.com/flows'
__all__ = ["EventStream"]
class Eve... | nilq/baby-python | python |
"""
File: My_drawing.py
Name:Elsa
----------------------
TODO:
"""
from campy.graphics.gobjects import GOval, GRect
from campy.graphics.gwindow import GWindow
from campy.graphics.gobjects import GOval, GRect,GPolygon,GLabel
from campy.graphics.gwindow import GWindow
def main():
"""
TODO:
This figure uses ... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import json
from lib import xmltodict
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
SCRAMBLED = u'да'
class ReferenceBase(object):
def __init__(self, url):
self.url = url
self.data = {}
... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__name__ = "Phoniebox"
import configparser # needed only for the exception types ?!
from ConfigParserExtended import ConfigParserExtended
import codecs
import subprocess # needed for aplay call
import os,sys
from time import sleep
from mpd import MPDClient
# get absolut... | nilq/baby-python | python |
from datetime import timedelta
from django.db import models
from django.utils import timezone
import time
from .config import YEKPAY_SIMULATION
class TransactionManager(models.Manager):
""" Manager for :class:`Transaction` """
def create_transaction(self, transaction_data):
transaction_data["status"... | nilq/baby-python | python |
from Utility.Types.Reconstruction import Reconstruction
class Background_Reconstruction(Reconstruction):
def __init__(self, cams, points, image_folder_path, sparse_reconstruction_type):
super(Background_Reconstruction, self).__init__(
cams,
points,
image_folder_path,
... | nilq/baby-python | python |
from .approach import Approach
from .challenge import Challenge
from .review_history import ReviewHistory
from .submission import Submission
from .task import Task
from .team import Team
from .team_invitation import TeamInvitation
__all__ = ['Approach', 'Challenge', 'ReviewHistory', 'Submission', 'Task', 'Team', 'Team... | nilq/baby-python | python |
# Telegram
# TELEGRAM
import telegram
from telegram import ReplyKeyboardMarkup
from telegram.error import NetworkError, Unauthorized
# ACCESO A DATOS EN SERVIDORES (usado por telegram)
import json
import requests
import config
import emailUtil
import Datos
# mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
# F... | nilq/baby-python | python |
# Andrew Riker
# CS1400 - LW2 XL
# Assignment #04
import math
# user enters length of sides
length = eval(input("Enter length of the polygon sides: "))
# user enters number of sides
numOfSides = eval(input("Enter the number of sides the polygon has: "))
# calculate the area of the polygon
area = (numOfSide... | nilq/baby-python | python |
# flake8: noqa
import geonomics as gnx
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
from mpl_toolkits.axes_grid1 import make_axes_locatable
# define number of individuals to plot tracks for, and number of timesteps for
# tracks
n_individs = 20
n_timesteps = 5000
# make figure
fi... | nilq/baby-python | python |
#!/usr/bin/env python
import paramiko
import sys
hostname = sys.argv[1]
port = 22
usr = 'user'
pwd = 'pass'
try:
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
client.connect(hostname, port=port, username=usr, password=pwd)
ex... | nilq/baby-python | python |
#!/usr/bin/env python3
# Imports
import prometheus_client
import traceback
import speedtest
import threading
import argparse
import time
# Arguments
parser = argparse.ArgumentParser(description='Prometheus exporter where it reports speedtest statistics based on user\'s preference.')
parser.add_argument('--w... | nilq/baby-python | python |
import logging
import os
import signal
import socket
import time
from contextlib import contextmanager
from subprocess import Popen
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed
class UserObject:
def predict(self, X, features_names):
logging.info("Predict called")
... | nilq/baby-python | python |
__author__ = 'alex'
import os
import subprocess
import logging
from mountn.utils import lsblk, SubprocessException
from mountn.gui import gui
from locale import gettext as _
class TcplayDevice(object):
class Item(object):
def __init__(self, plugin, **kwargs):
self.plugin = plugin
... | nilq/baby-python | python |
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from numpy import pi
qreg_q = QuantumRegister(3, 'q')
creg_c = ClassicalRegister(3, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
circuit.h(qreg_q[1])
circuit.cx(qreg_q[1], qreg_q[2])
circuit.barrier(qreg_q[1], qreg_q[2], qreg_q[0])
circuit.cx(qreg... | nilq/baby-python | python |
from mmdet.models.necks.fpn import FPN
from .second_fpn import SECONDFPN
from .imvoxelnet import ImVoxelNeck, KittiImVoxelNeck, NuScenesImVoxelNeck
__all__ = ['FPN', 'SECONDFPN', 'ImVoxelNeck', 'KittiImVoxelNeck', 'NuScenesImVoxelNeck']
| nilq/baby-python | python |
import cv2
face_cascade = cv2.CascadeClassifier("./haarcascade_frontalface_default.xml")
img = cv2.imread("face1.jpg")
gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces= face_cascade.detectMultiScale(gray_img, scaleFactor = 1.15, minNeighbors=5)
print(type(faces))
print(faces)
# for x,y,w,h in face... | nilq/baby-python | python |
# Copyright 2018 IBM 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 law or a... | nilq/baby-python | python |
try:
from setuptools import setup
except:
from distutils.core import setup
setup(
name='pytorch_custom',
version='0.0dev',
author='Alexander Soare',
packages=['pytorch_custom'],
url='https://github.com/alexander-soare/PyTorch-Custom',
license='Apache 2.0',
description='My own miscel... | nilq/baby-python | python |
'''
Copyright Hackers' Club, University Of Peradeniya
Author : E/13/181 (Samurdhi Karunarathne)
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 r... | nilq/baby-python | python |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | nilq/baby-python | python |
import datetime
import logging
import random
from GameParent import Game
from GameParent import SetupFailure, SetupSuccess
logger = logging.getLogger(__name__)
handler = logging.FileHandler('../logs/{}.log'.format(str(datetime.datetime.now()).replace(' ', '_').replace(':', 'h', 1).replace(':', 'm').split('.')[0][:-2]... | nilq/baby-python | python |
import torch.nn as nn
import torch
from .initModel import initModel
import torch.nn.functional as F
from torch.autograd import Variable
import codecs
import os
import json
class simplE(initModel):
def __init__(self, config):
super(simplE, self).__init__(config)
self.entHeadEmbedding = nn.Embedding... | nilq/baby-python | python |
__author__ = 'jonnyfunfun'
| nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.