text stringlengths 3.07k 12.6k |
|---|
import pandas as pd
import numpy as np
import h5py
import os
import logging
from pathlib import Path
from numba import jit
#@jit() # Set "nopython" mode for best performance, equivalent to @njit
def get_road_network(dir, image_size, testing, data_type):
grid = np.zeros(image_size)
i=0
tot = len(os.listdir(... |
import hashlib
import os
import shutil
import sublime
import tarfile
from threading import Thread
from urllib.request import FancyURLopener
from sublime_lib import ActivityIndicator
from LSP.plugin.core.handlers import LanguageHandler
from LSP.plugin.core.settings import ClientConfig, read_client_config
from LSP.plugin... |
# @cfcayno
# date created: 11/27/2020
# FEATURES:
# - semi-automatic waveform capture feature
# - set the oscilloscope before capturing it via screenshot
# - fix trigger setup
# -
# TODO:
# - User must load the dfl preset on the oscilloscope since
# this code doesn't include remote oscilloscope modif... |
"""Handles different kind of browser streams."""
import copy
import logging
from typing import Dict
import cv2
import imutils
import tornado.ioloop
import tornado.web
from tornado.queues import Queue
from viseron.config.config_camera import MJPEG_STREAM_SCHEMA
from viseron.const import TOPIC_FRAME_PROCESSED, TOPIC_S... |
import os
import time
import json
import socket
import requests
import threading
import pandas as pd
from configparser import ConfigParser
start_global = 0.0
api_invoke_add = []
api_invoke_delete = []
rule_apply = []
total_time = []
global_time = []
type_test = []
def change_format_float_list(old_list):
new_lis... |
"""
Web Crawler intended for Microsoft's Career Page
Crawls for all entry-level software engineer positions
involved with some invitation-only hiring event
"""
from bs4 import BeautifulSoup
from urllib.request import urlopen
import requests
import json
import datetime
def atoi(s : str):
"""
Co... |
import torch
import torch.nn.functional as F
from torch import nn, Tensor
from torch.jit import trace
from my_types import LossWithStats
def diff(x: Tensor, dim: int, pad=True) -> Tensor:
r"""
x.shape: (8, 3, 224, 224)
dim: -1
mask0: [:, :, :, 1:]
mask1: [:, :, :, :-1] <- shifted by 1 pixel alo... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, print_function
import warnings
import collections
import io
from psd_tools.constants import TaggedBlock, SectionDivider
from psd_tools.decoder.actions import decode_descriptor, UnknownOSType
from psd_tools.utils import read_fmt, read_uni... |
"""
Atmosphere service machine rest api.
"""
import copy
import re
from rest_framework.response import Response
from rest_framework import status
from threepio import logger
from core.models.machine_request import MachineRequest as CoreMachineRequest
from core.models import Provider
from core.models import Identity... |
'''
Copyright 2020 <NAME>, <EMAIL>
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 ... |
# encoding: utf-8
# Sample-based Monte Carlo Denoising using a Kernel-Splatting Network
# <NAME> <NAME>
# Siggraph 2019
#
# Copyright (c) 2019 <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 Lice... |
#!/usr/bin/python3
import sys
import os
import argparse
import traceback
import random
import math
import time
import re
import logging
import colorsys
import json
import tensorflow as tf
import numpy as np
import data
from board import Board
from model import Model, Target_vars, Metrics
import common
description = "... |
# -*- coding: utf-8 -*-
"""
Test all the various getitem/setitem flavours.
"""
import numpy as np
import pytest
from rockhopper import RaggedArray, RequestMeError
from tests import sliced
NESTED = [[1, 2, 3], [4, 5]]
def test_index_index():
"""Test ragged[number, number]"""
self = RaggedArray.from_nested(N... |
#-*coding:utf-8--*-
from shutil import copyfile,move
import cv2
import numpy as np
import imutils
import os
import time
folders = {
'images_folder' : 'private/data',
'face_found_image_path' : "private/data/faces/",
'face_not_found_image_path' : "private/data/not_faces/"
}
def try_creating_folders():
f... |
#!/usr/bin/env python
import os
import sys
import argparse
import yaml
# import necessary modules
import ultraheatmap.computeMatrix as cm
sys.path.append(os.path.join(os.path.dirname(os.path.dirname((os.path.abspath(
__file__))))))
# Code directory:
configDir = os.path.dirname(os.path.realpath(__file... |
import os
import re
from logging import Formatter
from logging.handlers import TimedRotatingFileHandler
GET_FILES_TO_DELETE = "getFilesToDelete"
DO_ROLLOVER = "doRollover"
class KolibriTimedRotatingFileHandler(TimedRotatingFileHandler):
"""
A custom TimedRotatingFileHandler that overrides two methods, getFil... |
import numpy as np
import torch
import torchvision
import argparse
import json
import torch.nn.functional as F
from torch import nn
from torch import optim
from torchvision import datasets, transforms, models
from torch.autograd import Variable
from PIL import Image
from collections import OrderedDict
'''
Class Functi... |
from manul_utils import SHM_SIZE
from typing import Tuple
import logging
import numpy as np
import random
import string
from fuzzwatch_state import BITMAP_SIZE, ROW_SIZE
LOG_FILE = 'gui_log.txt'
def get_logger() -> logging.Logger:
logger = logging.getLogger('__FILE__')
logger.setLevel(logging.DEBUG)
# ... |
"""This module allows you to parse a string into its native type."""
import ast
import re
from distutils.util import strtobool
from typing import Any
def parse_value(value: Any) -> Any:
"""Parse a value into native type.
parse_value('5') -> 5 (int)
parse_value('-5') -> -5 (int)
parse_value('5.52')... |
# Copyright (c) 2020, NVIDIA CORPORATION.
#
# 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... |
from __future__ import annotations
import json
from typing import Dict, List, ClassVar
import os
import shutil
from pathlib import Path, PurePosixPath
from dataclasses import dataclass, field
import pydantic
from ferrite.utils.run import capture, run
from ferrite.components.base import Artifact, Component, Task, Con... |
# -*- coding: utf-8 -*-
import sys
import uuid
from datetime import datetime
from typing import Any, Dict, List, NoReturn, Optional
import pytz
import simplejson as json
from chaoslib.types import (Configuration, Experiment, Extension, Journal,
Secrets, Settings)
from chaostoolkit import en... |
from big_ol_pile_of_manim_imports import *
from PIL import Image
import time
class ColorMatrix:
def __init__(self, mtx, text_scale=1.0, no_text=False, norm_colors=False, tint='K'):
self.__mtx = self.make_mtx_group(mtx, text_scale, no_text, norm_colors, tint)
def mtx(self):
return self.__mtx
def make_mtx_group... |
"""
Use Jinja and data from Home Assistant to generate your README.md file
For more details about this component, please refer to
https://github.com/custom-components/readme
"""
import os
import json
from datetime import timedelta
from jinja2 import Template
import voluptuous as vol
from homeassistant import config_en... |
from pydub import AudioSegment
from array import array
from struct import pack
from tqdm import tqdm
import os
import glob
import audiosegment
import webrtcvad
import sys
import wave
import time
import numpy as np
import librosa
import soundfile as sf
RATE = 16000
CHUNK_DURATION_MS = 30 # supports 10, 20, 30 (ms)
C... |
# pylint: disable=redefined-outer-name
# pylint: disable=unused-argument
import asyncio
import copy
import random
from collections import deque
from dataclasses import dataclass
from time import time
from typing import Any, AsyncIterable, Dict, List, Optional
import pytest
from servicelib.async_utils import (
_se... |
"""
A module to quickly produce some overview plots
"""
import numpy as np
from matplotlib import pyplot as plt
from tracklib import Trajectory, TaggedSet
from .p2 import MSD
def length_distribution(dataset, ax=None, **kwargs):
"""
Plot a histogram of trajectory lengths for the given dataset
All keyword... |
# Dedicated to the public domain under CC0: https://creativecommons.org/publicdomain/zero/1.0/.
# Coven is a code coverage tool that analyzes CPython bytecode to opcode-accurate coverage reports.
# It depends on FrameType.f_trace_opcodes to generate opcode-level trace data,
# and CodeType.co_lines (PEP 626, Python 3.1... |
import tensorflow
from tensorflow.keras.layers import (Activation, Add, BatchNormalization,
Conv2D, Input, MaxPool2D, UpSampling2D)
from tensorflow.keras.models import Model, load_model, model_from_json
def ResidualModel1(image, detail, is_training):
conv_regularizer = ten... |
import pygame
from network import Network
pygame.font.init()
# Window width and height
width = 500
height = 500
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Client")
class Button:
"""
To create and interface a button in pygame
"""
def __init__(self, text, x, y, color)... |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .forms import EditProfileForm,ProfileForm,CreateCommunityForm,BusinessForm,PostForm
from .models import Profile,Location,NeighbourHood,Business,Post
from django.http import HttpResponseRedirect, Http404
from django.shortc... |
import graphene
from graphene_django import DjangoObjectType
from graphql import GraphQLError
from django.db.models import Q
from .models import CalenderSlot, SlotBooking
from django.contrib.auth import get_user_model
from datetime import datetime
class AvailableSlot(DjangoObjectType):
class Meta:
model = CalenderS... |
import datetime
import math
import os
import boto3
import cloudwatch_interactions as cw_interactions
import http_handler as hh
def handle_webhook(payload: dict) -> dict:
"""Based on what type of webhook event is posted, calls separate handling functions
:param payload: the payload of the POST request comin... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Filename: utils.py
# @Project: GuideNet
# @Author: jie
# @Time: 2021/3/15 5:25 PM
import os
import torch
import random
import numpy as np
import augs
import models
import datasets
import optimizers
import encoding
import criteria
from PIL import Image
... |
import copy
import re
from typing import Union, Callable, Optional, List
from .attribute import Attribute
from .error import E
from .symbol import Symbol
@E.register()
class PError:
PATTERN_NOT_MATCH = E("Pattern not match")
NULL_NOT_ALLOW = E("Param {0}({1}) is not allowed null")
REQUIRE_LIST = E("Param... |
import urllib.request
import zipfile
from pathlib import Path
import tensorflow as tf
import config
from data.base import Dataset
AUTOTUNE = tf.data.experimental.AUTOTUNE
def random_padding(x, y):
hpad_b = tf.random.uniform((), minval=0, maxval=8, dtype=tf.int32)
hpad_a = 7 - hpad_b
wpad_b = tf.random... |
import re
import os
import json
import datetime as dt
from collections import Counter
from gensim import corpora
import numpy as np
import subprocess
import argparse
from nltk.corpus import wordnet
from nltk.stem import WordNetLemmatizer
from nltk import pos_tag
class stopwords(object):
"""
Simple container ... |
'''
Utility functions for handling the units in `Equations`.
'''
import re
from brian2.units.fundamentalunits import (Quantity, Unit,
fail_for_dimension_mismatch)
from brian2.units.fundamentalunits import DIMENSIONLESS
from brian2.units.allunits import (metre, meter, second, ... |
import json
import numpy as np
from PIL import Image
import torch
from torch import nn, Tensor
from torchvision import models
import argparse
from workspace_utils import active_session, keep_awake
import sys
def load_categories_to_names(cat_to_name_filepath):
"""
Loads a dictionary of categories names
:p... |
import numpy
from math import floor, pow
import warnings
class _CodonSpace():
"""
This private base class weakly enforces a read-only/immutable codon mutation matrix
"""
def __init__(self, num_codons, mu):
if (mu <= 0 or mu >= 1):
raise ValueError("Mutation parameter mu must be in... |
import os
import numpy as np
import tensorflow as tf
import six
class SessionUpdate(object):
""" Update the variables in a session """
def __init__(self, sess, vars_to_update, logger):
"""
Args:
sess (tf.Session): a session object
vars_to_update: a collection of va... |
import numpy as np
from .py_cpu_nms import py_cpu_nms
img_channel_mean = [103.939, 116.779, 123.68]
def format_img_channels(img):
""" formats the image channels based on config """
# img = img[:, :, (2, 1, 0)]
img = img.astype(np.float32)
img[:, :, 0] -= img_channel_mean[0]
img[:, :, 1] -= img_ch... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from tensorflow.examples.tutorials.mnist import input_data
data = input_data.read_data_sets("data/MNIST/", one_hot=True)
print('Size of dataset:')
print('Training size:{}'.format(len(data.train.labe... |
# -*- coding: utf-8 -*-
from flask_bcrypt import Bcrypt
from flask_debugtoolbar import DebugToolbarExtension
from flask_ldap3_login import LDAP3LoginManager
from flask_login import LoginManager
from flask_mail import Mail
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf impo... |
import tensorflow
tensorflow.config.experimental_run_functions_eagerly(True)
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Conv2D, UpSampling2D
from tensorflow.keras.layers import Lambda, Activation, Flatten
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.la... |
from flask import Flask, request, g, redirect, url_for, render_template, send_from_directory
from flask_cors import CORS, cross_origin
from contextlib import closing
import sqlite3
import json
import sys
import os
import requests
import time
import datetime
args = sys.argv
# SERVER_NAME = "localhost:" + str(4000 + int... |
""" Translate input text with trained model. """
import os
import torch
from torch.utils.data import DataLoader
import argparse
from tqdm import tqdm
import random
import numpy as np
from src.translator import Translator
from src.rtransformer.vatex_dataset import VatexDataset, single_sentence_collate, prepare_batch_in... |
from __future__ import division
import logging
import platform
import re
import subprocess
import traceback
from contextlib import contextmanager
from datetime import datetime
from functools import wraps
from flask import request, url_for, abort
from jpegtran import JPEGImage
from werkzeug.contrib.cache import Simple... |
# chickenrobot - a controller for a coop door and cam controller
# author: <NAME> <<EMAIL>>
# date: Oct 2020
# license: MIT
import config
from comms import Comms
from light import Light
from door import Door
from camera import Camera
from time import sleep
from streamtologger import StreamToLogger
import sys
import lo... |
import sys
sys.path.insert(0, 'gen-efficientnet-pytorch/')
from fastai2.basics import *
from fastai2.vision.all import *
from fastai2.medical.imaging import *
from fastai2.vision.learner import _resnet_split
from fastai2.callback.tracker import *
from fastai2.callback.all import *
from scipy.optimize... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import __future__
import subprocess
import sys
import os
import platform
import time
import tempfile
dfu = "dfu-util"
dfu_help = '''
The device is probably not in DFU mode
1. Make sure the USB cable is connected to your desktop (host).
2. Press the BOOT button on... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from allennlp.data.token_indexers import TokenCharactersIndexer
from allennlp.data.token_indexers import SingleIdTokenIndexer
from allennlp.data.tokenizers import CharacterTokenizer
from allennlp.data.vocabulary import Vocabulary
import numpy as ... |
# encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""... |
# -*- coding: utf-8 -*-
from enum import Enum
from typing import List, NoReturn, Union
import uuid
from uuid import UUID
from chaosplt_relational_storage.db import Base
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, \
String, func
from sqlalchemy import Enum as EnumType
from sqlalchemy.orm import re... |
# -*- coding: utf-8 -*-
"""
Author: <NAME>
"""
"""
This module implement classes that can be used in stytra to control cameras.
"""
import numpy as np
try:
from ximea import xiapi
except ImportError:
pass
try:
from pymba import Vimba
from pymba.vimbaexception import VimbaException
except ImportErro... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
###### Data Processing ##############
def separate_practice_main_repeated_and_catch_trials(
data_df, main_ablation_rebuttal_exp
):
data_df_practice = data_df[data_df["trial_type"] == "practice"].copy()
data_df_main = data_... |
# -*- coding: utf-8 -*-
"""
pyrseas.dbobject.privileges
~~~~~~~~~~~~~~~~~~~~~~~~~~~
This defines functions for dealing with access privileges.
"""
PRIVCODES = {'a': 'insert', 'r': 'select', 'w': 'update', 'd': 'delete',
'D': 'truncate', 'x': 'references', 't': 'trigger',
'X': 'ex... |
import tornado.auth
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import simplejson as json
import yaml
from tornado.options import define, options
from django.conf import settings
from hydeengine import setup_env, Generator
from hydeengine.siteinfo import SiteInfo
from hyde... |
import torch
import torchvision
from torchvision import transforms
from tqdm import tqdm
import os
import pickle
import statistics
import glob
import numpy as np
import losses
import models.resnet_size_32 as cifar_resnet
from inception_score import inceptions_score_all_weights
def load_cifar(batch_size):
trans = ... |
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import dataclasses
import functools
import itertools
import logging
import typing
from google.cloud import datastore
from google.protobuf import any_pb2
fro... |
#
# Authors: Security Intelligence Team within the Security Coordination Center
#
# Copyright (c) 2018 Adobe Systems Incorporated. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the Li... |
# Copyright (c) 2021 Huayun Inc.
# hostha 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 PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANT... |
import torch
import pickle
from utils import *
class Model(object):
def __init__(self, args, my_id_bank):
self.args = args
self.my_id_bank = my_id_bank
self.model = self.prepare_gmf()
def prepare_gmf(self):
if self.my_id_bank is None:
print('ERR: Pleas... |
#!/usr/bin/env python
import argparse
import logging
import os
import typing as t
import onnx
import onnxruntime as ort
import torch
from onnxsim import simplify
from opti_models.models.backbones.backbone_factory import show_available_backbones
from opti_models.utils.model_utils import get_model
logging.basicConfig(... |
'''
This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de).
PM4Py 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 late... |
import logging
from functools import partial
from pyspark.sql.functions import col, udf
from pyspark.sql.types import TimestampType, DoubleType
__all__ = ["rename_columns", "do_convertion", "convert_column"]
###############################################################################
#############################... |
import argparse
from collections import namedtuple
from datetime import datetime
import re
mention_pattern = re.compile(r'<@\D?(\d+)>')
channel_mention_pattern = re.compile(r'<#(\d+)>')
def get_client(obj):
if hasattr(obj, 'bot') and obj.bot is not None:
return obj.bot
return obj
def ljoin(args, op='... |
#!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
# Allows recording of tied matches.
# Matches opponents of relative standings.
# Pairs players in unique matches.
#
# TODO: implement match byes
# TODO: implement pairing for odd number of players
# TODO: implement Opponent match w... |
import os
import luigi
import uuid
import cluster_tools.utils.volume_utils as vu
from ..graph import GraphWorkflow
from ..cluster_tasks import WorkflowBase
from ..features import EdgeFeaturesWorkflow
from .. import copy_volume as copy_tasks
from . import prediction as predict_tasks
from . import merge_predictions as ... |
import abc
from collections import defaultdict
import contextlib
import functools
from logging import getLogger
import numpy as np
import tensorflow as tf
logger = getLogger("rl")
def lazy_function(function):
attribute = '_cache_' + function.__name__
@functools.wraps(function)
def decorator(self):
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
import numpy as np
import scipy.optimize as opt
import scipy.stats as stats
from . import matrix as mat
# class Gauss(object):
# def __init__(self, A, l):
# self.A = A
# self.l = l
# def Cr(self, r)
# return self.A*np.exp(-0.5*(r/self.l)**2)
# def
def gauss(r, A, l):
"""Gaus... |
# flake8: noqa: E402
# pylint: disable=unused-import, redefined-outer-name, missing-function-docstring
from pathlib import Path
import django
import django.conf
import django.core.handlers.exception
import django.db
import django.http
from django.template.loader import render_to_string
import django.test
from django.... |
# Author: <NAME> <<EMAIL>>
from itertools import product
import os
from eelbrain.testing import TempDir
from eelbrain._experiment import TreeModel, FileTree
class Tree(TreeModel):
_templates = dict(apath="/{afield}/",
afield=('a1', 'a2', 'a3'),
field2=('', 'value'))
... |
# -*- coding: utf-8 -*-
import factory
from django.contrib.gis.geos import Point
from . import models
from geotrek.core.factories import TopologyFactory, PointTopologyFactory
from geotrek.common.utils.testdata import dummy_filefield_as_sequence
class TrekNetworkFactory(factory.Factory):
FACTORY_FOR = models.Tre... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os.path
import re
import sys
import tarfile
import numpy as np
from six.moves import urllib
import tensorflow as tf
'''
Source: https://www.tensorflow.org/tutorials/image_recognition
Or... |
import time
import random
from hks_pylib.cryptography.batchcrypt.batchnumber import SignedBatchNumber
from hks_pylib.errors.cryptography.batchcrypt.quantization import OverflowQuantizerError
from hks_pylib.errors.cryptography.batchcrypt.integer import OverflowIntegerError
SLEEP_TIME = 0
def random_array(low, high,... |
"""
Contains expressions and type bases
"""
from abc import abstractmethod
def from_value(value):
if isinstance(value, Expression):
return value
elif hasattr(value, 'symbol'):
from pysmt.theories import ints
return Symbol.from_value(ints.Int(), value)
else:
return Value.fro... |
import pandas as pd
from tkinter import Tk
from tkinter.filedialog import askopenfilename, asksaveasfilename
def main():
print("Program: Remove Duplicates")
print("Release: 0.1.0")
print("Date: 2019-10-15")
print("Author: <NAME>")
print()
print()
print("This program reads a csv file remove ... |
# -*- coding=utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
import stat
import sys
from contextlib import contextmanager
import six
from .compat import NamedTemporaryFile, Path
from .path import is_file_url, is_valid_url, path_to_url, url_to_path
__all__ = ["temp_environ", "temp_path... |
# A2B Dispatch v1
# Made by <NAME>
import json
import discord
import geopy.distance
import requests
import math
import xml.etree.ElementTree as ET
from discord.ext import commands
# Opening the config.json file that stores the Discord Token, AVWX auth header and FSEconomy Datafeed
with open('config.json') as config_... |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
import datetime
from functools import partial
from itertools import permutations
import pytest
import pytz
from cereal_lazer.cereal import INSTANCE_KEY, Cereal
from cereal_lazer.naive_serializing import LimitedMethodError
cr = Cereal()
to_test = [
# Bools, Int, Float, str
True,
False,
5,
5.5,
... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
##
## Plot hist fast
##
# y = pd.Series
## plot hist :
def plot_hist_y(y,fig_name = None):
nb_bins = min(20, len(np.unique(y.values)))
plt.hist(y, bins = nb_bins, color='steelblue', edgecolor='none')
plt.title(... |
import math
import os
from typing import List
MODULE_DIR = os.path.dirname(os.path.realpath(__file__))
PROJECT_DIR = os.path.join(MODULE_DIR, "..")
INPUT_SOURCE_DIR = os.path.join(PROJECT_DIR, "input")
HEX_TO_BITS = {
"0": "0000",
"1": "0001",
"2": "0010",
"3": "0011",
"4": "0100",
"5": "0101"... |
# Clebsch-Gordan decomposition of tensor product of two SU(3) irreps (= irreducible representations). This works!
# Still, very rudimentary. Next step: generalized to SU(N) / add interface!
import copy
class Irrep(): # A class object for SU(3) irrep
def __init__(self, n, m):
self.idx1 = n
self.i... |
from unittest import skipIf
import six
from django.db import connection
from django.db.models import F
from django.test import TestCase
from django_pg_hll import HllEmpty, HllInteger
from django_pg_hll.aggregate import Cardinality, UnionAgg, UnionAggCardinality, CardinalitySum
# !!! Don't remove this import, or bulk... |
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404, HttpResponseRedirect
import datetime as dt
from django.db.models import Sum
from django.shortcuts import render, redirect
from .models import Project, Profile, Rating
from django.contrib.auth.models import User
from dj... |
##
# this script is for approximating what happens on the server and can be used to build shared_Crypto locally
# It assumes that stuart is setup and able to be invoked from the command line
# please see https://github.com/tianocore/edk2-pytool-extensions for more info
#
# Copyright (c) Microsoft Corporation
#
# SPDX-L... |
#! /usr/bin/python3
from queue import Queue
from threading import Thread
import time, random, json, os, sys
from image_generation.make_img import Make_img
from backend.server import back_server
from api.TellonymApi import Tellonym_api
from api.QuestionmiApi import Questionmi_api
from api.Instagram_Api import Instagra... |
"""
Utility functions for dealing with zones within the IDS.
Includes functions for retrieving zone information as
well as functions for creating and deleting zones.
"""
import os
from ids.utils import run_iquest, run_iadmin, shell_command
def get_local_zone(verbose=False):
"""
This function retrieves the n... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Alex
# @Date: 2015-11-16 19:10:36
# @Last Modified by: Alex
# @Last Modified time: 2015-12-30 22:59:51
from django.db.models import Q
from django.db import models
from django.contrib.auth.models import User
from Inventationery.apps.Vendor.models import Vendor... |
# System and utils for preprocessing
import logging
import os
from pathlib import Path
# Deep learning libs
import numpy as np
import pandas as pd
import torch
import wandb
from PIL import Image
from rich.progress import (BarColumn, Progress, SpinnerColumn, TextColumn,
TimeElapsedColumn, Tim... |
# Copyright 2021 The ProLoaF Authors. All Rights Reserved.
#
# 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
audio_codec, audio_profile and audio_channels property
"""
from rebulk.remodule import re
from rebulk import Rebulk, Rule, RemoveMatch
from ..common import dash
from ..common.validators import seps_before, seps_after
audio_properties = ['audio_codec', 'audio_profile',... |
#
# (c) Copyright 2015 <NAME>. All Rights Reserved.
#
"""
User and user registration management.
"""
import string
import random
import hashlib
import uuid
from axeshome.api import mongo
from flask.ext.login import UserMixin
from flask.ext.login import current_user
from flask.ext.restful import abort
class Registrat... |
"""
This class interfaces with the Student Web Service, Term resource.
"""
import logging
from datetime import datetime
from restclients.sws import (
get_resource, get_current_sws_version, parse_sws_date, QUARTER_SEQ)
from restclients.models.sws import Term as TermModel
from restclients.exceptions import DataFailur... |
import asyncio
from nats.aio.client import INBOX_PREFIX
import nrpc.exc
from . import nrpc_pb2
class InvalidSubject(Exception):
pass
class ClientLost(RuntimeError):
pass
class CanceledByClient(RuntimeError):
pass
def parse_subject(
package_subject,
package_params_count,
service_subjec... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 20 21:33:46 2021
@author: <NAME> (<EMAIL>) at USTC
This script:
1) function read_GFs_json is preprocess of function build_GFs_pyfk;
Modify history:
1) Apr 20 21:33:46 2021 || Fu Yin at USTC || The initial release.
2) ...
... |
"""
All models need to return a CSP object, and a list of lists of Variable objects
representing the board. The returned list of lists is used to access the
solution.
For example, after these three lines of code
csp, var_array = kenken_csp_model(board)
solver = BT(csp)
solver.bt_search(prop_FC, v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.