repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
hanlind/nova | nova/tests/unit/volume/encryptors/test_luks.py | Python | apache-2.0 | 10,988 | 0.000091 | # Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/... | len | (unmangled_raw_key) * 8,
unmangled_raw_key)
unmangled_encoded_key = symmetric_key.get_encoded()
encryptor = luks.LuksEncryptor(self.connection_info)
self.assertEqual(encryptor._get_mangled_passphrase(
|
kimegitee/python-koans | python3/koans/about_with_statements.py | Python | mit | 3,602 | 0.004997 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutSandwichCode in the Ruby Koans
#
from runner.koan import *
import re # For regular expression string comparisons
class AboutWithStatements(Koan):
def count_lines(self, file_name):
try:
file = open(file_name)
try:
... |
# Now we write:
def count_lines2(self, file_name):
with self.FileContextManager(file_name) as file:
return len(file.readlines())
def test_counting_lines2(self):
self.assertEqual(4, self.count_lines2("example_file.txt"))
# --------------------------------------------------... | for line in file.readlines():
if re.search('e', line):
return line
def test_finding_lines2(self):
self.assertEqual('test\n', self.find_line2("example_file.txt"))
self.assertNotEqual('a', self.find_line2("example_file.txt"))
# --------------------------... |
alan-wu/neon | src/opencmiss/neon/ui/editors/spectrumeditorwidget.py | Python | apache-2.0 | 26,338 | 0.002202 | '''
Copyright 2015 University of Auckland
Licensed under t | he 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
distributed under 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 govern... |
whiterabbitengine/fifeplusplus | tools/editor/scripts/mapcontroller.py | Python | lgpl-2.1 | 18,203 | 0.02983 | # -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2013 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General ... |
instances = []
for loc in self._selection:
instances.extend(self.getInstancesFromPosition(loc.getExactLayerCoordinates() | , loc.getLayer()))
return instances
def getInstancesFromPosition(self, position, layer=None):
""" Returns all instances on a specified position
Interprets ivar _single_instance and returns only the
first instance if flag is set to True
"""
if not self._layer and not layer:
if self.debug: ... |
izacus/slo_pos | tests.py | Python | lgpl-2.1 | 987 | 0.007136 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
import slopos
class TestTagger(unittest.TestCase):
def setUp(self):
slopos.load_from_path("slopos/sl-tagger.pickle")
def testSentenceTagging(self):
tagged = slopos.tag("To je test.")
self.assertEqual(tagge... | Equal(tagged, [('To', 'ZK-SEI'), ('je', 'GP-STE-N'), ('test', 'SOMETN')])
def testUnicodeSentenceTagging(self):
tagged = slopos.tag("V kožuščku zelene lisice stopiclja jezen otrok.")
self.assertEqual(tagged, [('V', 'DM'), ('kožuščku', 'SOMEM'), ('zelene', 'PPNZER'), | ('lisice', 'SOZER,'),
('stopiclja', 'GGNSTE'), ('jezen', 'PPNMEIN'), ('otrok', 'SOMEI.'), ('.', '-None-')])
if __name__ == "__main__":
unittest.main()
|
stackforge/tricircle | tricircle/tests/unit/network/test_central_trunk_plugin.py | Python | apache-2.0 | 24,196 | 0 | # Copyright 2015 Huawei Technologies Co., Ltd.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... |
sub_ports = res.get('sub_ports')
if sub_ports:
for sub_port in sub_ports:
if sub_port['port_id'] == port_id:
sub_ports.remove(sub_port)
def delete_hook(self, model_obj):
if model_obj.get('segmentation_t... | f __init__(self):
self._segmentation_types = {'vlan': utils.is_valid_vlan_tag}
self.xjob_handler = FakeRPCAPI(self)
self.helper = helper.NetworkHelper(self)
def _get_client(self, region_name):
return FakeClient(region_name)
def fake_get_context_from_neutron_context(q_context):
... |
yeyanchao/calibre | src/calibre/ebooks/txt/processor.py | Python | gpl-3.0 | 8,709 | 0.006889 | # -*- coding: utf-8 -*-
__license__ = 'GPL v3'
__copyright__ = '2009, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
'''
Read content from txt file.
'''
import os, re
from calibre import prepare_string_for_xml, isbytestring
from calibre.ebooks.metadata.opf2 import OPFCreator
from cal... | cent <= .75:
return 'print'
| elif .15 <= block_percent <= .75:
return 'block'
# Assume unformatted text with hardbreaks if nothing else matches
return 'unformatted'
# return single if hardbreaks is false
return 'single'
def detect_formatting_type(txt):
'''
Tries to determine the formatting of the doc... |
thedep2/CouchPotatoServer | couchpotato/core/media/_base/providers/nzb/binnewz/main.py | Python | gpl-3.0 | 18,081 | 0.008683 | from binsearch import BinSearch
from nzbclub import NZBClub
from nzbindex import NZBIndex
from bs4 import BeautifulSoup
from couchpotato.core.helpers.variable import getTitle, splitString, tryInt
from couchpotato.core.helpers.encoding import simplifyString
from couchpotato.environment import Env
from couchpotato.core.... | .binaries.multimedia"
elif newsgroup == "ab.moovee":
newsgroup = "alt.binaries.moovee"
elif newsgr | oup == "abtvseries":
newsgroup = "alt.binaries.tvseries"
elif newsgroup == "abtv":
newsgroup = "alt.binaries.tv"
elif newsgroup == "a.b.teevee":
newsgroup = "alt.binaries.teevee"
... |
NifTK/NiftyNet | tests/downsample_test.py | Python | apache-2.0 | 3,371 | 0.000297 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
import tensorflow as tf
from niftynet.layer.downsample import DownSampleLayer
from tests.niftynet_testcase import NiftyNetTestCase
class DownSampleTest(NiftyNetTestCase):
def get_3d_input(self):
input_shape = (2, 16, 16, 16, 8... | 3,
'stride': 3}
self._test_nd_downsample_output_shape(rank=3,
param_dict=input_pa | ram,
output_shape=(2, 6, 6, 6, 8))
def test_3d_avg_shape(self):
input_param = {'func': 'AVG',
'kernel_size': [3, 3, 2],
'stride': [3, 2, 1]}
self._test_nd_downsample_output_shape(rank=3,
... |
readline/btb | cancer/integrate/coMut/mafSignature2plot.py | Python | gpl-2.0 | 3,469 | 0.036322 | #!/usr/bin/env python
# Kai Yu
# github.com/readline
# mafSignature2plot.py
# 150410
from __future__ import division
import os,sys,math
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
matplotlib.use('Agg')
import os,sys,matplotlib,pylab
import matplotlib.pyplot as plt
import numpy as np
def font(size):
... | eturn matplotlib.font_manager.FontProperties( | size=size,\
fname='/Share/BP/yukai/src/font/consola.ttf')
def getMatrix(sigPath):
infile = open(sigPath,'r')
countn = infile.readline().rstrip().split('=')[1]
mutList, tmpList = [],[]
sumdic = {'TA':0,'TC':0,'TG':0,'CA':0,'CG':0,'CT':0}
while 1:
line = infile.readline().rstrip()
... |
iirlas/OpenJam-2017 | sge/gfx.py | Python | gpl-3.0 | 106,231 | 0.000028 | # Copyright (C) 2012-2016 Julie Marchant <onpon4@riseup.net>
#
# This file is part of the Pygame SGE.
#
# The Pygame SGE 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, ... | is duplicated;
for example, ``"#F80"`` is equivalent to ``"#FF8800"``.
- An integer which, when written as a hexadecimal n | umber,
specifies the components of the color in the same way as an
HTML-style hex string containing 6 digits.
- A list or tuple indicating the red, green, and blue
components, and optionally the alpha component, in that
order.
"""
self.alpha = 25... |
emilleishida/snclass | snclass/matrix.py | Python | gpl-3.0 | 10,669 | 0.001312 | """
Created by Emille Ishida in May, 2015.
Class to implement calculations on data matrix.
"""
import os
import sys
import matplotlib.pylab as plt
import numpy as np
from multiprocessing import Pool
from snclass.treat_lc import LC
from snclass.util import read_user_input, read_snana_lc, translate_snid
from snclass.... | ""
# list all files in sample directory
file_list = os.listdir(self.user_choices['samples_dir'][0])
datam = []
redshift = []
sntype = []
for obj in file_list:
if 'mean' in obj:
sn_char = self.check_file(obj, epoch=check_epoch,
... | sn_char[1])
sntype.append(sn_char[2])
self.datam = np.array(datam)
self.redshift = np.array(redshift)
self.sntype = np.array(sntype)
# store results
self.store_training(file_out)
def reduce_dimension(self):
"""Perform dimensionality reduction wi... |
deyvedvm/cederj | urionlinejudge/python/1379.py | Python | gpl-3.0 | 781 | 0.006452 | """
The mean of three integers A, B and C is (A + B + C)/3. The median of three integers is the one that would be in the
middle if they are sort | ed in non-decreasing order. Given two integers A and B, return the minimum possible integer C
such that the mean and the median of A, B and C are equal.
Input
Each test case is given in a single line that contains two integers A and B (1 ≤ A ≤ B ≤ 109). The las | t test case is
followed by a line containing two zeros.
Output
For each test case output one line containing the minimum possible integer C such that the mean and the median of A, B
and C are equal.
"""
A = int
B = int
C = int
while B != 0 and C != 0:
B, C = map(int, input().split())
if 1 <= B <= C <= 10 ... |
googleads/google-ads-python | google/ads/googleads/v10/enums/types/asset_set_asset_status.py | Python | apache-2.0 | 1,168 | 0.000856 | # -*- coding: utf-8 -*-
# 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, software
# distributed under 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 ... |
apple/coremltools | coremltools/converters/mil/mil/passes/test_layernorm_instancenorm_fusion.py | Python | bsd-3-clause | 15,619 | 0.002753 | # Copyright (c) 2021, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import numpy as np
import pytest
from coremltools.converters.mil.mil import Builder as mb
from coreml... | [-1,-2] and so on
and gamma and beta are constants with rank equal to the length of the axes parameter.
"""
| shape = (3, 5, 6)
rank = len(shape)
axes = list(range(rank - axes_size, rank))
@mb.program(input_specs=[mb.TensorSpec(shape=shape)])
def prog(x):
x1 = mb.reduce_mean(x=x, axes=axes, keep_dims=True)
x2 = mb.sub(x=x, y=x1)
x2 = mb.square(x=x2)
... |
Got-iT-Services-Inc/pyDebugger | Debug.py | Python | gpl-3.0 | 2,272 | 0.007482 | #! /usr/bin/env python3
#############################################################
# Title: Python Debug Class #
# Description: Wrapper around Debugging and Logging for any #
# python class #
# Version: ... | PrintDebugLevel == True:
sCN += "[" + DebugLevel + "] "
sCN += self.ClassName + ":"
if self.__Debug == True:
print(sCN + sString,end=endd)
if self.__LogToFile == True:
try:
with open("/var/log/" + self.ClassN... | as e:
print(self.ClassName + "_Logging Error: " + str(e))
def SetDebugLevel(self,DebugLevel):
if "," in DebugLevel:
self.__DebugLevel = DebugLevel.split(",")
else:
self.__DebugLevel = DebugLevel
def __init__(self,otherSelf, Debug, LogToFile, DebugLe... |
smartfile/django-mysqlpool | django_mysqlpool/backends/mysqlpool/base.py | Python | mit | 3,693 | 0 | # -*- coding: utf-8 -*-
"""The top-level package for ``django-mysqlpool``."""
# These imports make 2 act like 3, making it easier on us to switch to PyPy or
# some other VM if we need to for performance reasons.
from __future__ import (absolute_import, print_function, unicode_literals,
division)... | that needs to be passed to MySQLdb.
"""
def __hash__(self):
"""Calculate the hash of this ``dict``.
The hash is determined by converting to a sorted tuple of key-value
pairs and hashing that.
"""
items = [(n, tuple(v)) for n, v in self.items() if isiterable(v)]
... | .
DatabaseWrapper = base.DatabaseWrapper
# Wrap the old connect() function so our pool can call it.
OldDatabase = OldDatabaseProxy(base.Database.connect)
def get_pool():
"""Create one and only one pool using the configured settings."""
global MYSQLPOOL
if MYSQLPOOL is None:
backend_name = getatt... |
qadium-memex/linkalytics | linkalytics/factor_validator/coincidence/coincidence.py | Python | apache-2.0 | 1,870 | 0.01123 | from datetime import datetime
from ... search import get_results, phone_hits, both_hits
from ... run_cli import Arguments
from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(16)
def unique_featu | res(feature, data):
features = set()
for v in data.values():
try:
if isinstance(v[feature], str):
| features.add(v[feature])
elif isinstance(v[feature], list):
for i in v:
features.add(v[feature])
except:
pass
return features
def parsetime(timestring):
return datetime.strptime(timestring, '%Y-%m-%dT%H:%M:%S').ctime()
def specific_ter... |
mitsei/dlkit | dlkit/abstract_osid/authorization/managers.py | Python | mit | 119,516 | 0.002083 | """Implementations of authorization abstract base class managers."""
# pylint: disable=invalid-name
# Method names comply with OSID specification.
# pylint: disable=no-init
# Abstract classes do not define __init__.
# pylint: disable=too-few-public-methods
# Some interfaces are specified as 'markers' and in... | -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_authorization_lookup(self):
"""Tests if an authorization lookup service is supported.
An authorization lookup service defines methods to access
authorizations.
|
:return: true if authorization lookup is supported, false otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.*
"""
return # boolean
@abc.abstractmethod
def supports_authorization_query(self):
"""Tests if an authorization ... |
ESOedX/edx-platform | openedx/core/djangoapps/crawlers/tests/test_models.py | Python | agpl-3.0 | 1,412 | 0.002126 | # -*- coding: utf-8 -*-
"""
Tests that the request came from a crawler or not.
"""
from __future__ import absolute_import
import ddt
from django.test import TestCase
from django.http import HttpRequest
from ..models import CrawlersConfig
@ddt.ddt
class CrawlersConfigTest(TestCase):
def setUp(self):
supe... | @ddt.data(
"Mozilla/5.0 (Linux; Android 5.1; Nexus 5 Build/LMY47I; wv) AppleWebKit/537.36 (KHTML, like Gecko) "
"Version/4.0 Chrome/47.0.2526.100 Mobile Safari/537.36 edX/org.edx.mobile/2.0.0",
| "Le Héros des Deux Mondes",
)
def test_req_user_agent_is_not_crawler(self, req_user_agent):
"""
verify that the request did not come from a crawler.
"""
fake_request = HttpRequest()
fake_request.META['HTTP_USER_AGENT'] = req_user_agent
self.assertFalse(Crawle... |
citrix-openstack-build/sahara | sahara/conductor/manager.py | Python | apache-2.0 | 14,758 | 0 | # Copyright (c) 2013 Mirantis 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 applicable law or agreed to in writ... | node_group_remove(self, context, node_group):
"""Destroy the node_group or raise if it does not exist."""
self.db.node_group_remove(cont | ext, node_group)
# Instance ops
def instance_add(self, context, node_group, values):
"""Create an Instance from the values dictionary."""
values = copy.deepcopy(values)
values = _apply_defaults(values, INSTANCE_DEFAULTS)
values['tenant_id'] = context.tenant_id
return se... |
JoKaWare/WTL-DUI | tools/grit/grit/node/message.py | Python | bsd-3-clause | 10,287 | 0.009138 | #!/usr/bin/env python
# Copyright (c) 2012 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.
'''Handling of the <message> element.
'''
import re
import types
from grit.node import base
import grit.format.rc_header
import ... | 'validation_expr', 'use_name_for_id', 'sub_variable']:
return False
if (name in ('translateable', 'sub_variable') and
value not in ['true', 'false']):
return False
return True
def MandatoryAttributes(self):
return ['name|offset']
def DefaultAttributes(self):
r... | alse',
'translateable' : 'true',
'use_name_for_id' : 'false',
'validation_expr' : '',
}
def GetTextualIds(self):
'''
Returns the concatenation of the parent's node first_id and
this node's offset if it has one, otherwise just call the
superclass' implementation
'''
if 'o... |
jarnoln/mitasny | tasks/admin.py | Python | mit | 238 | 0 | from django.contrib import admin
from tasks import models
admin.site.register(m | odels.Project)
admin.site.register(models.Priority)
admin.site.register(models.TaskSt | atus)
admin.site.register(models.Phase)
admin.site.register(models.Task)
|
KaranToor/MA450 | google-cloud-sdk/lib/googlecloudsdk/core/resource/resource_exceptions.py | Python | apache-2.0 | 1,244 | 0.008039 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | import exceptions
class Error(exceptions.Error):
"""A bas | e exception for all recoverable resource errors => no stack trace."""
pass
class InternalError(exceptions.InternalError):
"""A base exception for all unrecoverable resource errors => stack trace."""
pass
class ExpressionSyntaxError(Error):
"""Resource expression syntax error."""
pass
class ResourceRegis... |
willb/wallaroo | clients/python-wallaroo/wallaroo/client/node.py | Python | apache-2.0 | 5,705 | 0.009465 | # Copyright (c) 2013 Red Hat, Inc.
# Author: William Benton (willb@redhat.com)
# 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 r... | ame = property(pag(" | name"))
memberships = property(*pags("memberships"))
identity_group = property(lambda self : self.cm.make_proxy_object("group", self.attr_vals["identity_group"], refresh=True))
provisioned = property(*pags("provisioned"))
last_updated_version = property(pag("last_updated_version"))
modifyMember... |
MisterPup/Ceilometer-Juno-Extension | ceilometer/alarm/evaluator/threshold.py | Python | apache-2.0 | 8,086 | 0 | #
# Copyright 2013 Red Hat, Inc
#
# Author: Eoghan Glynn <eglynn@redhat.com>
# Author: Mehdi Abaakouk <mehdi.abaakouk@enovance.com>
#
# 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
#
# ht... | rm stats retrieval failed'))
return []
def _sufficient(self, alarm, statistics):
"""Check for the sufficiency of the data for evaluation.
Ensure there is suffi | cient data for evaluation, transitioning to
unknown otherwise.
"""
sufficient = len(statistics) >= self.quorum
if not sufficient and alarm.state != evaluator.UNKNOWN:
reason = _('%d datapoints are unknown') % alarm.rule[
'evaluation_periods']
reaso... |
GrognardsFromHell/TemplePlus | tpdatasrc/tpgamefiles/rules/d20_actions/action02603_feat_divine_spell_power.py | Python | mit | 346 | 0.040462 | from toee import *
import tpactions
def G | etActionName():
return "Divine Spell Power"
def GetActionDefinitionFlags():
return D20ADF_None
def GetTargetingClassification():
return D20TC_Target0
def GetActionCostType():
return D20ACT_N | ULL
def AddToSequence(d20action, action_seq, tb_status):
action_seq.add_action(d20action)
return AEC_OK |
commonsmachinery/commonshasher | config.py | Python | gpl-3.0 | 246 | 0.004065 | WMC_RATE_LIMIT = 5
WMC_USER = ''
WMC_PASSWORD = ''
BLOCKHASH_COMMAND = 'blockhash'
SQLALCHEMY_URL = 'postgresql://user:pass@localhost/test'
BROKER_URL = 'amqp://guest@localhost/'
try:
from config_local import *
except ImportError:
pas | s
| |
enritoomey/DiagramaDeRafagasyManiobras | diagramas_class.py | Python | mit | 20,658 | 0.004211 | import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import fsolve
import argparse
import json
class Diagramas(object):
def __init__(self, datos, w, h, den, units='SI'):
self.CAM = datos["CAM"]
self.sw = datos["sw"]
self.a3D = datos["a3D"]
self.MTOW = datos["MTOW"... | z + self.fgm)
def calculos(self):
self.R1 = sel | f.MLW[self.units] / self.MTOW[self.units]
self.R2 = self.MZFW[self.units] / self.MTOW[self.units]
self.fgm = np.sqrt(self.R2 * np.tan(np.pi * self.R1 / 4.0))
self.fgz = 1 - self.Zmo[self.units] / self.cte_fgz[self.units]
self.fg = 0.5 * (self.fgz + self.fgm)
self.carga_alar[self... |
Glandos/FreeMobile-SMS | config.sample.py | Python | mit | 82 | 0 | # -*- coding: utf-8 -*-
users = {
'Jean-jacques': ('123 | 45678', | 'api-key'),
}
|
safwanrahman/kitsune | kitsune/products/tests/test_templates.py | Python | bsd-3-clause | 6,625 | 0.001057 | from django.conf import settings
from django.core.cache import cache
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.products.models import HOT_TOPIC_SLUG
from kitsune.products.tests import ProductFactory, TopicFactory
from kitsune.questions.models import QuestionLocale
from kitsune.search.t... | tatus_code)
doc | = pq(r.content)
eq_(3, len(doc('#document-list > ul > li')))
eq_(p.slug, doc('#support-search input[name=product]').attr['value'])
def test_document_listing_order(self):
"""Verify documents are sorted by display_order and number of helpful votes."""
# Create topic, product and docu... |
ifduyue/sentry | src/sentry/api/exceptions.py | Python | bsd-3-clause | 2,003 | 0.000499 | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.exceptions import APIException
class ResourceDoesNotExist(APIException):
status_code = status.HTTP_404_NOT_FOUND
class SentryAPIException(APIExceptio | n):
code = ''
message = ''
def __init__(self, code=None, message=None, detail=None, **kwargs):
if detail is None:
detail = {
'code': code or self.code,
'message': message or self.message,
'extra': kwargs,
}
super(Sentr... | ntly don't get used
code = 'resource-moved'
message = 'Resource has been moved'
def __init__(self, new_url, slug):
super(ProjectMoved, self).__init__(
url=new_url,
slug=slug,
)
class SsoRequired(SentryAPIException):
status_code = status.HTTP_401_UNAUTHORIZED
... |
Team4819/Yeti | tests/resources/engine/module2.py | Python | bsd-3-clause | 96 | 0.010417 | import yeti
class | ModuleUno(yeti.Module):
def module_init(self):
raise Excep | tion()
|
JaeGyu/PythonEx_1 | MatplotlibEx.py | Python | mit | 116 | 0.051724 | import matplotlib.pyplot as pl
import random as rnd
a = rnd.sample(range( | 10),10)
pri | nt([a])
pl.imshow([a])
|
genokan/Python-Learning | scraper.py | Python | gpl-2.0 | 443 | 0.031603 | i | mport time
import urllib2
from urllib2 import urlopen
import datetime
from sys import argv
website = argv[1]
topSplit = '<div class=\"post\">'
bottomSplit = '<div class=\"sp_right\">'
def main():
try:
sourceCode = urllib2.urlopen(website).read()
#print sourceCode
sourceSplit = sourceCode.split(topSplit)[1].... | |
kjwilcox/digital_heist | src/tile.py | Python | gpl-2.0 | 2,393 | 0.006268 | #!/usr/bin/python3
import exhibition
from data import TILE_SIZE
import pygame
import collections
import logging
log = logging.getLogger(__name__)
DEBUG_RENDER_COORDS = True
class Tile:
""" A tile represents one tile in an area's map.
It has an image, a position rectangle, and an optional collision rect... |
self.collision_rect = None
self.image = None
if DEBUG_RENDER_COORDS:
font = pygame.font.Font(None, 24)
self.coord_text = font.render("({}, {})".format(self.tile_pos[0], self.tile_pos[1]), True, (0, 0, 0, 100))
def render(self, camera):
""" Renders t... | pleft)
screen.blit(self.image, pos)
if DEBUG_RENDER_COORDS:
x, y = pos
screen.blit(self.coord_text, (x + 4, y + 4))
##################################
class FloorTile(Tile):
def __init__(self, pos):
super().__init__(pos)
self.image = exhibition.ima... |
KAMI911/histogrammer | libs/timing.py | Python | mpl-2.0 | 609 | 0 | # -*- coding: cp1250 -*-
try:
import datetime
import time
except ImportError as | err:
print("Error import module: " + str(err))
exit(128)
__author__ = 'kszalai'
class Timing:
def __init__(self):
self.start = time.clock()
def end(self):
elapsed = time.clock() - self.start
# return self.__seconds_to_str(elapsed)
return str(datetime.timedelta(second... | d.%03d" % \
reduce(lambda ll, b: divmod(ll[0], b) + ll[1:],
[(t * 1000,), 1000, 60, 60])
|
Autostew/autostew | autostew_web_session/urls.py | Python | agpl-3.0 | 1,673 | 0.004782 | from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from django.views.generic.base import TemplateView
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from autostew_web_session.models.models import Track
from autostew_web_session.... | ailView.as_view(), name='track'),
url(r'^list/?$', SessionList.as_view(), name='sessions'),
url(r'^servers/?$', ListView.as_view(model=Server), name='servers'),
url(r'^servers/(?P<slug>.+)/?$', DetailView.as_view(model=Server, slug_fie | ld='name'), name='server'),
url(r'^(?P<pk>[0-9]+)/?$', SessionView.as_view(), name='session'),
url(r'^(?P<pk>[0-9]+)/events/?$', views.SessionEvents.as_view(), name='events'),
url(r'^(?P<session_id>[0-9]+)/participant/(?P<participant_id>[0-9]+)/?$', ParticipantDetailView.as_view(), name='participant'),
... |
agry/NGECore2 | scripts/mobiles/endor/frenzied_donkuwah.py | Python | lgpl-3.0 | 1,767 | 0.032258 | import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate... | reatureName('frenzied_donkuwah')
mobileTemplate.setLevel(78)
mobileTemplate.setDifficulty(Difficulty.NORMAL)
mobileTemplate.setMinSpawnDistance(3)
mobileTemplate.setMaxSpawnDistance(5)
mobileTemplate.setDeathblow(True)
mobileTemplate.setSocialGroup('donkuwah tribe')
mobileTemplate.setAssistRange(1)
mo... | ptions.ATTACKABLE)
mobileTemplate.setStalker(True)
templates = Vector()
templates.add('object/mobile/shared_jinda_male.iff')
templates.add('object/mobile/shared_jinda_female.iff')
mobileTemplate.setTemplates(templates)
weaponTemplates = Vector()
weapontemplate = WeaponTemplate('object/weapon/mele... |
jolbyandfriends/python-bandsintown | bandsintown/client.py | Python | mit | 4,358 | 0.000688 | try:
from urllib.parse import quote, urljoin
except ImportError:
from urllib import quote
from urlparse import urljoin
import requests
class BandsintownError(Exception):
def __init__(self, message, response=None):
self.message = message
| self.response = response
def __str__(self):
return self.message
class BandsintownInvalidAppIdError(BandsintownError):
pass
class BandsintownInvalidDateFormatError(BandsintownError):
pass
class Client(object):
api_base_url = 'https://rest.bandsintown.com'
def __init__(self, app_id):... | def request(self, path, params={}):
"""
Executes a request to the Bandsintown API and returns the response
object from `requests`
Args:
path: The API path to append to the base API URL for the request
params: Optional dict to tack on query string parameters to... |
anoopvalluthadam/bztools | auto_nag/scripts/email_nag.py | Python | bsd-3-clause | 24,245 | 0.003465 | #!/usr/bin/env python
"""
A script for automated nagging emails based on passed in queries
These can be collated into several 'queries' through the use of multiple query files with
a 'query_name' param set eg: 'Bugs tracked for Firefox Beta (13)'
Once the bugs have been collected from Bugzilla they are sorted into buc... | = template.render(queries=template_params, show_comment=show_comment)
if manager_email is not None and manager_email not in cclist:
cclist.append(manager_email)
| # no need to and cc the manager if more than one email
if len(toaddrs) > 1:
for email in toaddrs:
if email in cclist:
toaddrs.remove(email)
if cclist == ['']:
cclist = None
if rollup:
joined_to = ",".join(rollupEmail)
else:
joined_to = ",".jo... |
stfc/MagDB | client/magdb-discover.py | Python | apache-2.0 | 5,206 | 0.00365 | #!/usr/bin/env python2
from os import listdir
from os.path import isfile, isdir, join, dirname
from re import sub
from urllib import urlopen
from subprocess import Popen, PIPE
from configparser import ConfigParser
import fcntl, socket, struct
def getHwAddr(ifname):
"""The pure python solution for this problem un... | data = fh.read()
fh.close()
data = data.splitlines()
data = [ l.split(': ', 1) for l in data ]
# Initialise structure
sections = [{}]
for line in data:
... | ne) == 2:
key, value = line
# Munge the keys slightly
key = sub(r'\(.+\)', '', key)
key = key.title().replace(' ', '')
sections[-1][key] = value
... |
dssg/tweedr | tweedr/emr/gnip_wc.py | Python | mit | 1,253 | 0.00399 | from mrjob.job import MRJob
from mrjob.protocol import JSONValueProtocol
import json
class WordCount(MRJob):
'''
The default MRJob.INPUT_PROTOCOL is `RawValuePr | otocol`, but we are reading tweets,
so we'll add a | parser before we even get to the mapper.
'''
# incoming line needs to be parsed (I think), so we set a protocol to do so
INPUT_PROTOCOL = JSONValueProtocol
def mapper(self, key, line):
'''The key to the first mapper in the step-pipeline is always None.'''
# GNIP-style streams sometime... |
WiproOpenSourcePractice/bdreappstore | enu/real_time_event_detection/hadoopstream/reducer_post.py | Python | apache-2.0 | 2,141 | 0.015413 | #!/usr/bin/env python
import sys
import os
os.environ['MPLCONFIGDIR'] = "/tmp/"
import pandas as pd
import numpy as np
import commands
import csv
from sklearn import svm
from sklearn.cross_validation import StratifiedKFold
from sklearn import preprocessing
from sklearn.externals import joblib
current_key = None
key... |
w = csv.writer(f)
w.writerow(("Day","Event"))
for elem in dayList:
w.writerow((elem[0],elem[1]))
f.close()
#print commands.getoutput("ls")
#print commands.getoutput("hadoop fs -rm /user/dropuser/schlumberger-result/"+fname)
print commands.getoutput("hadoop f | s -put "+fname+" /user/dropuser/schlumberger-result/")
|
apllicationCOM/youtube-dl-api-server | youtube_dl_server/youtube_dl/extractor/porn91.py | Python | unlicense | 2,548 | 0.000808 | # encoding: utf-8
from __future__ import unicode_literals
from ..compat import compat_urllib_parse
from .common import InfoExtractor
from ..utils import (
parse_duration,
int_or_none,
ExtractorError,
)
class Porn91IE(InfoExtractor):
IE_NAME = '91porn'
_VALID_URL = r'(?:https?://)(?:www\.|)91porn\... | oad_webpage(url, video_id, 'get HTML content')
if '作为游客,你每天只可观看10个视频' in webpage:
raise ExtractorError('91 Porn says: Daily limit 10 videos exceeded', expected=True)
title = self._search_regex(
r'<div id="viewvideo-title">([^<]+)</div>', webpage, 'title')
title = title.... | file_id = self._search_regex(
r'so.addVariable\(\'file\',\'(\d+)\'', webpage, 'file id')
sec_code = self._search_regex(
r'so.addVariable\(\'seccode\',\'([^\']+)\'', webpage, 'sec code')
max_vid = self._search_regex(
r'so.addVariable\(\'max_vid\',\'(\d+)\'', webp... |
skilstak/code-dot-org-python | solutions/stage19-artist5/s1level108.py | Python | unlicense | 449 | 0.013363 | import sys
sys.path.append('../..')
import codestudio
z = codestudio.load('s1leve | l108')
z.speed = 'faster'
def draw_tree(depth,branches):
if depth > 0:
z.color = z.random_color()
z.move_forward(7*depth)
z.turn_left(130)
for count in range(branches):
z.turn_right(180/branches)
draw_tree(depth-1,branches)
z.turn_left(50)
| z.jump_backward(7*depth)
draw_tree(9,2)
z.wait()
|
ndparker/tdi | tests/tools/js_escape_string.py | Python | apache-2.0 | 1,877 | 0.007991 | #!/usr/bin/env python
import warnings as _warnings
_warnings.resetwarnings()
_warnings.filterwarnings('error')
from tdi.tools import javascript
x = javascript.escape_string(u'\xe9--"\'\\-----]]></script>')
print type(x).__name__, x
x = javascript.escape_string(u'\xe9---"\'\\----]]></script>', inlined=False)
print ty... | scape_string('\xe9--"\'\\-----]]></script>')
print type(x).__name__, x
x = javascript.escape_string('\xe9---"\'\\----]]></script>', inlined=False)
print type(x).__name__, x
try:
x = javascript.escape_string('\xe9--"\'\\-----]]></script>',
encoding='utf-8'
)
except UnicodeError:
print "UnicodeError... | escape_string('\xe9--"\'\\-----]]></script>',
inlined=False, encoding='utf-8'
)
except UnicodeError:
print "UnicodeError - OK"
x = javascript.escape_string('\xc3\xa9---"\'\\----]]></script>',
encoding='utf-8'
)
print type(x).__name__, x
x = javascript.escape_string('\xc3\xa9---"\'\\----]]></script... |
davinellulinvega/COM1005 | Lab8/wipe.py | Python | gpl-3.0 | 2,414 | 0.000829 | names = list()
times = list()
keys = list()
names.append("HeadPitch")
times.append([0.96, 1.68, 3.28, 3.96, 4.52, 5.08])
keys.append([-0.0261199, 0.427944, 0.308291, 0.11194, -0.013848, 0.061318])
names.append("HeadYaw")
times.append([0.96, 1.68, 3.28, 3.96, 4.52, 5.08])
keys.append([-0.234743, -0.622845, -0.113558, ... | 36, 2.96, 3.64, 4.2, 4.76])
keys.append([0.0767419, -0.59515, -0.866668, -0.613558, 0.584497, 0.882091])
names.append("RShoulderRoll")
times.append([0.64, 1.36, 2.96, 3.64, 4.2, 4.76])
keys.append([-0.019984, -0.019984, -0.615176, -0.833004, -0.224006, -0.214801])
names.append("RWristY | aw")
times.append([1.36, 2.96, 3.64, 4.76])
keys.append([-0.058334, -0.0521979, -0.067538, -0.038392])
def run_animation(motion):
"""Use the motion module to run the angular interpolations and execute the animation
:param motion: the ALMotion module
:return the id of the request
"""
# Req... |
brian-joseph-petersen/oply | interpreter/execute.py | Python | mit | 503 | 0.035785 | from interpreter.heap import stringify
from interpreter.interpret import DTREE, CTREE
cla | ss execute():
def __init__( self, program ):
self.len = 0
self.heap = {}
self.stack = []
H = "H" + str( self.len )
self.heap[H] = { "$": "nil" }
self.len = self.len + 1
self.stack.append( H )
for declaration in program[0]: DTREE( self | , declaration )
for command in program[1]: CTREE( self, command )
stringify( self ) |
GoodRx/pyramid-sendgrid-webhooks | tests/test_pyramid_sendgrid_webhooks.py | Python | mit | 6,637 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_pyramid_sendgrid_webhooks
----------------------------------
Tests for `pyramid_sendgrid_webhooks` module.
"""
from __future__ import unicode_literals
import unittest
import pyramid_sendgrid_webhooks as psw
from pyramid_sendgrid_webhooks import events, errors
... | = self._createGrabber()
request = self._createRequest(self._makeOne())
psw.receive_events(request)
self.assertEqual(len(grabber.events), 1)
def test_event_parsed_from_request(self):
app = self._createApp()
grabber = app.grabber
app.post_json(self._PATH, [self._make... | est_multiple_events_parsed_from_request(self, n=3):
app = self._createApp()
grabber = app.grabber
app.post_json(self._PATH, [self._makeOne()] * n)
self.assertEqual(len(grabber.events), n)
def test_specific_event_caught(self):
grabber = self._createGrabber(events.BounceEvent... |
unclev/vk.unclev.ru | extensions/forwarded_messages.py | Python | mit | 1,156 | 0.021683 | # coding: utf-8
# This file is a part of VK4XMPP transport
# © simpleApps, 2013 — 2015.
from datetime import datetime
if not require("attachments"):
raise AssertionError("'forwardMessages' requires 'attachments'")
BASE_SPACER = chr(32) + unichr(183) + chr(32)
def parseForwar | dedMessages(self, msg, depth=0):
body = ""
if msg.has_key("fwd_messages"):
spacer = BASE_SPACER * depth
body = "\n" + spacer
body += _("Forwarded messages:")
fwd_messages = sorted(msg["fwd_messages"], sortMsg)
for fwd in fwd_messages:
| source = fwd["user_id"]
date = fwd["date"]
fwdBody = escape("", uhtml(compile_eol.sub("\n" + spacer + BASE_SPACER, fwd["body"])))
date = datetime.fromtimestamp(date).strftime("%d.%m.%Y %H:%M:%S")
name = self.vk.getUserData(source)["name"]
body += "\n%s[%s] <%s> %s" % (spacer + BASE_SPACER, date, name, ... |
Tayamarn/socorro | socorro/unittest/external/postgresql/unittestbase.py | Python | mpl-2.0 | 3,175 | 0 | # 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 configman import ConfigurationManager, Namespace
from configman.converters import list_converter, class_converter
... | ql.crashstorage.'
'PostgreSQLCrashStorage',
from_string_converter=class_converter
)
required_config.add_option(
name='database_superusername',
default='test',
doc='Username to connect to database',
) |
required_config.add_option(
name='database_superuserpassword',
default='aPassword',
doc='Password to connect to database',
)
required_config.add_option(
name='dropdb',
default=False,
doc='Whether or not to drop database_name',
exclude_from_print_con... |
urbn/kombu | t/unit/transport/test_librabbitmq.py | Python | bsd-3-clause | 5,055 | 0 | from __future__ import absolute_import, unicode_literals
import pytest
from case import Mock, patch, skip
try:
import librabbitmq
except ImportError:
librabbitmq = None # noqa
else:
from kombu.transport import librabbitmq # noqa
@skip.unless_module('librabbitmq')
class lrmqCase:
pass
class test... | .fileno(), self.T.on_readable, conn, loop,
)
def test_verify_connection(self):
conn | = Mock(name='connection')
conn.connected = True
assert self.T.verify_connection(conn)
def test_close_connection(self):
conn = Mock(name='connection')
self.client.drain_events = 1234
self.T.close_connection(conn)
assert self.client.drain_events is None
conn.c... |
DonaldTrumpHasTinyHands/tiny_hands_pac | tiny_hands_pac/settings/base.py | Python | mit | 6,665 | 0.0006 | """
Django settings for tiny_hands_pac project.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import os
from os.path import abspath, dirname, join, normpath
from ... | = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.mess... | o.middleware.security.SecurityMiddleware',
'wagtail.wagtailcore.middleware.SiteMiddleware',
'wagtail.wagtailredirects.middleware.RedirectMiddleware',
)
ROOT_URLCONF = 'tiny_hands_pac.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'A... |
rooi/CouchPotatoServer | couchpotato/core/notifications/pushbullet/main.py | Python | gpl-3.0 | 2,483 | 0.012485 | from couchpotato.core.helpers.encoding import toUnicode
from couchpotato.core.helpers.variable import tryInt
from couchpotato.core.logger import CPLog
from couchpotato.core.notifications.base import Notification
import base64
import json
log = CPLog(__name__)
class Pushbullet(Notification):
url = 'https://api.p... | try:
base64string = base64.encodestring('%s:' % self.conf('api_key'))[:-1]
headers = {
"Authorization": "Basic %s" % base64string
}
if cache:
return self.getJsonData(self.url % method, headers = headers, data = kwargs)
els... | data = self.urlopen(self.url % method, headers = headers, data = kwargs)
return json.loads(data)
except Exception, ex:
log.error('Pushbullet request failed')
log.debug(ex)
return None
|
aerostitch/nagios_checks | hdfs_disk_usage_per_datanode.py | Python | gpl-2.0 | 3,375 | 0.002963 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Joseph Herlant <herlantj@gmail.com>
# File name: hdfs_disk_usage_per_datanode.py
# Creation date: 2014-10-08
#
# Distributed under terms of the GNU GPLv3 license.
"""
This nagios active check parses the Hadoop HDFS web interface url:
http://<namenode>:<port>/d... | Herlant'
__credits__ = ['Joseph Herlant']
__license__ = 'GNU GPLv3'
__version__ = '1.0.2'
__maintainer__ = 'Joseph Herlant'
__email__ = 'herlantj@gmail.com'
__status__ = 'Production'
__website__ = 'https://github.com/aerostitch/'
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import argparse, s... | ument to get help
parser = argparse.ArgumentParser(
description='A Nagios check to verify all datanodes disk usage in \
an HDFS cluster from the namenode web interface.')
parser.add_argument('-n', '--namenode', required=True,
help='hostname of the namenode of the ... |
jucimarjr/IPC_2017-1 | lista04/lista04_lista02_questao21.py | Python | apache-2.0 | 2,408 | 0.014632 | #----------------------------------------------------------------------------------------------------------------------#
# Introdução a Programação de Computadores - IPC
# Universidade do Estado do Amazonas - UEA
#
# Adham Lucas da Silva Oliveira 1715310059
# Alexandre Marques Uchôa 1715310028
# A... | wenty_five_cents = money//0.25
money = money - ( | twenty_five_cents * 0.25)
ten_cents = money//0.10
money = money - (ten_cents * 0.10)
five_cents = money//0.05
money = money - (five_cents * 0.05)
one_cent = money//0.01
money = money - (one_cent * 0.01)
print('NOTAS:')
print('%.0f nota(s) de R$ 100.00' % one_hundred_reals)
print('%.0f nota(s) de R$ 50.0... |
biddisco/VTK | ThirdParty/Twisted/twisted/names/dns.py | Python | bsd-3-clause | 58,390 | 0.004436 | # -*- test-case-name: twisted.names.test.test_dns -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
DNS protocol implementation.
Future Plans:
- Get rid of some toplevels, maybe.
"""
from __future__ import division, absolute_import
__all__ = [
'IEncodable', 'IRecord',
'A',... |
def str2time(s):
"""
Parse a string description of an interval into an integer number of seconds.
@param s: An interval definition constructed as an interval duration
followed by an interval unit. An interval duration is a base ten
representation of an integer. An interval unit is one o... | M (minutes), H (hours), D (days), W (weeks), or Y
(years). For example: C{"3S"} indicates an interval of three seconds;
C{"5D"} indicates an interval of five days. Alternatively, C{s} may be
any non-string and it will be returned unmodified.
@type s: text string (C{str}) for parsing; anyt... |
asphalt-framework/asphalt-web | asphalt/web/websocket.py | Python | apache-2.0 | 2,282 | 0 | from typing import Union
from asphalt.core.context import Context
from wsproto.connection import WSConnection, ConnectionType
from wsproto.events import ConnectionRequested, ConnectionClosed, DataReceived
from asphalt.web.api import AbstractEndpoint
from asphalt.web.request import HTTPRequest
from asphalt.web.servers... | def on_data(self, data: bytes) -> None:
"""Called when there is new data from the peer | ."""
|
arenadata/ambari | ambari-server/src/main/resources/stacks/BigInsights/4.2/services/KNOX/package/scripts/ldap.py | Python | apache-2.0 | 1,729 | 0.004627 | """
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 use this ... | implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
from resource_management import *
def _ldap_common():
import params
File(os.path.join(params.knox_conf_dir, 'ldap-log4j.properties'),
mode=params.mode,
group=params.k... | mode=params.mode,
group=params.knox_group,
owner=params.knox_user,
content=params.users_ldif
)
#@OsFamilyFuncImpl(os_#family=OSConst.WINSRV_FAMILY)
#def ldap():
# import params
#
# # Manually overriding service logon user & password set by the installation package
# ServiceConfi... |
ioO/billjobs | billjobs/migrations/0002_service_is_available.py | Python | mit | 478 | 0.002092 | # -*- codin | g: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-20 16:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('billjobs', '0001_initial'),
]
operations = [
migrations.AddField(
model_nam... | ),
),
]
|
mordred-descriptor/mordred | mordred/GeometricalIndex.py | Python | bsd-3-clause | 2,504 | 0.000399 | from __future__ import division
from ._base import Descriptor
from ._graph_matrix import Radius3D as CRadius3D
from ._graph_matrix import Diameter3D as CDiameter3D
__all__ = ("Diameter3D", "Radius3D", "GeometricalShapeIndex", "PetitjeanIndex3D")
class GeometricalIndexBase(Descriptor):
__slots__ = ()
explici... | eturn D
class GeometricalShapeIndex(GeometricalIndexBase):
r"""ge | ometrical shape index descriptor.
.. math::
I_{\rm topo} = \frac{D - R}{R}
where
:math:`R` is geometric radius,
:math:`D` is geometric diameter.
:returns: NaN when :math:`R = 0`
"""
since = "1.0.0"
__slots__ = ()
def description(self):
return "geometrical shape ... |
rosenvladimirov/addons | printer_tray/__openerp__.py | Python | agpl-3.0 | 1,538 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Yannick Vaucher
# 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
# pub... | ###############################
{'name': 'Report to printer - Paper tray selection | ',
'version': '8.0.1.0.1',
'category': 'Printer',
'author': "Camptocamp,Odoo Community Association (OCA)",
'maintainer': 'Camptocamp',
'website': 'http://www.camptocamp.com/',
'license': 'AGPL-3',
'depends': ['base_report_to_printer',
],
'data': [
'users_view.xml',
'ir_report_view.xml',
... |
wtpayne/hiai | a3_src/h70_internal/da/report/html_builder.py | Python | apache-2.0 | 2,607 | 0.003836 | # -*- coding: utf-8 -*-
"""
Module for the generation of docx format documents.
---
type:
python_module
validation_level:
v00_minimum
protection:
k00_public
copyright:
"Copyright 2016 High Integrity Artificial Intelligence Systems"
license:
"Licensed under the Apache License, Version 2.0 (the L... | section_list = filtered_list)
with open(filepath, 'wt') as file:
file.write(html)
# _add_title_section(document, doc_data['_metadata'])
# _add_toc_section(document)
# for item in sorted(_generate_content_items(doc_data),
# | key = _doc_data_sortkey):
# if item['section_level'] == 1:
# _add_content_section(document)
# if 0 < len(item['paragraph_list']):
# _add_content_para(document,
# level = item['section_level'],
# t... |
tuturto/pyherc | src/pyherc/rules/constants.py | Python | mit | 1,438 | 0.002086 | # -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# 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,... | ACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for various constants
"""
PIERCING_DAMAGE = 'piercing'
CRUSHING_DAMAGE = 'crushing'
SLASHING_DAMAGE = 'slashing'
ELEMENTAL_DAMAGE = 'elemental'
DARK_DAMAGE = 'dark'
LIGHT_DAMAGE... | TION = 2
NORMAL_ACTION = 4
SLOW_ACTION = 8
LONG_ACTION = 16
|
akosel/incubator-airflow | tests/contrib/hooks/test_jira_hook.py | Python | apache-2.0 | 1,861 | 0 | # -*- coding: utf-8 -*-
#
# 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
#... | dels.Connection(
conn_id='jira_default', conn_type='jira',
host='https://localhost/jira/', port=443,
extra='{"verify": "False", "project": "AIRFLOW"}'))
|
@patch("airflow.contrib.hooks.jira_hook.JIRA", autospec=True,
return_value=jira_client_mock)
def test_jira_client_connection(self, jira_mock):
jira_hook = JiraHook()
self.assertTrue(jira_mock.called)
self.assertIsInstance(jira_hook.client, Mock)
self.assertEqual(jira... |
FinnStutzenstein/OpenSlides | server/openslides/saml/urls.py | Python | mit | 229 | 0 | from django.conf.urls import url
from django.views.decorators.csrf import csrf_exempt
from . import views
urlpatterns | = [
url(r"^$", csrf_exempt(views.SamlView.as_view())),
url(r"^metadata/$", views.ser | ve_metadata),
]
|
enthought/etsproxy | enthought/mayavi/modules/slice_unstructured_grid.py | Python | bsd-3-clause | 107 | 0 | # proxy modu | le
from __future__ import absolute_import
from mayavi.modules.slice_unstructure | d_grid import *
|
sfu-ireceptor/gateway | resources/agave_apps/genoa/genoa.py | Python | lgpl-3.0 | 88 | 0 | import sys
if __name__ | == "__main__":
print("Genoa python | script")
sys.exit(0)
|
Jajcus/pyxmpp | examples/c2s_test.py | Python | lgpl-2.1 | 1,349 | 0.014837 | #!/usr/bin/python -u
# -*- coding: utf-8 -*-
import libxml2
import time
import traceback
import sys
import logging
from pyxmpp.all import JID,Iq,Presence,Message,StreamError
from pyxmpp.jabber.all import Client
class Disconnected(Exception):
pass
class MyClient(Client):
def session_started(self):
se... | ect(self):
print "Disconnected"
raise Disconnected
logger=logging.getLogger()
logger. | addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)
libxml2.debugMemory(1)
print "creating stream..."
s=MyClient(jid=JID("test@localhost/Test"),password=u"123",auth_methods=["sasl:DIGEST-MD5","digest"])
print "connecting..."
s.connect()
print "processing..."
try:
try:
s.loop(1)
finall... |
BeenzSyed/tempest | tempest/api/compute/floating_ips/test_floating_ips_actions.py | Python | apache-2.0 | 5,488 | 0.000182 | # Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | # Create server so as to use for Multiple association
new_name = rand_name('floating_se | rver')
resp, body = self.servers_client.create_server(new_name,
self.image_ref,
self.flavor_ref)
self.servers_client.wait_for_server_status(body['id'], 'ACTIVE')
self.new_server_id = bod... |
quaddra/engage | python_pkg/engage/drivers/genforma/drivertest_celery.py | Python | apache-2.0 | 2,355 | 0.001274 | resource_id = "celery-1"
_install_script = """
[ { "id": "celery-1",
"key": {"name": "Celery", "version": "2.3"},
"config_port": {
"password": "engage_129",
"username": "engage_celery",
"vhost": "engage_celery_vhost"
},
"input_ports": {
"broker": {
"BROKER_HOST": "${hos... | user_name": "${username}",
"private_ip": null,
"sudo_password": "GenForma/${username}/sudo_password"
},
"pip": {
"pipbin": "${deployment_home}/python/bin/pip"
},
"python": {
"PYTHONPATH": "${deployment_home}/python/lib/python2.7/site-packages/",
"home": "$... | ",
"type": "python",
"version": "2.7"
},
"setuptools": {
"easy_install": "${deployment_home}/python/bin/easy_install"
}
},
"output_ports": {
"celery": {
"broker": "rabbitmqctl",
"password": "engage_129",
"username": "engage_celery",
... |
wackou/smewt | smewt/actions.py | Python | gpl-3.0 | 5,613 | 0.004276 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Smewt - A smart collection manager
# Copyrig | ht (c) 2008-2013 Nicolas Wack <wackou@smewt.com>
#
# Smewt 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 Founda | tion; either version 3 of the License, or
# (at your option) any later version.
#
# Smewt 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.
#
#... |
mitodl/odl-video-service | ui/migrations/0011_collection_created_at.py | Python | bsd-3-clause | 602 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-09-12 19:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(m | igrations.Migration):
dependencies = [
("ui", "0010_video_default_sort"),
]
operations = [
migrations.AddField(
model_name="collection",
name="created_at",
field=models.DateTimeField(auto_now_add=True, null=True),
),
migrations.AlterModel... | ,
),
]
|
jiobert/python | Paracha_Junaid/Assignments/Python/Web_fund/stars.py | Python | mit | 368 | 0.048913 | # x = [4, 6, 1, 3, 5, 7, 25]
# def stars (a):
# i = 0
# while (i < len(a)):
# print '*' * a[i]
# i += 1
# stars(x)
x = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"]
def stars (a):
i = 0
while (i < len(a)):
if type(a[i]) is in | t:
| print '*' * a[i]
i+=1
else:
temp = a[i]
temp = temp.lower()
print (len(a[i])) * temp[0]
i += 1
stars(x)
|
Teekuningas/mne-python | mne/utils/tests/test_progressbar.py | Python | bsd-3-clause | 3,513 | 0 | import os.path as op
import numpy as np
from numpy.testing import assert_array_equal
import pytest
from mne.parallel import parallel_func
from mne.utils import ProgressBar, array_split_idx, use_log_level
def test_progressbar():
"""Test progressbar class."""
a = np.arange(10)
pbar = ProgressBar(a)
as... | ."""
assert capsys.readouterr().out == ''
# This must be "1" because "capsys" won't get stdout properly otherwise
parallel, | p_fun, _ = parallel_func(_identity_block_wide, n_jobs=1,
verbose=False)
arr = np.arange(10)
with use_log_level(True):
with ProgressBar(len(arr) * 2) as pb:
out = parallel(p_fun(x, pb.subset(pb_idx))
for pb_idx, x in array_spli... |
yubang/smallMonitor | lib/disk.py | Python | apache-2.0 | 903 | 0.025094 | #coding:UTF-8
"""
磁盘监控模块
"""
from config import disk
from lib | import core
import os,re
def init():
"对外接口"
sign=True
for t in disk.DISK_PATH:
warn,data=check(t)
if not warn:
login_time=time.time()
message="磁盘监控预警提示,磁盘使用率超过%s"%(disk.DISK_USED)+"%\n监控结果:"+data
message=message.decode("UTF-8")
print message
... | core.sendEmail(message)
print u"邮件已经发出"
sign=False
return sign
def getIntervalTime():
"获取检测间隔时间"
return disk.DISK_DELAY
def check(path):
"检测是否超出预警"
r=os.popen("df -h "+path)
for line in r:
data=line.rstrip()
datas=re.split(r'\s+',data)
used=d... |
endlessm/chromium-browser | third_party/llvm/lldb/examples/customization/pwd-cd-and-system/utils.py | Python | bsd-3-clause | 1,600 | 0 | """Utility for changing directories and execution of commands in a subshell."""
from __future__ import print_function
import os
import shlex
import subprocess
# Store the previ | ous working directory for the 'cd -' command.
class Holder:
"""Holds the _prev_dir_ class attribute for chdir() function."""
_prev_dir_ = None
@classmethod
def prev_dir(cls):
return cls._prev_dir_
@classmethod
def swap(cls, dir):
cls._prev_dir_ = dir
def chdir(debugger, arg... | also issue 'cd -' to change to the previous working directory."""
new_dir = args.strip()
if not new_dir:
new_dir = os.path.expanduser('~')
elif new_dir == '-':
if not Holder.prev_dir():
# Bad directory, not changing.
print("bad directory, not changing")
r... |
srirajan/lakkucast | lakkucast.py | Python | apache-2.0 | 21,535 | 0.014442 | #!/usr/bin/python
#credits : https://gist.github.com/TheCrazyT/11263599
import socket
import ssl
import select
import time
import re
import sys
from thread import start_new_thread
from struct import pack
from random import randint
from subprocess import call
import os
import fnmatch
import argparse
import logging
c... | len(data)),
self.getType(1,self.type_enum),
self.protocolVersion,
self.getType(2,self.type_string),
| len(self.source_id),
self.source_id,
self.getType(3,self.type_string),
len(self.destination_id),
self.destination_id,
... |
biomodels/BIOMD0000000155 | BIOMD0000000155/model.py | Python | cc0-1.0 | 427 | 0.009368 | i | mport os
path = os.path.dirname(os.path.realpath(__file__))
sbmlFilePath = os.path.join(path, 'BIOMD0000000155.xml')
with open(sbmlFilePath,'r') as f:
sbmlString = f.read()
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
retu... | ring(sbmlString) |
yangke/cluehunter | test/Test_objdump_addr.py | Python | gpl-3.0 | 852 | 0.023474 | '''
Created on Oct 29, 2015
@author: yangke
'''
from model.TaintVar import TaintVar
from TraceTrackTest import TraceTrackTest
class Test_objdump_addr:
def test(self):
passed_message="BINUTILS-2.23 'addr[1]' TEST PASSED!"
not_pass_message="ERRORS FOUND IN BINUTILS-2.23 'addr[1]' TEST!"
answe... | roj_path="gdb_logs/binutils-2.23/binutils-2.23"
taintVars=[TaintVar("addr",['*'])]
test=TraceTrackTest(answer_path,name,logfile_path,taintVars,passed_message,not_pass_message)
test.set_c_proj_path(c_proj_path)
passed=test.test()
return passed
if __name__ == '__main__':
test=T... | )
test.test() |
toontownfunserver/Panda3D-1.9.0 | direct/tkwidgets/Floater.py | Python | bsd-3-clause | 13,935 | 0.008396 | """
Floater Class: Velocity style controller for floating point values with
a label, entry (validated), and scale
"""
__all__ = ['Floater', 'FloaterWidget', 'FloaterGroup']
from direct.showbase.TkGlobal import *
from Tkinter import *
from Valuator import Valuator, VALUATOR_MINI, VALUATOR_FULL
from dir... | highlightthickness = 0,
scrollregion = (-width/2.0,
| -height/2.0,
width/2.0,
height/2.0))
self._widget.pack(expand = 1, fill = BOTH)
# The floater icon
self._widget.create_polyg... |
mastizada/pontoon | pontoon/api/schema.py | Python | bsd-3-clause | 3,806 | 0.000263 | import graphene
from graphene_django import DjangoObjectType
from graphene_django.debug import DjangoDebug
from pontoon.api.util import get_fields
from pontoon.base.models import (
Project as ProjectModel,
Locale as LocaleModel,
ProjectLocale as ProjectLocaleModel
)
class Stats(graphene.AbstractType):
... | eries are forbidden')
return qs.all()
def resolve_locale(obj, args, context, info):
qs = LocaleModel.objects
fields = get_fields(info)
if 'locale.localizations' in fields:
qs = qs.prefetch_related('project_locale__project')
if 'locale.localizations.project.loc... | 'code'])
schema = graphene.Schema(query=Query)
|
gabrielsaldana/sqmc | sabesqmc/quote/tests/test_forms.py | Python | agpl-3.0 | 2,384 | 0.001258 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.test import TestCase
from ..forms import QuoteForm
class TestQuoteForm(TestCase):
def setUp(self):
pass
def test_validate_emtpy_quote(self):
form = QuoteForm({'message': ''})
self.assertFals... | saje invalido'})
self.assertFalse(form.is_valid())
def test_urls_in_quote(self):
form = QuoteForm({'message': 'http://122.33.43.322'})
self.assertFalse(form.is_valid())
form = Q | uoteForm({'message': 'Me caga http://sabesquemecaga.com'})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': 'http://sabesquemecaga.com'})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': 'http://sabesquemecaga.com/asdfads/'})
self.assertFalse(form.is_v... |
six8/transloader | setup.py | Python | mit | 1,083 | 0.012927 | try:
from setuptools import setup
except ImportError:
from distutils.core | import setup
def main():
setup(
name = 'trans | loader',
packages=['transloader'],
package_dir = {'transloader':'transloader'},
version = open('VERSION.txt').read().strip(),
author='Mike Thornton',
author_email='six8@devdetails.com',
url='http://github.com/six8/transloader',
download_url='http://github.com/six8... |
ActiveState/code | recipes/Python/347462_Terminating_subprocess/recipe-347462.py | Python | mit | 817 | 0.00612 | # Create a process that won't end on its own
import subprocess
process = subprocess.Popen(['python.exe', '-c', 'while 1: pass'])
# Kill the process using pywin32
import win32api
win32api.TerminateProcess(int(process._handle), -1)
# Kill the process using ctypes
import ctypes
ctypes.windll.kernel32.TerminateProcess(... | t(process._handle), -1)
# Kill the proces using pywin32 and pid
import win32api
PROCESS_TERMINATE = 1
handle = win32api.OpenProcess(PROCESS_TERMINATE, False, process.pid)
win32api.TerminateProcess(handle, -1)
win32api.CloseHandle(handle)
# Kill the proces using ctypes and pid
import ctypes
PROCESS_TERMINATE = 1
han... | , process.pid)
ctypes.windll.kernel32.TerminateProcess(handle, -1)
ctypes.windll.kernel32.CloseHandle(handle)
|
gsehub/edx-platform | cms/djangoapps/contentstore/api/views/course_quality.py | Python | agpl-3.0 | 9,779 | 0.002761 | # pylint: disable=missing-docstring
import logging
import numpy as np
from scipy import stats
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from edxval.api import get_videos_for_course
from openedx.core.djangoapps.request_cache.middleware import request_cached
from ope... | ion in visible_sections:
visible_subsections = self._get_visible_children(section)
if get_bool_param(request, 'exclude_graded', False):
visible_subsections = [s for s in visible_subsections if not s.graded]
for subsection in visible_subsections:
unit... | ubsection)
for unit in visible_units:
leaf_blocks = self._get_leaf_blocks(unit)
unit_dict[unit.location] = dict(
num_leaf_blocks=len(leaf_blocks),
leaf_block_types=set(block.location.block_type for block in leaf_blo... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractFinebymetranslationsWordpressCom.py | Python | bsd-3-clause | 666 | 0.028529 | def extractFinebymetranslationsWordpressCom(item):
'''
Parser for 'finebymetranslations.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [ |
('Death Progress Bar', 'Death Progress Bar', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
r | eturn buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
pengzhangdev/slackbot | slackbot/plugins/component/ttsdriver/iflytek.py | Python | mit | 4,519 | 0.005567 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# iflytek.py ---
#
# Filename: iflytek.py
# Description:
# Author: Werther Zhang
# Maintainer:
# Created: Thu Sep 14 09:01:20 2017 (+0800)
#
# Change Log:
#
#
import time
from ctypes import *
from io import BytesIO
import wave
import platform
import logging
import os
... | if obj:
return obj
else:
| return defobj
class iflytekTTS():
def __init__(self, appid=None, voice_name=None, speed=None, volume=None, pitch=None):
self.__appid = not_none_return(appid, '59b4d5d4')
self.__voice_name = not_none_return(voice_name, 'xiaowanzi')
self.__speed = not_none_return(speed, 50)
self.__vol... |
cuducos/findaconf | migrations/env.py | Python | mit | 2,277 | 0.000878 | from __future__ import with_statement
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file | for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from flask import current_app
config.set_main_option('sqlal | chemy.url',
current_app.config.get('SQLALCHEMY_DATABASE_URI'))
target_metadata = current_app.extensions['migrate'].db.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def... |
avaika/avaikame | project/travel/migrations/0005_auto_20160917_2211.py | Python | gpl-3.0 | 868 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-09-17 19:11
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('travel', '0004_auto_20160319_0055'),
]
operations = [
migrations.RemoveField(
... | post',
name='category',
),
migrations.RemoveField(
model_name='post',
name='post',
),
migrations.RemoveField(
model_name='post',
name='post_en',
),
migrations.RemoveField(
model_name='post',
... | ry',
),
]
|
georgemarshall/django | django/shortcuts.py | Python | bsd-3-clause | 4,896 | 0.00143 | """
This module collects helper functions and classes that "span" multiple levels
of MVC. In other words, these functions/classes introduce controlled coupling
for convenience's sake.
"""
from django.http import (
Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect,
)
from django.template imp... |
def resolve_url(to, *args, **kwargs):
"""
Return a URL appropriate for the arguments passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urls.reverse()` will be used
to reverse-resolve th... | if hasattr(to, 'get_absolute_url'):
return to.get_absolute_url()
if isinstance(to, Promise):
# Expand the lazy instance, as it can cause issues when it is passed
# further to some Python functions like urlparse.
to = str(to)
if isinstance(to, str):
# Handle relative... |
esikachev/scenario | sahara/tests/unit/service/test_ops.py | Python | apache-2.0 | 7,257 | 0 | # Copyright (c) 2014 Mirantis 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 applicable law or agreed to in writ... | 'Order of calls is wrong')
@mock.patch('sahara.service.ops._prepare_provisioning',
return_value=(mock.Mock(), mock.Mock(), FakePlugin()))
@mock.patch('sahara.utils.general.change_cluster_status',
return_value=FakePlugin())
@mock.patch('sahara.utils.general.get_in... | ng):
del self.SEQUENCE[:]
ops.INFRA = FakeINFRA()
ops._provision_scaled_cluster('123', {'id': 1})
# checking that order of calls is right
self.assertEqual(['decommission_nodes', 'INFRA.scale_cluster',
'plugin.scale_cluster'], self.SEQUENCE,
... |
managai/myCert | vcert/wsgi.py | Python | mpl-2.0 | 1,416 | 0.000706 | """
WSGI config for vcert project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runse | rver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could int... | DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "vcert.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "vc... |
Samsung/ADBI | arch/arm/tests/blx_reg_a1.py | Python | apache-2.0 | 580 | 0.008621 | import random
from test import *
from | branch import *
def test(rm, fn):
name = 'test_blx_reg_a1_%s' % tn()
cleanup = asm_wrap(name, 'r0')
print ' adr %s, %s' % (rm, fn)
if fn.startswith('thumb'):
print ' orr %s, #1' % | (rm)
print '%s_tinsn:' % name
print ' blx %s' % (rm)
cleanup()
def iter_cases():
fun = 'thumb_fun_b thumb_fun_f arm_fun_b arm_fun_f'.split()
while True:
yield random.choice(T32REGS), random.choice(fun)
branch_helpers('b')
print ' .arm'
tests(test, iter_cases(), 30)
branch_hel... |
airbnb/airflow | tests/providers/telegram/hooks/test_telegram.py | Python | apache-2.0 | 7,973 | 0.003136 | #
# 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... | Connection(
conn_id='telegram-webhook-without-token',
conn_type= | 'http',
)
)
db.merge_conn(
Connection(
conn_id='telegram_default',
conn_type='http',
password=TELEGRAM_TOKEN,
)
)
db.merge_conn(
Connection(
conn_id='telegram-webhook-with-chat... |
snakeleon/YouCompleteMe-x64 | third_party/ycmd/third_party/jedi_deps/jedi/test/completion/lambdas.py | Python | gpl-3.0 | 1,833 | 0.022368 | # -----------------
# lambdas
# -----------------
a = lambda: 3
#? int()
a()
x = []
a = lambda x: x
#? int()
a(0)
#? float()
(lambda x: x)(3.0)
arg_l = lambda x, y: y, x
#? float()
arg_l[0]('', 1.0)
#? list()
arg_l[1]
arg_l = lambda x, y: (y, x)
args = 1,""
result = arg_l(*args)
#? tuple()
result
#? str()
result[0]... | ? float()
with_lambda(arg_l, y=1.0)[0]
#? int()
with_lambda(lambda x: x)
#? float()
with_lambda(lambda x, y: y, y=1.0)
arg_func = lambda *args, **kwargs: (args[0], kwargs['a'])
#? int()
arg_func(1, 2, a='', b=10)[0]
#? list()
arg_func(1, 2, a=[], b=10)[1]
# magic method
a = lambda: 3
#? ['__closure__']
a.__closure__
|
class C():
def __init__(self, foo=1.0):
self.a = lambda: 1
self.foo = foo
def ret(self):
return lambda: self.foo
def with_param(self):
return lambda x: x + self.a()
lambd = lambda self: self.foo
#? int()
C().a()
#? str()
C('foo').ret()()
index = C().with_param()(1)... |
macosforge/ccs-calendarserver | txdav/common/datastore/podding/migration/work.py | Python | apache-2.0 | 5,171 | 0.003674 | ##
# Copyright (c) 2015-2017 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | tem import WorkItem
from twisted.internet.defer import inlineCallbacks
from txdav.caldav.datastore.scheduling.imip.token import iMIPTokenRecord
from txdav.caldav.datastore.scheduling.work import allScheduleWork
from txdav.common.datastore.podding.migration.sync_metadata import CalendarMigrationRecord, \
CalendarO... | egateRecord, \
DelegateGroupsRecord, ExternalDelegateGroupsRecord
from txdav.common.datastore.sql_tables import schema, _HOME_STATUS_DISABLED
class HomeCleanupWork(WorkItem, fromTable(schema.HOME_CLEANUP_WORK)):
"""
Work item to clean up any previously "external" homes on the pod to which data was migrate... |
gridengine/config-api | test/test_parallel_environment.py | Python | apache-2.0 | 5,641 | 0.000709 | #!/usr/bin/env python
#
# ___INFO__MARK_BEGIN__
#######################################################################################
# Copyright 2016-2021 Univa Corporation (acquired and owned by Altair Engineering Inc.)
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file ex... | t_modify_pe():
pe = API.get_pe(PE_NAME)
slots = pe.data['slots']
pe = API.modify_pe(name=PE_NAME, data={'slots': slots + 1})
slots2 = pe.data['slots']
assert (slots2 == slots + 1)
def test_get_acls():
pel = API. | list_pes()
pes = API.get_pes()
for pe in pes:
print("#############################################")
print(pe.to_uge())
assert (pe.data['pe_name'] in pel)
def test_write_pes():
try:
tdir = tempfile.mkdtemp()
print("*************************** " + tdir)
pe_nam... |
mohittahiliani/tcp-eval-suite-ns3 | src/nix-vector-routing/bindings/modulegen__gcc_LP64.py | Python | gpl-2.0 | 373,845 | 0.015033 | from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
import pybindgen.settings
import warnings
class ErrorHandler(pybindgen.settings.ErrorHandler):
def handle_error(self, wrapper, exception, traceback_):
warnings.warn("exception %r in wrapper %s" % (exception, wrapper))
... | eAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet')
## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class]
module.add_class('Ipv4Mask', import_from_module='ns.network')
## ipv4-routing-helper.h (module 'internet'): ns3::I... | _from_module='ns.internet')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
module.add_class('Ipv6Address', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address'])
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.