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
catapult-project/catapult
third_party/gsutil/third_party/mock/mock/mock.py
Python
bsd-3-clause
83,928
0.001513
# mock.py # Test tools for mocking and patching. # E-mail: fuzzyman AT voidspace DOT org DOT uk # # mock 1.0.1 # http://www.voidspace.org.uk/python/mock/ # # Copyright (c) 2007-2013, Michael Foord & the mock team # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modificatio...
a with the same # signature as the original.
if not _callable(original): return skipfirst = isinstance(original, ClassTypes) result = _get_signature_object(original, instance, skipfirst) if resu
dbbhattacharya/kitsune
kitsune/wiki/facets.py
Python
bsd-3-clause
5,435
0
import hashlib from django.conf import settings from django.core.cache import cache from django.db.models import Count from elasticsearch.exceptions import TransportError from statsd import statsd from kitsune.products.models import Topic from kitsune.wiki.models import Document, DocumentMappingType def topics_for...
arent) return qs def documents_for(locale, topics=None, products=None): """Returns a tuple of lists of articles that apply to topics and products. The first item in the tuple is the list of articles for the locale specified. The second item is the list of fallback articles in en-US that aren't l...
l) a list of Topic instances :arg products: (optional) a list of Product instances The articles are returned as a list of dicts with the following keys: id document_title url document_parent_id """ documents = _documents_for(locale, topics, products) # For locales t...
EuroPython/djep
pyconde/proposals/cms_app.py
Python
bsd-3-clause
327
0.003058
fr
om cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from django.utils.translation import ugettext_lazy as _ from .menu import ProposalsMenu class ProposalsApp(CMSApp): name = _("Proposals app") urls = ["pyconde.proposals.urls"] menus = [ProposalsMenu] apphook_pool.register(Proposals...
fifengine/fifengine
engine/python/fife/extensions/pychan/widgets/slider.py
Python
lgpl-2.1
7,472
0.054738
# -*- coding: utf-8 -*- # #################################################################### # Copyright (C) 2005-2019 by the FIFE team # http://www.fifengine.net # This file is part of FIFE. # # FIFE is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public #...
base_color=base_color, background_color
=background_color, foreground_color=foreground_color, selection_color=selection_color, border_color=border_color, outline_color=outline_color, border_size=border_size, outline_size=outline_size, position_technique=position_technique, is_foc...
renatorangel/scheduler
src/structures/scheduler.py
Python
apache-2.0
566
0
class Scheduler(object): """Define a domain.""" d
ef __init__(self, matches, problem): """. PARAMETERS TYPE Potential Arguments ----------------------------------------------- """ self.matches = matches schedule = [] self.allSchedules = [] for result in problem.getSolutions(): ...
.pop())
cupertinomiranda/binutils
gdb/testsuite/gdb.perf/lib/perftest/testresult.py
Python
gpl-2.0
2,216
0.002708
# Copyright (C) 2013-2015 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This progr...
): super (SingleStatisticTestResult, self).__init__ () self.results = dict () def record(self, parameter, result): if parameter in self.results: self.results[parameter].append(result) else: self.results[parameter] = [result] def report(self, reporter, na...
class ResultFactory(object): """A factory to create an instance of TestResult.""" def create_result(self): """Create an instance of TestResult.""" raise NotImplementedError("Abstract Method:create_result.") class SingleStatisticResultFactory(ResultFactory): """A factory to create an inst...
RJT1990/pyflux
pyflux/setup.py
Python
bsd-3-clause
792
0.002525
import os PACKAGE_NAME = 'pyflux' def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration(PACKAGE_NAME, parent_package, top_path) config.add_subpackage('__check_build') config.add_subpackage('arma') config.add_subpacka...
package('families')
config.add_subpackage('garch') config.add_subpackage('gas') config.add_subpackage('gpnarx') config.add_subpackage('inference') config.add_subpackage('output') config.add_subpackage('ssm') config.add_subpackage('tests') config.add_subpackage('var') return config if __name__ == '__main...
ESOedX/edx-platform
openedx/core/djangoapps/catalog/tests/test_utils.py
Python
agpl-3.0
34,566
0.00243
"""Tests covering utilities for integrating with the catalog service.""" # pylint: disable=missing-docstring from __future__ import absolute_import from collections import defaultdict from datetime import timedelta import mock import six from django.contrib.auth import get_user_model from django.core.cache import ca...
) mock_info.assert_called_with('Failed to get details for 1 programs. Retrying.') mock_warning.assert_called_with( u'Failed to get details for program {uuid} from the cache.'.format(uuid=programs[2]['uuid']) ) mock_warning.reset_mock() # We can't use a set compa...
ed to do here is verify the accuracy of # the data itself. for program in actual_programs: key = PROGRAM_CACHE_KEY_TPL.format(uuid=program['uuid']) self.assertEqual(program, partial_programs[key]) # Cache details for all 3 programs. all_programs = { P...
Etxea/gestioneide
gestioneide/migrations/0050_auto_20180915_1745.py
Python
gpl-3.0
721
0.001387
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2018-09-15 15:45 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('gestioneide', '0049_auto_20180516_2
118'), ] operations = [ migrations.AddField( model_name='empresa', name='cif', field=models.CharField(default=b'B12345678', max_length=9), ), migrations.AlterField( model_name='empresa', name='razon_social', field=m...
ES E.I.D.E. S.L.', max_length=255, verbose_name=b'Raz\xc3\xb3n Social'), ), ]
satendrapandeymp/Facebook_message_download
Message_windows.py
Python
mit
13,157
0.031618
from fbchat import Client, log from getpass import getpass from datetime import datetime import sys, os, urllib, time, socket, shutil, requests from glob import glob from zipfile import ZipFile socket.setdefaulttimeout(60) reload(sys) sys.setdefaultencoding("utf-8") ending = '</div></div>' username = str(raw_input("...
le) zipfile.close() shutil.rmtree("Data") def do_rest(thread): check = 0 data = str(thread).split(" ") id = data[len(data)-1].split('(')[1].split(')')[0] other = data[1] name = str(
data[1]) if len(data) == 4: other = data[1] + " " + data[2] name = str(data[1]) + '_' + str(data[2]) if len(data) == 5: other = data[1] + " " + data[2] + " " + data[3] name = data[1] + '_' + data[2] + '_' + data[3] if len(data) == 6: other = data[1] + " " + data[2] + " " + data[3] + " " + data[4]...
bitcrystal/buildtools-BaseTools
Source/Python/Eot/ParserWarning.py
Python
bsd-2-clause
1,000
0.01
## @file # Warning information of Eot # # Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR> # # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the lic...
class Warning (Exception): ## The constructor # # @param self The object pointer # @param Str The
message to record # @param File The FDF name # @param Line The Line number that error occurs # def __init__(self, Str, File = None, Line = None): self.message = Str self.FileName = File self.LineNumber = Line self.ToolName = 'EOT'
dumel93/project-
type_page/migrations/0005_footballtype_comments.py
Python
mit
471
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-07-12 14:48 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [
('type_page', '0004_auto_20170711_1241'), ] operations = [ migrations.AddField( model_name='footballtype', name='comments', field=models.CharField(max_le
ngth=128, null=True), ), ]
benoitc/offset
examples/demo_ticker.py
Python
mit
302
0.003311
# -
*- coding: utf-8 - # # This file is part of offset. See the NOTICE for more information. from offset import run, maintask from offset.time import Ticker, SECOND @maintask def main(): ticker = Ticker(0.1 * SECOND) for i in range(3): print(ticker.c.recv()) ticker.stop() ru
n()
JakeColtman/bartpy
examples/score/core/sin.py
Python
mit
1,238
0
import pandas as pd import numpy as np from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split from bartpy.sklearnmodel import SklearnModel def run(size=100, alpha=0.95, beta=2.0, n_trees=50): import warnings warnings.simplefilter("error", UserWarni...
odel.fit(X_train, y_train) y_pred = model.predict(X_test)
plt.scatter(y_test, y_pred) plt.show() rmse = np.sqrt(np.sum(np.square(y_test - y_pred))) print(rmse) if __name__ == "__main__": run(50, 0.95, 2.0)
tntrung/youCVML
misc/patch.py
Python
gpl-2.0
222
0.022523
import numpy as np # ===== Patch normalization by mean intensity ======================== def mean_intensity_norm(
patch): mu = np(np.sum(patch))*1.0/(patch.shape[0]*shape[1]) retur
n (patch - mu[np.newaxis,np.newaxis])
simon-wenmouth/dealerships
dealerships/manufacturers/jeep/download_data.py
Python
mit
628
0.009554
#!/usr/bin/env python3 import os import errno import requests url='http://www.jeep.com/hostd/getlocatedealers.json?zipCode=60202&zipDistance=2500' directory_name=os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..', 'data')) try: os.makedirs(directory_name) except OSError as exc: if exc...
pass else: raise file_name=os.path.join(directory_name, 'jeep.json') response = requests.get(url, stream=True) with open(file_name, 'wb') as fd: for chunk in response.iter_content(chunk_
size=1024): fd.write(chunk)
RRCKI/panda-server
pandaserver/test/testDQ.py
Python
apache-2.0
6,730
0.021545
import commands from dataservice.DDM import ddm #print ddm.DQ2ProductionClient.generateUUID() #print ddm.DQ2.getFilesFromCatalog('aho.xml') #print ddm.DQ2ProductionClient.dq2_makeblocks('input.data') ids=['pandatest.000003.dd.input._00047.junk','09801b0a-9fd0-4237-8caf-a37932c26e39', 'pandatest.000003.dd.input._...
nDataset',datasetName]) print out ''' print (['registerDatasetLocations','-c',datasetName,'http://dms02.usatlas.bnl.gov/sites/bnl/lrc']) ddm.DQ2.main(['registerDatasetLocations','-c',datasetName, 'http://dms02.usatlas.bnl.gov/sites/bnl/lrc']) print (['regist
erDatasetSubscription',datasetName,'http://doe-dhcp241.bu.edu:8000/dq2/']) ddm.DQ2.main(['registerDatasetSubscription',datasetName,'http://doe-dhcp241.bu.edu:8000/dq2/']) #print ddm.DQ2.main(['eraseDataset',datasetName]) #print ddm.DQ2.main(['eraseDataset',datasetName]) #print ddm.DQ2ProductionClient.dq2_create_da...
findapad/find_a_pad
find_a_pad_app/migrations/0004_auto_20170709_1432.py
Python
mit
653
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-09 14:32 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migra
tion): dependencies = [ ('find_a_pad_app', '0003_auto_20170709_1432'), ] operations = [ migrations.Al
terField( model_name='organization', name='email', field=models.CharField(blank=True, max_length=100), ), migrations.AlterField( model_name='organization', name='phone_number', field=models.CharField(blank=True, max_length=12), ...
albertz/music-player
mac/pyobjc-framework-Cocoa/Examples/AppKit/PyObjCLauncher/FileSettings.py
Python
bsd-2-clause
6,020
0.001495
from Foundation import * from AppKit import * class FileSettings(NSObject): fsdefault_py = None fsdefault_pyw = None fsdefault_pyc = None default_py = None default_pyw = None default_pyc = None factorySettings = None prefskey = None settings = None def getFactorySettingsForFile...
leManager.defaultManager() self.settings['in
terpreter'] = u'no default found' for filename in interpreters: filename = filename.nsstring().stringByExpandingTildeInPath() if mgr.fileExistsAtPath_(filename): self.settings['interpreter'] = filename break self.origsource = None return se...
pivonroll/Qt_Creator
tests/system/shared/classes.py
Python
gpl-3.0
7,863
0.004324
############################################################################ # # Copyright (C) 2016 The Qt Company Ltd. # Contact: https://www.qt.io/licensing/ # # This file is part of Qt Creator. # # Commercial License Usage # Licensees holding valid commercial Qt license
s may use this file in # accordance with the commercial license agreement provided with the # Software or, alternatively, in accordance with the terms contained in # a written agreement between you and The Qt Company. For licensing terms # and conditions see https://www.qt.io/terms-conditions. For further # information...
the GNU # General Public License version 3 as published by the Free Software # Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT # included in the packaging of this file. Please review the following # information to ensure the GNU General Public License requirements will # be met: https://www.gnu....
tomlepaine/jobber
jobber/scripts/progress.py
Python
bsd-3-clause
130
0
from jobber import jobber from redis import Redis client = Redis() progress = jobber.JobPr
ogress(c
lient=client) progress.run()
divergentdave/inspectors-general
inspectors/agriculture.py
Python
cc0-1.0
11,641
0.007559
#!/usr/bin/env python import datetime import logging import os from urllib.parse import urljoin from utils import utils, inspector # http://www.usda.gov/oig/rptsaudits.htm archive = 1978 # options: # standard since/year options for a year range to fetch from. # # Notes for IG's web team: # - Some reports have li...
g a '.pdf' extension. LOWER_PDF_REPORT_IDS = [ "sarc1978_2_Part_1", "sarc1979_2", "sarc1980_2", "sarc1981_2", "sarc1982_2", "sarc1983_2", "sarc1984_2", "sarc1985_2", "sarc1986_2", "sarc1987_2", "sarc1988_2", "sarc1989_2", "sarc1990_2", "sarc1991_2", "sarc1992_2", "sarc1993_2", "sarc199...
1995_2", "sarc1996_2", "sarc1997_2", ] def run(options): year_range = inspector.year_range(options, archive) # Pull the audit reports all_audit_reports = {} for agency_slug, agency_path in AGENCY_URLS.items(): agency_url = urljoin(AGENCY_BASE_URL, agency_path) doc = utils.beautifulsoup_from_url(a...
PaesslerAG/django-act-as-auth
tests/testapp/tests.py
Python
bsd-3-clause
17,168
0
import django from django.utils.six.moves.urllib import parse from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User from django.contrib.auth import signals as auth_signals, REDIRECT_FIELD_NAME from django.contrib.auth.forms import AuthenticationForm from django.test import Tr...
def test_cannot
_authenticate_regular_user(self): with self.patched_get_backends(): self.assertEqual( None, auth_through_backend( self.act_as_auth_backend, username='foo', password='password')) self.assertEqual([], self.first_test_backe...
lukecwik/incubator-beam
sdks/python/apache_beam/utils/annotations.py
Python
apache-2.0
5,756
0.003648
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
ce of this annotation implies nothing about the quality or performance of the API in question, only the fact that the API or behavior may change in any way. Deprecated: Signifies that users are discouraged from using a public API typically because a better alternative exists, and the current form might be removed in a...
y guarantees. Annotations come in two flavors: deprecated and experimental The 'deprecated' annotation requires a 'since" parameter to specify what version deprecated it. Both 'deprecated' and 'experimental' annotations can specify the current recommended version to use by means of a 'current' parameter. The followi...
ezScrum/ezScrum
robotTesting/keywords/lib/DatabaseHandler.py
Python
gpl-2.0
1,547
0.007111
import MySQLdb class DatabaseHandler: def __init__(self): pass def is_delete(self, tableName): reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"] isDeleteFlag = 1 for name in reservedTableNameList: isIdentical = cmp(tab...
lean_Database(self, hostUrl, account, password, databaseName): print 'clean database1' db = MySQLdb.connect(host=hostUrl, user=account, passwd=password, db=databaseName) cursor = db.cursor() cursor.execute("Show Tables from " + datab
aseName) result = cursor.fetchall() for record in result: tableName = record[0] isDelete = self.is_delete(tableName) if isDelete == 0: print "Reserve " + tableName else : print "TRUNCATE TABLE `" + tableName + "`" ...
Bugheist/website
comments/migrations/0004_auto_20170727_1308.py
Python
agpl-3.0
559
0.001789
# -*- coding: utf-8 -*- # Generated by Djan
go 1.11.1 on 2017-07-27 13:08 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('comments', '0003_auto_20170726_1348'), ] operations = [ migrations.AlterField( model_name='comment', ...
field=models.ForeignKey(default=-1, null=True, on_delete=django.db.models.deletion.CASCADE, to='comments.Comment'), ), ]
voussoir/etiquette
frontends/etiquette_flask/backend/endpoints/album_endpoints.py
Python
bsd-2-clause
9,106
0.003075
import flask; from flask import request import os import urllib.parse from voussoirkit import flasktools from voussoirkit import gentools from voussoirkit import stringtools import etiquette from .. import common site = common.site session_manager = common.session_manager # Individual albums ######################...
album = common.P_album(album_id, response_type='json') directories = album.get_associated_directories() if len(directories) != 1: flask.abort(400) directory = directories.pop() if os.name == 'nt': command = f'start explorer.exe "{direct
ory.absolute_path}"' os.system(command) return flasktools.json_response({}) flask.abort(501) # Album listings ################################################################################### @site.route('/all_albums.json') @flasktools.cached_endpoint(max_age=15) def get_all_album_names(): ...
googleapis/python-talent
samples/generated_samples/jobs_v4beta1_generated_profile_service_delete_profile_sync.py
Python
apache-2.0
1,401
0.000714
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
r DeleteProfile # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-talent # [START jobs_v4beta1_generated
_ProfileService_DeleteProfile_sync] from google.cloud import talent_v4beta1 def sample_delete_profile(): # Create a client client = talent_v4beta1.ProfileServiceClient() # Initialize request argument(s) request = talent_v4beta1.DeleteProfileRequest( name="name_value", ) # Make the re...
NeuromorphicProcessorProject/snn_toolbox
tests/core/test_config.py
Python
mit
1,363
0
# coding=utf-8 """Test configuration of toolbox.""" import importlib import os import pytest from snntoolbox.bin.utils import update_setup from snntoolbox.utils.utils import import_configparser with open(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'req...
_file__), 'filename_ann': '98.96'}}, False) ] @pytest.mark.parametrize('params, expect_pass', _in_and_out) def test_updating_settings(params, expect_pass, _path_wd)
: configparser = import_configparser() config = configparser.ConfigParser() config.read_dict(params) configpath = os.path.join(str(_path_wd), 'config') with open(configpath, 'w') as file: config.write(file) if expect_pass: assert update_setup(configpath) else: pytest....
edx-solutions/edx-platform
openedx/core/lib/tests/assertions/events.py
Python
agpl-3.0
9,836
0.004778
"""Assertions related to event validation""" import json import pprint import six def assert_event_matches(expected, actual, tolerate=None): """ Compare two event dictionaries. Fail if any discrepancies exist, and output the list of all discrepancies. The intent is to produce clearer error messages...
pected fields to exist in the "context" dictionary. This is where new fields that appear in multiple # events are most commonly added, so we freq
uently want to tolerate variation here. CONTEXT_EXTRA_FIELDS = 'context_extra_fields' # Allow unexpected fields to exist in the "event" dictionary. Typically in unit tests we don't want to allow this # type of variance since there are typically only a small number of tests for a particular event type. ...
Zetten/pypkgmirror
pypkgmirror/__init__.py
Python
gpl-3.0
3,339
0.000898
# Copyright 2015 Peter van Zetten # # This file is part of pypkgmirror. # # pypkgmirror 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....
n and trivial handling of missing executables. """ try: subprocess.call(
call, stdout=stdout, stderr=stderr) except OSError as e: if e.errno == os.errno.ENOENT: log.error("The required program %s was not found, no packages synced", call[0]) else: raise if __name__ == "__main__": main()
elbeardmorez/quodlibet
quodlibet/tests/test_library_libraries.py
Python
gpl-2.0
24,563
0.000366
# -*- coding: utf-8 -*- # 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. from gi.repository import Gtk import os import...
self.failUnlessEqual(self.changed, self.Frange(5)) def test_changed_not_present(self): self.library.add(self.Frange(10)) self.library.changed(self.Frange(2, 20, 3)) while Gtk.events_pending(): Gtk.main_iteration() self.failUnlessEqual(set(self.c
hanged), {2, 5, 8}) def test_changed_none_present(self): self.library.changed(self.Frange(5)) while Gtk.events_pending(): Gtk.main_iteration() def test___iter__(self): self.library.add(self.Frange(10)) self.failUnlessEqual(sorted(list(self.library)), self.Frange(10)...
lkash/test
dpkt/stp.py
Python
bsd-3-clause
1,695
0.00059
# $Id: stp.py 23 2006-11-08 15:45:33Z dugsong $ # -*- coding: utf-8 -*- """Spanning Tree Protocol.""" import dpkt class STP(dpkt.Packet): __hdr__ = (
('proto_id', 'H', 0), ('v', 'B', 0), ('type', 'B', 0), ('flags', 'B', 0),
('root_id', '8s', ''), ('root_path', 'I', 0), ('bridge_id', '8s', ''), ('port_id', 'H', 0), ('_age', 'H', 0), ('_max_age', 'H', 0), ('_hello', 'H', 0), ('_fd', 'H', 0) ) @property def age(self): return self._age >> 8 @age.setter d...
ofer43211/unisubs
apps/comments/__init__.py
Python
agpl-3.0
763
0.006553
# Amara, universalsubtitles.org # # Copyright (C) 2013 Participatory Culture Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your ...
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 Affero General Public License
for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see # http://www.gnu.org/licenses/agpl-3.0.html.
stackforge/solum
solum/api/controllers/v1/component.py
Python
apache-2.0
4,074
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
r(rest.RestController): """Manages operations on the components collection.""" @pecan.ex
pose() def _lookup(self, component_id, *remainder): if remainder and not remainder[-1]: remainder = remainder[:-1] return ComponentController(component_id), remainder @exception.wrap_wsme_pecan_controller_exception @wsme_pecan.wsexpose(component.Component, body=component.Compone...
xwdeng/MiniProxyPool
miniproxypool/config.py
Python
mit
2,154
0.011142
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Auther: Xiaowei Deng # # This file is part of Mini Proxy Pool # # This program is free software and it is distributed under # the terms of the MIT license. Please see LICENSE file for details. PROXY_DB_FILE = "_proxies.db" VALIDATOR_TIMEOUT = 1 # seconds ...
'url_base': 'https://www.us-proxy.org', 'pattern': "((?:\d{1,3}\.){1,3}\d{1,3})<\/td><td>(\d{1,6})(.{1,200})<td class='hx'>(.{2,3})", 'ip_ind': 0, 'port_ind': 1, 'protocal_ind': 3 # todo: to specify the protocol: http or https }, { ...
cal_ind': None } ] PROXY_SOURCE_FILES = [ 'custom_proxies_list.txt' ] DEFAULT_HEADERS = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2693.2 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*...
pombredanne/lineup
lineup/framework.py
Python
mit
1,964
0.000509
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import os import socket import traceback from lineup.datastructures impo
rt Queue class Node(object): def __init__(self, *args, **kw): self.initialize(*args, **kw) def initialize(self, *args, **kw): pass @property def id(self): return '|'.join([self.get_hostname(), str(os.getpid())]) @property def taxonomy(self): class_name = self...
ttr(self, 'name', None) or self.taxonomy def get_hostname(self): return socket.gethostname() def make_worker(self, Worker, index): return Worker(self, self.input, self.output) def start(self): for worker in self.workers: worker.start() def feed(self, item): ...
allotory/basilinna
config.py
Python
mit
850
0.002353
# -*- coding: utf-8 -*- import os basedir
= os.path.abspath(os.path.dirname(__file__)) CSRF_ENABLED = True SECRET_KEY = 'UsTd+_P&kv#jdQ!3Oc.Kb$yd,ey/B2i-aM8em' SITE_NAME = 'basilinna' MYSQL_DB = 'basilinna' MYSQL_USER = 'root' MYSQL_PASSWD = 'root' MYSQL_HOST = 'localhost' MYSQL_POST = 3306 basedir = os.path.abspath(os.path.dirname(__file__)) SQLALCHEMY_D...
PASSWD, MYSQL_HOST, MYSQL_POST, MYSQL_DB) SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'migrations') HOST = 'http://localhost:5000/' UPLOAD_FOLDER = '.\\app\\static\\uploads' UPLOAD_AVATAR_FOLDER = '.\\app\\static\\avatars' ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif...
2015fallhw/cdw11
static/plugin/liquid_tags/test_audio.py
Python
agpl-3.0
1,494
0
from . import audio import pytest import re @pytest.mark.parametrize('input,expected', [ ('http://foo.bar https://bar.foo', ('http://foo.bar', 'https://bar.foo', None)), ('http://test.foo', ('http://test.foo', None, None)), ('https://test.foo', ('https://test.foo', None, None)), ...
ar.opus', ('<audio controls>' '<source src="https:
//foo.foo/foo.ogg" type="audio/ogg">' '<source src="http://bar.bar/bar.opus" type="audio/ogg">' 'Your browser does not support the audio element.</audio>')), ('http://1.de/1.wav http://2.de/2.mp4 http://3.de/3.ogg', ('<audio controls>' '<source src="http://1.de/1.wav" type="audio/wav">' ...
hei-hilman/microblog
app/forms.py
Python
bsd-3-clause
1,059
0.004721
from flask.ext.wtf import Form from wtforms import StringField, BooleanField, TextAreaField from wtforms.validators import DataRequired, Length from app.models import User class LoginForm(Form): openid = StringField('openid', validators=[DataRequired()]) remember_me = BooleanField('remember_me', default=False)...
*args, **kwargs) self.original_nickname = original_nickname def validate(self): if not Form.validate(self): ret
urn False if self.nickname.data == self.original_nickname: return True user = User.query.filter_by(nickname=self.nickname.data).first() if user != None: self.nickname.errors.append('This nickname is already in use. Please choose another one.') return False ...
SiLab-Bonn/online_monitor
online_monitor/stop_online_monitor.py
Python
mit
362
0.002762
#!/usr/
bin/env python import psutil def main(): for proc in psutil.process_iter(): if any(name in proc.name() for name in ['start_produc
er', 'start_converter', 'start_online']) or any(name in ''.join(proc.cmdline()) for name in ['start_producer', 'start_converter', 'start_online']): proc.kill() if __name__ == '__main__': main()
robosafe/mc-vs-bdi
tiago_simulator/scripts/grasp_demo.py
Python
gpl-3.0
1,252
0.023962
#!/usr/bin/env python import rospy import actionlib from play_motion_msgs.msg import PlayMotionAction, PlayMotionGoal from sensor_msgs.msg import JointState if __name__ == "__main__": rospy.init_node("grasp_demo") rospy.loginfo("Waiting for play_motion...") client = actionlib.SimpleActionClient("/play_motion", ...
goal.skip_planning = True client.send_goal(goal) client.wait_for_result(rospy.Duration(5.0)) goal.motion_name = 'pregrasp_demo' goal.skip_planning = True
client.send_goal(goal) client.wait_for_result(rospy.Duration(40.0)) goal.motion_name = 'grasp_demo' goal.skip_planning = True client.send_goal(goal) client.wait_for_result(rospy.Duration(80.0)) goal.motion_name = 'pick_demo' goal.skip_planning = True client.send_goal(goal) client.wait_for_result(r...
moto-timo/robotframework
src/robot/running/timeouts/__init__.py
Python
apache-2.0
3,987
0.000251
# Copyright 2008-2015 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
imeout tests fail # intermittently on Windows, probably due to threading.Event.wait(). return round(self.secs - elapsed, 3) def timed_out(self): return self.active and self.time_left() <= 0 def __unicode__(self): return self.string @property def _sort_key(self): ...
me_left()) def __nonzero__(self): return bool(self.string and self.string.upper() != 'NONE') def run(self, runnable, args=None, kwargs=None): if self.error: raise DataError(self.error) if not self.active: raise FrameworkError('Timeout is not active') tim...
roofit-dev/parallel-roofit-scripts
int2ext_precision_solution.py
Python
apache-2.0
1,674
0.001792
import numpy as np # for the double bounded trafo def i2e(v, u, l): return l + 0.5 * (u - l) * (np.sin(v) + 1) def e2i(v, u, l, eps2): piby2 = 2. * np.arctan(1.) distnn = 8. * np.sqrt(eps2) vlimhi = piby2 - distnn vlimlo = -piby2 + distnn yy = 2. * (v - l) / (u - l) - 1. yy2 = yy * yy ...
print("vlimhi") return vlimhi else: print("arcsin") return np.arcsin(yy) def i2e2i(v_hex, u, l): eps2 = float.fromhex('0x1p-24') i = np.longdouble(float.fromhex(v_hex)) e = i2e(i, u, l) i2 = e2i(e, u, l, eps2) return i, i2 def print_i2e2i(i, i2): p...
float(i2))) # this is the first number in my test that goes wrong right1, wrong1 = i2e2i('-0x1.abadef0339ab8p-3', 3, -3) print_i2e2i(right1, wrong1) # prints: # -0.20882784584610703 -0.208827845846 # -0x1.abadef0339ab8p-3 -0x1.abadef0339ab9p-3 # i.e. the last bit is now one higher than before # let's try another: pri...
google/tf-quant-finance
tf_quant_finance/models/legacy/brownian_motion.py
Python
apache-2.0
19,227
0.003173
# Lint as: python3 # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
ss. For more details, see Ref [1]. #### References: [1]: Brent Oksendal. Stochastic Differential Equations: An Introduction with Applications. Springer. 2010. """ import tensorflow.compat.v2 as tf from tf_quant_finance.math.random_ops import multivariate_normal as mvn from tf_quant_finance.models.legacy impor...
ls.legacy import ito_process class BrownianMotion(ito_process.ItoProcess): """The multi dimensional Brownian Motion.""" def __init__(self, dim=1, drift=None, volatility=None, total_drift_fn=None, total_covariance_fn=None, d...
certik/pyjamas
pgen/test_support.py
Python
apache-2.0
18,242
0.003728
"""Supporting definitions for the Python regression tests.""" if __name__ != 'test.test_support': raise ImportError, 'test_support must be imported from the test package' import sys class Error(Exception): """Base class for regression test exceptions.""" class TestFailed(Error): """Test failed.""" clas...
files.''' unload(modname) import os for dirname in sys.path: unlink(os.path.join(dirname, mo
dname + os.extsep + 'pyc')) # Deleting the .pyo file cannot be within the 'try' for the .pyc since # the chance exists that there is no .pyc (and thus the 'try' statement # is exited) but there is a .pyo file. unlink(os.path.join(dirname, modname + os.extsep + 'pyo')) def is_resource_en...
bennylope/pygeocodio
docs/conf.py
Python
bsd-3-clause
8,264
0.000242
# -*- coding: utf-8 -*- # # pygeocodio documentation build configuration file, created by # sphinx-quickstart on Wed Jan 22 14:09:09 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # ...
o template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is ...
= True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> ta...
pylada/pylada-light
tests/ipython/conftest.py
Python
gpl-3.0
2,390
0.000837
############################### # This file is part of PyLaDa. # # Copyright (C) 2013 National Renewable Energy Lab # # PyLaDa is a high throughput computational platform for Physics. It aims to # make it easier to submit large numbers of jobs on supercomputers. It # provides a python interface to physical input, ...
edtuple("Extract", ["success", "directory", "indiv", "functional"]) if not exists(outdir): return Extract(False, outdir, None, functional) with chdir(outdir): if not exists("OUTCAR"): return Extract(False, outdir, None, functional) with open("OUTCAR", "rb") as file: ...
tional) def call_functional(indiv, outdir=None, value=False, **kwargs): from pylada.misc import local_path from pickle import dump path = local_path(outdir) path.ensure(dir=True) dump((indiv, value), path.join("OUTCAR").open("wb")) return Extract(outdir) call_functional.Extract = Extract ...
thecrackofdawn/Peach2.3
Peach/Analyzers/shark.py
Python
mit
32,258
0.048112
''' Wireshark Analyzer(s) @author: Michael Eddington @version: $Id$ ''' # # Copyright (c) Michael Eddington # # 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...
at we want! #i
f (parentSize - sizeUptoMe) == size: # return True #else: # debug("Nope: ParentSize: %d - SizeUptoMe: %d -- Size: %d" % (parentSize, sizeUptoMe, size)) return None def findSizes(self, nodes): ''' Find nodes that could be sizes or lengths. ''' if nodes == None: return [] findValues = ["l...
mooseman/pdteco
pdteco.py
Python
unlicense
6,753
0.041636
# pdteco.py # A public-domain Python implementation of the core commands of TECO. # This code is released to the public domain. # "Share and enjoy....." ;) # # *** To do...... *** # NOTE - the built-in functions f.tell() and f.seek() should be very # useful. # From the Python docs - # f.tell() ...
def move2line(self, line): pass # Move by a given number of bytes from the current position def moveinline(self, n): self.f.seek(n, 1) # Show the current position of the pointer. def showptr(self): return self.f.tell() # Print a given number of by...
# Search for some text def search(self, str): pass # Replace some text def replace(self, target, repwith): pass # Insert some text def ins_text(self, txt): pass # Delete some text def del_text(self, txt): ...
waymo-research/waymo-open-dataset
waymo_open_dataset/metrics/ops/motion_metrics_ops_test.py
Python
apache-2.0
13,287
0.001806
# Copyright 2021 The Waymo Open Dataset 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 Lic
ense. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See ...
the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import numpy as np import tensorfl...
blakerohde/sidewalk
sidewalk/core/exceptions.py
Python
isc
1,924
0.04262
""" sidewalk.exceptions This module contains custom exceptions that can be thrown by Sidewalk. :copyright: (c) 2013 by Blake Rohde. :license: ISC, see LICENSE for more details. """ class SidewalkSettingsFileIOError(Exception): """Settings file IOError.""" def __init__(self, filename, permission): self.filenam...
cessor group requested is not defined.""" def __init__(self, group_key): self.group_key = group_key def __str__(self): return repr(self.group_key) class SidewalkModuleImportError(Exception): """Activity processor module could not be imported.""" d
ef __init__(self, module): self.module = module def __str__(self): return repr(self.module) class SidewalkMethodDoesNotExist(Exception): """The Activity processor (method) does exist in the specified module.""" def __init__(self, module, method): self.module = module self.method = method def __str...
viswanathgs/EratoSCP
src/mountremote.py
Python
gpl-3.0
2,361
0.034307
import gtk import pygtk import pexpect import gio import commands import gobject class RemoteMounter: def login_remote(self, host, port, username, password): ''' Mount the remote file system and update the remote file chooser to the corresponding location. Any remote filesystem, previously mounted by the ...
t.find('sftp for ' + username + ' on ' + host) != -1: return True return False def mount_remote(self, host, port, username, password): ''' Mount the remote filesystem if it is not m
ounted already. Also, set the remote file chooser widget sensitive. ''' if port == '': port = 22 remote = username + '@' + host + ':' + str(port) if not self.already_mounted(host, username): child = pexpect.spawn('gvfs-mount sftp://' + remote) child.expect('Password:\s*') child.sendline(passw...
dcf21/4most-4gp
src/pythonModules/fourgp_specsynth/fourgp_specsynth/__init__.py
Python
mit
666
0.001502
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This python module defines a wrapper for synthesising spectra using TurboSpectrum. """ import logging fr
om numpy import RankWarning from warnings import simplefilter from .turbospectrum import TurboSpectrum from .solar_abundances import solar_abundances __version__ = "20190301.1" logger = logging.getLogger(__name__) logger.setLevel(logging.I
NFO) # TODO: Remove this when stable. handler = logging.StreamHandler() handler.setFormatter(logging.Formatter( "%(asctime)s [%(levelname)-8s] %(message)s")) logger.addHandler(handler) simplefilter("ignore", RankWarning) simplefilter("ignore", RuntimeWarning)
SphinxKnight/kuma
kuma/wiki/tests/conftest.py
Python
mpl-2.0
11,242
0.000089
# -*- coding: utf-8 -*- """py.test fixtures for kuma.wiki.tests.""" import base64 import json from collections import namedtuple from datetime import datetime import pytest from django.contrib.auth.models import Permission from waffle.testutils import override_flag from ..models import Document, DocumentDeletionLog, ...
le_bottom=middle_bottom_doc, bottom=bottom_doc, ) @pytest.fixture def root_doc_with_mixed_contributors(root_doc, wiki_user, wiki_user_2, inactive_wiki_user, banned_wiki_user): """ A top-level English document with mixed contributors (some are valid, some ar...
document.</p>', comment='Done with the initial version.', created=datetime(2017, 4, 17, 12, 35)) root_doc.save() root_doc.current_revision = Revision.objects.create( document=root_doc, creator=inactive_wiki_user, content='<p>The root document re-envisioned.</p>', ...
percyfal/bokeh
examples/plotting/file/tap.py
Python
bsd-3-clause
898
0.005568
import numpy as np from bokeh.plotting import figure, show, output_file from bokeh.models import TapTool xx, yy = np.meshgrid(range(0,101,4), range(0,101,4)) x = xx.flatten() y = yy.flatten() N = len(x) inds = [str(i) for i in np.arange(N)] radii = np.random.random(size=N)*0.4 + 1.7 colors = [ "#%02x%02x%02x" % (...
ve" p = figure(title="Tappy Scatter", tools=TOOLS) cr = p.circle(x, y, radius=radii,
fill_color=colors, fill_alpha=0.6, line_color=None) tr = p.text(x, y, text=inds, alpha=0.5, text_font_size="5pt", text_baseline="middle", text_align="center") # in the browser console, you will see messages when circles are clicked tool = p.select_one(TapTool).renderers = [cr] output_file("tap.html...
guyrt/teaching
2017/Com597I/babynames/problem8.py
Python
mit
607
0.003295
import ssadata # how many boys names are also girls names? # implementation details: # find all names in the boys data set that are # also
keys in the girls data set. num_shared_names = 0 for name in ssadata.boys: if name in ssadata.girls: num_shared_names = num_shared_names + 1 print(str(num_shared_names) + " names out of " + str(len(ssadata.boys)) + " are shared.") num_shared_names = 0 for name in ssadata.girls: if name in ssadata.boy...
_names + 1 print(str(num_shared_names) + " names out of " + str(len(ssadata.girls)) + " are shared.")
balanced/balanced-python
balanced/exc.py
Python
mit
2,557
0.000391
from __future__ import unicode_literals import httplib import wac class BalancedError(Exception): def __str__(self): attrs = ', '.join([ '{0}={1}'.format(k, repr(v)) for k, v in self.__dict__.iteritems() ]) return '{0}({1})'.format(self.__class__.__name__, attrs)...
esponses[requests_ex.response.status_code] error = data['errors'][0] status = error.pop('status', status) status_code = error.pop('status_code', requests_ex.response.status_code) desc = error.pop('description', None) message = ': '.join(str(v) for ...
us, status_code, desc] if v) return message @classmethod def from_response(cls, **data): try: err = data['errors'][0] exc = cls.type_to_error.get(err['category_code'], HTTPError) except: exc = HTTPError return exc type_to_error = {} cla...
jencce/stuff
py/class.py
Python
gpl-2.0
693
0.049062
#! /usr/bin/env python class myclass: "zx class" i = 11111 def f(self): return 'hw' def pi(self): print "pi i={0}".format(self.i) def si(self, v): self.i = v def pp(self): print 'pp', self.pi() x = myclass() x.f() x.pi() x.si(9) x.pi() x.pp() print '============================' class newclass(mycl...
=========
===========" z=myclass() z.pp()
Odingod/mne-python
mne/io/fiff/tests/test_raw.py
Python
bsd-3-clause
38,869
0
from __future__ import print_function # Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Denis Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import os import os.path as op import glob from copy import deepcopy import warnings import itertools as itt import numpy as np ...
raw_2._data[0, 0] -= 1 assert_not_equal(hash(raw), hash(raw_2)) @testing.requires_testing_data def test_subject_info(): """Test reading subject information """ tempdir = _TempDir() raw = Raw(fif_fname).crop(0, 1, False
) assert_true(raw.info['subject_info'] is None) # fake some subject data keys = ['id', 'his_id', 'last_name', 'first_name', 'birthday', 'sex', 'hand'] vals = [1, 'foobar', 'bar', 'foo', (1901, 2, 3), 0, 1] subject_info = dict() for key, val in zip(keys, vals): subject_info[ke...
batxes/4Cin
SHH_WT_models/SHH_WT_models_final_output_0.1_-0.1_11000/SHH_WT_models12702.py
Python
gpl-3.0
17,583
0.025081
import _surface import chimera try: import chimera.runCommand except: pass from VolumePath import markerset as ms try: from VolumePath import Marker_Set, Link new_marker_set=Marker_Set except: from VolumePath import volume_path_dialog d= volume_path_dialog(True) new_marker_set= d.new_marker_set marker_set...
y"]=s s= marker_sets["particle_4 geometry"] mark=s.place_marker((2401.45, 10810.3, 1711.38), (0.7, 0.7, 0.7), 761.442) if "particle_5 geom
etry" not in marker_sets: s=new_marker_set('particle_5 geometry') marker_sets["particle_5 geometry"]=s s= marker_sets["particle_5 geometry"] mark=s.place_marker((3826.97, 10319.9, 3558.07), (0.7, 0.7, 0.7), 961.183) if "particle_6 geometry" not in marker_sets: s=new_marker_set('particle_6 geometry') marker_sets...
Azure/azure-sdk-for-python
sdk/search/azure-mgmt-search/azure/mgmt/search/operations/_shared_private_link_resources_operations.py
Python
mit
27,117
0.00579
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
shared_private_link_resource_name, # type: str shared_private_link_resource, # type: "_models.SharedPrivateLinkResource" search_management_request_options=None, # type: Optional["_models.SearchManagementRequestOptions"] **kwargs # type: Any ): # type: (...) -> Optional["_models.S...
e: ClsType[Optional["_models.SharedPrivateLinkResource"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _client_request_id = None if search_management_request...
robofit/artable
art_simple_tracker/scripts/fake_detector.py
Python
lgpl-2.1
2,036
0.002456
#!/usr/bin/env python import rospy from art_msgs.msg import ObjInstance, InstancesArray import time import sys import random from tf import transformations from math import pi def a2q(q, arr): q.x = arr[0] q.y = arr[1] q.z = arr[2] q.w = arr[3] class FakeDetector: def __init__(self, obj_id, fr...
a) if __name__ == '__main__': rospy.init_node('fake_detector', anonymous=True) tr
y: pos = (float(sys.argv[3]), float(sys.argv[4]), float(sys.argv[5])) rpy = (float(sys.argv[6]), float(sys.argv[7]), float(sys.argv[8])) FakeDetector(sys.argv[1], sys.argv[2], pos, rpy, float(sys.argv[9])) rospy.spin() except rospy.ROSInterruptException: pass except Index...
vagonbar/GNUnetwork
gwn/utils/testing/__init__.py
Python
gpl-3.0
90
0.011111
#!/usr/bin/env python # -*-
coding: utf-8 -*- '''Testing and te
sting related modules. '''
jumpserver/jumpserver
apps/assets/api/asset.py
Python
gpl-3.0
10,108
0.001187
# -*- coding: utf-8 -*- # from rest_framework.viewsets import ModelViewSet from rest_framework.generics import RetrieveAPIView, ListAPIView from django.shortcuts import get_object_or_404 from django.db.models import Q from common.utils import get_logger, get_object_or_none from common.mixins.api import SuggestionMixin...
ode = get_object_or_none(Node, pk=node_id) if not node: return node.assets.add(*assets) def perform_create(self, serializer): assets = serializer.sa
ve() self.set_assets_node(assets) class AssetPlatformRetrieveApi(RetrieveAPIView): queryset = Platform.objects.all() serializer_class = serializers.PlatformSerializer rbac_perms = { 'retrieve': 'assets.view_gateway' } def get_object(self): asset_pk = self.kwargs.get('pk') ...
fako/datascope
src/online_discourse/elastic.py
Python
gpl-3.0
1,813
0
from elasticsearch import Elasticsearch from django.conf import settings def get_es_client(silent=False): """ Returns the elasticsearch client which uses the configuration file """ es_client = Elasticsearch([settings.ELASTIC_SEARCH_HOST], scheme='http', ...
"number_of_shards": 1, "number_of_replicas": 0 } }, 'mappings': { '_doc': { 'properties': { 'title': { 'type': 'text',
'analyzer': settings.ELASTIC_SEARCH_ANALYSERS[lang] }, 'content': { 'type': 'text', 'analyzer': settings.ELASTIC_SEARCH_ANALYSERS[lang] }, 'url': {'type': 'text'}, 'title...
asdf2014/superset
superset/cache_util.py
Python
apache-2.0
1,105
0
from superset import tables_cache from flask import request def view_cache_key(*unused_args, **unused_kwargs): args_hash = hash(frozenset(request.args.items())) return 'view/{}/{}'.format(request.path, args_hash) def memoized_func(timeout=5 * 60, key=view_cache_key): """Use this decorator to cache funct...
caching key. """ def wrap(f): if tables_cache: def wrapped_f(cls, *args, **kwargs): cache_key = key(*args, **kwargs) o = tables_cache.get(cache_key) if not kwargs['force'] and o is not None:
return o o = f(cls, *args, **kwargs) tables_cache.set(cache_key, o, timeout=timeout) return o else: # noop def wrapped_f(cls, *args, **kwargs): return f(cls, *args, **kwargs) return wrapped_f return wrap
calaldees/KaraKara
processmedia2/processmedia_libs/processed_files_manager.py
Python
gpl-3.0
3,137
0.000638
import os import shutil import hashlib from collections import namedtuple, defaultdict from calaldees.files.scan import fast_scan ProcessedFileType = namedtuple('ProcessedFileType', ('source_hash_group', 'dict_key', 'attachment_type', 'ext', 'salt')) class ProcessedFilesManager(object): FILE_TYPES = ( Pr...
(self): os.makedirs(os.path.join(self.path, self.folder), exist_ok=True) def move(self, source_file): """ It is important that 'move' is used rather than opening a stream to the absolute pa
th directly. The remote destination could be 'scp' or another remote service. Always using move allows for this abstraction at a later date """ self._create_folders_if_needed() shutil.move(source_file, self.absolute) def copy(self, source_file): self._create_folders_...
masterkorp/obfsproxy
obfsproxy/common/hmac_sha256.py
Python
bsd-3-clause
230
0.004348
import hashlib import hmac def hmac_sha256_di
gest(key, msg): """ Return the HMAC-SHA256 message authentication code of the message 'msg' wit
h key 'key'. """ return hmac.new(key, msg, hashlib.sha256).digest()
nvbn/thefuck
tests/rules/test_git_remote_seturl_add.py
Python
mit
920
0
import pytest
from thefuck.rules.git_remote_seturl_add import match, get_new_command from thefuck.types import Command @pytest.mark.parametrize('command', [ Command('git remote set-url origin url', "fatal
: No such remote")]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [ Command('git remote set-url origin url', ""), Command('git remote add origin url', ''), Command('git remote remove origin', ''), Command('git remote prune origin', ''), Command('git remote...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractMyTranslations.py
Python
bsd-3-clause
355
0.028169
def extractMyTranslations(item): """ Parser for 'My Translations' """ vol, chp, frag
, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'WATTT' in item['tags']: return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, postfix=postfix) return Fal
se
awslabs/chalice
chalice/local.py
Python
apache-2.0
29,826
0
"""Dev server used for running a chalice app locally. This is intended only for local development purposes. """ from __future__ import print_function import re import threading import time import uuid import base64 import functools import warnings from collections import namedtuple import json from six.moves.BaseHTT...
urce_path=path ) class ARNMatcher(object): def __init__(self, target_arn): # type: (str) -> None self._arn = target_arn def _resource_match(self, resource): # type: (str) -> bool # Arn matching supports two special case characetrs that are not # escapable. * re...
te to a regex using .*? and . respectivly. escaped_resource = re.escape(resource) resource_regex = escaped_resource.replace(r'\?', '.').replace( r'\*', '.*?') resource_regex = '^%s$' % resource_regex return re.match(resource_regex, self._arn) is not None def does_any_res...
irzaip/chippy
cp_hand.py
Python
lgpl-3.0
1,479
0.006085
########################################### # # # cp_hand.py # # author: irza pulungan # # # # this py will forward incoming MQTT # # message to Serial USB port arduino # # loaded wit...
cted with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then
subscriptions will be renewed. client.subscribe("$SYS/#") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): if (msg.topic == "servo"): print str(msg.payload) ser.write(str(msg.payload)+"\n\r") ser.flushInput() ser.flushOutput(...
ericgarrigues/ansible-modules-extras
cloud/gandi/gandi_iface.py
Python
gpl-3.0
7,326
0.000546
#!/usr/bin/python # Copyright 2013 Gandi SAS # # 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 versio...
ip_version=dict(), ip_address=dict(), vlan=dict(), bandwidth=dict() ) ) ip_version = module.params.get('ip_version') ip_address = module.params.get('ip_address') vlan_name = module.params.get('vlan') bandwidth
= module.params.get('bandwidth') state = module.params.get('state') dc = module.params.get('datacenter') changed = False try: gandi = get_driver(Provider.GANDI)(*ARGS) gandi.connection.user_agent_append("%s/%s" % ( USER_AGENT_PRODUCT, USER_AGENT_VERSION)) except Excepti...
ericpp/hippyvm
hippy/module/date/dateinterval_klass.py
Python
mit
9,931
0.003927
from rpython.rtyper.lltypesystem import rffi, lltype from rpython.rlib.rarithmetic import intmask from hippy import consts from hippy.error import PHPException from hippy.builtin import wrap_method, ThisUnwrapper, StringArg from hippy.builtin_klass import GetterSetterWrapper, k_Exception from hippy.klass import def_cl...
, this): return interp.space.wrap(intmask(this.time_diff.c_have_weekday_relative)) def set_have_weekday_relative(interp, this, value): raise NotImplementedError("bogus cast!") this.time_diff.c_have_weekday_relative = rffi.cast(rffi.UINT, value) def get_have_special_relative(interp, this): return inter...
c_have_special_relative = rffi.cast(rffi.UINT, value) k_DateInterval = def_class( 'DateInterval', [const
lmjohns3/theanets
theanets/graph.py
Python
mit
28,912
0.001349
# -*- coding: utf-8 -*- r'''This module contains a base class for modeling computation graphs.''' import downhill import gzip import hashlib import numpy as np import pickle import theano import time import warnings from . import layers from . import losses from . import regularizers from . import trainer from . imp...
et, check that the # "layer" param is an int and use it for "size". if 'shape' not in kwargs and 'size' not in kwargs and isinstance(layer, int): kwargs['size'] = layer # if it hasn't been provided in some other way yet, set input # dimensionality based on the model.
if form == 'input' and 'shape' not in kwargs: kwargs.setdefault('ndim', self.INPUT_NDIM) # set some default layer parameters. if form != 'input': kwargs.setdefault('inputs', self.layers[-1].output_name) kwargs.setdefault('rng', self._rng) if form.low...
Azure/azure-sdk-for-python
sdk/containerregistry/azure-mgmt-containerregistry/azure/mgmt/containerregistry/v2019_12_01_preview/aio/_container_registry_management_client.py
Python
mit
6,266
0.003671
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.export_pipelines = ExportPipelinesOperations(self._client, self._config, se
lf._serialize, self._deserialize) self.registries = RegistriesOperations(self._client, self._config, self._serialize, self._deserialize) self.import_pipelines = ImportPipelinesOperations(self._client, self._config, self._serialize, self._deserialize) self.operations = Operations(self._client, se...
rsnakamura/oldape
apetools/devices/iosdevice.py
Python
apache-2.0
3,060
0.003922
#from apetools.commands.ifconfig import IfconfigCommand #from apetools.commands.iwconfig import Iwconfig from apetools.commons.enumerations import OperatingSystem from apetools.devices.basedevice import BaseDevice from apetools.commons.errors import ConfigurationError class IosDevice(BaseDevice): """ A class...
""" Not implemented :return: rssi from the wifi_query """ self.logger.warning('rssi query not implemented') return "NA" @property def bitrate(self): """ Not implemented :return: NA """ self.logger.warning("...
rn "NA" def disable_wifi(self): """ Not implemented """ self.logger.warning('disable wifi not implemented') return def enable_wifi(self): """ Not implemented """ self.logger.warning('enable wifi not implemented') return def l...
apophys/freeipa
ipaserver/install/server/install.py
Python
gpl-3.0
44,536
0.000135
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # from __future__ import print_function import errno import logging import os import pickle import shutil import sys import tempfile import textwrap import six from ipalib.install import certmonger, sysrestore from ipapython import ipautil from ip...
tion of generating a random password dm_password = read_password("Directory Ma
nager", validator=validate_dm_password) return dm_password def read_admin_password(): print("The IPA server requires an administrative user, named 'admin'.") print("This user is a regular system account used for IPA server " "administration.") print("") # ...
TaiSakuma/scribblers
tests/compare_obj.py
Python
bsd-3-clause
1,134
0.003527
# Tai Sakuma <tai.sakuma@gmail.com> import numbers ##__________________________________________________________________|| def cmp_obj_list_almost_equal(list1, list2, rtol=1e-05, atol=1e-08): if not len(list1) == len(list2): return False for obj1, obj2 in zip(list1, list2): if not cmp_obj_almost...
rdict.keys()) if not attrs1 == attrs2: return False for attr in attrs2: v1 = getattr(obj1, attr) v2 = getattr(obj2, attr) if v1 == v2: continue if isinstance(v2, number
s.Integral): return False if isinstance(v2, numbers.Real): if abs(v1 - v2) > (atol + rtol * abs(v2)): return False return True ##__________________________________________________________________||
edisonlz/fruit
web_project/base/site-packages/gridfs/__init__.py
Python
apache-2.0
11,413
0
# Copyright 2009-2012 10gen, Inc. # # Licensed under the Apache License, Version 2.0 (the "Li
cense"); # you may not use this file except in compliance with the License. # You may obtain a copy of t
he License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language ...
xuweiliang/Codelibrary
openstack_dashboard/dashboards/admin/overview/views.py
Python
apache-2.0
3,126
0.00032
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the...
retrieve project list.')) # for instance in data: # project = [t for t in projects if t.id == instance.tena
nt_id] # # If we could not get the project name, show the tenant_id with # # a 'Deleted' identifier instead. # if project: # instance.project_name = getattr(project[0], "name", None) # else: # deleted = _("Deleted") # instance.proj...
fcurella/cookiejar
tests/test_client.py
Python
mit
2,942
0.004079
import os from unittest import TestCase from cookiejar.client import CookiejarClient class Cli
entTests(TestCase): maxDiff = None def test_pagination(self): index = os.path.join((os.path.dirname(os.path.abspath(__file__))), 'index.1.json') client = CookiejarClient(index=index) expected = [ { u'id': 1, u'name': u'audreyr/pypacka...
a.zip', u'version': u'0.0.1', u'author': u'Audrey Roy', u'description': u'Cookiecutter template for a Python package.', u'checksum': "md5$a79cc0ef3897d14eeb3b5be6a37a5ff8", u'user': u'audreyr', }, { u...
SalesforceEng/Providence
providence.py
Python
bsd-3-clause
10,230
0.006158
''' Copyright (c) 2015, Salesforce.com, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the foll...
for repository_na
me, repository_data in repositories.items(): repository_watchers_by_path = watchers.get(repository_name) logger.info("In repo %s", repository_name) if repository_watchers_by_path is None: continue for repository_path, repo_watchers in repository_watchers_b...
flyinactor91/Raspi-Hardware
7Segment/Counter.py
Python
mit
481
0.035343
#!/usr/bin/python ##--Michael duPont (flyinactor91.com) ##--Display increasing values on the seven-segment display from Adafruit_7Segment import SevenSegment import time segment = SevenSegment(address=0x70) num = 0 rest = float(raw_input('Step: ')) while True: segment.setColon((num / 10000)%2) segment.wri
teDigit(0 , (num /
1000)%10) segment.writeDigit(1 , (num / 100)%10) segment.writeDigit(3 , (num / 10)%10) segment.writeDigit(4 , num % 10) num += 1 time.sleep(rest)
agartland/utils
.ipynb_checkpoints/quickr-checkpoint.py
Python
mit
5,563
0.007011
import subprocess import pandas as pd import tempfile import os __all__ = ['runRscript'] def runRscript(Rcmd, inDf=None, outputFiles=0, removeTempFiles=None): """Runs an R cmd with option to provide a DataFrame as input and file as output. Params ------ Rcmd : str String containing the R-...
ad.csv("%s")\n' % inputFn Rcmd = readCmd + Rcmd os.close(inputH) inDf.to_csv(inputFn) else: inputFilenames = [] for i, idf in enumerate(inDf): inputH, inputFn = tempfile.mkstemp(suffix='.csv', prefix='tmp-Rinput%d-' % i, text=True) ...
d = readCmd + Rcmd os.close(inputH) idf.to_csv(inputFn) inputFilenames.append(inputFn) """Set up an output file if required""" outFn = [] for outi in range(outputFiles): outputH, outputFn = tempfile.mkstemp(suffix='.txt', prefix='tmp-R...
ioGrow/iogrowCRM
crm/tests/test_mail.py
Python
agpl-3.0
811
0
import unittest from google.appengine.api import mail from google.appengine.ext import testbed class MailTestCase(unittest.TestCase): def setUp(self): self.testbed = testbed.Testbed() sel
f.testbed.activate() self.testbed.init_mail_stub() self.mail_stub = self.testbed.get_stub(testbed.MAIL_SERVICE_NAME) def tearDown(self): self.testbed.deactivate() def testMailSent(self): mail.send_mail(to='alice@example.com', subject='This is a test', ...
='alice@example.com') self.assertEqual(1, len(messages)) self.assertEqual('alice@example.com', messages[0].to)
davy39/eric
MultiProject/MultiProject.py
Python
gpl-3.0
32,000
0.004
# -*- coding: utf-8 -*- # Copyright (c) 2008 - 2014 Detlev Offenbach <detlev@die-offenbachs.de> # """ Module implementing the multi project management functionality. """ from __future__ import unicode_literals import os from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QFileInfo, QFile, \ QIODevice, QObject f...
""" super(MultiProject, self).__init__(parent) self.ui = parent self.projectObject
= project self.__initData() self.recent = [] self.__loadRecent() if filename is not None: self.openMultiProject(filename) def __initData(self): """ Private method to initialize the multi project data part. """ ...
nkremerh/cctools
prune/src/prune/class_item.py
Python
gpl-2.0
6,649
0.048428
import json, time import glob import timer from utils import * class Item(object): __slots__ = ( 'type', 'cbid', 'dbid', 'wfid', 'step', 'when', 'meta', 'body', 'repo', 'path', 'size', 'id' ) def __init__( self, obj={}, **kwargs ): # Three situations: Network streamed data (obj), Database data (obj), Newly create...
args) kwargs.update( obj ) self.type = kwargs['type'] self.cbid = kwargs['cbid'] if 'cbid' in kwargs else None self.dbid = kwargs['dbid'] if 'db
id' in kwargs else None self.wfid = kwargs['wfid'] if 'wfid' in kwargs else glob.workflow_id self.step = kwargs['step'] if 'step' in kwargs else glob.workflow_step self.when = kwargs['when'] if 'when' in kwargs else time.time() self.id = kwargs['id'] if 'id' in kwargs else None if 'meta' in kwargs: if isi...
h4r5h1t/django-hauthy
tests/model_forms/models.py
Python
bsd-3-clause
12,503
0.00192
""" XX. Generating HTML forms from models This is mostly just a reworking of the ``form_for_model``/``form_for_instance`` tests to use ``ModelForm``. As such, the text may not make sense in all cases, and the examples are probably a poor fit for the ``ModelForm`` syntax. In other words, most of these tests should be r...
ault=0) class Meta: unique_together = (('suffix1', 'suffix2')) abstract = True class DerivedBook(Book, BookXtra): pass @python_2_unicode_compatible class ExplicitPK(
models.Model): key = models.CharField(max_length=20, primary_key=True) desc = models.CharField(max_length=20, blank=True, unique=True) class Meta: unique_together = ('key', 'desc') def __str__(self):
Tayamarn/socorro
e2e-tests/pages/crash_report_page.py
Python
mpl-2.0
2,049
0.00244
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from pypom import Region from selenium.webdriver.common.by import By from pages.base_page import ...
'td:nth-of-type(4)') _report_date_link_locator = (By.CSS_SELECTOR, '#reports-list a.external-link') @property d
ef product(self): return self.find_element(*self._product_locator).text @property def version(self): return self.find_element(*self._version_locator).text def click_report_date(self): self.find_element(*self._report_date_link_locator).click() fro...
oracc/nammu
python/nammu/test/test_yaml_update.py
Python
gpl-3.0
2,813
0
''' Copyright 2015 - 2018 University College London. This file is part of Nammu. Nammu 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. Nam...
# Make sure the user (project) setting is not overwritten assert (new_config["projects"]["default"] == orig_config["projects"]["default"]) def test_settings_copied_correctly(monkeypatch, tmpdir):
""" Check that the settings are initialised correctly at first launch. More specifically, this test ensures that, if the user starts Nammu without already having any configuration files, then local configuration files with the correct content will be created, without affecting the original files. ...
resmo/ansible
lib/ansible/modules/identity/keycloak/keycloak_client.py
Python
gpl-3.0
33,175
0.003044
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2017, Eike Frost <ei@kefro.st> # 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...
- Default URL to use when the auth server needs to redirect or link back to the client This is 'baseUrl' in the Keycloak REST API. aliases: - baseUrl enabled: description: - Is this client enabled or not? type: bool client_authenticator_ty...
- How do clients authenticate with the auth server? Either C(client-secret) or C(client-jwt) can be chosen. When using C(client-secret), the module parameter I(secret) can set it, while for C(client-jwt), you can use the keys C(use.jwks.url), C(jwks.url), and C(jwt.credenti...
saisankargochhayat/algo_quest
Company-Based/SAP/social_sabatical_name.py
Python
apache-2.0
938
0.007463
# maximum number of letters(ignoring spaces and duplicates) if tie choose alphabetical order. # import sys # text = "".join(sys.stdin.readlines()) # name_list = text.split("\n") inputList = ["kylan charles", "raymond strickland", "juliss
a shepard", "andrea meza", "destiny alvarado"] inputList2 = ["maria garcia", "smith hernandez", "hernandez smith", "mary martinez", "james johnson"] inputList3 = ["Sheldon Cooper", "Howord Wolowitz", "Amy Farrah Fowler", "Leo
nard Hofstadter", "Bernadette R"] name_store = {} for name in inputList3: name_store[name] = len(set(name.lower().replace(" ", ""))) # Remove spaces using replace and remove duplicates using set res = [] maxLen = -float("inf") for name in name_store.keys(): if name_store.get(name) > maxLen: res.clear(...
bastorer/SPINSpy
spinspy/isdim.py
Python
mit
178
0.011236
import os from spinspy import local_data def isdim(dim):
if os.path.isfile('{0:s}{1:s}grid'.format(local_data.path,dim)): return True else:
return False
sheshkovsky/jaryan
links/utils.py
Python
apache-2.0
1,792
0.029576
from django.db.models import Q from links.models import Post from comments.models import ThreadedComment as comments from django.utils import timezone from datetime import datetime, timedelta from django.contrib import messages KARMA_LOW = 100 KARMA_MEDIUM = 1000 KARMA_HIGH = 5000 INTERVAL_LOW = 3600 INTERVAL_MEDIUM...
es.success(request, 'Please try in an hour!') return result elif karma > KARMA_LOW and karma < KARMA_HIGH: result = diff > INTERVAL_MEDIUM if not result: messages.success(request, 'Please try in ten minutes!') return result else: result = diff > INTERVAL_HIGH if not result: messages.warning(request,...
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip
nyaruka/motome
motome/public/views.py
Python
bsd-3-clause
11,780
0.005772
from decimal import Decimal from customers.models import Customer from django.contrib import auth from products.models import * from django_quickblocks.models import * import re from smartmin.views import * from django.http import HttpResponse, HttpResponseRedirect from django.template import RequestContext from django...
er) customer = Cus
tomer.get_or_create_customer(phone_number) customer.send_password() request.session['customer'] = customer return HttpResponseRedirect(reverse('public_login')) else: form=LoginForm(initial_data) context = dict(order=order, country=country, currency=country.currency,...
Havate/havate-openstack
proto-build/gui/horizon/openstack-dashboard/config/views.py
Python
apache-2.0
15,052
0.007109
import os import subprocess import yaml from django.views.generic import View from django.views.generic.base import TemplateView from django.views.generic.edit import FormView from django.core.urlresolvers import reverse from django.core import serializers from django.conf import settings from django.template.loader i...
nt[hostname]['power_address'] =ip else: processed_cobbler_content[hostname] = {'hostname': hostname, 'power_address':ip} traverse_tree(processed_cobbler_content) # with open(cobbler_file_path, 'w') as content_file: # ...
.objects.all().delete() nodes = int(self.request.POST.get('node_number', 0)) for x in range(nodes): node_name = self.request.POST.get('node_name__'+str(x), "") node_number = x chassis_number = int(self.request.POST.get('chassis_number__'+str(x), 0)...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.3/Lib/plat-mac/lib-scriptpackages/CodeWarrior/CodeWarrior_suite.py
Python
mit
23,097
0.012296
"""Suite CodeWarrior suite: Terms for scripting the CodeWarrior IDE Level 0, version 0 Generated from /Volumes/Sap/Applications (Mac OS 9)/Metrowerks CodeWarrior 7.0/Metrowerks CodeWarrior/CodeWarrior IDE 4.2.5 AETE/AEUT resource version 1/0, language 0, script 0 """ import aetools import MacOS _code = 'CWIE' class...
XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----'] def build(self, _no_object=None, _attributes={}, **_arguments): """build: build a project or target (equivalent of the Make men
u command) Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'CWIE' _subcode = 'MAKE' if _arguments: raise TypeError, 'No optional args expected' if _no_object != None: raise TypeError, 'No direct arg expected' _reply, _arguments, _attri...
bkonersman/utils
seqCheck.py
Python
artistic-2.0
1,631
0.010423
#! /usr/bin/env python #edited on c9 import os import array as array import sys if (len(sys.argv)==1): print "usage >>seqCheck.py [fileRootName, path ('.') for cwd]" sys.exit() elif (len(sys.argv)==2): fileRootName = sys.argv[1] rootpath = os.getcwd() elif (len(sys.argv)==3): fileRootName = sys.a...
l_path = os.path.realpath(__file__) print(full_path
+ "\n") print("This file directory and name") path, file = os.path.split(full_path) print(path + ' --> ' + file + "\n") print("This file directory only") print(os.path.dirname(full_path)) ''' f = [] for (dirpath,dirnames,filenames) in os.walk(rootpath): #print filenames f.extend(filenames) br...