input
stringlengths
2.65k
237k
output
stringclasses
1 value
<gh_stars>10-100 #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Jun 16 22:56:22 2017 @author: Arpan Description: Use MBH Features and ImageNetShuffle Features """ import json import os import utils import numpy as np import h5py import pandas as pd import collections import cPickle from sklearn im...
constant matrix; we don't # want to broadcast the matrix!). So, outside the loop we perform a partial # evaluation with known 'const' inputs (but all other inputs unknown). const_pvals = [pe.PartialVal.known(t.pval.get_known()) for t in tracers[:num_consts] if t.pval.is_known()] other_pvals = [pe.PartialVal.unknow...
<filename>untitled0.py<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 28 13:30:29 2021 @author: jr3 """ """ Write a Python program that takes as input a file containing DNA sequences in multi-FASTA format, and computes the answers to the following questions. You can choose to wr...
# import system packages import os from datetime import datetime import sys import argparse import traceback import pickle import yaml from argparse import ArgumentParser, RawTextHelpFormatter # import numpy import numpy as np import healpy as hp # the MPI comunicator class, customized for pycal data storage from pyc...
import itertools import sqlite3 def establish_connection(output_db): """ Establishes connection with sqlite3 database. If the file does not exist, it will be created. Parameters ---------- output_db : string The full path to the SQLite database. Returns ------- conn : sqlite3 connection An object used t...
namespace_='', name_='TileMatrixSetLink', fromsubclass_=False): if self.TileMatrixSet is not None: showIndent(outfile, level) outfile.write('<%sTileMatrixSet>%s</%sTileMatrixSet>\n' % (namespace_, self.gds_format_string(quote_xml(self.TileMatrixSet).encode(ExternalEncoding), input_name='TileMatrixSet'), namespace_))...
# -*- coding: utf-8 -*- """ This script is used to run convert the raw data to train and test data It is designed to be idempotent [stateless transformation] Usage: python ./scripts/etl.py """ from pathlib import Path import click import pandas as pd import numpy as np import calendar import datetime as dt import pps...
to [2]_ for more information on this xarray behavior. * "drop_incomplete_djf" (bool, by default False) If the "dec_mode" is "DJF", this flag drops (True) or keeps (False) time coordinates that fall under incomplete DJF seasons Incomplete DJF seasons include the start year Jan/Feb and the end year Dec. Configs ...
""" WRITEME """ from __future__ import absolute_import, print_function, division import logging import warnings import theano from theano import gof import theano.gof.vm from theano.configparser import config from six import string_types from theano.compile.function_module import Supervisor _logger = logging.getLog...
# Copyright 2022 The TensorFlow 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 # # Unless required by applicable ...
1/4, 50 1/2, 75 3/4 on pi.set_PWM_range(9, 500) # now 125 1/4, 250 1/2, 375 3/4 on pi.set_PWM_range(9, 3000) # now 750 1/4, 1500 1/2, 2250 3/4 on ... """ return _u2i(_pigpio_command(self.sl, _PI_CMD_PRS, user_gpio, range_)) def get_PWM_range(self, user_gpio): """ Returns the range of PWM values being used on t...
left_key(self): r""" Return the left key of the alternating sign matrix ``self``. The left key of an alternating sign matrix was defined by Lascoux in [LascouxPreprint]_ and is obtained by successively removing all the `-1`'suntil what remains is a permutation matrix. This notion corresponds to the notion of lef...
signals = jm_client_special_interrupt_signals) for p in self.procs: p.join() log.debug("worker process %s exitcode %s", p.pid, p.exitcode) log.debug("worker process %s was joined", p.pid) log.debug("all workers joind") log.debug("still in progressBar context") log.debug("progressBar context has been left") ...
<reponame>LucasBorges-Santos/docker-odoo<gh_stars>0 # -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import defaultdict from dateutil.relativedelta import relativedelta from itertools import groupby from odoo import api, fields, models, _, SUPERUSER_I...
import platform import re import sys import traceback from .DataGridder import DataGridder from . import ClassifyUtils from . import ClassifyMethod from .ClassifyMethod import ClassifyMethodError qgis_qhull_fails=platform.platform().startswith('Linux') from qgis.core import ( QgsExpression, QgsExpressionContext, ...
<filename>maya/libs/dagutils.py import maya.cmds as mc import maya.OpenMaya as legacy import maya.api.OpenMaya as om import maya.api.OpenMayaAnim as oma from six import string_types from collections import deque from itertools import chain import logging logging.basicConfig() log = logging.getLogger(__name__) log.set...
<gh_stars>0 # Author: <NAME>, <NAME> & <NAME> """ Molecule graph kernels for Gaussian Process Regression implemented in GPflow using Graphkit-learn. """ import gpflow from gpflow.utilities import positive from gpflow.utilities.ops import broadcasting_elementwise import tensorflow as tf from pysmiles import read_smiles...
<filename>graylog/apis/pluginsorggraylogpluginscollector_api.py<gh_stars>1-10 # coding: utf-8 """ No descripton provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 2.1.1+01d50e5 Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed u...
server data variable under this server's ID server_data[server.id] = server_cache() create_board( server_id=server.id, name=server.name, description=board_base_desc.format(server.name) ) # Backup the server data now that we've made changes backup() await bot.send_message(admin, step1_setup_msg.f...
<filename>tests/models/dfoundations/test_dfoundations_model.py import logging import os from pathlib import Path from typing import Type import pytest from teamcity import is_running_under_teamcity from geolib.errors import CalculationError from geolib.geometry.one import Point from geolib.models import BaseModel, DF...
<reponame>keerockl/PerfKitBenchmarker<filename>perfkitbenchmarker/providers/gcp/gcp_relational_db.py # Copyright 2017 PerfKitBenchmarker 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...
<reponame>Yelp/zygote import atexit import datetime import errno import fcntl import logging import os import signal import socket import struct import sys import time import tornado.ioloop from zygote import accounting from zygote import handlers from zygote import message from zygote.util import close_fds from zygo...
""" Contains functions to estimate aspects of blocks (like area and delay) by either using internal models or by making calls out to external tool chains. """ from __future__ import print_function, unicode_literals import re import os import math import tempfile import subprocess import sys import collections from ...
ttk.Frame(self.Window_vectorconfig,padding=10) ttk.Label(fsel,text="File: ").grid(row=0,column=0,sticky='e',padx=3) _wsel = ttk.Combobox(fsel,textvariable=self.VEC_INDX, values=self.VEC_LIST,width=5) _wsel.grid(row=0,column=1,sticky='w',padx=3) _wsel.bind('<<ComboboxSelected>>',lambda e:_selected()) _went = ttk.E...
frame to execute. """ # Set the current frame number self.__frame = frame # Set any arg overrides from args_override in the session self.setup_args_override() # Find the local frame set, ie the frames that this # instance is responsible for. frames = self.get_local_frame_set(frame) # Set OL_ environment var...
# coding: utf-8 """ Python InsightVM API Client OpenAPI spec version: 3 Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from rapid7vmconsole.api_client ...
<reponame>arminnh/c-to-p-compilers import copy from enum import Enum from TypeInfo import TypeInfo from antlr4.Token import CommonToken from antlr4.tree.Tree import TerminalNode offset = " | " class ASTNode(object): def __init__(self, label="no label", ctx=None, parent=None): self.tree = None self.parent = parent...
from __future__ import unicode_literals import frappe, math from frappe import _ from frappe.utils import flt from frappe.model.mapper import get_mapped_doc from frappe.model.document import Document from frappe.contacts.doctype.address.address import get_company_address from frappe.contacts.doctype.address.address imp...
scores(self) -> np.ndarray: """Return point scores for each predicted node.""" return self.points_and_scores_array[:, 2] @classmethod def from_instance(cls, instance: Instance, score: float) -> "PredictedInstance": """Create a `PredictedInstance` from an `Instance`. The fields are copied in a shallow manner wit...
<reponame>bcurnow/mfrc522-reader import re import pytest import RPi.GPIO as realGPIO from unittest.mock import call from mfrc522reader.mfrc522 import MFRC522 ANTENNA_ON = 0b00000011 ANTENNA_OFF = 0b00000000 def test_Register_read(): # Make sure we're starting with the value we intend assert MFRC522.Register.Com...
<filename>arena/game.py import pygame import sys import math import random import numpy as np from .base import PyGameWrapper from .base import Agent, Bombv, Blast, Enemy, Obstacle, Projectile, Reward from .base import vec2d from pygame.constants import K_w, K_a, K_s, K_d, K_j, K_SPACE class Arena(PyGameWrapper): d...
<gh_stars>1-10 ''' Contains the code for training the encoder/decoders, including: - Cross model loss - Supervised loss - Denoising loss - Discriminator loss ''' from utils import * from preprocess import get_dataset, DataLoader, collate_fn_transformer from module import TextPrenet, TextPostnet, RNNDecoder, RNNEnco...
<gh_stars>100-1000 # Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
"most_likely_winner", "partial_rate", ) def __init__(self, bets: Bets): self._odds_values = bets.nfc._data_dict["odds"][bets._indices] self._odds = [ Chance(**chance) for chance in NFCMath.get_bet_odds_from_bets( bets.indices, self._odds_values, bets.nfc._stds # type: ignore ) ] self.best = self._odds[-1] #...
keys, values or the whole style-dict, passing in the current :class:`plot_args <.PlotArgs>`, and replace those with the callable's result (even more flexible than templates). - Resolve any :class:`.Ref` instances, first against the current *nx_attrs* and then against the attributes of the current theme. - Render...
in the model parameters (L2-norm). Returns ------- test_success : list of bool's List of success flags. test_results : list of tuple's of numpy.ndarray's List of tuples containing the predicted and the expected result. ''' test_successes = [] test_results = [] test_results.append(inverse_solver.test_model...
[128] CS_l1b_mds['Waveform_20Hz']['Waveform'] = np.zeros((n_records,n_blocks,n_LRM_RW),dtype=np.uint16) # Echo Scale Factor (to scale echo to watts) CS_l1b_mds['Waveform_20Hz']['Linear_Wfm_Multiplier'] = np.zeros((n_records,n_blocks),dtype=np.int32) # Echo Scale Power (a power of 2 to scale echo to Watts) CS_l1b_m...
import time import datetime import os import tellopy import numpy as np import av import cv2 from pynput import keyboard from threading import Thread import argparse from math import pi, atan2, degrees, sqrt from simple_pid import PID from FPS import FPS from CameraMorse import RollingGraph import logging import re d...
import numpy import pandas import hts.hierarchy from hts.functions import ( _create_bl_str_col, get_agg_series, get_hierarchichal_df, to_sum_mat, ) def test_sum_mat_uv(uv_tree): mat, sum_mat_labels = to_sum_mat(uv_tree) assert isinstance(mat, numpy.ndarray) shp = mat.shape assert shp[0] == uv_tree.num_nodes(...
thorugh the progression tree and generates the entity list based on the node objects """ nodes_strings_distinct = list(set([self._get_object_string_from_vector(node.value) for node in self.tree.get_leaves()])) entity_list = [] # initiate list of unoccupied indices indices = np.array(np.unravel_index(range(self.gri...
<gh_stars>0 # pyfu/ifu.py """ Objects for managing IFU fibres and their spectra. """ import numpy as np import sys import logging from astropy.io import fits from astropy.table import Table, Column from astropy.wcs import WCS from matplotlib import pyplot as plt, cm as colourmaps from matplotlib.colors import Norm...
import collections import glob import itertools import json import logging import os from copy import deepcopy from functools import lru_cache from typing import Callable, Dict, List, NamedTuple, Optional, Tuple, Union import _jsonnet import numpy as np import trimesh from collision import Poly, Vector, collide from m...
""" This script reproduces Fig. 1 of Izhikevich (2004). Original implementation references: Izhikevich E.M. (2004) Which Model to Use for Cortical Spiking Neurons? IEEE Transactions on Neural Networks, 15:1063-1070 (special issue on temporal coding) Izhikevich E.M. (2003) Simple Model of Spiking Neurons. ...
<reponame>nealedj/eq-survey-runner # coding: utf-8 from types import SimpleNamespace from datetime import datetime, timedelta from unittest.mock import patch from dateutil.relativedelta import relativedelta from jinja2 import Undefined, Markup from mock import Mock from app.jinja_filters import ( format_date, forma...
"""OpenID Connect authentication provider.""" from __future__ import annotations from typing import Any, Dict, List, Mapping, Optional from urllib.parse import urlencode, urljoin import jwt from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import rsa from cryptog...
<filename>tools/jallib.py #!/usr/bin/python # # Title: jallib main wrapper script # Author: <NAME>, Copyright (c) 2008..2022, all rights reserved. # Adapted-by: <NAME> # Compiler: # # This file is part of jallib (https://github.com/jallib/jallib) # Released under the ZLIB license (http://www.opensource.org/lice...
Unit.create_scaled_unit(kelvin, "p") ukelvin = Unit.create_scaled_unit(kelvin, "u") Tkelvin = Unit.create_scaled_unit(kelvin, "T") ykelvin = Unit.create_scaled_unit(kelvin, "y") Ekelvin = Unit.create_scaled_unit(kelvin, "E") zkelvin = Unit.create_scaled_unit(kelvin, "z") Mkelvin = Unit.create_scaled_unit(kelvin, "M") k...
= 0 df.loc[threes == True, (f"{prefix[0]}_fill_4", prefix[1])] = 1 df[(f"{prefix[0]}_fill_3", prefix[1])] = np.zeros(threes.shape) ld = self.copy().denormalize() if self.label is not None and not exclude_label: convert_label(ld.label) if self.pred is not None: convert_label(ld.pred) if self.data is not None: ...
"""Compares two image tarballs and finds how their layers differ. Compares two images layer by layer and prints out which layers differ and what files differ per layer. usage: idd.py [-h] [-c] [-d] [-f] [-l MAX_LAYER] [-v] tar1 tar2 positional arguments: tar1 First image tar path tar2 Second image tar path optio...
<reponame>carbonplan/trace import gc import json from itertools import compress import boto3 import dask import numpy as np import rasterio as rio import rioxarray # for the extension to load import utm import xarray as xr from botocore.exceptions import ClientError from rasterio.session import AWSSession from s3fs im...
<filename>gff_to_gbk.py #!/usr/bin/env python3 # coding: utf8 """ Description: Using fasta files (scaffold/chromosme/contig file, protein file), gff file, annotation tsv file and the species name this script writes a genbank file. The annotation tsv file contains association between gene and annotation (EC number, GO...
length >= CONST.lengthMidGame): if (largest and health > CONST.healthMed and length >= CONST.lengthMidGame): interruptlist.append(['Idle', 'Centre']) reason.append('largest snake. length: '+str(length)) # Early game - Survive & eat # or (health > CONST.healthMed and length < CONST.lengthMidGame # if (numMoves...
<filename>nltk/sourcedstring.py # Natural Language Toolkit: Sourced Strings # # Copyright (C) 2001-2009 NLTK Project # Author: <NAME> <<EMAIL>> # URL: <http://www.nltk.org/> # For license information, see LICENSE.TXT """ "Sourced strings" are strings that are annotated with information about the location in a document...
data point. If rel=True, assumes that center point is 0.0 ppm and calculates the relative hertz away represented by the ppm value. """ hpp = self.raw_hpp if acq else self.spectral_hpp ppm = self.pts2hz(self.ppm2pts(val)) if rel else self.ppm2pts(val, rel=rel) * hpp return ppm def pts2ppm(self, val, acq=False,...
<reponame>a-fox/indy-node from copy import deepcopy from typing import List import base58 from indy_common.auth import Authoriser from indy_common.constants import NYM, ROLE, ATTRIB, SCHEMA, CLAIM_DEF, REF, \ GET_NYM, GET_ATTR, GET_SCHEMA, GET_CLAIM_DEF, SIGNATURE_TYPE, REVOC_REG_DEF from indy_common.roles import Ro...
<reponame>longtermrisk/marltoolbox import copy import logging import os import ray from ray import tune from ray.rllib.agents import dqn from ray.rllib.agents.dqn.dqn_torch_policy import postprocess_nstep_and_prio from ray.rllib.utils import merge_dicts from ray.rllib.utils.schedules import PiecewiseSchedule from ray....
<reponame>GangQiao520/1_microscopic_wo_disentanglement<gh_stars>0 import numpy as np import cv2 import keras from keras import callbacks from keras.models import Sequential, Model from keras.layers import TimeDistributed, Conv2D, MaxPooling2D, Dense, Dropout, Flatten, LSTM, Reshape, Conv2DTranspose, Input, LeakyReLU f...
zodiacal light doesn't use PSF information if inst.is_lyot: fzodi_pix *= 0.19 # Total stellar flux and associated magnitude star_flux = obs.countrate() # e/sec mag_nrc = obs.effstim('vegamag') _log.debug('Total Source Count Rate for {0} = {1:0.1f} mags: {2:.0f} e-/sec'.\ format(bp_lim.name, mag_norm, star_flux...
string def set_dtype(self, dtype): """ Set the detector type (photon or energy)""" self.mean_.set_dtype(dtype) for filter_k in self.samples_: filter_k.set_dtype(dtype) self.dtype = self.mean_.dtype def set_wavelength_unit(self, unit): """ Set the wavelength units """ self.mean_.set_wavelength_unit(unit) for...
import scipy.sparse as sp import scipy.sparse.linalg as slinalg from numpy import linalg import scipy.misc from sklearn.preprocessing import normalize from gcn.utils import Test21, absorption_probability, smooth, load_data, taubin_smoothing import gcn.utils from config import configuration import matplotlib.pyplot as p...
import copy import re from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned from django.db import connection from django.db.models import Q from django.db.models.sql.query import AND, OR from django.utils.tree import Node ORDER_PATTERN = re.compile(r'^[-+]?[a-zA-Z0-9_]+$') FIELD_PATTERN = re...
>>> >>> response = client.get_model(name) Args: name (str): Resource name of the model. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the reques...
self._store[chunk_id] = chunk def ensure_header(self, f): self._add_header = f # Reconstruct a level 2 volume header if we miss the first block @property def vol_hdr(self): if not self._vol_hdr and self._add_header: pi = self.first_chunk().prod_info hdr = pi.as_vol_hdr() logger.warning('Created volume header...
graph. Returns ------- int The number of edges """ return self._graph.number_of_edges() def has_node(self, vid): """Return True if the graph contains node `vid`. Identical to `vid in G`. Parameters ---------- vid : int The node ID. Returns ------- bool True if the node exists Examples -------- ...
padded_ids = ids + [0] * (bucket_size - len(ids)) return padded_ids def padding_data_instance(instance, bucket): """ NOTE: currently this function does not padding for post length. """ _, text_word_size, query_word_size, code_token_size = bucket iid, text_blocks, text_block_actual_lengths, code_blocks, code_block...
import json import base64 from yadacoin.transactionutils import TU from bitcoin.wallet import P2PKHBitcoinAddress from bson.son import SON from coincurve import PrivateKey class _BU(object): # Blockchain Utilities collection = None database = None @classmethod def get_blocks(cls, config, mongo, reverse=False): ...
-0.07, -0.34], [-0.2 , 0.25, 0.24, 0.02, 0.12, 0.37, -0.56, -0.17, -0.46, 0.46, 0.1 , -0.4 , 0.52, -0.47, 0.06, 0.24, -0.39]], dtype=float32), array([ 0.24, -0.21, 0.39, -0.23, -0.39, -0.34, 0.17, 0.33, 0.4 , -0.35, -0.36, 0.32, -0.3 , 0.32, 0.4 , -0.3 , 0.28], dtype=float32), array([[ 0.32, 0.35, -0.27, -0.4 , 0....
child < self.branching_factor nodes.append((node, child)) node = self.__ChildNodeId(node, child) return nodes def __WhichChild(self, low, high, want, branching_factor): """Determines which child of the range [low, high) 'want' belongs to. Args: low: An int, the low end of the range. high: An int, the high end...
of credits fromt the user and adding the item into the user's inventory. :param basedUser user: The user attempting to buy the ship :param Ship requestedWeapon: The ship to sell to user :raise RuntimeError: If user cannot afford to buy requestedWeapon """ if self.userCanAffordItemObj(user, requestedShip): self.s...
unembarrassed unemotional unending unendurable unenforceable unenthusiastic unenviable unequally unequivocally unerringly unevenness uneventfully unexampled unexceptionable unexceptional unexciting unexplored unexpurgated unfailingly unfairness unfaithfully unfaithfulness unfamiliarity unfashionable unfathomable unfeel...
#!/usr/bin/env python3 import os import sys import math import enum import urllib import hashlib import pathlib import inspect import logging import argparse import datetime import itertools import collections import multiprocessing # TODO: version dependencies statically import bottle import ffmpeg import PIL import...
"""Tuya devices.""" import datetime import logging from typing import Any, List, Optional, Tuple, Union from zigpy.quirks import CustomCluster, CustomDevice import zigpy.types as t from zigpy.zcl import foundation from zigpy.zcl.clusters.general import OnOff, PowerConfiguration from zigpy.zcl.clusters.hvac import Ther...
distance map """ from scipy import ndimage import numpy as np # distance metric if distance_method is 'edt': data_dist = ndimage.distance_transform_edt(data).astype('float32') elif distance_method is 'fmm': import skfmm # scikit-fmm data_dist = skfmm.distance(data).astype('float32') data_grad = np.array(np....
import math from collections import OrderedDict import pytest import torch from torch import nn import continual as co from continual.module import TensorPlaceholder torch.manual_seed(42) def test_sequential(): S = 3 long_example_clip = torch.normal(mean=torch.zeros(10 * 3 * 3)).reshape( (1, 1, 10, 3, 3) ) ...
<gh_stars>0 import functools from operator import lt from itertools import product, starmap from collections import OrderedDict import numpy as np from pgmpy.exceptions import Exceptions from pgmpy.extern import tabulate class Factor: """ Base class for *Factor*. Public Methods -------------- assignment(index...
* qa) cuts.append(x1 + x) if len(cuts) == npieces - 1: return cuts segment_remaining -= needed needed = size return qb def func_a95cb57b432c495f9ea61358ecb327e7(npieces, x2, h1, x1, needed, cuts, size, h2): area_from_left += needed width = x2 - x1 if h1 == h2: x = area_from_left / h1 else: qa = (h2 - h1)...
Sequence[str]], *, shell: bool, stdin: int, stdout: int, stderr: int, cwd: Union[str, bytes, PathLike, None] = None, env: Optional[Mapping[str, str]] = None) -> Process: await checkpoint() if shell: process = await asyncio.create_subprocess_shell( command, stdin=stdin, stdout=stdout, # type: ignore[arg-type] st...
terms of R^2 (percentage). In the full-fit and bootstrap cases, <R2> is an R^2 value indicating how well the final model estimate (<modelmd>) fits the data. In the cross-validation case, <R2> is an R^2 value indicating how well the cross-validated predictions of the model match the data. (The predictions and the d...
= pd.read_pickle(os.path.join(basepath, self.params['output_path'] + 'feature_groups/' + 'previous_application.pkl')) credit_bal = pd.read_pickle(os.path.join(basepath, self.params['output_path'] + 'feature_groups/' + 'credit_card_balance.pkl')) for col in bureau.select_dtypes(include=['category']).columns: bure...
pass in no Flask server or client path. if reactor_args is None: reactor_args = {} if (flask_app is None) and (client_dir is None): print('ERROR: Neither client or server are defined.') return None if do_log: # Set up logging. globalLogBeginner.beginLoggingTo([FileLogObserver(sys.stdout, lambda _: formatEvent...
"""main threadcount module.""" import json import csv from types import SimpleNamespace from collections import OrderedDict, UserList import numpy as np import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages import lmfit import mpdaf.obj import astropy.units as u from . import lines from ...
import networkx as nx from krrt.planning.strips.representation import Action, Fluent from krrt.utils import read_file def create_serial_pop(plan): pop = POP() for action in plan: pop.add_action(action) for i in range(len(plan) - 1): pop.link_actions(plan[i], plan[i+1], 'serial') return pop class POP(object)...
<gh_stars>1-10 # coding=utf-8 # Copyright 2020 The Google Research Authors. # # 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 ...
* x for x in cad_library.Vec3.zunit()]) == 0: self.orientation = [0.0, math.pi, 0.0] return # Compute the cross product of z-Axis and the given unit axis cross_product = cad_library.Vec3.zunit().crossprod(axis_unit) # Compute the unit vector of cross product -> rotation vector cross_sum = sum([x ** 2 for x ...
# Generated from /home/srix/workspace/pytamil/pytamil/தமிழ்/resources/மாத்திரை.g4 by ANTLR 4.8 # encoding: utf-8 from antlr4 import * from io import StringIO import sys if sys.version_info[1] > 5: from typing import TextIO else: from typing.io import TextIO def serializedATN(): with StringIO() as buf: buf.write("...
<gh_stars>0 power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dyn...
s.displayName: print "[Target] Gift" break else: targets.append(copy) if targets == []: pass else: for target in targets: try: cl.sendText(msg.to,"Gift Sudah Terkirim!") msg.contentType = 9 msg.contentMetadata= {'PRDTYPE': 'STICKER', 'STKVER': '1', 'MSGTPL': '1', 'STKPKGID': '1296261'} msg.to = target ...
<reponame>cons3rt/cons3rt-python-sdk """ Copyright 2020 Jackpine Technologies Corporation 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 re...
""" Miscellaneous utilities """ import os import sys import ctypes import numpy as np import pandas from ..exceptions import GMTOSError, GMTCLibError, GMTCLibNotFoundError, \ GMTInvalidInput def dataarray_to_matrix(grid): """ Transform a xarray.DataArray into a data 2D array and metadata. Use this to extract t...
<gh_stars>0 import sys import os import ctypes from ctypes import c_long, c_double, POINTER, c_int, Structure, c_char _libraries = {} dllname = ['geotrans2-32.dll', 'geotrans2-64.dll']['AMD64' in sys.version] dllname = os.path.join(os.path.dirname(__file__), dllname) # dllname = ( # r'c:\users\jaraco\projects\geotrans...
# coding: utf-8 # non standard packages required: # - mako: templating engine to create the SVG # - cairosvg: conversion to PDF import os, sys, getopt, datetime, math, re from collections import OrderedDict from mako.template import Template from mako import exceptions from mako.exceptions import RichTraceback from m...
''' Triconex Honeypot emulating arbitrary modules (PoC) date : April, 4th 2018 author : <NAME> (@adipinto) author : <NAME> author : <NAME> (@ydragoni) contact : secresearch [ @ ] nozominetworks [ . ] com ''' import sys import time import socket import struct import argparse try: import crcmod except ImportError: ...
<reponame>LGruenhaupt/Qcodes<gh_stars>100-1000 """ This module provides a class that encapsulates Alazar ATS API, :class:`AlazarATSAPI`. The class is used to expose Alazar API functions of its C library in a python-friendly way. """ from typing import Dict, Tuple, Union, Any import ctypes from ctypes import POINTER ...
sqrt(6.0)*d/3.0) vecs = np.array(len(self.traj) * [[a, b, c]]) if self.traj.unitcell_vectors: raise ValueError(f'self.traj already has a unit cell') self.traj.unitcell_vectors = vecs return self.traj def calc_maxdist(self): return maxdist(self.traj) def calc_mindist(self): xyz = self.coords vecs = self.box ...
types that cannot be converted should raise! """ # All the coordinate values should be converted to floats. station = {"id": "BW.FURT", "latitude": "A", "longitude": 2, "elevation_in_m": 3, "local_depth_in_m": 4} gen = InputFileGenerator() with pytest.raises(ValueError): gen.add_stations(station) def test_...
<gh_stars>0 from math import cos, sin, pi import numpy import random from OpenGL.GL import * import viewport LINE_SHADOW_VERTEX_SHADER_SOURCE = """ #version 460 core #define INV2PI 0.15915494309189533576888376337251436203445964574 #define UV2NDA(x) 2.0 * (x) - 1.0 layout(location = 0) uniform float invTextureH...
<gh_stars>10-100 from flask import render_template, redirect, url_for, session, flash, abort from flask_wtf import FlaskForm from wtforms import RadioField, SubmitField, FormField, BooleanField from wtforms.fields.html5 import IntegerRangeField from wtforms.validators import DataRequired from app.main.forms import Soft...
#!/usr/bin/env python import os import numpy import pyquaternion import pcl import tf2_ros import rospy import rospkg import threading import random import ctypes from PIL import Image as pil import pybullet as p import pybullet_data from pybullet_utils import gazebo_world_parser from sensor_msgs.msg import Image, Imu...
from sklearn.svm import SVR from sklearn.linear_model import LinearRegression import os import random import sys import csv import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler f...
"10425-10513"], }, "1.A.1.c.ii-2": { "title": "Gaseous Fuels", "alternative_codes": ["1.A.1.c.ii-10524", "10425-10524"], }, "1.A.1.c.ii-3": { "title": "Liquid Fuels", "alternative_codes": ["1.A.1.c.ii-10530", "10425-10530"], }, "1.A.1.c.ii-4": { "title": "Other Fossil Fuels", "alternative_codes": ["1.A.1.c....