lang
stringclasses 10
values | seed
stringlengths 5
2.12k
|
---|---|
python | def camel_case_to_lower_case(string: str) -> str:
return re.sub(r"(?<!^)(?=[A-Z])", "_", string).lower()
def get_filename_by_extension(name: str, extension: str) -> str:
lower_case_name = camel_case_to_lower_case(name)
if lower_case_name.endswith("".join(["_", extension])):
return lower_case_name
return "_".join([lower_case_name, extension])
|
python | x, sum = num, 0
while x > 0:
sum += x % 10
x = x // 10
return num % sum == 0
number = int(input())
while 1:
if is_harshad(number):
print(number)
break |
python | new_proposal = Proposal(user_porposed_from=current_user.user_name,
user_porposed_to=meal_request_creater.user_name,
meal_request=current_meal_request)
session.add(new_proposal)
session.commit()
return jsonify(dict(message="Success, created proposal: {}!".format(new_proposal.request_id))),201
else:
return jsonify(dict(message="ERROR, request id {} does already exist".format(proposal_request_id))), 404
@app_endpoints.route('/v1/proposals/<int:id>', methods=['GET', 'POST'])
@require_api_key
|
python | """
URLs to be tested via API requests.
"""
BASE_URL = "https://httpbin.org"
BASIC_AUTH_URL = f"{BASE_URL}/basic-auth"
BEARER_AUTH_URL = f"{BASE_URL}/bearer"
SET_COOKIES_URL = f"{BASE_URL}/cookies/set"
BASE64_URL = f"{BASE_URL}/base64"
|
python | from rdkit.Chem import AllChem
import math
def get_centroid(pdb):
mol = Chem.MolFromMolFile('%s/chem.sdf'%pdb, sanitize=False)
try:
for conf in mol.GetConformers():
centroid = Chem.rdMolTransforms.ComputeCentroid(conf)
x = centroid[0]
y = centroid[1]
z = centroid[2]
return "%s %s %s"%(x,y,z)
|
python | import os
from gooey import *
from Bio.PDB import *
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
# input parameters
@Gooey(required_cols=0, program_name='subset pdb to fasta', header_bg_color= '#DCDCDC', terminal_font_color= '#DCDCDC', terminal_panel_color= '#DCDCDC')
def main():
ap = GooeyParser()
ap.add_argument("-pdb", "--pdb", required=False, widget='FileChooser', help="input pdb file")
ap.add_argument("-dir", "--directory", required=False, type=str, widget='DirChooser', help="directory to search for fasta files")
ap.add_argument("-model", "--model",required=False, default=0, help="model from pdb file to select(integer). Default is 0(1 model only)")
ap.add_argument("-chain", "--chain", required=False, default='A', help="chain from pdb file to select. Default is A")
ap.add_argument("-start", "--start", required=False, default=1, type=int, help="amino acid in chain to start writing the fasta file") |
python | # print type(v)
# print v
#
# v = s.ExampleDict()
# print type(v)
# print type(v.x)
# print v
#
# def isObject(obj): |
python | X_new = np.array([[0],[2]])
X_new_b = np.c_[np.ones((2,1)), X_new]
y_pred = X_new_b.dot(theta)
plt.plot(X_new, y_pred, 'r-')
plt.plot(X,y,'b.')
plt.axis([0,2,0,15])
plt.show()
|
python | sample2 = mock.MagicMock()
sample2.value.count = 2
sample2.value.max = 102
sample2.value.min = 101
sample2.step = 1
sample2.filename = 'filename'
my_reservoir.add_sample(sample1)
my_reservoir.add_sample(sample2) |
python | # Birger move commands block until the move is finished, so if the command has
# returned then the focuser is no longer moving.
self._is_moving = False
self.logger.debug("Moved by {} encoder units".format(moved_by))
return moved_by
##################################################################################################
# Private Methods
##################################################################################################
def _send_command(self, command, response_length=None):
""" |
python | from map import Map
from section import Section
from map_creation_tool import edit_map
if __name__ == "__main__":
map = Map()
map.load_map('map1.json')
done = False
while not done:
done = map.update()
|
python | `apple_dynamic_framework_import` already have their module maps provided to
swift_library targets depending on them. Set this to `False` in that case to
avoid duplicate modules.
""",
),
"out": attr.output(
doc = "The name of the output module map file.",
),
},
doc = "Generates a module map given a list of header files.",
)
# TODO: Revisit. Stardoc generation of this. Stardoc will look at this macro
# instead of the rule above, so it is generating empty documentation for this.
def module_map(name, **kwargs): |
python |
@tag('INT', r'-?\d+')
def mkint(self, s):
return int(s)
|
python | from django.shortcuts import render
from django.http import HttpResponse
from django.forms.models import model_to_dict
from resume.models import Resume
from resume.forms import ResumeForm
from joboard.models import Factory
import logging
logger = logging.getLogger(__name__)
def applysync(request): |
python | format='%(asctime)s,%(levelname)s,%(message)s')
# Read credentials
json_file = open('credentials.json','r')
json_data = json_file.read()
json_object = json.loads(json_data)
# Parse cluster credentials
cluster_address = json_object['cluster_address']
port_number = json_object['port_number']
username = json_object['username'] |
python | assert sorted_list == []
def test_one_no_deps(self):
sort = Sort({'a': []})
sorted_list = sort.sort() |
python | 4. Binary Thresholding ToZero ... \n")
# cv2.namedWindow("Pre-processed", cv2.WINDOW_NORMAL)
# cv2.imshow("Pre-processed", threshed)
# cv2.waitKey()
|
python | def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
audit_log_configs: Optional[pulumi.Input[List[pulumi.Input[pulumi.InputType['IamAuditConfigAuditLogConfigArgs']]]]] = None,
folder: Optional[pulumi.Input[str]] = None,
service: Optional[pulumi.Input[str]] = None,
__props__=None,
__name__=None,
__opts__=None):
"""
Create a IamAuditConfig resource with the given unique name, props, and options.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[List[pulumi.Input[pulumi.InputType['IamAuditConfigAuditLogConfigArgs']]]] audit_log_configs: The configuration for logging of each type of permission. This can be specified multiple times. |
python | def solve(self, node):
head = node
while node and node.next:
later = node.next.next
node.val, node.next.val = node.next.val, node.val
node = later
return head |
python | loader = make_single_loader(data_set, bsz, shuffle)
return loader
def get_loaders(samples_train, samples_val, samples_test, entities, max_len, |
python | random_tensor = keep_prob
random_tensor += random_ops.random_uniform(noise_shape, seed=seed, dtype=x.dtype)
binary_tensor = math_ops.floor(random_tensor)
ret = x * binary_tensor + alpha * (1-binary_tensor)
a = math_ops.sqrt(fixedPointVar / (keep_prob *((1-keep_prob) * math_ops.pow(alpha-fixedPointMean,2) + fixedPointVar)))
|
python | def nightlight(self, to_state=None):
payload = {"ngtlt": to_state}
self.send_cmd(WULGT, payload)
def bedtime(self, to_state):
payload = {"night": to_state}
self.send_cmd(WUNGT, payload) |
python | from apps.mail.views import setup_message_reassignment
from apps.mail.models import MailBox, Attachment
from apps.government.models import Government
from apps.requests.models import Agency, Request, ViewableLink
from apps.contacts.models import Contact
from apps.requests.forms import PubPrivateForm,\ |
python | import time, os
from datetime import datetime, timedelta
#
waittime = 60
if not os.path.isfile('lastupd.txt'): open('lastupd.txt', 'w').write(datetime.now().strftime('%Y-%m-%d'))
while (True):
#날짜 갱신이 안되어있을시 본격적 작업 시작 |
python | "Make the Invisible More Visible",
"Message Passing Leads to Better Scalability in Parallel Systems",
"A Message to the Future",
"Missing Opportunities for Polymorphism",
"News of the Weird: Testers Are Your Friends",
"One Binary",
"Only the Code Tells the Truth",
"Own (and Refactor) the Build",
"Pair Program and Feel the Flow",
"Prefer Domain-Specific Types to Primitive Types",
"Prevent Errors", |
python | full_filename = os.path.join(
os.path.abspath(os.path.dirname(__file__)),
filename)
return open(full_filename, mode='r', encoding='utf-8').read()
long_description = read('README.rst') |
python |
app = flask.Flask(__name__)
message = {
'messsage': "Hello, world!"
}
@app.route('/hello', methods=['GET'])
def hello():
return jsonify(message)
if __name__ == '__main__':
|
python | from app.models.model_base import BareBaseModel
class ClinicHistory(BareBaseModel):
__tablename__ = 'clinic_history'
clinic_id = Column(Integer, ForeignKey("clinic.id"))
history_id = Column(Integer, ForeignKey("history.id"))
clinic = relationship('Clinic', remote_side='Clinic.id')
history_medical = relationship('History', remote_side='History.id')
|
python | def setUp(self):
"""Sets up the needed objects used throughout the test."""
self._resolver_context = context.Context()
test_path = self._GetTestFilePath(['testdir_os'])
self._SkipIfPathNotExists(test_path)
self._os_path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_OS, location=test_path)
self._file_system = os_file_system.OSFileSystem(
self._resolver_context, self._os_path_spec)
self._file_system.Open()
def tearDown(self):
"""Cleans up the needed objects used throughout the test.""" |
python | default_app_config = 'template_supersuper.apps.TemplateSupersuperConfig'
|
python | assert unicode(rv) == 'const std::vector<unsigned int, long>& name'
x = 'std::vector<std::pair<std::string, int>>& module::test(register ' \
'foo, bar, std::string baz="foobar, blah, bleh") const = 0'
assert unicode(parse('function', x)) == x
x = 'module::myclass::operator std::vector<std::string>()'
assert unicode(parse('function', x)) == x |
python | def matches(self) -> int:
base_counts = Counter(self.read_bases)
matches_forward = base_counts["."]
matches_reverse = base_counts[","]
return matches_forward + matches_reverse
def match_ratio(self) -> float:
try:
return self.matches() / self.depth
except ZeroDivisionError:
return 0 |
python | end = row['end']
peak_loc = 1057
allele = row['allele']
seq = fasta_ref.fetch(row['chrom'], start, end).upper()
seq = insert_variant(seq, allele, peak_loc)
if len(seq) != 2114:
continue
sequences.append(seq)
|
python | for x in ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'NOTSET')
])
def __init__(self):
"""Constructor. |
python | import pkg_resources
__version__ = pkg_resources.get_distribution("django_user_accounts").version |
python |
print("Successfully converted epw file to a wea file...")
return wea_file
except:
print("Something went wrong, check the name of the input file...")
|
python | node = self.scenario['nodes'][node_osmid]
# node_id_map[node['id']]=node_osmid
etree.SubElement(node_set, 'node', {
'id': str(node_osmid),
'x': '{:f}'.format(node['x']),
'y': '{:f}'.format(node['y'])
})
node_id += 1
# link_id_map = {}
link_set = etree.SubElement(network, 'links')
# link_id = 0
for link_osmid, link in self.scenario['links'].items():
# link_id_map[str(link['id'])] = link_id |
python | Column,
NVARCHAR,
Integer,
Index,
) |
python | class TestBlockchainMethods(unittest.TestCase):
"""
All unit-testing for the blockchain class exists here
"""
def test_node_registration(self):
blockchain = Blockchain()
self.assertEqual(len(blockchain.nodes), 0)
blockchain.register_node("http://127.0.0.1:9000")
self.assertEqual(len(blockchain.nodes), 1)
def test_create_transaction(self):
blockchain = Blockchain() |
python | import numpy as np
import json
import os
import os.path as osp
import sys
import time
import itertools
import google.protobuf as pb
#import caffe
import matplotlib.pyplot as plt
|
python | if (width > ((width1 + width2) / 2)):
print("r2 does not overlap r1.")
elif ((width < ((width1 + width2) / 2)) and (width > math.fabs(
(width1 - width2) / 2))):
if height > ((height1 + height2) / 2):
print("r2 does not overlap r1.")
elif (height < ((height1 + height2) / 2)) and (height > math.fabs(
(height1 - height2) / 2)):
print("r2 overlap r1.")
elif (height < math.fabs((height1 - height2) / 2)): |
python | self.stoplistLookup = {}
for iiid in trainset.all_items():
self.stoplistLookup[iiid] = False
movieID = trainset.to_raw_iid(iiid)
title = self.ml.getMovieName(int(movieID))
if (title):
title = title.lower()
for term in self.stoplist:
if term in title:
print ("Blocked ", title)
self.stoplistLookup[iiid] = True
def softmax(self, x):
|
python | from pkg_resources import DistributionNotFound, get_distribution
from .data_access import get_monthly_data
from .data_access import preprocessor
from .stats import leadtime_skill_seas_resamp
try:
__version__ = get_distribution(__name__).version
except DistributionNotFound: # pragma: no cover
__version__ = '0.0.0' # pragma: no cover
|
python | ProtocolExtension(ExtensionName.Metadata, "ut_metadata", ExtensionType.Extension, ExtensionProtocolMessageType.Metadata, 0, True)
]
@staticmethod
def get_extension(name):
filtered = [x for x in ProtocolExtensionManager.known_extensions if x.extension_name == name]
if len(filtered) == 1:
return filtered[0]
|
python | instance=push_notification_translation.first()
)
else:
push_notification_translation_form = PushNotificationTranslationForm()
else:
push_notification_form = PushNotificationForm()
push_notification_translation_form = PushNotificationTranslationForm()
return render(
request,
self.template_name,
{
**self.base_context,
"push_notification": push_notification,
"push_notification_form": push_notification_form, |
python | return episode_reward
def main():
env = gym.make('LunarLander-v2') |
python | time.sleep(0.1)
# --------------------------------------------------------------------------
p = None
try:
p = mp.Process(target=proc)
p.start()
# proc should still be alive after 2 seconds
time.sleep(2) |
python | cinst = C()
class C2(object):
abc = 42
def __init__(self):
self.bar = 100
def f(self): pass
c2inst = C2()
l = [1, 2, ]
|
python | ##
# Status constants
#
# enabled | disabled | pending | expired
#
class Status(object):
ENABLED = 'enabled'
DISABLED = 'disabled'
PENDING = 'pending'
EXPIRED = 'expired' |
python | sportsData = fc.readConfig(sessionFiles[f])
searchTS = int(fc.datetime.datetime.strptime(searchString, "%Y-%m-%d").timestamp())*1000
if sportsData["start_time"] >= searchTS:
#print ("Your searchitem was found!")
if searchData["ignoreGPSCheck"] == 0:
if fc.checkfile(dataPath + "/" + configData["gpsFolder"] + fc.os.path.basename(sessionFiles[f])) == 1:
output.write(fc.os.path.basename(fc.os.path.splitext(sessionFiles[f])[0]) + "\n")
validFileCounter = validFileCounter + 1
else:
#print("file ignored -- no gps data")
ignoredFileCounter = ignoredFileCounter + 1
else:
output.write(fc.os.path.basename(fc.os.path.splitext(sessionFiles[f])[0]) + "\n")
validFileCounter = validFileCounter + 1
|
python | from rest_framework.serializers import ModelSerializer
from loan.models import Loan
class LoanSerializer(ModelSerializer):
class Meta:
model = Loan
fields = ('book', 'borrower', 'pk', 'date') |
python | facesOfDice = int(input("Please enter the number of faces you want on your dices, please enter a value below or equal to 6 here : "))
if facesOfDice <= 6:
print("You have", facesOfDice, "faces on your dice(s).")
possibilities = facesOfDice ** numberOfDice
print("For the number of dice you have and faces you gace, there are ", possibilities)
wantedValue = int(input("Please enter the number you want to calculate the numbber of possibilities you have for x amount of dice and faces here : "))
listeOfAllFaces = []
for i in range(1,facesOfDice+1):
listeOfAllFaces.append(i)
numberOfPossibilities = 0 |
python |
from colour.utilities.documentation import (
DocstringFloat,
is_documentation_building,
) |
python | """Produces plots for multiple results files."""
# standard libraries
import argparse
import re
import pickle
import pathlib
import numpy as np
# own libararies
import lib.utils as utils
import lib.plotting as plotting
|
python | def name(self):
return "sentiment"
def _get_output_field(self, text_field):
norm_name = self.model_name.replace("/", "-")
return f"_sentiment_.{text_field}.{norm_name}"
|
python | rl, rr = 0, 0
for i in range(h_end, h_start):
rl += np.sum(step2[i][:int(l_k * i + l_b)]) / 255
rr += np.sum(step2[i][int(r_k * i + r_b):]) / 255
sl = np.sum(step2[h_end:h_start, :640 - gap]) / 255 - rl
sr = np.sum(step2[h_end:h_start, 640 + gap:]) / 255 - rr
realthr_common = int(max(max(sl, sr) * thr_common_base, thr_common_min))
state = 0 if abs(sl - sr) < realthr_common else 1 if sl < sr else 2
is_pesd = False
print(thr_pesd_area, sl, sr)
if sl > thr_pesd_area and sr > thr_pesd_area:
is_pesd = True
if rr < thr_pesd_force:
state = 1 |
python | class WebSocket:
def __init__(self, url:str):
self.cls = aiohttp.ClientSession()
self.url = url |
python | """
All available quest objectives.
"""
def __init__(self):
# finish a dialogue, object: dialogue_id
self.dict = {
defines.OBJECTIVE_TALK: {
"name": _("Talk to someone. (The object is the NPC's key.)", category="quest_objective")
},
# arrive a room, object: room_id
defines.OBJECTIVE_ARRIVE: { |
python | "Programming Language :: Python",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
],
packages = ['parrot'],
platforms = 'any',
keywords='oauth2 oauth web framework',
author=parrot.__author__,
author_email=parrot.__author_email__,
url=parrot.__url__,
license=parrot.__license__,
include_package_data=True,
zip_safe=False,
entry_points = {
|
python | assert isinstance(egg.get_pres_features(), pd.DataFrame)
def test_egg_get_rec_items():
assert isinstance(egg.get_rec_items(), pd.DataFrame)
def test_egg_get_rec_items_cat(): |
python | claims = jwt.decode(id_token, 'k', claims_options=claims_options)
self.assertRaises(
errors.InvalidClaimError,
claims.validate
)
def test_validate_custom(self): |
python | def text_content(text_path: str) -> str:
with open(text_path, encoding="utf-8") as text_file:
return text_file.read()
class DataError(Exception):
def __init__(self, path: str, message: str, line_number: Optional[int] = None): |
python | #!/usr/bin/python3
import argparse
import cv2
import math
import os
import random
import numpy as np
import matplotlib.pyplot as plt
import clustering
|
python | from django.contrib.auth.models import User
from main.models import Neighborhood
class Profile(models.Model):
'''
class for user profiles
'''
user = models.OneToOneField(User,on_delete=models.CASCADE)
id_number = models.IntegerField(blank=True,null=True)
profile_picture = models.ImageField(default="default.jpg",upload_to='profile_pics')
bio = models.TextField() |
python | if i == 0:
continue
Y_PRED.append(row[1])
# Y_TRUE = Y_TRUE[:10] |
python | # Example objects for pickling.
from persistent import Persistent
def print_dict(d):
d = sorted(d.items())
print('{%s}' % (', '.join(
[('%r: %r' % (k, v)) for (k, v) in d]
)))
def cmpattrs(self, other, *attrs): |
python | model_name='biharapidemographics',
name='last_class_attended_ever',
field=models.SmallIntegerField(null=True),
),
migrations.AddField(
model_name='biharapidemographics',
name='out_of_school_status',
field=models.SmallIntegerField(null=True),
), |
python |
# 2. get sorted ids (old->new)
r = cartosql.getFields('cartodb_id', table, order='{}'.format(time_field),
f='csv')
ids = r.text.split('\r\n')[1:-1]
# 3. delete excess
if len(ids) > max_rows:
r = cartosql.deleteRowsByIDs(table, ids[:-max_rows])
num_dropped += r.json()['total_rows']
if num_dropped: |
python | if result_ndim > 0:
result_type = result_dtype[(slice(None),) * result_ndim]
elif result_ndim == 0:
result_type = result_dtype
else:
result_type = object_ |
python |
Note that we are doing weighted loss that only sum up over non-zero entries.
Args:
input_tensor: input tensor
target_tensor: target tensor
weight: weight tensor, in this case 1/sigma^2
Returns:
the weighted MSE loss
"""
observation_dim = input_tensor.size()[-1]
streched_tensor = ((input_tensor - target_tensor) ** 2).view(
-1, observation_dim) |
python |
self.maximum = max(self.maximum, value)
self.minimum = min(self.minimum, value)
def normalize(self, value: float) -> float:
# If the value is unknow, by default we set it to the minimum possible value
if value is None:
return 0.0
if self.maximum > self.minimum:
# We normalize only when we have set the maximum and minimum values.
return (value - self.minimum) / (self.maximum - self.minimum)
return value
|
python | import cv2
video = cv2.VideoCapture('pedestrain_5.mp4')
# pre trained car classifier
car_tracker_file = 'car_detector.xml'
pedestrian_tracker_file = 'pedestrian_tracking.xml'
# create car classifier
car_tracker = cv2.CascadeClassifier(car_tracker_file)
pedestrian_tracker = cv2.CascadeClassifier(pedestrian_tracker_file)
while True:
(read_successful, frame) = video.read() |
python | # 2017, after channel delays corrections
cms.PSet(
validityRange = cms.EventRange("301418:min - 301517:max"),
centralOOT = cms.int32(1),
),
# 2017, after channel delays corrections
cms.PSet(
validityRange = cms.EventRange("301518:min - 9999999:max"), |
python |
class CustomHead(PredictionHead):
def __init__(
self,
model,
head_name,
**config,
):
super().__init__(head_name)
self.config = config
self.build(model=model)
def forward(self, outputs, cls_output=None, attention_mask=None, return_dict=False, **kwargs):
logits = super().forward(outputs[0]) |
python | """Executes a command cmd as root; returns bytes, bytes."""
(out, err) = subprocess.Popen("/system/bin/su -c '{0}' && exit &".format(cmd), stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True).communicate()
if err:
(out, err) = subprocess.Popen("/system/xbin/su -c '{0}' && exit &".format(cmd), stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True).communicate()
return out, err
def get_current_time():
"""Retrieves the current time; returns float."""
return time.time()
def check_aapt_aopt(): |
python | """
* `x` is the input embedding tensor $X$ of shape `[seq_len, batch_size, d_model]`
* `mask` is a boolean mask of shape `[seq_len, seq_len, 1]` that controls the visibility of tokens
among each other.
"""
# Keep a copy for shortcut connection
shortcut = x |
python | sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error
cef.Initialize()
cef.CreateBrowserSync(url=url_target,
window_title=title)
cef.MessageLoop()
cef.Shutdown()
def check_versions():
print("[cefwindow.py] CEF Python {ver}".format(ver=cef.__version__))
print("[cefwindow.py] Python {ver} {arch}".format(
ver=platform.python_version(), arch=platform.architecture()[0])) |
python | # lower and upper shall be specified.
if (to_upper(code_point) != code_point
and not (is_lower(code_point) or is_upper(code_point))):
sys.stderr.write(
('%(sym)s is not upper|lower '
+ 'but toupper(0x%(c)04X) = 0x%(uc)04X\n') %{
'sym': ucs_symbol(code_point), |
python | command=['get-obj', 'arg1', 'arg2', '&', 'as-bool', 'True',
'--', '--separator', '&']),
True)
self.assertEqual(
fire.Fire(tc.ReturnsObj, |
python | dependencies = [
('photograph', '0011_auto_20200720_1538'),
]
operations = [
migrations.AlterField(
model_name='photograph', |
python | <gh_stars>1-10
# Space : O(n)
# Time : O(n**2)
class Solution:
def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: |
python | load_plugins(
settings.PLUGINS,
settings.INSTALLED_APPS,
settings.PLUGINS_CONFIG,
settings.VERSION,
settings.MIDDLEWARE,
settings.CACHEOPS,
)
|
python | # coding=utf-8
'''Developed by Jakub21 in June 2018 under MIT License.
Python version: 3.6.5
Start Editor in debug mode
'''
from src.main import main
main(True) |
python | from test_junkie.metrics import ClassMetrics, TestMetrics, Aggregator
from test_junkie.compatability_utils import CompatibilityUtils as CU
class _FuncEval:
@staticmethod
def eval_skip(obj):
val = obj.get_skip()
try:
if not isinstance(val, bool): |
python | @pytest.fixture
def right():
return pd.Series([
"NARINO",
"Amazonas",
"Choco",
"<NAME>", |
python |
Returns:
allocation (p numpy array): Percent of capital to keep in one asset
returns (float): The return of the given allocation on historical
the data
''' |
python | logger = getlogger()
whitelist = ['found legacy entry', "doesn't match", 'reconciling nodeReg',
'missing', 'conflicts', 'matches', 'nodeReg',
'conflicting address', 'unable to send message',
'got error while verifying message']
|
python | from .handlers import handler_dispatch
class Flow(flow_pb2_grpc.FlowDaemon):
def ApplyWorkflow(self, request, context):
return handler_dispatch('apply', request, context)
def DeleteWorkflow(self, request, context):
return handler_dispatch('delete', request, context) |
python | message = data.encode()
with self._send_lock:
self._socket.sendall(struct.pack('!I', len(message)))
self._socket.sendall(message)
def recv_msg(self) -> str:
try:
length, = struct.unpack('!I', self._recvall(4))
return self._recvall(length).decode()
except timeout:
raise TimeoutError()
def _recvall(self, count: int) -> bytes: |
python | if not data_dir:
raise ("'data_dir' is needed")
if os.path.exists(data_dir):
os.rmdir(data_dir)
command = 'screen -S node{} -d -m {}'.format(self.node_num, self.node_path)
command += ' --data-dir {} --create-genesis-json'.format(data_dir)
subprocess.Popen(command, shell=True)
return '{}/genesis.json'.format(data_dir) |
python | :param d: A dict-like object
:return: True if ALL values exist in keys; False if NOT ALL values exist in keys
"""
return all(_ in dict(d) for _ in values)
def any_in_dict(
values: Iterable[Any], d: Union[Dict[Any, Any], TxData, TxParams]
) -> bool:
"""
Returns a bool based on whether ANY of the provided values exist among the keys of the provided
dict-like object.
:param values: An iterable with values to look for within the dict-like object
:param d: A dict-like object |
python |
from books_app.books.views import index, create_book, update_book
urlpatterns = (
path('', index, name='index'),
path('create/', create_book, name='create_book'),
path('update/<int:pk>', update_book, name='update_book'),
) |
python | self.driver.find_element_by_xpath('//*[@id="app"]/div/div/div/div/form/fieldset/fieldset[2]/input').clear()
self.driver.find_element_by_xpath('//*[@id="app"]/div/div/div/div/form/fieldset/fieldset[2]/input').send_keys(row['About'])
self.driver.find_element_by_xpath("//textarea[@placeholder='Write your article (in markdown)']").clear()
self.driver.find_element_by_xpath("//textarea[@placeholder='Write your article (in markdown)']").send_keys(row['Content'])
self.driver.find_element_by_xpath("//input[@placeholder='Enter tags']").send_keys(row['Tag']) |
python | # load from local.
if os.path.exists(self.diff_result_path):
with open(self.diff_result_path) as read_file:
compare_result = json.load(read_file)
else:
# local file not exist
return
else:
# If the compare result is not crawled, start to crawl. |
python | # Labels ...
main_ax.set_xlabel('X [mm]')
main_ax.set_ylabel('Y [mm]')
top_ax.set_ylabel('Intensity [a.u.]')
right_ax.set_xlabel('Intensity [a.u.]')
#plot ...
main_ax.pcolormesh(F.xvalues/mm, F.yvalues/mm, I0)
main_ax.axvline(Xc/mm, color='r')
main_ax.axhline(Yc/mm, color='g')
main_ax.add_patch(patches.Ellipse((Xc/mm, Yc/mm), sx/mm, sy/mm, fill=False, lw=1,color='w', ls='--'))
right_ax.plot(I0[:,NXc],F.yvalues/mm, 'r-', lw=1) |
python | elif (nums[mid] < target):
left = mid + 1 # target 在右区间,[mid + 1, right)
else: # nums[mid] == target
return mid
# 目标值在所有元素之前:return right
# 目标值等于数组中的某一个元素: return mid
# 目标值插入数组中的位置: return right
# 目标值在所有元素之后: return right
return right
|
python | from lxml import html
class Document:
def __init__(self, url, user_agent, timeout=10):
self.url = url
self.user_agent = user_agent |
python | <gh_stars>0
"""
Slixmpp: The Slick XMPP Library
Copyright (C) 2013 <NAME>, <NAME>
This file is part of slixmpp.
See the file LICENSE for copying permission.
"""
from slixmpp.plugins.google.nosave import stanza
from slixmpp.plugins.google.nosave.nosave import GoogleNoSave
|
python |
master = frb_master.FRBMaster()
click.echo(f"Backend: {master.version()}")
for job in range(jobs):
response = master.swarm.spawn_job(
job_name=f"subpulse-toa-{event}-{job}",
image_name="chimefrb/subpulse",
command=["python"],
arguments=[ |
python | self.value = value
def __lt__(self, other):
"""Return True if this object is strictly less than the specified
object; False, otherwise. |
Subsets and Splits