input
stringlengths
2.65k
237k
output
stringclasses
1 value
except Exception: callback = self.null_callback if line == '': pass elif line == '{': cur_parent = parent_list[-1][-1] parent_list.append(cur_parent) parent_list_end = cur_parent elif line == '}': parent_list.pop() parent_list_end = parent_list[-1] else: try: key, value = line_parser(line) except (TypeE...
import os import time import sys from copy import deepcopy import torch import torch.nn as nn import numpy as np import numpy.random as rd import pandas as pd """finance environment Source: https://github.com/AI4Finance-Foundation/FinRL-Meta/blob/master/Demo_China_A_share_market.ipynb Modify: Github YonV...
<filename>demonstrations/tutorial_rosalin.py r""" Frugal shot optimization with Rosalin ===================================== .. meta:: :property="og:description": The Rosalin optimizer uses a measurement-frugal optimization strategy to minimize the number of times a quantum computer is accessed. :property="...
#!/usr/bin/env python ############################################################################## # DESCRIPTION ############################################################################## """ new SRM probe, using gfal2, NAP, and compatible with python3 """ import sys import time import gridutils import tempfil...
import requests import robot from robot.api.deco import keyword from robot.libraries.BuiltIn import BuiltIn from RequestsLibrary import log from RequestsLibrary.compat import urljoin from RequestsLibrary.utils import is_file_descriptor, warn_if_equal_symbol_in_url_session_less class RequestsKeywords(object): ROBOT_...
<gh_stars>0 """ Module with functions to plot and extract CSD info from LFP data """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals from __future__ import absolute_import try: basestring except NameError: basestring = str # THIRD PARTY IMPORTS import ...
u('\u5e7f\u4e1c\u7701\u6885\u5dde\u5e02')}, '861572878':{'en': 'Zhanjiang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6e5b\u6c5f\u5e02')}, '861572879':{'en': 'Shenzhen, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6df1\u5733\u5e02')}, '861572880':{'en': 'Shanwei, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5c3e\u5e02')...
: Get `hx` and `x0` for a flexible number of `nx` with given bounds. Parameters ---------- min_width : float Minimum cell width. If x1 is provided, the actual minimum cell width might be smaller than min_width. domain : list [start, end] of model domain. nx : int Number of cells. x0 : float Center of ...
subscription.event_handlers: self.add_waitable(event_handler) return subscription def create_client( self, srv_type, srv_name: str, *, qos_profile: QoSProfile = qos_profile_services_default, callback_group: CallbackGroup = None ) -> Client: """ Create a new service client. :param srv_type: The service t...
""" Kubernetes watching/streaming and the per-object queueing system. The framework can handle multiple resources at once. Every custom resource type is "watched" (as in ``kubectl get --watch``) in a separate asyncio task in the never-ending loop. The events for this resource type (of all its objects) are then pushed...
<gh_stars>1-10 # /******************************************* # * * # * <NAME>'s Vertex Array Example * # * nehe.gamedev.net * # * 2003 * # * * # *******************************************/ # # # NeHe Tutorial Lesson: 45 - Vertex Buffer Objects # # Ported to PyOpenGL 2.0 by <NAME> 2004 # # This code was created by <NA...
:param color: The hex color code, prefixed with '#' (e.g. '#00ff00'), to use when this metric is rendered on a graph. The ``Color`` class has a set of standard colors that can be used here. Default: - Automatic color :param dimensions: (deprecated) Dimensions of the metric. Default: - No dimensions. :param dimensions...
a reward_dist = - np.linalg.norm(vec) #reward_ctrl = - np.square(total_torque).sum() reward_shoulder = - np.square(total_torque[0:3]).sum() reward_wristrot = - np.square(total_torque[4::]).sum() reward = self.distance_reward_weight * reward_dist\ + self.shoulder_cost_weight*reward_shoulder\ + self.wrist_cost...
<gh_stars>1-10 """ Mask R-CNN Train on the toy Balloon dataset and implement color splash effect. Copyright (c) 2018 Matterport, Inc. Licensed under the MIT License (see LICENSE for details) Written by <NAME> ------------------------------------------------------------ Usage: import the module (see Jupyter notebooks...
<reponame>PartumSomnia/bns_ppr_tools # from __future__ import division from sys import path from dask.array.ma import masked_array path.append('modules/') from _curses import raw import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt from matplotlib import rc plt.rc('text', usetex=True) plt.rc('fo...
d.replace("...",".") unused = ["[unused1]", "[unused2]"] a = [] if is_speaker(x): a += [x] else: a += [None] if x != y and is_speaker(y): a += [y] else: a += [None] for i in range(len(a)): if a[i] is None: continue d = d.replace(a[i] + ":", unused[i] + " :") if x == a[i]: x = unused[i] if y == a[i]: y...
= f[-1] + n, f[:-1] layer_number0 = int(n) if layer_number0 >= number_of_layers: msg = 'fields {}: layer {} greater then the maximum number of layers'.format(field_x, str(layer_number0)) raise ValueError(msg) layers_dict[layer_number0] = fieldname_dict for ilc in range(number_of_layers): ly_in = self.dataset.Ge...
#!/usr/bin/env python # # Indexes scans into csv file # Run with ./index.py (or python index.py on Windows) import argparse import csv import json import re import os import sys import logging import util import compute_timings as timings from glob import glob FORMAT = "%(asctime)-15s [%(levelname)s] %(message)s" l...
<reponame>cosmodesi/cosmoprimo<gh_stars>1-10 """Cosmological calculation with the Boltzmann code CAMB.""" import warnings import numpy as np import camb from camb import CAMBdata, model, CAMBError from .cosmology import BaseEngine, BaseSection, BaseBackground, CosmologyError from .interpolator import PowerSpectrumIn...
video_tools.get_frames_from_segment(result[2])) self.assertEqual(112, video_tools.get_start_frame_from_segment(result[2])) self.assertEqual(135, video_tools.get_end_frame_from_segment(result[2])) self.assertEqual(1.1, video_tools.get_error_from_segment(result[0])) self.assertEqual(1.2, video_tools.get_error_from_se...
# Copyright (c) 2020: <NAME> (<EMAIL>). # # This file is modified from <https://github.com/philip-huang/PIXOR>: # Copyright (c) [2019] [<NAME>] # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. """Utils for PIXOR detection.""" from __future__ import...
op, val, 'safe-useval') else: add(lines, op, -1, 'safe-noval') if op == c.OP_HALT: break position = primitive.advance_position(position, direction, step) return lines, label_map, code_map def optimize1(self): self.optimize_jump() reachability = self.optimize_deadcode1() self.optimize_adjust(reachability) r...
import os import sys sys.path.append(os.getcwd() + "/facerecognition/PyFaceRecClient/simple-faster-rcnn-pytorch/") import torchvision import torch import numpy as np from models.utils.bbox_tools import bbox2loc, bbox_iou, loc2bbox from models.utils.nms import non_maximum_suppression ''' class ProposalTargetCreator(ob...
item in params.get("SnapshotByTimeOffsetTaskSet"): obj = SnapshotByTimeOffsetTaskInput() obj._deserialize(item) self.SnapshotByTimeOffsetTaskSet.append(obj) if params.get("SampleSnapshotTaskSet") is not None: self.SampleSnapshotTaskSet = [] for item in params.get("SampleSnapshotTaskSet"): obj = SampleSnapshotTas...
# noqa: E501 self._size = size @property def iceberg(self): """Gets the iceberg of this OptionsOrder. # noqa: E501 Display size for iceberg order. 0 for non-iceberg. Note that you will have to pay the taker fee for the hidden size # noqa: E501 :return: The iceberg of this OptionsOrder. # noqa: E501 :rtype: i...
<filename>ellipse_editor.py<gh_stars>1-10 #! /usr/bin/env python3 ''' Ellipse editor, standalone utility for use with steelpan images & annotations Author: <NAME> License: MIT (below) Reads a CSV file of the format cx,cy,a,b,angle,rings (a & b are ellipse axes), as in.. $ cat test_img.csv 37,42,30,42,63,0 402,71,37,2...
import argparse import os import random import shutil import time import warnings import builtins import math import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.distributed as dist import torch.optim import torch.multiprocessing as mp import torch.utils.data i...
<gh_stars>0 ####################################################################################################### ## ## ## Script name: linear_eq_solver.py ## ## Purpose of script: Linear equation solver for a Python CodeClub Estonia challenge ## ## Author: <NAME> ## ## Date Created: 3 Nov 2021 ## ## ## ## Copyright:...
<filename>src/ixdat/techniques/ec_ms.py """Module for representation and analysis of EC-MS measurements""" import numpy as np from ..constants import FARADAY_CONSTANT from .ec import ECMeasurement from .ms import MSMeasurement, MSCalResult from .cv import CyclicVoltammagram from ..exporters.ecms_exporter import ECMSExp...
import math from decimal import Decimal, getcontext import numpy as np import scipy.sparse as sp import scipy.sparse.linalg as LA # # Runge-Kutta IMEX methods of order 1 to 3 # class rk_imex: def __init__(self, M_fast, M_slow, order): assert np.shape(M_fast)[0] == np.shape(M_fast)[1], "A_fast must be square" asse...
optional): TenantIds contains ids of the tenants for which objects are to be returned. all_under_hierarchy (bool, optional): AllUnderHierarchy specifies if objects of all the tenants under the hierarchy of the logged in user's organization should be returned. usernames (list of string, optional): Optionally specif...
from pyxform.errors import PyXFormError from pyxform.tests_v1.pyxform_test_case import PyxformTestCase from pyxform.tests_v1.pyxform_test_case import PyxformTestError class ExternalInstanceTests(PyxformTestCase): """ External Instance Tests """ def test_can__output_single_external_xml_item(self): """Simplest po...
ValueError('to draw, first attach elements!') GL.glBindVertexArray(self.id) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, self.elements) if num is None: num = self.numElements - offset GL.glDrawElements(self.mode, num, self.elementsType, GL.GLvoidp(offset*self.elementsItemSize)) def drawArrays(self, mode, first, ...
<gh_stars>1-10 import socket from time import sleep from datetime import datetime def port_scanner(): host = '8.8.8.8' port = 53 try: socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port)) except socket.error: print('MikkOS cannot establish an internet connection using this device....
#To import required modules: import numpy as np import time import matplotlib import matplotlib.cm as cm #for color maps import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec #for specifying plot attributes from matplotlib import ticker #for setting contour plots to log scale import scipy.integrate #...
as JSONSchemaValidatorB3284240745E5B929C51495Fe80Bc1C4_v3_1_0 from .validators.v3_1_0.jsd_b5097e4db7505ba390914b50b1c2046b \ import JSONSchemaValidatorB5097E4DB7505Ba390914B50B1C2046B \ as JSONSchemaValidatorB5097E4DB7505Ba390914B50B1C2046B_v3_1_0 from .validators.v3_1_0.jsd_b55622f1671359919573b261ba16ea71 \ import...
<reponame>lekhanhbf121/Electron-Cash-SLP import copy import datetime from functools import partial import json import threading import sys, traceback from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from electroncash.address import Address, PublicKey from electroncash.bitcoin import ...
python path # use it for initializing basic options for # built-in integration for python_path in sys.path: if ('shotgun' in python_path) and ('flame_hooks' in python_path): shotgun_plugin_path = os.path.join( os.path.dirname(python_path), 'python' ) if shotgun_plugin_path not in sys.path: sys.path.append(...
0.25 3 3.86e+05 1782.66 | 1031.96 0.0 1000 0 | 0.13 0.23 45.79 0.16 3 3.94e+05 2410.15 | 3 3.94e+05 2410.15 | 2410.15 4.9 1000 0 | 0.12 0.14 32.34 0.09 3 4.04e+05 2556.36 | 3 4.04e+05 2556.36 | 2556.36 3.4 1000 0 | 0.15 0.09 24.99 0.08 3 4.13e+05 2575.00 | 3 4.13e+05 2575.00 | 2575.00 6.8 1000 0 | 0.17 0.07 22.31 0.07 ...
- gaps_first_segment_Transcript) #Position_in_Transcript.append(List[1] - gaps_first_segment_Transcript - ''.join(Aligned_B[List[0]:List[1]]).count('-')) accumulated_number_gaps_in_this_segment_transcript = gaps_first_segment_Transcript for i in range(0, len(List)): # we skip the first interval try: accumul...
<filename>adafruit_circuitpython_libs/adafruit-circuitpython-bundle-py-20210214/lib/adafruit_thermal_printer/thermal_printer.py # SPDX-FileCopyrightText: 2017 <NAME> for Adafruit Industries # # SPDX-License-Identifier: MIT """ `adafruit_thermal_printer.thermal_printer` - Thermal Printer Driver ========================...
<filename>tests/dcerpc/test_lsad.py # Impacket - Collection of Python classes for working with network protocols. # # SECUREAUTH LABS. Copyright (C) 2021 SecureAuth Corporation. All rights reserved. # # This software is provided under a slightly modified version # of the Apache Software License. See the accompanying LI...
#!/usr/bin/env python3 from collections import defaultdict from warnings import warn import numpy as np from pandas import DataFrame from scipy.linalg import eig from pgmpy.factors.discrete import State from pgmpy.utils import sample_discrete from pgmpy.extern import six from pgmpy.extern.six.moves import range, zip ...
<gh_stars>10-100 #!/usr/bin/env python from postgresadapter import PostgresAdapter import unittest import pandas as pd import numpy as np import sqlalchemy import psycopg2 import string import pytest @pytest.fixture(scope='class') def pg_config(request): """Set the postgresql_url attribute on TestCase classes.""" ...
#!/usr/bin/env python3.9 """ A small console script to set an alarm clock. Summary ------- Small alarm function for your console. Usable with one ([minutes] like a pomodoro) or two numeric arguments ([hh] [mm] sets alarm time). Also usable as module. But for bigger projects another approach should be used, because...
<gh_stars>0 __author__ = '<NAME>' __license__ = 'MIT' # copy of the license available @ https://prodicus.mit-license.org/ __version__ = '2.9' __email__ = '<EMAIL>' __github__ = "github.com/noahvendrig" # @noahvendrig __course__ = 'Software Design and Development' __date__ = '30/07/2021' __description__ = '\'Samson\' is...
length to wrap to if possible verbosity_option (str): 'brief', None (default), or 'verbose' Returns: str: Appropriately formatted and verbose string. """ header, str_list = self.profile_info_list( width, (verbosity_option != 'brief')) return "\n".join([header] + str_list) def create_configuration_profile(self...
# -*- coding: utf-8 -*- from __future__ import division from matplotlib.colors import ListedColormap import numpy as np import pandas as pd import matplotlib.pyplot as plt __all__ = ['decision_boundary_grid', 'plot_decision_boundary'] def decision_boundary_grid(clf, X, y, feat_list=None, cmap_bkg='RdBu', \ color_lab...
<reponame>ishtjot/susereumutep import gi import numpy as np #from datetime import datetime import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter import json import subprocess gi.require_version("Gtk", "3.0") from gi.repository import Gtk import requests # Have to manually send requests to each bloc...
<reponame>bob-bins/pulumi-newrelic # 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, Seque...
if response.content: mission = json.loads(response.content) return mission except Exception as err: message = str(err.message) current_app.logger.info(message) raise def uframe_mission_runs(id): """ Get mission runs. Sample request to be executed: http://localhost:port/mission/id/runs response: { "runs": [...
<reponame>zhouli121018/nodejsgm<gh_stars>0 # coding=utf-8 import re from django import forms from models import DomainBlacklist, KeywordBlacklist, MAIL_STATE, CHECK_RESULT, REVIEW_RESULT, CheckSettings, \ SubjectKeywordBlacklist, BounceSettings, SubjectKeywordWhitelist, FAIL_OR_SUCCESS, \ SenderBlacklist, InvalidMai...
= "dropCmdDeltaMax" DROP_CMD_DELTA_MIN = "dropCmdDeltaMin" DROP_FC_LIF_INVALID = "dropFcLifInvalid" DROP_FC_LIF_INVALID_DELTA = "dropFcLifInvalidDelta" DROP_FC_LIF_INVALID_DELTA_AVG = "dropFcLifInvalidDeltaAvg" DROP_FC_LIF_INVALID_DELTA_MAX = "dropFcLifInvalidDeltaMax" DROP_FC_LIF_INVALID_DELTA_MIN = "dropFcLifIn...
fields=( Field( name='QuestFlag', type='int', ), ), ), 'ShieldTypes.dat': File( fields=( Field( name='BaseItemTypesKey', type='ulong', key='BaseItemTypes.dat', unique=True, ), Field( name='Block', type='int', ), ), ), 'ShopCategory.dat': File( fields=( Field( name='Id', type='ref|string', uniq...
<gh_stars>0 # Copyright 2012, Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can # be found in the LICENSE file. # Handle transport and serialization callbacks for Go-style RPC servers. # # This is pretty simple. The client initiates an HTTP CONNECT and then # hijack...
the ebs configuration for your master group instances. Only a single block is allowed. :param pulumi.Input[bool] master_ebs_optimized: EBS Optimization setting for instances in group. :param pulumi.Input[Sequence[pulumi.Input[str]]] master_instance_types: The MrScaler instance types for the master nodes. :param pulu...
import os import pandas as pd import numpy as np import json import copy import getpass from time import gmtime, strftime from .operations import OperationTools from coconnect.tools.logger import Logger from coconnect.tools.profiling import Profiler from coconnect.tools.file_helpers import InputData from coconnect im...
<reponame>ya-enot/edk2<filename>BaseTools/Source/Python/AutoGen/GenDepex.py ## @file # This file is used to generate DEPEX file for module's dependency expression # # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR> # This program and the accompanying materials # are licensed and made availab...
shape=(self.numNodes,1)) self.f = numpy.array(self.parameters['f']).reshape((self.numNodes, 1)) if isinstance(self.parameters['f'], (list, numpy.ndarray)) else numpy.full(fill_value=self.parameters['f'], shape=(self.numNodes,1)) self.p = numpy.array(self.parameters['p']).reshape((self.numNodes, 1)) if isinstance(self...
TABLE', 12, 'COMMENT ANY TABLE', 13, 'SELECT ANY TABLE', 14, 'INSERT ANY TABLE', 15, 'UPDATE ANY TABLE', 16, 'DELETE ANY TABLE', 17, 'FLASHBACK ANY TABLE', 18, 'CREATE ROLE', 19, 'DROP ANY ROLE', 20, 'GRANT ANY ROLE', 21, 'ALTER ANY ROLE', 22, 'AUDIT ANY', 23, 'GRANT ANY PRIVILEGE', 24, 'GRANT ANY OBJECT P...
<reponame>djstroky/OnBoard from fabric.contrib.files import exists try: input = raw_input except NameError: pass from datetime import datetime import os import sys import time import boto.ec2 from fabric.api import env, run, sudo, cd, put from fabric.exceptions import NetworkError import requests from transitfeed....
'Redecentralization of the Web', 'observation_id': 568, 'receiver': 'B', 'sender': 'A', 'topic': 'Web Engineering'}, {'author': 'C', 'before': [568], 'message': 'Redecentralization of the Web', 'observation_id': 569, 'receiver': 'B', 'sender': 'C', 'topic': 'Web Engineering'}, {'author': 'A', 'before': [56...
<reponame>spencerkent/pyPyrTools from pyramid import pyramid import numpy from sp0Filters import sp0Filters from sp1Filters import sp1Filters from sp3Filters import sp3Filters from sp5Filters import sp5Filters import os from maxPyrHt import maxPyrHt from corrDn import corrDn import math from LB2idx import LB2idx import...
in by the user; *bed* is automatically passed in as the bedfile of this object; *fo* by default is a temp file. Use save_seqs() to save as a file. The end result is that this BedTool will have an attribute, self.seqfn, that points to the new fasta file. Example usage: >>> a = pybedtools.BedTool(""" ... chr1 1...
<reponame>iceokoli/pyfolio<gh_stars>0 # # Copyright 2018 Quantopian, 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...
# coding=utf-8 import logging import struct SS0 = [ 0x2989a1a8, 0x05858184, 0x16c6d2d4, 0x13c3d3d0, 0x14445054, 0x1d0d111c, 0x2c8ca0ac, 0x25052124, 0x1d4d515c, 0x03434340, 0x18081018, 0x1e0e121c, 0x11415150, 0x3cccf0fc, 0x0acac2c8, 0x23436360, 0x28082028, 0x04444044, 0x20002020, 0x1d8d919c, 0x20c0e0e0, 0x22c2e2e0, ...
self.challenging, 'desire' : self.desire, 'calm' : self.calm, # 'emphatic' : self.emphatic, 'sarcastic' : self.sarcastic, 'instructive' : self.instructive, 'accusative' : self.accusative, # 'admiration' : self.admiration, 'inquisitive' : self.inquisitive, 'modest' : self.modest, 'pride' : self.pride, # 'ambivalence'...
#!/usr/bin/env python3 # coding: utf8 # Author: <NAME>, 2016 ''' Parameter handling. This module provides: - a description of all parameters and their defaults - parsers for command-line arguments and .ini-file settings - a config object initialised with parameter attributes ''' import re import sys import json i...
date :type end: ``osid.calendaring.DateTime`` :param match: ``true`` for a positive match, ``false`` for a negative match :type match: ``boolean`` :raise: ``InvalidArgument`` -- ``end`` is less than ``start`` :raise: ``NullArgument`` -- ``end`` or ``start`` is ``null`` *compliance: mandatory -- This method must ...
src_id: An identifier that enables the constructed profile to be placed correctly in the results array. :param Quantity lower: The lower energy limit to use. :param Quantity upper: The higher energy limit to use. :return: The scaled profile, the cluster identifier, and the original generated surface brightness pro...
import json import pickle import sys from collections import Counter, defaultdict from dataclasses import dataclass, field from datetime import datetime, timedelta, timezone from functools import cached_property, partial from pathlib import Path from time import sleep from typing import Any, Callable, Dict, List, Opti...
import os from collections import OrderedDict from copy import deepcopy import numpy as np from bokeh.models import Row, Panel, Tabs from tqdm import tqdm from pimp.utils.bokeh_helpers import bokeh_boxplot, bokeh_line_uncertainty, save_and_show tqdm.monitor_interval = 0 import matplotlib as mpl mpl.use('Agg') from m...
98), (0, 251, 0x0000000071727374, 112, 112, 112, 112, 113, 113), (0, 251, 0x0000000072737475, 113, 113, 113, 113, 114, 114), (0, 251, 0x0000000081828384, 128, 128, 128, 128, 129, 129), (0, 251, 0x0000000082838485, 129, 129, 129, 129, 130, 130), (0, 251, 0x0000000091929394, 144, 144, 144, 144, 145, 145), (0, 251, ...
<reponame>radekg/netapp-ontap-lib-get from netapp.connection import NaConnection from snapshotstate_enum import SnapshotstateEnum # 0 properties from snapshot_id import SnapshotId # 0 properties from snapshot_info import SnapshotInfo # 22 properties from snapshot_multirename_error import SnapshotMultirenameError # 3 pr...
# coding=utf-8 ''' Created on Mar 17, 2016 @author: <NAME> <<EMAIL>> ''' import os import re import csv import itertools import tempfile import shutil from itertools import chain from random import shuffle from Bio import SeqIO from Bio.SeqFeature import FeatureLocation from Bio.SeqRecord import SeqRecord from Bio...
<reponame>OPU-Surveillance-System/monitoring<gh_stars>1-10 """ Define an abstract solver and a greedy, a random, a simulated annealing solvers. """ import copy import matplotlib.pyplot as plt from matplotlib import colors from sys import path import operator from simanneal import Annealer import random path.append(".....
workclass_map = {"Not in universe": "None", "Private": "Private", "Self-employed-not incorporated": "Self-emp-not-inc", "Local government": "Local-gov", "State government": "State-gov", "Self-employed-incorporated": "Self-emp-inc", "Federal government": "Federal-gov", "Never worked": "Never-worked", "Without pa...
] # hard coded for this particular file num_frames = 21304 processor = DataProcessor(config) signal = processor(self.signal) self.assertEqual(signal.shape, (n_fft // 2 + 1, num_frames)) def test_spectrogram_transform_complex(self): """Checks the case with spectrogram transform applied""" n_fft = 440 config =...
# coding: utf-8 # # Machine Learning Engineer Nanodegree # ## Unsupervised Learning # ## Project: Creating Customer Segments # Welcome to the third project of the Machine Learning Engineer Nanodegree! In this notebook, some template code has already been provided for you, and it will be your job to implement the add...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Statistic and fit indices.""" from .utils import duplication_matrix from scipy.stats import norm, chi2 from collections import namedtuple from .optimizer import Optimizer from .model_generalized_effects import ModelGeneralizedEffects from .model_effects import ModelEffe...
""" This file is part of gempy. Created on 21/02/2020 @author: <NAME> """ import numpy as np import matplotlib.colors as mcolors import pandas as pd rexFileHeaderSize = 64 rexCoordSize = 22 file_header_size = 86 rexDataBlockHeaderSize = 16 file_header_and_data_header = 102 mesh_header_size = 128 all_header_size =...
return status @_handle_errors @_ensure_connected async def watch( self, key: bytes, range_end: typing.Optional[bytes] = None, start_revision: typing.Optional[int] = None, progress_notify: bool = False, kind: typing.Optional[rtypes.EventKind] = None, prev_kv: bool = False, watch_id: typing.Optional[int] = No...
from machine import UART import utime as time # This hashmap collects all generic AT commands CMDS_GENERIC = { 'TEST_AT': b'AT', 'RESET': b'AT+RST', 'VERSION_INFO': b'AT+GMR', 'DEEP_SLEEP': b'AT+GSLP', 'ECHO': b'ATE', 'FACTORY_RESET': b'AT+RESTORE', 'UART_CFG_DEF': b'AT+UART_DEF=9600,8,1,0,0' } # All WIFI rela...
from googleapiclient import discovery from httplib2 import Http from oauth2client import file, client, tools import json import os import random import re import requests import string import sqlite3 import time import urllib import yaml import collections import io import csv import zipfile from flask import Flask f...
<gh_stars>1-10 # -*- coding: utf-8 -*- # script.module.python.koding.aio # Python Koding AIO (c) by whufclee (<EMAIL>) # Python Koding AIO is licensed under a # Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. # You should have received a copy of the license along with this # work...
#!/usr/bin/env python # encoding: ascii ############################################################################### # sagews2ipynb Convert a SageMathCloud worksheet into an iPython notebook. # This is useful because iPython notebooks are the only format # that works both for pushing/pulling files from sagemathcloud...
import torch from torch.autograd import Function from torch.nn import functional as F from torch.nn.modules.utils import _pair from torch import Tensor from cupy_layers.utils import Dtype, Stream, load_kernel CUDA_NUM_THREADS = 1024 kernel_loop = ''' #define CUDA_KERNEL_LOOP(i, n) \ for (int i = blockIdx.x * blockDi...
<reponame>Saurabh200598/Submitty<gh_stars>1-10 #!/usr/bin/env python3 import argparse from collections import OrderedDict import grp import json import os import pwd import secrets import shutil import string import tzlocal import tempfile import readline def get_uid(user): return pwd.getpwnam(user).pw_uid def ge...
The value of the attribute. Default is None. keys : list[int], optional A list of vertex identifiers. Returns ------- list[Any] | None The value of the attribute for each vertex, or None if the function is used as a "setter". Raises ------ KeyError If any of the vertices does not exist. """ vertices = ...
""" sentry.tagstore.v2.backend ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2017 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import collections import six import logging from collections import defaultdict from dat...
not a numpy array" print(e) return False # Get head objects status1 = status1.upper() unstructured1 = False if status1 == dbs: headobj1 = flopy.utils.HeadFile( hfpth1, precision=precision, verbose=verbose, text=text ) txt = headobj1.recordarray["text"][0] if isinstance(txt, bytes): txt = txt.decode("utf-8"...
q_list: 默认 [0.05, 0.10, 0.25, 0.50, 0.75, 0.90, 0.95] :return: """ fund_nav_df = get_fund_nav_weekly_by_strategy(strategy_type_en, date_from, date_to, show_fund_name=True) fund_nav_df = fh_utils.DataFrame.interpolate_inner(fund_nav_df) fund_pct_df = fund_nav_df.pct_change().fillna(0) # 超过 6次净值不变则剔除 if ...
vartype='CONT')] >>> m.drop_variables(x) >>> print(m.get_variables()) [] See also -------- :func:`Model.drop_variable` :func:`Model.drop_constraint` :func:`Model.drop_constraints` ''' for v in variables: self.drop_variable(v) if variables in self._vargroups: self._vargroups.remove(variables) def drop_c...
#!/usr/bin/env python """ A mini test harness. Runs all the files you specify through an interpreter you specify, and collates the exit codes for you. Call with the -h switch to find out about options. """ import argparse import signal import subprocess import os import getpass import calendar import sqlite3 as db imp...
<gh_stars>10-100 import ast import sys from contextlib import contextmanager from dataclasses import dataclass, field from typing import Any, Callable from . import mast, utils _PY = (sys.version_info.major, sys.version_info.minor) def _get_ast_slice(node): if _PY >= (3, 9): return node.slice else: assert isin...
return if response.code != 200: self.logger.error("%s: error from jss" % inspect.stack()[0][3]) self.status_label.configure(style='Warning.TLabel') self.status_string.set("%i returned." % response.code) return # # handle various communication errors except urllib2.HTTPError, error: if error.code == 400: self...
# from muvi.view.ooopengl import ShaderProgram try: # this fails in <= 2020 versions of Python on OS X 11.x from OpenGL import GL except ImportError: # print('Patching ctypes for OS X 11.x...') from ctypes import util orig_util_find_library = util.find_library def new_util_find_library(name): res = orig_util_fi...
<gh_stars>1-10 # coding: utf-8 # # Copyright 2017 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Un...
and P_+ and P_- are projectors on to the eigenspaces corresponding to +1 (+i) & -1 (-i) eigenvalues, then # l P_+ - l P_- = W, and P_+ + P_- = \id. We can solve for P_+ and P_- from this. l \in {1, i}, depending on the pase. # l = 1 or i can be obtained from the phase as sgn(phase) * phase, noting that phase is one o...
''' Extensions to ConsIndShockModel concerning models with preference shocks. It currently only two models: 1) An extension of ConsIndShock, but with an iid lognormal multiplicative shock each period. 2) A combination of (1) and ConsKinkedR, demonstrating how to construct a new model by inheriting from multiple class...