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
KlausPopp/Moddy
src/moddy/version.py
Python
lgpl-3.0
51
0
version = (2, 0, 0) VERSION = "%d.%
d.%d" %
version
faskiri/barry2gugl
dn.py
Python
apache-2.0
3,915
0.02069
# # Copyright 2015 Fasih # # 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...
ng permissions and # limitations under the License. # class DN(object): def __init__(self, dn): self._dn
= dn.replace(',dn', '') self._cn = [] self._displayName = [] self._givenName = [] self._homePhone = [] self._homePostalAddress = [] self._mail = [] self._mobile = [] self._o = [] self._objectClass = [] self._sn = [] self._telephoneNumber = [] self._title = [] @propert...
abhijitbangera/ecommerce
src/carts/migrations/0007_merge.py
Python
mit
293
0
# -*- coding: utf-8 -*- from __future__ import u
nicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('carts', '0006_auto_20150930_1739'), ('carts', '0005_auto_20151022_2158'), ] opera
tions = [ ]
rtfd/sphinx-autoapi
autoapi/toctree.py
Python
mit
5,871
0.001533
""" A small Sphinx extension that adds Domain objects (eg. Python Classes & Methods) to the TOC Tree. It dynamically adds them to the already rendered ``app.env.tocs`` dict on the Sphinx environment. Traditionally this only contains Section's, we then nest our Domain references inside the already existing Sections. ""...
y default, and other Desc nodes that we've previously placed. parent_node = _traverse_parent( node=desc_node, objtypes=(addnodes.desc, nodes.section) ) if parent
_node: toc_reference = _get_toc_reference(parent_node, toc, docname) if toc_reference: # Get the last child of our parent's bullet list, this is where "we" live. toc_insertion_point = _traverse_parent( toc_reference, nodes.bullet_list ...
TieWei/nova
nova/virt/libvirt/imagebackend.py
Python
apache-2.0
23,315
0.000815
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Grid Dynamics # 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/l...
base_dir = os.path.join(CONF.instances_path, CONF.base_dir_name) if not os.path.exists(base_dir): fileutils.ensure_tree(base_dir) base = os.path.join(base_dir, filename) if not self.check_image_exists() or not os.path.exists(base): self.create
_image(call_if_not_exists, base, size, *args, **kwargs) if (size and self.preallocate and self._can_fallocate() and os.access(self.path, os.W_OK)): utils.execute('fallocate', '-n', '-l', size, self.path) def _can_fallocate(self): """Check o...
anhstudios/swganh
data/scripts/templates/object/mobile/shared_huff_darklighter.py
Python
mit
452
0.04646
#### NOTICE: THIS FIL
E IS AUTOGENERATED #### M
ODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_huff_darklighter.iff" result.attribute_template_id = 9 result.stfName("theme_park_name","base_npc_theme_par...
tosmun/AdventOfCode
solutions/day1/p1/main.py
Python
apache-2.0
233
0.042918
floor = 0 with open('../input.txt', 'r') as fp: while True: bu
ffer = fp.read(1024) if buffer is None or len(buffer) <= 0: break for c in buffer: if c == '(': floor += 1 elif c == ')': floor -= 1 print f
loor
dbaxa/GitPython
git/repo/base.py
Python
bsd-3-clause
30,180
0.00666
# repo.py # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors # # This module is part of GitPython and is released under # the BSD License: http://www.opensource.org/licenses/bsd-license.php from git.exc import InvalidGitRepositoryError, NoSuchPathError from git.cmd import Git from git.util im...
, self.git_dir) # Description property def _get_description(self): filename = join(self.git_dir, 'description') return file(filename).read().rstrip() def _set_description(self, descr): filename = join(self.git_dir, 'description') file(filename, 'w').write(descr+'\n') d...
tion del _set_description @property def working_tree_dir(self): """:return: The working tree directory of our git repository :raise AssertionError: If we are a bare repository""" if self._working_tree_dir is None: raise AssertionError( "Repository at %r is ...
AutorestCI/azure-sdk-for-python
azure-servicefabric/azure/servicefabric/models/applications_health_evaluation.py
Python
mit
2,699
0.002223
# 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 ...
aluation): """Represents health evaluation for applications, containing health evaluations for each unhealthy application that impacted current aggregated health state. :param aggregated_health_state: Possible values include: 'Invalid', 'Ok', 'Warning', 'E
rror', 'Unknown' :type aggregated_health_state: str or :class:`enum <azure.servicefabric.models.enum>` :param description: Description of the health evaluation, which represents a summary of the evaluation process. :type description: str :param kind: Polymorphic Discriminator :type kind: s...
pawhewitt/Dev
SU2_PY/SU2/run/adaptation.py
Python
lgpl-2.1
2,501
0.015194
#!/usr/bin/env python ## \file adjoint.py # \brief python package for running adjoint problems # \author T. Lukaczyk, F. Palacios # \version 5.0.0 "Raven" # # SU2 Original Developers: Dr. Francisco D. Palacios. # Dr. Thomas D. Economon. # # SU2 Developers: Prof. Juan J. Alonso's group at St...
group at Kaisers
lautern University of Technology. # Prof. Alberto Guardone's group at Polytechnic University of Milan. # Prof. Rafael Palacios' group at Imperial College London. # Prof. Edwin van der Weide's group at the University of Twente. # Prof. Vincent Terrapon's gr...
Phelimb/atlas
scripts/newick2json.py
Python
mit
1,160
0
#! /usr/bin/env python import sys from ete2 import Tree import random def get_json(node): # Read ETE tag for duplication or speciation events if not hasattr(node, 'evoltype'): dup = random.sample(['N', 'Y'], 1)[0] elif node.evoltype == "S": dup = "N" elif node.evoltype == "D": ...
json if __name__ == '__main__': if len(sys.argv) > 1: t = Tree(sys.argv[1]) else: # create a random example tree t = Tree()
t.populate(100, random_branches=True) # TreeWidget seems to fail with simple quotes print str(get_json(t)).replace("'", '"')
Hasimir/brython
www/src/Lib/encodings/iso8859_13.py
Python
bsd-3-clause
13,578
0.020916
""" Python Character Mapping Codec iso8859_13 generated
from 'MAPPINGS/ISO8859/8859-13.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,errors='strict'): return codecs.charmap...
ecs.charmap_encode(input,self.errors,encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,co...
yasir1brahim/OLiMS
lims/idserver.py
Python
agpl-3.0
8,055
0.003228
from dependencies.dependency import ModuleSecurityInfo#, #allow_module from dependencies.dependency import DateTime from dependencies.dependency import DisplayList from dependencies.dependency import getToolByName from dependencies.dependency import TranslationServiceTool from lims.browser import BrowserView from lims ...
id_normalize = getUtility(IIDNormalizer).normalize prefixes = context.bika_setup.getPrefixes() year = context.bika_setup.getYearInPrefix() and \ DateTime().strftime("%Y")[2:] or '' separator = '-' for e in prefixes: if 'separator' not in e: e['separator'] = '' if...
e == "AnalysisRequest": sample = context.getSample() s_prefix = fn_normalize(sample.getSampleType().getPrefix()) sample_padding = context.bika_setup.getSampleIDPadding() ar_padding = context.bika_setup.getARIDPadding() sample_id = sample.getId() sample_number = sample_id....
1001genomes/AraGWAS
aragwas_server/gwasdb/migrations/0007_study_n_hits_thr.py
Python
mit
462
0
# -*- cod
ing: utf-8 -*- # Generated by Django 1.11b1 on 2017-06-23 09:35 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('gwasdb', '0006_auto_20170623_0933'), ] operations = [ migrations.AddField( ...
r', field=models.IntegerField(blank=True, null=True), ), ]
trilan/lemon-filebrowser
setup.py
Python
bsd-3-clause
998
0
import codecs import os from setuptools import setup, find_packages def read(filename): filepath = os.path.join(os.path.dirname(__file__), filename) return codecs.open(filepath, encoding='utf-8').read() setup( name='lemon-filebrowser', version='0.1.2', license='ISC', description="Fork of Pat...
endent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Pytho
n :: 2.7', 'Topic :: Internet :: WWW/HTTP', ], )
pyrrho314/recipesystem
trunk/astrodata/samples/astrodata_Sample/RECIPES_Sample/primitives/primitives_OBSERVED.py
Python
mpl-2.0
968
0.007231
from astrodata.ReductionObjects import PrimitiveSet class OBSERVEDPrimitives(PrimitiveSet): astrotype = "OBSERVED" def init(self, rc): print "OBSERVEDPrimitives.init(rc)" return def typeSpecificPrimitive(self, rc): print "OBSERVEDPrimitives::typeSpecificPrimitive()" ...
ED"): print "OBSERVEDPrimitives::mark(%s) already marked" % ad.filename else: ad.phu_set_key_value("S_MARKED", "TRUE") rc.report_output(ad) yield rc def unmark(self, rc): for ad in rc.get_inputs_as_astrodata():
if ad.is_type("UNMARKED"): print "OBSERVEDPrimitives::unmark(%s) not marked" % ad.filename else: ad.phu_set_key_value("S_MARKED", None) rc.report_output(ad) yield rc
dimven/SpringNodes
py/Element.IsCut.py
Python
mit
932
0.032189
import clr clr.AddReference("RevitServices") import RevitServices from RevitServices.Persistence import DocumentManager doc = DocumentManager.Instance.CurrentDBDocument clr.AddReference("RevitAPI") from Autodesk.Revit.DB import * clr.AddReference("RevitNodes") imp
ort Revit clr.ImportExtensions(Revit.Elements) def tolist(obj1): if hasattr(obj1,"__iter__"): return obj1 else: return [obj1] elements = UnwrapElement(tolist(IN[0])) out1 = [] cutters = [] cutU = InstanceVoidCutUtils for i in xrange(len(elements)): try: if cutU.CanBeCutWithVoid(elements[i]): cut1 = cutU.GetC...
: out1.append(False) cutters.append([]) else: out1.append(True) cut1 = [doc.GetElement(id).ToDSType(True) for id in cut1] cutters.append(cut1) else: out1.append(False) cutters.append([]) except: out1.append(False) cutters.append([]) OUT = out1, cutters
openstack/renderspec
renderspec/distloader.py
Python
apache-2.0
2,522
0
#!/usr/bin/python # Copyright (c) 2016 Red Hat # # 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 agree...
dist_templates_pat
h() def get_source(self, environment, template): if template == self.base_ref: fn = self.base_fn else: fn = os.path.join(self.disttemp_path, template + self.template_postfix) f = open_if_exists(fn) if not f: return T...
croxis/SpaceDrive
spacedrive/renderpipeline/rplibs/yaml/yaml_py2/parser.py
Python
mit
26,131
0.002334
# The following YAML grammar is LL(1) and is parsed by a recursive descent # parser. # # stream ::= STREAM-START implicit_document? explicit_document* STREAM-END # implicit_document ::= block_node DOCUMENT-END* # explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* # block_node_o...
= None self.yaml_version = None self.tag_handles = {} self.states = [] self.marks = [] self.state = self.parse_stream_start def dispose(
self): # Reset the state attributes (to clear self-references) self.states = [] self.state = None def check_event(self, *choices): # Check the type of the next event. if self.current_event is None: if self.state: self.current_event = self...
google/har-sanitizer
harsanitizer/harsan_api.py
Python
apache-2.0
7,146
0.012175
"""Scans and sanitzes HAR files containing sensitive information.""" # Copyright 2017, Google Inc. # Authors: Garrett Anderson # # 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://w...
) return Response(data, 200, mimetype="application/json") @app.route("/scrub_har", methods=["POST"]) @decorators.accept("application/json") @decorators.require("application/json") def scrub(): """Scrubs data["har"] with optional wordlists,
content types, and scrub_all type bools. """ hs = HarSanitizer() hs_kwargs = {} data = request.json har = Har(har=data["har"]) if "wordlist" in data.keys(): hs_kwargs["wordlist"] = data["wordlist"] if "content_list" in data.keys(): hs_kwargs["content_list"] = data["content_list"] if "all_cook...
kelly-shen/canigraduate.uchicago.edu
backend/uchicago/src/timeschedules_parser_test.py
Python
mit
1,945
0
import unittest import re import requests from .timeschedules_parser import FSM class TestTimeschedulesParser(unittest.TestCase): def _construct_fsm(self, string): fsm = FSM([]) def stub(*args, **kwargs): return string fsm.next_string = stub return fsm def test_...
[[9420, 9600]], self._construct_fsm("Sat1:00PM-4:00PM").next_schedule()) self.assertEqual( [[2190, 2240], [5070, 5120], [6510, 6560], [7950, 8000]], self._construct_fsm("MWHF12:30PM-1:20PM").next_schedule()) self.assertEqual( [[2190, 2240], [50...
ext_schedule()) self.assertEqual( [[2190, 2240], [5070, 5120], [6510, 6560], [7950, 8000]], self._construct_fsm("MWTHF12:30PM-1:20PM").next_schedule()) self.assertEqual( [[6660, 6830]], self._construct_fsm("Thu3:00PM-5:50PM").next_schedule()) if __name__...
pombredanne/invenio
modules/webaccess/lib/access_control_firerole.py
Python
gpl-2.0
15,550
0.007203
## This file is part of Invenio. ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 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, ...
## Something bad might have happened? (Update of Python?) repair_role_definitions() res = run_sql("SELECT firerole_def_ser FROM accROLE WHERE id=%s", (role_id, ), 1) if res: return deserialize(res[0][0]) return CFG_ACC_EMPTY_ROLE_DEFINITION_OBJ def acc_firero...
extract all the possible email addresses authorized by the given firerole. """ authorized_emails = set() try: default_allow_p, rules = firerole_def_obj for (allow_p, not_p, field, expressions_list) in rules: # for every rule if not_p: continue if ...
seattleacademy/fall27
arrowup.py
Python
mit
336
0.029762
from sense_hat import SenseHat sense = SenseHat() X = [255, 0, 0] # Red O = [255, 255, 255] # White up_arrow = [ O, O, O, X, X, O, O, O, O, O, X, X, X, X, O, O, O, X,
X, X, X, X, X, O, O, O, O, X, X, O, O, O, O, O, O, X, X, O, O, O, O, O,
O, X, X, O, O, O, O, O, O, X, X, O, O, O, O, O, O, X, X, O, O, O ] sense.set_pixels(up_arrow)
kuasha/cosmos
cosmos/schema/object.py
Python
mit
154
0.006494
""" Copyright (C) 201
4 Maruf Maniruzzaman Website: http://cosmosframework.com Author: Maruf Maniruzz
aman License :: OSI Approved :: MIT License """
mmenz/michaelmenz
spare-parts/animatedgifs.py
Python
apache-2.0
420
0.033333
import gizeh su
rface = gizeh.Surface(width=320
, height=260) circle = gizeh.circle (r=40, # radius, in pixels xy= [156, 200], # coordinates of the center fill= (1,0,0)) # 'red' in RGB coordinates circle.draw( surface ) # draw the circle on the surface surface.get_npimage() # export as a numpy array (we will use that) su...
awolfly9/hammer
test/test.py
Python
mit
2,505
0.004391
# -*- coding=utf-8 -*- import sys import time import logging import os sys.path.append(os.getcwd()) logging.basicConfig() from hammer.sqlhelper import SqlHelper db_config = { 'host': 'localhost', 'port': 3306, 'user': 'root', 'password': '123456', 'db': 'test', } def test_create_table(): c...
print(sql.check_table_exists('test', db_name = 'tesdt')) if __name__ == '__main__': sql = SqlHelper(**db_config)
# test_insert() # test_update() # test_is_exists() # test_check_table_exists() datas = [] for i in range(1, 3): data = { 'id': i, 'name': "vvv", 'age': None, 'date': None, } datas.append(data) print(datas) print(len(da...
twilio/twilio-python
twilio/rest/insights/v1/setting.py
Python
mit
7,805
0.000769
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource f...
self, subaccount_sid=values.unset): """ Fetch the SettingInstance :param unicode subaccount_sid: The subaccount_sid :returns: The fetched SettingInstance :rtype: twilio.rest.insights.v1.setting.SettingInstance """ data = values.of({'Subac
countSid': subaccount_sid, }) payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) return SettingInstance(self._version, payload, ) def update(self, advanced_features=values.unset, voice_trace=values.unset, subaccount_sid=values.unset): """ Upda...
USGSDenverPychron/pychron
docs/user_guide/operation/scripts/examples/basic.py
Python
apache-2.0
2,487
0.002413
#!Measurement # all of this is configuration info that can be used in the script. # you refer to these values using mx.<group>.<attribute> # e.g # mx.baseline.counts is 180 # mx.multicollect.detector is H1 ''' baseline: after: true before: false counts: 180 detector: H1 mass: 34.2 settling_time: 15 d...
true multicollect: counts: 400 detector: H1 isotope: Ar40 peakcenter: after: true before: false detector: H1 detectors: - H1 - AX - CDD isotop
e: Ar40 peakhop: hops_name: '' use_peak_hop: false ''' # entry point for the script def main(): # print a message to the user info('unknown measurement script') # activate the following detectors. measurements will be plotted and save for these detectors activate_detectors('H2', 'H1', 'AX', 'L1'...
tboyce021/home-assistant
homeassistant/components/volvooncall/binary_sensor.py
Python
apache-2.0
856
0.002336
"""Support for VOC.""" from homeassistant.components.binary_sensor import DEVICE_CLASSES, BinarySensorEntity from . import DATA_KEY, VolvoEntity async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Volvo sensors.""" if discovery_info is None: return ...
s.data[DATA_KEY], *discovery_info)]) class VolvoSensor(VolvoEntity, BinarySensorEntity): """Representation of a Volvo sensor.""" @property def is_on(self): """Return True if the binary sensor is on.""" return self.instrument.is_on @property def device_class(self): """Retu...
urn None
Crystal-SDS/filter-middleware
crystal_filter_middleware/handlers/proxy.py
Python
gpl-3.0
13,744
0.001237
from crystal_filter_middleware.handlers import CrystalBaseHandler from swift.common.swob import HTTPMethodNotAllowed from swift.common.wsgi import make_subrequest from swift.common.utils import public import operator import json import copy import urllib import os import re mappings = {'>': operator.gt, '>=': operator...
'type': filter_type, 'main': filter_main, 'dependencies': filter_dep, 'size': filter_size} return filter_data def _build_filter_execution_list(self, server): """
This method builds the filter execution list (ordered). """ filter_execution_list = {} ''' Parse global filters ''' for _, filter_metadata in self.global_filters.items(): filter_metadata = json.loads(filter_metadata) if self.method in filter_metadata and filter_...
sc68cal/neutron-classifier
neutron_classifier/db/models.py
Python
apache-2.0
5,550
0
# Copyright (c) 2015 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
ions # under the License. from neutron_classifier.common import constants from oslo_utils import uuidutils import sql
alchemy as sa from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.orderinglist import ordering_list from sqlalchemy import orm Base = declarative_base() # Stolen from neutron/db/model_base.py class HasTenant(object): """Tenant mixin, add to subclasses that have a tenant.""" tenant_id...
MichaelDoyle/Diamond
src/collectors/amavis/amavis.py
Python
mit
3,732
0
# coding=utf-8 """ Collector that reports amavis metrics as reported by amavisd-agent #### Dependencies * amavisd-agent must be present in PATH """ import os import subprocess import re import diamond.collector import diamond.convertor from diamond.collector import str_to_bool class AmavisCollector(diamond.coll...
value, metric_type=mtype,
precision=precision) except OSError as err: self.log.error("Could not run %s: %s", self.config['amavisd_exe'], err) return None return True
dhocker/athomepowerlineserver
helpers/sun_data.py
Python
gpl-3.0
3,610
0.000831
# AtHomePowerlineServer - networked server for CM11/CM11A/XTB-232 X10 controllers # Copyright (C) 2014, 2015 Dave Hocker # # 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, version 3 of the Licen...
g/astral/module.html :param for_datetime: :return: Returns a dict containing the keys sunrise and sunset. ''' sun_data = get_astral_data(for_datetime) sun_d
ata_response = {} sun_data_response["sunrise"] = sun_data["sunrise"].isoformat() sun_data_response["sunset"] = sun_data["sunset"].isoformat() return sun_data_response def round_to_minute(time_to_round): round_adj = 0 rounded = datetime(time_to_round.year, time_to_round.month, time_to_round.day, ...
andrius-preimantas/odoo
addons/base_action_rule/base_action_rule.py
Python
agpl-3.0
15,745
0.005017
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
values['user_id'] = action.act_user_id.id if values: model.write(cr, uid, record_ids, values, context=context) if action.act_followers and hasattr(model, 'message_subscribe'): follower_ids = map(int, action.act_followers) model.message_subscribe(cr, uid,...
server_action_ids) for record in model.browse(cr, uid, record_ids, context): action_server_obj = self.pool.get('ir.actions.server') ctx = dict(context, active_model=model._name, active_ids=[record.id], active_id=record.id) action_server_obj.run(cr, uid, server...
bennylope/django-firstclass
firstclass/south_migrations/0001_initial.py
Python
mit
1,013
0.00691
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db imp
ort db from south.v2 import SchemaMigration from django.db import models class Migration(Schem
aMigration): def forwards(self, orm): # Adding model 'Message' db.create_table('firstclass_message', ( ('key', self.gf('django.db.models.fields.CharField')(max_length=40, primary_key=True)), ('data', self.gf('django.db.models.fields.TextField')(default='{}')), )) ...
fwenzel/strassendeutsch
woerterbuch/__init__.py
Python
gpl-3.0
739
0.005413
from flask import Flask from flaskext.cache import Cache from flaskext.mongokit import BSONObjectIdConverter from werkzeug.routing import Base
Converter import settings app = Flask(__name__) app.config.from_object('woerterbuch.settings') app.secret_key = settings.SECRET_KEY ## Hook up custom URL converters. class RegexConverter(BaseConverter): """Regex-powered url converter.""" def __init__(self, url_map, *it
ems): super(RegexConverter, self).__init__(url_map) self.regex = items[0] app.url_map.converters['regex'] = RegexConverter app.url_map.converters['ObjectId'] = BSONObjectIdConverter # Caching cache = Cache(app) # Templates import woerterbuch.context_processors # Views import woerterbuch.views
tony-rasskazov/meteo
weewx/bin/weeutil/rsyncupload.py
Python
mit
6,592
0.005765
# # Copyright (c) 2012 Will Page <compenguy@gmail.com> # Derivative of ftpupload.py, credit to Tom Keffer <tkeffer@gmail.com> # # See the file LICENSE.txt for your full rights. # # $Id: rsyncupload.py 2766 2014-12-02 02:45:36Z tkeffer $ # """For uploading files to a remove server via Rsync""" import os imp...
rsynccmd = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout = rsynccmd.communicate()[0] stroutput = stdout.encode("utf-8").strip() except OSError, e: if e.errno == errno.ENOENT: syslog.syslog(syslog.LOG_ERR, "rsyncuplo...
d on this system. (errno %d, \"%s\")" % (e.errno, e.strerror)) raise # we have some output from rsync so generate an appropriate message if stroutput.find('rsync error:') < 0: # no rsync error message so parse rsync --stats results rsyncinfo = {} ...
giuva90/TreeBot
bot.py
Python
gpl-3.0
11,462
0.022596
#!/usr/bin/python # -*- coding: iso-8859-1 -*- import configparser from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, RegexHandler, ConversationHandler from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove) from copy import deepcopy import logging import logging.handlers from decisionT...
sage += getClassName(data['classHumanization'][str(which_classes[0][5:])]) else: message += getClassName(str(which_classes[0])) # handling of connection among tree if 'hasSuccessors' in data: update.message.reply_text("Credo di essere sulla buona strada...\n") chat_
data['chose'] = data['successorsMap'][getClassName(which_classes[0])] d
ahmadshahwan/cohorte-runtime
python/cohorte/config/parser.py
Python
apache-2.0
14,427
0
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ COHORTE configuration file parser: converts a parsed configuration file to beans :author: Thomas Calmant :license: Apache Software License 2.0 .. Copyright 2014 isandlaTech Licensed under the Apache License, Version 2.0 (the "License"); you may n...
Error: A mandatory parameter is missing """ if not bundles: return [] return [self._parse_bundle(bundle) for bundle in bundles] @staticmethod def _parse_component(json_object): """
Reads the given JSON object and returns its Component representation :param json_object: A parsed JSON object :return: A Component object :raise KeyError: A mandatory parameter is missing """ # Mandatory values factory = json_object['factory'] # Computed nam...
saymedia/seosuite
seoreporter/__init__.py
Python
mit
13,442
0.002232
# -*- coding: utf-8 -*- # usage: # > python seoreporter/__init__.py [type] [format] [run_id] # example: # > python seoreporter/__init__.py build junit d09b8571-5c8a-42ff-8ab7-c38f4f8871c4 # to
do # output valid jUnit XML outpu
t # output html files in a folder # output html pages that show the data # output json import yaml import time import datetime import os import MySQLdb start = None def report(db, report_type, report_format, run_id): global start report_data = [] start = time.time() # print [report_type, report_form...
bmya/tkobr-addons
tko_point_of_sale_discount_cards/__openerp__.py
Python
agpl-3.0
2,070
0.004348
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # Thinkopen Brasil # Copyright (C) Thinkopen Solutions Brasil (<http://www.tkobr.com>). # # This ...
'point_of_sale_view.xml', 'static/src/xml/pos.xml', ], 'qweb' : ['static/src/xml/discount.xml',], 'init': [], 'demo':
[], 'update': [], 'test': [], #YAML files with tests 'installable': True, 'application': False, 'auto_install': False, #If it's True, the modules will be auto-installed when all dependencies are installed 'certificate': '', }
sassoftware/robj
robj_test/robjtest/httptest.py
Python
apache-2.0
3,456
0.000579
#!/usr/bin/python # # Copyright (c) SAS Institute Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
pdate it. employee1 = self.getArchiveContents('employee1.xml') req = self.client.do_POST('/employees', employee1)
req.wait() req2 = self.client.do_DELETE('/employees/0') req2.wait() self.failUnlessEqual(req2.response.status, 200) req3 = self.client.do_DELETE('/employees/0') req3.wait() self.failUnlessEqual(req3.response.status, 404) def testDELETEError(self): req ...
spjmurray/openstack-sentinel
sentinel/tests/functional/metering/v2/test_meters.py
Python
apache-2.0
1,567
0.005105
# Copyright 2017 DataCentred Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
uage governing permissions and limitations # under the License. from sentinel.tests.functional import base from sentinel.tests.functional import client_fixtures
as fixtures COMPUTE_CREATE_START_QUERY = [ {'field': 'event_type', 'op': 'eq', 'value': 'compute.instance.create.start'} ] class MeteringV2MetersTestCase(base.BaseTestCase): def test_meters_by_type(self): grant = self.useFixture(fixtures.UserProjectGrant(self.sentinel)) client = base.Federat...
ayushgoel/FixGoogleContacts
phonenumbers/data/region_878.py
Python
mit
1,847
0.009746
"""Auto-generated file, do not edit by hand. 878 metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_878 = PhoneMetadata(id='001', country_code=878, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='1\\d{11}', possible_number_pattern='\\d{12}', example_number='101234567890'), fixed_line=PhoneNumberDesc(national_number_pattern='
NA', possible_number_pattern='NA', example_number='101234567890'), mobile=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA', example_number='101234567890'), toll_free=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), premium_rate=PhoneNumberDesc(national_n...
georgyberdyshev/ascend
models/johnpye/fprops/python/solve_ph_array.py
Python
gpl-2.0
2,054
0.041383
from fprops import * from pylab import * import sys #P = fluid('water','helmholtz'); #P = fluid('ammonia','pengrob'); P = fluid('carbondioxide','pengrob'); print "SOLVING TRIPLE POINT..." print "Fluid: %s\nData source: %s" %(P.name, P.source) try: p_t, rhof_t, rhog_t = P.triple_point() except RuntimeError,e: prin...
ntinue try: S = P.set_ph(p,h) T1 = S.T rho1 = S.rho except ValueError,e: print "ERROR %s at p = %f, h = %f (T = %.12e, rho = %.12e)" % (str(e),p, h,T,rho) badT.append(T); badv.append(v) continue if isnan(T1) or isnan(rho1): print "ERROR at T1 = %f, rho1 = %f (T = %.12e, rho = %.12
e)" % (T1, rho1,T,rho) badT.append(T); badv.append(v) else: goodT.append(T); goodv.append(v) #print " +++ GOOD RESULT T1 = %f, rho1 = %f" % (T1, rho1) figure() print "i \tbad T \tbad v" for i in range(len(badT)): print "%d\t%e\t%e" % (i,badT[i], badv[i]) print "TOTAL %d BAD POINTS" % (len(badT)) pr...
brahmastra2016/bleachbit
tests/TestWindows.py
Python
gpl-3.0
13,915
0.000216
# vim: ts=4:sw=4:expandtab # -*- coding: UTF-8 -*- # BleachBit # Copyright (C) 2008-2017 Andrew Ziem # https://www.bleachbit.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version...
f.assert_(not detect_registry_key('HKCU\\Software\\DoesNotExist')) def test_get_autostart_path(self): """Unit test for get_autostart_path""" pathname = get_autostart_path() dirname = os.path.dirname(pathname)
self.assert_(os.path.exists(dirname), 'startup directory does not exist: %s' % dirname) def test_get_known_folder_path(self): """Unit test for get_known_folder_path""" version = platform.uname()[3][0:3] ret = get_known_folder_path('LocalAppDataLow') self...
biomodels/MODEL1006230072
MODEL1006230072/model.py
Python
cc0-1.0
427
0.009368
import o
s path = os.path.dirname(os.path.realpath(__file__)) sbmlFilePath = os.path.join(path, 'MODEL1006230072.xml') with open(sbmlFilePath,'r') as f: sbmlString = f.read() def module_exists(module_name): try: __import__(module_name) except ImportError: return False else: return True...
g(sbmlString)
acsone/acsone-addons
hr_timesheet_no_closed_project_task/models/project_task.py
Python
agpl-3.0
1,843
0
# -*- coding: utf-8 -*- ############################################################################## # # This file is part of hr_timesheet_no_closed_project_task, # an Odoo module. # # Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>) # # hr_timesheet_invoice_hide_to_invoice is free software: # ...
te', 'Template'), ('draft', 'New'), ('open', 'In Progress'), ('cancelled', 'Cancelled'), ('pending', 'Pending'), ('close', 'Closed')] class ProjectTask(models.Model): _inherit = 'project.task' stage_close...
election(PROJECT_SELECTION, related='project_id.state', string='Project State', readonly=True)
laginha/yard
src/yard/resources/decorators/adapted.py
Python
mit
1,471
0.004759
#!/usr/bin/env python # encoding: utf-8 from django.contrib.auth.decorators import ( permission_required as original_permission_required, login_required as original_login_required,) from keyauth.decorators import key_required as original_key_required from functools import wraps class DjangoToYardDecorator(obj...
f login_required(*args, **kwargs): ''' Check if user is authenticated ''' return DjangoToYardDecorator( original_login_required )(*args, **kwargs) def permission_required(*args, **kwargs): ''' Check if user has permissions ''' return DjangoToYardDecorator(original_permission_requir...
key_required(*args, **kwargs): ''' Check key for access ''' return DjangoToYardDecorator( original_key_required )(*args, **kwargs)
larsks/gitblogger
gitblogger/lock.py
Python
gpl-3.0
966
0.009317
import os import errno class LockError (Exception): pass class LockIsLocked (LockError): pass class LockIsUnlocked (LockError): pass class Lock (object): def __init__ (self, path): self.path = path self.locked = False def
acquire (self): if self.locked: raise LocksLocked() try: os.mkdir(self.path) self.locked = True except OSError, detail: if detail.errno == errno.EEXIST: raise LockIsLocked() else: raise def release...
locked() try: os.rmdir(self.path) self.locked = False except OSError, detail: if detail.errno == errno.ENOENT: raise LockIsUnlocked() else: raise def __del__ (self): if self.locked: self.release()
Juniper/contrail-dev-neutron
neutron/plugins/ml2/drivers/mechanism_odl.py
Python
apache-2.0
15,181
0
# Copyright (c) 2013-2014 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 # # Un...
networks' ODL_SUBNET = 'subnet' ODL_SUBNETS = 'subnets' ODL_PORT
= 'port' ODL_PORTS = 'ports' not_found_exception_map = {ODL_NETWORKS: n_exc.NetworkNotFound, ODL_SUBNETS: n_exc.SubnetNotFound, ODL_PORTS: n_exc.PortNotFound} odl_opts = [ cfg.StrOpt('url', help=_("HTTP URL of OpenDaylight REST interface.")), ...
lmcro/webserver
admin/plugins/error_redir.py
Python
gpl-2.0
4,572
0.012905
# -*- coding: utf-8 -*- # # Cheroke-admin # # Authors: # Alvaro Lopez Ortega <alvaro@alobbs.com> # # Copyright (C) 2001-2014 Alvaro Lopez Ortega # # This program is
free software; you can redistribute it and/or # modify it under the terms of version 2 of the GNU General Public # License as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY ...
# along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. # import CTK import validations from util import * from consts import * URL_APPLY = '/plugin/error_redir/apply' REDIRECTION_TYPE = [ ('0', N_('Internal')), ('1', N...
markgw/pimlico
admin/bootstrap.py
Python
gpl-3.0
8,150
0.003067
""" Bootstrapping script that create a basic Pimlico setup, either for an existing config file, or for a new project. Distribute this with your Pimlico project code. You don't need to distribute Pimlico itself with your project, since it can be downloaded later. Just distribute a directory tree containing your config ...
llib.request import urlopen else: from urllib2 import urlopen import tarfile import json RAW_URL = "https://raw.githubusercontent.com/markgw/pimlico/" DOWNLOAD_URL = "https://github.com/markgw/pimlico/archive/" GIT_URL = "https://github.com/markgw/pimlico.git" GITHUB_API = "https://api.github.com" def lookup_p...
n(tag_api_url).read().decode("utf-8") except Exception as e: print("Could not fetch Pimlico release tags from {}: {}".format(tag_api_url, e)) sys.exit(1) tag_data = json.loads(tag_response) return [tag["name"] for tag in reversed(tag_data)] def lookup_bleeding_edge(branch_url): release...
mayankcu/Django-social
venv/Lib/site-packages/distribute-0.6.28-py2.7.egg/setuptools/command/bdist_egg.py
Python
bsd-3-clause
18,594
0.006023
"""setuptools.command.bdist_egg Build .egg distributions""" # This module should be kept compatible with Python 2.3 import sys, os, marshal from setuptools import Command from distutils.dir_util import remove_tree, mkpath try: from distutils.sysconfig import get_python_version, get_python_lib except ImportError: ...
ensure_directory(native_libs) libs_file = open(native_libs, 'wt') libs_file.write('\n'.join(all_outputs)) libs_file.write('\n') libs_file.close() elif os.path.isfile(native_libs): log.info("removing %s" % native_libs) ...
_libs) write_safety_flag( os.path.join(archive_root,'EGG-INFO'), self.zip_safe() ) if os.path.exists(os.path.join(self.egg_info,'depends.txt')): log.warn( "WARNING: 'depends.txt' will not be used by setuptools 0.6!\n" "Use the install_req...
mbalasso/mynumpy
numpy/core/tests/test_memmap.py
Python
bsd-3-clause
4,069
0.002949
import sys from tempfile import NamedTemporaryFile, TemporaryFile, mktemp import os from numpy import memmap from numpy import arange, allclose, asarray from numpy.testing import * class TestMemmap(TestCase): def setUp(self): self.tmpfp = NamedTemporaryFile(prefix='mmap') self.shape = (3,4) ...
ertEqual(abspath, fp.filename) b = fp[:1] self.assertEqual(abspath, b.filename) del b del fp os.unlink(tmpname) def test_filename_fileobj(self): fp = memmap(self.tmpfp, dtype=self.dtype, mode="w+", shape=self.shape)
self.assertEqual(fp.filename, self.tmpfp.name) @dec.knownfailureif(sys.platform=='gnu0', "This test is known to fail on hurd") def test_flush(self): fp = memmap(self.tmpfp, dtype=self.dtype, mode='w+', shape=self.shape) fp[:] = self.data[:] assert_equal(fp[0...
chris48s/UK-Polling-Stations
polling_stations/apps/data_collection/management/commands/import_monmouthshire.py
Python
bsd-3-clause
1,244
0.004019
from django.contrib.gis.geos import Point from data_collection.management.commands import BaseShpStationsShpDistrictsImporter class Command(BaseShpStationsShpDistrictsImporter): srid = 27700 council_id = 'W06000021' districts_name = 'polling_district' stations_name = 'polling_station.shp' elections...
thshire provided this corrected point by e
mail """ station['location'] = Point(335973, 206322, srid=27700) return station
abhinavagarwalla/modular_rl
modular_rl/core.py
Python
mit
24,088
0.008261
import numpy as np, time, itertools from collections import OrderedDict from .misc_utils import * from . import distributions concat = np.concatenate import theano.tensor as T, theano from importlib import import_module import scipy.optimize from .keras_theano_setup import floatX, FNOPTS from keras.layers.core import L...
n result.get() except KeyboardInterrupt: pool.terminate() raise except Exception: pool.terminate() raise else: pool.close() finally:
pool.join() print("Time elapsed (%d workers): %.2f" % (num_processes, time.time() - start_time)) else: paths = do_rollouts_serial(agent, cfg["timestep_limit"], cfg["timesteps_per_batch"], cfg["filter"], next(seed_iter)) return paths def rollout(env, agent, timestep_limit, seed): ...
catapult-project/catapult-csm
telemetry/telemetry/value/scalar_unittest.py
Python
bsd-3-clause
7,682
0.002343
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import unittest from telemetry import story from telemetry import page as page_module from telemetry import value from telemetry.value import impro...
arValue(page0, 'x', 'unit', 3, important=True, improvement_direction=improvement_direction.DOWN) self.assertEquals('default', v.GetBuildbotDataType( value.COMPUTED_PER_PAGE_SUMMARY_OUTPUT_CONTEXT)) self.assertEquals([3], v.GetBuildbotValue()) se
lf.assertEquals(('x', page0.name), v.GetChartAndTraceNameForPerPageResult()) v = scalar.ScalarValue(page0, 'x', 'unit', 3, important=False, improvement_direction=improvement_direction.DOWN) self.assertEquals( 'unimportant', v.GetBuildbotDataType(...
epaglier/Project-JARVIS
jarvis-features/Weather AI/weatherai.py
Python
gpl-3.0
2,382
0.011755
from sklearn.ensemble import RandomForestClassifier from sklearn.datasets import make_classification import numpy as np def predictClothesGeneral(temp): dataFile = open("data.txt") data = dataFile.read() data = data.split("\n") X = [] Y = [] Y2 = [] for i in ra...
ata2 = data[i].split(":")
print "At " + data2[1].split(",")[0] + " degrees... I would recommend a " + predictClothesData(float(data2[1].split(",")[0]))[0]
Z2PackDev/bands_inspect
bands_inspect/lattice.py
Python
apache-2.0
1,413
0
# -*- c
oding: utf-8 -*- # (c) 2017-2019, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> """ Defines a crystal lattice class. """ import numpy as np import scipy.linalg as l
a from fsc.export import export # TODO: move to a separate module # pylint: disable=fixme,useless-suppression @export class Lattice: """ Defines a periodic lattice. """ def __init__(self, matrix): self.matrix = np.array(matrix) def __array__(self): return self.matrix @prope...
ericholscher/django
django/contrib/gis/db/backends/base.py
Python
bsd-3-clause
11,584
0.001468
""" Base/mixin classes for the spatial backend database operations and the `SpatialRefSys` model the backend. """ import re from django.contrib.gis import gdal from django.utils import six from django.utils.encoding import python_2_unicode_compatible class BaseSpatialOperations(object): """ This module holds...
seSpatialBackend` object, which is instantiated by each spatial database backend with the features it has. """ distance_functions = {} geometry_func
tions = {} geometry_operators = {} geography_operators = {} geography_functions = {} gis_terms = set() truncate_params = {} # Quick booleans for the type of this spatial backend, and # an attribute for the spatial database version tuple (if applicable) postgis = False spatialite = F...
abawchen/leetcode
solutions/019_remove_nth_node_from_end_of_list.py
Python
mit
1,751
0.003427
# Given a linked list, remove the nth node from the end of list and return its head. # For example, # Given linked list: 1->2->3->4->5, and n = 2. # After removing the second node from the end, the linked list becomes 1->2->3->5. # Note: # Given n will always be valid. # Try to do this in one pass. # Defin...
{ListNode} head # @param {integer} n # @return {ListNode} def removeNthFromEnd(self, head, n): # no extra space fast = slow = head for _ in range(n): fast = fast.next if not
fast: return head.next while fast.next: fast, slow = fast.next, slow.next slow.next = slow.next.next return head # extra space O(n) # if not head: # return head # i = 0 # dic = {} # node = head; # while node...
detiber/lib_openshift
lib_openshift/models/v1_image_source.py
Python
apache-2.0
5,181
0.001544
# coding: utf-8 """ OpenAPI spec version: Generated by: https://github.com/swagger-api/swagger-codegen.git 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 ...
elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict
): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self)...
gencer/python-phonenumbers
python/phonenumbers/shortdata/region_NZ.py
Python
apache-2.0
673
0.008915
"""Auto-generated file, do not edit by hand. NZ metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_NZ = PhoneMetadata(id='NZ', country_code=None, international_prefix=None, general_desc=PhoneNumberDesc(national_number_pattern='[14]\\d{2,3}', po
ssible_length=(3, 4)), emergency=PhoneNumberDesc(national_number_pattern='111', example_number='111', possible_length=(3,)), short_code=PhoneNumberDesc(national_number_pattern='111|4098', example_number='111', possible_length=(3, 4)), sms_services=PhoneNumberDesc(national_number_pattern='4098', example_numb...
)
szymanskirafal/ab
zadania/urls.py
Python
mit
388
0.010309
from django.conf.urls import url from .views import ZadanieCreateView, ZadanieDetailView, ZadanieUpdateView urlpatterns = [ url(r'^dodaj/(?P<dopuszczenie_id>[0-9]+)/$', ZadanieCreateVie
w.as_view(), name='create'), url(r'(?P<pk>
[0-9]+)/detail/$', ZadanieDetailView.as_view(), name='detail'), url(r'(?P<pk>[0-9]+)/update/$', ZadanieUpdateView.as_view(), name='update'), ]
vaniakosmos/memes-reposter
server.py
Python
mit
432
0
import multiprocessing import os from datetime import timedelta import easy_env fr
om dotenv import find_dotenv, load_dotenv load_dotenv(find_dotenv()) PORT = os.environ.get('PORT', '8000') WEB_WORKERS = easy_env.get_int('WEB_WORKERS', multiprocessing.cpu_count()) bind = ":" + PORT workers = WEB_WORKERS timeout = timedelta(minutes=30).seconds accesslog = '-' access_log_format
= '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s'
tonygalmiche/ove_structure
is_api.py
Python
mit
13,118
0.008564
# -*- coding: utf-8 -*- from datetime import datetime, timedelta import time from openerp import pooler from openerp.osv import fields, osv from openerp.tools.translate import _ class is_api(osv.osv): _name = 'is_api' _description = u'Fonctions générales' def get_usagers_structure(self, cr...
usager_obj.write(cr, uid, usager_id, {'group_3': group_id}, context=context) if group_usager == 'G4': usager_obj.write(cr, uid, usager_id, {'group_4': group_id}, context=context) if group_usag
er == 'G5': usager_obj.write(cr, uid, usager_id, {'group_5': group_id}, context=context) if group_usager == 'G6': usager_obj.write(cr, uid, usager_id, {'group_6': group_id}, context=context) if group_usager == 'G7': usager_obj.write(cr, uid, usager_id, {'group_7': gro...
bbradbury/yum-utils
debuginfo-install.py
Python
gpl-2.0
7,411
0.004723
#!/usr/bin/python # 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 program is distributed in the hope that it w...
buginfo-install: Install debuginfo packages and their dependencies based on the name of the non-debug package debuginfo-install [options] package1 [package2] [package..]""" def __init__(self): YumUtilBase.__init__(self,
DebugInfoInstall.NAME, DebugInfoInstall.VERSION, DebugInfoInstall.USAGE) self.logger = logging.getLogger("yum.verbose.cli.debuginfoinstall") self.optparser = self.getOptionParser() opts = self.optparser # Add util commandl...
gdikos/qstk-on-ec2
market_sim.py
Python
mit
5,585
0.005909
import datetime as dt import numpy as np import pandas as pd # QSTK Imports import QSTK.qstkutil.DataAccess as da import QSTK.qstkutil.qsdateutil as du def get_orders_list(s_file_path): l_columns = ["year", "month", "day", "sym", "type", "num"] df_orders_list = pd.read_csv(s_file_path, sep=',', header=None) ...
s_in_file_path = "data\\q1_orders.csv" s_out_file_path = "data\\q1_values.csv" s_cash = "100000" f_cash = float(s_cash)
df_orders_list = get_orders_list(s_in_file_path) df_orders, dt_start, dt_end, ls_symbols = get_orders(df_orders_list) df_prices = get_prices(dt_start, dt_end, ls_symbols) df_port = process_orders(df_orders, df_prices, f_cash) save_values(df_port, s_out_file_path) print "end market_sim.py"
callowayproject/django-massmedia
massmedia/admin.py
Python
apache-2.0
10,650
0.001784
from django.contrib import admin from django.contrib.admin.widgets import AdminFileWidget, AdminURLFieldWidget from django.contrib.contenttypes.models import ContentType from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from models import (Image, Video, Audio, Flash, Col...
(None, {'fields': ('title', 'caption')}), (_("Content"), {'fields': (('file', 'external_url'), 'thumbnail')}), (_("Credit"), {'fields': ('author', 'one_off_author', 'reproduction_allowed')}), (_("Metadata"), {'fields': ('metadata', 'mime_type')}), (_("Connections"), {'fields': ('publ...
idget"), {'fields': ('width', 'height')}), (_("Advanced options"), { 'classes': ('collapse',), 'fields': ('widget_template',) }), ) raw_id_fields = ('thumbnail',) add_fieldsets = ( (None, {'fields': ('title', )}), (_("Content"), {'fields': (('external...
LethusTI/supportcenter
vendor/mongoengine/mongoengine/django/mongo_auth/models.py
Python
gpl-3.0
3,378
0.000592
from django.conf import settings from django.contrib.auth.models import UserManager from django.core.exceptions import ImproperlyConfigured from django.db import models from django.utils.importlib import import_module from django.utils.translation import ugettext_lazy as _ __all__ = ( 'get_user_document', ) MON...
ell django.contrib.auth to use MongoUser as the user model. In you settings.py, you need: INSTAL
LED_APPS = ( ... 'django.contrib.auth', 'mongoengine.django.mongo_auth', ... ) AUTH_USER_MODEL = 'mongo_auth.MongoUser' Django will use the model object to access the custom Manager, which will replace the original queryset with MongoEngine querys...
mikedingjan/wagtail
wagtail/embeds/apps.py
Python
bsd-3-clause
347
0
from django.apps import AppConfig from
django.utils.translation import ugettext_lazy as _ from .finders import get_finders class WagtailEmbeds
AppConfig(AppConfig): name = 'wagtail.embeds' label = 'wagtailembeds' verbose_name = _("Wagtail embeds") def ready(self): # Check configuration on startup get_finders()
plotly/plotly.py
packages/python/plotly/plotly/validators/pointcloud/_meta.py
Python
mit
438
0
impor
t _plotly_utils.basevalidators class MetaValidator(_plotly_utils.basevalidators.AnyValidator): def __init__(self, plotly_name="meta", parent_name="pointcloud", **kwargs): super(MetaValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwa...
args )
arturcalves/dqc
dqc_django/wsgi.py
Python
mit
397
0
""" WSGI config for dqc_django project. It exposes the
WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "
dqc_django.settings") application = get_wsgi_application()
Typecraft/norsourceparser
norsourceparser/core/rules.py
Python
mit
11,982
0.002921
# coding: utf-8 """ This file contains methods for translation norsource rules into rules we can convert easily to a Typeraft compatible format. """ import re from norsourceparser.core.config import config from norsourceparser.core.constants import REDUCED_RULE_POS, REDUCED_RULE_GLOSSES, REDUCED_RULE_MORPHOLOGICAL_BRE...
lue, priority=REDUCED_RULE_PRIORITY_AMBIGUOUS ): self.rule_id = rule_id self.value
= value self.priority = priority def __unicode__(self): return u"%d %s (Priority %d)" % (self.rule_id, self.value, self.priority) def get_rules_from_partial_branch(partial_branch): """ This method is the main `entry-point` for inferring rules from a branch. The method will analyse t...
pmatigakis/Huginn
huginn/cli/huginn_record.py
Python
bsd-3-clause
2,622
0.000381
""" The huginn_record script is used to record flight data from the simulator """ from argparse import ArgumentParser import json from twisted.internet import reactor from twisted.web.client import Agent, readBody from twisted.web.http_headers import Headers from twisted.internet.task import LoopingCall from huginn...
ble])) print ("") def main(): args = get_arguments() output_file = open(args.output, "w") variables = ["time", "dt", "latitude", "longitude", "altitude", "airspeed", "heading", "x_acceleration", "y_acceleration", "z_acceleration", "roll_rate", "pitch_rate", "yaw_rat...
le"] csv_telemetry_writer = CSVFDMDataWriter(variables, output_file) csv_telemetry_writer.write_header() task = LoopingCall(request_fdm_data, args, csv_telemetry_writer) task.start(args.dt) reactor.run() # @UndefinedVariable output_file.close()
sbktechnology/trufil-frappe
frappe/config/setup.py
Python
mit
5,480
0.042336
from __future__ import unicode_literals from frappe import _ from frappe.desk.moduleview import add_setup_section def get_data(): data = [ { "label": _("Users"), "icon": "icon-group", "items": [ { "type": "doctype", "name": "User", "description": _("System and Website Users") }, ...
: _("Drag and Drop tool to build and customize Print Formats.") }, { "type": "doctype", "name": "Print Settings", "description": _("Set default format, page size, print s
tyle etc.") }, { "type": "doctype", "name": "Print Format", "description": _("Customized HTML Templates for printing transactions.") }, ] }, { "label": _("Workflow"), "icon": "icon-random", "items": [ { "type": "doctype", "name": "Workflow", "description": _...
eviljeff/zamboni
mkt/abuse/models.py
Python
bsd-3-clause
3,467
0
import logging from django.conf import settings from django.db import models from mkt.site.mail import send_mail from mkt.site.models import ModelBase from mkt.users.models import UserProfile from mkt.webapps.models import Webapp from mkt.websites.models import Website log = logging.getLogger('z.abuse') class Abu...
nd_mail(subject,
msg, recipient_list=(settings.ABUSE_EMAIL,)) @classmethod def recent_high_abuse_reports(cls, threshold, period, addon_id=None): """ Returns AbuseReport objects for the given threshold over the given time period (in days). Filters by addon_id if provided. E.g. Greater than 5 abu...
kevinlee12/oppia
scripts/linters/css_linter_test.py
Python
apache-2.0
4,592
0.000653
# coding: utf-8 # # Copyright 2020 The Oppia Authors. All Rights Reserved. # # Licensed under the Apa
che 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 distribute...
specific language governing permissions and # limitations under the License. """Unit tests for scripts/linters/css_linter.py.""" from __future__ import annotations import os import subprocess from core.tests import test_utils from scripts import scripts_test_utils from . import css_linter PARENT_DIR = os.path.abs...
akrherz/iem
scripts/dbutil/compute_hads_sts.py
Python
mit
2,162
0
"""Compute the archive start time of a HADS/DCP/COOP network""" import sys import datetime from pyiem.network import Table as NetworkTable from pyiem.util import get_dbconn, logger LOG = logger() THISYEAR = datetime.datetime.now().year HADSDB = get_dbconn("hads") MESOSITEDB = get_dbconn("mesosite") def get_minvalid...
) minv = cursor.fetchone()[0] if minv is not None:
return minv def do_network(network): """Do network""" nt = NetworkTable(network) for sid in nt.sts: sts = get_minvalid(sid) if sts is None: continue if ( nt.sts[sid]["archive_begin"] is None or nt.sts[sid]["archive_begin"] != sts ): ...
Rotendahl/DormitoryLife
cashier/migrations/0015_auto_20171108_1351.py
Python
gpl-3.0
552
0.001818
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-11-08 12:51 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): depende
ncies = [ ('cashier', '0014_fix_transaction'), ] operations = [ migrations.AlterField(
model_name='transaction', name='typeOfTransaction', field=models.CharField(choices=[('debt', 'Gæld'), ('expense', 'Udlæg')], default='debt', max_length=7, verbose_name='Type'), ), ]
mokieyue/mopidy
mopidy/core/listener.py
Python
apache-2.0
5,283
0
from __future__ import absolute_import, unicode_literals from mopidy import listener class CoreListener(listener.Listener): """ Marker interface for recipients of events sent by the core actor. Any Pykka actor that mixes in this class will receive calls to the methods defined here when the correspo...
ack): """ Called whenever a new track starts playing. *MAY* be implemented by actor. :param tl_track: the track that just started playing :type t
l_track: :class:`mopidy.models.TlTrack` """ pass def track_playback_ended(self, tl_track, time_position): """ Called whenever playback of a track ends. *MAY* be implemented by actor. :param tl_track: the track that was played before playback stopped :type t...
BanzaiTokyo/akihabara-tokyo
askapp/migrations/0013_auto_20170206_0748.py
Python
apache-2.0
542
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('askapp', '0012_au
to_20170203_1436'), ] operations = [ migrations.RenameField( model_name='post', old_name='the_answer', new_name='is_answer', ), migrations.AddField( model_name='post', na
me='accepted', field=models.DateTimeField(null=True), ), ]
joshuamckenty/yolo-octo-wookie
nova/endpoint/images.py
Python
apache-2.0
2,782
0.002516
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the #
Administrator of the National Aeronautics and Space Administration. # 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/...
ASIS, 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. """ Proxy AMI-related calls from the cloud controller, to the running objectstore daemon. """ import json import random impor...
grahame/ealgis
django/ealgis/dataschema/schema_v1.py
Python
gpl-3.0
3,861
0.001554
from sqlalchemy.schema import ( Table, Column, MetaData, ForeignKey) from sqlalchemy.types import ( Text, JSON, DateTime, Integer, String) from collections import defaultdict from uuid import uuid4 import datetime class SchemaStore: def __init__(self): self.metadata = d...
Column('id', Integer, primary_key=True), # in the source schema: may not be the same schema as this Table instance Column('geometry_source_schema_name', St
ring, nullable=False), Column('geometry_source_id', Integer, nullable=False), # these must be in this schema Column('attr_table_id', Integer, fkey('table_info.id'), nullable=False), Column('attr_column', String(256)), schema=schema_name)) tables.append...
slackapi/python-slackclient
slack_sdk/__init__.py
Python
mit
1,429
0.002099
""" * The SDK website: https://slack.dev/python-slack-sdk/ * PyPI package: https://pypi.org/project/slack-sdk/ Here is the list of key modules in this SDK: #### Web API Client * Web API client: `slack_sdk.web.client` * asyncio-based Web API client: `slack_sdk.web.async_client` #### Webhook / response_url Client * ...
gs. logging.getLogger(__name__).
addHandler(NullHandler())
uclouvain/osis
base/migrations/0063_populate_uuid_values.py
Python
agpl-3.0
969
0.002064
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-09-05 09:13 from __future__ import unicode_literals import uuid from django.core.exceptions import FieldDoesNotExist from django.db import migrations def set_uuid_field(apps, schema_editor): """ Set a random uuid value to all existing rows in all mod...
[ ('base', '0062_add_uuid_field'),
] operations = [ migrations.RunPython(set_uuid_field, elidable=True, reverse_code=migrations.RunPython.noop), ]
SpaceGroupUCL/qgisSpaceSyntaxToolkit
esstoolkit/external/pyqtgraph/multiprocess/parallelizer.py
Python
gpl-3.0
12,494
0.014647
# -*- coding: utf-8 -*- import os
, sys, time, multiprocessing, re from .processes import ForkedProcess from .remoteproxy import ClosedError from ..python2_3 import basestring, xrange class CanceledError(Exception): """Raised when the progress dialog is canceled during a processing operation.""" pass class Parallelize(object): """ Cl...
tion on multi-core CPUs Example:: ## Here is the serial (single-process) task: tasks = [1, 2, 4, 8] results = [] for task in tasks: result = processTask(task) results.append(result) print(results) ## Here is...
sidharta/hansel-app
main/auth/yahoo.py
Python
mit
2,275
0
# coding: utf-8 # pylint: disable=missing-docstring, invalid-name import flask import auth import config import model from main import app yahoo_config = dict( access_token_url='https://api.login.yahoo.com/oauth/v2/get_token', authorize_url='https://api.login.yahoo.com/oauth/v2/request_auth', base_url=...
ret, request_token_url='https://api.login.yahoo.com/oauth/v2/get_request_token', ) yahoo = auth.create_oauth_app(yahoo_config, 'yahoo') @app.route('/_s/callback/yahoo/oauth-authorized/') def yahoo_authorized(): response = yahoo.authorized_response() if response is None: flask.flash(
'You denied the request to sign in.') return flask.redirect(flask.url_for('index')) flask.session['oauth_token'] = ( response['oauth_token'], response['oauth_token_secret'], ) fields = 'guid, emails, familyName, givenName, nickname' me = yahoo.get( '/v1/yql', da...
great-expectations/great_expectations
tests/datasource/batch_kwarg_generator/test_s3_subdir_reader_generator.py
Python
apache-2.0
3,834
0.001826
import os import time import pandas as pd import pytes
t import requests from botocore.session import Session from great_expectations.datasource.batch
_kwargs_generator import ( S3SubdirReaderBatchKwargsGenerator, ) port = 5555 url_host = os.getenv("GE_TEST_LOCALHOST_URL", "127.0.0.1") endpoint_uri = f"http://{url_host}:%s/" % port os.environ["AWS_ACCESS_KEY_ID"] = "dummy_key" os.environ["AWS_SECRET_ACCESS_KEY"] = "dummy_secret" @pytest.fixture(scope="module")...
npo-poms/pyapi
npoapi/utils.py
Python
gpl-3.0
1,076
0.003717
import os import logging import re from typing import Final logger: Final = logging.getLogger("Npo.Utils") pattern: Final = re.compile('[a-z0-9]{2,}', re.IGNORECASE) def looks_like_form(form: str): """ Checks if the given string looks like a form. E.g. it represents json, xml, a file, or 'stdin'. Otherw...
form)
return True if form == "-": logger.debug("Detected explicit stdin") return True if not pattern.match(form): logger.warning("Form does not look like a credible text search. It doesn't look like a file either though") return False return False
SP2LC/procon25-main
A-star/L-dynamic.py
Python
apache-2.0
17,085
0.024341
# -*- coding: utf-8 -*- import pairing_heap as pheap from copy import deepcopy,copy import threading import Queue import requests from requests.auth import HTTPDigestAuth import json import sys import communication import config import time import L_sprit # グローバル変数の宣言 LIMIT_SELECTION = 0 SELECTON_RATE = 0 EXCHANGE_RAT...
.append(None) table.append(col) for i in range(len(goal)): for j in range(len(goal[0])): (goal_x, goal_y) = goal[i][j] table[goal_x][goal_y] = (i, j) return table def distance_to_goal(table, board): #ノードとゴールノードまでの予測距離を返す。引数は(距離計算用テーブル,ゴールのボード) ans = 0 for i in ra...
][board_y] b = (i, j) x = abs(a[0] - b[0]) y = abs(a[1] - b[1]) ans += x + y return ans * EXCHANGE_RATE def point_md(point,board, table): table_x, table_y = board[point[0]][point[1]] a = table[table_x][table_y] x = abs(a[0] - point[0]) y = abs(a[1] - ...
daniellawrence/pdfclassification
main.py
Python
mit
2,887
0.002425
#!/usr/bin/env python from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage from cStringIO import StringIO from collections import defaultdict import sys import yaml raw_classification...
png").read() os.popen("convert -density 300 %s /tmp/x.png" % pdf).read()
barcode = os.popen("zbarimg -q /tmp/x*.png").read().strip() if barcode: print "%s has a barcode of %s" % (pdf, barcode) def main(): import os pdffiles = [] if len(sys.argv) == 1: for root, dirnames, filenames in os.walk("/home/dannyla"): for filename in filenames: ...
eestay/edx-platform
lms/djangoapps/courseware/tests/test_middleware.py
Python
agpl-3.0
1,873
0
""" Tests for courseware middleware """ from django.core.urlresolvers import reverse from django.test.client import RequestFactory from django.http import Http404 from mock import patch import courseware.courses as courses from courseware.middlewar
e import RedirectUnenrolledMiddleware from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory class CoursewareMiddlewareTestCase(ModuleStoreTestCase): """Tests that courseware mi
ddleware is correctly redirected""" def setUp(self): super(CoursewareMiddlewareTestCase, self).setUp() self.course = CourseFactory.create() def check_user_not_enrolled_redirect(self): """A UserNotEnrolled exception should trigger a redirect""" request = RequestFactory().get("d...
csb-toolbox/CSB
csb/bio/io/mrc.py
Python
mit
9,732
0.009453
""" Cryo-EM density map I/O @warning: dragons ahead, this module is experimental """ import numpy import struct class DensityMapFormatError(ValueError): pass class ByteOrder(object): NATIVE = '=' LITTLE = '<' BIG = '>' class DensityInfo(object): def __init__(self, data, spacing, origin...
def _rawheader(self, stream): """ Read and return the raw binary header. """ raw = stream.read(DensityMapReader.HEADER_SIZE) return bytes(raw) def _inspect(self, rawheader, order): """ Parse a raw binary hea
der. """ format = '{0}10l6f3l3f3l'.format(order) fields = struct.unpack(format, rawheader[:4 * 25]) return HeaderInfo(fields) def _spacing(self, header): if header.nx != 0 and header.ny != 0 and header.nz != 0: return (header.x / header.nx, header.y...
gully/PyKE
pyke/__init__.py
Python
mit
1,296
0.036265
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import os PACKAGEDIR = os.path.abspath(os.path.dirname(__file__)) import matplotlib matplotlib.use('TkAgg') from .version import _
_version__ from .keparray import * from .kepbls import * from .kepclean import * from .kepclip import * from .kepconvert import * from .kepcotrend import * from .kepdetrend import * from .kepdiffim import * from .kepdraw import * from .kepdynamic import * from .kepextract import * from .kepfilter import * from .kepfit ...
en import * from .kepfold import * from .kepfourier import * from .kepperiodogram import * from .kepfunc import * from .kephead import * from .kepimages import * from .kepio import * from .kepkey import * from .kepmask import * from .kepmsg import * from .kepoutlier import * from .keppca import * from .keppixseries im...
amol-mandhane/konnactivity
settings/__init__.py
Python
mit
71
0.014085
from
.base import * from .local import * FB_AP
P_ID = "557603244304943"
restless/django-guardian
guardian/admin.py
Python
bsd-2-clause
14,636
0.001366
from django import forms from django.conf import settings from guardian.compat import url, patterns from django.contrib import admin from django.contrib import messages from django.contrib.admin.widgets import FilteredSelectMultiple from django.core.urlresolvers import reverse from django.shortcuts import render_to_res...
) re
turn myurls + urls def get_obj_perms_base_context(self, request, obj): """ Returns context dictionary with common admin and object permissions related content. """ context = { 'adminform': {'model_admin': self}, 'object': obj, 'app_label':...
cobbler/koan
koan/configurator.py
Python
gpl-2.0
10,535
0.00019
""" Configuration class. Copyright 2010 Kelsey Hightower Kelsey Hightower <kelsey.hightower@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 2 of the License, or (at your op...
rt shutil from . import utils import tempfile import stat import os.path import sys import time import pwd import grp import json try: import yum sys.path.append('/usr/share/yum-cli') import cli yum_availab
le = True except: yum_available = False class KoanConfigure: """ Used for all configuration methods, used by koan to configure repos, files and packages. """ def __init__(self, config): """Constructor. Requires json config object.""" self.config = json.JSONDecoder().decode(co...
LearnEra/LearnEraPlaftform
lms/djangoapps/django_comment_client/utils.py
Python
agpl-3.0
18,621
0.003007
import pytz from collections import defaultdict import logging from datetime import datetime from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db import connection from django.http import HttpResponse from django.utils import simplejson from django_comment_common.mode...
o.utils.timezone import UTC from opaque_keys.edx.locations import i4xEncoder from opaque_keys.edx.keys import CourseKey import json log = logging.getLogger(__name__) def extract(dic, keys): return {k: dic.get(k) for k in keys} def strip_none(dic): return dict([(k, v) for k, v in dic.iteritems() if v is not...
v) for k, v in dic.iteritems() if not _is_blank(v)]) # TODO should we be checking if d1 and d2 have the same keys with different values? def merge_dict(dic1, dic2): return dict(dic1.items() + dic2.items()) def get_role_ids(course_id): roles = Role.objects.filter(course_id=course_id).exclude(name=FORUM_ROLE...