text stringlengths 3.07k 22.1k |
|---|
'''
Seed a new project with a directory tree and first files
'''
# Import python libs
import os
BUILD = """#!/usr/bin/python3
import sys
import os
import shutil
import subprocess
import tempfile
import venv
import argparse
OMIT = ('__pycache__', 'PyInstaller', 'pip', 'setuptools', 'pkg_resources', '__pycache__', 'dis... |
import torch
import numpy as np
import time
import os
# import argparse
import cv2
from LapNet import LAPNet
from loss import DiscriminativeLoss
from create_dataset import createDataset
from logger import Logger
from torch.nn import DataParallel
from collections import OrderedDict
from torch.nn.paramete... |
#*
# @file Different utility functions
# Copyright (c) <NAME>, <NAME>, <NAME>
# All rights reserved.
# This file is part of AdaHessian library.
#
# AdaHessian 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, ei... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from itertools import accumulate
import torch
from torch import nn
from torch.nn import functional as F
from maskrcnn_benchmark.modeling.matcher import Matcher
from maskrcnn_benchmark.modeling.utils import cat
from maskrcnn_benchmark.structures.b... |
import json
import requests
import unittest
class RiskApiCache:
def __init__(self):
self.players = None
self.mercs = None
self.player_info = {}
self.turns = None
class RiskApi:
def __init__(self):
self.api_base_url = "https://collegefootballrisk.com/api"
self.... |
import struct
import pytest
from oscpython import Packet, Message, Bundle, TimeTag
from oscpython.messages import (
ParseError, PacketStartError, MessageStartError, BundleStartError,
)
from oscpython import arguments
def check_message_args(msg: Message, all_arg_bytes: bytes):
for arg in msg:
try:
... |
"""
Models for Learning Sequences and Course Outline generation.
Conventions:
1. Only things in the `api` package should ever import this file. Do NOT import
from views.py or anywhere else. Even if that means we have to give up some DRF
niceties.
2. The vast majority of what our public API promises should be efficie... |
# %% imports
import argparse
import importlib
from copy import deepcopy
from logging import warning
import mne
import h5io
import numpy as np
import pandas as pd
from sklearn.linear_model import RidgeCV
from sklearn.dummy import DummyRegressor
from sklearn.pipeline import make_pipeline
from sklearn.ensemble import Ran... |
import csv
import os
from zipfile import ZipFile
import nltk
from flask import (Blueprint, flash, redirect, render_template, request, url_for, Flask)
from flask_table import Table, Col, LinkCol
from gensim.models import Word2Vec
from scipy import spatial
from sklearn.metrics.pairwise import cosine_similarity
from werk... |
from ..tokens.token_types import Token, TokenType
from typing import Union, List
from ..symbol_table.symbol_table import SymbolTable
class NumberNode:
"""Node for a number created by the parser for the abstract syntax tree"""
def __init__(self, tok: Token) -> None:
self.tok = tok
def __repr__(se... |
import os
import h5py
import pickle
import json
import numpy as np
import _init_paths
from tqdm import tqdm
import argparse
import utils.boxes as box_utils
from core.config import cfg
def get_obj_det(obj_anno_list):
obj_det = [{'bbox': [], 'category_id': []} for _ in range(len(obj_anno_list)+1)]
for obj_anno... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
import numpy as np
from typing import Any, Iterator, List, Union
import pycocotools.mask as mask_utils
import torch
from .boxes import Boxes
def polygons_to_bitmask(polygons: List[np.ndarray], height: int, width: int) -> np.ndarray:
... |
# Copyright 2017 <NAME> All Rights Reserved.
"""
Module containing code contracts.
"""
import re
import traceback
from collections import Iterable
# Regex used to extract the name of the variable passed as the first parameter to the
# contract function.
_MATCH_FIRST_PARAMETER_REGEX = re.compile(r"\(([\w.]+)[,)]")
... |
import configparser
from datetime import datetime
import os
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf, col, monotonically_increasing_id
from pyspark.sql.functions import year, month, dayofmonth, hour, weekofyear, date_format
from pyspark.sql.types import *
config = configparser.Config... |
'''renderVideo.py'''
# Included Libaries
from usefulFunctions import ProgressBar, sep
# Internal Libraries
import subprocess
def properties(cmd, args, vidFile, ffprobe):
if(args.video_codec == 'copy'):
cmd.extend(['-vcodec', ffprobe.getVideoCodec(vidFile)])
elif(args.video_codec == 'uncompressed'):
... |
from keras.models import Model, load_model
from keras.layers import *
from keras import backend as K
K.set_image_data_format('channels_last')
def expand(x):
x = K.expand_dims(x, axis=-1)
return x
def squeeze(x):
x = K.squeeze(x, axis=-1)
return x
#2D卷积模块
def BN_block(filter_num, input):
x = Conv... |
# for main
import sys
import csv
from github import Github
import os
import time
from collections import Counter
from collections import defaultdict
import csv
from github.IssueComment import IssueComment
# for logfile
import my_log
import datetime
# for get_links
import re
csv.field_size_limit(sys.maxsize)
args = sys... |
"""
Support for BMR HC64 Heating Regulation.
configuration.yaml
climate:
- platform: bmr
base_url: http://192.168.1.254/
username: !secret bmr_username
password: !secret bmr_password
away_temperature: 18
min_temperature: 18
max_temperature: 35
circuits:
- name: ... |
"""TransRAC network"""
from mmcv import Config
from mmaction.models import build_model
from mmcv.runner import load_checkpoint
import torch
import torch.nn as nn
import math
from torch.cuda.amp import autocast
import numpy as np
import torch.nn.functional as F
class attention(nn.Module):
"""Scaled dot-product att... |
# Qtile config file
# Please see http://docs.qtile.org/en/latest/
import os
import subprocess
from libqtile import hook, layout, bar, widget, qtile
from libqtile.config import Key, Click, Drag, Group, Match, Screen
from libqtile.lazy import lazy
from libqtile.dgroups import simple_key_binder
from libqtile.log_utils ... |
from load_data import Data
import numpy as np
import torch
import time
from collections import defaultdict
from model import *
from torch.optim.lr_scheduler import ExponentialLR
import argparse
import os
def compute_scores(score_instances):
"""
Given a list of scored instances [(stuff, label, score)], this me... |
from astropy.convolution import Box1DKernel
import emcee
import numpy as np
from scipy import integrate, optimize, signal
from .utils import acf, get_noise, smooth
def Vrng_Basri2011(y):
"""Basri et al. 2011, AJ, 141, 20"""
vrng = np.percentile(y, 95) - np.percentile(y, 5)
return vrng
def HFrms_Basri20... |
import os
import scrapy
import weakref
from scrapy.http.cookies import CookieJar
from scrapy.http import HtmlResponse
from scrapy.settings import Settings
from scrapy.selector import SelectorList, Selector
from os.path import abspath, join
from typing import Callable, Sequence, List, Iterable, Any, Union, Type
from cr... |
#!/usr/bin/env python
"""
Converts notebooks to interactive HTML pages with Juniper + Binder.
Standalone usage:
nbjuniper TARGET (+ optional flags below)
`nbjuniper example_notebook.ipynb` converts example_notebook.ipynb into
example_notebook.html.
Jupyter-book usage:
nbjuniper -j TARGET (+ optional flags b... |
import numpy as np
import torch
from torchvision import datasets
import torchvision.transforms as transforms
from tvm.tensor_graph.nn.layers import Layer, Conv2d, BatchNorm2d, ReLU, \
AvgPool2d, GlobalAvgPool2d, Linear, Sequential, CapsuleConv2d
from tvm.tensor_graph.nn.functional impo... |
# Copyright (c) 2019, Danish Technological Institute.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
# -*- coding: utf-8 -*-
""" Command to run an experiment
"""
import logging
import os
import click
from tr... |
# %%
import json
import re
import editdistance
import pandas as pd
from tqdm import tqdm
# %%
engineers_df = pd.read_csv("Data/all_engineers.csv", encoding="utf-8")
half_names = [
x.split(",")
for x in open("half_names.csv", "r", encoding="utf-8").read().split("\n")
if x != ""
]
# %%
# %%
full_name_map = ... |
#!/usr/bin/python
"""
G2_RIGHTS
Script to create a linear BPG network with 'n' links.
Usage:
./createNLinksExample.py -t <base_example_folder> -l <number_of_links> -cc <tcp_congestion_control> -f <scale_factor>
Given the above inputs, the script does the following:
* Uses the network topology and default config... |
#!/usr/bin/env python3.6
# 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
#... |
from keras import backend as K
from keras.models import Model
from keras.optimizers import SGD
from keras.layers import Input
from deephar.activations import channel_softmax_2d
from deephar.models.blocks import build_context_aggregation
from deephar.utils import *
from deephar.layers import *
from deephar.objectives... |
# coding: utf-8
# ---
#
# _You are currently looking at **version 1.2** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-data-analysis/resources/0dhYG) course resource._
#
... |
#!/usr/bin/env python
""" LearnedLeague Luck
This is an implementation of SheahanJ's algorithm for computing
"luck" in the [LearnedLeague](http://learnedleague.com), as described
by his post at in the [LearnedLeague Forum](http://www.learnedleague.com/viewtopic.php?f=3&t=5250)
The program expects to receive a CSV of ... |
import logging
from decimal import Decimal
from typing import Dict, List, Tuple
import braintree as braintree_sdk
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import pgettext_lazy
from prices import Money
from ... import TransactionKind
from ..... |
# This code is licensed under the MIT License (see LICENSE file for details)
from collections import abc
from PyQt5 import Qt
import textwrap
class _QtAbcMeta(type(Qt.QObject), type(abc.MutableSequence)):
# for SignalingList below to inherit from QObject and MutableSequence,
# it has to have a metaclass that ... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow
from tensorflow import keras
import os
import sys
from tensorflow import TensorSpec, float32, int32
from tensorflow import data
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential, load_model
from ... |
import random as rand
class Vehicle:
mr = 0.2
# Food weight, Poison weight, Food percep, Poison percep, FOV, Drone weight, Drone percep
feature_creation = [lambda x: random(0, 2), lambda x:random(-2, 0), lambda x:random(20, 100),
lambda x:random(20, 100), lambda x:random(P... |
"""Test SatelliteDataSource."""
import numpy as np
import pandas as pd
import pytest
from nowcasting_dataset.data_sources.metadata.metadata_model import SpaceTimeLocation
from nowcasting_dataset.data_sources.satellite.satellite_data_source import SatelliteDataSource
def test_satellite_data_source_init(sat_data_sourc... |
"""
reactions.py
Automate generation of synthetic workflows for the OpenTrons robotics platform
Handles getting reactants and/or products from an input
"""
import time
import pandas as pd
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem import Descriptors
from rdkit.Chem import rdChemReactions
... |
# -*- coding:utf-8 -*-
"""
state.py
Basic Setting and Quantum states
"""
import numpy
twopi = 2.0*numpy.pi
class ScaleInfo(object):
"""
ScaleInfoは位相空間の定義域を設定するためのclassです.
Parameters
----------
dim : int
Hilbert Space dimension
domain: list
domain of phase sp... |
"""Allow for easily adding segments to lines."""
from functools import singledispatch
from typing import Optional
from cairo import ANTIALIAS_NONE
from gi.repository import Gtk
from gaphas.aspect import MoveType
from gaphas.aspect.handlemove import HandleMove, ItemHandleMove, item_at_point
from gaphas.connector impor... |
import gym
import itertools
import matplotlib
import numpy as np
import sys
import tensorflow as tf
import collections
import math
if "../" not in sys.path:
sys.path.append("../")
from lib.envs.cliff_walking import CliffWalkingEnv
from lib import plotting
matplotlib.style.use('ggplot')
env = CliffWalkingEnv()
cl... |
import numpy as np
import plotly.graph_objs as go
import os, pickle
stats_dir = os.path.dirname(os.path.realpath(__file__)) + '/statistics'
mm10_genes = open(stats_dir + '/mm10_coding_genes.txt').readlines()
mm10_genes = [s.strip() for s in mm10_genes]
mm10_choices = [{'label': s, 'value': s} for s in mm10_ge... |
import MySQLdb
import discord
from discord.ext import commands
import asyncio
from pokemonlist import pokemon, pokejson, base_stats, cp_multipliers
from config import bot_channel, token, host, user, password, database, website, log_channel, raids_channel, spawn_channel, quest_channel
import datetime
import calendar
imp... |
from application import app
from application.forms import DashboardCreationForm, ModuleTypes, DataSources
from application.helpers import (
base_template_context,
requires_authentication,
requires_feature,
)
from flask import (
flash, redirect, render_template, request,
session, url_for
)
from appli... |
from PyQt5.QtCore import QEvent, pyqtSignal, pyqtSlot, QObject, QTime
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QAbstractSlider, QListWidget, QListWidgetItem, \
QRadioButton, QGroupBox
from datasets import data_read_utils as dutils
import pyqtgraph as pg
import csv
##### Override class #####... |
from collections import defaultdict, namedtuple
from contextlib import contextmanager
import functools
import clr
import os.path
import pandas as pd
clr.AddReference("DHI.Mike1D.ResultDataAccess")
from DHI.Mike1D.ResultDataAccess import ResultData # noqa
clr.AddReference("DHI.Mike1D.Generic")
from DHI.Mike1D.Generi... |
from typing import Dict, List, Tuple, Optional
from pathlib import Path
from fastprogress import master_bar, progress_bar
from fastprogress.fastprogress import IN_NOTEBOOK
import pickle
import timeit
import numpy as np
import os
import sys
from random import shuffle
from collections import OrderedDict
import math
from ... |
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTI... |
import pytest
import geometry
import objects
import util
from containers import put_object_in_container, put_objects_in_container, \
can_enclose, can_contain_both, can_contain
from geometry import are_adjacent
DEFAULT_CONTAINER = {
'type': 'box',
'attributes': ['receptacle', 'openable'],
'dimensions'... |
from src.interface import Coord
from src.sons import Sons
from src.jeu import Jeu
def listeJoueursTri(listeJoueurs):
"""Retourne la liste des joueurs du plus avancé en km au moins avancé."""
listeTri = []
for joueur in listeJoueurs[::-1]:
i = 0
while len(listeTri) > i and listeTri[i].km >=... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
def ct_get_links(link, platforms='facebook', count=100, start_date= None,
end_date=None, include_history=None, include_summary='false',
offset = 0, sortBy = 'date', api_token=None):
""" Retrieve a set of posts matching ... |
import torch
import torch.nn as nn
from torch.nn.utils import weight_norm
from pytorch_model_summary import summary
import numpy as np
import math
from torch.autograd import Variable
class Transpose_Layer(nn.Module):
def __init__(self, *dims):
"""
Trasposes input wrt to the last two di... |
import os
import re
import json
import simplejson
import datetime
import unittest
import requests_mock
from freezegun import freeze_time
from freezegun.api import FakeDate
from datapackage_pipelines.utilities.lib_test_helpers import (
ProcessorFixtureTestsBase,
rejsonize,
mock_processor_test
)
import dat... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
import unittest
import ezgal.astro_filter
from ezgal.cosmology import Cosmology
import tests
import numpy as np
def build_grid_astro_filter():
astro_filter = ezgal.astro_filter(tests.v_filter,
cosmology=Cosmology(),
vega=tests.vega,
... |
import numpy as np
import os
from scipy import stats
from sklearn.model_selection import LeaveOneOut
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics.pairwise import cosine_distances
import torch
from pytorch_metric_learning.distances import CosineSimilarity
import matplotlib.pyplot as plt
from m... |
from __future__ import print_function
from __future__ import absolute_import
from builtins import zip
from builtins import str
from builtins import object
from future.utils import raise_from
import sys
import yaml
import struct
import snappy
import traceback
from functools import partial
from .mapping import NAME_CLA... |
import numpy as np
import pandas as pd
import gym
# import gym_anytrading
import os
import pickle
from enum import Enum
from gym import spaces
from matplotlib import pyplot as plt
# Stable baselines - rl stuff
# from stable_baselines.common.vec_env import DummyVecEnv
# from stable_baselines import A2C
class Actions(... |
import asyncio
from mini.apis import errors
from mini.apis.api_sound import ChangeRobotVolume, ChangeRobotVolumeResponse
from mini.apis.api_sound import FetchAudioList, GetAudioListResponse, AudioSearchType
from mini.apis.api_sound import PlayAudio, PlayAudioResponse, AudioStorageType
# from mini.apis.api_sound import... |
from .digest import digest
anyNterm = "AnyN-term"
max_peptidoforms_per_seq = 100
class Protein:
def __init__(self, AC, DE, seq):
self.AC = AC
self.DE = DE
self.seq = seq
def read_protein_list(fasta, protein_list):
'''
For exmaple, 'sp|P08603|CFAH_HUMAN', protein in protein_list co... |
import re
import numpy as np
import pandas as pd
from collections import Counter, defaultdict
from scipy.sparse import csr_matrix
def sanitize_input(input_str_list):
r"""Replace all instances of 'weird' characters and spaces in string elements of a input_str_list sequence with '_'.
Examples:
[a/?, b\... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2008-2009 Zuza Software Foundation
#
# This file is part of the Translate Toolkit.
#
# This program 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; e... |
import json
import pandas as pd
from .. import Client as VanillaClient
from .. import Time
from ..constants import DEFAULT_DECISION_TREE_VERSION
from ..errors import CraftAiBadRequestError
from ..types import GENERATED_TIME_TYPES
from .interpreter import Interpreter
from .utils import format_input, is_valid_property_v... |
###########################################################
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import scikitplot as skplt
import pandas as pd
from sklearn.metrics import classification_report
#Util functions
def Extract(lst):
return [item[0] for item in lst]
fontdict... |
'''HIST data analysis module.
The functions in the module extract the bid and ask from the Historic Rate Data
from HIST Capital in a year.
This script requires the following modules:
* os
* pickle
* typing
* zipfile
* datetime
* numpy
* pandas
* hist_data_tools_extraction
The module c... |
import os
import json
from time import time
import torch
from utilities.captioning_utils import HiddenPrints
from epoch_loops.captioning_epoch_loops import calculate_metrics
from sklearn.cluster import KMeans
def tiou_vectorized(segments1, segments2, without_center_coords=False, center_length=True):
def center_... |
# Copyright 2012 Google Inc. All Rights Reserved.
"""File Interface for Google Cloud Storage."""
from __future__ import with_statement
__all__ = ['delete',
'listbucket',
'open',
'stat',
]
import urllib
import xml.etree.ElementTree as ET
from . import common
from . impo... |
from collections import OrderedDict
import re
#------------------------
# shared variables:
#------------------------
words = OrderedDict()
outputFilename = 'output.txt'
filename1 = 'data.txt'
allophones = {
'aeiou' : 'a',
'bp' : 'b',
'cjsz' : 'z',
'dt' : 'd',
'fv' : 'v',
'gkq' : 'g',
'... |
import asyncio
import logging
import pickle
import time
from enum import IntEnum
from typing import Any, Callable
from aioredis.client import PubSub, Redis
from aioredis.exceptions import ConnectionError
logger = logging.getLogger(__name__)
class Engine(IntEnum):
IN_PROCESS = 0
REDIS = 1
# for aio-redis m... |
import random
import uuid
import factory
from ozpcenter import models
def _generate_uuid():
return str(uuid.uuid4())
class ImageTypeFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.ImageType
django_get_or_create = ("name",)
name = factory.Sequence(lambda n: "imag... |
#!/usr/bin/env python3
"""Generate burn in tests to run on certain build variants."""
from collections import namedtuple
import logging
import os
import sys
from typing import Any, Dict, List
import click
from git import Repo
from shrub.v2 import ShrubProject, BuildVariant, ExistingTask
from evergreen.api import Retr... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import gi
import os
import tempfile
import wave
import azure.cognitiveservices.speech as speechsdk
from batchkit.logger import LogEventQueue, LogLevel
gi.require_version('Gst', '1.0')
# noinspection PyUnresolvedReferences
from gi.repository impo... |
#! /usr/bin/env python3
# ==========================================================================================================================================================
# Copyright 2021 Carnegie Mellon University.
#
# NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING INSTITUTE MATERIA... |
import unittest
import itertools
import pytest
import numpy
from csep.core.regions import CartesianGrid2D, compute_vertex, compute_vertices, _bin_catalog_spatio_magnitude_counts, \
_bin_catalog_spatial_counts, _bin_catalog_probability, Polygon
class TestPolygon(unittest.TestCase):
def setUp(self):
... |
"""The product Matern52 kernel embeddings."""
from typing import List, Optional, Tuple
import numpy as np
from ...quadrature.interfaces.standard_kernels import IProductMatern52
from ..measures import IntegrationMeasure
from ..typing import BoundsType
from .quadrature_kernels import QuadratureKernel
class Quadratur... |
"""
Software License Agreement (Apache 2.0)
Copyright (c) 2020, The MITRE Corporation.
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
https://www.apache.org/licenses/LICENSE-... |
from ctypes import BigEndianStructure, create_string_buffer, c_ubyte, c_uint8, \
c_uint16, c_uint32, sizeof
from socket import inet_ntop, AF_INET, AF_INET6
class Protocol(BigEndianStructure):
_pack_ = 1
def __new__(cls, packet):
return cls.from_buffer_copy(packet)
def __init__(self, *args):
... |
'''
===============================================================================
-- Author: <NAME>, <NAME>
-- Create date: 04/11/2020
-- Description: This codes is for detection and ecxtraction of
any text in wild range by MSER and SWT.
-- Status: In progress
======================... |
import copy
import inspect
import logging
import sys
from bs4 import BeautifulSoup
from oic.exception import IssuerMismatch
from oic.oauth2 import ResponseError
from oic.oauth2.message import AccessTokenResponse
from oic.oauth2.message import ErrorResponse
from oic.oauth2.message import Message
from oic.oauth2.message... |
#!/usr/bin/env python3
import json
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sn
GPS_FILENAME = 'gps.json'
ACCEL_FILENAME = 'accel.json'
GYRO_FILENAME = 'gyro.json'
BARO_FILENAME = 'baro.json'
COMPASS_FILENAME = 'compass.json'
def read_file(filename):
with open(filena... |
# -*-coding: utf-8 -*-
import time
import leancloud
from leancloud.errors import LeanCloudError
from .oauth2 import OAuth2API
from .bind import bind_method, RealtimeAPIError
from .helper import md5_constructor as md5
SUPPORTED_FORMATS = ['json']
class RealtimeAPI(OAuth2API):
host = 'api.leancloud.cn'
ba... |
import us
import os
from pathlib import Path
BUILD_USER = 'build-db'
GEN_USER = 'generate-docs'
GEN_PWD = '<PASSWORD>'
ATLAS_URI = 'mongodb+srv://{usr}:{<EMAIL>/{db}?retryWrites=true&w=majority'
DEFAULT_BATCH_INSERT_SIZE = 500000
DATA_DIR = os.path.join(os.getcwd(), 'data-library')
DATA_SCRIPTS_PATH = os.path.join... |
import serial
import time
import struct
##from pid import PID
from multiprocessing import Process, Value
import cv2 as cv
from picamera.array import PiRGBArray
from picamera import PiCamera
import numpy as np
import imutils
#function prepares values to be sent to arduino
def pack(value):
return struct.pack('>B', v... |
#!/usr/bin/env python
######################################################
# Python script for analysis of dynamic rheology
# from Cognac Calculations
# 2007/2/20 <NAME>, <NAME>
# 2007/9/01 <NAME>
# 2016/4/18 H.Sasaki
############################... |
import bpy
from mathutils import Vector
import numpy
import math
from bpy_extras.view3d_utils import location_3d_to_region_2d
from .utilities.raycast_utils import *
from .utilities.grid_utils import *
from .utilities.draw_utils import *
def SnapDrawHandler(snapClass, context):
if snapClass.isSnapActive... |
"""Policies that can be evaluated in blackjack."""
import collections
import itertools
import random
import string
from abc import ABC, abstractmethod
from collections.abc import Sequence
import requests
from blackjack.blackjack import Card, Hand, SimulatorModel
AVAILABLE_POLICIES = ['basic', 'brain', 'random', 'ran... |
# --------------------------------------------------------------------------
# Handles the creation and rendering of Page objects.
# --------------------------------------------------------------------------
import os
import re
import sys
import math
from . import site
from . import hooks
from . import utils
from . i... |
# Import modules
import os
os.environ["OMP_NUM_THREADS"] = "1"
import numpy as np
import argparse
import datetime
import warnings
import sys
warnings.filterwarnings('ignore')
np.set_printoptions(threshold=np.inf)
# Define physical constants
KtoeV = 8.617333262e-5
# Define functions
# For reading jmpdata.csv
def read... |
# Copyright 2019 The TensorFlow 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 applica... |
#!/usr/bin/env python
# Copyright (c) 2019 <NAME>, <NAME>, <NAME>, <NAME>
#
# 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
# ... |
import os, urlparse
from datetime import datetime
from rauth import OAuth1Service
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from django.contrib import messages
from djang... |
__all__ = ["Twitter"]
import bisect
import collections
import datetime as dt
import json
import typing
from copy import deepcopy
import requests
class Memento(collections.namedtuple("Memento", "key i x t_expire")):
def __lt__(self, other):
return self.t_expire < other.t_expire
class Twitter:
"""G... |
from qiskit.aqua.components.feature_maps import FeatureMap
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit.library import BlueprintCircuit
import numpy as np
import matplotlib.pyplot as plt
import functools
from qiskit import BasicAer
from qiskit.circuit.library import ZFeatur... |
from __future__ import division
import numpy as np
from openmdao.api import ExplicitComponent
from openmdao.api import Group
from .empirical_data.prop_maps import propeller_map_Raymer, propeller_map_highpower, static_propeller_map_Raymer, static_propeller_map_highpower, propeller_map_scaled, propeller_map_constant_prop... |
# Copyright (C) 2021 Members of the Simons Observatory collaboration.
# Please refer to the LICENSE file in the root of this repository.
import matplotlib.pyplot as plt
import numpy as np
import ref
from waferscreen.plot.band_and_keepout import band_and_keepout_plot
from waferscreen.plot.band_and_keepout import colors... |
import threading
from multiprocessing import Process
import json
import socket
import asyncio
import logging
import sys
from resources.commands import build_porter_command, build_porter_command_for_outputs
from shared.config import get_config
from resources.helpers import get_installation_id
from resources.httpserver i... |
import torch
import torch.nn as nn
from datetime import datetime
from src.control import Control
from torchvision.models.utils import load_state_dict_from_url
from src.utils.functions import save_weights, load_weights
class Parser(object):
"""
Converts the info of a tasks file into objects expected by `Schedu... |
# Copyright 2014 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... |
"""
metadata.views
"""
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.template import loader
from django.core.exceptions import ValidationError
from django.utils import timezone
from django.db import transaction
from django.contrib.auth.decorators import login_required, user_passes_tes... |
# import pretty_errors
__version__ = 'v1.2'
import PySimpleGUI as sg
import tabulate
import random, math
from pprint import pprint
import webbrowser
sg.theme('Reddit')
sg.SetOptions(font='Arial 10')
window_title = 'Распределитель билетов'
bilet_count = 30
students_count = 3
student_names = list()
student_numbers =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.