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
zerc/django-sirtrevor
sirtrevor/fields.py
Python
mit
974
0.00308
import json from django.db import models from django.conf import settings from django.utils.six import with_metaclass, text_type from django.utils.translation import ugettext_lazy as _ from . import SirTrevorContent from .forms import SirTrevorFormField class SirTrevorFiel
d(with_metaclass(models.SubfieldBase, models.Field)): description = _("TODO") def get_internal_type(self): return 'TextField' def formfield(self, **kwargs): defaults = { 'form_class': SirTrevorFormField }
defaults.update(kwargs) return super(SirTrevorField, self).formfield(**defaults) def to_python(self, value): return SirTrevorContent(value) def get_db_prep_value(self, value, connection, prepared=False): return text_type(value) if 'south' in settings.INSTALLED_APPS: from south...
ProjectSWGCore/NGECore2
scripts/object/weapon/ranged/pistol/weapon_pistol_trader_roadmap_01_02.py
Python
lgpl-3.0
580
0.037931
import sys from resources.datatables import WeaponType def setup(core, object): object.setStfFilename('stati
c_item_n') object.setStfName('weapon_pistol_trader_roadmap_01_02') object.setDetailFilename('static_item
_d') object.setDetailName('weapon_pistol_trader_roadmap_01_02') object.setStringAttribute('class_required', 'Trader') object.setIntAttribute('required_combat_level', 62) object.setAttackSpeed(0.4); object.setMaxRange(35); object.setDamageType("energy"); object.setMinDamage(250); object.setMaxDamage(500); obje...
ceb8/astroquery
astroquery/irsa_dust/__init__.py
Python
bsd-3-clause
317
0.003155
# Licensed under a 3-clause BSD style license - see LICENSE.rst import warnings warnings.warn("the ``irsa_dust`` module has been moved to " "astroquery.ipac.irsa.irsa_dust, "
"please update your imports.", DeprecationWarning, stacklevel=2) from astroq
uery.ipac.irsa.irsa_dust import *
icandigitbaby/openchange
script/bug-analysis/test_sqlite.py
Python
gpl-3.0
9,687
0.002684
""" Unit tests over SQLite backend for Crash Database """ from apport.report import Report import os from unittest import TestCase from sqlite import CrashDatabase class CrashDatabaseTestCase(TestCase): def setUp(self): self.crash_base = os.path.sep + 'tmp' self.crash_base_url = 'file://' + self....
h_id = cb.upload(se
lf.r) self.assertIsNone(cb.get_distro_release(crash_id)) self.r['DistroRelease'] = 'Ubuntu 14.04' crash_id = cb.upload(self.r) self.assertEqual(cb.get_distro_release(crash_id), 'Ubuntu 14.04') def test_get_unretraced(self): cb = CrashDatabase(None, {'dbfile': ':memory:', '...
huaweiswitch/neutron
neutron/tests/unit/linuxbridge/test_lb_neutron_agent.py
Python
apache-2.0
48,351
0.000041
# Copyright (c) 2012 OpenStack 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 # # Unless required by applicable...
self.assertTrue(flat_bridge_func.called) def test_ensure_physical_in_bridge_vlan(self): with mock.patch.object(self.linux_bridge, 'ensure_vlan_bridge') as vlan_bridge_func: self.linux_bridge.ensure_physical_in_bridge( 'network_id', p_const.TYPE_...
ridge_vxlan(self): self.linux_bridge.vxlan_mode = lconst.VXLAN_UCAST with mock.patch.object(self.linux_bridge, 'ensure_vxlan_bridge') as vxlan_bridge_func: self.linux_bridge.ensure_physical_in_bridge( 'network_id', 'vxlan', 'physnet1', 7) ...
realmarcin/transform
lib/biokbase/Transform/script_utils.py
Python
mit
3,187
0.011923
import sys import logging import time import requests from biokbase.AbstractHandle.Client import AbstractHandle def getStderrLogger(name, level=logging.INFO): logger = logging.getLogger(name) logger.setLevel(level) # send messages to sys.stderr streamHandler = logging.StreamHandler(sys.__stderr...
handles.append(single_handle[0]) except: logger.error("The input shock node id {} is already registered or could not be r
egistered".format(sid)) raise elif handle_ids is not None: for hid in handle_ids: try: single_handle = hs.hids_to_handles([hid]) assert len(single_handle) != 0 handles.append(single_handle[0]) excep...
tgraf/libnl
doc/resolve-asciidoc-refs.py
Python
lgpl-2.1
521
0.026871
#!/usr/bin/env pyth
on import fileinput import re import sys
refs = {} complete_file = "" for line in open(sys.argv[1], 'r'): complete_file += line for m in re.findall('\[\[(.+)\]\]\n=+ ([^\n]+)', complete_file): ref, title = m refs["<<" + ref + ">>"] = "<<" + ref + ", " + title + ">>" def translate(match): try: return refs[match.group(0)] except KeyError: return "...
serggrom/python-projects
Aplication_B.py
Python
gpl-3.0
1,409
0.003549
''' import csv from collections import Counter counts = Counter() with open ('zoo.csv') as fin: cin = csv.reader(fin) for num, row in enumerate(cin): if num > 0: counts[row[0]] += int (row[-1]) for animal, hush in counts.items()
: print("%10s %10s" % (animal, hush)) ''' ''' import bubbles p = bubbles.Pipeline() p.source(bubbles.data_object('csv_source', 'zoo.csv', inter_field=True)) p.aggregate('animal', 'hush') p.pretty_print() ''' def display_shapefile(name, iwidth=500, iheight=500): import shapefile from PIL import Ima...
, mright, mtop = r.bbox # map units mwidth = mright - mleft mheight = mtop - mbottom # scale map units to image units hscale = iwidth/mwidth vscale = iheight/mheight img = Image.new("RGB", (iwidth, iheight), "white") draw = ImageDraw(img) for shape in r.shapes(): pixels = [ ...
holmes-app/holmes-api
holmes/validators/image_alt.py
Python
mit
3,935
0
#!/usr/bin/python # -*- coding: utf-8 -*- from holmes.validators.base import Validator from holmes.utils import _ class ImageAltValidator(Validator): @classmethod def get_without_alt_parsed_value(cls, value): result = [] for src, name in value: data = '<a href="%s" target="_blank"...
not src: continue src = self.normalize_url(src) img_alt = img.get('alt') if src: name = src.rsplit('/', 1)[-1]
if not img_alt: result_no_alt.append((src, name)) elif len(img_alt) > max_alt_size: result_alt_too_big.append((src, name, img_alt)) if result_no_alt: self.add_violation( key='invalid.images.alt', value=result...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_10_01/aio/operations/_network_interface_load_balancers_operations.py
Python
mit
5,732
0.004187
# 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 ...
args.pop('cls', None) # type: ClsType["_models.NetworkInterfaceLoadBalancerListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-10-01" accep...
are_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url']...
ClaudiaSaxer/PlasoScaffolder
src/tests/fake/fake_sqlite_plugin_helper.py
Python
apache-2.0
7,987
0.004132
# -*- coding: utf-8 -*- # this default value is just for testing in a fake. # pylint: disable=dangerous-default-value """Fake Module containing helper functions for the SQLite plugin""" from plasoscaffolder.bll.services import base_sqlite_plugin_helper from plasoscaffolder.bll.services import base_sqlite_plugin_path_he...
executor: base_sql_query_execution.BaseSQLQueryExecution()): """ Validates the
sql Query Args: executor (base_sql_query_execution.SQLQueryExection()) the sql executor query (str): the sql Query Returns: base_sql_query_execution.SQLQueryData: the data to the executed Query """ return executor.ExecuteQuery(query) def GetDistinctColumnsFromSQLQueryData( ...
nuclear-wizard/moose
python/MooseDocs/test/extensions/test_core.py
Python
lgpl-2.1
3,665
0.004093
#!/usr/bin/env python3 #* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/licenses/lgp...
''Break\\ this''' ast = self.tokenize(text) self.assertToken(ast(0), 'Paragraph', size=3)
self.assertToken(ast(0)(0), 'Word', content='Break') self.assertToken(ast(0)(1), 'LineBreak') self.assertToken(ast(0)(2), 'Word', content='this') def testEscapeCharacter(self): text = "No \[link\] and no \!\! comment" ast = self.tokenize(text) self.assertToken(ast(0), 'Pa...
Orav/kbengine
kbe/src/lib/python/Lib/lib2to3/fixes/fix_raw_input.py
Python
lgpl-3.0
471
0.002123
"""Fixer that changes raw_input(...) into input(...).""" # Author: Andre Roberge # Local imports from .. import fixer_base from ..fixer_util import Name class FixRa
wInput(fixer_base.BaseFix): BM_compatible = True PATTERN = """ power< name='raw_input' trailer< '(' [any] ')' > any* > """ def transform(self, node, results): name = results["name"] name.re
place(Name("input", prefix=name.prefix))
devonhollowood/adventofcode
2018/day09.py
Python
mit
3,328
0.0003
#!/usr/bin/env python3 """ 2018 AOC Day 09 """ import argparse import ty
ping import unittest
class Node(object): ''' Class representing node in cyclic linked list ''' def __init__(self, prev: 'Node', next: 'Node', value: int): ''' Create a node with explicit parameters ''' self._prev = prev self._next = next self._value = value @staticmethod def default() -> '...
antgonza/qp-shotgun
qp_shogun/sortmerna/sortmerna.py
Python
bsd-3-clause
6,980
0
# ----------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
name = 'Ribosomal reads' ainfo.extend(_per_sample_ainfo( out_dir
, samples, suffixes, prg_name, file_type_name, bool(rs))) return True, ainfo, ""
SymbiFlow/fpga-tool-perf
utils/utils.py
Python
isc
5,117
0.000391
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2018-2022 F4PGA Authors # # 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 # # Unl...
cense 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 governing permissions and # limitations under the License. # # SPDX-License-Identifier: Apache-2.0 import time import os class Timed: def __init__(self,...
self.unprinted_runtime = unprinted_runtime def __enter__(self): self.start = time.time() def __exit__(self, type, value, traceback): end = time.time() self.t.add_runtime( self.name, end - self.start, unprinted_runtime=self.unprinted_runtime ...
emsrc/timbl-tools
setup.py
Python
gpl-3.0
3,905
0.014597
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2007-2013 by Erwin Marsi and TST-Centrale # # This file is part of the DAESO Framework. # # The DAESO Framework 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 Softwa...
rmtree if exists('MANIFEST'): remove('MANIFEST') if exists("build"): rmtree("build") name = "timbl-tools" version = "0.5.0" description = """Timbl Tools is a collection of Python modules and scripts for working with TiMBL, the Tilburg Memory-based Learner.""" long_description = """ Timbl Tools is a co
llection of Python modules and scripts for working with TiMBL, the Tilburg Memory-based Learner. It provides support for: * creating Timbl servers and clients * running (cross-validated) experiments * lazy parsing of verbose Timbl ouput (e.g. NN distributions) * down-sampling of instances * writing ascii graphs of the...
lmazuel/azure-sdk-for-python
azure-mgmt-applicationinsights/azure/mgmt/applicationinsights/operations/__init__.py
Python
mit
1,314
0.001522
# 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 ...
s_operations import ExportConfigurationsOperations from .proactive_detection_configurations_operations import ProactiveDetectionConfigurationsOperations from .component_current_billing_features_operations import ComponentCurrentBillingFeaturesOperations from .component_quota_status_operations import ComponentQuotaStatu...
'WebTestsOperations', 'ExportConfigurationsOperations', 'ProactiveDetectionConfigurationsOperations', 'ComponentCurrentBillingFeaturesOperations', 'ComponentQuotaStatusOperations', 'APIKeysOperations', ]
whodewho/FluxEnder
src/extract_feature.py
Python
gpl-2.0
3,943
0.003297
from extract_feature_lib import * from sys import argv from dga_model_eval import * from __init__ import * def clear_cache(index, cache): print "clear cache", index for tmp in cache: client[db_name][coll_name_list[index]+"_matrix"].insert(cache[tmp]) def extract_domain_feature(index): #cursor = ...
float(number), 3) cache[row["_id"]] = {"number": number, "dd": dd, "ips": ips, "dga": dga, "ttl": [min_ttl, max_ttl], "lifetime": lifetime, "_id": row["_id"]} # client[db_name][coll_name_list[index]+"_matrix"].insert(tmp) clear_cache(index, cache) def main(index): ...
8): extract_ip_feature(i) for i in range(0, 4): extract_domain_feature(i) if __name__ == '__main__': script, db_name = argv main(8)
luca-vercelli/l10n-italy
l10n_it_invoice_report/invoice.py
Python
agpl-3.0
1,213
0.004122
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2011 OpenERP Italian Community (<http://www.openerp-italia.org>). # # 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 option) any later version. # # This program is distributed in the 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 General Public License for more details. # # ...
leecannon/trending
trending/command_line.py
Python
mit
5,764
0.002255
# Copyright (c) 2016 Lee Cannon # Licensed under the MIT License, see included LICENSE File import click import os import re from datetime import datetime def _is_file_modnet(file_name: str) -> bool: """Returns True if the filename contains Modnet. :param file_name: The filename to check. :type file_nam...
ntents.replace( '<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/re
quire.min.js"></script>', '<script>' + require + '</script>') # Replace jQuery CDN with full code. with open(includes + 'jquery.min.js', 'r') as f: jquery = f.read() contents = contents.replace( '<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></scrip...
phrocker/sharkbite
test/python/TestSecurityOperations.py
Python
apache-2.0
3,290
0.061398
from testmodule import * import sys class TestWrites(TestRunner): def __init__(self): super().__init__() def mthd(self): import pysharkbite securityOps = super().getSecurityOperations() securityOps.create_user("testUser","password") ## validate that we DON'T see the permissions assert( Fals...
"testUser",pysharkbite.SystemPermissions.CREATE_TABLE) ) auths = pysharkbite.Authorizations() auths.addAuthorization("blah1") auths.addAuthorization("blah2") securityOps.grantAuthorizations(auths,"testUser")
tableOperations = super().getTableOperations() tableOperations.create(False) ## validate that we DO see the permissions securityOps.grant_table_permission("testUser",super().getTable(),pysharkbite.TablePermissions.READ ) securityOps.grant_table_permission("testUser",super().getTable(),pysharkbite.TableP...
cflq3/getcms
plugins/jiasule_cloudsec.py
Python
mit
126
0.007937
#!/usr/bin/env python
# encoding: utf-8 def run(whatweb, pluginname): whatweb.recog
_from_header(pluginname, "X-Cache")
felipenaselva/felipe.repository
script.module.placenta/lib/resources/lib/sources/en/to_be_fixed/sitedown/savaze.py
Python
gpl-2.0
4,194
0.010491
# -*- coding: UTF-8 -*- ####################################################################### # ---------------------------------------------------------------------------- # "THE BEER-WARE LICENSE" (Revision 42): # @tantrumdev wrote this file. As long as you retain this notice you # can do whatever you want wit...
[] lst = ['1080p','720p','bluray-2','bluray'] clean_season = season if len(season) >= 2 else '0'
+ season clean_episode = episode if len(episode) >= 2 else '0' + episode for i in lst: url = urlparse.urljoin(self.base_link, self.movies_search_path % (imdb) + '-s%se%s-%s' % (clean_season, clean_episode, i)) r = client.request(url) if r: urls.ap...
emersonmx/ippl
ippl/test/render.py
Python
gpl-3.0
1,381
0.003621
# # Copyright (C) 2013-2014 Emerson Max de Medeiros Silva # # This file is part of ippl. # # ippl 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...
r FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with
ippl. If not, see <http://www.gnu.org/licenses/>. # import math from ippl.shape import * from ippl.render import * if __name__ == "__main__": s = Shape() # IV - Lines l = Line(Point(0, 0), Point(50, 25)) s.outer_loop.append(l) l = Line(Point(50, 25), Point(0, 0)) l.move(0, 30) s.outer_lo...
sdiehl/ghc
docs/users_guide/compare-flags.py
Python
bsd-3-clause
2,799
0.002145
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Linter to verify that all flags reported by GHC's --show-options mode are documented in the user's guide. """ import sys import subprocess from typing import Set from pathlib imp
ort Path # A list of known-undocumented flags. This should be considered to be a to-do # list of flags that need to be documented
. EXPECTED_UNDOCUMENTED_PATH = \ Path(__file__).parent / 'expected-undocumented-flags.txt' EXPECTED_UNDOCUMENTED = \ {line for line in open(EXPECTED_UNDOCUMENTED_PATH).read().split()} def expected_undocumented(flag: str) -> bool: if flag in EXPECTED_UNDOCUMENTED: return True if flag.startswith...
hlzz/dotfiles
graphics/VTK-7.0.0/Imaging/Core/Testing/Python/reconstructSurface.py
Python
bsd-3-clause
3,635
0.001926
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ========================================================================= Program: Visualization Toolkit Module: TestNamedColorsIntegration.py Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or ...
3337.pts", "r") points = vtk.vtkPoints() while True: line = fp.readline().split() if len(line) == 0: break if line[0] == "p": points.InsertNextPoint(float(line[1]), float(line[2]), float(line[3])) ...
etPoints(points) pointSource.SetExecuteMethod(readPoints) # Construct the surface and create isosurface # surf = vtk.vtkSurfaceReconstructionFilter() surf.SetInputConnection(pointSource.GetOutputPort()) cf = vtk.vtkContourFilter() cf.SetInputConnectio...
praekelt/molo.profiles
molo/profiles/migrations/0007_add_password_recovery_retries.py
Python
bsd-2-clause
845
0.002367
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-09-01 11:41 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('profiles', '0006_add_show_security_question
_field'), ] operations = [ migrations.AddField( model_name='userprofilessettings',
name='num_security_questions', field=models.PositiveSmallIntegerField(default=3, verbose_name='Number of security questions asked for password recovery'), ), migrations.AddField( model_name='userprofilessettings', name='password_recovery_retries', ...
assemblio/project-nastradin
nastradini/views/forms/position.py
Python
gpl-2.0
700
0
from flask import render_template, redirect, url_for, request from flask.views import MethodView from nastradini import mongo, utils from positionform import PositionForm class Position(MethodView): methods = ['GE
T', 'POST'] def get(self): form = PositionForm() return render_template('position.html', form=form) def post(self): # First, let's get the doc id. doc_id = utils.get_doc_id() # Create position info object. form = PositionForm(request.form) json = form.d...
ngo.db.positions.update({'_id': doc_id}, json, True) return redirect(url_for('browse_internal_positions'))
M4sse/chromium.src
tools/gn/bin/gyp_flag_compare.py
Python
bsd-3-clause
7,719
0.010882
#!/usr/bin/env python # Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Given the output of -t commands from a ninja build for a gyp and GN generated build, report on differences between the command line...
GN:\n %s' % '\n '.join( sorted(gyp_files - gn_files)) print ' In GN, not in gyp:\n %s' % '\n '.join( sorted(gn_files - gyp_files)) print '\nNote that flags will only be compared for files in both sets.\n' file_list = gyp_files & gn_files files_with_given_differences = {} for ...
Lists(gyp_flags, gn_flags, 'dash_f') differences += CompareLists(gyp_flags, gn_flags, 'defines') differences += CompareLists(gyp_flags, gn_flags, 'include_dirs') differences += CompareLists(gyp_flags, gn_flags, 'warnings', dont_care_gn=[ # More conservative warnings in GN we consider to be OK. ...
harunyasar/rabbitmq_playground
default_exchange_sender.py
Python
gpl-3.0
166
0
from sender i
mport * if __name__ == '__main__': connection = Connection().initialize()
connection.send('Default exchange message!') connection.destroy()
modulexcite/wal-e
wal_e/blobstore/wabs/wabs_util.py
Python
bsd-3-clause
9,211
0
import base64 import collections import errno import gevent import os import socket import sys import traceback from azure import WindowsAzureMissingResourceError from azure.storage import BlobService from . import calling_format from hashlib import md5 from urlparse import urlparse from wal_e import log_help from wa...
ret_size + WABS_CHUNK_SIZE - 1) while True:
# Because we're downloading in chunks, catch rate limiting and # connection errors here instead of letting them bubble up to the # @retry decorator so that we don't have to start downloading the # whole file over again. try: part = conn.get_blob(url_t...
d120/pyophase
exam/dashboard_urls.py
Python
agpl-3.0
483
0
from django.urls import path from . import dashboard_views app_name = 'exam' urlpa
tterns = [ path('assignment/new/', dashboard_views.MakeAssignmentView.as_view(), name='as
signment_new'), path('assignment/success/', dashboard_views.MakeAssignmentSuccess.as_view(), name='assignment_success'), path('assignment/<int:assignment_id>/name_list/', dashboard_views.AssignmentNameListView.as_view(), name='assignment_name_list'), ]
bellowsj/aiopogo
aiopogo/pogoprotos/networking/requests/messages/release_pokemon_message_pb2.py
Python
mit
2,798
0.007505
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: pogoprotos/networking/requests/messages/release_pokemon_message
.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor
as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _desc...
curious-containers/faice
faice/__main__.py
Python
gpl-3.0
1,622
0.003083
import os import sys import textwrap from collections import OrderedDict from argparse import ArgumentParser, RawDescriptionHelpFormatter from faice.tools.run.__main__ import main as run_main from faice.tools.run.__main__ import DESCRIPTION as RUN_DESCRIPTION from faice.tools.vagrant.__main__ import main as vagrant_ma...
r certain conditions. See the LICENSE file distributed with this software for details.', ] parser = ArgumentParser( description=os.linesep.join([textwra
p.fill(block) for block in description]), formatter_class=RawDescriptionHelpFormatter ) parser.add_argument( '-v', '--version', action='version', version=VERSION ) subparsers = parser.add_subparsers(title="tools") sub_parser = subparsers.add_parser('run', help=RUN_DESCRIPTION, add_h...
tcqiuyu/aquam
aquam/apps/geoanalytics/models.py
Python
mit
1,526
0.003277
from django.contrib.gis.db import models # Create your models here. class GeoWaterUse(models.Model): id = models.AutoField(primary_key=True) geometry = models.PointF
ield() api = models.CharField(max_length=20, null=False) well_name = models.CharField(max_length=100, null=True) frac_date = models.DateField(auto_now=False, auto_now_add=F
alse) state = models.CharField(max_length=20, null=True) county = models.CharField(max_length=20, null=True) latitude = models.DecimalField(max_digits=20, decimal_places=6) longitude = models.DecimalField(max_digits=20, decimal_places=6) horizontal_length = models.DecimalField(max_digits=20, decimal...
vitan/openrave
sandbox/debugkinbody.py
Python
lgpl-3.0
4,041
0.022272
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the...
lveeq.subs([(sin(theta/2),sthetad2),(cos(theta/2),cthetad2)]),sthetad2,cthetad2) # shoul
d be: # Poly((qw**2/2 + qx**2/2 + qy**2/2 + qz**2/2 - qw**2*vx**2/2 - qw**2*vy**2/2 - qw**2*vz**2/2 - qx**2*vx**2/2 - qx**2*vy**2/2 - qx**2*vz**2/2 - qy**2*vx**2/2 - qy**2*vy**2/2 - qy**2*vz**2/2 - qz**2*vx**2/2 - qz**2*vy**2/2 - qz**2*vz**2/2)*sthetad2*cthetad2 - qx/2*sthetad2 + (-qw*vz/2 - qy*vx/2 - qz*vy/2)*cthe...
SergeySatskiy/codimension
codimension/utils/config.py
Python
gpl-3.0
1,187
0
# -*- coding: utf-8 -*- # # codimension - graphics python two-way code editor and analyzer # Copyright (C) 2010-2017 Sergey Satskiy <sergey.satskiy@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Softw...
the encoding could not be detected # - replaces ascii to be on the safe side DEFAULT_ENCODING = 'utf-8' # File encoding used for various settings and project
files SETTINGS_ENCODING = 'utf-8' # Directory to store Codimension settings and projects CONFIG_DIR = '.codimension3'
ShyamSS-95/Bolt
example_problems/nonrelativistic_boltzmann/beam_test/1D/domain.py
Python
gpl-3.0
225
0.044444
q1_start = 0 q1_end = 1 N_q1 = 128 q2_start = 0 q2_end = 1
N_q2 = 3 p1_start = -4 p1_end = 4 N_p1 = 4 p2_start = -0.5 p2
_end = 0.5 N_p2 = 1 p3_start = -0.5 p3_end = 0.5 N_p3 = 1 N_ghost = 3
sigopt/sigopt-python
sigopt/orchestrate/cluster/service.py
Python
mit
5,588
0.0102
from ..provider.constants import Provider, string_to_provider from ..services.base import Service from .context import DisconnectOnException from .errors import ( AlreadyConnectedException, ClusterError, MultipleClustersConnectionError, NotConnectedError, PleaseDisconnectError, ) class ClusterService(Servic...
e: raise AlreadyConnectedException(e.current_cluster_name) from e
raise provider = string_to_provider(provider_string) provider_service = self.services.provider_broker.get_provider_service(provider) if kubeconfig is None: kubeconfig = provider_service.create_kubeconfig(cluster_name) else: assert provider == Provider.CUSTOM, "Must use --provider cust...
NeuPhysics/codebase
ipynb/matter/py-server/save-data-on-site.py
Python
mit
2,819
0.023058
import numpy as np from scipy.integrate import odeint from scipy.integrate import ode import matplotlib.pylab as plt import csv import time endpoint = 1000000000; # integration range dx = 10.0; # step size lam0 = 0.845258; # in unit of omegam, omegam = 3.66619*10^-17 dellam = np.array([0.00003588645221954444, 0.06486...
, 0.0], 0 # initial condition savestep = 100000; # save to file every savestep steps xlin = np.arange(dx,endpoint+1*dx, dx) psi = np.zeros([len(
xlin) , 2], dtype='complex_') xlinsave = np.zeros(len(xlin)/savestep); psisave = np.zeros([len(xlinsave) , 2], dtype='complex_') probsave = np.zeros([len(xlinsave) , 3]) def hamiltonian(x, deltalambda, k, thetam): return [[ 0, 0.5* np.sin(2*thetam) * ( deltalambda[0] * np.sin(k[0]*x) + deltalambda[1] * np....
knights-lab/analysis_SHOGUN
scripts/parse_shear.py
Python
mit
2,010
0.000498
#!/usr/bin/env python # Usage parse_shear sequences.fna a2t.txt emb_output.b6 import sys import csv from collections import Counter, defaultdict sequences = sys.argv[1] accession2taxonomy = sys.argv[2] alignment = sys.argv[3] with open(accession2taxonomy) as inf: next(inf) csv_inf = csv.reader(inf...
or i, species in enumerate(counts_dict.keys()): row = [0] * 10 row[-1] = reads_counter[species] row[0] = species counts = counts_dict[species] if i % 10000 == 0: print("Processed %d records" % i) print(counts) for j in counts.keys(): ...
)) outf.write("\t".join(row) + "\n")
VillanCh/g3ar
g3ar/threadutils/thread_pool.py
Python
bsd-2-clause
9,669
0.005378
#!/usr/bin/env python #coding:utf-8 """ Author: --<v1ll4n> Purpose: Provide some useful thread utils Created: 2016/10/29 """ import unittest #import multiprocessing from pprint import pprint from time import sleep try: from Queue import Full, Empty, Queue except: from queue import Full, ...
r=self, clean_mod=self._clean_mod)
_tmp_labor.daemon = True _tmp_labor.start() self._current_thread.append(_tmp_labor) #---------------------------------------------------------------------- def feed(self, target_func, *vargs, **kwargs): """""" self._task_queue.put(tuple([target_func, vargs, kwargs]...
vportascarta/UQAC-8INF844-SPHERO
agents/ExempleAgentReceveur.py
Python
gpl-3.0
789
0
import spade import time class MyAgent(spade.Agent.Agent): class ReceiveBehav(spade.Behaviour.Behaviour): """This behaviour will receive all kind of messages""" def _proc
ess(self): self.msg = None # Blocking receive for 10 seconds self.msg = self._receive(True, 10) # Check wether the message arrived if self.msg: print "I got a message!" else: print "I waited but got no message" ...
haviour rb = self.ReceiveBehav() self.setDefaultBehaviour(rb) if __name__ == "__main__": a = MyAgent("agent2@127.0.0.1", "secret") a.start()
liqd/a4-meinberlin
meinberlin/apps/plans/migrations/0018_point_label_required.py
Python
agpl-3.0
621
0.00161
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-09-20 15:04 from __future__ import unicode_literals from django.db import migrations from django.db import models class Migration(migrations.Migration): dep
endencies = [ ('meinberlin_plans', '0017_rename_cost_field'), ] operations = [ migrations.AlterField( model_name='plan', name='point_label', field=models.CharField(default=
'Label of the location', help_text='This could be an address or the name of a landmark.', max_length=255, verbose_name='Label of the location'), ), ]
fako/datascope
src/core/tests/mocks/http.py
Python
gpl-3.0
3,044
0
from unittest.mock import Mock from django.db.models import QuerySet from datagrowth.resources import HttpResource fr
om core.tests.mocks.requests import MockRequests MockErrorQuerySet = Mock(QuerySet) MockErrorQuerySet.count = Mo
ck(return_value=0) class HttpResourceMock(HttpResource): URI_TEMPLATE = "http://localhost:8000/{}/?q={}" PARAMETERS = { "param": 1 } HEADERS = { "Accept": "application/json" } GET_SCHEMA = { "args": { "title": "resource mock arguments", "type": ...
weitzner/Dotfiles
pymol_scripts/axes_cyl.py
Python
mit
853
0.078546
from pymol.cgo import * from pymol import cmd from pymol.vfont import plain # create the axes object, draw axes with cylinders coloured red, green, #blue for X, Y and Z obj = [ CYLINDER, 0., 0., 0., 10., 0., 0., 0.2, 1.0, 1.0, 1.0, 1.0, 0.0, 0., CYLINDER, 0., 0., 0., 0., 10., 0., 0.2, 1.0, 1.0, 1.0, 0., 1.0, 0....
n',0.20,axes=[[3.0,0.0,0.0],[0.0,3.0,0.0],[0.0,0.0,3.0]]) cyl_text(obj,plain,[10.,0.,0.],'X',0.20,axes=[[3.0,0.0,0.0],[0.0,3.0,0.0],[0.0,0.0,3.0]]) c
yl_text(obj,plain,[0.,10.,0.],'Y',0.20,axes=[[3.0,0.0,0.0],[0.0,3.0,0.0],[0.0,0.0,3.0]]) cyl_text(obj,plain,[0.,0.,10.],'Z',0.20,axes=[[3.0,0.0,0.0],[0.0,3.0,0.0],[0.0,0.0,3.0]]) # then we load it into PyMOL cmd.load_cgo(obj,'axes')
aonotas/chainer
chainer/training/updaters/multiprocess_parallel_updater.py
Python
mit
15,115
0
import multiprocessing import warnings import six from chainer.backends import cuda from chainer.dataset import convert from chainer import reporter from chainer.training.updaters import standard_updater try: from cupy.cuda import nccl _available = True except ImportError: _available = False import num...
assert len(iterators) == len(devices) for iterator in iterators[1:]: assert len(iterator.dataset) == len(iterators[0].dataset)
# Correct optimizer parameters for new minibatch size optim = optimizer.__class__.__name__ if optim in ('Adam', 'AdaGrad', 'RMSprop'): optimizer.eps *= len(devices) warnings.warn('optimizer.eps is changed to {} ' 'by MultiprocessParallelUpdater for n...
RetSamys/midiflip
midiflip.py
Python
gpl-3.0
5,501
0.028722
#Ret Samys, creator of this program, can be found at RetSamys.deviantArt.com #Please feel free to change anything or to correct me or to make requests... I'm a really bad coder. =) #Watch Andrew Huang's video here: https://www.youtube.com/watch?v=4IAZY7JdSHU changecounter=0 path="for_elise_by_beethoven.mid" prin...
byte of the variable-length quantity for delta_time delta=False #found last byte! next byte should be event else: pass else: #event checking mode if ord(i[4:][byte])==2
55 and ord(i[4:][byte+1])==81 and ord(i[4:][byte+2])==3: #check for set tempo meta-event byte+=5 #skip set tempo meta-event elif ord(i[4:][byte])>=144 and ord(i[4:][byte])<=159: #check for note on event byte+=1 #go to note byte if cset=="": ...
illicitonion/synapse
synapse/events/validator.py
Python
apache-2.0
2,913
0
# -*- coding: utf-8 -*- # Copyright 2014, 2015 OpenMarket Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
if hasattr(event, "state_key"): strings.append("state_key") for s in strings: if not isinstance(getattr(event, s), basestring): raise SynapseError(400, "Not '%s' a string type" % (s,)) if event.type == EventTypes.Member: if "membership" not in ...
raise SynapseError(400, "Content has not membership key") if event.content["membership"] not in Membership.LIST: raise SynapseError(400, "Invalid membership key") # Check that the following keys have dictionary values # TODO # Check that the following key...
aferrero2707/PhotoFlow
src/external/rawspeed/docs/conf.py
Python
gpl-3.0
3,214
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # RawSpeed documentation build configuration file, created by # sphinx-quickstart on Mon Aug 14 18:30:09 2017. # # 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 # a...
feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths th
at contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static']
oscarbranson/latools
latools/helpers/stat_fns.py
Python
mit
7,150
0.002238
""" Functions for calculating statistics and handling uncertainties. (c) Oscar Branson : https://github.com/oscarbranson """ import numpy as np import uncertainties.unumpy as un import scipy.interpolate as interp from scipy.stats import pearsonr def nan_pearsonr(x, y): xy = np.vstack([x, y]) xy = xy[:, ~np.a...
nalysis. """ tmax = 0 for di in d.values(): if di.uTime.max() > tmax: tmax = di.uTime.max() return tmax class un_interp1d(object): """ object for handling interpolation of values with uncertainties. """ def __init__(self, x, y, fill_value=np.nan, **kwargs): ...
e]) else: nom_fill = std_fill = fill_value self.nom_interp = interp.interp1d(un.nominal_values(x), un.nominal_values(y), fill_value=nom_fill, **kwargs) self.std_interp = interp.interp1d(un.nominal_val...
poiesisconsulting/openerp-restaurant
portal_project_issue/tests/test_access_rights.py
Python
agpl-3.0
10,548
0.004645
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (c) 2013-TODAY OpenERP S.A. <http://openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of ...
ssues of an employees project') # Do: Chell reads pr
oject -> ko (portal ko employee) # Test: no project issue visible + assigned issue_ids = self.project_issue.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)]) self.assertFalse(issue_ids, 'access rights: portal user should not see issues of an employees project, even if assigned') ...
perfectsearch/sandman
code/bzr-plugins/__init__.py
Python
mit
254
0.015748
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Proprietary and confidential.
# Copyright 2011 Perfect Search Corporation. # Al
l rights reserved. # import sys sys.dont_write_bytecode = True #import clientplugin import fastbranches import serverplugin
cernops/ceilometer
ceilometer/meter/notifications.py
Python
apache-2.0
12,538
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...
'name', 'type', 'event_type', 'unit', 'volume', 'resource_id'] def __init__(self, definition_cfg): self.cfg = definition_cfg missing = [field for field in self.REQUIRED_FIELDS if not self.cfg.get(field)] if missing: raise MeterDefinition...
ied") % missing, self.cfg) self._event_type = self.cfg.get('event_type') if isinstance(self._event_type, six.string_types): self._event_type = [self._event_type] if ('type' not in self.cfg.get('lookup', []) and self.cfg['type'] not in sample.TYPES): raise...
FireBladeNooT/Medusa_1_6
lib/github/tests/Issue54.py
Python
gpl-3.0
2,437
0.010259
# -*- coding: utf-8 -*- # ########################## Copyrights and license ############################ # # # Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> # # Copyright 2012 Zearin <zearin@gonk.net> ...
rg/licenses/>. # # # # ############################################################################## import datetime import Framework class Issue54(Framework.TestCase): def setUp(se
lf): Framework.TestCase.setUp(self) self.repo = self.g.get_user().get_repo("TestRepo") def testConversion(self): commit = self.repo.get_git_commit("73f320ae06cd565cf38faca34b6a482addfc721b") self.assertEqual(commit.message, "Test commit created around Fri, 13 Jul 2012 18:43:21 GMT, ...
OpenC-IIIT/scriptonia
notif.py
Python
mit
695
0.021583
import notify2 import os
from time import * start_time = time() notify2.init('') r = notify2.Notification('', '') while True: for i in [ ('TO DO', 'Write JavaScript'), ('TO DO', 'Write Python'), ('Thought of the Day', 'Support Open Source'), ('Learn. . .', 'Use Linux'), ('Thou...
the Day', 'Stay Cool'), ('Thought of the Day', 'Stop running for cheese'), ('Thought of the Day', 'You are cool')]: r.update(i[0], i[1]) sleep(120) x = int(time() - start_time)%120 if x == 119: os.system('play --no-show-progress --null --channels 1 synth %s sine %f' % ( 0.5,...
burakbayramli/quant_at
book/Ratio.py
Python
gpl-3.0
750
0.008
import statsmodels.tsa.stattools as st import matplotlib.pylab as plt import numpy as np import panda
s as pd df = pd.read_csv('gld_uso.csv') cols = ['GLD','USO'] df['hedgeRatio'] = df['USO'] / df['GLD'] data_mean = pd.rolling_mean(df['hedgeRatio'], window=20) data_std = pd.rolling_std(df['hedgeRatio'], window=20) df['numUnits'] = -1*(df['hedgeRatio
']-data_mean) / data_std positions = df[['numUnits','numUnits']].copy() positions = positions * np.array([-1., 1.]) pnl = positions.shift(1) * np.array((df[cols] - df[cols].shift(1)) / df[cols].shift(1)) pnl = pnl.fillna(0).sum(axis=1) ret=pnl / np.sum(np.abs(positions.shift(1)),axis=1) print 'APR', ((np.prod(1.+ret))...
GovCERT-CZ/dionaea
modules/python/scripts/ftp.py
Python
gpl-2.0
32,082
0.005143
#************************************************************************* #* Dionaea #* - catches bugs - #* #* #* # Copyright (c) 2009 Markus Koetter # Copyright (c) 2001-2007 Twisted Matrix Laboratories. # Copyright (c) 2001-2009 # # Allen Short # Andrew Bennett...
INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALI
NGS IN THE SOFTWARE. #* #* contact nepenthesdev@gmail.com #* #*******************************************************************************/ # ftp server from dionaea.core import connection, ihandler, g_dionaea, incident import logging import os import urllib.parse import tempfile logger = logging.get...
dimasad/sym2num
examples/function_example.py
Python
mit
896
0.007813
import collections import numpy as np import sympy from sym2num import function, var def reload_all(): """Reload modules for testing.""" import imp for m in (var, function): imp.reload(m) if __name__ == '__main__'
: reload_all() g = var.UnivariateCallable('g') h = var.UnivariateCallable('h') from sympy.abc import t, w, x, y, z, m output = [x**2 + sympy.erf(x) + g(x), sympy.cos(y) + 2*t + sympy.GoldenRatio, z*sympy.sqrt(sympy.sin(w)+2)*h(x, 2)] obj = {'data': [w], 'extra':...
nt_def()) sf = function.SymbolicSubsFunction(function.Arguments(t=t, m=[x,y]), t**2+x) print( "\n" + "*" * 80 + "\n") print(sf(w**4, [2*x,3*z]))
HPPTECH/hpp_IOSTressTest
Refer/IOST_OLD_SRC/IOST_0.17/Libs/IOST_WRun_CTRL.py
Python
mit
2,555
0.009785
#!/usr/bin/python #====================================================================== # # Project : hpp_IOStressTest # File : IOST_WRun_CTRL.py # Date : Oct 25, 2016 # Author : HuuHoang Nguyen # Contact : hhnguyen@apm.com # : hoangnh.hpp@gmail.com # License : MIT License # Copyright : 2016 # ...
"], self.WRun_Host.name) self.IOST_Objs[window_name][window_name+"_Terminal_ScrolledWindow"].add(self.WRun_Term.IOST_vte) def WRun_IOST_VTE_show(self): self.WRun_Term.IOST_vte.show()
nacx/kahuna
kahuna/pluginmanager.py
Python
mit
2,347
0.000852
#!/usr/bin/env jython from __future__ import with_statement from contextlib import contextmanager import logging from plugins import __all__ log = logging.getLogger('kahuna') class PluginManager: """ Manages available plugins """ def __init__(self): """ Initialize the plugin list """ self.__...
print "%s" % plugin.__doc__ for command in sorted(commands.iterkeys()): print " %s %s\t%s" % (plugin_name, command, commands[command].__doc__) def help_all(self): """ Prints the help for all registered plugins """ for name in sorted(_
_all__): plugin = self.load_plugin(name) self.help(plugin) print @contextmanager def opencontext(plugin): """ Loads the context each plugin needs to be initialized in order to be executed """ plugin._load_context() yield plugin._close_context()
kpreid/shinysdr
shinysdr/units.py
Python
gpl-3.0
1,966
0.004585
# -*- coding: utf-8 -*- # Copyright 2016, 2017 Kevin Reid and the ShinySDR contributors # # This file is part of ShinySDR. # # ShinySDR 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...
return { 'type': 'Unit', 'symbol': self.symbol, 'si_prefix_ok': self.si_prefix_ok } def __str__(self): return self.symbol __all__.append('Unit') #
TODO: reflectively put units into __all__ none = Unit('', True) s = Unit('s', True) degree = Unit('°', False) # degree of angle degC = Unit('°C', False) degF = Unit('°F', False) dB = Unit('dB', False) dBm = Unit('dBm', False) dBFS = Unit('dBFS', False) Hz = Unit('Hz', True) MHz = Unit('MHz', False) # TODO: Remove or...
smallyear/linuxLearn
salt/salt/cloud/clouds/cloudstack.py
Python
apache-2.0
16,091
0.000559
# -*- coding: utf-8 -*- ''' CloudStack Cloud Module ======================= The CloudStack cloud module is used to control access to a CloudStack based Public Cloud. :depends: libcloud >= 0.15 Use of this module requires the ``apikey``, ``secretkey``, ``host`` and ``path`` parameters. .. code-block:: yaml my-c...
''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('apikey',
'secretkey', 'host', 'path') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'libcloud': HAS_LIBS} ) def get_conn(): ''' Return a conn object for the passed VM data ''' driver = get...
ClarkYan/msc-thesis
code/data_owner_1/interface.py
Python
apache-2.0
2,180
0.002752
#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Author: ClarkYAN -*- from get_connection import * from get_key import * import Tkinter import tkMessageBox class mainFrame: def __init__(self): self.root = Tkinter.Tk() self.root.title('Secure Protocol Systems') self.root.geometry('600x3...
sender = 'data_owner_1'
result = str(set_up_connection(url, sender)) tkMessageBox.showinfo("Recent Event", result) print result def getKey(): url = 'http://127.0.0.1:5000/key' sender = 'data_owner_1' result = send_info(url, sender) tkMessageBox.showinfo("Recent Event", result) print result def main(): ...
gamikun/xmppgcm
setup.py
Python
apache-2.0
574
0.04007
from os.path import join, dirname from setuptools import setup setup( name = 'xmppgcm', packages = ['xmppgcm'], # this must be the same as the name above version = '0.2.3', description = 'Client Library for Firebase Cloud Messaging using XMPP', long_description = open(join(dirname(__file__), 'README.txt')).r...
Winster Jose', author_email = 'wtjose@gmail.com', url = 'https://github.com/winster/xmppgcm', keywords = ['gcm', 'fcm', 'xmpp', 'xmppgcm', 'xmppfcm'], # arbitrary keywords class
ifiers = [], )
JoelBender/bacpypes
py34/bacpypes/service/__init__.py
Python
mit
171
0
#!/usr/bin/env python """ S
ervice Subpackage """ from . import test from . import detect from . import device from . import object from . import cov from . import file
frastlin/PyAudioGame
examples/basic_tutorial/ex6.py
Python
mit
2,789
0.023664
#Pizza please import pyaudiogame from pyaudiogame import storage spk = pyaudiogame.speak MyApp = pyaudiogame.App("Pizza Please") storage.screen = ["start"] storage.toppings = ["cheese", "olives", "mushrooms", "Pepperoni", "french fries"] storage.your_toppings = ["cheese"] storage.did_run = False def is_number(number,...
spk("You can't remove cheese, what are you, Italian?") storage.your_toppings.insert(0, "cheese") else: spk("You removed %s from your pizza. Now your pizza has %s on top" % (t, storage.your_toppings)) def logic(actions): """Press a and d to switch from adding and removing toppings, press 0-9 to deal with the t...
storage.screen[0] = "remove" storage.did_run = False elif key == "a": spk("Press a number to add a topping to your pizza. Press d to remove a topping you don't like") storage.screen[0] = "add" storage.did_run = False elif key == "space": spk("You sit down to enjoy a yummy pizza. You eat... eat... eat... e...
Jonpro03/Minecrunch_Web
src/servers/models.py
Python
mit
921
0.008686
from __future__ import unicode_literals from django.db import models from modpacks.models.modpack import Modpack class Server(models.Model): """ Minecraft Server details for display on the server page """ name = models.CharField(verbose_name='Server Name', max_length=200) desc = models.TextFi...
er Description', blank=True) modpack = models.ForeignKey(Modpack, verbose_name='Server Modpack') address = models.CharField(verbose_name='Server Address', max_length=200, blank=True) screenshot = models.ImageField(verbose_name='Screenshot', blank=True) dyn...
, blank=True) slug = models.SlugField() def get_absolute_url(self): return reverse("server", self.slug) def __str__(self): return self.name
dsp-jetpack/JetPack
src/pilot/dell_nfv_edge.py
Python
apache-2.0
6,869
0.000728
#!/usr/bin/python3 # Copyright (c) 2018-2021 Dell Inc. or its subsidiaries. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
faces_by_keyword(nic_env_file,
'Dpdk') logger.debug("DPDK-NICs >>" + str(dpdk_nics)) self.nfv_params.get_pmd_cpus(self.mtu, dpdk_nics) self.nfv_params.get_socket_memory(self.mtu, dpdk_nics) kernel_args += " isolcpus={}".format(self.nfv_params.isol_cpus) # dell-environmm...
ioram7/keystone-federado-pgid2013
build/sqlalchemy/test/sql/test_rowcount.py
Python
apache-2.0
2,260
0.00531
from sqlalchemy import * from test.lib import * class FoundRowsTest(fixtures.TestBase, AssertsExecutionResults): """tests rowcount functionality""" __requires__ = ('sane_rowcount', ) @classmethod def setup_class(cls): global employees_table, metadata metadata = MetaData(testing.db) ...
): s = employees_table.select() r = s.execute().fetchall() assert len(r) == len(data) def test_update_rowcount1(self): # WHERE matches 3, 3 rows changed department = employees_table.c.department r = employees_table.update(department=='C').execute(department='Z') ...
.rowcount == 3 def test_update_rowcount2(self): # WHERE matches 3, 0 rows changed department = employees_table.c.department r = employees_table.update(department=='C').execute(department='C') print "expecting 3, dialect reports %s" % r.rowcount assert r.rowcount == 3 de...
gacosta1/CATS
Software/src/keypad.py
Python
gpl-3.0
3,522
0.012777
#!/usr/bin/python import RPi.GPIO as GPIO import signal import time from on_off import * class keypad(): def __init__(self, columnCount = 3): GPIO.setmode(GPIO.BCM) # CONSTANTS if columnCount is 3: self.KEYPAD = [ [1,2,3], ...
: tmpRead = GPIO.inpu
t(self.ROW[i]) if tmpRead == 0: rowVal = i # if rowVal is not 0 thru 3 then no button was pressed and we can exit if rowVal <0 or rowVal >3: self.exit() return # Convert columns to input for j in range(len(self.COLUMN)): ...
YzPaul3/h2o-3
h2o-py/tests/testdir_javapredict/pyunit_javapredict_dynamic_data_paramsKmeans.py
Python
apache-2.0
2,376
0.020202
from __future__ import print_function from builtins import range import sys sys.path.insert(1,"../../") import h2o from tests import pyunit_utils import random import os def javapredict_dynamic_data(): # Generate random dataset dataset_params = {} dataset_params['rows'] = random.sample(list(range(5000,150...
ample(list(range(10,21)),1)[0] dataset_params['categorical_fraction'] = round(random.r
andom(),1) left_over = (1 - dataset_params['categorical_fraction']) dataset_params['integer_fraction'] = round(left_over - round(random.uniform(0,left_over),1),1) if dataset_params['integer_fraction'] + dataset_params['categorical_fraction'] == 1: if dataset_params['integer_fraction'] > dataset_para...
IZSVenezie/VetEpiGIS-Stat
plugin/globalt.py
Python
gpl-3.0
21,379
0.005052
# -*- coding: utf-8 -*- """ /*************************************************************************** VetEpiGIS-Stat A QGIS plugin Spatial functions for vet epidemiology ------------------- begin : 2016-01-06 git sha : $Format:%H$ ...
e based on the spdep R package: https://cran.r-project.org/web/packages/spdep ***************************************************************************/ /*************************************************************************** *
* * 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. ...
rjpower/falcon
benchmarks/old/matmult_int.py
Python
apache-2.0
511
0.029354
def mm_loops(X
,Y,Z): m = len(X) n = len(Y) for i in xrange(len(X)): xi = X[i] for j in xrange(len(Y)): yj = Y[j] total = 0 for k in xrange(len(yj)): total += xi[k] * yj[k] Z[i][j] = tot
al return Z def make_matrix(m,n): mat = [] for i in xrange(m): mat.append(range(n)) return mat if __name__ == '__main__': n = 200 x = make_matrix(n,n) z = make_matrix(n,n) mm_loops(x, x, z)
bcaudell95/schema
test_schema.py
Python
mit
21,259
0.002493
from __future__ import with_statement from collections import defaultdict, namedtuple from functools import partial from operator import methodcaller import os import re import sys import copy import platform from pytest import raises, mark from schema import (Schema, Use, And, Or, Regex, Optional, Const, ...
index")), unique_list)))) data = [ {"index": 1, "value": "foo"}, {"index": 2, "value": "bar"}] assert schema.validate(data) == data bad_data = [ {"index": 1, "va
lue": "foo"}, {"index": 1, "value": "bar"}] with SE: schema.validate(bad_data) def test_regex(): # Simple case: validate string assert Regex(r'foo').validate('afoot') == 'afoot' with SE: Regex(r'bar').validate('afoot') # More complex case: validate string assert Regex(r'^[a-z]+$').val...
iemejia/incubator-beam
sdks/python/apache_beam/runners/interactive/pipeline_fragment.py
Python
apache-2.0
9,582
0.005844
# # 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 thi
s file to You 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...
or the specific language governing permissions and # limitations under the License. # """Module to build pipeline fragment that produces given PCollections. For internal use only; no backwards-compatibility guarantees. """ from __future__ import absolute_import import apache_beam as beam from apache_beam.pipeline im...
teeple/pns_server
work/install/Python-2.7.4/Lib/test/test_wait4.py
Python
gpl-2.0
940
0.005319
"""This test checks for correct wait4() behavior. """ import os import time from test.fork_wait import ForkWait from test.test_support import run_unittest, reap_child
ren, get_attribute # If either of these do not exist, skip this test. get_attribute(os, 'fork') get_attribute(os, 'wait4') class Wait4Test(ForkWait): def wait_impl
(self, cpid): for i in range(10): # wait4() shouldn't hang, but some of the buildbots seem to hang # in the forking tests. This is an attempt to fix the problem. spid, status, rusage = os.wait4(cpid, os.WNOHANG) if spid == cpid: break ...
matbra/radio_fearit
app/views.py
Python
gpl-3.0
670
0.008955
from flask import render_template from app import app, db, models import json @app.route('/') @app.route('/index') def index(): # obtain today's words # words = models.Words.query.all() # word
s =
list((str(word[0]), word[1]) for word in db.session.query(models.Words, db.func.count(models.Words.id).label("total")).group_by(models.Words.word).order_by("total DESC")) data = db.session.query(models.Words, db.func.count(models.Words.id).label("total")).group_by(models.Words.word).order_by("total DESC").all()[:5...
erasche/argparse2tool
argparse2tool/dropins/argparse/argparse_galaxy_translation.py
Python
apache-2.0
10,696
0.00215
import galaxyxml.tool.parameters as gxtp from collections import Counter from pydoc import locate class ArgparseGalaxyTranslation(object): def __gxtp_param_from_type(self, param, flag, label, num_dashes, gxparam_extra_kwargs, default=None): from argparse import FileType """Based on a type, conver...
DO: Handle argparse.REMAINDER") return (gxrepeat_args, gxrepeat_kwargs, gxrepeat_cli_after, gxrepeat_cli_before, gxrepeat_cli_actual, gxparam_cli_before, gxparam_cli_after) def __init__(self): self.repeat_count = 0 self.positional_count = Counter() def _VersionAction(s...
now. # TODO handle their templating of version # This is kinda ugly but meh. tool.root.attrib['version'] = param.version # Count the repeats for unique names # TODO improve def _StoreAction(self, param, tool=None): """ Parse argparse arguments action type o...
globalspin/haemapod
haemapod/handlers/events/proximity.py
Python
mit
264
0.018939
from model import Event from geo.geomodel import geotypes def get(
handler, response): lat = handler.request.get('lat') lon = handler.request.get('lng') response.events = Event.proximity_fetch( Event.all(), geotypes.Point(float
(lat),float(lon)), )
rgreinho/molecule
molecule/command/dependency.py
Python
mit
2,997
0
# Copyright (c) 2015-2016 Cisco Systems, Inc. # # 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 # furn
ished to do so, subject to the following conditions: # # The above copyright notice and this permission 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 WARRANT...
eric-stanley/freeciv-android
lib/freeciv/tutorial.py
Python
gpl-2.0
497
0.008048
import save import client def start(): def callback(): client.client.chat('/novice') found_na
tions = [ (name, style, id) for name, style, id in client.get_nations() if name == 'Poles' ] if found_nations: name, style, id = found_nations[0] print 'change nation to', name, style, id client.freeciv.func.set_nation_
settings(id, 'Player', style, 2) return True save.load_game('data/tutorial.sav', before_callback=callback)
unho/pootle
tests/models/translationproject.py
Python
gpl-3.0
5,854
0
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os import pytest from translate.fil...
# When initing a tp from a file called `template.pot` the resulting # store should be called `langcode.po` if the project is gnuish project0.config["pootle_fs.translation_mappings"] = dict( default="/<dir_path>/<language_code>.<ext>") template_tp =
TranslationProject.objects.create( language=templates, project=project0) template = Store.objects.create( name="template.pot", translation_project=template_tp, parent=template_tp.directory) template.update(complex_ttk) tp = TranslationProject.objects.create( project=...
ixaxaar/pytorch-dnc
test/test_rnn.py
Python
mit
4,532
0.02714
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import pytest import numpy as np import torch.nn as nn import torch as T from torch.autograd import Variable as var import torch.nn.functional as F from torch.nn.utils import clip_grad_norm_ import torch.optim as optim import numpy as np import sys import os import mat...
ngth = 10 batch_size = 10 cuda = gpu_id clip = 10 length = 10 rnn = DNC( input_size=input_size, hidden_size=hidden_size, rnn_type=rnn_type, num_layers=
num_layers, num_hidden_layers=num_hidden_layers, dropout=dropout, nr_cells=nr_cells, cell_size=cell_size, read_heads=read_heads, gpu_id=gpu_id, debug=debug ) optimizer = optim.Adam(rnn.parameters(), lr=lr) optimizer.zero_grad() input_data, target_output = generate_dat...
zigapk/adventofcode
2017/8/main.py
Python
mit
1,081
0.014801
from collections import defaultdict import fileinput mem = defaultdict(int) s1 = -100000 s2 = -100000 def condition(line): global mem l = line[-3:] if l[1] == "==": if mem[l[0]] == int(l[2]): return True else: return False elif l[1] == "<": if mem[l[0]] < int(l[2]): return Tru...
ine.split() if condition(line): if line[1] == "inc": mem[line[0]] += int(l
ine[2]) elif line[1] == "dec": mem[line[0]] -= int(line[2]) if mem[line[0]] > s2: s2 = mem[line[0]] for k in mem.keys(): if mem[k] > s1: s1 = mem[k] print(s1) print(s2)
saigrain/CBVshrink
src/VBLinRegARD.py
Python
gpl-2.0
3,845
0.008583
import numpy, sys import scipy.linalg, scipy.special ''' VBLinRegARD: Linear basis regression with automatic relevance priors using Variational Bayes. For more details on the algorithm see Apprendix of Roberts, McQuillan, Reece & Aigrain, 2013, MNRAS, 354, 3639. History: 2011: Translated by Thomas Evans from origina...
Outputs w: basis function weights ***need to document the others!*** ''' # uninformative priors a0 = 1e-2
b0 = 1e-4 c0 = 1e-2 d0 = 1e-4 # pre-process data [N, D] = X.shape X_corr = X.T * X Xy_corr = X.T * y an = a0 + N / 2. gammaln_an = scipy.special.gammaln(an) cn = c0 + 1 / 2. D_gammaln_cn = D * scipy.special.gammaln(cn) # iterate to find hyperparameters L_la...
ibell/coolprop
wrappers/Python/CoolProp/Plots/SimpleCycles.py
Python
mit
13,341
0.069935
import matplotlib, numpy import CoolProp Props = CoolProp.CoolProp.Props from scipy.optimize import newton def SimpleCycle(Ref,Te,Tc,DTsh,DTsc,eta_a,Ts_Ph='Ph',skipPlot=False,axis=None): """ This function plots a simple four-component cycle, on the current axis, or that given by the optional parameter *axis* ...
1.0,Ref) Tbubble_c=Props('T','P',pc,'Q',0,Ref) Tbubble_e=Props('T','P',pe,'Q',0,Ref) h[1]=Props('H','T',T[1],'P',pe,Ref) s[1]=Pr
ops('S','T',T[1],'P',pe,Ref) rho[1]=Props('D','T',T[1],'P',pe,Ref) T[5]=Tbubble_c-DTsc h[5]=Props('H','T',T[5],'P',pc,Ref) s[5]=Props('S','T',T[5],'P',pc,Ref) rho[5]=Props('D','T',T[5],'P',pc,Ref) mdot=Q/(h[1]-h[5]) rho1=Props('D','T',T[1],'P',pe,Ref) h2s=Props('H','S',s[1],'P',pic,Ref)...
cloudbase/maas
src/maasserver/migrations/0046_add_nodegroup_maas_url.py
Python
agpl-3.0
15,514
0.007413
# -*- coding: utf-8 -*- import datetime from django.db import models from south.db import db from south.v2 import SchemaMigration class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'NodeGroup.maas_url' db.add_column(u'maasserver_nodegroup', 'maas_url', ...
s.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], ...
ult': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.M...
praekeltfoundation/mc2-freebasics
freebasics/migrations/0006_change_site_url_field_type.py
Python
bsd-2-clause
477
0.002096
# -*- coding: utf-8 -*- from __future__ import unicode_literals from dja
ngo.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('freebasics', '0005_remove_selected_template_field'), ] operations = [ migrations.Alter
Field( model_name='freebasicstemplatedata', name='site_name_url', field=models.CharField(max_length=255, unique=True, null=True, blank=True), ), ]
notriddle/servo
tests/wpt/web-platform-tests/referrer-policy/generic/tools/generate.py
Python
mpl-2.0
1,383
0.001446
#!/usr/bin/env python import os import sys sys.path.insert( 0, os.path.join( os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', 'common', 'security-features', 'tools')) import generate cl
ass ReferrerPolicyConfig(object): def __init__(self): self.selecti
on_pattern = \ '%(source_context_list)s.%(delivery_type)s/' + \ '%(delivery_value)s/' + \ '%(subresource)s/' + \ '%(origin)s.%(redirection)s.%(source_scheme)s' self.test_file_path_pattern = 'gen/' + self.selection_pattern + '.html' self.test_desc...
purduesigbots/pros-cli
pros/conductor/depots/local_depot.py
Python
mpl-2.0
2,366
0.003381
import os.path import shutil import zipfile import click from pros.config import ConfigNotFoundException from .depot import Depot from ..templates import BaseTemplate, Template, ExternalTemplate from pros.common.utils import logger class LocalDepot(Depot): def fetch_template(self, template: BaseTemplate, destin...
h.join(destination, 'template.pros') location_dir = destination elif os.path.isfile(location): location_dir = os.path.dirname(location) template_file = location elif isinstance(template, ExternalTemplate): location_dir = template.directory temp...
f location_dir != destination: n_files = len([os.path.join(dp, f) for dp, dn, fn in os.walk(location_dir) for f in fn]) with click.progressbar(length=n_files, label='Copying to local cache') as pb: def my_copy(*args): pb.update(1) shutil.co...
arcyfelix/Courses
17-06-05-Machine-Learning-For-Trading/25_arithmetic operations.py
Python
apache-2.0
1,058
0.040643
import numpy as
np def array_generator(): array = np.array([(1, 2, 3, 4, 5), (10, 20, 30, 40, 50)]) return array def multiply_by_number(array, number): print(array) multiplied = array * number print(multiplied) return multiplied def divide_by_number(array, number): # Either the numer or the elements of the array need to be ...
array_2 def elemtwise_mul(array_1, array_2): return array_1 * array_2 if __name__ == "__main__": # ----------------------------------------------------- x = array_generator() two_x = multiply_by_number(x, 2) half_x = divide_by_number(x, 2) added = addition(two_x, half_x) element_multiplied = elemtwise_mul(x, t...
clemfeelsgood/hackathontools
code_challenges/mopub/calc.py
Python
mit
1,320
0.012121
""" calc.py >>> import calc >>> s='2+4+8+7-5+3-1' >>> calc.calc(s) 18 >>> calc.calc('2*3+4-5*4') -10 """ import re from operator import concat operator_function_table = { '+' : lambda x, y: x + y, '-' : lambda x, y: x - y, '*' : lambda x, y: x ...
operands = [int(k) for k in re.split(op_re, s)] operators = filter(lambda x: x, re.split('\d', s)) operator_functions = [operator_function_table[x] for x in operators]
for f in operator_functions: result = apply(f, [operands[0], operands[1]]) operands = [result] + operands[2:] final_result = operands[0] return final_result
tareqmalas/girih
scripts/sisc/paper_bytes_requirement_analysis.py
Python
bsd-3-clause
6,160
0.010714
#!/usr/bin/env python def main(): import sys raw_data = load_csv(sys.argv[1]) create_table(raw_data) def get_stencil_num(k): # add the stencil operator if k['Stencil Kernel coefficients'] in 'constant': if int(k['Stencil Kernel semi-bandwidth'])==4: stencil = 0 else: ...
if __name__ == "__main__": main() # if 'constant' in tup['Stencil Kernel coefficients']: # BpU1 = (YT_section + width + 2*R + (t_order-1)*width) * word_size / YT_section # tup['No TS'] = BpU1 # # BpU2 = (width + 2*R + (t_order-1)*width) * word_size / YT_section #
tup['All TS'] = BpU2 # # BpU3 = ((width - 2*R) + 2*width + 2*R + (t_order-1)*width) * word_size / YT_section # tup['Interior TS'] = BpU3 # # BpU4 = ( ((width - 2*R) + width) + ((t_order+1)*width + 2*R) ) * word_size / YT_section # tup['Interior TS 2'] = BpU4 # # elif 'variable' in tu...
AccelAI/accel.ai
flask-aws/lib/python2.7/site-packages/ebcli/operations/scaleops.py
Python
mit
2,296
0.001742
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
boolean_response() if not switch: return options.append({'Namespace': namespace, 'OptionName': 'EnvironmentType', 'Value': 'LoadBalanced'}) # change autoscaling min AND max to number namespace = 'aws:autoscaling:asg' max =...
r name in [max, min]: options.append( {'Namespace': namespace, 'OptionName': name, 'Value': str(number) } ) request_id = elasticbeanstalk.update_environment(env_name, options) try: commonops.wait_for_success_events(request_id, ...
llluiop/skia
platform_tools/android/bin/gyp_to_android.py
Python
bsd-3-clause
6,621
0.00589
#!/usr/bin/python # Copyright 2014 Google Inc. # # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Script for generating the Android framework's version of Skia from gyp files. """ import android_framework_gyp import os import shutil import sys import tempfile ...
k. com
mon.DEFINES.reset() # Further trim arm_neon_var_dict with arm_var_dict. After this call, # arm_var_dict (which will now be the intersection) includes all definitions # used by both arm and arm + neon, and arm_neon_var_dict will only contain # those specific to arm + neon. arm_var_dict = vars_dict_l...
AnandMoorthy/kodak_bank_excel_parser
kodak_excel_parser.py
Python
gpl-3.0
1,376
0.025436
""" Code : Remove the dependency for Kodak Bank, default excel parser macros and just GNU/Linux to acheive it. Authors : Ramaseshan, Anandhamoorthy , Engineers, Fractalio Data Pvt Ltd, Magadi, Karnataka. Licence : GNU GPL v3. Code Repo URL : https://github.com/ramaseshan/kodak_bank_excel_parser """ import pyexcel as ...
",filename records = pe.get_array(file_name=filename) f = open(fileout,'w') print "Starting to process data. Hold your breath" for count,rec in enumerate(records[1:]): rec[0] = "DATALIFE" rec[1] = "RPAY" rec[5] = "04182010000104" rec[4]
= time.strftime("%d/%m/%Y") line = "" for value in rec: if value and type(value) is unicode: value = unicodedata.normalize('NFKD', value).encode('ascii','ignore') if rec[6] % 2 == 0: rec[6] = int(rec[6]) # Cross check payment types with mahesh if rec[2] == "NEFT" or rec[2] == "IFT": line = line + st...
GateNLP/gateplugin-python
examples/pythonSlaveMaster.py
Python
lgpl-3.0
469
0.002132
from py4j.java_gateway import JavaGateway, GatewayParameters gateway = JavaGateway(gateway_parameters=GatewayParameters(port=25333))
doc1 = gateway.jvm.gate.Factory.newDocument("initial text") print(doc1.getContent().toStr
ing()) doc2 = gateway.jvm.gate.plugin.python.PythonSlave.loadDocument("docs/doc1.xml") print(doc2.getContent().toString()) js1 = gateway.jvm.gate.plugin.python.PythonSlave.getBdocDocumentJson(doc2) print(js1) gateway.close()
yejia/osl_notebook
scraps/views.py
Python
mit
5,990
0.018364
from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import render_to_response from django import forms from django.forms import ModelForm from django.db.models import F from django.db import connection from django.utils import simplejson from django.contrib import messages from django.contri...
reate(name=tag_name) #==============Don't need below any more since add_tags will do this logic================================================================= # if created or not w.tags.filter(name=t.name).exists(): #
w.tags.add(t) #=============================================================================== #tags.append(t.id) tags.append(t.name) #if not tag_names: # tags = [T.objects.get(name='untagged').id] if ...