content stringlengths 5 1.05M |
|---|
#!/usr/bin/python3
#Read file $1 and convert to $2
from tabulate import tabulate
from sys import argv
data = []
f1 = open(argv[1], "r")
for line in f1:
nw = line.split()
if len(nw) != 4:
continue
data.append(nw)
f1.close()
rst = tabulate(data[1:], headers=data[0],tablefmt='rst')
f2 = open(argv[2], "w")
f2.write... |
from lpd.enums import Phase, State
from lpd.callbacks.callback_base import CallbackBase
from typing import Union, List, Optional
class LossOptimizerHandlerBase(CallbackBase):
"""
In case LossOptimizerHandler does not suitable for your needs, create your custom
callback and derive from this class, ... |
import math
import time
from utils.defines import *
from utils.interface import *
kb = KeyBoard(r'/dev/hidg0')
mouse = Mouse(r'/dev/hidg1')
def makeCircle(r):
points = []
for i in range(r):
x = r * math.cos(i * 2 * math.pi / r)
y = r * math.sin(i * 2 * math.pi / r)
points.append((int(... |
from flask import Flask, render_template
from flask_socketio import SocketIO
from config import app_config
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# app.config['SECRET_KEY'] = 'secret!'
app.config.from_pyfile('config.py', silent=True)
app.config.from_object(app_config['development'])
socketio =... |
"""
File: boggle.py
Name: Jeffrey Lin 2020/12
----------------------------------------
This program aim to find words that can be constructed from sequentially
adjacent letters from the 4×4 grid. “Adjacent” letters are those horizontally, vertically,
and diagonally neighbouring. Words must be at least four letters long... |
from exponent_server_sdk import (
DeviceNotRegisteredError,
PushClient,
PushMessage,
# PushResponseError,
)
from app.services.user import UserService
class Notification:
def __init__(self, user_svc: UserService) -> None:
self.user_svc = user_svc
# Basic arguments. You should extend this... |
import os
from os.path import join, dirname
from dotenv import load_dotenv # need to `pip install -U python-dotenv`
# Create .env file path.
dotenv_path = join(dirname(__file__), '.env')
print(dotenv_path)
# Load file from the path.
load_dotenv(dotenv_path)
# Accessing variables.
ACCOUNT_SID = os.getenv('TWILIO_ACC... |
from joblib import load
import pandas as pd
import numpy as np
class models():
def __init__(self):
self.bmi_model = self.load_model(model_path='assets/bmi_model.joblib')
self.general_health_model = self.load_model(model_path='assets/gen_health_model.joblib')
self.model_status = 'Loading'
... |
from numbers import Number
from typing import Iterable
class Skin:
def get_index(self, x: Number, y: Number):
raise NotImplementedError
def get_bounds(self):
raise NotImplementedError
class DefiniteSkin(Skin, object):
__slots__ = ("_skin",)
def __init__(self, skin: Iterable[Iterabl... |
import random
import hashlib
import os
import errno
import base64
from datetime import datetime
import calendar
import time
import flask
from flask import jsonify
from flask.ext.restful import Resource
from sqlalchemy import Column, String, DateTime, SmallInteger, ForeignKey, exc, Integer, not_, exists, BL... |
from onegov.election_day import ElectionDayApp
from onegov.election_day.layouts import ManageLayout
from onegov.election_day.models import Principal
@ElectionDayApp.manage_html(
model=Principal,
name='provoke_error',
template='manage/provoke_error.pt'
)
def view_provoke_error(self, request):
""" Prov... |
from abc import ABC, abstractmethod
class Motorcycle(ABC):
@abstractmethod
def useful_function_b(self) -> str:
pass
|
"""
In order to facilitate data exchange between nodes written in potentially
different languages we use these intermediate data types to encode
to/from the data types used inside of the nodes.
This submodule contains the following user-facing parts:
- Primitive data types:
:py:class:`Bool`
:py:class:`Char`
:py... |
class Solution:
def subarrayBitwiseORs(self, A):
"""
:type A: List[int]
:rtype: int
"""
res, cur = set(), set()
for x in A:
cur = {x | y for y in cur} | {x}
res |= cur
return len(res)
|
from .main import parent_child
|
#
# Autogenerated by Thrift Compiler (0.9.2)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TException, TApplicationException
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol, TProtocol
tr... |
command = input()
all_language = {}
submissions = {}
max_points = {}
while command != "exam finished":
command = command.split("-")
# check for no banned
if len(command) == 3:
language = command[1]
username = command[0]
points = int(command[2])
# collect all submissions
... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
#things to do
#1 comment and review
#imports
import numpy as np
import matplotlib.pyplot as plt
import lightkurve as lk
import tqdm as tq
from scipy.interpolate import interp1d
# In[ ]:
# In[2]:
#downloading the lightcurve file for our example star KIC 106851... |
from datetime import datetime, timedelta, timezone
import json
from .test_envelope import generate_transaction_item
TEST_CONFIG = {
"aggregator": {"bucket_interval": 1, "initial_delay": 0, "debounce_delay": 0,}
}
def test_metrics(mini_sentry, relay):
relay = relay(mini_sentry, options=TEST_CONFIG)
pro... |
from .ahk_binding import AhkBinding |
#!/usr/bin/env python3
import dbus
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GObject
import array
DBusGMainLoop(set_as_default=True)
def get_ble():
return dbus.Interface(dbus.SystemBus().get_object("com.devicehive.bluetooth", '/com/devicehive/bluetooth'), "com.devicehive.bluetooth")
... |
from django.contrib import messages
from django.contrib.auth import get_user_model, login, logout
from django.contrib.auth.views import LoginView
from django.shortcuts import HttpResponseRedirect
from django.urls import reverse_lazy
from django.views.generic import TemplateView, RedirectView
from .forms import UserReg... |
# Copyright (c) 2021 Jana Darulova
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
import logging
from nanotune.device.device_channel import DeviceChannel
from typing import Mapping, Optional, Sequence
from nanotune.device.device import Device
from nanotune.device_tuner.tuner... |
# Importar librerias
import pandas # importar libreria pandas
import time # importar libreria time
import datetime ... |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
class Database:
_conn_string = None
_connection = None
_engine = None
_session_factory = None
_session = None
def __init__(self, *, db, engine, **kwargs):
if not self._conn_string:
... |
cont = ("zero","um", "dois", "três", "quatro",
"cinco", "seis", "sete", "oito", "nove")
while True:
x = int(input("Digite um número entre 1 e 9: "))
if 1 <= x <= 9:
break
print("Tente outra vez. ", end="")
print(f"O número digitado foi {cont[x]}")
|
# Copyright 2017 Google LLC.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
#... |
import numpy as np
import torch
from torch import nn
from torch.autograd import Function
from Code.broyden import broyden
class Broyden_RootFind(Function):
""" Generic layer module that uses bad broyden's method to find the solution """
@staticmethod
def fval(func, q_next, *args):
q_past, q, u_pas... |
"""
Hackerrank Hourglass Solution
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the hourglassSum function below.
def hourglassSum(arr):
largest = -float("inf");pos=-1
for i in range(1, len(arr) -1) :
for j in range(1, len(arr[i])-1) :
sum = arr[... |
import unittest
from parameterized import parameterized as p
from solns.naryTreePreorderTraversal.naryTreePreorderTraversal import *
class UnitTest_NaryTreePreorderTraversal(unittest.TestCase):
@p.expand([
[[1,3,5,6,2,4]]
])
def test_naive(self,expected):
n5 = Node(5)
n6 = Node(6)
... |
import uuid
from datetime import date, datetime
from sqlalchemy import BigInteger, Boolean, Column, Date, DateTime, Enum, ForeignKey, Integer, String, Text, func
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from app.database.dbo.baseclass import Base
from app.domain.models.A... |
import numpy as np
import sys
import os
import bpy
def ShowMessageBox(message = "", title = "Message Box", icon = 'INFO'):
def draw(self, context):
self.layout.label(text=message)
bpy.context.window_manager.popup_menu(draw, title = title, icon = icon)
def is_module_available(module_name):
if sys... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------------------... |
#!/usr/bin/env python3
# Copyright IAIK TU Graz.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
from argparse import ArgumentParser, FileType
from helpers import *
from CircuitGraph import CircuitGraph
from time import perf_counter, process_time
from Z3... |
# Value Function Iteration with IID Income
# Greg Kaplan 2017
# Translated by Tom Sweeney Dec 2020
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
# PARAMETERS
## preferences
risk_aver = 2
beta = 0.95
## returns
r = 0.03
R = 1+r
## income
y = 1
## asset grids
na = 1000
am... |
from colorama import Fore
from rtxlib import info, error
from rtxlib.execution import experimentFunction
def start_sequential_strategy(wf):
""" executes all experiments from the definition file """
info("> ExecStrategy | Sequential", Fore.CYAN)
wf.totalExperiments = len(wf.execution_strategy["knobs"])
... |
#
# PySNMP MIB module Unisphere-Data-ADDRESS-POOL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-ADDRESS-POOL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:23:06 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pytho... |
try:
from setuptools import find_packages, setup
except ImportError:
from distutils.core import find_packages, setup
import sys
from castle.version import VERSION
install_requires = ['requests>=2.5']
test_require = ['responses']
if sys.version_info[:2] == (3, 4):
test_require = ['responses<0.10.16']
set... |
class Issue(object):
"""
Abstract class for issues.
"""
code = ''
description = ''
def __init__(self, lineno, col, parameters=None):
self.parameters = {} if parameters is None else parameters
self.col = col
self.lineno = lineno
@property
def message(self):
... |
#!/usr/bin/env python3
# Usage:
# PYTHONPATH=src ./train --dataset <file|directory|glob>
import argparse
import json
import os
import numpy as np
import tensorflow as tf
import time
import tqdm
from tensorflow.core.protobuf import rewriter_config_pb2
import model, sample, encoder
from load_dataset import load_datase... |
# Copyright 2019 Google LLC.
#
# 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,... |
"""A standard time-integrated analysis is performed, using one year of
IceCube data (IC86_1).
"""
import logging
import unittest
from flarestack.data.public import icecube_ps_3_year
from flarestack.core.unblinding import create_unblinder
from flarestack.analyses.tde.shared_TDE import tde_catalogue_name
from flarestack ... |
#!/usr/bin/env python
# setup.py generated by flit for tools that don't yet use PEP 517
from setuptools import setup, find_packages
setup(
name="nbopen",
version="0.6",
description='Open a notebook from the command line in the best available server',
author='Thomas Kluyver',
author_email='thomas@k... |
import unittest
from unittest import mock
from itertools import product
from remake.task_query_set import TaskQuerySet
class TestTaskQuerySet(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
tasks = []
statuses = {'a': 'completed', 'b': 'pending', 'c': 'remaining'}
for va... |
from experiment_impact_tracker.emissions.rough_emissions_estimator import RoughEmissionsEstimator
def test_rough_emissoins_estimator():
assert "GTX 1080 Ti" in RoughEmissionsEstimator.get_available_gpus()
assert "Dual-core PowerPC MPC8641D" in RoughEmissionsEstimator.get_available_cpus()
emissions_estim... |
"""
made by Gladox114
https://github.com/Gladox114/Python/upload/master/Snake/
"""
import tkinter as tk
import copy
class Map:
def __init__(self, master=None, width=500, height=500, color="black", offset=10, Block=20,FrameColor="pink",FrameColor2="red"):
self.master = master
self.width = width
self.height = hei... |
from django.contrib import admin
from .models import WeChatUser,PhoneUser,UserCreateBookList,BookInList,StarBookList
admin.site.register(WeChatUser)
admin.site.register(PhoneUser)
admin.site.register(UserCreateBookList)
admin.site.register(BookInList)
admin.site.register(StarBookList)
# Register your models here... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010-2016 .
# Guijin Ding, [email protected]
#
#
from .basehandler import BaseHandler
from ppmessage.core.redis import redis_hash_to_dict
from ppmessage.core.utils.datetimestring import datetime_to_timestamp
from ppmessage.core.utils.datetimestring import string_to_datetim... |
class A:
pass
class B(A):
pass
class S(str):
pass
class Animal:
pass
class Person(Animal):
def __init__(self, name: str, age: int):
self.name = name
self.age = age
class PersonAndStr:
def __init__(self, person_a: Person, st: str):
self.pe... |
from django.contrib import admin
from django.urls import path
from base import views
urlpatterns = [
path('', views.algorithmsView, name='pagina_inicial'),
path(r'dataset/', views.datasetView, name='dataset'),
path(r'training/', views.trainingView, name='training'),
#Create
path(r'create_dataset/'... |
import numpy as np
from numpy import ndarray
import scipy.linalg as la
#import solution
from utils.gaussparams import MultiVarGaussian
from config import DEBUG
from typing import Sequence
def get_NIS(z_pred_gauss: MultiVarGaussian, z: ndarray):
"""Calculate the normalized innovation squared (NIS), this can be see... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from .utils import MultiTaskStopOnPlateau
import json
from io import open
from easydict import EasyDict as edict
import torch
import os
from im... |
import redis
from threading import Thread, RLock
import json
import time
import queue
import traceback
import logging
import random
from . import defaults
from . import common
from .utils import (
hook_console,
__org_stdout__,
_stdout,
_stderr,
check_connect_sender,
Valve,
TaskEnv,
)
... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.2.4
# kernelspec:
# display_name: Python (halite)
# language: python
# name: halite
# ---
# # FastAPI Usage
... |
""" Reprosim library - routines for a modelling the lung
The Reprosim library is an advanced modelling library for models of the reproductive system.
"""
classifiers = """\
Development Status :: 4 - Beta
Intended Audience :: Developers
Intended Audience :: Education
Intended Audience :: Science/Research
License :: OS... |
class LocalCache(object):
pass
|
from pwn import *
from Crypto.Util.number import *
from Crypto.Cipher import AES
debug = True
r = remote("crypto.chall.pwnoh.io", 13374, level = 'debug' if debug else None)
r.recvuntil('p = ')
p = int(r.recvline())
assert isPrime(p)
g = 5
r.recvuntil('A = ')
A = int(r.recvline())
B = pow(g, 57, p)
ss = pow(A, 57, ... |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
import os, sys
import numpy as np
from cntk.cntk_py import DeviceKind_GPU
from cntk... |
# http://stackoverflow.com/
# questions/12507274/how-to-get-bounds-of-a-google-static-map
import math
MERCATOR_RANGE = 256
def bound(value, opt_min, opt_max):
if opt_min is not None:
value = max(value, opt_min)
if opt_max is not None:
value = min(value, opt_max)
return value... |
count = 0
ls = [1,2,3,0,4,0]
for i in ls:
if i == 0:
count += 1
print(count)
|
# Copyright European Organization for Nuclear Research (CERN)
#
# 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
#
# Authors:
# - Vincent Garonne, <vin... |
import unittest
from test import testlmlexer
from test import testlmparser
suite = unittest.TestLoader().loadTestsFromTestCase(testlmlexer.testLmLexer)
unittest.TextTestRunner(verbosity=2).run(suite)
suite = unittest.TestLoader().loadTestsFromTestCase(testlmparser.TestLmParser)
unittest.TextTestRunner(verbosity=2).run... |
class Solution:
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
self.is_bipartite = True
visited = [False] * (n + 1)
color = [False] * (n + 1)
# build a graph
graph = [[] for _ in range(n + 1)]
for edge in dislikes:
# undirected g... |
#! /usr/bin/env python
"""
File: interpolate_exp_cos.py
Copyright (c) 2016 Taylor Patti
License: MIT
This module calculates an interpolant approximation to the given function at the given point.
"""
import numpy as np
def exp_cos_func(q):
"""Approximates interpolant approximation to the function."""
mesh... |
import pandas as pd
import itertools
class Node(object):
# frequent pattern tree node
def __init__(self, value, count, parent):
# initialize the node
self.value = value
self.count = count
self.parent = parent
self.link = None
self.children = []
def get_c... |
# -*- coding: utf-8 -*-
# Copyright Joseph Holland
#
# 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... |
import urllib.request,json
from .models import News, news_article
# Getting api key
apiKey = None
# Getting the news base url
base_url = None
def configure_request(app):
global apiKey,base_url
apiKey = app.config['NEWS_API_KEY']
base_url = app.config['NEWS_API_BASE_URL']
def get_news(endpoint):
'''
... |
"""
Author: Colin Rioux
Group SPoC pseudo code and source code together
*Should be run after fix_data
"""
import glob
import pandas as pd
import string
import random
import argparse
import os
from pathlib import Path
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--data_path', default='./data/in/')
ar... |
import click
import numpy as np
from tqdm import tqdm
from ..io import (
append_column_to_hdf5,
read_telescope_data_chunked,
get_column_names_in_file,
remove_column_from_file,
load_model,
)
from ..apply import predict_disp
from ..configuration import AICTConfig
from ..logging import setup_logging
... |
# Copyright 2021 AlQuraishi Laboratory
# Copyright 2021 DeepMind Technologies Limited
#
# 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
#
# U... |
import curses.ascii
class EditField:
"""Single line edit field.
Returns content on Enter, None on cancel (Escape).
Does not touch attributes, does not care about win size.
Does not touch area behind current cursor pos + width.
Clears the touched are when done.
"""
def __init__(self, w... |
"""
This file contains the routes (with a basic example on validation) for
the application.
Either extend this OR create a new routes file and include that one.
"""
import json
import sys
from app import app
from app.utils import Validation, Configuration
from app.payloads import ApplicationPayload, AddUserPayload
... |
import random
random.seed(42)
num_nodes = 10000
max_id = 2**32
max_id = num_nodes * 100
num_channels = 4
node_by_id = dict()
nodeids = []
print "use pypy"
def get_closest_node_id(target_id):
for node_id in nodeids:
if node_id > target_id:
return node_id
return nodeids[0]
class Node(obj... |
# from django.db import models # silence pyflakes
# Create your models here. |
import json
from copy import copy
import dateutil.parser
from mythx_models.response import Analysis, AnalysisStatus
from . import common as testdata
def assert_analysis(analysis):
assert analysis.uuid == testdata.UUID_1
assert analysis.api_version == testdata.API_VERSION_1
assert analysis.maru_version ... |
def validate_thing_amount(user_input):
try:
user_input = int(user_input)
except:
return False
if user_input in range(1, 5):
return user_input
def validate_month_amount(user_input):
try:
user_input = int(user_input)
except:
return False
... |
# %%
cd ..
# %%
from tptp_features.tptp_v7_0_0_0Lexer import tptp_v7_0_0_0Lexer
from tptp_features.tptp_v7_0_0_0Parser import tptp_v7_0_0_0Parser
from tptp_features.tptp_v7_0_0_0Listener import tptp_v7_0_0_0Listener
from antlr4 import FileStream, CommonTokenStream, ParseTreeWalker
from pprint import pprint
#%%
from t... |
#======================================================#
# + Projet: How to use API Rest with Python and Flask #
# + Author: Pedro Impulcetto, Adapted: Thiago Piovesan #
# + API documentation using Swagger:
# YouTube video: https://youtu.be/levz4eumJ98
#======================================================#
# Libra... |
import typing
def main() -> typing.NoReturn:
n, x = map(int, input().split())
# dp
a = list(map(int, input().split()))
dp = [0] * n
dp[0] = x
mn = x
for i in range(n - 1):
p = a[i + 1] // a[i]
dp[i + 1], dp[i] = divmod(dp[i], p)
assert p > dp[i]
... |
from .aBuffer import ABuffer, AMappable
from ...constants import _GL_TYPE_NP_TYPE_MAP, _GL_TYPE_SIZE_MAP
from OpenGL import GL
import numpy as np
class StaticBuffer(ABuffer):
_BufferUsageFlags = 0
def __init__(self, data: list, dataType: GL.GLenum):
super().__init__(len(data) * _GL_TYPE_SIZE_MAP[dataType], dataT... |
"""END MODEL
To better evaluate the quality of our generated training data,
we evaluate an end model trained on this data.
Here, the end model is implemented as a logistic regression bag of words model.
However, you can replace this with any model of your choosing, as long as it has
functions "fit" and "predict" wi... |
"""Collection module."""
from .catalog import Catalog
from .item import ItemCollection
from .utils import Utils
class Extent(dict):
"""The Extent object."""
def __init__(self, data):
"""Initialize instance with dictionary data.
:param data: Dict with Extent metadata.
"""
supe... |
class Solution:
def hasGroupsSizeX(self, deck):
helper = {}
for card in deck:
if helper.__contains__(card):
helper[card] += 1
else:
helper[card] = 1
i = 2
while i <= helper[card]:
status = True
for j in h... |
import numpy as np
import torch
from torch import nn
class regressor_fcn_bn_32_b2h(nn.Module):
def __init__(self):
super(regressor_fcn_bn_32_b2h, self).__init__()
def build_net(self, feature_in_dim, feature_out_dim, require_image=False, default_size=256):
self.require_image = require_image
self.default_size ... |
from qiskit import *
from qiskit.chemistry.drivers import UnitsType, HFMethodType, PySCFDriver
from qiskit.chemistry.core import Hamiltonian, TransformationType, QubitMappingType
from qiskit.chemistry.components.initial_states import HartreeFock... |
import unittest
from cnc.pulses import *
from cnc.config import *
from cnc.coordinates import *
from cnc import hal_virtual
class TestPulses(unittest.TestCase):
def setUp(self):
self.v = min(MAX_VELOCITY_MM_PER_MIN_X,
MAX_VELOCITY_MM_PER_MIN_Y,
MAX_VE... |
"""Simple DHT scraper."""
import logging
import os
import threading
from logging.handlers import TimedRotatingFileHandler
from queue import Queue
from random import randint
from secrets import token_hex
from signal import SIGINT, SIGTERM, signal
from typing import List
from dht_node import DHTNode
from dht_node.data_s... |
#tuto obtenido de aca https://www.youtube.com/watch?v=a8xNuu-2X_4
import sys
import pyqtgraph as pg
import numpy as np
from PyQt5 import QtGui, QtCore
app = QtGui.QApplication(sys.argv) #QGuiApplication
x = np.random.normal(loc=0.0, scale=2, size=100)
widget = pg.PlotWidget(title="Some plotting")
widget.setWindow... |
# 실제로 게임이 진행되는 게임 월드
from character import Player
from attack_kind import FireAttackKind, IceAttackKind
from monsters import (FireMonster, IceMonster, StoneMonster,
KungfuMonster)
fm=FireMonster()
im=IceMonster()
sm=StoneMonster()
kfm=KungfuMonster()
monsters=[]
monsters.extend((f... |
"Bidirectional IPC with anonymous pipes"
'''
Pipes normally let data flow in only one direction—one side is input, one is output.
What if you need your programs to talk back and forth, though? For example, one
program might send another a request for information and then wait for that information
to be sent back. A sin... |
def lastk(head,k):
slow,fast = head,head
while k > 0:
fast = fast.next
k -= 1
while fast != None:
slow = slow.next
fast = fast.next
return slow
|
from core.Model import *
from core.Utils import Utils
class AppVersion(Base, Model):
__tablename__ = 'app_version'
id = Column(Integer, primary_key = True, autoincrement=True)
version = Column(Float, nullable=False)
created = Column(DateTime, default = Utils.time())
formatters = {
"c... |
import yaml
from lib.dashboard import Dashboard
from lib.widgets.wmata_widget import WMATAWidget
from lib.widgets.weather_widget import WeatherWidget
from lib.widgets.calendar_widget import CalendarWidget
from lib.widgets.rss_widget import RSSWidget
from lib.widgets.message_widget import MessageWidget
class DashboardC... |
import subprocess
from manifestManager import ManifestManager
class DiskManager(object):
def __init__(self, configure):
self.imagesLocation = configure.VM_IMAGES_LOCATION
self.vmLocation = configure.INSTANTIATED_VM_LOCATION
self.manifestManager = ManifestManager(configure)
def retriveDisk(self, nfID... |
from datetime import date
from django.shortcuts import render
from django.db.models import Count
from django.http import HttpResponseRedirect
# Create your views here.
from .models import Book, Author, BookInstance, Genre, Loan
def toggle_available_only(request):
if "available_only" in request.session:
r... |
def test_import_databand():
print("Starting Import")
import dbnd
str(dbnd)
def test_import_airflow_settings():
print("Starting Import")
import airflow.settings
str(airflow.settings)
|
from __future__ import annotations
from typing import List, TYPE_CHECKING
from numpy.core.numeric import _outer_dispatcher
if TYPE_CHECKING:
from typing import Any
from .modifiers import Passive
from .stats import Stats
class Item:
def __init__(self, name, cost, stat, passives=None) -> None:
sel... |
from .AbbreviationLegalFormNormalizer import AbbreviationLegalFormNormalizer
from .AndNormalizer import AndNormalizer
from .CharacterNormalizer import CharacterNormalizer
from .CommonAbbreviationNormalizer import CommonAbbreviationNormalizer
from .KeepOtherWordsNormalizer import KeepOtherWordsNormalizer
from .Misplace... |
import asyncio
from datetime import datetime
from nats.aio.client import Client as NATS
async def run(loop):
nc = NATS()
await nc.connect(loop=loop)
async def message_handler(msg):
with open('received.jpg', 'wb') as f:
f.write(msg.data)
await nc.subscribe('webcam', cb=message_ha... |
import pytest
from core.location.mobility import WayPoint
POSITION = (0.0, 0.0, 0.0)
class TestMobility:
@pytest.mark.parametrize(
"wp1, wp2, expected",
[
(WayPoint(10.0, 1, POSITION, 1.0), WayPoint(1.0, 2, POSITION, 1.0), False),
(WayPoint(1.0, 1, POSITION, 1.0), WayPoin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.