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 |
|---|---|---|---|---|---|---|---|---|
eyecatchup/gomoz | win/winsetup.py | Python | gpl-3.0 | 689 | 0.063861 | from distutils.core import setup
import py2exe
opts = {
"py2exe": {
"compressed": 1,
"optimize": 2,
"ascii": 1,
"bundle_files": 1,
"packages": ["encodings"],
"dist_dir": "dist"
}
}
setup (name = "Gomoz",
fullname = | "Gomoz web scanner",
version = "1.0.1",
description = "Gomoz scanner web application",
author = "Handrix",
au | thor_email = "securfox@gmail.com",
url = "http://www.sourceforge.net/projects/gomoz/",
license = "GPL",
keywords = ["scanner", "web application", "securfox", "wxPython"],
windows = [{"script": "gomoz"}],
options = opts,
zipfile = None
)
|
plannerstack/testset | mmri/test_runner.py | Python | mit | 2,465 | 0.004462 | #!/usr/bin/env python
#
# Test a trip planner
import sys
import argparse
from importlib import import_module
import logging
from color_logging import ColoredFormatter
PROVIDER_CHOICES = ['otp', 'hpjp']
logger = logging.getLogger(__name__)
def setup_logging(options):
SUCCESS_LEVEL_NUM = 9
logging.addLevel... | help='planner URL (optional based on planner)')
parser.add_argument('-d', '--debug', action='store_true',
help='show debugging output')
parser.add_argument('-s', '--stop_on_error', action='store_true',
help='stop on first test error')
return parser.parse_args(args)
def... | der)
except ImportError:
provider = import_module("mmri.test_%s" % options.provider)
test_class = provider.TestClass(options, logger=logger)
test_class.run_tests(run_test_id=options.test)
if __name__ == '__main__':
main()
|
valentin-krasontovitsch/ansible | lib/ansible/modules/cloud/amazon/elb_classic_lb.py | Python | gpl-3.0 | 53,523 | 0.002111 | #!/usr/bin/python
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... | st of security group names to apply to t | he elb
version_added: "2.0"
health_check:
description:
- An associative array of health check configuration settings (see example)
access_logs:
description:
- An associative array of access logs configuration settings (see example)
version_added: "2.0"
subnets:
description:
-... |
anhstudios/swganh | data/scripts/templates/object/mobile/shared_dressed_theed_palace_chamberlain.py | Python | mit | 457 | 0.045952 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.tem | plate = "object/mobile/shared_dressed_theed_palace_chamberlain.iff"
result.attribute_template_id = 9
result.stfName("npc_name","human_base_male")
#### BEGIN MODIFICATIONS ####
#### END MODIFI | CATIONS ####
return result |
Daniel-CA/odoomrp-wip-public | procurement_service/models/product_product.py | Python | agpl-3.0 | 903 | 0 | # -*- coding: utf-8 -*-
# Copyright © 201 | 7 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import models, api
class ProductProduct(models.Model):
_inherit = 'product.product'
@api.multi
def _is_service_buy_make_to_order(self):
for product in self:
if (product.type... | elf.env.ref('purchase.route_warehouse0_buy').id in
product.route_ids.ids):
return True
return False
@api.multi
def need_procurement(self):
for product in self:
if product._is_service_buy_make_to_order():
return True
return ... |
reeshupatel/demo | keystone/identity/core.py | Python | apache-2.0 | 42,880 | 0.000023 | # Copyright 2012 OpenStack Foundation
#
# 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... |
from oslo.config import cfg
import six
from keystone import clean
from keystone.common import dependency
from keystone.common import driver_hints
from keystone.common import manager
from keystone import config
from keystone import exception
from keystone.i18n import _
from keystone.identity.mapping_backends import ma... | notifications
from keystone.openstack.common import importutils
from keystone.openstack.common import log
CONF = config.CONF
LOG = log.getLogger(__name__)
DOMAIN_CONF_FHEAD = 'keystone.'
DOMAIN_CONF_FTAIL = '.conf'
def filter_user(user_ref):
"""Filter out private items in a user dict.
'password', 'tena... |
DarioGT/OMS-PluginXML | org.modelsphere.sms/lib/jython-2.2.1/Lib/email/MIMEBase.py | Python | gpl-3.0 | 780 | 0.001282 | # Copyright (C) 2001,2002 Python Software Foundation
# Author: barry@zope.com (Barry Warsaw)
"""Base class for MIME specializations.
"""
from email import Message
class MIMEBase(Message.Message):
"""Base class for MIME specializations."""
def __init__(self, _maintype, _subtype, **_params):
... | intype and _subtype
arguments. Additional parameters for this header are taken from the
keyword arguments.
"""
Message.Message.__init__(self)
ctype = '%s/%s' % (_maintype, _subtype)
self.add_header('C | ontent-Type', ctype, **_params)
self['MIME-Version'] = '1.0'
|
turtledb/0install | setup.py | Python | lgpl-2.1 | 3,194 | 0.020664 | from distutils import log
from distutils.core import setup
from distutils.core import Command
from distutils.command.build_py import build_py
from distutils.command.install import install
import os
import zeroinstall
class adjust_scripts_for_home(Command):
"""setup.py install --home puts libraries in ~/lib/python, bu... | ail="zero-install-devel@lists.sourceforge.net",
url="http://0install.net",
scripts=['0install-python-fallback', '0alias'],
license='LGPL',
cmdclass={
'build_py': build_with_data,
'adjust_scripts_for_home': adjust_scripts_for_home,
'install': my_install,
},
long_descript | ion="""\
A running process is created by combining many different libraries (and other
components). In the Zero Install world, we have all versions of each library
available at all times. The problem then is how to choose which versions to
use.
The injector solves this problem by selecting components to meet a program... |
chiaki-yu/PyYu | videos/models.py | Python | lgpl-3.0 | 3,730 | 0.00256 | # coding: utf-8
from ckeditor_uploader.fields import RichTextUploadingField
from django.contrib.auth.models import User
from django.db import models
class Column(models.Model):
name = models.CharField(max_length=64, unique=True, verbose_name=u'栏目名称')
ename = models.CharField(max_length=64, unique=True, verbo... | anFi | eld(default=True, verbose_name=u'是否显示')
created_time = models.DateTimeField(auto_now_add=True, verbose_name=u'创建时间')
def __unicode__(self):
return self.title
def author_name(self):
blog_author_name = self.author.username
if self.author.first_name or self.author.last_name:
... |
nuclear-wizard/moose | python/MooseDocs/common/read.py | Python | lgpl-2.1 | 1,466 | 0.00955 | #* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserve | d, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgpl-2.1.html
"""Utiliti | es for reading files."""
import sys
import codecs
import os
def read(filename):
"""
Reads file using utf-8 encoding.
This function exists simply for convenience and not needing to remember to use "codecs" when
reading files.
Additionally, it handles the MOOSE headers automatically. The prism.js p... |
nickpack/django-project-template | docs/source/conf.py | Python | mit | 9,716 | 0.005867 | # -*- coding: utf-8 -*-
#
# {{project_name}} documentation build configuration file, created by
# sphinx-quickstart on Fri Sep 20 20:45:07 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file... | ml_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None |
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied a... |
heyglen/netobj | nettool/nettest.py | Python | mit | 14,175 | 0.001199 | # -*- coding: utf-8 -*-
import re
import ipaddress
from unidecode import unidecode
class NetTest(object):
wildcards = [ipaddress.IPv4Interface(
unicode('0.0.0.0/{}'.format(x))).network.hostmask.exploded for x in range(0, 33)]
netmasks = [ipaddress.IPv4Interface(
unicode('255.255.255.255/{}'.... | id_character_match.group(1))
raise ValueError(message)
return F | alse
return True
@staticmethod
def host(value, raise_exception=False):
if not isinstance(value, basestring):
if raise_exception:
raise TypeError('Invalid type \'{}\''.format(type(value)))
return False
if not NetTest... |
release-engineering/product-definition-center | examples/find-duplicated-contacts.py | Python | mit | 1,148 | 0 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Find components defining more than one contact with the same role.
In older versions of PDC, it was possible to have multiple contacts with the
same role. When limits for cardinality of this relationship were introduced, we
need to find all components that would not ... | nt[resource]._):
pk = component['id']
name = component['name']
release = component.get('release', {}).get('release_id', '[global]')
seen_roles = set()
for contact in compo | nent['contacts']:
if contact['contact_role'] in seen_roles:
print 'Duplicated roles for {}:{}/{}'.format(pk, release, name)
seen_roles.add(contact['contact_role'])
print ''
run('global-components')
run('release-components')
|
oser-cs/oser-website | tests/test_users/test_user.py | Python | gpl-3.0 | 2,826 | 0 | """Users tests."""
from django.contrib.auth import get_user_model, authenticate
from django.test import TestCase
from django.test import RequestFactory
from tests.utils import ModelTestCase
from users.factory import UserFactory
User = get_user_model()
class EmailAuthenticationTest(TestCase):
"""Tests to make s... | class UserModelTest(ModelTestCase):
"""Test the user model."""
model = User
field_tests = {
'username': {
'unique': False,
'blank': True,
'null': True,
},
'email': {
'unique': True,
'blank': False,
' | null': False,
},
'profile_type': {
'verbose_name': 'type de profil',
'blank': False,
'null': True,
'choices': (
(User.PROFILE_STUDENT, 'Lycéen'),
(User.PROFILE_TUTOR, 'Tuteur'),
)
},
'phone_number... |
moumoutte/django-perf-rec | django_perf_rec/orm.py | Python | mit | 3,345 | 0.000897 | # -*- coding:utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import django
import patchy
from django.db.models.deletion import get_candidate_relations_to_delete
from django.db.models.query import QuerySet
from django.db.models.query_utils import Q
from django.db.models.sql.... | ations require an alias")
annotations[arg.default_alias] = arg
- annotations.update(kwargs)
+ annotations.update(sorted(kwargs.items()))
clone = self._clone()
names = self._fields
""")
def patch_Query():
pat | chy.patch(Query.add_extra, """\
@@ -13,7 +13,7 @@
param_iter = iter(select_params)
else:
param_iter = iter([])
- for name, entry in select.items():
+ for name, entry in sorted(select.items()):
entry = f... |
klahnakoski/MoHg | setup.py | Python | mpl-2.0 | 2,261 | 0.008846 | # 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 distutils.util import convert_path
import os... | os.path.abspath(os.path.dirname(__file__))
path = lambda *p: os.path.join(root, *p)
try:
long_desc = open(path('README.txt')).read()
except Exception:
long_desc = "<Missing README.txt>"
print("Missing README.txt")
def find_packages(where='.', lib_prefix='', exclude=()):
| """
SNAGGED FROM distribute-0.6.49-py2.7.egg/setuptools/__init__.py
"""
out = []
stack=[(convert_path(where), lib_prefix)]
while stack:
where,prefix = stack.pop(0)
for name in os.listdir(where):
fn = os.path.join(where,name)
if ('.' not in name and os.path.is... |
tienhm-p4u/shorten_url | endpoint/__init__.py | Python | gpl-3.0 | 1,393 | 0 | """Endpoint to handle URL shorten request"""
from hashids import Hashids
from flask import Blueprint, request, jsonify, current_app
import models
from lib.url_validate import is_valid_url
from lib import error
api = Blueprint(__name__, "url")
@api.route("/url", methods=["POST"])
def shorten():
"""Shorten a pur... | te({"url": url})
url_id = created.id
hashid = Hashids().encode(url_id)
short_url = "http://%s%s" % (current_app.config["SHORTEN_PREFIX"], hashid)
return jsonify({"shorten_url": short_url})
@api.route("/url/<hashid>", methods=["GET"])
def decode(hashid):
"""Translate from shorten URL t | o pure URL"""
item_id = Hashids().decode(hashid)
if not item_id:
raise error.NotFound(hashid)
saved_url = models.URL.find_by_id(item_id)
if not saved_url:
raise error.NotFound(hashid)
return jsonify({"url": saved_url.url})
@api.errorhandler(error.BaseError)
def handle_error(e: er... |
smashwilson/strac | strac/rootnode.py | Python | mit | 2,306 | 0.00477 | # Copyright (C) 2009 Ashley J. Wilson
# This software is licensed as described in the file COPYING in the root
# directory of this distribution.
from storenode import StoreNode
from bundlenode import BundleNode
from packagenode import PackageNode
class RootNode(StoreNode):
"""The virtual root of a Store repositor... | that are specified by the trac.ini file as the interesting part of
the Store repository. RootNodes have only the special revision 'ONLY' and
no previous or next changeset.
"""
def __init__(self, repos, bundle_desc, package_desc):
"""Create a RootNode that will report the interesting subset ... | ated list of the same. Similarly, package_desc is either one or
many package prefixes. Either parameter may be 'ALL', which will return every
such entity in the repository, or '', which will return nothing of that type.
"""
StoreNode.__init__(self, '/', 'ONLY', StoreNode.DIRECTORY, re... |
tlake/advent-of-code | 2016/day07_internet_protocol_version_7/python/src/part2.py | Python | mit | 2,010 | 0.000995 | #!/usr/bin/env python
"""Docstring."""
import re
from functools import reduce
from collections import Counter
from common import get_input
class SSLTester:
"""."""
def __init__(self, input_list=[]):
"""Initialize."""
self.input_list = input_list
def find_aba(self, seq):
"""Retu... | aba(x) for x in seqs], [])
def has_corresponding_bab(self, input_key, seqs):
"""Return bool: <key> exists for any st | ring in <seqs>."""
key = input_key[1::] + input_key[1]
return True in [key in x for x in seqs]
def ip_supports_ssl(self, ip_string):
"""Return bool: <ip_string> supports SSL.
True:
some string in <unbracketed> contains 'aba' pattern
AND some string in <brack... |
Taywee/makerestapiclient | makerestapiclient/__init__.py | Python | mit | 313 | 0.003205 | #!/usr/bin/env python
# -*- coding: utf | -8 -*-
# Copyright © 2016 Taylor C. Richberger <taywee@gmx.com>
# This code is released under the license described in the LICENSE file
from __future__ imp | ort absolute_import, division, print_function, unicode_literals
from .makerestapiclient import make_rest_api_client
|
betogulliver/JupyterWorkflow | jupyterworkflow/data.py | Python | mit | 1,112 | 0.009892 | import os
from urllib import urlretrieve
import pandas as pd
FREEMONT_URL = "https://data.seattle.gov/api/views/65db-xm6k/rows.csv?accessType=DOWNLOAD"
def get_freemont_data(filename="Freemont.csv", url=FREEMONT_URL,
force_download=False) :
"""Download and cache the Freemont data
Param... | filename)
data = pd.read_csv("Freemont.csv", index_col="Date")#, parse_dates=True) # XXX: sloooooow
try:
data.index = pd.to_datetime(data.index, format="%m/%d/%Y %I:%M:%S %p") # XXX: fast
except TypeError:
data.index = pd | .to_datetime(data.index)
data.columns = ['West', "East"]
data['Total'] = data["West"] + data["East"]
return data
|
blaze/hdfs3 | hdfs3/core.py | Python | bsd-3-clause | 34,058 | 0.000352 | # -*- coding: utf-8 -*-
"Main module defining filesystem and file classes"
from __future__ import absolute_import
import ctypes
import logging
import os
import posixpath
import re
import warnings
import operator
import functools
from collections import deque
from .compatibility import FileNotFoundError, ConnectionErr... | pical
things to set are:
host : str (localhost)
namenode hostname or IP address, in case of HA mode it is name
of the cluster that can be fo | und in "fs.defaultFS" option.
port : int (8020)
namenode RPC port usually 8020, in HA mode port mast be None
user, ticket_cache, token, effective_user : str
kerberos things
"""
self.conf = conf.copy() if autoconf else {}
if pars:
... |
Ultimaker/Cura | plugins/GCodeGzReader/GCodeGzReader.py | Python | lgpl-3.0 | 1,298 | 0.010786 | # Copyright (c) 2020 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
import gzip
from UM.Mesh.MeshReader import MeshReader #The class we're extending/implementing.
from UM.MimeTypeDatabase import MimeTypeDatabase, MimeType #To add the .gcode.gz files to the MIME type database.
from UM.Plugi... | e File",
suffixes = ["gcode.gz"]
)
)
self._supported_extensions = [".gcode.gz"]
def _read(self, file_name):
with open(file_name, "rb") as file:
file_data = file.read()
uncompressed_gcode = gzip.decompress(file_data).decode("utf-8")
Plu... | .getInstance().getPluginObject("GCodeReader").readFromStream(uncompressed_gcode, file_name)
return result
|
ikki407/stacking | examples/Santander/scripts/ikki_NN_1.py | Python | mit | 44,881 | 0.016757 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#Genaral packages
import os, sys
import pandas as pd
import numpy as np
sys.path.append(os.getcwd())
#os.chdir('/Users/IkkiTanaka/Documents/kaggle/Santander/')
#各種PATH
from stacking.base import FOLDER_NAME, PATH, INPUT_PATH, OUTPUT_PATH, ORIGINAL_TRAIN_FORMAT, SUBMIT_FOR... | ntum=0.9, nesterov=True)
model.compile(optimizer=sgd, loss='binary_crossentropy',class_mode='binary')
return KerasClassifier(nn=model,**self.params)
PARAMS_V2 = {
'batch_size':512,
'nb_epoch':70,
'verbose':1,
'callbacks':[],
'valid... | e,
'show_accuracy':True,
'class_weight':None,#{0:0.0396, 1:0.9604},
'sample_weight':None,
'normalize':True,
'categorize_y':True
}
class ModelV2(BaseModel):
def build_model(self):
model = Sequential()
model.add(Dropo... |
jjas0nn/solvem | tensorflow/lib/python2.7/site-packages/numpy/core/setup.py | Python | mit | 41,471 | 0.001495 | from __future__ import division, print_function
import os
import sys
import pickle
import copy
import warnings
from os.path import join
from numpy.distutils import log
from distutils.dep_util import newer
from distutils.sysconfig import get_config_var
from numpy._build_utils.apple_accelerate import (
uses_accelera... | n win32, force long d | ouble format string to be 'g', not
# 'Lg', since the MS runtime does not support long double whose
# size is > sizeof(double)
if a == "Intel" or a == "AMD64":
deflist.append('FORCE_NO_LONG_DOUBLE_FORMATTING')
def check_math_capabilities(config, moredefs, mathlibs):
def check_func(func_name):
... |
icereval/osf.io | api/scopes/views.py | Python | apache-2.0 | 2,283 | 0.000876 | from rest_framework import generics, permissions as drf_permissions
from rest_framework.exceptions import NotFound
from framework.auth.oauth_scopes import CoreScopes, public_scopes
from api.base.filters import ListFilterMixin
from api.base import permissions as base_permissions
from api.scopes.serializers import Scope... | ion. Do not expect this to be stable.
"""
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
IsPublicScope,
)
required_read_scopes = [CoreScopes.SCOPES_READ]
required_write_scopes = [CoreScopes.NULL]
serializer_class = Scop... | RetrieveAPIView
def get_object(self):
id = self.kwargs[self.lookup_url_kwarg]
scope_item = public_scopes.get(id, None)
if scope_item:
scope = Scope(id=id, scope=scope_item)
self.check_object_permissions(self.request, scope)
return scope
else:
... |
apache/incubator-systemml | src/main/python/systemds/operator/algorithm/builtin/xgboostPredictClassification.py | Python | apache-2.0 | 1,910 | 0.002618 | # --------------------------------------- | ----------------------
#
# 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
# ... | n 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 ... |
Ezhil-Language-Foundation/open-tamil | solthiruthi/data_parser.py | Python | mit | 3,224 | 0.00062 | #!/usr/bin/python
# (C) 2015-2106 - Muthiah Annamalai
# parse data files for Tamil proper nouns
from __future__ import print_function
import codecs
import json
import pprint
import re
import sys
import tamil
class WordList:
# data structure for a WordList containing only one category
def __init__(self, cat)... | t in self.categories:
cat_wlen = len(cat.words)
r["dict"][cat.category] = list(cat.words)
word_count.append(cat_wlen)
r["total"] = sum(word_count)
return r
def __unicode__(self):
"print the | statistics of the wordlist etc"
rep = u"# categories = %d" % len(self.categories)
word_count = []
for cat in self.categories:
cat_wlen = len(cat.words)
rep += u" %s -> %d\n" % (cat.category, cat_wlen)
word_count.append(cat_wlen)
rep += "Total words -> ... |
locatw/Autonek | TweLiteGateway/twe_lite_gateway/gateway.py | Python | mit | 4,912 | 0.003054 | import twe_lite
import json
import queue
import sys
import time
import traceback
import yaml
from threading import Thread
from datetime import datetime
from pytz import timezone
from iothub_client import IoTHubClient, IoTHubClientError, IoTHubTransportProvider, IoTHubClientResult, IoTHubClientStatus
from iot... | = DEFAULT_PORT_NAME
if len(sys.argv) == 2:
device_id = sys.argv[1]
elif len(sys.argv) == 3:
device_id = sys.argv[1]
port_name = sys.argv[2]
else:
print_usage()
sys.exit(1)
print("Device ID: " + device_id)
print("Port name: " + port_name)
continues = True
class MonoStickTread(Thre... |
def __init__(self, mono_stick, parser, queue):
super().__init__()
self.__mono_stick = mono_stick
self.__parser = parser
self.__queue = queue
def run(self):
print("Start reading data from monostick.")
while continues:
try:
... |
oluwex/Akede | Articles/admin.py | Python | gpl-3.0 | 424 | 0.007075 | fr | om django.contrib import admin
from .models import Article
# Register your models here.
class ArticleModelAdmin(admin.ModelAdmin):
class Meta:
model = Article
list_display = ['name', 'timestamp', 'updated_time','cate | gory']
list_display_links = ['name']
search_fields = ['name', 'article']
list_filter = ['updated_time', 'author', 'category']
admin.site.register(Article, ArticleModelAdmin) |
kinetifex/maya-kinetifex | scripts/kinetifex/poses.py | Python | gpl-2.0 | 28,451 | 0.024358 | """
Module for building and working with Poses.
"""
import thread, random, re, pprint, sets
import pickle
import maya.cmds as mc
import pymel.core as pm
from pymel.core import mel, Path
from pymel.core.uitypes import OptionMenu
#from pymelX import register_runtime
from impress import register
from config import RUN... | for (attr, v) in stored.iteritems():
pm.setAttr( attr, v )
def apply( self, alterNamespace=False, namespace='' ):
"apply the stored pose to the current scene"
for t in self._stored:
attr, v = t
if alterNamespace:
split = attr.split(':')
... | |
conan-io/conan | conans/test/unittests/model/manifest_test.py | Python | mit | 2,125 | 0.002824 | import os
from conans.model.manifest import FileTreeManifest
from conans.test.utils.test_files import temp_folder
from conans.util.files import load, md5, save
class TestManifest:
def test_tree_manifest(self):
tmp_dir = temp_folder()
files = {"one.ext": "aalakjshdlkjahsdlkjahsdljkhsadljkhasljkd... | save(os.path.join(tmp_dir, "conanmanifest.txt"), "1478122267\nsome: file.py: 123\n")
read_manifest = FileTreeManifest.load(tmp_dir)
assert read_manifest.file_sums["some: file.py"] == "123" | |
huaili-cid/metagen_cli | metagen/api/upload.py | Python | mit | 4,807 | 0.001872 |
import os
import sys
import threading
import boto3
import requests
import json
import logging
from boto3.s3.transfer import TransferConfig, ProgressCallbackInvoker
from s3transfer.utils import OSUtils
from botocore.exceptions import ClientError
from boto3.exceptions import RetriesExceededError, S3UploadFailedError
fro... | ta = dict(kwargs)
mp_up = requests.put(self.burl, json=data, headers=self.header)
resp = dict()
if mp_up.status_code == requests.codes.ok:
resp = mp_up.json()
return resp
def abort_multipart_upload(self, *args, **kwargs):
data = dict(kwargs)
ab_mp = requ... | args, **kwargs):
data = dict(kwargs)
resp = None
upload_body = data.pop('Body')
url_ = requests.get(self.burl, json=data, headers=self.header)
if url_.status_code == requests.codes.ok:
resp = requests.put(url_.json(), upload_body)
return dict(resp.headers)
... |
adusca/treeherder | tests/log_parser/test_step_parser.py | Python | mpl-2.0 | 570 | 0 | from datetime import datetime
from treeherder.log_parser.parsers import StepParser
def test_date_with_milliseconds():
"""Handle buildbot dates that have a decimal on the seconds."""
parser = StepParser()
dt = parser.parsetime('2015-01-20 16:42:33.352 | 621')
assert dt == datetime(2015, 1, 20, 16, 42, 33, 352621)
def test_date_without_milliseconds():
"""Handle buildbot dates that DON'T have a decimal on the seconds."""
parser = StepParser()
dt = parser | .parsetime('2015-01-20 16:42:33')
assert dt == datetime(2015, 1, 20, 16, 42, 33)
|
praekelt/casepro | casepro/contacts/management/commands/pullcontacts.py | Python | bsd-3-clause | 1,909 | 0.003667 | from dash.orgs.models import Org
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
class Command(BaseCommand):
help = "Pulls all contacts, groups and fields from the backend for the specified org"
def add_arguments(self, parser):
parser.add_argument("... | % num_synced)
backend = org.get_backend()
created, updated, deleted, ignored = backend.pull_fields(org)
self.stdout.write(
"Finished field pull (%d created, %d updated, %d deleted, %d ignored)"
% (created, updated, deleted, ignored)
)
created, updated... | ignored = backend.pull_groups(org)
self.stdout.write(
"Finished group pull (%d created, %d updated, %d deleted, %d ignored)"
% (created, updated, deleted, ignored)
)
created, updated, deleted, ignored = backend.pull_contacts(org, None, timezone.now(), progress_callback)... |
rossnomann/playlog | tests/src/tests/common/test_json.py | Python | mit | 167 | 0 | impo | rt pytest
from playlog.lib.json import Encoder
def test_encoder():
encoder = Encoder()
with pytest.raises(TypeError):
encoder | .default(object())
|
Andrwe/py3status | py3status/modules/xrandr_rotate.py | Python | bsd-3-clause | 5,237 | 0 | # -*- coding: utf-8 -*-
"""
Control screen rotation.
Configuration parameters:
cache_timeout: how often to refresh this module.
(default 10)
format: a string that formats the output, can include placeholders.
(default '{icon}')
hide_if_disconnected: a boolean flag to hide icon when `screen`... | tical_icon`.
{screen} a screen name, specified by `screen` option or detected
automatically if only one screen is connected, otherwise 'ALL'.
Color options:
c | olor_degraded: Screen is disconnected
color_good: Displayed rotation is active
@author Maxim Baz (https://github.com/maximbaz)
@license BSD
SAMPLE OUTPUT
{'color': '#00FF00', 'full_text': u'H'}
vertical
{'full_text': u'V'}
"""
class Py3status:
"""
"""
# available configuration parameters
cache... |
jat255/hyperspy | hyperspy/tests/io/test_hdf5.py | Python | gpl-3.0 | 31,740 | 0.001323 | # -*- coding: utf-8 -*-
# Copyright 2007-2022 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 y... | me()
fname = tmp_path / file
s.save(fname)
end = time.time()
assert end - start < 1.0 # It should finish in less that 1 s.
@zspy_marker
def test_numpy_only_inner_lists(self, tmp_path, file):
s = self.s
s.metadata.set_item('test', [[1., 2], ('3', 4)])
fna... | nce(l.metadata.test, list)
assert isinstance(l.metadata.test[0], list)
assert isinstance(l.metadata.test[1], tuple)
@pytest.mark.xfail(sys.platform == 'win32',
reason="randomly fails in win32")
@zspy_marker
def test_numpy_general_type(self, tmp_path, file):
s ... |
tomstokes/redeem | software/Adafruit_I2C.py | Python | gpl-3.0 | 4,135 | 0.014994 | #!/usr/bin/python
# NOTE!! This code is from the Adafruit Learning System articles on the Raspberry Pi (http://learn.adafruit.com/)
# The original version of the code can be found in the Adafruit Raspberry Pi Python Library on Github at https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code
import smbus
# ==... | def writeList(self, reg, list):
"Writes an array of bytes using I2C format"
try:
if (self.debug):
print "I2C: Writing list to register 0x%02X:" % reg
| print list
self.bus.write_i2c_block_data(self.address, reg, list)
except IOError, err:
print "Error accessing 0x%02X: Check your I2C address" % self.address
return -1
def readList(self, reg, length):
"Read a list of bytes from the I2C device"
results = []
try:
results = s... |
N-Parsons/exercism-python | exercises/bank-account/bank_account_test.py | Python | mit | 4,295 | 0 | import sys
import threading
import time
import unittest
from bank_account import BankAccount
class BankAccountTest(unittest.TestCase):
def test_newly_opened_account_has_zero_balance(self):
account = BankAccount()
account.open()
self.assertEqual(account.get_balance(), 0)
def test_can_... | thdraw(80)
self.assertEqual(account.get_balance(), 0)
def test_checking_balance_of_closed_account_throws_error(self):
account = BankAccount()
account.open()
account.close()
with self.assertRaisesWi | thMessage(ValueError):
account.get_balance()
def test_deposit_into_closed_account(self):
account = BankAccount()
account.open()
account.close()
with self.assertRaisesWithMessage(ValueError):
account.deposit(50)
def test_withdraw_from_closed_account(self... |
mysteryjeans/doorsale-demo | doorstep/urls.py | Python | gpl-2.0 | 355 | 0 | from django.conf.urls | import include, url
# Doorstep apps urls
urlpatterns = [
url(r'^', include('doorstep.catalog.urls')),
url(r'^accounts/', include('doorstep.accounts.urls')),
url(r'^sales/', includ | e('doorstep.sales.urls')),
url(r'^payments/', include('doorstep.payments.urls')),
url(r'^pages/', include('doorstep.pages.urls'))
]
|
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_10_01/operations/express_route_circuit_authorizations_operations.py | Python | mit | 18,188 | 0.003079 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | t_name: The name of the express route circuit.
:type circuit_name: str
:param authorization_name: The name of the authorization.
:type authorization_name: str
:param dict custom_headers: headers that will be added to the request
| :param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns None or... |
guangjian/openstack-api-client | test.py | Python | apache-2.0 | 2,512 | 0.01035 | #!/usr/bin/python |
import httplib
import json
# arguments
## make sure that url is set to the actual hostname/IP address,
## port ... |
#url = "135.251.0.109:8080"
#url = "135.251.218.126:8774" ... |
garnertb/firecares | firecares/firestation/urls.py | Python | mit | 2,033 | 0.004919 | from .views import DepartmentDetailView, Stats, FireDepartmentListView, SimilarDepartmentsListView, DepartmentUpdateGovernmentUnits
from django.contrib.auth.decorators import permission_required
from django.views.generic import TemplateView
from django.conf.urls import patterns, url
from django.views.decorators.cache i... | /?$', SimilarDepartmentsListView.as_view(template_name='firestation/firedepartment_list.html'), name='similar_departments_slug'),
url(r'departments/(?P<pk>\d+)/similar-departments/?$', SimilarDepartmentsListView.as_view(template_name='firestation/firedepartment_list.html'), name='similar_departme... | nits/?$', permission_required('firestation.change_firedepartment')(DepartmentUpdateGovernmentUnits.as_view()), name='firedepartment_update_government_units'),
url(r'departments/(?P<pk>\d+)/?$', DepartmentDetailView.as_view(template_name='firestation/department_detail.html'), name='firedepartment_... |
dsm054/pandas | pandas/tests/groupby/conftest.py | Python | bsd-3-clause | 3,673 | 0.000545 | import numpy as np
import pytest
from pandas import (
DataFrame,
MultiIndex,
)
import pandas._testing as tm
from pandas.core.groupby.base import (
reduction_kernels,
transformation_kernels,
)
@pytest.fixture(params=[True, False])
def as_index(request):
return request.param
@pytest.fixture
def m... | : [
"dull",
"dull",
"shiny",
"dull",
"dull",
"shiny",
"shiny",
"dull", |
"shiny",
"shiny",
"shiny",
],
"D": np.random.randn(11),
"E": np.random.randn(11),
"F": np.random.randn(11),
}
)
@pytest.fixture(params=sorted(reduction_kernels))
def reduction_func(request):
"""
yields... |
OCA/contract | agreement_account/__manifest__.py | Python | agpl-3.0 | 776 | 0 | # Copyright 2017-2020 Akretion France (http://www.akretion.com/)
# @author: Alexis de Lattre <alexis.delattre@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Agreement Account",
"summary": "Agreement on invoices",
"version": "14.0.1.0.0",
"category": "Contract",... | "author": "Akretion, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/contract",
"license": "AGPL-3",
"depends": [
"agreement",
"account",
],
"data": [
" | security/ir.model.access.csv",
"views/agreement.xml",
"views/account_move.xml",
],
"development_status": "Beta",
"maintainers": [
"alexis-via",
"bealdav",
],
"installable": True,
}
|
cccaballero/services-manager | services-manager.py | Python | gpl-3.0 | 5,938 | 0.006231 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2013 Carlos Cesar Caballero Diaz <ccesar@linuxmail.org>
#
# 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 ve... | rue)
return False
def do_response(self, dialog, response):
if response == gtk.RESPONSE_CANCEL:
dialog.destroy()
def notify(self, notification):
try:
import pynotify
if pynotify.init("Services Manager"):
n =... | n.show()
except:
pass
def abaut_dialog(self, *args):
"""Show the Abaut dialog"""
about = gtk.AboutDialog()
about.set_name("services-manager")
about.set_version("0.2")
about.set_comments(ABAUT_COMMENTS)
about.set_license("GPL v3")
about... |
cuauv/software | cave/mainForCommandline.py | Python | bsd-3-clause | 75 | 0.013333 | #!/usr/bin/env python2
import os, sygnal, sys
impor | t argparse
import | math
|
ahmedaljazzar/edx-platform | openedx/core/djangoapps/zendesk_proxy/tests/test_utils.py | Python | agpl-3.0 | 2,179 | 0.000918 | import ddt
from django.test.utils import override_settings
from mock import MagicMock, patch
from openedx.core.djangoapps.zendesk_proxy.utils import create_zendesk_ticket
from openedx.core.lib.api.test_utils import ApiTestCase
@ddt.ddt
@override_settings(
ZENDESK_URL="https://www.superrealurlsthataredefinitelyno... | factory and I can't get out!",
}
return super(TestUtils, self).setUp()
@override_settings(
ZENDESK_URL=None,
ZENDESK_OAUTH_ACCESS_TOKEN=None
)
def test_missing_settings(self):
status_code = create_zendes | k_ticket(
requester_name=self.request_data['name'],
requester_email=self.request_data['email'],
subject=self.request_data['subject'],
body=self.request_data['body'],
)
self.assertEqual(status_code, 503)
@ddt.data(201, 400, 401, 403, 404, 500)
def... |
theodotos/arena | rewrite_from.py | Python | gpl-3.0 | 1,572 | 0.001908 | #!/usr/bin/python
'''
## Description
A script to get mail from info@example.com and re-write the 'From"' Header
as "From: John Doe via info at example.com <noreply@example.com>'"
## Installation Instuctions
* Place the script under */usr/local/sbin/rewrite_from.py*.
* Edit */etc/aliases*:
```
info: "|/usr/local/sb... | '''
Main Function
'''
raw_msg = ''
for line in sys.stdin:
raw_msg = raw_msg + line
msg = email.message_from_string(raw_msg)
reply_to_re = re.search(
r'([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-.]+\.[a-zA-Z0-9-.]+)',
msg['From'])
if reply_to_re:
reply_to = reply_to_re.g... | om_h = from_re.group(1)
if msg['Reply-To']:
msg['Reply-To'] = reply_to
msg.replace_header('Reply-To', reply_to)
else:
msg.add_header('Reply-To', reply_to)
msg.replace_header('From', from_h + ' via info at example.com <noreply@example.com>')
send_mail = smtplib.SMTP('localhost'... |
bamos/parsec-benchmark | pkgs/libs/uptcpip/src/scripts/gen-wrap-funclist.py | Python | bsd-3-clause | 1,350 | 0.033333 | import time
import os, fnmatch
import sys
#########################################################
#
# 1. execute ld to generate log
# 2. collect all undefined reference symbols
# 3. find out the files defining the symbols
# 4. sort all the files
# 5. let user decide whether copy the ... | "tmpfile.1", "r")
line = fp.readline().strip()
while line != '':
iterms = line.split()
if len(iterms) != 0:
if "undefined" in iterms and "reference" in iterms:
if not (iterms[-1] in func_def_list):
func_def_list.append(iterms[-1])
count = count + 1
line = fp.readline()... | nction list
fpw = open(output_file, "w")
for i in range(count):
fpw.write("NULL \t")
fpw.write(func_def_list[i][1:-1])
fpw.write(" \t 0\t NULL\n")
fpw.close()
print("Find %d Wrap-Function Definitaions\n", count)
os.remove("tmpfile.1")
|
pyaiot/pyaiot | pyaiot/gateway/mqtt/gateway.py | Python | bsd-3-clause | 7,515 | 0 | # Copyright 2017 IoT-Lab Team
# Contributor(s) : see AUTHORS file
#
# Redistribution 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 a... | teway module."""
import logging
import time
import uuid
import json
import asyncio
from tornado.ioloop import PeriodicCallback
from gmqtt import Client as MQTTClient
from pyaiot.gateway.common import Node, GatewayBase
logger = logging.getLogger("pyaiot.gw.mqtt")
MQTT_HOST = 'localhost'
MQTT_PORT = 1886
MAX_TIME | = 120
class MQTTGateway(GatewayBase):
"""Gateway application for MQTT nodes on a network."""
PROTOCOL = "MQTT"
def __init__(self, keys, options):
self.host = options.mqtt_host
self.port = options.mqtt_port
self.max_time = options.max_time
self.options = options
s... |
smartczm/python-learn | Old-day01-10/s13-day5/s3.py | Python | gpl-2.0 | 8,551 | 0.002026 | #!/usr/bin/env python3.5
# -*- coding: utf-8 -*-
# Author: ChenLiang
# Python 叫模块,其他叫 类库
"""
模块,用一砣代码实现了某个功能的代码集合。
类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块。
如:os 是系统相关的模块;file是文件操作相关的模块
模块分为三种:
自定义模块
第三方模块
内置模块
"""
"""
# 自定义模块
文件
1. 新... | ), error() and critical() 5个级别,下面我们看一下怎么用。
用于便捷记录日志且线程安全的模块
import logging
logging.warning("user [admin] attempted wrong password more than 3 times")
logging.critical("ser | ver is down")
logging.basicConfig(filename='log.log',
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y/%m/%d %H:%M:%S %p',
level=10)
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('e... |
DBuildService/atomic-reactor | atomic_reactor/plugins/exit_store_metadata_in_osv3.py | Python | bsd-3-clause | 12,020 | 0.001581 | """
Copyright (c) 2015, 2019 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
import json
import os
from osbs.exceptions import OsbsResponseException
from atomic_reactor.plugins.pre_reactor_config import get_open... | her.get_usage_data()
self.log.debug("filesystem metadata: %s", data)
except Exception:
self.log.exception("Error getting filesystem stats")
return data
def _update_labels(self, labels, updates):
| if updates:
updates = {key: str(value) for key, value in updates.items()}
labels.update(updates)
def make_labels(self):
labels = {}
self._update_labels(labels, self.workflow.labels)
self._update_labels(labels, self.workflow.build_result.labels)
if 'sou... |
isislovecruft/txrecaptcha | test/test_resources.py | Python | bsd-3-clause | 9,079 | 0.000661 | # -*- coding: utf-8 -*-
#_____________________________________________________________________________
#
# This file is part of txrecaptcha, a Twisted reCAPTCHA client.
#
# :authors: Isis Lovecruft 0xA3ADB67A2CDB8B35 <isis@torproject.org>
# Matthew Finkel 0x017DD169EA793BE2 <sysrqb@torproject.org>
# :copyri... | self.request.method = b'POST'
def testCB(request):
"""Check the ``Request`` returned from ``_renderDeferred``."""
self.assertIsInstance(request, DummyRequest)
html = b''.join(request.written)
self.assertSubstring('Sorry! Something went wrong with your request.',... | r(reactor, 0, lambda x: x, (True, self.request))
d.addCallback(self.captchaResource._renderDeferred)
d.addCallback(testCB)
return d
def test_renderDeferred_nontuple(self):
""":meth:`_renderDeferred` should correctly render a ``Request`` (after
the CAPTCHA has been successful... |
squirrelo/qiita | qiita_pet/handlers/api_proxy/tests/test_artifact.py | Python | bsd-3-clause | 19,979 | 0.00005 | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | import sleep
import pandas as pd
import numpy.testing as npt
from moi import r_client
from qiita_core.util import qiita_t | est_checker
from qiita_db.artifact import Artifact
from qiita_db.metadata_template.prep_template import PrepTemplate
from qiita_db.study import Study
from qiita_db.util import get_count, get_mountpoint
from qiita_db.processing_job import ProcessingJob
from qiita_db.user import User
from qiita_db.software import Command... |
zamattiac/ROSIEBot | deleter.py | Python | mit | 2,875 | 0.002087 | import shutil
import os
import codecs
import json
"""
Using the list of active pages generated by compile_active from the API,
deleter removes whatever isn't accounted for online.
Warning: anything in a category folder that isn't in the compile_active list will be deleted.
"""
MIRROR = 'archive'
class Deleter:
... | _type)
print("OSF type: " + osf_type)
for subdir in mirror_list:
print("Checking", subdir)
if subdir not in active_list:
print(subdir, "inactive. Deleting")
subdir_path = '/'.join([MIRROR, osf_type, subdir])
self.delete_directory(s... | path):
"""
Deletes a given directory
:param directory_path: The path to the directory to be deleted
"""
print(directory_path)
if os.path.isdir(directory_path):
shutil.rmtree(directory_path)
print("Deleted", directory_path)
def run(sel... |
django-de/django-de-v3 | django_de/versions/utils.py | Python | bsd-3-clause | 1,906 | 0.002623 | import requests
import logging
from django.core.cache import cache
from django.conf import settings
LOG = logging.getLogger(__name__)
def is_prerelease(version_str):
"""
Checks if the given version_str represents a prerelease version.
"""
return any([c.isalpha() for c in version_str])
def get_ver... | rsioninfo in cache. Refetching...")
try:
data = requests.get(api_url).json()
except:
LOG.exception("Failed to fetch versinfo data")
return None
if not isinstance(data, list):
# We have probably run into a rate limit an | d will therefor store
# a dummy value to prevent re-fetching for at least 10 minutes
info = ('-', '-')
cache.set(cache_key, info, 600)
return info
for tag in data:
tag_name = tag['ref'].split('/')[-1]
if is_prerelease(tag_name):
latest_pre = tag_name
... |
adblockplus/abpbot | abpbot.py | Python | gpl-2.0 | 4,512 | 0.000887 | #!/usr/bin/env python
#
# Simple IRC Bot to announce messages
#
# Code originally based on example bot and irc-bot class from
# Joel Rosdahl <joel@rosdahl.net>, author of included python-irclib.
#
"""
An IRC bot stub, it will join a particular channel on a server. All
further functionality is implemented by additio | nal handler classes.
"""
import sys
import ConfigParser
from ircbot import SingleServerIRCBot
import irclib
from botcommon import OutputManager
import logbot
import beanbot
import decisionbot
# The message returned w | hen someone messages the bot
HELP_MESSAGE = "I am the Adblock Plus logging bot."
def parse_host_port(hostport, default_port=None):
lis = hostport.split(":", 1)
host = lis[0]
if len(lis) == 2:
try:
port = int(lis[1])
except ValueError:
print "Error: Erroneous port."
... |
siosio/intellij-community | python/testData/intentions/PyAnnotateTypesIntentionTest/resolveAmbiguity.py | Python | apache-2.0 | 94 | 0.031915 | if condition:
def func():
pass
else:
| def func():
| pass
fu<caret>nc() |
pkesist/buildpal | Python/test/test_client.py | Python | gpl-3.0 | 4,561 | 0.004385 | from buildpal_client import compile as buildpal_compile
import os
import subprocess |
import asyncio
import sys
import struct
import threading
import pytest
from buildpal.common import MessageProtocol
class ProtocolTester(MessageProtocol):
@classmethod
def check_exit_code(cls, code):
if hasattr(cls, 'expected_exit_code'):
assert code == cls.expected_exit | _code
def __init__(self, loop):
self.initial = True
self.loop = loop
super().__init__()
def process_msg(self, msg):
if self.initial:
assert len(msg) > 5
self.compiler_name = msg[0].decode()
assert self.compiler_name == 'msvc'
... |
cwoebker/paxo | paxo/core.py | Python | bsd-3-clause | 3,371 | 0.000593 | """
paxo.core - the guts of it all
"""
import os
from clint.textui import colored, puts
from clint import resources
from paxo import __author__
from paxo.command import define_command, Collection
from paxo.util import args, show_error, ExitStatus, XDG_DATA_HOME
from paxo.storage import storage
class Paxo(object):
... | colored.yellow(self.name),
colored.green(self.co | mmand_info)
)
puts(header_info)
puts('-' * len(header_info))
for command in Collection.list_commands():
usage = command.usage or command.name
text = command.help or ''
puts('{0} {1}'.format(colored.green(usage), text))
def cmd_help(self, args):
... |
satyammittal/sample-platform | mod_auth/models.py | Python | isc | 3,955 | 0.000506 | """
mod_auth Models
===================
In this module, we are trying to maintain all database models used
for authentication.
List of models corresponding to mysql tables: ['User' => 'user']
"""
import string
from passlib.apps import custom_app_context as pwd_context
from sqlalchemy import Column, Integer, String, T... | elf.password)
def update_password(self, new_password):
| """
Updates the password to a new one
:param new_password: The new password to be updated
:type new_password: str
"""
self.password = self.generate_hash(new_password)
@property
def is_admin(self):
"""
Verifies if a User is the admin
:return : C... |
hroncok/devassistant | test/dapi/test_dap.py | Python | gpl-2.0 | 21,493 | 0.00219 | # -*- coding: utf-8 -*-
import pytest
import sys
import os
import logging
import itertools
import glob
import subprocess
from flexmock import flexmock
try:
from cStringIO import StringIO
except:
try:
from StringIO import StringIO
except:
from io import StringIO
from devassistant.dapi import ... | o Hrončok ',
' ',
u' Miro Hrončok',
u'Miro Hrončok miro@hroncok.cz',
u'Miro Hrončok <miro@hr@oncok.cz>',
'']
for r in range(1, len(pool) + 1):
for authors in itertools.combinations(pool, r):
d.meta['autho... | 'authors')
assert not ok
assert bads == list(authors)
d.meta['authors'] = ['OK2 <ok@ok.ok>'] + pool + ['OK <ok@ok.ok>']
ok, bads = d._arevalid('authors')
assert bads == pool
def test_duplicate_authors(self):
'''Test if duplicate valid authors are inva... |
rwightman/pytorch-image-models | timm/loss/asymmetric_loss.py | Python | apache-2.0 | 3,322 | 0.001505 | import torch
import torch.nn as nn
class AsymmetricLossMultiLabel(nn.Module):
def __init__(self, gamma_neg=4, gamma_pos=1, clip=0.05, eps=1e-8, disable_torch_grad_focal_loss=False):
super(AsymmetricLossMultiLabel, self).__init__()
self.gamma_neg = gamma_neg
self.gamma_pos = gamma... | orch_grad_focal_loss:
torch._C.set_grad_enabled(False)
pt0 = xs_pos * y
pt1 = xs_neg * (1 - y) # pt = p if t > 0 else 1-p
pt = pt0 + pt1
one_sided_gamma = self.gamma_pos * y + self.gamma_neg * (1 - y)
one_sided_w = torch.pow(1 - pt, one_... | ided_w
return -loss.sum()
class AsymmetricLossSingleLabel(nn.Module):
def __init__(self, gamma_pos=1, gamma_neg=4, eps: float = 0.1, reduction='mean'):
super(AsymmetricLossSingleLabel, self).__init__()
self.eps = eps
self.logsoftmax = nn.LogSoftmax(dim=-1)
self... |
rimbalinux/LMD3 | transaction/urls.py | Python | bsd-3-clause | 171 | 0.005848 | from django.conf.urls.defaults import *
|
urlpatterns = patterns('transaction.views',
(r'^create/(?P<pid>.*)$', 'create'),
(r'^edit/( | ?P<tid>.*)$', 'edit'),
)
|
box/box-python-sdk | demo/example.py | Python | apache-2.0 | 9,973 | 0.002005 | import os
from boxsdk import Client
from boxsdk.exception import BoxAPIException
from boxsdk.object.collaboration import CollaborationRole
from demo.auth import authenticate
def run_user_example(client):
# 'me' is a handy value to get info on the current authenticated user.
me = client.user(user_id='me').get(... | older.create_subfolder('move_sub2')
try:
| subfolder1.move(subfolder2)
print(subfolder2.get_items(limit=10, offset=0))
finally:
subfolder2.delete()
finally:
try:
subfolder1.delete()
except BoxAPIException:
pass
finally:
try:
... |
lyynocs/magento-connector-v8 | sale_automatic_workflow_exception/__openerp__.py | Python | agpl-3.0 | 1,693 | 0 | # -*- coding: utf-8 -*-
###############################################################################
#
# Module for OpenERP
# Copyright (C) 2014 Akretion (http://www.akretion.com).
# @author Sébastien BEAU <sebastien.beau@akretion.com>
#
# This program is free software: you can redistribute it and/or modify
... | by the cron to avoid useless testing
every minutes. Please take care to active the cron "test all draft"
in order to retest some time the order with an ex | ception.
""",
'depends': [
'sale_exceptions',
'sale_automatic_workflow',
],
'data': [
],
'installable': True,
'application': False,
'auto_install': True,
}
|
mzuther/lalikan | src/Lalikan.py | Python | gpl-3.0 | 7,043 | 0 | #!/usr/bin/env py | thon3
"""Lalikan
=======
Backup s | cheduler for Disk ARchive (DAR)
Copyright (c) 2010-2019 Dr. Martin Zuther (http://www.mzuther.de/)
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
... |
MehdiSfr/tensor-flow | tensorflow/g3doc/how_tos/reading_data/fully_connected_preloaded.py | Python | apache-2.0 | 5,244 | 0.005721 | # 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 a... | e
import tensorflow.python.platform
import numpy
import tensorflow as tf
from tensorflow.g3doc.tutorials.mnist import input_data
from tensorflow.g3doc.tutorials.mnist import mnist
# Basic model par | ameters as external flags.
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.')
flags.DEFINE_integer('num_epochs', 2, 'Number of epochs to run trainer.')
flags.DEFINE_integer('hidden1', 128, 'Number of units in hidden layer 1.')
flags.DEFINE_integer('hidden2', 32,... |
mcgee/ns-3 | src/click/bindings/modulegen__gcc_LP64.py | Python | gpl-2.0 | 362,122 | 0.015152 | 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))
... | _module='ns.network')
## packet.h (module 'network'): ns3::ByteTagIterator::Item [class]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList [class]
module.add_class('ByteTagList', import_from_... | ator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator'])
## callback.h (module 'core')... |
bongtrop/cilab-python | ann/bp.py | Python | bsd-3-clause | 1,933 | 0.017072 | import math
import net
SIGMOID = 0
TANH = 1
class bp:
def __init__(self, net, learning_rate, momentum):
self.type = net.getType()
self.net = net
self.lr = learning_rate
self.m = momentum
self.layer = net.getLayer()
self.lc = [[[0]*max(self.layer)]*max(self.layer)]*len(self.layer)
def _dfu... | self.net.getNode(l, i)
w = self.net.getWeight(l+1, i, j) + self.lr * change + self.m * self.lc[l+1][i][j]
self.net.setWeight(l+1, i, j, w)
self.lc[l+1][i][j] = change
for i in range(0, self.layer[l+1]):
b = self.net.getBias(l+1, i) + delta[l+1][i]
self.net.setBia | s(l+1, i, b)
error = 0.0
for i in range(0, len(target)):
error = error + 0.5 * (target[i] - self.net.getNode(nlayer-1, i))**2
return error
|
roxma/nvim-completion-manager | pythonx/cm_scopers/html_scoper.py | Python | mit | 4,724 | 0.012066 | # -*- coding: utf-8 -*-
import re
import logging
import copy
from cm import Base, getLogger
logger = getLogger(__name__)
class Scoper(Base):
scopes = ['html','xhtml','php','blade','jinja','jinja2','vue.html.javascript.css','vue']
def sub_context(self,ctx,src):
lnum = ctx['lnum']
col = ctx['... | ()
parser.feed(src)
if parser.scope_info:
new_ctx = copy.deepcopy(ctx)
new_ctx['scope'] = parser.scope_info['scope']
new_ctx['lnum'] = parser.scope_info['lnum']
new_ctx['col'] = parser.scope_info['col']
new_ctx['scope_offset'] = parser.scope_... | ['scope_offset']
new_ctx['scope_len'] = parser.scope_info['scope_len']
new_ctx['scope_lnum'] = parser.scope_info['scope_lnum']
new_ctx['scope_col'] = parser.scope_info['scope_col']
return new_ctx
pos = self.get_pos(lnum,col,src)
# css completions for st... |
NaturalGIS/QGIS | python/plugins/processing/gui/menus.py | Python | gpl-2.0 | 13,513 | 0.001406 | # -*- coding: utf-8 -*-
"""
***************************************************************************
menus.py
---------------------
Date : February 2016
Copyright : (C) 2016 by Victor Olaya
Email : volayaf at gmail dot com
*******************************... | 'qgis:randomselection': researchToolsMenu,
'qgis:randomselectionwithinsubsets': researchToolsMenu,
'native:ra | ndompointsinextent': researchToolsMenu,
'qgis:randompointsinlayerbounds': researchToolsMenu,
'qgis:randompointsinsidepolygons': researchToolsMenu,
'qgis:regularpoints': researchToolsMenu,
'native:selectbylocation... |
trousev/watchme | backend/models.py | Python | bsd-2-clause | 800 | 0.00625 | from django.db.models import *
from django.contrib.auth.models import User
from uuid import uuid4
class Device(Model):
user = ForeignKey(User, on_delete=CASCADE, related_name='devices')
api_token = CharField(max_length=512, default=uuid4)
name = CharField(max_length=512)
def len(self):
return ... | ds.all() )
class Record(Model):
# This is a DEVICE which user was operating with
device = ForeignKey(Device, on_delete=CASCADE, related_name='records')
# When this was reported. It should be CLIENT time, not SERVER
reported_at = DateTimeField()
# Application which was under user's eyes (a.k.a. "A... | th=512)
# Context. Most propably window title.
context = CharField(max_length=4096)
|
NeoRazorX/ubuntufaq | enlaces.py | Python | agpl-3.0 | 11,757 | 0.007487 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of ubuntufaq
# Copyright (C) 2011 Carlos Garcia Gomez neorazorx@gmail.com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foun... | SELECT * FROM Enlace ORDER BY fecha DESC")
# paginamos
enlaces, paginas, p_actual = self.paginar(enlaces_query, 20, p)
datos_paginacion = [paginas, p_actual, '/actualidad/']
template_values = {
'titulo': 'Act | ualidad de Ubuntu FAQ',
'descripcion': u'Noticias, blogs, vídeos, imágenes y en definitiva toda la actualidad en torno a Ubuntu y Linux en general. Comparte con nosotros!',
'tags': 'ubufaq, ubuntu faq, noticias ubuntu, actualidad ubuntu, linux, lucid, maverick, natty',
'url': self.ur... |
h3llrais3r/Auto-Subliminal | autosubliminal/core/websocket.py | Python | gpl-3.0 | 4,134 | 0.001935 | # coding=utf-8
import codecs
import logging
import cherrypy
import tailer
from schema import And, Schema, SchemaError, Use
from ws4py.messaging import TextMessage
from ws4py.websocket import WebSocket
import autosubliminal
from autosubliminal import system
from autosubliminal.core.runner import Runner
from autosubli... | l.util.json | import from_json, to_json
log = logging.getLogger(__name__)
RUN_SCHEDULER = 'RUN_SCHEDULER'
RUN_SYSTEM_PROCESS = 'RUN_SYSTEM_PROCESS'
SUPPORTED_EVENT_TYPES = [RUN_SCHEDULER, RUN_SYSTEM_PROCESS]
MESSAGE_SCHEMA = Schema({
'type': 'EVENT',
'event': {
'type': And(Use(str), lambda t: t in SUPPORTED_EVEN... |
pranavj1001/LearnLanguages | python/DataStructures/Heaps/App.py | Python | mit | 159 | 0 | from Heap import Heap
newHeap = Heap()
n | ewHeap.insert(12)
newHeap.insert(-3)
newHeap | .insert(23)
newHeap.insert(4)
newHeap.insert(100)
newHeap.displayHeap()
|
vigojug/reto | 201705/peque/biggest_set.py | Python | bsd-3-clause | 1,385 | 0.000722 | #!/usr/bin/env python3
from contextlib import contextmanager
import time
from main import has_subset_sum_zero
class Duration:
def __init__(self, elapsed=None):
self.elapsed = elapsed
@contextmanager
def tim | eit():
duration = Duration()
tic = time.time()
yield duration
elapsed = time.time() - tic
duration.elapsed | = elapsed
def nosolution_case(N):
return range(1, N + 1)
def negative_worst_case(N):
case = list(range(-N + 1, 0))
case += [abs(sum(case))]
return case
def positive_worst_case(N):
case = list(range(1, N))
case.insert(0, - sum(case))
return case
def do():
strategies = [nosolution... |
SF-Zhou/prett | prett/__init__.py | Python | mit | 1,611 | 0.004345 | from .sender import SignalSender, connect_with
from .base import ValueModel, AttachAbility
from .base import ValueInterface, ChangedInterface
from .base import AbstractItem, Item, AbstractProperty
from .multi_types import StringValueModel, StringProperty, StringItemInterface, StringItem
from .multi_types import IntVa... | intItem
from .setting import AbstractSetting, AbstractSettingItem
from .set | ting import StringSettingItem, StringListSettingItem, IntSettingItem, FloatSettingItem
from .widget_interface import WidgetStringItem, WidgetStringInterface
from .widget_interface import IndexItem, WidgetIndexInterface
from .widget_interface import StringsItem, WidgetStringListInterface
from .widget_interface import W... |
andymckay/zamboni | mkt/commonplace/views.py | Python | bsd-3-clause | 4,032 | 0.000744 | import datetime
import importlib
import os
from urlparse import urlparse
from django.conf import settings
from django.core.files.storage import default_storage as storage
from django.http import HttpResponse, Http404
from django.shortcuts import render
import jingo
import jinja2
import newrelic.agent
import waffle
f... | Response(template, content_type='text/cache-manifest')
@memoize('appcache-manifest-template')
def appcache_manifest_template(repo):
ctx = {
'BUILD_ID': get_build_id(repo),
'imgurls': get_imgurls(repo),
'repo': repo,
'timestamp': datetime.datetime.now(),
}
t = jingo.env.get_... | nja2.Markup(t))
def iframe_install(request):
return render(request, 'commonplace/iframe-install.html')
def potatolytics(request):
return render(request, 'commonplace/potatolytics.html')
|
lamestation/packthing | packthing/packagers/inno.py | Python | gpl-3.0 | 4,477 | 0.000893 | # -*- coding: utf-8 -*-
import os
import subprocess
import uuid
from .. import icons, util
from . import _base
try:
from PIL import Image
except:
util.error("Failed to import Python Imaging Library; is it installed?")
REQUIRE = [
"iscc",
"windeployqt",
]
KEYS = ["banner"]
class Packager(_base.Pac... | metypes, executable, reponame):
for mimetype in mimetypes:
self.iss += self.iss_mime(mimetype, executable, reponame)
self.pillow(
os.path.join(reponame, mimetype["icon"]),
os.path.join(self.DIR_OUT, os.path.basename(mimetype["icon"])),
25... | (self):
super(Packager, self).make()
self.iss = self.iss_setup() + "\n"
def finish(self):
super(Packager, self).finish()
with util.pushd(self.DIR_STAGING):
util.write(self.iss, "installer.iss")
try:
subprocess.check_call(["iscc", "installer.... |
JustinTulloss/harmonize.fm | masterapp/masterapp/model/manage/versions/22/22.py | Python | mit | 650 | 0.015385 | from sqlalchemy import *
from sqlalchemy.exceptions import | OperationalError
from sqlalchemy.schema import DDL
import migrate.changeset
from migrate.changeset.exceptions import NotSupportedError
from migrate import *
metadata = MetaData(migrate_engine)
users_table = Table('users', metadata,
Column('id', Integer, primary_key=True))
premiumcol = Column('p | remium', Boolean)
def upgrade():
users_table.append_column(premiumcol)
migrate.changeset.create_column(premiumcol, users_table)
def downgrade():
try:
migrate.changeset.drop_column('premium', users_table)
except NotSupportedError:
print 'Unable to downgrade!'
|
osantana/correios | tests/vcr.py | Python | apache-2.0 | 1,315 | 0 | # Copyright 2016 Osvaldo Santana Neto
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except i | n 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.... |
urbn/kombu | t/unit/utils/test_encoding.py | Python | bsd-3-clause | 3,499 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import sys
from contextlib import contextmanager
from case import patch, skip
from kombu.five import bytes_t, string_t, string
from kombu.utils.encoding import (
get_default_encoding_file, safe_str,
set_default_encoding_file, d... | file(self):
prev = get_d | efault_encoding_file()
try:
set_default_encoding_file('/foo.txt')
assert get_default_encoding_file() == '/foo.txt'
finally:
set_default_encoding_file(prev)
@patch('sys.getfilesystemencoding')
def test_default(self, getdefaultencoding):
getdefaultencod... |
bndl/bndl | bndl/compute/tests/test_many_nodes.py | Python | apache-2.0 | 745 | 0 | # 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 th... | IS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from bndl.compute.tests import ComputeTest
class ManyN | odesTest(ComputeTest):
executor_count = 8
def test_many_nodes(self):
self.assertAlmostEqual(self.ctx.range(1, 100).mean(), 50)
|
patrickwestphal/owlapy | tests/util/hashcode_tests.py | Python | gpl-3.0 | 55,391 | 0.000036 | import unittest
from rdflib import URIRef
from owlapy import model
from owlapy.util.hashcode import HashCode
from owlapy.vocab.owlfacet import OWLFacet
class TestHashCode(unittest.TestCase):
def test_hash_ontology(self):
ont_id = model.OWLOntologyID()
data_factory = model.OWLDataFactory()
... | model.IRI('http://ex.org/anProp2'))
ann_val2 = model.OWLLiteral('annotation 2')
ann2 = model.OWLAnnotation(ann_prop2, ann_val2, [])
anns = {ann1, ann2}
axiom = model.OWLDeclarationAxiom(entity, anns)
axiom_hash = (((23 * HashCode.MULT) + hash(entity)) *
... | self.assertEqual(axiom_hash, HashCode.hash_code(axiom))
def test_diff_indivs_axiom(self):
indiv1 = model.OWLNamedIndividual(model.IRI('http://ex.org/indivABC'))
indiv2 = model.OWLAnonymousIndividual(model.NodeID('_:23'))
indivs = {indiv1, indiv2}
ann_prop1 = model.OWLAnnotationPr... |
avsm/perscon-imap | offlineimap/folder/UIDMaps.py | Python | gpl-2.0 | 8,119 | 0.002833 | # Base folder support
# Copyright (C) 2002 John Goerzen
# <jgoerzen@complete.org>
#
# 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 of the License, or
# (at your opt... | while 1:
line = file.readline()
if not len(line):
break
line = line.strip()
(str1, str2) = line.split(':')
loc = long(str1)
rem = long(str2)
r2l[rem] = loc
l2r[loc]... | if dolock: self.maplock.acquire()
try:
file = open(mapfilename + ".tmp", 'wt')
for (key, value) in self.diskl2r.iteritems():
file.write("%d:%d\n" % (key, value))
file.close()
os.rename(mapfilename + '.tmp', mapfilename)
finally:
... |
dotsdl/PyTables | tables/group.py | Python | bsd-3-clause | 47,685 | 0.000713 | # -*- coding: utf-8 -*-
########################################################################
#
# License: BSD
# Created: September 4, 2002
# Author: Francesc Alted - faltet@pytables.com
#
# $Id$
#
########################################################################
"""Here is defined the Group class."""
impo... | nchildren
# Add a Table child called 'table' under 'group'.
h5file.create_table(group, 'table', myDescription)
table = group.table # get the table child instance
group.table = 'foo' # set a Python attribute
# (PyTables warns you here about using the name of a ... | Python attribute
del group.table # delete a Python attribute
table = group.table # get the table child instance again
.. rubric:: Group attributes
The following instance variables are provided in addition to those
in Node (see :ref:`NodeClassDescr`):
.. attribut... |
arnavd96/Cinemiezer | myvenv/lib/python3.4/site-packages/music21/alpha/webapps/server/urlqueryapp.py | Python | mit | 3,408 | 0.013791 | # -*- coding: utf-8 -*-
'''
An interface for music21 using mod_wsgi
To use, first install mod_wsgi and include it in the HTTPD.conf file.
Add this file to the server, ideally not in the document root,
on mac this could be /Library/WebServer/wsgi-scripts/music21wsgiapp.py
Then edit the HTTPD.conf file to re... |
Further down the conf file, give the webserver access to this directory:
<Directory "/Library/WebServer/wsgi-scripts">
Order allow,deny
Allow from all
</Directory>
The mod_wsgi handler will call the application function below with the request
content in the environ variable.
To use the applicat... | tring.
See docs for music21.webapps for specifications about the JSON string structure
'''
#sys.path.insert(0, '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/')
#sys.path.insert(0, '/Library/Python/2.7/site-packages/')
#import cgi
#from music21 import webapps
from music2... |
ESOedX/edx-platform | common/lib/capa/capa/tests/test_input_templates.py | Python | agpl-3.0 | 46,422 | 0.001896 | """
Tests for the logic in input type mako templates.
"""
from __future__ import absolute_import
import json
import unittest
from collections import OrderedDict
from lxml import etree
from mako import exceptions
from six.moves import range
from capa.inputtypes import Status
from capa.tests.helpers import capa_rende... | o/bar'`
`text` is t | he expected text that the element should contain
If multiple elements are found, checks the first one.
If no elements are found, the assertion fails.
"""
element_list = xml_root.xpath(xpath)
self.assertGreater(len(element_list), 0, "Could not find element at '%s'\n%s" %
... |
jimberlage/servo | tests/wpt/web-platform-tests/webdriver/tests/take_element_screenshot/__init__.py | Python | mpl-2.0 | 516 | 0 | def el | ement_rect(session, element):
return session.execute_script("""
let {devicePixelRatio} = window;
let rect = arguments[0].getBoundingClientRect();
return {
x: Math.floor((rect.left + window.pageXOffset) * devicePixelRatio),
y: Math.floor((rect.top + window.pageYOffset... | ment,))
|
pli3/enigma2-git | lib/python/Screens/MessageBox.py | Python | gpl-2.0 | 3,710 | 0.040162 | from Screen import Screen
from Components.ActionMap import ActionMap
from Components.Label import Label
from Components.Pixmap import Pixmap
from Components.Sources.StaticText import StaticText
from Components.MenuList import MenuList
from enigma import eTimer
class MessageBox(Screen):
TYPE_YESNO = 0
TYPE_INFO = 1
... | ()
def startTimer(self):
self.timer.start(1000)
def stopTimer(self):
if self.timerRunning:
del self.timer
self.onExecBegin.remove(self.startTimer)
self.setTitle(self.origTitle)
self.timerRunning = | False
def timerTick(self):
if self.execing:
self.timeout -= 1
if self.origTitle is None:
self.origTitle = self.instance.getTitle()
self.setTitle(self.origTitle + " (" + str(self.timeout) + ")")
if self.timeout == 0:
self.timer.stop()
self.timerRunning = False
self.timeoutCallback()
def... |
mfem/PyMFEM | mfem/common/generate_lininteg_ext.py | Python | bsd-3-clause | 1,212 | 0.00165 | file = "../_ser/lininteg.py"
out = ["namespace mfem {"]
fid = open(file, 'r')
for line in fid.readlines():
if line.startswith("class"):
cname = (line.split(' ')[1]).split('(')[0]
if line.startswith(" def __init__"):
pp = ""
if line.find("*args") != -1:
pp = " ... | pp = " self._coeff = F"
elif line.find(", f, s=1.0, ir=None)") != -1:
pp = " self._coeff = (f, ir)"
elif | line.find(", uD_, lambda_, mu_, alpha_, kappa_)") != -1:
pp = " self._coeff = uD_"
elif line.find("(self)") != -1:
pass
else:
print(cname)
print(line)
assert False, "No recipt for this pattern "
if pp != "":
out.append("... |
euccas/CodingPuzzles-Python | leet/source/twopointers/sort_colors.py | Python | mit | 3,224 | 0.004963 | class Solution():
def sortColors(nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
store = [[],[],[]]
for i in nums:
store[i].append(i)
return store[0]+store[1]+store[2]
class Solution1():
... | if nums[i] == 2:
nums = swap(nums, i, p_blue)
p_blue -= 1
else:
i += 1
print(nums)
class Solution4:
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead... | nums[i] == 0:
nums[i], nums[pl] = nums[pl], nums[i]
pl += 1
i += 1
elif nums[i] == 1:
i += 1
else:
nums[i], nums[pr] = nums[pr], nums[i]
pr -= 1
return nums
class Solution5:
def sortColo... |
rsmuc/health_monitoring_plugins | health_monitoring_plugins/ilo.py | Python | gpl-2.0 | 17,237 | 0.003017 | """
Module for check_snmp_ilo4
"""
# Copyright (C) 2016-2019 rsmuc <rsmuc@sec-dev.de>
# This file is part of "Health Monitoring Plugins".
# "Health Monitoring Plugins" is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the F... | RATURE_OIDS = {
"oid_env_temp": '.1.3.6.1.4.1.232.6.2.6.8.1.4',
"oid_env_temp_ | thres": '.1.3.6.1.4.1.232.6.2.6.8.1.5'
}
# State definitions
NORMAL_STATE = {
1: 'other',
2: 'ok',
3: 'degraded',
4: 'failed'
}
SERVER_POWER_STATE = {
1: 'unknown',
2: 'poweredOff',
3: 'poweredOn',
4: 'insufficientPowerOrPowerOnDenied'
}
LOG_DRV_STATE = {
1: 'other',
2: 'ok',... |
c0s/juju-apache-bigtop-namenode | tests/01-basic-deployment.py | Python | apache-2.0 | 578 | 0 | #!/usr/bin/env python3
import unittest
import amulet
class TestDeploy(unittest.TestCase):
"""
Trivial deployment test for Apache Hadoop NameNode.
This charm cannot do anything useful by | itself, so integrati | on testing
is done in the bundle.
"""
def test_deploy(self):
self.d = amulet.Deployment(series='trusty')
self.d.add('namenode', 'apache-hadoop-namenode')
self.d.setup(timeout=900)
self.d.sentry.wait(timeout=1800)
self.unit = self.d.sentry['namenode'][0]
if __name__... |
spin13/python_maclib | fsevent_dog.py | Python | mit | 1,485 | 0.005394 | # -*- coding: utf-8 -*-
import os
import time
import util
import urllib, urllib2
import base64
from datetime import datetime
import env
from glob import glob
END_POINT = env.END_POINT
BASE_DIR = env.BASE_DIR
STORAGE_URL = env.STORAGE_URL
def get_latest_file(dirname):
dest = o | s.path.join(dirname, '*.png')
files = [(f, os.path.getmtime(f)) for f in glob(dest)]
if len(files) <= 0:
return
latest_path = sorted(files, key=lambda files: files[1])[-1]
return latest_path[0]
def get_file_timestamp(filename):
if filename == None:
return
return os.sta... |
def getext(filename):
return os.path.splitext(filename)[-1].lower()
def post_data(filename):
now = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
params = {
'base64_data': base64.b64encode(open(filename, 'rt').read()),
'name': now
}
params = urllib.urlencode(params)
... |
Eric89GXL/scipy | scipy/linalg/basic.py | Python | bsd-3-clause | 55,293 | 0 | #
# Author: Pearu Peterson, March 2002
#
# w/ additions by Travis Oliphant, March 2002
# and Jake Vanderplas, August 2012
from __future__ import division, print_function, absolute_import
from warnings import warn
import numpy as np
from numpy import atleast_1d, atleast_2d
from .flinalg import get_flinalg... | '.format(-info))
elif 0 < info:
raise LinAlgError('Matrix is singular.')
if lamch is None:
return
E = lamch('E')
if rcond < E:
warn('Ill-conditioned matrix (rcond={:.6g}): '
'result may not be accur | ate.'.format(rcond),
LinAlgWarning, stacklevel=3)
def solve(a, b, sym_pos=False, lower=False, overwrite_a=False,
overwrite_b=False, debug=None, check_finite=True, assume_a='gen',
transposed=False):
"""
Solves the linear equation set ``a * x = b`` for the unknown ``x``
for ... |
twister/twister.github.io | binaries/JenkinsPlugin/Jenkins/Jenkins_Post_Script.py | Python | apache-2.0 | 810 | 0.006173 |
import xmlrpclib
# version: 2.001
from jenkinsapi import api
j | enkins = api.Jenkins('http://localhost:8080')
twister_job = jenkins.get_job('twister') # The Jenkins job is called `twister` !
twister_build = twister_job.get_ | last_build()
twister_status = twister_build.get_status()
print 'Status:', twister_status
if twister_build.is_good():
print 'The build passed successfully'
else:
print 'The build is not successful!'
exit(1)
# Central Engine is considered to run on localhost:8000
server = xmlrpclib.ServerProxy('http://127.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.