input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: medical.py
# Author: <NAME> <<EMAIL>>
import csv
import itertools
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
warnings.simplefilter("ignore", category=PendingDeprecationWarning)
import os
import sys
import six
import random
import th... | |
<reponame>hadassa2807/QuantumGraphs
"""
This file presents the quantum graph class.
"""
# Needed libraries:
import inspect
import os
import sys
import importlib
import numpy as np
import math
import cmath
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from mpl_toolkits.mplot3d import Ax... | |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
##############################################################################
"""Functions for evaluating results computed... | |
<filename>cadee/qscripts/q_analysemaps.py
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# MIT License
#
# Copyright (c) 2016 <NAME> <<EMAIL>>
#
# 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... | |
the type of observation.
Odd number place the PSF on the center of the pixel,
whereas an even number centers it on the "crosshairs."
oversample : int
Factor to oversample during WebbPSF calculations.
Default 2 for coronagraphy and 4 otherwise.
include_si_wfe : bool
Include SI WFE measurements? Default=True.
inc... | |
import os
import sys
from pathlib import Path
from typing import Type
import numpy as np
from qtpy.QtCore import QByteArray, QEvent, Qt
from qtpy.QtGui import QIcon, QKeyEvent, QKeySequence, QResizeEvent
from qtpy.QtWidgets import (
QCheckBox,
QComboBox,
QGridLayout,
QHBoxLayout,
QInputDialog,
QLabel,
QMessageB... | |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import logging
import unittest
from datetime import date
from sqlalchemy import create_engine, select, and_
from src.scripts.data_loader import DataLoader, DocumentClass, DocumentField
logging.basicConfig( format='%(asctime)s %(levelname)s %(name)s %(message)s', level=lo... | |
<gh_stars>10-100
from torch.utils.data import Dataset, DataLoader, Subset
from torch.utils.data.dataloader import default_collate
from torch.utils.data.sampler import Sampler
import torch
import torch.nn as nn
import torch.nn.functional as F
from base import BaseDataLoader
import pickle
import numpy as np
import json
i... | |
the "SiteCode"/"IAGA_code" identifier
ds2 = ds2.set_index({"Site": codevar})
ds2 = ds2.rename({"Site": codevar})
return ds2
def make_pandas_DataFrame_from_csv(csv_filename):
"""Load a csv file into a pandas.DataFrame
Set the Timestamp as a datetime index.
Args:
csv_filename (str)
Returns:
pandas.DataFrame... | |
# -*- coding: utf-8 -*-
#
# qtUC - pyUC with a QT interface
# Based on the original pyUC code, modified for QT5 use
# <NAME> - VK3VW - <EMAIL>
#
# pyUC ("puck")
# Copyright (C) 2014, 2015, 2016, 2019, 2020, 2021 N4IRR
#
# This software is for use on amateur radio networks only, it is to be used
# for educational purpos... | |
MultiValues(offset_to_values={0: {top}})
result: Optional[MultiValues] = None
for addr in addrs_v:
if not isinstance(addr, claripy.ast.Base):
continue
if addr.concrete:
# a concrete address
concrete_addr: int = addr._model_concrete.value
try:
vs: MultiValues = self.state.memory_definitions.load(concrete_addr,... | |
thread to repeatedly record phrases from ``source`` (an ``AudioSource`` instance) into an ``AudioData`` instance and call ``callback`` with that ``AudioData`` instance as soon as each phrase are detected.
Returns a function object that, when called, requests that the background listener thread stop, and waits until it... | |
'Candidate Matches for Body %s',
'Canned Fish': 'Canned Fish',
'Cannot be empty': 'Cannot be empty',
'Cannot disable your own account!': 'Cannot disable your own account!',
'Capacity (Max Persons)': 'Capacity (Max Persons)',
'Capture Information on Disaster Victim groups (Tourists, Passengers, Families, etc.)': 'Captur... | |
<gh_stars>0
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemi... | |
<filename>BlendNet/providers/aws/__init__.py
'''Amazon Web Services
Provide API access to allocate required resources in AWS
Dependencies: aws cli v2 installed and configured auth
Help: https://github.com/state-of-the-art/BlendNet/wiki/HOWTO:-Setup-provider:-Amazon-Web-Services-(AWS)
'''
__all__ = [
'Processor',
'Ma... | |
# This converter has code borrowed from here:
# https://codegolf.stackexchange.com/questions/42217/paint-by-numbers
import random
import time
from collections import defaultdict
from argparse import ArgumentParser
from pathlib import Path
from PIL import Image
if __name__ == '__main__':
root_path = Path("converter... | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
# python imports
import sys
import struct
from enum import Enum
PY3 = sys.version_info > (3,)
class EColor(Enum):
White = 0
Red = 3
Green = 4
Blue = -2
Black = -1
class Parent(object):
@staticmethod
def name():
return 'Parent'
def __init__(self, first_name=None,... | |
args.ssid = ssid
args.anchor = anchor
args.status = status
args.enter_date = enter_date
args.stuff_name = stuff_name
args.supplier_name = supplier_name
args.vichele_number = vichele_number
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_get_company_vichele_info(self):... | |
continue
elif tok not in self.operators_flow:
tokens[i] = self.buildRule(current_col,current_opr,tok)
i+=1
# return the single rule of a meta rule of all rules
if len(tokens) == 1:
return tokens[0]
return self.operators_flow_join( tokens )
def addMeta(self, colid, tok, value, top):
""" meta options control s... | |
<reponame>jay-johnson/spylunking
"""
Including a handler derived from the original repository:
https://github.com/zach-taylor/splunk_handler
This version was built to fix issues seen
with multiple Celery worker processes.
Available environment variables:
::
export SPLUNK_HOST="<splunk host>"
export SPLUNK_PORT="<... | |
'\n*Created* » `%02d/%02d/%d'%(Day, Month, Year) + '`' +
'\n*Size* » `' + FileSize(os.getcwd() + '\\' + File) + '`',
parse_mode='Markdown')
os.remove(os.getcwd() + '\\' + File)
except:
try:
Created = os.path.getctime(os.getcwd() + '\\' + File)
Year, Month, Day, Hour, Minute, Second=localtime(Created)[:-3]
Fo... | |
from Events import handler
from RiseAndFall import *
from RFCUtils import *
from Core import *
from Locations import *
dRelocatedCapitals = CivDict({
iPhoenicia : tCarthage,
iMongols : tBeijing,
iOttomans : tConstantinople
})
dCapitalInfrastructure = CivDict({
iPhoenicia : (3, [], []),
iByzantium : (5, [iBarrac... | |
to evaluate.
:param env: The gym environment or ``VecEnv`` environment.
:param n_eval_episodes: Number of episode to evaluate the agent
:param deterministic: Whether to use deterministic or stochastic actions
:param render: Whether to render the environment or not
:param callback: callback function to do additiona... | |
import nipype.interfaces.fsl as fsl
import nipype.pipeline.engine as pe
import nipype.interfaces.utility as util
from nipype.interfaces.afni import preprocess
from CPAC.registration import create_nonlinear_register, \
create_register_func_to_anat, \
create_bbregister_func_to_anat, \
create_wf_calculate_ants_warp, \... | |
<reponame>samplchallenges/SAMPL7<filename>protein_ligand/Analysis/Scripts/pkganalysis/RMSD_calculator.py<gh_stars>10-100
#!/usr/bin/env python
__author__ = "<NAME>"
__email__ = "<EMAIL>"
import shutil
import glob
import pickle
import logging
import sys
import os
import time
import subprocess
import argparse
def mcs(r... | |
"""
Define the models used by the redistricting app.
The classes in redistricting.models define the data models used in the
application. Each class relates to one table in the database; foreign key
fields may define a second, intermediate table to map the records to one
another.
This file is part of The Public Mappin... | |
<gh_stars>0
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from derived_object_msgs/ObjectArray.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import geometry_msgs.msg
import derived_object_msgs.msg
import shape_msgs.... | |
<filename>mem_mem/avgblk.py
import pandas as pd
import numpy as np
from math import *
import copy # deep copy objects
from model_param import *
#------------------------------------------------------------------------------
# Figure out when to launch another block for current kernel
#--------------------------------... | |
<reponame>oasys-esrf-kit/OASYS1-ESRF-Extensions
import os, sys
import numpy
import scipy.constants as codata
from syned.storage_ring.magnetic_structures.undulator import Undulator
from syned.storage_ring.magnetic_structures import insertion_device
from PyQt5.QtGui import QPalette, QColor, QFont
from PyQt5.QtWidgets... | |
import copy
import datetime
import json
import logging
import numbers
import re
from typing import Any, List, Mapping, Optional, Set, Tuple, Union
import datasketches
import jsonschema
import numpy as np
import pandas as pd
from datasketches import theta_a_not_b, update_theta_sketch
from dateutil.parser import parse
f... | |
"ja_JP": "メルサ",
"ko_KR": "메르사",
"pl_PL": "Mersa",
"pt_BR": "Mersa",
"ru_RU": "Мэрса"
},
"MESEMBRIA": {
"de_DE": "Mesembria",
"es_ES": "Mesembria",
"fr_FR": "Mésembria",
"it_IT": "Mesembria",
"ja_JP": "メセンブリア",
"ko_KR": "메셈브리아",
"pl_PL": "Mesembria",
"pt_BR": "Mesembria",
"ru_RU": "Месембрия"
},
"METHON... | |
# Enter a parse tree produced by SystemVerilogParser#list_of_cross_items.
def enterList_of_cross_items(self, ctx:SystemVerilogParser.List_of_cross_itemsContext):
pass
# Exit a parse tree produced by SystemVerilogParser#list_of_cross_items.
def exitList_of_cross_items(self, ctx:SystemVerilogParser.List_of_cros... | |
<gh_stars>10-100
import unittest
import warnings
from mtgtools import MtgDB
from mtgtools.PCardList import PCardList
from mtgtools.PSetList import PSetList
tool = MtgDB.MtgDB("testdb.fs")
tool.scryfall_update()
cards = tool.root.scryfall_cards
sets = tool.root.scryfall_sets
basic_lands = 3 * cards.where_exactly(nam... | |
from hachoir.field import (MissingField, BasicFieldSet, Field, ParserError,
createRawField, createNullField, createPaddingField, FakeArray)
from hachoir.core.dict import Dict, UniqKeyError
from hachoir.core.tools import lowerBound, makeUnicode
import hachoir.core.config as config
class GenericFieldSet(BasicFieldSet)... | |
from warnings import warn
import numpy
import cupy
from cupy.cuda import cublas
from cupy.cuda import cusolver
from cupy.cuda import device
from cupy.linalg import _util
def lu_factor(a, overwrite_a=False, check_finite=True):
"""LU decomposition.
Decompose a given two-dimensional square matrix into ``P * L * U``... | |
Load the reduced data from reduced_data/.
Parameters
----------
suffix: str
The suffix added to the file name (the nominal is dtf.joblib)
Returns
-------
dtf: pandas DataFrames of the reduced data
'''
if suffix != '':
if not suffix.startswith('_'):
suffix = '_{}'.format(suffix)
data_file_name = Path('re... | |
Args:
input_shape: shape of the input data
grab_after_block: list of floats specifying what fraction of the channels
should exit the network after each glow block.
Returns:
blockwise_splits: the number of channels left, taken, and passed over for
each glow block.
"""
blockwise_splits = []
ngrab, nleave, npass... | |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | |
<gh_stars>1-10
# Copyright (c) 2012 OpenStack Foundation.
# 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 requi... | |
# Tetromino for Idiots, by <NAME> <EMAIL>
# (Pygame) Tetris, but... simpler.
import random, time, pygame, sys
from pygame.locals import *
FPS = 25
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
BOXSIZE = 20
BOARDWIDTH = 10
BOARDHEIGHT = 20
BLANK = '.'
MOVESIDEWAYSFREQ = 0.15
MOVEDOWNFREQ = 0.1
XMARGIN = int((WINDOWWIDTH - ... | |
<gh_stars>0
from veroviz._common import *
from veroviz._validation import valCreateLeaflet
from veroviz._validation import valAddLeafletCircle
from veroviz._validation import valAddLeafletMarker
from veroviz._validation import valAddLeafletPolygon
from veroviz._validation import valAddLeafletPolyline
from veroviz._vali... | |
from __future__ import annotations
from enum import Enum
import logging
import copy
log = logging.getLogger(__name__)
class TagType(Enum):
REQUIRE = 2
PREFER = 1
ACCEPT = 0
REJECT = -1
def __int__(self):
return self.value
class Tag:
def __init__(self, name, value, tag_type: Enum):
self.name = name
sel... | |
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import brenth, root, brentq, bisect
from scipy.constants import c, pi
from scipy.special import jv, kv, jvp, kvp
from scipy.interpolate import interp1d
from scipy.integrate import simps
import sys
import warnings
from pprint import pprint
from math... | |
db.update_user_current(
content["email"], content["image_id"])
image = db.find_image(
content["image_id"], content["email"])
if not image:
return error_handler(
400, "Image does not exist", "ValueError")
image = db.image_to_json(image)
return jsonify(image)
@app.route("/api/process/confirm", methods=["POST"])... | |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, io, traceback, time, json, copy, math
import logging
from calendar import timegm
import datetime as dt
from datetime import timedelta
sys.path.append('../stakingsvc/')
from django.contrib.auth.models import User
from django.test import TestCase, TransactionTestCas... | |
# -*- coding: utf-8 -*-
"""
This module contains the base classes for generating re-usable device classes.
The Device class
----------------
The `Device` class is an interface to generate specific devices.
In `samplemaker` a device is the combination of drawing commands that generate
a specific pattern which is typic... | |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
sys.path.append(r'D:\DeepLearning\Kaggle\Datahandling')
import utils_for_datasets
import glob
import numpy as np
import cv2
import re
import os.path
import scipy
import time
from skimage.measure import label
import skimage.... | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from backpack import extensions
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.autograd as autograd
from torch.autograd import Variable
import random
from statistics import mean
import math
import copy
import numpy... | |
'''
AUTHORS: <NAME> and <NAME>
DATE: March 22, 2019
COPYRIGHT MARCH 22, 2019 <NAME> AND <NAME>
'''
from __future__ import print_function
'''
This module should be organized as follows:
Main function:
chi_estimate() = returns chi_n, chi_b
- calls:
wealth.get_wealth_data() - returns data moments on wealth distribut... | |
<filename>assignment_03_regularization.py<gh_stars>1-10
"""
Udacity Deep Learning course by Google.
Assignment #03: various regularization techniques.
"""
import os
import sys
import time
import logging
import argparse
from os.path import join
import numpy as np
import tensorflow as tf
from tensorflow.contrib.data... | |
<gh_stars>0
# -*- coding: iso-8859-15 -*-
#
# Copyright 2017 Mycroft AI 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... | |
= Constraint(expr= m.x965 == 0)
m.c1442 = Constraint(expr= m.x980 == 0)
m.c1443 = Constraint(expr= m.x981 == 0)
m.c1444 = Constraint(expr= m.x720 - m.x962 - m.x964 == 0)
m.c1445 = Constraint(expr= m.x721 - m.x963 - m.x965 == 0)
m.c1446 = Constraint(expr= m.x730 - m.x978 - m.x980 == 0)
m.c1447 = Constraint(expr= m... | |
slider.
digital_tx_level = 20
## HiQSDR_BandDict IO Bus, dict
# This sets the preselect (4 bits) on the X1 connector.
HiQSDR_BandDict = {
'160':1, '80':2, '40':3, '30':4, '20':5, '15':6, '17':7,
'12':8, '10':9, '6':10, '500k':11, '137k':12 }
## cw_delay CW Delay, integer
# This is the delay for CW from 0 to 255.
c... | |
electrostatic_potential
Average electrostatic potential at each atomic position in order
of the atoms in POSCAR.
..attribute: final_energy_contribs
Individual contributions to the total final energy as a dictionary.
Include contirbutions from keys, e.g.:
{'DENC': -505778.5184347, 'EATOM': 15561.06492564, 'EBAN... | |
<gh_stars>0
# Copyright 2016 Canonical Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | |
<filename>tests/python/unittest/test_gluon_probability_v1.py<gh_stars>1-10
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to y... | |
y.
delta: Backprop amount for this Op.
*args: The args of this Op.
"""
pass
@property
def shape(self):
"""
This is required for parameter initializers in legacy neon code. It
expects layers to implement a shape that it can use to pass through
layers.
Returns: self.axes
"""
return self.axes
def shape_di... | |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2007 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions o... | |
replace_path = ensure_posix_path(pak_path)
try:
return replace_path.split(context.config.game_directory_name + '/')[1]
except:
return replace_path
def _add_pak_to_manifest(context, pak_path, manifest_path, manifest, platform_name):
paks_list = _get_paks_list(context, manifest)
potential_pak_file_entry_path = _g... | |
'command'):
self.known_programs.add(run.command)
self.passes.append(p)
self.passes_awaiting_requeue.append(p)
self.passes_by_name[p.name] = p
return p
def shrink_pass(self, name):
if hasattr(Shrinker, name) and name not in self.passes_by_name:
self.add_new_pass(name, classification=PassClassification.SPECIAL)
... | |
# encoding: utf-8
import pytest
from collections import defaultdict
import datetime
import json
import logging
import re
import time
from psycopg2.extras import NumericRange
from ..testing import (
DatabaseTest,
)
from elasticsearch_dsl import Q
from elasticsearch_dsl.function import (
ScriptScore,
RandomScore,
)
... | |
#!/usr/bin/env python
# coding: utf-8
# <img style="float: left;padding: 1.3em" src="https://indico.in2p3.fr/event/18313/logo-786578160.png">
#
# # Gravitational Wave Open Data Workshop #3
#
#
# ## Tutorial 2.1 PyCBC Tutorial, An introduction to matched-filtering
#
# We will be using the [PyCBC](http://github.com... | |
0, 0, 0, 0],
[1109, 0.617493, 0, 9999, -9999, 1.0, 100, 1, 0.77821, 0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1110, 1.394187, 0, 9999, -9999, 1.0, 100, 1, 1.654557, 0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1111, 40.889352, 0, 9999, -9999, 1.0, 100, 1, 89.637993, 0.0, 0, 0, 0, 0, 0, 0, 0... | |
# Taken from the Lasagne project: http://lasagne.readthedocs.io/en/latest/
# License:
# The MIT License (MIT)
# Copyright (c) 2014-2015 Lasagne contributors
# Lasagne uses a shared copyright model: each contributor holds copyright over
# their contributions to Lasagne. The project versioning records all such
# contri... | |
" + country + "\n")
f3.write("Input Interested Category from User: ")
for key , value in original_input.items():
f3.write(key + ":" +str(value) +",")
f3.write("\nMatched Interested Category: \n")
for key , value in all_interest.items():
f3.write(key + ":" +str(value) +",")
f3.write("\n \n")
f3.write("Top Ranki... | |
import warnings
import astropy.units as u
import numpy as np
import pytest
from numpy.testing import assert_allclose
from einsteinpy.metric import Schwarzschild, Kerr, KerrNewman
from einsteinpy.coordinates import CartesianConversion
from einsteinpy.coordinates.utils import four_position, stacked_vec
from einsteinpy.... | |
train, test)
statement_url = self.host + '/sessions' + '/' + str(livy_id) + '/statements'
headers = {'Content-Type': 'application/json'}
data = {"code": code}
r = requests.post(statement_url, data=json.dumps(data), headers=headers)
if str(r.status_code) == '201' or str(r.status_code) == '200':
self.ret_message['... | |
= input("Apakah anda yakin ingin menghapus " + gadget[urutan][1] + " (Y/N)? ")
# Validasi jawaban
while not validasiYN(jawaban):
jawaban = input("Apakah anda yakin ingin menghapus " + gadget[urutan][1] + " (Y/N)? ")
if jawaban == 'Y':
gadget.pop(urutan)
print()
print("Item telah berhasil dihapus dari databas... | |
pl.gca().xaxis.set_visible(False)
pl.ylabel('colour index')
if horizontal:
cbar = pl.colorbar(orientation='horizontal', ticks = colour_index_ticks)
cbar.ax.set_xticklabels(ticks*scale_factor)
else:
cbar = pl.colorbar(ticks = colour_index_ticks)
cbar.ax.set_yticklabels(ticks*scale_factor)
cbar.solids.set_edgeco... | |
<reponame>jhaapako/tcf
#! /usr/bin/python3
#
# Copyright (c) 2017 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
#
"""
Power on or off the target or any its power rail components
-----------------------------------------------------------
This module implements the client side API for controlling the power'... | |
handle_three_day_forecast(self, message):
try:
report = self.__initialize_report(message)
self.report_threeday_forecast(report)
except HTTPError as e:
self.__api_error(e)
except Exception as e:
LOG.exception("Error: {0}".format(e))
# Handle: What is the weather forecast?
@intent_handler(IntentBuilder("").requ... | |
if the thread has been requested to terminate or not.
"""
lock = QReadLocker(self._lock)
return self._teminationFlag
#---------------------------------------------
def fps(self):
"""
Gets the Frame Rate of the video currently opened.
Returns
-------
fps: int
Value of the Frame Rate (in frames per second) o... | |
import collections
def inv(n, q):
"""div on PN modulo a/b mod q as a * inv(b, q) mod q
>>> assert n * inv(n, q) % q == 1
"""
# n*inv % q = 1 => n*inv = q*m + 1 => n*inv + q*-m = 1
# => egcd(n, q) = (inv, -m, 1) => inv = egcd(n, q)[0] (mod q)
return egcd(n, q)[0] % q
#[ref] naive implementation
#for i in range... | |
from dataclasses import dataclass
from typing import ClassVar, Dict, List, Optional
import resotolib.logger
from resotolib.baseresources import (
BaseAccount,
BaseDatabase,
BaseInstance,
BaseIPAddress,
BaseLoadBalancer,
BaseNetwork,
BaseRegion,
BaseResource,
BaseSnapshot,
BaseVolume,
InstanceStatus,
Volume... | |
concentration, rho_f,
phi, diffusivity, l_disp, t_disp,
solute_source,
specific_storage,
k_tensor, k_vector,
dispersion_tensor,
viscosity,
gamma, alpha,
fluid_source,
rho_f_0,
specified_pressure_bnd,
specified_pressure,
specified_concentration_bnd,
specified_concentration,
specified_concentration_rho_f,
... | |
<reponame>MondoAurora/pydust
import json
import os
import yaml
import traceback
import inspect
import deepdiff
from enum import Enum
from collections import namedtuple
from datetime import datetime
from dust import Datatypes, ValueTypes, Operation, MetaProps, FieldProps, Committed
from importlib import import_module
i... | |
"""Support for the Philips Hue lights."""
from __future__ import annotations
from datetime import timedelta
from functools import partial
import logging
import random
import aiohue
import async_timeout
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP,
ATTR_EFFECT,
ATTR_FLASH,
ATTR_H... | |
import torch
import torch.nn as nn
from torchvision.datasets.vision import VisionDataset
from PIL import Image
import os, sys, math
import os.path
import torch
import json
import torch.utils.model_zoo as model_zoo
from Yolo_v2_pytorch.src.utils import *
from Yolo_v2_pytorch.src.yolo_net import Yolo
from Yolo_v2_pytorc... | |
advanced_end_game_piece_score(piece_type, position, color):
if color == chess.WHITE:
if piece_type == chess.PAWN:
# pawn score at the given position based on the modifier + the value of the piece
return end_game_white_pawn_modifier[position] + 10
elif piece_type == chess.KNIGHT:
# pawn score at the given position... | |
in params:
query_params.append(('offset', params['offset'])) # noqa: E501
if 'limit' in params:
query_params.append(('limit', params['limit'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_hea... | |
<reponame>rashley-iqt/network-tools
"""
Plugin that takes pcap files and outputs stats
Created on 1 November 2019
@author: <NAME>
"""
from datetime import datetime
import json
import os
import shlex
import subprocess
import sys
import pika
from enchant.tokenize import get_tokenizer
from scapy.all import *
def str... | |
which will be killed by VBoxService on the
# guest because it ran out of execution time (5 seconds).
if fRc:
try:
curProc = oGuestSession.processCreate(sImage, [sImage,] if self.oTstDrv.fpApiVer >= 5.0 else [], \
[], [], 5 * 1000);
reporter.log('Waiting for process 2 being started ...');
waitRes = curProc.waitFo... | |
= pcheck(params, 'TELLUP_TRANS_SIGLIM', 'trans_siglim', kwargs,
func_name)
force_airmass = pcheck(params, 'TELLUP_FORCE_AIRMASS', 'force_airmass',
kwargs, func_name)
others_bounds = pcheck(params, 'TELLUP_OTHER_BOUNDS', 'others_bounds',
kwargs, func_name, mapf='list', dtype=float)
water_bounds = pcheck(params, 'T... | |
# coding: utf-8
"""
Memsource REST API
Welcome to Memsource's API documentation. To view our legacy APIs please [visit our documentation](https://wiki.memsource.com/wiki/Memsource_API) and for more information about our new APIs, [visit our blog](https://www.memsource.com/blog/2017/10/24/introducing-rest-apis-qa-wi... | |
import logging
import time
from typing import Dict, Callable, Union
import pandas as pd
import json
import os
import gzip
from google.protobuf.json_format import _Printer
from typing.io import IO
from .utils.json_encoder import CarballJsonEncoder
script_path = os.path.abspath(__file__)
with open(os.path.join(os.pat... | |
<filename>utils/models.py
from __future__ import (absolute_import, division,
print_function, unicode_literals)
import numpy as np
from enterprise.signals import parameter
from enterprise.signals import selections
from enterprise.signals import signal_base
from enterprise.signals import white_signals
from enterprise.s... | |
= 0
for edge in edges_in:
u = edge.child
v = edge.parent
parent[u] = v
branch_length[u] = time[v] - time[u]
while v != -1:
update_result(window_index, v, t_left)
count[v] += count[u]
v = parent[v]
# Update the windows
while window_index < num_windows and windows[window_index + 1] <= t_right:
w_right = win... | |
# Lint as: python2, python3
# Copyright 2020 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or a... | |
<filename>pyatv/interface.py<gh_stars>0
"""Public interface exposed by library.
This module contains all the interfaces that represents a generic Apple TV device and
all its features.
"""
import re
import inspect
import hashlib
from typing import (
Any,
Dict,
Optional,
NamedTuple,
Callable,
TypeVar,
Tuple,
Un... | |
"iso2": "NG",
"admin_name": "Edo",
"capital": "minor",
"population": "",
"population_proper": ""
},
{
"city": "Onueke",
"lat": "6.1554",
"lng": "8.0374",
"country": "Nigeria",
"iso2": "NG",
"admin_name": "Ebonyi",
"capital": "minor",
"population": "",
"population_proper": ""
},
{
"city... | |
<filename>elaspic/elaspic_database.py
import datetime
import logging
import os
import os.path as op
import shlex
import shutil
import subprocess
from contextlib import contextmanager
import pandas as pd
import six
import sqlalchemy as sa
from elaspic import conf, errors, helper
from elaspic.elaspic_database_tables im... | |
<filename>tests/bugs/core_2006_test.py
#coding:utf-8
#
# id: bugs.core_2006
# title: SUBSTRING with regular expression (SIMILAR TO) capability
# decription:
# tracker_id: CORE-2006
# min_versions: ['3.0']
# versions: 3.0
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
# version: 3.0
#... | |
to complain that original conf collides - bad path?
return make_move(default_conf, hpn_end_conf) # Default config is the mode of a belief state? Closer to the actual value
elif action == 'move_no_base':
start_conf, end_conf = args
hpn_start_conf = hpn_from_or_conf(default_conf, or_robot, start_conf)
hpn_end_conf =... | |
+ .5 * c / segs_tc
v = .5 + .5 * s * (-1. if inverted else 1.) / segs_tc
if tex_size:
u = (u - .5) * 2. * radius_h / tex_size[0] + .5
v = (v - .5) * 2. * radius_h / tex_size[1] + .5
if mat:
u, v = mat.xform_point(Point2(u, v))
else:
u = v = 0.
vert = {
"pos": (x, y, z),
"normal": normal,... | |
mode = request.GET.get("mode", None)
if mode:
# Store the mode passed in the URL on the session to remember for the next report
request.session["mode"] = mode
else:
# Pick up the mode from the session
mode = request.session.get("mode", "graph")
is_popup = "_popup" in request.GET
sidx, sord = cls.getSortName(req... | |
<filename>mapel/main/objects/Experiment.py
#!/usr/bin/env python
import csv
import itertools
import logging
import math
import os
import warnings
from abc import ABCMeta, abstractmethod
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
from scipy.stats import stats
from mapel.main.embedding.kam... | |
<reponame>DakaraProject/dakara-base
"""HTTP client helper module.
This module provides the HTTP client class `HTTPClient`, built on the requests
library. The class is designed to be used with an API which communicates with
JSON messages. It is pretty straightforward to use:
>>> config = {
... "url": "http://www.examp... | |
import argparse
import sys
from util.enum_util import PackageManagerEnum, LanguageEnum, DistanceAlgorithmEnum, TraceTypeEnum, DataTypeEnum
def parse_args(argv):
parser = argparse.ArgumentParser(prog="maloss", description="Parse arguments")
subparsers = parser.add_subparsers(help='Command (e.g. crawl )', dest='cmd'... | |
class="table2">'
award_cat_id = record[0][AWARD_CAT_ID]
award_cat_name = record[0][AWARD_CAT_NAME]
print '<td>%s</td>' % ISFDBLink('award_category.cgi', award_cat_id, award_cat_name)
print '</tr>'
record = result.fetch_row()
bgcolor ^= 1
print '</table>'
else:
print '<h3>No empty Award Categories found</h3>'... | |
# -*- coding: utf-8 -*-
# -*- coding: utf8 -*-
"""Autogenerated file - DO NOT EDIT
If you spot a bug, please report it on the mailing list and/or change the generator."""
import os
from ...base import (CommandLine, CommandLineInputSpec, SEMLikeCommandLine,
TraitedSpec, File, Directory, traits, isdefined,
InputMulti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.