text stringlengths 3.07k 12.6k |
|---|
import traceback
from alog import debug, info, error
from mykonos.core.core import Core
from mykonos.keywords.management_device import ManagementDevice
from mykonos.keywords.decorators import Parallel
class LocatorElement(Core):
def __init__(self):
self.device_mobile = self.device()
self.manageme... |
import os
import numpy as np
def read_data(input_path, english_only, english_indices=None):
"""Returns the list of signatures, labels, and ids. These can have English-only signatures if specified."""
if english_indices is None:
english_indices = []
sig_list = []
lab_list = [] # Genuine = 0, Forged = 1... |
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, BooleanField, SelectField,\
SubmitField,IntegerField,DateField
from wtforms.validators import DataRequired, Length, Email, Regexp
from wtforms import ValidationError
from flask_pagedown.fields import PageDownField
from ..models im... |
#
# Copyright (c) 2012 The Chromium OS Authors.
#
# SPDX-License-Identifier: GPL-2.0+
#
import os
import shutil
import sys
import tempfile
import time
import unittest
# Bring in the patman libraries
our_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(our_path, '../patman'))
import boa... |
#!/usr/bin/env python
from __future__ import division, unicode_literals
import argparse
import os
import time
import cv2
from net.wyun.blankanswer import image_utils
from net.wyun.blankanswer.loader import SimplePreprocessor
default_buckets = '[[240,100], [320,80], [400,80],[400,100], [480,80], [480,100], [560,80],... |
import re
from typing import Generator
from django.db import models, transaction, IntegrityError, InternalError
from django.db.models import Q
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from django.conf impor... |
import logging
import asyncio
import json
from datetime import datetime, timedelta
from dateutil import tz, relativedelta
from pyhydroquebec.error import PyHydroQuebecHTTPError
from pyhydroquebec.client import HydroQuebecClient
from pyhydroquebec.consts import (
CURRENT_MAP,
DAILY_MAP,
)
import voluptuous a... |
"""Random Forest classification and computation of assessment metrics."""
import numpy as np
from imblearn.over_sampling import RandomOverSampler
from imblearn.under_sampling import RandomUnderSampler
from sklearn import metrics
from sklearn.ensemble import RandomForestClassifier
from raster import is_raster
def tr... |
#!/usr/bin/env python3
import os
import sys
import argparse
import logging
from typing import List, Optional, Union, Dict, Tuple
from datetime import datetime, timedelta
from sqlalchemy import create_engine
import rx
import rx.operators as ops
from rx.subject import AsyncSubject, Subject, BehaviorSubject, ReplaySubje... |
import numpy as np
import serial
import struct
import threading
import time
from array import array
from datetime import datetime
class ImuData:
def __init__(self, t=0.0, freq=0, ypr=np.zeros(3), a=np.zeros(3), \
W=np.zeros(3)):
self.t = t
self.freq = freq
self.ypr = ypr
... |
"""
module containing functions to use ffprobe to parse video frame info
"""
from __future__ import print_function
import subprocess
import cStringIO
class base_frame(object):
"""
Base Frame from FFProbe
[FRAME]
media_type=video
stream_index=0
key_frame=0
pkt_pts=11745667
pkt_pts_time=... |
"""
Custom added maze tasks with dense rewards and progressively farther goals
For creating expert demonstrations
"""
from typing import Dict, List, Type, Tuple
import numpy as np
from mujoco_maze.custom_maze_task import (
GoalRewardLargeUMaze,
GoalRewardRoom3x5,
GoalRewardRoom3x10,
)
from mujoco_maze.t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-06-30 10:19:04
# @Author : gwentmaster(<EMAIL>)
# I regret in my life
"""summary
"""
import json
import os
import re
from collections import defaultdict
from typing import Any, Dict, List, Generator, Union
import click
TEMPLATE = "INSERT INTO {tabl... |
#!/usr/bin/env python
'''
kmer-collapse.py
Starting with a set of kmers using a standard DNA alphabet (ACTG), collapse
it to an encoded, optimized set using IUPAC-derived, degenerate base alphabet.
'''
import sys
import json
import itertools as it
import marisa_trie as mt
"""
Generate all subsets of specified set. ... |
import os
import cv2
import numpy as np
import tensorflow as tf
import tensorflow.compat.v1 as tf
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from flask_ngrok import run_with_ngrok
from flask import Flask,request,send_from_directory,render_template
# GLOBAL ACCESS
os.environ['TF_CPP_MIN_L... |
import json
from flask import Flask, request
import requests
# Token that has to be generated from webhook page portal
ACCESS_TOKEN = "random <PASSWORD>"
# Token that has to be added for verification with developer portal
VERIFICATION_TOKEN = "abc"
# Identifier payloads for initial button
C19INDIA = "C19INDIA"
app = Fl... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
#!/usr/bin/env python3
from pathlib import Path
import sys
import subprocess
import re
import argparse
import os
#Path of file
dir_path = os.path.dirname(os.path.realpath(__file__))
#TODO: insert correct org name
org='YOUR_ORG_NAME_HERE'
pmd_pos = dir_path + '/pmd-bin-6.14.0/bin'
pos_yaclu = dir_path+ '/yaclu'
root... |
from cv2 import cv2
from collections import Counter
from PIL import Image, ImageDraw, ImageFont
from scipy.fftpack import dct
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import gmpy2
import numpy as np
import time
import os
"""
Transparency
If putting the pixel with RGBA = (Ra, Ga, Ba, Aa) over... |
# Cryptomath Module
import random
def gcd(a, b):
# Returns the GCD of positive integers a and b using the Euclidean Algorithm.
if a>b:
x, y = a, b
else:
y, x = a, b
while y!= 0:
temp = x % y
x = y
y = temp
return x
def extendedGCD(a,b): #used to find mod ... |
#
# Copyright 2021, NTT Communications Corp.
#
# 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 applic... |
from typing import List
from .controls import ACTION_TYPE, ExecutionControl, Logger
from .processor import Processor
import curses
import datetime
FRAME_WIDTH = 100
APP_NAME = 'RhProcessor'
proc_map = None
class Slot():
def __init__(self, node_dict: dict, logger: Logger, execution_control: ExecutionControl, ids: ... |
class EntityPair(object):
"""实体对
Atrributes:
entity1: WordUnit,实体1的词单元
entity2: WordUnit,实体2的词单元
"""
def __init__(self, entity1, entity2):
self.entity1 = entity1
self.entity2 = entity2
def get_entity1(self):
return self.entity1
def set_entity1(self, en... |
import os
import numpy as np
import matplotlib.pyplot as plt
from .kshell_utilities import atomic_numbers, loadtxt
from .general_utilities import create_spin_parity_list, gamma_strength_function_average
class LEE:
def __init__(self, directory):
self.bin_width = 0.2
self.E_max = 30
self.Ex_m... |
from typing import Union, Optional, Sequence, Any, Mapping, List, Tuple, Callable
from collections.abc import Iterable
import operator
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.axes import Axes
def pie_marker(
ratios: Sequence[float],
res: int = 50,
... |
"""
My commenly used Modules:
(1) get_directory_name(caption) -- browses for directory name
(2) get_file_name(caption) -- browses for a specific file
(3) save_file_name(caption) -- saves named file to selected directory
(4) get_exif(fn) -- gets inag exif data
(5) get_gps_deg(exf) -- extracts GPS data from exi... |
from __future__ import unicode_literals
import frappe
from frappe import msgprint, _
import datetime
from frappe.utils import flt
from erpnext.accounts.utils import get_balance_on
from frappe.utils import (flt, getdate, get_url, now,
nowtime, get_time, today, get_datetime, add_days)
def execute(filters=None):
col... |
#!/usr/bin/env python3
import os
import sys
import json
import configparser
import logging
import logging.config
import traceback
# install required package if in docker
if os.geteuid() == 0:
import pkgutil
import subprocess
required_pkgs = ["pytz"]
for pkg in required_pkgs:
if not pkgutil.fin... |
"""Test for XBee Pro S3B"""
from xbradio import XBRadio
from pyb import SPI, Pin, delay
def test_PacketBuffer():
import test_PacketBuffer
test_PacketBuffer.main()
def test_as(xb):
#xb.verbose = True
#g = xb.get_and_process_available_packets
#BUG, this doesn't work: print("values: %r" % xb.values)... |
# Created By: <NAME>
# Created On: 2010-02-06
# Copyright 2011 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses/bsd_... |
"""
Friends-of-Friends (FOF) for N-body simulations
<NAME> - Oct 2016
"""
from __future__ import absolute_import, print_function
from lizard.periodic import pad_unitcube
from scipy.spatial import Delaunay
from scipy.sparse import csr_matrix, csgraph
from numpy import square, flatnonzero, ones, zeros_like, cumsum, con... |
# -*- coding: utf-8 -*-
#@+leo-ver=5-thin
#@+node:ekr.20201129023817.1: * @file leoTest2.py
#@@first
"""
Support for Leo's new unit tests, contained in leo/unittests/test_*.py.
Run these tests using unittest or pytest from the command line.
See g.run_unit_tests and g.run_coverage_tests.
This file also contains classe... |
import sys, math, numpy, struct
import matplotlib.pyplot as plt
class readBinaryModels(object):
'''Class for reading binary models'''
def __init__(self, fil):
'''Initialize'''
super(readBinaryModels, self).__init__()
self.fread = open(fil, "rb")
self.head = None
self.m... |
# ------------------------------------------------------------
# Copyright (c) 2017-present, SeetaTech, Co.,Ltd.
#
# Licensed under the BSD 2-Clause License.
# You should have received a copy of the BSD 2-Clause License
# along with the software. If not, See,
#
# <https://opensource.org/licenses/BSD-2-Clause>
#
# ... |
"""Tabular iterators."""
from typing import Optional
from typing import Tuple
from typing import Union
from typing import cast
import cupy as cp
from lightautoml.dataset.gpu.gpu_dataset import CupyDataset
from lightautoml.dataset.gpu.gpu_dataset import CudfDataset
from lightautoml.dataset.gpu.gpu_dataset import Dask... |
"""
TODO: the code is take from Apache-2 Licensed NLTK: make sure we do this properly!
Copied over from nltk.tranlate.bleu_score. This code has two major changes:
- allows to turn off length/brevity penalty --- it has no sense for self-bleu,
- allows to use arithmetic instead of geometric mean
"""
impor... |
#!/usr/bin/env python3
# Copyright (c) 2021 <NAME>
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
"""This module does comparison of two images"""
import argparse
import os
from io import BytesIO
from typing import Union, List, Tuple
from pathlib import Path
import numpy a... |
#!/usr/bin/env python
#
# check-tms
#
# DESCRIPTION:
# Plugin to test the old, but still used, TMS map tile API for basic
# functionality. Loads several tiles around the given centerpoint
# and verifies that they loaded OK.
#
# OUTPUT:
# plain text describing the abnormal condition encountered
#
# PLATFORMS:
... |
# coding=utf-8
'''
accuracy:98%
'''
import tensorflow as tf
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W):
return tf.nn.con... |
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import check_password
from django.shortcuts import get_object_or_404
from rest_framework import viewsets, mixins, status
from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser, AllowAny
from rest_fra... |
#!/usr/bin/python3
import argparse
import logging
import os
import re
import shlex
import sys
from subprocess import Popen, PIPE
# Main function
def build_index(parser_result):
aligner = parser_result.aligner.lower()
global quiet
quiet = parser_result.quiet
check_tools(aligner)
if not quiet:
... |
import numpy as np
import random
import cv2
import os
import json
from csv_utils import load_csv
import rect
import mask
def plot_one_box(x, img, color=None, label=None, line_thickness=None):
"""
description: Plots one bounding box on image img,
this function comes from YoLov5 project.
ar... |
""" This is a modified version of simple.py script bundled with Read Until API"""
import argparse
import logging
import sys
import traceback
import time
import numpy
import read_until
import cffi
import os
import h5py
import glob
import concurrent.futures
import dyss
def _get_parser():
parser = argparse.ArgumentPa... |
"""scrapli.transport.plugins.asyncssh.transport"""
import asyncio
from dataclasses import dataclass
from typing import Optional
from asyncssh import connect
from asyncssh.connection import SSHClientConnection
from asyncssh.misc import ConnectionLost, PermissionDenied
from asyncssh.stream import SSHReader, SSHWriter
f... |
from __future__ import annotations
import torch
import torch.nn as nn
from typing import Optional
import warnings
warnings.simplefilter("ignore")
class ConvNormRelu(nn.Module):
def __init__(self, in_channels: int, out_channels: int, upsample: Optional[bool] = False) -> None:
super(ConvNormRe... |
import json
def confirm():
print("")
# custom function
def rowPrint(xrow=-1,yrow=-1,xpos=-1,ypos=-1,width=9,height=9):
rows = [["O"]*width for _ in range(height)]
for list in rows:
if yrow != -1:
list[yrow]="X"
if xrow != -1:
rows[xrow] = ["X"]*width
if ypos != -1:
... |
import re
from dateutil.parser import parse
from vessel import Vessel,Forum,InvalidVesselException,engine,session
from tqdm import tqdm
import urllib.request
import codecs
program_to_jinja={
"children count": "vessel.children|length",
"children random":"(vessel.children|random).name",
"children list":"('\n ... |
# vim: set ts=8 sts=4 sw=4 tw=99 et:
#
# This file is part of AMBuild.
#
# AMBuild is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ... |
import logging
import time
from torch.utils.data import DataLoader
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torch
import torch.nn.functional as functional
import numpy as np
from DTI import models, dataset, cli, utils, analyse
import os
device = torch.device('cuda:0... |
# coding=utf-8
def process_qq_history(path, skip_system=True, encoding="utf-8", strip=None, output_path=None):
"""
Process QQ chat history export text file to sentences.
:param path: Path to QQ history txt file.
:param skip_system: Skip system message if set.
:param encoding: Encoding of the tx... |
#
# オセロ(リバーシ) 6x6
#
N = 6 # 大きさ
EMPTY = 0 # 空
BLACK = 1 # 黒
WHITE = 2 # 白
STONE = ['□', '●', '○'] #石の文字
#
# board = [0] * (N*N)
#
def xy(p): # 1次元から2次元へ
return p % N, p // N #35の座標の出力(5,5)
def p(x, y): # 2次元から1次元へ
return x + y * N #35を出力
# リバーシの初期画面を生成する
def init_board():
board = [EMPTY]... |
import os
import pandas as pd
import numpy as np
from collections import Counter, defaultdict
def train_from_file(dir_path, leap_limit=15):
file_list = os.listdir(dir_path)
pig_format = [
"id",
"onset",
"offset",
"pitch",
"onsetvel",
"offsetvel",
"hand"... |
import cocos
import pyglet
from world import Terrain
TERRAIN_TEXTURES = {Terrain.GRASS: 'grass.png', Terrain.DIRT: 'dirt.png',
Terrain.WATER: 'water.png', Terrain.MOUNTAIN: 'mountain.png'}
CELL_SIZE = 32
DEFAULT_CHARACTER = pyglet.resource.image('res/img/dummy.png')
class WorldMap(cocos.tiles.Re... |
# -*- coding: utf-8 -*-
'''
Copyright (c) 2021 <NAME>.
This file is part of HermesBot.
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... |
# pylint: disable=fixme, line-too-long, import-error, no-name-in-module
#
# Copyright (c) 2020 Synopsys, Inc.
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownersh... |
from __future__ import absolute_import, division, print_function, unicode_literals
import json
from postgres.orm import Model
from psycopg2 import IntegrityError
from urlparse import urlsplit, urlunsplit
import xml.etree.ElementTree as ET
import xmltodict
from aspen import Response
from gratipay.exceptions import Pro... |
from flask import Flask, request, Response
import json
import pymongo
from flask_cors import CORS
from bson.json_util import dumps, loads
import os
from azure.storage.blob import BlockBlobService, PublicAccess
from celery import Celery
import subprocess
import uuid
app = Flask(__name__)
CORS(app)
db_cli... |
import math
from typing import Union, Dict
import numpy as np
import torch
import torchvision.transforms as transforms
from torchvision.transforms import InterpolationMode
import utility as utils
import utility.color as color
class Resolution:
def __init__(self, width, height):
self.width = width
... |
import sys
import random
import pygame
# Define Window Size
SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
# Define Frames Per Second
FRAMES_PER_SEC = 25
# Function: Draw a text to the screen
def blit_text(screen_object, font, msg_text, color_tuple, center_tuple, antialiased=True):
# Define a message in Main Menu with Co... |
# import the required packages
import warnings
import sys
from scipy.optimize import OptimizeWarning
from PyQt5 import QtCore, QtWidgets
from ._tools import Fitter, value_to_string
from ._widgets import PlotWidget, ModelWidget, ReportWidget
from ._settings import settings
from ._version import __version__ as CFGversio... |
import os
import os.path as op
import shutil
import sys
from datetime import datetime
from tempfile import TemporaryDirectory
import boto3
import sh
from termcolor import cprint
from .cloudformation import get_cf_resources
from .config import Config
def _docker(*args):
cprint("$", "red", end=" ")
cprint("do... |
#!/usr/bin/env python
import numpy as np
import scipy.sparse
from sklearn import svm
from sklearn.metrics import f1_score, recall_score, precision_score, accuracy_score, make_scorer
from sklearn.model_selection import cross_val_score
def zero_pivot_columns(matrix, pivots):
matrix_lil = scipy.sparse.lil_matrix(matr... |
"""Load the Tatoeba dataset."""
import sys
import os
import csv
import subprocess
import time
from multiprocessing import Pool, Lock, cpu_count
from tqdm import tqdm
from scipy.io import wavfile
from python.params import MIN_EXAMPLE_LENGTH, MAX_EXAMPLE_LENGTH
from python.dataset.config import CACHE_DIR, CORPUS_DIR
f... |
import re
from functools import lru_cache
from pathlib import Path
import typing as T
from yaml import dump as yaml_dump
from faker import Faker
from faker.config import AVAILABLE_LOCALES
from tools.faker_docs_utils.format_samples import (
yaml_samples_for_docstring,
snowfakery_output_for,
)
from .summarize_fa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 14 09:15:33 2020
@author: dhulls
"""
# Imports
import numpy as np
np.random.seed(100)
from tensorflow import random
random.set_seed(100)
import os
import pathlib
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
os.chdir('/... |
from abc import ABC, abstractmethod
from typing import Callable, cast, Set, List, Dict, Optional
import numpy as np
from autofit import ModelInstance, Analysis, DirectoryPaths
from autofit.graphical.expectation_propagation import AbstractFactorOptimiser
from autofit.graphical.expectation_propagation import EPMeanFiel... |
#!/usr/bin/env python3
import random
import time
import sys
import pygame
from pygame.locals import *
import pygame.surfarray as surfarray # for performance
import numpy as np
import colors # color definition
SCREEN_SIZE = (1600, 900) # change it to your screen size
#color definition... |
#!/usr/bin/python
import json
import sys
import csv
import math
def VarInBranchLimited(tree, uvars, writer, limit):
"""Return all variables in a branch with limit (list)"""
# Check if the numSplit drop below limit or if it raches a lastSplit node
if ((len(uvars)+tree['Weigth']) <= limit) or (tree['LastSpl... |
# Copyright (c) 2018 IoTeX
# This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no
# warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent
# permitted by law, all liability for your use of the code is... |
def convert(my_str):
my_list = list(my_str.split(' '))
return my_list
values = {}
times = {}
weights = {}
ids = []
f = open('crime_scene.txt')
my_lines = f.readlines()
stripped_lines = [line.strip() for line in my_lines]
f.close()
N = int(stripped_lines[1])
w = int(convert(stripped_lines[0])[0])... |
from __future__ import print_function
from scipy import sparse
import pandas as pd
import numpy as np
import argparse, os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
from torch.uti... |
import os
import re
import requests
from invoke import task
def _get_aws_token(c):
token = os.getenv("AWS_TOKEN")
if not token:
token = c.run("aws ecr get-authorization-token --output text "
"--query 'authorizationData[].authorizationToken'", hide=True).stdout.strip()
return ... |
import pigpio
import signal
import requests
import logging
import json
import os
import sys
import threading
from time import sleep
from uuid import uuid1
# Global variables
BUTTON_GPIO = 23
LED_GPIO = 21
is_blinking = False
pi = pigpio.pi()
dweetFile = 'dweet_name.txt'
dweetURL = 'https://dweet.io'
# States
stateON ... |
# Parse Newick-formatted file into tree of { 'kids': [], 'label': '', 'length': '' }
import logging
from utils import die
def skipSpaces(treeString, offset):
while (offset != len(treeString) and treeString[offset].isspace()):
offset += 1
return offset
def parseQuoted(treeString, offset):
"""Read ... |
import argparse
from multiprocessing import Queue, Process
from logging import getLogger
def main():
parser = argparse.ArgumentParser(
description="QkouBot is an application for KIT students. This automatically collect and "
"redistribute information and cancellation of lectures. QkouB... |
import numpy as np
import skimage as ski
import os
from matplotlib import pyplot as plt
from skimage.feature import blob_dog, blob_log, blob_doh
from skimage.color import rgb2gray
from math import sqrt
log_defaults = {
'min_s': 1,
'max_s': 30,
'num_s': 10,
'thresh':0.1,
'overlap': 0.5,
'log_sca... |
from ..cards import Card, Deck
from scipy.stats import bernoulli
from random import randint, shuffle
class Pile(object) :
def __init__(self):
self.cards = []
self.owner = None
def __getitem__(self, index):
if index < len(self.cards) :
return self.cards[-1 - index]
... |
#!/usr/local/bin/python
from __future__ import print_function
import sys
import time
import serial
import pylt
pusb = dict()
ver = "Prologix GPIB-USB Controller version 6.95"
hwset = (
"addr",
"auto",
"eoi",
"eos",
"eot_enable",
"eot_char",
"read_tmo_ms"
)
def def_set(setting):
setting["auto"] = 0... |
import time
import sys
import zmq
import pickle
from plico.utils.decorator import cacheResult, override, returnsNone
from plico.utils.logger import Logger
from plico.utils.barrier import Barrier, FunctionPredicate, BarrierTimeout
from plico.utils.constants import Constants
from plico.rpc.abstract_remote_procedure_call ... |
#!/usr/bin/env python3
import numpy as np
import os
import sys
import argparse
import glob
import time
import onnx
import onnxruntime
import cv2
import caffe
from cvi_toolkit.model import OnnxModel
from cvi_toolkit.utils.yolov3_util import preprocess, postprocess_v2, postprocess_v3, postprocess_v4_tiny, draw
def chec... |
# Copyright (c) 2017-2021, <NAME>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WA... |
# Copyright (c) 2016-2020 <NAME>
# Licensed under the zlib/libpng License
# https://opensource.org/licenses/Zlib
import math
__all__ = ('slownie', 'slownie_zl', 'slownie_zl100gr')
ZERO_LITERALLY = "zero"
MINUS_LITERALLY = "minus "
HUNDREDS_LITERALLY = [
"",
"sto ",
"dwie\u015Bcie ",
"trzysta ",
... |
import numpy as np
import torch
class ModuleMixin(object):
"""
Adds convenince functions to a torch module
"""
def number_of_parameters(self, trainable=True):
return number_of_parameters(self, trainable)
def number_of_parameters(model, trainable=True):
"""
Returns number of trainable... |
"""
Allows manipulation of custom jobs.
Jobs include creating predictions or preferences for a custom sequence.
"""
import uuid
import datetime
from pred.queries.dbutil import update_database, read_database
from pred.webserver.customresult import CustomResultData
class JobStatus(object):
"""
States a job can... |
import random
import gym
import sys
import numpy as np
from collections import deque,namedtuple
import os
import time
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torch.optim import Adam
plt.style.use('seaborn')
class DQN(nn.Module):
def __init__(self,hidden_sz,state_sz, action_sz):
... |
import re
import torch
import torch_geometric
from torch_geometric.data import Data, Batch
class MultiScaleData(Data):
r"""A plain old python object modeling a singlemulti scale graph with various
(optional) attributes:
Args:
x (Tensor, optional): Node feature matrix with shape :obj:`[num_nodes,
... |
import logging
from flask import Blueprint, abort
from flask import current_app as app
from flask import redirect, render_template, request, url_for
from itsdangerous import BadData, BadSignature, SignatureExpired, URLSafeSerializer
from structlog import wrap_logger
from response_operations_ui.common import token_dec... |
# -*- coding: utf-8 -*-
import re
import logging
import string
import textwrap
from collections import OrderedDict
def representsInt(s):
try:
int(s)
return True
except ValueError:
return False
def representsFloat(s):
try:
float(s)
return True
except ValueError:
... |
from collections import OrderedDict
import numpy as np
import math
import torch
import torch.optim as optim
from torch import nn as nn
import rlkit.torch.pytorch_util as ptu
from rlkit.core.eval_util import create_stats_ordered_dict
from rlkit.torch.torch_rl_algorithm import TorchTrainer
def kl_divergence(mu, std):... |
#!/usr/bin/env python3
# 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.
import os
import shutil
import subprocess
from mephisto.operations.operator import Operator
from mephisto.operations.uti... |
from django.db import models
import api.json_worker as json_worker
"""
ABSTRACT MODEL
Class BibliographyTemplateModel
Handles all fields that are in our bibliography databases.
"""
class BibliographyTemplateModel(models.Model):
# FIELDS GO HERE
id = models.IntegerField(primary_key=True) #1 - ID rekordu (inte... |
# Copyright 2020-2021 eBay Inc.
# 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... |
import json
import os
import sys
import re
import numpy as np
from Preprocess import processed_answer
from subquestions import filter_Questions
def most_frequent(List):
counter = 4
num = None
for i in List:
curr_frequency = List.count(i)
if(curr_frequency> counter):
... |
#!/usr/bin/env python3
# Test libLF.Regex's for SL behavior using the vuln-regex-detector suite.
# This analysis can run single-node many-core.
# Import libLF
import os
import sys
import re
sys.path.append(os.path.join(os.environ['ECOSYSTEM_REGEXP_PROJECT_ROOT'], 'lib'))
import libLF
import json
import tempfile
impor... |
# Copyright (c) 2021 Huawei Technologies Co.,Ltd. All rights reserved.
#
# StratoVirt is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan
# PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
# http:#license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PRO... |
from PyQt5 import uic, QtWidgets
import mysql.connector
from reportlab.pdfgen import canvas
global_id = 0
#Cria o banco de dados para ser usado na aplicação.
banco_de_dados = mysql.connector.connect(
host="localhost",
user="root",
password="",
database='cadastro_produtos'
)
def funcao_principal():
... |
# Copyright 2019 The Regents of the University of California.
#
# 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 applic... |
import numpy as np
from scipy.optimize import fsolve
from scipy.linalg import expm
import matplotlib.pyplot as plt
# Some utilities
# map a vector to a skew symmetric matrix
def skew(x):
return np.array([[0, -x[2], x[1]], [x[2], 0, -x[0]], [-x[1], x[0], 0]])
# map a twist to its adjoint form
def adjoint(x):
r... |
from mycroft.messagebus.message import Message, dig_for_message
from mycroft.skills.core import FallbackSkill, intent_file_handler, intent_handler
from adapt.intent import IntentBuilder
from jarbas_hive_mind_red import get_listener
from jarbas_hive_mind.settings import CERTS_PATH
from jarbas_hive_mind.database import C... |
"""
Functions to load and process Ausgrid dataset.
The dataset contains 300 users with their location, PV production and electrical consumption.
The timeline for this dataset is 3 years separated in 3 files.
"""
import os
import pickle
import numpy as np
import pandas as pd
from pandas.tseries.offsets import Day
from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.