text
stringlengths
3.07k
12.6k
import asyncio import json import logging import websockets import random import ssl import argparse logging.basicConfig() logging.getLogger().setLevel(logging.INFO) ''' need to handle: - joining the game - when they load into the room URL, they'll open a websocket - on first connection, we can assign ra...
# Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the ...
# -*- coding: utf-8 -*- import pandas as pd import numpy as np import math import sys, getopt from datetime import datetime, timedelta import matplotlib.pyplot as plt import src.utils.func_utils as func_utils # Import classes from src.classes.myCerebro import MyCerebro from src.classes.myAnalyzer import MyAnalyzer f...
""" Finite Discrete Random Variables - Prebuilt variable types Contains ======== FiniteRV DiscreteUniform Die Bernoulli Coin Binomial Hypergeometric """ from sympy.stats.frv import (SingleFinitePSpace, SingleFiniteDistribution) from sympy import (S, sympify, Rational, binomial, cacheit, Symbol, Integer, Dict,...
from django.core.exceptions import ImproperlyConfigured from django.core.paginator import InvalidPage, Paginator from django.db.models.query import QuerySet from django.http import Http404 from django.utils.translation import gettext as _ from django.views.generic.base import ContextMixin, TemplateResponseMixin, View ...
from __future__ import annotations import asyncio import logging import time import traceback from functools import wraps from typing import Any, Awaitable, Callable from aiogram import Bot, Dispatcher, exceptions from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.types.inline_keyboard import I...
import imutils #pip3 install imutils import time import cv2 #sudo apt install opencv-data opencv-doc python-opencv && pip3 install opencv-contrib-python from rtlsdr import RtlSdr # pip3 install pyrtlsdr import scipy.signal import numpy as np import matplotlib.pyplot as plt from scipy.ndimage.filters import gaussian_fil...
import tensorflow as tf import numpy as np from tensorflow.contrib.layers.python.layers import layers from tensorflow.python.layers import base from tensorflow.python.ops import variable_scope from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.ops im...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2016 Red Hat, Inc. # # This file is part of Ansible # # Ansible 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 #...
#!/usr/bin/env python3 import math import sys class Bingo: """ Stores the loaded state of a sequence of called numbers and a collection of bingo boards and supports checking for multiple win conditions for this game of bingo. """ def __init__(self, input_file): # Read the called numbe...
'''A set of strategies for retaining peaks following deconvolution to recover from low quality spectra. These methods are not recommended for use on spectra where most ions are multiply charged. These objects are meant to be provided to :func:`~.deconvolut_peaks`'s `retention_strategy` argument, which will take care o...
import haiku as hk import jax.numpy as jnp import jax from src.model.embeddings import Embedding class TransformerBlock(hk.Module): def __init__(self, config): super().__init__() self.config = config def __call__(self, x, mask, training=False, is_autoregressive=False): attention_...
import logging import numpy as np import torch from torch import optim from torch.nn import functional as F from torch.utils.data import Dataset from madminer.utils.ml import losses logger = logging.getLogger(__name__) def get_activation_function(activation): if activation == "relu": return torch.relu...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Code are based on # https://github.com/facebookresearch/detectron2/blob/master/detectron2/engine/launch.py # Copyright (c) Facebook, Inc. and its affiliates. # Copyright (c) Megvii, Inc. and its affiliates. import os import subprocess import sys import time fr...
# -*- coding: utf-8 -*- """ thai_time() - Spell out time to Thai words """ from datetime import datetime, time from typing import Union from pythainlp.util.numtoword import num_to_thaiword _TIME_FORMAT_WITH_SEC = "%H:%M:%S" _TIME_FORMAT_WITHOUT_SEC = "%H:%M" def _format_6h(h: int) -> str: """ Thai time (6-h...
from astropy.io import fits import numpy as np import astropy.units as u import pkg_resources # From https://heasarc.gsfc.nasa.gov/docs/software/fitsio/c/c_user/node20.html # Codes for the data type of binary table columns and/or for the # data type of variables when reading or writing keywords or data: # ...
from abc import ABC, abstractmethod from typing import List, Union from .text import Text def _combine_regex(*regexes: str) -> str: """Combine a number of regexes in to a single regex. Returns: str: New regex with all regexes ORed together. """ return "|".join(regexes) class Highlighter(AB...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** 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...
# Copyright (c) 2018-present, Baidu, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
import numpy as np import pandas as pd from tqdm import tqdm def perturb_trace(traces, perturbations, highlight=False): """ Perturb packet trace(s) according to the given perturbation(s). Not support multiple traces and multiple perturbations at the same time. Parameters ---------- traces : a...
__author__ = 'NarasMG' import peewee, os from iscii2utf8 import * conn = peewee.SqliteDatabase(os.getcwd() + '\WordsData.db', pragmas={'journal_mode': 'wal','cache_size': -1024 * 64}) cursor = conn.cursor() rowcursor = conn.cursor() maxrows = 5 mypar = Parser() mypar.set_script(1) def flatMap(f, li): mapped = map...
"""Transform a roidb into a trainable roidb by adding a bunch of metadata.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import datasets import numpy as np from model.utils.config import cfg from datasets.factory import get_imdb import PIL import pdb ...
# license: Copyright (C) 2018 NVIDIA Corporation. All rights reserved. # Licensed under the CC BY-NC-SA 4.0 license # (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). # utility functions import numpy as np import cv2 import pdb import os, json, glob import pickle C = 0.00029979245...
import numpy as np import torch import torch.nn as nn from torch import hub from . import vggish_input, vggish_params class VGG(nn.Module): def __init__(self, features): super(VGG, self).__init__() self.features = features self.embeddings = nn.Sequential( nn.Linear(512 * 4 * 6...
from core.registration.static.models import StaticReg import hashlib # This doesn't work for IPv6... yet def render_statements(statements, **kwargs): return _render_kv(statements, **kwargs) def render_options(options, **kwargs): return _render_kv(options, type_='option', **kwargs) def _render_kv(kvs, ty...
""" This module provides MAU metrics retrieval functionality """ from __future__ import absolute_import from datetime import datetime, timedelta from django.utils.timezone import utc from figures.compat import RELEASE_LINE from figures.models import CourseMauMetrics, SiteMauMetrics from figures.sites import ( ge...
import torch.nn as nn from torchvision import models import os import torchvision.transforms as transforms from torch.autograd import Variable import torch import numpy as np import cv2 import matplotlib.pyplot as plt ''' resnet-18 layer3--->thre=0.005 resnet-18 layer2--->thre=0.01 resnet-18 layer1--->thre=0.02 ''' ...
import numpy as np from typing import List, NamedTuple, Optional, Sequence from abc import ABC, abstractmethod from mujoco_maze.maze_env_utils import MazeCell def euc_dist(pos1, pos2): return np.linalg.norm(np.array(pos1) - np.array(pos2)) class Rgb(NamedTuple): red: float green: float blue: float ...
from typing import Optional import numpy as np import pytest import scipy.sparse as sps from irspack.dataset.movielens import MovieLens100KDataManager from irspack.split import ( UserTrainTestInteractionPair, split_dataframe_partial_user_holdout, ) RNS = np.random.RandomState(0) df = MovieLens100KDataManage...
from os.path import isfile from struct import unpack from typing import List class WarpMarker: def __init__(self, seconds : float, beats : float): self.seconds = seconds self.beats = beats def __repr__(self): return "WarpMarker(seconds={0},beats={1})".format(self.seconds, self.beats...
# 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, software # distrib...
from __future__ import absolute_import from builtins import object import testscenarios import testtools from . import fake_neutron from vnc_openstack.neutron_plugin_db import DBInterface load_tests = testscenarios.load_tests_apply_scenarios class FakeRouteTable(object): def __init__(self, prefix, next_hop): ...
# Copyright 2019 The Cirq Developers # # 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 ...
from __future__ import absolute_import from rest_framework import serializers from rest_framework.exceptions import PermissionDenied from rest_framework.response import Response from sentry.api.base import DocSection from sentry.api.bases.organization import OrganizationReleasesBaseEndpoint from sentry.api.exceptions...
from __future__ import annotations import re from typing import Any, Dict, List, Type, Union # Logical arrow type specs, for reference # (nb. the pyarrow api does not correspond directly to these) # # Null, # Int, # FloatingPoint, # Binary, # Utf8, # Bool, # Decimal, # Date, # Time, # Timestamp, # Interval, # List, #...
import parasail import numpy as np import operator __all__ = ['compute_many', 'compute_many_rect', 'nw_metric', 'nw_hamming_metric', 'np_subst_metric', 'str_subst_metric'] def compute_many(indices, metric, seqs, dtype, **kwargs): return np.array([metric(seqs...
''' keeps track of key-value pairs in different ways: - counts them (to count the number of logins, e.g.) - optionally stores a set of values (the used robots, e.g.) - optionally stores a list of values (the sequence of actions executed, e.g.) - optionally closes a key (makes sense to collect still opened sessions, e.g...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (C) 2014 Midokura SARL # 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.or...
import krpc import time import math as ma import numpy as np conn = krpc.connect(name='Mission Control') KSC = conn.space_center vessel = KSC.active_vessel print("") print(f"Mission Control is online!") vo = vessel.orbit vc = vessel.control ap = vessel.auto_pilot v_ref = vessel.reference_frame s_ref = vessel.surface_...
# License: BSD 3 clause import matplotlib.pyplot as plt import numpy as np from numpy.random import default_rng from tqdm import tqdm from scipy import stats import statsmodels.api as sm # Homogeneous Poisson Process def get_residuals_k_hpoisson(d, k, mu_k, list_times): residuals_k = mu_k*(list...
# # Copyright (c) 2021 Airbyte, Inc., all rights reserved. # import csv from abc import ABC from typing import Any, Iterable, List, Mapping, MutableMapping, Optional, Tuple from datetime import date, datetime, timedelta from airbyte_cdk.sources.streams.http.auth import NoAuth from typing import Any, Callable, Dict, I...
# -*- coding: utf-8 -*- r""" SageMath version and banner info """ #***************************************************************************** # Copyright (C) 2005 <NAME> <<EMAIL>> # # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation; either v...
""" Mock infrastructure for testing ModelManagers. """ import os import tempfile import shutil from galaxy.web import security from galaxy import objectstore from galaxy import model from galaxy.datatypes import registry from galaxy.model import mapping from galaxy.util.bunch import Bunch from galaxy.managers import ...
""" Copyright (C) Microsoft Corporation. All rights reserved.​ ​ Microsoft Corporation (“Microsoft”) grants you a nonexclusive, perpetual, royalty-free right to use, copy, and modify the software code provided by us ("Software Code"). You may not sublicense the Software Code or any use of it (except to your affiliates...
#!/usr/bin/env python3 """ Backend for mybobalist. """ import json import logging from flask import Flask from flask import g from flask import redirect from flask import render_template from flask import request from flask import send_from_directory from flask import url_for from bson.json_util import dumps from pym...
#!/usr/bin/env python # # # compute_gc.py # Compute GC and coverage model for gen_reads.py # # Takes output file from bedtools genomecov to generate GC/coverage model # # Usage: python compute_gc.py -i input.genomecov -r reference.fa -o output_prefix # # # Python 3 ready import time import argparse import nump...
import subprocess import httpx import re from prompt_toolkit.formatted_text import HTML from prompt_toolkit.shortcuts import button_dialog from ethwizard.platforms.ubuntu.common import ( log, save_state, quit_app, get_systemd_service_details ) from ethwizard.constants import ( CTX_SELECTED_EXECUT...
# # SPDX-License-Identifier: GPL-2.0-only # from __future__ import unicode_literals from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator from django.utils.encoding import force_text from orm.models import Project, ProjectLayer, ProjectVariable, ProjectTarget, Build, Laye...
import pytest from aiohttp.test_utils import make_mocked_coro @pytest.mark.parametrize("ready", [True, False]) @pytest.mark.parametrize("error", [None, "400", "403", "404"]) async def test_get(ready, error, mocker, snapshot, spawn_client, static_time, resp_is): client = await spawn_client(authorize=True) doc...
import argparse from RandomGenerators import * from RandomSequencesAnalyzers import LehmersUniformSequenceAnalyzer, RandomSequenceAnalyzer import matplotlib.pyplot as plt def get_lehmers_generator(arguments_parser): arguments_parser.add_argument('-a', action='store', type=int, required=True, help='value of...
import os import sys import numpy as np import torch from torch.utils import data from models.comboptnet import ilp_solver from utils.constraint_generation import sample_constraints from utils.utils import compute_normalized_solution, save_pickle, load_pickle, AvgMeters, check_equal_ys, \ solve_unconstrained, loa...
import datetime import tdclient import jinja2 import six from six.moves import urllib from .result import ResultProxy import logging logger = logging.getLogger(__name__) class NotFoundError(Exception): pass class Query(object): def __init__(self, context, database=None, query=None, source=None, variables=No...
#!/usr/bin/env python3 import bnet import json import logging import sys IGNORE_MOUNT_SPELLIDS = [ # Never actually added 10788, # Leopard https://www.wowhead.com/item=8633 10790, # Tiger https://www.wowhead.com/item=8630 61289, # Borrowed Broom https://www.wowhead.com/item=44604 123160, #...
#!/usr/bin/env python # coding: utf-8 import re import os import sys import numpy as np import pandas as pd import xml.dom.minidom import matplotlib.pyplot as plt from multicellds import MultiCellDS pd.options.mode.chained_assignment = None def get_timeserie_mean(mcds, filter_alive=True): time = [] values =...
import random from measure import Measure import measurements from decimal import Decimal from operator import attrgetter, itemgetter import math def initial_population(options): population_count = options['genetic']['population'] num_measures = options['genetic']['num_measures'] rest_chance = options['genetic']['...
from transformers.tokenization_bert import whitespace_tokenize from farm.visual.ascii.images import SAMPLE import logging logger = logging.getLogger(__name__) class SampleBasket: """ An object that contains one source text and the one or more samples that will be processed. This is needed for tasks like que...
import torch import torch.nn as nn from torch.distributions.normal import Normal import probtorch import math class Enc_coor(nn.Module): """ encoder of the digit positions """ def __init__(self, num_pixels, num_hidden, z_where_dim): super(self.__class__, self).__init__() self.enc_hidden...
# -*- coding: utf-8 -*- import datetime from unittest import skip from django.test import TestCase from django.utils import translation from indicators.models import Indicator from tola.test.base_classes import TestBase from factories.workflow_models import SiteProfileFactory, ProgramFactory from factories.indicators...
""" MobileNetV2 implementation used in <Knowledge Distillation via Route Constrained Optimization> """ import torch import torch.nn as nn import math __all__ = ['mobilenetv2_T_w', 'mobile_half'] BN = None def conv_bn(inp, oup, stride): return nn.Sequential( nn.Conv2d(inp, oup, 3, stride, 1, bias=False)...
"""GitHub related utils. """ from pathlib import Path import logging import urllib.request import shutil import re import requests from packaging.version import parse from packaging.specifiers import SpecifierSet from .utils import ( option_version, option_pip_bundle, add_subparser, run_cmd, ) def _ad...
""" This file contains an example search engine that will search the inverted index that we build as part of our assignments in units 3 and 5. """ import sys,os,re import math import sqlite3 import time # use simple dictionnary data structures in Python to maintain lists with hash keys docs = {} resultslist...
""" This module provides - basic crud functionality within alembic migration scripts, - advanced helpers for special tasks, like merging sources. .. note:: Using the functionality provided in this module is not possible for Alembic scripts supposed to be run in `offline mode <http://alembic.readthedocs.o...
import collections import pprint import copy class Node: def __init__(self, id_, data=None): self.id_ = id_ self.data = data def __eq__(self, other): return self.id_ == other.id_ def __hash__(self): return hash(self.id_) def __repr__(self): return ...
#!/usr/bin/env python # # Copyright 2012 eNovance <<EMAIL>> # # Author: <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 # # http://www.apache.org/licenses/LICENSE-2.0 # # ...
import sys import os.path import pygame import utils from apple import Apple from surface import Surface from snake import Snake from colors import * def home(game_values): """ Home page of the game / GUI """ width, height = rows * blocksize, columns * blocksize # icon size constants i_width, ...
import decimal import itertools import operator from typing import Any, Iterable, List, Tuple import eth_abi from tilapia.lib.coin import data as coin_data from tilapia.lib.coin import manager as coin_manager from tilapia.lib.conf import settings from tilapia.lib.price import data, interfaces from tilapia.lib.provide...
#Brain masking tool #Developed by <NAME> import argparse import os import cv2 import sys import glob import numpy as np from tqdm import tqdm from medpy.io import load, save from models.model import Unet from skimage.transform import resize from skimage.measure import label from skimage.morphology import binary_closin...
from kiri.models import Vectorisation, QA, Summarisation, Emotion, Classification import numpy as np import torch qa_example = { "q1": "Where does Sally live?", "q2": "How long has Sally lived in London?", "q2_conv": "How long has she lived there?", "q3": "Where did Sally live prior to London?", "q...
import hashlib import random from ..compat import compat_str from .common import InfoExtractor from ..utils import ( clean_html, int_or_none, try_get, ) class JamendoIE(InfoExtractor): _VALID_URL = r'''(?x) https?:// (?: licensin...
# Copyright (c) 2018 Mycroft AI, Inc. # # This file is part of Mycroft Skills Manager # (see https://github.com/MatthewScholefield/mycroft-light). # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional inf...
from inspect import signature from sequence_transfer.magic_transfer import MagicTransfer from typing import List, Tuple, Optional, Iterator from sequence_transfer.sequence import SequenceContext, ContextualizedSequence from itertools import groupby, filterfalse from sequence_transfer.sequence_transfer import Sequence...
# =============================================================================== # Copyright 2016 dgketchum # # 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...
#!/usr/bin/env python import sys class CType: def __init__(self, name): self.name = name def __str__(self): return self.name class GMPAPI: def __init__(self, ret_ty, name, *params, **kw): out = kw.get('out', [0]) inout = kw.get('inout', []) mixed = kw.get('mixed...
import logging from collections import defaultdict from django.views.decorators.http import condition from django.utils.decorators import method_decorator from django.http import Http404 from django.db.models import Count from django.forms.models import model_to_dict from django.http import Http404 from django.core.e...
import argparse from datetime import datetime import signal import json import subprocess import sys import time instances = {} instance_types = { ("v100", 1): "p3.2xlarge", ("v100", 4): "p3.8xlarge", ("v100", 8): "p3.16xlarge", ("k80", 1): "p2.xlarge", ("k80", 8): "p2.8xlarge", ("k80", 16): "...
# -*- coding: utf-8 -*- # @Author: 红白黑 # @Date: 2021-08-03 17:11:44 # @Last Modified by: 红白黑 # @Last Modified time: 2021-08-03 19:50:59 import cv2 import numpy as np from numpy.lib.arraysetops import isin def get_evaluate_result(inputs): '''获取评估的结果表示(inputs来自模型预测的输出) Args: inp...
# -*- 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 numpy as np from itertools import count import matplotlib from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from easy21 import Easy21 EPSILON = 0.05 GAMMA = 1 def feature_id(s, a): sf = [] for i, (l, r) in enumerate(zip(range(1, 8, 3), range(4, 11, 3))): if s[1] >= l and s[1] <= ...
import re from functools import cached_property from serde import deserialize, serde, Untagged, field, to_dict from dataclasses import dataclass import dataclasses from chris.common.types import ( PluginName, PluginVersion, ImageTag, ChrisURL, PluginUrl, ChrisUsername, ) from chris.cube.types im...
# Copyright (c) 2019. Partners HealthCare and other members of # Forome Association # # Developed by <NAME> based on contributions by <NAME>, # <NAME>, <NAME> and other members of Division of # Genetics, Brigham and Women's Hospital # # Licensed under the Apache License, Version 2.0 (the "License"); # you may no...
# # Copyright (C) 2007 <NAME> # All rights reserved. # For license terms see the file COPYING.txt. # import logging from roundup import hyperdb from roundup.exceptions import Unauthorised, UsageError from roundup.date import Date, Range, Interval from roundup import actions from roundup.anypy import xmlrpc_ SimpleXMLR...
#!/usr/bin/env python ############################################## # The MIT License (MIT) # Copyright (c) 2017 <NAME> # see LICENSE for full details ############################################## from __future__ import print_function, division from pyxl320 import ServoSerial from pyxl320.Packet import le, makeRead...
#!/usr/bin/python # create a bunch of job scripts from config import config from subprocess import call import numpy as np import os import socket import getpass import datetime as dt # ====== MODIFY ONLY THE CODE BETWEEN THESE LINES ====== try: os.stat(config['resultsdir']) except: os.makedirs(config['resu...
# Dieses Script überprüft welche Zelle die meiste Spannung besitzt und welche Spannung diese hat # Danach wird der maximale Ladestrom des Victron Systems eingestellt. # Dies hilft mit einer höhreren Strom zu laden und dann wenn der Akku nahezuvoll ist diesen zu verringern. # Auch die Spannung wird herrabgesetzt. impo...
# SPDX-License-Identifier: MIT # # Copyright (c) 2021 The Anvil Extras project team members listed at # https://github.com/anvilistas/anvil-extras/graphs/contributors # # This software is published at https://github.com/anvilistas/anvil-extras import anvil.js as _js from anvil import HtmlPanel as _HtmlPanel from anvil...
import os.path import sys import traceback import requests from file_list import ReleaseFile from util import retry_multi, GLOBAL_TIMEOUT metadata = { 'type': 'engine', 'title': 'FSO', 'notes': '', 'banner': 'https://fsnebula.org/storage/0d/e7/bf64bcdea9a9c115969cfb784e1ca457d24a7c2da4fc6f213521c3bb6...
import random from itertools import product import torch class CartesianSampler: """Random subset sampling from {0, 1, ..., M-1} X {0, 1, ..., L-2} where X is Cartesian product. Attributes: M: number of trajectories. L: trajectory length. batch_size: input batch size for training the...
#!/usr/bin/env python """A keyword index of client machines. An index of client machines, associating likely identifiers to client IDs. """ from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import functools import operator from future.builtins import map f...
import PySimpleGUI as sg import src.PDFCreator as PDFCreator import src.NumberEngine as NumberEngine import src.Language_manager as Language_manager from src.exceptions import ParseConfigException def get_layout(language_manager): ''' The method sets layout to return. :param Language_manager language_manager:...
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # pyre-strict import argparse import json import logging import os import subprocess import tempfile import threading from pathlib import P...
# -*- coding: utf-8 -*- ############################################################# # IMPORT # ############################################################# from PyQt5 import QtCore, QtGui, QtWidgets import os import io from PIL.ImageQt import ImageQt, Ima...
from dcaboostutils import DATA_MAIN_API_KEY, DATA_MAIN_API_SECRET, DATA_SUB_API_KEY, DATA_SUB_API_SECRET, ROUND_DOWN, Decimal, json, time, query, create_pair, amount_format, get_current_subaccount, send_message LOCK_QUERY_ACTIVE = 0 MASTER_ACCOUNT = "MASTER" SUB_ACCOUNT = "SUBACCOUNT" CRYPTO_CURRENCY_KEY = "CRYPTO_C...
from __future__ import print_function import tensorflow as tf from tensorflow.python.ops import variable_scope as vs from tensorflow.python.ops import array_ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops.math_ops import tanh from tensorflow.python.util import nest from tensorflow.contrib.distr...
import requests import io import os import json import pathlib import pathvalidate import time from typing import List, Union from pprint import pprint chaps = ["0D16B704A478D3FB9C33DC5901307461"] URL_BASE = "https://www.xuetangx.com" class SessionInfo: def __init__(self, session_id: str, sign_id: str): ...
import os import numpy as np import pandas as pd from sklearn import linear_model def allign_alleles(df): """Look for reversed alleles and inverts the z-score for one of them. Here, we take advantage of numpy's vectorized functions for performance. """ d = {'A': 0, 'C': 1, 'G': 2, 'T': 3} a = [] ...
""" Script to preprocess the JSON data retrieved from the API How it's used: * Reads "tweets.json" files in directories specified by 'root_dir' and 'directories' variables * Loads each JSON file into a dataframe * Drops unwanted columns * Renames columns to more user-friendly versions * Drops duplicate rows * Extracts...
""" Functions used in create-documentation notebook""" import os import pandas as pd import numpy as np button = ":raw-html:`&#10063;`" csv_header = "\n{}`\n" csv_entry = ".. csv-table::" csv_columns = " :header: {}{}\n" csv_delim = " :delim: |" csv_row = " {} | {}" csv_singlerow = " {}" bool_e...
# -*- coding: utf-8 -*- from django.contrib.postgres import fields from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from osf.models.base import BaseModel, ObjectIDMixin from osf.models.licenses import NodeLicense from osf.models.subject import Subject fro...
#!/usr/bin/env python import argparse import sys parser = argparse.ArgumentParser(description="") parser.add_argument("--bam", "-s", help="input bam file + index mapping contigs to location wehre original PSVs were called") parser.add_argument("--psvs", "-p", nargs='+', help="List of vcf files describing the different...
import bsddb from num2words import num2words """ A class for determining whether one entity entails the other. We use three resources: 1) Dictionary created by training HypeNET on a subset of two datasets: BLESS (Baroni and Lenci, 2011) and K&H+N (Necsulescu et al., 2015), using only hypernyms fro...