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
y-higuchi/ramcloud
scripts/transportgraph.py
Python
isc
2,912
0.00103
#!/usr/bin/env python # Copyright (c) 2011 Stanford University # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND ...
e=dat) print(file=dat) results = defaultdict(lambda: defaultdict(lambda: defaultdict(int))) for objectSize in objectSizes: for transport in transports: print('Running', transport, 'with', numObjects, objectSize, 'byte obj
ects') stats = transportBench(numObjects, objectSize, transport, uncached) run = stats['run'] runTime = stats['ns'] / 1e9 readSize = stats['size'] readCount = stats['count'] mbPerSecond = (readSize * readCount) / (runTime * 2**20) usPerObject = runTime * 1000000...
algorithm-ninja/territoriali-backend
terry/handlers/base_handler.py
Python
mpl-2.0
9,492
0.002739
#!/usr/bin/env python3 # 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/. # # Copyright 2017-2019 - Edoardo Morassutto <edoardo.morassutto@gmail.com> # Copyright 2017 - Luc...
otation is also supported for a simple type validation. The values are fetched, in order, from: - route_a
rgs - request.form - general_attrs - default values If a parameter is required but not sent a BadRequest (MISSING_PARAMETERS) error is thrown, if a parameter cannot be converted to the annotated type a BadRequest (FORMAT_ERROR) is thrown. :param method: Method to be calle...
DBrianKimmel/PyHouse
Project/src/Modules/House/Family/Upb/upb_data.py
Python
mit
787
0
""" @name: Modules/families/UPB/UPB_data.py @author: D. Brian Kimmel @contact: D.BrianKimmel@gmail.com @copyright: (c) 2014-2020 by D. Brian Kimmel @license: MIT License @note: Created on Aug 6, 2014 @summary: This module is for communi
cating with UPB controllers. """ __updated__ = '2020-02-17' # Import system type stuff # Import PyMh files from Modules.House.Lighting.Lights.lights import LightControlInformation class UPBData(LightControlInformation): """ Locally held data about each of the UPB PIM controllers we find. This is know...
lf.UPBNetworkID = 0 # ## END DBK
DirectXMan12/nova-hacking
nova/virt/powervm/common.py
Python
apache-2.0
9,118
0.000658
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 IBM Corp. # # 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 # # ...
user=connection.username, passwd=connection.password) ftp.cwd(remote_dir) name = os.path.split(local_path)[1] f = open(local_path, "rb") ftp.storbinary("STOR " + name, f) f.close() ftp.close() except Ex
ception: LOG.error(_('File transfer to PowerVM manager failed')) raise exception.PowerVMFTPTransferFailed(ftp_cmd='PUT', source_path=local_path, dest_path=remote_dir) def ftp_get_command(connection, remote_path, local_path): """Retrieve a file via FTP :param connection: a Conn...
userzimmermann/zetup.py
zetup/commands/test.py
Python
lgpl-3.0
1,403
0
# zetup.py # # Zimmermann's Python package setup. # # Copyright (C) 2014-2015 Stefan Zimmermann <zimmermann.code@gmail.com> # # zetup.py is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either ve...
r more details. # # You should have received a copy of the GNU Lesser General Public License # along with zetup.py. If not, see <http://www.gnu.org/licenses/>. """zetup.commands.test Defines ``zetup test`` command. .. moduleauthor:: Stefan Zimmermann <zimmermann.code@gmail.com> """ import os from zetup...
args=None): """Run configured ``test commands``. """ dev(zfg) # first (re)install project in develop mode for command in zfg.TEST_COMMANDS: print("zetup: Running %s" % repr(command)) status = call(command, shell=True, env=os.environ) if status: # ==> error r...
khchine5/lino-welfare
lino_welfare/modlib/aids/mixins.py
Python
agpl-3.0
13,679
0.001755
# -*- coding: UTF-8 -*- # Copyright 2014-2017 Luc Saffre # This file is part of Lino Welfare. # # Lino Welfare 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 y...
go.utils.translation import ugettext_lazy as _ from django.utils.translation import pgettext_lazy as pgettext from lino.api import dd, rt from lino import mixins from etgen.html import E, tostring from lino.utils.ranges import encompass from lino.modlib.checkdata.choicelists import Checker from lino.modlib.users.mix...
t rangefmt from .choicelists import ConfirmationStates from .roles import AidsStaff def e2text(v): return tostring(v) # if isinstance(v, types.GeneratorType): # return "".join([e2text(x) for x in v]) # if E.iselement(v): # return tostring(v) # return unicode(v) class SignConfirmatio...
atilag/qiskit-sdk-py
qiskit/extensions/standard/gatestools.py
Python
apache-2.0
1,248
0
# -*- coding: utf-8 -*- # pylint: disable=invalid-name # Copyright 2017 IBM RESEARCH. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License
at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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 governing permissions and # limitations under the License. # ============================================================================= """Gates tools."""...
sfstpala/png.py
png.py
Python
mit
2,602
0.001922
# Copyright (C) 2011 by Stefano Palazzo # # 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,...
HETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OT
HER DEALINGS IN # THE SOFTWARE. import zlib import struct def make(image: '[[[r, g, b, a, ], ], ]') -> bytes: ''' Create PNG image from RGBA data Expects a list of lines of pixels of R, G, B, and Alpha values. I.e: [ [ [0, 0, 0, 0], [0, 0, 0, 0], ], [ [0, 0, 0, 0], [0, 0, 0, 0], ],...
caser789/xuejiao-blog
app/main/__init__.py
Python
mit
219
0.013699
from flask import Blueprint main = Blueprint('main', __name__) from . import errors, views from ..models import Permission @main.app_c
ontext_processor def inject_permissions(): return dict(Permi
ssion=Permission)
croscon/fleaker
fleaker/marshmallow/json_schema.py
Python
bsd-3-clause
7,584
0
# ~*~ coding: utf-8 ~*~ """Module that contains a Marshmallow schema that generate JSON schemas. JSON Schemas can be a pain to write by hand. For example, the product requirements change, thus your schema changes. If you are maintaining your schemas by hand, you have to go through all of them and update them, or, even...
a folder json_schema = FleakerJSONSchema.write_schema_to_file( # This library doesn't care if the schema has been initialized UserSchema,
# The folder to write this schema to folder='docs/raml/schemas', # The context can control certain things about how the schema will # be dumped. context={'dump_schema': True} ) # Now, you can find the dumped schema in docs/raml/schemas/user.json...
stonebig/keras
keras/layers/convolutional.py
Python
mit
5,924
0.011648
# -*- coding: utf-8 -*- from __future__ import absolute_import import theano import theano.tensor as T from theano.tensor.signal import downsamp
le from .. import activations, i
nitializations from ..utils.theano_utils import shared_zeros from ..layers.core import Layer class Convolution1D(Layer): def __init__(self, nb_filter, stack_size, filter_length, init='uniform', activation='linear', weights=None, border_mode='valid', subsample_length=1, W_regularizer=None, ...
andhit-r/odoo-saas-tools
saas_portal/models/saas_portal.py
Python
lgpl-3.0
18,733
0.00315
# -*- coding: utf-8 -*- import openerp from openerp import models, fields, api, SUPERUSER_ID, exceptions from openerp.addons.saas_utils import connector, database from openerp import http from openerp.tools import config, scan_languages from openerp.tools.translate import _ from openerp.addons.base.res.res_partner impo...
fields.Boolean('Verify SSL', default=True, help="verify SSL certificates for HTTPS requests, just like a web browser") request_port = fields.Integer('Request Port', default=80) client_ids = fields.One2many('saas_portal.client', 'server_id', st
ring='Clients') @api.model def create(self, vals): self = super(SaasPortalServer, self).create(vals) self.create_access_token(self.oauth_application_id.id) return self @api.model def create_access_token(self, oauth_application_id): expires = datetime.now() + timedelta(s...
softcert/vsroom
vsroom/common/sanitizers/tallinnairport.py
Python
mit
1,903
0.008408
import time from vsroom.common import sanitizer from vsroom.common import timeconversion # sanitizer.Sanitizer is the base class for a simple sanitizer bot. class TallinnAirportSanitizer(sanitizer.Sanitizer): # .sanitize(event) is the hook method for sanitizing events. This # is the only method you have to imp...
= "%s - %s - utilization: %s%% - %s" % \ (isotime, event.value('organization',''), utilization, event.value('sou
rce','-')) event.add("description", description) # Return a list of events here. The list can contain 0-n events. return [event] if __name__ == "__main__": # Execute the sanitizer bot based on the command line options. TallinnAirportSanitizer.from_command_line().execute()
AdvancedClimateSystems/python-modbus
tests/system/validators.py
Python
mpl-2.0
2,302
0
import struct def validate_transaction_id(request_mbap, response): """ Check if Transaction id in request and response is equal. """ assert struct.unpack('>H', request_mbap[:2]) == \ struct.unpack('>H', response[:2]) def validate
_protocol_id(request_mbap, response): """ Check if Protocol id in request and response is e
qual. """ assert struct.unpack('>H', request_mbap[2:4]) == \ struct.unpack('>H', response[2:4]) def validate_length(response): """ Check if Length field contains actual length of response. """ assert struct.unpack('>H', response[4:6])[0] == len(response[6:]) def validate_unit_id(request_mbap, re...
dherbst/python-icontact
icontact/client.py
Python
apache-2.0
23,268
0.004255
# Copyright 2008 Online Agility (www.onlineagility.com) # # 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 b...
response_status = response.status else: # Perform a GET request req = urllib2.Request(url, None, headers) self.log.debug("GET headers=%s url=%s" % (req.headers,url)) response = urllib2.urlopen(req) response_status = response.code if t...
# type is json jsondata = response.read() self.log.debug(u"json response=\n%s" % (jsondata,)) result = simplejson.loads(jsondata) result = json_to_obj(result) if response_status >= 400: raise IContactServerError(response_status, result.er...
dts-ait/qgis-edge-bundling
summarize.py
Python
gpl-2.0
4,463
0.015685
##Edge bundling=group ##input_layer=vector ##cluster_field=field input_layer ##weight_field=field input_layer ##use_weight_field=boolean true ##max_distance=number 0.008 ##collapsed_lines=output vector from qgis.core import * from qgis.gui import * import qgis.utils from PyQt4.QtCore import * import processing from pr...
f[weight_field] else: self.weight = weight self.agg_weight = self.weight def increase_weight(self,value=1): self.agg_weight += value def get_weight(self): return self.weight def get_agg_weight(self): return self.agg_weight ...
= edges self.index = QgsSpatialIndex() for e in self.edges: self.index.insertFeature(e) self.allfeatures = {edge.id(): edge for (edge) in self.edges} def get_size(self): return len(self.edges) def collapse_lines(self): ids_to_delete = [] ...
rodrigopitanga/django-smssync
smssync/__init__.py
Python
gpl-3.0
772
0
# -*- coding: utf-8 -*- # # (C) 2016 Rodrigo Rodrigues da Silva <pitanga@members.fsf.org> # # This file is part of django-
smssync # # django-smssync 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. # # d
jango-smssync 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. # # You should have received a copy of the GNU General Public License # along w...
aammd/python-package-example
myPackage/__init__.py
Python
mit
22
0.045455
from .
import myModul
e
rosecatherinek/TransNets
src/DatasetUtils/DataPairMgr.py
Python
gpl-3.0
1,772
0.02088
''' read the input data, parse to int list; create mappings of (user,item) -> review int list @author: roseck @date Mar 15, 2017 ''' from __builtin__ import dict import gzip class DataPairMgr(): def _int_list(self,int_str): '''utility fn for converting an int string to a list of int ''' ...
n self.user_item_map[(user,item)] else: return [0] def get_int_review_rating(self, user, item): if (user,item) in self.user_item_map: return self.user_item_map[(user,item)], self.user_item_rating[(user,item)] else: return [0], 3.0 #average r...
michaelkuty/horizon-contrib
horizon_contrib/utils/__init__.py
Python
bsd-3-clause
79
0
from horiz
on_contrib.utils.dotdict import dotdict,
list_to_dotdict, to_dotdict
dimagi/commcare-hq
corehq/motech/fhir/tests/test_models.py
Python
bsd-3-clause
21,406
0.00028
import doctest from contextlib import contextmanager from django.core.exceptions import ValidationError from django.db import IntegrityError, transaction from django.db.models import ProtectedError from django.test import TestCase from nose.tools import assert_in from corehq.apps.data_dictionary.models import CasePr...
@classmethod def setUpClass(cls): super().setUpClass() cls.mother = CaseType.objects.create( domain=DOMAIN, name='mother', ) @classmethod def tearDownClass(cls): cls.mother.delete() super().tearDownClass() def test_search_params_emp...
import_config=self.import_config, name='ServiceRequest', case_type=self.referral, ) self.assertEqual(service_request.search_params, {}) def test_related_resource_types(self): service_request = FHIRImportResourceType.objects.create( import_config=self.imp...
darrylcousins/django-autocomplete
django_autocomplete/meta.py
Python
apache-2.0
1,979
0.002021
# -*- coding: utf-8 -*- class AutocompleteMeta: """ Simple meta class to allow the model to define aspects of the autocomplete. :var name: used for the named url :var path: the path to autocomplete view :var follow_fks: when searching should ForeignKey fields be followed. :var fields: list of...
onis defined in the ``iter`` See :class:`django_autocomplete.views.AutocompleteView` for more clarification. For example as a simple object: >>> from django_autocomplete.meta import AutocompleteMeta >>> class TestModel(object): ... autocomplete = AutocompleteMeta( ... ...
er/silly', ... ) The model autocomplete configures the model for use: >>> m = TestModel() >>> m.autocomplete <django_autocomplete.meta.AutocompleteMeta object at 0x...> >>> m.autocomplete.path 'api/filter/silly' >>> m.autocomplete.name 'sil...
eduNEXT/edunext-platform
import_shims/lms/discussion/rest_api/tests/test_pagination.py
Python
agpl-3.0
446
0.008969
"""Deprecated import support. Auto-generated by import_shims/generate_shims.sh.""" # pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-s
uppression,line-too-long from import_shims.warn import warn_deprecated_import warn_deprecated_import('discussion.rest_api.tests.test_pagination', 'lms.djangoapps.discussion.rest_
api.tests.test_pagination') from lms.djangoapps.discussion.rest_api.tests.test_pagination import *
DavidTingley/ephys-processing-pipeline
installation/klustaviewa-0.3.0/klustaviewa/views/tests/utils.py
Python
gpl-3.0
5,313
0.005835
"""Utils for unit tests for views package.""" # ----------------------------------------------------------------------------- # Imports # ----------------------------------------------------------------------------- import os import threading import time from qtools import QtGui, QtCore from qtools import s...
QtCore.Qt.Key_Q: self.close() def keyReleaseEvent(self, e): super(TestWindow, self).keyReleaseEvent(e) self.view.keyReleaseEvent(e) def closeEvent(self, e): if operators: self._thread.join() ...
usters, **kwargs): # loader.select(clusters=clusters) # data = vd.get_waveformview_data(loader) # kwargs.update(data) # show_view(v.WaveformView, **kwargs) # def show_featureview(loader, clusters, **kwargs): # loader.select(clusters=clusters) # data = vd.get_featureview_data(loader)...
SanketDG/networkx
networkx/algorithms/shortest_paths/weighted.py
Python
bsd-3-clause
33,546
0.000865
# -*- coding: utf-8 -*- """ Shortest path algorithms for weighed graphs. """ __author__ = """\n""".join(['Aric Hagberg <hagberg@lanl.gov>', 'Loïc Séguin-C. <loicseguin@gmail.com>', 'Dan Schult <dschult@colgate.edu>', 'Niels van Adrichem...
length, path) = single_source_dijkstra( G, source, cutoff=cutoff, weight=weight) return path def single_source_dijkstra_path_length(G, source, cutoff=None, weight='weight'): """Compute the shortest path length between source and all other reachable nodes for ...
) Edge data key corresponding to the edge weight. cutoff : integer or float, optional Depth to stop the search. Only paths of length <= cutoff are returned. Returns ------- length : iterator (target, shortest path length) iterator Examples -------- >>> G = nx.path_gr...
BenMotz/cubetoolkit
toolkit/members/migrations/0006_auto_20180223_2138.py
Python
agpl-3.0
506
0.001976
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-02-2
3 21:38 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('members', '0005_trainingrecordtype'), ] operations = [ migrations.AlterField( model_name='volunteer', name='portrait...
), ]
coders-creed/botathon
src/info/fetch_info.py
Python
mit
2,889
0.023884
# -*- coding: utf-8 -*- # @Author: karthik # @Date: 2016-12-10 21:40:07 # @Last Modified by: chandan # @Last Modified time: 2016-12-11 12:55:27 from models.portfolio import Portfolio from models.company import Company from models.position import Position import tenjin from tenjin.helpers import * import wikipedia...
'current_price': get_current_price(company), 'description': wikipedia.summary(company.name.split()[0], sentences=2) } wiki_page = wikipedia.page(company.name.split()[0]) html_page = urllib2.urlopen(wiki_page.url) soup = bs.BeautifulSoup(html_page) img_url = 'http:' + soup.find('td', { "class" : "logo" })....
ssage(parse_mode="HTML", chat_id=update.message.chat_id, text=html_str) symbols = [c.symbol for c in companies] if len(symbols) >= 2: symbol_string = ", ".join(symbols[:-1]) + " and " + symbols[-1] else: symbol_string = symbols[0] last_n_days = 10 if len(companies) < 4: create_graph(companies, last_n_days...
saltstack/salt
tests/unit/modules/nxos/nxos_n5k.py
Python
apache-2.0
5,857
0.004098
""" :codeauthor: Thomas Stoner <tmstoner@cisco.com> """ # Copyright (c) 2018 Cisco and/or its affiliates. # # 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/li...
tform class N5KPlatform(NXOSPlatform): """Cisco Systems N5K Platform Unit Test Object""" chassis = "cisco Nexus 5672UP 16G-FC Chassis" # Captured output from: show install all impact kickstart <kimage> system <image>
show_install_all_impact = """ Verifying image bootflash:/$KIMAGE for boot variable "kickstart". [####################] 100% -- SUCCESS Verifying image bootflash:/$IMAGE for boot variable "system". [####################] 100% -- SUCCESS Verifying image type. [####################] 100% -- SUCCESS Extracting "syst...
talkoopaiva/talkoohakemisto-api
talkoohakemisto/migrations/versions/597b5983e01c_create_voluntary_work_type_table.py
Python
mit
546
0.003663
"""Create `voluntary_work_type` table Revision ID: 597b5983e01c Revises: 2e20f
23a8ffd Create Date: 2014-02-08 17:14:35.812815 """ # revision identifiers, used by Alembic. revision = '597b5983e01c' down_revision = '2e20f23a8ffd' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( 'voluntary_work_type', sa.Column('id', sa.Integer(), nullable=Fals...
llable=False), ) def downgrade(): op.drop_table('voluntary_work_type')
pp-mo/iris
docs/iris/example_code/General/orca_projection.py
Python
lgpl-3.0
1,647
0
""" Tri-Polar Grid Projected Plotting ================================= This example demonstrates cell plots of data on the semi-structured ORCA2 model grid. First, the data is projected into the PlateCarree coordinate reference system. Second four pcolormesh plots are created from this projected dataset, using diff...
port iris import iris.analysis.cartography import iris.plot as iplt import iris.quickplot as qplt def main(): # Load data filepath = iris.sample_data_path("orca2_votemper.nc") cube = iris.load_cube(filepath)
# Choose plot projections projections = {} projections["Mollweide"] = ccrs.Mollweide() projections["PlateCarree"] = ccrs.PlateCarree() projections["NorthPolarStereo"] = ccrs.NorthPolarStereo() projections["Orthographic"] = ccrs.Orthographic( central_longitude=-90, central_latitude=45 ) ...
mtury/scapy
scapy/supersocket.py
Python
gpl-2.0
11,654
0
# This file is part of Scapy # See http://www.secdev.org/projects/scapy for more information # Copyright (C) Philippe Biondi <phil@secdev.org> # This program is published under a GPLv2 license """ SuperSocket. """ from __future__ import absolute_import from select import select, error as select_error import errno imp...
lvl = 3 try: pkt = cls(pkt) except KeyboardInterrupt: raise except Exception: if conf.debug_dissector: raise pkt = conf.raw_layer(pkt) if lvl == 2: pkt = pkt.payload if pkt is not None: ...
sx = raw(x) x.sent_time = time.time() self.outs.sendto(sx, (x.dst, 0)) except socket.error as msg: log_runtime.error(msg) class SimpleSocket(SuperSocket): desc = "wrapper around a classic socket" def __init__(self, sock): self.ins = sock self.outs ...
eranimo/historia
historia/world/biome.py
Python
mit
2,771
0.000361
from historia.enums.dict_enum import DictEnum class Biome(DictEnum): __exports__ = ['title', 'color', 'id'] arctic = { 'id': 1, 'title': 'Arctic', 'color': (224, 224, 224), 'fertility': 1, 'can_farm': False, 'has_forest': False, 'base_favorability': 10 ...
erate Forest', 'color': (76, 192, 0), 'fertility': 100, 'can_farm': True, 'has_forest': True, 'base_favorability': 50 } temperate_rainforest = { 'id': 10, 'titl
e': 'Temperate Rainforest', 'color': (89, 129, 89), 'fertility': 100, 'can_farm': True, 'has_forest': True, 'base_favorability': -10 } tropical_forest = { 'id': 11, 'title': 'Tropical Forest', 'color': (96, 122, 34), 'fertility': 70, ...
bjornaa/ladim
examples/line/plot_holoviews.py
Python
mit
1,481
0.000675
# Use holoviews to plot the particle distribution at given time from pathlib import Path import numpy as np import xarray as xr import holoviews as hv from postladim import ParticleFile hv.extension("bokeh") # --- Settings --- tstep = 40 # Time step to show
# Output file (and type) output_file = "line_hv.png" #output_file = "line_hv.html" scale = 5 # Figure size factor # --- Data files --- ladim_dir = Path("../../") grid_file = ladim_dir / "examples/data/ocean_avg_0014.nc" particle_file = ladim_dir / "examples/line/line.nc" # --- Read particle data --- pf = Particl...
# --- Background bathymetry data --- # Read bathymetry and land mask with xr.open_dataset(grid_file) as A: H = A.h M = A.mask_rho jmax, imax = M.shape H = H.where(M > 0) # Mask out land M = M.where(M < 1) # Mask out sea # --- Holoviews elements --- # Land image land = hv.Image(data=M, kdims=["xi_rho", "et...
jhermann/neutrino-wand
src/neutrino_wand/cli.py
Python
apache-2.0
1,396
0.002869
# -*- coding: utf-8 -*- """ Command
Line Interface. """ # Copyright © 2014 Jürgen Hermann # # 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...
ither express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, with_statement import sys import logging from neutrino_wand import pkg_info class NeutrinoWand(object): """ The main `wand` command line applic...
faylau/oVirt3.3WebAPITest
src/TestData/Profile/ITC090402_UpdateProfile_DupName.py
Python
apache-2.0
1,804
0.003898
#encoding:utf-8 __authors__ = ['"Wei Keke" <keke.wei@cs2c.com.cn>'] __version__ = "V0.1" ''' # ChangeLog: #--------------------------------------------------------------------------------- # Version Date Desc Author #----------------------------------------------------...
helled</description> <network id="%s"/> </vnic_profile> ''' ''' @note: TestData ''' update_info = ''' <vnic_profile> <name>p002</name> <description>shelled</description>
<port_mirroring>true</port_mirroring> </vnic_profile> ''' ''' @note: ExpectedData ''' expected_status_code = 409 expected_info = ''' <fault> <reason>Operation Failed</reason> <detail>[Cannot edit VM network interface profile. The VM network interface profile's name is already used by an existing profile...
trunca/enigma2
skin.py
Python
gpl-2.0
39,906
0.034506
from Tools.Profile import profile profile("LOAD:ElementTree") import xml.etree.cElementTree import os profile("LOAD:enigma_skin") from enigma import eSize, ePoint, eRect, gFont, eWindow, eLabel, ePixmap, eWindowStyleManager, addFont, gRGB, eWindowStyleSkinned, getDesktop from Components.config import ConfigSubsection, ...
er_header.xml', SCOPE_SKIN) print "[SKIN] loading user defined header file for skin", (primary_skin_path + 'skin_user_header.xml') except (SkinError, IOError, AssertionError), err: print "[SKIN] not loading user defined header file for skin" def load_modular_files(): modular_files = get_modular_files(primary_skin_p...
ath + f) except (SkinError, IOError, AssertionError), err: print "[SKIN] failed to load modular skin file : ", err load_modular_files() try: if not addSkin(config.skin.primary_skin.value): raise SkinError, "primary skin not found" except Exception, err: print "SKIN ERROR:", err skin = DEFAULT_SKIN if confi...
riccardomarotti/slidown
tests/test_config.py
Python
gpl-3.0
1,706
0.002345
# -*- coding: utf-8 -*- import os import tempfile from slidown import config def test_load_not_existing_config(): with tempfile.TemporaryDirectory() as temp_dir: configuration_file = os.path.join(temp_dir, 'config.json') import appdirs appdirs.user_config_dir = lambda any_appname: temp_d...
: 'config'} def test_save(): config_hash = { 'hash': 'of configuration', 'with': 'some', 'interesting': 'values' } with tempfile.TemporaryDirectory() as temp_dir: configuration_file = os.path.join(temp_dir, 'config.json') import appdirs appdirs.user_config_d...
ting_config_directory(): temp_dir_name = tempfile.TemporaryDirectory().name configuration_file = os.path.join(temp_dir_name, 'config.json') import appdirs appdirs.user_config_dir = lambda any_appname: temp_dir_name config_hash = config.load() assert open(configuration_file).read() == "{}" ...
inspirehep/invenio
modules/bibcheck/lib/plugins/rename_subfield.py
Python
gpl-2.0
1,062
0.013183
# -*- coding: utf-8 -*- ## ## Thi
s file is part of Invenio. ## Copyright (C) 2013 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any l
ater version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Publi...
CMPUT410W15T02/CMPUT410W15-project
social_distribution/authors/migrations/0002_auto_20150301_2125.py
Python
gpl-2.0
857
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import uuid class Migration(migrations.Migration): dependencies = [ ('authors', '0001_initial'), ] operations = [ migrations.AddField( model_name=
'profile', name='displayname', field=models.CharField(max_length=128, blank=True), preserve_default=True, ), migrations.AddField( model_name='profile', name='host', field=mo
dels.CharField(max_length=32, blank=True), preserve_default=True, ), migrations.AddField( model_name='profile', name='uuid', field=models.CharField(default=uuid.uuid1, max_length=32), preserve_default=True, ), ]
theblacklion/project-service
scripts/mysql-dump-splitter.py
Python
mit
5,954
0.000168
#!/usr/bin/env python3 # # Usage: mysql-dump-splitter.py dump.sql.gz # Usage: mysql-dump-splitter.py dump.sql.bz2 # # @author Oktay Acikalin <oktay.acikalin@gmail.com> # @copyright Oktay Acikalin # @license MIT (LICENSE.txt) import sys import re import gzip import bz2 # HEADER_REGEX = r'' SECTION_INDICATOR = r'...
>[^`]+)`' # SECTION_INDICATOR_FOOTER = r'UNLOCK TABLES;\n\/\*\!' SECTION_TYPE_HEADER = 1 SECTION_TYPE_DATABASE = 2 SECTION_TYPE_TABLE_STRUCTURE = 3 SECTION_TYPE_TABLE_DATA = 4 SECTION_TYPE_TEMP_VI
EW = 5 SECTION_TYPE_FINAL_VIEW = 6 SECTION_TYPE_FOOTER = 90 SECTION_TYPE_UNKNOWN = 99 def write_data_to_disk(file, section_type, section_name, data, excludes): stype = ( 'database' if section_type == SECTION_TYPE_DATABASE else 'structure' if section_type == SECTION_TYPE_TABLE_STRUCTURE else ...
ronekko/chainer
tests/chainer_tests/training_tests/extensions_tests/test_evaluator.py
Python
mit
8,187
0
import unittest import numpy import chainer from chainer import dataset from chainer import iterators from chainer import testing from chainer.training import extensions class DummyModel(chainer.Chain): def __init__(self, test): super(DummyModel, self).__init__() self.args = [] self.tes...
iterators.MultiprocessIterator, iterators.MultithreadIterator] })) class TestEvaluatorRepeat(unittest.TestCase): def test_user_warning(self): dataset = numpy.ones((4, 6)) iterator = self.iterator_class(dataset, 2, repeat=self.repeat)
if self.repeat: with testing.assert_warns(UserWarning): extensions.Evaluator(iterator, {}) testing.run_module(__name__, __f
tyarkoni/transitions
tests/test_codestyle.py
Python
mit
710
0
import unittest import pycodestyle from os.path import exists class TestCodeFormat(unittest.TestCase
): def test_conformance(self): """Test that we conform to PEP-8.""" style = pycodestyle.StyleGuide(quiet=False, ignore=['E501', 'W605']) if exists('transitions'): # when run from root directory (e.g. tox) style.input_dir('transitions') style.input_dir('tests') ...
st directory (e.g. pycharm) style.input_dir('../transitions') style.input_dir('.') result = style.check_files() self.assertEqual(result.total_errors, 0, "Found code style errors (and warnings).")
cirosantilli/sulley
sulley/primitives.py
Python
gpl-2.0
32,873
0.00721
import random import struct ######################################################################################################################## class base_primitive (object): ''' The primitive base class implements common functionality shared across most primitives. ''' def __init__ (self): ...
be fuzzed. self.mutant_index = 0 # current mutation index into the fuzz library. self.original_value = None #
original value of primitive. self.rendered = "" # rendered value of primitive. self.value = None # current value of primitive. def exhaust (self): ''' Exhaust the possible mutations for this primitive. @rtype: Integer @return: The number...
lvh/txeasymail
txeasymail/interface.py
Python
isc
541
0.001848
""" Interface definition. """ from zope import interface class IMailer(interface.Interface): """ An ob
ject that sends e-mail. """ def send(sender, recipient, content): """ S
ends the content to the recipient as the sender. """ class ITemplate(interface.Interface): """ An e-mail template. """ def evaluate(context): """ Evaluates a template given a context. Returns a pair of headers and parts that can be used to build a MIME message...
llvmpy/llvmpy
llvm/tests/test_exact.py
Python
bsd-3-clause
1,076
0.003717
import unittest from llvm.core import (Module, Type, Builder) from .support import TestCase, tests class TestExact(TestCase): def make_module(self): mod = Module.new('asdfa') fnty = Type.function(Type.void(), [Type.int()] * 2) func = mod.add_function(fnty, 'foo') bldr = Builder.new(...
me) def test_udiv_exact(self): self._test_template(Builder.udiv, 'udiv') def test_sdiv_exact(self): self._test_template(Builder.sdiv, 'sdiv') def test_lshr_exact(self): self._test_template(Builder.lshr, 'lshr') def test_ashr_exact(self): self._test_template(Builder.as...
'ashr') tests.append(TestExact) if __name__ == '__main__': unittest.main()
dchaplinsky/pep.org.ua
pepdb/tasks/management/commands/load_companies.py
Python
mit
11,229
0.001812
# -*- coding: utf-8 -*- from __future__ import unicode_literals import re from random import randrange import requests import os.path import xml.etree.ElementTree as ET from xml.etree.ElementTree import ParseError import logging from io import TextIOWrapper, open from unicodecsv import DictReader from itertools import...
o
cover records that was incorrectly exported and incomplete, thus make whole XML file invalid (happens sometime) """ with TextIOWrapper(fp_raw, encoding="cp1251") as fp: mapping = { 'NAME': 'name', 'SHORT_NAME': 'short_name', 'ED...
luanfonceca/econet
econet/accounts/migrations/0001_initial.py
Python
mit
5,920
0.007264
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'User' db.create_table(u'accounts_user', ( (u'id', self.gf('django.db.models.fiel...
anField')(default=False)), ('email', self.gf('django.db.models.fields.EmailField')(unique=True, max_length=254)), ('first_name', self.gf('django.db.models.fields.CharField')(max_length=30, null=True)), ('last_name', self.gf('django.db.models.fields.CharField')(max_length=254, null=Tr...
Field')(default=datetime.datetime.now)), ('is_staff', self.gf('django.db.models.fields.BooleanField')(default=False)), ('is_active', self.gf('django.db.models.fields.BooleanField')(default=True)), ('is_colector', self.gf('django.db.models.fields.BooleanField')(default=False)), ...
iwob/evoplotter
app/cdgp2/cdgp_processor.py
Python
mit
20,853
0.005946
from evoplotter import utils from evoplotter import printer from evoplotter import reporting from evoplotter.dims import * import numpy def load_correct_props(folders, name = ""): props0 = utils.load_properties_dirs(folders, exts=[".txt.cdgp"]) all_logs = utils.load_properties_dirs(folders, exts=[".txt.cdgp",...
Max4"} dim_method =
Dim([Config("CDGP non-conservative", p_method0, method="CDGP"), Config("CDGP conservative", p_method1, method="CDGPcons"), Config("GPR", p_method2, method="GPR")]) dim_sa = Dim([Config("GP", p_GP, searchAlgorithm="GP"), Config("GPSS", p_GPSteadyState, searchAlgorithm="G...
tejal29/pants
src/python/pants/backend/jvm/tasks/eclipse_gen.py
Python
apache-2.0
6,935
0.00721
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import pkg...
be a relative path unlike other paths outdir=os.path.relpath(outdir, get_buildroot()), ) def apply_template(output_path, template_relpath, **template_data): with s
afe_open(output_path, 'w') as output: Generator(pkgutil.get_data(__name__, template_relpath), **template_data).write(output) apply_template(self.project_filename, self.project_template, project=configured_project) apply_template(self.classpath_filename, self.classpath_template, classpath=configured_cla...
manahl/arctic
arctic/store/audit.py
Python
lgpl-2.1
6,512
0.005375
""" Handle audited data changes. """ import logging from functools import partial from pymongo.errors import OperationFailure from .versioned_item import VersionedItem, ChangedItem from .._util import are_equals from ..decorators import _get_host from ..exceptions import NoDataFoundException, ConcurrentModificationEx...
self.new_data = new_data class ArcticTransaction(object): """Use this context manager if you want to modify data in a version store while ensuring that no other writes interfere with your own. To use, base your modifications on the `base_ts` context manager field and put your newly created timese...
mple: ------- with ArcticTransaction(Arctic('hostname')['some_library'], 'symbol') as mt: ts_version_info = mt.base_ts # do some processing, come up with a new ts for 'symbol' called new_symbol_ts, presumably based on ts_version_info.data mt.write('symbol', new_symbol_ts, metadata=new_sy...
nim65s/django-cineclub
setup.py
Python
gpl-3.0
1,266
0.00079
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), "README.md")) as readme: README = readme.read() with open(os.path.join(os.path.dirname(__file__), "requirements.in")) as requirements: REQUIREMENTS = [ req.split("#egg=")[1] if "#egg=" in req else req for...
r_email="webmaster@saurel.me", classifiers=[ "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: GPL License", "Operating System :: OS Independent", "Programming Language :: Python", "Programm...
nternet :: WWW/HTTP :: Dynamic Content", ], )
puhitaku/AutoChime
ntptime_kai.py
Python
mit
1,216
0.002467
# Copy of ntptime.py with millisecond-accurate sync try: import usocket as socket except: import socket try: import ustruct as struct except: import struct # (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60 NTP_DELTA = 3155673600 MILLIS_PER_SECOND = 1000 host = "pool.ntp.org" def time(ms_accur...
t in MicroPython, so # utime.localtime() will return
UTC time (as if it was .gmtime()) def settime(ms_accuracy=False): import machine import utime if ms_accuracy: t, ms = time(ms_accuracy=True) else: t, ms = time(ms_accuracy=False), 0 tm = utime.localtime(t) tm = tm[0:3] + (0,) + tm[3:6] + (ms,) r = machine.RTC() r.datetim...
jayceyxc/hue
desktop/core/ext-py/navoptapi-0.1.0/navoptapi/old_serialize.py
Python
apache-2.0
3,364
0.000595
# Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Modifications made by Cloudera are: # Copyright (c) 2016 Cloudera, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A cop...
self._default_serialize(serialized, value, shape, key) def _serialize_type_object(self, serialized, value, shape, key): if key is not None: # If a key is provided, this is a result of a recursive call, so we # need to add a new child dict as the value of the passed in dict. ...
serialized = serialized[key] for member_key, member_value in value.items(): member_shape = shape.members[member_key] self._serialize(serialized, member_value, member_shape, member_key) def _serialize_type_array(self, serialized, value, shape, key): array_obj = [] se...
mediatum/mediatum
web/edit/modules/content.py
Python
gpl-3.0
5,793
0.002935
""" mediatum - a multimedia content repository Copyright (C) 2009 Arne Seifert <seiferta@in.tum.de> 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...
Data.get_all_datatypes() for scheme in _schemes: for dtype in scheme.getDatatypes(): if dtype not in _dtypes: for _t in datatypes: # if _t.getName() == dtype and not elemInList(dtypes, _t.getName()): dtypes.append(_t...
def get_ids_from_query(): ids = get_ids_from_req(req) return ",".join(ids) node = q(Data).get(long(ids[0])) if "action" in req.params: if req.params.get('action') == "resort": field = req.params.get('value', '').strip() res = showdir(req, node, sortfield=f...
ingted/crmsh
modules/xmlutil.py
Python
gpl-2.0
37,119
0.001051
# Copyright (C) 2008-2011 Dejan Muhamedagic <dmuhamedagic@suse.de> # See COPYING for license information. import os import subprocess from lxml import etree, doctestcompare import copy import bz2 from collections import defaultdict from . import config from . import options from . import schema from . import constant...
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: outp, errp = p.communicate() p.wait() return p.returncode, outp, errp except IOError, msg: common_err("running %s: %s" % (cmd, msg)) return None, None, None def cibdump2file(f...
dump) if outp is not None: return str2tmp(outp) except IOError, msg: common_err(msg) return None def cibtext2elem(cibtext): """ Convert a text format CIB to an XML tree. """ try: return etree.fromstring(cibtext) except Exception, err: cib_par...
mattkoskela/py-pdf-collate
pdf_collate/pdf.py
Python
mit
1,217
0.000822
## # This file contains an class for pdf_collate # # @package pdf_collate # @author Matt Koskela <mattkoskela@gmail.com> ## """ Example.py This file contains an example class with a basic function. """ import os import hashlib from PyPDF2 import PdfFileReader, PdfFileWriter class PDF(): """ This i...
pdfTest = PdfFileReader(file(source_filename, "rb")) output = PdfFileWriter() number_of_pages = pdfTest.getNumPages() for page_number in range(0, number_of_pages/2): output.addPage(pdfTest.getPage(page_
number)) output.addPage(pdfTest.getPage(page_number + number_of_pages/2)) outputStream = file(output_filename, "wb") output.write(outputStream) outputStream.close() if random_filename: os.rename(random_filename, source_filename)
ebu/PlugIt
tests/proxy_internal/test_proxyviews_generate.py
Python
bsd-3-clause
3,938
0.001524
from test_proxyviews import TestProxyViews import uuid class TestProxyViewsGenerate(TestProxyViews): def test_generate_user_nobody(self): assert(not self.views.generate_user(None, None)) def test_generate_user_ano(self): user = self.views.generate_user('ano') assert(user) a...
url, raison) assert(response) assert(response.status_code == 404) assert(response.content.strip() == '404,{},{},{}'.format(raison, url, usermode)
) self.restore_base_url() def test_gen_500(self): url = self.random_base_url() usermode = str(uuid.uuid4()) request = self.build_request('/') request.session['plugit-standalone-usermode'] = usermode response = self.views.gen500(request, url) assert(respon...
anthrotype/nototools
nototools/noto_data.py
Python
apache-2.0
16,915
0.003074
#!/usr/bin/env python # # Copyright 2014 Google Inc. All rights reserved. # # Licensed
under
the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is dis...
SteffenBauer/mia_elixir
python/mia_client1.py
Python
mit
2,536
0.024054
#!/usr/bin/env python import socket import random SERVERHOST = 'localhost' SERVERPORT = 4080 LOCALIP = '127.0.0.2' LOCALPORT = 4082 LOCALNAME = "30_PERCENT_SEE" def higher(dice_a, dice_b): ad1, ad2 = dice_a[0], dice_a[1] bd1, bd2 = dice_b[0], dice_b[1] if ad1 == bd1 and ad2 == bd2: return False if ad1 == "2...
d = None elif data.startswith("AN
NOUNCED;"): d1, _, d2 = data.strip().split(";")[2].partition(",") announced = (d1, d2) elif data.startswith("YOUR TURN;"): _, _, token = data.strip().partition(";") if announced == None or random.uniform(0,100) > 30.0: sock.sendto("ROLL;" + token, (SERVERHOST, SERVERPORT)) else...
ellipsis14/dolfin-adjoint
tests_firedrake/projection/projection.py
Python
lgpl-3.0
886
0.01693
import random from firedrake import * from firedrake_adjoint import * import sys mesh = UnitSquareMesh(4, 4) V3 = FunctionSpace(mesh, "CG", 3) V2 = FunctionSpace(mesh, "CG", 2) firedrake.parameters["adjoint"]["record_all"] = True def main(ic, annotate=False): soln = project(ic, V2, annotate=annotate) return soln...
_": ic = project(Expression("x[0]*(x[0]-1)*x[1]*(x[1]-1)"), V3) soln = main(ic, annotate=True) adj_html("projection_forward.html", "forward") assert replay_dolfin(tol=1e-12, stop=True) J = Functional(soln*soln*dx*dt[FINISH_TIME]) Jic = assemble(soln*soln*dx) dJdic = compute_gradient(J, InitialCondition...
Jic, dJdic) if minconv < 1.9: sys.exit(1)
makism/dyfunconn
examples/fc_mi.py
Python
bsd-3-clause
390
0.002564
# -*- coding: utf-8 -*- import numpy as np np.set_printoptions(precision=3, l
inewidth=256) from dyconnmap.fc import mi if __name__ == "__main__": data = np.load( "/home/makism/Github/dyconnmap/examples/data/eeg_32chans_10secs.npy") data
= data[0:5, :] fs = 128 fb_lo = [1.0, 4.0] fb_hi = [8.0, 13.0] ts, avg = mi(data, fb_lo, fb_hi, fs) print(avg)
cydenix/OpenGLCffi
OpenGLCffi/GL/EXT/ARB/ES3_2_compatibility.py
Python
mit
209
0.019139
from OpenGLCffi.GL import params @params(api='gl', prms=['minX', 'minY', 'minZ', 'minW', 'maxX', 'maxY', 'ma
xZ', 'maxW']) def g
lPrimitiveBoundingBoxARB(minX, minY, minZ, minW, maxX, maxY, maxZ, maxW): pass
kcl-ddh/chopin-online
ocve/scripts/ocvejp2converter.py
Python
gpl-3.0
10,997
0.010003
#!/usr/bin/python """Module for batch converting images to JPEG 2000 format. Takes an input directory and recreates the directory structure, with converted images, in the specified output directory. WARNING: If the same directory contains two or more images with the same name (excepting the extension), only one of th...
.O_CREAT | os.O_TRUNC | os.O_WRONLY) try: fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: return False return True if not lockFile("/vol/ocve3/webroot/stg/logs/.imageconvert.lock"): logger.error('Another instance detected as lock exists, exiting.') sys.exit(0) # End ...
progress=False): """Initialise this object. :param in_dir: path to directory containing images to be converted :type in_dir: `str` :param out_dir: path to directory to output converted images :type out_dir: `str` :param out_dir: archive directory for successfully converte...
michael-ball/sublime-text
sublime-text-3/Packages/User/linters/eclim.py
Python
unlicense
2,139
0.000468
import json import os import tempfile from lint import Linter from lint.util import find class Eclim(Linter): language = 'java' cmd = ('eclim', '-command', 'java_src_update') regex = r'.' defaults = { 'disable': True, } def run(self, cmd, code): project = find(os.path.dirname...
with open(self.filename, 'wb') as f: f.write(code) if os.name == 'posix': inode = os.stat(self.filename).st_ino try: cmd = cmd + ('-p', project, '-f', filename, '-v') output = self.communicate(cmd, '') finally: if inod...
if new_inode != inode: # they saved over our tmp file, bail return output os.unlink(self.filename) os.rename(tmp, self.filename) return output def find_errors(self, output): try: obj = json.loads(output) ...
matiskay/html-cluster
html_cluster/commands/make_graph.py
Python
bsd-3-clause
1,507
0.001991
import os im
por
t json import click def generate_graph(similarity_file, threshold=85): edges = dict() hosts_used = set() with open(similarity_file, 'r') as json_file: scores = json.load(json_file) score_dict = {s['similarity']: (s['path1'], s['path2']) for s in scores} for score, paths in score_dict.it...
philgyford/django-spectator
devproject/manage.py
Python
mit
822
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "devpro
ject.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is miss
ing to avoid masking other # exceptions on Python 2. try: import django # noqa: F401 except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did ...
peterjliu/rate_limit
test_lib.py
Python
mit
2,134
0.005623
#!/usr/bin/env python """ Test rate-limiter lib """ import logging import sys import time import unittest from google.appengine.api import memcache from google.appengine.ext import testbed from lib import Limiter, QuotaKey class Events: USER_READ = 1 USER_WRITE = 2 RATE_LIMIT_SPEC = { Events.USER_READ: ...
nfo("wait 1 second for cache to expire") time.sleep(1) for _ in range(0, 2): self.assertTrue(self.limiter.CanSpend(q)) if __name__ == '__main__': logging.basicConfig(stream=sys.stderr) logging.getLogger("rate_limit.lib.test" ).setLevel( logging.DEBUG ) unittest.main()
kevenli/scrapydd
scrapydd/process.py
Python
apache-2.0
3,812
0.001836
from tornado.process import cpu_count, _reseed_random from tornado import ioloop import logging import os import signal import sys from tornado.util import errno_from_exception import errno logger = logging.getLogger(__name__) _task_id = None exiting = False def fork_processes(num_processes, max_restar...
autoreload=True`` option to `tornado.web.Application` which defaults to True when ``debug=True``). When using multiple processes, no IOLoops can be created or referenced until after the call to ``fork_processes``. In each child process, ``fork_processes`` returns its *task id*, a number betwe...
parent process, ``fork_processes`` returns None if all child processes have exited normally, but will otherwise only exit by throwing an exception. """ global _task_id assert _task_id is None if num_processes is None or num_processes <= 0: num_processes = cpu_count() log...
baike21/blog
blogadmin/migrations/0002_auto_20170826_1818.py
Python
gpl-3.0
822
0.002433
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-08-26 10:18 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blogadmin', '0001_initial'), ] op
erations = [ migrations.AlterField( model_name='article', name='category', field=models.CharField(choices=[('Tech', '\u6280\u672f'), ('Chat', '\u6742\u6587'), ('Movie', '\u5f71\u8bc4'), ('Book', '\u8bfb\u4e66')], default='Tech', max_length=64, verbose_name='\u7c7b\u522b\u6807...
name='pub_date', field=models.DateTimeField(auto_now_add=True, verbose_name='\u53d1\u5e03\u65f6\u95f4'), ), ]
partofthething/home-assistant
homeassistant/components/owntracks/config_flow.py
Python
apache-2.0
2,860
0.002448
"""Config flow for OwnTracks.""" import secrets from homeassistant import config_entries from homeassistant.const import CONF_WEBHOOK_ID from .const import DOMAIN # pylint: disable=unused-import from .helper import supports_encryption CONF_SECRET = "secret" CONF_CLOUDHOOK = "cloudhook" class OwnTracksFlow(config_...
return self.async_abort(reason="single_instance_allowed") webhook_id, _webhook_url, cloudhook = await self._get_webhook_id() secret = secrets.token_hex(16) return self.async_create_entry( title="OwnTracks", data={ CON
F_WEBHOOK_ID: webhook_id, CONF_SECRET: secret, CONF_CLOUDHOOK: cloudhook, }, ) async def _get_webhook_id(self): """Generate webhook ID.""" webhook_id = self.hass.components.webhook.async_generate_id() if self.hass.components.cloud.async_ac...
junaart/Structure_data
Code/tree.py
Python
gpl-3.0
9,097
0.018138
###################### TREE###################### class node(): __parent = None __left = None __right = None __data = None def __init__(self, value): self.__data = value self.__parent = None self.__left = None self.__right = None def get_parent(self...
): if (current_node.get_right() != None): current_node = current_node.get_right() self.add_node(value, current_node) else: a = node(value) current_node.set_right(a) a.set_parent(current_node) else: ...
ft() != None): current_node = current_node.get_left() self.add_node(value, current_node) else: a = node(value) current_node.set_left(a) a.set_parent(current_node) def add_list(self, lst): ...
Duoxilian/home-assistant
homeassistant/components/history.py
Python
mit
11,138
0
""" Provide pre-made queries on top of the recorder component. For more details about this component, please refer to the documentation at https://home-assistant.io/components/history/ """ import asyncio from collections import defaultdict from datetime import timedelta from itertools import groupby import logging imp...
util.parse_datetime(datetime) if datetime is None: return self.json_message('Invalid datetime', HTTP_BAD_REQUEST) now = dt_util.utcnow() one_day = timedelta(days=1) if datetime: start_time = dt_util.as_utc(datetime) else: start_time ...
return self.json([]) end_time = request.GET.get('end_time') if end_time: end_time = dt_util.as_utc( dt_util.parse_datetime(end_time)) if end_time is None: return self.json_message('Invalid end_time', HTTP_BAD_REQUEST) else: ...
sgiavasis/C-PAC
CPAC/vmhc/vmhc.py
Python
bsd-3-clause
22,733
0.007918
import sys import os import commands import nipype.pipeline.engine as pe import nipype.algorithms.rapidart as ra import nipype.interfaces.fsl as fsl import nipype.interfaces.io as nio import nipype.interfaces.utility as util from utils import * from CPAC.vmhc import * from nipype.interfaces.afni import preprocess from ...
) MNI152_T1_2mm_brain_mask_symmetric_di
l.nii.gz inputspec.config_file_twomm_symmetric : string (existing .cnf file) T1_2_MNI152_2mm_symmetric.cnf inputspec.rest_mask : string (existing nifti file) A mask functional volume(derived by dilation from motion corrected functional volume) fwhm_input.fwhm : list (f...
EdDev/vdsm
lib/vdsm/network/ip/rule/__init__.py
Python
gpl-2.0
2,327
0
# Copyright 2017 Red Hat, 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 2 of the License, or # (at your option) any later version. # # This program is distributed in the ...
data object """ raise NotImplementedError @staticmethod def delete(rule_data): """ Delete a rule entry described by an IPRuleData data object """ raise NotImplementedError @staticmethod def rules(table='all'): raise NotImplementedError class IPRuleData(object): ""...
e, iif=None, table=None): self._to = to self._src = src self._iif = iif self._table = table @property def to(self): return self._to @property def src(self): return self._src @property def iif(self): return self._iif @property de...
EmreAtes/spack
lib/spack/spack/cmd/reindex.py
Python
lgpl-2.1
1,426
0
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by
Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it un
der the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # 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. ...
oscaro/django
tests/migrations/test_loader.py
Python
bsd-3-clause
12,020
0.002246
from __future__ import unicode_literals from unittest import skipIf from django.test import TestCase, override_settings from django.db import connection, connections from django.db.migrations.graph import NodeNotFoundError from django.db.migrations.loader import MigrationLoader, AmbiguityError from django.db.migratio...
rder = MigrationRecorder(connection) def num_nodes(): plan = set(loader.graph.forwards_plan(('migrations', '7_auto'))) return len(plan - loader.applied_migrations) # Empty database: use squashed migration loader.build_graph() self.assertEqual(num_nodes(), 5) ...
tions", "1_auto") loader.build_graph() self.assertEqual(num_nodes(), 4) recorder.record_app
Abjad/abjad
tests/test_NoteHeadList___delitem__.py
Python
gpl-3.0
216
0
import abjad def
test_NoteHeadList___delitem___01(): """ Deletes note-head. """ chord = abjad.Chord("<ef' cs'' f''>4") del chord.note_heads[1] assert abjad.lilypond(chord) == "<ef' f'
'>4"
PyAr/fades
tests/test_parsing/test_reqs.py
Python
gpl-3.0
3,030
0.00066
"""Check the requirements parsing.""" import io from logassert import Multiple from fades import parsing, REPO_PYPI, REPO_VCS from tests import get_reqs def test_empty(): parsed = parsing._parse_requirement(io.StringIO(""" """)) assert parsed == {} def test_simple(): parsed = parsing._parse_requ...
nt(io.StringIO(""" foo """)) assert parsed == {REPO_PYPI: get_reqs('foo')} def test_double(): parsed = parsing._parse_requirement(io.StringIO(""" pypi:
:time foo """)) assert parsed == { REPO_PYPI: get_reqs('time') + get_reqs('foo') } def test_version_same(): parsed = parsing._parse_requirement(io.StringIO(""" pypi::foo == 3.5 """)) assert parsed == { REPO_PYPI: get_reqs('foo == 3.5') } def test_version_s...
dawnpower/nova
nova/tests/unit/compute/test_compute.py
Python
apache-2.0
522,454
0.001066
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Piston Cloud Computing, Inc. # All Rights Reserved. # Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # no...
icense 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. """Tests for
compute service.""" import base64 import contextlib import datetime import operator import sys import time import traceback import uuid from eventlet import greenthread import mock from mox3 import mox from neutronclient.common import exceptions as neutron_exceptions from oslo_config import cfg from oslo_log import ...
clarkperkins/django-rest-framework-siren
rest_framework_siren/pagination.py
Python
apache-2.0
767
0
""" Siren pagination """ from __future__ import unicode_literals from collections import OrderedDict from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response from rest_framework_siren.utils imp
ort link_maker class SirenPagination(PageNumberPagination): """ Pagination class for Siren """ def get_paginated_respons
e(self, data): links = [ link_maker(['self'], 'self'), link_maker(['next'], self.get_next_link()), link_maker(['previous'], self.get_previous_link()), ] return Response(OrderedDict([ ('properties', {'count': self.page.paginator.count}), ...
kovidgoyal/html5-parser
src/html5_parser/soup.py
Python
apache-2.0
4,216
0.000949
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: Apache 2.0 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __future__ import absolute_import, division, print_function, unicode_literals unicode = type('') cdata_list_attributes = None universal_cdata_list_attributes = None empty = () def init_b...
eautifulSoup() new_tag = bs3_new_tag(bs.Tag, soup) append = bs3_fast_append soup.i
sSelfClosing = lambda self, name: name in VOID_ELEMENTS else: soup = bs.BeautifulSoup('', 'lxml') new_tag = bs4_new_tag(bs.Tag, soup) append = bs4_fast_append if universal_cdata_list_attributes is None: init_bs4_cdata_list_attributes() return bs, soup, new_tag, bs.Com...
Spooner/pixel-table
pixel_table/external/unicorn.py
Python
mit
513
0.003899
from __future__ import absolute_import, division, print_function, unicode_literals import n
umpy as np class Unicorn(object): def __init__(self): import unicornhathd as unicorn unicorn.rotation(180) unicorn.bright
ness(0.75) def write_pixels(self, data): import unicornhathd as unicorn for y, row in enumerate((data * 255).astype(np.uint8)): for x, color in enumerate(row): unicorn.set_pixel(x, y, *color) unicorn.show()
mikefeneley/topcoder
src/SRM-184/race_approximator.py
Python
mit
716
0.009777
import math class RaceApproximator: def timeToBeat(self, d1, t1, d2, t2, raceDistance): time = t1 * math.exp( math.log(float(t2)/t1) * math.log(float(d1)/raceDistance) / math.log(float(d1)/d2) ) time = int(time) hours = time / 3600 minutes = (time - hours * 3600) / 60 ...
' + str(minutes) else: minutes = str(minutes) if(seconds < 10): seconds = '0' + str(seconds) else: seconds = str(seconds) final = hours + ':' + minutes +
':' + seconds return final
VitalLabs/gcloud-python
scripts/run_pylint.py
Python
apache-2.0
9,455
0
# Copyright 2014 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
uple of the
diff base using the the list of filenames to be linted. """ diff_base = None if (os.getenv('TRAVIS_BRANCH') == 'master' and os.getenv('TRAVIS_PULL_REQUEST') != 'false'): # In the case of a pull request into master, we want to # diff against HEAD in master. ...
duanyifei/python_modules_test
test_message.py
Python
gpl-3.0
925
0.021935
#coding:utf8 ''' 发布订阅模式 ''' import message #Example def hello(name): print "hello, %s."%name def hi(name): print "hi, %s."%name def stop(name): print 'hello, %s. greet5'%name print 'discontinued.' ctx = message.Context() ctx.discontinued = Tru
e return ctx #订阅一个话题,并发布 message.sub('greet', hello) message.sub('greet', hi) message.pub('greet', 'lai') message.pub('greet1', 'lai1') #订阅另一个话题,并发布 message.sub('greet1', hello) message.pub('greet1', 'lai1') #取消订阅 message.unsub('greet', hello) message.pub('greet', 'unsub') #声明一个话题 message.declare('greet2', 'l...
ub('greet', hello) #stop执行后别的函数不再执行 message.sub('greet', stop, front=True) message.pub('greet', 'stop')
zeffii/sublimetext_productivity
Packages/User/open_gitbash_here.py
Python
mit
719
0.002782
import sublime, sublime_plugin import os import subprocess import threading class OpenGitbashHere(sublime_plugin.TextCommand): def run(self, edit): view = self.view file_path = view.file_name() dirname = os.path.dirname(file_path) th = BashTerminalThread(dirname) th.start(...
threading.Thread.__init__(self) def run(se
lf): if self.dirname: fpc = "--cd={0}".format(self.dirname) subprocess.call([r"C:\Program Files\Git\git-bash.exe", fpc])
XcomConvent/xcom40k-shades
xcom40k/app/urls.py
Python
apache-2.0
3,601
0.029714
from . import views from django.conf.urls import include, url from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # index page url(r'^$', views.site().index, name = 'index'), # login form url(r'^login/$', views.site().login, name = 'login'), url(r'^logout/$', ...
0-9]+)/reports/(?P<report_id>)/pdf/$', views.site().profile().reports()
.pdf, name = 'profile.reports.pdf'), ## chars url(r'^profile/chars/new/$', views.site().profile().chars().new, name = 'profile.chars.new'), url(r'^profile/chars/(?P<char_id>[0-9]+)/view/$', views.site().profile().chars().view, name = 'profile.chars.view'), url(r'^profile/chars/(?P<char_id>[0-9]+)/edit/$', ...
jon-jacky/PyModel
samples/WebApplication/ScenarioLogin.py
Python
bsd-3-clause
279
0.017921
"like scenario_login.txt in NMod
el WebApplication" from WebModel import Login, Logout actions = (Login, Logout) #
just these to allow interleaving testSuite = [ [ (Login, ( 'VinniPuhh', 'Correct' ), 'Success'), (Logout, ( 'VinniPuhh', ), None) ] ]
uberfastman/yahoo-fantasy-football-metrics
integrations/drive_integration.py
Python
gpl-3.0
8,962
0.002008
__author__ = "Wren J. R. (uberfastman)" __email__ = "wrenjr@yahoo.com" # code snippets taken from: http://stackoverflow.com/questions/24419188/automating-pydrive-verification-process import datetime import logging from pathlib import Path from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from...
e='application/vnd.google-apps.folder' and trashed=false"}).GetList() google_drive_folder_path_default = self.config.get("Drive", "google_drive_folder_path_default") google_drive_folder_path = Path(sel
f.config.get( "Drive", "google_drive_folder_path", fallback=google_drive_folder_path_default)).parts google_drive_root_folder_id = self.make_root_folder( drive, self.check_file_existence(google_drive_folder_path[0], root_folders, "root"), google_drive_folder_path...
ran777/edu_intell
edu_creative/views.py
Python
gpl-3.0
3,325
0.001535
from django.shortcuts import render from django.http import HttpResponse from django.db.models import Q, F from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from posts.models import Posts from uploadfiles.models import UploadFile from edu_warning.tools import user_setting # Create your views he...
ip(q, (i.uploadfile_set.all()[0].file for i in q))) context = {'q': __page_it(q, request.GET.get('page'))} return render(request, 'creative/design.html', context) def templates(request): q = Posts.objects.filter(post_category__name="模版创意").order_by('-click_num') q = list(zip(q, (i.uploadfile_set.all(...
return render(request, 'creative/template_creative.html', context) def method(request): q = Posts.objects.filter(post_category__name="方法形式").order_by('-click_num') # q = list(zip(q, (i.uploadfile_set.all()[0].file for i in q))) attachment = [i.uploadfile_set.all() for i in q] img = (i.filter(type='i')...
nrc/rustc-perf
collector/benchmarks/cranelift-codegen/cranelift-codegen/meta-python/isa/x86/defs.py
Python
mit
746
0
""" x86 definitions. Commonly used definitions. """ from __future__ import absolute_import from cdsl.isa import TargetISA, CPUMode import base.instructions from . import instructions as x86 from base.immediates import floatcc ISA = TargetISA('x86', [base.instructions.GROUP, x86.GROUP]) # type: TargetISA # CPU modes...
t are directly supported. # Other condition codes need to be reversed or expressed as two tests. supported_floatccs = [ floatcc.ord,
floatcc.uno, floatcc.one, floatcc.ueq, floatcc.gt, floatcc.ge, floatcc.ult, floatcc.ule]
DamienIrving/ocean-analysis
data_processing/obs/calc_durack_ocean_maps.py
Python
mit
5,232
0.005352
""" Filename: calc_durack_ocean_maps.py Author: Damien Irving, irving.damien@gmail.com Description: Calculate the zonal and vertical mean ocean anomaly fields from the Durack and Wijffels (2010) data files """ # Import general Python modules import sys, os, pdb import argparse, math import n...
climatology_cube = {} for variable in variables: change_cube[variable] = iris.load_cube(inargs.infile, 'change_over_time_in_sea_water_'+va
riable) change_cube[variable] = fix_cube(change_cube[variable], 'trend') climatology_cube[variable] = iris.load_cube(inargs.infile, 'sea_water_'+variable) climatology_cube[variable] = fix_cube(climatology_cube[variable], 'climatology') basin_array_default = calc_ocean_maps.create_basin_arr...
shlomimatichin/workflow
workflow/calendar/models.py
Python
gpl-3.0
554
0.057762
from django.db import models from django.contrib.auth.models import User class Attendance( models.Model ): date = models.DateField() teamMember = models.ForeignKey( User, blank = True, null = True, related_name = "cal
endarAttendances" ) workingDay = models.BooleanField() user = models.ForeignKey( User, related_name = "calendarAttendancesReported" ) when = models.DateTimeField( auto_now = True ) def __unicode__( self ): return "<Attendance %s %s %s>" % ( self.date, self.teamMember.username if self.teamMember else 'tea
m', self.workingDay )
inventree/InvenTree
InvenTree/stock/migrations/0063_auto_20210511_2343.py
Python
mit
676
0
# Generated by Django 3.2 on 2021-05-11 13:43 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('st
ock', '0062_auto_20210511_2151'), ] operations = [ migrations.RemoveField( model_name='stockitemtracking', name='link', ), migrations.RemoveField(
model_name='stockitemtracking', name='quantity', ), migrations.RemoveField( model_name='stockitemtracking', name='system', ), migrations.RemoveField( model_name='stockitemtracking', name='title', ), ]
rarcotvmw/capirca
tests/lib/iptables_test.py
Python
apache-2.0
39,394
0.002132
# Copyright 2008 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # unless required by applicable law or a...
reviations { protocol:: tcp action:: accept } """ GOOD_MULTIPORT = """ term multiport { source-port:: FOURTEEN_PORTS protocol:: tcp action:: accept } """ MULTIPORT_SWAP = """ term multiport { source-port:: HTTP HTTPS destination-port:: SSH protocol:: tcp action:: accept } """ EXPIRED_TERM = """ ter...
""" EXPIRING_TERM = """ term is_expiring { expiration:: %s action:: accept } """ GOOD_MULTIPORT_RANGE = """ term bad-mport-ranges { destination-port:: FIFTEEN_PORTS_WITH_RANGES protocol:: tcp action:: accept } """ LARGE_MULTIPORT = """ term bad-multiport { destination-port:: LOTS_OF_PORTS protocol:: t...
bendudson/BOUT-1.0
tools/tokamak_grids/cyclone/cyclone.py
Python
gpl-3.0
5,335
0.005061
#!/usr/bin/env python try: from numpy import * from scipy.integrate import quad except ImportError: print "ERROR: Need NumPy and SciPy modules" raise try: from boututils import DataFile except ImportError: print "ERROR: Missing boututils.Datafile. Add pylib to your PYTHONPATH" raise #####...
ld varies from "+str(Bt0*Rmaj/(Rmaj + rminor)) + \ " to "+str(Bt0*Rmaj/(Rmaj - rminor)) # Minor radius offset drprof = dr*((arange(nx) / float(nx-1)) - 0.5) #
q profile qprof = q + (s*q/rminor) * drprof print "q varies from "+str(min(qprof))+" to "+str(max(qprof)) ShiftAngle = qprof * 2.*pi Bpxy = zeros([nx,ny]) if varyBp: # Vary Bp to get shear for y in range(ny): Bpxy[:,y] = Bp * q / qprof print "Poloidal field varies from "+str(min(Bpxy))+" to "+str...
giginet/django-generic-tagging
generic_tagging/templatetags/tagging.py
Python
mit
1,210
0.000826
from django import template from django.contrib.contenttypes.models import ContentType from django.template.loader import render_to_string from ..models import TaggedItem, Tag register = template.Library() @register.assignment_tag def get_tagged_items_for(object): '''retrieve tagged items which relative with the...
nment_tag def get_content_type_for(object): '''retrieve content type object for the specific object. :syntax: {% get_content_typ
e_for <object> as <variable> %} ''' return ContentType.objects.get_for_model(object) @register.simple_tag def render_generic_tagging_head_tag(): return render_to_string('generic_tagging/head.html') @register.simple_tag def render_generic_tagging_component_tag_for(object): return render_to_string('ge...
mrjacobagilbert/gnuradio
grc/gui/FileDialogs.py
Python
gpl-3.0
6,524
0.002452
""" Copyright 2007 Free Software Foundation, Inc. This file is part of GNU Radio SPDX-License-Identifier: GPL-2.0-or-later """ from os import path from gi.repository import Gtk from . import Constants, Utils, Dialogs class FileDialogHelper(Gtk.FileChooserDialog, object): """ A wrapper class for the gtk ...
ve Console to a File...' filter_label = '
Test Files' filter_ext = '.txt' class SaveScreenShot(SaveFileDialog): title = 'Save a Flow Graph Screen Shot...' filters = [('PDF Files', '.pdf'), ('PNG Files', '.png'), ('SVG Files', '.svg')] filter_ext = '.pdf' # the default def __init__(self, parent, current_file_path=''): super(SaveS...
kashif/chainer
chainer/functions/connection/bilinear.py
Python
mit
6,625
0
import numpy from chainer import cuda from chainer import function from chainer.utils import array from chainer.utils import type_check class BilinearFunction(function.Function): def check_type_forward(self, in_types): n_in = type_check.eval(in_types.size()) if n_in != 3 and n_in != 6: ...
t(inputs[0]) e2 = array.as_mat(inputs[1]) W = inputs[2] gy
= grad_outputs[0] xp = cuda.get_array_module(*inputs) if xp is numpy: gW = numpy.einsum('ij,ik,il->jkl', e1, e2, gy) ge1 = numpy.einsum('ik,jkl,il->ij', e2, W, gy) ge2 = numpy.einsum('ij,jkl,il->ik', e1, W, gy) else: kern = cuda.reduce('T in0, T ...
kencochrane/django-defender
defender/models.py
Python
apache-2.0
1,116
0
from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class AccessAttempt(models.Model): """ Access Attempt log """ user_agent = models.CharField( max_length=255, ) ip_address = models.Ge...
) username = models.CharField( max_length=255,
null=True, ) http_accept = models.CharField( verbose_name='HTTP Accept', max_length=1025, ) path_info = models.CharField( verbose_name='Path', max_length=255, ) attempt_time = models.DateTimeField( auto_now_add=True, ) login_valid = models.Boolea...