content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from networkx.algorithms import bipartite
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
class BipartiteGraphState(QuantumCircuit):
def __init__(self, bipartite_graph):
super().__init__()
self.graph = bipartite_graph
# Create a quantum register based on the number o... | nilq/baby-python | python |
# pylint: disable=no-name-in-module
from collections import deque
from typing import Deque
from pydantic import BaseModel
from ..core.constants import Interval
from .timeframe import TimeFrame
class Window(BaseModel):
"""Holds a sequence of timeframes and additional metadata."""
interval: ... | nilq/baby-python | python |
#!/usr/bin/env python3
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GLib
# keyboard lib
from pynput.keyboard import Key, Listener, Controller
# capslock status
from capslock_status import status
# pop up time in ms
time = 700
# ... | nilq/baby-python | python |
from mix import save_color_image, brightness_limitization
import os
import shutil
from argparse import ArgumentParser
import json
from utils import change_datatype
from utils import timestamp_to_datetime
from utils import Bands
def parse_arguments():
parser = ArgumentParser(description='Create colored images and ... | nilq/baby-python | python |
def deleteWhitespaces(inputStr):
nonWhitespaces = inputStr.split(' ')
return ''.join(nonWhitespaces)
| nilq/baby-python | python |
"""Graph implementation using adjacency lists."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, Set, Optional, Union, Tuple
from collections.abc import Iterable
@dataclass
class Node:
"""This class can be used standalone or with a Graph
(if fast acce... | nilq/baby-python | python |
# encoding = utf-8
"""Wrapper for API calls to ExtraHop."""
# COPYRIGHT 2020 BY EXTRAHOP NETWORKS, INC.
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE', which is part of this source code package.
# This file is part of an ExtraHop Supported Integration. Make NO MODIFICATIONS below this ... | nilq/baby-python | python |
from distutils.core import setup
DESCRIPTION = ('Python interface to the Refinitiv Datastream (former Thomson '
'Reuters Datastream) API via Datastream Web Services (DSWS)')
# Long description to be published in PyPi
LONG_DESCRIPTION = """
**PyDatastream** is a Python interface to the Refinitiv Datastr... | nilq/baby-python | python |
from django.conf import settings
from django.contrib import admin
from django.template.response import TemplateResponse
from django.urls import path, resolve, reverse
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.views.generic import View
from constance import conf... | nilq/baby-python | python |
from robo_navegador import *
from dados_ritmistas import ler_dados
from alterar_docs import *
nomes = ('Matheus Delaqua Rocha De Jesus',
'Cecília')
if __name__ == '__main__':
renomear(nome_atual_pasta='Credenciamento TABU (File responses)')
mover(path=('Arquivo do Documento (File responses)', 'Compro... | nilq/baby-python | python |
import argparse
from pathlib import Path
from event_types import event_types
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=(
'Train event classes models.'
'Results are saved in the models directory.'
)
)
args = parser.parse_args()
n... | nilq/baby-python | python |
#-*- coding: utf-8 -*-
#!/usr/bin/python3
"""
Copyright (c) 2020 LG Electronics Inc.
SPDX-License-Identifier: MIT
"""
import argparse
import copy
import logging
import os
import sys
import textwrap
from .tool_wrapper import get_tool_list, get_tool_wrapper, load_tools
from .context import WrapperContext
from .report ... | nilq/baby-python | python |
from sqlalchemy import (
create_engine as create_engine,
MetaData, Table,
Column, Integer, Sequence,
String, ForeignKey, DateTime,
select, delete, insert, update, func
)
from sqlalchemy.sql import and_
from tornado import concurrent, ioloop
import datetime
import tornado
import sqlite3
#from concurr... | nilq/baby-python | python |
inp = open("input/day6.txt", "r")
prvotne_ribe = [int(x) for x in inp.readline().split(",")]
inp.close()
prvotna_populacija = [0 for _ in range(9)]
for riba in prvotne_ribe:
prvotna_populacija[riba] += 1
def zivljenje(N):
populacija = prvotna_populacija
for _ in range(N):
nova_populacija = [0 for ... | nilq/baby-python | python |
import sys
import pandas as pd
import matplotlib.pyplot as plt
def main():
dfpath = 'nr_dataframes/final.pkl'
df = pd.read_pickle(dfpath)
df.hist(column='length', bins=100)
df = df[df[show] > 400]
plt.show()
if __name__=="__main__":
show = sys.argv[1]
main()
| nilq/baby-python | python |
from selenium import webdriver
import datetime
from . import helper
class NewVisitorTest(helper.FunctionalTestBase):
def setUp(self):
self.browser = webdriver.Firefox()
self.data = {
"dhuha": "4",
"tilawah_from": "1",
"tilawah_to": "20",
"ql": "5",
... | nilq/baby-python | python |
# Generated by Django 2.0.6 on 2018-06-14 08:09
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('course', '0007_auto_2018... | nilq/baby-python | python |
# Generated by Django 3.2.9 on 2021-11-24 15:56
from django.db import migrations
EVENT_TYPES = (
(1, "CREATED", "Created the resourcing request"),
(2, "UPDATED", "Updated the resourcing request"),
(3, "SENT_FOR_APPROVAL", "Sent the resourcing request for approval"),
(4, "AMENDING", "Amending the reso... | nilq/baby-python | python |
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from ckeditor_uploader.fields import RichTextUploadingField
# Create your models here.
class RemoteProfile(models.Model):
host = models.URLField(max_length=200)
api_key = models.CharField(max_length=128... | nilq/baby-python | python |
#!/usr/bin/env python
# $Id: mailtrim.py,v 1.1 2002/05/31 04:57:44 msoulier Exp $
"""The purpose of this script is to trim a standard Unix mbox file. If the
main function is called, it expects two parameters in argv. The first is the
number of most recent messages to keep. The second is the path to the mbox
file."""
... | nilq/baby-python | python |
# 'hello_module.py'
def helloworld():
print ("Hello World!")
def goodbye():
print ("Good Bye Dear!")
| nilq/baby-python | python |
from django.conf.urls import url
from django.views.decorators.csrf import csrf_exempt
from .views import OrderView, PayNotifyView, OrderQueryView
urlpatterns = [
url(r"^order/$", OrderView.as_view(), name="order"),
url(r"^notify/$", csrf_exempt(PayNotifyView.as_view()), name="notify"),
url(r"^orderquery/$... | nilq/baby-python | python |
import flickr_api
import win32api, win32con, win32gui
username = 'NASA Goddard Photo and Video'
flickr_api.set_keys(api_key='73ec08be7826d8b0a608151ce5faaf9d', api_secret='fbb2fcd772ce44a6')
user = flickr_api.Person.findByUserName(username)
photos = user.getPublicPhotos()
print photos[0]
photos[0].save(photos[0].ti... | nilq/baby-python | python |
import math
from error import Error
from dataclasses import dataclass
class Value:
def add(self, other):
self.illegal_operation()
def subtract(self, other):
self.illegal_operation()
def multiply(self, other):
self.illegal_operation()
def divide(self, other):
self... | nilq/baby-python | python |
#
# Memento
# Backend
# Notification Models
#
import re
from datetime import datetime
from sqlalchemy.orm import validates
from ..app import db
# defines a channel where notifications are sent
class Channel(db.Model):
# kinds/types
class Kind:
Task = "task"
Event = "event"
Notice = ... | nilq/baby-python | python |
import unittest
from unittest.mock import Mock
from pydictionaria import sfm_lib
from clldutils.sfm import SFM, Entry
def test_normalize():
from pydictionaria.sfm_lib import normalize
sfm = SFM([Entry([('sd', 'a__b')])])
sfm.visit(normalize)
assert sfm[0].get('sd') == 'a b'
def test_split_join():
... | nilq/baby-python | python |
# shuffle can randomly shuffles a list, and choice make a choice from a set of different items !
from random import choice, shuffle
# use external module termcolor for genarate beautiful colors
from termcolor import colored, cprint
# using pyfiglet, external module -> we can draw ascii_art very easily !
import pyf... | nilq/baby-python | python |
from setuptools import setup
setup(
name='COERbuoyOne',
version='0.2.0',
author='Simon H. Thomas',
author_email='simon.thomas.2021@mumail.ie',
packages=['COERbuoyOne'],
url='http://coerbuoy.maynoothuniversity.ie',
license='LICENSE.txt',
description='A realistic benchmark for Wave Enegery Conver... | nilq/baby-python | python |
from setuptools import setup
setup(
name='ShapeWorld',
version='0.1',
description='A new test methodology for multimodal language understanding',
author='Alexander Kuhnle',
author_email='aok25@cam.ac.uk',
keywords=[],
license='MIT',
url='https://github.com/AlexKuhnle/ShapeWorld',
p... | nilq/baby-python | python |
class Solution:
def validWordSquare(self, words):
"""
:type words: List[str]
:rtype: bool
"""
m = len(words)
if m != 0:
n = len(words[0])
else:
n = 0
if m != n:
return False
for x in range(m):
n... | nilq/baby-python | python |
import matplotlib.pyplot as plt
from models import *
device="cuda:0" if torch.cuda.is_available() else "cpu"
def plot_random():
"""
Plots a random character from the Normal Distribution N[0,5).
No arguments
"""
# dec.eval()
samp=(torch.randn(1,8)*5).float().to(device)
plt.imshow(dec(samp).... | nilq/baby-python | python |
duration_seconds = int(input())
seconds = duration_seconds % 60
temp = duration_seconds // 60
minutes = temp % 60
temp = temp // 60
hours = temp % 60
print(f"{hours}:{minutes}:{seconds}")
| nilq/baby-python | python |
import pickle
import os
import sys
import genetic_algorithm as ga
import game
import pygame
import numpy as np
import snake
def save(generation, details, filename="generation"):
"""
Saves a snakes generation after checking if a file with same name
already exists (also asks for a new name before exiting)
"""
if ... | nilq/baby-python | python |
from bs4 import BeautifulSoup
from urllib.request import urlopen, Request
from time import gmtime, strftime
# Get the data from the source
url = "https://www.house.gov/representatives"
url_req = urlopen(Request(url, headers={'User-Agent': 'Mozilla'}))
raw_html = BeautifulSoup(url_req, "lxml")
html = raw_html.prettify(... | nilq/baby-python | python |
#PasswordGenerator GGearing314 01/10/19
from random import *
case=randint(1,2)
number=randint(1,99)
animals=("ant","alligator","baboon","badger","barb","bat","beagle","bear","beaver","bird","bison","bombay","bongo","booby","butterfly","bee","camel","cat","caterpillar","catfish","cheetah","chicken","chipmunk","cow","cra... | nilq/baby-python | python |
from thundra import constants
from thundra.context.execution_context_manager import ExecutionContextManager
from thundra.wrappers.fastapi.fastapi_wrapper import FastapiWrapper
from thundra.context.tracing_execution_context_provider import TracingExecutionContextProvider
from thundra.context.global_execution_context_pro... | nilq/baby-python | python |
import lanelines
from compgraph import CompGraph, CompGraphRunner
import numpy as np
import cv2
func_dict = {
'warp': lanelines.warp,
'gray': lanelines.gray,
'get_HLS': lanelines.get_hls_channels,
'weighted_HLS_sum': lanelines.weighted_HLS,
'threshold_gray': lanelines.mask_threashold_range,
'th... | nilq/baby-python | python |
import time
import typing as t
from huey import crontab
from app.db.session import db_session
from app.db.crud.server import get_server_with_ports_usage
from app.db.crud.port_forward import get_forward_rule, get_all_expire_rules
from app.db.models.port import Port
from .config import huey
from tasks.ansible import an... | nilq/baby-python | python |
# This is an exact clone of identification.py with functions renamed for clarity and all code relating to creating an
# alignment removed
from typing import Tuple
import sys
import os
path_to_src = (os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
sys.path.append(path_to_src)
from src.objects import Da... | nilq/baby-python | python |
from .base import NextcloudManager
class NextcloudGroupManager(NextcloudManager):
def all(self, search=None):
"""
Get all nextcloud groups
"""
request = self.api.get_groups(search=search)
self.check_request(request)
objs = []
for name i... | nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
from soundsig.plots import multi_plot
"""
Implementation of S. Zayd Enam's STRF modeling stuff:
S. Zayd Enam, Michael R. DeWeese, "Spectro-Temporal Models of Inferior Colliculus Neuron Receptive Fields"
http://users.soe.ucsc.edu/~afletcher/hdnips2013/papers/strfmode... | nilq/baby-python | python |
import binascii
import pytest
from random import random
import jmap
from jmap import errors
@pytest.mark.asyncio
async def test_mailbox_get_all(account, idmap):
response = await account.mailbox_get(idmap)
assert response['accountId'] == account.id
assert int(response['state']) > 0
assert isinstance(... | nilq/baby-python | python |
from ocha.libs import utils
import os, yaml
from ocha.libs import setting
def create_production_env(data_env, app_path):
host = data_env['app']['host']
port = data_env['app']['port']
f=open(app_path+"/production.sh", "a+")
f.write("gunicorn production:app -b "+str(host)+":"+str(port)+" -w 2 --chdir "+... | nilq/baby-python | python |
import os
import sys
import openpype
from openpype.api import Logger
log = Logger().get_logger(__name__)
def main(env):
from openpype.hosts.fusion.api import menu
import avalon.fusion
# Registers pype's Global pyblish plugins
openpype.install()
# activate resolve from pype
avalon.api.instal... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
import math
import numpy as np
VELOCITIES = np.array([
(1, 0),
(np.sqrt(1/2+np.sqrt(1/8)), np.sqrt(1/6-np.sqrt(1/72))),
(np.sqrt(1/2), np.sqrt(1/6)),
... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import hashlib
import json
import psycopg2
import psycopg2.extras
import re
import transforms
import signal
import sys
from get_pg_conn import get_pg_conn
# see https://filosophy.org/code/python-function-execution-deadlines---in-simple-examples/
class TimedOutExc(Except... | nilq/baby-python | python |
# vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:
import unittest
from karmia import KarmiaContext
class TestKarmiaContextSet(unittest.TestCase):
def test_parameter(self):
context = KarmiaContext()
key = 'key'
value = 'value'
context.set(key, value)
self.assert... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
# Copyright (c) 2018-2021 Nicolas Iooss
#
# 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, inc... | nilq/baby-python | python |
# import argv variable so we can take command line arguments
from sys import argv
# extract the command line arguments from argv and store them in variables
script, filename = argv
# print a formatted string with the filename command line arugment inserted
print(f"We're going to erase {filename}")
# print a string
pr... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from django.conf.urls import include, url
from django.contrib import admin
from s_analyzer.apps.rest.api import router
from s_analyzer.site.views import HomeView
urlpatterns = [
url(r'^admin/', admin.site.urls),
... | nilq/baby-python | python |
from django.db import models
from re import sub
# Create your models here.
class Movie(models.Model):
movie_name = models.CharField(max_length=250, unique=True, blank=False, null=False)
movie_year = models.IntegerField()
imdb_rating = models.DecimalField(max_digits=3, decimal_places=2, blank=True... | nilq/baby-python | python |
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from datetime import datetime
from helper.utils import TestUtils as tu
from mushroom_rl.core import Agent
from mushroom_rl.algorithms.actor_critic import SAC
from mushroom_rl.core import Core
from mushro... | nilq/baby-python | python |
# Copyright 2016 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 ... | nilq/baby-python | python |
from table import Table
class CSVTable(Table):
def __init__(self, savepath):
self.savepath = savepath
self.file_created = False
super().__init__()
def _table_add(self):
fieldnames = [column.generate_header() for column in self.columns]
with open(self.savepath, mode="w... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import csv
from pathlib import Path
import tkinter as tk
import argparse
import json
def matchKeyToName(pathToJsonfile:str, key : str):
cityKeysFile = json.load(open(pathToJsonfile))
return cityKeysFile[key]['Town']
def main():
parser = argparse.ArgumentParser()
pa... | nilq/baby-python | python |
"""Events that are emitted during pipeline execution"""
import abc
import datetime
import json
import enum
class Event():
def __init__(self) -> None:
"""
Base class for events that are emitted from mara.
"""
def to_json(self):
return json.dumps({field: value.isoformat() if i... | nilq/baby-python | python |
# An implementation of reference learning for the game TicTacToe
| nilq/baby-python | python |
from enum import Enum
import numpy as np
class TypeData(Enum):
BODY = 0
HAND = 1
class HandJointType(Enum):
BAMB_0 = 0
BAMB_1 = 1
BIG_TOE = 2
BIG_TOE_1 = 3
BIG_TOE_2 = 4
FINGER_1 = 5
FINGER_1_1 = 6
FINGER_1_2 = 7
FINGER_1_3 = 8
FINGER_2 = 9
FINGER_2_1 = 10
FING... | nilq/baby-python | python |
import tensorflow as tf
import time
import os
import sys
import model_nature as model
base = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(base,'../../'))
import datasets.Img2ImgPipeLine as train_dataset
physical_devices = tf.config.experimental.list_physical_devices(device_type='GPU')
t... | nilq/baby-python | python |
#
# Hangman
# Python Techdegree
#
# Created by Dulio Denis on 2/9/17.
# Copyright (c) 2017 ddApps. All rights reserved.
# ------------------------------------------------
# Guess what word the computer picked.
#
import random
import os
import sys
# make a list of words
words = [
'apple',
'... | nilq/baby-python | python |
#!/usr/bin/python3
from shutil import copyfile
from shutil import move
from os import remove
from os import environ
import os
import os.path
import sys
import subprocess
homedir = os.environ['HOME']
bash_target_file = homedir + "/.bashrc"
bash_backup_file = homedir + "/.backup-bashrc"
bash_new_file = homedir + "/.newb... | nilq/baby-python | python |
import json
import uuid
import factory
import mock
from django.test import TestCase
from facility_profile.models import Facility
from facility_profile.models import MyUser
from facility_profile.models import SummaryLog
from test.support import EnvironmentVarGuard
from .helpers import serialized_facility_factory
from ... | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os,sys
import inquirer
import untangle
import requests
import platform
from colors import *
#If you want to use the program using an alias
#uncomment the following line and write your correct path
#os.chdir("/home/user/test/tunein-cli/")
type={}
station={}
headers = { '... | nilq/baby-python | python |
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
# Allows to drag parent widget when holding pushbutton
# To use it you need to set screen_geometry in your QWidget first
class DragButton(QPushButton):
def __init__(self, parent: QWidget, constant_x0: bool):
super(DragButto... | nilq/baby-python | python |
from csv import reader
from . import Destination
from . import DestinationPro
from . import ProtocolPort
def read_prot_port_info(info):
prot_info = {"HTTP": ["1", "1", "1"], "HTTPS": ["1", "0", "1"]}
with open(info, "r") as f:
csv_reader = reader(f)
next(csv_reader)
for row in csv_rea... | nilq/baby-python | python |
# 執行時自行註解掉不需要的段落
# 自動型別
var = 'Hello World' # string
print(var)
var = 100 # int
print(var+10)
print('-----')
# 沒有 overflow
var = 17**3000 # 17的3000次方
print(var)
print('-----')
# swap
a=1
b=2
c=3
print(a,b,c)
c,a,b=b,c,a
print(a,b,c)
print('-----')
# string index
var1 = 'Hello World'
var2 = "Python Prog... | nilq/baby-python | python |
import os, sys, inspect
# use this if you want to include modules from a subforder
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"../")))
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
import simulation_parameters
impo... | nilq/baby-python | python |
# %%
# ml + loss vs inner steps (Sigmoid best val)
import numpy as np
import matplotlib.pyplot as plt
from pylab import MaxNLocator
from pathlib import Path
print('running')
save_plot = True
# save_plot = False
# - data for distance
inner_steps_for_dist = [1, 2, 4, 8, 16, 32]
meta_test_cca = [0.2801, 0.2866, 0.2... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Password generator to generate a password based on the specified pattern.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2018 - 2019 by rgb-24bit.
:license: MIT, see LICENSE for more details.
"""
from .__version__ import __version__, __... | nilq/baby-python | python |
"""Module :mod:`perslay.archi` implement the persistence layer."""
# Authors: Mathieu Carriere <mathieu.carriere3@gmail.com>
# License: MIT
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
# Post-processing opera... | nilq/baby-python | python |
from sqlalchemy.dialects.postgresql import UUID
from app.common.sqlalchemy_extensions import utcnow
from database import db
class BaseModel(db.Model):
__abstract__ = True
id = db.Column(
UUID,
primary_key=True,
server_default=db.func.uuid_generate_v4())
created = db.Column(db.Dat... | nilq/baby-python | python |
"""
Edge Detection.
A high-pass filter sharpens an image. This program analyzes every
pixel in an image in relation to the neighboring pixels to sharpen
the image.
"""
kernel = [[-1, -1, -1],
[-1, 9, -1],
[-1, -1, -1]]
img = None
def setup():
size(640, 360)
img = loadImage("moon.jpg")... | nilq/baby-python | python |
"""
关于dfs,bfs的解释
https://zhuanlan.zhihu.com/p/50187643
"""
class Solution:
def minDepth(self,root):
if not root:
return 0
l = self.minDepth(root.left)
r = self.minDepth(root.right)
return 1 + r + 1 if l == 0 or r == 0 else min(l,r)+1 | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 爬取 春暖花开 论坛帖子中的图片
import os
import fake_useragent
import re
import requests
import time
from bs4 import BeautifulSoup
class Picture:
def all_url(self, url):
"""一个页面有许多图集,而这样的页面有很多,该方法是根据传入的根url,获取所有的页面url"""
list_str = url.split('-')
html = ... | nilq/baby-python | python |
import logging
import numpy as np
import torch
import torch.optim as optim
INFTY = 1e20
class DKNN_PGD(object):
"""
Implement gradient-based attack on DkNN with L-inf norm constraint.
The loss function is the same as the L-2 attack, but it uses PGD as an
optimizer.
"""
def __init__(self, dk... | nilq/baby-python | python |
from projecteuler import util
from functools import reduce
from operator import mul
def solution():
"""
The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
Find the thirteen adjacent digits in the 1000-digit number that have the greatest product.
... | nilq/baby-python | python |
algo = input('Digite algo: ')
print('O tipo primitivo de algo é', type(algo))
| nilq/baby-python | python |
from __future__ import print_function
import base64
import random
from builtins import object, str
from textwrap import dedent
from typing import List
from empire.server.common import helpers, packets
from empire.server.utils import data_util, listener_util
class Listener(object):
def __init__(self, mainMenu, p... | nilq/baby-python | python |
from blackpearl.modules import Module
from blackpearl.modules import Timer
from blackpearl.projects import Project
class MyTimer(Timer):
tick = 0.1
def setup(self):
self.start()
class Listener(Module):
listening_for = ['timer']
def receive(self, message):
print(message['timer'... | nilq/baby-python | python |
from otree.api import *
c = Currency
doc = """
Your app description
"""
class Constants(BaseConstants):
name_in_url = 'payment_info'
players_per_group = None
num_rounds = 1
class Subsession(BaseSubsession):
pass
class Group(BaseGroup):
pass
class Player(BasePlayer):
pass
# PAGES
clas... | nilq/baby-python | python |
from src.grid.electrical_vehicle import EV
from collections import defaultdict
from typing import List
import numpy as np
class Scenario:
def __init__(self,
load_inds: list,
timesteps_hr: np.ndarray,
evs: List[EV],
power_price: np.ndarray,
... | nilq/baby-python | python |
from django.shortcuts import render, redirect
from django.http import HttpResponse
import django.contrib.auth as auth
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from apps import EftConfig
from . import models as etf_models
import json
from parser import parse... | nilq/baby-python | python |
from django.http import HttpResponse, StreamingHttpResponse
from django.views.decorators.csrf import csrf_exempt
from gzip import GzipFile
import tarfile
from io import BytesIO
from datetime import datetime
import json
import traceback
from psycopg2 import OperationalError
from interface.settings import PREVIEW_LIMIT... | nilq/baby-python | python |
import os.path
from PIL import Image
import json
appdata_folder = os.path.join(os.environ["LOCALAPPDATA"], "Nightshift")
def generate_wallpapers(day_img_path, night_img_path, step_count):
print "Generating {0} images from {1} and {2} to {3}"\
.format(step_count, day_img_path, night_img_path, appdata_fold... | nilq/baby-python | python |
"""
adapted from keras example cifar10_cnn.py
Train ResNet-18 on the CIFAR10 small images dataset.
GPU run command with Theano backend (with TensorFlow, the GPU is automatically used):
THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python cifar10.py
"""
from __future__ import print_function
import tensorflo... | nilq/baby-python | python |
class MiscUtils:
def __init__(self):
import requests
import json
r = requests.get("https://backpack.tf/filters")
obj = json.loads(r.text)
particles = obj['particle']
qualities = obj['quality']
rarities = obj['rarity']
paints = obj['paint']
o... | nilq/baby-python | python |
import asyncio
import typing
import logging
from lbrynet.utils import drain_tasks
from lbrynet.blob_exchange.client import request_blob
if typing.TYPE_CHECKING:
from lbrynet.conf import Config
from lbrynet.dht.node import Node
from lbrynet.dht.peer import KademliaPeer
from lbrynet.blob.blob_manager impo... | nilq/baby-python | python |
import grpc
from pkg.api.python import api_pb2
from pkg.api.python import api_pb2_grpc
from pkg.suggestion.test_func import func
from pkg.suggestion.types import DEFAULT_PORT
def run():
channel = grpc.insecure_channel(DEFAULT_PORT)
stub = api_pb2_grpc.SuggestionStub(channel)
set_param_response = stub.Set... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# @Time: 2020/10/10 11:58
# @Author: GraceKoo
# @File: interview_63.py
# @Desc: https://leetcode-cn.com/problems/shu-ju-liu-zhong-de-zhong-wei-shu-lcof/
from heapq import *
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
... | nilq/baby-python | python |
import pytest
from pytest_cases.case_parametrizer_legacy import get_pytest_marks_on_function, make_marked_parameter_value
def test_get_pytest_marks():
"""
Tests that we are able to correctly retrieve the marks on case_func
:return:
"""
skip_mark = pytest.mark.skipif(True, reason="why")
@skip... | nilq/baby-python | python |
from Game import game
class MyClass(object):
gamenew = game()
def executegame(self):
self.gamenew.gamce()
print 'test'
if __name__ == '__main__':
a = MyClass()
a.executegame()
| nilq/baby-python | python |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pickle
from combined_thresh import combined_thresh
from perspective_transform import perspective_transform
from Line import Line
from line_fit import line_fit, tune_fit, final_viz, calc_curve, calc_vehicle_offset, viz2... | nilq/baby-python | python |
from typing import List, Dict, Optional, Union
from sharpy.combat import *
from sharpy.general.extended_power import ExtendedPower
from sharpy.interfaces import ICombatManager
from sharpy.managers.core import UnitCacheManager, PathingManager, ManagerBase
from sharpy.combat import Action
from sc2.units import Units
fr... | nilq/baby-python | python |
names = []
while True:
name = input()
if name == '.':
break
names.append(name)
print(names)
print(len(names))
| nilq/baby-python | python |
import ctypes
import cairo
from pygame.rect import Rect
def get_rect_by_size(upper_corner, size):
return Rect(*upper_corner, size, size)
PyBUF_READ = 0x100
PyBUF_WRITE = 0x200
def get_cairo_surface(pygame_surface):
""" Black magic. """
class Surface(ctypes.Structure):
_fields_ = [
(
... | nilq/baby-python | python |
# Copyright 2018 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 applica... | nilq/baby-python | python |
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.db.models import CharField
from django.db.models.signals import post_save
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.core.mail import EmailMultiAlternatives
from djan... | nilq/baby-python | python |
import numpy as np
class Neurons:
def __init__(self, n_inputs, n_neurons):
self.weights = 1 * np.random.randn(n_inputs, n_neurons)
self.biases = np.zeros((1, n_neurons)) | nilq/baby-python | python |
import abc
import glob
import logging
import os
import subprocess as sp
from collections import OrderedDict
from enum import Enum
from paprika.utils import get_dict_without_keys
from .simulation import Simulation
logger = logging.getLogger(__name__)
class GROMACS(Simulation, abc.ABC):
"""
A wrapper that ca... | nilq/baby-python | python |
a1 = int(input())
a2 = int(input())
n = int(input())
for p in range(a1, ord(chr(a2 - 1)) + 1):
for i in range(1, (n - 1) + 1):
for j in range(1, (int((n / 2) - 1)) + 1):
if (p % 2 != 0) and (((i + j + p) % 2) != 0):
print(f"{chr(p)}-{i}{j}{p}")
| nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.