content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
from zomboid.java import ArrayList
from .base import BaseScriptObject
from ..parser import ScriptParser
Model = None #TODO: replace with class
Vector3f = None #TODO: replace with class
class ModelAttachment:
id : str = None
offset : Vector3f = None
rotate : Vector3f = None
bo... |
#!/usr/bin/env python
"""Tests for `dmx` package."""
import unittest
import time
import os
import numpy as np
import dmx
class TestDMX(unittest.TestCase):
"""Tests for `dmx` package."""
@classmethod
def setUpClass(cls):
"""
setting up everything
:return:
"""
def... |
__all__ = ["MMSegmentationCallback"]
from icevision.imports import *
from icevision.utils import *
from icevision.core import *
from icevision.data import *
from icevision.engines.fastai import *
from icevision.models.mmseg.utils import *
from icevision.models.mmseg.common.prediction import convert_raw_predictions
c... |
import unittest
import os
import bcrypt
from flask import session
from app import create_app as create_app_test
from utils.database import Database
from user.models import User
"""
NB: To run your tests safely, you should comment sending email operations in the `views.py` file.
"""
class UserTest(unittest.TestCa... |
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List
class Mediator(ABC):
@abstractmethod
def broadcast(self, person: Colleague, message: str) -> None:
pass
@abstractmethod
def direct(self, sender: Colleague, receiver: str, message: str) -> None:
... |
import pathmagic # noqa isort:skip
import datetime
import os
import unittest
from database import Database
class TestDB(unittest.TestCase):
def test_run(self):
TEST_DIR = os.path.dirname(os.path.abspath(__file__))
self.db = Database()
EVENT_COUNT = 4
ARTIST_COUNT = 3
... |
import types
import sys
import os
import simplejson
from kascfg import model as model
"""
This module can be used for loading data into your models, for example when setting up default application data,
unit tests, JSON export/import and importing/exporting legacy data. Data is serialized to and from the JSON format.... |
# Copyright 2011 OpenStack LLC.
# 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 b... |
#!/usr/bin/python3
from aos.util.trapezoid_profile import TrapezoidProfile
from frc971.control_loops.python import control_loop
from frc971.control_loops.python import controls
import numpy
import sys
from matplotlib import pylab
import gflags
import glog
FLAGS = gflags.FLAGS
try:
gflags.DEFINE_bool('plot', False,... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
import functools
from time import time
from parameterized import parameterized
import torch
from torch.optim import SGD, Adadelta, Adam # typ... |
# Generated by Django 2.2.13 on 2020-11-23 08:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('per', '0034_auto_20201119_1502'),
]
operations = [
migrations.AddField(
model_name='overview',
name='assessment_num... |
#!/bin/python3
'''
https://www.hackerrank.com/contests/101hack44/challenges/picking-numbers
'''
import sys
n = int(input().strip())
a = [int(a_temp) for a_temp in input().strip().split(' ')]
countArr = [0] * (max(a)+1)
for i in a:
countArr[i]+=1
maxRepeatedNum = countArr.index(max(countArr))
ans = 2
for... |
from django.urls import path
from .friends import MyFriendsAPI
from .request import RequestFriendsAPI, AcceptRequestAPI
urlpatterns = [
path('', MyFriendsAPI.as_view()),
path('request/', RequestFriendsAPI.as_view()),
path('accept-request/', AcceptRequestAPI.as_view()),
] |
import os
import pytest
import requests
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session
from carbonserver.config import settings
# Get the API utl to use from an env variable if exist
URL = os.getenv("CODECARBON_API_URL")
if URL is None:
pytest.exit("CODECARBON_API_URL is not define... |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\event_testing\statistic_tests.py
# Compiled at: 2020-08-18 22:50:49
# Size of source mod 2**32: 5946... |
from external_services import ExternalServices
from k8s import K8sResource
class K8sIngress(K8sResource):
def __init__(self, data: dict, svc: ExternalServices = ExternalServices()) -> None:
super().__init__(data=data, svc=svc)
def is_available(self, state: dict) -> bool:
if 'status' not in s... |
#HOST = '192.168.0.199'
#CONNECTION_INFO = f"host='{HOST}' dbname='{DBNAME}' user='{USERNAME}' password='{PASSWORD}'"
DBNAME = 'words'
file_name = 'words.db' |
# Copyright 2021 Arie Bregman
#
# 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 agree... |
# Created by MechAviv
# Masque's Puzzle Damage Skin | (2435954)
if sm.addDamageSkin(2435954):
sm.chat("'Masque's Puzzle Damage Skin' Damage Skin has been added to your account's damage skin collection.")
sm.consumeItem() |
import base64
import logging
import json
from calendar import monthrange
import datetime
from httplib2 import Http
from json import dumps
def handle_notification(event, context):
"""Triggered from a message on a Cloud Pub/Sub topic.
Args:
event (dict): Event payload.
context (google.cloud.fun... |
import eHive
import os
from VCF.VcfNormalize import VcfNormalize
class VcfAllelicPrim(eHive.BaseRunnable):
"""Run vcfallelicprimitives on a VCF file"""
def run(self):
filepath = self.param_required('filepath')
self.warning('Analysing file: %s'% filepath)
file = os.path.split(filepat... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Production d'un fichier ATOM XML
Definition : https://tools.ietf.org/html/rfc4287
Outil de validation : https://validator.w3.org/feed/
"""
__author__ = 'Frederic Laurent'
__version__ = "1.0"
__copyright__ = 'Copyright 2017, Frederic Laurent'
__license__ ... |
'''
Created on 25 Jan 2018
@author: Slaporter
'''
import platform
def get_platform_info():
return (platform.platform())
if __name__ == '__main__':
get_platform_info() |
from typing import Any, Iterable, Sequence, Optional, Union, overload, TypeVar
import pandas as pd
import numpy as np
from amstramdam.game.geo import Point
from amstramdam.datasets.types import (
Filter,
Mask,
Rank,
PointCreationRecord,
PointUpdateRecord,
GuessRecord,
)
T = TypeVar("T")
def... |
# 通用类
import cmath
import wave
import librosa
import librosa.display
import matplotlib.pyplot as plt
import numpy as np
import pyaudio
class Speech:
def audiorecorder(self, path, len=2, formater=pyaudio.paInt16, rate=16000, frames_per_buffer=1024, channels=2):
p = pyaudio.PyAudio()
stream = p.o... |
import json
import os.path
import re
import sys
import requests
from requests.cookies import RequestsCookieJar
from . import api
from . import errors
class CloudMail:
def __init__(self, login: str, password: str):
self.login = login
self.password = password
self.session = requests.Sessi... |
#!/usr/bin/env python3
'''
Authors: Patrick Kelly (patrickyunen@gmail.com) and Garbo Loo
Last Updated: 3-18-2020
'''
import binascii
import os
import random
import argparse
import ctypes
import ctypes.util
from PIL import Image
from bitstring import BitArray
delimiter = 256 * '1'
#Convert the executable payload t... |
import scipy
from SloppyCell.ReactionNetworks import *
from Nets import *
alb_net.resetDynamicVariables()
alb_times = scipy.logspace(-6, -2, 1000)
alb_traj = Dynamics.integrate(alb_net, alb_times)
heme_net.resetDynamicVariables()
heme_times = scipy.logspace(-1, 3, 1000)
heme_traj = Dynamics.integrate(heme_net, hem... |
from celery import Celery
celery = Celery()
|
# -*- coding: utf-8 -*-
# !/usr/bin/env python2
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
print sys.getdefaultencoding()
next_line_tag = '\n'
navigation = [u"关于我",u"Java",u"数据库",u"设计模式",u"集成框架",u"Linux",u"Go",u"Python",u"Docker",u"大前端",u"工具",u"解决方案",u"管理相关",u"面试题"]
navigationName = 'navigation... |
#!/home/ec2-user/anaconda3/bin/python
# Import data from a sim into the database.
import logging
import os
import sys
import silk
import psycopg2
from netdata.run_collect import SimProgram, silk_str, epoch_utc
def log_info(msg):
"""
Print info log message.
:params msg: message text.
"""
logging.... |
#: E251 E251
def foo(bar = False):
'''Test function with an error in declaration'''
pass
#: E251
foo(bar= True)
#: E251
foo(bar =True)
#: E251 E251
foo(bar = True)
#: E251
y = bar(root= "sdasd")
#: E251:2:29
parser.add_argument('--long-option',
default=
"/rather/long/file... |
import datetime
import logging
import os
import shutil
class Logger:
def __init__(self, context):
self.log_dir = context.workspace
self.path = self.log_dir / "log.txt"
self.logs_to_keep = context.config.get("logs_to_keep", 10)
def create_new_log_file(self):
"""Remove all handl... |
# Copyright 2013 Google Inc. All Rights Reserved.
"""Retrieves information about a Cloud SQL instance operation."""
from googlecloudsdk.calliope import base
from googlecloudsdk.sql import util
class Get(base.Command):
"""Retrieves information about a Cloud SQL instance operation."""
@staticmethod
def Args(pa... |
### Import modules
from base import BaseClass
from utils import utils
from utils.variables import imagenet_map, imagenet_stats
import torchvision.transforms as transforms
import numpy as np
import os, json, cv2, torch, torchvision, PIL
import matplotlib.pyplot as plt
import matplotlib.patches as patches
class Class... |
from unittest.mock import patch
from fastapi.testclient import TestClient
@patch('app.config.get_config')
@patch('app.config.config')
@patch('app.config.configure_logging')
def get_app(a, b, c):
from app.main import app
return TestClient(app)
client = get_app() |
import csv
from happytransformer.happy_text_to_text import HappyTextToText, TTTrainArgs
from datasets import load_dataset
def main():
happy_tt = HappyTextToText("T5", "t5-base")
input_text = "grammar: This sentences had bad grammars and spelling. "
before_text = happy_tt.generate_text(input_text).text
... |
#!/usr/bin/env python2
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directo... |
import unittest
import numpy
import chainer
from chainer.backends import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
@testing.parameterize(*testing.product({
'shape': [
# c, x, y,... |
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
import numpy as np
import dace
N = dace.symbol("N")
@dace.program
def add_one(A: dace.int64[N, N], result: dace.int64[N, N]):
result[:] = A + 1
def call_test():
@dace.program
def add_one_more(A: dace.int64[N, N]):
resul... |
import csv
import collections
import subprocess
from io import StringIO
import base64
import re
from wtforms import form, fields, widgets
from actionform import ActionForm, webserver
def clean(x, subgraph=None):
x = x.strip().replace(" ", "_")
x = re.sub("\W", "_", x)
if subgraph:
subgraph = clean... |
from sqlalchemy.exc import IntegrityError
from src.config import TAG_LOCAL_PICK_UP, TAG_LOCAL_DELIVERY, TAG_LOCAL_OPEN
from src.db.sqlalchemy import db_session
from src.model.local import Local
from src.helper import image as image_util, log
from src.service import category as category_service
from src.service import ... |
# -*- coding: utf-8 -*-
"""
Contain the implementation of the CSP algorithm. Developed for the train part of dataset IV-1-a of BCI competition.
This version (V2) implement the algorithm for data with two classes.
@author: Alberto Zancanaro (Jesus)
@organization: University of Padua (Italy)
"""
#%%
import numpy as np
... |
#!@PYTHON_EXECUTABLE@
"""Example
@PYTHON_EXECUTABLE@ -m timemory.profiler -m 10 -- ./@FILENAME@
@PYTHON_EXECUTABLE@ -m timemory.line_profiler -v -- ./@FILENAME@
@PYTHON_EXECUTABLE@ -m timemory.trace -- ./@FILENAME@
"""
import sys
import numpy as np
def fib(n):
return n if n < 2 else (fib(n - 1) + fib(n - 2))
... |
#!/bin/python3
# author: Jan Hybs
import os
import subprocess
import sys
import threading
from time import monotonic as _time
def construct(start, *rest, shell=False):
args = start.split() if type(start) is str else start
args.extend(rest)
return ' '.join(args) if shell else args
def create_execute_comm... |
import pytest
from typing import Tuple, List
import trees
import players
import games
##### TREES #####
class TreesTest:
def test_contains(self):
self.tree.insert('jon', (250, 250))
assert 'jon' in self.tree
assert 'joe' not in self.tree
def test_tree_contains_point(self):
sel... |
#!/usr/bin/python
# Classification (U)
"""Program: get_disks.py
Description: Unit testing of get_disks in elastic_class class.
Usage:
test/unit/elastic_class/get_disks.py
Arguments:
"""
# Libraries and Global Variables
# Standard
import sys
import os
if sys.version_info < (2, 7):
impor... |
'''
Created on Jun 5, 2021
@author: immanueltrummer
'''
from cp.fact import Fact
from cp.query import QueryEngine
from gym import spaces
from sentence_transformers import SentenceTransformer, util
import gym
import logging
import numpy as np
import torch
from cp.sum import SumGenerator, SumEvaluator
class EmbeddingGr... |
"""
analyst.scale
Corey Rayburn Yung <coreyrayburnyung@gmail.com>
Copyright 2021, Corey Rayburn Yung
License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0)
Contents:
"""
import abc
import dataclasses
from typing import (Any, Callable, ClassVar, Dict, Iterable, List, Mapping,
Optional,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 22 13:06:45 2019
@author: nbaya
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns #; sns.set(color_codes=False)
import scipy.stats as stats
df = pd.read_csv('/Users/nbaya/Documents/lab/risk_gradients/... |
lista = []
while True:
num = int(input('digite um nr: '))
lista.append(num)
loop = ' '
while loop not in 'SN':
loop = str(input('Quer continuar? [S/N] ')).upper().strip()[0]
if loop == 'N':
break
print(sorted(lista, reverse=True))
print(f'foram digitados {len(lista)... |
import sys
n, k, *x = map(int, sys.stdin.read().split())
def main():
res = float("inf")
for i in range(n - k + 1):
j = i + k - 1
if x[i] < 0:
d = -x[i] if x[j] <= 0 else min(-x[i], x[j]) * 2 + max(-x[i], x[j])
else:
d = x[j]
res = min(res, ... |
"""
CLI initialization command.
"""
import click
from rich.prompt import Prompt
from {{cookiecutter.project_slug}} import console
from {{cookiecutter.project_slug}}.constants import WELCOME_MESSAGE
@click.command()
def init():
"""
CLI Initialization demo.
"""
console.print(WELCOME_MESSAGE)
|
import os, sys
import pickle
sys.path.append("../../../")
from data.otb import *
from forecasters import load_forecaster
import torch as tc
if __name__ == "__main__":
dsld = loadOTB("../datasets/otb", 100, bb_format="xyxy")
ld_names = ['val1', 'val2', 'test']
lds = [dsld.val1, dsld.val2, dsld.test]
... |
import torch
import torch.nn as nn
import torchvision.models as models
import torch.nn.functional as F
# from quantizer.utils import Parser
from quantizer.torch.convert import Converter
def main():
# Set up hyper parameters
# dataset = Dataset((40,40,1), 7)
# hparams = HParams(dataset, 0.997, 1e-05)
... |
"""
Library Features:
Name: lib_rfarm_utils_mp
Author(s): Fabio Delogu (fabio.delogu@cimafoundation.org)
Date: '20170530'
Version: '3.5.0'
"""
#######################################################################################
# Logging
import logging
import os
import multiprocess... |
class Timecode():
frames = 0
def __init__(self, string=None, fps=25, total_frames=0):
self.fps = fps
if string is None:
self.total_frames = int(total_frames)
else:
unpacked = string.split(':')
if len(unpacked) == 1:
hours = minutes... |
# -*- coding: utf-8 -*-
from abc import ABC
import torch as T
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
class DeepQNetwork(nn.Module, ABC):
def __init__(self, lr, num_agents, action_size, input_size):
super(DeepQNetwork, self).__init__()
... |
# Bundles for JS/CSS Minification
MINIFY_BUNDLES = {
'css': {
'common': (
'css/normalize.css',
'less/main.less',
'less/search.less',
),
'community': (
'less/wiki-content.less',
'less/community.less',
'less/select.less',
... |
from asciimatics.widgets import Label, Divider, Text
from viewmodels.ethertoken.state import State
"""
Our subviews simply take a layout and inject their content into it
"""
def inject_ether_token_state(layout, col=0):
layout.add_widget(Label('Ether Token'), col)
layout.add_widget(Divider(line_char='-'), col)
... |
import redis
from django.contrib.auth import authenticate
from django.utils.encoding import smart_text
from rest_framework import serializers, status
from rest_framework.authentication import BaseAuthentication, get_authorization_header
from rest_framework.response import Response
from rest_framework_jwt.compat i... |
import gzip
import io
import random
from typing import List, Tuple
import numpy as np
from bsbolt.Impute.Imputation.GenomeImputation import GenomeImputation
from bsbolt.Impute.Impute_Utils.ImputationFunctions import get_bsb_matrix
class ImputeMissingValues:
"""
Launch and knn imputation task. This wrapper imp... |
from gunicorn_logging.formatters import GunicornJsonFormatter
from gunicorn_logging.handlers import LogstashHandler |
def findProfession(level, pos):
# Base case
if level == 1:
return "Engineer"
# Recursively find parent's profession. If parent
# is a doctar, this node will be a doctal if it is
# at odd position and an engineer if at even position
if findProfession(level - 1, (pos + 1) // 2) == "Doctor... |
/home/runner/.cache/pip/pool/16/e0/c9/461291bf12aa9b8a7c5fac61fd22c2aeae992fed1971617a77197b07c2 |
# -*- coding: utf-8 -*-
# @Author: XP
import logging
import os
import torch
import utils.data_loaders
import utils.helpers
from datetime import datetime
from tqdm import tqdm
from time import time
from tensorboardX import SummaryWriter
from core.test_c3d import test_net
from utils.average_meter import AverageMeter
fro... |
# uncompyle6 version 3.3.5
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)]
# Embedded file name: c:\Jenkins\live\output\win_64_static\Release\python-bundle\MIDI Remote Scripts\Push2\clip_control.py
# Compiled at: 2019-04-23 16:19:13
from __futur... |
'''Autogenerated by get_gl_extensions script, do not edit!'''
from OpenGL import platform as _p, constants as _cs, arrays
from OpenGL.GL import glget
import ctypes
EXTENSION_NAME = 'GL_ARB_sync'
def _f( function ):
return _p.createFunction( function,_p.GL,'GL_ARB_sync',False)
_p.unpack_constants( """GL_MAX_SERVER_W... |
from typing import Dict
import tensorflow as tf
__all__ = ["TargetLengthCrop1D"]
class TargetLengthCrop1D(tf.keras.layers.Layer):
def __init__(self, target_length: int, name="target_length_crop", **kwargs) -> None:
super(TargetLengthCrop1D, self).__init__(name=name, **kwargs)
self._target_length ... |
from crypt import methods
from flask import Flask, jsonify, request
from random import randint
import psycopg2
conn = None
try:
conn = psycopg2.connect("dbname='rolldb' user='flaskadmin' host='localhost' password='flaskadmin1'")
except:
print("I am unable to connect to the database")
app = Flask(__name__)
@app.... |
def build(soup, payload):
build_link(soup, payload)
build_summary(soup, payload)
build_tags(soup, payload)
def build_link(soup, payload):
tag = soup.find('link', rel="canonical")
if tag:
payload['id'] = tag.get('href')
payload['url'] = tag.get('href')
def build_summary(soup, payload):
tag = soup.find('meta'... |
"""Unit test package for arcliv."""
|
from __future__ import unicode_literals, print_function, absolute_import
from builtins import input
import bibtexparser
# from . import __version__
# from lxml.etree import ParserError
import re
from title2bib.crossref import get_bib_from_title
from scihub2pdf.scihub import SciHub
from scihub2pdf.libgen import LibGen
... |
import sys
import argparse
from pathlib import Path
from src.utility import *
from src.nut_detector import NutDetector
# st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
sys.stdout = open("log.txt", '+w')
if __name__=="__main__":
parser = argparse.ArgumentParser(description='Commandline ap... |
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Dict, List, Optional
from core.common.drivers.base import BaseDialect
from core.common.drivers.column import Column
from . import MonitorConfiguration, MonitorDefinition
from .base import Monitor
from .metrics import MetricBase
fro... |
import os
import discord
import numpy as np
from PIL import ImageFont, Image
from discord_slash.model import SlashCommandPermissionType
from discord_slash.utils.manage_commands import create_choice, create_permission
from dotenv import load_dotenv
load_dotenv()
def _int(name: str):
try:
return int(name)... |
"""
GraphQL output types and resolvers.
"""
import contextlib
import functools
import inspect
import operator
import types
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from typing import Callable, List, Optional
import pyarrow as pa
import pyarrow.compute as pc
import strawberry
from... |
#!/usr/bin/env python3
from pathlib import PurePath, Path
from typing import List, Dict, Union, Iterator, NamedTuple, Any, Sequence, Optional, Set
import json
from pathlib import Path
from datetime import datetime
import logging
import pytz
from .exporthelpers.dal_helper import PathIsh, Json, Res
def get_logger():
... |
from flask import Blueprint
from flask import (render_template,
url_for,
flash,
redirect,
request,
abort,
Blueprint)
from flask_login import current_user, login_required
from MessageBoard import db
fr... |
import os
import pytest
import requests
def just_test_if_mainnet_node() -> str:
mainnet_node_url = os.environ.get('ETHEREUM_MAINNET_NODE')
if not mainnet_node_url:
pytest.skip("Mainnet node not defined, cannot test oracles", allow_module_level=True)
elif requests.get(mainnet_node_url).status_code... |
# AUTOGENERATED! DO NOT EDIT! File to edit: 07_autoencoder.ipynb (unless otherwise specified).
__all__ = ['get_pixel', 'change_image_background', 'create_augmentor_pipeline', 'load_data']
# Cell
import Augmentor
import os
import numpy as np
from sklearn.model_selection import train_test_split
import matplotlib.pyplot... |
from scipy.cluster.hierarchy import cut_tree
import numpy as np
def cut_tree_balanced(Z, max_cluster_size):
"""
Given a linkage matrix Z and max cluster size, return a balanced cut tree.
The function looks recursively along the hierarchical tree, from the root
(single cluster gathering all the sample... |
# --------------------------------------------------------
# R-C3D
# Copyright (c) 2017 Boston University
# Licensed under The MIT License [see LICENSE for details]
# Written by Huijuan Xu
# --------------------------------------------------------
import os
import copy
import json
import cPickle
import subprocess
impo... |
from __future__ import print_function
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
import numpy as np
import matplotlib.pyplot as plt
import function_blocks as fb
def main():
# ... |
"""
Dinghy daily digest tool.
"""
__version__ = "0.11.2"
|
#!/usr/bin/python
# coding:utf-8
import sys
import subprocess
import socket
import psutil
import json
import datetime
from Crypto.PublicKey import RSA
from hashlib import sha512
device_white = ['eth0', 'eth1', 'eth2', 'eth3', 'bond0', 'bond1']
def get_system_serial_number():
ret = {}
cmd = ... |
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.autograd import Variable
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import torch.backends.cudnn as cudnn
from torch.nn import Parameter
import copy
import argparse
parse... |
#import numpy as np
MIN_SIZE=-1
"""This is the minimum size allowed!"""
_pro_min_size=-2
__pri_min_size=-3
def mini(x, y):
"""
Take the max between two numbers
**Parameters**
> **x:** `float` -- Description of parameter `x`.
> **y:** `float` -- Description of parameter `y`.
**Returns**
... |
#!/usr/bin/env python
import argparse
import time
import sys
from sys import exit
from Emulator import Emulator
import generators
from generators.fba2x.fba2xGenerator import Fba2xGenerator
from generators.kodi.kodiGenerator import KodiGenerator
from generators.linapple.linappleGenerator import LinappleGenerator
from g... |
import os
# print(os.getcwd())
# print(os.path.abspath(__file__))
# print(os.path.dirname(os.path.abspath(__file__)))
os.chdir(os.path.dirname(os.path.abspath(__file__)))
# print(os.getcwd())
file = open(r"test\nfiles\elzero.txt")
|
import runpy
if __name__ == "__main__":
runpy.run_module("pyfahrplan", run_name="__main__")
|
from typing import List, Tuple
from itertools import islice
from functools import reduce
from .cards import Card
from .enums import HandRanking, CardRank, CardSuit
def eval_hand(hand: List[Card]) -> Tuple[int, List[int]]:
""" Evaluate hand of cards
Params
------
hand : list of cards
Up to seven cards to evaluat... |
from petisco.application.application_config import ApplicationConfig
from tests.integration.flask_app.toy_app.application.use_cases.create_user import (
CreateUser,
)
from tests.integration.flask_app.toy_app.application.use_cases.get_user_name import (
GetUserName,
)
class UseCaseBuilder:
@staticmethod
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import codecs
import re
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages # noqa
here = os.path.abspath(os.path.dirname(__file... |
from datetime import datetime, timedelta
DATETIME_FMT = "%a, %d %b %Y %H:%M:%S %Z"
class Repository:
def __init__(self, repo):
self.repo = repo
def to_list(self):
"""
Return relevant fields as list, e.g. for exporting as CSV.
"""
return [
datetime.now().is... |
import logging
from .routes import routes
from loafer.managers import LoaferManager
logger = logging.getLogger(__name__)
logger.info("STARTED APLICATION - GOAT TWEETER ANALYZER")
manager = LoaferManager(routes=routes)
manager.run() |
import ssl
import pandas as pd
import json
from urllib import request as rq
def get_ssl_certificate():
url = "https://fga.unb.br/guia-fga/horario-dos-onibus-intercampi"
context = ssl._create_unverified_context()
response = rq.urlopen(url, context=context)
html = response.read()
return html
def... |
#Desafio 032: Faça um programa que leia um ano qualquer e mostre se ele é BISSEXTO.
import datetime
ano = int(input('Em que ano estamos? Coloque 0 para analisar o ano atual se preferir. '))
if ano == 0:
ano = datetime.date.today().year
if ano%4==0 and ano%100 !=0 or ano%400==0: #!= é diferente
print(f'{ano} é... |
__author__ = 'Christoph Heindl'
__copyright__ = 'Copyright 2017, Profactor GmbH'
__license__ = 'BSD'
import glob
import os
import numpy as np
import matplotlib.pyplot as plt
from sensor_correction.utils import sensor_unproject
from sensor_correction.gp_cpu import GPRegressor
def select_data(temps, poses, all_depths_... |
import logging
from datetime import datetime
from pathlib import Path
from secrets import token_bytes
from typing import Dict, List, Optional, Tuple
from blspy import AugSchemeMPL, G1Element, PrivateKey
from chiapos import DiskPlotter
from ecostake.daemon.keychain_proxy import KeychainProxy, connect_to_keychain_and_v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.