input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.2.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# <div style='background-image: url("../../../share/images/header.svg") ; padding: 0px ; background... | |
<filename>models/official/efficientnet/main.py
# Copyright 2019 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... | |
<gh_stars>10-100
#! /usr/bin/env python3
##MSVenom Basic Payloads
import os
import importlib
from importlib import util
spec = importlib.util.find_spec('.subserv', package='lib')
m = spec.loader.load_module()
customfolder = m.loc + "/aMALgamation/current/VenomCustom/"
if not os.path.exists(customfolder):
os.makedir... | |
<filename>tests/integration/test_target_snowflake.py
import datetime
import gzip
import json
import tempfile
import unittest
import mock
import os
import botocore
import boto3
import itertools
import target_snowflake
from target_snowflake import RecordValidationException
from target_snowflake.db_sync import DbSync
fro... | |
holding the dataset files
filename = os.path.basename(str(filename))
# see the param_grid at the bottom of this file for examples
metadata_grid[filename] = {
'dataset': dataset,
'X': X,
'y': y,
'y_train': y_train,
'y_test': y_test,
'X_train': X_train,
'X_test': X_test,
'header': head,
'X_header': X_header,
... | |
<gh_stars>10-100
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
db.rename_column(u'public_project_siteconfig', 'desc_about', 'about_text')
db.rename_column(u'public_project... | |
<reponame>cseelye/sfauto<filename>libsf/__init__.py<gh_stars>0
#!/usr/bin/env python
"""This module provides classes for connecting to SolidFire nodes/clusters via SSH and HTTP endpoints"""
#pylint: disable=unidiomatic-typecheck,protected-access,global-statement
from __future__ import print_function, absolute_import
... | |
for all DVAR.
LABEL : str
Label used to describe variable in output.
DELTAB : float; default=0.02
The change in the dimensionless design variable B to be used in the
calculation of the design sensitivity coefficients.
VIDi : List[int]
Identification number of DVSET entry.
"""
fields = ['DVAR', bid, label, del... | |
directory for
the MacOS SDK that should be used. Defaults to None and is
ignored.
vcpkg_dir (str, optional): Full path to the root directory containing
a vcpkg installation. This should be the directory that contains
the vcpkg executable and any packages installed by vcpkg (in
subdirectories). Defaults to None an... | |
self.th)
max_time = max(time)
if self.debug:
print('{}: {}'.format(name, max_time))
print('GEMM flops: {:,}'.format(flop))
for i in range(0, num_level):
print("L{}".format(i))
print("inflection_point: {:.2f}".format(inflection_point[i]))
print("comp_int: {:.2f}".format(comp_int[i]))
print("time: {}".fo... | |
<filename>src/ape/managers/chain.py
import time
from pathlib import Path
from typing import Callable, Dict, Iterator, List, Optional, Tuple, Union
from ethpm_types import ContractType
from ape.api import Address, BlockAPI, ReceiptAPI
from ape.api.address import BaseAddress
from ape.api.networks import LOCAL_NETWORK_N... | |
<filename>build/releases/release-0.499/ob/lisp.py
# -----------------------------------------------------------------------------
#
# Copyright 2013-2019 lispers.net - <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License... | |
'''
HTML is only at main link text, class log, hw, and additional
TODO
Verify MainLink content
Resource files
(Modify rendering options?)
TODO
Form validation! I need to make sure Dr. Dann doesn't enter any weird html
Verify main link content
Visual
Carousel Item
Angular preview
Force image to be a certain size
'... | |
c3r7_t1 + c4r7_t1
c5r1_t1_right = r1_t1_bene + c11r1_t1
c5r2_t1_right = r2_t1_bene + c11r2_t1
c5r3_t1_right = r3_t1_bene + c11r3_t1
c5r4_t1_right = r4_t1_bene + c11r4_t1
c5r5_t1_right = r5_t1_bene + c11r5_t1
c5r6_t1_right = r6_t1_bene + c11r6_t1
c5r7_t1_right = r7_t1_bene + c11r7_t1
# Table 2
r1_t2_bene = c6... | |
<gh_stars>0
"""One-dimensional histograms."""
from typing import Optional, Tuple
import numpy as np
from . import bin_utils
from .histogram_base import HistogramBase
from .binnings import BinningBase
# TODO: Fix I/O with binning
class Histogram1D(HistogramBase):
"""One-dimensional histogram data.
The bins can be... | |
#!/usr/bin/env python3
"""
* xml_dataset_generator_gm9.py
*
* Copyright (c) 2022, DarkMatterCore <<EMAIL>>.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear i... | |
100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.amin(cArray, NumCpp.Axis.COL).flatten(), np.min(data, axis=1))
shapeInput = np.random.randint(2... | |
import requests
import sys
from pingdomlib.check import PingdomCheck
from pingdomlib.contact import PingdomContact
from pingdomlib.reports import PingdomEmailReport, PingdomSharedReport
server_address = 'https://api.pingdom.com'
api_version = '2.0'
class Pingdom(object):
"""Main connection object to interact with ... | |
closelog = True
else:
closelog = False
if log is None:
log = mu.Log()
log.msg(
f"\n{log.sep}\n"
" Multi-core Markov-chain Monte Carlo (mc3).\n"
f" Version {__version__}.\n"
f" Copyright (c) 2015-{date.today().year} <NAME> "
"and collaborators.\n"
" mc3 is open-source software under the MIT license (see LICE... | |
import json
import os
import os.path
import random
import unittest
from datetime import datetime
from json.decoder import JSONDecodeError
from pathlib import Path
from instagrapi import Client
from instagrapi.story import StoryBuilder
from instagrapi.types import (
Account,
Collection,
Comment,
DirectMessage,
Dir... | |
is
returned.
Raises:
:class:`telegram.TelegramError`
"""
if inline_message_id is None and (chat_id is None or message_id is None):
raise TelegramError(
'editMessageCaption: Both chat_id and message_id are required when '
'inline_message_id is not specified')
url = '{0}/editMessageReplyMarkup'.format(self.ba... | |
<reponame>rwl/traitsbackendpyjamas
#------------------------------------------------------------------------------
# Copyright (c) 2007, Riverbank Computing Limited
# Copyright (c) 2009, <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentati... | |
{
'Stn1': station1,
'Msr': msr,
'Msr_SD': msr_SD,
'Adj': adj,
'Cor': cor,
'nStat': nStat,
'outlier': Outlier,
'matched': False
}
if msrType == 'R':
r_count += 1
station1 = line[2:22].strip()
flag = line[62:63]
data = line[67:].split()
msr = data[0]
adj = data[1]
cor = data[2]
msr_SD = data[3]
adj_SD... | |
"""
ExternalResources
=============================
This is a user guide to interacting with the ``ExternalResources`` class.
The ExternalResources type is experimental and is subject to change in future releases.
If you use this type, please provide feedback to the HDMF team so that we can
improve the structure and a... | |
test_nesting_in_message():
proto = """
|message FieldOptions {
| optional CType ctype = 1[old_default = STRING, deprecated = true];
| enum CType {
| STRING = 0[(opt_a) = 1, (opt_b) = 2];
| };
| // Clients can define custom options in extensions of this message. See above.
| extensions 500;
| extensions 1000 to... | |
<filename>metadata/geom.py
#-------------------------------------------------------------------------------
#
# Vector Geometry Manipulations
#
# Project: XML Metadata Handling
# Authors: <NAME> <<EMAIL>>
#
#-------------------------------------------------------------------------------
# Copyright (C) 2013 EOX IT Serv... | |
<gh_stars>0
import commands
import hashlib
from xos.config import Config
from core.models import Controller
try:
from openstack.client import OpenStackClient
has_openstack = True
except:
has_openstack = False
manager_enabled = Config().api_nova_enabled
class OpenStackDriver:
def __init__(self, config = None, cl... | |
<gh_stars>1-10
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utilities to generate content of bugs to be logged."""
import abc
import textwrap
from google.appengine.ext import ndb
from gae_libs.appen... | |
[]
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( #... | |
validity of generated mocks code
exec(generated +
"\nmock_b64decode.return_value.decode.return_value = '20'")
w_mock = tests.sample.code.tested_module.base_64_partial_functions(
"my msg2")
assert "20" == w_mock
def test_generate_mocks_function_list_comprehension(mocker):
wo_mock = get_square_root([1, 4, 9])
a... | |
(n_states)x1 ndarrays e.g. [[2.], [4.], [3.14]]
# n_states, n_controls: number of states and controls
# N: horizon
# T: time step
# lbg, lbx, ubg, ubx: lower and upper (l,u) state and input (x,g) bounds
# current_ref_traj, current_ref_inputs: reference trajectory and reference inputs as Nx(n_states) ndarrays# TODO: add... | |
"""
Autonomous Car Locator
This is a program that helps autonomous cars to find out the location and direction
of other autonomous cars. It is all based on what is provided by the car and from what the car detects.
By <NAME>
"""
import random
def locator():
cars = [
{
"speed" : 50, #the speed of the current... | |
sps: delay >= 1/sps
# We add 0.1ms to be sure
delay = 1.0/sps+0.0001
time.sleep(delay)
# Read the conversion results
result = self.i2c.readList(self.__ADS1015_REG_POINTER_CONVERT, 2)
if (self.ic == self.__IC_ADS1015):
# Shift right 4 bits for the 12-bit ADS1015 and convert to mV
return ( ((result[0] << 8) | ... | |
#!/usr/bin/python3
import argparse
from huepy import *
import sys
import importlib
import os
import base64
import pyperclip
import subprocess
from terminaltables import SingleTable
import random
import socket
#import atexit
POXSSON_PATH = os.path.realpath(__file__).replace("poxsson.py", "") #Absolute path of the projec... | |
"""Unit Test for Audit Info"""
import pytest
from unittest.mock import patch
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from altaudit.models import Base, Character, Gem
from altaudit.gem_enchant import gem_lookup
import altaudit.sections.audit as Section
@pytest.fixture
def mock_i... | |
m.x1047 + m.x1098 + m.x1147 + m.x1236 + m.x1287 + m.x1329 + m.x1371
+ m.x1413 + m.x1455 + m.x1495 + m.x1534 + m.x1567 + m.x1601 == 1)
m.c1901 = Constraint(expr= m.x92 + m.x275 + m.x365 + m.x478 + m.x533 + m.x595 + m.x670 + m.x721 + m.x815 + m.x840
+ m.x883 + m.x937 + m.x976 + m.x1099 + m.x1148 + m.x1237 + m.x1288 + ... | |
'''
Contains classes of models that can be found in `Vo and Zhang 2015 paper \
<https://www.ijcai.org/Proceedings/15/Papers/194.pdf>`_.
Classes:
1. :py:class:`bella.models.target.TargetInd` - Target indepdent model
'''
from collections import defaultdict
import copy
import time
import pandas as pd
from sklearn.model... | |
self.ss7i87in_5.setObjectName("ss7i87in_5")
self.gridLayout_100.addWidget(self.ss7i87in_5, 5, 1, 1, 1)
self.ss7i87in_6 = QtWidgets.QPushButton(self.groupBox_55)
self.ss7i87in_6.setObjectName("ss7i87in_6")
self.gridLayout_100.addWidget(self.ss7i87in_6, 6, 1, 1, 1)
self.ss7i87in_7 = QtWidgets.QPushButton(self.groupB... | |
<gh_stars>0
"""
[CONSUMER] Processes the data generated by the producer
1. Detect edges in real-time over streaming power data
2. Initiates the classification pipeline
3. Detects wastage/usage
4. Sends real-time feedback to user
"""
from __future__ import absolute_import
from energylenserver.setup_django_envt import... | |
----------
st : str or list of str
The name of the unit. If a list, the first element is the
canonical (short) name, and the rest of the elements are
aliases.
represents : UnitBase instance
The unit that this named unit represents.
doc : str, optional
A docstring describing the unit.
format : dict, optional... | |
only be written. Aborting.")
self.efs_close(efsmethod, fdata)
return 0
num_bytes = 0
offset = 0
fname = srcpath[srcpath.rfind("/") + 1:]
fname = os.path.join(dstpath, fname)
with open(fname, "wb") as write_handle:
dataleft = size
while dataleft > 0:
rsize = dataleft
if rsize > FS_DIAG_MAX_READ_REQ:
rsize =... | |
lnphis_l
l_old, g_old = l, g
# print(err, V_over_F, Ks) # xs, ys
# Check for
comp_difference = sum([abs(xi - yi) for xi, yi in zip(xs, ys)])
if comp_difference < trivial_solution_tol:
raise TrivialSolutionError("Converged to trivial condition, compositions of both phases equal",
comp_difference, iteration, err)... | |
Enter a parse tree produced by CParser#declarationSpecifier.
def enterDeclarationSpecifier(self, ctx:CParser.DeclarationSpecifierContext):
self.enter_rule(ctx)
# Exit a parse tree produced by CParser#declarationSpecifier.
def exitDeclarationSpecifier(self, ctx:CParser.DeclarationSpecifierContext):
self.exit_rule(... | |
The process can take some time so please be patient and cooperative.",
],
troubleshooting_guides=[
"https://bobcatminer.zendesk.com/hc/en-us/articles/4413692565659-Common-Error-Logs-in-Miner-5s-"
],
)
def check():
raise NotImplemented
class TooManyLookupAttemptsErrorCheck(BobcatCheck):
def __init__(self, bob... | |
<reponame>wdempsey/sense2stop-lvm
#%%
import pymc3 as pm
import arviz as az
import pandas as pd
import numpy as np
from datetime import datetime
from scipy import stats
import os
import pickle
import theano.tensor as tt
from scipy import special
# List down file paths
#dir_data = "../smoking-lvm-cleaned-data/final"
di... | |
<gh_stars>0
"""Elliptic Curve Method using Montgomery Curves.
"""
import random
import time
from math import gcd
import numpy as np
from wheel_sieve.common import (
PRIME_GEN,
InverseNotFound,
CurveInitFail,
inv,
init_wheel,
)
def get_curve_suyama(sigma, n):
"""Given parameter sigma, generate an Elliptic Curve ... | |
tf.convert_to_tensor(params['A0'], dtype=dtype)
# cost function parameters
sigmaM = params['sigmaM'] # matching
sigmaM2 = sigmaM**2
sigmaR = params['sigmaR'] # regularization
sigmaR2 = sigmaR**2
sigmaA = params['sigmaA'] # artifact
sigmaA2 = sigmaA**2
# optimization parameters
niter = params['niter'] # g... | |
<filename>hardware/ci/parse.py<gh_stars>0
#!/usr/bin/env python
# Parse json from machine files, build hardware.json
import os
import shutil
import sys
import re
import json
import jsontools
import openscad
import syntax
from types import *
def parse_machines():
src_dir = '../'
logfile = 'openscad.log'
outfile = ... | |
""" Module for requesting data from bitcointalk.org and parsing it. """
import codecs
from datetime import date
from datetime import datetime
from datetime import time as tm
import HTMLParser
import json
import logging
import lxml.html
import requests
import os
from random import random
import re
import sys
import time... | |
"""Functions to create and connect nodes."""
import pymel.core as pm
from pymel import versions
import pymel.core.datatypes as datatypes
from . import attribute
#############################################
# CREATE SIMPLE NODES
#############################################
def createMultMatrixNode(mA, mB, target=... | |
from pacman.model.constraints.abstract_constraints.abstract_constraint\
import AbstractConstraint
from pacman.model.constraints.placer_constraints\
.placer_chip_and_core_constraint import PlacerChipAndCoreConstraint
from spynnaker.pyNN.utilities import utility_calls
from spynnaker.pyNN.models.abstract_models.abstrac... | |
l))
if edge_property is not None:
# We might get duplicate edges, but this does handle the case of
# multiple edges.
edges_to_delete.extend(e for e in G.edge_iterator() if not edge_property(e))
G.delete_edges(edges_to_delete)
if not inplace:
if immutable is None:
immutable = self.is_immutable()
if immutable:
... | |
<filename>indra/tests/test_belief_sklearn.py<gh_stars>0
import random
import pickle
import numpy as np
from copy import copy
from collections import defaultdict
from os.path import join, abspath, dirname
from nose.tools import raises
from sklearn.linear_model import LogisticRegression
from indra.sources import signor
f... | |
in an unrecognised
format. If one or both of the two headers are present
yet neither are in a format which AWS4Auth recognises
then it will remove both headers and replace with a new
X-Amz-Date header using the current date.
If this behaviour is not wanted, set the
raise_invalid_date keyword argument to True, an... | |
the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == tensorboard_service.GetTensorboardRunRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, tensorboard_run.TensorboardRun)
assert response.name ... | |
#!/usr/bin/env python3
""" Base class for Models. ALL Models should at least inherit from this class
When inheriting model_data should be a list of NNMeta objects.
See the class for details.
"""
import logging
import os
import sys
import time
from json import JSONDecodeError
from shutil import copyfile, copytree
i... | |
ordem, já recebida do vendedor remetente',
'2122': 'Compra para industrialização em que a mercadoria foi remetida pelo fornecedor ao industrializador sem transitar pelo estabelecimento adquirente',
'2124': 'Industrialização efetuada por outra empresa',
'2125': 'Industrialização efetuada por outra empresa quando a... | |
- len(line))
line_x = list(line)
line_x.extend(temp)
adjusted_weights.append(line_x)
np.savetxt(file_name, np.array(adjusted_weights), delimiter=",", fmt='%.18g')
elif save_type == 1: # All outputs
results, labels = data_to_save
ending = '\n'
try:
file_ann = open(file_name, "a")
except:
file_ann... | |
AnalysisDependency.STATUS_RESOLVED
@property
def ready(self):
"""Returns True if target analysis has not been completed."""
return self.status == AnalysisDependency.STATUS_READY
@property
def completed(self):
"""Returns True if the target analysis has been completed."""
return self.status == AnalysisDependenc... | |
'sha_v1':
return self.sha_v1_hashpass(username, cloud_pass)
else:
return self.sha_v2_hashpass(username, cloud_pass)
def sha_v2_hashpass(self, username, cloud_pass):
if not cloud_pass or len(cloud_pass) < 32:
raise ValueError("Cloud config ['user']['secret'] is required and " +
"must be of length 32 or more")
... | |
showline=True, showspikes=True, spikethickness=1, spikedash='solid',
mirror=True, tickformat=".1f", title_standoff=10, range=[0, scaleup(df[x].max())]
).update_yaxes(spikedash='solid',
showgrid=False,
title_standoff=10,
title=dict(
text=y.translate(
SUP),
standoff=5),
autorange=True,
ticks='outside',
showspi... | |
# Copyright (c) <NAME>, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
# TODO:
# * if the input imageStackRDR is reconfigured to read a different stack
# by the user, then things will break. We probably have to add an observer
# and adapt to the new situation.
# * ditto for the input transformStackRDR
# ... | |
# # Autonomous driving - Car detection
import argparse
import os
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
import scipy.io
import scipy.misc
import numpy as np
import pandas as pd
import PIL
import tensorflow as tf
from keras import backend as K
from keras.layers import Input, Lambda, Conv... | |
"youtube": ""
}
},
"XGG": {
"symbol": "XGG",
"address": "0xf6b6AA0Ef0f5Edc2C1c5d925477F97eAF66303e7",
"decimals": 8,
"name": "Going Gems",
"ens_address": "",
"website": "https://www.going-gems.com",
"logo": {
"src": "",
"width": "",
"height": "",
"ipfs_hash": ""
},
"support": {
"email": "<EMAIL>",
"ur... | |
<reponame>Daggy1234/BotBot
from __future__ import annotations
import asyncio
import random
from functools import wraps
from string import ascii_uppercase
from collections import defaultdict
from collections.abc import Iterable
from typing import NamedTuple, Optional
import discord
from discord.ext import commands, m... | |
# Copyright (C) 2020 NTT DATA
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | |
self.properties.lcs = self.parent._read_val('h', vals[lcs], 2)
self.properties.lcp = self.parent._read_val('h', vals[lcp], 2)
class ColumnSizeSubheader(ProcessingSubheader):
def process_subheader(self, offset, length):
offset += self.int_length
vals = self.parent._read_bytes({
offset: self.int_length
})
if sel... | |
if (count > 512 or address > 0x1ff):
return False
dataCount = 4
replyCount = count
result = False
s_buffer = bytearray(MSG_HEADER_SIZE+MSG_CHECKSUM_SIZE+dataCount) # send buffer
r_buffer = bytearray(MSG_HEADER_SIZE+MSG_CHECKSUM_SIZE+replyCount) # reply buffer
s_buffer[MSG_INDEX_COMMAND] = self.CMD_SETTINGS_MEM... | |
<gh_stars>1-10
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import platform
import binascii
import functools
import numpy as np
from math import ceil, floor
from .core import DataViewWindow, Window
from .widgets.to... | |
u"peaksigTriMat": True,
u"translations":True, u"pixRegError":True,
u"CTFDiag":True, u"logisticWeights": True, u"FRC": True,
u'Transparent': True, u'plot_dpi':144, u'image_dpi':250,
u'image_cmap':u'gray', u'graph_cmap':u'gnuplot',
u'fontsize':12, u'fontstyle': u'serif', u'colorbar': True,
u'backend': u'Q... | |
"""Gym environment for chnging colors of shapes."""
import numpy as np
import torch
import torch.nn as nn
import gym
from collections import OrderedDict
from dataclasses import dataclass
from gym import spaces
from gym.utils import seeding
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mp... | |
<reponame>tomspur/scipy
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 2.0.10
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2,6,0):
def swig_import_helper():
from ... | |
[Declare(i.dtype, i)]
elif not isinstance(i, Variable):
decs += [FuncAddressDeclare(i)]
decs += [Declare(i.dtype, i) for i in self._additional_declare]
decs = ''.join(self._print(i) for i in decs)
self._additional_declare.clear()
sep = self._print(SeparatorComment(40))
if self._additional_args :
self._addition... | |
"""Module for the main simulation management class.
All component class interfaces are set by how the manager interacts
with them.
Managers should implement a three phase protocol for running
simulations:
- init
- run_simulation
- cleanup
The separate `init` method is different than the constructor
`__init__` metho... | |
i, f in enumerate(found):
if f is not None:
parents[missing_inds[i]] = f
return parents
class domain_transform(object):
"""
Simple helper class to keep track of transform variables to test for
equality
"""
def __init__(self, mapping, affine):
self.mapping = mapping
self.affine = affine
def __eq__(self,... | |
<gh_stars>0
import json
import os
from dataclasses import dataclass
from unittest.mock import patch
import appdirs
import pytest
from git import Head
from flexlate import branch_update
from flexlate.add_mode import AddMode
from flexlate.config import FlexlateConfig, FlexlateProjectConfig
from flexlate.constants impor... | |
<gh_stars>0
# MIT License
#
# Copyright (c) 2021 Emc2356
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify,... | |
# Copyright 2021 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 agreed to in writing, softwar... | |
'OB_ORA_SYS_DATABASE_ID',
table_id = '25100',
table_type = 'SYSTEM_VIEW',
rowkey_columns = [],
normal_columns = [],
gm_columns = [],
in_tenant_space = True,
view_definition = """
SELECT
CAST(NULL AS VARCHAR2(30)) AS JOB_NAME,
CAST(NULL AS VARCHAR2(30)) AS ARGUMENT_NAME,
CAST(NULL AS NUMBER) AS ARGUMENT_POSITI... | |
from floem import *
n_cores = 1
nic_rx_threads = 10
nic_tx_threads = 1
rx_queues = 1
tx_queues = 1
#mode = 'dpdk'
mode = target.CAVIUM
class protocol_binary_request_header_request(State):
magic = Field(Uint(8))
opcode = Field(Uint(8))
keylen = Field(Uint(16))
extlen = Field(Uint(8))
datatype = Field(Uint(8))
s... | |
<filename>lib/tpn/invariant.py<gh_stars>1-10
#===============================================================================
# Imports
#===============================================================================
import os
import re
import inspect
import datetime
import linecache
import itertools
from .util import... | |
# Copyright 2019 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 writing, s... | |
range(len(encoding)):
name = encoding[code]
if name != ".notdef":
m[name] = code
ranges = []
first = None
end = 0
for name in charset[1:]:
code = m.get(name, -1)
if first is None:
first = code
elif end + 1 != code:
nLeft = end - first
ranges.append((first, nLeft))
first = code
end = code
... | |
# -*- coding: utf-8 -*-
# @Time : 2019-12-24
# @Author : mizxc
# @Email : <EMAIL>
import datetime
from flask import current_app, request, flash, render_template, redirect, url_for, jsonify
from flask_login import login_required, current_user
from . import bpAdmin
from project.common.dataPreprocess import strLength, st... | |
go up one
yaml_dir = os.path.dirname(yaml_dir)
if 'MOBILE' in version_prefix:
globalYaml = os.path.join(yaml_dir, 'yaml_files/CSHORE/CSHORE_mobile_global.yml')
varYaml = os.path.join(yaml_dir, 'yaml_files/CSHORE/CSHORE_mobile_var.yml')
elif 'FIXED' in version_prefix:
globalYaml = os.path.join(yaml_dir, 'yaml_fil... | |
import logging
import json
import uuid
import requests
from kube_hunter.conf import get_config
from kube_hunter.modules.discovery.apiserver import ApiServer
from kube_hunter.core.events import handler
from kube_hunter.core.events.types import Vulnerability, Event, K8sVersionDisclosure
from kube_hunter.core.types impor... | |
"""
mathEX.py
@author: <NAME>
@email: <EMAIL>
Math-related functions, extensions.
"""
import numpy as np
def change_to_multi_class(label_set, num_of_labels):
"""
change the input prediction y to array-wise multi_class classifiers.
:param label_set:input prediction y, numpy arrays
:param num_of_labels: number of... | |
of lines (dataStream) to parse!')
self.parsePositionInStream = 0
self.eventList = []
for line in dataStream:
line = line.rstrip()
if line == "":
continue # technically forbidden by Humdrum but the source of so many errors!
elif re.match(r'\!\!\!', line):
self.eventList.append(GlobalReferenceLine(self.parsePos... | |
##
# 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. Dissemination
# to ... | |
"""
This handles mapping the filenames in the export
to the corresponding functions and caching the results
"""
import os
import re
from pathlib import Path
from typing import (
Iterator,
Dict,
Callable,
Any,
Optional,
List,
Type,
Tuple,
cast,
)
from collections import defaultdict
from cachew import cachew
... | |
"""
The Web Application
~~~~~~~~~~~~~~~~~~~
Implementation of all request handlers and core functionality.
"""
import csv
import datetime
import os
import pickle
import logging
import hashlib
import tarfile
import calendar
from cStringIO import StringIO
from collections import defaultdict, OrderedDict
from functo... | |
<filename>src/Classes/MSDS422/Module_05/exploring-mnist-v001.py
# Exploring MNIST with Binary Classification (Python SciKit Learn)
# program revised by <NAME> (2017/10/18)
# Using data from the MNIST dataset from Scikit Learn and
# beginning with code from chapter 3 of <NAME>. 2017.
# Hands-On Machine Learning with ... | |
# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
import numpy as np
import pandas as pd
import os
import re
from pyiron_base import state, ProjectHDFio
from pyiron_atomi... | |
<filename>tgt_grease/enterprise/Model/KafkaSource.py
import json
from time import time
import threading
from multiprocessing import Pipe
import kafka
from kafka import KafkaConsumer
from tgt_grease.core import GreaseContainer
from tgt_grease.enterprise.Model.CentralScheduling import Scheduling
from .Configuration impor... | |
import unittest
import warnings
from pyramid import testing
from pyramid.compat import (
text_,
bytes_,
)
class TestCallbackAuthenticationPolicyDebugging(unittest.TestCase):
def setUp(self):
from pyramid.interfaces import IDebugLogger
self.config = testing.setUp()
self.config.registry.registerUtility(self, IDeb... | |
'Exit':1990},
'R-60': {'Entry':1973, 'Exit':1992},
'R-60M': {'Entry':1983, 'Exit':2999},
'R-60MK': {'Entry':1983, 'Exit':2999},
'R-73': {'Entry':1972, 'Exit':2007},
'R-73E': {'Entry':1984, 'Exit':2999},
'R-73M': {'Entry':1997, 'Exit':2999},
'R-73M2': {'Entry':2011, 'Exit':2999},
'R-77': {'Entry':1991, 'Exit':29... | |
#!/usr/bin/env python3
"""
MediaServer Database module.
Contains all interactions between the webapp and the queries to the database.
"""
import configparser
import json
import sys
from modules import pg8000
################################################################################
# Welcome to the database fil... | |
<filename>VIP_modules/dictionaries/session.py
"""
This file lists all initial values that are used in building the VIP GUI.
We do so by assembling a large dictionary of dictionaries of dictionaries,
called 'Tree'. From this we construct the smaller 'default' dictionary of
dictionaries. The default session dictionar... | |
DataFrame:
"""BASP indicator serves to identify buying and selling pressure."""
sp = ohlc["high"] - ohlc["close"]
bp = ohlc["close"] - ohlc["low"]
spavg = sp.ewm(span=period, adjust=adjust).mean()
bpavg = bp.ewm(span=period, adjust=adjust).mean()
nbp = bp / bpavg
nsp = sp / spavg
varg = ohlc["volu... | |
<reponame>allansrc/fuchsia
# Copyright 2019 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import io
import json
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import unittest... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.