content stringlengths 5 1.05M |
|---|
import pandas
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
#Read data
games = pandas.read_csv("game.csv")
print games.columns
print games.shape
plt.hist (games... |
import komand
from .schema import ReadIncidentInput, ReadIncidentOutput, Input, Output, Component
# Custom imports below
from komand.exceptions import PluginException
class ReadIncident(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name='read_incident',
... |
# Copyright ClusterHQ Inc. See LICENSE file for details.
from __future__ import absolute_import
from functools import partial
from characteristic import attributes
from eliot import write_failure, Message, MessageType, Field
from effect import TypeDispatcher, ComposedDispatcher
from txeffect import (
make_twis... |
#!/bin/python3
import os, requests, zipfile, tempfile
t = tempfile.TemporaryFile()
print("Zipping lfs to temp ...")
def zipdir(path):
ziph = zipfile.ZipFile(t, 'w', zipfile.ZIP_DEFLATED)
# ziph is zipfile handle
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.pa... |
import requests
from bs4 import BeautifulSoup
liste=list()
url="https://www.webtekno.com/"
veri=requests.get(url)
html=veri.content
parcala=BeautifulSoup(html,"html.parser")
for i in parcala.find_all("span",{"class":"content-timeline--underline"}):
liste.append(i.text)
for x in liste:
p... |
import PySide2
from PySide2 import QtCore, QtWidgets, QtGui
class EmbeddedWidget(QtWidgets.QWidget):
def mousePressEvent(self, event:PySide2.QtGui.QMouseEvent):
print("EmbeddedWidget mousePress", event)
return super(EmbeddedWidget, self).mousePressEvent(event)
class EmbeddedChild(QtWidgets.QLabel):
def __init... |
import gym
from gym import Wrapper
from gym.wrappers import Monitor
from gym import error, version, logger
import os, json, numpy as np, six
from gym.wrappers.monitoring import stats_recorder, video_recorder
from gym.utils import atomic_write, closer
from gym.utils.json_utils import json_encode_np
import numpy as np
im... |
import telepot
from keys import telegram_api_key, telegram_bot_url
bot = telepot.Bot(telegram_api_key)
bot.setWebhook(telegram_bot_url) |
from django.views import generic
from django.conf import settings
from mnm.instances.models import Instance
class Index(generic.TemplateView):
template_name = 'pages/home.html'
def get_context_data(self):
context = super().get_context_data()
context['biggest_instances'] = Instance.objects.p... |
#https://codeforces.com/problemset/problem/112/A
s1 = input().lower()
s2 = input().lower()
for i in range(len(s1)):
if(ord(s1[i])==ord(s2[i])):
ans=0
elif ord(s1[i])>ord(s2[i]):
ans=1
break
else:
ans=-1
break
print(ans) |
from .. import utils
from . import NbGraderPreprocessor
from nbconvert.exporters.exporter import ResourcesDict
from nbformat.notebooknode import NotebookNode
from typing import Tuple
class ComputeChecksums(NbGraderPreprocessor):
"""A preprocessor to compute checksums of grade cells."""
def preprocess_cell(sel... |
from typing import Any, List, Optional
import phonenumbers
from django.core.exceptions import ValidationError as DjangoValidationError
from django.core.validators import URLValidator, validate_email
from django.db import transaction
from django.utils.translation import gettext as _
from rest_framework import serialize... |
from .sac_trps import Agent
|
import numpy as np
import geopandas as gpd
from shapely.geometry import mapping
from shapely.geometry.polygon import Polygon
from shapely.geometry.multipolygon import MultiPolygon
def Geo2Array(geo, skip=0):
result = []
all_coords = mapping(geo)["coordinates"]
array = np.array(all_coords)
result=list(a... |
from sak_cowsay.cowsay import cowsay
def test_cowsay_default() -> None:
# GIVEN.
ref = """\
_____________
< Hello world >
-------------
\\ ^__^
\\ (oo)\\_______
(__)\\ )\\/\\
||----w |
|| ||
"""
# WHEN.
ret = cowsay()
# ... |
# coding=utf-8
# @Time : 2020/12/3 17:31
# @Auto : zzf-jeff
'''
onnx model inference
using to check onnx output equal torch output
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import onnxruntime
import numpy as np
from torch imp... |
# ------------------------------------------------------------------------------
# CodeHawk Java Analyzer
# Author: Henny Sipma
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2016-2020 Kestrel Technology LLC
# Copyright (c) 2021 Andrew McG... |
"""
A pytorch implementation for cvpr17 paper "Deep Video Deblurring for Hand-held Cameras"
Author: Mingdeng Cao
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from ...build import BACKBONE_REGISTRY
@BACKBONE_REGISTRY.register()
class DBN(nn.Module):
def __init__(self, num_frames, in_... |
def f():
b = 1
#a = 1 + 3 + 5 + 1.1 + b
return b
a = 1 + f() + '111' |
def reverse_array(lista):
"""
-> Funcao de inverter valores de uma lista
:param lista: lista que ta sendo importada
:return: Nao ta retornando nada, ele faz o esquema e executa la msm
"""
print(f'Normal = {lista}')
x = 0
y = len(lista) - 1 # -1 Aqui pq len() retorna o número de valores ... |
"""
MongoDB is very easy to setup. There are no configuration options, just mention
it:
.. sourcecode:: yaml
deploy:
- mongodb
There remains one glitch, by default the mongodb port 27017 is open. Maybe add
``bind_ip = 127.0.0.1`` to ``/etc/mongodb.conf``? I have no idea how insecure
it is, but it seems t... |
from graph_common import *
def build(graph:Graph):
deps = []
added = [False] * len(graph.nodes)
for i in range(len(graph.nodes)):
error = resolve_dependencies(graph.nodes[i], deps, added)
if error == -1:
return "Projects have a cycle"
return ".".join([str(c) for c in deps])
def resolve_depen... |
# coding: utf-8
##############################################################################
# Copyright (C) 2019 Microchip Technology Inc. and its subsidiaries.
#
# Subject to your compliance with these terms, you may use Microchip software
# and any derivatives exclusively with Microchip products. It is your
# resp... |
from fhir_helpers.resources.lpr import LPR
from .helpers import get_example_bundle, get_example_bundle_proto
def test_lpr_init() -> None:
lpr_dict = LPR(get_example_bundle())
lpr_proto = LPR(get_example_bundle_proto())
assert lpr_dict.patient
assert len(lpr_dict.observations) == 137
assert len(l... |
import liraparser
import linear as linear
import graph_plot as gp
import numpy as np
def select_P():
pass
def iteration(P_init, le, lp, steps):
K = None
U = np.zeros(len(lp)*2)
delta=1/steps
count = delta
P = P_init*delta
s1 = [] # Сигма критическое
s2 = [] # Сигма э... |
from PyQt5 import QtCore
from PyQt5.QtCore import QPointF, QRect
from PyQt5.QtGui import QTextDocument, QTextOption
from PyQt5.QtGui import QPainter, QImage, QColor, QFont
import sys
from PyQt5 import QtGui
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication
from epyseg.draw.shapes.rect2d import Rect2D... |
import json # py2.6+ TODO: add support for other JSON serialization modules
from google.protobuf.descriptor import FieldDescriptor as FD
from functools import partial
class ParseError(Exception): pass
def json2pb(pb, js, useFieldNumber=False):
''' convert JSON string to google.protobuf.descriptor instance ''... |
import prettytable as pt
from pymatgen.util.serialization import pmg_serialize
from monty.json import MSONable
def seconds_to_hms(seconds):
"""
Converts second to the format "h:mm:ss"
Args:
seconds: number of seconds
Returns:
A string representing the seconds with the format "h:mm:s... |
"""
JADS 2020 Data-Driven Food Value Chain course
Introduction to Sensors
Lunar Lander Micropython Exercise
"""
# ------------------------ Objective of the game -------------------------------------
# this game simulates a lunar landing module (LLM) landing on the moon
# you are the pilot and need to c... |
#
"""tasks to configure machine
"""
import re, os
from .tasks import op_task_python_simple, fstab_template, efi_template, swap_template
#from .estimate import
from ..lib.util import get_triage_logger
from ..lib.grub import grub_set_wce_share
from ..ops.pplan import EFI_NAME
tlog = get_triage_logger()
#
# Generatin... |
#!/usr/bin/env python3
"""Python Essentials
Chapter 12, Script 1
"""
c= float(input("Temperature °C: "))
f = 32+9*c/5
print("C={c:.0f}°, F={f:.0f}°".format(c=c,f=f)) |
import tensorflow as tf
import matplotlib.pyplot as plt
from dlgAttack import *
if __name__ == "__main__":
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
x_train = x_train[:1]
x_train = x_train.reshape(1, ... |
import os
import requests
from . import base
from .. import utils
DEFAULT_SECTION = 'General'
class Client(base.Client):
options = {
'required': ['name', 'url', 'token'],
'properties': {
'name': {
'description': 'Name of the project.',
'type': 'string... |
from .CoreInternalError import InternalAPIError
class InvalidAPIMethod(InternalAPIError):
def __init__(self,method):
super().__init__(
message=f"{method} not allowed for this API",
returnCode=405)
class InvalidMethodForRoute(InternalAPIError):
def __init__(self,method,route):
... |
import numpy as np
import logging
from scipy.stats import truncnorm
def selection(Z):
"""
Characterising selecting the top K Models from vector Z as a linear
combination.
input
Z : "Feature vector" with a normal distribution.
K : Number of selections.
... |
# -*- Mode: Python -*-
# http://en.wikipedia.org/wiki/ANSI_escape_code
import array
import coro
import math
W = coro.write_stderr
CSI = '\x1B['
at_format = CSI + '%d;%dH%s' # + CSI + '0m'
def at (x, y, ch):
return at_format % (y, x, ch)
import random
class arena:
def __init__ (self, w=150, h=53):
... |
# encoding=utf8
# pylint: disable=too-many-function-args
from NiaPy.tests.test_algorithm import AlgorithmTestCase, MyBenchmark
from NiaPy.algorithms.basic import AntColonyOptimization
class ACOTestCase(AlgorithmTestCase):
def test_parameter_type(self):
d = AntColonyOptimization.typeParameters()
sel... |
from setuptools import setup
from gecrypt import VERSION
def readme():
with open('README.md') as f:
return f.read()
setup(
name='git-easy-crypt',
version=VERSION,
description='The easy way to encrypt/decrypt private files in the git repo.',
long_description=readme(),
long_description... |
import ctypes
from ctypes.util import find_library
import errno
from . import _libc
from ._constants import ScmpArch, ScmpCmp
__all__ = (
"ScmpArg",
"scmp_filter_ctx",
"seccomp_arch_add",
"seccomp_arch_native",
"seccomp_export_pfc",
"seccomp_init",
"seccomp_load",
"seccomp_release",
... |
# Hardware: ESP32
# Required modules:
# picoweb
# pkg_resources (required by picoweb)
# logging (required by picoweb)
# microbmp
# Required actions:
# Set essid and password of your own wifi
import network
from io import BytesIO
import picoweb
import logging
from microbmp import MicroBMP
essid = "YOUR_ESSI... |
from __future__ import absolute_import
import datetime
import django.test
from django.core.urlresolvers import reverse
from ..models import Topic, Question
class FAQModelTests(django.test.TestCase):
def test_model_save(self):
t = Topic.objects.create(name='t', slug='t')
q = Question.objects.c... |
import argparse
from onnxruntime.quantization import quantize_qat, QuantType
def parse_args():
parser = argparse.ArgumentParser(description='Evaluate metric of the '
'results saved in pkl format')
parser.add_argument('--model_path', type=str, default=None)
... |
class Solution:
def fizzBuzz(self, n: 'int') -> 'List[str]':
store = []
for buzzer in range(1, n + 1):
result = ""
if buzzer % 3 == 0:
result += "Fizz"
if buzzer % 5 == 0:
result += "Buzz"
store.append(result or str(... |
import matplotlib.pyplot as plt
valor_apl=input("Qual o número que será aplicado?\n")
valor_apl=int(valor_apl)
valor_ger=0
valor=[]
valorb=[]
while valor_apl !=1:
if valor_ger==0:
valor.append(valor_apl)
valor_ger+=1
print("valores: ")
if valor_apl%2==0:
print (str(valor_apl))
valor_apl=(... |
#!python
# -*- coding: UTF-8 -*-
import logging
from live_recorder import you_live
"""
File: recorder.py
Author: Doby2333
Date Created: 2021/01/24
Last Edited: 2021/01/24
Description: Does the recording thing.
Note: *** Deprecated ***
"""
class Recorder:
def __init__(self, room_id, save_dir='./download'):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# The MIT License
#
# Copyright (c) 2016 Grigory Chernyshev
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation file... |
"""Script that summarizes Skyfield test results."""
from pathlib import Path
import pandas as pd
RESULTS_DIR_PATH = Path(
'/Users/harold/Desktop/NFC/Data/Astronomy/Skyfield Test Results')
DIFF_COUNT_FILE_PATH = \
RESULTS_DIR_PATH / 'Twilight Event Difference Counts.csv'
UNMATCHED_EVENTS_FILE_PATH = RESUL... |
from statsmodels import NoseWrapper as Tester
test = Tester().test
from formulatools import handle_formula_data
|
import cv2
import os
import tqdm
import argparse
argparser = argparse.ArgumentParser(description='Help =)')
argparser.add_argument('-i', '--input', help='path to folder to flip')
argparser.add_argument('-o', '--output', help='path to folder to output')
def main(args):
inputFldr = args.input
outputFldr = args... |
import actions
def test_start_failure():
assert True
|
import distutils.cmd
import glob
from setuptools import setup
import setuptools.command.build_ext
import shutil
import subprocess
class WafCommand(distutils.cmd.Command):
user_options=[]
def initialize_options(self):
pass
def finalize_options(self):
pass
class WafConfigureCommand(WafComman... |
from pathlib import Path
# Generic file class
class File:
def __init__(self, file_path: str):
"""
Constructor for File object
:type file_path: full path to file
"""
self.file_path = file_path
def exists(self):
"""
Chek if the file specified by file_path... |
#! /usr/bin/env python
import multiprocessing, Queue
import time
from log_it import *
#if temporalBAStack is already imported from a higher level script, then
#this import is not needed
#from process_temporal_ba_stack import temporalBAStack
class parallelSceneWorker(multiprocessing.Process):
"""Runs th... |
from rest_framework import serializers
from question.models import Question, QuestionOption
class QuestionOptionSerializer(serializers.ModelSerializer):
class Meta:
model = QuestionOption
fields = '__all__'
class QuestionSerializer(serializers.ModelSerializer):
option = serializers.StringRe... |
import numpy as np
argsorted = lambda x: sorted(range(len(x)), key=x.__getitem__, reverse=True)
def log_probabilities(preferences):
probabilities = np.exp(np.array(preferences))
probabilities = list(probabilities)
#print(sum(list(probabilities)))
return probabilities / sum(probabilities)
class Builde... |
# -*- coding: utf-8 -*-
# Copyright 2020 PyPAL 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 applicable la... |
from Apartamento import Apartamento
from Torre import Torre
from ListaApartamento import ListaApartamento
from Fila import Fila
class main:
t1 = Torre()
t1.cadastrar(1, "A", "Acesso 123")
t2 = Torre()
t2.cadastrar(2, "B", "Acesso 456")
t3 = Torre()
t3.cadastrar(3, "C", "Acesso 789")
pri... |
from os.path import dirname, join
from my_lib.loader.specific.json_loader import load_json
from my_lib.loader.specific.yaml_loader import load_yaml
from my_lib.loader.txt_loader import load_text
def display_content(file_name: str):
if file_name.endswith('.txt'):
print('Text file:')
txt_content = ... |
from matplotlib import pyplot as plt, animation
from random import randint
fig: plt.Figure = plt.figure()
axis: plt.Axes = fig.add_subplot()
data = [randint(1, 10) for _ in range(100)]
def animate(i):
global data
data = [it + randint(-5, 0) for it in data]
axis.clear()
for i, v in enumerate(data):
... |
import logging
DEFAULT_PARTITIONS = 1
logging.basicConfig(level=logging.INFO, format="%(message)s")
__version__ = "0.0.1"
from .pyroar import Pyroar
from .manipulator import Manipulator
|
# Copyright 2012 OpenStack Foundation
#
# 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... |
import re
from collections import defaultdict
import textwrap
import copy
###Constants###
LABEL_SECTION = 'Label: '
PIC_TITLE = 'Detected labels for '
END_LABEL = '----------'
###Variables###
maxLevel = 0
oldest = ""
delete_list = defaultdict()
def LoadData(impLabels,text):
print(impLabels)
labels=defaultdi... |
from faked_nfvo.api.validation import parameter_types
"([0-9]{1,3}\.){3}[0-9]{1,3}"
uri_type = {'type': 'string',
'pattern': '^(https://)([0-9]{1,3}\.){3}[0-9]{1,3}:[0-9]{1,5}'
'/v1/vimPm/files/(.*)(\.gz)$'}
vim_src_type = {
"type": "string",
"enum": ["vpim", "vim"],
}
pu... |
from fastbay.fastbay import fbay
|
"""terraform_to_ansible/__init__.py"""
|
from common import *
import params
import util
import parrun
import weightsave
import net_mitral_centric as nmc
def build_complete_model(connection_file):
# distribute
nmc.build_net_round_robin(getmodel(), connection_file)
import distribute
import multisplit_distrib
multisplit_distrib.multisplit_distrib(d... |
"""Copyright 2021 Province of British Columbia.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing... |
# -*- coding: utf-8 -*-
from collections import OrderedDict
import six
from django.contrib.admin.filters import (BooleanFieldListFilter, ChoicesFieldListFilter, DateFieldListFilter,
FieldListFilter)
from django.contrib.admin.views import main
from django.db.models import Bool... |
fo = open("scripts_rnns_perfection.sh", "w")
for seed in range(100):
for model in ["gru", "lstm"]:
jobname = "perfection_" + model + "_trainsize_10000_dataset_length5_ninn_withholding_bs_10_patience_5_hidden_296_257_layers_2_seed_" + str(seed)
if model == "gru":
fo.write("time pytho... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from peewee import ForeignKeyField
from playhouse.postgres_ext import BinaryJSONField
from .base import BaseModel
from .round import Round
from .concerns.round_related_model import RoundRelatedModel
"""Feedback m... |
from settings import *
import torch.nn as nn
class Discriminator(nn.Module):
def __init__(self, ngpu):
super(Discriminator, self).__init__()
self.ngpu = ngpu
self.main = nn.Sequential(
# input is (nc) x 64 x 64
nn.Conv2d(nc, ndf, 4, 2, 1, bias=False),
nn.... |
import math
import unittest
import numpy as np
import fastestimator as fe
from fastestimator.architecture.pytorch import LeNet as LeNet_torch
from fastestimator.architecture.tensorflow import LeNet as LeNet_tf
from fastestimator.backend import get_lr
from fastestimator.dataset.data import mnist
from fastestimator.op.... |
"""empty message
Revision ID: 4887d7d44d6
Revises: None
Create Date: 2015-10-09 02:53:30.559553
"""
# revision identifiers, used by Alembic.
revision = '4887d7d44d6'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
... |
import datetime
import logging
import pandas as pd
import psycopg2
from psycopg2._psycopg import IntegrityError
from selenium.common.exceptions import StaleElementReferenceException
from database_operations import execute_sql_postgres
from live_betting.bookmaker import Bookmaker
def get_tournament_id(book_id: int, ... |
from torchero.models.vision.nn.torchvision import * |
#!/usr/bin/env python
#-*-*- encoding: utf-8 -*-*-
#
# Copyright (C) 2005 onwards University of Deusto
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# This software consists of contributions made by many individual... |
import pytest
from django.test import RequestFactory
from django.urls import reverse
from api.models import UserStats, Log
from api.views import bots
from mixer.backend.django import mixer
from api.tests.utils import *
@pytest.fixture(scope='module')
def factory():
return RequestFactory()
@pytest.fixture
def user_... |
from .seq import Seq
def matrix(seq1: Seq, seq2: Seq):
w, h = len(seq1), len(seq2)
Matrix = [[0 for x in range(w + 1)] for y in range(h + 1)]
for i, ibase in enumerate(seq1, 1):
for j, jbase in enumerate(seq2, 1):
if ibase == jbase:
Matrix[j][i] = Matrix[j - 1][i - 1]... |
#!/usr/bin/env python
# Copyright 2020 Amazon.com, Inc. or its affiliates. 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
# o... |
# Stdlib imports
import os
import pathlib
# Vendor imports
import yaml
# Local imports
from . import helper
_defaultConfig = {"v": 1, "profiles": {}}
def getDefaultConfigPath() -> str:
return os.environ.get("SPGILL_BACKUP_CONFIG", "~/.spgill.backup.yaml")
# Return the config values in the config file
def loa... |
"""
Factory Boy Factory Definition
"""
from django.contrib.auth import get_user_model
from factory.django import DjangoModelFactory as Factory
from factory import LazyAttribute, Sequence, SubFactory
model = get_user_model()
class UserFactory(Factory):
"""
Base User Factory
"""
email = LazyAttribute... |
#!/usr/bin/env python2.6
import lxml.html, re
class InvalidArguments(Exception):
pass
class MetaHeaders:
def __init__(self, url=None, page=None,name='name',content='content'):
if page:
self.root = lxml.html.document_fromstring(page)
elif url:
self.root = lxml.html.parse(url).getroot()
else:
raise In... |
from PyQt5 import uic, QtWidgets
import mysql.connector
import sqlite3
# Conexão com o Banco de Dados
banco = mysql.connector.connect(
host='127.0.0.1',
user='root',
password='',
database='fornecedores'
)
def do_login():
# Login no sistema
login.lineEdit.setText('')
user = login.lineEd... |
# -*- coding: utf-8 -*-
"""
Authentication module.
"""
import flask_login
import requests
from flask import redirect, render_template, request, url_for
from . import AUTH_SERVICE, app, login_manager
from .models import User
@app.route('/signup', methods=['GET', 'POST'])
def signup():
"""
Sign-up page.
... |
import os
from typing import Any, Dict
from jinja2 import Environment, FileSystemLoader
from jinja2.exceptions import TemplateNotFound
from routers import Router
class Bird(Router):
def __init__(self, family: int = 4, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.family = family
... |
from django.views import generic
# Create your views here.
class Index(generic.TemplateView):
template_name = 'index.html'
class Services(generic.TemplateView):
template_name = 'services.html'
class Prices(generic.TemplateView):
template_name = 'prices.html'
class Fleets(generic.TemplateView):
... |
import serial
import serial.tools.list_ports
import tkinter as tk
from tkinter import messagebox
import threading
import pyautogui
import PIL.Image
import PIL.ImageTk
import cv2
# Gloval variables
main_window = tk.Tk()
current_option = tk.StringVar(main_window)
btn_text_var = None
arduino_thread = None
window_is_aliv... |
#!/usr/bin/env python
import click
import json
import os
import re
import requests
import sys
from sh import git, ErrorReturnCode
from aeriscloud.ansible import get_organization_list
from aeriscloud.basebox import baseboxes
from aeriscloud.cli.aeris.sync import sync
from aeriscloud.cli.helpers import Command, fatal,... |
## =========================================================
## bot_v_bot.py
## ---------------------------------------------------------
import time
from nsl.go import agent
# Import goboard
# There are three versions with different degree of optimizations:
#| from nsl.go import goboard_slow as goboard
from nsl.go ... |
def test_convert_bytes32_to_num_overflow(assert_tx_failed, get_contract_with_gas_estimation):
code = """
@public
def test1():
y: bytes32 = 0x1000000000000000000000000000000000000000000000000000000000000000
x: int128 = convert(y, 'int128')
"""
c = get_contract_with_gas_estimation(code)
assert_... |
"""
Change Static IP for Lightsail VPS automatically and update respective DNS settings
"""
import boto3
import json
from datetime import datetime
from time import sleep
import numpy as np
import os
import logging
### Parameters ###
log_file = r'~/logs/changeStaticIP.log'
debug_level = logging.INFO
vHostedZoneId = '... |
import zipfile
import os
import glob
import json
from openstudio_server import OpenStudioServerAPI
def mos_exists(path):
mos = glob.glob(f'{path}/datapoint/*/modelica.mos')
if mos and len(mos) == 1:
return mos[0]
# just return the mos
elif mos and len(mos) > 1:
raise Exception(f"Th... |
from alarm import Alarm
from utilities import Days
import unittest
from unittest.mock import patch
class AlarmComposite(object):
def __init__(self):
self.alarms = []
def add_alarm(self, alarm):
self.alarms.append(alarm)
def add_alarms(self, *args):
for alarm in args:
... |
# static library
src_list= [
'function.cpp',
]
task_list= []
env= tool.createTargetEnvironment()
env.setConfig( 'Debug' )
env.refresh()
task_list.append( tool.addLibTask( env, 'test', src_list ) )
env= tool.createTargetEnvironment()
env.setConfig( 'Release' )
env.refresh()
task_list.append( ... |
import mrjob
from mrjob.job import MRJob
from utils import serialization, logging
import constants.internal as const
class EngineJob(MRJob):
'''
Base class for all M/R Jobs of this ML engine.
'''
def init(self):
try:
if self.is_initialized:
return
except A... |
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if (numRows == 1):
return [[1]]
Array = []
for i in range(numRows):
Array.append([1 for j in range(i+1)])
if (numRows > 2):
for i in range(2,numRows):
... |
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from lib.BootpayApi import BootpayApi
bootpay = BootpayApi('59bfc738e13f337dbd6ca48a', 'pDc0NwlkEX3aSaHTp/PPL/i8vn5E/CqRChgyEp/gHD0=')
result = bootpay.get_access_token()
if result['status'] is 200:
print(bootpay.certificate('12... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
import bcrypt
import re
class UserManager(models.Manager):
def basic_validator(self, postData):
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
errors = {}
if len(postDat... |
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, \
UserMixin, RoleMixin, login_required, roles_accepted
from film_search import config
# Create app
app = Flask(__name__)
app.config.from_object(config.Config)
# Create dat... |
from typing import Any, Dict, Union, Optional
import aiohttp
from .errors import PokemonNotFound, ConnectionError
__all__ = ("HTTPClient",)
BASE_URL = "https://pokeapi.co/api/v2"
class HTTPClient:
"""
Class which deals with all the Requests made to the API.
"""
def __init__(self) -> None:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.