content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
# -*- coding: utf-8 -*-
"""
Integrate with Google using openid
:copyright: (c) 2014 by Pradip Caulagi.
:license: MIT, see LICENSE for more details.
"""
import logging
from flask import Flask, render_template, request, g, session, flash, \
redirect, url_for, abort
from flask import Blueprint
from fla... | nilq/baby-python | python |
#
# Copyright (c) 2021 Arm Limited and Contributors. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
"""PyPI Package definition for greentea-host (htrun)."""
import os
from io import open
from distutils.core import setup
from setuptools import find_packages
DESCRIPTION = (
"greentea-host (htrun) is a ... | nilq/baby-python | python |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... | nilq/baby-python | python |
import protocol
import helpers
import hashes as h
import bloom_filter as bf
import garbled_bloom_filter as gbf
import PySimpleGUI as sg
sg.change_look_and_feel('DarkBlue2')
perform_protocol = sg.ReadButton('Start Simulation', font=('Segoe UI', 12), key='-RUN-')
stepTracker = 0
Protocol = None
disableChecks = False
... | nilq/baby-python | python |
def reverses(array, a, b):
while a < b:
array[a], array[b] = array[b], array[a]
a += 1
b -= 1
def rotate(nums, k):
n = len(nums)
k = k % n
reverses(nums, 0, n-k-1)
reverses(nums, n-k, n-1)
reverses(nums, 0, n-1)
return nums
if __name__ == '__main__':
nums = [i ... | nilq/baby-python | python |
""" XVM (c) www.modxvm.com 2013-2017 """
# PUBLIC
def getAvgStat(key):
return _data.get(key, {})
# PRIVATE
_data = {}
| nilq/baby-python | python |
import logging
logger = logging.getLogger(__name__)
import click, sys
from threatspec import app
def validate_logging(ctx, param, value):
levels = {
"none": 100,
"crit": logging.CRITICAL,
"error": logging.ERROR,
"warn": logging.WARNING,
"info": logging.INFO,
"debug"... | nilq/baby-python | python |
import torch
import numpy as np
import re
from collections import Counter
import string
import pickle
import random
from torch.autograd import Variable
import copy
import ujson as json
import traceback
import bisect
from torch.utils.data import Dataset, DataLoader
IGNORE_INDEX = -100
NUM_OF_PARAGRAPHS = 10
MAX_PARAG... | nilq/baby-python | python |
import pytest
@pytest.mark.e2e
def test_arp_packet_e2e(api, utils, b2b_raw_config):
"""
Configure a raw TCP flow with,
- sender_hardware_addr increase from 00:0c:29:e3:53:ea with count 5
- target_hardware_addr decrement from 00:0C:29:E3:54:EA with count 5
- 100 frames of 1518B size each
- 10% ... | nilq/baby-python | python |
import os
import pytest
import json
import regal
_samples_simple = [
("and.v", "and.jed"),
("nand.v", "nand.jed"),
("not.v", "not.jed"),
("or.v", "or.jed"),
("xor.v", "xor.jed"),
("v1.v", "v1.jed"),
("v0.v", "v0.jed"),
("fb.v", "fb.jed"),
]
_samples_registered = [
("clk.v", "clk.j... | nilq/baby-python | python |
from setuptools import setup
from setuptools import find_namespace_packages
with open(file="README.md", mode="r") as fh:
long_description = fh.read()
setup(
name='fin-news',
author='Alex Reed',
author_email='coding.sigma@gmail.com',
version='0.1.1',
description='A finance news aggregator used ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 11 17:33:22 2017
@author: Martin
"""
import collections
new_otus = collections.defaultdict(list)
with open('unique_renamed_otus.txt') as data:
for d in data:
d = d.strip("\n") # remove newline char
line = d.split("\t") # split line at tab char
... | nilq/baby-python | python |
"""Role testing files using testinfra"""
import pytest
@pytest.mark.parametrize("config", [
(
"NTP=0.debian.pool.ntp.org "
"1.debian.pool.ntp.org "
"2.debian.pool.ntp.org "
"3.debian.pool.ntp.org"
),
(
"FallbackNTP=0.de.pool.ntp.org "
"1.de.pool.ntp.org "
... | nilq/baby-python | python |
'''
Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.
Example 1:
Input:
"bbbab"
Output:
4
One possible longest palindromic subsequence is "bbbb".
Example 2:
Input:
"cbbd"
Output:
2
'''
'''
This is a standard problem of Dynamic Programm... | nilq/baby-python | python |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | nilq/baby-python | python |
#
# Copyright (C) 2012-2020 Euclid Science Ground Segment
#
# This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General
# Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option)
# any ... | nilq/baby-python | python |
from django.conf.urls import patterns, url
urlpatterns = patterns('scheduler.views',
url(r'^list/$', 'job_list', (), 'job_list'),
)
| nilq/baby-python | python |
from django.apps import AppConfig
class PhonebooksApiConfig(AppConfig):
name = 'phonebooks_api'
| nilq/baby-python | python |
from os import listdir
from os.path import isfile, isdir, join
from typing import List
from bs4 import BeautifulSoup
from .model import Imagenet, Imagenet_Object
from ...generator import Generator
from ...helper import grouper
## Configure paths
out_dir = '/data/streamable4'
in_dir = '/data/ILSVRC'
in_dir_kaggle = '... | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2014 Mikael Sandstrรถm <oravirt@gmail.com>
# Copyright: (c) 2021, Ari Stark <ari.stark@netcourrier.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_functio... | nilq/baby-python | python |
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
def main():
import sys
input = sys.stdin.readline
n = int(input())
xy = [list(map(int, input().split())) for _ in range(n)]
ans = 0
for xy1, xy2 in zip(xy, xy[1:]):
ans += abs(xy1[0] - xy2[0])
ans += abs(xy1[1] - xy2[1])
print(ans)
if __name__ ... | nilq/baby-python | python |
# --------------------------
# UFSC - CTC - INE - INE5603
# Exercรญcio calculos
# --------------------------
# Classe responsรกvel por determinar se um nรบmero รฉ primo.
from view.paineis.painel_abstrato import PainelAbstrato
from model.calculos import primo
class PainelPrimo(PainelAbstrato):
def __init__(self):
... | nilq/baby-python | python |
import os
from dotenv import find_dotenv
from dotenv import load_dotenv
load_dotenv(find_dotenv())
BASE_URL = os.getenv("BASE_URL")
CURRENCY = os.getenv("CURRENCY")
API_URL = BASE_URL + CURRENCY
OUTPUT_FILE = os.getenv("OUTPUT_FILE")
REQUEST_TIMEOUT = int(os.getenv("REQUEST_TIMEOUT"))
CANCEL_ON_FAILURE = os.getenv("... | nilq/baby-python | python |
from ctypes import PyDLL, py_object, c_int
from os import path
from sys import exit
import numpy as np
my_path = path.abspath(path.dirname(__file__))
path = path.join(my_path, "./bin/libmotion_detector_optimization.so")
try:
lib = PyDLL(path)
lib.c_scan.restype = py_object
lib.c_scan.argtypes = [py_objec... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import Popen
processes = []
for counter in range(10):
chrome_cmd = 'export BROWSER=chrome && python test_search.py'
firefox_cmd = 'export BROWSER=firefox && python test_search.py'
processes.append(Popen(chrome_cmd, shell=True))
processes.... | nilq/baby-python | python |
import re
"""
# Line based token containers
As denoted by `^` in the regex
"""
BLANK = re.compile(r"^$")
#TODO this will fail to match correctly if a line is `<div><p>foo bar</p></div>`
HTML_LINE = re.compile(
r"""
\s{0,3}
(?P<content>\<[... | nilq/baby-python | python |
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
"""
This example demonstrates how to instantiate the
Adafruit BNO055 Sensor using this library and just
the I2C bus number.
This example will only work on a Raspberry Pi
and does require the i2c-gpio kernel module to be
insta... | nilq/baby-python | python |
import os
import json
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
DEPENDS_PATH = os.path.join(SCRIPT_DIR, '.depends.json')
FLAGS = [
'-Wall',
'-Wextra',
'-x', 'c++',
'-std=c++17',
'-isystem', '/usr/include/c++/8.2.1',
'-isystem', '/usr/include/c++/8.2.1/x86_64-pc-linux-gnu',
'... | nilq/baby-python | python |
from .quantizer import *
from .api import *
| nilq/baby-python | python |
# ะกัะธัะฐะตะผ, ัะบะพะปัะบะพ ัะฐะท ะฒัััะตัะฐะตััั ัะพ ะธะปะธ ะธะฝะพะต ัะธัะปะพ ะฒ ะผะฐััะธะฒะต.
# ะะฝะฐั ััะธ ะบะพะปะธัะตััะฒะฐ, ะฑััััะพ ัะพัะผะธััะตะผ ัะถะต ัะฟะพััะดะพัะตะฝะฝัะน ะผะฐััะธะฒ.
# ะะปั ััะพะน ัะพััะธัะพะฒะบะธ ะฝัะถะฝะพ ะทะฝะฐัั ะผะธะฝะธะผัะผ ะธ ะผะฐะบัะธะผัะผ ะฒ ะผะฐััะธะฒะต.
# ะขะพะณะดะฐ ะณะตะฝะตัะธัััััั ะบะปััะธ ะดะปั ะฒัะฟะพะผะพะณะฐัะตะปัะฝะพะณะพ ะผะฐััะธะฒะฐ, ะฒ ะบะพัะพัะพะผ
# ะธ ัะธะบัะธััะตะผ ัะตะณะพ ะธ ัะบะพะปัะบะพ ัะฐะท ะฒัััะตัะธะปะพัั.
def count_sor... | nilq/baby-python | python |
# Generated by Django 2.1.7 on 2019-03-27 15:22
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... | nilq/baby-python | python |
names= ('ali', 'ahmet')
sayฤฑ=int(input("sayฤฑ giriniz:"))
if sayฤฑ>=10 :
print(names[0])
else :
print(names[1]) | 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 use ... | nilq/baby-python | python |
nums = [int(i) for i in input().split()]
prefixsum = [0] * (len(nums) + 1)
mi = prefixsum[0]
ma = -100000
msum = nums[0]
for i in range(1, len(nums) + 1):
prefixsum[i] = prefixsum[i-1] + nums[i-1]
if prefixsum[i-1] < mi:
mi = prefixsum[i-1]
if prefixsum[i] - mi > msum:
msum = prefixsum[i... | nilq/baby-python | python |
import psycopg2
from config import config
class PostgresConnector:
def __init__(self):
# read connection parameters
self.params = config()
def connect(self):
""" Connect to the PostgreSQL database server """
conn = None
try:
# connect to the PostgreSQL serve... | nilq/baby-python | python |
from gopygo.parser import parse
from gopygo.unparser import unparse
__version__ = '0.3.2'
| nilq/baby-python | python |
import random
from scicast_bot_session.client.scicast_bot_session import SciCastBotSession
from scicast_bot_session.common.utils import scicast_bot_urls
import botutils
from time import sleep
import datetime
import sys
def getinfo(site,bot='',roundid:str='', percent=0.005):
try:
api_key = botutils.lookup_k... | nilq/baby-python | python |
import sys
import os
from pathlib import Path
import locale
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QLocale
from configs import Configurator
from gui.appwidget import App
from pa import generate_pa_test
CONFIG_FILE = 'duet_pressure_advance.cfg'
def generate(cfg):
pass
if __name__ == '... | nilq/baby-python | python |
from tkinter import *
root=Tk()
root.geometry("600x500")
addno=StringVar()
e1=Entry(root)
e1.grid(row=0,column=1)
e2=Entry(root)
e2.grid(row=1,column=1)
def add():
res1 = int(e1.get())+int(e2.get())
addno.set(res1)
n1=Label(root,text="num1").grid(row=0)
n2=Label(root,text="num2").grid(row=1)
n3=Label(r... | nilq/baby-python | python |
import re
from random import randrange
from model.contact import Contact
def test_random_contact_home_page(app):
old_contacts = app.contact.get_contact_list()
index = randrange(len(old_contacts))
contact_from_home_page = app.contact.get_contact_list()[index]
contact_from_edit_page = app.contact.get_co... | nilq/baby-python | python |
import json
from flask import request
from flask_restful import Resource, reqparse
from database.interface import FirebaseInterface
from models.Service import Service
class ServicesController(Resource):
def __init__(self):
self.parser = reqparse.RequestParser()
self.interface = FirebaseInterface(... | nilq/baby-python | python |
from hashlib import sha256
from tornado.web import HTTPError
from .db import Model, DoesNotExistError, NonUniqueError
from .game import Game
from .player import Player
from .location import Location
from .template import templater, inside_page
class Admin(Model):
_table = 'admin'
def __init__(self, id, name, passw... | nilq/baby-python | python |
"""Orcaflex output plugin - using orcaflex API."""
import numpy as np
def to_orcaflex(self, model, minEnergy=1e-6):
"""Writes the spectrum to an Orcaflex model
Uses the orcaflex API (OrcFxAPI) to set the wave-data of the provided orcaflex model.
The axis system conversion used is:
- Orcaflex global ... | nilq/baby-python | python |
import subprocess
import sys
with open('out.txt','w+') as fout:
with open('err.txt','w+') as ferr:
out=subprocess.call(["./bash-script-with-bad-syntax"],stdout=fout,stderr=ferr)
fout.seek(0)
print('output:')
print(fout.read())
ferr.seek(0)
print('error:')
pr... | nilq/baby-python | python |
#esperava um ident depois do ':'
def x(y):
z=1
| nilq/baby-python | python |
# encoding: utf-8
# Copyright 2011 California Institute of Technology. ALL RIGHTS
# RESERVED. U.S. Government Sponsorship acknowledged.
'''Curator: interface'''
from zope.interface import Interface
from zope import schema
from ipdasite.services import ProjectMessageFactory as _
class ICurator(Interface):
'''A pe... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('wod_rules', '0006_auto_20150414_1606'),
]
operations = [
migrations.RemoveField(
model_name='merit',
... | nilq/baby-python | python |
#!/usr/bin/env python
# Copyright 2019 The Vitess 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 applicabl... | nilq/baby-python | python |
from django.shortcuts import redirect, render
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic import (CreateView, UpdateView, DetailView, TemplateView, View, DeleteView,ListView)
from django.shortcuts import render, redire... | nilq/baby-python | python |
import logging
# Setup basic logging
logging.basicConfig(
format='%(asctime)s : %(levelname)s : %(name)s : %(message)s',
level=logging.WARNING
)
from flask import Flask
from flask_uuid import FlaskUUID
from flask_migrate import Migrate
from simple_events.apis import api
from simple_events.models ... | nilq/baby-python | python |
import graphene
class SystemQueries(graphene.ObjectType):
hello = graphene.String(name=graphene.String(default_value="stranger"))
def resolve_hello(self, info, name):
return 'Hello ' + name
root_schema = graphene.Schema(query=SystemQueries)
| nilq/baby-python | python |
from .version import VERSION
from .SoapLibrary import SoapLibrary
class SoapLibrary(SoapLibrary):
"""
SoapLibrary is a library for testing SOAP-based web services.
SoapLibrary is based on [https://python-zeep.readthedocs.io/en/master/|Zeep], a modern SOAP client for Python.
This library ... | nilq/baby-python | python |
import argparse
from os import path
from datetime import datetime
import logging
from logging.config import fileConfig
import tempfile
from dicom.dataset import Dataset
from pydicom.datadict import tag_for_name, dictionaryVR
from mip import Pacs, DicomAnonymizer
# parse commandline
parser = argparse.ArgumentParser(de... | nilq/baby-python | python |
# Copyright (c) 2013, GPy authors (see AUTHORS.txt).
# Licensed under the BSD 3-clause license (see LICENSE.txt)
from .kern import Kern
from ...core.parameterization import Param
from ...core.parameterization.transformations import Logexp
import numpy as np
from ...util.linalg import tdot
from ...util.caching import C... | nilq/baby-python | python |
from .socket_provider import SocketProvider
from .pcapy_provider import PcapyProvider
from .provider import Provider
from core.exceptions import *
class ProviderType():
Socket = "SocketProvider"
Pcapy = "PcapyProvider"
def create(providerType, device=None):
return globals()[providerType](device) | nilq/baby-python | python |
# Python3 Finding Lowest Common Ancestor in Binary Tree ----> O(N)
def find_lca_bt(root, n1, n2):
if not root:
return None
left_lca = find_lca_bt(root.left, n1, n2)
right_lca = find_lca_bt(root.right, n1, n2)
if left_lca and right_lca:
return root
return left_lca if left_lca else right_lca
# Python3 Findi... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. moduleauthor:: hbldh <henrik.blidh@nedomkull.com>
Created on 2015-11-13
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from pkg_resources import resource_fi... | nilq/baby-python | python |
#!/usr/bin/env python
# Copyright 2020 Naoyuki Kanda
# MIT license
import sys
import os
import json
import soundfile
import librosa
import numpy as np
def get_delayed_audio(wav_file, delay, sampling_rate=16000):
audio, _ = soundfile.read(wav_file)
delay_frame = int(delay * sampling_rate)
if delay_frame ... | nilq/baby-python | python |
"""
api for running OpenCL ports of nervana neon convolutional kernels
status: in progress
approximate guidelines/requirements:
- caller should handle opencl context and queue setup
- caller should allocate cl buffers
- library can/should provide a means to provide required dimensions of buffers to caller
- library w... | nilq/baby-python | python |
# Created By: Virgil Dupras
# Created On: 2007-10-06
# Copyright 2013 Hardcoded Software (http://www.hardcoded.net)
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ===============================================================
# Copyright (C) 2018 HuangYk.
# Licensed under The MIT Lincese.
#
# Filename : torchsoa.py
# Author : HuangYK
# Last Modified: 2018-08-12 14:15
# Description :
#
# ================================... | nilq/baby-python | python |
import unittest
import sys
from ctypeslib import clang2py
class ToolchainTest(unittest.TestCase):
if sys.platform == "win32":
def test_windows(self):
clang2py.main(["clang2py",
"-c",
"-w",
"-m", "ctypes.wintypes",... | nilq/baby-python | python |
import random
import numpy as np
import math
from collections import deque
import time
import pickle
from sklearn.linear_model import LinearRegression
from Simulations.GameFeatures import GameFeatures as GF
from BehaviouralModels.BehaviouralModels import BehaviouralModelInterface
MIN_REPLAY_MEMORY_SIZE = 16_384
MAX... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright 2015 Donne Martin. 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. A copy of
# the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "lice... | nilq/baby-python | python |
from selenium import webdriver
import unittest
import os
import sys
PACKAGE_ROOT = '../..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(),
os.path.expanduser(__file__))))
PACKAGE_PATH = os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_R... | nilq/baby-python | python |
# encoding: UTF-8
'''
v1:yalinwang
้ๅฏนbitfinex ๆฅๅฃ่ฟ่กไบๆน่ฟไธไผๅ๏ผๅขๅ ไบ้จๅๆฅๅฟๅ่ฝ
ๆฌๆไปถไธญๅฎ็ฐไบCTA็ญ็ฅๅผๆ๏ผ้ๅฏนCTA็ฑปๅ็็ญ็ฅ๏ผๆฝ่ฑก็ฎๅไบ้จๅๅบๅฑๆฅๅฃ็ๅ่ฝใ
ๅ
ณไบๅนณไปๅๅนณๆจ่งๅ๏ผ
1. ๆฎ้็ๅนณไปOFFSET_CLOSET็ญไบๅนณๆจOFFSET_CLOSEYESTERDAY
2. ๅชๆไธๆๆ็ๅ็ง้่ฆ่่ๅนณไปๅๅนณๆจ็ๅบๅซ
3. ๅฝไธๆๆ็ๆ่ดงๆไปไปๆถ๏ผ่ฐ็จSellๅCoverไผไฝฟ็จOFFSET_CLOSETODAY๏ผๅฆๅ
ไผไฝฟ็จOFFSET_CLOSE
4. ไปฅไธ่ฎพ่ฎกๆๅณ็ๅฆๆSellๅCover็ๆฐ้่ถ
่ฟไปๆฅๆไป้ๆถ๏ผไผๅฏผ่ดๅบ้๏ผๅณ็จๆท
ๅธๆ้่ฟไธ... | nilq/baby-python | python |
################################################################################
#
# Copyright (C) 2019 Garrett Brown
# This file is part of pyqudt - https://github.com/eigendude/pyqudt
#
# pyqudt is derived from jQUDT
# Copyright (C) 2012-2013 Egon Willighagen <egonw@users.sf.net>
#
# SPDX-License-Identifier: BS... | nilq/baby-python | python |
import json, subprocess
from .... pyaz_utils import get_cli_name, get_params
def start(account_name=None, account_key=None, connection_string=None, sas_token=None, auth_mode=None, destination_blob, destination_container, timeout=None, destination_if_modified_since=None, destination_if_unmodified_since=None, destinati... | nilq/baby-python | python |
import csv, json
import to_json
# LOD preparations
# Import the LOD library.
from lod import lod
# The object_manager contains every object that has been created in this Scenario so far.
object_manager = lod.get_object_manager()
def main(lod_manager):
#
# Get the arguments that were given to this Program.
... | nilq/baby-python | python |
import berrl as bl
import pandas as pd
import numpy as np
d=pd.read_csv('STSIFARS.csv')
d=d[d.STANAME=='WEST VIRGINIA']
d.to_csv('wv_traffic_fatals.csv') | nilq/baby-python | python |
##parameters=title=None, description=None, event_type=None, effectiveDay=None, effectiveMo=None, effectiveYear=None, expirationDay=None, expirationMo=None, expirationYear=None, start_time=None, startAMPM=None, stop_time=None, stopAMPM=None, location=None, contact_name=None, contact_email=None, contact_phone=None, event... | nilq/baby-python | python |
class ColorTranslator(object):
""" Translates colors to and from GDI+ System.Drawing.Color structures. This class cannot be inherited. """
@staticmethod
def FromHtml(htmlColor):
"""
FromHtml(htmlColor: str) -> Color
Translates an HTML color representation to a GDI+ System.Drawin... | nilq/baby-python | python |
from functools import wraps
#PUBLIC COMMAND
def init(fn):
def wrapper(*args,**kwargs):
message = args[0].message
if message.chat.type == 'supergroup' or message.chat.type == 'group':
return fn(*args,**kwargs)
else:
return False
return wrapper | nilq/baby-python | python |
class BadMoves(object):
def bad_move(self, move, gs):
if move is None:
return True
coord = gs.me.head + move
if gs.me.neck == coord:
return True
if not gs.is_empty(coord) and coord not in gs.all_tails:
return True
if coord in gs.possible... | nilq/baby-python | python |
'''
Created on Jan 3, 2016
@author: graysonelias
'''
seeding = False
import wallaby as w
# Time
startTime = -1
# Motor ports
LMOTOR = 0
RMOTOR = 3
COWMOTOR = 1
# analog ports
LTOPHAT = 0
RTOPHAT = 1
# Digital ports
LEFT_BUTTON = 0
RIGHT_BUTTON = 1
CLONE_SWITCH = 9
RIGHT_BUTTON = 13
isClone = w.digital(CLONE_SWIT... | nilq/baby-python | python |
# O(n) time complexity
# O(n) space complexity
def reverse1(a):
i = 0
j = len(a)
b = a[:]
while j > 0:
#b.append(a[j - 1]) -> not efficient
b[i] = a[j - 1]
i += 1
j -= 1
return b
# O(n) time complexity
# O(1) space complexity
def reverse2(a... | nilq/baby-python | python |
import sys
import time
from sdk import *
addr_list = addresses()
_pid = 20036
_proposer = addr_list[0]
_initial_funding = (int("2") * 10 ** 9)
_each_funding = (int("3") * 10 ** 9)
_big_funding = (int("8") * 10 ** 9)
_funding_goal_general = (int("10") * 10 ** 9)
def gen_prop():
global _pid
prop = Proposal(str... | nilq/baby-python | python |
text_3 = '3'
print(text_3.isalnum()) | nilq/baby-python | python |
import subprocess
import time
import unittest
from game.client.controller.network import Network
class TestServer(unittest.TestCase):
def setUp(self) -> None:
self.server = subprocess.Popen(["python3", "-m", "game", "--server"])
time.sleep(2)
def test_game_creation(self):
network = ... | nilq/baby-python | python |
from unittest.mock import ANY, mock_open, patch
import pytest
import rumps
from src.app_functions.exceptions.credentials_failed import CredentialInputFailed
from src.duo.login.input_credentials import input_credentials
def test_succesful_entry_of_credentials(mocker):
"""Check if prompt correctly returns when to ... | nilq/baby-python | python |
import torch
from ..bayesian.models.models import create_model
import numpy as np
from xopt.vocs import VOCS
class TestModelCreation:
vocs = VOCS(variables = {'x1': [0, 1],
'x2': [0, 1],
'x3': [0, 1]} )
def test_create_model(self):
train_x = torch.r... | nilq/baby-python | python |
#64
# Given a m x n grid filled with non-negative numbers,
# find a path from top left to bottom right
# which minimizes the sum of all numbers along its path.
#
# Note: You can only move either down or right at any point in time.
class DynamicProgrammingSol():
# Time: O(m * n)
# Space: O(m + n)
def... | nilq/baby-python | python |
from flask import Flask,jsonify
from flask_restplus import Resource, Api
from faker import Faker
app = Flask(__name__)
api = Api(app, version='0.1.0', title='Faker', description="""## Faker API
**๋น์ ์ ์๋ก์ด ์์
์ ์ํํ์ธ์.**
""")
ns = api.namespace('Hero', description='์์
์ด ์ฌ๊ธฐ ์ ๋ค๋ค.')
fake = Faker("ko-KR")
@ns.route('/new_her... | nilq/baby-python | python |
import cv2
img = cv2.imread("example_images/brain_noise.jpeg")
# Structuring element
se = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) # also called kernel
# Basic morphology
img_erosion = cv2.erode(img, se, iterations=1)
img_dilation = cv2.dilate(img, se, iterations=1)
img_opening = cv2.morphologyEx(img, cv2.... | nilq/baby-python | python |
from django.contrib.auth.models import User
from rest_framework import serializers
from blog.models import Like, Post
class UserInfoSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="api:user-detail")
class Meta:
model = User
fields = ("url", "id",... | nilq/baby-python | python |
def merge_the_tools(string, k):
# your code goes here
s = int(len(string)/k)
l=[]
for i in range(0,len(string),k):
l.append(string[i:i+k])
aux = []
aux_2 = []
for j in l:
for k in j:
if k not in aux:
aux.append(k)
st = ''.join(aux)
... | nilq/baby-python | python |
import numpy as np
import random
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
from matplotlib import ticker
import torch
import math
k = 20 # num of selected clients in each round
K = 100 # num of total activated clients
T = 2500 # num of total rounds
def classA(size... | nilq/baby-python | python |
import Formatter
import Config
import Logger
import Arguments
from Utils import *
args = Arguments.Parse()
cfg = Config.Get()
@Formatter.Register("csv")
def csv_formatter(components):
""" Formats components as a CSV """
columns = cfg['columns']
nl = cfg['outputLineSeparator']
result = denormalizeStr(columns... | nilq/baby-python | python |
import collections
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
# freq = collections.Counter(words)
# return [item[0] for item in heapq.nsmallest(k, (freq.items()), key=lambda x: (x[1] * -1, x[0]))]
# sorted_freq = [item[0] for item in sorted(freq.items(),... | nilq/baby-python | python |
###############################################################
# Autogenerated module. Please don't modify. #
# Edit according file in protocol_generator/templates instead #
###############################################################
from typing import Dict
from ...structs.api.list_offsets_reque... | nilq/baby-python | python |
from septentrion import core
def test_initialize(db):
settings_kwargs = {
# database connection settings
"host": db["host"],
"port": db["port"],
"username": db["user"],
"dbname": db["dbname"],
# migrate settings
"target_version": "1.1",
"migrations_... | nilq/baby-python | python |
from .motion_dataloader import *
from .spatial_dataloader import * | nilq/baby-python | python |
import pytest
from pathlib import Path
from app.database import db
from app.main import create_app
TEST_DB = 'test.db'
class TestMainCase:
@pytest.fixture
def client(self):
BASE_DIR = Path(__file__).resolve().parent.parent
self.app = create_app()
self.app.app_context().push()
... | nilq/baby-python | python |
import json
import falcon
import smtplib
from smtplib import SMTPException
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
corp_email_server = 'mail.example.com'
corp_email_port = 587
corp_email_name = "My Company"
corp_email_sentfrom = 'donotreply@example.com'
corp_email... | nilq/baby-python | python |
import pyctrl.bbb as pyctrl
class Controller(pyctrl.Controller):
def __init__(self, *vargs, **kwargs):
# Initialize controller
super().__init__(*vargs, **kwargs)
def __reset(self):
# call super
super().__reset()
# add source: encoder1
self.add_device('encode... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2014, Nicolas P. Rougier. All rights reserved.
# Distributed under the terms of the new BSD License.
# -----------------------------------------------------------------------------
import unittest
imp... | nilq/baby-python | python |
'''
A recursive approach to implementing the fibonacci series
This is a BAD approach since it takes a very long time to execute
takes a ridiculously long time
'''
def fib_recurr(n):
if n <= 1:
return n
else:
return fib_recurr(n-1) + fib_recurr(n -2)
| nilq/baby-python | python |
def create_mapping_with_unk(dico):
sorted_items = sorted(dico.items(), key=lambda x: (-x[1], x[0]))
id_to_word = {index + 1: w[0] for (index, w) in enumerate(sorted_items)}
word_to_id = {v: k for k, v in id_to_word.items()}
id_to_word[0] = "<unk>"
word_to_id["<unk>"] = 0
return word_t... | nilq/baby-python | python |
"""
Scenario:
1 speaker, 2 listeners (one of which is an adversary). Good agents rewarded for proximity to goal, and distance from
adversary to goal. Adversary is rewarded for its distance to the goal.
"""
import numpy as np
from multiagent.core import World, Agent, Landmark
from multiagent.scenario import BaseScenar... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.