input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
from django.db import models
from django.conf import settings
from django.urls import reverse
from django.contrib.auth import get_user_model
from autoslug import AutoSlugField
from django.utils import timezone
from phonenumber_field.modelfields import PhoneNumberField
from django.db.models.signals import post_save, pre... | |
import os
import json
from sets import Set
import time
from concurrent.futures import ThreadPoolExecutor
from parsers.medline_xml import MedlineFileParser
def calcPrecision(tp, fp, fn):
al = float(tp + fp)
return float(tp) / al if al != 0.0 else 1
def calcRecall(tp, fp, fn):
al = float(tp + fn)
return float(t... | |
method and after all required
data has been extracted and store from the class to prepare the class for
the next image/target processing. You should use this method as an
opportunity to remove any old data that you don't want to potentially
carry over to a new image/target pair. Typically, you can leave this
metho... | |
0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ]
]
],
[
[
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ]
],
[
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ]
],
[
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ]
],
[
[ 0, 0, 0,... | |
# -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404, render, redirect
from django.views.decorators.csrf import csrf_exempt
from django.http import Http404, HttpResponse, HttpResponseNotFound
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators impo... | |
<filename>signjoey/prediction.py
#!/usr/bin/env python
import torch
torch.backends.cudnn.deterministic = True
import logging
import numpy as np
import pickle as pickle
import time
import torch.nn as nn
from typing import List
from torchtext.data import Dataset
from signjoey.loss import XentLoss
from signjoey.helpers... | |
import os
import sys
import argparse
import json
import random
import soundfile as sf
from itertools import permutations, combinations
from math import factorial, inf
sys.path.extend('..')
from wham_scripts.utils import read_scaled_wav
import matplotlib.pyplot as plt
from pprint import pprint
"""
this script is used t... | |
<reponame>grst/diffxpy
import abc
try:
import anndata
except ImportError:
anndata = None
import batchglm.api as glm
import logging
import numpy as np
import patsy
import pandas as pd
from random import sample
import scipy.sparse
from typing import Union, Dict, Tuple, List, Set
from .utils import split_x, dmat_unique... | |
self.helper_bones[cat].values():
for bone in bone:
if bone:
prefix, bone = bone_convert(bone)
armature.pose.bones[prefix + bone].bone_group_index = 5
armature.data.bones[prefix + bone].layers[5] = True
armature.data.bones[prefix + bone].layers[0] = False
for container, bone in self.other_bones.items():
for ... | |
import sys
import pytest
import numpy as np
from msl.io.dataset import Dataset
def test_instantiate():
dset = Dataset(name='/data', parent=None, is_read_only=True, shape=(10, 10))
assert dset.name == '/data'
assert len(dset) == 10
assert dset.size == 100
assert dset.dtype == float
assert dset.dtype.names is N... | |
"""
Some commonly used functions for defining a task.
"""
from __future__ import division
import numpy as np
import pdb
from sklearn.metrics import r2_score
#-----------------------------------------------------------------------------------------
# Define E/I populations
#-------------------------------------------... | |
import random
from sys import exit
game_state = {
'discarded': [],
'active': {},
'colors': ['blue', 'green', 'red', 'white', 'yellow'],
'hints': 8,
'fuses': 3,
'game_over': False,
'current_player': 0,
'deck': [],
'hand_size': 5,
'recent_draw_index': -1
}
for c in game_state['colors']:
game_state['active'][... | |
the request originated from.
@type requestor: L{jid.JID}
@param service: The entity the request was addressed to.
@type service: L{jid.JID}
@return: A deferred that fires with a C{list} of affiliations as
C{tuple}s of (node identifier as C{unicode}, affiliation state
as C{str}). The affiliation can be C{'owner'},... | |
* x,
),
x,
)
def replacement6302(A, B, C, a, b, c, d, n, p, x):
return Dist(
S(1) / d,
Subst(
Int(
(a + b * acosh(x)) ** n
* (C * x ** S(2) / d ** S(2) - C / d ** S(2)) ** p,
x,
),
x,
c + d * x,
),
x,
)
def replacement6303(A, B, C, a, b, c, d, e, f, m, n, p, x):
return Dist(
S(1) / d,
Subst(
Int... | |
from sklearn.model_selection import RepeatedKFold, RepeatedStratifiedKFold
from sklearn.metrics import *
from tqdm import tqdm
import sklearn
import optuna
import pandas as pd
import numpy as np
import time
import sys
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style(style="darkgrid")
# disable chain... | |
# If the player chooses to go up, decrease the net vertical velocity
if self.player_moving_up and self.player.y + self.player.radius < self.height:
net_vely += increment
# Apply the net vertical velocity to the player
self.player.vely = net_vely
# Update the player's position
self.player.update(dt)
self.pla... | |
= NONE
if len(self._styles) and self.caret.index <= len(self._styles):
cstyle = self._styles[self.caret.index-1]
self._styles.insert(self.caret.index, cstyle)
self.caret.index += 1
self._text = txt
self._layout()
def deleteCaretLeft(self):
if self.caret.index > 0:
txt = self._text
ci = self.caret.index
txt ... | |
'HLT_Ele45_WPLoose_Gsf_v4',
'HLT_Ele50_CaloIdVT_GsfTrkIdT_PFJet140_v4',
'HLT_Ele50_CaloIdVT_GsfTrkIdT_PFJet165_v4',
'HLT_Ele50_IsoVVVL_PFHT400_v3',
'HLT_Ele8_CaloIdL_TrackIdL_IsoVL_PFJet30_v4',
'HLT_Ele8_CaloIdM_TrackIdM_PFJet30_v6',
'HLT_FullTracks_Multiplicity100_v2',
'HLT_FullTracks_Multiplicity130_v2'... | |
<https://arxiv.org/abs/1303.0518>.
Only implemented for single-dimensional output.
.. testsetup::
import numpy as np
from sklearn.linear_model import lasso_path
Parameters
----------
alpha : string | float, optional, default 'auto'.
Constant that multiplies the L1 term. Defaults to 'auto'.
``alpha = 0`` is... | |
"""Classes for migrating repos"""
import os
import re
import dateutil.parser
import datetime
from itertools import chain
import typing
import logging
from typing import (
List,
Any,
Optional,
Sequence,
Set,
)
import networkx as nx
from conda_forge_tick.path_lengths import cyclic_topological_sort
from conda_forg... | |
<reponame>bwhmather/python-payment-terminal
from collections import OrderedDict
from .fields import (
BBSField, DelimitedField,
ConstantField, EnumField,
IntegerField, PriceField,
TextField, FormattedTextField,
DateTimeField,
)
import logging
log = logging.getLogger('payment_terminal')
class BBSMessageMeta(typ... | |
'9e4e'
kaihimore(moves)
if oute.oute == 0:
depth1.append(moves)
if re.match(r'\+R|R', Bboard.b9e)and b3e==''\
and board.s8e+board.s7e+board.s6e+board.s5e+board.s4e=='':
moves = '9e3e'
kaihimore(moves)
if oute.oute == 0:
depth1.append(moves)
if re.match(r'\+R|R', Bboard.b9e)and b2e==''\
and board.s8e+board.s7... | |
[robot, hammer]
option_vars = [robot, hammer]
option = PickHammer
preconditions = {
LiftedAtom(HandEmpty, [robot]),
LiftedAtom(HammerGraspable, [hammer])
}
add_effects = {LiftedAtom(HoldingHammer, [hammer])}
delete_effects = {LiftedAtom(HandEmpty, [robot])}
nsrts.add(
NSRT("PickHammer", parameters, preconditi... | |
#!/usr/bin/env python
# coding: utf-8
from typing import List, Dict, Optional, Any, Tuple
import random
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.utils.data import Dataset, DataLoader
from torch.nn.utils.rnn import pad_sequence
from tokenizers import Tokeniz... | |
import os
import torch
from torch.utils.data import Dataset, DataLoader
import numpy as np
import glob
import cv2
import json
import utils.data_utils as util_
from . import data_augmentation
from models.clip import tokenize
import matplotlib.pyplot as plt
import IPython
import random
from datasets.ocid_data_loader imp... | |
<gh_stars>0
# Copyright (c) 2012 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.
"""Common python commands used by various build scripts."""
from __future__ import print_function
import __main__
import collections
imp... | |
from __future__ import absolute_import, division, print_function
from scitbx.math import tensor_rank_2_gradient_transform_matrix
from scitbx import matrix
from scitbx.array_family import flex
import cmath
import math
from six.moves import zip
mtps = -2 * math.pi**2
class structure_factor:
def __init__(self, xray_st... | |
<filename>deephop/onmt/myutils.py<gh_stars>1-10
import re
import numpy as np
import networkx as nx
import rdkit
import torchtext
from rdkit import Chem
from rdkit import RDConfig
from rdkit.Chem import ChemicalFeatures, AllChem
import os
import torch
import time
import dgl
import dgl.function as fn
import torch
import ... | |
0:
return sum_absolute_errors(y_l) + sum_absolute_errors(y_r), (0, 0)
y_i = np.sort(y_i)
max_error = 0
indices = None
for i in range(len(y_i)):
error = 0
error += sum_absolute_errors(np.concatenate((y_l, y_i[:i])))
error += sum_absolute_errors(np.concatenate((y_r, y_i[i:])))
if error > max_error:
max_error ... | |
("[-] Ca ,get error in VALUE_METHOD at class : ")
os._exit(1)
for i in range(0, self.arg+1):
self.value.append(struct.unpack("B", file.read(1))[0])
elif self.type == 0x1b:
# print 'here 0x1b VALUE_ENUM in class : ' + str(curClass_idx)
if self.arg >= 4:
print ("[-] Ca ,get error in VALUE_ENUM at class : ")... | |
by the vSphere License Level.
except vim.fault.RestrictedVersion as err:
log.debug(err)
ret.update({host_name: {'Error': err}})
continue
ret.update({host_name: {'Service Restarted': True}})
return ret
@depends(HAS_PYVMOMI)
@ignores_kwargs('credstore')
def set_service_policy(host,
username,
password,
servic... | |
<reponame>arjkesh/deep-learning-containers-1
# Copyright 2016 Google Inc. 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
#... | |
<filename>algorithm/operators.py<gh_stars>1-10
##############
# Efficient operators like SMA, EMA etc
# those operators are all sub-classes of a base operator
# which defines basic storage structure to enable efficient calculation of those indicators
# 1, initialize.
# to construct an operator, we need to initialize ba... | |
from PyQt5.QtCore import QCoreApplication, Qt
import random
import numpy as np
from scipy.sparse import csr_matrix
from GUI_classes.utils_gui import choose_dataset, pause_execution
from GUI_classes.generic_gui import StartingGui
from base import appctxt
class PAM_class(StartingGui):
def __init__(self):
super(PAM_... | |
import numpy as np
import xarray as xr
import pandas as pd
import multiprocessing as mp
class PreprocessData:
"""Class instantiation of PreprocessData:
Here we will be preprocessing data for deep learning model training.
Attributes:
working_directory (str): The path to the directory where the deep learning pre... | |
complete
self._trace_logger.debug("handshake complete")
self._extra.update(
peercert=self._tls_conn.get_peer_certificate()
)
if self._tls_post_handshake_callback:
self._trace_logger.debug("post handshake scheduled via callback")
task = asyncio.ensure_future(
self._tls_post_handshake_callback(self)
)
task.ad... | |
<gh_stars>1-10
# encoding: UTF-8
print(u'启动load vtEngine.py')
import shelve
from collections import OrderedDict
import os,sys
import copy
from pymongo import MongoClient, ASCENDING
from pymongo.errors import ConnectionFailure,AutoReconnect
#import vnpy.trader.mongo_proxy
from vnpy.trader.vtEvent import Event as vn_... | |
is not None:
oprot.writeFieldBegin('start_process', TType.BOOL, 1)
oprot.writeBool(self.start_process)
oprot.writeFieldEnd()
if self.cli_args is not None:
oprot.writeFieldBegin('cli_args', TType.STRUCT, 2)
self.cli_args.write(oprot)
oprot.writeFieldEnd()
if self.server_path is not None:
oprot.writeFieldBegin('... | |
= ogr.Open(shapefile)
lyr = shp.GetLayer()
featList = list(range(lyr.GetFeatureCount()))
feat = lyr.GetFeature(featList[0])
geom = feat.GetGeometryRef()
return geom.GetGeometryName()
def compute_area(shapefile):
shp = ogr.Open(shapefile)
lyr = shp.GetLayer()
featList = list(range(lyr.GetFeatureCount()))
area_... | |
number of intervals (numAPs - 1) to get mean ISI
inter_spike_interval = time_diff/(numAPs-1)
return inter_spike_interval
def absmax(i):
"""
Returns the largest absolute value present in an array in its raw form
(e.g. in [-2, 0, 1] it returns -2, in [-2,0,3] it returns 3.)
"""
# Use the absolute largest value in... | |
''' main '''
import argparse
import json
import logging
import os
import pkgutil
import re
import sys
import time
import uuid
from httplib import HTTPConnection
from ..common import status
from heron.common.src.python.utils import log
# The location of default configure file
DEFAULT_TEST_CONF_FILE = "integration_test... | |
TypeError(
"Got an unexpected keyword argument '%s'"
" to method search_proxy_deleted_for_facets" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
... | |
"""Archives test results to Google Storage."""
test_tarball = commands.ArchiveTestResults(
self._build_root, test_results_dir, prefix='')
# Wait for breakpad symbols. The archive path will be ready by the time
# the breakpad symbols are ready.
got_symbols = self._archive_stage.WaitForBreakpadSymbols()
archive_pat... | |
<filename>darch/datasets.py
import numpy as np
import scipy as sp
import tensorflow as tf
try:
import cPickle
except ImportError:
import pickle as cPickle
import gc
import os, sys, tarfile, urllib
import scipy.io as sio
from scipy.misc import *
import argparse
import glob
from PIL import Image
import random
class I... | |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""Keyvaul... | |
<filename>Kaggle/Playgroud/RiskPrediction/Home-Credit-Default-Risk-master/py_bureau/utils_agg.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 5 19:27:07 2018
@author: kazuki.onodera
"""
stats = ['min', 'mean', 'max', 'var']
stats_sum = ['min', 'mean', 'max', 'var', 'sum']
# ===============... | |
<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 25 01:24:10 2021
@author: <NAME>
This module contains all of the functions used to model drunks leaving a pub
and moving around a town. It is used by the drunk_model and
measure_drunks_moves modules.
"""
import csv
import matplotlib.animation
import matplo... | |
RR, LL, RL or LR!"
stokes_num = [self.stokes_dict_inv[stokes_] for stokes_ in stokes]
return to_boolean_array(stokes_num, self.nstokes)
def _get_uvdata_slice(self, baselines=None, start_time=None, stop_time=None,
bands=None, stokes=None):
"""
Return tuple of index arrays that represent portion of ``UVData.uvdata... | |
<filename>httpswhatcms.orgAPIEndpointDetectkey=/general.py
import os
import pandas as pd
from queue import Queue
# Each website is a separate project (folder)
def create_project_dir(project_name):
if not os.path.exists(project_name):
print('Creating directory ' + project_name)
os.makedirs(project_name)
# Create q... | |
do so via calling thisObj._set_interface_ref() directly.
YANG Description: Reference to an interface or subinterface
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_interface_ref_openconfig_relay_agent__relay_agent_dhcp_interfaces_interface_interface_ref, is_container='container', ya... | |
#!/usr/bin/env python
# Copyright (c) 2021 FrostBit Software Lab
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>
import glob
import os
import sys
try:
sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (
sys.version_info.major,
sys.... | |
{2}
RETURN NEW;
END;
$$ LANGUAGE plpgsql;""" # 0 - имя функции, 1 - блок DECLARE с внутренними переменными, 2 - текст функции
sql_template = """DROP TRIGGER IF EXISTS {0} ON {1};
CREATE TRIGGER {0}
{2} ON {1} FOR EACH ROW EXECUTE PROCEDURE {3}();""" # 0 - имя триггера, 1 - имя таблицы, 2 - тип действия, например (BEFO... | |
"
"to report this bug.")
def _apply(self, fn):
for module in self.children():
module._apply(fn)
def compute_should_use_set_data(tensor, tensor_applied):
if torch._has_compatible_shallow_copy_type(tensor, tensor_applied):
# If the new tensor has compatible tensor type as the existing tensor,
# the current beha... | |
not None:
rule['vertexColorStreamName'] = vertex_color_stream
mesh_group['rules']['rules'].append(rule)
def mesh_group_add_skin_rule(self, mesh_group: dict, max_weights_per_vertex: int = 4, weight_threshold: float = 0.001) -> None:
"""Adds a Skin rule.
Parameters
----------
mesh_group :
Mesh Group to add the... | |
else:
err_msg = ("Input argument %r is not of type 'complex'!"
% (name))
e13.raise_error(err_msg, TypeError, logger)
# Check for float
elif 'float' in args:
# Check if float is provided and continue if so
if issubclass(values.dtype.type, (np.integer, np.floating)):
# Remove 'float' from args and check it again... | |
<reponame>sandyfloren/sequenceAlignment
#!/usr/bin/env python3
# Name: <NAME> (afloren)
# Group Members: None
"""This module provides tools for personalizing Multiple Sequence Alignments.
Currently, only genomic 23andMe tab-delimited files are suitable input data.
23andMe is still using human genome build 37, which ma... | |
if country == 'uk':
if card[0] == 240 and active_country == 'uk':
keyboard.append([InlineKeyboardButton("Bolster - " + card[1], callback_data="['status_victory', '{}', {}, {}]".format(country, handler_id, card[0]))])
if card[0] == 245 and active_country == 'uk':
keyboard.append([InlineKeyboardButton("Bolster - " + ... | |
:param delete_strokes: Delete the strokes that are currently stored.
:type delete_strokes: bool
'''
pass
@staticmethod
def select(pred: 'UnaryPredicate1D'):
''' Selects the ViewEdges of the ViewMap verifying a specified condition.
:param pred: The predicate expressing this condition.
:type pred: 'UnaryPredica... | |
<reponame>IDEHCO3/kanban-backend
import requests, os, sys
#se'rvidor = ''
#servidor = 'http://LUC00557347.ibge.gov.br/'
SERVER = 'http://LUC00557196:8000/'
#SERVER = "http://172.30.11.72:8000/"
class RequestTest():
def __init__(self, uri, expec_status_code, method='GET', default_server=SERVER):
self.method = method
... | |
Jd[:,i] = np.ravel(Jtemp)
beta = beta + np.dot(Jvi[:,i-1], qd[i-1]).reshape((3,1))
# cross z0 x beta
Jvd = np.cross(np.array([0, 0, 1]).reshape((3,1)), beta, axis=0)
Jwd = np.array([0, 0, 0]).reshape((3,1))
Jtemp = np.concatenate((Jvd, Jwd))
Jd[:,0] = np.ravel(Jtemp)
return Jd
def eul2Ja(self, phi,theta,psi)... | |
<filename>src/sgraph/selement.py
import sys
from typing import Optional, Dict
from sgraph.selementmergedexception import SElementMergedException
from sgraph.selementassociation import SElementAssociation
DEBUG = False
class SElement:
__slots__ = 'name', 'parent', 'children', 'childrenDict', 'outgoing', 'incoming',... | |
cluster labels, classification threshold)
Returns the original object, not a copy. Changes to the returned object are persisted to DSS by calling
:meth:`save_user_meta`
"""
return self.details["userMeta"]
def save_user_meta(self):
um = self.details["userMeta"]
if self.mltask is not None:
self.mltask.client._... | |
<filename>applications/zcomx/modules/books.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Book classes and functions.
"""
import datetime
import functools
import json
import os
import re
import shutil
import urllib.parse
from gluon import *
from pydal.helpers.regex import REGEX_UPLOAD_EXTENSION
from applications.... | |
work out the
# auth chain difference of the unpersisted events.
unpersisted_ids.update(e for e in event_chain if e in event_map)
else:
set_ids.add(event_id)
# The auth chain difference of the unpersisted events of the state sets
# is calculated by taking the difference between the union and
# intersections.
un... | |
<gh_stars>1-10
"""
Baseline hierarchical configuration setup functions for Brokkr.
"""
# Standard library imports
import abc
import argparse
import collections.abc
import copy
import json
import logging
import os
from pathlib import Path
# Third party imports
import toml
import toml.decoder
# Local imports
from brok... | |
Check that name looks like a glob-string before calling fnmatch
# because this is called for every name in each collected module,
# and fnmatch is somewhat expensive to call.
elif ("*" in option or "?" in option or "[" in option) and fnmatch.fnmatch(
name, option
):
return True
return False
def collect(self) -... | |
<gh_stars>10-100
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overlo... | |
if word in temp_res and not temp_res[word]:
#Python 字典 pop() 方法删除字典给定键 key 及对应的值,返回值为被删除的值。key 值必须给出。 否则,返回 default 值。
temp_res.pop(word)
if word in temp_lda and not temp_lda[word]:
temp_lda.pop(word)
if not temp_res and not temp_lda:
return []
#返回xy(x的y次方) 的值。
cof = math.pow(10e-6, len(words) - max(len(temp_re... | |
can be to stop the loop'
' (raise PulseLoopStop in callback or event_loop_stop() from another thread),'
' doing whatever pulse calls synchronously and then resuming event_listen() loop.' )
self._loop_running, self._loop_stop = True, False
try: yield self._loop
finally:
self._loop_running = Fals... | |
<filename>common/gamesrv.py
from __future__ import generators
from socket import *
from select import select
from struct import pack, unpack
import zlib, os, random, struct, md5, sys
from time import time, ctime
from msgstruct import *
from errno import EWOULDBLOCK
SERVER_TIMEOUT = 7200 # 2 hours without any connecti... | |
<gh_stars>1-10
#!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, <NAME>
# 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 so... | |
<reponame>larson-group/clubb_release
"""
-------------------------------------------------------------------------------
G E N E R A L I N F O R M A T I O N
-------------------------------------------------------------------------------
This file contains general constants and information about the variables saved
in ... | |
Arguments(agent_class, env_func=env_func, env_args=env_args)
args.num_layer = 3
args.net_dim = 2 ** 7
args.batch_size = int(args.net_dim * 2)
args.worker_num = 2
args.target_step = args.max_step
args.repeat_times = 2 ** -1
args.reward_scale = 2 ** -4
args.learning_rate = 2 ** -15
args.clip_grad_norm = 1.0
... | |
)
self.colorsCanvas = Tk.Canvas( mainFrame, borderwidth=2, relief='ridge', background='white', width=197, height=canvasHeight )
self.colorsCanvas.pack( pady=4 )
x = 10
y = 9
for i, rgbaColor in enumerate( reversed(self.recentColors) ):
# Prepare and store an image object for the color
co... | |
<reponame>Aorjoa/aiyara-ceph-dash<filename>.tox/py27/lib/python2.7/site-packages/ceph_argparse.py
"""
Types and routines used by the ceph CLI as well as the RESTful
interface. These have to do with querying the daemons for
command-description information, validating user command input against
those descriptions, and su... | |
content type EMPTY
class Port_ (PortMapTarget_):
"""Complex type {avm}Port with content type EMPTY"""
_TypeDefinition = None
_ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_EMPTY
_Abstract = True
_ExpandedName = pyxb.namespace.ExpandedName(Namespace, u'Port')
_XSDLocation = pyxb.utils.utilit... | |
length of each dash and the gap length between
the dashes.
"""
self._cmd.distance(
name,
self._into_selection(selection1),
self._into_selection(selection2),
cutoff,
mode,
label=int(show_label),
width=width,
length=length,
gap=gap
)
@validate
def dss(self, selection=None, state=None):
"""
Determine th... | |
# Copyright 2014 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | |
/= retain_prob
# use nonsymbolic shape for dropout mask if possible
return tf.nn.dropout(input, keep_prob=retain_prob)
def get_output_shape_for(self, input_shape):
return input_shape
# TODO: add Conv3DLayer
class FlattenLayer(Layer):
"""
A layer that flattens its input. The leading ``outdim-1`` dimensions o... | |
= pandas.DataFrame({'src': [0,1,2], 'dst': [1,2,0]})
graphistry
.bind(source='src', destination='dst')
.edges(es)
.plot()
**Example: Shorthand**
::
import graphistry
es = pandas.DataFrame({'src': [0,1,2], 'dst': [1,2,0]})
graphistry
.bind(source='src', destination='dst')
.plot(es)
"""
if graph is None:... | |
INTEGER '
'NOT NULL,received_bytes INTEGER NOT NULL,total_bytes INTEGER NOT '
'NULL,state INTEGER NOT NULL,end_time INTEGER NOT NULL,opened '
'INTEGER NOT NULL)'),
'keyword_search_terms': (
'CREATE TABLE keyword_search_terms (keyword_id INTEGER NOT '
'NULL,url_id INTEGER NOT NULL,lower_term LONGVARCHAR NOT NULL,t... | |
np.sum(normdata,axis=2)[:,:,np.newaxis]
# Divide by mean spectrum to remove wavelength dependence
normdata /= np.mean(normdata,axis=(0,1))[np.newaxis,np.newaxis,:]
# Average frames to get flat-field correction
flat_norm = np.mean(normdata,axis=0)
flat_norm[np.where(np.mean(normmask,axis=0)<1)] = 1
'''
normdata /... | |
"""Probability distributions."""
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Tuple, Union
import gym
import torch as th
from gym import spaces
from torch import nn
from torch.distributions import Bernoulli, Categorical, Normal
from stable_baselines3.common.preprocessing import g... | |
import typing
import warnings
from typing import List, Optional, Tuple
import numpy as np
import torch
from torch import Tensor
from tsts.collators import Collator
from tsts.dataloaders.dataloader import DataLoader
from tsts.datasets import Dataset
from tsts.loggers import Logger
from tsts.losses.loss import Loss
from... | |
<reponame>wlongo/django-rest-framework-braces<filename>drf_braces/serializers/form_serializer.py<gh_stars>10-100
from __future__ import absolute_import, print_function, unicode_literals
from collections import OrderedDict
import six
from django import forms
from rest_framework import serializers
from .. import fields... | |
proceed to calculating the (y) coordinate
if x1 == x2:
x0 = x1
# if the vertical direction is positive from
# vertex 1 to vertex 2 on the euclidean plane
if y1 < y2:
y0 = y1 + distance
# if the vertical direction is negative from
# vertex 1 to vertex 2 on the euclidean plane
# -- this shouldn't happen due to... | |
bound = (1 + percentile/200)*latest_D
predictions = [0 for i in range(int(14)+start)]
predictions = predictions + [0 for i in range(int(extrapolate-14))]
forecast = list(np.concatenate((deaths, predictions)))
death_cdf.append(forecast)
for percentile in [80, 90]:
if percentile == 80:
bound ... | |
defines = {}
if __preprocessedFiles is None:
__preprocessedFiles = []
log.info("preprocess(infile=%r, outfile=%r, defines=%r, force=%r, "
"keepLines=%r, includePath=%r, contentType=%r, "
"__preprocessedFiles=%r)", infile, outfile, defines, force,
keepLines, includePath, contentType, __preprocessedFiles)
absInf... | |
# encoding=utf8
from __future__ import unicode_literals
from datetime import datetime
from sw.allotmentclub import User, Member, Organization
from sw.allotmentclub.model import ENGINE_NAME
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
import random
import psycopg2
import csv
import json
import os.path
impo... | |
, eol_))
if self.cUF is not None:
namespaceprefix_ = self.cUF_nsprefix_ + ':' if (UseCapturedNS_ and self.cUF_nsprefix_) else ''
showIndent(outfile, level, pretty_print)
outfile.write('<%scUF>%s</%scUF>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.cUF), input_name='cUF')), namespac... | |
required: If C{True}, indicates that the attribute must appear
in the DOM node used to create an instance of the corresponding
L{pyxb.binding.basis.complexTypeDefinition}. The default value is
C{False}. No more that one of L{required} and L{prohibited} should be
assigned C{True}.
@type required: C{bool}
@keyword... | |
<reponame>cowboygneox/boto3_type_annotations
from typing import Optional
from botocore.client import BaseClient
from typing import Dict
from botocore.paginate import Paginator
from botocore.waiter import Waiter
from typing import Union
from typing import List
class Client(BaseClient):
def associate_role_to_group(sel... | |
convert units from mm to cm
numslices = int(gdata['nslices'])
numangles = int(gdata['nangles'])
angularrange = float(gdata['arange'])
numrays = int(gdata['nrays'])
npad = int(np.ceil(numrays * np.sqrt(2)) - numrays)//2 if npad is None else npad
projused = (0,numangles-1,1) if projused is None else projused
... | |
nid.NodeIdType == NodeIdType.String:
nid.NamespaceIndex = uabin.Primitives.UInt16.unpack(data)
nid.Identifier = uabin.Primitives.String.unpack(data)
elif nid.NodeIdType == NodeIdType.ByteString:
nid.NamespaceIndex = uabin.Primitives.UInt16.unpack(data)
nid.Identifier = uabin.Primitives.Bytes.unpack(data)
elif nid... | |
ext + "_imm", [w_bit, root010, (0xf, 4, 22)],
[OK.XREG_5_9_SP, imm_scaled, src1, src2], OPC_FLAG.STORE | OPC_FLAG.REG_PAIR)
########################################
root011 = (7, 3, 26)
########################################
for ext, reg1, reg2, imm, bits in [
("s", OK.SREG_0_4, OK.SREG_10_14, OK.SIMM_15_21_TIMES_... | |
from utils.modulos import *
class Pesquisar:
def __init__(self, master=None, app=None):
img_pesquisar = PhotoImage(data=base64.b64decode(img_pesquisar_base64)) # imagem do botão Pesquisar
img_listar = PhotoImage(data=base64.b64decode(img_listar_doc_base64)) # imagem do botão Listar
img_calendario = Photo... | |
<reponame>oplatek/e2end<gh_stars>10-100
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json, logging, os, pickle, bisect
import numpy as np
from collections import OrderedDict
from . import Vocabulary
logger = logging.getLogger(__name__)
class Dstc2DB:
def __init__(self, filename, first_n=None):
logger.inf... | |
Set to zero to find representative profile on all resource, not
just included.
n_profiles : int
Number of representative profiles to output.
rerank : bool
Flag to rerank representative generation profiles after removing
excluded generation pixels.
cluster_kwargs : dict
RPMClusters kwargs
max_workers : int, opt... | |
self.control)
self.ddLuu_path_fn = casadi.Function('ddLuu_path',
[self.state, self.control, costate, v_path, w_path, self.auxvar],
[self.ddLuu_path])
self.ddLue_path = jacobian(self.dLu_path, self.auxvar)
self.ddLue_path_fn = casadi.Function('ddHue_path',
[self.state, self.control, costate, v_path, w_path, self.a... | |
#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-
import os
import re
import sys
import time
import subprocess
import multiprocessing
import git
import typing
import itertools
import argparse
import string
import math
import tty
import ctypes
import termios
import xml.etree.ElementTree as ET
COPYRIGHT = b"""/**
* Cop... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.