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 |
|---|---|---|---|---|---|---|---|---|
pombredanne/straight.plugin | test-packages/package-test-plugins/testplugin/foo/__init__.py | Python | mit | 25 | 0.04 | def do(i):
| return i+2 | |
riklaunim/django-examples | suqashexamples/manage.py | Python | mit | 257 | 0 | #!/ | usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "suqashexamples.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) | |
botswana-harvard/edc-visit-schedule | edc_visit_schedule/fieldsets.py | Python | gpl-2.0 | 430 | 0 | visit_schedule_fields = ('visit_schedule_name', 'schedule_name | ', 'visit_code')
visit_schedule_fieldset_tuple = (
'Visit Schedule', {
'classes': ('collapse',),
'fields': visit_schedule_fields})
visit_schedule_only_fields = ('visit_schedule_name', 'schedule_name')
visit_schedule_only_fieldset_tuple = (
'Visit Schedule', | {
'classes': ('collapse',),
'fields': visit_schedule_only_fields})
|
rchakra3/x9115rc3 | hw/code/8/optimizer/de2.py | Python | gpl-2.0 | 6,313 | 0.000634 | from __future__ import division
import random
import math
from common import prerun_each_obj
from model.helpers.candidate import Candidate
from helpers.a12 import a12
""" This contains the optimizers """
def de(model, frontier_size=10, cop=0.4, ea=0.5, max_tries=100, threshold=0.01, era_size=10, era0=None, lives=5):
... | cores):
curr_era[index] += [score]
eras += [curr_era]
curr_era = [[] for _ in model.objectives()]
if len(eras) > 1:
if type2(eras[len(eras) - 2], eras[len(eras) - 1]):
curr_lives += lives
else:
curr_lives -= 1
... | if curr_lives == 0:
# print "No more"
out += ["\nNo more Lives"]
break
# print ''.join(out)
# print "\nNumber of repeats:" + str(j + 1)
# print "Best Score:" + str(best_score)
return _, best_score, eras[len(eras) - 1]
def de_update(frontier,... |
akretion/python-cfonb | cfonb/__init__.py | Python | lgpl-3.0 | 48 | 0 | #
| from .parser.statement import StatementReader
| |
jantman/gw2copilot | gw2copilot/wine_mumble_reader.py | Python | agpl-3.0 | 9,880 | 0.000405 | """
gw2copilot/wine_mumble_reader.py
The latest version of this package is available at:
<https://github.com/jantman/gw2copilot>
################################################################################
Copyright 2016 Jason Antman <[email protected]> <http://www.jasonantman.com>
This file is part of g... | ##########
"""
import logging
import os
import json
import psutil
import pkg_resources
from twisted.internet import protocol
from twisted.internet.task import LoopingCall
logger = logging.getLogger(__name__)
class WineMumbleLinkReader(object):
"""
Class to handle reading MumbleLink via wine.
"""
de... | """
Initialize the class.
:param parent_server: the TwistedServer instance that started this
:type parent_server: :py:class:`~.TwistedServer`
:param poll_interval: interval in seconds to poll MumbleLink
:type poll_interval: float
"""
logger.debug("Instantiating Wi... |
looker/sentry | src/sentry/db/models/base.py | Python | bsd-3-clause | 4,686 | 0.00064 | """
sentry.db.models
~~~~~~~~~~~~~~~~
: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 copy import copy
import logging
import six
from bitfield.types import BitHandler
from django.db import models... | "Returns ``True`` if ``field`` has changed since initialization."
if self.__data is UNSAVED:
return False
field = self._meta.get_field(field_name)
value = self.__get_field_value(field)
if value is DEFERRED:
return False
return self.__data.get(field_nam... | D:
return None
value = self.__data.get(field_name)
if value is DEFERRED:
return None
return self.__data.get(field_name)
class Model(BaseModel):
id = BoundedBigAutoField(primary_key=True)
class Meta:
abstract = True
__repr__ = sane_repr('id')
def ... |
kkozarev/mwacme | casa_commands_instructions/plot_max_spectra_calibrated.py | Python | gpl-2.0 | 12,151 | 0.026088 | import glob, os, sys,fnmatch
import matplotlib.pyplot as plt
from astropy.io import ascii
import numpy as np
def match_list_values(ls1,ls2):
#Return lists of the indices where the values in two lists match
#It will return only the first index of occurrence of repeating values in the lists
#Written by Kame... | ions/480214/how-do-you-remove-duplicates-fro | m-a-list-in-whilst-preserving-order
#list1=['03:39:04','03:40:04','03:41:15','03:43:20','03:45:39']
#list2=['03:39:04','03:41:15','03:43:20','03:45:39','03:40:04','03:40:04']
list1=list(ls1)
list2=list(ls2)
matches=set(list1).intersection(list2)
indlist1=[i for i,item in enumerate(list1) if item... |
aadarshkarumathil/Webserver | webserver.py | Python | gpl-3.0 | 10,173 | 0.021921 | #!/usr/bin/python2
from conf import *
import socket
import os
from threading import Thread
import time
def get_cookie(request_lines):
#print("cookie data is: " + request_lines[-3])
data = request_lines[-3].split(":")[-1]
return (data.split("=")[-1])
def error_404(addr,request_words):
print("File not ... | #f.close()
csock.sendall(response)
csock.close()
#print(file_name)
def error_501(addr,request_words):
print("NOT Implemented")
logging(addr,reques | t_words,"error","501")
csock.sendall(error_handle(501,"text/html",False))
response = """<html><head><body>Not Implemented </body></head></html>"""
#f = open("404.html","r")
#response = f.read()
#f.close()
csock.sendall(response)
csock.close()
#print(file_name)
def error_401(addr,request... |
michaelBenin/autopep8 | test/suite/out/long_lines.py | Python | mit | 300 | 0 | if True:
| if True:
if True:
self.__heap.sort(
) # pylint: builtin sort probably faster than O(n)-time heapify
if True:
foo = '( | ' + \
array[0] + ' '
|
lancifollia/laon_crf | feature.py | Python | mit | 8,052 | 0.001987 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import Counter
import numpy as np
STARTING_LABEL = '*' # Label of t=-1
STARTING_LABEL_INDEX = 0
def default_feature_func(_, X, t):
"""
Returns a list of feature strings.
(Default feature function)
:param X: An observation vector... | urn self.num_features
def _add(self, prev_y, y, X, t):
"""
Generates features, constructs feature_dic.
:param prev_y: previous label
:param | y: present label
:param X: observation vector
:param t: time
"""
for feature_string in self.feature_func(X, t):
if feature_string in self.feature_dic.keys():
if (prev_y, y) in self.feature_dic[feature_string].keys():
self.empirical_counts[s... |
rartino/ENVISIoN | envisionpy/hdf5parser/vasp/check_for_parse.py | Python | bsd-2-clause | 3,028 | 0.012884 | ## ENVISIoN
##
## Copyright (c) 2021 Gabriel Anderberg, Didrik Axén, Adam Engman,
## Kristoffer Gubberud Maras, Joakim Stenborg
## All rights reserved.
##
## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are met:
##
## 1. ... | pyright notice,
## this list of conditions and the following disclaimer in the documentation
## and/or other materials provided with the distribution.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
## ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIE... | GHT OWNER OR CONTRIBUTORS BE LIABLE FOR
## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
## (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
## LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
## ON ANY THEORY OF LIABILITY, WHET... |
daviddoria/itkHoughTransform | Wrapping/WrapITK/Languages/SwigInterface/pygccxml-1.0.0/pygccxml/utils/__init__.py | Python | apache-2.0 | 5,211 | 0.014585 | # Copyright 2004-2008 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
"""
defines logger classes and few convinience methods, not related to the declarations
tree
"""
import os
import sys
import l... |
"""returns computer architecture: 32 or 64.
The guess is based on maxint.
"""
if | sys.maxint == 2147483647:
return 32
elif sys.maxint == 9223372036854775807:
return 64
else:
raise RuntimeError( "Unknown architecture" )
#The following code is cut-and-paste from this post:
#http://groups.google.com/group/comp.lang.python/browse_thread/thread/5b71896c06bd0f76/
#Thanks... |
tkarabela/pysubs2 | tests/test_parse_tags.py | Python | mit | 1,695 | 0.00413 | from pysubs2 import SSAStyle
from pysubs2.substation | import parse_tags
def test_no_tags():
text = "Hello, world!"
assert parse_tags(text) == [(text, SSAStyle())]
def test_i_tag():
text = "Hello, {\\i1}world{\\i0}!"
| assert parse_tags(text) == [("Hello, ", SSAStyle()),
("world", SSAStyle(italic=True)),
("!", SSAStyle())]
def test_r_tag():
text = "{\\i1}Hello, {\\r}world!"
assert parse_tags(text) == [("", SSAStyle()),
("Hello... |
zepto/musio | examples/musioencode.py | Python | gpl-3.0 | 11,944 | 0.000084 | #!/usr/bin/env python
# vim: sw=4:ts=4:sts=4:fdm=indent:fdl=0:
# -*- coding: UTF8 -*-
#
# Test the vorbis encoder.
# Copyright (C) 2013 Josiah Gordon <[email protected]>
#
# 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 ... | quit_val = False
break
elif command == '\n':
break
except Exception as err:
print("Error: %s" % err, flush=True)
raise(err)
finally:
# Re-set the terminal state.
tcsetattr(stdin, TCSANOW, norm | al)
if args['show_position']:
print("\nDone.")
return quit_val
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser(description="Musio encoder")
parser.add_argument('-e', '--quality', action='store', default=-10,
type=int, help='E... |
nxvl/critsend_test | test_proyect/urls.py | Python | mit | 482 | 0 | # coding=utf-8
"""
CritSend test proyect urls.
Copyright (C) 2013 Nicolas Valcárcel Scerpella
Authors:
Nicolas Valcárcel Scerpella <[email protected]>
"""
# Standard library imports
# Framework imports
from dj | ango.conf.urls import patterns, include, url
from django.contrib import admin
# 3rd party imports
# Local imports
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^', include('upload.urls')) | ,
url(r'^admin/', include(admin.site.urls)),
)
|
jawilson/home-assistant | homeassistant/components/freedompro/binary_sensor.py | Python | apache-2.0 | 2,578 | 0.000388 | """Support for Freedompro binary_sensor."""
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_MOTION,
DEVICE_CLASS_OCCUPANCY,
DEVICE_CLASS_OPENING,
DEVICE_CLASS_SMOKE,
BinarySensorEntity,
)
from homeassistant.core import callback
from homeassistant.helpers.entity import DeviceInfo
fr... | motionDetected",
"contactSensor": "contactSensorState",
}
SUPPORTED_SENSORS = {"smokeSensor", "occupancySensor", "motionSensor", "contactSensor"}
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up Freedompro binary_sensor."""
coordi | nator = hass.data[DOMAIN][entry.entry_id]
async_add_entities(
Device(device, coordinator)
for device in coordinator.data
if device["type"] in SUPPORTED_SENSORS
)
class Device(CoordinatorEntity, BinarySensorEntity):
"""Representation of an Freedompro binary_sensor."""
def __ini... |
b12io/orchestra | orchestra/admin.py | Python | apache-2.0 | 13,202 | 0 | from ajax_select import make_ajax_form
from ajax_select.admin import AjaxSelectAdmin
from bitfield import BitField
from bitfield.admin import BitFieldListFilter
from bitfield.forms import BitFieldCheckboxSelectMultiple
from django.contrib import admin
from django.http import HttpResponseRedirect
from django.shortcuts i... | ated_at',)
search_fields = ('todo__title', 'comment',)
@admin.register(TodoListTemplateImportRecord)
class TodoListTemplateImportRecordAdmin(AjaxSelectAdmin):
list_display = ('id', 'created_at', 'todo_list_template', 'importer')
list_filter = ('todo_list_template',)
search_fields = (
'todo_lis... | te__description',
'import_url'
)
ordering = ('-created_at',)
@admin.register(TodoListTemplate)
class TodoListTemplateAdmin(DjangoObjectActions, AjaxSelectAdmin):
change_actions = ('export_spreadsheet', 'import_spreadsheet')
form = make_ajax_form(TodoListTemplate, {
'creator': 'workers'... |
gocardless/gocardless-pro-python | gocardless_pro/services/mandate_pdfs_service.py | Python | mit | 3,470 | 0.007205 | # WARNING: Do not edit by hand, this file was generated by Crank:
#
# https://github.com/gocardless/crank
#
from . import base_service
from .. import resources
from ..paginator import Paginator
from .. import errors
class MandatePdfsService(base_service.BaseService):
"""Service class that provides access to the... |
|
| BECS NZ | English (`en`)
|
|
| Betalingsservice | Danish (`da`), English (`en`)
|
| PAD | English (`en`) ... |
ya790206/call_seq | setup.py | Python | apache-2.0 | 446 | 0.044843 | #!/usr/bin/en | v python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import call_seq
setup(
name = 'call_seq',
version = '0.0.2',
description = 'call sequence visualization',
author = 'ya790206',
url = 'https://github.com/ya790206/call_seq',
license = 'Apache License Version 2.0',
... | packages = find_packages(),
entry_points = {
}
)
|
open-homeautomation/home-assistant | homeassistant/components/sensor/ups.py | Python | apache-2.0 | 3,298 | 0 | """
Sensor for UPS packages.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.ups/
"""
from collections import defaultdict
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_... | hrottle(interval)(self._update)
self.update()
@property
def name(self):
"""Return the name of the sensor."""
return self._na | me or DOMAIN
@property
def state(self):
"""Return the state of the sensor."""
return self._state
def _update(self):
"""Update device state."""
import upsmychoice
status_counts = defaultdict(int)
for package in upsmychoice.get_packages(self._session):
... |
landscape-test/all-messages | messages/pep8/E128.py | Python | unlicense | 65 | 0 | """
E128
|
Continuation line under-indented for visu | al indent
"""
|
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/pylint/test/input/func_unused_overridden_argument.py | Python | agpl-3.0 | 913 | 0.003286 | # pylint: disable=R0903, print-statement
"""for Sub.inherited, only the warning for "aay" is desired.
The warnings for "aab" and "aac" are most likely false positives though,
because there could be another subclass that overrides the same method and does
use the arguments (eg Sub2)
"""
__revision__ = 'thx to M... | "abstract method"
raise NotImplementedError
class Sub(Base):
"child 1"
def in | herited(self, aaa, aab, aac):
"overridden method, though don't use every argument"
return aaa
def newmethod(self, aax, aay):
"another method, warning for aay desired"
print(self, aax)
class Sub2(Base):
"child 1"
def inherited(self, aaa, aab, aac):
"over... |
scieloorg/opac | opac/webapp/models.py | Python | bsd-2-clause | 5,095 | 0.001185 | # coding: utf-8
"""
Conjunto de modelos relacionais para o controle da app (Usuarios, auditorias, logs, etc)
Os modelos do catálogo do OPAC (periódicos, números, artigos) estão definidos na
lib: opac_schema (ver requirements.txt)
"""
import os
from sqlalchemy.event import listens_for
from sqlalchemy.ext.h... | ia (self) do usuário, tem um email válido.
retorna False em outro caso.
"""
from webapp.admin.forms import EmailForm
if not self.email or self.email == '' or self.email == '':
return False
else:
form = Em | ailForm(data={'email': self.email})
return form.validate()
# Required for administrative interface
def __unicode__(self):
return self.email
@login_manager.user_loader
def load_user(user_id):
"""
Retora usuário pelo id.
Necessário para o login manager.
"""
retur... |
endlessm/chromium-browser | third_party/catapult/third_party/gsutil/third_party/gcs-oauth2-boto-plugin/setup.py | Python | bsd-3-clause | 3,026 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2014 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | rmissions and
# limitations under the License.
"""Setup installation module for gcs-oauth2-boto-plugin."""
from setuptools import find_packages
from setuptools import setup
long_desc = """
gcs-oauth2-boto-plugin is a Python application whose purpose is to behave as an
auth plugin for the boto auth plugin framework f... | er accounts and service accounts, and its functionality is essentially a
wrapper around oauth2client with the addition of automatically caching tokens
for the machine in a thread- and process-safe fashion.
"""
requires = [
'boto>=2.29.1',
'google-reauth>=0.1.0',
'httplib2>=0.8',
'oauth2client>=2.2.0',
... |
xStream-Kodi/plugin.video.xstream | resources/lib/handler/requestHandler.py | Python | gpl-3.0 | 11,867 | 0.002949 | #!/usr/bin/env python2.7
import hashlib
import httplib
import os
import socket
import sys
import time
import urllib
import mechanize
import xbmcgui
from resources.lib import common
from resources.lib import logger, cookie_helper
from resources.lib.cBFScrape import cBFScrape
from resources.lib.cCFScrape import cCFScra... |
if (self.__bRemoveBreakLines == True):
sContent = sContent.replace(" ", "")
self.__sRealUrl = oResponse.geturl()
oResponse.close()
if self.caching and self.cacheTime > 0:
self.writeCache(self.getRequestUri(), sContent)
return sContent
def __... | erification' in html:
oResponse = cCFScrape().resolve(self.__sUrl, cookie_jar, user_agent)
elif 'Blazingfast.io' in html:
oResponse = cBFScrape().resolve(self.__sUrl, cookie_jar, user_agent)
return oResponse
def getHeaderLocationUrl(self):
opened = mechanize.urlopen... |
caronc/nzb-subliminal | Subliminal/subliminal/providers/thesubdb.py | Python | gpl-3.0 | 3,140 | 0.003503 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
import babelfish
import requests
from . import Provider
from .. import __version__
from ..exceptions import InvalidSubtitle, ProviderNotAvailable, ProviderError
from ..subtitle import Subtitle, is_valid_subtitle, detect
logger = logging.ge... | split(',')])]
def list_subtitles(self, video, languages):
return [s for s in self.query(video.hashes['thesubdb']) if s.language in languages]
def download_subtitle(self, subtitle):
params = {'action': | 'download', 'hash': subtitle.hash, 'language': subtitle.language.alpha2}
r = self.get(params)
if r.status_code != 200:
raise ProviderError('Request failed with status code %d' % r.status_code)
logger.debug('Download URL: %s {hash=%s, lang=%s}' % (
'http://api.thesubdb.co... |
koduj-z-klasa/python101 | docs/conf.py | Python | mit | 9,897 | 0.00475 | # -*- coding: utf-8 -*-
#
# Python 101 documentation build configuration file, created by
# sphinx-quickstart on Tue Sep 16 15:47:34 2014.
#
# 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... | ilt documents.
#
# The short X.Y version.
version = '0.5'
# The full version, including alpha/beta/rc tags.
release = '0.5'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either,... | alse value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (u... |
CingHu/neutron-ustack | neutron/tests/unit/services/loadbalancer/drivers/haproxy/test_namespace_driver.py | Python | apache-2.0 | 25,764 | 0.000116 | # Copyright 2013 New Dream Network, LLC (DreamHost)
#
# 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 a... | _in_file'),
mock.patch.object(self.driver, | '_unplug'),
mock.patch('neutron.agent.linux.ip_lib.IPWrapper'),
mock.patch('os.path.isdir'),
mock.patch('shutil.rmtree')
) as (gsp, kill, unplug, ip_wrap, isdir, rmtree):
gsp.side_effect = lambda x, y: '/pool/' + y
self.driver.pool_to_port_id['pool_i... |
MartinSilvert/overlappingGenesCreator | src/modifDoublon2.py | Python | apache-2.0 | 1,846 | 0.022814 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 09:30:47 2015
@author: martin
"""
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
from Bio.SubsMat.MatrixInfo import blosum62
#remarque : Ceci n'est pas une maélioration de modifDoublon,
#c'est une version alternative qui ne s'applique pas aux même doublons.
de... | return matrix[(a,b)]
def modifDoublon2(x,y,z,ldna,offset,doublon,i,q,patternX,patternY):
ATCG = ["A","T","C","G"]
# on | commence par déterminer quels acides aminés de x et y sont "ciblés"
aaX = Seq("", IUPAC.protein)
aaY = Seq("", IUPAC.protein)
q_bis = 0.
q_bis += q
if(z<=0):
aaX += x[i]
q_bis /= patternX[i]
else:
aaX += x[i+1+z//3]
q_bis /=patternX[i+1+z//3]
if(z>0):
... |
mikemaccana/resilience | __init__.py | Python | mit | 2,874 | 0.012178 | import sys
import traceback
import logging
import time
import inspect
def run_resilient(function, function_args=[], function_kwargs={}, tolerated_errors=(Exception,), log_prefix='Something failed, tolerating error and retrying: ', retries=5, delay=True, critical=False, initial_delay_time=0.1, delay_multiplier = 2.0):
... | should either fix something, or, if we want to tolerate it,
# add it to our tolerated_errors.
# Those things require human judgement, so we'll raise the exception.
logging.exception('Unanticipated error recieved!') #Log the exception
raise #Re-rai... | # We've received an exception that isn't even an Exception subclass!
# This is bad manners - see http://docs.python.org/tutorial/errors.html:
# "Exceptions should typically be derived from the Exception class, either directly or indirectly."
logging.exception("Bad manne... |
eammx/proyectosWeb | proyectoPython/app/__init__.py | Python | mit | 269 | 0.011152 | from flask import F | lask
from flask_bootstrap import Bootstrap
app = Flask(__name__)
bootstrap = Bootstrap()
from .views import page
def create_app(config):
app.config.from_object(config)
bootstrap.init_app(app)
app.register_blueprint(page)
return | app |
NeCTAR-RC/nectar-images | community_image_tests/community_image_tests_tempest_plugin/services/v2/community_image_client.py | Python | apache-2.0 | 1,416 | 0 | # Copyright (c) 2016, Monash e-Research Centre
# (Monash University, Australia)
# 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... | rt images_client
class CommunityImagesClient(images_client.ImagesClient):
def show_image(self, image_id):
url = 'images/%s' % image_id
resp, body = self.get(url)
self.expected_success(200, resp.status)
body = json.loads(body)
self. | validate_response(schema.community_image_schema, resp, body)
return rest_client.ResponseBody(resp, body)
|
arfathpasha/kb_cufflinks | lib/kb_cufflinks/core/script_utils.py | Python | mit | 5,654 | 0.000707 | import logging
import os
import subprocess
import traceback
from zipfile import ZipFile
from os import listdir
from os.path import isfile, join
'''
A utility python module containing a set of methods necessary for this kbase
module.
'''
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'war... | _l):
obj_list = ws_client.list_objects({"workspaces": [ws_id], "type": o_type, 'showHidden': 1})
obj_names = [i[1] for i in obj_list]
existing_names = [i for i in obj_l if i in obj_names]
obj_ids = | None
if len(existing_names) != 0:
e_queries = [{'name': j, 'workspace': ws_id} for j in existing_names]
e_infos = ws_client.get_object_info_new({"objects": e_queries})
obj_ids = [(str(k[1]), (str(k[6]) + '/' + str(k[0]) + '/' + str(k[4]))) for k in e_infos]
return obj_ids
def log(messa... |
dkamotsky/program-y | src/programy/utils/classes/loader.py | Python | mit | 1,706 | 0.005862 | """
Copyright (c) 2016 Keith Sterling
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute,... | e, class_name)
| return new_class
|
Cyber-Neuron/inception_v3 | inception/inception/data/build_image_test_data.py | Python | apache-2.0 | 15,171 | 0.007251 | # Copyright 2016 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 held in th | is file.
# Assumes that the file contains entries as such:
# dog
# cat
# flower
# where each line corresponds to a label. We map each label contained in
# the file to an integer corresponding to the line number starting from 0.
tf.app.flags.DEFINE_string('labels_file', '', 'Labels file')
FLAGS = tf.app.flags.FL... |
Vettejeep/Boulder_County_Home_Prices | plots.py | Python | gpl-3.0 | 5,261 | 0.00114 | # Plotting routines in Python
# requires data from Assemble_Data.py
# Copyright (C) 2017 Kevin Maher
# This progra | m is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOU... | PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Data for this project may be the property of the Boulder County Assessor's office,
# they gave me free ... |
dhermes/project-euler | python/complete/no071.py | Python | apache-2.0 | 971 | 0.00103 | #!/usr/bin/env python
# neighbors
# a/b < c/d
# need bc - ad = 1
# The converse is also true. If
# bc - ad = 1
# for positive integers | a,b,c and d with a < b and c < d then a/b and c/d
# will be neighbours in the Farey sequence of order max(b,d).
# By listing the set of reduced proper fractions for D <= 1,000,000 in
# ascending order of size, find the numerator of the fraction immediately
# to the left of 3/7.
#######################################... | d = 7, 3b - 7a = 1
# 0 + 2a == 1 mod 3, a == 2 mod 3
# a = 3k + 2, b = 7k + 5
# a < b <==> 3k + 2 < 7k + 5, -3 < 4k, -0.75 < k, k >= 0
# a/b < 3/7 <==> 7a < 3b <==> 0 < 3b - 7a <==> ALWAYS
# gcd(a,b) = (3k+2,7k+5) = (3k+2,k+1) = (k,k+1) = 1
# b <= D
# 7k + 5 <= D
# k <= floor((D-5)/7)
from python.decorators import e... |
jjd27/xapi-storage-datapath-plugins | src/tapdisk/plugin.py | Python | lgpl-2.1 | 1,061 | 0.000943 | #!/usr/bin/env python
import os
import sys
import xapi
import xapi.storage.api.plugin
from xapi.storage import log
class Implementation(xapi.storage.api.plugin.Plugin_skeleton):
def query(self, dbg):
return {
"plugin": "tapdisk",
"name": "The tapdisk user-space datapath plugin",
... | " instances backend by either raw or vhd"
" format files"),
"vendor": "Citrix",
"copyrig | ht": "(C) 2015 Citrix Inc",
"version": "3.0",
"required_api_version": "3.0",
"features": [
],
"configuration": {},
"required_cluster_stack": []}
if __name__ == "__main__":
log.log_call_argv()
cmd = xapi.storage.api.plugin.Plugin_commandlin... |
annarev/tensorflow | tensorflow/python/autograph/pyct/testing/basic_definitions.py | Python | apache-2.0 | 1,533 | 0.009132 | # Copyright 2017 The TensorFlow Authors. 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 applica... |
x + 1,
)
def basic_decorator(f):
return f
@basic_decorator
@basic_decorator
def decorated_function(x):
if x > 0:
return 1 |
return 2
|
gwtsa/gwtsa | examples/reads/test_knmidata.py | Python | mit | 1,974 | 0.00304 | """
@author: ruben
"""
import matplotlib.pyplot as p | lt
from pastas.read.knmi import KnmiStation
import numpy as np
# How to use it?
# data from | a meteorological station
download = True
meteo = True
hourly = False
if hourly and not meteo:
raise(ValueError('Hourly data is only available in meteorological stations'))
if download:
# download the data directly from the site of the KNMI
if meteo:
if hourly:
knmi = KnmiStation.downloa... |
cortext/crawtextV2 | ~/venvs/crawler/lib/python2.7/site-packages/setuptools/svn_utils.py | Python | mit | 18,879 | 0.002013 | import os
import re
import sys
from distutils import log
import xml.dom.pulldom
import shlex
import locale
import codecs
import unicodedata
import warnings
from setuptools.compat import unicode
from setuptools.py31compat import TemporaryDirectory
from xml.sax.saxutils import unescape
try:
import url... | staticmethod
def get_svn_version():
# Temp config directory should be enough to check for repository
# This is needed because .svn always creates .subversion and
# some operating systems do not handle dot directory correctly.
# Real queries i | n real svn repos with be concerned with it creation
with TemporaryDirectory() as tempdir:
code, data = _run_command(['svn',
'--config-dir', tempdir,
'--version',
'--quiet'])
... |
tapo-it/odoo-addons-worktrail | addons_worktrail/tapoit_hr_project/wizard/tapoit_hr_project_sign_in_out.py | Python | agpl-3.0 | 10,543 | 0.00332 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2011 TaPo-IT (http://tapo-it.at) All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the ... | neral Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm, fields
from openerp.tools.translate import _
import logging
import time
_logger = | logging.getLogger(__name__)
class hr_so_project(orm.TransientModel):
_name = 'hr.sign.out.task.work'
_description = 'Sign Out By Task Work'
_columns = {
'task_id': fields.many2one('project.task', 'Task', required=True),
'action_desc': fields.many2one('hr.action.reason', 'Action description... |
hendrikjeb/Euler | 07.py | Python | mit | 364 | 0.021978 | # -*- | coding: utf-8 -*-
"""
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
from time import time
s = time()
x = 3
priem = [2, 3]
while len(priem) < 10001:
x += 2
for y in | priem:
if x % y == 0:
break
else:
priem.append(x)
print priem[-1]
print time() - s |
ktan2020/legacy-automation | win/Lib/site-packages/docutils/writers/manpage.py | Python | mit | 35,646 | 0.001964 | # -*- coding: utf-8 -*-
# $Id: manpage.py 7485 2012-07-06 08:17:28Z grubert $
# Author: Engelbert Gruber <[email protected]>
# Copyright: This module is put into the public domain.
"""
Simple man page writer for reStructuredText.
Man pages (short for "manual pages") contain system documentation on unix-li... | ` lines"""
while (cell_lines and cell_lines[0] in ('\n', '.sp\n')):
| del cell_lines[0]
while (cell_lines and cell_lines[-1] in ('\n', '.sp\n')):
del cell_lines[-1]
def as_list(self):
text = ['.TS\n']
text.append(' '.join(self._options) + ';\n')
text.append('|%s|.\n' % ('|'.join(self._coldefs)))
for row in self._rows:
... |
ivanxalie/learning_log | learning_logs/forms.py | Python | unlicense | 394 | 0.005076 | from django import forms
from .models import Topic, Entry
class Topi | cForm(forms.ModelForm):
class Meta:
model = To | pic
fields = ['text']
labels = {'text': ''}
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = ['text']
labels = {'text': ''}
widgets = {'text': forms.Textarea(attrs={'cols': 80})}
|
m3zbaul/ai-search | simulated_annealing.py | Python | mit | 668 | 0.001497 | # coding=utf-8
import random
import math
import n_queen
def simulated_annealing_search(problem):
# annealing parameters
alpha = 0.99
T = 10000.0
T_min = 3.95
current = problem
while T > T_min:
T = T * alpha
successor = n_queen.NQueenState.random | _successor(current)
E = current.heuristic_value - successor.heuristic_value
#print "E: ", E
if E > 0:
# (old-new) > 0 is ` | `good`` trade for n-queen
current = successor
elif math.exp(E/T) > random.random():
current = successor
if current.heuristic_value == 0:
return current
return current
|
vincentbetro/NACA-SIM | scripts/adaptationruns1.py | Python | gpl-2.0 | 9,065 | 0.046884 | #!/usr/bin/env python
#import sys and global var libraries, as well as option parser to make command line args
import os,sys
import glob
from optparse import OptionParser
#first, define system call with default retval for debugging
def mysystem(s,defaultretval=0):
#allows us to set effective debug flag
global... | tem("./EULER < MYSO | LVER%s > stdo.out"%options.parallel)
mysystem("rm -f *_%d_%+03d_%0.2f_%03d_%03d_%02d.dat"%(order,alpha,mach,ptiter,cfl,refinelevel))
write_euler_file("MYSOLVER%s"%options.parallel,options.case,alpha,mach,order,cfl,ptiter,refinelevel,"_out")
... |
iCarto/siga | extScripting/scripts/jython/Lib/xml/dom/html/HTMLDocument.py | Python | gpl-3.0 | 11,605 | 0.004222 | ########################################################################
#
# File Name: HTMLDocument.py
#
# Documentation: http://docs.4suite.com/4DOM/HTMLDocument.py.html
#
"""
WWW: http://4suite.com/4DOM e-mail: [email protected]
Copyright (c) 2000 Fourthought Inc, USA. All Rights Reserv... | )
if lowered in NoClassTags:
from HTMLElement import HTMLElement
return HTMLElement(self, tagName)
#FIXME: capitalize() broken with unicode in Python 2.0
#normTagName = string.capitalize(tagName)
capitalized = string.up | per(tagName[0]) + lowered[1:]
element = HTMLTagMap.get(capitalized, capitalized)
module = 'HTML%sElement' % element
if not self._html.has_key(module):
#Try to import it (should never fail)
__import__('xml.dom.html.%s' % module)
# Class and module have the same nam... |
chubbymaggie/simuvex | simuvex/procedures/cgc/receive.py | Python | bsd-2-clause | 3,563 | 0.003929 | import simuvex
from itertools import count
fastpath_data_counter = count()
class receive(simuvex.SimProcedure):
#pylint:disable=arguments-differ,attribute-defined-outside-init,redefined-outer-name
IS_SYSCALL = True
def run(self, fd, buf, count, rx_bytes):
if simuvex.options.CGC_ENFORCE_FD in se... | a.ast = action.actual_value.ast
self.data = self.state.memory.load(buf, read_length)
except StopIteration:
# the write didn't occur (i.e., size of 0)
self.data = None
else:
self.data = None
self.size = a... | ual_size, condition=rx_bytes != 0, endness='Iend_LE')
# return values
return self.state.se.If(
actual_size == 0,
self.state.se.BVV(0xffffffff, self.state.arch.bits),
self.state.se.BVV(0, self.state.arch.bits)
)
from ...s_options impor... |
pyQode/pyqode-uic | setup.py | Python | mit | 958 | 0.001044 | from setuptools import setup
setup(
name='pyqode-uic',
version='0.1.1',
py_modules=['pyqode_uic'],
url='https://github.com/pyQode/pyqode-pyuic',
license='MIT',
author='Colin Duquesnoy',
author_email='colin.duquesnoy',
description='pyQode Qt ui compiler',
entry_points={
'cons... | 'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: | 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
]
)
|
halfak/Difference-Engine | diffengine/synchronizers/xml_dump.py | Python | mit | 5,555 | 0.008461 | """
Assumptions:
* Revisions appear ordered by page ASC, timestamp ASC, rev_id ASC
* The max(rev_id) and max(timestamp) of revisions represents the last revision
chronologically captured by the dump
"""
import logging
import traceback
from mw.xml_dump import Iterator, map, open_file
from ..errors import Revision... | elif isinstance | (rev_proc_or_path, str):
path = rev_proc_or_path
logger.info("Completed processing dump {0}".format(path))
else:
raise RuntimeError(
"Did not expect a " + \
... |
FreshetDMS/FDCapacityPlanner | tests/test_generator.py | Python | gpl-3.0 | 941 | 0.03932 | import unittest
from vsvbp.container import Item, Bin, Instance
from vsvbp.generator import generator
class ItemBinTestCase(unittest.TestCase):
def setUp(self):
self.i1 = Item([1,2,9]); self.i2 = Item([4,5,3])
self.i3 = Item([0,1,0]); self.i4 = Item([9,8,7])
self.i1.size = 1; self.i2.size ... | self.ins = Instance(self.items, self.bins)
def testInstance(self):
assert str(self.ins)=="Items:\n"+str(self.items)+"\nBins:\n"+str(self.bins)
# def testGenerator(self):
# iss=generator(2,2,.5,seed=0)
# assert iss.items[1].requirements==[356, 197]
# | assert iss.bins[1].capacities == [516,411] |
Spiderlover/Toontown | otp/friends/PlayerFriendsManager.py | Python | mit | 9,425 | 0.001167 | from direct.distributed.DistributedObjectGlobal import DistributedObjectGlobal
from direct.directnotify.DirectNotifyGlobal import directNotify
from otp.otpbase import OTPGlobals
from otp.avatar.Avatar import teleportNotify
from otp.friends import FriendResponseCodes
class PlayerFriendsManager(DistributedObjectGlobal):... | n pInfo.avatarId
else:
return None
return None
def findPlayerInfoFromAvId(self, avId):
playerId = self.findPlayerIdFromAvId(avId)
if playerId:
return self.getFriendInfo(playerId)
else:
return None
return None
def askAvatarOnli... | if avId in self.cr.doId2do:
returnValue = 1
if avId in self.playerAvId2avInfo:
playerId = self.findPlayerIdFromAvId(avId)
if playerId in self.playerId2Info:
playerInfo = self.playerId2Info[playerId]
if playerInfo.onlineYesNo:
... |
khchine5/atelier | atelier/invlib/tasks.py | Python | bsd-2-clause | 23,664 | 0.001225 | # -*- coding: UTF-8 -*-
# Copyright 2013-2018 Rumma & Ko Ltd
# License: BSD, see LICENSE for more details.
"""
This is the module that defines the invoke namespace.
It is imported by :func:`atelier.invlib.setup_from_tasks` which passes
it to :func:`invoke.Collection.from_module`.
"""
from __future__ import print_func... |
directories under the project's root direcotory.
"""
for root, dirs, files in os.walk(ctx.root_dir):
for fn in files:
if fn.endswith(".pyc"):
full_path = os.path.join(root, fn)
if batch or confirm("Remove file %s:" % full_path):
os.rem... | kage.__file__).parent
# cleanup_pyc(atelier.current_project.root_dir, batch)
# except AttributeError:
# # happened 20170310 in namespace package:
# # $ pywhich commondata
# # Traceback (most recent call last):
# # File "<string>", line 1, in <module>... |
erochest/threepress-rdfa | bookworm/api/forms.py | Python | bsd-3-clause | 139 | 0.007194 | from dj | ango import forms
class APIUploadForm(forms.Form):
epub_data = forms.FileField()
api_key = forms.CharField(max_length=25 | 5)
|
plotly/python-api | packages/python/plotly/plotly/validators/volume/surface/_pattern.py | Python | mit | 582 | 0.001718 | import _plotly_utils.basevalidators
class PatternValidator(_plotly_utils.basevalidators.FlaglistValidator):
def __init__(self, plotly_name="pattern", parent_name="volume.surface", **kwargs):
super( | PatternValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
extras=kwargs.pop("extras", ["all", "odd", "even"]),
flags=kwargs.pop("flags", ["A", "B", "C", "D", "E | "]),
role=kwargs.pop("role", "style"),
**kwargs
)
|
sunfishcode/cretonne | lib/cretonne/meta/isa/arm32/defs.py | Python | apache-2.0 | 417 | 0 | """
ARM 32-bit definitions.
Commonly used definitions.
"""
from __future__ import absolute_import
from cdsl.isa import TargetISA, CP | UMode
import base.instructions
from base.legalize import narrow
ISA = TargetISA('arm32', [base.instructions.GROUP])
# CPU modes for 32-bit ARM and Thumb | 2.
A32 = CPUMode('A32', ISA)
T32 = CPUMode('T32', ISA)
# TODO: Refine these.
A32.legalize_type(narrow)
T32.legalize_type(narrow)
|
mlperf/training_results_v0.5 | v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/staging/models/rough/nmt/utils/iterator_utils.py | Python | apache-2.0 | 10,400 | 0.006923 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "Lic | ense");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WA... | issions and
# limitations under the License.
# ==============================================================================
"""For loading data into NMT models."""
from __future__ import print_function
import tensorflow as tf
from mlperf_compliance import mlperf_log
from utils import vocab_utils
__all__ = ["get_it... |
darvid/reqwire | src/reqwire/__init__.py | Python | mit | 264 | 0 | """reqwire: wire up Python requirements with p | ip-tools."""
from __future__ import absolute_import
import pkg_resources
try: # pragma: no cover
__version__ = pkg_resources.get_distribution(__name__).version
except: # noqa: B901
__version__ = 'unkno | wn'
|
priyesingh/rijenpy | libs/robotremoteserver.py | Python | gpl-3.0 | 21,857 | 0.000229 | # Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework 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
#
# ... | 'DEPRECATED', serve=True, allow_remote_stop=True):
"""Configure and start-up remote server.
:param library: Test library instance or module to host.
:param host: | Address to listen. Use ``'0.0.0.0'`` to listen
to all available interfaces.
:param port: Port to listen. Use ``0`` to select a free port
automatically. Can be given as an integer or as
a string.
:param port_file... |
himanshu-dixit/oppia | core/domain/question_services_test.py | Python | apache-2.0 | 4,658 | 0.000859 | # coding: utf-8
#
# Copyright 2017 The Oppia Authors. 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 requi... | ta_schema_version,
collection_id, language_code)
question.validate()
question_model = question_services.add_question(self.owner_id, quest | ion)
model = question_models.QuestionModel.get(question_model.id)
self.assertEqual(model.title, title)
self.assertEqual(model.question_data, question_data)
self.assertEqual(model.question_data_schema_version,
question_data_schema_version)
self.assertEqua... |
dmccue/ansible | lib/ansible/plugins/lookup/file.py | Python | gpl-3.0 | 2,091 | 0.002869 | # (c) 2012, Daniel Hokka Zakrisson <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any lat... | Ansible. If n | ot, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import codecs
from ansible.errors import *
from ansible.plugins.lookup import LookupBase
class LookupModule(LookupBase):
def run(self, terms, variables=None, **kwargs):
... |
patilsangram/erpnext | erpnext/shopping_cart/product_info.py | Python | gpl-3.0 | 2,040 | 0.022549 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from erpnext.shopping_cart.cart import _get_cart_quotation
from erpnext.shopping_cart.doctype.shopping_cart_settings.shopping_cart_settin... | ck_qty": show_quantity_in_website(),
"sales_uom": frappe.db.get_value("Item", item_code, "sales_uom")
}
if product_info["price"]:
if frappe.session.user != "Guest":
item = cart_quotation.get({"item_code": item_code})
| if item:
product_info["qty"] = item[0].qty
return {
"product_info": product_info,
"cart_settings": cart_settings
}
def set_product_info_for_website(item):
"""set product price uom for website"""
product_info = get_product_info_for_website(item.item_code)
if product_info:
item.update(product_info)
i... |
detuxsandbox/detux | core/sandbox.py | Python | mit | 8,692 | 0.009894 | # Copyright (c) 2015 Vikas Iyengar, [email protected] (http://garage4hackers.com)
# Copyright (c) 2016 Detux Sandbox, http://detux.org
# See the file 'COPYING' for copying permission.
import pexpect
import paramiko
import time
from ConfigParser import ConfigParser
from hashlib import sha256
from magic import Mag... | ,12)))))
sha256hash = sha256(open(binary_filepath, "rb").read()).hexdigest()
interpreter_path = { "python" : "/usr/bin/python", "perl" : "/usr/bin/perl", "sh" : "/bin/sh", "bash" : "/bin/bash" }
if qemu_command == None :
return {}
qemu_command += " -net nic,macaddr=%s -net t... | try:
qemu.expect("(qemu).*")
qemu.sendline("info network")
qemu.expect("(qemu).*")
ifname = qemu.before.split("ifname=", 1)[1].split(",", 1)[0]
qemu.sendline("loadvm init")
qemu.expect("(qemu).*")
pre_exec = {}
p... |
noironetworks/horizon | openstack_dashboard/dashboards/identity/users/forms.py | Python | apache-2.0 | 14,486 | 0 | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... | .tenant_list(
request, user=user_id)
for project in sorted(projects, key=lambda p: p.name.lower()):
if project.enabled:
project_choices.append((project.id, project.name))
if not project_choices:
project_choices.insert(0, ('... | eystoneclient is fixed to allow unsetting
# the default project, then this condition should be removed.
elif default_project_id is None:
project_choices.insert(0, ('', _("Select a project")))
self.fields['project'].choices = project_choices
except Exception:
... |
tschalch/pyTray | src/lib/reportlab/pdfgen/pycanvas.py | Python | bsd-3-clause | 12,353 | 0.006152 | # a Pythonesque Canvas v0.8
# Author : Jerome Alet - <[email protected]>
# License : ReportLab's license
#
# $Id: pycanvas.py,v 1.1 2006/05/26 19:19:48 thomas Exp $
#
__doc__ = """pycanvas.Canvas : a Canvas class which can also output Python source code.
pycanvas.Canvas class works exactly like canvas.Can... | hobject
from reportlab.pdfgen import textobject
from reportlab.lib.colors import Color
def doIt(file, regenerate=0) :
"""Generates a PDF document, save it into file.
file : either a filename or a file-like | object.
regenerate : if set then this function returns the Python source
code which when run will produce the same result.
if unset then this function returns None, and is
much faster.
"""
if regenerate :
from reportlab.pdfgen.p... |
fantasyy8/pythonintask | BITs/2014/KOSTAREV_A_I/task_10_13.py | Python | apache-2.0 | 3,987 | 0.016903 | #Задача №10, Вариант 13
#Напишите программу "Генератор персонажей" для игры.
#Пользователю должно быть предоставлено 30 пунктов,
#которые можно распределить между четырьмя
#характеристиками: Сила, Здоровье, Мудрость и Ловкость.
#Надо сделать так, чтобы пользователь мог не только брать
#эти пункты из общего "... | й характеристики, проверьте введенные данные: ")
char = str(input("\n:"))
ch | ar = char.title()
else:
print("\nВведите количество пунктов для характеристики. Доступно", person[char], "пунктов:")
points = int(input("\n:"))
while points > int(person[char]) or points < 0:
print("Невозможно удалить такое количество пунктов. Доступно",... |
sargas/scipy | scipy/sparse/setupscons.py | Python | bsd-3-clause | 656 | 0.010671 | #!/usr/bin/env python
from __future__ import division, print_function, absolute_import
from os.path import join
import sys
def configuration(parent_package='',top_path=None):
import numpy
from numpy.distutils.misc_util import Configuration
config = Configuration('spa | rse',parent_package,top_path,
setup_name = 'setupscons.py')
config.add_data_dir('tests')
config.add_subpackage('linalg')
config.add_subpackage('sparsetools')
config.add_subpackage('csgraph')
return config
if __name__ == '__main__':
from numpy.distutils.core import s... | p(**configuration(top_path='').todict())
|
ModestoCabrera/is210-week-05-warmup | tests/test_task_02.py | Python | mpl-2.0 | 689 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests Task 02."""
# Import Python libs
import unittest
import hamlet
import task_02
class Task02TestCase(unittest.TestCase):
"""
Test cases for Task 02.
"""
def test_positional_value(self):
"""
Tests that the POSITIONAL constant has ... | ((monkeys / hamlet.SHIFTS) + banana_effect))
chance /= hamlet.HAMLET_HOURS
self.assertEqual(task_02.POSITIONAL, chance)
if __name__ == '__ma | in__':
unittest.main()
|
GaryKriebel/osf.io | website/addons/dropbox/__init__.py | Python | apache-2.0 | 961 | 0.002081 | import os
from website.addons.dropbox import model, routes, views
MODELS = [model.DropboxUserSettings, model.DropboxNodeSettings, model.DropboxFile]
USER_SETTINGS_MODEL = model.DropboxUserSettings
NODE_SETTINGS_MODEL = model.DropboxNodeSettings
ROUTES = [routes.auth_routes, routes.api_routes]
SHORT_NAME = 'dropbox... | ],
'page': [],
'files': []
}
INCLUDE_CSS = {
'widget': [],
'page': [],
}
| HAS_HGRID_FILES = True
GET_HGRID_DATA = views.hgrid.dropbox_addon_folder
# MAX_FILE_SIZE = 5 # MB
HERE = os.path.dirname(os.path.abspath(__file__))
NODE_SETTINGS_TEMPLATE = None # use default node settings template
USER_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 'dropbox_user_settings.mako')
|
CivilHub/CivilHub | blog/forms.py | Python | gpl-3.0 | 1,065 | 0.003759 | # -*- coding: utf-8 -*-
from django import forms
from djan | go.utils.translation import ugettext_lazy as _
from taggit.forms import TagField
from | places_core.forms import BootstrapBaseForm
from .models import Category, News
class NewsForm(forms.ModelForm, BootstrapBaseForm):
""" Edit/update/create blog entry. """
title = forms.CharField(
label=_(u"Da tytuł"),
max_length=64,
widget=forms.TextInput(attrs={
'class': 'f... |
patdaburu/mothergeo-py | mothergeo/db/postgis/__init__.py | Python | gpl-2.0 | 175 | 0.011429 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
. | . currentmodule:: __ini | t__.py
.. moduleauthor:: Pat Daburu <[email protected]>
Provide a brief description of the module.
""" |
chaosking121/mal | plaintext.py | Python | mit | 1,309 | 0.004584 | def interpret(slackMessage):
import random
import tools.settings
if ("@mal" in slackMessage.message.lower()):
return ".1.2.1."
elif (slackMessage.message.lower() == '{}, what is the meaning of life?'.format(tools.settings.getName()).lower()):
from tools.file_handling import rando... | elif (slackMessage.message.lower() == '{}, how are you?'.format(tools.settings.getName()).lower()):
from tools.classes import Conversation
return Conversation(slackMessage.user, slackMessage.channel, "I'm fine. How about you?", [('tools. | arshad', 'greeting')])
elif ('*her*' in slackMessage.message):
return "*her*"
elif ('*she*' in slackMessage.message):
return"*she*"
elif ('superhot' in slackMessage.message.lower()):
return "SUPERHOT IS THE MOST INNOVATIVE SHOOTER I'VE PLAYED IN YEARS!"
elif ((('thank you'... |
PGower/Unsync | unsync_timetabler/unsync_timetabler/dof9/emergency_teacher_import.py | Python | apache-2.0 | 2,918 | 0.007882 | """Timetabler DOF9 import functions."""
import unsync
import petl
@unsync.command()
@unsync.option('--input-file', '-i', type=unsync.Path(exists=True, dir_okay=False, readable=True, resolve_path=True), help='Timetabler DOF9 file to extract data from.', required=True)
@unsync.option('--destination', '-d', required=Tru... | //www.timetabling.com.au/DOV9}Mobile',
'OtherPhone': '{http://w | ww.timetabling.com.au/DOV9}OtherPhone',
'Priority': '{http://www.timetabling.com.au/DOV9}Priority',
'Notes': '{http://www.timetabling.com.au/DOV9}Notes',
'SpareField1': '... |
leighpauls/k2cro4 | third_party/python_26/Lib/json/tests/test_indent.py | Python | bsd-3-clause | 906 | 0.004415 | from unittest import TestCase
import json
import textwrap
class TestIndent(TestCase):
def test_indent(self):
h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth',
| {'nifty': 87}, {'field': 'yes', 'morefield': False} ]
expect = textwrap.dedent("""\
[
[
"blorpie"
],
[
"whoops"
],
[],
"d-shta | eou",
"d-nthiouh",
"i-vhbjkhnth",
{
"nifty": 87
},
{
"field": "yes",
"morefield": false
}
]""")
d1 = json.dumps(h)
d2 = json.dumps(h, indent=2, sort_keys=True, separators=(',', ': '))
h1 = ... |
CSC522-Data-mining-NCSU/reputation-hpc | calc_repu/getMovieGrade.py | Python | mit | 1,211 | 0.050372 | import csv
import pickle
from WeightFinder import Weigh | tFinder
import time
from mpi4py import MPI
import pickle
from demo | s import cmd
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
finder = WeightFinder()
def get_movie_grade(movie_id):
try:
f = open('../training_set/mv_'+str(movie_id).zfill(7)+'.txt','r')
except: return 0
reader = csv.reader(f)
reader.next()
score = 0
sum_w = 0
for row in reader:
a = int(row[0])
rate = float... |
arturh85/projecteuler | python/src/problem002.py | Python | mit | 1,592 | 0.011935 | '''
Problem 2
19 October 2001
Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not
e | xceed four million, find the sum of the even-valued terms.
----------------------------------------------------------
Created on 25.01.2012
@author: ahallmann
'''
import unittest
import timeit
def generate_fibonacci_sequence(limit=0):
| a = 1
yield a
b = 1
yield b
i = 0
while(limit == 0 or a + b < limit):
i = a + b
a = b
b = i
yield i
'''
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the ... |
bernardopires/django-tenant-schemas | examples/tenant_tutorial/customers/views.py | Python | mit | 1,718 | 0 | from django.contrib.auth.models import User
from django.db.utils import DatabaseError
from django.views.generic import FormView
from customers.forms import GenerateUsersForm
from customers.models import Client
from random import choice
class TenantView(FormView):
form_class = GenerateUsersForm
template_name =... | email="%s | @%s.com" % (first_name, last_name),
first_name=first_name,
last_name=last_name)
user.save()
except DatabaseError:
pass
return super(TenantView, self).form_valid(form)
|
nthall/pip | tests/unit/test_index.py | Python | mit | 4,551 | 0 | import os.path
import pytest
from pip.download import PipSession
from pip.index import HTMLPage
from pip.index import PackageFinder, Link
def test_sort_locations_file_expand_dir(data):
"""
Test that a file:// dir gets listdir run with expand_dir
"""
finder = PackageFinder([data.find_links], [], sessi... | ions_non_existing_path():
"""
Test that a non-existing path is ignored.
"""
finder = PackageFinder([], [], session=PipSession())
files, urls = finder._sort_locations(
[os.path.join('this', 'doesnt', 'exist')])
assert not urls and not files, "nothing should have been found"
class TestLi... | ("url", "expected"),
[
("http://yo/wheel.whl", "wheel.whl"),
("http://yo/wheel", "wheel"),
(
"http://yo/myproject-1.0%2Bfoobar.0-py2.py3-none-any.whl",
"myproject-1.0+foobar.0-py2.py3-none-any.whl",
),
],
)
def... |
googleapis/python-datacatalog | samples/generated_samples/datacatalog_generated_datacatalog_v1beta1_data_catalog_create_tag_template_sync.py | Python | apache-2.0 | 1,586 | 0.001892 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License | .
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the ... | e governing permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for CreateTagTemplate
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dep... |
blablacar/exabgp | lib/exabgp/bgp/message/update/nlri/ipvpn.py | Python | bsd-3-clause | 3,348 | 0.028674 | # encoding: utf-8
"""
bgp.py
Created by Thomas Mangin on 2012-07-08.
Copyright (c) 2009-2015 Exa Networks. All rights reserved.
"""
from exabgp.protocol.family import AFI
from exabgp.protocol.family import SAFI
from exabgp.bgp.message import OUT
from exabgp.bgp.message.update.nlri.nlri import NLRI
from exabgp.bgp.m... | T.UNSET):
Labelled.__init__(self, afi, safi, action)
self.rd = RouteDistinguisher.NORD
@classmethod
def new (cls, afi, safi, packed, mask, labels, rd, nexthop=None, action=OUT.UNSET):
instance = cls(afi,safi,action)
instance.cidr = CIDR(packed, mask)
instance.labels = labels
instance.rd = rd
instance.n... | f):
return "%s%s%s%s%s" % (self.prefix(),str(self.labels),str(self.rd),str(self.path_info),str(self.rd))
def __len__ (self):
return Labelled.__len__(self) + len(self.rd)
def __repr__ (self):
nexthop = ' next-hop %s' % self.nexthop if self.nexthop else ''
return "%s%s" % (self.extensive(),nexthop)
def __eq... |
fad4470/pastagram | meatballify.py | Python | gpl-3.0 | 2,227 | 0.035474 | import numpy as np
import cv2
from PIL import Image, ImageDraw
import sys
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread(sys.argv[1])
h, w = img.shape[:2]
png = Image.new('RGBA',(w,h))
png.save('meatball-' + sys.... | ballCV[:,:,0:3]
#origMeatballHeight, origMeatballWidth = meatballCV.shape[:2]
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for(x, y, w, h) in faces:
cv2.rectangle(img, (x,y), (x+w, y+h), (255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+ | h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for(ex, ey, ew, eh) in eyes:
cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0,255,0), 2)
for(ex, ey, ew, eh) in eyes:
meatballWidth = ew
meatballHeight = eh
x1 = ex
x2 = ex + ew
y1 = ey
y2 = ey + eh
if x1 < 0:
x1 = 0
... |
stephane-martin/salt-debian-packaging | salt-2016.3.3/tests/unit/modules/linux_lvm_test.py | Python | apache-2.0 | 11,687 | 0.000941 | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Rupesh Tare <[email protected]>`
'''
# Import Python libs
from __future__ import absolute_import
import os.path
# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.mock import (
MagicMock,
patch,
NO_MOCK,
NO_MOCK... | k = MagicMock(return_value={'retcode': 1})
with patch.dict(linux_lvm.__salt__, {'cmd.run_all': mock}):
self.assertDictEqual(linux_lvm.pvdisplay(), {})
mock = MagicMock(return_value={'retcode': 0,
'stdout': 'A:B:C:D:E:F:G:H:I:J:K'})
with patch.d... | self.assertDictEqual(linux_lvm.pvdisplay(),
{'A': {'Allocated Physical Extents': 'K',
'Current Logical Volumes Here': 'G',
'Free Physical Extents': 'J',
'Internal... |
ivorbosloper/pestileaks | fabfile.py | Python | gpl-2.0 | 973 | 0.006166 | from __future__ import with_statement
from fabric.api import local, abort, run, cd, env
from fabric.context_managers import prefix
env.directory = '/home/pestileaks/pestileaks'
env.activate = 'source /home/pestileaks/env/bin/activat | e'
env.user = 'pestileaks'
env.hosts = ['pestileaks.nl']
env.restart = 'killall -HUP gunicorn'
#Show current status versus current github master state
def status():
with cd(env.directory):
run('git status')
def dep | loy():
with cd(env.directory):
run("git pull")
#run("rm -rf /home/pestileaks/run/static")
run("mkdir -p /home/pestileaks/run/static")
with prefix(env.activate):
run("if [ doc/requirements.txt -nt doc/requirements.pyc ]; then pip install -r doc/requirements.txt; touch doc... |
AlanBell/ExceptionalEmails | mongoreceiver.py | Python | agpl-3.0 | 7,066 | 0.020662 | #!/usr/bin/python
import smtpd
import asyncore
import email
import re
from pymongo import MongoClient
from bson.dbref import DBRef
from datetime import datetime
from pytz import timezone
import pytz
from sendfail import sendfail
#this is the daemon part of exceptional emails
#it recieves emails and if they are to a va... | user preference
eventobj=exceptionalemails.events.find_one({"user":userref,"alert":alertref,"date":userdate})
#this really should find the event for the day
if eventobj:
#we can tie this email to an expectation, lets check it for good words and badwords
#we do bo... | goodre=re.compile(alertobj['goodregex'])
print alertobj['goodregex'],post['subject']
if goodre.search(post['subject'] or goodre.search(post['data'])):
eventobj['goodregex']=True
#print "good match"
else:
eventobj['goodregex']=... |
skitazaki/django-access-dashboard | src/accesslog/serializers.py | Python | apache-2.0 | 1,315 | 0 | # -*- coding: utf-8 -*-
from rest_framework import serializers
from accesslog.models import AccessLog, DaySummary, MonthSummary
class SourceSerializer(serializers.Serializer):
source = serializers.CharField(max_length=200)
total = serializers.IntegerField()
time_min = serializers.DateTimeField()
tim... | HyperlinkedModelSerializer):
class Meta:
model = AccessLog
fields = ('id', 'time', 'host', 'path', 'query', 'method', 'protocol',
'status', 'size', 'referer', 'ua', 'trailing', 'source')
class DaySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ... | vg', 'referer_kind',
'ua_kind', 'total', 'source')
class MonthSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = MonthSummary
fields = ('id', 'year', 'month', 'host_kind', 'path_kind', 'protocol',
'method', 'status', 'size_min', 'size_max', ... |
Akagi201/learning-python | pyramid/misc/MyProject/myproject/views.py | Python | mit | 1,090 | 0.001835 | from pyramid.response import Response
from pyramid.view import view_config
from sqlalchemy.exc import DBAPIError
from .models import (
DBSession,
MyModel,
)
@view_config(route_name='home', renderer='templates/mytemplate.pt')
def my_view(request):
try:
one = DBSession.query(MyModel).filter(My... | lain', status_int=500)
return {'one': one, 'project': 'MyProject'}
conn_err_msg = """\
Pyramid is having a problem using your SQL database. The problem
might be caused by one of the following things:
1. You may need to run the "initialize_MyProject_db" script
to initialize your database tables. Check your... | ript and try to run it.
2. Your database server may not be running. Check that the
database server referred to by the "sqlalchemy.url" setting in
your "development.ini" file is running.
After you fix the problem, please restart the Pyramid application to
try it again.
"""
|
nkoech/csacompendium | csacompendium/countries/models.py | Python | mit | 1,969 | 0.001016 | from __future__ import unicode_literals
from csacompendium.utils.abstractmodels import (
AuthUserDetail,
CreateUpdateTime,
)
from csacompendium.locations.models import | Location
from cs | acompendium.utils.createslug import create_slug
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.core.urlresolvers import reverse
class Country(AuthUserDetail, CreateUpdateTime):
"... |
omelkonian/cds | cds/modules/records/api.py | Python | gpl-2.0 | 2,845 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2017 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 version.
#
# Invenio is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS F... | ot, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Record API.... |
sejust/pykit | humannum/__init__.py | Python | mit | 341 | 0 | from .humannum import (
K,
M,
G,
T,
P,
E,
Z,
Y,
humannum,
parsenum,
parseint,
value_to_unit,
unit_to_value,
| )
__all__ = [
'K',
'M',
'G',
'T',
'P',
'E',
'Z',
'Y',
'humannum',
'parsenum',
' | parseint',
'value_to_unit',
'unit_to_value',
]
|
getnamo/UnrealEnginePython | tutorials/FaceRecognitionWithOpenCVAndUnrealEnginePython_Assets/eyes_fourth.py | Python | mit | 1,501 | 0.004664 | import unreal_engine as ue
from unreal_engine.classes import SceneCaptureComponent2D, PyHUD
from unreal_engine.enums import ESceneCaptureSource
class Sight:
def __init__(self):
self.what_i_am_seeing = ue.create_transient_texture_render_target2d(512, 512)
def pre_initialize_components(self):
... | mannequin Mesh component
self.uobject.attach_to_component(mannequin.Mesh, 'head')
# spawn a new HUD (well, a PyHUD)
hud = self.uobject.actor_spawn(PyHUD, PythonModule='hud_first', P | ythonClass='FacesDetector')
# get a reference to its proxy class
self.py_hud = hud.get_py_proxy()
# set the texture to draw
self.py_hud.texture_to_draw = self.what_i_am_seeing
# use this new HUD as the player default one (so the engine will start drawing it)
self.uobjec... |
alex8866/cinder | cinder/tests/api/v1/test_snapshot_metadata.py | Python | apache-2.0 | 21,261 | 0.000141 | # Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | ive()
def return_new_snapshot_metadata(context, snapshot_id, metadata, delete):
| return stub_new_snapshot_metadata()
def return_snapshot_metadata(context, snapshot_id):
if not isinstance(snapshot_id, str) or not len(snapshot_id) == 36:
msg = 'id %s must be a uuid in return snapshot metadata' % snapshot_id
raise Exception(msg)
return stub_snapshot_metadata()
def return_e... |
DonaldWhyte/machine-learning-experiments | scripts/combine_dataset.py | Python | bsd-2-clause | 4,113 | 0.004863 | #-------------------------------------------------------------------------------
# Name: combine_dataset.py
# Author: Donald Whyte
# Date last modified: 29/06/12
# Description:
# Reads the directory containing a shellcode training/test dataset and combines
# ALL of the data items (individual files) into a single file. ... | taset_directory>".format(sys.argv[0]))
args = { 'archive_filename' : sys.argv[1], 'dataset_directory' : sys.argv[2] }
return args
if __name__ == "__main__":
args = parse_commandline_arguments()
if not combine_dataitems(args['archive_filename'], args['dataset_directory']):
print("Attempt to co... | irectory'])) |
googleapis/python-redis | samples/generated_samples/redis_v1beta1_generated_cloud_redis_reschedule_maintenance_async.py | Python | apache-2.0 | 1,639 | 0.00061 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apach | e License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License i | s distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for RescheduleMaintenance
# NOTE: This snippet has been automa... |
pmelchior/hydra | push_jobs.py | Python | mit | 1,520 | 0.003289 | #!/bin/env python
from os import system
from sys import argv
import json
from time import sleep
if len(argv) < 2:
print "usage: " + argv[0] + " <job file>"
exit(1)
def push_to_hosts(config):
counter = 0
counting = False
sleep_time = 1
try:
counting = config['counting']
counter... | if config['listen']:
command += '\''
else:
command += ' < /dev/null >& /dev/null &\''
if counting:
if counter > max_count:
break
print "starting job %d on %s" % (counter, host['name'])
el... | counter += 1
if counting:
print "submitted jobs %d/%d" % (counter-1, max_count)
else:
print "submitted %d jobs" % (counter-1)
# read the job file
fp = open(argv[1])
config = json.load(fp)
push_to_hosts(config)
fp.close()
|
ostree/plaso | plaso/lib/eventdata.py | Python | apache-2.0 | 1,819 | 0.020891 | # -*- coding: utf-8 -*-
"""A place to store information about events, such as format strings, etc."""
# TODO: move this class to events/definitions.py or equiv.
class EventTimestamp(object):
"""Class to manage event data."""
# The timestamp_desc values.
ACCESS_TIME = u'Last Access Time'
CHANGE_TIME = u'Metada... | sume Time'
# The timestamp does not represent a date and time value.
NOT_A_TIME = u'Not a time'
# Note that the unknown time is used for date and time values
| # of which the exact meaning is unknown and being researched.
# For most cases do not use this timestamp description.
UNKNOWN = u'Unknown Time'
|
DTOcean/dtocean-core | tests/test_data_definitions_xgrid2d.py | Python | gpl-3.0 | 4,013 | 0.009469 | import pytest
import numpy as np
import matplotlib.pyplot as plt
from aneris.control.factory import InterfaceFactory
from dtocean_core.core import (AutoFileInput,
AutoFileOutput,
AutoPlot,
Core)
from dtocean_core.data import ... | "values": np.random.randn(2, 3),
"coords": [['a', 'b'], [-2, 0, 2]]}
meta = CoreMetaData({"identifier": "test",
"structure": "test",
"title": "test",
"labels": ['x', 'y'],
| "units": [None, 'm', 'POWER!']})
test = XGrid2D()
a = test.get_data(raw, meta)
b = test.get_value(a)
assert b.values.shape == (2,3)
assert b.units == 'POWER!'
assert b.y.units == 'm'
def test_get_None():
test = XGrid2D()
result = test.get_value(None)
... |
jacenkow/inspire-next | tests/integration/test_orcid.py | Python | gpl-2.0 | 5,384 | 0.000743 | # -*- coding: utf-8 -*-
#
# This file is part of INSPIRE.
# Copyright (C) 2016 CERN.
#
# INSPIRE is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later... | t(mock_user, request):
"""Orcid test fixture."""
app = mock_user.app
def teardown(app):
with app.app_context():
es.delete(index='records-authors', doc_type='authors', id=10)
record = {
"name": {
"status": "ACTIVE",
"preferred_name": "Full Name",
... | schemas/records/authors.json",
"control_number": "10",
"self": {"$ref": "http://localhost:5000/api/authors/10"},
"ids": [{
"type": "INSPIRE",
"value": "INSPIRE-0000000"
},
{
"type": "ORCID",
"value": "0000-0001-9412-8627"
... |
PhoenixRacing/PhoenixRacingWebApp-noregrets | application/controllers/index.py | Python | bsd-3-clause | 156 | 0.019231 | from flask import request, | render_template
from flask.ext.login import current_user
d | ef index():
return render_template('index.html', active_page='index') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.