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
cchristelis/inasafe
safe/impact_functions/bases/layer_types/classified_vector_exposure.py
Python
gpl-3.0
1,719
0
# coding=utf-8 from safe.common.exceptions import NoAttributeInLayerError from safe.impact_functions.bases.utilities import check_attribute_exist __author__ = 'Rizky Maulana Nugraha "lucernae" <lana.pcfre@gmail.com>' __date__ = '08/05/15' class ClassifiedVectorExposureMixin(object): def __init__(self): ...
tes()[attr_index] if feature_value not in unique_list: unique_list.append(feature_value) self.exposure_unique_values = unique_list @property def exposure_unique_values(self): return self._exposure_unique_values @exposure_unique_values.setter def...
nique_values(self, value): self._exposure_unique_values = value
kd7iwp/cube-bookstore
cube/urls.py
Python
gpl-3.0
2,981
0.006038
# Copyright (C) 2010 Trinity Western University from cube.books.models import Book from cube.twupass.settings import TWUPASS_LOGOUT_URL from django.contrib.auth.model
s import User from django.contrib import admin from django.conf.urls.defaults import * from django.views.generic.si
mple import direct_to_template, redirect_to admin.autodiscover() urlpatterns = patterns('', url(r'^twupass-logout/$', redirect_to, {'url': TWUPASS_LOGOUT_URL}, name="twupass-logout"), url(r'^help/$', direct_to_template, {'template' : 'help.html'}, name="help"), (r'^admin/doc/', include('dj...
jcchuks/MiscCodes
CheckPathSum.py
Python
mit
2,184
0.012821
''' https://leetcode.com/problems/path-sum/#/description Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree and sum = 22, 5 / \ 4 8 ...
and exit happily. - else, at each valid node, check if the node is a leaf an
d if the val plus total equal the sum, if true, you have found your result,just return. - if not, check on the left node, then check then check right and return answer. - Your base condition takes care of unnecessary traversal. - If you reach the leaf without finding the sum, return Fals...
j3camero/galaxyatlas
data-release-2/render-lmc-frames.py
Python
mit
5,728
0.00419
import csv import math import numpy as np from PIL import Image width = 854 height = 480 fov_multiplier = 1.73 # For 60 degrees, set to 1.73. For 90 degrees, set to 1. minwh2 = 0.5 * min(width, height) class Star: def __init__(self, ra, dec, parallax, g_flux, bp_flux, rp_flux): self.ra = ra self...
cs * 3.26156 ra_rad = ra * math.pi / 180 dec_rad = (dec + 90) * math.pi / 180 self.x = distance_ly * math.sin(dec_rad) * math.cos(ra_rad) self.y = distance_ly * math.sin
(dec_rad) * math.sin(ra_rad) self.z = distance_ly * math.cos(dec_rad) self.absolute_luminosity = g_flux * distance_ly**2 def ParseFloat(s): try: return float(s) except: return 0 stars = [] with open('lmc-stars.csv', 'rb') as input_file: reader = csv.DictReader(input_file) ...
aluminiumgeek/organic
utils.py
Python
lgpl-3.0
212
0
# -*- coding: utf-8 -*- # Some utils import hashlib impo
rt uuid def get_hash(dat
a): """Returns hashed string""" return hashlib.sha256(data).hexdigest() def get_token(): return str(uuid.uuid4())
voutilad/courtlistener
cl/corpus_importer/dup_helpers.py
Python
agpl-3.0
14,568
0.003089
import string from django.utils.text import slugify from django.utils.timezone import now from lxml import html from lxml.html import tostring from lxml.html.clean import Cleaner from cl.lib.string_utils import anonymize, trunc from cl.search.models import OpinionCluster from juriscraper.lib.string_utils import clean_...
r true for any LB case. # save_doc_and_cite(target, index=False) def merge_cases_complex(case, target_ids): """Merge data from PRO with multiple cases that seem to be a
match. The process here is a conservative one. We take *only* the information from PRO that is not already in CL in any form, and add only that. """ # THIS CODE ONLY UPDATED IN THE MOST CURSORY FASHION. DO NOT TRUST IT. for target_id in target_ids: simulate = False oc = OpinionClus...
april/http-observatory
httpobs/scanner/retriever/retriever.py
Python
mpl-2.0
7,939
0.004157
from celery.exceptions import SoftTimeLimitExceeded, TimeLimitExceeded from urllib.parse import urlparse from httpobs.conf import (RETRIEVER_CONNECT_TIMEOUT, RETRIEVER_CORS_ORIGIN, RETRIEVER_READ_TIMEOUT, RETRIEVER_USER_AGENT) from httpobs.s...
return None return response.text else: return None def retrieve_all(hostname, **kwargs): kwargs['cookies'] = kwargs.get('cookies', {}) # HTTP cookies to send, instead of from the database kwargs['headers'] = kwargs.get('
headers', {}) # HTTP headers to send, instead of from the database # This way of doing it keeps the urls tidy even if makes the code ugly kwargs['http_port'] = ':' + str(kwargs.get('http_port', '')) if 'http_port' in kwargs else '' kwargs['https_port'] = ':' + str(kwargs.get('https_port', '')) if 'https_...
azam-a/malaysiaflights
malaysiaflights/tests/test_aa.py
Python
mit
3,889
0
import unittest import datetime import httpretty as HP import json from urllib.parse import parse_qsl from malaysiaflights.aa import AirAsia as AA class AARequestTests(unittest.TestCase): def url_helper(self, from_, to, date): host = 'https://argon.airasia.com' path = '/api/7.0/search' ...
def test_get_flight_details_using_index_1_should_return_results(self): json = self.single expected = { 'flight_number': 'AK6229', 'departure_airport': 'TGG', 'arrival_airport': 'KUL', 'departure_time': 'Sat, 20 Jun 2015 13:10:00 +0800', 'ar...
'total_fare': 133.99, 'fare_currency': 'MYR'} actual = AA.get_direct_flight_details(json, 1) self.assertEqual(expected, actual) @unittest.skip('no-data-yet') def test_is_connecting_flights_should_return_true_for_connecting(self): json = '' actual = AA.is_connecting_...
plaid/plaid-python
plaid/model/pay_period_details.py
Python
mit
9,216
0.000434
""" The Plaid API The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from plaid.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal...
is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. ...
hen traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the cla...
ShapeNet/RenderForCNN
view_estimation/run_evaluation.py
Python
mit
932
0.006438
import os import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) sys.path.append(os.path.dirname(BASE_DIR)) from global_variables import * from evaluation_helper import * cls_names = g_shape_names img_name_file_list = [os.path.join(g_real_images_voc12val_det_bbox_folder, name+'.tx...
ults') test_avp_nv(cls_names, img_name_file_list, det_bbox_mat_file_list, result_folder) img_name_file_list = [os.path.join(g_real_images_voc12val_easy_gt_bbox_folder, name+'.txt') for name in cls_names] view_label_folder = g_real_images_voc12val_easy_gt_bbox_folder result_folder = os.path.join(BASE_DIR, 'vp_test_resu...
p_acc(cls_names, img_name_file_list, result_folder, view_label_folder)
facebookexperimental/eden
eden/hg-server/edenscm/mercurial/hgweb/__init__.py
Python
gpl-2.0
3,073
0
# Portions Copyright (c) Facebook, Inc. and its affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. # hgweb/__init__.py - web interface to a mercurial repository # # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net> # Copyright 2005 ...
irs (multi-repo view) - list of virtual:real tuples (multi-repo view) """ if ( (isinstance(config, str) and not os.path.isdir(config)) or isinstance(config, dict) or isinstance(config, list) ): # create a multi-dir interface return hgwebdir_mod.hgwebdir(config, b...
ebdir(config, baseui=baseui) class httpservice(object): def __init__(self, ui, app, opts): self.ui = ui self.app = app self.opts = opts def init(self): util.setsignalhandler() self.httpd = server.create_server(self.ui, self.app) portfile = self.opts.get("port_...
mhnatiuk/phd_sociology_of_religion
scrapper/build/cffi/testing/test_ffi_backend.py
Python
gpl-2.0
9,406
0.001701
import py, sys, platform import pytest from testing import backend_tests, test_function, test_ownlib from cffi import FFI import _cffi_backend class TestFFI(backend_tests.BackendTests, test_function.TestFunction, test_ownlib.TestOwnLib): TypeRepr = "<ctype '%s'>" @staticmethod ...
long z:57; char y;", L + 8, L, L + 8 + L) self.check("char x; long long :57; char y;"
, L + 8, 1, L + 9) @pytest.mark.skipif("not platform.machine().startswith('arm')") def test_bitfield_anonymous_align_arm(self): L = FFI().alignof("long long") self.check("char y; int :1;", 0, 4, 4) self.check("char x; int z:1; char y;", 2, 4, 4) self.check("char x; int :1; char...
Lanceolata/code-problems
python/leetcode/Question_168_Excel_Sheet_Column_Title.py
Python
mit
255
0.003922
#!/usr/bin/python # coding:
utf-8 class Solution(object): def convertT
oTitle(self, n): """ :type n: int :rtype: str """ return "" if n == 0 else self.convertToTitle((n - 1) / 26) + chr((n - 1) % 26 + ord('A'))
snakeleon/YouCompleteMe-x86
third_party/ycmd/third_party/JediHTTP/vendor/jedi/jedi/evaluate/compiled/__init__.py
Python
gpl-3.0
17,309
0.000924
""" Imitate the parser representation. """ import inspect import re import sys import os from functools import partial from jedi._compatibility import builtins as _builtins, unicode from jedi import debug from jedi.cache import underscore_memoization, memoize_method from jedi.parser.tree import Param, Base, Operator, ...
ed scopes - the other ones are not important for internal analysis. """ module = self.get_parent_until() faked_subscopes = [] for name in dir(self.obj): try: faked_subscopes.append( fake.get_faked
(module.obj, self.obj, parent=self, name=name) ) except fake.FakeDoesNotExist: pass return faked_subscopes def is_scope(self): return True def get_self_attributes(self): return [] # Instance compatibility def get_imports(self): ...
duncan-r/SHIP
tests/test_rowdatacollection.py
Python
mit
10,219
0.002838
from __future__ import unicode_literals import unittest from ship.datastructures import rowdatacollection as rdc from ship.datastructures import dataobject as do from ship.fmp.datunits import ROW_DATA_TYPES as rdt class RowDataCollectionTests(unittest.TestCase): def setUp(self): # Create some object t...
(row, testrows[i]) i += 1 def test_iterateRowsWithKey(se
lf): """Test generator for a single DataObject""" testrows = [ 32.345, 33.45, ] i = 0 for row in self.testcol.iterateRows(rdt.ELEVATION): self.assertEqual(row, testrows[i]) i += 1 def test_rowAsDict(self): """Shoud retu...
Nomadblue/django-nomad-activity-feed
setup.py
Python
bsd-3-clause
1,187
0.000843
# coding: utf-8 import os from
setuptools import setup, find_packages README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-nomad-activity-feed', version='0.1.1', packages=fi...
ch an activity feed to any Django model.', long_description=README, url='https://github.com/Nomadblue/django-activity-feed', author='José Sazo', author_email='jose@nomadblue.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Dev...
drnlm/sqlobject
sqlobject/tests/test_boundattributes.py
Python
lgpl-2.1
1,672
0
import pytest from sqlobject import boundattributes from sqlobject import declarative pytestmark = pytest.mark.skipif( True, reason='The module "boundattributes" and its tests were not finished yet') class SOTestMe(object): pass class AttrReplace(boundattributes.BoundAttribute): __unpackargs__ = ...
def make_object(self, cls, added_class, attr_name, **attrs): if not self: return cls.singleton().make_object( added_class, attr_name, **attrs) self.replace.added_class = added_class self.replace.name = attr_name assert attrs['replace'] is self.replace ...
return self.replace class Holder: def __init__(self, name): self.holder_name = name def __repr__(self): return '<Holder %s>' % self.holder_name def test_1(): v1 = Holder('v1') v2 = Holder('v2') v3 = Holder('v3') class V2Class(AttrReplace): arg1 = 'nothing' ...
panmari/tensorflow
tensorflow/tensorboard/scripts/serialize_tensorboard.py
Python
apache-2.0
6,341
0.008831
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
rBoard server to static json.""" def __init__(self, connection, target_path): self.connection = connection EnsureDirectoryExists(os.path.join(target_path, 'data')) self.path = target_path def GetAndSave(self, url): """GET the given url. Serialize the result at clean path version of url.""" sel...
t('GET', '/data/' + url) response = self.connection.getresponse() destination = self.path + '/data/' + Clean(url) if response.status != 200: raise IOError(url) content = response.read() with open(destination, 'w') as f: f.write(content) return content def GetRouteAndSave(self, ro...
rbu/mediadrop
mediadrop/migrations/versions/004-280565a54124-add_custom_head_tags.py
Python
gpl-3.0
1,908
0.007862
# This file is a part of MediaDrop (http://www.mediadrop.net), # Copyright 2009-2015 MediaDrop contributors # For the exact contribution history, see the git revision log. # The source code contained in this file is licensed under the GPLv3 or # (at your option) any later version. # See LICENSE.txt in the main project ...
12-02-13 (v0.10dev) previously migrate script v054 Revision ID: 280
565a54124 Revises: 4d27ff5680e5 Create Date: 2013-05-14 22:38:02.552230 """ # revision identifiers, used by Alembic. revision = '280565a54124' down_revision = '4d27ff5680e5' from alembic.op import execute, inline_literal from sqlalchemy import Integer, Unicode, UnicodeText from sqlalchemy import Column, MetaData, Ta...
snfactory/cubefit
cubefit/main.py
Python
mit
26,267
0.000533
"""Main entry points for scripts.""" from __future__ import print_function, division from argparse import ArgumentParser from collections import OrderedDict from copy import copy from datetime import datetime import glob import json import logging import math import os import scipy.stats import numpy as np from .ve...
%d %H:%M:%S")) tsteps = OrderedDict() # finish time of each step. logging.
info("parameters: mu_wave={:.3g} mu_xy={:.3g} refitgal={}" .format(args.mu_wave, args.mu_xy, args.refitgal)) logging.info(" psftype={}".format(args.psftype)) logging.info("reading config file") with open(args.configfile) as f: cfg = json.load(f) # basic checks on co...
talkincode/txportal
txportal/simulator/handlers/auth_handler.py
Python
mit
1,737
0.003454
#!/usr/bin/env python # coding=utf-8 import struct from twisted.internet import defer from txportal.packet import cmcc, huawei from txportal.simulator.handlers import base_handler import functools class AuthHandler(base_handler.BasicHandler): def proc_cmccv1(self, req, rundata): resp = cmcc.Portal.newMess...
req.userIp, req.serialNo, req.reqId, secret=self.secret ) resp.attrNum = 1 resp.attrs = [ (0x05, 'success'), ] return resp @defer.inlineCallbacks def proc_huaweiv2(self, req, rundata):
resp = huawei.PortalV2.newMessage( huawei.ACK_AUTH, req.userIp, req.serialNo, req.reqId, self.secret, auth=req.auth, chap=(req.isChap==0x00) ) resp.attrNum = 1 resp.attrs = [ ...
nugget/home-assistant
homeassistant/components/satel_integra/binary_sensor.py
Python
apache-2.0
3,430
0
"""Support for Satel Integra zone states- represented as binary sensors.""" import logging from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from . import ( CONF_OUTPUTS, CONF_ZONE_NAM...
return self._name @property def icon(self): """Icon for device by its type.""" if self._zone_type == 'smoke': return "mdi:fire" @property def should_poll(self): """No polling needed.""" return False @property def is_on(self): """Retu...
class(self): """Return the class of this sensor, from DEVICE_CLASSES.""" return self._zone_type @callback def _devices_updated(self, zones): """Update the zone's state, if needed.""" if self._device_number in zones \ and self._state != zones[self._device_number]:...
jaloren/robotframework
src/robot/libraries/BuiltIn.py
Python
apache-2.0
146,969
0.001082
# 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 ...
190 def run_keyword_variant(resolve): def decorator(method): RUN_KW_REGISTER.register_run_keyword('BuiltIn', method.__name__, resolve, deprecation_warning=False) return method return decorator class _BuiltInBase(object): @propert
y def _context(self): return self._get_context() def _get_context(self, top=False): ctx = EXECUTION_CONTEXTS.current if not top else EXECUTION_CONTEXTS.top if ctx is None: raise RobotNotRunningError('Cannot access execution context') return ctx @property def...
AWhetter/pacman
test/pacman/tests/remove047.py
Python
gpl-2.0
521
0
self.description = "Remove a package required by other packages" lp1
= pmpkg("pkg1") self.addpkg2db("local", lp1) lp2 = pmpkg("pkg2") lp2.depends = ["pkg1"] self.addpkg2db("local", lp2) lp3 = pmpkg("pkg3") lp3.depends = ["pkg1"] self.addpkg2db("local", lp3) lp4 = pmpkg("pkg4") lp4.depends = ["pkg1"] self.addpkg2db("local", lp4) self.args = "-R pkg1 pkg2" self.addrule("!PACMAN_RETCO...
lf.addrule("PKG_EXIST=pkg4")
asedunov/intellij-community
python/testData/quickFixes/PyUpdatePropertySignatureQuickFixTest/getter.py
Python
apache-2.0
245
0.053061
class A(Aa)
: @property def <warning descr="Getter signature should be (self)">x<caret></warning>(self, r): return "" @x.setter
def <warning descr="Setter should not return a value">x</warning>(self, r): return r
annarev/tensorflow
tensorflow/python/ops/list_ops.py
Python
apache-2.0
14,846
0.00714
# Copyright 2018 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...
port array_ops from tensorflow.python.ops import gen_list_ops from tensorflow.python.ops import handle_data_util # go/tf-wildcard-import # pylint: disable=wildcard-import from tensorflow.python.ops.gen_list_ops import * # pylint: enable=wildcard-import from tensorflow.python.util.lazy_loader import LazyLoader # list_o...
ps control_flow_ops = LazyLoader( "control_flow_ops", globals(), "tensorflow.python.ops.control_flow_ops") ops.NotDifferentiable("TensorListConcatLists") ops.NotDifferentiable("TensorListElementShape") ops.NotDifferentiable("TensorListLength") ops.NotDifferentiable("TensorListPushBackBatch") def empty_tenso...
Alexander-M-Waldman/local_currency_site
lib/python2.7/site-packages/allauth/socialaccount/south_migrations/0013_auto__chg_field_socialaccount_uid__chg_field_socialapp_secret__chg_fie.py
Python
gpl-3.0
7,605
0.00789
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'So
cialAccount.uid' db.alter_column(u'socialaccount_socialaccount', 'uid', self.gf('django.db.models.fields.CharField')(max_length=1
91)) # Changing field 'SocialApp.secret' db.alter_column(u'socialaccount_socialapp', 'secret', self.gf('django.db.models.fields.CharField')(max_length=191)) # Changing field 'SocialApp.client_id' db.alter_column(u'socialaccount_socialapp', 'client_id', self.gf('django.db.models.fields....
alogg/dolfin
demo/undocumented/ale/python/demo_ale.py
Python
gpl-3.0
1,429
0.0007
"""This demo demonstrates how to move the vertex coordinates of a boundary mesh and then updating the interior vertex coordinates of the original mesh by
suitably interpolating the vertex coordinates (useful for implementation of ALE methods).""" # Copyright (C) 2008 Solveig Bruvoll and Anders Logg # # This file is part of DOLFIN. # # DOLFIN is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as publishe...
e hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with DOLFIN. If not, s...
bmi-forum/bmi-pyre
pythia-0.8/packages/journal/journal/components/Device.py
Python
gpl-2.0
1,235
0.006478
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Michael A.G. Aivazis # California Institute of Technology # (C) 1998-2005 All Rights Reserved # # <LicenseText> # # ~~~~~~~~~~~~~~~~~~~~~~~~...
vice(self): raise NotImplementedError("class '%s' must override 'device'" % self.__class__.__name__) def __init__(self, name): Component.__init__(self, name, "journal-device") self.device = None return def _init(self): device = self.createDevice() renderer = s...
_ = "$Id: Device.py,v 1.2 2005/03/10 06:16:37 aivazis Exp $" # End of file
codefisher/djangopress
djangopress/accounts/models.py
Python
mit
5,282
0.006437
import random import datetime import time import hashlib from django.db import models from django.conf import settings from django.urls import reverse from django.contrib.auth.models import User, Group from django.db.models.signals import post_save from djangopress.core.models import Property from django.utils import ...
= ( ('twitter', 'Twitter'), ('google_plus', 'Google Plus'), ('facebook', 'Facebook'), ('linkedin', 'Linked In'), ('pinterest', 'Pinterest'), ) account = models.CharField(max_length=20, choices=ACCOUNTS) value = mod
els.CharField(max_length=100) user_profile = models.ForeignKey(User, related_name="social", on_delete=models.CASCADE) class UserProperty(Property): user_profile = models.ForeignKey(User, related_name="properties", on_delete=models.CASCADE) def create_profile(sender, **kargs): if kargs.get("created", F...
r-rathi/ckt-apps
bin/report_net.py
Python
mit
2,251
0.01466
#!/usr/bin/env python #------------------------------------------------------------------------------- import os import
sys bin_dir = os.path.dirname(os.path.abspath(__file__)) pkg_dir = os.path.abspath(os.path.join(bin_dir, "..")) sys.path.append(pkg_dir) #------------------------------------------------------------------------------- import argparse import c
ollections import cktapps from cktapps import apps from cktapps.formats import spice #------------------------------------------------------------------------------- def main(args=None): parser = argparse.ArgumentParser(description="Report net capacitances " "and f...
DazWorrall/ansible
lib/ansible/modules/network/aci/aci_filter_entry.py
Python
gpl-3.0
10,104
0.003068
#!/usr/bin/python # -*- coding: utf-8 -*- # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], ...
ed to set the destination end port when ip_protocol is tcp or udp. choices: [ Valid TCP/UDP Port Ranges] d
st_port_start: description: - Used to set the destination start port when ip_protocol is tcp or udp. choices: [ Valid TCP/UDP Port Ranges] entry: description: - Then name of the Filter Entry. aliases: [ entry_name, name ] ether_type: description: - The Ethernet type. choices: [ a...
Spoken-tutorial/spoken-website
events/migrations/0022_auto_20171023_1505.py
Python
gpl-3.0
2,412
0.002488
# -*- coding: utf-8 -*- from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('events', '0021_auto_20171023_1358'), ] operations = [ migrations.AlterField( model_name='inductioninterest', name='age', field=...
model_name='inductioninterest', name='medium_of_studies', field=models.CharField(max_length=100, choices=[(b'', b'-----'), (b'English', b'English'), (b'Other', b'Other')]), ), migrations.AlterField
( model_name='inductioninterest', name='phonemob', field=models.CharField(max_length=100), ), migrations.AlterField( model_name='inductioninterest', name='specialisation', field=models.CharField(max_length=100, choices=[(b'', b'----...
RocioDSI/Carta-Servicios-STIC
servicios/GeneraNagios.py
Python
agpl-3.0
2,787
0.024408
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2014-2015 # # STIC - Universidad de La Laguna (ULL) <gesinv@ull.edu.es> # # This file is part of Modelado de Servicios TIC. # # Modelado de Servicios TIC is free software: you can redistribute it and/or modify it under # t
he terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Modelado de Servicios TIC is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied wa...
y of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Modelado de Servicios TIC. If not, see # <http://www.gnu.org/licenses/>. # import funcione...
jwessel/meta-overc
meta-cube/recipes-support/overc-system-agent/files/overc-system-agent-1.2/run_server.py
Python
mit
11,160
0.007437
#!/usr/bin/python import sys, getopt, os, urllib2 import Overc from flask import Flask from flask import jsonify from flask import request from flask_httpauth import HTTPBasicAuth from passlib.context import CryptContext app = Flask(__name__) # Password hash generation with: #python<<EOF #from passlib.context import...
de" force=True overc._system_upgrade(template, reboot, force, skipscan, skip_del) return json_msg(overc.message) @app.route('/host/rollback') @auth.login_required def host_rollback(): overc=Overc.Overc() overc.host_rollback() return json_msg(overc.message) @app.route('/host/upgrade') @auth...
rc() reboot_s = request.args.get('reboot') force_s = request.args.get('force') reboot=False force=False if reboot_s == "True": print "do reboot" reboot = True if force_s == "True": print "do force to upgrade" force=True overc._host_upgrade(reboot, force) return ...
craigderington/django-code-library
snippets/admin.py
Python
gpl-3.0
978
0.005112
from django.contrib import admin from . import models from django_markdown.admin import MarkdownModelAdmin from django_markdown.widgets import AdminMarkdownWidget from django.db.models import TextField # Register your models here. class SnippetTagAdmin(admin.ModelAdmin): list_display = ('slug',) class SnippetAdm...
e Information', {'fields': ['modified_date'], 'classes': ['collapse']}), ('Tag Library', {'fields': ['snippet_tags']}) ] list_display = ('snippet_title', 'author', 'create_date', 'modified_date') search
_fields = ['snippet_title'] formfield_overrides = {TextField: {'widget': AdminMarkdownWidget}} list_filter = ['create_date', 'publish'] # register the classes with the Admin site admin.site.register(models.Snippet, SnippetAdmin) admin.site.register(models.SnippetTag, SnippetTagAdmin)
roberthodgen/thought-jot
src/api_v2.py
Python
mit
37,593
0.000718
""" The MIT License (MIT) Copyright (c) 2015 Robert Hodgen 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...
.out.write(json.dumps(response_object)) def delete(self, project_id, contributor_email): """ Remove Contributors from this Project. """ response_object = {} user = users.get_current_user() if not user: self.abort(401) # Get JSON request body if not projec...
roject_id) if not project_key: self.abort(400) project = project_key.get() if not (project and isinstance(project, model.Project)): self.abort(404) if not project.is_owner(user.email): self.abort(401) project.remove_contributors([contributor_em...
hardingnj/xpclr
setup.py
Python
mit
1,538
0.0013
from setuptools import setup from ast import literal_eval def get_version(source='xpclr/__init__.py'): with open(source) as sf: for line in sf: if line.
startswith('__version__'): return literal_eval(line.split('=')[-1].lstrip()) raise ValueError("__version__ not found") VERSION = get_version() DISTNAME = 'xpclr' PACKAGE_NAME = 'xpclr' DESCRIPTION = 'Co
de to compute xpclr as described in Chen 2010' with open('README.md') as f: LONG_DESCRIPTION = f.read() MAINTAINER = 'Nicholas Harding', MAINTAINER_EMAIL = 'nicholas.harding@bdi.ox.ac.uk', URL = 'https://github.com/hardingnj/xpclr' DOWNLOAD_URL = 'http://github.com/hardingnj/xpclr' LICENSE = 'MIT' # strictly...
bioothod/zbuilder
conf.d/deb_install_build_deps.py
Python
apache-2.0
3,249
0.004925
#!/usr/bin/python import apt import apt.progress import apt_pkg import logging import re import sys logging.basicConfig(filename1='/var/log/supervisor/rps.log', format='%(asctime)s %(levelname
)s: deb_install: %(message)s', level=logging.INFO) logging.getLogger().setLevel(logging.INFO) class control_parser(): def __init__(self): apt_pkg.init() self.cache = apt.Cache() self.cache.update() self.cache.open() def parse(self, path = 'debian/control'): try:...
devtronics/heck_site
polls/models.py
Python
agpl-3.0
953
0.002099
from django.db import models from django.utils import timezone import datetime class Question(models.Model): """ Question object model """ question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(self): # __unicode__ on Pyt...
unicode__ on Python 2 retu
rn self.choice_text
glukolog/calc256
cgserial.py
Python
gpl-3.0
673
0.007429
#!/usr/bin/python import simplejson as json i = open('/proc/cpuinfo') my_text = i.readlines() i.close() username
= "" for line in my_text: line = line.strip() ar = line.split(' ') if ar[0].startswith('Serial'): username = "a" + ar[1] if not username: exit(-1) o = open('/home/pi/.cgminer/cgminer.conf', 'w'); pools = [] pools.append({"url": "stratum+tcp://ghash.io:3333", "user": username,...
"api-listen" : "true", "api-port" : "4028", "api-allow" : "W:127.0.0.1"} txt = json.dumps(conf, sort_keys=True, indent=4 * ' ') o.write(txt) o.write("\n"); o.close()
dwillis/fumblerooski
urls.py
Python
bsd-3-clause
1,591
0.005657
from django.conf.urls.defaults import * from django.contrib import admin from fumblerooski.feeds import CoachesFeed feeds = { 'coaches': CoachesFeed, } admin.autodiscover() urlpatterns = patterns('', url(r'^admin/coach_totals/', "fumblerooski.college.views.admin_coach_totals"), url(r'^admin/doc/', incl...
ame="coach_vs"),
url(r'^coaches/detail/(?P<coach>\d+-[-a-z]+)/vs/(?P<coach2>\d+-[-a-z]+)/$', 'coach_compare', name="coach_compare"), url(r'^coaches/assistants/$', 'assistant_index'), url(r'^coaches/common/(?P<coach>\d+-[-a-z]+)/(?P<coach2>\d+-[-a-z]+)/$', 'coach_common'), url(r'^coaches/departures/(?P<year>\d\d\d\d)/...
hilgroth/fiware-IoTAgent-Cplusplus
tests/e2e_tests/common/gw_configuration.py
Python
agpl-3.0
1,230
0.017073
# -*- coding: utf-8 -*- ''' (c) Copyright 2013 Telefonica, I+D. Printed in Spain (Europe). All Rights Reserved. The copyright to the software program(s) is property of Telefonica I+D. The program(s) may be used and or copied only with the express written consent of Telefonica I+D or in accordance with the terms...
'http://{}:{}'.format(GW_HOSTNAME, MANAGER_PORT) CBROKER_URL='http://10.95.213.159:6500' CBROKER_HEADER='Fiware-Service' CBROKER_PATH_HEADER='Fiware-ServicePath' SMPP_URL='http://sbc04:5371' SMPP_FROM='682996050' DEF_ENTITY_TYPE='thing' DEF_TYPE='string' PATH_UL20_COMMAND='/iot/ngsi/d/updateContext' PATH_MQTT_...
Context' PATH_UL20_SIMULATOR='/simulaClient/ul20Command' TIMEOUT_COMMAND=10 MQTT_APIKEY='1234' UL20_APIKEY='apikey3'
mbr/tinyrpc
tests/test_server.py
Python
mit
1,748
0.006293
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from unittest.mock import Mock, call from tinyrpc.server import RPCServer from tinyrpc.transports import ServerTransport from tinyrpc.protocols import RPCProtocol, RPCResponse from tinyrpc.dispatch import RPCDispatcher CONTEXT='sapperdeflap' RECMSG='out of...
d_with(CONTEXT, SERMSG) def test_handle_message_callback(transport, protocol, dispatcher): server = RPCServer(transport, protocol, dispatcher) server.trace = Mock(return_value=None) server.receive_one_message() assert server.trace.call_args_list == [cal
l('-->', CONTEXT, RECMSG), call('<--', CONTEXT, SERMSG)] server.trace.assert_called()
woutdenolf/wdncrunch
wdncrunch/tests/__init__.py
Python
mit
1,226
0.000816
# -*- coding: utf-8 -*- # # Copyright (C) 2017 European Synchrotron Radiation Facility, Grenoble, France # # Principal author: Wout De Nolf (wout.de_nolf@esrf.eu) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software")...
sion notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #...
N OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE.
kaushik94/sympy
examples/advanced/grover_example.py
Python
bsd-3-clause
2,081
0.001442
#!/usr/bin/env python """Grover's quantum search algorithm example.""" from sympy import pprint from sympy.physics.quantum import qapply from sympy.physics.quantum.qubit import IntQubit from sympy.physics.quantum.grover import (OracleGate, superposition_basis, WGate, grover_iteration) def demo_vgate_app(v):...
leGate(nqubits, black_box) print('Oracle or v = OracleGate(%r, black_box)' % nqubits) print() print('iter1 = grover.grover_iteration
(psi, v)') iter1 = qapply(grover_iteration(psi, v)) pprint(iter1) print() print('iter2 = grover.grover_iteration(iter1, v)') iter2 = qapply(grover_iteration(iter1, v)) pprint(iter2) print() if __name__ == "__main__": main()
jaantollander/Convergence-of-Fourier-Series
src_legacy/fourier_series/basis_functions/legendre/fast_evaluation.py
Python
mit
1,726
0
# coding=utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np import numba from src_legacy.fourier_series.buffer.ringbuffer import Ringbuffer @numba.vectorize(nopython=True) def legendre_recursio...
f isinstance(arg, float): self.arg = arg self.size = 1 else: raise ValueError() self.max_degree = max_degree # @profile def generator(self, skip=0): buffer = Ringbuffer(buffer_size=3, array_size=self.size, ...
array_size_increment=None, array_margin=0) deg = self.start_index while self.max_degree is None or deg <= self.max_degree - 1: p1 = buffer[deg - 1, :] p2 = buffer[deg - 2, :] arr = legendre_recursion(deg, self.arg, p1, p2) # ~...
samizdatco/corduroy
corduroy/config.py
Python
bsd-3-clause
1,593
0.009416
# encoding: utf-8 """ corduroy.config Internal state """ from __future__ import with_statement import os, sys from .atoms import odict, adict, Document # LATER: add some sort of rcfile support... # from inspect import getouterframes, currentframe # _,filename,_,_,_,_ = getouterframes(currentframe())[-1] # print "fro...
types.dict, **opts) @classmethod def encode(cls, obj, **opts): """Encode the given object as a JSON string.
:param obj: the Python data structure to encode :type obj: object :return: the corresponding JSON string :rtype: basestring """ return _json.dumps(obj, allow_nan=False, ensure_ascii=False, encoding='utf-8', **opts)
Havate/havate-openstack
proto-build/gui/horizon/Horizon_GUI/openstack_dashboard/dashboards/project/database_backups/tables.py
Python
apache-2.0
3,772
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Rackspace Hosting # # 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...
): return if hasattr(obj.instance, 'name'): return reverse( 'horizon:project:databases:detail', kwargs={'instance_id': obj.instance_id
}) def db_name(obj): if hasattr(obj.instance, 'name'): return obj.instance.name return obj.instance_id class BackupsTable(tables.DataTable): name = tables.Column("name", link=("horizon:project:database_backups:detail"), verbose_name=_("Name")) ...
ellmetha/django-machina
machina/apps/forum_conversation/forum_attachments/models.py
Python
bsd-3-clause
346
0.00578
"""
Forum attachme
nts models ======================== This module defines models provided by the ``forum_attachments`` application. """ from machina.apps.forum_conversation.forum_attachments.abstract_models import AbstractAttachment from machina.core.db.models import model_factory Attachment = model_factory(AbstractAttachme...
mozilla/remo
remo/profiles/tests/test_forms.py
Python
bsd-3-clause
4,057
0.000739
from nose.tools import eq_, ok_ from remo.base.tests import RemoTestCase from remo.base.utils import get_date from remo.profiles.forms import ChangeUserForm, UserStatusForm from remo.profiles.models import UserStatus from remo.profiles.tests import UserFactory, UserStatusFactory class ChangeUserFormTest(RemoTestCase...
cted_date': expected_date} form = UserStatus
Form(data, instance=UserStatus(user=user)) ok_(form.is_valid()) db_obj = form.save() eq_(db_obj.expected_date, get_date(days=1)) eq_(db_obj.user.get_full_name(), user.get_full_name()) def test_invalid_expected_date(self): mentor = UserFactory.create() user = UserFact...
pearu/f2py
fparser/api.py
Python
bsd-3-clause
7,543
0.006364
"""Public API for Fortran parser. Module content -------------- """ from __future__ import absolute_import #Author: Pearu Peterson <pearu@cens.ioc.ee> #Created: Oct 2006 __autodoc__ = ['get_reader', 'parse', 'walk'] from . import Fortran2003 # import all Statement classes: from .base_classes import EndStatement, cla...
content until a line ``*/`` is found. See also -------- parse """ import os import re from .readfortran import FortranFileRe
ader, FortranStringReader if os.path.isfile(input): name,ext = os.path.splitext(input) if ext.lower() in ['.c']: # get signatures from C file comments starting with `/*f2py` and ending with `*/`. # TODO: improve parser to take line number offset making line numbers in ...
Pysellus/streaming-api-test
rx-tests/rx-stream-pacing.py
Python
mit
1,709
0.004096
#!/usr/bin/env pyt
hon3 ''' Make a stream emit at the pace of
a slower stream Pros: Introduce a delay between events in an otherwise rapid stream (like range) Cons: When the stream being delayed runs out of events to push, the zipped stream will keep pushing events, defined with the lambda fn passed to the zip operation. ''' from time import sleep from rx ...
ProfessionalIT/maxigenios-website
sdk/google_appengine/google/appengine/cron/GrocParser.py
Python
mit
29,691
0.00906
#!/usr/bin/env python # # Copyright 2007 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 required by applicable law o...
TH_OR_FIFTH)) : alt1 = 1 else: nvae = NoViableAltException("", 1, 0, self.input) raise nvae if alt1 == 1: pass self._state.following.append(self.FOLLOW_specifictime_in_timespec44) ...
self.specifictime() self._state.following.pop() elif alt1 == 2: pass self._state.following.append(self.FOLLOW_interval_in_timespec48) self.interval() self._state.following.pop() ...
eduNEXT/edunext-platform
import_shims/studio/contentstore/management/commands/tests/test_sync_courses.py
Python
agpl-3.0
491
0.010183
"""Deprecated import support. Auto-generated by import_shims/generate_shims.sh.""" # pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression
,line-too-long from import_shims.warn import warn_deprecated_import warn_deprecated_import('contentstore.management.commands.tests.test_sync_courses', 'cms.djangoapps.contentstore.management.commands.tests.test_sync_courses') from cms.djangoapps.contents
tore.management.commands.tests.test_sync_courses import *
vaquerizaslab/tadtool
tadtool/plot.py
Python
mit
28,848
0.002634
from __future__ import division, print_function from abc import ABCMeta, abstractmethod import matplotlib as mpl mpl.use('TkAgg') from matplotlib.ticker import MaxNLocator, Formatter, Locator from matplotlib.widgets import Slider, Button import matplotlib.patches as patches import matplotlib.pyplot as plt from matplotl...
in, tmax, minorstep) + t0 cond = np.abs((locs - t0) % majorstep) > minorstep / 10.0 locs = locs.compress(cond) else: locs = [] return self.raise_if_exceeds(np.array(locs)) class BasePlotter1D(BasePlotter): __metaclass__ = ABCMeta def __init__(self, title):...
if isinstance(region, string_types): region = GenomicRegion.from_string(region) if ax: self.ax = ax # set genome tick formatter self.ax.xaxis.set_major_formatter(GenomeCoordFormatter(region)) self.ax.xaxis.set_major_locator(GenomeCoordLocator(nbins=5)) ...
saloni10/librehatti_new
src/authentication/models.py
Python
gpl-2.0
1,479
0.00879
from django.db import models from django.contrib.auth.models import User class OrganisationType(models.Model): type_desc = models.CharField(max_length=200) def __unicode__(self): return self.type_desc class Address(models.Model): street_address = models.CharField(max_length=100) city = model...
max_length=140) class Meta: abstract = True class AdminOrganisations(HattiUser): title = models.CharField(max_length=200) organisation_type = models.ForeignKey(OrganisationType) def
__unicode__(self): return self.title class Customer(HattiUser): title = models.CharField(max_length=200, blank=True, null=True) is_org = models.BooleanField(); org_type = models.ForeignKey(OrganisationType) company = models.CharField(max_length = 200) def __unicode__(self, arg): return un...
stscieisenhamer/ginga
ginga/examples/gtk/example2_gtk.py
Python
bsd-3-clause
8,631
0.00139
#! /usr/bin/env python # # example2_gtk.py -- Simple, configurable FITS viewer. # # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # from __future__ import print_function import sys, os import logging, logging.handler
s from ginga import AstroImage from ginga.gtkw import GtkHelp from ginga.gtkw.ImageViewGtk import CanvasView from ginga.canvas.CanvasObject import get_canvas_types from ginga import colors from ginga.misc import log import gtk STD_FORMAT = '%(asctime)s | %(levelname)1.1s | %(filename)s:%(lineno)d (%(funcName)s) | %(...
logger): self.logger = logger self.drawcolors = colors.get_colors() self.dc = get_canvas_types() root = gtk.Window(gtk.WINDOW_TOPLEVEL) root.set_title("Gtk2 CanvasView Example") root.set_border_width(2) root.connect("delete_event", lambda w, e: quit(w)) ...
le9i0nx/ansible
test/units/modules/network/mlnxos/mlnxos_module.py
Python
gpl-3.0
2,693
0.001485
# (c) 2016 Red Hat Inc. # # 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 later version. # # Ansible is dis...
thout even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOS
E. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type imp...
pankshok/xoinvader
xoinvader/utils.py
Python
mit
3,433
0
"""Various useful tools.""" import copy import datetime import logging # FIXME: temporary backward compatibility from eaf.core import Vec3 as Point LOG_FORMAT = ( "[%(asctime)s] %(levelname)-8s %(name)s[%(funcName)s]:%(lineno)s: " "%(message)s" ) """Log message format string.""" TIME_FORMAT = "%H:%M:%S,%03...
rmatter(formatter) logger.addHandler(handler) date = datetime.date.today().strftime(DATE_FORMAT) logger.info("*** (%s) Initializing XOInvader ***", date) return logger def clamp(val, min_val, max_val): """Clamp value between boundaries.""" if max_val < min_val: raise ValueError("max_...
n(max(val, min_val), max_val) class dotdict(dict): # pylint: disable=invalid-name """Container for dot elements access.""" def __init__(self, *args, **kwargs): super(dotdict, self).__init__(*args, **kwargs) self.__dict__ = self self._wrap_nested() def _wrap_nested(self): ...
vsergeyev/os2online
desktop/desktop_items.py
Python
mit
3,022
0.009927
# -*- coding: utf-8 -*- import json from flask import jsonify from flask import render_template, request, url_for, redirect import time, random #------------------------------------------------------------------------------ def get_desktop_items_data(): """ Returns items for Desktop in JSON array: t
itle """ items = [ {'title': 'OS/2 System', 'icon': '/appmedia/imgs/system_folder.png', 'left': '0px', 'top': '40px', 'action': '/system_folder/'}, {'title': 'Information', 'icon': '/
appmedia/imgs/help.png', 'left': '0px', 'top': '120px', 'action': '/appmedia/help/desktop.html'}, {'title': 'Virtual PC', 'icon': '/appmedia/imgs/system/minimized.png', 'left': '0px', 'top': '200px', 'action': '/'}, {'title': 'WebExplorer', 'icon': '/appmedia/imgs/web/explore.gif', 'left': '0p...
fthuin/artificial-intelligence
assignment3/Code/zipremise/SimpleHTTPServer.py
Python
mit
238
0
#!/u
sr/bin/env python3 from http.server import HTTPServer, CGIHTTPRequestHandler port = 8000 httpd = HTTPServer(('', port), CGIHTTPRequestHandler) print("Starting simple_httpd on port: " + str(httpd.server_port)) httpd.serv
e_forever()
mancoast/CPythonPyc_test
cpython/266_test_strftime.py
Python
gpl-3.0
6,966
0.004594
""" Unittest for time.strftime """ import calendar import sys import os import re from test import test_support import time import unittest # helper functions def fixasctime(s): if s[8] == ' ': s = s[:8] + '0' + s[9:] return s def escapestr(text, ampm): """ Escape text to deal with possible ...
dered using fieldwidth'), ) for e in nonstandard_expectations: try: result = time.strftime(e[0], now) except ValueError, result: msg = "Error for nonstandard '
%s' format (%s): %s" % \ (e[0], e[2], str(result)) if test_support.verbose: print msg continue if re.match(escapestr(e[1], self.ampm), result): if test_support.verbose: print "Supports nonstandard ...
ckot/django-namespaced-session
setup.py
Python
mit
1,469
0.000681
# pylint: disable=I0011,C0301 from __future__ import absolute_import, unicode_literals import os from setuptools import find_packages, setup from namespaced_session import __version__ with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run fr...
sion=__version__, packages=find_packages(exclude=['tests']), include_package_data=True, test_suite="runtests.main", license='MIT', description='Django app which makes it easier to work with dictionaries in sessions', long_description=README, url='https://github.com/ckot/django-namespaced-ses...
l.com', classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Framework :: Django :: 1.7', 'Framework :: Django :: 1.8' 'Framework :: Django :: 1.9' 'Framework :: Django :: 1.10', 'Intended Audience :: Developers', 'License :: OSI App...
jamesfolberth/NGC_STEM_camp_AWS
notebooks/data8_notebooks/lab03/tests/q3_2.py
Python
bsd-3-clause
530
0.003774
test = { 'name': '', 'points': 1, 'suites': [ { 'cases': [ {
'code': r""" >>> type(imdb_by_year) == tables.Table True >>> imdb_by_year.column('Title').take(range(3)) array(['The Kid (1921)', 'The Gold Rush (1925)', 'The General (192
6)'], dtype='<U75') """, 'hidden': False, 'locked': False }, ], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest' } ] }
GabrielNicolasAvellaneda/riak-python-client
commands.py
Python
apache-2.0
15,906
0.000063
""" distutils commands for riak-python-client """ from distutils import log from distutils.core import Command from distutils.errors import DistutilsOptionError from subprocess import Popen, PIPE from string import Template import shutil import re import os.path __all__ = ['create_bucket_types', 'setup_security', 'en...
h to the riak-admin script') ] _props = { 'pytest-maps': {'datatype': 'map'}, 'pytest-sets': {'datatype': 'set'}, 'pytest-counters': {'datatype': 'counter'}, 'pytest-consistent': {'consistent': True}, 'pytest-mr': {}, 'pytest': {'allow_mult': False} } de...
ptions(self): if self.riak_admin is None: raise DistutilsOptionError("riak-admin option not set") def run(self): if self._check_available(): for name in self._props: self._create_and_activate_type(name, self._props[name]) def check_output(self, *args, **...
laslabs/odoo-connector-carepoint
connector_carepoint/tests/test_carepoint_import_mapper.py
Python
agpl-3.0
1,081
0
# -*- coding: utf-8 -*- # Copyright 2015-2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.addons.connector_carepoint.unit import mapper from .common import SetUpCarepointBase class TestCarepointImporterMapper(SetUpCarepointBase): def setUp(self): super(Te...
self.model ) self.importer = self.Importer(self.mock_env) def test_backend_id(self): """ It should map backend_id correctly """ res = self.importer.backend_id(True) expect = {'backend_id': self.importer.backend_record.id} self.assertDictEqual(expect, res) ...
est_company_id(self): """ It should map company_id correctly """ res = self.importer.company_id(True) expect = {'company_id': self.importer.backend_record.company_id.id} self.assertDictEqual(expect, res)
christianurich/VIBe2UrbanSim
3rdparty/opus/src/opus_gui/abstract_manager/models/xml_model.py
Python
gpl-2.0
21,520
0.002556
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from PyQt4.QtCore import Qt, QVariant, SIGNAL, QModelIndex, QAbstractItemModel from PyQt4.QtCore import QString from PyQt4.QtGui import QColor, QIcon, QStyle, QMessageBox from PyQt4.Qt import qApp # Fo...
tem = self._root_item else: item = parent_index.internalPointer() return len(item.child_items) def remove_node(self, node): ''' Convenience method to remove a node without bothering with the internal model representation
@param node (Element): Node to remove. ''' index = self.index_for_node(node) row = index.row() parent_index = self.parent(index) self.removeRow(row, parent_index) def removeRow(self, row, parent_index): ''' Removes an object from the data model ...
elasticsales/quotequail
setup.py
Python
mit
1,101
0.000908
from setuptools import setup setup( name='quotequail', version='0.2.3', url='http://github.com/closeio/quotequail', license='MIT', author='Thomas Steinacher', author_email='engineering@close.io', maintainer='Thomas Steinacher', maintainer_email='engineering@close.io', description='A...
='any', classifiers=[ 'Environment :: Web Environment',
'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3'...
twistedretard/LaserSimulatedSecurityTurret
src/turret/camera.py
Python
mit
620
0.001613
#!/usr/bin/env python # -*- coding: utf-8 -*- import time class CameraClass(object): ''' docstring for CameraClass ''' def __init__(self): super(CameraClass, self).__init__() def
visible_target(self): ''' Returns true if target is visible ''' return True if __name__ == '__main__': try: from picamera import PiCamera camera = PiCamera() try: camera.start_preview() time.sleep(10) camera.stop_previe...
pass
natedileas/ImageRIT
Server/qt_main.py
Python
gpl-3.0
762
0.002625
import sys import socket from PyQt5.QtWidgets import QApplication from qt_DisplayWindow import DisplayWindow from Server import Server def main(camID): hostname = socket.gethostname() ip_address = socket.gethostbyname_ex(hostname)[2][-1] print(hostna
me, ip_address) port = 12349 app = QApp
lication(sys.argv) server = Server(ip_address, port) # set up main display window display = DisplayWindow(camID, server.get_state) display.show() # connect server -> display slots server.selfie.connect(display.selfie) server.email.connect(display.email) server.status.connect(display.s...
nasfarley88/dicebeard
python/dicebeard/skb_roll/beardeddie.py
Python
unlicense
1,060
0
import os from pathlib import Path from PIL import Image import pyconfig import pydice class ImageNotSupported(Exception): pass class BeardedDie: def __init__(self, die): self.die = die # Time to strap our to_image to pydice's Die if pyconfig.get('dicebeard.images_path'): ...
'{}.png'.format(self.result)) try:
return Image.open(str(die_image_path)) except FileNotFoundError: raise ImageNotSupported( '{} is not currently supported.'.format(self.name))
pizzapanther/Church-Source
churchsource/people/migrations/0013_auto__add_field_group_auth.py
Python
gpl-3.0
6,849
0.008906
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Group.auth' db.add_column('people_group', 'auth', self.gf('django.db.models.fields.Boolean...
': ('django.db.models.fields.CharField', [], {'max_length': '25'}) }, 'people.group': { 'Meta': {'ordering': "('name',)", 'object_name': 'Group'}, 'auth': ('django.db.models.fields.BooleanField', [], {'default':
'True'}), 'desc': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'gtype': ('django.db.models.fields.CharField', [], {'default': "'general'", 'max_length': '10'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'Tru...
anselmobd/fo2
src/base/queries/models.py
Python
mit
391
0
from pprint import pprint from base.models import Colaborador def get_create_colaborad
or_by_user(user): try: colab = Colaborador.objects.get(user__username=user.username) except Colaborador.DoesNotExist: colab = Colaborador( user=user, matricula=72000+user.id,
cpf=72000+user.id, ) colab.save() return colab
LICEF/edx-platform
cms/djangoapps/contentstore/views/checklist.py
Python
agpl-3.0
6,004
0.002665
import json import copy from util.json_request import JsonResponse from django.http import HttpResponseBadRequest from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_http_methods from django_future.csrf import ensure_csrf_cookie from edxmako.shortcuts import rende...
{ 'handler_url': handler_url, # context_course is used by analytics 'context_course': course_module, 'checklists':
expanded_checklists }) elif json_request: # Can now assume POST or PUT because GET handled above. if checklist_index is not None and 0 <= int(checklist_index) < len(course_module.checklists): index = int(checklist_index) persisted_checkli...
chocjy/randomized-quantile-regression-solvers
hadoop/src/gen_id.py
Python
apache-2.0
97
0.010309
import numpy as np import sys R = np.eye(int(sys.argv[2])) np.savetxt
(sys.arg
v[1]+'/R.txt', R)
TuSimple/simpledet
config/dcn/faster_dcnv2_r50v1bc4_c5_512roi_1x.py
Python
apache-2.0
7,639
0.004451
from symbol.builder import FasterRcnn as Detector from models.dcn.builder import DCNResNetC4 as Backbone from symbol.builder import Neck from symbol.builder import RpnHead from symbol.builder import RoiAlign as RoiExtractor from symbol.builder import BboxC5V1Head as BboxHead from mxnext.complicate import normalizer_fac...
_factory(type="fixbn") class BackboneParam: fp16 = General.fp16 normalizer = NormalizeParam.normalizer depth = 50 num_c3_block = 4 num_c4_block = 6 class NeckParam: fp16 = General.fp16 normalizer = Norm
alizeParam.normalizer class RpnParam: fp16 = General.fp16 normalizer = NormalizeParam.normalizer batch_image = General.batch_image class anchor_generate: scale = (2, 4, 8, 16, 32) ratio = (0.5, 1.0, 2.0) stride = 16 image_anchor = 25...
fermat618/pida
pida/ui/views.py
Python
gpl-2.0
1,810
0.001105
# -*- coding: utf-8 -*- """ :copyright: 2005-2008 by The PIDA Project :license: GPL 2 or later (see README/COPYING/LICENSE) """ import gtk from pygtkhelpers.delegates import SlaveView # locale from pida.core.locale import Locale locale = Locale('pida') _ = locale.gettext class PidaView(SlaveView): # ...
turn False gladefile = None def __init__(self, service, title=None, icon=None, *args, **kw): if not self.builder_file: self.builder_file = self.gladefile self.svc = service self.label_text = tit
le or self.label_text self.icon_name = icon or self.icon_name if self.key: pass #self.toplevel.set_name(self.key.replace(".", "_")) super(PidaView, self).__init__() def get_toplevel(self): return self.widget toplevel = property(get_toplevel) def add...
DailyActie/Surrogate-Model
01-codes/tensorflow-master/tensorflow/python/client/notebook.py
Python
mit
4,766
0.002098
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
o start kernel # subprocesses. IS_KERNEL = len(sys.argv) > 1 and sys.argv[1] == "kernel" def main(unused_argv): sys.argv = ORIG_ARGV if not IS_KERNEL: # Drop all flags. sys.argv = [sys.argv[0]] # NOTE(sadovsky): For some reason, putting this import at the top level # breaks in...
tml.notebookapp import NotebookApp # pylint: disable=g-import-not-at-top notebookapp = NotebookApp.instance() notebookapp.open_browser = True # password functionality adopted from quality/ranklab/main/tools/notebook.py # add options to run with "password" if FLAGS.password: ...
iulian787/spack
var/spack/repos/builtin/packages/r-evd/package.py
Python
lgpl-2.1
597
0.00335
# Copyright
2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for detail
s. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class REvd(RPackage): """evd: Functions for Extreme Value Distributions""" homepage = "https://cloud.r-project.org/package=evd" url = "https://cloud.r-project.org/src/contrib/evd_2.3-3.tar.gz" list_url = "https://cloud.r-pr...
demis001/scikit-bio
skbio/util/tests/test_decorator.py
Python
bsd-3-clause
9,694
0.000103
# ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # --------------------------------------------...
" Parameters") self.assertTrue(f.__doc__.startswith(e1)) def test_function_signature(self): f = self._get_f('0.1.0') expected = inspect.ArgSpec( args=['x', 'y'], varargs=None, keywords=None, defaults=(42,)) self.a
ssertEqual(inspect.getargspec(f), expected) self.assertEqual(f.__name__, 'f') def test_missing_kwarg(self): self.assertRaises(ValueError, stable) self.assertRaises(ValueError, stable, '0.1.0') class TestExperimental(TestStabilityState): def _get_f(self, as_of): def f(x, y=42)...
ProReNata/django-castle
setup.py
Python
bsd-3-clause
1,596
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import django_castle try: from setuptools import setup except ImportError: from distutils.core import setup version = django_castle.__version__ if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') os.system('pytho...
ta=True, install_requires=[ ], license="BSD", zip_safe=False, keywords='django-castle', classifiers=[ 'Development Sta
tus :: 3 - Alpha', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python ::...
redpawfx/massiveImporter
python/ns/bridge/io/WReader.py
Python
mit
2,920
0.037329
# The MIT License # # Copyright (c) 2008 James Piechota # # 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, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substan...
seakers/daphne_brain
daphne_context/migrations/0011_auto_20201109_1100.py
Python
mit
1,011
0.002967
# Generated by Django 2.2.11 on 2020-11-09 17:00 import daphne_context.utils from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
True, primary_key=True, serialize=False, verbose_name='ID')), ('mycroft_session', models.CharField(default=daphne_context.utils.generate_mycroft_session, max_length=9)), ('user', models.OneToOneField(on_de
lete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
emory-libraries/findingaids
findingaids/fa/migrations/0001_initial.py
Python
apache-2.0
1,937
0.004646
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Archive', fields=[ ('id', models.AutoField(verb...
('name', models.CharField(help_text=b'repository name (subarea) in EAD to identify finding aids associated with this archive', max_length=255)), ('svn', models.URLField(help_text=b'URL to subversion repository containing EAD for this archive', verbose_name=b'Subversion Repository')), ('...
do not modify after initial archive definition)')), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Deleted', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created...
SiLab-Bonn/pyBAR
pybar/scans/scan_crosstalk.py
Python
bsd-3-clause
6,325
0.004111
import logging import inspect import numpy as np from pybar.analysis.analyze_raw_data import AnalyzeRawData from pybar.fei4.register_utils import invert_pixel_mask, make_xtalk_mask, make_pixel_mask from pybar.fei4_run_base import Fei4RunBase from pybar.fei4.register_utils import scan_loop from pybar.run_manager impor...
"scan_parameters": [('PlsrDAC', [None, 800])], # the PlsrDAC range "step_size": 10, # step size of the PlsrDAC during scan
"use_enable_mask": False, # if True, use Enable mask during scan, if False, all pixels will be enabled "enable_shift_masks": ["Enable"], # enable masks shifted during scan "disable_shift_masks": [], # disable masks shifted during scan "xtalk_shift_mask": ["C_High", "C_Low"], # crosstalk mask...
alexisbellido/programming-in-python
parse_file.py
Python
bsd-3-clause
1,192
0.00755
#!/usr/bin/env
python """ Parse a file and write output to another. """ from optparse import OptionParser import re from collections import OrderedDict parser = OptionParser() parser.add_option("
-i", "--input", dest="input_filepath", help="input filepath") parser.add_option("-o", "--output", dest="output_filepath", help="output filepath") (options, args) = parser.parse_args() #print options #print args input_filepath = options.input_filepath output_filepath = options.output_filepath lines = {} pattern_key ...
selvagit/experiments
nptel/nptel_programming_data_structure/week_1/q3.py
Python
gpl-3.0
97
0.082474
def f(m,n):
ans = 1 while (m - n >= 0): (ans,m) = (ans*2,m-n) return
(ans)
bitcraft/pyglet
tests/interactive/window/event_resize.py
Python
bsd-3-clause
801
0
"""Test that resize event works correctly. Expected behaviour: One window will be opened. Resize the window and ensure that the dimensions printed to the terminal are correct. You should see a green border inside the window but no red. Close the window or press ESC to end the test. """ import unit...
= w
indow.Window(200, 200, resizable=True) w.push_handlers(self) while not w.has_exit: w.dispatch_events() window_util.draw_client_border(w) w.flip() w.close()
uwosh/uwosh.themebase
uwosh/themebase/browser/interfaces.py
Python
gpl-2.0
138
0.014493
from zope.interface import Interface class IUWOshTheme
Layer(Interface): """ Marker int
erface that defines a browser layer """
anandology/pyjamas
library/gwt/ui/UIObject.py
Python
apache-2.0
10,085
0.002776
# Copyright 2006 James Tauber and contributors # Copyright (C) 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net> # # 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/...
of attr:value pairs """ if isinstance(attribute, basestring): return DOM.getStyleAttribute(self.getElement(), attribute) # if attribute is not a string, assume it is iterable, # and return the multi-attribute form el = self.getElement(...
or attr in attribute: result[attr] = DOM.getStyleAttribute(el,attr) return result def getTitle(self): return DOM.getAttribute(self.element, "title") def setElement(self, element): """Set the DOM element associated with the UIObject.""" self.element = element de...
johnson1228/pymatgen
pymatgen/io/lammps/tests/test_sets.py
Python
mit
2,130
0.000469
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, print_function, unicode_literals, \ absolute_import import os import unittest from pymatgen.io.lammps.sets import LammpsInputSet __author__ = 'Kiran Mathew' __email__ = '...
ass TestLammpsInputSet(unittest.TestCase): def setUp(self): template_file = os.path.join(test_dir, "in.peptide.template") data_file = os.path.join(test_dir, "data.peptide") self.
data_filename = "test_data.peptide" self.input_filename = "test_input.peptide" self.settings = { "pair_style": "lj/charmm/coul/long 8.0 10.0 10.0", "kspace_style": "pppm 0.0001", "fix_1": "1 all nvt temp 275.0 275.0 100.0 tchain 1", "fix_2": "2 all shake 0...
lucalianas/opendata_gym
odatagym_app/datasets_handler/views.py
Python
mit
1,158
0.002591
from csv import DictReader import os from rest_framework import status from rest_framework.viewsets import ViewSet from rest_framework.exceptions import NotFound from rest_framework.response import Response import odatagym_app.settings as ods import logging logger = logging.getLogger('odata_gym') class DatasetsHan...
et_folder, dataset_name) print dataset_path if os.path.exists(dataset_path): print request.query_params delimiter = request.GET.get('file_delimiter', 'c') print 'Delimiter is %s' % delimiter with open(dataset_path) as dataset: reader = Dict...
else: raise NotFound('There is no dataset %s for %s' % (dataset_name, dataset_folder))
fulfilio/trytond-waiting-customer-shipment-report
setup.py
Python
bsd-3-clause
4,152
0
#!/usr/bin/env python import re import os import time import sys import unittest import ConfigParser from setuptools import setup, Command def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() class SQLiteTest(Command): """ Run the tests on SQLite """ description = ...
r_version = int(major_version) minor_version = int(minor_version) requires = [] MODULE2PREFIX
= { 'report_webkit': 'openlabs' } MODULE = "waiting_customer_shipment_report" PREFIX = "fio" for dep in info.get('depends', []): if not re.match(r'(ir|res|webdav)(\W|$)', dep): requires.append( '%s_%s >= %s.%s, < %s.%s' % ( MODULE2PREFIX.get(dep, 'trytond'), dep, ...
monovertex/ygorganizer
manage.py
Python
mit
247
0
#!/usr/b
in/env python import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.prod') from django.core.management import execute_from_command_line execute_from_command_line
(sys.argv)
Panos512/invenio
modules/webaccess/lib/external_authentication_oauth1.py
Python
gpl-2.0
8,849
0.007232
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2012 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) a...
@type req: invenio.webinterface_handler_wsgi.SimulatedModPythonRequest @rtype: str or NoneType """ from invenio.access_control_config import CFG_OAUTH1_CONFIGURATIONS if req.g['oauth1_provid
er_name']: path = None if CFG_OAUTH1_CONFIGURATIONS[req.g['oauth1_provider_name']].has_key( 'nickname' ): path = CFG_OAUTH1_CONFIGURATIONS[req...
EthereumWebhooks/blockhooks
lib/ethereum/tests/bintrie.py
Python
apache-2.0
8,042
0.000373
# All nodes are of the form [path1, child1, path2, child2] # or <value> from ethereum import utils from ethereum.db import EphemDB, ListeningDB import rlp, sys import copy hashfunc = utils.sha3 HASHLEN = 32 # 0100000101010111010000110100100101001001 -> ASCII def decode_bin(x): return ''.join([chr(int(x[i:i+8],...
n(subpath): node[key[0]] = [_subpath, update(subnode, db, key[sl+1:], val)] else: subpath_next = subpath[sl] n = [0, 0] n[subpath_next] = [encode_bin_path(subpath[sl+1:]), subnode] n[(1 - subpath_next)] = [encode_bin_path(key[sl+2:]), [val]] ...
node[key[0]] = dbput([encode_bin_path(subpath[:sl]), n], db) return contract_node(node, db) # Compression algorithm specialized for merkle proof databases # The idea is similar to standard compression algorithms, where # you replace an instance of a repeat with a pointer to the repeat, # except that he...
rxuriguera/bibtexIndexMaker
src/bibim/gui/custom_widgets.py
Python
gpl-3.0
3,769
0.006898
# Copyright 2010 Ramon Xuriguera # # This file is part of BibtexIndexMaker. # # BibtexIndexMaker 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 late...
pathChanged.emit() path = QtCore.pyqtProperty(QtCore.QString, get_path, set_path) @QtCore.pyqtSlot() def chooseFile(self): if self.mode == self.DIR: self.path = QtGui.QFileDialog.getExistingDirectory(self) else: self.path = QtGui.QFileDialog.getOpenFileName(self) ...
NFO':QtGui.QColor(0, 0, 0), 'WARNING':QtGui.QColor(222, 145, 2), 'ERROR':QtGui.QColor(191, 21, 43), 'CRITICAL':QtGui.QColor(191, 21, 43)} def __init__(self, parent): QtGui.QTextEdit.__init__(self, parent) self.setReadOnly(True) @QtCore.pyqtSlot...
jcmcclurg/serverpower
utilities/intel_pcm/pmu-query.py
Python
gpl-2.0
3,641
0.014556
#!/usr/bin/python import urllib2 import json, csv import subprocess import sys import platform import getopt all_flag = False download_flag = False filename=None offcore_events=[] try: opts, args = getopt.getopt(sys.argv[1:],'a,f:,d',['all','file=','download']) for o, a in opts:
if o in ('-a','--all'): all_flag=True if o in ('-f','--file'): filename=a if o in ('-d','--download'): download_flag=True except getopt.GetoptError, err: print("parse error: %s\n" %(str(err))) exit(-2) if filename == None: map_file_raw=urllib2...
'' offcore_path = '' while True: try: map_file.append(map_dict.next()) except StopIteration: break if platform.system() == 'CYGWIN_NT-6.1': p = subprocess.Popen(['./pcm-core.exe -c'],stdout=subprocess.PIPE,shell=True) elif platform.system() ...
lzw120/django
tests/regressiontests/admin_custom_urls/tests.py
Python
bsd-3-clause
3,056
0.002291
from __future__ import absolute_import from django.core.urlresolvers import reverse from django.template.response import TemplateResponse from django.test import TestCase from django.test.utils import override_settings from .models import Action @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1...
to build the URL path = reverse('admin:%s_action_change' % Action._meta.app_label, args=('add',)) response = self.client.get(path) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Change action') # Should correctly get the change_view fo...
tion._meta.app_label, args=("path/to/html/document.html",)) response = self.client.get(path) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Change action') self.assertContains(response, 'value="path/to/html/document.html"')