input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
"Failed",
"Updating", "Deleting", "Creating".
:vartype provisioning_state: str or ~azure.mgmt.cdn.models.AfdProvisioningState
:ivar deployment_status: Possible values include: "NotStarted", "InProgress", "Succeeded",
"Failed".
:vartype deployment_status: str or ~azure.mgmt.cdn.models.DeploymentStatus
"""
_valid... | |
path: str
alist: int
attributeBuffer: int
result: str
def __str__(self):
rep = f'setattrlistat({self.fd}, "{self.path}", {hex(self.alist)}, {hex(self.attributeBuffer)})'
if self.result:
rep += f', {self.result}'
return rep
@dataclass
class BscNetQosGuideline:
ktraces: List
param: int
param_len: int
resul... | |
optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.create_tensorboard), "__call__"
) as call:
# De... | |
hyphens '-'. This approach may not be perfect in general, but it works for
the zhmc CLI because the original option names do not have any underscores.
Parameters:
options (dict): The click options dictionary as passed to the decorated
function by click (key: option name as changed by click, value: option
value).... | |
<reponame>jackievilladsen/dynspec
# -*- coding: utf-8 -*-
"""
plot.py: Tools for manipulating and plotting dynamic spectra, time series, etc.
This functionality is accessed by the user through the class Dynspec.
"""
from pylab import *
from numpy import *
import matplotlib.pyplot as plt
import os
from astropy.time i... | |
<gh_stars>1-10
# Copyright 2019 SAP SE
# 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 ... | |
'increment': 77,
'stepTime': 0.245965576648712, 'step': 1, 'jobName': 'OneTaper3D',
'severe': 0, 'iterations': 2, 'phase': STANDARD_PHASE, 'equilibrium': 2})
mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0,
'frame': 77, 'jobName': 'OneTaper3D'})
mdb.jobs['OneTaper3D']._Message(STATU... | |
None
self._children_name_map["tcp_small_servers"] = "tcp-small-servers"
self._children_yang_names.add("tcp-small-servers")
self.udp_small_servers = None
self._children_name_map["udp_small_servers"] = "Cisco-IOS-XR-ip-udp-cfg:udp-small-servers"
self._children_yang_names.add("Cisco-IOS-XR-ip-udp-cfg:udp-small-serve... | |
import pygame
from PIL import Image
import time
import pandas as pd
import os
import re # For string slicing stuff (used in natural sort function)
import difflib # For string matching in keywords for keyword suggestions and matching
# Center any windows opened (the map, for example)
os.environ['SDL_VIDEO_CENT... | |
import torch
from torch.utils.data import Dataset
from .collaters import *
import json
import pickle
import os
import glob
import sys
from musa.ops import *
from .utils import *
import timeit
import struct
import numpy as np
import multiprocessing as mp
from sklearn.cluster import KMeans
import copy
def read_aco_file... | |
is {0}".format(live_conn))
def _nat_setup_flows(vt, br_name, nat_spec):
# For all nat testing, flows are setup on client node only
vte = vt.allow[0]
sep = vte.sep
sut = sep.host
vif = sep.vif
setup_default_pipeline_on_all_suts(br_name)
sut.vswitch.execute(f"ovs-ofctl del-flows {br_name} table={Constants.OF_TA... | |
<reponame>ontoinsights/deep_narrative_analysis<filename>dna/help.py
# Displays various help texts in a popup window
# Called by app.py
import PySimpleGUI as sg
from utilities import encoded_logo
# Help text, Each line should be 70 chars or less
scrolled_existing = \
"Choose the 'Load Narratives From Existing Store'... | |
attribute["ExprWithAlias"]["expr"]
alias = [attribute["ExprWithAlias"]["alias"]["value"]]
if function:
if "Identifier" in function:
return {
"identifier": function["Identifier"]["value"],
"alias": alias,
}
if "CompoundIdentifier" in function:
return {
"identifier": [
".".join(
[p["value"] for p in function... | |
<gh_stars>0
from abc import ABC, abstractmethod
import torch
from torch import Tensor
from scipy.optimize import OptimizeResult
from scipy.optimize.optimize import _status_message
from .function import ScalarFunction
from .line_search import strong_wolfe
class HessianUpdateStrategy(ABC):
def __init__(self):
self.n... | |
<filename>neuro-cli/tests/unit/test_shell_completion.py
import logging
import os
import shlex
import sys
from dataclasses import replace
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from pathlib import Path
from typing import (
Any,
AsyncIterator,
Callable,
Iterable,
List,
Option... | |
<reponame>sahirsharma/Martian<filename>NASA SPACEAPPS CHALLENGE/Solution/Software part/Astronomical Data and Python Libraries/Astropy/astropy-1.1.2/astropy/io/fits/hdu/hdulist.py
# Licensed under a 3-clause BSD style license - see PYFITS.rst
from __future__ import print_function
import gzip
import os
import shutil
im... | |
self.onSaveAs(self.currfile) # may be None
def onSaveAs(self, forcefile=None):
"""
retains successful encoding name here for next save, because this
may be the first Save after New or a manual text insertion; Save
and SaveAs may both use last known encoding, per config file (it
probably should be used for... | |
default_stream_filter
self._default_file_filter_name = default_file_filter
self._default_stream_filter = _select(default_stream_filter)
self._default_string_filter = _select(default_string_filter)
default_file_filter = default_file_filter or default_stream_filter
self._default_file_filter = _select(default_file_fi... | |
request: Request instance for DeleteRecordPlan.
:type request: :class:`tencentcloud.iotvideoindustry.v20201201.models.DeleteRecordPlanRequest`
:rtype: :class:`tencentcloud.iotvideoindustry.v20201201.models.DeleteRecordPlanResponse`
"""
try:
params = request._serialize()
body = self.call("DeleteRecordPlan", param... | |
attr)
# return super().__getattr__(self, attr)
class Imaginary(Object):
def gen_name(self, name):
global _problem_compilation
if _problem_compilation:
hns = gen_hashnums(HASHNUM_DEPTH_DEFAULT)
return ' '.join([v.poodle_internal__sym_name for v in hns])
else:
return super().gen_name(name)
def __init__(self, ... | |
assert np.all(image[~bb_mask] == [0, 0, 0])
image = np.zeros_like(image)
bb = ia.BoundingBox(y1=-1, x1=-1, y2=2, x2=2, label=None)
bb_mask = np.zeros(image.shape[0:2], dtype=np.bool)
bb_mask[2, 0:3] = True
bb_mask[0:3, 2] = True
image_bb = bb.draw_on_image(image, color=[255, 255, 255], alpha=1.0, thickness=1, co... | |
+ n2)))/(8.*n1*(1 + n1)*(-1 + 2*n1)*n2*(1 + n2)*(-1 + 2*n2)),
38: lambda n1, n2: ((2 + n1 + n2)*(-3 + 2*n1 + 2*n2)*(-1 + 2*n1 + 2*n2)*(1 + 2*n1 + 2*n2))/(8.*n1*(1 + n1)*n2*(1 + n2)),
39: lambda n1, n2: -((-3 + 2*n1 + 2*n2)*(-1 + 2*n1 + 2*n2)*(-2 + 7*n1 + 7*n2))/(56.*n1*(1 + n1)*n2*(1 + n2)),
40: lambda n1, n2: ((-3 ... | |
# -*- coding: utf-8 -*-
"""
pygments.cmdline
~~~~~~~~~~~~~~~~
Command line interface.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import print_function
import sys
import getopt
from textwrap import dedent
from pygments import _... | |
if skip_select:
break
if next_node == P4_HLIR.PACKET_TOO_SHORT:
# Packet needs to be at least one byte too short
self.sym_packet.set_max_length(simplify(new_pos - 8))
break
if not skip_select:
sym_transition_key = []
for transition_key_elem in parse_state.transition_key:
if isinstance(transition_key_elem, Ty... | |
if my_val != other_val:
return False
return True
def __ne__(self, other):
return not (self == other)
all_structs.append(register_client_id_args)
register_client_id_args.thrift_spec = (
None, # 0
(1, TType.I32, 'block_id', None, None, ), # 1
(2, TType.I64, 'client_id', None, None, ), # 2
)
class register_clien... | |
# -*- coding: utf-8 -*-
"""Parser for PCAP files."""
import binascii
import operator
import socket
import dpkt
from plaso.events import time_events
from plaso.lib import errors
from plaso.lib import eventdata
from plaso.parsers import interface
from plaso.parsers import manager
__author__ = '<NAME> (<EMAIL>)'
de... | |
the frames visible.
pedantic: boolean whether to show aliasing for simple values.
If pedantic is false, simple values are replicated, rather
than, for example, having all references to 1 refer to the
same int object.
"""
Gui.__init__(self, debug)
self.pedantic = pedantic
self.withdraw()
# initially there is ... | |
request and disconnects the client from the server \
implicitly closing any subscriptions that the client has open. \
Once the stop has completed the optional callback is performed.
:type on_stopped: function or None
:param on_stopped: function to call when the connection is \
closed. This function prototype must... | |
\
\
\ / line_m
\ /
tex_2_theta[0] + r_2
/ \
/ \
\ / \
\ / \
\ / \
tex_2_theta[1] + r_1 \ line_o2
/ \
/ \
/ \
\
\
\
\ line_o1
"""
#----- theta-s
theta = self.ray_1_theta
self.arc_theta = []
self.arc_theta_pos_offset = []
self.tex_theta = []
# reflection points array
arc_origin_ary = [self.get... | |
[
['BOTSID', 'M', 3,'AN'],
['M1301', 'M', (2,4),'AN'],
['M1302', 'M', 30,'AN'],
['M1303', 'C', 1,'AN'],
['M1304', 'M', 12,'AN'],
['M1305', 'C', 15,'R'],
['M1306', 'C', (2,2),'AN'],
['M1307', 'C', 2,'AN'],
['M1308', 'C', 12,'AN'],
['M1309', 'M', (2,4),'AN'],
['M1310', 'C', (2,4),'AN'],
],
'M14': [
['BOTSID',... | |
import matplotlib.pyplot as plt
import seaborn as sb
import sys
import scipy
import scipy.signal
import matplotlib.dates as mdates
import pandas as pd
import numpy as np
import datetime
from datetime import date, timedelta
sys.path.append('/Users/hn/Documents/00_GitHub/Ag/NASA/Python_codes/')
sys.path.append('/home/hno... | |
m_flow_in = self._m_flow_in
cp_in = self._cp_in
# Dimensionless delta-circuit conductances
self._beta1 = 1./(self._Rd[0][0]*m_flow_in[0]*cp_in[0])
self._beta2 = 1./(self._Rd[1][1]*m_flow_in[0]*cp_in[0])
self._beta12 = 1./(self._Rd[0][1]*m_flow_in[0]*cp_in[0])
self._beta = 0.5*(self._beta2 - self._beta1)
# Eigen... | |
in degrees:
standard mode | logo mode
0 - east | 0 - north
90 - north | 90 - east
180 - west | 180 - south
270 - south | 270 - west
:param to_angle: the new turtle heading
"""
self._turn(to_angle - self._heading)
seth = setheading
def home(self):
"""Move turtle to the origin - coordinates (0,0) - and se... | |
sent_password = True
time.sleep(0.025)
return proc.exitstatus
except vt.TerminalException as err:
log.error(
'Failed to upload file {0!r}: {1}\n'.format(
dest_path, err
),
exc_info=True
)
# Signal an error
return 1
def smb_file(dest_path, contents, kwargs):
'''
Use smbclient to copy a file to a server... | |
<reponame>mjlshen/qontract-reconcile
import base64
import logging
import json
import os
import shutil
from datetime import datetime
from collections import defaultdict
from threading import Lock
from dataclasses import dataclass
from typing import Iterable, Mapping, Any
from python_terraform import Terraform, IsFlagg... | |
from __future__ import absolute_import, division, print_function
import warnings
import pkg_resources
import numpy as np
from numpy.linalg.linalg import LinAlgError
import theano
from theano import Op, config, tensor
from theano.scalar import bool as bool_t
from theano.gof import COp, ParamsType
from theano.gpuarray... | |
<reponame>bobh0303/fontbakery
import os
from fontbakery.profiles.universal import UNIVERSAL_PROFILE_CHECKS
from fontbakery.status import INFO, WARN, ERROR, SKIP, PASS, FAIL
from fontbakery.section import Section
from fontbakery.callable import check, disable
from fontbakery.utils import filesize_formatting
from fontba... | |
(sta - a_mean) / a_std
return _z
def trigger_onset(charfct, thres1, thres2, max_len=9e99, max_len_delete=False):
"""
Calculate trigger on and off times.
Given thres1 and thres2 calculate trigger on and off times from
characteristic function.
This method is written in pure Python and gets slow as soon as there... | |
"""
Copyright 2019 <NAME>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distribute... | |
<reponame>jborrelli98/ground-station-app
'''
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAI... | |
are stacked together so as to create a 4d filter.
# Using the same name = good idea?
filter_ref = tf.stack(kernels, axis=3, name='filter')
output = tf.nn.conv2d(_input, filter_ref, strides, padding)
return output, filter_ref
def dropout(self, _input):
"""
If the given keep_prob is not 1 AND if the graph is bein... | |
prob, _ = \
generator(example, params.train_maximum_sql_length,
sampling=params.is_sampling,
forcing=True)
if seq[-1] == EOS_TOK:
seq = seq[:-1]
prob = prob[:-1]
rewards = torch.Tensor(np.ones(len(seq))).cuda()
loss = generator.update_gan_loss(prob, rewards)
forcing_loss += loss
torch.cuda.empty_cache()
... | |
<filename>dlgr/griduniverse/experiment.py
"""The Griduniverse."""
import datetime
import flask
import gevent
import itertools
import json
import logging
import math
import random
import string
import time
import uuid
from cached_property import cached_property
from faker import Factory
from sqlalchemy import create_e... | |
def add_ui_from_string(self, buffer):
if not isinstance(buffer, _basestring):
raise TypeError('buffer must be a string')
length = len(buffer)
return Gtk.UIManager.add_ui_from_string(self, buffer, length)
def insert_action_group(self, buffer, length=-1):
return Gtk.UIManager.insert_action_group(self, buffer, le... | |
from __future__ import division
import json
import os
import shutil
import numpy as np
import torch, cv2
from random import choice
from torch.utils.data import Dataset
import json
from PIL import Image
import random
from utils.image import _palette
def all_to_onehot(masks, labels):
if len(masks.shape) == 3:
Ms = np.... | |
import telegram
import sqlite3
import function
import thread_lock
import battlebuild
import random
import air
import drawmap
import traceback
from telegram import ReplyKeyboardRemove, ReplyKeyboardMarkup
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, C... | |
# -*- coding: utf-8 -*-
from django import forms
from django.utils.safestring import mark_safe
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Field, Div, HTML
from .models import Candidate, EXPERTISE_CHOICES
from crm.models import Organization
class CandidateAddForm(forms... | |
<filename>build/management/commands/build_annotation.py
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.db import connection
from django.utils.text import slugify
from django.db import IntegrityError
from django.db import transaction
from build.management.... | |
<filename>src/biopsykit/carwatch_logs/log_data.py
"""Module providing classes and utility functions for handling log data from *CARWatch App*."""
import json
import warnings
from datetime import datetime
from typing import Dict, Optional, Sequence, Union
import numpy as np
import pandas as pd
from typing_extensions im... | |
not t.match(Tokens.DML, 'SELECT'):
raise Exception("Invalid subselect statement")
self._select(p, t)
else:
tablename = current_token.value.strip()
tablealias = current_token.get_name().strip()
if tablename == tablealias:
table_name_tokens.append(current_token)
else:
inject_table_view(current_token, tablename, ... | |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 11 21:09:02 2016
@author: alisazhila
"""
import dataset_generator as gd
import random
import quadprog as qp
import numpy as np
import cvxopt
from sklearn.svm import SVC
import scipy.optimize
#import sys
#sys.exit()
TINY_ADD = np.power(10.0, -13)
#np.testing.assert_arr... | |
"type" : {
"basetype" : "Enumeration",
"telnet" : {
"nodetype" : "namednumber",
"number" : "1"
},
"ssh" : {
"nodetype" : "namednumber",
"number" : "2"
},
"ftp" : {
"nodetype" : "namednumber",
"number" : "3"
},
"http" : {
"nodetype" : "namednumber",
"number" : "4"
},
"https" : {
"nodetype" : "namednum... | |
"""
PVSource.py
Author: <NAME>, Array Lead (2020).
Contact: <EMAIL>
Created: 11/14/20
Last Modified: 03/07/21
Description: Implementation of the PVEnvironment class.
"""
# Library Imports.
import json
import jsbeautifier
# Custom Imports.
class PVEnvironment:
"""
The PVEnvironment class is a concrete base class ... | |
pitch stab
# xxxxxx0x no yaw stab, xxxxxx1x yaw stab
returns: rslt, numpy array of strings containing the translated yawpitch values
"""
rslt = np.full(arr.shape, 'N', dtype='U2')
first_bit_chk = np.bitwise_and(arr, (1 << 0)).astype(bool)
sec_bit_chk = np.bitwise_and(arr, (1 << 1)).astype(bool)
rslt[np.interse... | |
import numpy as np
from PTSS import PtssJoint as ptssjnt
from PTSS import Ptss as ptss
from CFNS import CyFns as cfns
# define the 4th order Runge-Kutta algorithm.
class RK4:
def rk4(self, y0, dy, step):
k1 = step * dy
k2 = step * (dy + 1 / 2 * k1)
k3 = step * (dy + 1 / 2 * k2)
k4 = step * (dy + k3)
y1 = y0 + 1... | |
:param K:
:type K: int &
:rtype: Standard_Address
"""
return _TopTools.TopTools_DataMapOfIntegerListOfShape_ChangeFind1(self, *args)
def _kill_pointed(self):
"""_kill_pointed(TopTools_DataMapOfIntegerListOfShape self)"""
return _TopTools.TopTools_DataMapOfIntegerListOfShape__kill_pointed(self)
def __del__(se... | |
"""Helpers for listening to events."""
from datetime import datetime, timedelta
import functools as ft
from typing import Any, Callable, Dict, Iterable, Optional, Union, cast
import attr
from homeassistant.const import (
ATTR_NOW,
EVENT_CORE_CONFIG_UPDATE,
EVENT_STATE_CHANGED,
EVENT_TIME_CHANGED,
MATCH_ALL,
SUN... | |
<filename>interface/xbridge_rpc.py<gh_stars>0
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
import xbridge_config
from utils import xbridge_custom_exceptions
"""
port = '8888'
rpc_connection = AuthServiceProxy("http://%s:%s@127.0.0.1:41414" % ('Testuser', '<PASSWORD>'))
"""
login = xb... | |
"""Wrappers for `einops <https://einops.rocks/>`_.
The einops module is available only from ``xarray_einstats.einops`` and is not
imported when doing ``import xarray_einstats``.
To use it you need to have installed einops manually or alternatively
install this library as ``xarray-einstats[einops]`` or ``xarray-einstat... | |
'74', '90', '106', '122', '138', '154', '170', '186' ]
addCurvePieceEdgeLoops( 0.95 , edges )
edges.extend( [ '189', '191', '193', '195', '197', '199' ] )
addCurvePieceEdgeLoops( 0.05 , edges )
edges = [ '36', '37', '39', '41', '68', '80', '100', '112', '132', '144', '164',
'176', '210', '230', '258', ... | |
import copy
from command_categories import *
from util import *
from ir_utils import *
from definitions.ir.redirection import *
from definitions.ir.resource import *
## Assumption: Everything related to a DFGNode must be already expanded.
## TODO: Ensure that this is true with assertions
class DFGNode:
## U... | |
<gh_stars>0
# -*- coding: utf-8 -*-
# Copyright (c) 2020, bikbuk and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
import json
import pytz
from datetime import datetime as dt
from frappe.model.document import Document
from vet_website.vet_website.d... | |
<gh_stars>0
import argparse
import os
import random
import time
import math
import json
from functools import partial
import codecs
import zipfile
import re
from tqdm import tqdm
import sys
import io
import collections
from typing import Optional, List, Union, Dict
from dataclasses import dataclass
import numpy as np... | |
<filename>Personal_Project/personalproject/aplication/routes.py
from flask import Blueprint, render_template, url_for, flash, redirect, request, abort
from personalproject import db
from personalproject.aplication.forms import (ContaBancariaForm,
CartaoCreditoForm,
DespesaCartaoCreditoForm,
DespesaForm, ReceitaFor... | |
'1710'),
('Nish<NAME>', '1711')],
'Sreepur': [('Barmi', '1743'),
('Bashamur', '1747'),
('Boubi', '1748'),
('Kawraid', '1745'),
('Satkhamair', '1744'),
('Sreepur', '1740')],
'Sripur': [('Rajendrapur', '1741'),
('Rajendrapur Canttome', '1742')]},
'Gopalganj': {'Gopalganj Sadar': [('Barfa', '8102'),
('Chandradi... | |
self.lineEdit_pop_pTr_modelPath.setEnabled(False)
self.lineEdit_pop_pTr_modelPath.setObjectName("lineEdit_pop_pTr_modelPath")
self.horizontalLayout_4.addWidget(self.lineEdit_pop_pTr_modelPath)
self.gridLayout.addLayout(self.horizontalLayout_4, 0, 0, 1, 3)
# self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
# se... | |
from django.shortcuts import render, redirect
from django.shortcuts import render_to_response
from django.http import *
from django.template import RequestContext, loader
from django.contrib import auth
from django.core.context_processors import csrf
from django.contrib.auth.models import User
from django.contrib.auth ... | |
from __future__ import absolute_import, division, print_function
import collections
import inspect
from enum import Flag, auto
from numbers import Number
from typing import Callable, List, Optional, Text, Union, Sequence
import numpy as np
import tensorflow as tf
from odin.bay import distributions as obd
from odin.ut... | |
of the function invocations
"""
return self._result
class PipelineCommand(object):
"""
Base class for constructing program command lines
This class should be subclassed to implement the 'init'
and 'cmd' methods.
The 'init' method should do any preprocessing and
caching of arguments to be used in the 'cmd' me... | |
<reponame>Sheng-Cheng/agile_flight<filename>envtest/ros/user_code.py
#!/usr/bin/python3
from pickle import NONE
from utils import AgileCommandMode, AgileCommand
from rl_example import rl_example
from scipy.spatial.transform import Rotation as Rot # for rotation matrix representation
from numpy import linalg as LA
im... | |
Schema Component : Test valid XML
for key definition, field xpath='attribute::*' , selector contains *
"""
assert_bindings(
schema="msData/identityConstraint/idL046.xsd",
instance="msData/identityConstraint/idL046.xml",
class_name="Root",
version="1.1",
mode=mode,
save_output=save_output,
output_format=output... | |
test_eq_explicit_name(self):
x1 = Variable("x1", [1, 2, 3])
x2 = Variable("x2", [1, 2])
def f(x, y):
return x + y
r1 = NAryFunctionRelation(f, [x1, x2], name="f")
r2 = NAryFunctionRelation(f, [x1, x2], name="f")
self.assertEqual(r1, r2)
def test_eq_expression_function(self):
x1 = Variable("x1", [1, 2, 3])
... | |
from __future__ import absolute_import
import csv
import datetime
import logging
import sys
from collections import OrderedDict
from decimal import Decimal
from pathlib import Path
import click
import yaml
import yaml.resolver
from click import echo
import json
from yaml import Node
from datacube.index.index import ... | |
"""Base class for all target calculators."""
from abc import ABC, abstractmethod
from ase.units import Rydberg, Bohr, kB
import ase.io
import numpy as np
from mala.common.parameters import Parameters, ParametersTargets
from mala.common.parallelizer import printout
from mala.targets.calculation_helpers import fermi_fu... | |
return buf.raw
def randombytes(size):
buf = ctypes.create_string_buffer(size)
sodium.randombytes(buf, ctypes.c_ulonglong(size))
return buf.raw
def crypto_box_keypair():
pk = ctypes.create_string_buffer(crypto_box_PUBLICKEYBYTES)
sk = ctypes.create_string_buffer(crypto_box_SECRETKEYBYTES)
__check(sodium.crypto... | |
import os
import secrets
from PIL import Image, ImageTk
from flask import render_template, url_for, flash, redirect, request, abort
from flaskblog import app, db, bcrypt
from flaskblog.forms import RegistrationForm, LoginForm, UpdateAccountForm, PostForm
from flaskblog.models import User, Post
from flask_login i... | |
url:::fo\no:True::::]",
"[text(2,14):a:]",
"[end-setext::]",
]
expected_gfm = """<h2>a<img src="/my%20url" alt="fo\no" />a</h2>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_setext_headings_extra_a3():
"""
Test case extra A3: SetExt with inline lin... | |
config file, construct the field map
and return it. If there is neither a fixed map or user specified
mapping then raise an error.
Input parameters:
source_type: String holding name of the section in
import_config_dict that holds config details for the
source being used.
source: Iterable holding the source da... | |
from drawnow import *
from matplotlib import pyplot as plt
import data
import redo_data as rd
from numpy import mean
import random as r
fig = plt.figure()
ax1 = fig.add_subplot(461)
ax2 = fig.add_subplot(462)
ax3 = fig.add_subplot(463)
ax4 = fig.add_subplot(464)
ax5 = fig.add_subplot(465)
ax6 = fig.add_subplot(466)
ax... | |
<gh_stars>100-1000
# -*- coding: utf-8 -*-
import json
import os
import datetime
import tempfile
import shutil
import pytz
from nose.tools import eq_, ok_
from django.contrib.auth.models import User, Group, Permission
from django.conf import settings
from django.utils import timezone
from django.utils.timezone impor... | |
if len(theseKeysP) > 0: # at least one key was pressed
if "backspace" in theseKeysP:
key_resp_2.keys=key_resp_2.keys[:-1]
key_resp_2.keys.extend([key for key in theseKeysP if key != "return" and key != "backspace"])
for n, i in enumerate(key_resp_2.keys):
if i =='num_1':
key_resp_2.keys[n] = '1'
elif i =='num_... | |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------
# Filename: <filename>
# Purpose: <purpose>
# Author: <author>
# Email: <email>
#
# Copyright (C) <copyright>
# --------------------------------------------------------------------
"""
:copyright:
<copyright>
:license:
GNU ... | |
<reponame>kayosman/Do-Not-Milk-The-Milk-Man<filename>src/entitys.py<gh_stars>0
import dialoge
import random
class Entity:
def __init__(self, name, health, evil):
self.name = name
self.evil = evil
self.health = health
self._health = health
def isEvil(self):
return self.evil
def randomNumber(self, value):
r... | |
will be raised.
frequencies : array_like of float, optional
The frequencies to keep in the object, each value passed here should
exist in the freq_array.
freq_chans : array_like of int, optional
The frequency channel numbers to keep in the object.
times : array_like of float, optional
The times to keep in the ob... | |
* hours
minutes = remaining // 60
seconds = remaining - 60 * minutes
print(fmt_str.format(bundle_i0,
bundle_i0 + bundle_size - 1,
100 * (bundle_i0 + bundle_size) / N,
hours, minutes, seconds,
FPS))
# Save groups of 100 frames together
if (bundle_i0 > last_saved_frames + save_group + 1):
all_points... | |
<reponame>massongit/deep-crf
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
os.environ["CHAINER_SEED"] = "1234"
import random
import numpy as np
random.seed(1234)
np.random.seed(1234)
import chainer
from chainer import cuda
from chainer import optimizers
from chainer import serializers
import chainer.functi... | |
# -*- coding: utf-8 -
#
# This file is part of couchdbkit released under the MIT license.
# See the NOTICE for more information.
""" properties used by Document object """
import decimal
import datetime
import re
import time
try:
from collections import MutableSet, Iterable
def is_iterable(c):
return isinstance(... | |
<reponame>DEVESHTARASIA/tensorflow<filename>tensorflow/contrib/bayesflow/python/ops/csiszar_divergence_impl.py<gh_stars>100-1000
# Copyright 2017 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 Lic... | |
6032 19728844 6032
19729379 6032 19730381 6032
19757045 9423 19758205 9423
19815622 17846 19816907 17846
19843858 6017 19845085 6017
19870553 22754 19871717 22754
19904035 97 19904908 97
19968539 14483 19969543 14483
19968539 14483 19969603 14483
19968539 14483 19969645 14483
19993679 56 19994657 56
20006661... | |
#! python3
"""
@created: 2020-10-11 11:10:00
@author: <NAME> ( pyGuru )
Moonlight PDF Reader
-------------------------------------------------------------------------------
Dependencies:
PyMuPDF v1.17.7+
PyMuPDF can be installed by : pip install pymupdf
-------------------------------------------------... | |
import os
import re
import io
import hashlib
import mutagen
import zipfile
import datetime
from dynamic_preferences.registries import global_preferences_registry
from django.db import models, transaction
from django.db.utils import IntegrityError
from django.utils import timezone
from django.db.models import Q
from ... | |
#!/usr/bin/env python
from __future__ import print_function
import logging
import json
from pprint import pformat
from collections import defaultdict
from apiclient.errors import HttpError
from errors import BadConfigError
from copy import deepcopy
import time
MAX_ACTIONS_PER_BATCH = 950
ITERATION_LIMIT = 100
clas... | |
<filename>tools/Vitis-AI-Quantizer/vai_q_pytorch/pytorch_binding/pytorch_nndct/export/op_descriptor.py
#
# Copyright 2019 Xilinx 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
#
# htt... | |
return (
X.groupby(group_colnames, as_index=False)
.apply(
lambda d: pd.DataFrame(
self.estimators_.get(d.name, self.fallback_).predict(
d[self.value_colnames_]
),
index=d.index,
)
)
.values.squeeze()
)
except AttributeError:
# Handle new groups
culprits = set(X[self.group_colnames_].agg(func=tuple, axis=... | |
a weight (float) to apply to the model's loss for the samples
from this class during training.
This can be useful to tell the model to "pay more attention" to
samples from an under-represented class.
reset_metrics: If `True`, the metrics returned will be only for this
batch. If `False`, the metrics will be statefu... | |
<gh_stars>1-10
# Copyright 2021 Curtin University
#
# 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 agree... | |
model.add_reactions([reaction])
print(reaction.name + ": " + str(reaction.check_mass_balance()))
# h2o_SFOc + ppi_SFOc -> h_SFOc + 2.0 pi_SFOc
reaction = Reaction('SFO_PPA')
reaction.name = 'Inorganic diphosphatase'
reaction.subsystem = 'AMP Conversion'
reaction.lower_bound = 0. # This is the default
reaction... | |
value
logger.debug(f'| FTDI device, port {port}: Set read latency timer')
self.device.ctrl_transfer(bmRequestType = usb.util.build_request_type(direction = usb.util.CTRL_OUT, type = usb.util.CTRL_TYPE_VENDOR, recipient = usb.util.CTRL_RECIPIENT_DEVICE),
bRequest = CONTROL_REQUESTS['set_latency_timer'],
wValue = 1,
... | |
pd.DataFrame(pctls, index=[0])
def parse_hist(rtypes, exps, clients=[], dt='client-end-to-end'):
if not clients:
print('No clients given')
return {}
hists = {t: {exp: {dt : None} for exp in exps} for t in rtypes}
hists['all'] = {exp: {dt: None} for exp in exps}
for exp in exps:
wl = exp.split('_')[2].split('.'... | |
not in set(cached_war.attacks))
else:
new_attacks = war.attacks
for attack in new_attacks:
await callback(attack, war)
return _ValidateEvent.shortcut_register(wrapped, tags, custom_class, retry_interval, WarEvents.event_type)
@_ValidateEvent
class ClientEvents:
"""Class that defines all valid client/misc even... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.