input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<filename>dragg/reformat.py
import os
import sys
import json
import toml
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
import itertools as it
import random
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.io as pio
i... | |
"Laotian",
"Laos People's Democratic Republic"
],
"latvia": [
"Latvia",
"Latvian",
"Latvians"
],
"lebanon": [
"Lebanon",
"Lebanese"
],
"lesotho": [
"Lesotho",
"Basotho",
"Basothos"
],
"liberia": [
"Liberia",
"Liberian",
"Liberians"
],
"libya": [
"Libya",
"Libyan",
"Libyans"
],
"liechtenstein"... | |
[self.target_variable_name]:
mice_data.set_imputer(
var, model_class=discrete_model.Logit, fit_kwds={"disp": False}
)
return mice_data
def _run_mice_loop(self, split_i: int, fold: str, mice_data: MICEData):
"""'Burn-in' and 'skip' imputations are discarded."""
for _ in range(self.n_mice_burn_in):
mice_data.upd... | |
data_dict[old_name]['end_line'] - data_dict[old_name]['start_line']
df = make_df(lines, start, nrows, df_header)
data_dict[old_name]['Data'] = df
varchange = True
elif "Analysis begun on" in lines[i]: # Catch last item to be parsed
main_logger.info("EPASWMM Model: " + lines[i].strip())
data_dict[old_name]['end_l... | |
<gh_stars>1-10
import numpy as np
import torch
from value_iteration.pendulum import BaseSystem
from value_iteration.cost_functions import ArcTangent, SineQuadraticCost, BarrierCost
CUDA_AVAILABLE = torch.cuda.is_available()
class Cartpole(BaseSystem):
name = "Cartpole"
labels = ('x', 'theta', 'x_dot', 'theta_dot')... | |
<reponame>glanyx/segachan<gh_stars>0
import datetime
import typing
import discord
from discord.ext import commands
from sqlalchemy.sql import func
from sweeperbot.cogs.utils import log, time
from sweeperbot.cogs.utils.timer import Timer
from sweeperbot.db import models
from sweeperbot.utilities.helpers import has_gui... | |
"failed".
* DeleteClusterSnapshot returns status as "deleted".
- **Port** *(integer) --*
The port that the cluster is listening on.
- **AvailabilityZone** *(string) --*
The Availability Zone in which the cluster was created.
- **ClusterCreateTime** *(datetime) --*
The time (UTC) when the cluster was origina... | |
#!/usr/bin/env python
# coding: utf-8
# In this notebook, I delete a triple from the neighbourhood of the target triple based on the **IJCAI deletion scores**
#
# - neighbourhood refers to the triples that share the entities with target's entities
# - I get the deletion from both neighbourhood of s and o, then choos... | |
= value
def get_uncertain_state_set(self): return self.uncertain_state_set
def set_uncertain_state_set(self, uncertain_state_set): self.uncertain_state_set = uncertain_state_set
def add_uncertain_state_set(self, value): self.uncertain_state_set.append(value)
def insert_uncertain_state_set(self, index, value): self.... | |
import asyncio
import copy
import logging
import talib as ta
from .exceptions import NotImplementedException
from sklearn.cluster import KMeans, DBSCAN, MeanShift
from sklearn.metrics import silhouette_score
import pandas as pd
import numpy as np
from itertools import groupby
from operator import itemgetter
from .utils... | |
# /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: <NAME>
@email: <EMAIL>
"""
from utils import *
# Fig.~S1a&c
def Analysis_halfyear(interactions):
Data = read('Results/Graph_Halfyear_TR_{}.txt'.format(interactions))
avg2, avg3, avg4, avg5, avg6 = [], [], [], [], []
for data in Data:
if data.count('-1') =... | |
from apps.lockto.utils import get_lockto_coll
from apps.fields.fields import unflatten_name, field_item_types
from apps.record.errors import ValidationError
from apps.shortcuts import getparam, getintparam, getparamlist, url
from apps.store.models import Collection
from apps.store.search import Collection as SearchColl... | |
<gh_stars>1-10
from __future__ import division, absolute_import
from struct import unpack as _unpack, pack as _pack
import os.path
from sys import byteorder as _BYTEORDER
import warnings
import numpy as np
from .spacegroups import GetSpaceGroup
from ._extensions import extend_to_p1
class Volume(object):
def __ini... | |
<filename>dbinit/patch.py
from utility import *
def patchMissilesDamage(env):
addEffect(10000, 'characterDamageMissiles', EffectCategory.passive, False, False, env)
addEffectGroup('Character', 'characterDamageMissiles', env)
updateEffect('characterDamageMissiles', env, [OwnerRequiredSkillModifier(Domain.charID, 'Mi... | |
y_self_bool['hat'] - y
failures = diff != 0
print('^' * 80)
print(type(failures))
print(failures.describe())
print(failures[:5])
failures_df = Series([False] * len(df), index=df.index)
for idx, val in failures.iteritems():
failures_df[idx] = val
df = df[failures_df]
y_self_df = Series([0.0] * len(df... | |
<filename>processing/processor.py<gh_stars>0
'''
Description: Implements the processors which generate the products the system
is capable of producing.
License: NASA Open Source Agreement 1.3
'''
import os
from os.path import expanduser
import shutil
import glob
import json
import datetime
import copy
import subproc... | |
Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
)
# Send the request.
response = rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# This method is paged; ... | |
<gh_stars>0
# MIT License
#
# Copyright (c) 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 Software without restriction, including without limitation the rights
# to use, copy, modify, ... | |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2013-2014, gamesun
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the ... | |
import enum
import pickle
from dataclasses import dataclass, replace
from typing import Callable, List
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
import optax
from einops import rearrange
from jax.example_libraries.optimizers import l2_norm
from jax.random import PRNGKey
from jax.tree_uti... | |
bool(state["Paused"]):
print("Container is in Paused State")
elif bool(state["Running"]):
print("Container is in Running State")
elif int(state["ExitCode"]) == 0:
print("Container is in Stopped State")
else:
print("Container is in Crashed State")
print("Ip Address of the container: " +detail['NetworkSettings']... | |
fit_types = self.fit_types
num_gen = self.num_gen
num_pop = self.num_pop
num_var = self.num_var
try:
fitl = [list(x) for x in zip(*self.parent_pop['fit_values'])]
best = [self.get_sorting_indices(l, reverse=False)[0] if self.fit_types[i] == 'min' else self.get_sorting_indices(l, reverse=True)[0] for i, l in... | |
x = cx - w/2
y = cy - h/2
pygame.draw.rect(screen, DARKRED, [x, y, w, h])
pygame.draw.rect(screen, DARKRED, [x, y, w, h], 4)
if mistakes < 5:
pygame.draw.rect(screen, LIGHTRED, [x+1, y+1, w-(w*(mistakes/(strikes-1)))-1, h-1])
## this life bar is pretty simple. I use center-x and center-y so it would be easier t... | |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... | |
<gh_stars>100-1000
import functools
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmseg.utils import resize
from mmseg.accuracy import accuracy
import math
from utils.coco_dataset import transform_preds
def cross_entropy(pred,
label,
weight=None,
class_weight=None,
redu... | |
<gh_stars>1-10
import time
import json
from service_fabrik_backup_restore import parse_options, create_iaas_client
def main():
# +-> Definition of constants
DIRECTORY_PERSISTENT = '/var/vcap/store'
DIRECTORY_SNAPSHOT = '/tmp/service-fabrik-backup/snapshot'
DIRECTORY_UPLOADS = '/tmp/service-fabrik-backup/uploads'
... | |
<reponame>gxdai/solt<filename>tests/test_transforms.py
import copy
import random
from contextlib import ExitStack as does_not_raise
import cv2
import numpy as np
import pytest
import solt.core as slc
import solt.transforms as slt
from solt.constants import ALLOWED_INTERPOLATIONS, ALLOWED_PADDINGS
from .fixtures imp... | |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 16 10:07:16 2020
PSDM Tools
----------
This file contains tools and associated functions geared at aiding in the
analysis of GAC adsorption data.
Functions Contained:
isotherm_fit()
predict_full_scale()
specific_throughput()
@author: <NAME>
EPA Disclaimer
=====... | |
<reponame>asrozar/python-netrecon<gh_stars>1-10
from netrecon import shared
from pexpect import TIMEOUT
from re import search, compile as recompile
from netaddr import IPAddress
from ipaddress import IPv4Network, IPv4Address
import time
def host_discovery(system_address, username, password):
ssh_session, prompt = sh... | |
"""Submodule provinding GAN model architectures."""
import torch
import torch.optim as optim
from torch import nn
from typing import Callable
class GANModel(torch.nn.Module):
def __init__(
self,
generator_model: torch.nn.Module,
encoding_model: torch.nn.Module,
masking_layer: torch.nn.Module,
image_preprocessi... | |
# -*- coding: utf-8 -*-
"""
Interface into SQL for the IBEIS Controller
TODO; need to use some sort of sticky bit so
sql files are created with reasonable permissions.
"""
import functools
import logging
import collections
import os
import parse
import re
import uuid
from collections.abc import Mapping, MutableMapping... | |
data = {
'data': {
'type': 'contributors',
'attributes': {
'bibliographic': True,
'permission': 'invalid',
},
'relationships': {
'users': {
'data': {
'id': self.user_two._id,
'type': 'users'
}
}
}
}
}
res = self.app.post_json_api(self.private_url, data, auth=self.user.auth, expect_errors=True)
assert_... | |
<gh_stars>0
import pdb
import time
import os
import subprocess
import re
import random
import json
import numpy as np
import glob
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
import socket
import argparse
import threading
import _thread
import signal
from datetime import datetime
... | |
import pytest
import sys
import time
from appdirs import user_config_dir
import os
import attr
import tempfile
import json
from functools import partial
dn = os.path.dirname
import devapps
# sys.path.insert(0, dn(dn(os.path.abspath(__file__))))
# import setup_method as devapps
# default providers:
CLI, Env, File = d... | |
c) are not uuid.
for col in [fld for fld in df.columns.difference(["uuid"]) if fld.endswith("id") and dtypes[fld] == "str"]:
# Subset dataframe to required column with non-default and non-"None" values.
series = df.loc[~df[col].isin([defaults[col], "None"]), col]
if len(series):
# Validation 1: ensure ids are 3... | |
the charm.
kubelet_extra_config = hookenv.config('kubelet-extra-config')
kubelet_extra_config = yaml.safe_load(kubelet_extra_config)
merge_kubelet_extra_config(kubelet_config, kubelet_extra_config)
# Render the file and configure Kubelet to use it
os.makedirs('/root/cdk/kubelet', exist_ok=True)
with open('/root/... | |
#@title
import numpy as np
import re
import string
import jax
import cmath
from typing import List
import tensorflow as tf
import tensornetwork as tn
from colorama import Fore
from colorama import Style
from itertools import product
class QCircuit:
"""Implementation of a QCircuit."""
def __init__(self, num_qubits,... | |
minimum
if callable(V):
Vrel = lambda r : V(r) - Emin
else:
Vrel = V - Emin
# compute low-lying levels E(v, J)
EvJ = np.zeros((3, 3))
for Nrot in range(3):
J = Nrot + omega
if callable(Vrel):
centrifug = lambda r : Vrel(r) + (J*(J+1)-omega*omega)/(2*mass*r*r)
else:
centrifug = Vrel + (J*(J+1)-omega*omega)/(... | |
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | |
# coding: utf-8
import pprint
import six
from enum import Enum
class SubscriptionProductVersion:
swagger_types = {
'activated_on': 'datetime',
'billing_cycle': 'str',
'comment': 'str',
'created_on': 'datetime',
'default_currency': 'str',
'enabled_currencies': 'list[str]',
'id': 'int',
'increment_number':... | |
<reponame>anna-hope/python-firestore
# Copyright 2017 Google LLC 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... | |
# type: ignore
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
import copy
from requests import Response
class AzureFirewallClient:
def __init__(self, subscription_id: str,
resource_group: str,
client_id: str,
api_version: str,
verify: bool,
proxy: bool,
client_secret: ... | |
<filename>tests/test_distribution.py
"""Test cases for the distribution module."""
from decimal import Decimal
from pytest_mock import MockFixture
from rdflib import Graph
from rdflib.compare import graph_diff, isomorphic
from skolemizer.testutils import skolemization
from datacatalogtordf import DataService
from dat... | |
neg = pos = 0
event = self.event
for e in events:
event.update(e)
voltage = self.get_voltage(event)
if voltage is not None:
neg += voltage["neg"]
pos += voltage["pos"]
self._state = int(neg / len(events) + pos / len(events))
self.attrs = dict(neg=round(float(neg / len(events)), 2), pos=round(float(pos / len(ev... | |
'APIGetVmMonitorNumberMsg',
'APIGetVmMonitorNumberReply',
'APIGetVmQgaMsg',
'APIGetVmQgaReply',
'APIGetVmRDPMsg',
'APIGetVmRDPReply',
'APIGetVmSshKeyMsg',
'APIGetVmSshKeyReply',
'APIGetVmStartingCandidateClustersHostsMsg',
'APIGetVmStartingCandidateClustersHostsReply',
'APIGetVmUsbRedirectMsg',
'APIGetVmUsbR... | |
is not None:
oprot.writeFieldBegin('tid', TType.STRUCT, 1)
self.tid.write(oprot)
oprot.writeFieldEnd()
if self.auth is not None:
oprot.writeFieldBegin('auth', TType.STRING, 2)
oprot.writeString(self.auth)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def _... | |
currency_type: the type of the currency
:type currency_type: ``osid.type.Type``
:return: the list of supported currency format types
:rtype: ``osid.type.TypeList``
:raise: ``NullArgument`` -- ``currency_type`` is ``null``
*compliance: mandatory -- This method must be implemented.*
"""
return # osid.type.TypeLi... | |
<filename>src/cool_to_cil.py
from semantic import Scope, VariableInfo
import visitor
import ast_nodes as COOL_AST
import cil_ast_nodes as CIL_AST
class BaseCOOLToCILVisitor:
def __init__(self, context):
self.dottypes = {}
self.dotdata = {}
self.dotcode = []
self.current_type = None
self.current_method... | |
the constraint relies on attribute values from other nodes,
# use the LHS/NAC constraint instead.
# The given constraint must evaluate to a boolean expression.
#===============================================================================
return True
"""
self.vs[4]["MT_dirty__"] = False
self.vs[4]["GUID__"] = UUID... | |
short_name = process_swagger_name(ref)
fullname = full_swagger_name(ref)
mod_def = get_module_def(version)
item_ref = mod_def.get_class_desc(short_name)
if item_ref is None:
item_ref = ClassDescriptor(fullname, {}) # make a placeholder
mod_def.save_class_desc(item_ref)
else:
itype = items.get("type")
if itype:... | |
1",
" two" : " 2",
" three" : " 3",
" four" : " 4",
" five" : " 5",
" six" : " 6",
" seven" : " 7",
" eight" : " 8",
" nine" : " 9",
" zero" : " 0"
}
for idx, turn in self.data.items():
slots_str = ", ".join([" ".join(slot) for slot in turn["slots"]])
if domain in turn["domains"]:
if domain+" "+slot_type... | |
<filename>ACME-oneM2M-CSE-master/tests/testMgmtObj.py
#
# testMgmtObj.py
#
# (c) 2020 by <NAME>
# License: BSD 3-Clause License. See the LICENSE file for further details.
#
# Unit tests for all kind of MgmtObj specialisations
#
import unittest, sys
import requests
sys.path.append('../acme')
from typing import Tuple
fr... | |
newDirDialog = QtGui.QInputDialog()
newDirDialog.setFocus()
dirName, ok = newDirDialog.getText(self, 'Add Directory', 'Enter directory name:')
if ok:
if dirName == '' or '/' in dirName:
warn_str = "add directory failed: the new directory name is an empty string or contains /: " + str(dirName) + "; directory not ad... | |
<gh_stars>1-10
import unittest
import datetime
import pytz
from forthic.interpreter import Interpreter
from forthic.tokenizer import DLE
from forthic.global_module import GlobalModuleError
class TestGlobalModule(unittest.TestCase):
def test_literal(self):
interp = Interpreter()
interp.run("TRUE FALSE 2 3.14 2020-06... | |
_find_only_threshold(self):
with torch.no_grad():
last_layer_fraction = self.nap_params.pop("last_layer_fraction", None)
self._get_layers_shapes(self.nap_params)
self.monitor = FullNetMonitor(self.class_count, self.nap_device,
layers_shapes=self.monitored_layers_shapes)
if not last_layer_fraction:
self.omit = Fa... | |
import inspect
import re
import pkg_resources
from PyQt5 import uic, QtGui, QtCore, QtWidgets
import numpy as np
import collections
import time as ttime
from isstools.elements import elements
from isstools.trajectory.trajectory import trajectory_manager
from isstools.batch.batch import BatchManager
ui_path = pkg_reso... | |
def is_proper_descendant_of(self, node1, node2):
return (self.is_descendant_of(node1, node2) and not (node1 == node2))
# Returns true iff node1 is a descendant of node2.
def is_descendant_of(self, node1, node2):
i = self.node_map[node1]
j = self.node_map[node2]
return self.dpath[i, j] == 1
# Returns the edge... | |
using Base64.
:param str to_encode: The string to encode.*
:param int to_encode: The integer to encode.*
:param float to_encode: The decimal to encode.*
:param bool to_encode: The boolean to encode.*
:param bytes to_encode: The bytes to encode.*
:param bool return_bytes: If True, this method will return the resu... | |
"""
lakeFS API
lakeFS HTTP API # noqa: E501
The version of the OpenAPI document: 0.1.0
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from lakefs_client.api_client import ApiClient, Endpoint as _Endpoint
from lakefs_client.model_utils import ( ... | |
<reponame>eberharf/cfl
import pickle
import json
import os
import numpy as np
from cfl.dataset import Dataset
from cfl.block import Block
import cfl.density_estimation_methods as cdem
import cfl.cluster_methods as ccm
from cfl import intervention_rec
'''
Methods in Experiment Class:
train()
predict()
__save_resul... | |
the type returned by ctx.Lock()?
self.data_blocks: typing.List[SharedMemory] = []
block_id: int
for block_id in range(maxsize):
self.data_blocks.append(SharedMemory(create=True, size=self.__class__.META_BLOCK_SIZE + self.chunk_size))
self.add_free_block(block_id)
def __getstate__(self):
"""This routine retrieve... | |
4], dtype=np.int32)
png_bytes = raster.to_png(transparent=True, thumbnail_size=512)
w = recwarn.pop(GeoRaster2Warning)
assert str(w.message) == "Limiting %d bands raster to first three bands to generate png" % raster.num_bands
w = recwarn.pop(GeoRaster2Warning)
assert str(w.message) == "downscaling dtype to 'ui... | |
CMap()
>>> m[5] = 1
>>> m[8] = 4
>>> i = m.__iter__()
>>> print int(i.next())
5
>>> print int(i.next())
8
>>> print int(i.prev())
5
We are still left with the odd behavior that an
iterator cannot be dereferenced until after the first next().
Ex edge cases:
>>> from CMap import CMap
>>> m = CMap()
>>>... | |
# generated by 'clang2py'
# flags '-c -d -l ftd2xx64.dll ftd2xx.h -vvv -o _ftd2xx64.py'
# -*- coding: utf-8 -*-
#
# TARGET arch is: []
# WORD_SIZE is: 4
# POINTER_SIZE is: 8
# LONGDOUBLE_SIZE is: 8
#
import ctypes
# if local wordsize is same as target, keep ctypes pointer function.
if ctypes.sizeof(ctypes.c_void_p) =... | |
If it is not specified, the numeric
value of the corresponding missing value in Stata is returned.
Returns
-------
List
A list of lists containing the values from the frame.
Each sublist contains values for one observation.
Raises
------
ValueError
This error can be raised if
- any of the variable indic... | |
= output_path + flood_objective["output"]['dret_index']
else:
gwater_index_cover = working_path + intermediate_files['index_cover']
gwater_index_rough = working_path + intermediate_files['index_rough']
gwater_slope_index = output_path + output_files['slope_index']
gwater_comb_weight_R = working_path + interme... | |
and (len(self.params) == 0)):
r = to_python(self.name, context, params)
if (r.startswith(".")):
r = r[1:]
r = indent_str + r
return r
# Is this a VBA internal function? Or a call to an external function?
func_name = str(self.name)
if ("." in func_name):
func_name = func_name[func_name.index(".") + 1:]
impor... | |
vars(self)
for key in attributes:
print(key, ': \t', attributes[key])
class CentralCamera(Camera):
"""
A (central projection) camera class
"""
# list of attributes
_name = [] # camera name (string)
_camtype = [] # camera type (string)
_nu = [] # number of pixels horizontal
_nv = [] # number of pixels verti... | |
a * l1 + entries * l2,
# if we suppose that n, m, i, j > 0 we would have 0 <= a <= n + i and 0 <= entries <= m + j
# If we don't restrict these to be positive, then we only know a has to be between
# the smallest and largest combination of n and i (and similarly for entries)
latt_vect1_mult = np.arange(np.min([... | |
see cytopy.transform.Scaler
scale_kwargs: dict, optional
Additional keyword arguments passed to Scaler
kwargs:
Keyword arguments for initialising Scikit-learn class
Returns
-------
Pandas.DataFrame and None and None
Updated dataframe with a new column named 'meta_label' with the meta-clustering
associations
... | |
from natsort import natsorted
import os
sntrim = sn[0].lower() + sn.split(' ')[1][0]
# rnaorderedkeys = natsorted(drna.keys(), alg=ns.IGNORECASE)
# print(rnaorderedkeys[:10])
output = []
for k in drna.keys():
try:
ddna[k]
except KeyError:
pass
else:
# if the read maps in the RNA and DNA sam fi... | |
# yellowbrick.datasaurus
# Plots a Datasaurus Quartet as an illustration of the importance of visualization.
#
# Author: <NAME>
# Created: Wed Jun 20 15:17:35 2018 -0400
#
# Copyright (C) 2018 District Data Labs
# For license information, see LICENSE.txt
#
# ID: datasaurus.py [] <EMAIL> $
"""
Plots a Datasaurus Quarte... | |
# -*- coding: utf-8 -*-
import itertools
import math
import six
def __get_target_length(size):
"""
Figures out the increased size of the string per
IBM Globalization Design Guideline A3: UI Expansion.
https://www-01.ibm.com/software/globalization/guidelines/a3.html
:param size: Current size of the string.
:... | |
import math
import rvo.math as rvo_math
from .line import Line
from .vector import Vector2
class Agent:
"""
Defines an agent in the simulation.
"""
def __init__(self, simulator):
self.simulator_ = simulator
self.agent_neighbors_ = [] # (float, Agent)
self.obstacle_neighbors_ = [] # (float, Obstacle)
self.or... | |
from typing import Dict, List
import onnx
import torch
from onnx import helper
from ppq.core import (PPQ_CONFIG, ChannelwiseTensorQuantizationConfig,
DataType, OperationMeta, QuantizationProperty,
QuantizationStates, TensorMeta, TensorQuantizationConfig,
convert_any_to_torch_tensor)
from ppq.IR import BaseGraph, Op... | |
# Copyright 2016 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.
"""Instalog datatypes.
Represents data that moves through Instalog (events, attachments) and ways of
iterating through it.
"""
import copy
import dateti... | |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from ydb.public.api.protos import ydb_table_pb2 as ydb_dot_public_dot_api_dot_protos_dot_ydb__table__pb2
class TableServiceStub(object):
"""Missing associated... | |
os.path.splitext(os.path.basename(selected_file))[0])
def accept(self):
selection_success = True
selected_path = self.lineEdit_fileName.text()
selected_filename = os.path.basename(selected_path)
timestamp = str(datetime.datetime.now())
# Remove some characters from timestap to get valid file name:
timestamp = t... | |
initialize the random number generator.
Can be None.
:param balance_experiences: If True, pattern of each class will be equally
spread across all experiences. If False, patterns will be assigned to
experiences in a complete random way. Defaults to False.
:param min_class_patterns_in_exp: The minimum amount of patt... | |
"""Tests for Samsung TV config flow."""
from unittest.mock import call, patch
from asynctest import mock
import pytest
from samsungctl.exceptions import AccessDenied, UnhandledResponse
from samsungtvws.exceptions import ConnectionFailure
from websocket import WebSocketProtocolException
from homeassistant.components.s... | |
portfolio_cfg['seed']
if seed is not None:
set_seed(seed)
if freq is None:
freq = portfolio_cfg['freq']
if broadcast_kwargs is None:
broadcast_kwargs = {}
if wrapper_kwargs is None:
wrapper_kwargs = {}
if not wrapper_kwargs.get('group_select', True) and cash_sharing:
raise ValueError("group_select cannot be d... | |
double *);
void drotg_(double *,double *,double *,double *);
void drotm_( const int*, double *, const int*, double *, const int*, const double *);
void drotmg_(double *,double *,double *,const double *, double *);
void dswap_( const int*, double *, const int*, double *, const int*);
void dcopy_( const int*, const ... | |
# coding: utf-8
"""
3Di API
3Di simulation API (latest stable version: v3) Framework release: 2.9.0 3Di core release: 2.2.2 deployed on: 11:01AM (UTC) on January 11, 2022 # noqa: E501
The version of the OpenAPI document: v3
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
import logging
impor... | |
return pulumi.get(self, "role")
@property
@pulumi.getter
def rules(self) -> Optional[Sequence['outputs.BucketV2ReplicationConfigurationRule']]:
"""
The rules managing the replication.
"""
return pulumi.get(self, "rules")
@pulumi.output_type
class BucketV2ReplicationConfigurationRule(dict):
@staticmethod
def... | |
"#670763",
"#650762",
"#630660",
"#62065e",
"#60055d",
"#5e055b",
"#5d045a",
"#5b0458",
"#5a0357",
"#580355",
"#560254",
"#550252",
"#530151",
"#51014f",
"#50004e",
"#4e004c",
"#4d004b"
],
"CMRmap": [
"#000000",
"#010104",
"#020208",
"#03030c",
"#040410",
"#060614",
"#070718",
"#08081c",
"#09... | |
= tmpTokens[1]
elif (len(tmpTokens) == 3):
if (tmpTokens[1] != "?"):
xName = tmpTokens[1] + "," + tmpTokens[2]
else:
xName = tmpTokens[2]
else:
print " FATAL ERROR ???? !!!! ", tmpTokens, cTokens
sys.exit(-1)
else:
if (len(tmpTokens) == 1):
print " FATAL ERROR ???? !!!! ", tmpTokens, cTokens
sys.exit(-1)
... | |
[no_entity_id
] + [self.label_map[label]
for label in labels] + [no_entity_id]
record = self.Record_With_Label_Id(
token_ids=token_ids,
text_type_ids=text_type_ids,
position_ids=position_ids,
label_id=label_ids)
else:
tokens = self._reseg_token_label(
tokens=tokens, tokenizer=tokenizer, phase=phase)
if len(... | |
index is not in the current frame.',
'Worm index is not in the current frame. Select a valid index.',
QMessageBox.Ok)
return
last_index = self.trajectories_data['worm_index_manual'].max()
new_ind1 = last_index + 1
new_ind2 = last_index + 2
good = self.trajectories_data['worm_index_manual'] == worm_ind
frames... | |
<reponame>polivbr/pulumi-azure-native
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, o... | |
<gh_stars>1-10
import os
import sys
import numpy as np
import tensorflow as tf
from tensorflow.python.keras import backend as K
from tensorflow.python.keras import initializers, regularizers, constraints
from tensorflow.python.keras.layers import Layer
from tensorflow.python.ops import variables as tf_variables
from te... | |
<reponame>emre2038/wazimap-ng
import uuid
import pathlib
import os
from collections import OrderedDict, defaultdict, Mapping
import logging
logger = logging.Logger(__name__)
def format_perc(n):
return f"{n :.2%}"
def format_float(n, decimals=2):
return f"{round(n, decimals) :,}"
def format_int(n):
return f"{roun... | |
self._backSteps == 0:
lst.append(item)
else:
lst.insert(self._backSteps, item)
def _constructHeaders(self):
headers = super()._constructHeaders()
if self._coulombEnergy:
self._add_item(headers, 'Coulomb Energy (kJ/mole)')
if self._atomicVirial:
self._add_item(headers, 'Atomic Virial (kJ/mole)')
if self._nonb... | |
####
####
##
## Project PairsDB
##
## Copyright (C) 2002 <NAME> All rights reserved
##
## Author: <NAME> <<EMAIL>>
##
## $Id: Table.py,v 1.2 2002/11/18 13:03:28 heger Exp $
##
##
####
####
#----------------------------------------------------------------
# Name: Table
#--------------General Information--------------... | |
<filename>vagrant/catalog/application.py
"""Module defining routes and associated methods for the item-catelog Flask applicaiton.
Methods:
show_login: Serves client with page to allows them to sign in using Google OAuth.
gconnect: Connects client using Google OAuth.
gdisconnect: Disconnects the client from the serv... | |
b=4, size=0)]
"""
jeżeli self.matching_blocks jest nie Nic:
zwróć self.matching_blocks
la, lb = len(self.a), len(self.b)
# This jest most naturally expressed jako a recursive algorithm, but
# at least one user bumped into extreme use cases that exceeded
# the recursion limit on their box. So, now we maintain a... | |
<reponame>sail-sg/mugs
# Copyright 2022 Garena Online Private Limited
#
# 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 app... | |
import numpy as np
import sys
class field():
def __init__( self, rows, columns):
if ((rows < 5 or rows > 19) or (columns < 5 or columns > 19)):
print("Game field size limited to 5..19 x 5..19.")
exit()
self.__rows = rows
self.__columns = columns
self.__rows_to_win = 5
self.__field = np.zero... | |
else:
for i in range(p):
phi.append(B[:, i * q : (i + 1) * q])
if check_stationarity:
M = np.zeros((p * q, p * q))
for i in range(p):
M[0:q, i * q : (i + 1) * q] = phi[i]
for i in range(1, p):
M[i * q : (i + 1) * q, (i - 1) * q : i * q] = np.eye(q, q)
r, v = np.linalg.eig(M)
if np.any(np.abs(r) > 0.999):
... | |
<filename>tencentcloud/vod/v20180717/models.py
# -*- coding: utf8 -*-
# Copyright (c) 2017-2021 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 L... | |
== 'ambient':
if self.dim() < self.ambient_dim():
return self.base_ring().zero()
if not self.is_compact():
from sage.rings.infinity import infinity
return infinity
from sage.functions.other import factorial
return self._volume_normaliz('induced_lattice') / factorial(self.dim())
else:
raise TypeError("the mea... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.