input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
# SPDX-License-Identifier: MIT
# Copyright (C) 2004-2008 <NAME> and <NAME>
# Copyright (C) 2012-2014 <NAME>
# Copyright (C) 2015-2021 <NAME>
# Copyright (C) 2019-2020 <NAME>
from re import compile, escape
from ..scraper import _BasicScraper, _ParserScraper
from ..helpers import bounceStarter, indirectStarter
from ..ut... | |
response = self.connection.request(req, method='POST', data=data)
response_dict = response.parse_body()
assert_response(response_dict=response_dict, status_code=200)
return self.ex_get_storage_pool_volume(pool_id=pool_id,
type=definition["type"],
name=definition["name"])
def attach_volume(self, container_id, v... | |
<reponame>balbasty/nitorch
"""Utility functions for registration algorithms.
Some (jg, jhj, affine_grid_backward) should maybe be moved to the `spatial`
module (?).
"""
from nitorch.core import py, utils, linalg
from nitorch import spatial
import torch
from . import optim as optm
def defaults_velocity(prm=None):
if... | |
import pd_base_tests
from ptf import config
from ptf.testutils import *
from ptf.thriftutils import *
from pltfm_pm_rpc.ttypes import *
from port_mapping import *
from pal_rpc.ttypes import *
from var_agg.p4_pd_rpc.ttypes import *
from res_pd_rpc.ttypes import *
class Flag(Packet):
name = "Flag"
fields_desc = [ Bi... | |
of Emitted, Transferred, Acked and Failed.
#
# @author <NAME>
# @date 2015-03-11
# @param topology_id, topology id.
# @param system_id, show/hide system stats.
# @return -
# @remarks -
#
def _get_detail_values(stats, spouts, bolts):
aEmitted = []
aTransferred = []
aAcked = []
aFailed = []
iEmitted = 0
iTransferre... | |
assert self.rating.created == original_created_date
activity_log = ActivityLog.objects.latest('pk')
assert activity_log.user == self.user
assert activity_log.arguments == [self.addon, self.rating]
assert activity_log.action == amo.LOG.EDIT_RATING.id
assert len(mail.outbox) == 0
def test_edit_owner_put_not_allo... | |
QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 740, 740))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.gridLayout_9 = QtWidgets.QGridLayout(self.scrollAreaWidgetContents)
self.gridLayout_9.setObjectName("gridLayout_9")
self.splitter = QtWidgets... | |
= torch.optim.SGD(model.parameters(), args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay)
# optionally resume from a checkpoint
if args.resume:
if '.pth' not in args.resume: # find the last model
resume_dir = args.resume if os.path.isdir(args.resume) else args.model_name
args.resume = os.path.join(... | |
<filename>tests/dummy_package/dummy_module.py
class Dense:
"""Just your regular densely-connected NN layer.
`Dense` implements the operation:
`output = activation(dot(input, kernel) + bias)`
where `activation` is the element-wise activation function
passed as the `activation` argument, `kernel` is a weights matri... | |
* (37 - n)
x.sort()
cx = list(x)
sx = sum(x)
mx = x[-1]
for i in xrange(1, 37):
crem = x[i - 1] * i - sum(x[:i])
if b >= crem:
cx.append(x[i - 1] + (b - crem) / i)
cx = cx + [(y - 1) for y in cx if y]
cx = cx + [(y + 1) for y in cx]
return cx
def func_624f8b2f461b4148a00c2b80b9567ce6(infile, b, n):
x = ma... | |
and SEEK_END or 2 (seek relative to the
file’s end).
"""
result = self._fd.seek(offset, whence)
self.tell()
return result
def tell(self):
"""
Return the file's current position, in bytes. Only available
in `seekable` returns `True`.
"""
return self._fd.tell()
def flush(self):
"""
Flush the internal buff... | |
phjPrintResults == True:
print(model.summary2())
print('\n')
else:
model.summary2() # It seems that the .summary2() method needs to be run even if not printed, otherwise an error occurs.
# Calculate predicted probabilities
X[phjPredProbName] = model.predict() # predicted probability
# Estimate confidence int... | |
# coding: utf-8
import wx
import cv2
import numpy as np
import pandas as pd
import wx.media
import matplotlib
import collections
from matplotlib.figure import Figure
import wx.lib.mixins.inspection as WIT
import wx.lib.calendar
import traceback
import sys, math, os
import random
import datetime
matplotlib.use('WXAgg'... | |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | |
the emulated version of the object_isClass runtime function, for systems older than OS X 10.10
or iOS 8, where the real function doesn't exist yet.
"""
return libobjc.class_isMetaClass(libobjc.object_getClass(obj))
else:
# BOOL object_isClass(id obj)
object_isClass.restype = c_bool
object_isClass.argtypes = [obj... | |
# -*- coding: utf-8 -*-
import datetime
import time
from threading import Lock
from typing import List, Optional
from confluent_kafka import Message
from pip_services3_commons.config import ConfigParams
from pip_services3_commons.errors import ConnectionException, InvalidStateException
from pip_services3_commons.refe... | |
import os
from itertools import zip_longest, product
from functools import partial
from os.path import dirname
import numpy as np
import scipy.sparse
from tqdm.autonotebook import tqdm
import torch
import random
import pdb
import string
import logging
from sklearn.cluster import k_means, DBSCAN
import matplotlib.pyplo... | |
<reponame>AndresdPM/GetGaia<gh_stars>1-10
#!/usr/bin/env python
from __future__ import print_function
import argparse
import sys
import os
import subprocess
import warnings
import numpy as np
import pandas as pd
pd.options.mode.chained_assignment = None
import matplotlib.pyplot as plt
from matplotlib.widgets import... | |
with ECDF.
"""
# Extract data
data = utils._convert_data(data)
# Data points on ECDF
x, y = _ecdf_vals(data, True, complementary)
# Line of steps
if q_axis == "y":
line = p.line(y, x, **line_kwargs)
elif q_axis == "x":
line = p.line(x, y, **line_kwargs)
# Rays for ends
if q_axis == "y":
if complementary... | |
<gh_stars>1-10
#!/usr/bin/env python3
"""Ruler component pulls all actions from Site-FE and applies these rules on
DTN.
Copyright 2017 California Institute of Technology
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 ... | |
<filename>gmg/gmg.py
"""
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GUI application for Forward modelling 2D potential field profiles.
Written by <NAME>, University of Oxford 2015-17. SIO 2018-19.
Includes ability to import seismic reflection... | |
if failed:
self.logger.error("\nBinary extensions failing to build:")
for binary_extension in failed:
self.logger.error(f" - {binary_extension}")
if not succeeded and not failed:
warning(f"No binary extensions found in package ({self.context.package_name}).")
def get_logger(self, log_file_path=None):
""""""
... | |
<gh_stars>1-10
"""
Defines base classes `Op` and `CLinkerOp`.
The `Op` class is the base interface for all operations
compatible with `graph`'s :doc:`graph` routines.
"""
import copy
import inspect
import os
import re
import sys
import warnings
from abc import abstractmethod
from typing import (
TYPE_CHECKING,
Any,... | |
<filename>src/spens.py
import numpy as np
import copy
from typing import List, Tuple, Union
from dataclasses import dataclass, astuple, replace
from torch.utils.data import DataLoader
from collections import OrderedDict, deque
import torch
import sys
from torch import nn
import torch.nn.functional as F
import torch.opt... | |
1, 11 ):
self._verify( testfile )
def _verify( self, testfile ):
with open( 'tests/usaco/digits/I.{}'.format( testfile ) ) as inputFile, \
open( 'tests/usaco/digits/O.{}'.format( testfile ) ) as solutionFile:
base2String = readString( inputFile )
base3String = readString( inputFile )
number = readIn... | |
pm.attributeQuery("mirrorLinks", node = "%s:module_grp" %objNamespaceInfo[0], exists = True):
mirrorLinks = pm.getAttr("%s:module_grp.mirrorLinks" %objNamespaceInfo[0])
moduleInfo = mirrorLinks.rpartition("__")
module = moduleInfo[0]
axis = moduleInfo[2]
# Apply symmetry to translation control
if objNamespace... | |
San Pietro Apostolo"),
Santo("La Commemorazione di tutti i fedeli defunti"),
Santo("La Conversione di San Paolo Apostolo"),
Santo("La Dedicazione della Basilica Lateranense"),
Santo("La Dedicazione delle basiliche dei Santi Pietro e Paolo"),
Santo("La devozione delle 3 Ave Maria"),
Santo("La Natività di San Giova... | |
>>> close = order_price = np.array([
... [1, 6],
... [2, 5],
... [3, 4],
... [4, 3],
... [5, 2],
... [6, 1]
... ])
>>> size = np.asarray([
... [1, -1],
... [0.1, -0.1],
... [-1, 1],
... [-0.1, 0.1],
... [1, -1],
... [-2, 2]
... ])
>>> target_shape = close.shape
>>> group_lens = np.full(target_shape[1],... | |
from __future__ import absolute_import
from __future__ import unicode_literals
from contextlib import contextmanager
import json
from collections import defaultdict, namedtuple, OrderedDict
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from couchdbkit import... | |
= t[last_down] - t[first_up]
return full_width
APFullWidth = ap_full_width # Alias
def ap_half_width(t,v, dvdt_threshold=5.):
"""
Definition from neuroelectro.org:
AP duration at membrane voltage halfway between AP threshold and AP peak.
Currently only uses gradient method for finding threshold for simplicity.... | |
<reponame>conzty01/RA_Scheduler
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import google_auth_oauthlib.flow
import logging
import os
class gCalIntegratinator:
""" Object for handling interactions between RADSA and Google... | |
in topo])
assert any([isinstance(node.op, cuda.GpuSubtensor) for node in topo])
# Test multiple use of the input + input as output
# We want the subtensor to be on the GPU to prevent multiple transfer.
t = tensor.fmatrix()
f = theano.function([t], [t[3:4], t+1, t], mode=mode_with_gpu)
topo = f.maker.fgraph.topos... | |
TypeError("cannot assign '{}' as parameter '{}' "
"(torch.nn.Parameter or None expected)"
.format(value, name))
self.register_parameter(name, value)
else:
modules = self.__dict__.get('_modules')
if isinstance(value, tf.Module):
if modules is None:
raise AttributeError(
"cannot assign module before Module.__ini... | |
<reponame>borro0/aceproxy
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
'''
AceProxy: Ace Stream to HTTP Proxy
Website: https://github.com/ValdikSS/AceProxy
'''
import traceback
import gevent
import gevent.monkey
import socket
# Monkeypatching and all the stuff
# Custom Scripts
from csvwriter import CSVWriter
geve... | |
<filename>convert-addresses.py<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
info = """The idea for this script originates from
https://github.com/BergWerkGIS/convert-bev-address-data/blob/master/README.md
The input are the various csv files from the publicly available dataset of
addresses of Austria, av... | |
to be used in encoder
"encoder_channels": ((1, 8), (8, 16), (16, 32), (32, 64), (64, 128)),
# Utilize encoder segmentation mapping for auxiliary loss
"encoder_segmentation_mapping": False,
# Set output shape
"encoder_output_shape": (8, 8, 8),
# Utilized fourier input features in decoder
"decoder_fourier_input_f... | |
# coding=utf-8
# Copyright (c) 2016, <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 of source code must retain the above copyright
# notice, this list of conditi... | |
<reponame>raychorn/svn_molten-magma<gh_stars>0
"""
This is the Magma Users Walker Process - handles those files that look like this "Headcount Report - November 2008 120108 LA.XLS".
"""
__version__ = 0.1
import pprint
import os, sys
import textwrap
import time
import datetime
import re
import ... | |
12'd641, 4'd0 };
mem[642] = { 16'd0, 12'd642, 4'd0 };
mem[643] = { 16'd0, 12'd643, 4'd0 };
mem[644] = { 16'd0, 12'd644, 4'd0 };
mem[645] = { 16'd0, 12'd645, 4'd0 };
mem[646] = { 16'd0, 12'd646, 4'd0 };
mem[647] = { 16'd0, 12'd647, 4'd0 };
mem[648] = { 16'd0, 12'd648, 4'd0 };
mem[649] = { 16'd0, 12'd649, 4'd0 };... | |
from PDA import PDA
import math
EMPTY_STRING = ''
def int_to_bin(x):
return x.__format__('b')
def s_2(x):
return int_to_bin(x).count('1')
def base_b(n,b):
s = EMPTY_STRING
while n > 0:
s += str(n % b)
n //= b
return s[::-1]
def s_b(n,b):
count = 0
while n > 0:
count += n % b
n //= b
return count
# ... | |
Description
================== ==================================================
``'line'`` Draws an straight line between consecutive points
``'steps-pre'`` Draws a line down from point A and then right to
point B
``'steps-post'`` Draws a line right from point A and then down
to point B
``'steps-mid-x'`` Draws... | |
""" AAAADtcRecord: DTC AAAA Record object.
Corresponds to WAPI object 'dtc:record:aaaa'
A DTC AAAA object represents a DNS Traffic Control IPv6 Address (DTC
AAAA) resource record. This resource record specifies mapping from
domain name to IPv6 address.
Fields:
auto_created: Flag that indicates whether this reco... | |
<gh_stars>1-10
from __future__ import absolute_import, division, print_function
import argparse
import json
import logging
import os
import random
import datetime
import numpy as np
import torch
import torch.nn.functional as F
from pytorch_transformers import (WEIGHTS_NAME, AdamW, BertConfig,
BertForTokenClassificat... | |
if not resource_map.get(rid):
resource_map[rid] = self.load_resource(config, rid)
resource_map[rid].setdefault(
'c7n:HealthEvent', []).append(event_map[e['eventArn']])
return list(resource_map.values())
def load_resource(self, config, rid):
resources_histories = config.get_resource_config_history(
resourceType=... | |
CSV, which will be more involved. The first
#thing to note is that we're again given a "list of lists". This time, each
#item is a list containing all the tonnage information for a given municipality
#along with all the auxillary information contained in the spreadsheet. Just
#like with Form 1, we need to make ... | |
fs=params['mixture']['fs'],
mono=True)
if fs_bg != fs_event:
message = '{name}: Sampling frequency mismatch. Material should be resampled.'.format(
name=self.__class__.__name__
)
self.logger.exception(message)
raise ValueError(message)
# Slice event audio
segment_start_samples = int(mixture_recipe['segment_... | |
[8.79358035e-03, 1.66785263e-04]],
[[2.09829286e-02, -2.45315596e-01],
[4.90596592e-02, -2.37422779e-01],
[-1.25929657e-02, 1.97644513e-02],
[-4.82313000e-02, 9.01009962e-02],
[-2.04636389e-03, 3.53614520e-03],
[-2.03452841e-03, 3.44079128e-03],
[2.60568969e-02, -4.13876921e-02],
[3.94379767e-03, -3.14201764e-... | |
import matplotlib.patches as patches
from PIL import Image, ImageDraw
from cv2 import VideoWriter, VideoWriter_fourcc
import cv2
import os
from __future__ import print_function, division
import os
import torch
import pandas as pd
from skimage import io, transform
import numpy as np
import matplotlib.pyplot a... | |
kw if key not in keywords]
if unknown:
s = 'Unknown sub-list identifier ("%s"). Known identifier ' + \
'are: %s'
self.error(s % (str(unknown), str(keywords)))
if kw:
keywords = kw.keys()
infra = self.getInfrastructure()
## structures (pdb-files)
it_settings = self.getIterationSettings(number)
n_struct... | |
= cms.string('PropagatorWithMaterialParabolicMf'),
propagatorOppositeTISE = cms.string('PropagatorWithMaterialParabolicMfOpposite')
),
cleanTrajectoryAfterInOut = cms.bool(False),
doSeedingRegionRebuilding = cms.bool(False),
maxNSeeds = cms.uint32(100000),
maxSeedsBeforeCleaning = cms.uint32(1000),
src = cms.Inp... | |
= Constraint(expr= m.x1605 - m.b3017 <= 0)
m.c1607 = Constraint(expr= m.x1606 - m.b3017 <= 0)
m.c1608 = Constraint(expr= m.x1607 - m.b3017 <= 0)
m.c1609 = Constraint(expr= m.x1608 - m.b3017 <= 0)
m.c1610 = Constraint(expr= m.x1609 - m.b3017 <= 0)
m.c1611 = Constraint(expr= m.x1610 - m.b3017 <= 0)
m.c1612 = Constr... | |
"""Sets-up and tears-down configuration used for testing."""
import json
import os
import re
import secrets
import urllib.parse
from typing import List
from typing import Tuple
import httpx
import pytest
import respx
import graph_onedrive
# Set the variables used to create the OneDrive instances in tests
# Warning:... | |
including buffers
col_buffer_lower = The amount of column buffer preceding the data
row_buffer_lower = The amount of row buffer preceding the data
nodata = no data value
data = list of arrays from the dataset
"""
# cast to ints since gdal will throw exception if float gets through (even if it's 1.0)
col_buffer_... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2018 EMBL - European Bioinformatics Institute
#
# 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/LICEN... | |
<filename>minesweeper.py
"""
Raw implementation of a minesweeper
game without the use of interfaces or coroutines.
"""
import random
from collections import deque
from typing import List, Union
# initialize gameboard with mines, randomly (both are input with restrictions)
# count number of mines each cell i... | |
#!/usr/bin/env python
import os
import time
import logging
import dask.bag as db
from dask.diagnostics import ProgressBar
from h5py import __version__ as H5PY_VERSION
from blimpy import __version__ as BLIMPY_VERSION
from .turbo_seti_version import TURBO_SETI_VERSION
from .kernels import Kernels, Scheduler
from .data... | |
<reponame>oracle/accelerated-data-science<gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8; -*-
# Copyright (c) 2021, 2022 Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
from copy import deepcopy
from typing import List, U... | |
int(num_args[0])))
elif op_name == 'floor':
return math.floor(num_args[0])
elif op_name == 'find_work':
return 1 / (
max(
min(num_args[0], 1 / num_args[0]), min(
num_args[1], 1 / num_args[1])) - min(
min(num_args[0], 1 / num_args[0]),
min(num_args[1], 1 / num_args[1])))
elif op_name == 'from_percent':
return... | |
import re
import numpy as np
import pandas as pd
import pytest
import woodwork as ww
from woodwork import DataColumn, DataTable
from woodwork.datatable import _check_unique_column_names
from woodwork.logical_types import (
URL,
Boolean,
Categorical,
CountryCode,
Datetime,
Double,
EmailAddress,
Filepath,
Full... | |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2012 <NAME>, <NAME>, <NAME>,
# <NAME>
# Copyright (c) 2009-2019 <NAME>, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provide... | |
"ru_RU": "Сонгдал"
},
"SOGUT": {
"de_DE": "Söğüt",
"es_ES": "Söğüt",
"fr_FR": "Söğüt",
"it_IT": "Söğüt",
"ja_JP": "ソユット",
"ko_KR": "쇠위트",
"pl_PL": "Söğüt",
"pt_BR": "Söğüt",
"ru_RU": "Сёгют"
},
"SOLEB": {
"de_DE": "Soleb",
"es_ES": "Soleb",
"fr_FR": "Soleb",
"it_IT": "Soleb",
"ja_JP": "ソレブ",
"ko_KR":... | |
"""
A general language for json-serialization of a function call.
- Any construction of a python object needs to go through a function call that makes it so
this approach is general.
- It’s also simple at its base, but open (and intended for) extensions to specialize
and compress the language as well as add layers for ... | |
<reponame>Eddddan/interfaceBuilder
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
from interfaceBuilder import interface
from interfaceBuilder import file_io
from interfaceBuilder import inputs
from interfaceBuilder import utils as ut
class Structure():
"""
Class for holding structure d... | |
# -*- coding: utf-8 -*-
'''
Return data to local job cache
'''
from __future__ import absolute_import
# Import python libs
import errno
import glob
import logging
import os
import shutil
import time
import hashlib
import bisect
import time
# Import salt libs
import salt.payload
import salt.utils
import salt.utils.fi... | |
= nvec // 3
k = nvec % 3
v[j, k] = float(line.strip()) * units.angstrom
self.system.box_vector = v
def read(self):
# Load in data from file
# Read data in Desmond format
# Args:
molnames = []
with open(self.cms_file, 'r') as fl:
self.lines = list(fl)
i=0
j=0
self.atomtypes = dict()
self.atomlist = []
... | |
import torch
import torch.nn as nn
# Resnet Blocks
class ResnetBlockFC(nn.Module):
''' Fully connected ResNet Block class.
Args:
size_in (int): input dimension
size_out (int): output dimension
size_h (int): hidden dimension
'''
def __init__(self, size_in, size_out=None, size_h=None):
super().__init__()
# A... | |
= visual.TextStim(myWin,pos=(0,0),colorSpace='rgb',color= (1,1,1),alignHoriz='center', alignVert='center',height=.5,units='deg',autoLog=autoLogging)
startTrialStimuli.text = 'Click here to start the trial'
startTrialBox = visual.Rect(myWin, height = .75, width = 6, units = 'deg', lineColor = bgColor, lineColorSpace = ... | |
2 43 46\n',
'M V30 51 1 43 47\n',
'M V30 52 2 44 45\n',
'M V30 53 1 44 50\n',
'M V30 54 1 44 101\n',
'M V30 55 1 45 46\n',
'M V30 56 1 45 156\n',
'M V30 57 1 46 51\n',
'M V30 58 1 47 48\n',
'M V30 59 1 47 52\n',
'M V30 60 1 48 49\n',
'M V30 61 1 48 53\n',
'M V30 62 1 48 54\n',
'M V30 63 1 49 55\n',
'M V30... | |
# -*- coding: utf-8 -*-
from __future__ import division, absolute_import, print_function
__copyright__ = "Copyright (C) 2009-15 <NAME>"
__license__ = """
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 S... | |
<reponame>osoco/better-ways-of-thinking-about-software
"""
Tests for student activation and login
"""
import datetime
import hashlib
import json
import unicodedata
from unittest.mock import Mock, patch
import ddt
from django.conf import settings
from django.contrib.auth.models import User # lint-amnesty, pylint: dis... | |
# Copyright The IETF Trust 2019, All Rights Reserved
# Copyright 2018 Cisco and its affiliates
#
# 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
#... | |
<reponame>kachelundmacher/edensahana
# -*- coding: utf-8 -*-
""" Sahana Eden Data Collection Models
@copyright: 2014-2016 (c) Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software")... | |
#####
#
# Module name: options.py
# Purpose: Manage program options from command line & .rc file
#
# Notes:
#
#####
# Import Python modules
import configparser
from configparser import SafeConfigParser
import argparse
import os
import sys
from getpass import getpass
# Import dupreport modules
import log
import drda... | |
misc.Popen([os.path.join(madir, 'plot_events')],
stdout = open(pjoin(plot_dir, 'plot.log'),'w'),
stderr = subprocess.STDOUT,
stdin=subprocess.PIPE,
cwd=plot_dir)
proc.communicate(('%s\n' % event_path).encode('utf-8'))
del proc
#proc.wait()
misc.call(['%s/plot' % self.dirbin, madir, td],
stdout = open(pjoin(plo... | |
read_markers(fname):
if 'fc.txt' in fname:
df = pd.read_csv(fname, header=0, comment='#', sep=" ")
print(df.head())
return df.iloc[:,0]
else:
with open(fname) as f:
return pd.Series([line.rstrip('\n') for line in f.readlines() if len(line) > 0 and line[0] != '#'])
def test_raw_expression(scobj, raw_file):
pass... | |
[1, 6, -900]})
schema = {
"codec": "struct",
"type": "object",
"properties": {
"array": {
"type": "array",
"items": {"type": "number", "binaryFormat": "d"},
}
},
}
self.round_trip(schema, {"array": []})
self.round_trip(schema, {"array": [1.5]})
self.round_trip(schema, {"array": [1.5, 6.7, -900.00001]})
... | |
the preview file for '%s'", img)
print("Error reading the preview file for {}".format(name))
self._previewtrain[name] = None
def _get_current_size(self, name):
""" Return the size of the currently displayed training preview image.
Parameters
----------
name: str
The name of the training image to get the size ... | |
import os
import subprocess as sp
import time
import warnings
from queue import Queue
from threading import Thread
from typing import Union
import cv2
import h5py
import numpy as np
import pandas as pd
# TODO: refactor videoreader and videowriter to have these different methods be subclasses of a single base class
... | |
<gh_stars>1-10
# Copyright Notice:
# Copyright 2016-2019 DMTF. All rights reserved.
# License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/Redfish-Service-Conformance-Check/blob/master/LICENSE.md
#################################################################################################... | |
False
#print('Left stop')
if event.key == ord('d'):
axisX = int(0)
panKeyPresseed = False
#print('Right stop')
if event.key == ord('w'):
axisY = int(0)
tiltKeyPresseed = False
#print('Up stop')
if event.key == ord('s'):
axisY = int(0)
tiltKeyPresseed = False
#print('Down stop')
if event.key == ord(','):
... | |
the HTTP port. Must be between 1 and 65535.
:type http_port: int
:param https_port: The value of the HTTPS port. Must be between 1 and 65535.
:type https_port: int
:param origin_host_header: The host header value sent to the origin with each request. If you
leave this blank, the request hostname determines this va... | |
<reponame>tiwarylab/Belief-Propagation
#!/usr/bin/env python
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
from networkx.algorithms import bipartite
import pandas as pd
from sklearn.neighbors import KernelDensity
from sklearn.covariance import GraphicalLasso
import copy
def... | |
FileNotFoundError
def mock_rmtree_ok(*args):
print('called rmtree() with arg `{}`'.format(args[0]))
monkeypatch.setattr(dmlp, '_get_site_id', lambda x: None)
monkeypatch.setattr(dmlp.pathlib.Path, 'exists', lambda x: False)
dmlp.clear_site_data('site_name')
assert capsys.readouterr().out == ''
monkeypatch.setat... | |
+ ielem, :] = ((np.ones((3, ))*(we + ielem)*(n_node_elem - 1)) + np.array([0, 2, 1]))
for inode in range(n_node_elem):
frame_of_reference_delta[we + ielem, inode, :] = [1.0, 0.0, 0.0]
conn[we, 0] = 0
elem_stiffness[we:we + n_elem_section] = 0
elem_mass[we:we + n_elem_section] = 0
we += n_elem_section
wn += n_nod... | |
from __future__ import unicode_literals, division, print_function, absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import object, range, next
import logging
import pickle as pkl
import re
import unicodedata
from copy import deepcopy
import numpy as np
from scipy.spar... | |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Business Applications
# Copyright (C) 2012-2013 OpenERP S.A. (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Af... | |
attr)))
except Exception as e:
skip_dict_pts.update({feature: e.__class__.__name__})
success_list_pts.append(feature)
else:
skip_dict_pts.update({feature:
'Feature {f} was not learned on {d} before, Skip updating'
.format(f=feature, d=self.device)})
log.warning(
'Feature {f} was not learned on {d} before, S... | |
+ c * deg(mpf(131.849)) + cap_F) +
sin_degrees(deg(mpf(119.75)) + c * deg(mpf(131.849)) - cap_F)))
flat_earth = (deg(-2235/1000000) * sin_degrees(cap_L_prime) +
deg(127/1000000) * sin_degrees(cap_L_prime - cap_M_prime) +
deg(-115/1000000) * sin_degrees(cap_L_prime + cap_M_prime))
extra = (deg(382/1000000) *
sin_d... | |
from __future__ import division
import os
# os.chdir('/home/stu/gandahua/MBR/')
#os.chdir('/home/chenchong/Multi_Behavior/')
import numpy as np
import math
import logging
from time import time, sleep
from time import strftime
from time import localtime
from Models import FISM
from Models import MLP... | |
""" Matrix profile anomaly detection.
Reference:
<NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>. (2016, December).
Matrix profile I: all pairs similarity joins for time series: a unifying view that includes motifs, discords and shapelets.
In Data Mining (ICDM), 2016 IEEE 16th International Conference ... | |
> 12 and num_reaveal < 2):
return False
return True
def can_discard(self, t34, hand_ana):
if t34 > 26:
return self._can_discard_chr(t34, hand_ana)
if t34 == self.game_table.last_discard:
return True
if (t34 in self.game_table.last_round_discard or self.turn_num < 7) and not self.game_table.has_reach:
return T... | |
#!/usr/bin/env python
# coding=utf-8
from __future__ import division, print_function, unicode_literals
import h5py
import numpy as np
import six
from brainstorm import layers, Network, initializers
from brainstorm.scorers import (aggregate_losses_and_scores,
gather_losses_and_scores)
from brainstorm.training.trainer... | |
0XFF, 0XFF, 0XFF, 0XFF, 0XC0, 0X00, 0XFF,
0XFF, 0XFF, 0X0F, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF,
0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XF0, 0XFF, 0X0F, 0XFF, 0XFF, 0XFF, 0XFF,
0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0X... | |
removeAliasedValues (enum):
valueByName = {}
for name, value in enum.values:
valueByName[name] = value
def removeDefExtPostfix (name):
for extPostfix in EXTENSION_POSTFIXES:
if endsWith(name, "_" + extPostfix):
return name[0:-(len(extPostfix)+1)]
return None
newValues = []
for name, value in enum.va... | |
#!/usr/bin/python
# coding: utf-8
import json
import pickle
import re
import jieba
import numpy as np
import pandas as pd
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.preprocessing import QuantileTransformer
def max_min_scaler(x):
return (x... | |
self._process_header_lines),
**kwargs)
else:
text_source = textio._TextSource(
file_pattern,
0, # min_bundle_size
compression_type,
True, # strip_trailing_newlines
coders.StrUtf8Coder(), # coder
validate=False,
header_processor_fns=(
lambda x: not x.strip() or x.startswith('#'),
self._process_header_lines),... | |
= "", cancelOnB = "True", layout = "dialogue"):
"""
Generated method for the GBS script action EVENT_MENU.
variable: str with a default value of "L0"
items: int with a default value of "2"
option1: str with a default value of ""
option2: str with a default value of ""
option3: str with a default value o... | |
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version 3.10.0-35-gd79d7781)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
##########################################################################... | |
<filename>build/android/test_runner.py<gh_stars>0
#!/usr/bin/env python
#
# Copyright 2013 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.
"""Runs all types of tests from one unified interface."""
import collections
impor... | |
<reponame>poc11/resqpy
"""A submodule containing grid transmissibility functions"""
# note: only IJK Grid format supported at present
# see also rq_import.py
import logging
log = logging.getLogger(__name__)
import numpy as np
import resqpy.olio.transmission as rqtr
always_write_pillar_geometry_is_defined_array = F... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.