input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<filename>fbmeshd/linkstatsd/collector.py
#!/usr/bin/env python3
# Copyright (c) 2004-present, Facebook, Inc.
# All rights reserved.
import asyncio
import json
import logging
import os
import random
import re
import time
import typing
from collections import defaultdict
from datetime import MINYEAR, datetime, timedelt... | |
KMinor: u.dimensionless or unitless
:return: inner diameter of pipe
:rtype: u.m
"""
ut.check_range([FlowRate.magnitude, ">0", "Flow rate"],
[KMinor, ">=0", "K minor"],
[HeadLossMinor.magnitude, ">0", "Headloss due to expansion"])
return (np.sqrt(4 * FlowRate / np.pi)
* (KMinor / (2 * u.gravity * HeadLossMinor)... | |
dataonly = False: If True only the resulting dataframes are returned
"""
try:
if keep_dim:
dfs = self.keep_get_dict(pat, start, slut, start_ofset, slut_ofset)
else:
dfs = self.keep_var_dict(pat, start, slut, start_ofset, slut_ofset)
if showtype == 'growth':
dfs = {v: vdf.pct_change()*100. for v, vdf in dfs... | |
<gh_stars>0
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you m... | |
import pytest
from plums.plot.engine.position_generator import (
SimpleImagePositionGenerator,
LayoutImagePositionGenerator,
AdaptiveImagePositionGenerator,
LegendItemPositionGenerator
)
class TestSimpleImagePositionGenerator:
def test_constructor(self):
dummy_datapoints = list(range(150))
dummy_max_cols = 20... | |
if digit not in digits:
# result.append(digit)
# digits.add(digit)
# return result
#
# def compare(logins, d1, d2):
# for login in logins:
# if d1 in login and d2 in login:
# i1 = login.find(d1)
# i2 = login.find(d2)
# if i1 < i2:
# return -1
# elif i1 > i2:
# return +1
# else:
# raise Exception, "Invalid comparison fo... | |
= 2048
elif device_type == "SAHD":
expected_block_size = 256
# Attempt to load the device properties file:
# same file name with PROPERTIES_SUFFIX appended
drive_properties = f"{CFG_DIR}/{file_name}.{PROPERTIES_SUFFIX}"
if Path(drive_properties).is_file():
process = file_cmds.read_drive_properties(drive_propert... | |
<reponame>pulumi/pulumi-alicloud
# 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, Sequenc... | |
== "silva":
execute("identify_chimeric_seqs.py -i %s -m usearch61 -o %s -r %s"
% (inFolder + i, temp + i, PR['silva_chim_ref']),
shell=True)
else:
execute("identify_chimeric_seqs.py -i %s -m usearch61 -o %s -r %s" % (
inFolder + i, temp + i, PR['gg_chim_ref']),
shell=True)
execute("filter_fasta.py -f %s -o %s ... | |
dossier partagé',
'Audio' : 'Son',
'Enable Audio' : 'Activer le son',
'Host Audio Driver' : 'Pilote audio hôte',
'Audio Controller' : 'Controleur audio',
'WinMM' : 'Windows multimedia',
'Null Audio Driver' : 'Null Audio Driver',
'OSS' : 'Open Sound System',
'ALSA' : 'Advanced Linux Sound Archit... | |
# ========== pointer distribution (decoder self-attention) mask ==========
if self.args.apply_tgt_actnode_masks:
assert tgt_actnode_masks is not None
if self.args.shift_pointer_value:
tgt_actnode_masks[:, 1:] = tgt_actnode_masks[:, :-1]
tgt_actnode_masks[:, 0] = 0
ptr_self_attn_mask = tgt_actnode_masks.unsqueeze(... | |
possibly several levels
proposals (list[BoxList]): proposal boxes
targets (list[BoxList], optional): the ground-truth targets.
Returns:
x (Tensor): the result of the feature extractor
proposals (list[BoxList]): during training, the subsampled proposals
are returned. During testing, the predicted boxlists ... | |
<gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from enum import Enum
class THOST_TE_RESUME_TYPE(Enum):
TERT_RESTART = 0
TERT_RESUME = 1
TERT_QUICK = 2
class TThostFtdcExchangePropertyType(Enum):
"""交易所属性类型"""
THOST_FTDC_EXP_Normal = 48
"""正常"""
THOST_FTDC_EXP_GenOrderByTrade = 49
"""根据成交生成报单"... | |
= argToList(args['file'])
extended_data = argToBoolean(args.get('extended_data'))
results: List[CommandResults] = list()
for file in files:
raise_if_hash_not_valid(file)
try:
raw_response = client.file(file, relationships)
results.append(build_file_output(client, score_calculator, file, raw_response, extended_da... | |
<gh_stars>0
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ____
# __ _ ___ ____ / __/__ __ __
# / ' \/ _ `/ _ \_\ \/ _ \/ // /
#/_/_/_/\_,_/_//_/___/ .__/\_, /
# /_/ /___/
#
# Auteur : <NAME>
# Outil : ManSpy
# Usage : ./manspy.py 'exemple.com' (ou) python manspy.py 'exemple.com'.
# La description : cet outil permet... | |
<gh_stars>10-100
import unittest
import numpy as np
import pandas as pd
from powersimdata.design.transmission.upgrade import (
_construct_composite_allow_list,
_find_branches_connected_to_bus,
_find_capacity_at_bus,
_find_first_degree_branches,
_find_stub_degree,
_identify_mesh_branch_upgrades,
_increment_bran... | |
self._exclude = exclude
self._pattern = pattern
self._ratio = ratio
self._hass = hass
self._ui = ui
self._tasks = {}
self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY)
self._dic_friendly_name = {}
self._dic_operation_en_to_cn = {
'on':'开',
'off':'关',
'temporary_on':'关⇌开',
'te... | |
>>> _ = plt.title('Using `fftcoef` for FFT curve fit')
>>> _ = plt.xlabel('Time (s)')
"""
if coef not in ("mag", "ab", "complex"):
raise ValueError(
f"invalid `coef` ({coef!r}). Must be one of 'mag', 'ab', or 'complex'."
)
x = np.atleast_1d(x)
n = x.shape[axis]
if isinstance(window, (str, tuple)):
window = si... | |
"""
To add a new kind of graphic items create a child class
of VisualizerGraphicItem in this file and add it in the
model.create_item function to the model. This is the only function
in the model that should be changed. The behaivor and values of the
object should be defindes inside of its own class.
To add new prop... | |
= Constraint(expr= m.b120 - m.b127 + m.b161 <= 1)
m.c907 = Constraint(expr= m.b121 - m.b122 + m.b162 <= 1)
m.c908 = Constraint(expr= m.b121 - m.b123 + m.b163 <= 1)
m.c909 = Constraint(expr= m.b121 - m.b124 + m.b164 <= 1)
m.c910 = Constraint(expr= m.b121 - m.b125 + m.b165 <= 1)
m.c911 = Constraint(expr= m.b121 - m.... | |
<filename>cli/cros/lint_unittest.py
# -*- coding: utf-8 -*-
# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Test the lint module."""
from __future__ import print_function
import collections
imp... | |
<reponame>carolgaudeoso/PyTTa
# -*- coding: utf-8 -*-
"""
This module does calculations compliant to ISO 3382-1 in order to obtain room
acoustic paramters.
It has an implementation of Lundeby et al. [1] algorithm to estimate the
correction factor for the cumulative integral, as suggested by the ISO 3382-1.
"""
impo... | |
export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PostShipmentUploadDetail', pretty_print=True):
imported_ns_def_ = GenerateDSNamespaceDefs_.get('PostShipmentUploadDetail')
if imported_ns_def_ is not None:
namespacedef_ = imported_ns_def_
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if ... | |
<reponame>chrhenning/snn_global_pattern_induction
#!/usr/bin/env python3
# Copyright 2017 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0... | |
Jersey'},
{'city': 'Barrington', 'state': 'New Hampshire'},
{'city': 'Barrington', 'state': 'Illinois'},
{'city': 'Barstow', 'state': 'California'},
{'city': 'Bartlesville', 'state': 'Oklahoma'},
{'city': 'Bartlett', 'state': 'Illinois'},
{'city': 'Bartlett', 'state': 'Tennessee'},
{'city': 'Barton', 'state': 'N... | |
import asyncio
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast
from asgiref.sync import async_to_sync
from django.apps import apps
from django.core.exceptions import ValidationError as DjangoValidationError
from mypy_extensions import TypedDict
from ..utils.cache import element_cache
... | |
#!/usr/bin/python
"""
atom_energy_reporter.py
MIT License
Copyright (c) 2018
Weill Cornell Medicine, Memorial Sloan Kettering Cancer Center, and Authors
Authors:
<NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software")... | |
import os
import logging
log = logging.getLogger("amaptor")
import arcpy
from amaptor.version_check import PRO, ARCMAP, mapping, mp
from amaptor.classes.map import Map
from amaptor.classes.layout import Layout
from amaptor.classes.map_frame import MapFrame
from amaptor.constants import _TEMPLATES, _PRO_BLANK_LAYOUT
... | |
<reponame>00schen/asha<filename>assistive-gym/assistive_gym/envs/util.py
import numpy as np
import pybullet as p
class Util:
def __init__(self, pid, np_random):
self.id = pid
self.ik_lower_limits = {}
self.ik_upper_limits = {}
self.ik_joint_ranges = {}
self.ik_rest_poses = {}
self.np_random = np_random
def ik... | |
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import os, argparse
import csv
from run1 import get_params_office_world, get_params_traffic_world, get_params_craft_world
def smooth(y, box_pts):
box = np.ones(box_pts)/box_pts
y.append(sum(y[-5:])/len(y[-5:]))
y.append(sum(y[-5:]) / len(y[-5:]))... | |
def get_Distance(self):
return self.Distance
def set_Distance(self, Distance):
self.Distance = Distance
def get_ReservationAvailabilityDetail(self):
return self.ReservationAvailabilityDetail
def set_ReservationAvailabilityDetail(self, ReservationAvailabilityDetail):
self.ReservationAvailabilityDetail = Reservati... | |
<filename>routing_changes/hornet/hornet.py
#!/usr/bin/env python3
import argparse
import atexit
from collections import Counter, ChainMap, defaultdict
import datetime
import functools
import hashlib
import ipaddress
import itertools
import logging
import random
import re
import sys
import ujson
from tempest import s... | |
0xb4)
return 1
class Sorcerer_fix(Fix):
needed = True
def __init__(self, gf):
self.gamefile = gf
self.contents = bytearray(gf.contents)
self.gamesize = gf.gamesize
elf.game_name = "Sorcerer"
self.desc = ("In Sorcerer, the copy protection consists of an Infotater wheel "
"where the player looks up one of 12 m... | |
<reponame>pearsontechnology/k8sv1<filename>test/test_apiv_api.py<gh_stars>1-10
# coding: utf-8
"""
No descripton provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the A... | |
<filename>nipype/interfaces/mrtrix3/utils.py
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
# -*- coding: utf-8 -*-
import os.path as op
from ...utils.filemanip import split_filename
from ..base import (
CommandLineInputSpec,
CommandLine,
traits,
... | |
:returns:
"""
pass
def list_device_definition_versions(self, DeviceDefinitionId: str, MaxResults: str = None, NextToken: str = None) -> Dict:
"""
Lists the versions of a device definition.
See also: `AWS API Documentation <https://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListDeviceDefinitionVersions... | |
<< (ClickHouseParser.K_LEFT - 64))
| (1 << (ClickHouseParser.K_LIKE - 64))
| (1 << (ClickHouseParser.K_LIMIT - 64))
| (1 << (ClickHouseParser.K_MAIN - 64))
| (1 << (ClickHouseParser.K_MATERIALIZED - 64))
| (1 << (ClickHouseParser.K_MODIFY - 64))
| (1 << (ClickHouseParser.K_NOT - 64))
| (1 << (ClickHouseParser.K_... | |
u"cadmium",
u"showers: angular distribution",
u"magnetic field: measurement methods",
u"cross section: high energy behavior",
u"Walecka model",
u"neutrino: Dirac: mass",
u"nuclear matter: saturation",
u"Delta(1232): width",
u"damage",
u"Sp(2)",
u"neutralino: direct detection",
u"analyzing power: tensor",
u"... | |
# Simulates a network with nodes, where each node can be either a
# transmitter or receiver (but not both) at any time step. The simulation
# examines the coverage based on the signal-to-interference ratio (SINR).
# The network has a random medium access control (MAC) scheme based on a
# determinantal point process, as... | |
= precfloat((float(Operation_info[h]['swap_asks_price5'][0]) + float(Operation_info[h]['swap_bids_price5'][0])) / 2, Necessary_info[h]['swap_tick_digit'])
else:
swap_close_price = precfloat(float(Operation_info[h]['swap_bids_price5'][0]), Necessary_info[h]['swap_tick_digit'])
mode_take_close_long_order = {'swap_inst... | |
DESTROYED.
destroyTime: Output only. The time this CryptoKeyVersion's key material is
scheduled for destruction. Only present if state is DESTROY_SCHEDULED.
externalProtectionLevelOptions: ExternalProtectionLevelOptions stores a
group of additional fields for configuring a CryptoKeyVersion that are
specific to the... | |
# update_I()
#-------------------------------------------------------------------
def update_q0(self):
if (self.DEBUG):
print 'Calling update_q0()...'
#-----------------------------------------------
# Note: self.q0 = np.float64(0) in __init__().
# Most infil methods don't compute q0.
# This method is over-r... | |
<filename>kivymd/uix/button.py
"""
Components/Button
=================
.. seealso::
`Material Design spec, Buttons <https://material.io/components/buttons>`_
`Material Design spec, Buttons: floating action button <https://material.io/components/buttons-floating-action-button>`_
.. rubric:: Buttons allow users to ... | |
cohen_kappa_score(y_vl, pred_test_y_k,weights='quadratic')
cv_score = rmse(y_vl, y_pred)
cv_scores.append(cv_score)
qwk_scores.append(qwk)
all_coefficients[i, :] = coefficients
print( ' cv score {}: RMSE {} QWK {}'.format(i+1, cv_score, qwk))
print("##"*40)
print('cv mean RMSE score : {}'.format( np.mean(cv_sc... | |
from subprocess import STDOUT
import sys
from tf.transformations import rotation_matrix
sys.path.insert(0, './yolov5')
from yolov5.utils.datasets import LoadImages, LoadStreams,LoadWebcam,LoadRealsense
from yolov5.utils.general import check_img_size, non_max_suppression, scale_coords
from yolov5.utils.torch_utils impo... | |
resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk
:param 'DatadogAgentSpecClusterChecksRunnerConfigVolumesGitRepoArgs' git_repo: GitRepo represents a git repository at a particular revision. DEPRECATED: Gi... | |
"""Graph visualization with HTML/CSS/JS based on d3.v7.js."""
from ..conversion import _internal
from ..utils.args import check_arg as _ca
from . import data_structures as _ds
from . import template_system as _ts
def d3(data,
graph_height=450, details_height=100,
show_details=False, show_details_toggle_button=True... | |
json.dumps(nds_travel_mode, ensure_ascii=False)
break
else:
travel_mode = ""
if travel_mode:
self.logger.debug(u"Returning travel mode JSON from the network dataset for travel mode name: {}".format(travel_mode_name))
return travel_mode
def _getPortalTravelModeJSON(self, travel_mode_name):
'''Returns a stringif... | |
# -*- coding: utf-8 -*-
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import binascii
import collections
import datetim... | |
import os
import time
import json
import zipfile
import base64
from distutils.util import strtobool
from uuid import uuid1
import django
from django.core.exceptions import ValidationError
from django.conf import settings
from django.http.response import FileResponse, HttpResponse
from django.db.models import Q
from dj... | |
<reponame>microtodd/yamledit
#!/usr/bin/python
#
# yamledit.py
# github.com/microtodd/yamledit
#
import os
import sys
import getopt
import ruamel.yaml
from ruamel import yaml
from ruamel.yaml.scalarstring import SingleQuotedScalarString, DoubleQuotedScalarString
__version__ = '0.5'
# TODO
#
# ) merge two yaml files c... | |
local2canonical ADD INDEX( src ), ADD INDEX( local ), ADD INDEX( canonical )"
execute( c, txt )
txt = "ALTER TABLE local2canonical ADD FULLTEXT( canonical )"
execute( c, txt )
if SQLITE:
txt = "CREATE INDEX local2canonical_index ON local2canonical( src, local, canonical )"
execute( c, txt )
conn.commit()
ret... | |
# Copyright (c) 2016 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to the S... | |
wrong because you can mark-for-deployment before deploying there"
)
)
print(
PaastaColors.red(
"but this is probably a typo. Did you mean one of these in-use deploy groups?:"
)
)
print(PaastaColors.red(" %s" % (",").join(in_use_deploy_groups)))
print()
print(PaastaColors.red("Continuing regardless..."))
if ... | |
bottom left gridpoint in meters
"""
self.nx = nx
self.ny = ny
self.dx = dx
self.dy = dy
self.xmin = xmin
self.ymin = ymin
# The swiss grid is not technically using a PlateCarree projection
# (in fact it is not using any projection implemented by cartopy),
# however the points returned by the cell_corners() m... | |
<reponame>nlafl/Network-Level-Adversaries-in-Federated-Learning
import os
import random
import numpy as np
from nlafl import common
def load_emnist():
""" Load the EMNIST dataet
Returns:
tuple: tuple of numpy arrays trn_x, trn_y, tst_x, tst_y
"""
trn_x = np.load(os.path.expanduser(common.emnist_trn_x_pth))
... | |
<reponame>FlamesLLC/GBACopilotv0<gh_stars>0
##
print("Welcome to GBAPY 1.0X")
## please make a gba emulator like no$gba
import socket
import sys
import time
import os
import threading
import time
import random
## please make the framework for the gui and make it look like a gba emulator with the width and ... | |
<reponame>edupaz2/Udacity-SelfDCars-CarND-Advanced-Lane-Lines
from glob import glob
import numpy as np
import cv2
import matplotlib.pyplot as plt
import pickle
CALIBRATION_IMAGES_PATH = 'camera_cal/calibration*.jpg'
CALIBRATION_POINTS_PATH = 'camera_cal/calibration.p'
nx = 9
ny = 6
# Define conversions in x and y from... | |
case
stats_df = _stats_numpy(
zones,
values,
zone_ids,
stats_funcs_dict,
nodata_zones,
nodata_values
)
else:
# dask case
stats_df = _stats_dask(
zones,
values,
zone_ids,
stats_funcs_dict,
nodata_zones,
nodata_values
)
return stats_df
def _crosstab_dict(zones, values, unique_zones, cats, nodata_val... | |
<filename>silx/gui/fit/FitWidgets.py
# coding: utf-8
# /*##########################################################################
# Copyright (C) 2004-2016 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documen... | |
all specified nodes for the deletion task.
:param nodes:
:param mclient_remove:
:return: dict
"""
nodes_to_delete = []
nodes_to_restore = []
for node in nodes:
nodes_to_delete.append(
cls.format_node_to_delete(node, mclient_remove=mclient_remove)
)
if not node.pending_deletion:
objects.Node.update(node, ... | |
assert batch[0][0].device.index == 0 and batch[0][0].type() == 'torch.cuda.FloatTensor'
assert batch[0][1].device.index == 0 and batch[0][1].type() == 'torch.cuda.FloatTensor'
# tensor dict
batch = [{'a': torch.rand(2, 3), 'b': torch.rand(2, 3)}]
batch = trainer.transfer_batch_to_gpu(batch, 0)
assert batch[0]['a'... | |
[0, 1, 2]
height = images.shape[2]
width = images.shape[3]
y_offset = int(math.ceil((height - size) / 2))
x_offset = int(math.ceil((width - size) / 2))
if height > width:
if spatial_idx == 0:
y_offset = 0
elif spatial_idx == 2:
y_offset = height - size
else:
if spatial_idx == 0:
x_offset = 0
elif spatial... | |
either float32, float64, complex64 or
complex128.
Note about BEM++ terminology: a *potential operator* acts on functions
defined on a surface S and produces functions defined at any point of the
space surrounding S, but not necessarily on S itself. In contrast, a
*boundary operator* acts on on functions defined o... | |
<reponame>simon-m-mudd/LSDMappingTools
"""
A set of functions to do some simple statistical analyses
Created on Thu Jun 8th 2017
Author: SMM
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import pandas as pd
import scipy.stats as ss
# This function comes f... | |
view.
:type type: object
:param url: Url of the view.
:type url: str
:param visibility: Visibility status of the view.
:type visibility: object
"""
_attribute_map = {
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'... | |
<gh_stars>0
import torch
import matplotlib.pyplot as plt
import numpy as np
import os
import time
from termcolor import cprint
from utils_numpy_filter import NUMPYIEKF
from utils import prepare_data
class InitProcessCovNet(torch.nn.Module):
def __init__(self):
super(InitProcessCovNet, self).__init__()
self.beta_p... | |
<reponame>DarthLazar/lenstronomy
__author__ = 'sibirrer'
import numpy as np
import copy
from lenstronomy.Util import class_creator
from lenstronomy.ImSim.image2source_mapping import Image2SourceMapping
from lenstronomy.LensModel.Solver.solver import Solver
from lenstronomy.LensModel.lens_param import LensParam
from le... | |
present and of the correct Python type.
parameterTypesBasicFields = swagGl.BASIC_PARAMETER_FIELDS.get(paramSwag['type'],{})
for basicFieldName in parameterTypesBasicFields:
fieldRules = parameterTypesBasicFields[basicFieldName]
if fieldRules['required'] and basicFieldName not in paramSwag:
raise CustomExc... | |
<gh_stars>0
import sys
#!{sys.executable} -m pip install nltk
import re
import random
from nltk import PCFG, Tree, nonterminals
from typing import *
from generator import generate, create_dataset_json, combine_dataset_jsons
S, VP, NP_nom3, NP_acc, PP, V_trans, Person, V_intrans = nonterminals(
'S, VP, NP_nom3, NP_a... | |
# -*- coding: UTF-8 -*-
from mpi4py import MPI
from sympy import pi, cos, sin
import pytest
import os
from sympde.calculus import grad, dot
from sympde.topology import ScalarFunctionSpace, VectorFunctionSpace
from sympde.topology import ProductSpace
from sympde.topology import element_of
from sympde.topology import N... | |
<filename>role_analyzer.py
from dataclasses import dataclass
from enum import Enum
import logging
import re
import sre_constants
import sre_parse
import typing
import z3 # type: ignore
@dataclass
class EntityTypeInfo:
"""
Information about an entity type (node, k8s cluster, etc.)
---------------------------------... | |
USA, which receives no attribution
if zoneGovt.strip() == "":
zoneGovt = "US"
# If we do not already know about this government
if zoneGovt not in govtList:
# Add it now
govtList.append(zoneGovt)
#---------------------------------------------------------------
# Get the impacted zones for this segment
ugcC... | |
<reponame>miklobit/OpenTimelineIO<gh_stars>1-10
#
# Copyright 2017 <NAME>ios
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks... | |
"%s" onbekend',
},
{
"language": "zh",
"use": {
"code": "display",
"system": "http://terminology.hl7.org/CodeSystem/designation-usage",
},
"value": '无法理解参数"%s"',
},
{
"language": "es",
"use": {
"code": "display",
"system": "http://terminology.hl7.org/CodeSystem/designation-usage",
},
"value": 'Parámetro... | |
"""
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
"""
import argparse
import copy
import datetime
import os
import time
import numpy as np
import pandas as pd
import rasterio
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from ... | |
cp = self.names['CP'], site = self.names['site'],
diagnosis ="Not Specified", status = "Not Specified", activity = "Active", unit = "DAYS")
assert str(response).lower().find('error')==-1, "Error creating an Event: "+str(response)
assert bool(response), "Error creating an Event"
self.ID['event']=response['id']
self... | |
import copy
import operator
import itertools
import scipy.stats
import numpy as np
import pandas as pd
import plum.util.data
import scipy.optimize
import sklearn.metrics
from plum.models.modelABC import Model
#from plum.util.cpruning import getNodeProbs, getNodeProbs_prior_weighted
from plum.util.cpruning import cgetN... | |
for tf in dict_lines_to_keep_per_tf.keys():
adjusted_dict_p_values_per_tf[tf] = adjust_pvales(dict_p_values_per_tf[tf])
adjusted_dict_p_values_overall_per_tf[tf] = adjust_pvales(dict_p_values_overall_per_tf[tf])
#get the sig and write them to output file
for i, tf_motif in enumerate(dict_lines_to_keep_per_tf[tf]):
... | |
[val]
for each in val:
if not isinstance(each, Variable):
raise ValueError("input of {0} must be variable".format(
op_type))
if dtype is None:
dtype = each.dtype
elif dtype != each.dtype:
raise ValueError(
"operator {0} must input same dtype. {1} vs {2}".format(
op_type, dtype, each.dtype))
return dtype
... | |
"""
Code to extract a box-like region, typically for another modeler to use
as a boundary contition. In cases where it gets velocity in addition to
the rho-grid variables the grid limits mimic the standard ROMS organization,
with the outermost corners being on the rho-grid.
Job definitions are in LO_user/extract/box/j... | |
<gh_stars>0
# -*- coding: utf-8 -*-
#
# awsdbrparser/parser.py
#
# Copyright 2015 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.
# You may obtain a copy of the License at
#
# ... | |
<reponame>himanshu-setia/myKeystone
# 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,... | |
# General
import os, sys, pickle, json
import pandas as pd
import numpy as np
# Dash and plotly
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import plotly.graph_objs as go
# colors
import matplotlib
from matplotlib import cm
# Mat... | |
<reponame>Volumental/tc-hue
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
phue by <NAME> - A Philips Hue Python library
Contributions by <NAME>, <NAME>
https://github.com/studioimaginaire/phue
Original protocol hacking by rsmck : http://rsmck.co.uk/hue
Published under the MIT license - See LICENSE file for more detai... | |
<gh_stars>10-100
from tkinter import *
from tkinter.ttk import *
from tkinter import ttk
import tkinter.messagebox as ms
import os
import database
class RecordManagement(Frame):
# Constructor Function
def __init__(self, root):
root.maxsize(560,500)
root.minsize(560,500)
root.wm_iconbitmap('RecordManager-icon.ic... | |
center
# distmat = matrix with squared distance from center (more efficient if calculated only once)
# use kernel:
# if True: select based on region overlap AND distance from center in stage 2,
# otherwise only use overlap from first pass
# Note: always use kernel when first pass returns nothing
zdim, xdi... | |
print(
"\b\b\b{:02d}%".format(pct),
file=sys.stderr,
end="",
)
if args.gui:
worker.updateProgress(pct)
sys.stderr.flush()
os.remove("ffmpeg.log")
if os.path.exists(image["img"] + ".webp"):
ET.SubElement(asset, "type").text = "animatedImage"
ET.SubElement(asset, "resource").text = (
image["img"] + ".webp"
)... | |
'_TKE_' + str(className))
ResultsLists_class = populate_resultsLists(ResultsLists_class, 'class_', adjustment_name, lm_adj,
inputdata_adj, Timestamps, method)
className += 1
ResultsList_stability = populate_resultsLists_stability(ResultsLists_stability, ResultsLists_class, '')
if RSD_alphaFlag:
print('Apply... | |
import os
import argparse
from datetime import datetime
import time
import torch
import torch.nn.functional as F
import torch.multiprocessing as mp
import numpy as np
import pandas as pd
from tqdm import tqdm
import matplotlib
import matplotlib.pyplot as plt
from tensorboardX import SummaryWriter
import data
import... | |
<filename>scripts/preprocessing/bcdi_read_BCDI_scan.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# BCDI: tools for pre(post)-processing Bragg coherent X-ray diffraction imaging data
# (c) 07/2017-06/2019 : CNRS UMR 7344 IM2NP
# (c) 07/2019-present : DESY PHOTON SCIENCE
# authors:
# <NAME>, <EMAIL>
try:
import h... | |
SNAPSHOT_KEYS_IDX,
'timestamp_keys_idx': TIMESTAMP_KEYS_IDX,
}
TARGETS_KWARGS = {
'targets_keys_idx': TARGETS_KEYS_IDX,
}
SNAPSHOT_KWARGS = {
'snapshot_keys_idx': SNAPSHOT_KEYS_IDX,
}
TIMESTAMP_KWARGS = {
'timestamp_keys_idx': TIMESTAMP_KEYS_IDX,
}
class DirectorStep(Step):
TARGETS_KEYS_IDX = [5]
RO... | |
#!/usr/bin/env python
#
# Copyright 2018 VMware, Inc.
# SPDX-License-Identifier: BSD-2-Clause OR GPL-3.0-only
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FO... | |
import random
import sys
import math
import pygame
from pygame.locals import *
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import SGD
START_MUTATION_RATE = 0.1
MIN_MUTATION_RATE = 0.05
MUTATION_STEP = 0.05
POPULATION_SIZE = 50... | |
import re
import inspect
import copy
import torch
from pykeops.torch.kernel_product.formula import Formula
from pykeops.torch.kernel_product.features_kernels import FeaturesKP
# Define the standard kernel building blocks.
# They will be concatenated depending on the "name" argument of Kernel.__init__
# Feel free to ... | |
<reponame>zhanghxpku/project-3-for-EMNLP-course
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
import datetime
import logging
import numpy as np
import tensorflow as tf
from tensorflow.python import debug as tf_debug
from utils import get_dataset
import traceback
from tensorflow.python.client impo... | |
def spb_setRange(self, minTuple, maxTuple):
"""
This function does the job of setting the Maximum value and Minimum value in one go.
...
Parameters
--------------
maxTuple : tuple
Maximum value of each progressbar, in tuple, with elements in order
Ex: maxVal = (100, 200, 300) : corresponding to 100 for the ou... | |
<filename>cubepy/factory.py
#functions for use as: import cubepy.factory as cp
import numpy as np
import cubepy
import numbers
from sys import platform
from cubepy.cube import kindToString, apply_op
import os
import csv
random = -123798
byVal = 1
byPos = 2
exact = 1
start_with = 2
end_with = 3
contain = 4
def cub... | |
Client identifier, takes precedence over headers
:param str x_user_agent: Client identifier, takes precedence over User-Agent
:return: list[GetCorporationsCorporationIdBlueprints200Ok]
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['corporation_id', 'datasource', 'page', 't... | |
<filename>dnsMasterChef.py
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from optparse import OptionParser, OptionGroup
from configparser import ConfigParser
from dnslib import *
from IPy import IP
import threading
import random
import operator
import time
import socketserver
import socket
import sys
import os
import bin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.