input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
select from available object types",
"Select type for object array", bG.objectArrayChoices)
if choice != "":
self.Save()
bG.insertObjectArray(p.element, p.graph, choice)
elif id == const.ID_InsertMenuDataDelayOfSelected:
self.Save()
bG.makeDelay(Xref.get(obj).elem, p.graph, 3)
elif id == const.ID_InsertMenuData... | |
import copy
import logging as log
import os
from typing import Dict
import torch
import torch.nn as nn
from allennlp.modules import scalar_mix
import pytorch_transformers
from jiant.preprocess import parse_task_list_arg
from jiant.utils import utils
class PytorchTransformersEmbedderModule(nn.Module):
""" Shared c... | |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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... | |
"""
This module tracks and validates the status of Genomics Pipeline Subprocesses.
"""
import logging
from datetime import datetime
import pytz
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from rdr_service import clock, config
from rdr_service.api_util import list_blobs
from rdr_service.cloud_ut... | |
<gh_stars>0
#-*- coding: utf-8 -*-
#tentando importar python 2x ou 3x
try:
#python 2x
from Tkinter import Tk, Frame, Label, Menu, Scrollbar, Toplevel, Entry, Button, StringVar
from tkMessageBox import showinfo
from ttk import Treeview, Style, Button as Buttonttk, Label as Labelttk, Entry as Entryttk, OptionMenu as... | |
<gh_stars>1-10
from enum import auto, Enum
import logging
import pathlib
from .yaml import load_yaml
import tomli
from .cache import Cache
from .signals import document_loaded
from typing import (
Any,
Callable,
Dict,
Generic,
Iterable,
List,
Literal,
Optional,
Type,
TypeVar,
Union,
)
import re
import datepa... | |
replicate to all lanes of three registers"""
logger.debug("%s instruction not currently implemented.", instruction.mnem)
@opcode
def LD4R(cpu_context: ProcessorContext, instruction: Instruction):
"""Load single 4-element structure and replicate to all lanes of four registers"""
logger.debug("%s instruction not cur... | |
<reponame>pinyoothotaboot/engineering_tool
import math
class Area:
"""
Function : circularsector
Description : This function to calculate area of circular sector.
Formula : angle/2 x radius^2
Input :
- Radius number type integer or float
- Angle number type integer or float
Return : Area of circle sector in ... | |
== 11 and not ob.complet)
ob = Observation(json.dumps(dict((obs_1, loc1, dat3))))
self.assertTrue(ob.score == 12 and not ob.complet)
ob = Observation(json.dumps(dict((obs_1, loc3))))
self.assertTrue(ob.score == 20 and not ob.complet)
ob = Observation(json.dumps(dict((obs_1, loc3, dat1))))
self.assertTrue(ob.score... | |
<reponame>mansi-team/mansi_corpus
import re
import copy
import os
class DumbMorphParser:
"""
Contains methods that add context-independent word-level
morhological information from a parsed word list to a
collection of JSON sentences. No actual parsing takes
place here.
"""
rxWordsRNC = re.compile('<w>(<ana.*?... | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from scipy import interpolate
# from utils.utils import bilinear_sampler, coords_grid
class FlowHead(nn.Module):
def __init__(self, input_dim=128, hidden_dim=256):
super(FlowHead, self).__init__()
self.conv1 = nn.Conv2d(input_dim,... | |
<filename>docs/autodoc.py
# Copyright (c) AIRBUS and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import ast
import importlib
import inspect
import json
import logging
import os
import pkgutil
import re
import sys
import url... | |
name of the workgroup to delete.
:type RecursiveDeleteOption: boolean
:param RecursiveDeleteOption:
The option to delete the workgroup and its contents even if the workgroup contains any named queries.
:rtype: dict
:returns:
"""
pass
def generate_presigned_url(self, ClientMethod: str = None, Params: Dict = Non... | |
<filename>pytwitcasting/api.py
import json
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from pytwitcasting.error import TwitcastingException
from pytwitcasting.parsers import ModelParser
from pprint import pprint
API_BASE_URL = 'https://apiv2.twitc... | |
# Module containing functions that interact with the statline API
from typing import Union
from pathlib import Path
import requests
import xml.etree.ElementTree as ET
import pyarrow as pa
import dask.bag as db
from statline_bq.utils import _create_dir, _url_to_ndjson, convert_ndjsons_to_parquet
from statline_bq.log i... | |
error : Error
instance_types : typing.Sequence[~InstanceType]
'''
cost_currency_ = cost_currency
cost_divisor_ = cost_divisor
cost_unit_ = cost_unit
error_ = Error.from_json(error) if error else None
instance_types_ = [InstanceType.from_json(o) for o in instance_types or []]
# Validate arguments against known ... | |
clusterable, this should be roughly
# block diagonal
# take the absolute value of all the weights
weight_mat = np.abs(weight_mat)
# print(weight_mat)
# now for the actual calculation...
# divide the matrix into blocks depending on the cluster of the rows and
# columns. then add everything in that block to the ... | |
'billing_month') and self.billing_month is not None:
_dict['billing_month'] = self.billing_month
if hasattr(self, 'billing_country_code') and self.billing_country_code is not None:
_dict['billing_country_code'] = self.billing_country_code
if hasattr(self, 'billing_currency_code') and self.billing_currency_code is n... | |
'VirtualNetworkProfile'},
'internal_load_balancing_mode': {'key': 'properties.internalLoadBalancingMode', 'type': 'str'},
'multi_size': {'key': 'properties.multiSize', 'type': 'str'},
'multi_role_count': {'key': 'properties.multiRoleCount', 'type': 'int'},
'worker_pools': {'key': 'properties.workerPools', 'type': '... | |
Index of parent node for this child node.
LBD_prev : float
Previous iteration value of LBD.
LBD : float
Current value of lower bound estimate.
UBD : float
Current value of upper bound esimate.
fopt : float
Current best objective value
xopt : ndarray
Current best design values.
node_num : int
Index of this c... | |
binvals = copy.deepcopy(binvals)
if not isinstance(binvals, (list, tuple)):
binvals = [binvals]
if not isinstance(zeropad, (list, tuple, np.ndarray)):
zeropad = [zeropad]
if isinstance(axis, (list, tuple, np.ndarray)) and not isinstance(zeropad, (list, tuple, np.ndarray)):
raise ValueError("If axis is an iterable... | |
?, ?, ?)''',
(user_id,
None,
engine_workflow.expiration_date,
name,
constants.WORKFLOW_NOT_STARTED,
datetime.now(),
engine_workflow.queue))
engine_workflow.wf_id = cursor.lastrowid
# the transfers must be registered before the jobs
for transfer in six.itervalues(
engine_workflow.transfer_mapping):
transfe... | |
)
"""
Input graph:
input(shape=10,2,3)--->transpose(axis=[0,2,1])----->relu---->transpose(axis=[0,2,1])---->out1
|
|
--->reduce(axis=2)----->log---->transpose(axis=[0,2,1])---->out2
Output graph:
input(shape=10,2,3)----->relu---->out1
|
|
--->reduce(axis=1)----->log---->out2
"""
def test_fusion_with_axi... | |
# -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2019 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
import pytest
from _pytest.outcomes import Skipped
import os
import numpy as np
import pyuvdata.tests as uvtest
from pyuvdata import UVData, UVCal, utils as uvutils
from pyuvdata.data imp... | |
``X``. Next calls the
``draw`` method of the Yellowbrick visualizer, finally returning a new array of
transformed features of shape ``(len(X), projection)``.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features.
y : ndarray or Series of length n
An array or ser... | |
#!/usr/bin/env python3
# tab-width:4
# pylint: disable=missing-docstring
# MIT License
# https://github.com/jakeogh/dnsgate/blob/master/LICENSE
#
# "psl domain" is "Public Second Level domain"
# extracted using https://publicsuffix.org/
# essentially this is the first level at which
# the public could register domains... | |
dict()
resource_to_mod_issn_nlm[mod] = dict()
filename = base_path + 'dqm_data/RESOURCE_' + mod + '.json'
try:
with open(filename, 'r') as f:
dqm_data = json.load(f)
for entry in dqm_data['data']:
primary_id = entry['primaryId']
values_to_add = []
for field in resource_fields:
if field in entry:
value = simp... | |
# Copyright 2021 National Technology & Engineering Solutions
# of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS,
# the U.S. Government retains certain rights in this software.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance ... | |
#!/usr/bin/env python
# coding: utf-8
# # Decision Trees (with GINI) for Predictive Maintenance
# Supplementary Jupyter Notebook for the seminar paper of <NAME> and <NAME>.
#
# This Notebook implements the procedure to build a decision-tree based on Gini-index metric.
# It has been setup to build a Decision-Tree for... | |
yang_type='oc-yang:counter64', is_config=False)""",
})
self.__connection_failures = t
if hasattr(self, '_set'):
self._set()
def _unset_connection_failures(self):
self.__connection_failures = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=6... | |
<gh_stars>0
#!/usr/bin/env python3
import ctypes
import enum
import os
if os.name == "nt":
DM_ODBC_NAME = "odbc32.dll"
else:
DM_ODBC_NAME = "libodbc.so"
def UnimplementedSQLFunction(*args):
raise NotImplementedError("This SQL function is not implemented")
class Driver:
def __init__(self, odbc_driver_name = DM_O... | |
#!/usr/bin/env python
"""
Takes a cifti map ('dscalar.nii') and outputs a csv of results
Usage:
ciftify_statclust_report [options] <func.dscalar.nii>
Arguments:
<func.dscalar.nii> Input map.
Options:
--min-threshold MIN the largest value [default: -2.85] to consider for being a minimum
--max-threshold MAX the sm... | |
<gh_stars>0
# -*- coding: utf8 -*-
# Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org... | |
#!/usr/bin/env python3
#
# Name: mrf_join
# Purpose:
'''Joins multiple MRF files with the same structure into a single one'''
# Created: 11/08/2018
# Updated: 12/14/2018 - Added Z dimension append mode
# Updated: 12/09/2020 - Updated to python3
#
# Author: <NAME>
#
# Licensed under the Apache License, Version 2.0 (th... | |
<reponame>chadtilbury/hindsight
"""
Copyright 2020, CCL Forensics
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify,... | |
<reponame>rcmelendez/devo-lapua-docker
# -*- coding: utf-8 -*-
import socket
import json
import re
import cmd
import os
import math
import time
import readline
import pytz
from .utils.constants import PERIOD_REGEX, NUMBER_REGEX, STATUS, \
MESSAGES, OK_MESSAGE, KO_MESSAGE, \
END_OF_MESSAGE, LAPUA_VERSION
from .utils.c... | |
vals, vecs, stats):
self.eigenvalues = vals
self.eigenvectors = vecs
self.stats = stats
self.transform = LinearTransform(self.eigenvectors.T, pre=-self.mean)
@property
def mean(self):
return self.stats.mean
@property
def cov(self):
return self.stats.cov
def reduce(self, N=0, **kwargs):
'''Reduces the num... | |
sentence in summary_sentences:
lcs = _lcs_elements(sentence, reference_sentence)
lcs_union = lcs_union.union(ref_idx for _, ref_idx in lcs)
return lcs_union
def _flatten_and_count_ngrams(sentences, n):
"""
First flatten a list of sentences, then count ngrams on it.
>>> s1 = 'the cat sat on the mat'.split()
>>... | |
<filename>mayachemtools/bin/RDKitGenerateMolecularFrameworks.py
#!/bin/env python
#
# File: RDKitGenerateMolecularFrameworks.py
# Author: <NAME> <<EMAIL>>
#
# Copyright (C) 2020 <NAME>. All rights reserved.
#
# The functionality available in this script is implemented using RDKit, an
# open source toolkit for cheminfor... | |
something else, set the notes attribute.
elif response:
entry.notes = response
# end if
return 1
except Exception as err:
_z_exc("wl_add.py/add_note", err)
# end try
# end function
def add_recurrance(wl_obj, entry):
"""
Sets the recurrance of a task if the user so chooses.
Arguments:
- wl_... | |
"""Specific Pysyft exceptions."""
from tblib import Traceback
import traceback
from six import reraise
from typing import Tuple
import syft as sy
from syft.generic.frameworks.types import FrameworkTensor
class DependencyError(Exception):
def __init__(self, package, pypi_alias=None):
if pypi_alias is None:
pypi_al... | |
from numpy import mean
import pandas as pd
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plot
import matplotlib.mlab as mlab
import matplotlib.pylab as lab
import matplotlib.patches as patches
import matplotlib.ticker as plticker
from matplotlib import rcParams
from matplotlib import gridspec... | |
<reponame>galletitaoreo/PythonPentest
# -*- encoding: utf-8 -*-
'''
Author:<NAME>
email:<EMAIL>
'''
import sys
import os
import nmap
import socket
import getopt, sys
import platform
import urllib, urllib2, json
import ftplib
import time
import utils
import re
import argparse
try:
from bs4 import BeautifulSoup
except ... | |
in_row[u'收件人邮编']
n_package = in_row.get(u'物品种类数量', None)
if not n_package:
n_package = in_row.get(u'包裹数量', None)
package_weight = in_row[u'包裹重量(公斤)']
length = in_row[u'长(厘米)']
width = in_row[u'宽(厘米)']
height = in_row[u'高(厘米)']
id_number = in_row[u'身份证号(EMS需要)']
for check_field in (sender_name, sender_phone, s... | |
os.environ.get(environment_variable, None)
for environment_variable in self.environment_variables
}
yield environment
class SimpleTransforms(MetalNode):
def __init__(
self,
missing_keypath_action="ignore",
starting_path=None,
transform_mapping=None,
target_value=None,
keypath=None,
**kwargs
):
self.miss... | |
ints
for cluster, nodes in clusters.items():
clusters[cluster] = sorted([int(node) for node in nodes])
remove_outliers(clusters)
clustered = []
for cluster, nodes in clusters.items():
for n in nodes:
clustered.append(n)
clusters['singles'] = [] # Add singles to clusters if not in top n scores
clusters['rem... | |
"http://127.0.0.1:9200")
error.append(error6)
h, error7 = a.process_action(0, "schedule-add-client", {'--uuid':f[9][1], '--client_id':g[5][1]}, m_server, "localhost", "hemlock", "hemlock", "password", 0, "http://127.0.0.1:9200")
error.append(error7)
x, error8 = a.process_action(0, "schedule-remove-client", {'--uuid... | |
<filename>test/unit/neural_networks/pytorch/test_EncDecDyn.py
#
# Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Written by <NAME> <<EMAIL>>
#
import unittest
import copy
import os
import torch
import jsonpickle
from idiaptts.misc.utils import makedirs_safe
import idiaptts.src.neural_networks.p... | |
map.get('thumbnail')
if map.get('trashed_at') is not None:
self.trashed_at = map.get('trashed_at')
if map.get('type') is not None:
self.type = map.get('type')
if map.get('updated_at') is not None:
self.updated_at = map.get('updated_at')
if map.get('upload_id') is not None:
self.upload_id = map.get('upload_id')
... | |
<gh_stars>1-10
"""
element.py
lists and tools to deal with motifs (words).
pwms, pwm and element need to be merged into a single 'motif.py'...
Part of glbase.
"""
from . import config
import re, random, sys, os, string, numpy, copy
from . import utils
from .genelist import genelist as new_gl
from .errors import... | |
user_cn = AD.GetLDAPObject(cn)
if user_cn is None and auto_create is True:
# Try and create it
if AD.CreateOU(cn) is not True:
AD._errors.append("<b>Error creating faculty OU: </b> " + cn + "<br />")
ret = False
else:
AD._errors.append("<b>Faculty OU created: </b> " + cn + "<br />")
elif user_cn is None and aut... | |
<filename>oslo_db/sqlalchemy/exc_filters.py
# 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 ... | |
viewing_condition_dependent_parameters(Y_b, Y_w, L_A):
"""
Returns the viewing condition dependent parameters.
Parameters
----------
Y_b : numeric
Adapting field *Y* tristimulus value :math:`Y_b`.
Y_w : numeric
Whitepoint *Y* tristimulus value :math:`Y_w`.
L_A : numeric
Adapting field *luminance* :math:`L_A`... | |
## Set new state value
def set_state(self, mid, value):
self._STATE[mid].appendleft(value)
return None
# Construct the measurable using id
def construct_measurable(self, mid, definition=None, init_value=None, depth=1, decdep=False):
"""
:param mid: the input id, if it is none, id will be generated
:param defin... | |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | |
#####################################################
# Title: HTML parse- and analyser
# Author: <NAME> (<EMAIL>)
# Licence: GPLv2
#####################################################
#!/usr/bin/python
import sys
import sqlite3
import datetime
import timeit
import math
import re
import pandas as pd
imp... | |
<filename>django_evolution/tests/test_change_field.py<gh_stars>0
from __future__ import unicode_literals
from django.db import connection, models
from django_evolution.db import EvolutionOperationsMulti
from django_evolution.diff import Diff
from django_evolution.errors import SimulationFailure
from django_evolution.... | |
user = cred_data[1]
pwd = cred_data[2]
lhost = get_local_ip(get_iface())
cmd, output, err = await run_smb_login(client, c_id, lhost, threads, user, pwd, dom, target_ips)
await parse_smb_login(lock, c_id, output, domain_data)
async def make_session_busy(sess_num, sess_data):
while sess_data[sess_num][b'busy'] == ... | |
<filename>BDMLtools/selector/bin_fun.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 27 23:08:38 2021
@author: zengke
"""
import pandas as pd
import numpy as np
from pandas.api.types import is_numeric_dtype,is_string_dtype,is_array_like
from sklearn.base import BaseEstimator
from joblib impor... | |
<filename>model.py
from abc import ABC, abstractmethod
from datetime import date, datetime
from decimal import Decimal, ROUND_HALF_EVEN
from enum import Enum, Flag, auto, unique
from itertools import permutations
from typing import Any, Dict, Iterable, NamedTuple, Optional, TypeVar, Union
import re
@unique
class Cur... | |
# Copyright 2019 The Keras Tuner 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | |
<gh_stars>0
"""
(C) Copyright 2021 IBM Corp.
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, ... | |
<reponame>ballinc/covid19-api
from decouple import config
from flask import Flask, jsonify, url_for
from flask_caching import Cache
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_restplus import Api, Resource
import src.utils as util
from src.errors import CountryNotFoun... | |
( self.tasks[self.iter][0] + key2str[e.key()], self.tasks[self.iter][1], self.tasks[self.iter][2], self.tasks[self.iter][3])
self.visualizer.setStringToPrint(self.tasks[self.iter][0])
elif((e.key() == QtCore.Qt.Key_Enter) or (e.key() == QtCore.Qt.Key_Return)):
# Validate and Execute
if(self.validateEquation() == T... | |
db_column='to_table', related_name = 'to_table')
to_column = models.CharField(max_length=50)
value_vocabulary_id = models.CharField(max_length=50, blank=True, null=True)
value_concept_code = models.CharField(max_length=50, blank=True, null=True)
addl_column = models.CharField(max_length=50, blank=True, null=True)
... | |
<filename>account_invoice.py
# -*- coding: utf-8 -*-
from openerp import models,fields,api
from openerp import SUPERUSER_ID
from openerp.tools.translate import _
from openerp.exceptions import Warning
import time
from datetime import date, datetime
from ftplib import FTP
import os
import tempfile
from pyPdf import Pdf... | |
<reponame>bellrichm/weather
""" The uploader """
# pylint: disable=invalid-name
# pylint: enable=invalid-name
import json
import sys
import time
import jwt
import weewx.restx
#from weeutil.weeutil import to_int
#import six
from six.moves import urllib
try:
# Python 2
from Queue import Queue
except ImportError:
# P... | |
import re
import numpy as np
import warnings
import copy
from .utils import is_pos_int, is_non_neg_int, \
is_proportion, is_positive, is_non_negative, \
inherits
class layout:
def __init__(self,
ncol=None,
nrow=None,
byrow=None,
rel_widths=None,
rel_heights=None,
design=None
):
"""
layout class to store in... | |
<reponame>PFalkowski/UnpackValidateEegData
import unittest
import pandas as pd
import EegSignalProcessing as eeg
import numpy as np
import matplotlib.pyplot as plt
import numpy.fft as fft
import mne
import os
import json
from pandas.testing import assert_frame_equal
class UnitTestHelper:
@staticmethod
def assert_dic... | |
# Copyright (C) 2008 The Android Open Source Project
#
# 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 ag... | |
""" Decoder for the SQL generation problem."""
from collections import namedtuple, defaultdict
import numpy as np
import torch
import torch.nn.functional as F
from . import torch_utils
from .token_predictor import PredictionInput, PredictionInputWithSchema
import EditSQL.data_util.snippets as snippet_handler
from . ... | |
Column('Date_Time_Stamp',
DateTime,
nullable=True,
doc='Date Time Stamp',
comment='N/A'),
Column('Cntr_Num',
String(length=10),
nullable=True,
index=True,
doc='Contract Number',
comment='The key to the contract record.'),
Column('Desc',
String(length=30),
nullable=True,
doc='Description',
comment='The de... | |
import sys
from calendar import month_name
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
from sklearn.model_selection import TimeSeriesSplit, StratifiedKFold, GroupKFold, KFold
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
from dateutil.rel... | |
<reponame>TingtingAlice/MPM-LTL
from __future__ import print_function
import os.path as osp
import time
import numpy as np
import scipy.io as sio
import matplotlib.image as mpimg
import glob
from collections import defaultdict
import shutil
import torch
from utils import may_make_dir
from utils import save_pickle
from... | |
upper += via_ext
# draw ports
lower_tracks, upper_tracks = port_tracks[cur_layer]
lower_warrs = [self.add_wires(cur_layer, tr_idx, lower, upper, width=port_tr_w)
for tr_idx in lower_tracks]
upper_warrs = [self.add_wires(cur_layer, tr_idx, lower, upper, width=port_tr_w)
for tr_idx in upper_tracks]
# assign port... | |
# For image output to bmp file
import numpy as np
import imageio
# For image operation
from library.image_tool_box import *
# For math/statistic operation
from library.math_tool_box import StatMaker
import math
### 1. Downlaod and unpack those 4 test data from MNIST database.
# train-images-idx3-ubyte.gz: trainin... | |
that are selected to be exposed
Returns:
the prediction of the model in JSON format
"""
fileio = open(filename, 'rb')
if is_video is True:
input = Video(file_obj=fileio)
else:
input = Image(file_obj=fileio)
output_config=ModelOutputConfig(language=lang,
min_value=min_value,
max_concepts=max_concepts,
se... | |
<filename>venus/db/yasdl/ast.py
"""Abstract Syntax Tree for YASDL."""
from typing import List, Union
import venus.i18n
_ = venus.i18n.get_my_translator(__file__)
# noinspection PyPep8Naming
class dotted_name(str):
"""This is a special string type that represents a dotted name.
The imp attribute is set if the nam... | |
"""
Tools for generating heatmaps from latitude and longitude data.
MIT License
Original work Copyright (c) 2018 <NAME>
Modified work Copyright 2021 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the... | |
270, 'width': 240},
'N703iD': { 'color': True, 'depth': 262144, 'height': 270, 'width': 240},
'N703imyu': { 'color': True, 'depth': 262144, 'height': 270, 'width': 240},
'N704imyu': { 'color': True, 'depth': 262144, 'height': 270, 'width': 240},
'N705i': { 'color': True, 'depth': 262144, 'height': 320, 'width': 240... | |
import abc
import itertools
from typing import Iterable
from .indexes import Index
from .internal import _InternalAccessor
from .merge import MergeExpression
from .operator import (ArithExpression, BooleanExpression, DataFrameLike,
SeriesLike, StatOpsMixin)
from .series import Series
from .utils import (ORCA_INDEX_NA... | |
import contextlib
import functools
import operator
import sys
import threading
import numpy
import six
import chainer
from chainer.backends import cuda
_thread_local = threading.local()
@contextlib.contextmanager
def get_function_check_context(f):
try:
default = _thread_local.current_function
except AttributeE... | |
#!/usr/bin/env python
"""Simple parsers for the output of linux commands."""
import logging
import os
import re
from builtins import zip # pylint: disable=redefined-builtin
from future.utils import iteritems
from grr_response_core.lib import parser
from grr_response_core.lib.rdfvalues import anomaly as rdf_anomaly
f... | |
%s' % len(ast_node.args))
[arg] = ast_node.args
elem_type = type_declaration_ast_to_ir3_expression_type(arg, compilation_context)
return ir3.SetExpr(elem_type=elem_type, elem_exprs=[])
def int_iterable_sum_expr_ast_to_ir3(ast_node: ast.Call,
compilation_context: CompilationContext,
in_match_pattern: bool,
check_... | |
# Copyright 2011 <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
#
# Unless required by applicable law or agreed to in writing,... | |
<reponame>alphagov-mirror/stagecraft
import json
from django.test import TestCase
from hamcrest import (
assert_that, equal_to, is_,
has_entry, has_item, has_key, is_not,
has_length, greater_than
)
from stagecraft.apps.users.models import User
from stagecraft.libs.authorization.tests.test_http import with_govuk_sig... | |
#
# Copyright (C) 2009-2010 <NAME>, <NAME>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | |
# -*- coding: utf-8 -*-
"""
@author: <NAME>
"""
import math
import random
import warnings
import numpy as np
import tensorflow as tf
try:
tf.train.AdamOptimizer
except AttributeError:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import sklearn.metrics
#TODO Clean this
# Animesh commented this line o... | |
car leave gaussain
YOLO(frame_resized, darknet_image, 0)
if (forward_appear[0] == 1):
forward_temp[0] = 1
else:
forward_temp[0] = 0
elif (forward_road_number == 2): #2 road
forward_road_1 = forward_foreground
forward_road_1 = forward_foreground[forward_road_coord[0, 1] - forward_gaussian_range... | |
#!/usr/bin/env python3
# encoding: utf-8
"""
Determine scaling factors for a given list of levels of theory
Based on DOI: 10.1016/j.cpc.2016.09.004
Adapted by <NAME> and <NAME>
"""
import os
import time
import shutil
from arc.common import get_logger, check_ess_settings, time_lapse, initialize_log, initialize_job_t... | |
<reponame>SereneQI/text-image-similarity
import json
import os
import re
import io
import argparse
import multiprocessing
import numpy as np
import torch
import torch.utils.data as data
import numpy as np
from PIL import Image
from nltk.tokenize import word_tokenize
import fastText
from torchvision import transforms
... | |
from numba import config, ir, ir_utils, utils, prange
import types
from numba.ir_utils import (
mk_unique_var,
next_label,
add_offset_to_labels,
replace_vars,
remove_dels,
remove_dead,
rename_labels,
find_topo_order,
merge_adjacent_blocks,
GuardException,
require,
guard,
get_definition,
find_callname
)
... | |
<filename>tests/test_merge.py
# Test unit for decomon with Dense layers
from __future__ import absolute_import
import pytest
import numpy as np
from decomon.layers.decomon_layers import to_monotonic
from decomon.layers.decomon_merge_layers import (
DecomonConcatenate,
DecomonAverage,
DecomonMaximum,
DecomonMinimum,... | |
(pickle file) created with the function cover_dom_mp.
Parameters
----------
filename : name of the pickle file containing the data
Returns
----------
den, col_den, median_mp, avg_mp, centers
'''
with open(filename, "rb") as all_data:
data = pickle.load(all_data)
den = data['density']
col_den = d... | |
"""
Access to the Soliscloud API for PV monitoring.
Works for all Ginlong brands using the Soliscloud API
For more information: https://github.com/hultenvp/solis-sensor/
"""
from __future__ import annotations
import hashlib
#from hashlib import sha1
import hmac
import base64
import asyncio
from datetime import dateti... | |
and following: (element of x (row) abscissa), followed
by table data.
From line/row 3 onwards the first element is the x abscissa value
followed by the row of data, one point for each y abscissa value.
The file format can depicted as follows: ::
x-name y-name ordinates-name
0 y1 y2 y3 y4
x1 v11 v12 v13 v14
... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import logging
import tempfile
import subprocess
import argparse
import zipfile
import time
import shutil
import uuid
from slugify import slugify
import version
from modules.utils import get_executable_name, get_executable_path, format_pattern, cl... | |
<gh_stars>100-1000
from __future__ import unicode_literals
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
from django.db.models import Q
from django.utils import six
from djblets.webapi.errors import DOES_NOT_EXIST, WebAPIError
from djblets.webapi.fields import (BooleanFieldType,
ChoiceFieldT... | |
"1959:147"): "metadataonly",
("prop", "1959:148"): "metadataonly",
("prop", "1959:149"): "metadataonly",
("prop", "1959:15"): "metadataonly",
("prop", "1959:151"): "metadataonly",
("prop", "1959:152"): "metadataonly",
("prop", "1959:154"): "metadataonly",
("prop", "1959:156"): "metadataonly",
("prop", "1959:159... | |
tell if {ndim}-d cells with {nbounds} vertices "
"are contiguous"
)
# Check cells (j, i) and cells (j, i+1) are contiguous
diff = bounds[:, :-1, 1] - bounds[:, 1:, 0]
if period is not None:
diff = diff % period
if diff.any():
return False
diff = bounds[:, :-1, 2] - bounds[:, 1:, 3]
if period is not None:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.