prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2017 Tijme Gommers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to... | OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import requests
from acstis.Payloads import Payloads
from acstis.helpers.BrowserHel... | ctions.TraverseUrlAction import TraverseUrlAction
from acstis.actions.FormDataAction import FormDataAction
from acstis.actions.QueryDataAction import QueryDataAction
from nyawc.http.Handler import Handler as HTTPHandler
class Scanner:
"""The Scanner scans specific queue items on sandbox escaping/bypassing.
At... |
import zeeguu_core
from zeeguu_core.model import Article, Language, LocalizedTopic
session = zeeguu_core.db.session
counter = 0
languages = Language.available_languages()
languages = [Language.find('da')]
for language in languages:
articles = Article.query.filter(Article.language == language).order_by(Article.i... | es done ({percentage}%). last article id: {article.id}. Comitting... ")
session.commit( | )
percentage = (100 * counter / total_articles) / 100
print(f"{counter} dorticles done ({percentage}%). last article id: {article.id}. Comitting... ")
session.commit()
|
from tictactoe import game, player
import unittest
from unittest import mock
class GameTest(unittest.TestCase):
def setUp(self):
self.num_of_players = 2
self.width = 3
self.height = 3
self.game = game.Game(2, 3, 3)
def test_init(self):
self.assertEqual(self.game.board,... | uke', 'x', 'Leia', 'o']
with mock.patch('builtins.input', side_effect=input_seq):
self.game.setup()
expected = [('Luke', 'x'), ('Leia', 'o')]
for e, p in zip(expected, self.game.players):
self.assertEqual(p.name, e[0])
self.assertEqual(p.symbol, e[1])
def... |
self.game.setup()
input_seq = ['2', '5', '3', '1', '9', '6', '7', '4']
with mock.patch('builtins.input', side_effect=input_seq):
self.game.play_round()
finished, winner = self.game.board.finished()
self.assertTrue(finished)
self.assertEqual(winner, 1)
... |
' | ''
'''
from rest_framework import serializers
import models
class PluginSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Plugin
fields = ('id', 'name', )
class ScoredServiceSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.... | ializer):
class Meta:
model = models.Check
fields = ('id', 'key', 'value', 'scored_service')
class TeamSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Team
fields = ('id', 'name', 'services')
class ServiceSerializer(serializers.HyperlinkedModelS... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-14 12:09
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('account', '0005_user_last_... | ,
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='notifications', serialize=False, to=settings.AUTH_USER_MODEL)),
('account_expires', models.BooleanField(default=False, help_text='Accounts are deleted if they | are not used for a year. Warn me a week before mine would be deleted.')),
('gpg_expires', models.BooleanField(default=False, help_text='Warn me a week before any of my GPG keys is about to expire.')),
],
options={
'abstract': False,
},
),
]... |
}
self.module = module
self._connect()
self.domain = None
self.account = None
self.project = None
self.ip_address = None
self.zone = None
self.vm = None
self.os_type = None
self.hypervisor = None
self.capabilities = None
... | one)
self.module.fail_json(msg="zone '%s' not found" % zone)
def get_os_type(self, key=None):
if self.os_type:
return self._get_by_key(key, self.zone)
os_type = self | .module.params.get('os_type')
if not os_type:
return None
os_types = self.cs.listOsTypes()
if os_types:
for o in os_types['ostype']:
if os_type in [ o['description'], o['id'] ]:
self.os_type = o
return self._get_by_... |
import logging
from borgmatic.borg.flags import make_flags, make_flags_from_arguments
from borgmatic.execute import execute_command
logger = logging.getLogger(__name__)
# A hack to convince Borg to exclude archives ending in ".checkpoint". This assumes that a
# non-checkpoint archive name ends in a digit (e.g. from... | -short', repository)
)
output = execute_command(full_command, output_log_level=None, borg_local_path=local_path)
try:
latest_archive = output.strip().splitlines()[-1]
except IndexError:
r | aise ValueError('No archives found in the repository')
logger.debug('{}: Latest archive is {}'.format(repository, latest_archive))
return latest_archive
def list_archives(repository, storage_config, list_arguments, local_path='borg', remote_path=None):
'''
Given a local or remote repository path, a ... |
import datetime
import io
import boto3
import mock
import pytest
import requests
import testfixtures
from botocore.exceptions import ClientError
from opentracing.ext import tags
from opentracing_instrumentation.client_hooks import boto3 as boto3_hooks
DYNAMODB_ENDPOINT_URL = 'http://localhost:4569'
S3_ENDPOINT_URL... | finally:
boto3_hooks.reset_patches()
def assert_last_span(kind, service_name, operation, tracer, response=N | one):
span = tracer.recorder.get_spans()[-1]
request_id = response and response['ResponseMetadata'].get('RequestId')
assert span.operation_name == 'boto3:{}:{}:{}'.format(
kind, service_name, operation
)
assert span.tags.get(tags.SPAN_KIND) == tags.SPAN_KIND_RPC_CLIENT
assert span.tags.g... |
import unittest
from dosbox.filesystem.directory import *
class DirectoryTestCase(unittest.TestCase):
def setUp(self):
self.root_dir = Directory("root")
self.sub_dir1 = Directory("subdir1")
def test_path(self):
self.root_dir.add(self.sub_dir1)
self.assertEqual(self.sub_d | ir1.parent, self.root_dir)
self.assertEqual(self.sub_dir1.path, "root\subdir1")
def test_add_remove(self):
subdir = Directory("subdir")
self.root_dir.add(subdir)
self.assertEqual(subdir.parent, self.root_dir)
self.root_dir.remove(subdir)
self.assertEqual( | subdir.parent, None)
def test_number_of_contained_file_system_item(self):
return NotImplemented |
# -*- coding: utf-8 -*-
# Scrapy settings for saymedia project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'saymedia'
SPIDER_MODULES = ['saymedia.spiders']
N... | DDLEWARES = {
'saymedia.middleware.ErrorConverterMiddleware': 1,
# 'saymedia.middleware.MysqlDownloaderM | iddleware': 1,
'saymedia.middleware.OriginHostMiddleware': 2,
'saymedia.middleware.TimerDownloaderMiddleware': 998,
}
SPIDER_REPORTS = {
'xml': 'saymedia.reports.XmlReport',
'firebase': 'saymedia.reports.FirebaseReport',
}
SPIDER_MIDDLEWARES = {
'scrapy.contrib.spidermiddleware.httperror.HttpError... |
import _plotly_utils.basevalidators
class HistfuncValidator(_plotly_ | utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="histfunc", parent_name="histogram2d", **kwargs):
super(HistfuncValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
va... | max"]),
**kwargs
)
|
from django.http import HttpResponse, JsonResponse
from pa3_web.models import Subscriber
|
#
# Example of a subscription client
#
def delete_subscriber(phone_number):
[sub.delete() for sub in Subscriber.objects.filter(protocol='sms',
identifier=phone_number)]
return HttpResponse( | 200)
def notify(subscriber):
# Send Notifying SMS
return |
#!/usr/bin/env python
import subprocess, os, sys, argparse
parser = argparse.ArgumentParser()
parser.add_argument("directory", help="First target directory for evaluation")
parser.add_argument("directories", nargs='+', help="All other directories to be evaluated")
parser.add_argument("-o", "--output", help="Output des... | commonList = findIdentical(dirs).rstrip()
outputCommon(commonList, outputDir)
def findIdentical(dirs):
prev = None
for index in dirs:
if prev is None:
prev = index
else:
diff = "diff --brief -Nrs %s %s" % (prev, index)
egrepPattern = "^Files .+ and .+ a... | stdout=subprocess.PIPE)
egrepProcess = subprocess.Popen(["egrep", egrepPattern], stdout=subprocess.PIPE, stdin=diffProcess.stdout)
awkProcess = subprocess.Popen(["awk", "-F", awkPattern, "{print($2, \"==\", $3)}"], stdout=subprocess.PIPE, stdin=egrepProcess.stdout)
(out, err) = awkPr... |
"""Taking screenshots inside tests!
If you want to take a screenshot inside your test, just do it like this:
.. code-block:: python
def test_my_test(take_screenshot):
# do something
take_screenshot("Particular name for the screenshot")
# do something else
"""
import fauxfactory
import py... | logger.info(f"Taking a screenshot named {name}")
ss, ss_error = take_browser_screenshot()
g_id = fauxfactory.gen_alpha(length=6)
if ss:
fire_art_test_hook(
item, 'filedump',
| description=f"Screenshot {name}", file_type="screenshot", mode="wb",
contents_base64=True, contents=ss, display_glyph="camera",
group_id=f"fix-screenshot-{g_id}", slaveid=store.slaveid)
if ss_error:
fire_art_test_hook(
item, 'filedump',
... |
import os
import datetime
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'invest.settings')
import django
django.setup()
from myportfolio.models import Investor, Portfolio, AssetClass, STOCKS, BONDS,\
ALTERNATIVES, Security, Transaction, Account
def populate():
investor1 = add_investor(name='David Lim',
... | ss( | owner=investor2,
name='World',
asset_type=STOCKS)
a5 = add_assetclass(owner=investor2,
name='REIT',
asset_type=ALTERNATIVES)
a6 = add_assetclass(owner=investor2,
name='Global Bonds',
ass... |
from django.apps import AppConfig
class Rest | ateConfig( | AppConfig):
name = 'restate'
|
import click
from parsec.cli | import pass_context, json_loads
from parsec.decorators import custom_exception, json_output
@click.command('delete_group_user')
@click.argument("group_id", type=str)
@click.argument("user_id", type=str)
@pass_context
@custom_exception
@json_output
def cli(ctx, group_id, user_id):
"""Remove a user from the given g... | _id, user_id)
|
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST | IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_doak_sif.iff"
result.attribute_template_id = 9
result.stfName("npc_name","human_ba | se_male")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
from a10sdk.common.A10BaseClass import A10BaseClass
class DisablePartitionName(A10BaseClass):
"""Class Description::
.
Class disable-partition-name supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param disable_partition... | L for this object::
`https://<Hostname|Ip address>//axapi/v3/logging/disable-partition-name`.
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.required=[]
self.b_key = "disable-partition-name"
self.a10_url="/axapi/v3/logging/disable-partition-name"
... | ems():
setattr(self,keys, value)
|
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
def make_name(name: st | r) -> str:
# Sample function parameter name in delete_specialist_pool_sample
name = name
return name
|
# Copyright 2006 James Tauber and contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | .getInnerHTML(self.labelElem)
def getName(self):
return DOM.getAttribute(self.inputElem, "name")
def getText(self):
return DOM.getInnerText(self.labelElem)
def setChec | ked(self, checked):
DOM.setBooleanAttribute(self.inputElem, "checked", checked)
DOM.setBooleanAttribute(self.inputElem, "defaultChecked", checked)
def isChecked(self):
if self.isAttached():
propName = "checked"
else:
propName = "defaultChecked"
retur... |
ame of Six Apart Ltd. nor the names of its contributors may
# be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIM... | other
@classmethod
def statefields(cls):
return cls.fields.keys() + ['api_data']
def __getstate__(self):
return dict((k, self.__dict__[k]) for k in self.statefields()
if k in self.__dict__)
def get(self, attr, *args):
return getattr(self, attr, *args)
def __it... | r__(self):
for key in self.fields.keys():
yield key
def to_dict(self):
"""Encodes the DataObject to a dictionary."""
# Start with the last set of data we got from the API
data = deepcopy(self.api_data)
# Now replace the data with what's actually in our object
... |
from collections import OrderedDict
from rest_framework.fields import Field
from ..models import SourceImageIOError
class ImageRenditionField(Field):
"""
A field that generates a rendition with the specified filter spec, and serialises
details of that rendition.
Example:
"thumbnail": {
... | """
def __init__(self, filter_spec, *args, **kwargs):
self.filter_spec = filter_spec
super().__init__(*args, **kwargs)
def to_representation(self, image):
try:
thumbnail = image.get_rendition(self.filter_spec)
return OrderedDict(
[
... | ]
)
except SourceImageIOError:
return OrderedDict(
[
("error", "SourceImageIOError"),
]
)
|
# Copyright (c) 2014 Dark Secret Software Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl | icable law or agreed to in writing, software
# distributed un | der the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import struct
class InvalidVersion(Exception):
pass
class OutOfSync(Exception):... |
ed if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime... | ames.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
| # If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an Ope... |
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2011 Agile Business Group sagl (<http://www.agilebg.com>)
# Copyright (C) 2011 Domsense srl (<http://www.domsense.com>)
#
# This program is free | software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Fre | e Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Gener... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-05-02 15:41
from __future__ import unicode_literals
from django.db import migrations, models
class Migra | tion(migrations.Migration):
dependencies = [
('sponsors', '0005_auto_20160530_1255'),
| ]
operations = [
migrations.AddField(
model_name='sponsor',
name='conference',
field=models.SlugField(choices=[('pycontw-2016', 'PyCon Taiwan 2016'), ('pycontw-2017', 'PyCon Taiwan 2017')], default='pycontw-2017', verbose_name='conference'),
),
]
|
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | """
homepage = "https://github.com/hpc/libhio"
url = "https://github.com/hpc/libhio/releases/download/hio.1.4.1.0/libhio-1.4.1.0.tar.bz2"
#
# We don't include older versions since they are missing features
# needed by current and future consumers of libhio
#
version('1.4.1.0', '6ef5... | efault
#
variant('hdf5', default=True, description='Enable HDF5 support')
depends_on("json-c")
depends_on("bzip2")
depends_on("pkgconfig", type="build")
depends_on('mpi')
#
# libhio depends on hdf5+mpi if hdf5 is being used since it
# autodetects the presence of an MPI and/or uses ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Unit tests for all SQL implementations of spectrum libraries.
"""
from os import path as os_path
import uuid
import unittest
import numpy as np
import fourgp_speclib
class TestSpectrumLibrarySQL(object):
"""
This class is a mixin which adds lots of standard... | value_errors=np.random.random(size),
metadata={"origin": "unit-test",
"x_value": alphabet[x:x + 3]})
self._lib.insert(input_spectrum, "x_{}".format(x))
... | ch for spectra with x in a defined range
my_spectra = self._lib.search(x_value=["dxx", "h"])
x_values_expected = ["efg", "fgh", "ghi"]
filenames_got = [str(item["filename"]) for item in my_spectra]
x_values_got = [str(i["x_value"]) for i in self._lib.get_metadata(filenames=filenames_got)... |
d import tasks_v2beta2
>>>
>>> client = tasks_v2beta2.CloudTasksClient()
>>>
>>> name = client.queue_path('[PROJECT]', '[LOCATION]', '[QUEUE]')
>>>
>>> response = client.resume_queue(name)
Args:
name (str): Required. The queue ... | the client library method.
Returns:
A :class:`~google.cloud.tasks_v2beta2.types.Queue` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.ex | ceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "resume_queue" not in self._inner_api_calls:
se... |
agebox
from PDFManager.PDFMangerFacade import PDFMangerFacade
class PDFManager_UI:
def __init__(self):
self.i= -1;
self.files=[]
self.root = Tk()
self.root.title('PDFManager')
self.root.wm_iconbitmap("ico.ico") #icona
self.frame = Frame(self.root,height=2,bd=2,rel... | ))
self.button_delete.grid(row=1,column=0,columnspan=2,sticky=(W,E))
self.button_clear.grid(row = 2,column=0,columnspan=2,sticky=(W,E))
self.list_file.grid(row=0,column=2,columnspan=3,rowspan=3)
self.frame.grid(row=3,column=0,columnspan=5,sticky=(W,E),pady=5)
| self.button_merge.grid(row=4,column=0,columnspan=2,sticky=(W,E))
self.button_stitching.grid(row=4,column=3,columnspan=2,sticky=(W,E))
self.button_split.grid(row=5,column=0,columnspan=2,sticky=(W,E))
self.button_watermark.grid(row=5,column=3,columnspan=2,sticky=(W,E))
self.button_encri... |
# thesquirrel.org
#
# Copyright (C) 2015 Flying Squirrel Community Space
#
# thesquirrel.org is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any la... | ocation': 'Library',
'bottomliner': 'Santa',
'date': '1/1/2015',
| 'start_time': '18:30',
'end_time': '19:30',
})
assert form.is_valid()
form.save()
class EventRepeatFormTest(TestCase):
def make_form(self, update=False, number=1):
if update:
event = EventFactory(with_repeat=True)
instance = event.repeat... |
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'openwisp2.settings')
from django.core.management import execute_from_command_line
exec | ute_from_c | ommand_line(sys.argv)
|
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
| # SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyPickleshare(PythonPackage):
"""Tiny 'shelve'-like database with concurrency support"""
pypi = "pickleshare/pickleshare-0.7.4.tar.gz"
version('0.7.5', sha256='87683d47965c1da65cdacaf31c8441d12b8044cdec9aca500cd78fc2c683afca')
... | pends_on('py-setuptools', type='build')
depends_on('py-pathlib2', type=('build', 'run'), when='^python@2.6:2.8,3.2:3.3')
|
i])/interval
else:
datum = (float(cur[i]) - float(prev[i]))/interval
data.append(datum)
ds = DiskStat(name=disk, reads_completed=data[0],
reads_merged=data[1],
... | break # no need to look at lines after dirty.
ts = datetime.utcnow().replace(tzinfo=utc)
mi = MemInfo(total=total, free=free, buffers=buffers, cached=cached,
swap_total=swap_total, swap_free=swap_free, active=active,
inactive=inactive, dirty=dirty, ts=ts)
... | pass
def network_stats(self, prev_stats, interval):
interfaces = [i.name for i in NetworkInterface.objects.all()]
cur_stats = {}
with open('/proc/net/dev') as sfo:
sfo.readline()
sfo.readline()
for l in sfo.readlines():
fields = l.spl... |
from django.contrib import admin
from django.utils.translati | on import ugettext_lazy as _
from example.apps.things.models import Thing
class ThingAdmin(admin.ModelAdmin):
fieldsets = (
(None, {
'fields': ('name', 'slug', 'image', 'description'),
}),
(_(u'Dates'), {
'fields': ('created', 'modified'),
'classes': ('... | 'slug')
list_filter = ('created', 'modified')
prepopulated_fields = {'slug': ('name', )}
readonly_fields = ('created', 'modified')
search_fields = ('name', 'slug')
admin.site.register(Thing, ThingAdmin)
|
init_config, agentConfig, instances)
# Initialize a HTTP opener with Unix socket support
socket_timeout = int(init_config.get('socket_timeout', 0)) or DEFAULT_SOCKET_TIMEOUT
UnixHTTPConnection.socket_timeout = socket_timeout
self.url_opener = urllib2.build_opener(UnixSocketHandler())
... | d not instance.get("tag_by_command", False):
return None
if instance.get("new_tag_names", False):
tag_name = self._new_tags_conversion(tag_name)
return "%s:%s" % (tag_name, value.strip())
def _new_tags_conversion(self, tag):
# Prefix tags to avoid conflict with AWS ... | self._get_events(instance)
aggregated_events = self._pre_aggregate_events(api_events, skipped_container_ids)
events = self._format_events(aggregated_events, ids_to_names)
self._report_events(events)
except (socket.timeout, urllib2.URLError):
self.warning('Timeout... |
5,
doc='Maximum energy for fit. Default=0.5')
self.declareProperty(name='BinReductionF | actor', defaultValue=10.0,
doc='Decrease total number of spectrum points by this ratio through merging of '
'intensities from neighbouring bins. Default=1')
self.declareProperty(ITableWorkspaceProperty('ParameterWorkspace', '',
... | tional),
doc='Table workspace for saving TransformToIqt properties')
self.declareProperty(MatrixWorkspaceProperty('OutputWorkspace', '',
direction=Direction.Output,
optional=Pr... |
# -*- coding: utf-8 -*-
from openerp.osv import osv, fields
from openerp.tools.translate import _
import logging
from datetime import dat | etime
from openerp.osv.fields import datetime as datetime_field
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT
from unidecode import unidecode
import types
class pq_thang_luong(osv.osv):
_name = 'pq.thang.luong'
_desc | ription = 'Thang Luong'
_columns = {
'name': fields.char('Tên', size=128, required=True),
'ty_le': fields.float('Tỷ lệ', digits=(16,2)),
'create_date': fields.datetime('Ngày giờ tạo', readonly=True),
'user_id': fields.many2one('res.users', string="Người tạo", readon... |
riable belongs to dataset1 or dataset2.
dataset_pool holds available datasets.
"""
if not isinstance(name, VariableName):
variable_name = VariableName(name)
else:
variable_name = name
short_name = variable_name.get_alias()
if (short_name in... | return self.index2
return None
def attribute_sum(self, name):
"""Return the sum of values of the given attribute.
"""
return (ma.ravel(self.get_attribute(name))).sum()
def attribute_average(self, name):
"""Return the value of the given attribute aver... | """Print a marginal summary of the attributes given in the list 'names'.
"""
print "Summary\t\tsum\t\taverage"
print "------------------------------------------------"
if not isinstance(names,list):
names = [names]
for item in names:
if not (it... |
from django.apps import AppConfig
|
class JcvrbaseappConfig(AppConfig):
| name = 'jcvrbaseapp'
|
from common.utility.utils import FileUtils
default_resource_path = '/Users/Fernando/Develop/downloader'
def get_image(image_hash):
"""
Download huaban image by image hash code.
Such as get_image('3058ff7398b8b725f436c6c7 | d56f60447468034d2347b-fGd8hd')
:param image_hash: Image hash code.
:return: None
"""
# Download normal auto size iamge.
url_normal = f'http://img.hb.aicdn.com/{image_hash}'
FileUtils.save_file(url_normal, f'{default_resource_path}/normal/{image_hash}.jpg')
# Download 236px width size iamg... | le(url_fw236, f'{default_resource_path}/fw236/{image_hash}.jpg')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_yadi
----------------------------------
T | ests for `yadi` module.
"""
import unittest
from yadi | import yadi
class TestYadi(unittest.TestCase):
def setUp(self):
pass
def test_something(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main() |
#!/usr/bin/env python
# File created February 29, 2012
from __future__ import division
__author__ = "William Walters"
__copyright__ = "Copyright 2011, The QIIME Project"
__credits__ = ["William Walters", "Emily TerAvest"]
__license__ = "GPL"
__version__ = "1.8.0-dev"
__maintainer__ = "William Walters"
__email__ = "Wil... | " %
log_data['reverse_primer_not_found'])
def truncate_reverse_primer(fasta_fp,
mapping_fp,
output_dir=".",
truncate_option='truncate_only',
primer_mismatches=2):
""" Main program functi... | option, either truncate_only, truncate_remove
primer_mismatches: Number is mismatches allowed in reverse primer"""
reverse_primers = get_rev_primer_seqs(open(mapping_fp, "U"))
output_fp, log_fp = get_output_filepaths(output_dir, fasta_fp)
log_data = truncate_rev_primers(open(fasta_fp, "U"),
... |
# -*- coding: utf-8 -*-
"""
Unit tests for student optouts from course email
"""
import json
from mock import patch, Mock
from django.core import mail
from django.core.management import call_command
from django.core.urlresolvers import reverse
from django.conf import settings
from student.tests.factories import UserF... | ail view on instructor dashboard
url = reverse('instructor_dashboard', kwargs={'course_id': s | elf.course.id.to_deprecated_string()})
response = self.client.get(url)
email_section = '<div class="vert-left send-email" id="section-send-email">'
# If this fails, it is likely because ENABLE_INSTRUCTOR_EMAIL is set to False
self.assertTrue(email_section in response.content)
@patch... |
"""Represent the :class:`.Trophy` class."""
from typing import TYPE_CHECKING, Any, Dict, Union
from .base import PRAWBase
if TYPE_CHECKING: # pragma: no cover
import praw
class Trophy(PRAWBase):
"""Represent a trophy.
End users should not instantiate this class directly. :meth:`.Redditor.trophies` can... | ta, dict) and "name" in _data
super().__init__(reddit, _data=_data)
def __eq__(self, other: Union["Trophy", Any]) -> bool:
"""Check if two Trophies are equal."""
if isinstance(other, self.__class__):
return self.name == other.name
return super().__eq__(other)
def __... | """
return self.name # pylint: disable=no-member
def __repr__(self) -> str:
"""Return an object initialization representation of the instance."""
return f"{self.__class__.__name__}(name={self.name!r})"
|
ourse_id = entry.course_id
task_input = json.loads(entry.task_input)
module_state_key = task_input.get('problem_url')
student_ident = task_input['student'] if 'student' in task_input else None
fmt = 'Starting to update problem modules as task "{task_id}": course "{course_id}" problem "{state_key}": not... | udent}--access denied?".format(loc=module_state_key,
| student=student)
TASK_LOG.debug(msg)
raise UpdateProblemModuleStateError(msg)
if not hasattr(instance, 'rescore_problem'):
# This should also not happen, since it should be already checked in the caller,
# but check here to be sure.
msg = "Specified problem ... |
#!/usr/bin/python
from pygame import mixer
from threading import Timer
from random import randint
from xml.etree import ElementTree as XmlEt
import argparse
from utils import LOGGER
from sounds import SoundPool
# @brief constrain - constrains x to interval [mi, ma]
def constrain(x, mi, ma):
return min(ma, max(m... | raise ValueError("Volume base +/- drift exceeds boundaries [0.0,1.0]")
# initialize rate
self.newRate()
# initialize sound
self.sound.setVolume(self.base)
# @brief newRate - s | ets new random rate with opposite sign than before
def newRate(self):
if self.rate > 0:
self.rate = -float(randint(self.rate_min, self.rate_max))
else:
self.rate = float(randint(self.rate_min, self.rate_max))
# @brief adaptVolume - adapts the sound volume by 'drift/rate'... |
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | imitations
# under the License.
#
import netaddr
from oslo_config import cfg
from oslo_log import log as logging
from tacker._i18n import _
from tacker.agent.linux import utils as linux_utils
from tacker.common import log
from tacker.vnfm.monitor_drivers import abstract_driver
LOG = logging.getLogger(__name_ | _)
OPTS = [
cfg.IntOpt('count', default=5,
help=_('Number of ICMP packets to send')),
cfg.FloatOpt('timeout', default=5,
help=_('Number of seconds to wait for a response')),
cfg.FloatOpt('interval', default=1,
help=_('Number of seconds to wait between packets')),... |
14.10f}'.format(atom[2]),
'{:14.10f}'.format(atom[3]),
'\n'
)))
f.write('\n')
for atom in elements_in_structure:
f.write('{0} {1}\n'.format(atom,co.CHELPG_RADII... | ).T
# Convert to MacroModel units.
self._hess *= co.HESSIAN_CONVERSION
logger.log(5, ' -- Read {} Hessian.'.format(self._hess.shape) | )
class GaussLog(File):
"""
Used to retrieve data from Gaussian log files.
If you are extracting frequencies/Hessian data from this file, use
the keyword NoSymmetry when running the Gaussian calculation.
"""
def __init__(self, path):
super(GaussLog, self).__init__(path)
self._e... |
from unittest.mock import patch
from superdesk.tests import TestCase
from apps.publish.enqueue.enqueu | e_service import EnqueueService
class NoTakesEnqueueTestCase(TestCase):
def setUp(self):
super().setUp()
self.product_ids = self.app.data.insert(
"products",
[
{"name": "all"},
| ],
)
self.subscriber_ids = self.app.data.insert(
"subscribers",
[
{"name": "digi", "subscriber_type": "digital", "is_targetable": True, "products": self.product_ids},
],
)
self.desk_ids = self.app.data.insert(
"desks",... |
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# Copyright (c) 2014, Arista Networks, Inc.
# 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 reta... | SCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABI... | SUCH DAMAGE.
#
''' The setup script is the center of all activity in building,
distributing, and installing modules using the Distutils. The
main purpose of the setup script is to describe your module
distribution to the Distutils, so that the various commands
that operate on your modules do the right ... |
#!/usr/bin/python
# coding: utf-8
import copy
import json
from lcg import LCG
class Game(object):
def __init__(self, json_file):
super(Game, self).__init__()
with open(json_file) as f:
json_data = json.load(f)
self.ID = json_data["id"]
self.units = [Unit(json_u... | -------"
#print board
#print "Fill lvl: %s" % board.get_fill_level(4)
solution = {}
solution["problemId"] = self.ID
solution["seed"] = ss
solution["tag"] = "Algo v3.1"
solution["solution"] = commands
... | elf.solutions)
def generate_source(self, seed, sourceLength):
source = []
rng = LCG(seed)
for i in range(sourceLength):
unit_nr = rng.next() % len(self.units)
unit = copy.deepcopy(self.units[unit_nr])
source.append(unit)
return source
def __s... |
not produce safe or "
"verifiable files." % link)
self.need_warn_unverified = True
continue
all_locations.append(link)
_egg_fragment_re = re.compile(r'#egg=([^&]*)')
_egg_info_re = re.compile(r'([a-z0-9_.]+)-([a-z0-9_.-]+)... | latform" % link
)
return []
version = wheel.version
if not version:
version = self._egg_info_matches(egg_info, search_name, link)
if version is None:
logger.debug('Skipping link %s; wrong project name (not %s)' % (l... | rmalize_name(search_name).lower() in self.allow_external
and not self.allow_all_external):
# We have a link that we are sure is external, so we should skip
# it unless we are allowing externals
logger.debug("Skipping %s because it is externally hosted." % link)
... |
from django.conf import settings
from django.core.cache import caches
from django.core.cache.backends.db import BaseDatabaseCache
from django.core.management.base import BaseCommand, CommandError
from django.db import (
DEFAULT_DB_ALIAS, connections, models, router, transaction,
)
from django.db.utils import Databa... | ot be created.\nThe error was: %s." %
| (tablename, force_text(e)))
for statement in index_output:
curs.execute(statement)
if self.verbosity > 1:
self.stdout.write("Cache table '%s' created." % tablename)
|
after* there are files:
addon = Addon.objects.get(pk=addon.id)
addon.update(status=addon_status)
return addon
class TestQueue(TestCase):
"""Tests common attributes and coercions that each view must support."""
__test__ = False # this is an abstract test case
def test_latest_version(self):
... | s_are_in_q(self):
self.new_addon('Public', addon_status= | amo.STATUS_PUBLIC,
file_status=amo.STATUS_PUBLIC)
self.new_addon('Nominated', addon_status=amo.STATUS_NOMINATED,
file_status=amo.STATUS_AWAITING_REVIEW)
self.new_addon('Deleted', addon_status=amo.STATUS_PUBLIC,
file_status=amo.STATUS_P... |
# -*- coding: utf-8 -*-
stopwords = """
| A French stop word list. Comments begin with vertical bar. Each stop
| word is at the start of a line.
au | a + le
aux | a + les
avec | with
ce | this
ces | these
dans | with
de | of
des ... | | de + le
elle | she
en | `of them' etc
et | and
eux | them
il | he
je | I
la | the
le | the
leur | their
lui | | him
ma | my (fem)
mais | but
me | me
même | same; as in moi-même (myself) etc
mes | me (pl)
moi | me
mon | my (masc)
ne | not
nos | our (pl)
notre | our
nous | we
on |... |
e_name, get_leave_period
from erpnext.hr.doctype.leave_ledger_entry.leave_ledger_entry import expire_allocation, create_leave_ledger_entry
class OverlapError(frappe.ValidationError): pass
class BackDatedAllocationError(frappe.ValidationError): pass
class OverAllocationError(frappe.ValidationError): pass
class LessAllo... | self.new_leaves_allocated) % 0.5:
frappe.throw(_("Leaves must be allocated in multiples of 0.5"), ValueMultiplierError)
def validate_allocation_overlap(self):
leave_allocation = frappe.db.sql("""
select name from `tabLeave Allocation`
where employee=%s and leave_type=%s and docstatus=1
and to_date >= %s... | to_date))
if leave_allocation:
frappe.msgprint(_("{0} already allocated for Employee {1} for period {2} to {3}")
.format(self.leave_type, self.employee, formatdate(self.from_date), formatdate(self.to_date)))
frappe.throw(_('Reference') + ': <a href="#Form/Leave Allocation/{0}">{0}</a>'
.format(leave_a... |
from PyQt5.QtCore import QThread, pyqtSignal
from API.CurseAPI import CurseAPI, CurseFile, CurseModpack
from PyQt5.QtWidgets import *
from GUI.Strings import Strings
strings = | Strings()
translate = strings.get
class FileDownloaderWindow(QWidget):
def __init__(self, file: str, curse: CurseAPI, path: str, fname=False, callback=False):
super().__init__()
self.callback = callback
self.setWindowTitle(translate("downloading.update"))
self.layout = QVBoxLay... |
self.layout.addWidget(self.progress)
self.show()
self.downloader = FileDownloaderThread(file, curse, path, fname)
self.downloader.done.connect(self.download_done)
self.downloader.update.connect(self.progress.setValue)
self.download_thread = QThread()
self.dow... |
""" Protocol Buffer Breaking Change Detector
This tool is used to detect "breaking changes" in protobuf files, to
ensure proper backwards-compatibility in protobuf API updates. The tool
can check for breaking changes of a single API by taking 2 .proto file
paths as input (before and after) and outputting a bool `is_br... | he breaking change detector to detect rule violations
This method should populate the detector's internal data such
that `is_breaking` does not require any additional invocation | s
to the breaking change detector.
"""
pass
def is_breaking(self) -> bool:
"""Return True if breaking changes were detected in the given protos"""
pass
def get_breaking_changes(self) -> List[str]:
"""Return a list of strings containing breaking changes output by... |
rr.write("\nSearching with values %s result=%s\n" %
(search_params, current_resultset))
sleep(sleeptime)
if current_resultset == None:
continue
if current_resultset == [] and empty_results < CFG_... | result_hitset = current_resultset
if current_operator == '+':
r | esult_hitset = list(set(result_hitset) & set(current_resultset))
elif current_operator == '-':
result_hitset = list(set(result_hitset) - set(current_resultset))
elif current_operator == '|':
result_hitset = list(set(... |
"""
Installs and configures MySQL
"""
import uuid
import logging
from packstack.installer import validators
from packstack.installer import utils
from packstack.modules.ospluginutils import getManifestTemplate, appendManifestFile
# Controller object will be initialized from main flow
controller = None
# Plugin nam... | "LOOSE_VALIDATION": True,
"CONF_NAME" : "CONFIG_MYSQL_PW",
"USE_DEFAULT" : False,
"NEED_CONFIRM" : True,
| "CONDITION" : False },
]
groupDict = { "GROUP_NAME" : "MYSQL",
"DESCRIPTION" : "MySQL Config parameters",
"PRE_CONDITION" : lambda x: 'yes',
"PRE_CONDITION_MATCH" : "yes",
"POST_CONDITION"... |
# Copyright (C) 2013 Go | ogle Inc. 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 conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc.... |
from JumpScale import j
"""
Provides the Params object and the ParamsFactory that is used in the Q-Tree
"""
class ParamsFactory:
"""
This factory can create new Params objects
"""
def __init__(self):
self.__jslocation__ = "j.data.params"
def get(self, dictObject={}):
"""
... | et in the params already
| can further use it as follows:
params.result=infomgr.getInfoWithHeaders(**args)
full example:
#############
args=params.expandParamsAsDict(maxvalues=100,id=None,start="-3d",stop=None)
args["start"]=j.data.time.getEpochAgo(args["start"])
args["stop"]=j.data.time.g... |
import mahotas as mh
from sklearn import cross_validation
from sklearn.linear_model.logistic import LogisticRegression
import numpy as np
from glob import glob
from edginess import edginess_sobe | l
#basedir = 'simple-dataset'
basedir = 'simple-dataset/'
def features_for(im):
im = mh.imread(im,as_grey=True).astype(np.uint8)
return mh.features.haralick(im).mean(0)
features | = []
sobels = []
labels = []
images = glob('{}/*.jpg'.format(basedir))
for im in images:
features.append(features_for(im))
sobels.append(edginess_sobel(mh.imread(im, as_grey=True)))
labels.append(im[:-len('00.jpg')])
features = np.array(features)
labels = np.array(labels)
n = features.shape;
nl = labels.... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright 2016 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.
"""
Builds applications in debug mode:
- Copies the module directories into their destinations.
- Copies app.h... | f hasattr(os, 'symlink'):
if path.exists(dest):
if os.path.islink(dest):
os.unlink(dest)
else:
shutil.rmtree(dest)
os.symlink(join(os.getcwd(), src), dest)
else:
for filename in os.listdir(src):
| new_src = join(os.getcwd(), src, filename)
if os.path.isdir(new_src):
copy_dir(new_src, join(dest, filename))
else:
copy_file(new_src, join(dest, filename), safe=True)
def copy_file(src, dest, safe=False):
if safe and path.exists(dest):
os.re... |
lity(QtCore.Qt.NonModal)
frmIntrodDatos.resize(975, 591)
frmIntrodDatos.setWindowTitle(QtGui.QApplication.translate("frmIntrodDatos", "TopoDelProp. Introducción de datos de: ", None, QtGui.QApplication.UnicodeUTF8))
frmIntrodDatos.setModal(False)
self.tableWidget = QtGui.QTableWidget... | ajo.setObjectName(_fromUtf8("tbId_trabajo"))
self.tbSrc_trabajo = QtGui.QLineEdit(frmIntrodDatos)
self.tbSrc_trabajo.setEnabled(False)
self.tbSrc_trabajo.setGeometry(QtCore.QRect(120, 440, 121, 2 | 2))
self.tbSrc_trabajo.setReadOnly(False)
self.tbSrc_trabajo.setObjectName(_fromUtf8("tbSrc_trabajo"))
self.label_2 = QtGui.QLabel(frmIntrodDatos)
self.label_2.setGeometry(QtCore.QRect(20, 420, 81, 16))
self.label_2.setText(QtGui.QApplication.translate("frmIntrodDatos", "ID ... |
eserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# -----------------------------------------------------------------------... | eCircuitCo | nnectionsOperations(object):
"""PeerExpressRouteCircuitConnectionsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operatio... |
if __name__ == '__main__':
import os
import sys
port = int(sys.argv[1])
root_dirname = os.path.dirname(os.path.dirname(__file__ | ))
if root_dirname not in sys.path:
sys.path.append(root_dirname)
print('before pydevd.settrace')
breakpoint(port=port) # Set up through custom sitecustomize.py
print('after pydevd.settrace')
print('TEST SUCEEDED!')
| |
# -*- coding: utf-8 -*-
# Copyright 2019 OpenSynergy Indonesia
# Copyright 2022 PT. Simetri Sinergi Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
# pylint: disable=locally-disabled, manife | st-required-author
{
"name": "Employee Job Family From Contract",
"version": "8.0.1.0.0",
"category": "Human Resource",
"website": "https://simetri-sinergi.id",
"author": "OpenSynergy Indonesia, PT. Simetri Sinergi Indonesia",
"license": "AGPL-3",
"installable": True,
"depends": [
... | yee_data_from_contract",
"hr_job_family_modelling",
],
"data": [
"views/hr_contract_views.xml",
],
}
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import random
sys.path.append('.')
from twisted.internet import re | actor
from twisted.python import log
from . import driver
from . import multiplexer
from . import record_layer
from . import updater
from . import dsl
from . import conf
EVENT_LOOP_FREQUENCY_S = 0.01
AUTOUPDATE_DELAY = 5
class Client(object):
def __init__(self, format_name, format_version):
self.multip... | oming_ = multiplexer.BufferIncoming()
self.multiplexer_incoming_.addCallback(self.process_cell)
self.streams_ = {}
self.stream_counter_ = random.randint(1,2**32-1)
self.set_driver(format_name, format_version)
self.reload_ = False
# first update must be
reactor.c... |
_order_line or [])))
return res
_columns = {
'website_order_line': fields.one2many(
'sale.order.line', 'order_id',
string='Order Lines displayed on Website', readonly=True,
help='Order Lines to be displayed on the website. They should not be used for computation ... | code != sale_order.pricelist_id.code:
pricelist_ids = self.pool['product.pricelist'].search(cr, SUPERUSER_ID, [('code', '=', code)], context=context)
if pricelist_ids:
pricelist_id = pricelist_ids[0]
request.session['sale_order_code_pricelist_id']... | celist.id
# check for change of partner_id ie after signup
if sale_order.partner_id.id != partner.id and request.website.partner_id.id != partner.id:
flag_pricelist = False
if pricelist_id != sale_order.pricelist_id.id:
flag_pricelist = True
... |
def get_loss(self, loss_function, output, target, aggregation=None):
from lasagne.objectives import Objective
input_layer = self.input_layer(output)
obj = Objective(input_layer, loss_function)
return obj.get_loss(target=target, aggregation=aggregation)
@pytest.fixture
def get_m... | aggregation='mean')
assert result_with_mask.eval() == 1/2.0
result_with_mask = self.get_masked_loss(binary_crossentropy,
output, target, mask_2d,
aggregation='mean')
a... | 0
result_with_mask = self.get_masked_loss(binary_crossentropy,
output, target, mask,
aggregation='normalized_sum')
assert result_with_mask.eval() == 4
result_with_mask = self.get_masked_loss(binary_cr... |
# coding: utf8
from ...symbols import (
ADJ, DET, NOUN, NUM, PRON, PROPN, PUNCT, VERB, POS
)
from ...lemmatizer import Lemmatizer
class RussianLemmatizer(Lemmatizer):
_morph = None
def __init__(self):
super(RussianLemmatizer, self).__init__()
try:
from pymorphy2 import MorphAn... | 'PRTS': 'Brev',
},
'VerbForm': {
'GRND': 'Conv',
'INFN': 'Inf',
'PRTF': 'Part',
'PRTS': 'Part',
'VERB': 'Fin',
},
'Voice': {
'actv': 'Act',
| 'pssv': 'Pass',
},
'Abbr': {
'Abbr': 'Yes'
}
}
pos = 'X'
morphology = dict()
unmatched = set()
grams = oc_tag.replace(' ', ',').split(',')
for gram in grams:
match = False
for categ, gmap in sorted(gram_map.items()):
if gram in... |
xtField')()),
('answer', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)),
))
db.send_create_signal('smartgrid_design', ['DesignerTextPromptQuestion'])
# Adding model 'DesignerQuestionChoice'
db.create_table('smartgrid_design_designerquest... | h=50, null=True, db_index=True)),
('priority', self.gf('django.db.models.fields.IntegerField')(default=1)),
))
db.send_create_signal('smartgrid_ | design', ['DesignerCategory'])
# Adding model 'DesignerAction'
db.create_table('smartgrid_design_designeraction', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=20)),
('slug',... |
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2013 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | tion
is automatically lifted.
The reserved products are substracted from the virtual stock. It means
that if you reserved a quantity of products which bring the virtual
stock below the minimum, the orderpoint will be triggered and new
purchase orders will be generated. It also implies th | at the max may be
exceeded if the reservations are canceled.
Contributors
------------
* Guewen Baconnier <guewen.baconnier@camptocamp.com>
* Yannick Vaucher <yannick.vaucher@camptocamp.com>
""",
'depends': ['stock',
],
'demo': [],
'data': ['view/stock_reserve.xml',
'view/product.xml',
... |
import __settings__
from __settings__ im | port INSTALLED_APPS
assert hasattr(__settings__, 'BASE_DIR'), 'BASE_DIR required'
INSTALLED_APPS += | (
'post',
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=no-self-use, pointless-statement, missing-docstring, invalid-name,len-as-condition
from functools import partial
from rebulk.pattern import StringPattern
from ..validators import chars_before, chars_after, chars_surround, validators
chars = ' _.'
left ... | or=surrounding).matches("xxxword xxx"))
assert len(matches) == 0
matches = list(StringPattern("word", validator=surrounding).matches | ("xxx.wordxxx"))
assert len(matches) == 0
matches = list(StringPattern("word", validator=surrounding).matches("xxx word_xxx"))
assert len(matches) == 1
matches = list(StringPattern("word", validator=surrounding).matches("word"))
assert len(matches) == 1
def test_chain():
matches = list(Strin... |
from iSoft.entity.model import db, FaQuery
import math
import json
from iSoft.model.AppReturnDTO import AppReturnDTO
from iSoft.core.Fun import Fun
import re
class QueryDal(FaQuery):
def __init__(self):
pass
def query_findall(self, pageIndex, pageSize, criterion, where):
relist, is_succ = Fun... | O(True)
# 查看数据
def query_queryByCode(self, code, pageIndex, pageSize, criterion, where):
sql, cfg, msg = self.query_GetSqlByCode(code, criterion, where)
if not msg.IsSuccess:
return sql, msg
relist = db.session.execute(sql)
num = relist.rowcount
relist.close... |
pageSize = 1
if pageSize < 1:
pageSize = 10
# 最大页码
max_page = math.ceil(num / pageSize) # 向上取整
if pageIndex > max_page:
return None, AppReturnDTO(True, num)
pageSql = "{0} LIMIT {1},{2}".format(sql, (pageIndex - 1) * pageSize,
... |
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
import math
import scipy.special as sps
mean = 0
variance = 1
sigma = math.sqrt(variance)
def drawSampleNormal(sampleSize):
samples = np.random.normal(mean, sigma, sampleSize)
count, bins, ignored = plt.hist(samples, 80, normed... | al(500)
alpha = 7.5
beta = 10
def drawSampleGamma(sampleSize):
samples = np.random.gamma(alpha, beta, sampleSize)
count, bins, ignored = plt.hist(samples, 80, normed=True)
pdf = bins**(alpha-1)*(np.exp(-bins/beta) / (sps.gamma(alpha)*beta**alpha))
plt.plot(bins, pdf, linewidth=2, color='r')
plt.... | _samples.png")
plt.clf()
drawSampleGamma(20)
drawSampleGamma(50)
drawSampleGamma(100)
drawSampleGamma(500) |
from io import BytesIO
import os
import pickle
from tempfile import mkstemp
import unittest
from unittest.mock import patch, Mock
import warnings
from Orange.widgets.settings import SettingsHandler, Setting, SettingProvider
class SettingHandlerTestCase(unittest.TestCase):
@patch('Orange.widgets.settings.SettingPr... | tialize.assert_called_once_with(widget, {'default': 42,
'setting': 5})
def test_initialize_component(self):
handler = SettingsHan | dler()
handler.defaults = {'default': 42}
provider = Mock()
handler.provider = Mock(get_provider=Mock(return_value=provider))
widget = SimpleWidget()
# No data
handler.initialize(widget)
provider.initialize.assert_called_once_with(widget, None)
# Diction... |
+xml', QtCore.QByteArray(xml.encode('UTF-8')))
QtGui.QApplication.clipboard().setMimeData(md)
else:
with open(fileName, 'wb') as fh:
fh.write(asUnicode(xml).encode('utf-8'))
xmlHeader = """\
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w... | {}
if root is None:
root = item
## Skip hidden items
if hasattr(item, 'isVisible') and not item.isVisible():
return None
## If this item defines its own SVG generator, use that.
if hasattr(item, 'generateSvg'):
return item.generateSvg(nodes... | ()
if isinstance(item, QtGui.QGraphicsScene):
xmlStr = "<g>\n</g>\n"
doc = xml.parseString(xmlStr)
childs = [i for i in item.items() if i.parentItem() is None]
elif item.__class__.paint == QtGui.QGraphicsItem.paint:
xmlStr = "<g>\n</g>\n"
doc = xml.parseString(xmlStr)
... |
# -*- coding: utf-8 -*-
from Plugins.Extensions.MediaPortal.plugin import _
from Plugins.Extensions.MediaPortal.resources.imports import *
from Plugins.Extensions.MediaPortal.resources.keyboardext import VirtualKeyBoardExt
CONFIG = "/usr/lib/enigma2/python/Plugins/Extensions/MediaPortal/additions/additions.xml"
clas... | NFIG)
for x in conf.getroot():
if x.tag == "set" and x.get("name") == 'additions':
root = x
for x in root:
if x.tag == "plugin":
if x.get("type") == "mod":
if x.get("confcat") == "porn" and x.get("search") == "1":
gz = x.get("gz")
if not config.mediaportal.showgrauzone.value and gz =... | &")+"\", None))")
self.genreliste.sort(key=lambda t : t[0].lower())
self.keyLocked = False
self.ml.setList(map(self._defaultlistcenter, self.genreliste))
def keyOK(self):
if self.keyLocked:
return
auswahl = self['liste'].getCurrent()[0][0]
self.suchString = self.suchString.rstrip()
conf = xml.etree... |
import webipy
import numpy as np
import matplotlib.pyplot as plt |
import pylab
import pandas as pd
pylab.rcParams['figure.figsize'] = (15, 11)
|
@webipy.exports
def plot(x, n=4):
"""
Demo of scatter plot on a polar axis.
Size increases radially in this example and color increases with angle
"""
N = int(x)
r = 2 * np.random.rand(N)
theta = 2 * np.pi * np.random.rand(N)
area = 200 * r**2 * np.random.rand(N)
colors = theta
... |
#!/usr/bin/env python
import os
import sys
PREFIX_DELIMITER = '_'
def enumerate_symbols(symbols_folder_path):
symbols = []
for filename in os.listdir(symbols_folder_path):
parts = os.path.splitext(filename)
if parts[1] == ".svg":
symbols.append(parts[0])
return symbols
def ... | path.isdir(path_to_styles):
print('Invalid path to styles folder')
sys.exit(-1)
target_path = ''
if len(sys.argv) >= 3:
target_path = sys.argv[2]
output_name = os.path.join(target_path, 'local_ads_symbols.txt');
if os.path.exists(output_name):
os.remove(output_name)
... | e-night']
symbols = []
for folder_path in paths:
s = enumerate_symbols(os.path.join(path_to_styles, folder_path, 'symbols-ad'))
if len(symbols) != 0:
symbols.sort()
s.sort()
if symbols != s:
raise ValueError('Different symbols set in folders' +... |
C': 'weight', 'nodeA': 'weight'},
'nodeN': {}}),
]
GRAPHS_ADD_EDGE = [
({'nodeA': {'nodeB': 'weight'},
'nodeB': {'nodeA': 'weight'}},
"nodeX",
"nodeY",
{'nodeA': {'nodeB': 'weight'},
'nodeB': {'nodeA': 'weight'},
'nodeX': {'nodeY': 'weight'},
'nodeY': {}}),
({'node... | {},
'C': {},
'D': {}},
'A',
['A', 'E', 'B', 'D', 'C']),
({'A': {'B': 'weight', 'E': 'weight'},
"B": {'C': 'weight', | 'D': 'weight'},
'E': {},
'C': {'A': 'weight', 'E': 'weight'},
'D': {}},
'A',
['A', 'E', 'B', 'D', 'C']),
({'a': {'b': 'weight', 'g': 'weight'},
'b': {'c': 'weight'},
'g': {'h': 'weight', 'j': 'weight'},
'c': {'d': 'weight'},
'h': {'i': 'weight'},
'j': {'k': ... |
s_key(nonce):
msgcount[redundancy][nonce]["s"] += 1
else:
msgcount[redundancy][nonce] = {}
msgcount[redundancy][nonce]["s"] = 1
msgcount[redundancy][nonce]["r"... | dundancy)s_%(logcontent)s.data"%vars())
for line in file:
if(line[0:2] == logcontent or line[0:3] == logcontent):
info = line.split(" ")
hopnonce = 0
for x in info:
if x[0:2] == "Ho":
hopnonce = int(x.... |
file.close()
for i in xrange(100):
for x in sendList[i]:
recv = 0
for ki in [-11,-10,-9,-1,1,9,10,11]:
if (i+ki >99 or i+ki<0):
continue
elif(i %10 == 0 and (ki == -1 or ki == -11 or ki == 9)):
... |
"""
Routines to compute RMSD of all PROT_IND_ files
These routines were developed by:
Rodrigo Antonio Faccioli - rodrigo.faccioli@usp.br / rodrigo.faccioli@gmail.com
Leandro Oliveira Bortot - leandro.bortot@usp.br / leandro.obt@gmail.com
"""
import os
import sys
from collections import OrderedDict... | o C-alpha C-alpha | @PATH_GROMACS@./g_rms -f @PROT@ -s @NATIVE@ -o temporary_rmsd.xvg 2>/dev/null"
""" This function obtains all pdb files
in mypath
"""
def get_PROT_IND_files_pdb(mypath):
only_pdb_file = []
for root, dirs, files in os.walk(mypath):
for file in files:
#if file.endswith(".pdb"):
if file... | )
only_pdb_file.append(f_path)
return only_pdb_file
def main():
pdb_path = sys.argv[1]
dict_rmsd = {}
all_pdbs = get_PROT_IND_files_pdb(pdb_path)
for pdb in all_pdbs:
aux_command = main_command.replace("@PATH_GROMACS@", path_gromacs).replace("@PROT@",pdb).replace("@NATIVE@", native)
os.system(aux_comm... |
="transfer_mode", state="copy_to_scratch", type="input")
else:
# determine if the file is a root file according to its name
rootFile = self.isRootFileName(lfn)
if prodDBlockToken == 'local' or not rootFile:
directIn = False
... | = "Could not get file size: %s" % str(e)
tolog('!!WARNING!!2999!! %s' % (pilotErrorDiag))
self.__sendReport('FS_FAIL', report)
# remove the local file before any get retry is attempted
_status = self.rem | oveLocal(dest_path)
if not _status:
tolog("!!WARNING!!1112!! Failed to remove local file, get retry will fail")
return error.ERR_FAILEDSIZELOCAL, pilotErrorDiag
loc_filename = lfn
dest_file = os.path.join(path, loc_filename)
# get the checksu... |
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
import json
from intranet.models import User, Project, Part, STATE_CREATED
class Test(TestCase):
@classmethod
def setUpClass(self):
self.c = Client()
Use... | esponse['valid'], False)
response = self.c.get(reverse('api:imputation-list'), {'token_auth': self.token_auth, 'day':3, 'part':self.part.id, 'project': self.project.id})
self.assertEqual(response.status_code,200)
json_response = json.loads(response.content)
self.assertEqual(len(json_res... | project': self.project.id})
self.assertEqual(response.status_code,200)
json_response = json.loads(response.content)
self.assertEqual(len(json_response['imputations']), 0)
#Delete
response = self.c.get(reverse('api:imputation-delete', args=[id_imp]), {'token_auth': self.token_aut... |
# Voitto - a simple yet efficient double ledger bookkeeping system
# Copyright (C) 2010 Santtu Pajukanta <santtu@pajukanta.fi>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | =DEFAULT_BEGIN, end=DEFAULT_END, accounts=None,
events=None):
self.identity = identity
self.version = version
self.name = name
self.begin = begin
self.end = end
self.accounts = accounts if accounts is not None else []
self.events = events if events is ... | ):
def __init__(self, number=None, name="", subaccounts=None, vat_type=None, vat_percent=None):
self.number = number
self.name = name
self.vat_type = vat_type
self.vat_percent = vat_percent
self.subaccounts = subaccounts if subaccounts is not None else []
class Event(object... |
': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'mrn': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'notes': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'pr... | ,
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True' | }),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'md5': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
'modified': ('... |
"""
Django settings for quixotic_webapp project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
i... | ors.debug',
'django.template.context_processors.request',
| 'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'quixotic_webapp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'def... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | rvals from an
underlying schedule representation (e.g. a cron expression, or a timedelta
instance), and schedule a DagRun at the end of each interval.
"""
| _schedule: Schedule
def __eq__(self, other: Any) -> bool:
"""Delegate to the schedule."""
if not isinstance(other, _DataIntervalTimetable):
return NotImplemented
return self._schedule == other._schedule
def validate(self) -> None:
self._schedule.validate()
de... |
# -*- coding: utf-8 -*-
import sys
sys.path.append('../')
import time
import pytest
import os
import telebot
from telebot import types
from telebot import util
should_skip = 'TOKEN' and 'CHAT_ID' not in os.environ
if not should_skip:
TOKEN = os.environ['TOKEN']
CHAT_ID = os.environ['CHAT_ID']
@pytest.mar... | b.send_video(CHAT_ID, file_data)
assert ret_msg.message_id
def test_send_video_more_params(self):
file_data = open('./test_data/test_video.mp4', 'rb')
tb = telebot.TeleBot(TOKEN)
ret_msg = tb.send_video(CHAT_ID, file_data, 1)
assert ret_msg.message_id
def test_send_file... | tb.send_document(CHAT_ID, None)
assert False
except Exception as e:
print(e)
assert True
def test_send_photo(self):
file_data = open('../examples/detailed_example/kitten.jpg', 'rb')
tb = telebot.TeleBot(TOKEN)
ret_msg = tb.send_photo(CHAT... |
# Copy | right (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: miha@reciprocitylabs.com
# Maintained By: miha@reciprocitylabs.com
import random
from tests.ggrc import TestCase
from freezegun import freeze_time
from d... | ggrc import notification
from ggrc.models import NotificationConfig, Notification, Person
from tests.ggrc_workflows.generator import WorkflowsGenerator
from tests.ggrc.api_helper import Api
from tests.ggrc.generator import GgrcGenerator
if os.environ.get('TRAVIS', False):
random.seed(1) # so we can reproduce the ... |
ck to location only for event {}".format(event.key.id()))
geocode_result = cls.google_maps_geocode_async(event.location).get_result()
if geocode_result:
location_info = cls.construct_location_info_async(geocode_result[0]).get_result()
else:
logging.war... | rmatted_address'])), 1.0/3)
else:
score = 0
return score
@classmethod
def update_team_location(cls, team):
if not team.location:
return
# # Try with and without textsearch, pick best
# location_info, score = cls.get_team_location_info(team)
... | # logging.warning("Using textsearch for {}".format(team.key.id()))
# location_info2, score2 = cls.get_team_location_info(team, textsearch=True)
# if score2 > score:
# location_info = location_info2
# score = score2
# # Log performance
# text =... |
#!/usr/bin/env python | 3
delineator = "//"
hashtag = "#"
# generate poems from a file
# out: list of poe | m lines
def generate_poems(filename):
g = []
# get to the first poem in the file
with open(filename, 'r') as f:
for line in f:
line = line.rstrip()
if line.startswith( delineator ) and g:
yield g
g = []
if line:
g.ap... |
import os
ARCH = 'arm'
CPU = 'arm926'
# toolchains options
CROSS_TOOL = 'gcc'
#------- toolchains path -------------------------------------------------------
if os.getenv('RTT_CC'):
CROSS_TOOL = os.getenv('RTT_CC')
if CROSS_TOOL == 'gcc':
PLATFORM = 'gcc'
EXEC_PATH = r'D:\arm-2013.11\bin'
elif CROSS_T... | try __iar_program_start'
LFLAGS += ' --map ' + MAP_FILE
LFLAGS += ' --sil | ent'
EXEC_PATH = EXEC_PATH + '/arm/bin/'
POST_ACTION = 'ielftool --silent --bin $TARGET ' + TARGET_NAME
|
# -*- coding: utf-8 -*-
from __fut | ure__ import unicode_literals, absolute_import
def check_junior(sender, instance, created, **kwargs):
# from .models import Entry # avoid circled import
if created and instance.user.junior:
total_entry = sender.objects.filter(user=instance.user).count()
if total_entry >= 2:
insta... | unior = False
instance.user.save()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.