input
stringlengths
2.65k
237k
output
stringclasses
1 value
dy = self.map_canvas.yview()[0] * len(self.tilemap) x = max(int(dx + event.x / 64), 0) y = max(int(dy + event.y / 64), 0) # Regular base-layer tile mode if view_mode.get() == 0: map_of_tiles = list(self.tilemap) self.map_canvas.create_image((32 + 64 * x, 32 + 64 * y), image=App.tiles[selected_image.get()]) row =...
<filename>models/tripletext2seq.py from __future__ import print_function import time import math import pickle import tensorflow as tf from tensorflow.python.layers.core import Dense import numpy as np class TripleText2SeqModel(): """ This Model is called triples sequences to sequence model model takes a single tr...
not include PyPI. argv.extend( [ "--no-pypi", *(f"--index={index}" for index in python_repos.indexes), *(f"--repo={repo}" for repo in python_repos.repos), "--resolver-version", "pip-2020-resolver", ] ) python: PythonExecutable | None = None # NB: If `--platform` is specified, this signals that the PEX shou...
custom radius", default = False) fit = bpy.props.EnumProperty(name = "Method", items = (("best", "Best fit", "Non-linear least squares"), ("inside", "Fit inside","Only move vertices towards the center")), description = "Method used for fitting a circle to the vertices", default = 'best') flatten = bpy.props.Bool...
Creator) sendMention(msg.to, msg._from, "","Success Invite AllGroup") else: sendMention(msg.to, msg._from, "","Limit boss") elif text.lower() == 'kiinviteme': if msg._from in admin: gid = ki.getGroupIdsJoined() for i in gid: ki.inviteIntoGroup(i, Creator) sendMention(msg.to, msg._from, "","Success Invite AllGr...
box. """ @staticmethod def box_type_default(): box_type = BoxType.objects \ .filter(box_type_code__istartswith='ev') \ .first() if box_type: return box_type box_type = BoxType.objects.first() if box_type: return box_type return None box_type_help_text = 'Type of box with this number.' box_type = models.F...
'C6H14O8P', 'g3pi': 'C9H18O11P', 'g3pi_e': 'C9H18O11P', 'g3pi_p': 'C9H18O11P', 'g3ps': 'C6H13NO8P', 'g3ps_e': 'C6H13NO8P', 'g3ps_p': 'C6H13NO8P', 'g6p': 'C6H11O9P', 'g6p_e': 'C6H11O9P', 'g6p_p': 'C6H11O9P', 'gagicolipa': 'C157H271N2O84P4', 'gal': 'C6H12O6', 'gal1p': 'C6H11O9P', 'gal1p_e': 'C6H11O9P', 'gal...
from torch.cuda.amp import GradScaler from utils.loss_accumulator import LossAccumulator from torch.nn import Module import logging from trainer.losses import create_loss import torch from collections import OrderedDict from trainer.inject import create_injector from utils.util import recursively_detach, opt_get logg...
<reponame>SobolGaming/Trivianator import json import re from django.db import models from django.core.exceptions import ValidationError, ImproperlyConfigured from django.core.validators import MaxValueValidator, validate_comma_separated_integer_list from django.utils.timezone import now from django.conf import settings...
[종목명, 단축코드, 확장코드, ETF구분, 상한가, 하한가, 전일가, 주문수량단위, 기준가, 구분, 증권그룹, 기업인수목적회사여부] result.append(lst) columns = ['종목명', '단축코드', '확장코드', 'ETF구분', '상한가', '하한가', '전일가', '주문수량단위', '기준가', '구분', '증권그룹', '기업인수목적회사여부'] df = DataFrame(data=result, columns=columns) if self.parent != None: self.parent.OnReceiveData(szTrCode, [df])...
# a_i^{(1)} = x_i # Compute z values at second layer # zSup2 (i.e., z^{(2)}) is the matrix of z values at layer 2 # zSup2 = W^{(1)} x + b^{(1)} zSup2 = W1.dot(data) + numpy.tile(b1, (m, 1)).transpose() # Compute activations at second layer by mapping z^{(2)} to sigmoid(z^{(2)}) aSup2 = sigmoid(zSup2) #Comput...
0: self.ListSize = 0 return self.ListSize if self.ItemSize == 0: self.ListSize = self.GetInterOffset(len(self.RawDataList) - 1) + len(self.RawDataList[len(self.RawDataList)-1]) else: for Datas in self.RawDataList: if type(Datas) in (list, tuple): self.ListSize += len(Datas) * self.ItemSize else: self.ListSize...
PlotSnapList, simulation_norm, mean_galaxy_sfr, std_galaxy_sfr, mean_galaxy_ssfr, std_galaxy_ssfr, N_galaxy, model_tags, output_tag): """ Plots the specific star formation rate (sSFR) as a function of stellar mass. Parallel compatible. Accepts 3D arrays of the sSFR binned into Stellar Mass bins. Mass units ...
from __future__ import division from itertools import chain from numpy import inf from span.chunking.utils.fixed_step import fixed_step_chunker import random def fragment_list(tot_len, n_frags): """ A little function to help trouble shoot list_chunker. Creates a list of lists by randomly fragmenting range(tot_len)...
= True break if not found: res.append({ # 轮次 'round_financing_id': round_financing_and_foundation_entity.round_financing_id.id, 'round_financing_name': round_financing_and_foundation_entity.round_financing_id.name, 'foundation_names': [{ 'foundation_id': round_financing_and_foundation_entity.found...
<reponame>PeterJackNaylor/segmentation_net #!/usr/bin/env python # -*- coding: utf-8 -*- """segnet package file tf_record Segmentation_base_class -> SegmentationInput -> SegmentationCompile -> SegmentationSummaries -> Segmentation_model_utils -> Segmentation_train """ from datetime import datetime from tqdm import...
is sex-stratified). """ file_base = 'pananc_31063_pcgc_covariates' file_base = file_base + ('_nosexcovar' if sex_specific else '') suffix = '.tsv' if dictout: out = {anc: anc + '_' + file_base + suffix for anc in ancestries} else: out = [anc + '_' + file_base + suffix for anc in ancestries] return out def g...
275: 'podoon', 276: 'life_time_fitness', 277: 'falco_e_motors', # Falco eMotors Inc. 5759: 'actigraphcorp', }, ), 'mesg_count': FieldType( name='mesg_count', base_type=BASE_TYPES[0x00], # enum values={ 0: 'num_per_file', 1: 'max_per_file', 2: 'max_per_file_type', }, ), 'mesg_num': FieldType( name='mesg_...
# Normal-exponential using out-of-band probes # normex: negative control probes # noob: ‘out-of-band’ Infinium I probes # Lib import logging import numpy as np import pandas as pd from statsmodels import robust from scipy.stats import norm, lognorm # App from ..models import ControlType, ArrayType from ..models.sketch...
<filename>rbs_m2/solver/solver.py import argparse import csv import re import sys, os import struct from attr import dataclass from abc import abstractmethod from typing import Iterator, List, Tuple, Set #from skyfield.sgp4lib import EarthSatellite from skyfield.api import load, Topos, EarthSatellite from randomize_c...
(go_trials, nogo_trials) = (0, 0) for lever in lever_on: if eventcode[lever + 1] in ('LightOn1', 'LightOn2'): nogo_trials += 1 else: go_trials += 1 return go_trials, nogo_trials def num_switch_trials(eventcode): """ :param eventcode: list of event codes from operant conditioning file :return: number of lar...
# MIT license # <EMAIL> import OpenGL from OpenGL.GL import * from OpenGL.GLU import * from .math import * from .tool import * from .qt import * from . import gl import time import sys class Camera(object): def __init__(self, owner): self.owner = owner # frame/pivot self.frame = Rigid3() self.frame.cente...
<= 27: return 1 else: if f5 <= 26: if f6 <= 20: if f6 <= 5: if f4 <= 4: return 3 else: return 4 else: return 3 else: return 3 else: return 3 else: if f4 <= 17: if f4 <= 8: if f4 <= 7: if f5 <= 27: if f1 <= 28: return 1 else: return 6 else: return 5 else: if f5 <= 33: return 4 else: return...
return default return "Default" row = cloud_utils.lower_key(db.get_row_dict("tblEntities", {"id": dbid}, order="ORDER BY id LIMIT 1")) if row: return row["name"] else: return "None" ## "external_address_type": row["externalipaddresstype"], # "external_address": row["externalipaddress"], # "external_address_nat"...
<gh_stars>0 import pandas as pd import os, sys, inspect import xlsxwriter from math import floor, log10, isnan # below 3 lines add the parent directory to the path, so that SQL_functions can be found. currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(curr...
self.solver.solve(N, self.solver.dynamics_local, x0=x0, u0=u0) self.tti, self.F, self.f = ret return ret def compute_tti(self, x): """ Returns time to impact in seconds """ return self.dynamics_global.get_time_to_impact(x)[0] def run(self, x0): """ Execute the controller for a given system The control...
<filename>src/crl/devutils/tasks.py from __future__ import print_function import os import shutil import sys from collections import namedtuple from contextlib import contextmanager from invoke import task from invoke.main import program from crl.devutils import ( versionhandler, githandler, packagehandler, setupha...
"""Base implementation of event loop. The event loop can be broken up into a multiplexer (the part responsible for notifying us of IO events) and the event loop proper, which wraps a multiplexer with functionality for scheduling callbacks, immediately or at a given time in the future. Whenever a public API takes a ca...
<reponame>geoboxers/thatsDEM2<filename>thatsDEM2/array_geometry.py # Original work Copyright (c) 2015, Danish Geodata Agency <<EMAIL>> # Modified work Copyright (c) 2015-2016, Geoboxers <<EMAIL>> # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, ...
import numpy as np import matplotlib import matplotlib.pyplot as plt import skimage.io as io import skimage.filters as flt #%matplotlib inline # since we can't use imports import numpy as np import scipy.ndimage.filters as flt import warnings from sklearn.mixture import GaussianMixture as GM from scipy import interpo...
"fair_share:TAGS TIME %s"%(time.time()-start_t, )) start_t=time.time() Trace.trace(self.trace_level+4, 'fair_share:postponed rqs %s'%(self.postponed_requests)) if len(tags) > 1: for key in tags: if self.pending_work.get_sg(key) in self.postponed_requests.sg_list.keys(): pass # request for this SG is already in po...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated Tue Oct 10 00:42:20 2017 by generateDS.py version 2.28b. # Python 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609] # # Command line options: # ('--no-process-includes', '') # ('-o', 'esociallib/v2_04/evtAltContratual.py') # # Command line argument...
<reponame>codegrande/hammer import boto3 import json import logging import configparser import re from functools import lru_cache from datetime import datetime, timedelta, timezone class Config(object): """ Basic class do deal with hammer configuration. It takes uses local file to construct config object. """ ...
import os import numpy as np import logging import h5py from ..builder_utils import mpi_rank, mpi_size, barrier from .edge_props_table import EdgeTypesTableMPI logger = logging.getLogger(__name__) class EdgesCollatorSingular(object): """Used to collect all the edges data-tables created and stored in the EdgeTypes...
<filename>compute_xlmetrics.py #!/usr/bin/env python import errno import os import sys import subprocess import json import argparse def mkdir_p(path): """ mkdir -p """ try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def listdir_full_path...
'v_10'), ('v_10', 't_2'), ('t_2', 'v_10'), ('v_7', 't_3'), ('c_1', 't_3'), ('v_8', 't_4')}, '>': {('c_1', 'v_5'), ('t_3', 'v_8'), ('t_3', 'v_9'), ('c_1', 't_4'), ('t_2', 'v_5'), ('t_2', 'v_6'), ('t_3', 'v_10'), ('t_2', 'v_7'), ('c_1', 'v_7'), ('t_4', 'v_8'), ('c_1', 'v_6'), ('t_4', 'v_10'), ('c_1', 't_3'), ('t_2', '...
############################################################################### # # The MIT License (MIT) # # Copyright (c) Crossbar.io Technologies GmbH # # 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 ...
# -*- coding: utf-8 -*- """Classes for interacting with models.""" import logging from datetime import datetime from ._api_object import ApiObject from urllib.parse import urlencode from .error import NotFoundError, ResponseError from typing import Union from time import time as t from time import sleep class Models:...
<filename>src/cnlpt/cnlp_data.py import os from os.path import basename, dirname import time import logging from filelock import FileLock from typing import Callable, Dict, Optional, List, Union, Tuple import numpy as np import torch from torch.utils.data.dataset import Dataset from transformers.data.processors.utils...
entity=None, removed=None, **unknown_fields): ''' entity : Any removed : bool ''' entity_ = entity removed_ = removed # Validate arguments against known Juju API types. if removed_ is not None and not isinstance(removed_, bool): raise Exception("Expected removed_ to be a bool, received: {}".format(type(remove...
may have been deprecated such as 'crs_transform'. Returns: An unstarted Task that exports the image to Drive. """ config = _capture_parameters(locals(), ['image']) config = _prepare_image_export_config(image, config, Task.ExportDestination.ASSET) return _create_export_task(config, Task.Type.EXPORT_IMAGE) # D...
<filename>yapypy/extended_python/grammar.py<gh_stars>0 RBNF = r""" NEWLINE := '' ENDMARKER := '' NAME := '' INDENT := '' DEDENT := '' NUMBER := '' STRING := '' single_input ::= it=NEWLINE | seq=simple_stmt | it=compound_stmt NEWLINE file_input ::= (NEWLINE | seqs<<stmt)* [ENDMARKER] -> mod=Module(sum(seqs or [], []));...
#coding: utf-8 import subprocess, sys, os import threading, time, datetime import logging, argparse import shutil from inter.apkcookpy.lib.apk import APKCook import xml.etree.ElementTree as ET logging.basicConfig(level = logging.INFO, format='%(asctime)s - %(levelname)s [%(filename)s:%(lineno)d]: %(message)s') def ...
<filename>pypsexec/scmr.py # -*- coding: utf-8 -*- # Copyright: (c) 2019, <NAME> (@jborean93) <<EMAIL>> # MIT License (see LICENSE or https://opensource.org/licenses/MIT) import logging import struct import uuid from collections import ( OrderedDict, ) from smbprotocol.connection import ( NtStatus, ) from smbprot...
<reponame>vaMuchenje/Template-Python # # The Template-Python distribution is Copyright (C) <NAME> 2007-2008, # derived from the Perl Template Toolkit Copyright (C) 1996-2007 Andy # Wardley. All Rights Reserved. # # The file "LICENSE" at the top level of this source distribution describes # the terms under which this fi...
# This file was automatically generated by SWIG (http://www.swig.org). # Version 2.0.10 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info if version_info >= (3,0,0): new_instancemethod = lambda func, inst, cls: _IntCurvesF...
the level's random effects covariance Returns ------- Jf: dict of array_like For each level contains the derivative of the cholesky parameters with respect to the covariance Notes ----- Function evaluates the derivative of the cholesky parameterization with respect to the lower triangular componen...
<reponame>msobrevillac/sockeye # Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License # is located at # # http://aws.amazon.com/apache2.0/ # # o...
table table-striped table-bordered " "table-condensed")) @property def name(self): return self.table_name @property def table_link(self): return '<a href="{obj.explore_url}">{obj.table_name}</a>'.format(obj=self) @property def metrics_combo(self): return sorted( [ (m.metric_name, m.verbose_name or m.metr...
<reponame>piyengar/jigsaw-severity<gh_stars>0 #!/usr/bin/env python # coding: utf-8 # In[1]: import os # operating system library import gc # Garbage Collector - module provides the ability to disable the collector, tune the collection frequency, and set debugging options import copy # The assignment operation does ...
<gh_stars>10-100 # -*- coding: utf-8 -*- # Copyright 2022, SERTIT-ICube - France, https://sertit.unistra.fr/ # This file is part of eoreader project # https://github.com/sertit/eoreader # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License....
broker._waitForStable() return self.schemaCache.getClasses(packageName) def getSchema(self, classKey): """ Get the schema for a QMF class """ for broker in self.brokers: broker._waitForStable() return self.schemaCache.getSchema(classKey) def bindPackage(self, packageName): """ Filter object and event callba...
if "transition_y" in slide.overlay_text else "center" text = slide.overlay_text["title"].replace(':', r'\:') # fixed text in the middle if transition_x == "center": x = "(main_w/2-text_w/2)" # scroll from left to right till the middle of the image in half of the duration time elif transition_x == "left-in" or tr...
""" mfcln module. Contains the ModflowCln class. Note that the user can access the ModflowCln class as `flopy.modflow.ModflowCln`. Compatible with USG-Transport Version 1.7.0. which can be downloade from https://www.gsi-net.com/en/software/free-software/modflow-usg.html Additional information for this MODFLOW package...
k_hop: Number of layers for gcnii. lambda_l: The hyperparameter of lambda in the paper. alpha: The hyperparameter of alpha in the paper. dropout: Feature dropout rate. """ def __init__(self, hidden_size, activation=None, lambda_l=0.5, alpha=0.2, k_hop=10, dropout=0.6): super(GCNII, self).__init__() s...
<reponame>hbrunie/cctbx_project from __future__ import absolute_import, division, print_function from iotbx.pdb.atom_selection import selection_string_from_selection from scitbx.array_family import flex from mmtbx.ncs import ncs_search from libtbx.utils import Sorry, null_out import libtbx.phil import iotbx.pdb.hierarc...
from __future__ import print_function import torch import torch.nn as nn import torch.utils.data from torch.autograd import Variable import torch.nn.functional as F import math import numpy as np import pdb import kornia class residualBlock(nn.Module): expansion = 1 def __init__(self, in_channels, n_filters, stride...
#Python 2.7.9 (default, Apr 5 2015, 22:21:35) # full env in environment.yml import sys, os ''' This is a full aggregation of the Pulsar Hunters project, including user weighting. Note it's quite a simple project - basically one Yes/No question - and there is gold-standard data, so the weighting is relatively straigh...
<gh_stars>1-10 ''' Class for transforming a lexed list of tokens into a parse tree for a WoW macro. ''' import re import sys from sys import exit # Macro modules from macro.exceptions import * from macro.logger import logger from macro.util import clean_macro from macro.lex.lexer import GLOBAL_MACRO_TOKENIZER, MacroC...
#!/usr/bin/env python # coding=utf-8 # author=<NAME> """SFTPClone tests.""" # Simply launch me by using nosetests and I'll do the magic. # I require paramiko # Python 2.7 backward compatibility from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals impor...
'''expand the INCA Ecoli model to account for additional metabolites''' query = stage02_isotopomer_query() # get the xml model cobra_model_sbml = '' cobra_model_sbml = query.get_row_modelID_dataStage02IsotopomerModels(model_id_I); # load the model if cobra_model_sbml: if cobra_model_sbml['file_type'] == 'sbml':...
#!/usr/bin/env python # # Copyright 2020 Autodesk # # 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 agre...
<reponame>dbernaciak/bayes-np<gh_stars>1-10 import scipy.stats as st import numpy as np import numba as nb import matplotlib.pyplot as plt from tqdm.auto import tqdm import asyncio import nest_asyncio from nb_stats import * nest_asyncio.apply() class GaussianMixture: def __init__(self, sd, rho, mu=None): """ :par...
a zero form pressed. def plot(self, axis): ''' Finilises the plotting Uses the attribues of the object as set originally and as customised with methods to create a plot of the 2-form. parametes: ------------- axis - matplotlib axis that 0-form will be plotted on ''' # Extract L from the x and y grids Lx ...
'blocking': self.mode = 'blocking' curses.flushinp() return self.__poll_waiting_blocking(0, flag, indent) # change verbosity if k == ord('v'): self.verbose_mode += 1 if self.verbose_mode > 3: self.verbose_mode = 1 do_refresh = True # change duration mode if k == ord('T'): self.duration_mode += 1 if self.du...
<filename>pinkfish/statistics.py """ statistics --------- Calculate trading statistics """ # Use future imports for python 3.0 forward compatibility from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import # Other imports impo...
# Part of the JBEI Quantitative Metabolic Modeling Library (JQMM) # Copyright (c) 2016, The Regents of the University of California. # For licensing details see "license.txt" and "legal.txt". """ All functions to obtain the Toya data and a test suite. This module effectively reproduces all figures in Garcia Martin et a...
FileName in L: MSG.append (" - " + FileName); MSG.append ("-"*80); self.__PRJ.lp (MSG); allsentences = [] ; for FileAddress in L: Sentences , Root , LOCAL_TotalCorpusRootAnalysisResult = self.__PRJ.Preprocessor.ProcessCorpus (FileAddress,DuplicationRemovalPolicy,SkipSentences); allsentences.extend (Sente...
= os.stat(fname) os.chmod(fname, st.st_mode | stat.S_IEXEC) if stage: param = stage.replace('-', '_') option = "stage_" + param dict_ = vars(self.args) if option in dict_: if dict_[option]: print("*"*20) print("Executing ", fname) print("*"*20) os.system("./" + fname) pass def build_nuitkas(self): # i...
"HAK": { "symbol": "HAK", "name": "Shaka", "type": "ERC20", "address": "0x93a7174dafd31d13400cD9fa01f4e5B5BAa00D39", "ens_address": "", "decimals": 18, "website": "https://www.friendsfingers.com", "logo": { "src": "https://www.friendsfingers.com/img/brand-resources/shaka_logo_white.png", "width": "600px", "h...
""" auralib module containing plotting functions and related stuff... Author: <NAME> Created: 20-Jan-2017 Last Mod: 20-Aug-2016 """ import matplotlib.pyplot as plt import matplotlib.patches as mpatches from matplotlib.widgets import MultiCursor import numpy as np def t2xy(d1, d2, d3, norm=True): ...
'Not Found': logger.debug('**%s %s already deleted.' % (kind, name)) else: logger.error(e) raise e def create_and_start_vm_from_iso(params): metadata_name = _get_param('--name', params) network_config = _get_param('--network', params) try: operation_queue = ['virsh dommemstat --period %s --domain %s --config ...
op): bk = self.rtyper.annotator.bookkeeper funcdesc, = s_pbc.descriptions args = simple_args(args_s) with bk.at_position(None): graph = funcdesc.get_graph(args, op) llfn = self.rtyper.getcallable(graph) return inputconst(typeOf(llfn), llfn) class __extend__(pairtype(FunctionRepr, FunctionRepr)): def convert_...
<reponame>tlapusan/DecisionTreeStructure import logging import sys import graphviz import numpy as np import pygraphviz as pgv from matplotlib import pyplot as plt from sklearn import tree as sklearn_tree from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier logging.basicConfig(level=logging.INFO, fo...
<gh_stars>1-10 # -*- coding: utf-8 -*- import sys, os import subprocess import datetime, time import argparse import cairo from math import pi, radians, sin, cos, asin, sqrt from multiprocessing import Process, Queue gpxfile = None output = None parser = argparse.ArgumentParser() parser.add_argument("-g", "--gpx", de...
<reponame>alvarolgn/toolium # -*- coding: utf-8 -*- """ Copyright 2022 Telefónica Investigación y Desarrollo, S.A.U. This file is part of Toolium. 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 h...
#!/usr/bin/python3 # First choice pack and unpack into sqlite # <NAME> 2021 try: import sys except: print("Please install the sys module") print("\tit should be part of the standard python3 distribution") raise try: import struct except: print("Please install the struct module") print("\tit should be part o...
<reponame>wangg12/torchsample import os.path as osp import random import math import numpy as np from collections import Sequence import torch import mmcv import torch as th import torch.nn.functional as F from ..utils import th_random_choice class Compose(object): """Composes several transforms together.""" def ...
"""A set of stream oriented parsers for http requests and responses, inline with the current draft recommendations from the http working group. http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-17 Unlike other libraries, this is for clients, servers and proxies. Missing: comma parsing/header folding """ ...
import collections import json import logging import os import numpy as np import torch from torch.utils.data import TensorDataset, DataLoader from tqdm import tqdm from transformers import AutoTokenizer, AutoModelForSequenceClassification current_script_path = __file__ project_root = os.path.realpath( os.path.join(...
# 100,15,300003 tem=1 for j in range(sequence_length[0]-1): tem*=prob_old[j][input[0][j+1]] tem*=prob_old[j+1][option.dict_size+1] prob_old_prob=tem if sim!=None: similarity_old=similarity(input, input_original,sta_vec,\ id2sen, emb_word, option, similaritymodel)[0] prob_old_prob=prob_old_prob*similarity_old ...
50, "all"), ("Fcst", "T", "SCALAR", 6, 9, 70, "all"), ("Fcst", "T", "SCALAR", 9, 12, 70, "all"), ("Fcst", "MaxT", "SCALAR", "MaxTBegin", "MaxTEnd", 47, ["AboveElev"]), ("Fcst", "MaxT", "SCALAR", "MaxTBegin", "MaxTEnd", 52, ["BelowElev"]), ], "checkStrings": ["Highs 47 to 52"], }, { "name": "Temp_25-30", "co...
{'name': '土默特右旗', 'pid': 96, 'zipcode': 14100}, 1430: {'name': '昆都仑区', 'pid': 96, 'zipcode': 14000}, 1431: {'name': '白云鄂博矿区', 'pid': 96, 'zipcode': 14000}, 1432: {'name': '石拐区', 'pid': 96, 'zipcode': 14000}, 1433: {'name': '达尔罕茂明安联合旗', 'pid': 96, 'zipcode': 14500}, 1434: {'name': '青山区', 'pid': 96, 'zipcode': 14000...
= m.get('enabled') if m.get('remark') is not None: self.remark = m.get('remark') return self class UpdateAlertStrategyResponse(TeaModel): def __init__( self, req_msg_id: str = None, result_code: str = None, result_msg: str = None, ): # 请求唯一ID,用于链路跟踪和问题排查 self.req_msg_id = req_msg_id # 结果码,一般OK表示调用成功 self...
# Copyright 2019 D-Wave Systems 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 in writi...
#<NAME> mouseExpMan, that big old file with classes for all the data I'm going to collect #lol how this is all actually metadata... >_< #sqlite3 and/or sqlalchemy backed by sqlite, franky, I'm going to use sqlite one way or another, and I think sqlalchemy is a better fit for my needs #FIXME: this is old, should it be h...
= image_file_reader.read_frame(frame_index) if frame_number > int(getattr(metadata, 'NumberOfFrames', '1')): raise ValueError( f'Provided frame number {frame_number} exceeds number ' 'of available frames.' ) if not transfer_syntax_uid.is_encapsulated: pixels = frame else: if reencoding_media_type is None: p...
else: column_args.insert(0, Column(record_key, String, primary_key=True)) elif datatype == 'float': column_args.insert(0, Column(record_key, Float, primary_key=True)) elif datatype == 'integer': column_args.insert(0, Column(record_key, Integer, primary_key=True)) else: raise ValueError('Field "id" in record_sche...
crime | candy"], gain, "statgems") else: desc += " :lollipop:`lollipop`" sql.add(PlayerID, "lollipop", gain, "inventory") sql.add(PlayerID, ["Halloween", "Halloween | crime | lollipop"], gain, "statgems") else: desc = "{1} {0} :gem:`gems`".format(gain, lang_P.forge_msg(lang, "crime array", None, True)) sql.addGe...
list :param size: Number of sample to draw from data :return: """ # Hack to avoid skipping the first value of the parameter list. # This function is called once when the _algorithm __init__ # has to initialize the parameter names. Because of this, we end up # losing the first value in the list, which is undesira...
<reponame>lauraschachter/pydrograph __author__ = 'lschachter' import datetime as dt import time from urllib.request import urlopen import numpy as np import pandas as pd from shapely.geometry import Point, Polygon, shape import pyproj import gisutils import urllib3 import xmltodict import datetime def make_url(site_c...
YOLO format and export as files. If you pass classes, classes.txt will be generated based on it . If not , classes.txt will be generated based on passed tasks .(Annotations never used in your project will not be exported.) tasks is a list of tasks. (Required) classes is a list of annotation values. e.g. ['dog','bi...
<reponame>Kochise/canette #!/usr/bin/env python # author: d.koch # coding: utf-8 # naming: pep-0008 # typing: pep-0484 # docstring: pep-0257 # indentation: tabulation """ canp_node.py Node card-chan-NODE-conf """ # --- IMPORT --- # Standard libraries (installed with python) #import logging import os import sys s...
need_num = 2 break d_ite.append(pool[j]) need_num = need_num - 1 pai_num = pai_num - 1 if need_num == 0: combine(qua_two,r_qua[i],d_ite) remove_pack(pool,d_ite) d_ite = [] d_qua.append(r_qua[i]) break else: if is_pai(pool[j]): continue else: if len(d_ite) == 1 and n_need == 1: if d_ite[0] == pool[j]: ...
= Var(within=Reals,bounds=(0,500),initialize=0) m.x1877 = Var(within=Reals,bounds=(0,500),initialize=0) m.x1878 = Var(within=Reals,bounds=(0,500),initialize=0) m.x1879 = Var(within=Reals,bounds=(0,500),initialize=0) m.x1880 = Var(within=Reals,bounds=(0,500),initialize=0) m.x1881 = Var(within=Reals,bounds=(0,500),initia...
<gh_stars>0 # -*- coding: utf-8 -*- """ Created by <NAME> on 08/20/2020 """ import tkinter as tk import tkinter.messagebox as messagebox from tkinter import ttk from datetime import datetime import sys from PIL import ImageTk, Image import cv2 import database from win10toast import ToastNotifier from os import path ...
for batch in to_insert_batches(rows): res = self.cursor.executemany(stmt, batch) # new version of crate does not bomb anymore when # something goes wrong in multi entries # simply it returns -2 for each row that have an issue # TODO: improve error handling. # using batches, we don't need to fail the whole set # ...
85, 13), (166, 54, 3)], 6: [ (254, 237, 222), (253, 208, 162), (253, 174, 107), (253, 141, 60), (230, 85, 13), (166, 54, 3)], 7: [ (254, 237, 222), (253, 208, 162), (253, 174, 107), (253, 141, 60), (241, 105, 19), (217, 72, 1), (140, 45, 4)], 8: [ (255, 245, 235), (254, 230, 206), (253, 208, 162), ...
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # 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 appl...
<filename>day05/day05_puz1.py<gh_stars>1-10 #! /usr/bin/env python def run_opcode(code_list, programme_input=1): """Run the opcode as determined by the values in code_list Before you enter the next loop, check to see if the opcode (the first number in the sequence) is 99. If it is, then you can stop and return t...