text stringlengths 3.07k 12.6k |
|---|
from pygears import alternative, gear, module, reg
from pygears.core.intf import IntfOperPlugin
from pygears.typing import Any, Bool, Integer, Integral, Number, Tuple
from pygears.typing import div as typing_div, is_type, Uint, typeof
from pygears.typing import code as type_code
from pygears.util.hof import oper_tree
f... |
import csv
import numpy as np
from glumpy import app, gl, glm, gloo, data
from glumpy.geometry.primitives import sphere
from glumpy.transforms import Arcball, Viewport, Position
from glumpy.graphics.text import FontManager
from glumpy.graphics.collections import GlyphCollection
from glumpy.graphics.collections import P... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI 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 ... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Callable, Dict, List, Optional, Any
from io import BytesIO, StringIO
from os import linesep
from urllib.parse import urlparse
from wsgiref.headers import Headers
from ._abc import Context
from ._http impor... |
import os
import click
from kaos_cli.constants import SYM_CHECK
from kaos_cli.exceptions.handle_exceptions import handle_specific_exception, handle_exception
from kaos_cli.facades.notebook_facade import NotebookFacade
from kaos_cli.utils.custom_classes import CustomHelpOrder, NotRequiredIf
from kaos_cli.utils.decorato... |
import sys
from PIL import Image
from lib.img2txt import ansi
from lib.img2txt.graphics_util import alpha_blend
def HTMLColorToRGB(colorstring):
""" convert #RRGGBB to an (R, G, B) tuple """
colorstring = colorstring.strip()
if colorstring[0] == '#':
colorstring = colorstring[1:]
if len(colors... |
import os
import math
import tensorflow as tf
import tensorflow_datasets as tfds
import argparse
import utils
import utils.anchors
import utils.anchors_tpu
import utils.compute_overlap
from model import image_sizes
parser = argparse.ArgumentParser(
description='Generate a preprocessed dataset .')
parser.add_arg... |
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt, QThread
from PyQt5.QtGui import QBrush, QPen, QColor
from math import *
from edge_func import *
EPS = 10e-3
def round_down(x):
return floor(x)
def round_up(x):
return round(x+0.5)
class MyScene(QtWidgets.QGraphicsScene):
edge_arr = ... |
from importlib.resources import path
import os
from pathlib import Path
import cv2
from cv2 import threshold
import numpy as np
from pdf2image import convert_from_path
import glob
from tqdm import tqdm
from PIL import Image
import pyocr
import pyocr.builders
import re
from pdfminer.high_level import extract_text
import... |
#!/usr/bin/env python
import os
import re
import fnmatch
import toml
import collections
from googletrans import Translator
# set the language
# set whether to use google translate or not
lang = "es"
translator = Translator()
# this function does regex match to convert three toml fields into comment fields
def add_c... |
from pyspark.ml.feature import CountVectorizer
from utils import MovieDataApp, movie_protrait_db, movie_model_path
from pyspark.ml.feature import IDF
from functools import partial
spark = MovieDataApp().spark
def get_cv_idf_model():
# doc = get_words()
doc = spark.sql('select * from {}.cut_words'.format(movi... |
import logging
import os
import subprocess
from pyramid_beaker import session_factory_from_settings
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
from pyramid.decorator import reify
from pyramid.events import BeforeRender, ContextFound, NewRequest
from pyramid.request... |
help_message = """
XOR-decrypt is a simple tool which allows you to find a key for a xor cipher,
using which some text was encrypted. Is automatically finds the length of the
key, and the key itself.
Options:
-i --input-file File with encrypted text.
-o --output-file File for decrypted text.
-m --max... |
from collections import OrderedDict
from ctypes import (
cdll,
create_string_buffer,
c_bool,
c_char_p,
c_long
)
import json
from os import system
from os.path import (
join as p_join,
realpath,
split as p_split
)
import sys
def make() -> None:
dir_path = p_split(realpath(__file__))[... |
"""
pyrallex2.cell_parse.py
Version: 0.1
AUTHOR: <NAME>
Date: 5-Feb-2021
"""
import re
import numpy as np
class Cell:
"""
Class encapsulating Cell object
"""
def __init__(
self,
cell_file=None,
):
"""
Initialising a Cell object
"""
self.c... |
#!/usr/bin/python
# encoding: utf-8
import numpy as np
def parse_input(line, dataset, idx2word):
seqin = line.split()
seqlen = len(seqin)
seq = np.zeros(seqlen + 1, dtype='int64')
seq_words = []
for idx, sx in enumerate(seqin):
if idx2word.get(sx) is not None:
seq[idx] = idx2wo... |
#!/usr/bin/env python
'''
Class used to segment images.
Created on Apr 2, 2021
@author: maltaweel
'''
import os
import csv
import pixellib
from pixellib.instance import custom_segmentation
from pixellib.instance import instance_segmentation
#this is local pathway data set and the output segment_data class set
pn=os.... |
import csv, codecs
import cStringIO
class ClCsv():
def __init__(self, file_path):
"""
Class to wrap the Python CSV library. Allows reading and writing by column.
:param file_path: A file object or path to a file. Will create one at specified path if it does not exist.
"""
... |
#------------------------------------------------------------------------------
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions describ... |
#!/usr/bin/env python
#
# Copyright (c) 2012, <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
# Copyright 2021 MosaicML. All Rights Reserved.
import pathlib
import random
from typing import Any, Dict, List
import torch
import torch.nn.functional as F
from torch.functional import Tensor
from composer.algorithms import ChannelsLastHparams
from composer.core import DataSpec, Evaluator, Precision, State
from com... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import logging
FORMAT = "%(asctime)-15s %(message)s"
logging.basicConfig(filename='example.log',
level=logging.INFO,
format=FORMAT)
logging.debug("Test")
import re
import pymysql
import pymysql.c... |
import pygame
import constants as c
import math
class Powerup:
def __init__(self, game, surface, pos=(0, 0)):
self.radius = 24
self.age = 0
self.game = game
self.x, self.y = pos
self.y_offset = -self.y
self.surface = surface
self.shadow = pygame.Surface((sel... |
# Simple pong in Python 3 for beginers
# @<NAME>
# Prt 1: Getting started
# With turtle you can make some basic graphics
import turtle
import os
window = turtle.Screen()
window.title("Pong by @Dennis")
window.bgcolor("Black")
window.setup(width=800, height=600)
window.tracer(0) # Stop the window of updating th who... |
import json
import typing
from quicksect import Interval, IntervalTree
from random import randint
import hermes.language as lng
from hermes.core.attributes import get_decoder
from hermes.core.preprocess import preprocess
from hermes.types import LANGUAGE
from .annotation import Annotation
from .hstring import HString
f... |
"""Support for the CAME climate devices."""
from typing import Optional
from homeassistant.components.climate import DOMAIN as CLIMATE_DOMAIN
from homeassistant.components.climate import (
ENTITY_ID_FORMAT,
HVAC_MODE_OFF,
SUPPORT_FAN_MODE,
SUPPORT_TARGET_HUMIDITY,
SUPPORT_TARGET_TEMPERATURE,
C... |
# Copyright 2021 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from typing import Any
import gym
from gym.spaces import Box, Discrete
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from mytest.datautil import read_data_from_file, MTDataset_Split, MTDataset
from mytest.net import MTN
from mytest.arg import EnvArgs
class MTLEnv(gym.Env):
de... |
from __future__ import annotations
from functools import wraps
from typing import TYPE_CHECKING, Callable, Literal, Optional, Protocol, Type, TypeVar, Union, cast, overload
from django.apps import apps
from django.db import models
from django.db.models import Model
from django.db.models.base import ModelBase
from typ... |
from pyAudioAnalysis import audioTrainTest as att
import os
import argparse
import glob
import numpy as np
from sklearn.preprocessing import StandardScaler
import pickle as cPickle
def make_group_list(filenames):
'''
This function is responsible for creating group id of every sample according to the theat... |
import argparse
import pickle
import sys
from pathlib import Path
from typing import Any, List, Tuple
import pandas as pd
import numpy as np
import torch
from torchvideo.samplers import frame_idx_to_list
from tqdm import tqdm
from attribution.online_shapley_value_attributor import OnlineShapleyAttributor
from attribu... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import tf_util as U
import numpy as np
import matplotlib.pyplot as plt
mnist = input_data.read_data_sets("/tmp/tensorflow/mnist/input_data")
ROUTE_ITER = 3
def capsule(inputs, units, dim):
shape = inputs.get_shape() # [batch, unit... |
#Builtin imports
import logging
import os
import sys
import time
import threading
#External imports
import importlib
from Queue import Queue
import dataset
#Internal imports
import main
import interface
log = logging.getLogger()
dir_path = 'plugins'
plugin_subscriptions = []
command_plugins = {}
default_plugin_d... |
"""Simulate a population of Kepler planets."""
import numpy as np
import matplotlib.pyplot as pl
import tidal
from scipy.stats import beta
from tqdm import tqdm
from collections import OrderedDict
np.random.seed(1234)
def sample_e(size=1):
"""From Kipping (2013). See also Hogg, Myers and Bovy (2010)."""
a = 0... |
# -*- coding:utf-8 -*-
# ------------------------------
# Author: <NAME>
# Date: 2021/12/15 13:13
# For:
# ------------------------------
import cv2
import numpy as np
class LaneDetection:
# some of the codes is functional with other project, if there are some misunderstanding, just igno... |
import numpy as np
from scipy.stats import norm, uniform, bernoulli
from scipy.integrate import quad
x = np.array([2.5, 3, 3.5, 4, 4.5, 5.])
y = np.array([3.5, 4, 4.5, 5, 5.5, 6.])
q = np.array([2.4, 3.1, 3.6, 4, 4.5, 5.])
r = np.array([3.5, 4, 4.4, 5.01, 5.46, 6.1])
def nuts_sample_unif_normal_posterior_mean():
... |
#!/usr/bin/env python3
#
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2021, Intel Corporation
#
#
# base.py
#
"""generating a report (EXPERIMENTAL)"""
import os
import shutil
from copy import deepcopy
import markdown2
import jinja2
from .part import Part
from ..common import escape
__TESTING_DATE = 'Testing... |
from json import dumps as json_stringify
from functools import reduce
from faker import Faker
from user_registry_api.models import UserRegistry
from user_registry_api.rest import ResponseResult, ResponseMessage, ResponseErrorMessage
faker = Faker()
@given("a new user")
def step_impl(context):
userData = __get_use... |
import io
import logging
import fcntl
import I2CController
import ctypes
import array
# I2C C API constants (from linux kernel headers)
I2C_M_TEN = 0x0010 # this is a ten bit chip address
I2C_M_RD = 0x0001 # read data, from slave to master
I2C_M_STOP = 0x8000 # if I2C_FUNC_PROTOC... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 numpy as np
import pytest
from physt.histogram1d import Histogram1D
from physt import h1, h2, histogramdd
@pytest.fixture
def empty_adaptive1(create_adaptive) -> Histogram1D:
"""One-dimesion adaptive fixed-width histogram with bin_width=1."""
return create_adaptive((0,))
class TestAdaptive(object):
... |
"""Config flow for iParcelBox (Beta) integration."""
from __future__ import annotations
import logging
from typing import Any
import voluptuous as vol
from iparcelboxpy import iParcelBox
import requests
import asyncio
import async_timeout
from http import HTTPStatus
from homeassistant import config_entries
from home... |
'''
Round 1C 2020 - Code Jam 2020
Overexcited Fan (4pts, 6pts, 12pts)
Problem
Today will be the day—today will be the day that you finally get a picture with Peppurr the cat!
It has just been announced that Peppurr will be touring your city. The city has infinitely many infinitely-long streets running north-south and... |
import os
import sys
import pandas
import re
import json
from pathlib import Path
from flask import Flask, render_template, request, redirect, url_for
from werkzeug.utils import secure_filename
import urllib.parse
ALLOWED_EXTENSIONS = set(['csv'])
app = Flask(__name__)
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = Tru... |
import json
import copy
import zlib
import six
import datetime
from decimal import Decimal
from collections import namedtuple, OrderedDict
import pytest
from botoflow import WorkflowDefinition, execute
from botoflow.data_converter import JSONDataConverter
class SimpleObj(object):
def __init__(self, input):
... |
# ======================================================================
# Alchemical Reduction
# Advent of Code 2018 Day 5 -- <NAME> -- https://adventofcode.com
#
# Computer simulation by Dr. <NAME>
# ======================================================================
# ==================================... |
"""
WiP.
Soon.
"""
# region [Imports]
# * Standard Library Imports ---------------------------------------------------------------------------->
from typing import Mapping, Iterable
from pathlib import Path
from functools import cached_property
# * Qt Imports --------------------------------------------------------... |
import logging
from django.db import models
from django.utils.text import slugify
from import_export import resources
from import_export.fields import Field
from import_export.widgets import ForeignKeyWidget
import requests
log = logging.getLogger(__name__)
CATEGORIES = {
'A': 'metro',
'B': 'local',
'C'... |
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# ScanCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/nexB/scancode-toolkit for support or download.
# See https://aboutcode.org for more in... |
import math
def encode_per_group(group):
encoded = list()
tags = 0
offset = 6
for i in range(len(group)):
temp = group[i]
count = 0x0
if(temp != 0):
current_byte = 0xFF
while(temp != 0):
current_byte = current_byte & temp
... |
import numpy as np
import torch
'''
Mixup code from https://github.com/facebookresearch/mixup-cifar10
'''
def mixup_data(x, y, alpha=1.0, use_cuda=True):
'''Returns mixed inputs, pairs of targets, and lambda'''
if alpha > 0:
lam = np.random.beta(alpha, alpha)
else:
lam = 1
batch_size =... |
__doc__ = """The engine of mass-decomposer
The main function to be used is processFile()"""
import numpy as np
def processFile(filepath, molecs, weights = {}, outpath = None, decimal_separator = '.'):
"""processFile(filepath, molecs, weights = {}, outpath = None, decimal_separator = '.'):
molecs: list of tupl... |
#!/usr/bin/env python3
#
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the MIT license.
#
# Title : superpmi_asmdiffs_checked_release_setup.py
#
# Notes:
#
# Script to setup directory structure required to perform SuperPMI asmdiffs ch... |
from multiprocessing import Process, Manager
import numpy as np
from cxotime import CxoTime
import itertools
import pandas as pd
from timbre import f_to_c, Composite
def add_inputs(p, limits, date, dwell_type, roll, chips):
"""
Add input data to Timbre coposite results.
:param p: Output data
:type p... |
import argparse
import pytest
from memory_core.memory_core_magma import MemCore
from lake.utils.test_infra import lake_test_app_args
from lake.utils.parse_clkwork_csv import generate_data_lists
from gemstone.common.testers import ResetTester
from gemstone.common.testers import BasicTester
from gemstone.common.util impo... |
#
# Copyright 2017 Pixar Animation Studios
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
... |
import configparser
import json
import re
import calendar
import click
from ibata.CategoriesSummary import CategoriesSummary
from ibata.TransactionAnalyzer import TransactionAnalyzer
from ibata.downloaders.TransactionDownloaderResolver import TransactionDownloaderResolver
from ibata.utils.CategoriesManager import Cat... |
"""
Supports the Zeptrion Air Devices.
Version V.0.0.1
Package:
custom_components.zeptrionairhub.py
custom_components.light.zeptrionairhub.py
custom_components.cover.zeptrionairhub.py
configuration.yaml:
zeptrionairhub:
ToDo:
For more details about this Class, please refer to the documentation at
h... |
import os
import shutil
import traceback
import re
import sys
import time
import struct
import binascii
import subprocess
import hashlib
from pathlib import Path
def sum_check(bdata):
result = 0
for i in bdata:
result += i
return result
def encode_ch(string, d='gbk'):
if type(string) is not s... |
#!/usr/bin/env python
# coding: utf-8
import os
import pprint
import pandas as pd
from collections import OrderedDict
def get_parameters():
# Read Data
try:
#print('Read local table')
df_357 = pd.read_excel(
io=os.path.join(os.path.dirname(__file__), 'data', 'tab_conama_357.xlsx')... |
from inspect import getmodule
import re
from importlib import import_module
from django.db.models import fields
from django.db.models.base import ModelBase
from .dot import UmlClassLabel, Association, Node, Edge, UmlField
class GetIdMixin(object):
def get_id(self, model):
return '%s.%s' % (getmodule(m... |
import logging
from datetime import datetime
from uuid import uuid4
from flask import Blueprint, url_for
from sqlalchemy.orm import Query
from telegram import Bot, Message
from telegram import User as TgUser
from telegram.ext import *
from todoist.models import Item
from app.telegram import emoji
from app.telegram.mo... |
# Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# -*- coding: utf-8 -*-
import cv2
import math
import librosa
import numpy as np
from visual import vfps
from face import get_landmark, LandmarkIndex
def test_aloud(mp3_path, thr1=1e-3, thr2=0.5, ksize=3, n=100):
# test if each synthesized frame is 'aloud' using threshold $(thr1)
data, _ = librosa.... |
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from datetime import timedelta
mpl.style.use('clean.mplstyle')
eps = 1e-8
def log1(x, base=np.e):
y = np.log(x)/np.log(base)
y[np.isinf(y)] = np.nan
return y
def get_start(ser, start):
pos = ser > start
... |
charset = "abcdefghijklmnopqurstuvwxyz"
import math
import sys
import copy
def egcd(a, b):
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
gcd = b
return gcd, x, y
def modinv(a, m):
gcd, x, y = egcd(a, m)
if gcd != 1:
return None
else:
return x... |
from datetime import datetime
from functools import reduce
from typing import Dict, List
from shapely.geometry import Point, Polygon, MultiPolygon
from pylandsat import Catalog, Product, Scene
from geotiff import GeoTiff
import os
import numpy as np
from PIL import Image
import math
def make_area_box(polygons... |
import numpy as np
from sklearn.metrics import precision_score, recall_score, f1_score
from transformers import BertTokenizerFast, DistilBertTokenizerFast, RobertaTokenizerFast, XLMRobertaTokenizerFast, XLNetTokenizerFast
KEYWORDS = ["migrant", "women", "vulnerable", "refugee", "homeless",
"immigrant", "in... |
from django.apps import apps
from django.conf import settings
from django.contrib.admin.utils import unquote
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ImproperlyConfigured
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.urls i... |
#!/usr/bin/python
import binascii
import shutil
import math
import os
from pathlib import Path
size = 0
blocksize = 1024
file = "\\\\.\\D:"
def read_file(in_file, start_cluster, file_size):
#print(start_cluster)
in_file.seek(start_cluster, os.SEEK_SET)
# prints current position
print(in_file.tell())
... |
import numpy as np
import scipy
from .. import _frequency
from . import _fullcorrphase
__all__ = ['tau_unwraped_corrphase']
_MAX_TAU_SCALE_ = 3.33
#--------------------------------------------------------------
def tau_unwraped_corrphase(s1,s2=None,
f0=1,delta_f=1,Tm=None,fs=None,
... |
import numpy as np
import math
from pyquaternion import Quaternion
from Math import get_corners
def iou(gt_box, est_box):
xA = max(gt_box[0], est_box[0])
yA = max(gt_box[1], est_box[1])
xB = min(gt_box[2], est_box[2])
yB = min(gt_box[3], est_box[3])
if xB <= xA or yB <= yA:
return 0.
... |
#!/usr/bin/env python2
import rosbag
import argparse
from cv_bridge import CvBridge, CvBridgeError
import rospy
import cv2
from std_msgs.msg import String
from sensor_msgs.msg import Image, PointCloud2
import sensor_msgs.point_cloud2 as pc2
import logging
import roslib
import numpy as np
import os
from datasetbuilder ... |
# ==================================================================================================
# Copyright 2012 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
"""
This script can be used to run multiple generated or CBF problems. You have
to spacify the folder where the problem are stored. You must keep in mind that
inside the problem folder the files are considered to be CBF problems and
the directories are considered generated problems (see problem_generator.py).
Th... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ===========================================================
# File Name: read_csv.py
# Author: <NAME>, Columbia University
# Creation Date: 09-15-2018
# Last Modified: Tue Jan 15 14:43:40 2019
#
# Usage: python read_csv.py
# Description: Get final result
#
# Copyright ... |
import numpy as np
import matplotlib.pyplot as plt
from functools import reduce
######## Parameters #############
nqubit = 3 ## number of qubits
c_depth = 3 ## circuit depth
time_step = 0.77 ## Time step for random Hamiltonian
## take num_x_train randomly from [x_min, x_max]
x_min = - 1.; x_max = 1.;
num_x_train = 5... |
#!/usr/bin/env python3
# -*- Coding: UTF-8 -*- #
# -*- System: Linux -*- #
# -*- Usage: *.py -*- #
# Owner: <NAME>
# Source: code.cloud-technology.io
# License: BSD 2-Clause License
#
# BSD 2-Clause License
#
# Copyright (c) 2020, Cloud Hybrid LLC. & Affiliates
#
# All rights reserved.
#
# Redistribution and us... |
__authors__ = """<NAME>, <NAME>"""
# native libs
import os, sys
# external libs
import numpy as np
import pandas as pd
################################################################################
################################################################################
def _np_5_to_3_sc(gene, data, widt... |
#!/usr/bin/env python3
#pybisect
# 1 Known good
# 2
# 3
# 4
# 5 <--- First test, success
# 6
# 7 <-- Second test, success
# 8 <-- Third test, fail
# 9 <-- Fourth test, success.
# 10 Known Bad
# result = 10 is the first bad version
# Selector, pick middle version and round down.
import json
import math
import os
... |
# Copyright 2020 <NAME>, University of Pittsburgh
#
# 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 a... |
from enum import Enum
from typing import Literal, NewType
from typing import Mapping
from typing import Any, NamedTuple, Optional, Sequence, FrozenSet, Union
from pyrsistent import pmap, pvector
from pyrsistent.typing import PVector, PMap
from .custom_types import *
__all__ = ('parse_spec', 'serialize_spec', 'Open... |
import os
import sys
import pandas as pd
import json
import yaml
import time
from ananke.graphs import ADMG
from networkx import DiGraph
from optparse import OptionParser
sys.path.append(os.getcwd())
sys.path.append('/root')
from src.causal_model import CausalModel
from src.generate_params import GenerateParams
def... |
import argparse
import json
import os
from typing import List
import torch
from PIL import Image
from torch import nn
from torch.utils.data import DataLoader
from tqdm import tqdm
from transformers import BertConfig
from scene_layouts.datasets import (
BUCKET_SIZE,
ContinuousInferenceDataset,
DiscreteInfe... |
import argparse
import os
import subprocess
import time
import sys
import ipdb
import pickle
from utils.meter import *
def main(args):
# Parameters from the args
dir, h, w, fps, suffix = args.dir, args.height, args.width, args.fps, args.suffix
# Video dir
dir_split = dir.split('/')
video_dir = di... |
"""
This is based on Lingzhi's upgraded version
(https://www.kaggle.com/vrtjso/lgbm-one-step-ahead)
of Ceshine's LGBM starter script
(https://www.kaggle.com/ceshine/lgbm-starter),
but it is just the data preparation steps,
so we don't have to repeat them every time.
"""
from datetime import date, timedelta
impo... |
from datetime import datetime, timezone
from bearer.auth_details import AuthDetails, OAuth1SignatureMethod, TokenType
ACCESS_TOKEN = '<PASSWORD>-access-token'
REFRESH_TOKEN = '<PASSWORD>-token'
ID_TOKEN = '<PASSWORD>-id-token'
ID_TOKEN_JWT = { 'some': 'id-data' }
RESPONSE_BODY = { 'body': 'data' }
RESPONSE_HEADERS = ... |
# -*- coding: utf-8 -*-
import os
import csv
import shutil
import subprocess
from datetime import datetime
from django.db import connection
from django.conf import settings
from django.core.management.base import BaseCommand
def write(path, header, cursor):
with open(path, 'w') as fout:
writer = csv.wri... |
# Copyright 2020 QuantumBlack Visual Analytics 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
#
# THE SOFTWARE IS PROVIDED "AS IS", WIT... |
import glob
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from spektral.layers import GraphConv, GlobalMaxPool
from spektral.utils import conversion
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.layers import Input, Dense, Dropout
fr... |
# Fully Convolutional LSTM Network (the 3rd in DeepMind's paper)
# Architecture is the same as the FullyConv but we add a ConvLSTM after the state concatenation.
import logging
import sys
import os
import shutil
import sys
from datetime import datetime
from functools import partial
import tensorflow as tf
from absl imp... |
# Pandoc plugin for typesetting bridge-related documents
import pandocfilters as pf
import re
def is_bidding(blocks):
for block in blocks:
data = pf.stringify(block[0])
if re.match('.*![CDHSN].*--.*', data):
return True
return False
prev_key = '' # worst hack ever
def bidding... |
import re
import requests
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password as auth_validate_password
from django.core.validators import validate_email, ValidationError
from rest_framework import serializers
... |
import csv
import itertools
import re
import hashlib
from androidcrypto import constants
import base64
import random
import logging
import json
import numpy as np
import pandas as pd
import copy
from collections.abc import Iterable
def decolorize_source_code(src_code):
reaesc = re.compile(r'\x1b[^m]*m')
retur... |
# import libraries
import gensim
import random
import pandas as pd
import numpy as np
import fire
import os
from itertools import combinations
# import implemented python files
import models_gensim, plot
class Preprocessor():
def build_taggedDocument_df(self, df, random_sampling=False, num_sampling=10, ... |
from .common import ScanSerializerBase
class _HeaderInformation(dict):
"""A simple key-value store that also carries a reference to a :class:`~.Scan` object.
Intended to be used internally by the :class:`TextScanSerializerBase` class hierarchy,
but should not be needed elsewhere either.
"""
def ... |
'''
Name: cmd_client.py
Author: <NAME>
Desc: TCP client threads/processes for sending
commands to wheelson and receiving position updates
'''
import wheelsonTCP as wTCP
import time
import sys
import argparse
import time
import os
import multiprocessing as mp
import atexit
PDU_START_BYTE0 = 0... |
#!/usr/bin/python
# Copyright: (c) 2020, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: virtual_machine_inter... |
# -*- coding: utf-8 -*-
import sys
import time
import json
import random
import numpy as np
import sklearn
from itertools import product
from sklearn.metrics import accuracy_score, confusion_matrix, roc_auc_score, average_precision_score, cohen_kappa_score, matthews_corrcoef
from sklearn.neighbors import KNe... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
import os
import glob
import imageio
import random
import scipy.misc as misc
import numpy as np
from cStringIO import StringIO
#make sure that the sequence is multiple of batches, necessary?
def padding_seq(seq, batc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.