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
tylereaves/26md
setlist/management/commands/__init__.py
Python
bsd-3-clause
22
0
__auth
or__ = 'Ty
ler'
coala/coala
tests/results/SourcePositionTest.py
Python
agpl-3.0
1,906
0.000525
import unittest from os.path import relpath from coalib.results.SourcePosition import SourcePosition from coala_utils.ContextManagers import prepare_file class SourcePositionTest(unittest.TestCase): def test_initialization(self): with self.assertRaises(TypeError): SourcePosition(None, 0) ...
"<SourcePosition object\\(file='.*filename', line=1, " 'column=None\\) at 0x[0-9a-fA-F]+>') self.assertEqual(str(uut), 'filename:1') uut = SourcePosition('None', None) self.assertRegex( repr(uut), "<SourcePosition object\\(file='.*None', line=None, column=...
Position('filename', 3, 2) self.assertEqual(str(uut), 'filename:3:2') def test_json(self): with prepare_file([''], None) as (_, filename): uut = SourcePosition(filename, 1) self.assertEqual(uut.__json__(use_relpath=True) ['file'], relpath(filenam...
pytorch/fairseq
examples/discriminative_reranking_nmt/tasks/discriminative_reranking_task.py
Python
mit
17,731
0.001184
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass, field import itertools import logging import os import numpy as np import torch from fairseq import metr...
dictionary self._max_positions = cfg.max_positions # args.tokens_per_sample = self._max_positions # self.num_classes = 1 # for model @classmethod def load_dictionary(cls, cfg, filename): """Load the dictionary from the filename""" dictionary = Dictionary.load(filename) ...
ary @classmethod def setup_task(cls, cfg: DiscriminativeRerankingNMTConfig, **kwargs): # load data dictionary (assume joint dictionary) data_path = cfg.data data_dict = cls.load_dictionary( cfg, os.path.join(data_path, "input_src/dict.txt") ) logger.info("[i...
mtils/ems
examples/qt4/widgets/test_imageeditor.py
Python
mit
341
0.005865
#coding=utf-8 from
ems.qt4.application import MainApplication from ems.qt4.gui.widgets.imageeditor import ImageEditor import sys if __name__ == '__main__': import sys app = MainApplication(sys.argv) fileName = sys.argv[1] if len(sys.argv) > 1 else None dlg = ImageEditor.toDialog(fileName) dlg.show() app
.exec_()
palaniyappanBala/rekall
rekall-core/rekall/config.py
Python
gpl-2.0
8,986
0.00089
#!/usr/bin/python # Rekall # Copyright (C) 2012 Michael Cohen <[email protected]> # Copyright 2013 Google Inc. All Rights Reserved. # # 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 ver...
x strings). - ArrayStringParser: A list of strings. -
Float: A float. - IntParser: An integer (possibly encoded as a hex string). - Boolean: A flag - true/false. - ChoiceArray: A comma separated list of strings which must be from the choices parameter. """ if "action" in options: raise RuntimeError("Action ke...
severin-lemaignan/dialogs
src/dialogs/timescale_manager_test.py
Python
bsd-3-clause
33,296
0.004835
# coding=utf-8 """ Created by Chouayakh Mahdi 26/08/2010 The package contains the unit test of timescale_manager function unit_tests : to perform un...
########### test 1.4 ##############################') print("Object of this test : With an indirect complement and adverb") print('') d_time = {'year': '2010', 'month': 'August', 'day': '27', 'hour': '10', 'minute': '0', 'second': '0'} sentence = Sentence('w_question', 'description', ...
imple', [], [IndirectComplement(['in'], [NominalGroup(['the'], ['winter'], [], [], [])])], [], ['here'], 'affirmative', [])]) print('The sente...
Eveler/libs
__Python__/ufms_blanks/appy3/fields/search.py
Python
gpl-3.0
8,383
0.002982
# ------------------------------------------------------------------------------ # This file is part of Appy, a framework for building applications in the Python # language. Copyright (C) 2007 Gaetan Delannay # Appy is free software; you can redistribute it and/or modify it under the # terms of the GNU General Public ...
ne: rangev = 'min' queryv = minv res = {'query':queryv,
'range':rangev} else: res = fieldValue return res def updateSearchCriteria(self, criteria, klass, advanced=False): '''This method updates dict p_criteria with all the search criteria corresponding to this Search instance. If p_advanced is True, p_criteria ...
ad-dycost/mindhouse
manage_pressure/watching.py
Python
gpl-3.0
576
0.013889
#!/usr/bin/env python # - * - mode: python; coding: utf-8 - * - # Copyright (C) 2013 Andrey Degtyarev <[email protected]> # This program is distributed licensed under the GNU General Public License v.3 # as published by the Free Softwa
re Foundation. import manage_pressure.constants, manage_pressure.work_device, time def control(motor_id, pressure_1_id, pressure_2_id): devices = manage_pressure.work_device.WorkDevice(motor_id, pressure_1_id, pressure_2_id) while 1: devi
ces.check() devices.action() time.sleep(manage_pressure.constants.TIME_REQUEST_DEVICE)
zygmuntz/evaluating-recommenders
plot_ndcgs.py
Python
bsd-3-clause
885
0.055367
"plot average NDCGs" import cPickle as pickle from collections import OrderedDict from matplotlib import pyplot as plt from os import listdir from os.
path import isfile, join # minimum number of users we
have scores for to average min_users = 10 input_dir = 'ndcgs/' # a list of input files input_files = [ join( input_dir, f ) for f in listdir( input_dir ) if isfile( join( input_dir, f )) and f.endswith( '.pkl' ) ] for i_f in input_files: print i_f # ndcgs = [ pickle.load( open( i_f, 'rb' ))['ndcgs'] for i_f in i...
vonwenm/pbft
sfslite-1.2/Attic/python/ex1/tst.py
Python
gpl-2.0
165
0.054545
import ex1 import async import socket sock = socket.socket () fd = sock.fileno () x = async.arpc.axprt_s
tream (fd) cl = async.arpc.
aclnt (x, ex1.foo_prog_1 ())
opendatakosovo/relate-with-it
importer/kosovo_importer.py
Python
mit
1,479
0.005409
from abstract_importer import AbstractImporter from slugify import slugify class KosovoImporter(AbstractImporter): def __init__(self): pass def get_csv_filename(self): return "importer/data/kosovo/kosovo-budget-expenditures-2014.csv" def get_region(self): return 'Kosovo' def...
slugify(self.get_dataset(), to_lower=True) }, 'activity': { 'type': row[0], 'description': row[1] }, 'cost': float(cost), 'year': int(year) } # Console output to provide user with feedback on status of importin...
cess. print '%s - %s: %s (%s %i)' % (doc['activity']['type'], doc['activity']['description'], doc['cost'], doc['region']['name'], doc['year']) return [doc]
googleads/google-ads-python
google/ads/googleads/v9/services/services/customer_feed_service/transports/grpc.py
Python
apache-2.0
12,306
0.000975
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
gleads.v9.services.types import customer_feed_service from .base import CustomerFeedServiceTransport, DEFAULT_CLIENT_INFO class CustomerFeedServiceGrpcTransport(CustomerFeedServiceTransport): """gRPC backend transport f
or CustomerFeedService. Service to manage customer feeds. This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation and call it. It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``...
ashawnbandy-te-tfb/FrameworkBenchmarks
frameworks/Python/web2py/app/standard/modules/database.py
Python
bsd-3-clause
2,330
0.003863
# -*- coding: utf-8 -*- import os from operator import itemgetter from gluon.storage import Storage from gluon.dal import DAL, Field, Row DBHOST = os.environ.get('DBHOST', 'localhost') DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST class Dal(object): def __init__(self, table...
d WHERE id = %s', placeholders=[wid], as_dict=True)[0] def update_world(self, wid, randomNumber): self.world_updates.extend([randomNumber, wid]) def flush_world_updates(self): query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s' ...
d_updates) / 2)) self.db.executesql(query, placeholders=self.world_updates) def get_fortunes(self, new_message): fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True) fortunes.append(new_message) return sorted(fortunes, key=itemgetter('message')) def num_queries(quer...
Shevraar/jovabot
modules/addressbook/paginebianche.py
Python
gpl-2.0
1,262
0.000792
import logging import sys import requests from bs4 import BeautifulSoup # White pages url WHITE_PAGES_URL = "http://www.paginebianch
e.it/execute.cgi" class wp_response(object)
: def __init__(self, name, tel, addr): self.name = name self.tel = tel self.addr = addr def search_wp(name, location): payload = {'btt': '1', 'qs': name, 'dv': location} try: r = requests.get(WHITE_PAGES_URL, params=payload) logging.info('requesting url {0}'.format...
xahhy/Django-vod
epg/models.py
Python
lgpl-3.0
1,604
0.000633
from django.db import models class Channel(models.Model): channel_id = models.CharField(max_length=50, unique=True) channel_name = models.CharField(max_length=50, null=True, blank=True) rtmp_url = models.CharField(max_length=100, null=True, blank=True) active = models.IntegerField(null=True, blank=Tru...
elf.channel_name + '(' + self.channel_id + ')' class Program(models.Model): channel = models.ForeignKey(Channel, to_field='channel_id', null=True) start_time = models.DateTimeField(auto_now_add=False, null=True, blank=True) end_time = models.DateTimeField(auto_now_add=False, null=True, blank=True) url...
h=50, null=True, blank=True) title = models.CharField(max_length=50, null=True, blank=True) finished = models.IntegerField(null=True, blank=True, default=0) event_id = models.IntegerField(null=True, blank=True) class Meta: managed = False db_table = 'program' verbose_name = '节目'...
JacobSheehy/pressureNETAnalysis
readings/serializers.py
Python
gpl-3.0
1,723
0
from rest_framework import serializers from customers import choices as customers_choices from customers.models import Customer from readings.models import Reading, Condition class ReadingListSerializer(serializers.ModelSerializer): class Meta: model = Reading fields = ( 'reading', ...
unt', 'precipitation_unit', 'thunderstorm_intensity', 'u
ser_comment', )
framasoft/searx
searx/engines/kickass.py
Python
agpl-3.0
3,732
0.000536
""" Kickass Torrent (Videos, Music, Files) @website https://kickass.so @provide-api no (nothing found) @using-api no @results HTML (using search portal) @stable yes (HTML can change) @parse url, title, content, seed, leech, magnetlink """ from urlparse import urljoin from cgi import escap...
t) search_res = dom.xpath('//table[@class="data"]//tr') # return empty array if noth
ing is found if not search_res: return [] # parse results for result in search_res[1:]: link = result.xpath('.//a[@class="cellMainLink"]')[0] href = urljoin(url, link.attrib['href']) title = extract_text(link) content = escape(extract_text(result.xpath(content_xpath)...
ArchiFleKs/magnum
magnum/api/app.py
Python
apache-2.0
2,079
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 # di...
__name__) def get_
pecan_config(): # Set up the pecan configuration filename = api_config.__file__.replace('.pyc', '.py') return pecan.configuration.conf_from_file(filename) def setup_app(config=None): if not config: config = get_pecan_config() app_conf = dict(config.app) common_config.set_config_defaul...
MostlyOpen/odoo_addons_jcafb
myo_address_cst/models/address.py
Python
agpl-3.0
1,235
0
# -*- coding: utf-8 -*- ############################################################################### # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # 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 #...
RANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You s
hould have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### from openerp import models class AddressCategory(models.Model): _inherit = 'myo.address.cat...
jamrootz/challenge100
hundredBeers.py
Python
gpl-3.0
7,054
0.033598
#!/usr/bin/python3 ''' Program to parse the beer standings table. Should categorize beers into a dictionary or other data structure. Add some new categories: Distribution Regions, Season, Rarity ''' from html.parser import HTMLParser import json import math beerList = [] #Will contain all the the beer objects extra...
ut("\n"*5 + "Enter the number of the beer (q=quit, a=add, u=uncheck, c=clear highlights, b=brewery sort, s=state sort): ") return opt.lower() def edit_beer(beer): clear_screen() print("Selected %(Brewery)s (%(Beer)s) " % beer.details) print("\n\n\n\tOptions:\n") print("\t\t1. Check in") print("\t\t2. Add D
istribution Details") print("\t\t3. Add Dates of availability") print("\t\t4. Add Establishments carrying the beer") print("\t\t5. Describe abundance of the beer") print("\t\t6. Toggle Highlight (%(highlight)s)" % beer.details) print("\t\t7. Done") choice = input("\n\n\nWhat would you like to do? ") if choice ==...
agentmilindu/stratos
components/org.apache.stratos.python.cartridge.agent/src/main/python/cartridge.agent/cartridge.agent/extensions/py/ExtensionExecutor.py
Python
apache-2.0
2,389
0.003349
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
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 fo
r the # specific language governing permissions and limitations # under the License. from plugins.contracts import ICartridgeAgentPlugin import os import subprocess from modules.util.log import LogFactory class ExtensionExecutor(ICartridgeAgentPlugin): def run_plugin(self, values): log = LogFactory().ge...
adrianmoisey/lint-review
tests/tools/test_shellcheck.py
Python
mit
2,600
0
from lintreview.review import Problems from lintreview.review import Comment from lintreview.tools.shellcheck import Shellcheck from lintreview.utils import in_path from unittest import TestCase from unittest import skipIf from nose.tools import eq_ shellcheck_missing = not(in_path('shellCheck')) class Testshellchec...
nt ' 'globbing and word splitting.') eq_(expected, problems[0]) expected = Comment( fname, 5, 5, 'The order of the 2>&1 and the redirect matte
rs. The 2>&1 has to ' 'be last.') eq_(expected, problems[1]) @needs_shellcheck def test_process_files_two_files(self): self.tool.process_files(self.fixtures) eq_([], self.problems.all(self.fixtures[0])) problems = self.problems.all(self.fixtures[1]) eq_(2, ...
VTabolin/networking-vsphere
networking_vsphere/agent/firewalls/dvs_securitygroup_rpc.py
Python
apache-2.0
2,782
0
# Copyright 2015 Mirantis, 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 a...
device filter for %r"), device_ids) self.firewall.remove_port_filter(device_ids) def _refresh_ports(self): device_ids = self._devices_to_update self._devices_to_update = self._devices_to_update - device_ids if not device_id
s: return if self.use_enhanced_rpc: devices_info = self.plugin_rpc.security_group_info_for_devices( self.context, device_ids) devices = update_rules(devices_info) else: devices = self.plugin_rpc.security_group_rules_for_devices( ...
JazzeYoung/VeryDeepAutoEncoder
theano/gpuarray/nerv.py
Python
bsd-3-clause
6,598
0.000152
from __future__ import absolute_import, print_function, division import os.path import theano from theano import Apply, Variable, tensor from theano.compile import optdb from theano.compile.ops import shape_i from theano.gof import local_optimizer, COp from theano.scalar import as_scalar, constant from . import opt f...
codel.append("memset(&k_{0}, 0, sizeof(GpuKernel));".format(name)) codel.append("const char *bcode;") codel.append("size_t sz;") codel.append("PyGpuContextObject *c = %s;" % (sub['params'],)) codel.append("int types[13] =
{GA_BUFFER, GA_BUFFER, GA_BUFFER, " "GA_BUFFER, GA_INT, GA_INT, GA_INT, GA_INT, GA_INT, " "GA_INT, GA_FLOAT, GA_FLOAT, GA_INT};") for name in self.KERN_NAMES: codel.append(self.init_gpukernel(name, sub['fail'])) return '\n'.join(codel) def c_cle...
jcrudy/clinvoc
clinvoc/examples/parser_example.py
Python
mit
312
0.003205
from clinvoc.icd9 import ICD9CM # This string describes a
set of ICD 9 codes codestring = '745.0-745.3, 745.6*, 746, 747.1-747.49, 747.81, 747.89, 35.8, 35.81, 35.82, 35.83, 35.84' # Use clinvoc to parse and standardize the above codes vocab = ICD9CM() codeset = vocab.parse(
codestring) print(sorted(codeset))
afaheem88/tempest_neutron
tempest/tests/fake_credentials.py
Python
apache-2.0
1,922
0
# Copyright 2014 Hewlett-Packard Development Company, L.P. # 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...
als(auth.KeystoneV3Credentials): """ Fake credentials suitable for the Keystone Identity V3 API, with no scope """ def __init__(self): creds = dict(
username='fake_username', password='fake_password', user_domain_name='fake_domain_name' ) super(FakeKeystoneV3DomainCredentials, self).__init__(**creds)
akshaybabloo/Car-ND
Term_1/CNN_5/CNN_example_5.py
Python
mit
7,593
0.003688
""" Applying Convolutional Neural Network in TensorFlow The structure of this network follows the classic structure of CNNs, which is a mix of convolutional layers and max pooling, followed by fully-connected layers. The code you'll be looking at is similar to what you saw in the segment on Deep Neural Network in Ten...
x pooling followed by a fully connected and output layer. The transformation of each layer to new dimensions are shown in the comments. For example, the first layer shapes the images from 28x28x1 to 28x
28x32 in the convolution step. Then next step applies max pooling, turning each sample into 14x14x32. All the layers are applied from conv1 to output, producing 10 class predictions. Parameters ---------- x weights biases dropout Returns ------- """ # Layer 1 - 28*28*1...
Hybrid-Cloud/badam
patches_tool/aws_patch/code/neutron/plugins/openvswitch/agent/ovs_neutron_agent.py
Python
apache-2.0
107,162
0.001194
#!/usr/bin/env python # Copyright 2011 VMware, 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 # # ...
nvswitch.common import constants from neutron.plugins.openvswitch.agent import neutron_bus_client from neutron.services.qos.agents import qos_rpc LOG = logging.getLogger(__name__) # A placeholder for dead vlans. DEAD_VLAN_TAG = str(q_const.MAX_VLAN_TAG + 1) Agent_Start_Report_Retry_Interval = 2 class DeviceListRetr...
lError(exceptions.NeutronException): message = _("Unable to retrieve port details for devices: %(devices)s " "because of error: %(error)s") class AgentError(exceptions.NeutronException): msg_fmt = _('Error during following call to agent: %(method)s') # A class to represent a VIF (i.e., a por...
jumpstarter-io/keystone
keystone/contrib/oauth1/controllers.py
Python
apache-2.0
17,478
0
# Copyright 2013 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 law or agreed to in...
_CONSUMER_TOKENS, resource_id
_arg_index=0) def _emit_user_oauth_consumer_token_invalidate(payload): # This is a special case notification that expect the payload to be a dict # containing the user_id and the consumer_id. This is so that the token # provider can invalidate any tokens in the token persistence if # token persistence i...
ArcherSys/ArcherSys
skulpt/test/run/t152.py
Python
mit
124
0.080645
print str(ran
ge(5,0,-3))[:5] print len(range(5,0,-3)) print range(5,0,-3)[0] print range(5,0,-3)[1] print range(
5,0,-3)[-1]
jbonofre/beam
sdks/python/apache_beam/runners/direct/clock.py
Python
apache-2.0
1,544
0.004534
# # 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 ow
nership. # The ASF licenses this 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 writin...
pecific language governing permissions and # limitations under the License. # """Clock implementations for real time processing and testing. For internal use only. No backwards compatibility guarantees. """ from __future__ import absolute_import import time class Clock(object): def time(self): """Returns the...
mvaled/sentry
src/sentry/south_migrations/0458_global_searches_data_migration.py
Python
bsd-3-clause
120,420
0.007889
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import DataMigration from django.db import models from sentry.utils.query import RangeQuerySetWrapperWithProgressBar DEFAULT_SAVED_SEARCHES = [ { 'name': 'Unresolved Issues', 'query': ...
up']", 'null': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'ident': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to...
dels.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'null': 'True'}) }, 'sentry.apiapplication': { 'Meta': {'object_name': 'ApiApplication'}, 'allowed_origins': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'cli...
nwillemse/nctrader
nctrader/trading_session/trade_sim.py
Python
mit
2,643
0.000757
from __future__ import print_function from ..compat import queue from ..event import EventType from datetime import datetime class TradeSim(object): """ Enscapsulates the settings and components for carrying out an event-driven trade simulator. """ def __init__( self, price_handler, stra...
handler = execution_handler self.position_sizer = position_sizer self.risk_manager = risk_manager self.statistics = statistics self.equity = equity self.end_date = end_date self.events_queue = price_handler.events_queue self.cur_time = None def _run_backtest(...
""" Carries out an infinite while loop that polls the events queue and directs each event to either the strategy component of the execution handler. The loop continue until the event queue has been emptied. """ print("Running Backtest...") while self.pric...
ohickman/etch-a-sketch
point.py
Python
gpl-3.0
4,079
0.001961
""" Extensible image processing and Etch-a-sketch drawing program Copyright (C) 2014 Oliver Hickman This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option...
y numeric data type. >>> a = Point(0,8) >>> a.y = 8""" return self._y @y.setter def y(self, y): try: y = int(y) except ValueError: print ("Could not convert \"%s\" into an integer." %y) y = 0 self._y = y def __rmul__(self,...
>>> a = Point(1,2) >>> 2*a (2, 4)""" return Point(other*self.x, other*self.y) def __add__(self, other): """ Piecewise adds two Points together. >>> a = Point(1,2) >>> b = Point(1,2) >>> a + b (2, 4) """ return Point(self.x + other....
zouyapeng/horizon-newtouch
openstack_dashboard/dashboards/admin/info/tabs.py
Python
apache-2.0
3,879
0
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
ort exceptions from horizo
n import tabs from openstack_dashboard.api import base from openstack_dashboard.api import cinder from openstack_dashboard.api import keystone from openstack_dashboard.api import neutron from openstack_dashboard.api import nova from openstack_dashboard.dashboards.admin.info import constants from openstack_dashboard.das...
bigswitch/horizon
openstack_dashboard/test/error_pages_urls.py
Python
apache-2.0
184
0
from django.conf.url
s import url from django.
views import defaults from openstack_dashboard.urls import urlpatterns # noqa urlpatterns.append(url(r'^500/$', defaults.server_error))
GMadorell/larv
larv/Entity.py
Python
mit
493
0
# encoding:
UTF-8 class Entity: """ An entity is just an ID, which will be assigned some components. Components hold the data and systems are the responsables of the logic behind it. """ def __init__(self, id): """ Con
structor. We should pass a unique id everytime we create a new entity. """ self.__id = id @property def id(self): """Read only property for the id private variable.""" return self.__id
mdelorme/MNn
mnn/examples/simple_model.py
Python
mit
1,497
0.002004
import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from mnn.model import MNnModel # Single disc model = MNnModel() model.add_disc('z', 1.0, 10.0, 100.0) # Evaluating density and potential : print(model.evaluate_density(1.0, 2.0, -0.5)) print(model.evaluate_potential(1.0, 2.0, -...
ty = model.evaluate_density(x, 0.0, 0.0) fig = plt.plot(x, density) plt.show() # Plotting density meshgrid x, y,
z, v = model.generate_dataset_meshgrid((0.0, 0.0, -10.0), (30.0, 0.0, 10.0), (300, 1, 200)) fig = plt.imshow(v[:, 0].T) plt.show() # Contour plot x = np.linspace(0.0, 30.0, 300) z = np.linspace(-10.0, 10.0, 200) plt.contour(x, z, v[:, 0].T) plt.show() # Plotting force meshgrid plt.close('all') x, y, z, f = model.gene...
DavidMikeSimon/satyrnos
resman.py
Python
gpl-3.0
1,503
0.031271
import pygame import os from OpenGL.GL import * from OpenGL.GLU import * import app from geometry import * class Texture(object): """An OpenGL 2D texture. Data attributes: filename -- The filename that the texture w
as loaded from, or an empty string glname -- The OpenGL texture name. size -- The dimensions of the texture as a Size. surf -- The PyGame surface. """ cache = {} #Key: filename, value: Texture instance def __new__(cls, filename): """Creates a Texture from an image file, using pre-cached version if it exists....
ilename] = obj obj.glname = glGenTextures(1) fullpath = os.path.join('imgs', filename) surf = pygame.image.load(fullpath) obj.surf = surf obj.size = Size(surf.get_width(), surf.get_height()) texData = pygame.image.tostring(surf, "RGBA", 1) glBindTexture(GL_TEXTURE_2D, obj.glname) glTexImage2D(GL...
ThomasYeoLab/CBIG
setup/tests/hooks_tests/pre_commit_tests/G_check_flake8_format/notfollow_flake8.py
Python
mit
380
0.068421
# Written by Nanbo Sun and CBIG under MIT license: https://
github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md x = { 'a':37,'b':42, 'c':927} y = 'hello ''world' z = 'hello '+'world' a = 'hello {}'.format('world') class foo ( object ): def f
(self ): return 37*-+2 def g(self, x,y=42): return y def f ( a ) : return 37+-+a[42-x : y**3]
weechat/weechat.org
weechat/common/path.py
Python
gpl-3.0
1,672
0
# # Copyright (C) 2003-2022 Sébastien Helleu <flashc
[email protected]> # # This fil
e is part of WeeChat.org. # # WeeChat.org 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. # # WeeChat.org is distributed in the hope th...
PiotrGrzybowski/NeuralNetworks
networks/neurons/activations.py
Python
apache-2.0
291
0.003436
UNIPOLAR = 'unipolar' BIPOLAR
= 'bipolar' def unipolar(x): return 1 if x >= 0 else 0 def bipolar(x): return 1 if x >= 0 else -1 def get_activation(activation): return ACTIVATION_FUNCTIONS[activation] ACTIVATION_FUNCTIONS = { UNIPOLAR: unipolar
, BIPOLAR: bipolar }
die-uhus/blueman
blueman/bluez/obex/AgentManager.py
Python
gpl-3.0
976
0.003074
from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals from blueman.Functions import dprint from blueman.bluez.obex.Base import Base class AgentManager(Base): def __init__(self): super(AgentManager, self).__init...
dprint(agent_path, error) self._interface.RegisterAgent(agent_path, reply_handler=on_registered, error_handler=on_register_failed) def unregister_agent(self, agent_pat
h): def on_unregistered(): dprint(agent_path) def on_unregister_failed(error): dprint(agent_path, error) self._interface.UnregisterAgent(agent_path, reply_handler=on_unregistered, error_handler=on_unregister_failed)
SmartInfrastructures/fuel-web-dev
nailgun/nailgun/api/v1/handlers/plugin.py
Python
apache-2.0
2,321
0
# -*- coding: utf-8 -*- # Copyright 2014 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
f): """:returns: JSONized REST object. :http: * 200 (plugins successfully synced)
* 404 (plugin not found in db) * 400 (problem with parsing metadata file) """ data = self.checked_data() ids = data.get('ids', None) try: PluginManager.sync_plugins_metadata(plugin_ids=ids) except errors.ParseError as exc: raise ...
markgw/jazzparser
lib/nltk/corpus/__init__.py
Python
gpl-3.0
10,492
0.001906
# Natural Language Toolkit: Corpus Readers # # Copyright (C) 2001-2010 NLTK Project # Author: Edward Loper <[email protected]> # URL: <http://www.nltk.org/> # For license information, see LICENSE.TXT # [xx] this docstring isnt' up-to-date! """ NLTK corpus readers. The modules in this package provide func...
='utf-8') knbc = LazyCorpusLoader( 'knbc/corpus1', KNBCorpusReader, r'.*/KN.*', encoding='euc-jp') mac_morpho = LazyCorpusLoader( 'mac_morpho', MacMorphoCorpusReader, r'(?!\.).*\.txt', tag_mapping_function=simplify_tag, encoding='latin-1') machado = LazyCorpusLoader( 'machado', PortugueseCategorizedPlai...
z]*)/.*', encoding='latin-1') movie_reviews = LazyCorpusLoader( 'movie_reviews', CategorizedPlaintextCorpusReader, r'(?!\.).*\.txt', cat_pattern=r'(neg|pos)/.*') names = LazyCorpusLoader( 'names', WordListCorpusReader, r'(?!\.).*\.txt') nps_chat = LazyCorpusLoader( 'nps_chat', NPSChatCorpusReader, r'(?!...
matthewzhenggong/fiwt
XbeeZBS2Test/recparse.py
Python
lgpl-3.0
4,619
0.023815
import argparse import numpy as np import scipy.io as syio import struct import time def Get14bit(val) : if val & 0x2000 : return -(((val & 0x1FFF)^0x1FFF)+1) else : return val & 0x1FFF class fileParser(object): def __init__(self): self.packHdr = struct.Struct(">BH") self....
return {'data22':self.data22,'data33':self.data33, 'head22':self.head22,'head33':self.head33, 'headA6':self.headA6,'dataA6':self.dataA6, 'head44':self.head44,'data44':self.data44, } if __name__=='_
_main__' : parser = argparse.ArgumentParser( prog='recparse', description='parse rec data file') parser.add_argument('filenames', metavar='file', nargs='+', help='data filename') args = parser.parse_args() p = fileParser() for filename in args.filenames : mat_data...
ratnania/pyccel
tests/codegen/scripts/recursive_functions.py
Python
mit
155
0.058065
#$ heade
r fact(int) results(int) def fact(n): if n == 0: z = 1 return z else: z = n*fact(n-1) return z print(fact(5))
DarkenNav/UnionFreeArts
WebApp/WebSiteUnionFreeArts/WebSiteUnionFreeArts/wsgi.py
Python
mit
440
0
""
" WSGI config for WebSiteUnionFreeArts project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("...
cation = get_wsgi_application()
dario61081/koalixcrm
koalixcrm/crm/factories/factory_resource_price.py
Python
bsd-3-clause
1,499
0.000667
# -*- coding: utf-8 -*- import factory import datetime from koalixcrm.crm.models import ResourcePrice from koalixcrm.crm.factories.factory_resource import StandardResourceFactory from koalixcrm.crm.factories.factory_unit import StandardUnitFactory from koalixcrm.crm.factories.factory_currency import StandardCurrencyFa...
5, 00)) class HighResourcePriceFactory(factory.
django.DjangoModelFactory): class Meta: model = ResourcePrice resource = factory.SubFactory(StandardResourceFactory) unit = factory.SubFactory(StandardUnitFactory) currency = factory.SubFactory(StandardCurrencyFactory) customer_group = factory.SubFactory(StandardCustomerGroupFactory) pr...
Manuel7AP/dobc_web_app
app/views/add_guest.py
Python
apache-2.0
676
0
from flask import flash, redirect, render_template, url_for, request from sqlalchemy.exc import IntegrityError from app import app, db from app.forms import AddGuestForm from app.models import Guest from app.util import flash_form_errors @app.route('/guests/create', methods=['
GET', 'POST']) def add_guest(): add_guest_form = AddGuestForm() if request.method == 'GET': return render_template('add_guest.html', add_guest_form=add_guest_form) if request.method == 'POST': guest = Guest(add_guest_form.name.data, add_guest_form.message.data) db.session.add(guest) ...
w_guests'))
haphaeu/yoshimi
EulerProject/233_clever.py
Python
lgpl-3.0
2,521
0.02142
""" Project Euler - Problem 233 Circle passing through (0,0),(N,0),(0,N),(N,N) this is a square - so the diameter of the circle is N*Sqrt(2), and its centre is (N/2,N/2) Circle equation is (X-Xc)^2+(Y-Yc)^2=N^2/2 or (x-N/2)^2 + (y-N/2)^2 = N^2/2 for a given N, the x domain Dx is lower bound N/2 - N*sqrt(2)/...
%d (%.3e)" % (N, N) lowerBound = N/2*(1-sqrt(2)) upperBound = N/2*(1+sqrt(2)) domainRange = upperBound - lowerBound domainRangePercentage=domainRange/100. #prepare some variables to avoid re-calculate N_over_2=N/2.0 N_sqrd_over_2=0.5*N**2 rootFinderDelta=sqrt(N) rootFinderTol=1.0e-4 #iterate trhough domain x ct=0 x=in...
calculate y1 as float y1 = N_over_2 + sqrt( N_sqrd_over_2 - (x-N_over_2)**2 ) if abs(y1-int(y1))<eps: #due to symmetry, always 2 points count # +2 positive and negavtive y # +2 either sides (left and right) of the circle ct+=4 #progress (either one of the below) ...
dwt/simplesuper
setup.py
Python
isc
1,671
0.003593
#!/usr/bin/env python # encoding: utf-8 # from __future__ import unicode_literals from os import path from setuptools import setup, find_packages here = path.abspath(path.dirname(__file__)) def readme(): "Falls back to just file().read() on any error, because the conversion to rst is only really relevant when up...
all the repetition', long_description=readme(), version='1.0.9', classifiers=[ "Programming Language :: Python :: 2", "Topic :: Software Development", "Topic :: Utilities", "Intended Audience :: Developers", "Development Status :: 5 - Production/Stable", "Lic...
[email protected], [email protected]', license="ISC", url='https://github.com/dwt/simplesuper', keywords='python 2, super, convenience, api', py_modules=['simplesuper'], test_suite = "simplesuper", )
REBradley/WineArb
winearb/reviews/urls.py
Python
bsd-3-clause
1,074
0.001862
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.conf.urls import url from . import views urlpatterns = [ url( regex=r'^$', view=views.new_wine, #add review form name='home' ), url(
regex=r'^new_review/$', view=views.new_review, #actually add the review name='new_review' ), url( regex=r'^review/user/(?P<username>\w+)/$', view=views.user_review_list, name='user_review_list' ), url( regex=r'^review/edit/(?P<review_id>[0-9]+)/$', ...
review_form, name='edit_review_form' ), url( regex=r'^review/edit_review/(?P<review_id>[0-9]+)/$', view=views.edit_review, name='edit_review' ), url( regex=r'^review/delete_review/(?P<review_id>[0-9]+)/$', view=views.delete_review, name='delete_rev...
Delosari/dazer
bin/user_conf/ManageFlow.py
Python
mit
2,633
0.01861
def DataToTreat(Catalogue = 'WHT_observations'): Catalogue_Dictionary = {} if Catalogue == 'WHT_observations': Catalogue_Dictionary['Folder'] = '/home/vital/Dropbox/Astrophysics/Data/WHT_observations/' Catalogue_Dictionary['Datatype'] = 'WHT' Catalogue_Dictionary['Obj_F...
"/home/vital/Dropbox/Astrophysics/Data/WHT_MartaCandidates_2016/Objects/" if Catalogu
e == 'SDSS_Catalogue': Catalogue_Dictionary['Folder'] = "Dropbox/Astrophysics/Data/Fabian_Catalogue/" Catalogue_Dictionary['Datatype'] = "dr10" Catalogue_Dictionary['Obj_Folder'] = "Dropbox/Astrophysics/Data/Fabian_Catalogue/" if Catalogue == 'Testing_Pypeline': Catalogue_...
astrofrog/ginga
setup.py
Python
bsd-3-clause
1,354
0.024372
#! /usr/bin/env python # from distutils.core import setup from g
inga.version import version import os def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "ginga", version = version, author = "Eric Jeschke", author_email = "[email protected]", description = ("An astronomical (FITS) image viewer and toolkit."), l...
keywords = "FITS image viewer astronomy", url = "http://ejeschke.github.com/ginga", packages = ['ginga', 'ginga.gtkw', 'ginga.gtkw.plugins', 'ginga.gtkw.tests', 'ginga.qtw', 'ginga.qtw.plugins', 'ginga.qtw.tests', 'ginga.misc', 'ginga.misc.plugins', 'ginga.ico...
thaskell1/volatility
volatility/plugins/linux/lsmod.py
Python
gpl-2.0
25,003
0.014358
# Volatility # Copyright (C) 2007-2013 Volatility Foundation # # This file is part of Volatility. # # Volatility is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License Version 2 as # published by the Free Software Foundation. You may not use, modify or # distribu...
UMP-DIR', short_option = 'D', default = None, help = 'Directory in which to dump the files', action = 'store', type = 'string') config.add_option('REGEX', short_option = 'r', help = 'Dump modules matching REGEX', acti...
true', default = False) config.add_option('BASE', short_option = 'b', default = None, help = 'Dump driver with BASE address (in hex)', action = 'store', type = 'int') def calculate(self): linux_common.set_plugin_members(self) if self._con...
K-3D/k3d
share/k3d/scripts/RenderManScript/tribble.py
Python
gpl-2.0
1,686
0.020166
#python # Load this script into a RenderManScript node to create # what is either a Tribble or a really bad-hair-day ... import k3d k3d.check_node_environment(context, "RenderManScript") impor
t sys import ri from ri import * from random import * from cgtypes import vec3 from noise import vsnoise from sl import mix message = """You're probably trying to run this script manually, which won't work - this script is meant to be loaded into a RenderManScript node, where it will be run at render-time. Use the Cr...
y("archive"): k3d.ui.error_message(message) raise # Redirect output to our RIB archive ri._ribout = open(str(context.archive), "w") body_size = 5 lumpyness = 1 hair_length = 2 hair_count = 10000 hair_wavyness = 1 control_point_counts = [] control_points = [] widths = [] seed(12345) for i in range(hair_...
skbly7/serc
website/lab/migrations/0016_auto_20160311_1224.py
Python
mit
582
0.001718
# -*- coding: utf-8 -*- # Gen
erated by Django 1.9.4 on 2016-03-11 12:24 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('lab', '0015_auto_20160311_1221'), ] operations = [ migrations.AlterField...
ation', name='author', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='publication_author', to='lab.ShortNames'), ), ]
mF2C/COMPSs
tests/sources/python/0_multireturn/src/multireturn.py
Python
apache-2.0
919
0.006529
#!/usr/bin/python # -*- coding: utf-8 -*- """ PyCOMPSs Testbench Tasks ======================== """ # Imports import unittest from modules.testMultiRe
turnFunctions import testMulti
ReturnFunctions from modules.testMultiReturnInstanceMethods import testMultiReturnInstanceMethods from modules.testMultiReturnIntFunctions import testMultiReturnIntFunctions from modules.testMultiReturnIntInstanceMethods import testMultiReturnIntInstanceMethods def main(): suite = unittest.TestLoader().loadTestsF...
edenzik/elastiCity
api/yelp/freebase_key_needed_final.py
Python
gpl-3.0
2,478
0.006457
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ from json import loads from pprint import pprint from sys import argv import urllib class FREEBASE_KEY(): ''' please input the api_key here ''' api_key = 'AIzaSyBWsQpGo34Lk0Qa3wD0kjW5H1Nfb2m5eaM' def get_city_id(city_name...
main__': ''' just call the function get_freebase_info(city_name) and input the city_name, here is the sample '''
print main()
miltmobley/PatchTools
patchtools/lib/matcher.py
Python
apache-2.0
4,212
0.009022
# -*- coding: utf-8 -*- ''' Created on Apr 13, 2014 @copyright 2014, Milton C Mobley Select strings based on caller components: prefixes, suffixes and substrings. Regular expression matching is also supported. Note that some pa
tch and kernel files have utf-8 chars with code > 127. Some of these codes are no
t legal utf-8 start byte codes. See functions.py for the file read, write handling. ''' import re from inspect import isfunction from patchtools.lib.ptobject import PTObject from patchtools.lib.exceptions import PatchToolsError, PT_ParameterError #++ class Matcher(PTObject): """ Implement filter selection of ...
ayseyo/oclapi
django-nonrel/ocl/manage.py
Python
mpl-2.0
318
0
#!/
usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oclapi.settings.l
ocal') os.environ.setdefault('DJANGO_CONFIGURATION', 'Local') from configurations.management import execute_from_command_line execute_from_command_line(sys.argv)
moul/splitfs
fusepy/fuse.py
Python
mit
23,924
0.00163
# Copyright (c) 2008 Giorgos Verigakis <[email protected]> # # 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 THE A...
1), ('keep_cache', c_uint, 1), ('flush', c_uint, 1), ('padding', c_uint, 29), ('fh', c_uint64), ('lock_owner', c_uint64
)] class fuse_context(Structure): _fields_ = [ ('fuse', c_voidp), ('uid', c_uid_t), ('gid', c_gid_t), ('pid', c_pid_t), ('private_data', c_voidp)] _libfuse.fuse_get_context.restype = POINTER(fuse_context) class fuse_operations(Structure): _fields_ = [ ('getattr...
rcdailey/videosort
lib/guessit/transfo/guess_episodes_rexps.py
Python
gpl-3.0
13,659
0.004759
#!/usr/bin/env python # -*- coding: utf-8 -*- # # GuessIt - A library for guessing information from filenames # Copyright (c) 2013 Nicolas Wack <[email protected]> # # GuessIt is free software; you can redistribute it and/or modify it under # the terms of the Lesser GNU General Public License as published by # the Free ...
strip() for x in range_values] if len(range_values) > 1: for x in range(0, len(range_values) - 1): start_range_ep = parse_numeral(range_values[x]) end_range_ep = parse_numeral(range_values[x+1]) for range_ep in r...
else: discrete_value = parse_numeral(discrete_element) if discrete_value not in ret: ret.append(discrete_value) if len(ret) > 1: if not allow_discrete: valid_ret = [] # replace discrete e...
smmribeiro/intellij-community
python/testData/quickFixes/PyMakeFunctionReturnTypeQuickFixTest/lambda.py
Python
apache-2.0
127
0.070866
def func() -> int: return <warning descr="Expected type 'int', got '(x: Any) -> int' instead">l
amb
da x: 42<caret></warning>
open-power-ref-design-toolkit/os-services
osa/dbaas_ui/dbaas_ui/shortcuts/workflows/workflows.py
Python
apache-2.0
16,518
0.000061
# Copyright 2017, IBM US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
LOG.error("Invalid datastore (%s) and version (%s)" ". Version is not active.", ds.name, v.
name) continue if hasattr(v, 'image') and v.image not in image_ids: LOG.error("Invalid datastore (%s) and version (%s)" ". Version does not have an image " "associated with it", ds.nam...
Yangqing/caffe2
scripts/get_python_cmake_flags.py
Python
apache-2.0
1,130
0.000885
## @package get_python_cmake_flags # Module scripts.get_python_cmake_flags ############################################################################## # Use this script to find your preferred python installation. ############################################################################## # # You can use the follo...
ython ../scripts/get_python_libs.py) .. # make # from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function from distutils import sysconfig import os import sys import platform # Flags to print to stdout flags = '' inc = sysconfig.get_python_inc(
) lib = sysconfig.get_config_var("LIBDIR") # macOS specific if sys.platform == "darwin": lib = os.path.dirname(lib) + '/Python' if os.path.isfile(lib): flags += '-DPYTHON_LIBRARY={lib} '.format(lib=lib) if os.path.isfile(inc + '/Python.h'): flags += '-DPYTHON_INCLUDE_DIR={inc} '.format(inc=inc) p...
Sikilabs/sikilabs
sikilabs/wsgi.py
Python
mit
493
0
"
"" WSGI config for sikilabs project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application from mezzanine.utils.conf import re...
application()
charany1/googlecl
src/googlecl/picasa/service.py
Python
mit
14,137
0.006437
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
EO_TYPES[
video_format]: wanted_content = content if not wanted_content: LOG.error('Did not find desired medium!') LOG.debug('photo_or_video.media:\n' + photo_or_video.media) return None elif wanted_content.medium == 'image': url = googlecl.picasa.make_download_url(photo_or_v...
andrewtron3000/jampy
generator_matrix.py
Python
bsd-3-clause
4,610
0.015835
import random import time import sys import Csound import subprocess import base64 import hashlib import matrixmusic csd = None oscillator = None buzzer = None voice = None truevoice = None song_publisher = None def add_motif(instrument, req): global csd time = req.motif_start_time for note in req.score:...
i*0.8) for i in range(3)] # if biasedFlip(0.8): # motifs.append(Motif(3.0, 10, 0.32, "A3 B3 D4 E4 F#4 A4 B4 D5 E5 F#5 A5 B5 D6 E6 F#6", a, b, selectInstrument())) # if biasedFlip(0.9): # motifs.append(Motif(6.0, 4, 0.10, "A2 B2 D3 D3 F#3 A3 B3 D4 E4 F#4 A4 B4 D5 E5 F#5", ...
)
shootstar/novatest
nova/api/openstack/wsgi.py
Python
apache-2.0
44,600
0.000112
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain #
a copy of the License at # # http://www.apache.org/licenses/LICENSE
-2.0 # # 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 # u...
dragorosson/heat
heat/tests/engine/service/test_stack_create.py
Python
apache-2.0
15,923
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 # ...
, return_value=stk) # test stack create using context without password ctx_no_pwd = utils.dummy_context(password=None) ex = self.assertRaises(dispatcher.ExpectedException, self.man.create_stack, ctx_no_pwd, stack_name, ...
, six.text_type(ex.exc_info[1])) mock_tmpl.assert_called_once_with(template,
AdaCore/spark2014
testsuite/gnatprove/tests/Q217-039__assume/test.py
Python
gpl-3.0
96
0
from test_support import check_out
put_file, prove_all prov
e_all() check_output_file(sort=True)
pyrocko/pyrocko
examples/trace_restitution_pz.py
Python
gpl-3.0
1,069
0
from pyrocko import pz, io, trace from pyrocko.example import get_example_data # Download example data get_example_data('STS2-Generic.polezero.txt') get_example_data('test.mseed') # read poles and zeros from SAC format pole-zero file zeros, poles, constant = pz.read_sac_zpk('STS2-Generic.polezero.txt') # one more ze...
ent->counts zeros.append(0.0j) rest_sts2 = trace.PoleZeroResponse( zeros=zeros, poles=poles, constant=constant) traces = io.load('test.mseed') out_traces = list(traces) for tr in traces: displacement = tr.transfer( 1000., # rise and fall of time window taper in [s] ...
change to (counts->displacement) # change channel id, so we can distinguish the traces in a trace viewer. displacement.set_codes(channel='D'+tr.channel[-1]) out_traces.append(displacement) io.save(out_traces, 'displacement.mseed')
fxia22/ASM_xf
PythonD/site_python/MMTK/Random.py
Python
gpl-2.0
5,293
0.004723
# Functions for finding random points and orientations. # # Written by: Konrad Hinsen # Last revision: 2000-8-9 # """This module defines various random quantities that are useful in molecular simulations. For obtaining random numbers, it tries to use the RNG module, which is part of the LLNL package distribution, whi...
# def randomDirection(): """Returns a vector drawn from a uniform distribution on the surface of a unit sphere.""" r = randomPointInSphere(1.) return r.normal() def randomDirect
ions(n): """Returns a list of |n| vectors drawn from a uniform distribution on the surface of a unit sphere. If |n| is negative, return a deterministic list of not more than -|n| vectors of unit length (useful for testing purposes).""" if n < 0: list = [Vector(1., 0., 0.), Vector(0., -1., 0....
dreibh/planetlab-lxc-plcapi
PLC/Methods/AddConfFile.py
Python
bsd-3-clause
1,107
0.004517
from PLC.Faults import * from PLC.Method import Method from PLC.Parameter import Parameter, Mixed from PLC.ConfFiles import Co
nfFile, ConfFiles from PLC.Auth import Auth can_update = lambda field_value: field_value[0] not in \ ['conf_file_id', 'node_ids', 'nodegroup_ids'] class AddConfFile(Method): """ Adds a new node configuration file. Any fields specified in conf_file_fields are used, otherwise defaults are used....
uccessful, faults otherwise. """ roles = ['admin'] conf_file_fields = dict(list(filter(can_update, list(ConfFile.fields.items())))) accepts = [ Auth(), conf_file_fields ] returns = Parameter(int, 'New conf_file_id (> 0) if successful') def call(self, auth, conf_file...
stevefaeembra/cartogram-plugin
form.py
Python
gpl-2.0
6,749
0
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'form.ui' # # Created: Mon Mar 24 20:22:18 2014 # by: PyQt4 UI code generator 4.10.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except Attribute...
) self.gridlayout.addItem(spacerItem1, 8, 0, 1, 2) self.txtProgress = QtGui.QLabel(Dialog) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed ) sizePolicy.setHorizo...
gress .sizePolicy() .hasHeightForWidth()) self.txtProgress.setSizePolicy(sizePolicy) self.txtProgress.setMinimumSize(QtCore.QSize(113, 20)) self.txtProgress.setText(_fromUtf8("")) self.txtProgress.setObjectName(_fr...
by46/flask-kits
setup.py
Python
mit
2,009
0
from __future__ import print_function import io import os.path import re from distutils.text_file import TextFile from setuptools import find_packages, setup home = os.path.abspath(os.path.dirname(__file__)) missing = object() def read_description(*files, **kwargs): encoding = kwargs.get('encodin...
text.close() def read_version(module_name): with open(os.path.join(module_name, '__i
nit__.py'), 'r') as fd: result = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE) return result.group(1) if result else '0.0.1' setup( name='flask_kits', version=read_version('flask_kits'), license='The MIT License', des...
stevenmizuno/QGIS
python/plugins/db_manager/db_plugins/postgis/connector.py
Python
gpl-2.0
44,359
0.002976
# -*- coding: utf-8 -*- """ /*************************************************************************** Name : DB Manager Description : Database manager plugin for QGIS Date : May 23, 2011 copyright : (C) 2011 by Giuseppe Sucameli email : brush.tyler@...
ibute it and/or modi
fy * * 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. * * * *****...
PyPlanet/PyPlanet
pyplanet/apps/contrib/funcmd/__init__.py
Python
gpl-3.0
4,483
0.022376
from pyplanet.apps.config import AppConfig from pyplanet.apps.contrib.funcmd.view import EmojiToolbarView from pyplanet.contrib.command import Command from pyplanet.apps.core.maniaplanet import callbacks as mp_signals from pyplanet.contrib.setting import Setting class FunCmd(AppConfig): app_dependencies = ['core.ma...
Display Emoji Toolbar', Setting.CAT_DESIGN, type=bool, default=True, description='Display the Emoji Toolbar to users
.', change_target=self.reload_settings ) self.emoji_toolbar = EmojiToolbarView(self) async def on_start(self): await self.context.setting.register( self.setting_emoji_toolbar ) await self.instance.command_manager.register( Command(command='afk', target=self.command_afk, admin=False, description='...
metabrainz/picard
test/formats/test_apev2.py
Python
gpl-2.0
11,058
0.000724
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # # Copyright (C) 2019, 2021 Philipp Wolfer # Copyright (C) 2020-2021 Laurent Monin # Copyright (C) 2021 Bob Swift # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # ...
nnels': '2', '~sample_rate': '44100', '~bits_per_sample': '16', } unexpected_info = ['~video'] class WavPackTest(CommonApeTests.ApeTestCase): testfile = 'test.wv' supports_ratings = False expected_
info = { 'length': 82, '~channels': '2', '~sample_rate': '44100', } unexpected_info = ['~video'] def setUp(self): super().setUp() config.setting['rename_files'] = True config.setting['move_files'] = False config.setting['ascii_filenames'] = False ...
remb0/CouchPotatoServer
libs/guessit/transfo/post_process.py
Python
gpl-3.0
2,521
0.000397
#!/usr/bin/env python # -*- coding: utf-8 -*- # # GuessIt - A library for guessing information from filenames # Copyright (c) 2012 Nicolas Wack <[email protected]> # # GuessIt is free software; you can redistribute it and/or modify it under # the terms of the Lesser GNU General Public License as published by # the Free ...
subtitle # (eg: 'xxx.english.srt') if (mtree.node_at((-1,)).value.lower() in subtitle_exts and node == mtree.leaves()[-2]): promote_subtitle() # - if a language is in an explicit group just preceded by "st", # it is a subtitle language (eg: '...st[fr-eng]......
= 'st': promote_subtitle() except IndexError: pass # 2- ", the" at the end of a series title should be prepended to it for node in mtree.nodes(): if 'series' not in node.guess: continue series = node.guess['series'] lseries = series.lower...
tvtsoft/odoo8
addons/sale_contract/__init__.py
Python
agpl-3.0
141
0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details.
import model
s import report import tests
HIPS/autograd
examples/rnn.py
Python
mit
4,931
0.00365
"""Implements the long-short term memory character model. This version vectorizes over multiple examples, but each string has a fixed length.""" from __future__ import absolute_import from __future__ import print_function from builtins import range import autograd.numpy as np import autograd.numpy.random as npr from a...
_matrix]) def build_dataset(filename, sequence_length, alphabet_size, max_lines=-1): """Loads a text file, and turns each line into an encoded sequence.""" with
open(filename) as f: content = f.readlines() content = content[:max_lines] content = [line for line in content if len(line) > 2] # Remove blank lines seqs = np.zeros((sequence_length, len(content), alphabet_size)) for ix, line in enumerate(content): padded_line = (line + " " * sequence...
interlegis/sapl
sapl/api/pagination.py
Python
gpl-3.0
3,967
0.000504
from django.core.paginator import EmptyPage from rest_framework import pagination from rest_framework.response import Response class StandardPagination(pagination.PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 100 def paginate_queryset(self, queryset, reques...
mber()
except EmptyPage: previous_page_number = None try: next_page_number = self.page.next_page_number() except EmptyPage: next_page_number = None return Response({ 'pagination': { 'links': { 'next': self.get_...
akamensky/sssd
src/config/SSSDConfigTest.py
Python
gpl-3.0
80,155
0.00136
#!/usr/bin/env python ''' Created on Sep 18, 2009 @author: sgallagh ''' import unittest import os import shutil import tempfile from stat import * import sys srcdir = os.getenv('srcdir') if srcdir: sys.path.insert(0, "./src/config") srcdir = srcdir + "/src/config" else: srcdir = "." import SSSDConfig d...
os.unlink(of) def testModifyExistingConfig(self): sssdconfig = SSSDConfig.SSSDConfig(srcdir + "/etc/sssd.api.conf", srcdir + "/etc/sssd.api.d") sssdconfig.import_config(srcdir + "/testconfigs/sssd-valid.conf") ldap_domain = sssdconfig.get_domain('LDAP...
ldap_domain.set_active(True) sssdconfig.save_domain(ldap_domain) proxy_domain = sssdconfig.get_domain('PROXY') proxy_domain.set_option('debug_level', 0x1f10) sssdconfig.save_domain(proxy_domain) sudo_responder = sssdco
soileater/noobest
rank/training.py
Python
mit
4,006
0.007489
from rank.models import Player from utils.api import get_watcher import time import json def search(my_id): if True: match = get_watcher().get_match_list(my_id,'na') match_id_list = [i['matchId'] for i
in match['matches'] if i['queue'] == 'TEAM_BUILDER_DRAFT_RANKED_5x5'][:9] match_details = [] all_players_id = dict() for match_id in match_id_list: match_detail = get_watcher().get_match(match_id) match_details.append(match_detail) for data in match_detail['p...
yers_id[data['player']['summonerId']].append([match_detail, data['participantId']]) else: all_players_id[data['player']['summonerId']] = [[match_detail, data['participantId']]] friends_id = [key for key, value in all_players_id.items() if len(value) > 1] for fid in fr...
Tafkas/solarpi
migrations/versions/721be6649087_.py
Python
bsd-3-clause
2,933
0
"""Initialize database Revision ID: 721be6649087 Revises: None Create Date: 2016-05-18 22:42:25.431499 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "721be6649087" down_revision = None def upgrade(): # commands auto generated by Alembic - please adjust!...
sa.Column("created_at", sa.Text(), nullable=False), sa.Column("temp", sa.Float(), nullable=True), sa.Column("pressure", sa.Integer(), nullable=True), sa.Column("temp_min", sa.Float(), nullable=True), sa.Column("temp_max", sa.Floa
t(), nullable=True), sa.Column("humidity", sa.Integer(), nullable=True), sa.Column("wind_speed", sa.Float(), nullable=True), sa.Column("wind_gust", sa.Float(), nullable=True), sa.Column("wind_deg", sa.Integer(), nullable=True), sa.Column("clouds", sa.Integer(), nullable=True), ...
rudivs/TaxonLinker
taxonutils.py
Python
mit
4,328
0.013863
#!/usr/bin/env python import csv import difflib try: from settings import FIELD_SEP except ImportError: FIELD_SEP = '\t' class TaxonIndex(): """ TaxonIndex is a class for reading a taxon dictionary file (which must be in the form of a tab-separated CSV text file), and matching genera and taxa ...
ndex.keys()
,n,sensitivity) def matchtaxa(self,t,genus=None,n=1,sensitivity=0.65): """Returns up to n taxa which have a similar name to the one provided. If genus is provided, limits search to that genus. """ test = t.strip().lower() if genus == None: re...
dipanshunagar/PySyft
syft/mpc/rss/__init__.py
Python
apache-2.0
162
0
from .config import PrecisionConfig from .r
epo import MPCRepo from .tensor import RSSMPCTensor
s = str(PrecisionConfig) s += str(MPCRepo) s += str(RSSMPCTensor)
mozilla/bztools
auto_nag/scripts/workflow/p1.py
Python
bsd-3-clause
410
0
# 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 t
his file, # You can obtain one at http://mozilla.org/MPL/2.0/. from auto
_nag.scripts.workflow.p1_no_activity import P1NoActivity from auto_nag.scripts.workflow.p1_no_assignee import P1NoAssignee if __name__ == "__main__": P1NoAssignee().run() P1NoActivity().run()
bytebit-ch/uguubot
plugins/util/bucket.py
Python
gpl-3.0
1,212
0
from time import time class TokenBucket(object): """An implementation of the token bucket algorithm. >>> bucket = TokenBucket(80, 0.5) >>> print bucket.consume(10) True >>> print bucket.consume(90) False """ def __init__(self, tokens, fill_rate): """tokens is the total tokens ...
delta = self.fill_rate * (now - self.timestamp)
self._tokens = min(self.capacity, self._tokens + delta) self.timestamp = now return self._tokens tokens = property(get_tokens)
showell/zulip
zilencer/migrations/0016_remote_counts.py
Python
apache-2.0
2,165
0.002309
# Generated by Django 1.11.18 on 2019-02-02 06:02 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('zilencer', '0015_delete_billing'), ] operations = [ migrations.CreateModel( name='RemoteInsta...
e)), ('server', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zilencer.RemoteZulipServer')), ], ), migrations.CreateModel( name='RemoteRealmCount', fields=[ ('id', models.AutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('property', models.CharField(max_length=32)), ('subgroup', models.CharField(max_length=16, null=True)), ('end_time', models.DateTimeField()), ('value', models.BigIntegerField()), ...
0ps/wfuzz
src/wfuzz/externals/moduleman/plugin.py
Python
gpl-2.0
482
0
import collections
def moduleman_plugin(*args): method_args = [] def inner_decorator(cls): for method in method_args: if (not (method in dir(cls))): raise Exception("Required method %s not implemented" % method)
cls.__PLUGIN_MODULEMAN_MARK = "Plugin mark" return cls if not isinstance(args[0], collections.Callable): method_args += args return inner_decorator return inner_decorator(args[0])
jansohn/pyload
module/plugins/hoster/FileSharkPl.py
Python
gpl-3.0
3,815
0.007602
# -*- coding: utf-8 -*- import re import urlparse from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo class FileSharkPl(SimpleHoster): __name__ = "FileSharkPl" __type__ = "hoster" __version__ = "0.15" __status__ = "testing" __pattern__ = r'http://(?:www\.)?files...
None) def handle_free(self, pyfile):
m = re.search(self.LINK_FREE_PATTERN, self.html) if m is None: self.error(_("Download url not found")) link = urlparse.urljoin("http://fileshark.pl/", m.group(1)) self.html = self.load(link) m = re.search(self.WAIT_PATTERN, self.html) if m is not None: ...
LBatsoft/python3-webapp
www/pymonitor.py
Python
gpl-3.0
1,748
0.006865
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "pwxc" import os, sys, time, subprocess from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler def log(s): print('[Monitor] %s' % s) class MyFileSystemEventHander(FileSystemEventHandler): def __init__(self, fn)...
code %s.' % process.returncode) process = None def start_process(): global process, command log('Start process %s...' % ' '.join(command)) process = subprocess.Popen(command, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr) def restart_process(): kill_process() start_process() def ...
rt() log('Watching directory %s...' % path) start_process() try: while True: time.sleep(0.5) except KeyboardInterrupt: observer.stop() observer.join() if __name__ == '__main__': argv = sys.argv[1:] if not argv: print('Usage: ./pymonitor your-script.py') ...
Microsoft/ApplicationInsights-Python
tests/applicationinsights_tests/channel_tests/contracts_tests/TestMessageData.py
Python
mit
2,310
0.007359
import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from ...
ssert
Equal(expected, actual) expected = 13 item.ver = expected actual = item.ver self.assertEqual(expected, actual) def test_message_property_works_as_expected(self): expected = 'Test string' item = MessageData() item.message = expected actual = item.m...
giacomov/3ML
threeML/utils/data_builders/time_series_builder.py
Python
bsd-3-clause
44,553
0.001369
import copy import re import astropy.io.fits as fits import numpy as np from threeML.exceptions.custom_exceptions import custom_warnings from threeML.io.file_utils import file_existing_and_readable from threeML.io.progress_bar import progress_bar from threeML.plugins.DispersionSpectrumLike import DispersionSpectrumLi...
ogram), "must be a subclass of Histogram" self._name = name self._container_type = container_type self._time_series = time_series # type: TimeSeries # make sure we have a proper response if response is not None: assert ( isinstance(response, Inst...
esponseSet) or isinstance(response, str) ), "Response must be an instance of InstrumentResponse" # deal with RSP weighting if need be if isinstance(response, InstrumentResponseSet): # we have a weighted response self._rsp_is_weighted = True ...
emesene/emesene
emesene/gui/common/TrayIcon.py
Python
gpl-3.0
14,327
0.001466
# -*- coding: utf-8 -*- # This file is part of emesene. # # emesene 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. # #...
Show emesene')) self.hide_show_mainwindow.connect('activate', lambda *args: self.handler.on_hide_show_mainwindow(main_window)) self.quit = gtk.ImageMenuItem(gtk.STOCK_QUIT)
self.quit.connect('activate', lambda *args: self.handler.on_quit_selected()) self.append(self.hide_show_mainwindow) self.append(self.quit) def unsubscribe(self): pass class MainMenu(gtk.Menu): """ a widget that represents the menu displayed on the trayicon on the ...
openweave/openweave-core
src/device-manager/python/openweave/WeaveUtility.py
Python
apache-2.0
2,006
0.001994
# # Copyright (c) 2020 Google LLC. # 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 re...
eturn False return True @staticmethod def ByteArrayToHex(arr
ay): return WeaveUtility.Hexlify(bytes(array)) @staticmethod def CStringToString(s): return None if s is None else s.decode() @staticmethod def StringToCString(s): return None if s is None else s.encode()