input
stringlengths
2.65k
237k
output
stringclasses
1 value
####Please do not remove lines below#### from lmfit import Parameters import numpy as np import sys import os sys.path.append(os.path.abspath('.')) sys.path.append(os.path.abspath('./Functions')) sys.path.append(os.path.abspath('./Fortran_routines')) ####Please do not remove lines above#### ####Import your modules bel...
# 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, software # distributed under the Li...
<gh_stars>0 #!/usr/bin/env python3 desc="""Convert basecalled Fast5 with modifications annotated by guppy v3.1.5+ to FastQ with modification probabilities encoded as FastQ qualities. More info at: https://github.com/lpryszcz/modPhred Dependencies: h5py, pyguppyclient, running guppy_basecall_server TO DO: - catch exc...
<reponame>kzeiler/modflow6 import os import numpy as np import pytest try: import flopy except: msg = "Error. FloPy package is not available.\n" msg += "Try installing using the following command:\n" msg += " pip install flopy" raise Exception(msg) from flopy.utils.lgrutil import Lgr from framework import testin...
import json import logging import os import time from pathlib import Path import click import requests from requests import HTTPError from tenacity import retry, stop_after_delay, wait_fixed from n26.config import Config, MFA_TYPE_SMS from n26.const import DAILY_WITHDRAWAL_LIMIT, DAILY_PAYMENT_LIMIT from n26.util imp...
from builtins import object import uuid from axes.handlers.proxy import AxesProxyHandler from django import forms from django.conf import settings from django.contrib.auth import get_user_model, password_validation, authenticate from django.contrib.auth.hashers import make_password from django.contrib.auth.password_va...
diff_rel) return OptionalStartEnd(self.start_abs_msec, self.end_abs_msec) HeapId = int TimeForStageByHeap = Mapping[GcJoinStage, Mapping[HeapId, OptionalStartEnd]] MutTimeForStageByHeap = Dict[GcJoinStage, Dict[HeapId, MutOptionalStartEnd]] def get_join_stage_start_end_times_for_heaps(gc: AbstractTraceGC) -> TimeF...
<gh_stars>10-100 # MIT License # # Copyright (c) 2018 kuangliu # # 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, m...
<reponame>oliviertrottier/dendrites-ssd<gh_stars>1-10 import sys import os import json import re from argparse import ArgumentParser from collections import OrderedDict from utils.augmentations import SSDAugmentation, TreeAugmentation # Get project and dataset directories across platform from .host_config import get_...
dtype=np.float).flatten() x = np.asanyarray(x, dtype=np.float).flatten() if np.isnan(mindx): mindx = 0 mindx = mindx or 0 if np.isnan(startdat): startdat = 0 startdat = startdat or 0 # No strict validation here, they are scalards and they must be validated # before going into the C-layer if not utils.issca...
3 Args: file_path (str): path to pickle file Returns: obj (object): object saved in pickle file ''' with open(file_path, 'rb') as f: try: obj = pickle.load(f, encoding='latin1') except TypeError: # pragma no cover obj = pickle.load(f) # pragma no cover return obj def rate_conversion(annual_rate, start_a...
<reponame>mhauskn/dm_control """ This model taken from: https://github.com/karpathy/minGPT/blob/master/mingpt/model.py GPT model: - the initial stem consists of a combination of token encoding and a positional encoding - the meat of it is a uniform sequence of Transformer blocks - each Transformer is a sequential com...
from __future__ import print_function, division import matplotlib matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! from neuralnilm import Net, RealApplianceSource, BLSTMLayer, SubsampleLayer, DimshuffleLayer from lasagne.nonlinearities import sigmoid, rectify from lasagne.objectives import c...
= self.start_epoch*len(self.train_loader) stage3_epoches = self.epoch_stage3 - self.start_epoch lr_scheduler = optim.lr_scheduler.CosineAnnealingLR(self.optimizer, stage3_epoches+5) for epoch in range(self.start_epoch, self.epoch_stage3): epoch += 1 self.unet.train(True) epoch_loss = 0 self.reset_gr...
# -*- coding: utf-8 -*- #!/usr/bin/env bash # # Author: XuMing <<EMAIL>> # Brief: corrector with spell and stroke import codecs import os import pdb import time import math import sys import argparse import jieba.posseg as pseg from collections import defaultdict from pypinyin import lazy_pinyin pwd_path = os.path.abs...
import os import time import logging import numpy as np from scipy.interpolate import interp1d from scipy.optimize import fsolve from scipy.integrate import solve_ivp, trapz, quad from .utils import InvalidJumpError from .utils import GRAV_ACC, EPS from .utils import compute_dist_from_flat, vel2speed if 'ONHEROKU' ...
customdatasrc Sets the source reference on Chart Studio Cloud for customdata . fill Sets the area to fill with a solid color. Use with `fillcolor` if not "none". "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. fillcolor Sets the fill color. Defaul...
will be set if the application can process the # policyConstraints extension. If the application can process the # policyConstraints extension, then the path should not validate # successfully. If the application can not process the policyConstraints # extension, then the path should validate successfully. TestInf...
numbers) """ # Note: can also get usd_attr.GetTimeSamples() prim = stage.GetPrimAtPath(scene_path) if UsdGeom.Points(prim): geom_points = UsdGeom.Points(prim) result = geom_points.GetPointsAttr().GetBracketingTimeSamples(target_time) elif UsdGeom.PointInstancer(prim): instancer = UsdGeom.PointInstancer(prim) ...
EXACT same) : >>> model = nn.models.NeuralNetwork() >>> model.add(nn.layers.Flatten()) >>> model.add(nn.layers.Dense(784, 64, activation = nn.layers.ReLU())) >>> model.add(nn.layers.Dense(64, 32, activation = nn.layers.ReLU())) >>> model.add(nn.layers.Dense(32, 10, activation = nn.layers.ReLU())) Obviously we wa...
- all need looped over... - settings_inputs to be moved to switchboard print Dir[l].split('/')[-2] ntor = setting_ntor[1] #requested ntor mode number !!! NEEDS A FUNCTION !!! #Create global 2D diagnostics folder and extract current simulation name DirEquil2D = CreateNewFolder(Dir[l],'2DEquil_Plots/') Di...
<gh_stars>0 import logging from typing import Dict, List, Optional, Union import copy import torch import torch.nn.functional as F from overrides import overrides from allennlp.data import Vocabulary from allennlp.common.params import Params from allennlp.models.model import Model from allennlp.modules import TextFie...
"set_segment_records\(\) missing 2 required ", "positional arguments: 'values' and 'file'", ) ), self.database.set_segment_records, ) self.assertRaisesRegex( TypeError, "".join( ( "delete_segment_records\(\) missing 2 required ", "positional arguments: 'values' and 'file'", ) ), self.database.delete_segme...
<filename>chi/plots/_time_series.py<gh_stars>1-10 # # This file is part of the chi repository # (https://github.com/DavAug/chi/) which is released under the # BSD 3-clause license. See accompanying LICENSE.md for copyright notice and # full license details. # import numpy as np import pandas as pd import plotly.colors...
# Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. import numpy as np import pandas as pd import warnings from sklearn.linear_model import LinearRegression import scipy.cluster.hierarchy as sch import datetime ...
whitespace before newline """ # Arrange source_markdown = """a![Foo](/uri\a\a "testing")a ---""".replace( "\a", " " ) expected_tokens = [ "[setext(3,1):-:3::(1,1)]", "[text(1,1):a:]", '[image(1,2):inline:/uri:testing:Foo::::Foo:False:":: \n:]', "[text(2,11):a:]", "[end-setext::]", ] expected_gfm = """<h2>...
<gh_stars>0 # ========================================================================================================================= # File Name : preprocessing.py # ------------------------------------------------------------------------------------------------------------------------- # Purpose : Purpose of this s...
import math from functools import wraps, partial, reduce from operator import mul import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, repeat from src.modules import FeedForwardNetwork, ESM1bLayerNorm, NormalizedResidualBlock, MLP TOKEN_SELF_ATTN_VALUE = <PASSWORD> # caref...
records:%s' %(k,len(chrDataSets))) if(lengthChrDataSets>=clusterConfigs['record']): ##总行数>record ##对chrDataSets进行考虑record 和 threshold ##对chrDataSets根据Region value 进行排序 #for item in chrDataSets: # print(item[regionColumn]) chrDataSets.sort(key=lambda x:x[regionColumn]) ##此时chrDataSets已经排序 按照region...
<reponame>androm3da/clang_sles #!/usr/bin/python #===-- x86_64_target_definition.py -----------------------------*- C++ -*-===// # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # #===----------------------------------...
import base64 import logging import os import typing as t from dataclasses import dataclass from functools import partial from inspect import isfunction import click from flask import Blueprint as FlaskBlueprint from flask import Flask from flask import Response from flask import abort from flask import current_app fr...
__createSvgTable__(tempData) root.appendChild(headerGroup) root.appendChild(alternativeTableHeaderBackgroundGround) root.appendChild(alternativeTableDataBackgrounGroup) root.appendChild(alternativeNewWordGroup) root.appendChild(xmlAlternativeTable) return xmlDoc.toxml('utf-8') # meanData, rangeData and stdDat...
<gh_stars>1-10 # GameHelper.py # Class implementation for 'GameHelper' import sys import json import struct import msgpack from game.Map import Map from game.Command import Command from game.Coordinate import Coordinate, direction_deltas from game.params import ( MOVE_COMMAND, BUILD_COMMAND, MINE_COMMAND, HIVE_CO...
HEAVY BARB ARROW': 129154, 'WIDE-HEADED SOUTH EAST BARB ARROW': 129134, 'WIDE-HEADED SOUTH EAST HEAVY BARB ARROW': 129150, 'WIDE-HEADED SOUTH EAST LIGHT BARB ARROW': 129126, 'WIDE-HEADED SOUTH EAST MEDIUM BARB ARROW': 129142, 'WIDE-HEADED SOUTH EAST VERY HEAVY BARB ARROW': 129158, 'WIDE-HEADED SOUTH WEST BARB ARROW': 1...
' + str(launch_args)) d.launch_args = launch_args d.load_preferences() cache = d.cache_load() prompt = d.prefs['prompt'] out = d.menu(cache,prompt).strip() aliased = False if len(out) > 0: if d.debug: print("First menu closed with user input: " + out) # Check if the action relates to a plugin plugins = loa...
str(today.month) + "/" + str(today.day) + "/" + str(today.year) self.visdatev.set(tstr) self.visitdate.grid(row=8, column=3) #prepopulate volunteer self.volv.set(self.volunteerName) ###############self.visv.set(self....?) #prepopulate visitor (add test to see if this exists, in case of newclient) self.notescv.c...
cname in matplotlib.cm._cmap_registry: return matplotlib.cm.get_cmap(cname) cmap_file = os.path.join(CMAPSFILE_DIR, "colorbrewer", "reds_4.rgb") cmap = Colormap(self._coltbl(cmap_file), name=cname) matplotlib.cm.register_cmap(name=cname, cmap=cmap) return cmap @property def reds_4_r(self): cname = "reds_4_r" ...
var_name, ax, u, colorbar_index): ax.clear() ax.set_xlabel('$\\phi$') ax.set_ylabel('$\\theta$') ax.set_title(f'{var_name} averaged across $r$') if self.contour_plot_available: # matplotlib has problems plotting repeatedly `contourf` until version 3.3 # see https://github.com/matplotlib/matplotlib/issues/15986 ...
''' Name: color_segmentation.py Version: 1.0 Summary: K-means color clustering based segmentation. This is achieved by converting the source image to a desired color space and running K-means clustering on only the desired channels, with the pixels being grouped into a desired number of clusters. Author: <N...
import abc import inspect import json import os import multiprocessing import time import numpy as np import pandas as pd import tensorflow as tf2 from tqdm import tqdm from ..feature import features_from_batch_data from ..utils.tf_ops import modify_variable_names from ..utils.misc import time_block, colorize from ..ut...
pattern @time_measure def quantstrategies(context: DataContext): global lock_qm totalresultdata = {} transientresult100 = context.totalresult[DataContext.strategy100] for sector_usd in context.markets: resultdata = {} sector_tmp = stock_group[sector_usd] for symbol_tmp in context.symbols[sector_tmp]: results = ...
<filename>wordvecs/wordvecs.py #!/usr/bin/env python # coding=utf-8 # Author: <NAME> <<EMAIL>> KTH 2018 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from __future__ import division, absolute_import, print_function f...
import numpy as np import matplotlib.pyplot as plt import hrgames as hrg import sys def classic_pd(R=None, tf=None, xini=None): """Plays a classic prisoner's dilemma between two players""" # Two connected players A = np.zeros([2, 2]) A[0, 1] = 1 A[1, 0] = 1 # Classic positive prisoner's dilemma B = np.zeros([2...
<reponame>imaginaryusername/Electron-Cash # # This file is: # Copyright (C) 2018 <NAME> <<EMAIL>> # # MIT License # from . import utils from . import gui from .history import HistoryEntry from . import txdetail from . import contacts from electroncash import WalletStorage, Wallet from electroncash.util import timestamp...
detected. link_aggregation: This field indicates if this is a link aggregation interface. mac: The MAC address of the interface. ms_ad_user_data: The Microsoft Active Directory user related information. name: The interface system name. network_view: Th name of the network view. oper_status: Operating state of t...
ctx, cc_toolchain = cc_toolchain, requested_features = ctx.features, unsupported_features = ctx.disabled_features, ) library_to_link = cc_common.create_library_to_link( actions = ctx.actions, feature_configuration = feature_configuration, dynamic_library = dynamic_library, dynamic_library_symlink_path = _shor...
~ ('callcode', :gas, :addr, :wei, :fname, :fparams): fname = pretty_fname(fname, add_color=add_color) if type(addr) == int: addr = hex(addr) addr = prettify(addr, add_color = add_color) gas = prettify(gas, parentheses = False, add_color = add_color) fparams = pretty_memory(fparams, add_color = add_color) if fn...
from directory_constants.constants import cms from django.forms import Textarea, CheckboxSelectMultiple from django.utils.text import slugify from modelcluster.fields import ParentalManyToManyField from wagtail.admin.edit_handlers import ( HelpPanel, FieldPanel, FieldRowPanel, MultiFieldPanel, PageChooserPanel ) from ...
graphical simulation interface ######################################################### def draw(self,dc,transform,px,py): c = self.properties.get('color','blue') dc.SetPen(wx.Pen(c,1,wx.SOLID)) dc.SetBrush(wx.Brush(c)) radius = transform[0]/16 dc.DrawCircle(px,py,radius) def draw_on_link(self,dc,transform,n...
# This file contains methods to deal with criu images. # # According to http://criu.org/Images, criu images can be described # with such IOW: # # IMAGE_FILE ::= MAGIC { ENTRY } # ENTRY ::= SIZE PAYLOAD [ EXTRA ] # PAYLOAD ::= "message encoded in ProtocolBuffer format" # EXTRA ::= "arbitrary blob, depends on the PAYLOAD...
<filename>experiments/smal_shape.py """ Example usage: python -m smalst.experiments.smal_shape --zebra_dir='smalst/zebra_no_toys_wtex_1000_0' --num_epochs=100000 --save_epoch_freq=20 --name=smal_net_600 --save_training_imgs=True --num_images=20000 --do_validation=True """ from __future__ import absolute_import from...
""" A resource API for WAF and WAF-regional """ from enum import Enum, auto from typing import Iterable, Dict, Container, Union, Generator, Optional, List import boto3 from .basic import scroll import abc import logging import json import collections from .cleaning import clean_up_stack logger = logging.getLogger(__n...
""" if addr is None: raise TypeError('Address can not be set to None') self._addr = addr def get_scope(self): """ Get the subnet scope :returns: The subnet scope as a string """ return self._scope def set_scope(self, scope): """ Set the subnet address :param scope: The subnet scope. It can be either "p...
""" Aggregate tools =============== """ import sys import numpy from .._lib.hashmap import factorize from ..compat import tqdm from ..ds.scaling import linearscaling from .arrays import first, lexsort_uint32_pair, to_structured def igroupby(ids, values, n=None, logging_prefix=None, assume_sorted=False, find_next_h...
import torch import numpy as np import pandas as pd import scipy.stats as stats import sys import os import time from collections import OrderedDict sys.path.insert(1, os.path.dirname(__file__)) import genotypeio, eigenmt from core import * import imp import core imp.reload(core) from core import * imp.reload(eigenmt...
cursor.close() connection.close() six.reraise(DatabaseError, DatabaseError(e), sys.exc_info()[2]) if not external_cursor: cursor.close() connection.commit() connection.close() return engine_temp def _check_transfer(self, connection, cursor, transfer_id, user_id): try: sel = cursor.execute( '''SELECT id FR...
from xapi import success, Rpc_light_failure, InternalError, UnmarshalException, TypeError, is_long, UnknownMethod import xapi import sys import json import argparse import traceback import logging class Unimplemented(Rpc_light_failure): def __init__(self, arg_0): Rpc_light_failure.__init__(self, "Unimplemented", [ ar...
= self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, response_type='str', auth_settings=auth_settings, callback=params.get('callback')) return response def proxy_delete_namespaced_service(self, namespace, name, **...
<reponame>murthyn/composer # Copyright 2021 MosaicML. All Rights Reserved. """Callback to save checkpoints during training.""" from __future__ import annotations import logging import os import textwrap from typing import Callable, Optional, Union from composer.core import Event, State from composer.core.callback i...
that the resource was updated. An `RFC3339`__ formatted datetime string. __ https://tools.ietf.org/html/rfc3339 :param str created_by_id: (optional) OCID of the user who created the resource. :param str updated_by_id: (optional) OCID of the user who updated the resource. :param list[str] fields: (optional) S...
# Copyright 2014 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 # Unless required by applicable law or agreed t...
<reponame>gr4viton/kivent-robotic-visualizer<filename>py/surface.py from random import randint, choice, randrange from math import radians, pi, sin, cos from kivy.core.window import Window import logging from logging import info as prinf from logging import debug as prind from logging import warning as prinw from log...
import re import collections from enum import Enum from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLI...
<reponame>ravithanneeru/azure-cli-extensions<gh_stars>1000+ # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code genera...
lineage_probability_color=lineage_probability_color, abs_prob_cmap=abs_prob_cmap, lineage_probability=show_prob, ylabel=ylabel, **kwargs, ) if sharey in ("row", "all", True) and not ylabel_shown: plt.setp(ax.get_yticklabels(), visible=True) if show_xticks_and_label[i]: plt.setp(ax.get_xticklabels(), visible=T...
- 30: o0oOOo0O0Ooo % OoOoOO00 * IiII % iIii1I11I1II1 % O0 elif ( IIiiIiIIiI1 . type == LISP_ECM ) : lisp_process_ecm ( lisp_sockets , packet , source , udp_sport ) if 76 - 76: II111iiii * I11i else : lprint ( "Invalid LISP control packet type {}" . format ( IIiiIiIIiI1 . type ) ) if 29 - 29: OoooooooOO . i1IIi r...
<filename>CartPole.py #!/usr/bin/env python3 import numpy as np from scipy.stats.mstats import gmean import theano.tensor as T from ilqr import iLQR from ilqr.cost import QRCost from ilqr.dynamics import constrain from ilqr.dynamics import AutoDiffDynamics ''' Author: Sameer Date: May 2019 ''' class CartPole(object)...
bits, static_row + 1, bcol) header_offset = static_row + 1 __writeAnchorListData(sheet, seq_ref[seq], bits, row + header_offset, bcol, data_func = lambda data, test: data[test][_KB], data_format = __S_BIT_FORMAT, abs_format = __S_BIT_ABS_FORMAT) # Write sequence sheet.cell(row = row + header_offset, column = bc...
<reponame>agentdavidjoseph/slycat # Copyright (c) 2013, 2018 National Technology and Engineering Solutions of Sandia, LLC . Under the terms of Contract # DE-NA0003525 with National Technology and Engineering Solutions of Sandia, LLC, the U.S. Government # retains certain rights in this software. """Functions for manag...
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 """ Example: Hilbert space approximation for Gaussian processes. ============================================================ This example replicates a few of the models in the excellent case study by <NAME> [1] (originally written us...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- #--------------------------------------------------------------------------- #Global mathematical model of SAC-A with 31 nodes and according to design # status of March 3, 1997. Orbit of 51.6 degrees of inclination in winter # solstice (beta=15), at 205 mn (380 km...
import torch import warnings from torch.optim.optimizer import Optimizer, required import math import itertools as it import torch.optim as optim warnings.filterwarnings("once") def get_optimizer(optimizer: str = 'Adam', lookahead: bool = False, model=None, separate_decoder: bool = True, lr: float = 1e-3, lr_e: ...
"full".') return None if df is None: self._logger.warning('Return df format not provided. Default is "pred".') return None if svd == True: # update SVD for dimensionality reducation self.svd() data = self.data else: data = self.UI gmm = GaussianMixture(n_components=n, n_init=10, covariance_type=covaria...
with corporate actions information **Usage** Retrieve corporate actions for a basket across a date range **Examples** Retrieve historical acquisition corporate actions for a basket >>> from gs_quant.markets.baskets import Basket >>> from gs_quant.markets.indices_utils import CorporateActionType >>> >>> bas...
"""Supporting functions for the 'fix' command.""" import logging import numpy as np import pandas as pd from . import descriptives, params, smoothing def do_fix(target_raw, antitarget_raw, reference, do_gc=True, do_edge=True, do_rmask=True, do_cluster=False): """Combine target and antitarget coverages and correct...
import time import logging import json import copy import math import base64 import grpc from grpc._cython import cygrpc from ..grpc_gen import milvus_pb2_grpc from ..grpc_gen import milvus_pb2 as milvus_types from ..grpc_gen import common_pb2 from .abstract import CollectionSchema, ChunkedQueryResult, MutationResul...
<reponame>dbmi-bgm/cgap-portal import json import mock import pytest import webtest from datetime import datetime, timedelta from dcicutils.misc_utils import Retry, ignored from dcicutils.qa_utils import notice_pytest_fixtures, local_attrs from pyramid.httpexceptions import HTTPBadRequest from snovault import TYPES, C...
<filename>Traclus_DL.py<gh_stars>1-10 from Trajectory import * from ClusterQ import * import sys import datetime from collections import defaultdict from numpy import arange from itertools import count import math """This is a collection of methods to read in a set of 2 dimensional desire lines trajectories, and create...
list of genome_servers. Use reset argument to overwrite the current list. Otherwise the current one will be appended to. :param list[str] | str url: url(s) to update the genome_servers list with :param bool reset: whether the current list should be overwritten """ urls = _make_list_of_str(url) if CFG_SERVERS_KE...
the self.image_info list. # this happens in place, and returns None shuffle(self.image_info) # add all the class info for category in updated_category_dict: # self.add_class(dataset_name, category['id'], category['name']) self.add_class(dataset_name, updated_category_dict[category], category) print(len(up...
import json import argparse import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset import os import random import numpy as np import requests import logging import math import copy import wandb import string import re from time import time from tqdm import tqdm, trange f...
<gh_stars>0 """ Tools for converting CPAN packages to conda recipes. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import json import subprocess import sys from distutils.version import LooseVersion from glob import glob from io import open from os import makedirs from os.p...
<filename>lightweight_mmm/plot.py # Copyright 2022 Google LLC. # # 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...
or int(isValue) == 0) : # сохраним заголовок, если он определен для ЭТОГО класса объектов. sqlStr = "INSERT INTO " + self._headStruct.getTableName() +" ( " + headParamsObj.strListAttrNames + ") VALUES " +\ "( " + headParamsObj.strListAttrValues + " ) returning " + self._headStruct.getIdFieldName() + "; " headValue ...
== flop[2]+1 and x[1] == flop[2]-1) or (x[0] == flop[2]+2 and x[1] == flop[2]+1))] if board_type == "two-tone": my_hands_s_3_to_straight_low_end_bdfd = [(x, 1) for x in my_hands[1] if x[0] != 13 and (x[0] not in flop and x[1] not in flop) and ((x[0] == flop[0]-1 and x[1] == flop[0]-2) or (x[0] == flop[1]-1 and x[1] =...
*args) -> "void": r""" *Overload 1:* 获取椭圆属性 | *Overload 2:* 设置椭圆属性 | *Overload 3:* 设置椭圆属性 """ return _gskernel.GsArcPointSymbol_EllipseParameter(self, *args) def LongAxis(self, *args) -> "void": r""" *Overload 1:* 获取长轴长度 | *Overload 2:* 设置长轴长度 """ return _gskernel.G...
# coding:utf-8 # Author: 阿财(<EMAIL>)(<EMAIL>) # Created date: 2020-02-27 # # The MIT License (MIT) # # Copyright (c) 2016-2019 yutiansut/QUANTAXIS # # 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 Sof...
statistics' + suffix logger.info ( title + "\n%s" % self.table ( title = title , prefix = "# " ) ) ## standard printout as table def table ( self , title = 'Jobs execution statistics' , prefix = '' ) : text = [ (' #jobs ' , '%' , ' total time' , 'time/job' , 'job server') ] njobs = self.njobs keys = self._...
_general.PyNode) return res @_factories.addCmdDocs def polyCut(*args, **kwargs): res = cmds.polyCut(*args, **kwargs) if not kwargs.get('query', kwargs.get('q', False)): res = _factories.maybeConvert(res, _general.PyNode) return res @_factories.addCmdDocs def polyCylinder(*args, **kwargs): res = cmds.polyCylinde...
<filename>functions_for_AirBnB.py # The collection of functions for the Boston AirBnB dataset # import necessary libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from pandas.tseries.holiday import USFederalHolidayCalendar as calendar #To check holidays in the U.S i...
of each tensor in `outputs`. name: A name for the operation (optional). Returns: A list of `Tensor` objects of type `dtypes`. """ _ctx = _context._context or _context.context() tld = _ctx._thread_local_data if tld.is_eager: try: _result = pywrap_tfe.TFE_Py_FastPathExecute( _ctx._context_handle, tld.device_na...
<filename>fourInARowWrapper.py import numpy as np from gym import spaces import gym import fourInARow import copy class ActionSpace(spaces.Discrete): def __init__(self, size): self.high = fourInARow.width self.low = 0 super().__init__(size) class FourInARowWrapper(gym.Env): def __init__(self, pl...
# coding=utf-8 from __future__ import absolute_import, division, print_function, unicode_literals from builtins import str from io import open from dynet import * import dynet from utils import read_conll, read_conll_predict, write_conll, load_embeddings_file from operator import itemgetter import utils, time, random...
"object dependencies.", req.status_code, nb_id ) log.debug("NetBox %s status body: %s", req.status_code, req.json()) else: raise SystemExit( log.critical( "Well this in unexpected. Please report this. " "%s request received %s status with body '%s' and response " "'%s'.", req_type.upper(), req.status_code, da...
<reponame>jacer2020/ui2 # coding: utf-8 # from __future__ import absolute_import, print_function import base64 import io import logging import re import time import warnings import xml.dom.minidom import requests import six from retry import retry from uiautomator2.exceptions import (RetryError, NullPointerExceptio...
(left_index and right_index): left_on = right_on = list(same_named_columns) return left_on, right_on @staticmethod def _get_left_right_indices(lhs, rhs, left_on, right_on, left_index, right_index): """ Calculate left and right column indices to perform shuffle on this is based on the "join" function in cudf fi...
<filename>examples/seismic/skew_self_adjoint/wavesolver.py from devito import Function, TimeFunction from examples.seismic import PointSource, Receiver from examples.seismic.skew_self_adjoint.utils import setup_w_over_q, compute_critical_dt from examples.seismic.skew_self_adjoint.operators import IsoFwdOperator, IsoAdj...
<reponame>LaudateCorpus1/ppo-ewma<gh_stars>10-100 """ Mostly copied from ppo.py but with some extra options added that are relevant to phasic """ import numpy as np import torch as th from queue import Queue from mpi4py import MPI from functools import partial from .tree_util import tree_map, tree_multimap from . impo...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # This combines configurable build-time constants (documented on REPO_CFG # below), and non-configurable constants that are currently not name...
# Author: <NAME> # E-mail: <EMAIL> # Author: <NAME> # E-mail: <EMAIL> # Author: <NAME> # E-mail: <EMAIL> from sklearn.preprocessing import OneHotEncoder from sklearn.metrics import accuracy_score from tqdm import tqdm import numpy as np import torch from torch import nn from tqdm import tqdm from sklearn.metrics i...