id
stringlengths
3
8
content
stringlengths
100
981k
11464657
from typing import Any, Callable, List, Tuple, Union import numpy as np import pandas as pd import tensorflow as tf import torch from sklearn.model_selection import train_test_split from carla.data.catalog import DataCatalog from carla.data.causal_model.synthethic_data import ScmDataset from carla.data.load_catalog i...
11464695
import idc import idaapi from idaapi import Choose2 import driverlib import ctypes import ioctl_decoder as ioctl_decoder # yoinked from https://stackoverflow.com/a/25678113 OpenClipboard = ctypes.windll.user32.OpenClipboard EmptyClipboard = ctypes.windll.user32.EmptyClipboard GetClipboardData = ctypes.windll.user32.Ge...
11464735
class Shape: ''' A class for shape ''' def __init__(self): ''' You won't believe the next five lines ''' print(0) shape = Shape()
11464750
from __future__ import print_function from kivy.properties import ( ObjectProperty, ListProperty, DictProperty, StringProperty) from kivy.uix.boxlayout import BoxLayout from .app_buttons import AppBlueButton from kivy.logger import Logger from kivy.lang import Builder Builder.load_string(''' <ActivitieBox>: o...
11464778
import pylab # import seaborn as sns from scipy.sparse import diags from scipy.sparse.linalg import cg MAX_VAL = 255.0 from scipy.sparse import csr_matrix import numpy as np from scipy.sparse.linalg import inv RGB_TO_YUV = np.array([ [ 0.299, 0.587, 0.114], [-0.168736, -0.331264, 0.5], [ 0.5,...
11464798
from pkg_resources import get_distribution __import__('pkg_resources').declare_namespace(__name__) __version__ = get_distribution("telesign").version __author__ = "TeleSign" __copyright__ = "Copyright 2017, TeleSign Corp." __credits__ = ["TeleSign"] __license__ = "MIT" __maintainer__ = "TeleSign Corp." __email__ = "<...
11464820
class EmrClusterBuilder(object): def __init__(self, emr_client, ec2_client): super(EmrClusterBuilder, self).__init__() self.emr = emr_client self.ec2 = ec2_client # boto3.client("ec2", region_name=region_name) def get_security_group_id(self, group_name, region_name): response =...
11464823
import os from .deploy_manifest import log from . import exceptions as exc class BlueGreen(object): """This class orchestrates a Blue-Green deployment in the style of the Autopilot CF CLI plugin. """ def __init__(self, space, manifest, verbose=True, ...
11464830
import logging import pytest from ocs_ci.framework.testlib import ManageTest, tier1 from ocs_ci.framework.pytest_customization.marks import ( skipif_external_mode, skipif_ocs_version, ) from ocs_ci.ocs.cluster import ( validate_compression, validate_replica_data, ) from ocs_ci.ocs.constants import CEPHB...
11464832
import io import os import re import shutil import sys from pathlib import Path from typing import Generator from unittest import mock import pytest from _pytest._io import terminalwriter from _pytest.monkeypatch import MonkeyPatch # These tests were initially copied from py 1.8.1. def test_terminal_width_COLUMNS(...
11464890
import os import sys import inspect class FindFilePath: def __new__(cls, name) -> str: if name is None: raise NameError("Please specify filename") stack_t = inspect.stack() ins = inspect.getframeinfo(stack_t[1][0]) this_file_dir = os.path.dirname(os.path.dirname(os.pat...
11464993
from veroviz._common import * from veroviz._queryOpenWeather import owGetWeather def privGetWeather(location, id, metricUnits, dataProvider, dataProviderArgs): try: dataProvider = dataProvider.lower() except: pass if (weatherDataProviderDictionary[dataProvider] == 'openweather'): weatherDF = owGetWeather(...
11465016
import matplotlib.pyplot as plt from matplotlib.ticker import FuncFormatter, MaxNLocator import numpy as np import plotly.graph_objs as go import seaborn as sns import plotly.figure_factory as pff DEFAULT_COLORSCALE = "Viridis" def plot_distribution(ls, column, bins=None): """Plot the distribution of numerical c...
11465089
from __future__ import absolute_import, division import torch from torch import nn import torch.nn.functional as F def my_grid_sample(inputs, grid): return F.grid_sample(inputs, grid, align_corners=True) def interpolate2d(inputs, size, mode="bilinear"): return F.interpolate(inputs, size, mode=mode, align_c...
11465243
import torch.nn as nn PADDING_LAYERS = { 'zero': nn.ZeroPad2d, 'reflect': nn.ReflectionPad2d, 'replicate': nn.ReplicationPad2d } def build_padding_layer(cfg, *args, **kwargs): """Build padding layer. Args: cfg (None or dict): The padding layer config, which should contain: - ...
11465297
from psana import DataSource from psana.psexp.utils import DataSourceFromString import argparse import sys def detnames(): # this argument parsing doesn't feel ideal. ideally user should # be able to pass in the "python code" specifying the datasource # on the command line (e.g. exp=xpptut15,run=[1,2,4,7] or ...
11465309
import matplotlib.pyplot as plt import os import numpy as np SMALL_SIZE = 24 MEDIUM_SIZE = 24 BIGGER_SIZE = 24 plt.rc('font', size=SMALL_SIZE) # controls default text sizes plt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y...
11465320
from progress.bar import Bar from config.test_config import BasicParam import os import cv2 as cv import time import torch import numpy as np from dataset.dataset import YorkDataset from progress.bar import Bar from utils.utils import load_model from utils.reconstruct import save_pic_mat, save_image device = torch.de...
11465409
from .pypi import PyPi, __red_end_user_data_statement__ def setup(bot): bot.add_cog(PyPi(bot))
11465472
import os.path import numpy as np from PIL import Image from .cityscapes import remap_labels_to_train_ids from .gta5 import GTA5 #, LABEL2TRAIN from .data_loader import register_data_params, register_dataset_obj @register_dataset_obj('cyclegta5') class CycleGTA5(GTA5): def collect_ids(self): ids = GTA...
11465520
from django.test import TestCase from .models import ( HouseholdBillTotal, HouseholdServiceTotal, FinancialYear, BudgetPhase, HouseholdService, HouseholdClass, ) from scorecard.models import Geography class HouseholdsTestCase(TestCase): def setUp(self): FinancialYear.objects.bulk_c...
11465529
from django.test import TestCase, override_settings from django.utils.translation import override from translations.languages import _get_supported_language, \ _get_default_language, _get_active_language, \ _get_all_languages, _get_all_choices, \ _get_translation_languages, _get_translation_choices, \ ...
11465588
from collections import namedtuple from .nodes import * import re ConditionalBlock = namedtuple('ConditionalBlock', 'parent source output skip_to_end') class ParamStr(str): def __new__(cls, s, args, n): self = super().__new__(cls, s) self._args = args self._arg_idx = n return sel...
11465590
from surprise import Dataset from surprise import Reader from surprise import NormalPredictor from surprise import BaselineOnly from surprise import KNNBasic from surprise import KNNWithMeans from surprise import KNNBaseline from surprise import KNNWithZScore from surprise import SVD from surprise import SVDpp from sur...
11465607
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from six.moves import xrange import tensorflow as tf from tensorflow.python.platform import flags import logging, os, sys, pickle, argparse sys.path.a...
11465608
from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter class Command(BaseXpressDemocracyClubCsvImporter): council_id = "BOT" addresses_name = ( "2021-04-16T11:13:32.139850/Boston Democracy_Club__06May2021 (2).tsv" ) stations_name = ( "2021-04-16T11:13:32.1398...
11465620
from toee import * ################################# # TELEPORT SHORTCUTS # ################################# TELE_SHORT_TEMPLE_LEVEL_3 = 5078 def shopmap(): game.fade_and_teleport(0,0,0,5107,480,480) return def lgvignette(): game.fade_and_teleport(0,0,0,5096,480,480) return def lawfulgoodvignette(): lgvig...
11465642
import operator import rutokenizer import rupostagger import rulemma if __name__ == '__main__': print('Loading dictionaries and models...') lemmatizer = rulemma.Lemmatizer() lemmatizer.load('../tmp/rulemma.dat') tokenizer = rutokenizer.Tokenizer() tokenizer.load() tagger = rupostagger.RuPosT...
11465643
class CloudExternalFileProcessorMixin(object): def get_input_path(self, in_file): return in_file.instance.file.url
11465647
from setuptools import find_packages, setup VERSION = {} # type: ignore with open("trapper/version.py", "r") as version_file: exec(version_file.read(), VERSION) def get_requirements(): with open("requirements.txt") as f: return f.read().splitlines() extras_require = { "dev": [ "black==...
11465670
import sys sys.path.insert(0, '..') import kalman_filter import kf_simple3d import numpy as np import matplotlib.pyplot as plt import pickle import os.path import pdb np.set_printoptions(precision=4) class Track: def __init__(self, track_id, first_detection, kf_type): # initiate kf if kf_type == "2...
11465681
import numpy as np from sklearn.decomposition import PCA def test(X): pca = PCA(n_components=2) projected = pca.fit_transform(X) print(f'n_observations: {pca.n_samples_}') print(f'n_features: {pca.n_features_}') print(f'n_components: {pca.n_components_}') print(f'\nprojected:\n{projected}') ...
11465690
from django.test import TestCase from django.utils import timezone from . import schedules from datetime import datetime now = timezone.make_aware( datetime(1983, 7, 1, 3, 41), timezone.utc) class ScheduleTest(TestCase): def test_hourly(self): sched = schedules.Hourly(20, 2, 4) self.asse...
11465719
t_SH_StockMarketDataL2 = { "nTime": "T_I32", "nStatus": "T_I32", "uPreClose": "T_U32", "uOpen": "T_U32", "uHigh": "T_U32", "uLow": "T_U32", "uMatch": "T_U32", "uAskPrice": "T_U32", "uAskVol": "T_U32", "uBidPrice": "T_U32", "uBidVol": "T_U32", "uNumTrades": "T_U32", "i...
11465745
aa = 0 a = 1 fim = int(input('Digite um termo: ')) for n in range (0, fim): s = (aa + a) print(s, end = ' → ') aa = a a = s print() s = 0 while s <= fim: if s % 2 == 0: print(s, end=' → ') s = s + 1 #https://pt.stackoverflow.com/q/411542/101
11465757
from .client import GCSClient from .data import CollectionDocument, GuestCollectionDocument, MappedCollectionDocument from .errors import GCSAPIError from .response import IterableGCSResponse, UnpackingGCSResponse __all__ = ( "GCSClient", "CollectionDocument", "GuestCollectionDocument", "MappedCollecti...
11465760
import pytest from BetweenHours import is_between_hours TEST_INPUTS = [ ('12:00:00', '02:00:00', '21:00:00', True, 'sanity 1'), ('12:00:00', '11:10:00', '12:50:00', True, 'sanity 3'), ('12:00:00', '12:00:00', '12:00:00', True, 'exact same date'), ('12:00:00', '12:00:00', '22:00:00', True, 'same as beg...
11465773
from rest_framework.throttling import AnonRateThrottle from app.throttling import ConfigurableThrottlingMixin class AuthAnonRateThrottle(ConfigurableThrottlingMixin, AnonRateThrottle): """Throttle for any authorization views.""" scope = 'anon-auth'
11465805
from __future__ import absolute_import, division, print_function, with_statement from tornado.concurrent import Future from tornado import gen from tornado import netutil from tornado.stack_context import NullContext from tornado.testing import AsyncTestCase, bind_unused_port, gen_test from tornado.test.util import uni...
11465826
import json from os.path import isdir from os import mkdir from pathlib import Path from gitlab_api_client import GitlabApi config_location = Path.home() / ".gitlab-client.json" def get_gitlab_api_client(gitlab_instance) -> GitlabApi: config = __get_gitlab_instance_config(gitlab_instance) return GitlabApi(c...
11465887
import this from flask import Flask app = Flask(__name__) rot13 = str.maketrans( "ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz", "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm" ) def simple_html(body): return f""" <!DOCTYPE html> <html lang="en"> <head> <meta charse...
11465892
from envs.IsaacGym import * from elegantrl.demo import * """ Humanoid GPU 4 GPU 5 if_use_cri_target = True """ def demo_isaac_on_policy(): args = Arguments(if_on_policy=True) # hyper-parameters of on-policy is different from off-policy args.agent = AgentPPO() args.random_seed += 1943 ...
11465931
import os import sys import torch import shutil import random import numpy as np from tensorboardX import SummaryWriter from Datasets.dataset_shapenetpart import ShapeNetPartDataset from Datasets.dataset_samplers import RandomSampler, Sampler from Models.model_PN2 import PointNet2 from Models.model_mRes import mRes f...
11465978
from __future__ import print_function from __future__ import division import math import torch import torch.nn as nn from torch.nn import Parameter from torchkit.head.localfc.common import calc_logits class CosFace(nn.Module): """ Implement of CosFace (https://arxiv.org/abs/1801.09414) """ def __init__(s...
11466025
import numpy as np import gym #******************************************************************* # FIND CAVE TASK #******************************************************************* # custom action wrapper for complete GAIL agent for MineRL class ActionShaping_FindCave(gym.ActionWrapper): def __init__(self, e...
11466048
from __future__ import print_function from stompy import harm_decomp import numpy as np def test_basic(): # A sample problem: omegas = np.array([1.0,0.0]) # the constructed data: amps = np.array([1,5.0]) phis = np.array([1,0]) t = np.linspace(0,10*np.pi,125) h = amps[0]*np.cos(omegas[0]...
11466072
import FWCore.ParameterSet.Config as cms from PhysicsTools.NanoAOD.common_cff import * rhoTable = cms.EDProducer("GlobalVariablesTableProducer", variables = cms.PSet( fixedGridRhoFastjetAll = ExtVar( cms.InputTag("fixedGridRhoFastjetAll"), "double", doc = "rho from all PF Candidates, used e.g. for JECs" ),...
11466096
import os import csv, json from collections import defaultdict from expertise.evaluators.mean_avg_precision import eval_map from expertise.evaluators.hits_at_k import eval_hits_at_k from expertise.dataset import Dataset from expertise import utils import ipdb def setup(config): assert os.path.exists(config.tpms_s...
11466138
from tests.analyzer.utils import UnusedTestCase from unimport.statement import Import, ImportFrom class AsImportTestCase(UnusedTestCase): def test_as_import_all_unused_all_cases(self): self.assertSourceAfterScanningEqualToExpected( """\ from x import y as z import x ...
11466160
from datetime import timedelta from pathlib import Path import click from overhave.base_settings import LoggingSettings from overhave.cli.group import overhave from overhave.transport import OverhaveS3Bucket, OverhaveS3ManagerSettings, S3Manager from overhave.utils import get_current_time @overhave.group(short_help...
11466212
import argparse, yaml, os, os.path parser = argparse.ArgumentParser() parser.add_argument("-i", "--input") parser.add_argument("-o", "--output") parser.add_argument("--tm2", "--tm", action="store_const", const="tm2", dest="action") parser.add_argument("--tm2source", "--tmsource", action="store_const", const="tm2source...
11466232
import copy import io import itertools import os import shutil import unittest import tempfile import pkg_resources import pyhmmer from pyhmmer.errors import EaselError, AlphabetMismatch from pyhmmer.easel import Alphabet, SequenceFile from pyhmmer.plan7 import HMM, HMMFile, Profile, Background class TestProfile(uni...
11466238
from project import db import datetime from project.corsi.models import Corso # Tabella di relazione 1 Corso : N Serate class Serata(db.Model): __tablename__ = "serata" __table_args__ = (db.UniqueConstraint("id", "data", name="constraint_serata"),) id = db.Column(db.Integer(), primary_key=True) nom...
11466248
import shutil from typing import Dict from covid_shared import workflow import covid_model_seiir_pipeline from covid_model_seiir_pipeline.pipeline.parameter_fit.specification import FIT_JOBS, FitScenario class BetaFitTaskTemplate(workflow.TaskTemplate): tool = workflow.get_jobmon_tool(covid_model_seiir_pipeline...
11466249
execfile('ex-3.02.py') B = (3, 1) D = (4 * dtype.extent, 0) newtype = dtype.Create_hindexed(B, D) dtype.Free() newtype.Free()
11466252
import copy import logging import lib.const as C import lib.visit as v from .. import util from ..meta import class_nonce, register_class, class_lookup from ..meta.program import Program from ..meta.clazz import Clazz from ..meta.method import Method from ..meta.field import Field from ..meta.statement import Stateme...
11466259
import numpy as np import properties import z_order_utils class BaseMetadata(properties.HasProperties): name = properties.String("Name of the block model", default="") description = properties.String("Description of the block model", default="") # Other named metadata? class BaseOrientation(properties.H...
11466342
import enum class WeekDay(enum.Enum): monday = 'MONDAY' tuesday = 'TUESDAY' wednesday = 'WEDNESDAY' thursday = 'THURSDAY' friday = 'FRIDAY' saturday = 'SATURDAY' sunday = 'SUNDAY'
11466392
from django.apps import AppConfig class FiberConfig(AppConfig): name = 'fiber' default_auto_field = 'django.db.models.AutoField'
11466423
from dartcms.utils.loading import is_model_registered from django.db.models.signals import post_save, pre_delete, pre_save from .abstract_models import * from .signals import * __all__ = [] if not is_model_registered('shop', 'ProductCatalog'): class ProductCatalog(AbstractProductCatalog): pass __all...
11466430
import pytest import numpy as np @pytest.fixture(autouse=True) def reload_cmap(): import importlib import terracotta.cmaps.get_cmaps try: yield finally: importlib.reload(terracotta.cmaps.get_cmaps) def test_get_cmap(): from terracotta.cmaps.get_cmaps import get_cmap, AVAILABLE_C...
11466462
import datetime import math import random import string import bson import bsonnumpy import numpy as np from test import client_context, millis, unittest, TestToNdarray, PY3 class TestSequenceFlat(TestToNdarray): def test_incorrect_arguments(self): # Expects iterator, dtype, count needs_iter = r...
11466500
import json from uuid import uuid4 from urllib.request import urlopen, Request from urllib.error import HTTPError class Yggdrasil(object): ygg_version = 1 ygg_url = 'https://authserver.mojang.com' def __init__(self, username='', password='', client_token='', access_token=''): self.username =...
11466530
import boto3 import time stream_name = 'mystream' #Creating a kinesis client client = boto3.client('kinesis') #Getting shard id by describing the stream response = client.describe_stream(StreamName=stream_name) shard_id = response['StreamDescription']['Shards'][1]['ShardId'] #getting the shard iterator (pointer) va...
11466608
import sys import json from subprocess import Popen, PIPE from smac.configspace import Configuration from smac.tae.execute_ta_run import StatusType, ExecuteTARun __author__ = "<NAME>" __copyright__ = "Copyright 2015, ML4AAD" __license__ = "3-clause BSD" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __version__ = "0...
11466618
from .args import Args from .format.args_format import ArgsFormat from .raw_args import RawArgs class ArgsParser(object): """ Parses raw console arguments and returns the parsed arguments. """ def parse( self, args, fmt, lenient=False ): # type: (RawArgs, ArgsFormat, bool) -> Args ...
11466644
import pytest from plenum.common.util import randomString from storage.optimistic_kv_store import OptimisticKVStore @pytest.fixture() def optimistic_store(parametrised_storage) -> OptimisticKVStore: store = OptimisticKVStore(parametrised_storage) return store def gen_data(num): return {randomString(32)...
11466646
import pexpect import sys def run(name,opts,res): child = pexpect.spawn('./{}'.format(name)) child.logfile = sys.stdout try: child.expect('>') child.sendline('app.async(0)') child.expect(r'< trans.send\(1,1\)') child.expect('>') child.sendline('trans.recv(1,1)') ...
11466663
from collections import Counter from collections import ChainMap from multiprocessing import Pool import itertools def chunks(l, n): for i in range(0, len(l), n): yield l[i : i + n] def multiprocessing(strings, function, cores = 16, list_mode = True): df_split = chunks(strings, len(strings) //...
11466669
import numpy as np import pandas as pd import pvl import sys import functools import json from os import path from plio.io.io_json import read_json from plio.utils._tes2numpy import tes_dtype_map from plio.utils._tes2numpy import tes_columns from plio.utils._tes2numpy import tes_scaling_factors class Tes(object): ...
11466675
import sys # sys.argv.append("--dynet-viz") #the package is broken import dynet_config # Declare GPU as the default device type # dynet_config.set_gpu() # Set some parameters manualy from dynetcon import Deserializer dynet_config.set(mem=4, random_seed=9) # Initialize dynet import using above configuration in the ...
11466697
import re from typing import Optional from openvpn_api.models import VPNModelBase from openvpn_api.util import errors class ServerStats(VPNModelBase): """OpenVPN server stats model.""" def __init__(self, client_count: int = None, bytes_in: int = None, bytes_out: int = None,) -> None: # Number of con...
11466703
from genty import genty, genty_dataset from os.path import expanduser, join from app.common.build_artifact import BuildArtifact from app.util.conf.configuration import Configuration from test.framework.base_unit_test_case import BaseUnitTestCase @genty class TestBuildArtifact(BaseUnitTestCase): def setUp(self): ...
11466707
from typing import Union from typing import List from typing import Tuple from typing import Optional from typing import Dict from typing import Any import copy import random import itertools from loguru import logger from rdkit import Chem from rdkit.Chem import rdmolops from rdkit.Chem.MolStandardize import rdMolS...
11466713
import os def rid(i,base64): os.makedirs('pic',exist_ok=True) with open(os.path.join('pic',i+'.txt'),'w') as f: f.write(base64)
11466759
import datetime from django.utils.timezone import utc import factory from factory import fuzzy from product_details import product_details from pytz import common_timezones from remo.events.models import (Attendance, Event, EventComment, EventMetric, EventMetricOutcome) from remo.pro...
11466765
import eel from file_handler import getFile, read_data from json import load from os.path import join from program import start, loadEditor, cleanup, loadOptions, saveEditor from generator import gen_img eel.init("UI") @eel.expose def getTemplate(): return getFile("template") @eel.expose def getCSV(): return getFi...
11466788
from app.main.model.database import BlacklistToken from sanic.log import logger from ..util.response import * async def save_token(token): blacklist_token = BlacklistToken(token=token) try: # insert the token await blacklist_token.commit() return response_message(SUCCESS) except Ex...
11466811
import multiprocessing import math import cv2 as cv import keras.backend as K import numpy as np from tensorflow.python.client import device_lib from config import epsilon, epsilon_sqr from config import img_cols from config import img_rows from config import unknown_code # overall loss: weighted summation of the tw...
11466878
from .ExamplePage import ExamplePage class OtherFileTypes(ExamplePage): def writeContent(self): self.writeln('<h4>Test for other file types:</h4>') self.writeLink('test.text') self.writeLink('test.html') def writeLink(self, link): self.writeln(f'<p><a href="Tests/{link}">{lin...
11466936
import random import torch import numpy as np PAD, UNK, BOS, EOS = '<pad>', '<unk>', '<bos>', '<eos>' BOC, EOC = '<boc>', '<eoc>' LS, RS, SP = '<s>', '</s>', ' ' CS = ['<c-1>'] + ['<c' + str(i) + '>' for i in range(32)] # content SS = ['<s-1>'] + ['<s' + str(i) + '>' for i in range(512)] # segment PS = ['<p-1>'] + ['<...
11467009
from pelican import readers from pelican.readers import PelicanHTMLTranslator from pelican import signals from docutils import nodes LINK_CHAR = "*" def init_headerid(sender): global LINK_CHAR char = sender.settings.get("HEADERID_LINK_CHAR") if char: LINK_CHAR = char def register(): signals...
11467014
from PyQt5 import QtCore, QtWidgets, QtGui from shapely.geometry import Point as ShapelyPoint from shapely.geometry.polygon import Polygon as ShapelyPolygon from Item import Item from Tikzifyables.DashPatternable import DashPatternable from Tikzifyables.Colourable.LineColourable import LineColourable from Tikzifyables...
11467031
from rest_framework import status from usaspending_api.download.lookups import CFO_CGACS base_query = "/api/v2/references/filter_tree/tas/" common_query = base_query + "?depth=0" # Can the endpoint successfully create a search tree node? def test_one_agency(client, basic_agency): resp = _call_and_expect_200(cli...
11467032
import unicodedata import jsonlines import re from urllib.parse import unquote import regex import numpy as np import scipy.sparse as sp from sklearn.utils import murmurhash3_32 def normalize(text): """Resolve different type of unicode encodings / capitarization in HotpotQA data.""" text = unicodedata.normaliz...
11467048
from typing import Optional, Tuple from .endpoint_type import EndpointType SHOULD_USE_MAP = { "globus collection delete": [ ("globus endpoint delete", EndpointType.traditional_endpoints()), ], "globus endpoint delete": [ ("globus collection delete", EndpointType.collections()), ], ...
11467057
from docusign_click import AccountsApi from flask import request, session from ...utils import create_click_api_client class Eg005Controller: @staticmethod def get_args(): """Get required session and request arguments""" return { "account_id": session.get("ds_account_id"), # Repr...
11467084
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import io import os from observations.util import maybe_download_and_extract def ptb(path): """Load the Penn Treebank data set [@marcus1993building]. The dataset is preprocessed and ha...
11467091
import itertools import json import time import ray from typing import Callable import numpy as np from mesh_transformer.train_actor import NetworkRunner from google.cloud import storage from smart_open import open from func_timeout import func_set_timeout class TPUCluster: @func_set_timeout(1200) def __in...
11467176
from DataReader import * class Png(DataReader): """ Manages the fetching of single peices of data on the cpu onto the gpu """ def __init__(self,dataset_root,data_list_path,channels=3,dtype=tf.uint8): with tf.variable_scope(None,default_name="image_data_reader"): DataReader.__init__(self,dataset_root,data_list...
11467181
import os import tkinter import tkinter.ttk import warnings from concurrent.futures import ThreadPoolExecutor from tkinter import scrolledtext import matplotlib.colors as mcolors from pynput.keyboard import Listener import constants import helper import keyboard_helper from forza import Forza from logger import Logge...
11467192
import unittest2 from hashlib import sha1 from pykafka.partitioners import GroupHashingPartitioner class TestGroupHashingPartitioner(unittest2.TestCase): def test_valid_inputs_success(self): # Test data; 1st element is group size, 2nd is total partition count, 3rd is the key key = 'foo'.encode('...
11467201
import matplotlib.pyplot as plt import pyDNase from pyDNase.footprinting import wellington #Load test data reads = pyDNase.BAMHandler("example.bam") regions = pyDNase.GenomicIntervalSet("example.bed") #Plot cuts data plt.plot(reads[regions[0]]["+"],c="red") plt.plot(-reads[regions[0]]["-"],c="blue") #Footprint and p...
11467209
def calMean(array): mean = 0 for i in range(len(array)): mean = mean + array[i] mean = mean/float(len(array)) return mean if __name__ == "__main__": array = [1,2,3,4] mean = calMean(array) print (mean)
11467283
from xbrr.base.reader.base_element_schema import BaseElementSchema class ElementSchema(BaseElementSchema): def __init__(self, name="", reference="", label="", alias="", abstract="", data_type="", period_type="", balance=""): super().__init__() se...
11467312
import numpy as np import sys,os,glob ######################################## INPUT ########################################## root = '/simons/scratch/fvillaescusa/pdf_information/PDF/matter/' cosmos = ['Om_p/', 'Ob_p/', 'Ob2_p/', 'h_p/', 'ns_p/', 's8_p/', 'Om_m/', 'Ob_m/', 'Ob2_m/', 'h_m/', '...
11467347
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import numpy import os #python setup.py build_ext --inplace ext_modules = [ Extension("treecode_bem", sources = ['common.c', 'bem_pbc.c', ...
11467379
import json from urllib.parse import urlencode, parse_qsl def pref_custom_id(custom_id: str, data: dict): """ Convert dict to string. Args: custom_id (str): Name of custom_id. data (dict): Data you want to convert. Raises: ValueError: Data can not contain '__'. Returns: ...
11467410
from __future__ import absolute_import import logging from abc import ABCMeta, abstractmethod from collections import Iterable import six from frontera.core import models from frontera.core.components import Backend, DistributedBackend, Middleware, CanonicalSolver from frontera.exceptions import NotConfigured from f...
11467413
from random import expovariate from statistics import mean from math import inf as Infinity # Parameters lamda = 1.3 # Arrival rate (Lambda) mu = 2.0 # Departure rate (Mu) Num_Pkts = 100000 # Number of Packets to be simulated count = 0 # Count number of simulated packets clock = 0 N = 0 ...