prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
from __future__ import absolute_import
import logging
from requests.exceptions import RequestException
from sentry import options
from sentry.http import Session
f | rom sentry.lang.native.utils import sdk_info_to_sdk_id
MAX_ATTEMPTS = 3
logger = logging.getLogger(__name__)
def lookup_system_symbols(symbols, sdk_info=None, cpu_name=None):
"""Looks for system symbols in the configured system server if
enabled. If this failes or the server is disabled, `None` is
retu... | sess = Session()
symbol_query = {
'sdk_id': sdk_info_to_sdk_id(sdk_info),
'cpu_name': cpu_name,
'symbols': symbols,
}
attempts = 0
with sess:
while 1:
try:
rv = sess.post(url, json=symbol_query)
# If the symbols server doe... |
# ./_qdt.py
# -*- coding: utf-8 -*-
# PyXB bindings for NM:763e66503f6e9797a3b5522270417bad82c9c82c
# Generated 2015-02-11 21:35:49.975 | 995 by PyXB version 1.2.4 using Python 2.6.9.final.0
# Namespace urn:oasis:names:specification:ubl:schema:xsd:QualifiedDataTypes-2 [xmlns:qdt]
from __future__ import unicode_literals
import pyxb
import pyxb.binding
import pyxb.binding.saxer
import io
import pyxb.utils.utility
import pyxb.utils.domutils
import sys
impo... | er('urn:uuid:2b2e2fd1-b225-11e4-b26c-14109fe53921')
# Version of PyXB used to generate the bindings
_PyXBVersion = '1.2.4'
# Generated bindings are not compatible across PyXB versions
if pyxb.__version__ != _PyXBVersion:
raise pyxb.PyXBVersionError(_PyXBVersion)
# Import bindings for namespaces imported into sche... |
import boto3
import logging |
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logger.info("RECEIVED EVENT: %s"%( str( event )) )
params = event['params']
sid = params['MessageSid' | ]
from_number = params['From']
to_number = params['To']
body = params['Body']
logger.info("RECEIVED MESSAGE SID: %s, FROM: %s, TO: %s, BODY: %s" % ( sid, from_number, to_number, body))
client = boto3.client('dynamodb')
client.put_item(TableName="sms_messages", Item={
"sid": {'S': sid},
... |
from django.contrib im | port admin
# Register your models here.
from .models imp | ort Uploader
admin.site.register(Uploader)
|
artifact = u"Artifact"
creature = u"Creature"
enchantment = u"Enchantment"
land = u"Land"
planeswalker = u"Planeswalker"
instant = u"Instant"
sorcery = u"Sorcery"
permanents = frozenset({artifact, creature, enchantment, land, planeswalker})
nonpermanents = frozenset({instant, sorcery})
all = permanents | nonpermanen... | "Equipment", u"Fort | ification"}),
creature : frozenset({
u"Advisor", u"Ally", u"Angel", u"Anteater", u"Antelope", u"Ape",
u"Archer", u"Archon", u"Artificer", u"Assassin", u"Assembly-Worker",
u"Atog", u"Aurochs", u"Avatar", u"Badger", u"Barbarian", u"Basilisk",
u"Bat", u"Bear", u"Beast", u"Beeble", u"Ber... |
import urllib2
import base64
import simplejson as json
import logging
from urllib import urlencode
from functools import partial
log = logging.getLogger(__name__)
log_formatter = logging.Formatter('%(name)s - %(message)s')
log_handler = logging.StreamHandler()
log_handler.setFormatter(log_formatter)
log.addHandler(lo... | g.ERROR)
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
urllib2.install_opener(opener)
class EndPointPartial(partial):
| def __new__(cls, func, conf, _repr):
cls._repr = _repr
return super(EndPointPartial, cls).__new__(cls, func, conf)
def __repr__(self):
return unicode('<API endpoint %s>' % self._repr)
class CampBX(object):
"""Camp BX API Class"""
username = None
password = None
api_url ... |
#This script is made by cotax
#cotax is blenderartists.org user's nickname.
#1. Place a lamp in the scene and put its energy to 0.0
#2. | Connect this script to the lamp, always(true)- python
#- Add a property: energy(float) to the lamp
#- Add a property: distance(integer) to the lamp
#Set the energy and distance to your likings
from bge import logic
own = logic.getCurrentController().owner
cam = own.scene.active_camera
#get the distance ... | own['energy']
#check distance and set the energy
if own.getDistanceTo(cam) < distance:
own.energy = energy
else:
own.energy = 0.0 |
import matplotlib.pyplot as plt
from collections import defaultdict
from itertools import combinations
from pprint import pprint
from scipy import stats
import random
from itertools import chain
import results
def choose_points(qr_list):
return [d.total_response() - getattr(d, 'median', 0) for d in qr_list]
de... | 1]),
choose_points(data[k2]))
print k1, k2, d, p
if p < p_threshold:
data_roundup[k1] += 1
data_roundup[k2] += 1
return dict(data_roundup)
data = results.read_data(bucket=r'^/api/\w{3}(\w)\w{6}/config$',
data_dir='more_... | unclear = 0
shortened = []
shorten_error = 0
ANSWER = '0'
for x in range(1000):
print "Iteration: ", x
res = check_data(data)
if not res:
unclear += 1
continue
if ANSWER not in res.keys() and max(res.values()) >= 4:
pprint(res)
print "shorten error"
shorten_error ... |
gene_num++;
if (f00 == 0 && gene > 0) fld_new[xp1 * h + y] += ({1} << 17);
if (gene > 0) genes_count--;
if (genes_count <= 0) break;
}
if (seed > 0) seed--;
if (seed == ... | = step; else blue = 0;
return blue + (green << 8) + (red << 16);
}
__device__ uint h | sv2rgb(int hue, int sat, int val) {
float r, g, b;
float h, s, v;
h = hue;
s = fmin(255, (float) sat);
s /= 255;
v = fmin(255, (float) val);
float f = ((float) h) / 60.0f;
float hi = floorf(f);
f = f - hi;
int p = (int) (v * (1 - s));
int q = (int) (v * (1 - s * f));
int t = (int) (v * (1 - s * (... |
# python
# This file is generated by a progra | m (mib2py).
import HP_SN_IGMP_MIB
OIDMAP = {
'1.3.6.1.4.1.11.2.3.7.11.12.2.6.1': HP_SN_IGMP_MIB.snIgmpMIBObjects,
'1.3.6.1.4.1.11.2.3.7.11.12.2.6.1.1': HP_SN_IGMP_MIB.snIgmpQueryInterval,
'1.3.6.1.4.1.11.2.3.7.11.12.2.6.1.2': HP_SN_IGMP_MIB.snIgmpGroupMembershipTime,
'1.3.6.1.4.1.11.2.3.7.11.12.2.6.1.3.1.1': HP_SN_I... | IfPortNumber,
'1.3.6.1.4.1.11.2.3.7.11.12.2.6.1.3.1.3': HP_SN_IGMP_MIB.snIgmpIfGroupAddress,
'1.3.6.1.4.1.11.2.3.7.11.12.2.6.1.3.1.4': HP_SN_IGMP_MIB.snIgmpIfGroupAge,
}
|
from django.contrib import admin
from models import Page, TPage, Content, TContent
class PageAdmin(admin.ModelAdmin):
exclude = ['posted']
#fields = ['posted', 'title']
list_display = ('title', 'posted', 'slug')
prepopulated_fields = {'slug': ('title',)}
class TPageAdmin(admin.ModelAdmin):
list_di... | anguage', 'page')
#prepopulated_fields = {'slug': (' | title',)}
admin.site.register(Page, PageAdmin)
admin.site.register(TPage, TPageAdmin)
admin.site.register(Content, ContentAdmin)
admin.site.register(TContent, TContentAdmin)
|
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
def readfile(fn):
"""Read fn and return the contents."""
with open(path.join(here, fn), "r", encoding="utf-8") as f:
return f.read()
setup(
name="usfm2osis",
... | ers | ion="0.6.1",
description="Tools for converting Bibles from USFM to OSIS XML",
author="Christopher C. Little",
author_email="chrisclittle+usfm2osis@gmail.com",
url="https://github.com/chrislit/usfm2osis",
download_url="https://github.com/chrislit/usfm2osis/archive/master.zip",
keywords=["OSIS", "... |
import heapq
import os
import numpy
from smqtk.algorithms.nn_index.hash_index import HashIndex
from smqtk.utils.bit_utils import (
bit_vector_to_int_large,
int_to_bit_vector_large,
)
from smqtk.utils.metrics import hamming_distance
__author__ = "paul.tunison@kitware.com"
class LinearHashIndex (HashIndex):... | return True
def __init__(self, file_cache=None):
"""
Initialize linear, brute-force hash index
:param file_cache: Optional path to a file to cache our index to.
:type file_cache: str
"""
super(LinearHashIndex, self).__init__()
self.file_cache = file_cache
... | .file_cache,
}
def load_cache(self):
"""
Load from file cache if we have one
"""
if self.file_cache and os.path.isfile(self.file_cache):
self.index = numpy.load(self.file_cache)
def save_cache(self):
"""
save to file cache if configures
... |
from django.conf.urls import patterns, url
from django.contrib.auth import views as auth_views
urlpatterns = patterns('',
url(r'^login/$',
auth_views.login,
{'template_name': 'authstrap/login.html'},
name='auth_login'),
url(r'^logout/$',
auth_views.logo... | 'template_name': 'authstrap/password_change_form.html'},
name='auth_password_change'),
url(r'^password/change/done/$',
auth_views.password_change_done,
{'template_name': 'authstrap/password_change_done.html'},
name='auth_password | _change_done'),
url(r'^password/reset/$',
auth_views.password_reset,
{'template_name': 'authstrap/password_reset_form.html'},
name='auth_password_reset'),
url(r'^password/reset/confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
auth_views.password_reset... |
from __future__ import absolute_import
from .base import * # NOQA
from .registry import RuleRegistry # NOQA
def init_registry():
from sentry.constants import _SENTRY_RULES
from sentry.plugins.base import plugins
from sentry.utils.imports import import_string
from sentry.utils.safe import safe_execu... | registry.add(cls)
for plugin in plugins.all(version=2):
for cls in safe_execute(plugin.get_rules, _with_transaction=False) or ():
registry.add(cls)
return registry
|
rules = init_registry()
|
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
last,i,j = m+n-1,m-1,n-1
while i >=... | if nums1[i] > nums2[j]:
nums1[last] = nums1[i]
last,i = last-1,i-1
else:
nums1[last] = nums2[j]
last,j = last-1,j-1
while j >= 0:
nums1[last] = nums2[j]
last,j = las | t-1,j-1
|
#===========================================================================
# mjpegger.py
#
# Runs a MJPG stream on provided port.
#
# 2016-07-25
# Carter Nelson
#===========================================================================
import threading
import SimpleHTTPServer
import SocketServer
import io
keepStre... | print "MJPEGThread starting"
self.server = Socke | tServer.TCPServer(("",self.port), MJPEGStreamHandler,
bind_and_activate=False)
self.server.allow_reuse_address = True
self.server.timeout = 0.1
self.server.server_bind()
self.server.server_activate()
self.keepRunning = True
self.streamRunning = True
... |
from test.classes.ball_detector.BallDetector import BallDetector
from test.classes.ball_detector.BounceCalculator import BounceCalculator
from test.classes.ball_detector.Extrapolator import Extrapolator
from test.classes.utils.Ball import Ball
from test.classes.utils.BallHistory import BallHistory
VERTICAL_THRESHOLD ... | or()
def first_frame(self, first_frame):
self | .ball_detector = BallDetector(first_frame)
def track(self, frame):
found_ball = self.ball_detector.detect(frame)
if found_ball.is_none():
found_ball = self.extrapolator.extrapolate(self.track_history)
# Remove vertical movement logic
# If we have no one to compare to,... |
ends on version?
PAGE_MAPPING_ANON = 1
types = Types(['unsigned long', 'struct page', 'enum pageflags',
'enum zone_type', 'struct mem_section'])
symvals = Symvals(['mem_section', 'max_pfn'])
PageType = TypeVar('PageType', bound='Page')
class Page:
slab_cache_name = None
slab_page_name = None
... | _SIZE_BITS = -1 # Depends on sparsemem=True
SECTIONS_PER_ROOT = -1 # Depends on SPARSEMEM_EXTREME
_is_tail: Ca | llable[['Page'], bool]
_compound_head: Callable[['Page'], int]
@classmethod
def setup_page_type(cls, gdbtype: gdb.Type) -> None:
# TODO: should check config, but that failed to work on ppc64, hardcode
# 64k for now
if crash.current_target().arch.name() == "powerpc:common64":
... |
"""Tests for tensorflow.ops.tf.Cholesky."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.python.platform
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
class CholeskyOpTest... | = np.dot(matrices[i].T, matrices[i])
self._verifyCholesky(matrices)
def testNonSquareMatrix(self):
with self.assertRaises(ValueError):
tf.cholesky(np.array([[1., 2., 3.], [3., 4., 5.]]))
def testWrongDimensions(self):
tensor3 = tf.constant([1., 2.])
with self.assertRaises(ValueError):
... | not successful. The "
"input might not be valid."):
# All rows of the matrix below add to zero
self._verifyCholesky(np.array([[1., -1., 0.], [-1., 1., -1.], [0., -1.,
1.]]))
def testEmpty(self):... |
# html2PraatMan - Version 1.0 - October 16, 2013
# Batch html-to-ManPages converter for Praat documentation
# Copyright (C) 2013 Charalampos Karypidis
# Email: ch.karypidis@gmail.com
# http://addictiveknowledge.blogspot.com/
##############################
##############################
# This program is free software... | ####
allFiles = []
htmlList = []
for (dirpath, dirnames, filenames) in os.walk(os.getcwd()):
allFiles.extend(filenames)
for x in range(0,len(allFiles)-1):
if allFiles[x].endswith("html",len(allFiles[x])-4):
htmlList.append(allFiles[x])
for inputFilename in htmlList:
input = BeautifulSoup | (open(inputFilename))
address = input.address.string
addressCleaned = address.strip()
addressComps = addressCleaned.split('\n')
intro = input.cite.string
if len(addressComps) == 3:
recordTime = addressComps[2]
else:
recordTime = '0'
intro = input.cite.string
#####################################
output... |
_only=True)[0])
self.assertEquals([], self.resource_registry.find_objects(site_1_id, PRED.hasPrimaryDeployment, id_only=True)[0])
self.assertEquals([], self.resource_registry.find_objects(device_1_id, PRED.withinDeployment, id_only=True)[0])
self.observatory_management.activate_deployment... | assoc_type=RT.DataProduct)
sdp = self.resource_registry.read(sdp_id)
sdp.category = DataProductTypeEnum.SITE
self.resource_registry.update(sdp)
self.observatory_management.activate_deployment(deployment_id=deployment_1_id)
self.assertEquals(deployment_1_... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
## @copyright
# Software License Agreement (BSD License)
#
# Copyright (c) 2017, Jorge De La Cruz, Carmen Castano.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the followi... | ENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS 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 P | ROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__author__ = 'Jorge De La Cruz,... |
# -*- coding: utf-8 -*-
"""
user
Add the employee relation ship to nereid user
:copyright: (c) 2012-2014 by Openlabs Technologies & Consulting (P) Limited
:license: GPLv3, see LICENSE for more details.
"""
from datetime import datetime
from nereid import request, jsonify, login_required, route
from t... |
"project.work.member", "user", "Member of Projects"
)
def serialize(self, purpose=None):
'''
Serialize NereidUser and return a dictonary.
'''
result = super(NereidUser, self).serialize(purpose)
result['image'] = {
'url | ': self.get_profile_picture(size=20),
}
result['email'] = self.email
result['employee'] = self.employee and self.employee.id or None
result['permissions'] = [p.value for p in self.permissions]
return result
@classmethod
@route("/me", methods=["GET", "POST"])
@login_r... |
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from nasa_r2_common_msgs/ResetTableSceneRequest.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class ResetTableSceneRequest(genpy.Message):
_md5sum = "ba4b0b221fb425ac... | (self.reset,) = _struct_B.unpack(str[start:end])
self.reset = bool(self.reset)
return se | lf
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
buff.wr... |
vely(self):
"""Discover a host with multiple NIC on a network with dhcp
using ISO image in interactive TUI mode.
:id: e29c7f71-096e-42ef-9bbf-77fecac86a9c
:expectedresults: Host should be discovered successfully
:caseautomation: notautomated
:CaseLevel: System
... | ost is not in the list of discovered
# hosts anymore
self.assertIsNone(self.discoveredhosts.search(host_name))
@run_only_on('sat')
@tier3
def test_positive_delete(self):
"""Delete the selected | discovered host
:id: 25a2a3ea-9659-4bdb-8631-c4dd19766014
:Setup: Host should already be discovered
:expectedresults: Selected host should be removed successfully
:CaseLevel: System
"""
with Session(self) as session:
session.nav.go_to_select_org(self.org_... |
import sys
from beaker.container import NamespaceManager, Container
from beaker.exceptions import InvalidCacheBackendError, MissingCacheParameter
from beaker.synchronization import _threading, Synchronizer
from beaker.util import verify_directory, SyncDict
try:
import cmemcache as memcache
except ImportError:
... | Namesp | aceManager.clients.get(url,
lambda: memcache.Client(url.split(';'), debug=0))
# memcached does its own locking. override our own stuff
def do_acquire_read_lock(self): pass
def do_release_read_lock(self): pass
def do_acquire_write_lock(self, wait = True): return True
def do_release_wri... |
""" Forms for use with User objects """
from django import forms
from django.contrib.auth.models import User
class UserForm(forms.ModelForm):
"""
Form for django.contrib.auth.models.User
"""
class Meta:
"""
Meta data for User Form
"""
model = User
fields = ('us... | super(UserForm, self).__init__(*args, **kwargs)
self.fields['username'].required = True
self.fields['email'].required = True
self.fields['password'].required = True
def save(self, commit=True):
"""
Override save so creates a user using create_user method on User model
... | n: Instance of UserForm
"""
instance = super(UserForm, self).save(commit=False)
User.objects.create_user(
username=self.cleaned_data.get('username'),
password=self.cleaned_data.get('password'),
email=self.cleaned_data.get('email')
)
return inst... |
from django import forms
from django.contrib.auth.models import User
from .models import Message
from tinymce.widgets import TinyMCE
class MessageForm(forms.Form):
recipient = forms.CharField(widget=forms.Text | Input(attrs={'class':'form-control'}))
subject = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
content = f | orms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30}))
encrypted = forms.BooleanField(required=False)
#class Meta:
# model = Message
# fields = ('recipient', 'subject', 'content', 'encrypted',)
class KeyForm(forms.Form):
pem_file = forms.FileField()
|
#!/usr/bin/env python2.7
import os
import sys
this_dir = os.path.dirname(os.path.abspath(__file__))
trunk_dir = os.path.split(this_dir)[0]
sys.path.insert(0,trunk_dir)
from ikol.dbregister import DataBase
from ikol import var
if os.path.exists(var.DB_PATH):
os.remove(var.DB_PATH)
DB = DataBase(var.DB_PATH)
... | ","testb")
| DB.insertVideo("KDk2341oEQQ","loLWOCl7nlk","test")
DB.insertVideo("KDktIWeoE23","loLWOCl7nlk","testb")
print DB.getAllVideosByPlaylist("loLWOCl7nlk")
print DB.getVideoById("KDk2341oEQQ") |
# encoding: utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import unicode_literals
from __f... | f.settings.port,
userid=self.settings.user,
password=self.settings.password,
virtual_host=sel | f.settings.vhost,
ssl=self.settings.ssl
)
def disconnect(self):
if self.connection:
self.connection.release()
self.connection = None
def send(self, topic, message):
"""Publishes a pulse message to the proper exchange."""
if not messa... |
# -*- coding: UTF-8 -*-
# /*
# * Copyright (C) 2013 Libor Zoubek + jondas
# *
# *
# * 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 2, or (at your option)
# * ... | a copy of the GNU General Public License
# * along with this program; se | e the file COPYING. If not, write to
# * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
# * http://www.gnu.org/copyleft/gpl.html
# *
# */
import sys
import xbmcaddon
import xbmcutil
import util
from resources.lib.sosac import SosacContentProvider
from resources.lib.sutils import XBMCSosac... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Getting Things GNOME! - a personal organizer for the GNOME desktop
# Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau
#
# This program is free software: you can redistribute it and/or modify it under
# t... | et_size_request(width=width, height=-1)
self.pack_start(password_label, False, True, 0)
align = Gtk.Alignment.new(0, 0.5, 1, 0)
align.set_padding(0, 0, 10, 0)
self.pack_start(align, True, True, 0)
self.password_textbox = Gtk.Entry()
align.add(self.password_textbox)
d... | sword(self):
'''Loads the password from the backend'''
password = self.backend.get_parameters()['password']
self.password_textbox.set_invisible_char('*')
self.password_textbox.set_visibility(False)
self.password_textbox.set_text(password)
def _connect_signals(self):
... |
'''
Copyright 2013 Cosnita Radu Viorel
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute... | 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.
.. codeauthor:: Radu Viorel Cosnita <radu.cosnita@gmail.com>
.. py:module:: fantastico.samples.simple_component.simple_urls
'''
from fantastico.... | roller import BaseController
from fantastico.mvc.controller_decorators import ControllerProvider, Controller
from webob.response import Response
@ControllerProvider()
class SampleUrlsController(BaseController):
'''This class provides some urls with limited functionality in order to enrich the samples from fantasti... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
de | f create(kernel):
result = Intangible()
result.template = "object/intangible/pet/shared_3po_protocol_droid_silver.iff"
result.attribute_template_id = -1
result.stfName("" | ,"")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
"""
Write a program that will help you play poker by telling you what kind of hand you have.
Input:
The first line of input contains the number of test cases (no more than 20). Each test case consists of one line - five
space separated cards. Each card is represented by a two-letter (or digit) word. The first characte... | rint('Straight')
elif three_of_a_kind(inp):
print('Three of a Kind')
elif two_pair(inp):
print('Two Pair')
elif one_pair(inp):
print('One Pair')
else:
print('"High" Card')
def straight_flush(inp):
return same_suit(inp) and consecutive(inp)
def royal_flush(inp):
... | me_rank(inp[:3]) and same_rank(inp[3:])) or \
(same_rank(inp[:2]) and same_rank(inp[2:]))
def flush(inp):
return same_suit(inp)
def straight(inp):
return consecutive(inp)
def three_of_a_kind(inp):
return (same_rank(inp[0:3])) or \
(same_rank(inp[1:4])) or \
(same_rank(... |
#!/usr/bin/env python
import os
import shutil
# def main(src, dst, symlinks=False, ignore=None):
# """Main entry point for the script."""
# copytree(src, dst, symlinks=False, ignore=None)
| def copytree(src, dst, symlinks=False, ignore=None):
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
shutil.copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d)
# # calling main
# if ... | = sys.argv[2]
# symlinks = sys.argv[3]
# ignore = sys.argv[4]
# main(src, dst, symlinks, ignore) |
param lower: A section.
:param higher: A section which values will take precedence over the ones
from the other.
:return: The merged dict.
"""
for name in higher:
if name i | n lower:
lower[name].update(higher[name], ignore_defaults=True)
else:
# no deep copy needed
lower[name] = higher[name]
return lower
def load_config_file(filename, log_printer, silent=False):
"""
Loads sections from a config file. Prints an appropriate warning i... | :param filename: The file to load settings from.
:param log_printer: The log printer to log the warning/error to (in case).
:param silent: Whether or not to warn the user/exit if the file
doesn't exist.
:raises SystemExit: Exits when the given filename is invalid and is not t... |
import elasticsearch
import migrates
from .test_utils import callmigrates, iterate_test_data, remove_test_data
document_count = 1000
def insert_test_data(connection):
with migrates.Batch(connection, migrates.Logger()) as batch:
for i in range(0, document_count):
batch.add({
... | _main__():
logger = migrates.Logger()
connection = elasticsearch.Elasticsearch()
logger.log('Removing old test data.')
remove_test_data(connection)
try:
logger.log('Inserting new test data.')
insert_test_data(connection)
|
logger.log('Reindexing data back into the same index.')
callmigrates('reindex migrates_test_reindex -y')
logger.log('Validating resulting data.')
validate_test_data(connection, index='migrates_test_reindex')
logger.log('Reindexing data into a different ind... |
#### 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 = Tangibl | e()
result.template = "object/tangible/ship/crafted/droid_ | interface/shared_base_droid_interface_subcomponent_mk3.iff"
result.attribute_template_id = 8
result.stfName("space_crafting_n","base_droid_interface_subcomponent_mk3")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
DB_CONFIG = "postgresql://user:password@localhost/db"
ROOT_DIR = "/path/to/project"
ADMIN_USER = "username"
| ADMI | N_PW = "password"
|
##############################################################################
# Copyright (c) 2013-2017, 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... | eveloped to complement the set of
functions related to file systems offered by the standard Lua distribution.
LuaFileSystem offers a portable way to access the underlying directory
structure and file attributes.
LuaFileSystem is free software and uses the same license as Lua 5.1
"""
homepage ... | ps://github.com/keplerproject/luafilesystem/archive/v1_6_3.tar.gz'
version('1_6_3', 'bed11874cfded8b4beed7dd054127b24')
# The version constraint here comes from this post:
#
# https://www.perforce.com/blog/git-beyond-basics-using-shallow-clones
#
# where it is claimed that full shallow clone s... |
#!/usr/bin/env python
"""interpret a comapct grid specification using regex"""
import re
# use a compact regular expression with nested OR expressions,
# and hence many groups, but name the outer (main) groups:
real_short1 = \
r'\s*(?P<lower>-?(\d+(\.\d*)?|\d*\.\d+)([eE][+\-]?\d+)?)\s*'
real_short2 = \
r'\s*(?P<uppe... | ger interval [a:b] :
indices = r'\[\s*(-?\d+)\s*:\s*(-?\d+)\s*\]'
print '\navoid so many parenthesis (just two groups now for each interval):'
for ex in examples:
print re.findall(indices, ex)
print re.findall(domain, ex)
print
# much simpler _working_ versions:
domain = r'\[([^,]*),([^\]]*)\]'
indices = ... | pler regular expressions:\n', domain, indices
for ex in examples:
print re.findall(indices, ex)
print re.findall(domain, ex)
print
# these give wrong results
domain = r'\[(.*?),(.*?)\]'
indices = r'\[(.*?):(.*?)\]'
print '\nalternative; simpler regular expressions:\n', domain, indices
for ex in examples:
... |
init'.format(self.__class__))
def __del__(self):
logging.debug('{0} module del'.format(self.__class__))
def setupUi(self, dia_credits):
dia_credits.setObjectName(_fromUtf8("dia_credits"))
dia_credits.resize(420, 800)
dia_credits.setMinimumSize(QtCore.QSize(420, 700... | em(0, item)
item = QtGui.QTableWidgetItem()
self.table_li | bs.setVerticalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
self.table_libs.setVerticalHeaderItem(2, item)
item = QtGui.QTableWidgetItem()
self.table_libs.setVerticalHeaderItem(3, item)
item = QtGui.QTableWidgetItem()
self.table_libs.setVerticalHeaderItem(4, item)
... |
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/ | .
#
from uitest.framework import UITestCase
import time
class tdf92611(UITestCase):
def test_launch_and_close_bibliography(self):
self.ui_test.create_doc_in_start_center("writer")
self.xUITest.executeCommand(".uno:BibliographyComponent")
time.sleep(2)
self.xUITest.executeComm... | time.sleep(2)
self.ui_test.close_doc()
# vim: set shiftwidth=4 softtabstop=4 expandtab:
|
"""
p | ip.vendor is for vendoring dependencies of pip to prevent needing pip to
depend on something external.
Files inside | of pip.vendor should be considered immutable and should only be
updated to versions from upstream.
"""
from __future__ import absolute_import
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import uuid
import socket
import time
__appname__ = "pymessage"
__author__ = "Marco Sirabella, Owen Davies"
__copyright__ = ""
__credits__ = "Marco Sirabella, Owen Davies"
__license__ = "new BSD 3-Clause"
__version__ = "0.0.3"
__maintainers__ = "Ma... | lguid.encode())
print('sent latest guid: {}'.format(lguid))
| # contents = "latest guid +5: {}".format(lguid + '5')
msg = True
fullmsg = ''
while msg:
msg = sock.recv(16).decode() # low byte count for whatever reason
#print('mes rec: {}'.format(msg))
fullmsg += msg
print('received message: {}'.format(fullmsg))
sock.close()
connect... |
import sys
import time
from collectors.lib import utils
def main():
"""Main loop"""
sys.stdin.close()
interval = 15
page_size = resource.getpagesize()
try:
sockstat = open("/proc/net/sockstat")
netstat = open("/proc/net/netstat")
snmp = open("/proc/net/snmp")
except ... | while
# we were fast retransmitting, so we were able to partially undo some
# of our CWND reduction.
"TCPPartialUndo": ("congestion.recovery", "type=hoe_heuristic"),
# We detected some erroneous retransmits, a D-SACK arrived and ACK'ed
| # all the retransmitted data, so we undid our CWND reduction.
"TCPDSACKUndo": ("congestion.recovery", "type=sack"),
# We detected some erroneous retransmits, a partial ACK arrived, so we
# undid our CWND reduction.
"TCPLossUndo": ("congestion.recovery", "type=ack"),
# We r... |
#ue.exec('pip2.py')
import subprocess
import sys
import os
import unreal_engine as ue
import _thread as thread
#ue.log(sys.path)
_problemPaths = ['']
def NormalizePaths():
problemPaths = _problemPaths
#replace '/' to '\\'
for i in range(len(sys.path)):
currentPath = sys.path[i]
sys.path[i] = currentPath.repl... | (line)
print(line)
output += line
if verbose:
print("cmd Result: ")
print(output)
return output #return the data for dependent functions
#convenience override
def runLogOutput(process, path=_PythonHomePath):
fullcommand = FolderCommand(path) + process
stdoutdata = subprocess.getstatusoutput(fullcommand)
... | ta[1])
return stdoutdata[1]
#convenience wrappers
def dir(path=_PythonHomePath):
run('dir', path)
def ls(path=_PythonHomePath):
dir(path)
def md(folder, path=_PythonHomePath):
run('md ' + folder, path)
def mkdir(folder, path=_PythonHomePath):
md(folder, path) |
class Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class OldestUnique:
def __init__(self):
self.uniq = {}
self.seen = set()
self.head = None
self.tail = None
def feed(self, value):
if value in self.un... | # unlink from list but leave in uniq dict
node = self.uniq[value]
if node.prev is not None:
node.prev.next = node.next
else:
self.head = node.next
if node.next is not None:
node.next.prev = node.prev
else:
... | ad is None:
self.tail = node
else:
node.next = self.head
self.head.prev = node
self.head = node
self.uniq[value] = node
self.seen.add(value)
def query(self):
if self.tail is not None:
return self.tai... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 | .5 on 2018-08-31 12:06
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('basicviz', '0073_auto_20180831_1203'),
]
operations = [
migrations.AddField(
model_name='experiment',
... | field=models.CharField(blank=True, max_length=128, null=True),
),
migrations.AddField(
model_name='experiment',
name='ms2_id_field',
field=models.CharField(blank=True, max_length=128, null=True),
),
]
|
"""
Goal: set the environment for tests
Docs:
https://pythonhosted.org/Flask-SQLAlchemy/quickstart.html
The only things you need to know compared to plain SQLAlchemy are:
SQLAlchemy gives you access to the following things:
- al | l the functions and classes from sqlalchemy and sqlalchemy.orm
- a preconfigured scoped session called session
- the metadata
- the engine
- a SQLAlchemy.create_all() and S | QLAlchemy.drop_all() methods to create and
drop tables according to the models
- a Model baseclass that is a configured declarative base
- The Model declarative base class behaves like a regular Python class but has
a query attribute attached that can be used to query the model
- You have to commit the sessi... |
from .lconfiguration import LocalConfiguration
from .printing import Printing
from .word import Word
from xml.etree import ElementTree
class LinearisationRule:
@classmethod
def deserialise(cls, grammars, def_rule_etree):
probability = float(def_rule_etree.get('p'))
head_node_etree = def_rule_... | e.values())
dependents.sort()
local_configuration = LocalConfiguration(head_node[0], head_node[1],
tuple(dependents))
head_node_ord = int(head_node_etree.get('ord'))
linearisation_rule[head_node_ord] = head_node
linearisation_rule ... | ort()
head_node_index = linearisation_rule.index((head_node_ord, head_node))
linearisation_rule = LinearisationRule(
[value for key, value in linearisation_rule[:head_node_index]],
[value for key, value in linearisation_rule[head_node_index + 1:]])
try:
gramm... |
#
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of GNUHAWK.
#
# GNUHAWK is free software: you can redistribute it and/or modify is under the
# terms of the GNU General Public License as published by the Free Software
# F... | if type(dest) == tuple:
dest, index = dest
else:
# Default to the first port
index = 0
if isinstance(dest, local.LocalComponent):
# Get just the provides ports from the destination
| provides_ports = filter(lambda x: x._direction == 'Provides', dest._ports)
# -1 inputs; connect everybody to the same input port until existing components are
# modified to have 1 port per allowed input
if len(provides_ports) == 1:
index = 0
dest... |
#!/usr/bin/env pyth | on3
"""
DNSSEC Single-Type Signing Scheme, RFC 6781
"""
from dnstest.utils import *
from dnstest.test import Test
t = Test()
knot = t.server("knot")
zones = t.zone_rnd(5, dnssec=False, records=10)
t.link(zones, knot)
t.start()
# one KSK
knot.gen_key(zones[0], ksk=True, zsk=True, alg="ECDSAP256SHA256", key_len="25 | 6")
# multiple KSKs
knot.gen_key(zones[1], ksk=True, zsk=True, alg="ECDSAP384SHA384", key_len="384")
knot.gen_key(zones[1], ksk=True, zsk=True, alg="ECDSAP256SHA256", key_len="256")
# different algorithms: KSK+ZSK pair, one KSK
knot.gen_key(zones[2], ksk=True, alg="ECDSAP256SHA256", key_len="256")
knot.gen_key(zones[... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, division
f | rom django.shortcuts import redirect, get_object_or_404
from django.db import transaction
from xue.common.decorators import quickview, limit_role
from xue.tutor.forms import St | udentApplicationForm, ProjectSelectionForm
from xue.tutor.models import StudentProject, StudentApplication, TutorProject
# expiration...
PRELIMINARY_EXPIRED, SECONDARY_EXPIRED = False, False
@limit_role([0])
@quickview('tutor/stud_apply_expired.html')
def apply_expired_view(request):
return {}
@limit_role([0])... |
# -*- coding: utf-8 -*-
# MORFEO Project
# http://morfeo-project.org
#
# Component: EzForge
#
# (C) Copyright 2004 Telefónica Investigación y Desarrollo
# S.A.Unipersonal (Telefónica I+D)
#
# Info about members and contributors of the MORFEO project
# is available at:
#
# http://morfeo-project.org/
#
... | son.dumps() cant handle Decimal
ret = str(data)
elif isinstance(data, models.query.QuerySet):
# Actually its the same as a list ...
ret = _list(data)
elif isinstanc | e(data, models.Model):
ret = _model(data)
else:
ret = data
return ret
def _model(data):
ret = {}
# If we only have a model, we only want to encode the fields.
for f in data._meta.fields:
ret[f.attname] = _any(getattr(data, f.attname))
... |
################################## | ######################################
# File name: __init__.py
# This file is part of: aioxmpp
#
# LICENSE
#
# This program is | free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 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 A... |
import datetime
import os
import shutil
import time
from files_by_date.utils.logging_wrapper import get_logger, log_message
from files_by_date.validators.argument_validator import ArgumentValidator
logger = get_logger(name='files_service')
class FilesService:
def __init__(self):
raise NotImplementedErro... | group_dir=group_dir))
for file in file_groups[group]:
# file_path = f'{group_dir}{os.sep}{os.path.basename(file)}' # 3.6
file_path = '{group_dir}{os_sep}{file_n | ame}'.format(group_dir=group_dir, os_sep=os.sep,
file_name=os.path.basename(file))
if force_overwrite and os.path.exists(file_path):
os.remove(file_path)
if not os.path.exists(file_path):
... |
presented by multiple XML elements.
"""
def __get__(self, instance, cls):
instance.get()
result = []
for node in instance.root.findall(self.tag):
result.append(node.text)
return result
class StringDictionaryDescriptor(TagDescriptor):
"""An instance attribute co... | ot isinstance(value, str):
if not self._is_string(value):
value = str(value)
elem.text = value
| #update the internal elements and lookup with new values
self._update_elems()
self._prepare_lookup()
def __delitem__(self, key):
del self._lookup[key]
for node in self._elems:
if node.attrib['name'] == key:
self.rootnode.remove(node)
... |
from allauth.account.signals import email_confirmed, email_changed, email_added, email_removed, user_signed_up, user_logged_in
from django.contrib.auth.models import User, Group, Permission
from django.db.models import Q
from django.dispatch import receiver
"""intercept signals from allauth"""
@receiver(email_confir... | ociallogin', None)
if social_login:
social_account = social_login.account
if social_account:
if 'verified_email' in social_account.extra_data:
if social_account.ext | ra_data['verified_email']:
group = Group.objects.get(name='AllowedCommentary')
user.groups.add(group)
|
from django.contrib import | admin
from .models import Message
admin.site.register(Message) | |
#!/usr/bin/env python
"""macro_tests.py: Some macro tests"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Fabien Cromieres"
__license__ = "undecided"
__version__ = "1.0"
__email__ = "fabien.cromieres@gmail.com"
__status__ = "Development"
# import nmt_chainer.make_dat... | rain_dir = tmpdir.mkdir("train")
data_prefix = str(train_dir.join("test1.data"))
train_prefix = str(train_dir.join("test1.train"))
data_src_file = os.path.join(test_data_dir, "src2.txt")
data_tgt_file = os.path.join(test_data_dir, "tgt2.txt")
args = 'make_data {0} {1} {2} --dev_s... |
args_train = ["train", data_prefix, train_prefix] + "--max_nb_iters 10 --mb_size 2 --Ei 10 --Eo 12 --Hi 30 --Ha 70 --Ho 15 --Hl 23 --save_ckpt_every 5".split(" ")
if gpu is not None:
args_train += ['--gpu', gpu]
main(arguments=args_train)
def test_config_saving(self, tmpdir, g... |
efore, tAfter)
def sumLayerRangeTime(self, slx, elx):
return sum(self.layerTimes[slx:elx])
def changeLayer(self, lx):
self.currentLayer = lx
self.slLayers.SetValue(lx)
ht = self.gObj.getLayerHeight(lx)
self.setLayerText(ht)
if ht is None:
self.propDlg.setProperty(PropertyEnum.layerNum, "%d / %d" ... | m, "%d / %d (%.2f mm) " % (lx, self.gObj.layerCount(), ht))
f, l = self.gObj.getGCodeLines(lx)
if f is None:
self.propDlg.setProperty(PropertyEnum.gCodeRange, "")
self.layerRange = (0, 0)
else:
self.propDlg.setProperty(PropertyEnum.gCodeRange, "%d - %d" % (f, l))
self.layerRange = (f, l)
x0,... |
self.propDlg.setProperty(PropertyEnum.minMaxXY, "(%.2f, %.2f) - (%.2f, %.2f)" % (x0, y0, xn, yn))
le, prior, after = self.gObj.getLayerFilament(lx)
s = []
for i in range(self.settings.nextruders):
s.append("%.2f/%.2f <: %.2f >: %.2f" % (le[i], self.eUsed[i], prior[i], after[i]))
self.pro... |
"""empty message
Revision ID: 8e7f7864cb60
Revises: | ('80a704b880db', 'adf34c11b0df')
Create Date: 2016-06-19 15:43:23.027000
"""
# revision identifiers, used by Alembic.
revision = '8e7f7864cb60'
down_revision = ('80a704b880db', 'adf34c11b0df')
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
def upgrade():
pass |
def downgrade():
pass
|
# -*- coding: utf-8 -*-
'''
FanFilm Add-on
Copyright (C) 2016 mrknow
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 of the License, or
(at your option) any ... | son), int(episode))
url = client.replaceHTMLCodes(url)
url = url.encode('utf-8')
return url
def get_sources(self, url, hosthdDict, hostDict, locDict):
try:
sources = []
if url == None: return sources
url = urlparse.urljoin(self.base_link, url)
... | findall('<div class="col-lg-9 col-md-9 col-sm-9">\s.*<b>Język</b>:(.*?)\.*</div>',result)[0].strip()
q = re.findall('<div class="col-lg-9 col-md-9 col-sm-9">\s.*<b>Jakość</b>:(.*?)\.*</div>', result)[0].strip()
quality = 'SD'
if '720' in q: quality = 'HD'
if '1080' in q: ... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
FindProjection.py
-----------------
Date : February 2017
Copyright : (C) 2017 by Nyall Dawson
Email : nyall dot dawson at gmail dot com
*****************... | *
***************************************************************************
"""
__author__ = 'Nyall Dawson'
__date__ = 'February 2017'
__copyright__ | = '(C) 2017, Nyall Dawson'
import os
from qgis.core import (QgsGeometry,
QgsFeature,
QgsFeatureSink,
QgsField,
QgsFields,
QgsCoordinateReferenceSystem,
QgsCoordinateTransform,
... |
ature====
Default for ABS is 195 degrees Celcius.
Defines the infill temperature of the first layer of the object.
====Object First Layer Perimeter Temperature====
Default for ABS is two hundred and twenty degrees Celcius.
Defines the perimeter temperature of the first layer of the object.
====Object Next Layers Te... | mperature (Celcius):', self, 260.0, 230.0 )
self.executeTitle = 'Temperature'
def execute(self):
"Temperature button has been clicked."
fileNames = skeinforge_polyfile.getFileOrDirectoryTypesUnmodifiedGcode(self.fileNameInput.value, fabmetheus_interpret.getImportPluginFileNames(), self.fileNameInput.wasCa | ncelled)
for fileName in fileNames:
writeOutput(fileName)
class TemperatureSkein:
"A class to temperature a skein of extrusions."
def __init__(self):
self.distanceFeedRate = gcodec.DistanceFeedRate()
self.lineIndex = 0
self.lines = None
def getCraftedGcode(self, gcodeText, repository):
"Parse gcode t... |
#PyInterstate by @pygeek
import urllib2
import json
class InterstateError(Exception):
"""Base class for Interstate App Exceptions."""
pass
class AuthError(InterstateError):
"""Exception raised upon authentication errors."""
pass
class IdError(InterstateError):
"""Raised when an operatio... | uts: JSON
See: http://interstateapp.com/developers/method/1/0
"""
if self.auth_test() and self.id_test(road_id=road_id):
get_url = "{0}{1}/api/{2}/road/get/id/{3}" \
.format(self.protocol, self.base_url, self.api_version, \
road_id)
... | rn json.loads(road)
else:
return False
def updates(self, road_id):
"""road/get:
Retrieve updates attached to a specific Interstate road.
Parameters:
- id(Road ID)
The unique id of the Interstate road.
Example Request:
... |
from yum.plugins import PluginYumExit, TYPE_CORE, TYPE_INTERACTIVE
try:
import json
except ImportError:
import simplejson as json
requires_api_version = '2.5'
plugin_type = (TYPE_INTERACTIVE,)
def config_hook(conduit):
parser = conduit.getOptParser()
parser.add_option('', '--json', dest='json', acti... | o, 'repoid')
}
if transaction.ts_state:
packages[trans | action.name]["pending"] = version
else:
packages[transaction.name]["current"] = version
print(json.dumps(packages))
raise PluginYumExit('')
|
# Log into t | he site with your browser, obtain the "Cookie" header,
# and put it here
cookie | = ''
|
from django.forms import *
from django.forms.formsets import BaseFormSet
from django.utils.translation import ugettext_lazy as _
from django.contrib.sites.models import Site
from tradeschool.models import *
class DefaultBranchForm(Form):
def __init__(self, user, redirect_to, *args, **kwargs):
super(Defaul... | t.attrs['class'] = 'barter_item'
self.fields['title'].error_messages['required'] = _(
"Barter item cannot be blank")
class Meta:
model = BarterItem
fields = ('title',)
class BaseBarterItemFormSet(BaseFormSet):
def __init__(self, branch, *args, **kwargs):
""
... | count = 0
required = self.branch.min_barteritems
if any(self.errors):
return
for form in self.forms:
if form.is_bound:
if form['title'].data:
count += 1
if count < required:
raise forms.ValidationError(
... |
# Copyright (C) 2008-2011 Dejan Muhamedagic <dmuhamedagic@suse.de>
# Copyright (C) 2013 Kristoffer Gronlund <kgronlund@suse.com>
# See COPYING for license information.
from . import command
from . import completers as compl
from . import utils
from . import ra
from . import constants
from . import options
def comple... | eters(compl.call(ra.ra_classes), lambda args: ra.ra_providers_all(args[1]))
def do_list(self, context, class_, provider_=None):
"usage: list <class> [<provider>]"
if class_ not in ra.ra_classes():
context.fatal_error("class | %s does not exist" % class_)
if provider_ and provider_ not in ra.ra_providers_all(class_):
context.fatal_error("there is no provider %s for class %s" % (provider_, class_))
types = ra.ra_types(class_, provider_)
if options.regression_tests:
for t in types:
... |
"""SCons.Tool.bcc32
XXX
"""
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, ... | r SCons.Util.WhereIs(program)
if borwin:
dir = os.path.dirname(borwin)
path = env['ENV'].get('PATH', [])
if not p | ath:
path = []
if SCons.Util.is_String(path):
path = string.split(path, os.pathsep)
env['ENV']['PATH'] = string.join([dir]+path, os.pathsep)
return borwin
def generate(env):
findIt('bcc32', env)
"""Add Builders and construction variables for bcc to an
Environment... |
blic": True,
}
}
self.expected_flavor = self.request_body
def _setup_app(self):
return fakes.wsgi_app_v21(init_only=('os-flavor-manage',
'os-flavor-rxtx',
'os-flavor-access', 'flavors',
... | _create_flavor_bad_request_case(self.request_body)
def test_create_without_ram(self):
del self.request_body['flavor']['ram']
self._create_flavor_bad_request_case(self.request_body)
def test_create_with_0_ram(self):
self.request_body['flavor']['ram'] = 0
self._create_flavor_bad_... | vor']['vcpus']
self._create_flavor_bad_request_case(self.request_body)
def test_create_with_0_vcpus(self):
self.request_body['flavor']['vcpus'] = 0
self._create_flavor_bad_request_case(self.request_body)
def test_create_without_disk(self):
del self.request_body['flavor']['disk'... |
ssage('testStarted', {'name': test_name, 'flowId': test_name}),
ServiceMessage('testFailed', {'name': test_name, 'message': 'Error', 'flowId': test_name}),
ServiceMessage('testFinished', {'name': test_name, 'flowId': test_name}),
])
failed_ms = match(ms, ServiceMessage('testFailed',... | : "stderr_test1", 'flowId': test_name}),
ServiceMessage('testFailed', {'name': test_name, 'flowId': test_name}),
ServiceMessage('testStdErr', {'out': "stderr_test2", 'flowId': test_name}),
ServiceMessage('testFinished', {'name': test_name, 'flowId': test_name}),
])
# Che... | ).replace("out='stderr_test", "")
assert output.find("stdout_test") < 0
assert output.find("stderr_test") < 0
def test_doctests(venv):
output = run_directly(venv, 'doctests.py')
test_name = '__main__.factorial'
assert_service_messages(
output,
[
ServiceMessage('testCoun... |
from Queue import Queue, Empty
import contextlib
from logging import getLogger
import random
import time
from gevent.monkey import saved
LOG = getLogger(__name__)
if bool(saved):
LOG.info('using zmq.green...')
import zmq.green as zmq
else:
import zmq
class ZMQConnection(object):
def __init__(self... |
if self.size >= self.maxsize or pool.qsize():
# we're over limit or there are already created objects in the queue
try:
conn = pool.get(block=block, timeout=timeout)
except Empty:
raise ConnectionError("Too many connections")
# we ... | st be valid!
# a null connection means we need to create a new one
if conn and not conn.closed:
return conn
# we didn't get a valid connection, add one.
else:
# we have to room to grow, so reserve a spot!
self.size += 1
try:
... |
import pandas as pd
import numpy as np
import re
from gensim import corpora, models, similarities
from gensim.parsing.preprocessing import STOPWORDS
def split(text):
'''
Split the input text into words/tokens; ignoring stopwords and empty strings
'''
delimiters = ".", ",", ";", ":", "-", "(", ")", " ", "\t"
... | urn [word for word in re.split(regexPattern, text.lower()) if word not in STOPWORDS and word != ""]
def main():
# Load data
df_train = pd.read_csv('data/train.csv', encoding="ISO-8859-1")
df_desc = pd.read_csv('data/product_descriptions.csv', encoding="ISO-8859-1")
df_attr = pd.read_csv('data/attributes_combin... | les = [split(line) for line in df_train["product_title"]]
descs = [split(line) for line in df_desc["product_description"]]
attrs = [[str(line)] if isinstance(line, float) else split(line) for line in df_attr["attr_value"]]
queries = [split(line) for line in df_train["search_term"]]
texts = np.concatenate((title... |
# -*- coding: utf-8 -*-
import pytest
from lupin.validators import Equal
from lupin.errors import ValidationError
@pytest.fixture
def invalid():
return Equal("sernine")
@pytest.fixture
def valid():
return Equal("lupin")
class TestAnd(object):
def test_returns_an_and_combination(self, valid, invalid):
... | f test_returns_an_and_combination(self, valid, invalid):
combination = valid | invalid
combination("lupin", [])
| |
from sandbox.dalz.data import ArticleCommentCountFileData, ArticlePublicationDateFileData, ArticleAuthorFileData, \
ArticleWordCountFileData, CommentAuthorCommentCountFilesDatas, AuthorArticleCountFilesData, \
AuthorArticlesCommentsCountAverageFilesData, AuthorArticlesWordsCountAverageFilesData, \
ArticlePu... | ordCountFileData,
ArticleCommentCountFileData,
| ArticlePublicationDateFileData,
ArticlePublicationHourFileData,
ArticleAuthorFileData,
ArticlePatriceCommentCountFileData]
class AuthorImplode(Implode):
_name = 'Authors'
_data_classes = [AuthorArticleCountFilesData,
... |
# pylint: disabl | e=missing-docstring
# pylint: disable=wildcard-import
from .test_mocks import *
from .cpython.testmock import *
from .cpython.testwith imp | ort *
|
from project_cron.utils import processutil
def open(app_name):
script = '''
if application "%s" is not running then
tell application "%s" to activate
end if
''' % (app_name, app_name)
processutil.call(['/usr/bin/osascript', '-e', script])
def close(app_name):
script ... | to quit' % app_nam | e
processutil.call(['/usr/bin/osascript', '-e', script])
|
#!/usr/bin/env python
# A python script to take targets from a google spreadsheet and run a
# Nessus vulnerability scan.
import json
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from nessrest import ness6rest
import getpass
# Login with your Google account's API key
scopes = ['ht... |
# login = "username"
# password = "password"
scan = ness6rest.Scanner(url=nessus_url, login=user,
password=password, insecure=True)
# Set scan policy that should be used
scan.policy_set(name=scan_policy)
# alt_targets on edit can take an array otherwise a new scan expects a string
hosts = '... |
# Run Scan
scan.scan_run()
# Download results
# scan.action(action="scans", method="get")
# for s in scan.res['scans']:
# scan.scan_name = s['name']
# scan.scan_id = s['id']
# xml_nessus = scan.download_scan(export_format='nessus')
# fp = open('%s_%s.nessus'%(scan.scan_name,scan.scan_id),"w")
# fp.writ... |
# -*- coding: utf-8 -*-
# Copyright 2007-2021 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy 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 of the License, or
# (at... | peak()
with pytest.raises(NotImplementedError):
s.create_model(ll=s)
with pytest.raises(NotImplementedError):
s.fourier_log_d | econvolution(0)
with pytest.raises(NotImplementedError):
s.fourier_ratio_deconvolution(s)
with pytest.raises(NotImplementedError):
s.fourier_ratio_deconvolution(s0)
with pytest.raises(NotImplementedError):
s0.fourier_ratio_deconvolution(s)
with pytest.raises(NotImplementedError):... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_str
class TF1IE(InfoExtractor):
"""TF1 uses the wat.tv player."""
_VALID_URL = r'https?://(?:(?:videos|www|lci)\.tf1|(?:www\.)?(?:tfou|ushuaiatv|histoire|tvbreizh))\.fr/(?:[^/]+/)*(?P<id>[^/?... | },
'params': {
# Sometimes wat serves the whole file with the --test option
| 'skip_download': True,
},
'skip': 'HTTP Error 410: Gone',
}, {
'url': 'http://www.tf1.fr/tf1/koh-lanta/videos/replay-koh-lanta-22-mai-2015.html',
'only_matching': True,
}, {
'url': 'http://lci.tf1.fr/sept-a-huit/videos/sept-a-huit-du-24-mai-2015-8611550.html',
... |
ult=.05,
help='Exploration rate used during evaluation.')
arg_alg.add_argument("--test-samples", type=int, default=125000,
help='Number of collected samples for each'
'evaluation.')
arg_alg.add_argument("--max-no-op-actions", type=i... | ncy = args.evaluati | on_frequency
max_steps = args.max_steps
# MDP
mdp = Atari(args.name, args.screen_width, args.screen_height,
ends_at_life=True, history_length=args.history_length,
max_no_op_actions=args.max_no_op_actions)
if args.load_path:
logger = Logger(DQN.__name__, resu... |
e = loop.create_future()
self._quit_future = loop.create_future()
self._ip_address = ip_address
self._is_owner = False
self._port = port
await self._connect()
return self
async def disconnect(self) -> "AsyncServer":
if not self._is_running:
raise ... | >>> import supriya.realtime
>>> server = supriya.realtime.Server()
>>> server.boot()
<Server: udp://127.0.0.1:57110, 8i8o>
::
>>> server.quit()
<Server: offline>
"""
### CLASS VARIABLES ###
_servers: | Set["Server"] = set()
### INITIALIZER ###
def __init__(self):
BaseServer.__init__(self)
self._lock = threading.RLock()
# proxies
self._audio_input_bus_group = None
self._audio_output_bus_group = None
self._default_group = None
self._root_node = None
... |
# Copyright (C) 2012 Balazs Ankes (bank@inf.u-szeged.hu) University of Szeged
#
# Redistri | bution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must re... | ith the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONT... |
ef _save_preferences():
return save_settings('Preferences.sublime-settings')
class ClearWindowCommand(sublime_plugin.WindowCommand):
def run(self):
if self.window.is_sidebar_visible():
self.window.set_sidebar_visible(False)
if self.window.is_minimap_visible():
self.wi... | size)
_save_preferences()
if not self.window.is_sidebar_visible():
self.window.set_sidebar_visible(True)
if not self.window.is_minimap_visible():
self.window.set_minimap_visible(True)
if not self.window.is_menu_visible():
self.window.set_m | enu_visible(True)
if not self.window.is_status_bar_visible():
self.window.set_status_bar_visible(True)
self.window.run_command('resize_groups_almost_equally')
class ResizeGroupsAlmostEquallyCommand(sublime_plugin.WindowCommand):
"""
Resize groups equally.
Make all groups (al... |
from django | .conf.urls import url
from api.applications import views
app_name = 'osf'
urlpatterns = [
url(r'^$', views.ApplicationList.as_view(), name=views.ApplicationList.view_name),
url(r'^(?P<client_id>\w+)/$', views.ApplicationDetail.as_view(), name=views.ApplicationDetail.view_name),
url(r'^(?P<client_id>\w+)/... |
]
|
#encoding:utf-8
sub | reddit = 'ikeahacks'
t_channel = '@r_IKEAhacks'
def send_post(submission, r2t):
return r2t.s | end_simple(submission)
|
from datetime import datetime
class Schedule(object):
WEEK_ONE = datetime(2014, 9, 2, 9)
def week(self):
time_difference = datetime.now() - | self.WEEK_ONE
return (time_difference.days/7)+1
def season_year(self):
return 2 | 014
|
"File-based cache backend"
import glob
import hashlib
import os
import pickle
import random
import tempfile
import time
import zlib
from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache
from django.core.files.move import file_move_safe
from django.utils.encoding import force_bytes
class FileBasedCac... | rn []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1( | self._dir, '*%s' % self.cache_suffix)]
return filelist
|
r
# (at your option) any later version.
#
# This Ansible library 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 General Public License for more details.
#
# You should have received... | description:
- "The CIDR block for the subnet. E.g. 192.0.2.0/24. Only required when state=present."
required: false
default: null
tags:
description:
- "A dict of tags to apply to the subnet. Any tags currently applied to the su | bnet and not present here will be removed."
required: false
default: null
aliases: [ 'resource_tags' ]
state:
description:
- "Create or remove the subnet"
required: false
default: present
choices: [ 'present', 'absent' ]
vpc_id:
description:
- "VPC ID of the VPC in which ... |
b64decode(
'eJzlvX10ZFd1J0pVqaTSbbV0VN2222o3fV3+aKktVbvbxoY2xqOW5LZMd6unpIaYGSyuqq6kcp'
'fqirpVLcuBlWQyhI98vEcAY+eBSfgyMQFCgCQDi5dhArMWvIQk7zFkzcKTYQWcQAjmw7OAISHv'
'7d8++5x7bpXaNoTO/PG8Elq177n77LPPPvvsvc8++3r/UPB2x2HrQr0aljdbUTsqDtbqcTW6EL'
'a2x/y1KFprhEf4wUpn9UgtjKut+mY7aunGpX6v7yVRvVZqe2qWn62ElTDejJp... | iPaWg4a9SAW0f'
'AYNA3Is526f6Elklf9pUcynuo2bLvIzPyvJLP0tow3nLZmu8i7+n8peV/OertTNuyzpe6V3mi9'
'Fm5sRm0Ez5cb4YWwsa/ESqM3qJjqoTyfvHcKrx3fMz87d/rswtLcmZl7ls+defGZhZeeqah6V7'
'NLuOzPeqqbqOIV3k5k0cre442cWaA9kTbGuTvvnJtZWtRxD9t6KbXAS7+R8/bsQAmpce2xaCdq'
'6tlQX4bNcJZcSXFwyBYiLjXb9dU62fPaB9duzEgC1yGlSa+4GelDsGXCK... | V7B8AFbNThBphM721kEwprmIXVaj5eTIH6Wnhcqu+qxDYCWHiWDJX0IQb5LoRGRkOuTds'
'zN+DOcW5RPSfuKfXPs8xmvYMC03fZtBu11Rpc/kVWZCv8GnCzAJouAwPEb89oIgxo7PdHGBs1k'
'bOZV4DMCxllYuxXUG6m2fdxWmQe28XHvSoO3RlYoOVS15KV+Dm5cIQ1m5bl5t/QXGW/UuGk1y6'
'zTnhc0m1HbZVevKPe8V562L1UcBGMbnpc8uSjbaJ+SEyY+ptSOvadB8OcQflkJ1+pNiRvrHyb8'
'0... |
#!/usr/bin/env python
import roslib; roslib.load_manifest('master_monitor')
import rospy
from rosgraph_msgs.msg import Log
from syscall import runCmd, runCmdOutput
from move_base_msgs.msg import MoveBaseGoal, MoveBaseAction
from geometry_msgs.msg import PoseStamped
import actionlib
import numpy as np
class ControlMod... | a.level))]+", From node " + data.name + ", a message: "+data.msg.strip()
if str(data.msg).strip() == str("Connectivity Error: Could not find a common time /base_link and /map.") and data.name == "/move_base_node":
kinect_reconfiguration()
# if data.name == "/sicklms":
# print "Level: "+level[int(np.sqrt(data.le... | ata.name == "/sicklms" and str(data.msg).strip() == "woah! error!":
kinect_reconfiguration()
def current_goal_callback(data):
global control_model
control_model.current_goal = data
rospy.loginfo("Current goal received and stored")
def kinect_reconfiguration():
global kinect_recov_launched
global move_base_c... |
# This file is part of eventmq.
#
# eventmq is free software: you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License | as published by the Free
# Software Foundation, either version 2.1 of the License, or (at your option)
# any later version.
#
# eventmq 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
# G... | License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with eventmq. If not, see <http://www.gnu.org/licenses/>.
"""
:mod:`client` -- Client Utilities
=================================
This module contains a utilities that can be used when acting as a client in
e... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests lesson 04 task 05."""
# Import Python libs
import unittest
import mock
import random
class Lesson04Task05TestCase(unittest.TestCase):
"""
Test cases for lesson 04 task 05.
"""
def test_blood_pressure_status(self):
"""
Tests that... | 159],
'emergency': [160, 256]
}
for key, value in levels.iteritems():
systolic = random.randint(value[0], value[1])
with mock.patch('__builtin__.raw_input', side_effec | t=[systolic]):
try:
task_05 = reload(task_05)
except NameError:
import task_05
self.assertEqual(task_05.BP_STATUS.lower(), key)
if __name__ == '__main__':
unittest.main()
|
Schema object or None if not found.
"""
return self._schemas.get(schema_name, None)
def SetVariantInfo(self, ref, discriminant, value, schema):
"""Sets variant info for the given reference."""
if ref in self._variant_info:
logging.warning("Base type of '%s' changed from '%s' to '%s'. "
... | pe[ref].wireName, schema.wireName)
self._variant_info[ref] = {'discriminant': discriminant, 'value': value,
'schema': schema}
de | f VisitAll(self, func):
"""Visit all nodes of an API tree and apply a function to each.
Walks a tree and calls a function on each element of it. This should be
called after the API is fully loaded.
Args:
func: (function) Method to call on each object.
"""
_LOGGER.debug('Applying function... |
import collections
from supriya.enums import CalculationRate
from supriya.synthdefs import MultiOutUGen
class XFadeRotate(MultiOutUGen):
"""
::
>>> source = supriya.ugens.In.ar(bus=0)
>>> xfade_rotate = supriya.ugens.XFadeRotate.ar(
... n=0,
... source=source,
... | w_expanded(
calculation_rate=calculation_rate,
n=n,
source=source,
)
| return ugen
# def newFromDesc(): ...
### PUBLIC PROPERTIES ###
@property
def n(self):
"""
Gets `n` input of XFadeRotate.
::
>>> source = supriya.ugens.In.ar(bus=0)
>>> xfade_rotate = supriya.ugens.XFadeRotate.ar(
... n=0,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.