input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
on the right, the output is to be
# B x N x F (the multiplication is not along the N dimension), so we reshape
# z to be B x N x E x K x F and reshape it to B x N x EKG (remember we
# always reshape the last dimensions), and then make h be E x K x F x G and
# reshape it to EKF x G, and then multiply
y = torch.matm... | |
<filename>contrib/buildbot/server.py
#!/usr/bin/env python3
#
# Copyright (c) 2019 The Bitcoin ABC developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from build import BuildStatus, BuildTarget
from deepmerge import always... | |
'int'},
'test_case_id': {'key': 'testCaseId', 'type': 'int'}
}
def __init__(self, child_suite_id=None, sequence_number=None, suite_id=None, test_case_id=None):
super(SuiteEntry, self).__init__()
self.child_suite_id = child_suite_id
self.sequence_number = sequence_number
self.suite_id = suite_id
self.test_case_... | |
#!/usr/bin/env python
import os
import argparse
import json
import re
import pathlib
import networkx
from jinja2 import Environment, FileSystemLoader
from . import __version__
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
class JsonSchema2Popo:
"""Converts a JSON Schema to a Plain Old Python Object clas... | |
# Copyright 2013 The Swarming Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0 that
# can be found in the LICENSE file.
"""subprocess42 is the answer to life the universe and everything.
It has the particularity of having a Popen implementation that can yield o... | |
2*x/5 + 1, domain='QQ').all_coeffs() == [S(3)/5, S(2)/5, 1]
assert _eq(Poly(3*x**2/5 + 2*x/5 + 1, domain='RR').all_coeffs(),
[0.6, 0.4, 1.0])
assert Poly(3.0*x**2 + 2.0*x + 1, domain='ZZ').all_coeffs() == [3, 2, 1]
assert Poly(3.0*x**2 + 2.0*x + 1, domain='QQ').all_coeffs() == [3, 2, 1]
assert Poly(3.0*x**2 + 2.0... | |
<gh_stars>10-100
"""Algorithms for STRIPS learning that start from the most general operators,
then specialize them based on the data."""
import itertools
from typing import Dict, List, Set
from predicators.src import utils
from predicators.src.nsrt_learning.strips_learning import BaseSTRIPSLearner
from predicators.s... | |
dest, keys, *args):
"""
Store the intersection of sets specified by ``keys`` into a new
set named ``dest``. Returns the number of keys in the new set.
"""
keys = list_or_args('sinterstore', keys, args)
return self.execute_command('SINTERSTORE', dest, *keys)
def sismember(self, name, value):
"Return a boolean i... | |
"""
SQuAD with Bidirectional Encoder Representations from Transformers
=========================================================================================
This example shows how to implement finetune a model with pre-trained BERT parameters for
SQuAD, with Gluon NLP Toolkit.
@article{devlin2018bert,
title={BE... | |
from jira import JIRA
import csv
import codecs
import datetime
options = {'server': '*'}
jira = JIRA(options, basic_auth=("*", "*"))
projects = jira.projects() # list containing all projects
# loop to print all of the projects
for i in projects:
print(i)
print("")
# Clears the CSV file before writing reports to... | |
#!/usr/bin/env python3
# Copyright 2016-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
impo... | |
and -stat_vox mean: <NAME>.; <NAME>.; <NAME>.; <NAME>.; <NAME>. & <NAME>. The
average pathlength map: A diffusion MRI tractography-derived index
for studying brain pathology. NeuroImage, 2011, 55, 133-141
* If using -dixel option with TDI contrast only: <NAME>., Tournier,
J-D., <NAME>., <NAME>. A novel paradigm fo... | |
#!/usr/bin/env python3
"""@@@
program: Constants.py
Creation Date: cr 2017.03~
Last Update: 200416, more refactoring of constants
Version: 1.0
Purpose:
Contains a hodgepodge of constants, labels and indices that that are
often used by various programs. These are uniform, fundamental
definitions that are used in a... | |
xydspec
# text
# primitive
# labelbar
# legend
# cafield
# sffield
# vffield
#
rval = PlotIds()
if (lst[0] is None):
rval.nbase = 0
else:
rval.nbase = len(lst[0])
rval.base = lst[0]
if (lst[1] is None):
rval.ncontour = 0
else:
rval.ncontour = len(lst[1])
rval.contour = lst[1]
if (lst[2] is None):
rval.n... | |
not return control flow."""
self.intermediates.append(
ExpressionIntermediate.Terminal(expression)
)
def pushMove(self, typed_expression):
"""Given a typed expression, allocate space for it on the stack and 'move' it
(copy its bits, but don't inc or decref it)
"""
return self.push(
typed_expression.expr_type,... | |
= t.replace("Pky ", "<NAME> ")
t = t.replace("Ii ", "II ")
t = t.replace("Iii ", "III ")
t = t.replace("Iv ", "IV ")
t = t.replace("Communic ", "Communications ")
t = t.replace("Postdoc ", "Postdoctoral ")
t = t.replace("Tech ", "Technician ")
t = t.replace("Vp ", "Vice President ")
t = t.replace(" @", "/") # r... | |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | |
Default is descend.
Returns:
sorted_boxlist: A sorted BoxList with the field in the specified order.
Raises:
ValueError: if specified field does not exist or is not of single dimension.
ValueError: if the order is not either descend or ascend.
"""
if not boxlist.has_field(field):
raise ValueError('Field ' + f... | |
#!/usr/bin/python
# -----------------------------------------------------------------------------
#
# 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.
# You may obtain a copy of the ... | |
value: pulumi.Input[Union[str, 'ActionType']]):
pulumi.set(self, "action", value)
@property
@pulumi.getter(name="matchConditions")
def match_conditions(self) -> pulumi.Input[Sequence[pulumi.Input['MatchConditionArgs']]]:
"""
List of match conditions.
"""
return pulumi.get(self, "match_conditions")
@match_con... | |
'wavy_dash', 'wavy_dash'),
(b'\xe2\x98\xb8\xef\xb8\x8f', 'wheel_of_dharma', 'wheel_of_dharma'),
(b'\xf0\x9f\xa4\x8d', 'white_heart', 'white_heart'),
(b'\xe2\x97\xbb\xef\xb8\x8f', 'white_medium_square', 'white_medium_square'),
(b'\xe2\x96\xab\xef\xb8\x8f', 'white_small_square', 'white_small_square'),
(b'\xf0\x9f\x8... | |
<filename>tests/orca_unit_testing/test_func_application_rolling.py
import unittest
import orca
import os.path as path
from setup.settings import *
from pandas.util.testing import *
class Csv:
pdf_csv = None
odf_csv = None
class RollingTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
# configure data ... | |
19),
woosh.Token(woosh.OP, '.', 294, 19, 294, 20),
woosh.Token(woosh.NAME, '__class__', 294, 20, 294, 29),
woosh.Token(woosh.OP, ',', 294, 29, 294, 30),
woosh.Token(woosh.NAME, 'self', 294, 31, 294, 35),
woosh.Token(woosh.OP, '.', 294, 35, 294, 36),
woosh.Token(woosh.NAME, '_items', 294, 36, 294, 42),
woosh.Token(woosh... | |
for each line in path up to a limit.
:param path: Path to files containing sentences.
:param limit: How many lines to read from path.
:return: Iterator over lists of words.
"""
with smart_open(path) as indata:
for i, line in enumerate(indata):
if limit is not None and i == limit:
break
yield list(get_tokens(l... | |
testuser
self.client.login(username='testuser_system', password='<PASSWORD>')
# get response
response = self.client.get('/system/' + str(system_1.system_id) + '/')
# compare
self.assertTrue(response.context['dfirtrack_api'])
def test_system_detail_context_without_api(self):
"""test detail view"""
# remove app... | |
<gh_stars>1-10
import hashlib
import hmac
from base64 import b64decode, b64encode
from glob import glob
from io import BufferedIOBase
from os import unlink
from os.path import exists
from pbkdf2 import PBKDF2
from typing import Any, Dict, List, Optional, Tuple
BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcde... | |
& protocol parameters
self.protocol_object.loadParameterPresets()
self.updateParameterPresetSelector(self.serial_grid)
self.updateProtocolParametersInput(self.serial_grid)
self.updateRunParamtersInput(self.serial_grid)
self.show()
def onPressedButton(self):
sender = self.sender()
if sender.text() == 'Record':... | |
s = phrases[i]
if s.level > level:
raise BadIndent(i)
if s.level < level:
return Goto('end', None, i - 1)
if not s.name == 'else' and not s.name == 'elif':
return Goto('end', None, i - 1)
if is_true:
i = skip_block(phrases, i + 1, level + 1) + 1
continue
if s.name == 'else':
goto = yield from gblock(phras... | |
'WARNING',
'process': 'PRODUCER',
'message': 'Could not migrate to new temporary file folder, returning to old one',
'method': 'producer'}
theLogSocket.send(json.dumps(toSend).encode())
theLogSocket.close()
globals.tempfolder = OLDAPATH
session.commit()
return (OLDBPATH, OLDIPATH, OLDAPATH)
def emptyDirectory... | |
order.", date_open.strftime("%Y-%m-%d"), traded_price, date_limit.strftime("%Y-%m-%d"))
order = Order(order_type, symbol_to_buy, num_shares, date_open, traded_price, date_limit, target_up, target_down)
order_target_percent(order, percentage)
#Iterate through positions and see if need to sell any of them on this dat... | |
hex-pose, scale the rot-servo around 90*
l.list[ROT_SERVO] = ((l.list[ROT_SERVO] - 90.) * scale) + 90. # subtract 90, scale, add 90
temp_both.append(pose) # store
# re-split the merged list
left_step = temp_both[:4] # first half
right_step = temp_both[4:] # second half
# begin rotate sequence by lift... | |
"""
Contains backtesting logic and objects.
"""
from __future__ import division
from copy import deepcopy
import bt
import ffn
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import pyprind
def run(*backtests):
"""
Runs a series of backtests and returns a Result
object containing the re... | |
False, 'RequestUID'),
"0031xx45" : ('LT', '1', 'RequestingPhysician', False, 'RequestingPhysician'),
"0031xx50" : ('LT', '1', 'RequestedPhysician', False, 'RequestedPhysician'),
"0033xx10" : ('LT', '1', 'PatientStudyUID', False, 'PatientStudyUID'),
},
'SIEMENS SIENET' : {
"0019xx01" : (u'DS', u'1', u'?', False, u... | |
<reponame>eladrich/pyrallis
import argparse
import dataclasses
import inspect
from logging import getLogger
from typing import Any, Optional, List, Type, Dict, Set, Union, Tuple
from . import docstring
from .wrapper import Wrapper
from .. import utils
logger = getLogger(__name__)
class FieldWrapper(Wrapper[dataclas... | |
<filename>experiment/models/punctuation_domain_model.py
import copy
import math
import logging
import os
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import tarfile
import pytorch_lightning as pl
import torch
import torch.nn.functional as F
from core import ClassificationReport
from co... | |
def get_off_datas(cls):
"""
Instanciate Category class objects,
Then inserts theirs products in database
"""
for i in cf.CATEGORIES:
print("Téléchargement des produits de la catégorie :", i, "...")
i = Category(i)
print("Terminé.")
cls.insert_products_from_category(i)
@classmethod
def check_user(cls, user... | |
self, State s) -> Vec3
Parameters
----------
s: SimTK::State const &
"""
return _simbody.SimbodyMatterSubsystem_calcSystemMassCenterLocationInGround(self, s)
def calcSystemMassPropertiesInGround(self, s):
"""
calcSystemMassPropertiesInGround(SimbodyMatterSubsystem self, State s) -> MassProperties
Paramete... | |
<reponame>ajamtli/DCSLiveryManager
import argparse
import glob
import os
import platform
import sys
from pprint import pprint
from prompt_toolkit import PromptSession, HTML
from prompt_toolkit.completion import NestedCompleter
from rich import box
from rich.align import Align
from rich.console import Console, RenderGro... | |
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2016 <NAME> All rights reserved
# Langstrasse 4, A--2244 Spannberg, Austria. <EMAIL>
# ****************************************************************************
# This module is part of the package GTW.__test__.
#
# This module is licensed under the terms of the BSD 3-Cla... | |
#!/usr/bin/env python3
# -*- encoding: utf-8
# SPDX-License-Identifier: MIT
# Copyright (c) 2021 - 2021, <EMAIL>
__banner__ = r""" (
______ ____ _____ _______ _ _ /\ ____
_ | ____| / __ \ | __ \ |__ __| | | | | |/\| |___ \ _
(_) | |__ | | | | | |__) | | | | |__| | __) | (_)
| __| | | | | | _ / | | | __ | |__ <
_... | |
class Console(object):
""" Represents the standard input,output,and error streams for console applications. This class cannot be inherited. """
@staticmethod
def Beep(frequency=None,duration=None):
"""
Beep(frequency: int,duration: int)
Plays the sound of a beep of a specified frequency and duration throu... | |
<gh_stars>0
"""
A Tkinter UI that allows me to scroll through the images and select regions on the images
that should be tagged by the solution.
"""
# pyright: reportUnknownVariableType=false, reportUnknownMemberType=false
import os
import tkinter as tk
from tkinter import filedialog
from typing import Union
import th... | |
<filename>restware.py
"""
Restware is a plugin for bottle and a piece of middleware (wsgi) to help developers create more guideline-conforming REST APIs using bottle.
.. codeauthor:: <NAME> <<EMAIL>>
Released under the BSD 2-Clause license, http://opensource.org/licenses/BSD-2-Clause
"""
import StringIO
import gzip
i... | |
# this is the camera class which can do the rayCasting and is moved throughout the maze
# inspiration for raycasting from 3d sage's explanation in C : https://www.youtube.com/watch?v=gYRrGTC7GtA&t=423s
# and also inspired from https://lodev.org/cgtutor/raycasting.html
# cmu_112_graphics is from https://www.cs.c... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Module with functions to build plantuml text"""
# Modules
import datamodel
from jarvis.shared_orchestrator import check_type_recursively
from jarvis.question_answer import get_objects_names, check_get_object
from .util import ObjDiagram, StateDiagram, SequenceDiagram
d... | |
def handle_lookup(self, present_map, msg_len, comp_id, comp_id_s):
mm = 'Lookup Response='
self.logger.info('Lookup Request')
if self.config_map is None:
self.logger.info('Unsupported Lookup Request in current Service, Please check your config file')
self.request = b''
self._set_selector_events_mask('r')
... | |
attribute:: interval
AIS transmission interval
**type**\: :py:class:`CfmBagAisInterval <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ethernet_cfm_oper.CfmBagAisInterval>`
.. attribute:: sending_ais
Details of how AIS is being transmitted
**type**\: :py:class:`CfmPmAisTransmit <ydk.models.cisco_ios_xr.Cisco_IOS_X... | |
= "33664717.log"
job_id = 33664717
file_path = "terminated/" + log
ts, r = self.get_trigger_sha_and_repo(job_id)
result = self.dispatcher.analyze(file_path, job_id, trigger_sha=ts, repo=r)
yield self.compare_status, result, "terminated"
def test_python_0(self):
log = '250808150-orig.log'
job_id = 250808150
fi... | |
# Copyright (c) 2018-2019 <NAME> and contributors.
# bibmanager is open-source software under the MIT license (see LICENSE).
__all__ = [
'Bib',
'display_bibs',
'remove_duplicates',
'filter_field',
'loadfile',
'save',
'load',
'export',
'merge',
'init',
'add_entries',
'edit',
'search',
]
import os
import s... | |
<reponame>handsome3163/H2Dgame-Firefly<gh_stars>100-1000
#coding:utf8
'''
Created on 2013-8-21
@author: lan (www.9miao.com)
'''
import itertools
import datetime
def safeunicode(obj, encoding='utf-8'):
r"""
Converts any given object to unicode string.
>>> safeunicode('hello')
u'hello'
>>> safeunicode(2)
u'2'
... | |
== parts[index + 1].lower():
if branch == '' or name != parts[index + 1]:
branch = parts[index + 1]
return True, name, branch
else:
print('ERROR: The label, ' + labelStr + ', does not belong to branch ' + branch + '.')
return False, name, branch
print('ERROR: The label, ' + labelStr + ', does not belo... | |
initialization
of key/val pairs will occur on that instance,
instead of self. Used only when called from
__new__()
:type instance: ExperimentManager
'''
if instance is not None:
self = instance
for file in os.listdir(self.csv_files_path):
path = os.path.join(self.csv_files_path, file)
# Sanity check:
if Pa... | |
<gh_stars>0
import math
import random
from typing import List
import numpy as np
from choreography.choreography import Choreography
from choreography.drone import Drone, slow_to_pos
from choreography.group_step import (BlindBehaviorStep, DroneListStep,
PerDroneStep, StepResult)
from rlbot.agents.base_agent import Sim... | |
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *text* updates
if text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
text.frameNS... | |
<filename>HIVE MIND.py
import datetime
class hivemind:
class mind:
class neurone:
def __init__(self,name,resistance=0,accelerate=0.999,brake=0.999,bayeslearningrate=10):
import random
self.learningrate={}
self.bayeslearningrate=bayeslearningrate
self.inputs={}
self.bias={}
self.bayesbias={}
if is... | |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020 <NAME> <<EMAIL>>
# Copyright (c) 2014 <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without ... | |
method get_corporations_corporation_id_outposts_outpost_id" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'corporation_id' is set
if ('corporation_id' not in params or
params['corporation_id'] is None):
raise ValueError("Missing the required parameter `corporation_id` when callin... | |
<reponame>tmct/statsmodels
# -*- coding: utf-8 -*-
""" Distance dependence measure and the dCov test.
Implementation of Székely et al. (2007) calculation of distance
dependence statistics, including the Distance covariance (dCov) test
for independence of random vectors of arbitrary length.
Author: <NAME>
References
... | |
<filename>src/controller/GameManager.py
import random
#import when running testMain.py in src
from model.Player import Player
#from ..model.Player import Player
from model.card.Sanity import Sanity
#from ..model.card.Sanity import Sanity
from model.card.saneCard import *
#from ..model.card.saneCard import *
from mode... | |
Metadata.update(imdbid, tmdbid)
if r['response'] is True:
return {'response': True, 'message': _('Metadata updated.')}
else:
return r
@cherrypy.expose
@cherrypy.tools.json_out()
def single_movie_details(self, key, value):
''' Gets single movie's details from database
key (str): key for sql.get_movie_details
... | |
<filename>tankobon/ui/gui.py
# coding: utf8
"""
# tankobon {version}
Copyright (c) 2020-2021 <NAME>
Licensed under the MIT License.
star this project at [ongyx/tankobon](https://github.com/ongyx/tankobon) or something, idk
sources:
{supported}
"""
import functools
import pathlib
import signal
import sys
import th... | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
"""This module contains the methods used to deal with BELGraphs."""
import logging
from operator import methodcaller
import networkx as nx
from flask import abort, Response, jsonify, send_file
from flask import current_app
from itertools import combinations
from pybel import co... | |
"chemical_substance"
},
{
"id": "umlscui:C1966623",
"type": "chemical_substance"
},
{
"id": "umlscui:C2961550",
"type": "chemical_substance"
},
{
"id": "umlscui:C0710420",
"type": "chemical_substance"
},
{
"id": "umlscui:C2962545",
"type": "chemical_substance"
},
{
"id": "umlscui:C2962729",
"type": ... | |
from __future__ import print_function
import re
import sys
import itertools
from collections import OrderedDict
from copy import copy
try: # python 3.3+
from inspect import signature, Signature, Parameter
except ImportError:
from funcsigs import signature, Signature, Parameter
try:
from inspect import iscoroutinef... | |
type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized... | |
+ m.b85 <= 0)
m.c47 = Constraint(expr= - m.b42 + m.b86 <= 0)
m.c48 = Constraint(expr= - m.b42 + m.b87 <= 0)
m.c49 = Constraint(expr= - m.b42 + m.b88 <= 0)
m.c50 = Constraint(expr= - m.b42 + m.b89 <= 0)
m.c51 = Constraint(expr= - m.b42 + m.b90 <= 0)
m.c52 = Constraint(expr= - m.b42 + m.b91 <= 0)
m.c53 = Constrain... | |
<reponame>cubed4th/cubed4th-py
#!/usr/bin/env python3
# -*- encoding: utf-8
# SPDX-License-Identifier: MIT
# Copyright (c) https://github.com/scott91e1 ~ 2021 - 2021
__banner__ = r""" (
_ _ ______ ____ _____ _______ _ _
| | | | | ____/ __ \| __ \__ __| | | |
| |_ ___ ___| |_ | |__ | | | | |__) | | | | |__| |
| _... | |
hasattr(self, "target_user_id") and self.target_user_id:
result["targetUserId"] = str(self.target_user_id)
elif include_empty:
result["targetUserId"] = str()
if hasattr(self, "payment_provider") and self.payment_provider:
result["paymentProvider"] = str(self.payment_provider)
elif include_empty:
result["paymentP... | |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Util functions
# @author <EMAIL>
from lxml import etree
from lxml.etree import tostring
from itertools import chain
from nltk.tokenize import wordpunct_tokenize
from random import shuffle
from sklearn import metrics
import numpy
import operator
import pandas
import re
impor... | |
import %r", item)
imports_to_remove = set(find_all_package_nodes(item))
# Remove references between module nodes, as though they would
# not be imported from 'name'.
# Note: Doing this in a nested loop is less efficient than
# collecting all import to remove first, but log messages
# are easier to understand sin... | |
from dataclasses import dataclass
from typing import Any, List
import inspect
import itertools
import warnings
import types
import requests
from flask_discord_interactions.response import Response
class CommandOptionType:
"Represents the different option type integers."
SUB_COMMAND = 1
SUB_COMMAND_GROUP = 2
STR... | |
np.random.gamma(p1,p2) #Where p1 is the shape parameter and p2 the scale parameter.
- ('exponential', p1) = np.random.exponential(p1) #Where p1 is the scale parameter (NOT the rate).
- ('uniform', lower, upper) = np.random.uniform(0,lower,upper)
"""
self._putative_reaction_times, self._putative_reaction_times_dist... | |
# internal data manipulations
import numpy as np # operate on data from the hdf5 file and image generation
import pandas as pd # Data frames from numpy arrays, especially for output
# image generation, manipulation, and analysis
import cv2
from matplotlib import path # dealing with voronoi facets polylines as paths
im... | |
_RecordingFileDurationMeasurement, _First):
name = 'First Recording File Duration'
class FirstRecordingFileEndIndexMeasurement(
_RecordingFileEndIndexMeasurement, _First):
name = 'First Recording File End Index'
class FirstRecordingFileEndTimeMeasurement(
_RecordingFileEndTimeMeasurement, _First):
name = 'Firs... | |
be changed in the current session state"),
content_type='application/xml')
else:
return HttpResponse(createXmlErrorResponse("Grid was not found"),
content_type='application/xml')
else:
return HttpResponse(createXmlErrorResponse("Session was not found"),
content_type='application/xml')
else:
return HttpResponse... | |
<filename>nltk/corpus/reader/util.py
# Natural Language Toolkit: Corpus Reader Utilities
#
# Copyright (C) 2001-2012 NLTK Project
# Author: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
import os
import sys
import bisect
import re
import tempfile
try: impo... | |
#! /usr/bin/python3
#
# Copyright (c) 2020 <NAME> <<EMAIL>>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#... | |
include-stmt as a string.
:rtype: str
'''
return '#include "{0}"'.format(self.items[0])
class Cpp_Macro_Stmt(Base): # 6.10.3 Macro replacement
"""
C99 6.10.3 Macro replacement
macro_stmt is # define identifier [( [identifier-list] ) or (...) ]
[ replacement-list ] new-line
Important: No preceding whitespace... | |
import warnings
warnings.filterwarnings('ignore', module='matplotlib')
import logging
root.setLevel(logging.CRITICAL)
n_volumes = 57
n_runs = 3
min_rest = 3
min_medit = 6
matplotlib.rcParams['figure.facecolor'] = 'white'
matplotlib.rcParams['axes.facecolor'] = 'white'
matplotlib.rcParams['font.size'] = 18
def aran... | |
"QueryID" / Int32ul
)
@declare(guid=guid("5c8bb950-959e-4309-8908-67961a1205d5"), event_id=436, version=0)
class Microsoft_IEFRAME_436_0(Etw):
pattern = Struct(
"QueryID" / Int32ul
)
@declare(guid=guid("5c8bb950-959e-4309-8908-67961a1205d5"), event_id=456, version=0)
class Microsoft_IEFRAME_456_0(Etw):
pattern... | |
<filename>haproxy.py
# haproxy-collectd-plugin - haproxy.py
#
# Author: <NAME>
# Description: This is a collectd plugin which runs under the Python plugin to
# collect metrics from haproxy.
# Plugin structure and logging func taken from
# https://github.com/phrawzty/rabbitmq-collectd-plugin
#
# Modified by "<NAME>" <<E... | |
<reponame>NREL/dgen_globetrotter
# -*- coding: utf-8 -*-
"""
Edited Monday Nov 5, 218
@author: tkwasnik
"""
import pandas as pd
import numpy as np
import decorators
import utility_functions as utilfunc
import config
import os
# GLOBAL SETTINGS
# load logger
logger = utilfunc.get_logger()
@decorators.fn_timer(logger... | |
No | No |
+--------------------------------+-----------+-----------+-----------+-----------+-----------+---------------------+---------------------+----------------+
| pulse_voltage_level_range | Yes | Yes | Yes | Yes | Yes | No | No | No |
+--------------------------------+-----------+-----------+-----------+------... | |
<gh_stars>1000+
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import timeit
import mpld3
from mpld3 import plugins, utils
# Install tabulate using "pip-install tabulate"
from tabulate import tabulate
import os
def clear(): os.system('clear')
# Functio... | |
import abc
import copy
import logging
import time
import weakref
import six
import kafka.errors as Errors
from kafka.future import Future
from kafka.protocol.commit import GroupCoordinatorRequest, OffsetCommitRequest
from kafka.protocol.group import (HeartbeatRequest, JoinGroupRequest,
LeaveGroupRequest, SyncGroupRe... | |
# -*- encoding: utf-8 -*-
# Copyright 2009-2013 Yelp and Contributors
# Copyright 2015-2016 Yelp
#
# 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... | |
"""Evaluation of Wigner-d functions and spin-weighted spherical harmonic functions."""
import numpy as np
import warnings
from numba import njit, prange
from scipy.special import binom, factorial
from .utils import tri_ravel, tri_base, el_block_size
__all__ = [
'spin_spharm_goldberg',
'DeltaMatrix',
'spin_spheri... | |
<gh_stars>0
import numpy as np
import pandas as pd
import pytest
from pandas.testing import assert_frame_equal
# from http://imachordata.com/2016/02/05/you-complete-me/
@pytest.fixture
def df1():
return pd.DataFrame(
{
"Year": [1999, 2000, 2004, 1999, 2004],
"Taxon": [
"Saccharina",
"Saccharina",
"Saccharina",... | |
""" TODO: Module docstring
"""
from copy import copy
from decimal import Decimal
from itertools import repeat
from math import acos
from math import copysign
from math import floor
from math import sqrt
from typing import Iterator
from typing import List
from typing import Tuple
from typing import Union
from astrolib.... | |
ansatz from the cost and mixer Hamiltonians
def qaoa_layer(gamma, alpha):
qaoa.cost_layer(gamma, cost_h)
qaoa.mixer_layer(alpha, mixer_h)
# Creates the actual quantum circuit for the QAOA algorithm
def circuit(params, **kwargs):
for w in wires:
qml.Hadamard(wires=w)
qml.layer(qaoa_layer, n_layers, params[0], p... | |
<reponame>beenfhb/AlphaGo
# -*- coding: utf-8 -*-
"""Tests for sgf.py."""
import unittest
from textwrap import dedent
from betago import gosgf
SAMPLE_SGF = b"""\
(;AP[testsuite:0]CA[utf-8]DT[2009-06-06]FF[4]GM[1]KM[7.5]PB[Black engine]
PL[B]PW[White engine]RE[W+R]SZ[9]AB[ai][bh][ee]AW[fc][gc];B[dg];W[ef]C[comment
on... | |
/
# newpar
if debugging:
print 'add case 1'
newpar.lchild = newnd
newnd.rsib = nd
newnd.par = newpar
nd.par = newpar
tree.root = newpar #bug: should be self.root = newpar?
elif nd == nd.par.lchild:
# nd---x---y newnd---nd
# \\ | / \\ /
# \\ | / --> newpar---x-y
# \\|/ \\ / /
# par par
if debugging:
prin... | |
encrypted, ``1`` othewise
:rtype: int
.. note:: Return-value ``1`` means that ``UndecodableRecordError`` has been implicitely raised
:raises FileNotFoundError: if the specified file does not exist
"""
try:
with open(os.path.abspath(file_path), mode='r') as _file:
with contextlib.closing(
mmap.mmap(
_file.fil... | |
"""Build RESTCONF request from user-provided inputs."""
from collections import OrderedDict
import os
import logging
import re
import json
log = logging.getLogger(__name__)
# Translate edit-op property in a node to an HTTP method
HTTP_METHODS = {
'merge': 'PATCH',
'create': 'POST',
'replace': 'PUT',
'delete': 'DE... | |
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.attach_addon_with_http_info(booking_id, bookingdetail_id, addon_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int booking_id: (required)
:param int booking... | |
<gh_stars>10-100
"""Training script for vision models.
Training, evaluation, and tuning scheme:
1. Use `python train_vision.py [options]` to build, train, and validate models.
2. Logs and model checkpoints will be stored in a unique dir for each specific
run (e.g. .../{model_version}_{datetime}/), within the specifi... | |
<filename>cheshire3/datamining/preParser.py<gh_stars>1-10
from __future__ import absolute_import
import os
import random
import tempfile
import commands
import math
import re
import operator
try:
import cPickle as pickle
except ImportError:
import pickle
from cheshire3.baseObjects import PreParser
from cheshire3.d... | |
<reponame>Mikuana/oops_fhir
from pathlib import Path
from fhir.resources.codesystem import CodeSystem
from oops_fhir.utils import CodeSystemConcept
__all__ = ["v3hl7PublishingSubSection"]
_resource = CodeSystem.parse_file(Path(__file__).with_suffix(".json"))
class v3hl7PublishingSubSection:
"""
v3 Code System ... | |
= val.bitset # pylint: disable=W0201,E0237
return tree
return val
def copy(self, deep=False):
"""Create a copy of this tree."""
if not deep:
return self.__class__(self.label, self)
return self.__class__.convert(self)
def _frozen_class(self):
"""The frozen version of this class."""
return Immutable... | |
is visible,input X:")
datetimeFormat = '%Y-%m-%d %H:%M:%S.%f'
diff =datetime.strptime(str(f_time), datetimeFormat)\
- datetime.strptime(str(time), datetimeFormat)
print("Time difference:")
print(diff)
tofs=TimeDelta(f_time-time)
tofs = TimeDelta(np.linspace(0, 31* u.day, num=1))
# multiply Moon gravity ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.