text stringlengths 3.07k 12.6k |
|---|
"""
Report parity errors between PuppetDB and Netbox.
"""
import configparser
import requests
from functools import lru_cache
from dcim.choices import DeviceStatusChoices
from dcim.models import Device
from extras.reports import Report
from virtualization.models import VirtualMachine
VM_BLOCKLIST = ('d-i-test',)
C... |
# -*- coding:utf-8 -*-
import json
class ScoreEvaluator:
def __init__(self, notes_array):
self.pad_states = [PadState(notes) for notes in notes_array]
self.time = 0
self.commands = ["none", "none", "none", "none", "none"]
def reset(self):
# reset all pad states
for pad... |
with open('input.txt') as fh:
instructions = [
line.strip() for line in fh
]
# break full instruction sets into one for each input
digit_instructions = []
for i in instructions:
if i.startswith('inp'):
# start new rule set for input digit
digit_instructions.append([i])
else:
... |
"""WinUSB library wrapper functions
"""
from logging import getLogger
from ctypes import c_ulong
from ctypes import wstring_at, byref, sizeof, resize
from ctypes.wintypes import DWORD, BYTE
from .winsetupapi import SetupDiEnumDeviceInterfaces, SetupDiGetClassDevsW, SetupDiGetDeviceInterfaceDetailW,\
SpDevic... |
"""Django Models for TermsAndConditions App"""
# pylint: disable=C1001,E0202,W0613
from collections import OrderedDict
from django.urls import reverse
from django.db import models
from django.db.models import Q
from django.conf import settings
from django.core.cache import cache
from django.utils import timezone
from ... |
import datetime
from billy.utils.fulltext import pdfdata_to_text, text_after_line_numbers
from .bills import WIBillScraper
from .legislators import WILegislatorScraper
from .committees import WICommitteeScraper
from .events import WIEventScraper
metadata = {
'abbreviation': 'wi',
'name': 'Wisconsin',
'capi... |
import nanogds
import gdspy
import numpy as np
import helpers
PI = np.pi
def get_markerchip_shape(
chip_size=(9000, 5000),
markerfield1_pos=(3500, 2000),
markerfield2_pos=(5500, 2000),
intermediate_p2_bottom=3900,
intermediate_slope_bottom=50,
intermediate_offset_bottom=1100,
intermediate... |
import math
import numpy as np
from src.units import *
g = 1.4
R = 287.
K_von_Karman = 0.35
T0 = 293.15
T_01 = 273.16
p_s0 = atm_to_pa(1.)
"""
Ypologismos At: xrhsimopoietai ston oro poy ypeiserxetai mesa
ston kymatiko arithmo twn komvwn toy aporrofitikoy stromatos
"""
A_t_ = [.2, .2, .4, .5, 1., 10.]
f_ = [0., 30.... |
import numpy as np
from ctypes import *
import sys
import os
__all__ = ['LinearRegression', 'Lasso', 'Ridge', 'ElasticNet', 'LogisticRegression']
DIR_NAME = os.path.dirname(os.path.abspath(__file__))
# Load C-module.
if sys.platform == 'win32':
FILE_NAME = "liblm.dll"
elif sys.platform == 'darwin':
FILE_NAME... |
import struct
import base58
import logging
logger = logging.getLogger(__name__)
def data_entry_from_base58_str(str_object):
base58_str = base58.b58decode(str_object)
return data_entries_from_bytes(base58_str)
def data_entries_from_bytes(bytes_object):
length = struct.unpack(">H", bytes_object[0:2])[0]
... |
from snowboy import snowboydecoder
import sys
import signal
import time
from funcs import capture_image_usb, say
from api import post_face, get_reminders
from apscheduler.schedulers.background import BackgroundScheduler
interrupted = False
epoch = lambda: int(time.time() * 1000)
anti_epoch = lambda epoch: time.strf... |
from collections import defaultdict
import re
import math
import json
class FindNgrams:
def __init__(self, min_count=0, min_pmi=0, min_freq=0):
self.min_count = min_count
self.min_pmi = min_pmi
self.words = defaultdict(int)
self.ngrams, self.pairs = defaultdict(int), defaultdict(int... |
import os
from configuration import *
import yaml
import intervals as I
from .translator.result import *
from .translator.ast import *
##########################################
####### Result-Configuration Linker ######
##########################################
class Linker(object):
def __init__(self,configuration,... |
import sys
import logging
import numpy as np
import tensorflow.keras
from tensorflow.keras import initializers
from tensorflow.python.keras.layers import Input, Embedding, AveragePooling1D, MaxPooling1D, Flatten, Dense, Dropout
from tensorflow.python.keras.layers import Activation, Reshape, Multiply, Add, Lambda, Spat... |
# -*- coding: utf-8 -*-
# Copyright 2004-2007 <NAME>, <NAME>, <NAME>
# 2009-2010 <NAME>
# 2012-2013 <NAME>
# 2009-2013 <NAME>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free... |
"""
Main entry
"""
from collections import deque
import torch
import numpy as np
import time
from rich import print
from functools import partial
from ding.model import QAC
from ding.utils import set_pkg_seed
from ding.envs import BaseEnvManager, get_vec_env_setting
from ding.config import compile_config
from ding.poli... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import mechkit
import mechmean
def test_fabric_tensor_first_kind_discrete():
"""Compare einsum-implementation with loop-implementation"""
orientations = np.random.rand(10, 3) # Ten random vectors in 3D
# Normalize orientations
orie... |
import logging
import math
from .func import *
from .quantizer import *
logger = logging.getLogger()
def quantizer(default_cfg, this_cfg=None, before_model=None, activation=False):
target_cfg = dict(default_cfg)
if this_cfg is not None:
for k, v in this_cfg.items():
target_cfg[k] = v
... |
import json
import numpy as np
import time
import os
from constants import FREIHAND_SKELETON, FREIHAND_KPS
def _assert_exist(p):
msg = 'File does not exists: %s' % p
assert os.path.exists(p), msg
def db_size(set_name):
""" Hardcoded size of the datasets. """
if set_name == 'training':
return 3... |
import collections
from dataclasses import dataclass
from typing import List
import requests
from bs4 import BeautifulSoup
from colorhash import ColorHash
from flask import Flask
from flaskslack.attachment import Attachment, ButtonAttachment, Action, Field
from flaskslack.flaskslack import FlaskSlack
from flaskslack.s... |
from exceptions import InvalidCardSize, InvalidPlayerMove
from game.game_state_machine import GameState, PlayerAction
from game.state.game_state_play import GameStatePlay
from model.player import Player
# ------------------------------------------------------------
# Concrete game state class for bidding
# ---------... |
import tensorflow as tf
from tensorflow import contrib
from tensorflow.contrib import eager as tfe
from matplotlib import pyplot as plt
import numpy as np
from google_drive_downloader import GoogleDriveDownloader as gdd
from logistic_class import LogisticRegressionModel, LogisticRegressionEagerModel
def eager_main(n_... |
import httplib
import urllib
import random
import time
from PIL import Image
import os
from xml.etree import ElementTree
import logging
import StringIO
all_extras = ("description,license,date_upload,date_taken,owner_name,"
"icon_server,original_format,last_update,geo,tags,machine_tags,o_dims,"
"views,media,path_alias,... |
import base64
import json
import logging
from numbers import Number
import pytest
from cryptoadvance.specter.managers.device_manager import DeviceManager
from cryptoadvance.specter.specter import Specter
from cryptoadvance.specter.specter_error import SpecterError
from cryptoadvance.specter.util.wallet_importer import... |
from typing import Tuple
import numpy as np
from sklearn import preprocessing
from typing import List
import random
import torch
from collections import deque
# @Todo CD:Could we combine PrepareBatchOfPrediction and PrepareBatchOfTraining?
class PrepareBatchOfPrediction(torch.utils.data.Dataset):
def __init__(s... |
from collections import namedtuple
from .context import tohu
from tohu.v6 import CustomGenerator, Integer, HashDigest, GetAttribute, SelectOne
class QuuxGenerator(CustomGenerator):
"""
Helper class used in the tests below.
"""
aa = Integer(100, 200)
bb = HashDigest(length=8)
Quux = namedtuple("Q... |
from WassersteinRandomForests import WassersteinRandomForest
import matplotlib.pyplot as plt
import numpy as np
N_total =51000
N_train = 50000
X = np.random.uniform(0,1,(N_total,4))
#X = np.random.normal(0,1,(N_total,10))
def obj_func(x):
"""
conditional expectation
"""
# x0_tilde = 2.*(x[0] - 0.5)
... |
import json;
from mDateTime import cDateTime;
from mFileSystemItem import cFileSystemItem;
from mNotProvided import *;
from cSessionCookie import cSessionCookie;
def fxProcessType(sName, xValue, xAcceptedType):
if not isinstance(xValue, str if xAcceptedType in (bytes, cDateTime) else xAcceptedType):
raise Valu... |
import collections.abc
all_states_transmission = {} # all states that transmit by alphabets for states
t_nfa = [] # set of NFA alphabet
q_nfa = [] # set of NFA state
start_state_nfa = None
final_states_nfa = [] # set of NFA final state
transmissions_nfa = [] # set of NFA transmission
q_dfa = [] # ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright 2015 <NAME>
#
# 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 requir... |
"""Helpers for creating client .h/.cpp files."""
import re
from collections import namedtuple
from enum import Enum
from typing import List, Tuple
import common_helpers
class ParamMechanism(Enum):
"""Enumeration of parameter mechanisms supported by client codegen."""
BASIC = 0
ARRAY = 1
ENUM = 2
... |
import binascii
from PyQt5 import QtCore
from PyQt5.QtWidgets import (
QComboBox,
QMenu,
QMainWindow,
QMessageBox,
QWidget,
QApplication,
QLineEdit,
QTextEdit,
QLabel,
QPushButton,
QVBoxLayout,
QFileDialog,
QHBoxLayout,
QAction,
QMainWindow,... |
"""Parser for the Belief Change Format (BCF) representation of a graph and
associated scenario.
An example of the Belief Change Format is as follows:
n 1..5
a p q r
f 1 (-p)
f 3 (*(p q))
f 3 (+(-p r))
f 4 (+(*(p q) r))
f 5 (*(-q r))
e 1 2
e 1 3
e 3 1
e 2 4
e 4 2
e 2 5
e 5 2
e 4 5
"""
# Copyright (C) 2016
# <... |
import enum
import subprocess
import pathlib
import checksumdir
import numpy as np
import keras
import dataset_norb
class Dataset(enum.Enum):
MNIST = 1
CIFAR10 = 2
NORB = 3
def get_dataset(dataset: Dataset):
if dataset == Dataset.MNIST:
(x_train, y_train), (x_test, y_test) = keras.datasets.... |
"""Nautobot Models for Infoblox integration with SSoT plugin."""
from django.utils.text import slugify
from nautobot.extras.models import Status as OrmStatus
from nautobot.ipam.models import RIR
from nautobot.ipam.models import Aggregate as OrmAggregate
from nautobot.ipam.models import IPAddress as OrmIPAddress
from na... |
import logging
import boto
import boto.s3.connection
import requests
from urllib3.util import Retry
from requests.adapters import HTTPAdapter
from io import BytesIO
from boto.s3.key import Key
from wand.image import Image
from prism.image import ImageOperator, convert_to_premultiplied_png
logger = logging.getLogger(... |
import unittest
import unittest.mock
import io
import numpy as np
from mcstasscript.jb_interface.plot_interface import PlotInterface
from mcstasscript.jb_interface.plot_interface import LogCheckbox
from mcstasscript.jb_interface.plot_interface import ColormapDropdown
from mcstasscript.jb_interface.plot_interface impor... |
from threading import Thread
import pickle
import time
import queue
import redis
import logging
import threading
from rl_coach.memories.backend.memory import MemoryBackend
from rl_coach.core_types import Episode
from markov.utils import Logger, json_format_logger, build_system_error_dict
from markov.utils import SIMA... |
# SecretStorage module for Python
# Access passwords using the SecretService DBus API
# Author: <NAME>, 2013
# License: BSD
"""This module provides some utility functions, but these shouldn't
normally be used by external applications."""
import dbus
import os
from secretstorage.defines import DBUS_UNKNOWN_METHOD, DBU... |
# -*- coding: utf-8 -*-
# Copyright: (c) 2021, <NAME> (@jborean93) <<EMAIL>>
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
import typing
from psrpcore._command import Command
from psrpcore._payload import dict_to_psobject
from psrpcore.types import (
ApartmentState,
CommandTypes,
Crea... |
import pandas as pd
import numpy as np
import re
import statsmodels.formula.api as smf
import seaborn as sns
import matplotlib.pyplot as plt
def _combine_data(exp_design, pca_scores):
'''
combine PC scores and experiment design
generate a dataframe that's suitable for statsmodel
'''
data = exp_de... |
import torch
from transformers import BertTokenizer, BertModel, XLNetTokenizer, XLNetModel,GPT2Tokenizer, GPT2Model, OpenAIGPTTokenizer, OpenAIGPTModel
import numpy as np
from torchtext.datasets import PennTreebank
import re
import string
# from contractions import CONTRACTION_MAP
# https://towardsdatascience.com/nlp-b... |
# 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, software
# d... |
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 Agile Business Group sagl (<http://www.agilebg.com>)
# Copyright (C) 2012 Domsense srl (<http://www.domsense.com>)
# Copyright (C) 2012 Associazione OpenERP Italia
# (<http://www... |
import numpy as np
import datetime
from pychunkedgraph.backend import chunkedgraph
from pychunkedgraph.backend.utils import column_keys
from multiwrapper import multiprocessing_utils as mu
from typing import Optional, Sequence
def _read_delta_root_rows_thread(args) -> list:
start_seg_id, end_seg_id, serialized... |
import argparse
import torch
from torch import nn
from torch import optim
from torchvision import datasets, transforms, models
from collections import OrderedDict
import time
import json
# simple example
# python train.py "flowers" --arch "vgg16" --gpu
# complete example
# python train.py "flowers" --save_dir "train_c... |
from collections.abc import Iterable
import hypothesis.strategies as hst
from hypothesis import given, event, settings
import numpy as np
from qcodes.instrument.parameter import Parameter
def test_scale_raw_value():
p = Parameter(name='test_scale_raw_value', set_cmd=None)
p(42)
assert p.raw_value == 42
... |
from .i2c import I2C
__all__ = ['MCP230XX', 'GPIO']
MCP23017_IODIRA = 0x00
MCP23017_IODIRB = 0x01
MCP23017_GPIOA = 0x12
MCP23017_GPIOB = 0x13
MCP23017_GPPUA = 0x0C
MCP23017_GPPUB = 0x0D
MCP23017_OLATA = 0x14
MCP23017_OLATB = 0x15
MCP23008_GPIOA = 0x09
MCP23008_GPPUA = 0x06
MCP23008_OLATA = 0x0A
class MC... |
import collections
import multiprocessing
from typing import Dict, List
import numpy as np
import networkx as nx
import torch
import tqdm
from scipy.spatial import distance
from sklearn import svm
from sklearn.model_selection import ShuffleSplit, GridSearchCV
from model import GraphEncoder, CrossGraphAttention, CrossG... |
from django.db import models
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from django.utils.html import mark_safe
from django.urls import reverse, reverse_lazy
from django.template.defaultfilters import truncatechars
from cuser.middleware import CuserMiddleware
from diventi.... |
# Link to the original code:
# https://gist.github.com/t20100/e5a9ba1196101e618883
# /*##########################################################################
#
# Copyright (c) 2016 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this soft... |
import torch
import torch.nn as nn
from fc import FCNet
from torch.nn.utils.weight_norm import weight_norm
class TCNet(nn.Module):
def __init__(self, v_dim, q_dim, a_dim, h_dim, h_out, rank, glimpse, act='ReLU', dropout=[.2, .5], k=1):
super(TCNet, self).__init__()
self.v_dim = v_dim
self.... |
import logging
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.response import Response
from django.shortcuts import render
import json
from atlas.prodtask.models import StepTemplate, StepExecution, InputRequestList, TRequest, MCPattern, ProductionTask, \
... |
import pytest
import torch
from torch.autograd import gradcheck
from torch.testing import assert_allclose
import kornia.geometry.epipolar as epi
class TestIntrinsicsLike:
def test_smoke(self, device, dtype):
image = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
focal = torch.rand(1, device=... |
import keras
from keras.models import Model, load_model
from keras.layers import Concatenate,Dense,Input,Dropout,BatchNormalization,Activation,Add,Lambda, InputLayer, UpSampling2D,ZeroPadding2D
from keras.layers.core import Lambda
from keras.layers.convolutional import Conv2D, Conv2DTranspose
from keras.layers.pooling... |
"""
Test math overloads.
"""
import math
import unittest
import numpy as np
# Change this to inspect output.
VERBOSE = False
def debug_print(*args):
# Prints only if `VERBOSE` is true.
if VERBOSE:
print(*args)
def qualname(obj):
return "{}.{}".format(obj.__module__, obj.__name__)
class Ove... |
# Copyright © 2019 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 agr... |
from collections import OrderedDict
from django.http import Http404
from rest_framework.fields import SkipField
import graphene
import graphene.relay
from graphene.types import Field, InputField
from graphene.types.mutation import MutationOptions
from graphene.types.objecttype import yank_fields_from_attrs
from gra... |
import io
import os
import pickle
import pprint
import sys
from .Lexer import CreateLexer
from .Parser import CreateParser
from .Assembler import Assembler
from . import ParserAST
from . import Opcodes
import argparse
def parse_string(s):
if parse_string.assembler is None:
parse_string.assembler = Assemble... |
# -*- encoding: utf-8 -*-
import requests
import json
from enum import Enum
from copy import deepcopy
from typing import IO
COLORS = frozenset(('default', 'primary', 'negative', 'positive'))
DOWNLOADABLE = frozenset(('photo', 'doc', 'audio', 'graffiti'))
CONTENT_TYPES = {
'text': lambda m: 'text' in ... |
from typing import Any, Dict, Mapping, Optional, Sequence, Tuple
import dask.array as da
import dask.dataframe as dd
import numpy as np
import zarr
from ..typing import ArrayLike, DType
from ..utils import encode_array, max_str_len
INT_MISSING, INT_FILL = -1, -2
FLOAT32_MISSING, FLOAT32_FILL = np.array([0x7F800001,... |
from itertools import chain
from itertools import zip_longest
import numpy as np
from garage.algos import RLAlgorithm
from garage.core import Serializable
import garage.misc.logger as logger
from garage.misc.special import discount_cumsum
from garage.plotter import Plotter
from garage.sampler import parallel_sampler
... |
import git
from invoke import run
from invoke import task
DEFAULT_FRACTION = 0.5
FULL_TABLES = [
'dimdates',
'dimparty',
'dimyears',
'dimoffice',
'dimreporttype',
]
EXCLUDE_TABLES = [
'*_mv',
'*_tmp',
'*_old',
'sched_b2',
'sched_e2',
'pacronyms',
'ofec_*',
]
# Include r... |
"""Tests for the mnewton function provided by _mnewton.
.. codeauthor:: <NAME> <<EMAIL>>
"""
from functools import partial
import numpy as np
import pytest
import scipy.linalg
# pylint: disable=no-name-in-module
from .._mnewton import mnewton
def test_mnewton_sanity(qp_noargs):
"""Test input checking sanity of... |
"""
utils.py
miscellaneous tools helpful to work in and with MEDIS products
"""
import numpy as np
from inspect import getframeinfo, stack
import pickle
import tables as pt
import astropy.io.fits as afits
from medis.params import sp, ap, tp, iop
def dprint(*message, path_display=-3):
"""
prints location o... |
import redis
import msgpack
import json
import zlib
from .redis_stream_utilities_py3 import Redis_Stream
class Send_Object(object):
def __init__(self, redis_handle, transport_queue, queue_depth ):
self.redis_handle = redis_handle
self.transport_queue = transport_queue
self.queue_depth = queue_... |
from typing import List, Tuple, Generator, Callable, Union
from enum import Enum
DEBUG: bool = False
TEST_RUNS: Tuple[Tuple[str]] = (
(
'5',
'. . - - -',
'. . - - -',
'- - - - -',
'- - - . .',
'- - - . .',
),
(
'6',
'. . - . - .',
'- ... |
# 1) copy the source to a folder
# 2) remove the block, remove build folder and adapt CMakeLists.txt
# 3) build original system and copied system
# 4) verify test
# 5) cleanup copied folder
import os
import shutil
from pathlib import Path
from subprocess import call
import threading
import time
import sys
# make a co... |
# -*- coding: utf-8 -*-
"""
Globalcache constructs a memoization/caching decorator you can use to store
results in IPython or Spyder globals(). This lets you re-run a script and
skip the heavy computing if the result has already been processed, when you
make small changes to your script.
Requirements
-----------
Gl... |
# Copyright (c) 2016 Hewlett-Packard Enterprise Development Company, L.P.
#
# 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... |
'''
>> 'neomodel' is a python package for Object Graph Mapping.
:: Rules to add the data in Neo4j DB ::
1. Duplicate nodes are not allowed(uses the node if it exists).
2. Duplicate edges/relations b/w to same pair of nodes (source, dest) are not allowed.
3. Adds multiple edges from one node to multiple different node... |
import sys
import random
from itertools import product
import pygame
from pygame.sprite import Sprite, Group
GRID_SIZE = 30
WIN_WIDTH = 1020
WIN_HEIGHT = 620
BG = 0, 0, 0
class Walls():
"""Class to manage the walls."""
def __init__(self, screen):
"""Initialise the game walls"""
self.screen = s... |
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
import os
import sqlite3
from status_messages import MESSAGE_DICT
# from wtforms import Form, BooleanField, StringField, PasswordField, validators
app = Flask(__name__)
app.config.from_object(__name__)
app.config.updat... |
# Copyright 2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
import docx
from docx import Document
from docx.document import Document as _Document
from docx.oxml.text.paragraph import CT_P
from docx.oxml.table import CT_Tbl
from docx.table import _Cell, Table
from docx.text.paragraph import Paragraph
import datetime
import re
import pandas as pd
import numpy as np
from glob impo... |
"""
Tool for assigning nodes of a graph to points on a rectangle, so that heavy edges are short.
"""
import metis
def get_locations(G, width, height):
"""Returns a dictionary mapping every node in G to a Point in a width x height rectangle.
The mapper attempts to place nodes connected by heavy edges near ea... |
from collections.abc import Iterable
from pathlib import Path
from typing import Type
import pytest
from _pytest._code import Source
from _pytest.pytester import RunResult
from pytest_lambda import not_implemented_fixture, lambda_fixture, static_fixture
TEST_DIR: Path = Path(__file__).parent
REPO_DIR: Path = TEST_DIR... |
from .models import InteractionLine
from nanome.util import Color
from wtforms import BooleanField, Field, FloatField, Form, FormField
from wtforms.fields.core import StringField
color_map = {
"red": (255, 0, 0),
"orange": (255, 128, 0),
"yellow": (255, 255, 0),
"green": (0, 128, 0),
"blue": (0, 0... |
import random
import re
import itertools
from .const import *
def verify_adn(string):
ADN = ("ATCG")
limit = len(string)
flag = True
string = string.upper()
if string == "":
print("No es una secuencia de ADN válida")
else:
for i in range(limit):
if not string[i] in ... |
# -*- coding: utf-8 -*
import os
import json
import numpy as np
import face_recognition
from dotenv import load_dotenv
# line sdk
load_dotenv(os.path.join(os.getcwd(), '.env'))
from linebot import LineBotApi, WebhookHandler
line_bot_api = LineBotApi(os.getenv('LINE_CHANNEL_ACCESS_TOKEN'))
# 用戶傳進來的照片可能會有多張... |
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 3:
(080) is the area code for fixe... |
# merge component_to component_from delta_x delta_y
import json,sys,re
if len(sys.argv) < 4:
print ("Usage: <easy eda json to merge to> [optional merge from] DELTA_X DELTA_Y [optional NET=NEW_NAME,NET=... renames]")
print ("For renames you can also use K=REGEXP:REPLACE where if K is in net/name, re.sub(REGEXP... |
"""
mixcoatl.admin.account
----------------------
Implements access to the DCM Account API
"""
from mixcoatl.resource import Resource
from mixcoatl.decorators.lazy import lazy_property
from mixcoatl.decorators.validations import required_attrs
from mixcoatl.utils import camelize, camel_keys, uncamel_keys
import json
... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
#!/usr/bin/env python
import os
import sys
# sys.path.insert(1, os.path.join(sys.path[0], '..'))
import argparse
import yaml
import cv2
from cv2 import VideoWriter
import numpy as np
from pdb import set_trace
from multiagent.policy import Policy
from multiagent.core import idx2entity
from multiagent.environment im... |
import numpy as np
import matplotlib.pyplot as plt
# plot the number of one
def single_people_number(user, n_groups):
neutral_number = user[0]
std_neutral = ()
happy_number = user[1]
std_happy = ()
sad_number = user[2]
std_sad = ()
angry_number = user[3]
std_angry = ()
fear_num... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .settings import POOL_CREATING, POOL_ACTIVE, POOL_ERROR, POOL_STATES, \
PROTOCOL_CHOICES, LB_METHOD_CHOICES, ADMIN_STATE_UP, MONITOR_TYPE, PROVIDER_CHOICES, SESSION_PER_CHOICES
# Create your models here.
class BalancerPool(m... |
import logging.config
import logging
import os
import sys
import json
import contextlib
import time
# LOG LEVELS
# existing:
# CRITICAL = 50
# ERROR = 40
# WARNING = 30
# INFO = 20
# DEBUG = 10
DATA = 5
logging.addLevelName(DATA, "DATA")
class OnlyDataFilter(logging.Filter):
def filter(self, record):
ret... |
"""
Lambda handler for wanwu requests
"""
import json
from collections import namedtuple
Request = namedtuple(
'Request',
[
'method', # str 'GET' or 'POST'
'path', # str
'body', # None|str
'query', # dict
'headers', # dict
],
)
Response = namedtuple(
'Resp... |
'''
div128
======
Generate the constants for 128-bit division.
Note that not all approaches work for **all** values.
For unsigned values, the `precision` is the number
of bits of the type size, and we only guarantee that
m fits in `max(prec, bits − div_bits) + 1`, or
guarantee it fits ... |
import math
import operator as op
from collections import ChainMap
from types import MappingProxyType
from .symbol import Symbol
def eval(x, env):
"""
Avalia expressão no ambiente de execução dado.
"""
# Cria ambiente padrão, caso o usuário não passe o argumento opcional "env"
if env is None:
... |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import itertools
imp... |
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# Copyright 2019 The Prescience-Client Authors. All rights reserved.
import questionary
from prescience_client.client.prescience_client import PrescienceClient
from prescience_client.enum.output_format import OutputFo... |
# coloring.
from colorama import Fore, init
init()
'''
(MODULE FUNCTIONS)
------------------
vandal.toolkit is a set of data manipulation tools that can be directly accessed from the main module as vandal.any_function_listed_below()
random_value(mean, st_dev, **rounded) - gives a random value o... |
import platform
from datetime import datetime
import os
import time
import unittest
import threading
from collections import defaultdict
from logz import log
from jinja2 import Template
from htmlrunner.result import Result
from htmlrunner.loader import Loader
from htmlrunner.utils import isnotsuite, group_test_by_cl... |
# this import statement is needed if you want to use the AWS Lambda Layer called "pytorch-v1-py36"
# it unzips all of the pytorch & dependency packages when the script is loaded to avoid the 250 MB unpacked limit in AWS Lambda
try:
import unzip_requirements
except ImportError:
pass
import os
import re
import b... |
from math import isclose
from typing import Type, Union, List
from warnings import warn
from citrine._serialization import properties
from citrine._serialization.polymorphic_serializable import PolymorphicSerializable
from citrine._serialization.serializable import Serializable
__all__ = ['PredictorEvaluationMetric',... |
#!/usr/bin/python
from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import boto3_conn, get_aws_connection_info
DOCUMENTATION = '''
---
module: elasticbeanstalk_app
short_description: create, update, delete and list beanst... |
import numpy as np
import torch
from tqdm import tqdm
from .utils import save_checkpoint
from .losses import LpLoss, darcy_loss, PINO_loss
try:
import wandb
except ImportError:
wandb = None
def train_2d_operator(model,
train_loader,
optimizer, scheduler,
... |
import json
import re
import sys
import os
import requests
githup_api_url="https://api.github.com"
github_token=os.environ.get('GITHUB_TOKEN','no github token in env')
github_event_path=os.environ.get('GITHUB_EVENT_PATH')
attach=os.environ.get('INPUT_ATTACH_ARTIFACTS_TO_GITHUB_RELEASE')
distribute = os.environ.get('IN... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.