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 |
|---|---|---|---|---|---|---|---|---|
helicontech/zoo | Zoocmd/core/models/base_product.py | Python | apache-2.0 | 16,060 | 0.002684 | # -*- coding: utf-8 -*-
from core.exce | ption import ProductError
from core.core import Core
from core.helpers.yaml_literal import Literal
from core.env_manager import EnvManager
from core.helpers.version import compare_versions
from core.download_manager import DownloadManager
from core.log_ | manager import LogManager
from core.models.platform import Platform
from core.models.file import File
from core.models.installer import Installer
from core.models.installed_product import InstalledProductInfo
import os
from collections import Iterable
from collections import OrderedDict
class BaseProduct(object... |
dnerdy/django-reroute | reroute/verbs.py | Python | mit | 4,764 | 0.009236 | # Copyright (c) 2010 Mark Sandstrom
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, dis... | ike django.http.HttpRequest.method)
'''
# For security reasons POST is the only method that supports HTTP method emulation.
# For example, if POST requires csrf_token, we | don't want POST methods to be called via
# GET (thereby bypassing CSRF protection). POST has the most limited semantics, and it
# is therefore safe to emulate HTTP methods with less-limited semantics. See
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html ("Safe and Idempotent Methods")
# for detai... |
chevah/txghserf | txghserf/__init__.py | Python | bsd-3-clause | 32 | 0 | """
GitHu | b Web | Hooks Server.
"""
|
jwilder/nginx-proxy | test/test_default-host.py | Python | mit | 212 | 0.004717 | import pytest
def test_fallback_on_default(docker_compose, nginxproxy):
r = nginxproxy.ge | t("http://unknown.nginx-proxy.tld/port")
assert r.status_code == 200
ass | ert r.text == "answer from port 81\n" |
cmd-ntrf/jupyter-lmod | jupyterlmod/__init__.py | Python | mit | 1,051 | 0.001903 | from jupyter_server.utils import url_path_join as ujoin
from .config import Lmod as LmodConfig
from .handler import default_handlers, PinsHandler
def _jupyter_server_extension_paths():
return [{"module": "jupyterlmod"}]
# Jupyter Extension points
def _jupyter_nbextension_paths():
return [
dict(
... | lmod_config = LmodConfig(parent=nbapp)
launcher_pins = lmod_config.launcher_pins
web_app = nbapp.web_app
base_url = web_app.settings["base_url"]
for path, class_ in default_handlers:
web_app.add_handlers(".*$", [(ujoin(base_url, path), class_)])
web_app.add_handlers(".*$", [
(ujoin... | url, 'lmod/launcher-pins'), PinsHandler, {'launcher_pins': launcher_pins}),
])
|
cmjagtap/Algorithms_and_DS | searching/twoRepetedEle.py | Python | gpl-3.0 | 296 | 0.101351 | def twoRepEle(array):
if not array:
return None
else:
hash_table={}
for x in array:
if x in hash_table:
ha | sh_table[x] | +=1
elif x !=' ':
hash_table[x]=1
else:
hash_table[x]=0
for x in array:
if hash_table[x]==2:
print x
array=[1,2,3,1,2,5,6,7]
twoRepEle(array) |
nickpascucci/Robot-Arm | software/desktop/brazo/brazo/AboutBrazoDialog.py | Python | mit | 725 | 0.011034 | # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# This file is in the public domain
### END LICENSE
import gettext
from gettext import gettext as _
gettext.textdomain('brazo')
import logging
logger = logging.getLogger('brazo')
from brazo_lib.AboutDialog import AboutDialog... | , builder): # pylint: disable=E1002
"""Set up the about dialog"""
super(AboutBrazoDialog, self).finish_initializing(builder)
# Code for other initialization actio | ns should be added here.
|
sstacha/uweb-install | cms_files/forms.py | Python | apache-2.0 | 192 | 0.005208 | from django impo | rt forms
class LoginForm(forms.Form):
login = forms.CharField(max_length=255)
password = forms.CharField(widget=forms.PasswordInput())
target = forms.CharField()
| |
V11/volcano | server/sqlmap/plugins/generic/takeover.py | Python | mit | 17,888 | 0.001453 | #!/usr/bin/env python
"""
Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import os
from lib.core.common import Backend
from lib.core.common import isStackingAvailable
from lib.core.common import readInput
from lib.core.common import runningAsAdmin... | = "invalid value, valid values are 1 and 2"
logger.warn(warnMsg)
if choice == 1:
goUdf = True
if goUdf:
exitfunc = "thread"
setupSuccess = True
else:
exi... | EAX", encode="x86/alpha_mixed")
if not goUdf:
setupSuccess = self.uploadShellcodeexec(web=web)
if setupSuccess is not True:
if Backend.isDbms(DBMS.MYSQL):
fallbackToWeb = True
else:
... |
locationtech/geowave | python/src/main/python/pygw/statistics/statistic.py | Python | apache-2.0 | 5,623 | 0.001067 | #
# Copyright (c) 2013-2020 Contributors to the Eclipse Foundation
#
# See the NOTICE file distributed with this work for additional information regarding copyright
# ownership. All rights reserved. This program and the accompanying materials are made available
# under the terms of the Apache License, Version 2.0 whic... | istic
"""
self._java_ref.setTypeName(name)
def get_type_name(self):
"""
Get the type name associated with the statistic.
Returns:
The type name of this statistic.
"""
return self._java_ref.getTypeName()
class FieldStatistic(Statistic):
def... | """
return FieldStatisticType(self._java_ref.getStatisticType())
def set_type_name(self, name):
"""
Sets the type name of the statistic.
Args:
name (str): The type name to use for the statistic
"""
self._java_ref.setTypeName(name)
def get_type_name... |
ging/keystone | keystone/tests/test_v3_two_factor_auth.py | Python | apache-2.0 | 19,566 | 0.001738 | # Copyright (C) 2015 Universidad Politecnica de Madrid
#
# 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 la... | dy)['two_factor_auth']
def _check_for_device(self, expected_status=None, **kwargs):
response = self.head(TWO_FACTOR_BASE_URL + DEVICES_ENDPOINT + '?' + urllib. | urlencode(kwargs), expected_status=expected_status)
def _delete_devices(self, user_id, expected_status=None):
return self.delete(TWO_FACTOR_DEVICES_URL.format(user_id=user_id), expected_status=expected_status)
def _create_user(self):
user = self.new_user_ref(domain_id=self.domain_id)
... |
dmonroy/chilero.pg | tests/test_sample_app.py | Python | mit | 8,628 | 0.000695 | import asyncio
import random
import names
from chilero.web.test import asynctest
from chilero.pg import Resource
from chilero.pg.test import TestCase, TEST_DB_SUFFIX
import json
class Friends(Resource):
order_by = 'name ASC'
search_fields = ['name']
allowed_fields = ['name', 'meta']
required_fields ... | rl('/friends'))
assert resp.status == 200
resp.close()
@asynctest
def test_index_json(self):
resp = yield from self._index('/friends')
assert isinstance(resp, dict)
assert 'index' in resp
@asynctest
def test_index_json_condition(self):
resp = yield from... | , friend = yield from self._create_friend(name=name)
assert _.status == 201
_.close()
assert friend['name'] == name
assert len(friend.keys()) == 4
efriend = yield from self._delete(friend['url'])
assert efriend.status==200
@asynctest
def test_create_error(self):
... |
klahnakoski/esReplicate | pyLibrary/queries/es09/expressions.py | Python | mpl-2.0 | 26,115 | 0.003178 | # encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http:# mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import unicode_literals
from __... | ntext = self.getFrameVariables(body)
func = UID()
predef = addFunctions(select.head+context+body).head
param = "_source" if body.find(sourceVar) else ""
output = predef + \
select.head + \
context + \
'var ' + func + ' = function('+sourceVar+'){\n' +... | omPath, sourceVar, loopVariablePrefix):
"""
indexName NAME USED TO REFER TO HIGH LEVEL DOCUMENT
loopVariablePrefix PREFIX FOR LOOP VARIABLES
"""
loopCode = "if (<PATH> != null){ for(<VAR> : <PATH>){\n<CODE>\n}}\n"
self.prefixMap = []
code = "<CODE>"
path =... |
mirskytech/djangocms-carousel | setup.py | Python | bsd-3-clause | 1,241 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
from djangocms_carousel import __version__
INSTALL_REQUIRES = [
]
CLASSIFIERS = [
'Development Status :: 5 - Pr | oduction/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Communications',
'Topic :: Internet :: WWW/HTTP :: Dyn... |
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
]
setup(
name='djangocms-carousel',
version=__version__,
description='Slider Plugin for django CMS',
author='Andrew Mirsky',
author_email='andrew@mirsky.net',
url='https://git.mirsky.net/mirskyconsulting/... |
Novasoft-India/OperERP-AM-Motors | openerp/addons/giicourse/__openerp__.py | Python | agpl-3.0 | 444 | 0.018018 | {
"name" : " | GII",
"version" : "1.0",
"depends" : ['sale','product'],
"author" : "Novasoft Consultancy Services Pvt. Ltd.",
'ca | tegory' : 'Generic Modules/Others',
"description": """ GII - Management Module
""",
'website': 'http://www.novasoftindia.com',
'data': ['giisa.xml',
],
'demo': [],
'installable': True,
'auto_install': False,
'application': True,
} |
bfirsh/docker-py | docker/utils/utils.py | Python | apache-2.0 | 39,231 | 0.000051 | import base64
import io
import os
import os.path
import json
import shlex
import sys
import tarfile
import tempfile
import warnings
from distutils.version import StrictVersion
from datetime import datetime
from fnmatch import fnmatch
import requests
import six
from .. import constants
from .. import errors
from .. im... | exclude_patterns, include_patterns)]
for path in dirs:
if should_include(os.path.join(parent, path),
exclude_patterns, include_patterns):
paths.append(os.path.join(parent, path))
for path in files:
if should_include(os.path.... | r |
openstates/openstates | openstates/vi/legislators.py | Python | gpl-3.0 | 490 | 0.002041 | from pupa.scrape import Person, Scraper
from openstates.utils import LXMLMixin
class VIPersonScraper(Scraper, LXMLMixin):
def scrape(self, chamber, | term):
pass
yield Person()
# home_url = 'http://www.legvi.org/'
# doc = | lxml.html.fromstring(self.get(url=home_url).text)
# USVI offers name, island, and biography, but contact info is locked up in a PDF
# //*[@id="sp-main-menu"]/ul/li[2]/div/div/div/div/ul/li/div/div/ul/li/a/span/span
|
Locu/chronology | pykronos/tests/conf/django_settings.py | Python | mit | 149 | 0 | KRONOS_MIDDLEWARE = {
'host': 'http://localhost:9191/',
'stream': 'django_middleware',
'blockin | g': True,
'log_exception_stack | _trace': True
}
|
harishvc/tools | bigquery-github/TopGithubRepos.py | Python | mit | 4,367 | 0.0158 | # Query Github public timeline using Bigquery and display top new repositories
# Modified from sources
## https://developers.google.com/bigquery/bigquery-api-quickstart#completecode
## https://gist.github.com/igrigorik/f8742314320e0a4b1a89
import httplib2
import pprint
import sys
import time
import json
import logging... | repository_language, \
repository_description, \
repository_url HAVING cnt >= 5 \
ORDER BY cnt DESC LIMIT 5;',
"useQueryCache": "False" # True or False
... | response = query_request.query(projectId=PROJECT_NUMBER,body=query_data).execute()
#Did the bigquery get processed?
if ((query_response['jobComplete']) and (int(query_response['totalRows']) >1) and (int(query_response['totalBytesProcessed']) > 0 )):
#Store result for further analysi... |
fishjord/gsutil | gslib/commands/rm.py | Python | apache-2.0 | 15,054 | 0.004849 | # -*- coding: utf-8 -*-
# Copyright 2011 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 require... | ucket that shouldn't
result in a user-visible error.
Args:
bucket_strings_to_delete: Buckets slated for recursive deletion.
e: Exception to check.
Returns:
True if the exception was a no-URLs-matched exception and it matched
one of bucket_strings_to_delete, None otherwise.
"""
if bucket_stri... | (e):
parts = str(e).split(msg)
return len(parts) == 2 and parts[1] in bucket_strings_to_delete
class RmCommand(Command):
"""Implementation of gsutil rm command."""
# Command specification. See base class for documentation.
command_spec = Command.CreateCommandSpec(
'rm',
command_name_ali... |
adaptive-learning/proso-apps | proso_common/management/commands/load_global_custom_config.py | Python | mit | 1,269 | 0 | from django.conf import settings
from django.core.management.base import BaseCommand
from proso_common.models import CustomConfig
import os.path
import yaml
from django.db import transaction
from optparse import make_option
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option... | default=os.path.join(settings.BASE_DIR, 'proso_custom_config.yaml')
) | ,
)
def handle(self, *args, **options):
with transaction.atomic():
CustomConfig.objects.filter(user_id=None).delete()
with open(options['filename'], 'r', encoding='utf8') as f:
for app_name, keys in yaml.load(f).items():
for key, records in ke... |
boriel/zxbasic | src/api/debug.py | Python | gpl-3.0 | 810 | 0.001235 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:et:
# Simple debugging module
import os
import inspect
from .config import OPTIONS
__all__ = ["__DEBUG__", "__LINE__", "__FILE__"]
# --------------------- END OF GLOBAL FLAGS ---- | -----------------
def __DEBUG__(msg, level=1):
if level > OPTIONS.debug_level:
return
line = inspect.getouterframes(inspect.currentframe())[1][2]
fname = os.path.basename(inspect.getouterframes(inspect.currentframe())[1][1])
OPTIONS.stderr.write("debug: %s:%i %s\n" % (fname, line, msg))
def... | urrent file interpreter line"""
return inspect.currentframe().f_code.co_filename
|
hackultura/procult | procult/core/migrations/0004_auto_20160905_0938.py | Python | gpl-2.0 | 1,233 | 0.001622 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def port_models(apps, schema_editor):
Proposal = apps.get_model('core', 'Proposal')
Notice = apps.get_model('core', 'Notice')
n = Notice()
n.title = "Edital"
n.description = "Edital info"
... | s
class Migration(migrations.Migration):
dependencies = [
('core', '0003_proposaldate'),
]
operations = [
migrati | ons.CreateModel(
name='Notice',
fields=[
('id', models.AutoField(serialize=False, primary_key=True)),
('title', models.CharField(max_length=60)),
('description', models.CharField(max_length=500)),
('is_available', models.BooleanFiel... |
aroth-arsoft/arsoft-python | python3/arsoft/efi/__init__.py | Python | gpl-3.0 | 4,063 | 0.006153 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# kate: space-indent on; indent-width 4; mixedindent off; indent-mode python;
"""This module provides a general interface to EFI variables using platform-
specific methods. Current Windows and Linux (with sysfs and efivars) are
supported.
Under Windows the pywin32 extensions ... |
# import firmware variable API
self.GetFirmwareEnvironmentVariable = ctypes.windll.kernel32.GetFirmwareEnvironmentVariableW
self.GetFirmwareEnvironmentVariable.restype = ctypes.c_int
| self.GetFirmwareEnvironmentVariable.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_void_p, ctypes.c_int]
def read(self, name, guid):
buffer = ctypes.create_string_buffer(32768)
length = self.GetFirmwareEnvironmentVariable(name, "{%s}" % guid, buffer, 32768)
if length =... |
spbnick/sssd | src/config/SSSDConfig/sssd_upgrade_config.py | Python | gpl-3.0 | 18,663 | 0.008359 | #coding=utf-8
# SSSD
#
# upgrade_config.py
#
# Copyright (C) Jakub Hrozek <jhrozek@redhat.com> 2009
#
# 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 Licens... | 'ldap_user_principal' : 'userPrincipal',
'ldap_force_upper_case_realm' : 'force_upper_case_realm',
'ldap_user_fullname' : 'userFullname',
'ldap_user_member_of' : 'userMemberOf',
| 'ldap_user_modify_timestamp' : 'modifyTimestamp',
'ldap_group_search_base' : 'groupSearchBase',
|
lrocheWB/navitia | source/jormungandr/tests/authentication_tests.py | Python | agpl-3.0 | 17,792 | 0.003147 | # Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public tr... | self.old_public_val = app.config['PUBLIC']
app.config['PUBLIC'] = False |
self.app = app.test_client()
self.old_instance_getter = models.Instance.get_by_name
models.Instance.get_by_name = FakeInstance.get_by_name
def tearDown(self):
app.config['PUBLIC'] = self.old_public_val
models.Instance.get_by_name = self.old_instance_getter
@dataset({"mai... |
sorgerlab/belpy | indra/tests/test_hgnc_client.py | Python | mit | 2,834 | 0 | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from indra.databases import hgnc_client
from indra.util import unicode_strs
from nose.plugins.attrib import attr
def test_get_uniprot_id():
hgnc_id = '6840'
uniprot_id = hgnc_client.get_uniprot_id(hgnc_id)
... | sert unicode_strs(hgnc_name)
def test_entrez_hgnc():
entrez_id = '653509'
hgnc_id = hgnc_client.get_hgnc_from_entrez(entrez_id)
assert hgnc_id == '10798'
def test_entrez_hgnc_none():
entrez_id = 'xxx'
hgnc_id = hgnc_client.get_hgnc_from_entrez(entrez_id)
assert hgnc_id is None
def test_ens... | id == '59', hgnc_id
assert hgnc_client.get_ensembl_id(hgnc_id) == ensembl_id
def test_mouse_map():
hgnc_id1 = hgnc_client.get_hgnc_from_mouse('109599')
hgnc_id2 = hgnc_client.get_hgnc_from_mouse('MGI:109599')
assert hgnc_id1 == '4820'
assert hgnc_id2 == '4820'
hgnc_id = hgnc_client.get_hgnc_fr... |
dpazel/music_rep | transformation/functions/tonalfunctions/chromatic_tonal_reflection_function.py | Python | mit | 8,810 | 0.003973 | """
File: chromatic_tonal_reflection_function.py
Purpose: Class defining a function that tonally reflects over a given tone.
"""
from tonalmodel.diatonic_foundation import DiatonicFoundation
from tonalmodel.tonality import Tonality
from transformation.functions.pitchfunctions.diatonic_pitch_reflection_function impor... | on = None
for l in 'CDEFGAB':
for aug in ['bb', 'b', '', '#', "##"]:
tone = DiatonicFoundation.get_tone(l + aug)
| if tone not in self.tonal_map.keys():
if self.reflect_type == FlipType.CenterTone:
interval = Interval.calculate_tone_interval(tone, self.cue_tone)
if interval: # Some intervals are illegal, eg Cbb --> C, for now ignore
... |
insiderr/insiderr-app | app/widgets/bar.py | Python | gpl-3.0 | 1,558 | 0.000642 | from kivy.uix.label import Label
from kivy.uix.behaviors import ButtonBehavior
from widgets.layoutint import Grid | LayoutInt
from kivy.uix.image import Image
from kivy.properties import StringProperty, ListProperty, ObjectProperty, NumericProperty, BooleanProperty
from kivy.compat import string_types
from kivy.factory import Factory
class BarMiddleLabel(Label):
pass
class BarMiddleImage(Image):
pass
class BarMiddleBut... | ):
__events__ = ('on_left_click', 'on_right_click')
screen = ObjectProperty()
color = ListProperty([1, 1, 1, 1])
left_icon = StringProperty('')
right_icon = StringProperty('')
hide_right_icon = BooleanProperty(False)
middle_cls = ObjectProperty(None, allownone=True)
middle = ObjectPrope... |
Grumbel/dirtool | dirtools/extractor.py | Python | gpl-3.0 | 2,353 | 0.000425 | # dirtool.py - diff tool for directories
# Copyright (C) 2018 Ingo Ruhnke <grumbel@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opt... | None:
pass
def make | _extractor(filename: str, outdir: str)-> Extractor:
from dirtools.rar_extractor import RarExtractor
from dirtools.sevenzip_extractor import SevenZipExtractor
from dirtools.libarchive_extractor import LibArchiveExtractor
# FIXME: Use mime-type to decide proper extractor
if filename.lower().endswith... |
selaux/numpy2vtk | numpy2vtk/data/raw/__init__.py | Python | lgpl-3.0 | 150 | 0 | from raw import points
from raw import vertices
from raw import edges
from raw import polygons
__all__ = ['po | ints', 'vertices', | 'edges', 'polygons']
|
bockthom/codeface | codeface/fileCommit.py | Python | gpl-2.0 | 7,096 | 0.002114 | # This file is part of Codeface. Codeface 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even... | urns the identifier of a function given a line number
func_id = 'File_Level'
line_num = int(line_num)
if self.artefact_line_range == True:
if line_num in self.functionIds:
func_id = self.functionIds[line_num]
else:
i = bisect.bisect_right(self.func... | func_line = self.functionLineNums[i-1]
func_id = self.functionIds[func_line]
return func_id
def getLineCmtId(self, line_num):
## Retrieve the first file snap
line_num = str(line_num)
file_snapshot = self.getFileSnapShot()
return file_snapshot[line_num]
... |
kressi/erpnext | erpnext/buying/doctype/request_for_quotation/request_for_quotation.py | Python | gpl-3.0 | 10,014 | 0.027062 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, json
from frappe import _
from frappe.model.mapper import get_mapped_doc
from frappe.utils import get_url, cint
from frap... | em in self.items:
item.supplier_part_no = frappe.db.get_value('Item Supplier',
{'parent': item.item_code, 'supplier': args.supplier}, 'supplier_part_no')
def update_supplier_contact(self, rfq_supplier, link):
'''Create a new user for the supplier if not set in contact'''
update_password_link = ''
if fra... | (rfq_supplier, link)
self.update_contact_of_supplier(rfq_supplier, user)
return update_password_link
def update_contact_of_supplier(self, rfq_supplier, user):
if rfq_supplier.contact:
contact = frappe.get_doc("Contact", rfq_supplier.contact)
else:
contact = frappe.new_doc("Contact")
contact.first_n... |
m1k3r/gvi-accounts | gvi/budgets/migrations/0004_remove_budgetelement_subcategory.py | Python | mit | 364 | 0 | # -*- coding: utf-8 -*-
from __future__ | import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('budgets', '0003_auto_20150717_0147'),
]
operations = [
migrations.RemoveField(
model_name='budgetelement',
name='subcategory',
), |
]
|
mgabay/Variable-Size-Vector-Bin-Packing | scripts/vbp-optim.py | Python | gpl-3.0 | 4,279 | 0.00631 | from vsvbp import container, solver
import argparse, sys, os, re
def parse(inputfile):
""" Parse a file using format from
Brandao et al. [Bin Packing and Related Problems: General Arc-flow Formulation with Graph Compression (2013)]
Format:
d (number of dimensions)
C_1 ... C_d ca... | .split())
dem = req.pop()
assert len(req) == dim
items.extend([container.Item(req) for j in xrange(dem)])
i += 1
assert i == nitems
inp.close()
return items, container.Bin(cap)
def natural_sort(l):
convert = lambda text: int(text) if text.isdigit() else text.lower()
... | eturn sorted(l, key = alphanum_key)
def get_subdirectories(directory):
dirs = [os.path.join(directory,name) for name in os.listdir(directory)
if os.path.isdir(os.path.join(directory, name))]
return natural_sort(dirs)
def get_files(directory):
files = [os.path.join(directory,name) for name in... |
myDevicesIoT/Cayenne-Agent | myDevices/devices/digital/pcf8574.py | Python | mit | 2,274 | 0.006157 | # Copyright 2012-2013 Eric Ptak - trouch.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 required by applicable l... | rning permissions and
# limitations under the License.
from myDevices.utils.types import toint
from myDevices.dev | ices.i2c import I2C
from myDevices.devices.digital import GPIOPort
class PCF8574(I2C, GPIOPort):
FUNCTIONS = [GPIOPort.IN for i in range(8)]
def __init__(self, slave=0x20):
slave = toint(slave)
if slave in range(0x20, 0x28):
self.name = "PCF8574"
elif slave in range(0x3... |
lablup/sorna-repl | vendor/benchmark/minigo/oneoffs/ladder_detector.py | Python | lgpl-3.0 | 3,787 | 0.003169 | # Copyright 2019 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, ... | ards it maybe useful to inspect the files or thumbnails
find . -iname '*.sgf' | xargs -P4 -I{} gogui-thumbnailer -size 256 {} {}.png
"""
import sys
sys.path.insert(0, '.')
import os
from collections import Counter, defaultdict
from absl import app
from tqdm import tqdm
from sgfmill import sgf, sgf_moves
import on... | abs(d[0]) + abs(d[1])
def isLadderIsh(game_path):
with open(game_path) as sgf_file:
game_data = sgf_file.read().encode('utf-8')
g = sgf.Sgf_game.from_bytes(game_data)
_, moves = sgf_moves.get_setup_and_moves(g)
mostAdjacent = 0
mostStart = 0
# colorStart, moveStart
cS, mS = -1, (... |
Amber-MD/ambertools-conda-build | conda_tools/validate_ambertools_build.py | Python | mit | 5,502 | 0.000545 | import os
import sys
import subprocess
from contextlib import contextmanager
import argparse
import glob
ENV_ROOT = 'test_ambertools'
AMBER_VERSION = 'amber17'
def is_conda_package(package_dir):
basename = os.path.basename(package_dir)
return not (basename.startswith('osx') or basename.startswith('linux'))
... | os.system('source activate {}'.format(env_name))
yield
os.system('conda env remove -n {} -y'.format(env_name))
os.environ['PATH'] = ORIG_PATH
def ensure_no_gfortran_local(amberhome):
errors = []
for fn in get_tested_files(amberhome):
cmd = ['otool', '-L', fn]
try:
| output = subprocess.check_output(
cmd, stderr=subprocess.PIPE).decode()
except subprocess.CalledProcessError:
output = ''
if '/usr/local/gfortran' in output:
errors.append(fn)
return errors
def get_so_files(dest):
cmd = 'find {} -type f -name "*.... |
dean0x7d/pybinding | docs/examples/lattice/checkerboard.py | Python | bsd-2-clause | 801 | 0.003745 | """Two dimensional checkerboard lattice with real hoppings"""
import pybinding as pb
import matplotlib.pyplot as plt
from math import pi
pb.pltutils.use_style()
def checkerboard(d=0.2, delta=1.1, t=0.6):
lat = pb.Lattice(a1=[d, 0], a | 2=[0, d])
lat.add_sublattices(
('A', [0, 0], -delta),
('B', [d/2, d/2], delta)
)
lat.add_hoppings(
([ 0, 0], 'A', 'B', t),
([ 0, -1], 'A', 'B', t),
([-1, 0], 'A', 'B', t),
([-1, -1], 'A', 'B', t)
)
return lat
lattice = checkerboard()
lattice.plot()
... | 0, 5*pi], [5*pi, 5*pi], [0, 0])
bands.plot()
plt.show()
|
mehtadev17/mapusaurus | mapusaurus/api/tests.py | Python | cc0-1.0 | 4,338 | 0.014292 | import json
from django.core.urlresolvers import reverse
from django.http import HttpResponseNotFound
from django.test import TestCase
from mock import Mock
from utils import use_GET_in
from api.views import msas, tables
class ConversionTest(TestCase):
def test_use_GET_in(self):
fn, request = Mock(), Mo... | 'swLon':'',
| 'year':'2013',
'action_taken':'1,2,3,4,5',
'lender':'736-4045996'})
self.assertEqual(resp.status_code, 404)
def test_api_msas_endpoint(self):
"""should return a list of MSA ids in view"""
... |
NicovincX2/Python-3.5 | Statistiques/Statistique descriptive/Mode (statistiques)/one_mode.py | Python | gpl-3.0 | 124 | 0.008065 | # -*- coding: utf-8 - | *-
import os
def onemode(values):
return max(set(values) | , key=values.count)
os.system("pause")
|
kiyo-masui/SDdata | sddata/tests/test_psrfits_to_sdfits.py | Python | gpl-2.0 | 9,556 | 0.009209 | """Unit tests for psrfits_to_sdfits.py."""
import unittest
import sys
import scipy as sp
import numpy.random as rand
import psrfits_to_sdfits as p2s
import kiyopy.custom_exceptions as ce
class TestFormatData(unittest.TestCase) :
def setUp(self) :
self.ntime = 5
self.npol = 4
self.nfreq... | sition.
self.first_trans = rand.randint(0, self.n_bins_cal // 2)
# The following randomly assigns self.neg to -1 or 1.
self.neg = 0
while not self.neg: self.neg = rand.randint(-1, 2)
# First upward edge:
if self.neg == 1:
self.offset = self.first_trans
... | [:,0,:] += self.level
for ii in range(self.ntime//self.n_bins_cal) :
s = slice(self.first_trans + ii*self.n_bins_cal, self.first_trans +
(2*ii+1)*self.n_bins_cal//2)
self.data[s, 0, :] += self.neg * self.level
# Transition values and locations.
self.... |
samabhi/pstHealth | venv/lib/python2.7/site-packages/requests/models.py | Python | mit | 26,299 | 0.001711 | # -*- coding: utf-8 -*-
"""
requests.models
~~~~~~~~~~~~~~~
This module contains the primary objects that power Requests.
"""
import os
from datetime import datetime
from .hooks import dispatch_hook, HOOKS
from .structures import CaseInsensitiveDict
from .status_codes import codes
from .auth import HTTPBasicAuth, ... | Location``)
self.allow_redirects = allow_redirects
# Dictionary mapping protocol to the URL of the proxy | (e.g. {'http': 'foo.bar:3128'})
self.proxies = dict(proxies or [])
# If no proxies are given, allow configuration by environment variables
# HTTP_PROXY and HTTPS_PROXY.
if not self.proxies and self.config.get('trust_env'):
if 'HTTP_PROXY' in os.environ:
self.proxie... |
jhgg/discord.py | discord/channel.py | Python | mit | 12,385 | 0.001857 | # -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-2016 Rapptz
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 us... | rate : int
The channel's preferred audio bitrate in bits per second.
voice_members
A list of :class:`Members` that are currently inside this voice channel.
If :attr:`type` is not :attr:`ChannelType.voice` then this is always an empty array.
user_limit : int
The channel's limit fo... | f members that can be in a voice channel.
"""
__slots__ = [ 'voice_members', 'name', 'id', 'server', 'topic', 'position',
'is_private', 'type', 'bitrate', 'user_limit',
'_permission_overwrites' ]
def __init__(self, **kwargs):
self._update(**kwargs)
self.... |
yarikoptic/pystatsmodels | statsmodels/sandbox/stats/contrast_tools.py | Python | bsd-3-clause | 28,737 | 0.004941 | '''functions to work with contrasts for multiple tests
contrast matrices for comparing all pairs, all levels to reference level, ...
extension to 2-way groups in progress
TwoWay: class for bringing two-way analysis together and try out
various helper functions
Idea for second part
- get all transformation matrices ... | ])
for row in contrast_prod]
ee2 = np.zeros((1,n2))
ee2[0,0] = 1
#dd2 = np.r_[ee2, -contrast_all_one(n2)]
if not pairs:
dd2 = np.r_[ee2, -contrast_all_one(n2)]
else:
dd2 = np.r_[ee2, -contrast_allpairs(n2)]
contrast_prod2 = np.kron(np.eye(n1), d... | e),v)
for c,v in zip(row, names_prod)[::-1] if c != 0])
for row in contrast_prod2]
if (not intgroup1 is None) and (not intgroup1 is None):
d1, _ = dummy_1d(intgroup1)
d2, _ = dummy_1d(intgroup2)
dummy = dummy_product(d1, d2)
... |
Harrison-M/indent.txt-sublime | indentsublime.py | Python | mit | 967 | 0.004137 | import sublime, sublime_plugin
from indenttxt import indentparser
class IndentToList(sublime_plugin.TextCommand):
def run(self, edit):
parser = indentparser.IndentTxtParser()
#Get current selection
sels = self.view.sel()
selsParsed = 0
if(len(sels) > 0):
for sel... | sel, edit)
selsParsed += 1
#All selections just cursor marks?
if(selsParsed == 0):
region = sublime.Region(0, self.view.size() - 1)
self.parseRegion(parser, region, edit)
def parseRegion(self, parser, region, edit):
lines = self.view.line(region)... | ).new_file()
newview.insert(edit, 0, indented)
|
rahlk/WarnPlan | warnplan/commons/tools/axe/nasa93.py | Python | mit | 7,488 | 0.31437 | """
# The NASA93 Data Set
Standard header:
"""
from __future__ import division,print_function
import sys
sys.dont_write_bytecode = True
from lib import *
"""
data.dat:
"""
def nasa93():
vl=1;l=2;n=3;h=4;vh=5;xh=6
return data(indep= [
# 0..8
'Prec', 'Flex', 'Resl', 'Team', 'Pmat', 'rely', 'data.dat'... | ,n,l,h,h,n,h,n,h,n,n,n,339,444,8477,45.9],
[h,h,h,vh,n,l,h,l,n,n,n,n,h,h,h,n,h,n,h,n,n,n,240,192,10313,37.1],
[h,h,h,vh,l,h,n,h,n,n,n,vh,l,h,h,n,h,h,h,n,n,l,144,576,6129,28.8],
[h,h,h,vh,l,n,l,n,n,n,n,vh,l,h,h,n,h,h,h,n,n,l,151,432,6136,26.2],
[h,h,h,vh,l,n,l,h,n,n,n,vh,l,h,h,n,h,h,h,n,n,l,34,72... | n,vh,l,h,h,n,h,h,h,n,n,l,85,300,4256,23.2],
[h,h,h,vh,l,n,l,n,n,n,n,vh,l,h,h,n,h,h,h,n,n,l,20,240,813,12.8],
[h,h,h,vh,l,n,l,n,n,n,n,vh,l,h,h,n,h,h,h,n,n,l,111,600,4511,23.5],
[h,h,h,vh,l,h,vh,h,n,n,n,vh,l,h,h,n,h,h,h,n,n,l,162,756,7553,32.4],
[h,h,h,vh,l,h,h,vh,n,n,n,vh,l,h,h,n,h,h,h,n,n,l,352,... |
dcoles/ivle | ivle/webapp/security/views.py | Python | gpl-2.0 | 6,811 | 0.001175 | # IVLE
# Copyright (C) 2007-2009 The University of Melbourne
#
# 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 option) any later version.
#
# This ... | ls and rela | ted stuff.
req.throw_redirect(req.make_path('+tos') + query_string)
elif user.state == "pending":
# FIXME: this isn't quite the right answer, but it
# should be more robust in the short term.
session = req.get_session()
session.... |
windcode/xtools | CleanMoviePrefix.py | Python | mit | 1,426 | 0.019635 | # coding=gbk
import os
import re
import string
def isMov(filename):
# ÅжÏÊÇ·ñΪµçÓ°Îļþ
suffix = filename.split('.')[-1].lower() # ÌáÈ¡ºó׺
pattern = re.compile(r'mpg|mpeg|m2v|mkv|dat|vob|avi|wmv|rm|ram|rmvb|mov|avi|mp4|qt|viv')
if pattern.search(suffix): # Æ¥ÅäÊÇ·ñΪµçÓ°¸ñʽ
return True... | else:
return False
if __name__=='__main__':
# ±éÀúµ±Ç°Ä¿Â¼
print '´¦ÀíÖС¡'
cnt = 1
for fp in os.listdir(os.getcwd()):
if os.path.isfile(fp) and isMov(fp): # ÊǵçÓ°Îļþ
if fp[0]=='[': # È¥µô¿ªÍ·µÄ[]
index = fp.find(']')
if index!=-1... | os.rename(fp,fp[index+1:])
fp = fp[index+1:]
cnt+=1
elif fp[:2]=='¡¾': # È¥µô¿ªÍ·µÄ¡¾¡¿
index = fp.find('¡¿')
if index!=-1:
print '[%d] %s ==> %s'%(cnt,fp,fp[index+2:])
... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/scipy/stats/tests/test_kdeoth.py | Python | agpl-3.0 | 6,021 | 0.000997 | from __future__ import division, print_function, absolute_import
from scipy import stats
import numpy as np
from numpy.testing import assert_almost_equal, assert_, assert_raises, \
assert_array_almost_equal, assert_array_almost_equal_nulp, run_module_suite
def test_kde_1d():
#some basic tests comparing to no... | irectly.
class _kde_subclass1(stats.gaussian_kde):
def __init__(self, dataset):
self.dataset = np.atleast_2d(dataset)
self.d, self.n = self.dataset.shape
self.covariance_factor = self.scotts_factor
self._compute_covariance()
class _kde_subclass2(stats.gaussian_kde):
def __init... | ):
def __init__(self, dataset, covariance):
self.covariance = covariance
stats.gaussian_kde.__init__(self, dataset)
def _compute_covariance(self):
self.inv_cov = np.linalg.inv(self.covariance)
self._norm_factor = np.sqrt(np.linalg.det(2*np.pi * self.covariance)) \
... |
gratipay/postgres.py | postgres/context_managers.py | Python | mit | 5,280 | 0.001136 | from psycopg2 import InterfaceError
class CursorContextManager:
"""Instantiated once per :func:`~postgres.Postgres.get_cursor` call.
:param pool: see :mod:`psycopg2_pool`
:param bool autocommit: see :attr:`psycopg2:connection.autocommit`
:param bool readonly: see :attr:`psycopg2:connection.readonly`
... | it` is :obj:`True`, then the connection is neither
rolled back nor committed;
2. if :attr:`readonly` is :obj:`True`, then the connection is always rolled
back, never committed.
In all cases the cursor is closed.
"""
__slots__ = ('conn', 'cursor')
def __init__(self, conn, autocommit... | def __enter__(self):
return self.cursor
def __exit__(self, exc_type, exc_val, exc_tb):
self.cursor.close()
self.conn.__exit__(exc_type, exc_val, exc_tb)
class CursorSubcontextManager:
"""Wraps a cursor so that it can be used for a subtransaction.
See :meth:`~postgres.Postgres.ge... |
gwsu2008/automation | python/git-branch-diff.py | Python | gpl-2.0 | 3,650 | 0.001644 | #!/usr/bin/env python3
import urllib3
import sys
import os
import json
from datetime import datetime
import urllib.parse
import requests
import time
import argparse
urllib3.disable_warnings()
debug = os.getenv('DEBUG', 0)
batch_size = 100
workspace = os.getenv('WORKSPACE', os.getcwd())
user_name = 'jenkins-testerdh'
u... | default=None, dest=' | repo_url', help='Git clone URL with ssh syntax')
args, unknown = parser.parse_known_args()
return args, unknown
def main(argv):
start_time = time.time()
args, unknown = parse_args()
info('Starting')
info('Workspace {}'.format(workspace))
master_merge_file = '{}/merge.master'.format(workspa... |
davidar/pyzui | pyzui/ferntileprovider.py | Python | gpl-2.0 | 4,684 | 0.009821 | ## PyZUI 0.1 - Python Zooming User Interface
## Copyright (C) 2009 David Roberts <d@vidr.cc>
##
## 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 you... | tilesize_units):
"""Draw the given point on the given tile.
__draw_point(Image, float, float, float) -> None
Precondition: 0.0 <= x <= tilesize_units
Precondition: 0.0 < | = y <= tilesize_units
"""
x = x * self.tilesize / tilesize_units
x = min(int(x), self.tilesize-1)
y = y * self.tilesize / tilesize_units
y = min(int(self.tilesize - y), self.tilesize-1)
tile.putpixel((x,y), self.color)
def _load_dynamic(self, tile_id, outfile):
... |
olexiim/edx-platform | lms/djangoapps/mobile_api/users/tests.py | Python | agpl-3.0 | 9,422 | 0.002972 | """
Tests for users API
"""
import datetime
from django.utils import timezone
from xmodule.modulestore.tests.factories import ItemFactory, CourseFactory
from xmodule.modulestore.django import modulestore
from student.models import CourseEnrollment
from .. import errors
from ..testutils import MobileAPITestCase, Mobi... | n_and_enroll()
(__, __, __, other_unit) = self._setup_course_skeleton()
past_date = datetime.datetime.now()
response = self.api_response(
data={
"last_visited_module_id": unicode(other_unit.location),
| "modification_date": past_date.isoformat() # pylint: disable=maybe-no-member
},
expected_response_code=400
)
self.assertEqual(response.data, errors.ERROR_INVALID_MODIFICATION_DATE)
def _date_sync(self, date, initial_unit, update_unit, expected_unit):
"""
... |
Don-Li/CABexpt | CABexpt/clock.py | Python | gpl-3.0 | 1,906 | 0.026233 | from time import strftime, monotonic
import pigpio
import CABmanager
class clock(object):
"""Clock"""
def __init__( self, pigpio_pi ):
if type( pigpio_pi ) is CAB_manager.CABmanager:
self.pigpio_pi = pigpio_pi.pi
else:
self.pigpio_pi = pigpio_pi
self.t... | elf.get_current_ti | ck()
self.gpio_time_2 = 0
self.time_now = 0
def sleep( self, seconds ):
if seconds <= 0.5:
t1 = monotonic()
while monotonic() - t1 < seconds:
pass
else:
t1 = monotonic()
sleep( seconds - 0.4 )
while monotoni... |
dana-i2cat/felix | optin_manager/src/python/openflow/optin_manager/users/models.py | Python | apache-2.0 | 1,961 | 0.022947 | from django.db import models
from django.contrib import auth
from django.db.models.signals import post_save
class Priority(object):
Aggregate_Admin = 12000
Campus_Admin = 10000
Department_Admin = 8000
Building_Admin = 6000
Group_Admin = 4000
Strict_User... | = models.BooleanField("Can Confirm Flow Space Requests", default=False)
is_clearinghouse_user = models.BooleanField("Clearinghouse account", default=False)
max_priority_level = models.IntegerField(null=True) # Otherwise will complain
supervisor = models.ForeignKey(auth.models.User, re... | s.CharField(max_length = 1024, default="")
def __unicode__(self):
try:
return "Profile for %s" % self.user
except:
return "No user"
@classmethod
def get_or_create_profile(cls, user):
try:
profile = user.get_profile()
except UserProfile.D... |
FroggedTV/grenouilleAPI | backend/bot_app.py | Python | gpl-3.0 | 3,850 | 0.003377 | import logging
import pickle
import random
from gevent import Greenlet, sleep
from threading import Lock
from app import create_app
from dota_bot import DotaBot
from models import db, DynamicConfiguration, Game, | GameStatus, GameVIP
from helpers.general import divide_vip_list_per_type
# Log
logging.basicConfig(format='[%(asctime)s] %(levelname)s %(message)s', level=logging.INFO)
class Credential:
"""A St | eam account credentials.
Attributes:
login: Steam user login.
password: Steam user password.
"""
def __init__(self, login, password):
"""Create a user credentials.
Args:
login: user login.
password: user password.
"""
self.login = lo... |
openkamer/openkamer | website/tests.py | Python | mit | 13,880 | 0.001225 | import datetime
import logging
from django.contrib.auth.models import User
from django.test import Client
from django.test import TestCase
from django.urls import reverse
from person.models import Person
from parliament.models import ParliamentMember
from parliament.models import PoliticalParty
from document.models... | ame=surname, initials=initials)
self.assertEqual(member.person.forename, forename)
def test_find_member_non_ascii(self):
surname = 'Koser Kaya'
forename = 'Fatma'
initials = 'F.'
member = ParliamentMember.find(surname=surname, initials=initials)
self.assertEqual(memb... | ename, forename)
surname = 'Koşer Kaya'
member = ParliamentMember.find(surname=surname, initials=initials)
self.assertEqual(member.person.forename, forename)
class TestPersonView(TestCase):
fixtures = ['person.json']
@classmethod
def setUpTestData(cls):
cls.client = Client... |
RyanChinSang/ECNG3020-ORSS4SCVI | BETA/TestCode/Matplotlib/mpl1.py | Python | gpl-3.0 | 3,865 | 0.001811 | from __future__ import unicode_literals
import sys
import os
import random
import matplotlib
# Make sure that we are using QT5
matplotlib.use('Qt5Agg')
from PyQt5 import QtCore, QtWidgets
from numpy import arange, sin, pi
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib... | self.setCentralWidget(self.main_widget)
self.statusBar().showMessage("All hail matplotlib!", 2000)
def fileQuit(self):
self.close()
def closeEvent(self, ce):
self.fileQuit()
def about(self):
QtWid | gets.QMessageBox.about(self, "About",
"""embedding_in_qt5.py example
Copyright 2005 Florent Rougon, 2006 Darren Dale, 2015 Jens H Nielsen
This program is a simple example of a Qt5 application embedding matplotlib
canvases.
It may be used and modified with no restriction; raw copies... |
dashea/anaconda | tests/pyanaconda_tests/user_create_test.py | Python | gpl-2.0 | 15,039 | 0.001596 | # vim:set fileencoding=utf-8
#
# Copyright (C) 2015 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distribute... | ource code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
# Red Hat Author(s): David Shea <dshea@redhat.com>
#
from pyanaconda import users
import unittest
import tempfile
import shutil
import os
import crypt
impo... | be run as root")
class UserCreateTest(unittest.TestCase):
def setUp(self):
self.users = users.Users()
# Create a temporary directory with empty passwd and group files
self.tmpdir = tempfile.mkdtemp()
os.mkdir(self.tmpdir + "/etc")
open(self.tmpdir + "/etc/passwd", "w").clos... |
pferreir/indico-backup | indico/MaKaC/common/MaKaCConfig.py | Python | gpl-3.0 | 1,407 | 0.013504 | # -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico 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; eith... | join(os.path.dirname(__file__), '..', '..', '..', 'etc', 'indico.conf')
if not os.path.exists(indico_conf):
# eggmode
indico_conf = os.path.join(os.path.dirname(__file__), '..', '..', 'etc', 'indico.conf.sample')
if not os.path.exists(indico_conf):
i | ndico_conf = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'etc', 'indico.conf.sample')
execfile(indico_conf)
|
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_12_01/operations/_connection_monitors_operations.py | Python | mit | 42,196 | 0.00519 | # 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 may ... | re
def begin_create_or_update(
self,
resource_group_name, # type: str
network_watcher_name, # type: str
connection_monitor_name, # type: str
parameters, # type: "_models.ConnectionMonitor"
**kwargs # type: Any
):
# type: (...) -> LROPoller["_models.C... | lt"]
"""Create or update a connection monitor.
:param resource_group_name: The name of the resource group containing Network Watcher.
:type resource_group_name: str
:param network_watcher_name: The name of the Network Watcher resource.
:type network_watcher_name: str
:pa... |
infobloxopen/infoblox-netmri | infoblox_netmri/api/remote/models/spm_devices_vendor_model_grid_remote.py | Python | apache-2.0 | 4,572 | 0.00175 | from ..remote import RemoteModel
from infoblox_netmri.utils.utils import check_api_availability
class SpmDevicesVendorModelGridRemote(RemoteModel):
"""
This table lists all SPM devices that existed within the user specified period of time sorted by the Device Name in ascending order.
| ``id:`` The int... | ier of the grid entry.
| ``attribute type:`` number
| ``Network:`` The name of the Network View associated.
| ``attribute type:`` string
| ``DeviceID:`` The NetMRI internal identifier for the device.
| ``attribute type:`` number
| ``DeviceName:`` The NetMRI name of the device; this will... | viceIPDotted:`` The management IP address of the device, in dotted (or colon-delimited for IPv6) format.
| ``attribute type:`` string
| ``DeviceIPNumeric:`` The numerical value of the device IP address.
| ``attribute type:`` number
| ``DeviceDNSName:`` The device name as reported by DNS.
| ``... |
serein7/openag_brain | src/openag_brain/commands/update_launch.py | Python | gpl-3.0 | 5,299 | 0.001698 | import os
import rospkg
import lxml.etree as ET
from openag_brain import params
from openag.models import SoftwareModule, SoftwareModuleType
from openag.db_names import SOFTWARE_MODULE, SOFTWARE_MODULE_TYPE
# maping from python types to roslaunch acceptable ones
PARAM_TYPE_MAPPING = {'float' : 'double'}
def create_n... | te_group(parent, ns):
"""
Creates an xml node for the launch file that represents a ROS group.
`parent` is the parent xml node. `ns` is the namespace of the group.
"""
e = ET.SubElement(parent, 'group')
e.attrib['ns'] = ns
return e
def create_remap(parent, from_val, to_val):
"""
Cre... | apping.
`parent` is the parent xml node. `from_val` is the name that is to be
remapped. `to_val` is the target name.
"""
e = ET.SubElement(parent, 'remap')
e.attrib['from'] = from_val
e.attrib['to'] = to_val
def create_arg(parent, name, default=None, value=None):
"""
Creates an xml node... |
oyvindmal/SocoWebService | unittest/test_alarms.py | Python | mit | 538 | 0.003717 | # -*- coding: utf-8 -*-
""" Tests for the alarms module """
from __future__ import unicode_literals
from soco | .alarms import is_valid_recurrence
def test_recurrence():
for recur in ('DAILY', 'WEEKDAYS', 'WEEKENDS', 'ONCE'):
assert is_valid_recurrence(recur)
assert is_valid_recurrence('ON_1')
assert is_valid_recurrence('ON | _123412')
assert not is_valid_recurrence('on_1')
assert not is_valid_recurrence('ON_123456789')
assert not is_valid_recurrence('ON_')
assert not is_valid_recurrence(' ON_1')
|
imakin/PersonalAssistant | Fundkeep/modul/b__main_backu.py | Python | mit | 2,347 | 0.041329 | #!/usr/bin/env python
import os,sys
folder = "/media/kentir1/Development/Linux_Program/Fundkeep/"
def makinGetYear():
return os.popen("date +'%Y'").read()[:-1]
def makinGetMonth():
return os.popen("date +'%m'").read()[:-1]
def makinGetDay():
return os.popen("date +'%d'").read()[:-1]
def makinGetPrevYear(daypassed)... | t_tahun = makinGetYear()
if (i | nt(makinGetMonth())=1):
t_bulan = 12
t_tahun = makinGetYear()-1
print t_bulan
dapet = 0
while (dapet==0):
try:
f = open(folder+"data/"+t_tahun+"/"+t_bulan+"/"+("0"+str(t_day))[-2:]+"/balance_after","r")
print t_day
dapet = 1
balance_before = int(f.read())
except:
t_day = t_day - 1
f.close(... |
stvstnfrd/edx-platform | common/lib/xmodule/xmodule/tests/test_library_content.py | Python | agpl-3.0 | 26,994 | 0.002741 | # -*- coding: utf-8 -*-
"""
Basic unit tests for LibraryContentBlock
Higher-level tests are in `cms/djangoapps/contentstore/tests/test_libraries.py`.
"""
import six
from bson.objectid import ObjectId
from fs.memoryfs import MemoryFS
from lxml import etree
from mock import Mock, patch
from search.search_engine_base i... | lx.
node = etree.Element("unknown_root")
lc_block.add_xml_to_node(node)
# Read it back
with export_fs.open('{dir}/{file_name}.xml'.format(
dir=lc_block.scope_ids.usage_id.block_type,
file_name=lc_block.scope_ids.usage_id.block_id
)) as f:
expo... | ourse_id=lc_block.location.course_key)
runtime.resources_fs = export_fs
# Now import it.
olx_element = etree.fromstring(exported_olx)
id_generator = Mock()
imported_lc_block = LibraryContentBlock.parse_xml(olx_element, runtime, None, id_generator)
# Check the new XBlock... |
pacocampo/Backend | traveleando/project/usuario/admin.py | Python | gpl-3.0 | 213 | 0.018779 | from django.contrib import admin
from . import models
# Register your mod | els here.
#admin.site.register(models.MyUser)
@admin.registe | r(models.MyUser)
class MyUserAdmin(admin.ModelAdmin):
list_display = ['user'] |
AHAPX/dark-chess | src/handlers/v2/game.py | Python | gpl-3.0 | 7,424 | 0.002963 | from flask import request
from cache import (
add_to_queue, get_from_queue, get_from_any_queue, set_cache, get_cache,
delete_cache
)
import config
import consts
from connections import send_ws
from consts import WS_CHAT_MESSAGE
from decorators import validate
import errors
from game import Game
from handlers.v... | enemy_token, user_token, game_type, game_limit,
white_user=enemy_user, black_user=request.user
)
delete_cache('wait_{}'.format(enemy_token))
result = {'game': user_token}
re | sult.update(game.get_info(consts.BLACK))
return result
class RestGames(RestBase):
def get(self):
from models import Game
result = {
'games': {
'actives': [],
'ended': [],
}
}
if request.user:
games = Game.... |
ygol/odoo | addons/website_event_track_online/models/event_event.py | Python | agpl-3.0 | 2,962 | 0.002701 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api, _
from odoo.addons.http_routing.models.ir_http import slug
class EventEvent(models.Model):
_inherit = "event.event"
community_menu = fields.Boolean(
"Community Men... | # WEBSITE MENU MANAGEMENT
# ------------------------------------------------------------
# OVERRIDES: ADD SEQUENCE
def _get_menu_update_fields(self):
updat | e_fields = super(EventEvent, self)._get_menu_update_fields()
update_fields += ['community_menu']
return update_fields
def _update_website_menus(self, menus_update_by_field=None):
super(EventEvent, self)._update_website_menus(menus_update_by_field=menus_update_by_field)
for event in ... |
mivade/qCamera | qcamera/ring_buffer.py | Python | bsd-2-clause | 4,596 | 0.001958 | """Ring buffer for automatic storage of images"""
import os.path
import logging
from datetime import datetime
import numpy as np
from scipy.misc import imsave
import tables
class RingBuffer(object):
"""Ring buffer class.
Attributes
----------
directory : str
Location to store the ring buffer ... | ile(self.filenam | e, 'w', title="Ring Buffer")
self._db.create_group('/', 'images', 'Buffered Images')
def __enter__(self):
return self
def __exit__(self, type_, value, tb):
self.close()
def close(self):
self._db.close()
def get_current_index(self):
"""Return the current index.... |
craigem/MyAdventures | buildHouse2.py | Python | gpl-3.0 | 1,494 | 0 | # Build a simple house.
# Import necessary modules.
import mcpi.minecraft as minecraft
import mcpi.block as block
# Connect to Minecraft.
mc = minecraft.Minecr | aft.create()
# Set a base size for the house.
SIZE = 20
# Create the house function.
def house():
# Calculate the midpoints, used to position doors and windows.
midx = x + SIZE / 2
midy = y + SIZE / 2
# Build the outer shell.
mc.setBlocks(
x, y, z,
x + SIZE, y + SIZE, z + SIZE,
... | 1, y, z + 1,
x + SIZE - 2, y + SIZE - 1, z + SIZE - 2,
block.AIR.id
)
# Carve out the doorway.
mc.setBlocks(
midx - 1, y, z,
midx + 1, y + 3, z,
block.AIR.id
)
# Carve out two windows.
mc.setBlocks(
x + 3, y + SIZE - 3, z,
midx - ... |
inspirehep/raven-python | raven/transport/registry.py | Python | bsd-3-clause | 2,913 | 0.00103 | """
raven.transport.registry
~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import sys
# TODO(dcramer): we really should need to import all of these by default
from raven.trans... | plicateScheme
from raven.transport.http import HTTPTransport
from raven.transport.gevent import GeventedHTTPTransport
from raven.transport.r | equests import RequestsHTTPTransport
from raven.transport.threaded import ThreadedHTTPTransport
from raven.transport.twisted import TwistedHTTPTransport
from raven.transport.tornado import TornadoHTTPTransport
from raven.transport.udp import UDPTransport
from raven.utils import urlparse
if sys.version_info >= (3, 3):
... |
nonZero/demos-python | src/examples/short/iteration/iterator_generator.py | Python | gpl-3.0 | 652 | 0.001534 | #!/usr/bin/python2
'''
This is an example of how to build a simple generator
'''
def my_reverse(data):
for index in ra | nge(len(data) - 1, -1, -1):
yield data[index]
for char in my_reverse('golf'):
print(char)
'''
Notice that 'my_reverse' is still recognized as a plain function and not
'generator' or something.
When you do use it for da | ta the return value is a 'generator'.
Compare this to pythons own 'reversed' generator:
- it is built in so it's type is type
- when using it as a generator it's type is 'reversed'.
'''
print(type(my_reverse))
print(type(my_reverse('golf')))
print(type(reversed))
print(type(reversed('golf')))
|
openatx/uiautomator2 | examples/multi-thread-example.py | Python | mit | 747 | 0.001339 | # coding: utf-8
#
# GIL limit python multi-thread effectiveness.
# But is seems fine, because these operation have so many socket IO
# So it seems no need to use multiprocess
#
import uiautomator2 as u2
import adbutils
import threading
from logzero import logger
def worker(d: u2.Device):
d.app_start("io.appium.a... | ").wait | ()
for el in d.xpath("@android:id/list").child("/android.widget.TextView").all():
logger.info("%s click %s", d.serial, el.text)
el.click()
d.press("back")
logger.info("%s DONE", d.serial)
for dev in adbutils.adb.device_list():
print("Dev:", dev)
d = u2.connect(dev.serial)
t... |
Azure/azure-sdk-for-python | sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/v2016_09_01/aio/operations/_management_locks_operations.py | Python | mit | 49,288 | 0.005011 | # 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 may ... | alized
create_or_update_at_resource_group_level.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}'} # type: ignore
@distributed_trace_async
async def delete_at_resource_group_level(
self,
resource_gro... | : str,
lock_name: str,
**kwargs: Any
) -> None:
"""Deletes a management lock at the resource group level.
To delete management locks, you must have access to Microsoft.Authorization/\ * or
Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Ac... |
Chilledheart/seafile | scripts/setup-seafile-mysql.py | Python | gpl-3.0 | 43,261 | 0.002104 | #coding: UTF-8
'''This script would guide the seafile admin to setup seafile with MySQL'''
import sys
import os
import time
import re
import shutil
import glob
import subprocess
import hashlib
import getpass
import uuid
import warnings
import MySQLdb
from ConfigParser import ConfigParser
try:
import readline # ... | Answer(Exception):
def __init__(self, msg):
Exception.__init__(self)
self.msg = msg
def __str__(self):
return self.msg
### END of Utils
####################
class EnvM | anager(object):
'''System environment and directory layout'''
def __init__(self):
self.install_path = os.path.dirname(os.path.abspath(__file__))
self.top_dir = os.path.dirname(self.install_path)
self. |
acs-um/deptos | deptos/departamentos/urls.py | Python | apache-2.0 | 209 | 0.004785 | from django.conf.urls import include, url
from .view | s import alquiler_nuevo, home
from django.contrib.auth.decora | tors import login_required
from departamentos.views import home, details
urlpatterns = [
]
|
airelil/pywinauto | pywinauto/unittests/test_uiawrapper.py | Python | bsd-3-clause | 89,050 | 0.002223 | """Tests for UIAWrapper"""
from __future__ import print_function
from __future__ import unicode_literals
import time
import os
import sys
import unittest
import mock
import six
sys.path.append(".")
from pywinauto.application import Application, WindowSpecification # noqa: E402
from pywinauto.sysinfo import is_x64_Py... |
class UIAWrapperTests(unittest.TestCase):
"""Unit tests for the UIAWrapper class"""
def setUp(self):
"""Set some data and ensure the application is in the state we want"""
_set_timings()
mouse.move((-500, 500)) # remove the mouse from the screen to avoid sid... | f_app_1)
self.dlg = self.app.WPFSampleApplication
def tearDown(self):
"""Close the application after tests"""
self.app.kill()
def test_issue_296(self):
"""Test handling of disappered descendants"""
wrp = self.dlg.wrapper_object()
... |
esdalmaijer/PyGazeAnalyser | pygazeanalyser/traces.py | Python | gpl-3.0 | 19,865 | 0.037352 | # PyeNalysis
__author__ = "Edwin Dalmaijer"
import copy
import numpy
from scipy.interpolate import interp1d
# DEBUG #
#from matplotlib import pyplot
# # # # #
def interpolate_blink(signal, mode='auto', velthresh=5, maxdur=500, margin=10, invalid=-1, edfonly=False):
"""Returns signal with interpolated results, ... | signal['edftime']==et)[0]
# if th | e starting or ending time did not appear in the trial,
# correct the blink starting or ending point to the first or
# last sample, respectively
if len(st) == 0:
st = 0
else:
st = st[0]
if len(et) == 0:
et = len(signal['edftime'])
else:
et = et[0]
# compensate for underestimation of ... |
cancerregulome/gidget | commands/feature_matrix_construction/main/cleanClinTSV.py | Python | mit | 98,495 | 0.004041 | # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
import miscClin
import tsvIO
import sys
# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
remapDict = {}
DAYS_PER_YEAR = 365.2425
# ----------------------------------------------------------------------... | ]["na"] = "NA"
remapDict["histological_type"]["colon_adenocarcinoma"] = 0
remapDict["histological_type"]["rectal_adenocarcin | oma"] = 0
remapDict["histological_type"]["colon_mucinous_adenocarcinoma"] = 1
remapDict["histological_type"]["rectal_mucinous_adenocarcinoma"] = 1
if (0):
remapDict["histological_type"]["na"] = "NA"
remapDict["histological_type"][
"untreated_primary_(de_novo)_gbm"] = "de_novo"
remapDict["hi... |
npardington/fabric-bolt | fabric_bolt/task_runners/socketio/__init__.py | Python | mit | 241 | 0 | from ..base import BaseTaskRunn | erBackend
class SocketIOBackend(BaseTaskRunnerBackend):
def __init__(self):
from . import sockets
def get_detail_template(self):
return 'task_runners/deployment | _detail_socketio.html'
|
skyoo/jumpserver | apps/common/drf/parsers/base.py | Python | gpl-2.0 | 4,553 | 0.001349 | import abc
import json
import codecs
from rest_framework import serializers
from django.utils.translation import ugettext_lazy as _
from rest_framework.parsers import BaseParser
from rest_framework import status
from rest_framework.exceptions import ParseError, APIException
from common.utils import get_logger
logger =... | field_names = [
fields_map.get(column_title.strip('*'), '')
for column_title in column_titles
]
return field_names
@staticmethod
def _replace_chinese_quote(s):
trans_table = str.maketrans({
'“': '"',
'”': '"',
'‘': '"',
... | cess_row(cls, row):
"""
构建json数据前的行处理
"""
new_row = []
for col in row:
# 转换中文引号
col = cls._replace_chinese_quote(col)
# 列表/字典转换
if isinstance(col, str) and (
(col.startswith('[') and col.endswith(']'))
... |
robotpy/pynetconsole | netconsole/netconsole.py | Python | isc | 6,782 | 0.000885 | from argparse import ArgumentParser
import socket
import struct
import sys
import threading
import time
from ._fakeds import FakeDS
__all__ = ["Netconsole", "main", "run"]
def _output_fn(s):
sys.stdout.write(
s.encode(sys.stdout.encoding, errors="replace").decode(sys.stdout.encoding)
)
sys.stdo... | self._connectionDropped()
def _readThreadReady(self):
if not self.running:
return -1
return self.sockrfp
def _readThread(self):
while True | :
with self.cond:
sockrfp = self.cond.wait_for(self._readThreadReady)
if sockrfp == -1:
return
try:
data = sockrfp.read(self._headerSz)
except IOError:
data = ""
if len(data) != self._he... |
Zephor5/zspider | zspider/pipelines/test_result.py | Python | mit | 283 | 0 | # coding=utf-8
__author__ = " | zephor"
class TestResultPipeLine(object):
@classmethod
def from_crawler(cls, crawler):
crawler.spider.test_result = []
return cls()
@staticmethod
def process_item(item, spider):
| spider.test_result.append(item)
|
lgnq/RPI8836 | issi.py | Python | lgpl-3.0 | 2,227 | 0.015267 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
import define
import tw8836
import spi
def quad_check():
status = spi.status1_read()
if (status & 0x40):
print 'SPI flash is already in QUAD mode'
return define.TRUE
else:
print 'SPI flash is not in QUAD mode yet'
return def... | return define.FALSE
def four_byte_enter() | :
tw8836.write_page(0x04)
tw8836.write(0xF3, (spi.DMA_DEST_CHIPREG << 6) + spi.DMA_CMD_COUNT_1)
tw8836.write(0xF5, 0) #length high
tw8836.write(0xF8, 0) #length middle
tw8836.write(0xF9, 0) #length low
tw8836.write(0xFA, spi.SPICMD_EN4B)
tw8836.write(0xF4, spi.SPI... |
DanielNeugebauer/adhocracy | src/adhocracy/forms/common.py | Python | agpl-3.0 | 30,325 | 0.000297 | import csv
from datetime import datetime
import re
from StringIO import StringIO
from PIL import Image
import formencode
from pylons import tmpl_context as c
from pylons.i18n import _
from webhelpers.html import literal
from sqlalchemy import func
from adhocracy import config
from adhocracy.lib.auth import can
from ... | raise formencode.Invalid(
_('That email is already used b | y another account'),
value, state)
return value
class ValidLocale(formencode.FancyValidator):
def _to_python(self, value, state):
from adhocracy import i18n
if value in i18n.LOCALE_STRINGS:
return value
else:
raise formencode.Invalid(_('Inval... |
drjova/cds-demosite | cds/modules/records/minters.py | Python | gpl-2.0 | 1,381 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016 CERN.
#
# Invenio 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 option) any later... | record_uuid, data):
"""Mint record identifiers."""
assert 'recid' not in data
provider = CDSRecordIdProvider.create(
object_type='rec', object_uuid=record_uui | d)
data['recid'] = int(provider.pid.pid_value)
return provider.pid
|
jokey2k/sentry | src/sentry/rules/actions/__init__.py | Python | bsd-3-clause | 241 | 0 | """
sentry.rules.actions
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from .base import * # NO | QA
| |
helenst/django | tests/foreign_object/tests.py | Python | bsd-3-clause | 18,027 | 0.003495 | import datetime
from operator import attrgetter
from .models import (
Country, Person, Group, Membership, Friendship, Article,
ArticleTranslation, ArticleTag, ArticleIdea, NewsArticle)
from django.test import TestCase, skipUnlessDBFeature
from django.utils.translation import activate
from django.core.exception... | .id)
# Creating an invalid membership
| Membership.objects.create(membership_country_id=self.soviet_union.id,
person_id=self.george.id, group_id=self.cia.id)
self.assertQuerysetEqual(
Membership.objects.filter(person__name__contains='o'), [
self.bob.id
],
attrge... |
g76r/graphite-web | webapp/graphite/settings.py | Python | apache-2.0 | 6,812 | 0.009689 | """Copyright 2008 Orbitz WorldWide
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... | S_CONF:
GRAPHTEMPLATES_CONF = join(CONF_DIR, 'graphTemplates.conf')
if not STORAGE_DIR:
STORAGE_DIR = os.environ.get('GRAPHITE_STORAGE_DIR', join(GRAPHITE_ROOT, 'storage'))
if not WHITELIST_FILE:
WHITELIST_FILE = join(STORAGE_DIR, 'lists', 'whitelist')
if not INDEX_FILE:
INDEX_FILE = join(STORAGE_DIR, 'index')... | )
if not CERES_DIR:
CERES_DIR = join(STORAGE_DIR, 'ceres/')
if not RRD_DIR:
RRD_DIR = join(STORAGE_DIR, 'rrd/')
if not STANDARD_DIRS:
try:
import whisper
if os.path.exists(WHISPER_DIR):
STANDARD_DIRS.append(WHISPER_DIR)
except ImportError:
print >> sys.stderr, "WARNING: whisper module could no... |
gautsi/cRedditscore | docs/conf.py | Python | bsd-3-clause | 9,078 | 0.003855 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# cRedditscore documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 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
... | he version info for the project you're documenting, acts as replacement
# for |version| and |r | elease|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = cRedditscore.__version__
# The full version, including alpha/beta/rc tags.
release = cRedditscore.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supp... |
docusign/docusign-python-client | docusign_esign/models/app_store_product.py | Python | mit | 4,127 | 0.000242 | # coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501
OpenAPI spec version: v2.1
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.gi... | ute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'market_place': 'str',
'product_id': 'str'
}
attribute_map = {
'market_place': 'marketPlace',
'product_id': 'productId'
}
def __i... | """AppStoreProduct - a model defined in Swagger""" # noqa: E501
self._market_place = None
self._product_id = None
self.discriminator = None
if market_place is not None:
self.market_place = market_place
if product_id is not None:
self.product_id = pro... |
pyropeter/archweb | mirrors/views.py | Python | gpl-2.0 | 4,912 | 0.003054 | from django import forms
from django.db.models import Avg, Count, Max, Min, StdDev
from django.db.models import Q
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.simple import direct_to_template
from main.util... | irrors/mirrors.html',
{'mirror_list': mirrors})
def mirror_details(request, name):
mirror = get_object_or_404(Mirror, name=name)
if not request.user.is_authenticated() and \
(not mirror.public or not mirror.active):
# TODO: maybe this should be 403? but that would leak existence... | medelta = datetime.timedelta(days=3)
status_info = get_mirror_statuses()
urls = status_info['urls']
good_urls = []
bad_urls = []
for url in urls:
# split them into good and bad lists based on delay
if not url.delay or url.delay > bad_timedelta:
bad_urls.append(url)
... |
georgid/sms-tools | software/models_interface/dftModel_GUI_frame.py | Python | agpl-3.0 | 4,273 | 0.040019 | # GUI frame for the dftModel_function.py
from Tkinter import *
import tkFileDialog, tkMes | sageBox
import sys, os
import pygame
from scipy.io.wavfile import read
import dftModel_function
class DftModel_frame:
def __init__(self, parent):
self.parent = parent
self.initUI()
pygame.init()
def initUI(self):
choose_label = "Input file (.wav, mono and 44100 sampling rate):"
Label(se... | xt=choose_label).grid(row=0, column=0, sticky=W, padx=5, pady=(10,2))
#TEXTBOX TO PRINT PATH OF THE SOUND FILE
self.filelocation = Entry(self.parent)
self.filelocation.focus_set()
self.filelocation["width"] = 25
self.filelocation.grid(row=1,column=0, sticky=W, padx=10)
self.filelocation.delete(0, END)
s... |
cchurch/ansible | test/units/module_utils/urls/test_Request.py | Python | gpl-3.0 | 14,937 | 0.001674 | # -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# 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
import datetime
import os
from ansible.module_utils.urls import (Request, o... | ener_mock.call_args[0][0]
handlers = opener.handlers
expected_handlers = (
urllib_request.HTTPBasicAuthHandler,
urllib_request.HTTPDigestAuthHandler,
)
found_handlers = []
for handler in handlers:
if isinstance(handler, expected_handle | rs):
found_handlers.append(handler)
assert len(found_handlers) == 2
assert found_handlers[0].passwd.passwd[None] == {(('ansible.com', '/'),): ('user', None)}
def test_Request_open_username_in_url(urlopen_mock, install_opener_mock):
r = Request().open('GET', 'http://user2@ansible.com/')
op... |
szopu/datadiffs | datadiffs/exceptions.py | Python | mit | 46 | 0 | class InvalidValueSta | te(Valu | eError):
pass
|
antoinecarme/pyaf | tests/artificial/transf_Integration/trend_ConstantTrend/cycle_12/ar_12/test_artificial_128_Integration_ConstantTrend_12_12_0.py | Python | bsd-3-clause | 271 | 0.084871 | import pyaf.Bench.TS_datasets as tsds
import test | s.artificial.process_artificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "ConstantTrend", cycle_length = 12, transform = "Integration", | sigma = 0.0, exog_count = 0, ar_order = 12); |
Microvellum/Fluid-Designer | win64-vc/2.78/Python/bin/2.78/scripts/addons/presets/operator/mesh.primitive_round_cube_add/Capsule.py | Python | gpl-3.0 | 141 | 0 | import bpy
op = bpy.context.ac | tive_operator
op.radius = 0.5
op.arc_div = 8
op.lin_div = 0
op.size = (0.0, 0.0, 3.0)
op.div_type = 'COR | NERS'
|
SeedScientific/polio | source_data/migrations/0113_auto__del_field_sourceregion_is_high_risk.py | Python | agpl-3.0 | 20,716 | 0.008351 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'SourceRegion.is_high_risk'
db.execute('''
ALTER... | lds.related.ForeignKey', [], {'to': u"orm['datapoints.Re | gion']", 'null': 'True'}),
'region_code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'region_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['datapoints.RegionType']"}),
'slug': ('autoslug.fields.AutoSlugField', [], {'un... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.