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
SYHGroup/mau_mau_bot
utils.py
Python
agpl-3.0
3,582
0.000281
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Telegram bot to play UNO in group chats # Copyright (c) 2016 Jannes Höke <uno@jhoeke.de> # # T
his program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, ...
tchellomello/home-assistant
homeassistant/helpers/device_registry.py
Python
apache-2.0
22,499
0.001022
"""Provide a way to connect entities belonging to one device.""" from collections import OrderedDict import logging from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Tuple, Union import attr from homeassistant.const import EVENT_HOMEASSISTANT_STARTED from homeassistant.core import Event, callback impo...
it doesn't exist.""" if not identifiers and not connections: return None if identifiers is None: identifiers = set() if connections is None:
connections = set() else: connections = _normalize_connections(connections) device = self.async_get_device(identifiers, connections) if device is None: deleted_device = self._async_get_deleted_device(identifiers, connections) if deleted_device is None: ...
pusateri/canner
canner/personalities/junos.py
Python
gpl-3.0
1,104
0.001812
# # Copyright 2007 !j Incorporated # # This file is part of Canner. # # Canner is free software: you can redist
ribute 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. # # Canner is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warr...
ore details. # # You should have received a copy of the GNU General Public License # along with Canner. If not, see <http://www.gnu.org/licenses/>. # from . import Personality class JUNOSPersonality(Personality): os_name = "JUNOS" commands_to_probe = () def examine_evidence(self, command, output): ...
zbqf109/goodo
openerp/addons/sale_crm/res_users.py
Python
gpl-3.0
261
0.003831
# -*- coding: utf-8 -*- from openerp.osv import osv, field
s import openerp.addons.product.product class res_users(osv.osv): _inherit = 'res.users' _columns = { 'target_sales_invoiced': fields.integer('Invoiced in Sale Orders Target'), }
nijinashok/sos
sos/plugins/grub2.py
Python
gpl-2.0
2,119
0
# This file is part of the sos project: https://github.com/sosreport/sos # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # version 2 of the GNU General Public License. # # See the LICENSE file in the source distribution ...
_cmd_output("ls -lanR /boot") # call grub2-mkconfig with GRUB_DISABLE_OS_PROBER=true to prevent # possible unwanted loading of some kernel modules env = {} env['GRUB_DISABLE_OS_PROBER'] = 'true' self.add_cmd_output("grub2-mkconfig", env=env) def postproc(self): # the...
ord )\s*(\S*)\s*(\S*)" passwd_pbkdf2_exp = r"(password_pbkdf2)\s*(\S*)\s*(\S*)" passwd_sub = r"\1 \2 ********" passwd_pbkdf2_sub = r"\1 \2 grub.pbkdf2.********" self.do_cmd_output_sub( "grub2-mkconfig", passwd_pbkdf2_exp, passwd_pbkdf2_sub ) ...
Turupawn/website
games/migrations/0013_auto_20161001_0143.py
Python
agpl-3.0
561
0.001783
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-09-30 23:43 from __future__ import unicode_literals from django.db import migrations, models import django.db
.models.deletion class Migration(migrations.Migration): dependencies = [
('games', '0012_remove_gamelink_accepted_at'), ] operations = [ migrations.AlterField( model_name='gamelink', name='game', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='links', to='games.Game'), ), ]
umeckel/FS_coapy
coapy/connection.py
Python
bsd-3-clause
41,116
0.004937
# -*- coding: utf-8 -*- # Copyright (c) 2010 People Power Co. # All rights reserved. # # This open source code was developed with funding from People Power Company # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # ...
invoked with the parameter value to create an option that is associated with the message.""" def __init__ (self, transaction_type=CON, code=0, payload='', sockname=('127.0.0.1', coapy.COAP_PORT), uri_path = '', **kw): """Create a Message instance. As a
convenience, message options can be created from keyword parameters if the keywords are present in :attr:`.OptionKeywords`. :param transaction_type: One of :attr:`.CON`, :attr:`.NON`, :attr:`.ACK`, :attr:`.RST`. The message transaction type cannot be modified after creat...
ovnicraft/edx-platform
lms/urls.py
Python
agpl-3.0
33,307
0.002252
""" URLs for LMS """ from django.conf import settings from django.conf.urls import patterns, include, url from django.views.generic.base import RedirectView from ratelimitbackend import admin from django.conf.urls.static import static import django.contrib.auth.views from microsite_configuration import microsite impo...
^login$', 'student.views.signin_user', name="signin_user"), url(r'^register$', 'student.views.register_user', name="register_user"), ) if settings.FEATURES["ENABLE_MOBILE_REST_API"]:
urlpatterns += ( url(r'^api/mobile/v0.5/', include('mobile_api.urls')), ) # if settings.FEATURES.get("MULTIPLE_ENROLLMENT_ROLES"): urlpatterns += ( # TODO Namespace these! url(r'^verify_student/', include('verify_student.urls')), url(r'^course_modes/', include('course_modes.urls')), ) js_info_...
maciekswat/dolfin_1.3.0
site-packages/dolfin_utils/pjobs/slurm.py
Python
gpl-3.0
1,881
0.002127
#!/usr/bin/env python # Copyright (C) 2013 Johannes Ring # # This file is part of DOLFIN. # # DOLFIN is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your optio...
Generate a slurm specific job script. """ sbatch = "#SBATCH --job-name=" + jobname sbatch += " --time=%d:00:00" % walltime sbatch += " --ntasks=" + str(nodes) sbatch += " --cpus-per-task=" + str(ppn) if mem: sbatch += " --mem-per-cpu=" + mem if email: sbatch += " --mail-use...
t supported for the 'slurm' backend" if queue: print "Warning: 'queue' is not supported for the 'slurm' backend" if parallel_environment: print "Warning: 'parallel_environment' is not supported for the 'slurm' backend" args = dict(sbatch=sbatch, workdir=workdir, ...
pymedusa/SickRage
lib/unrar2/windows.py
Python
gpl-3.0
12,977
0.000848
# Copyright (c) 2003-2005 Jimmy Retzlaff, 2008 Konstantin Yegupov # # 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...
ARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PAR
TICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # Low level i...
xspager/openbaybrowser
csv_import/management/commands/import_csv.py
Python
mit
1,058
0.021739
import csv from django.core.management.base import BaseCommand, CommandError from torrent.models import
Torrent class Command(BaseCommand): args = '<poll_id poll_id ...>' help = 'Closes the specified poll for voting' def handle(self, *args, **options): with open("/home/dlemos/tmpfs/tmp/torrents_mini.csv") as csvfile: #reader = csv.reader(
csvfile, delimiter='|', quotechar='"') try: #for row in reader: torrents = [] for line in csvfile: rows = line.split('|') if len(rows) != 7: continue torrent = Torrent( ...
RT-Thread/rtthread_fsl
utils/mdp/eMPL-pythonclient/euclid.py
Python
lgpl-2.1
69,409
0.003472
#!/usr/bin/env python # # euclid graphics maths module # # Copyright (c) 2006 Alex Holkner # Alex.Holkner@mail.google.com # # This library 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 version ...
_len
__') and len(other) == 2 return self.x == other[0] and \ self.y == other[1] def __ne__(self, other): return not self.__eq__(other) def __nonzero__(self): return self.x != 0 or self.y != 0 def __len__(self): return 2 def __getitem__(self, key): ...
redhat-openstack/trove
trove/tests/scenario/groups/guest_log_group.py
Python
apache-2.0
9,327
0
# Copyright 2015 Tesora 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...
lf): """Test that log-show works for SYS log.""" self.test_runner.run_test_log_show_sys() @test(runs_after=[test_log_show_sys]) def test_log_publish_sys(self): """Test log-publish on SYS log.""" self.test_runner.run_test_log_publish_sys() @test(runs_after=[test_log_publish_...
og-publish again on SYS log.""" self.test_runner.run_test_log_publish_again_sys() @test(depends_on=[test_log_publish_again_sys]) def test_log_generator_sys(self): """Test log-generator on SYS log.""" self.test
renalreg/radar
radar/api/views/fuan.py
Python
agpl-3.0
1,288
0.003106
from radar.api.serializers.fuan import FuanClinicalPictureSerializer from radar.api.views.common import ( IntegerLookupListView, PatientObjectDetailView, PatientObjectListView, StringLookupListView, ) from radar.models.fuan import FuanClinicalPicture, RELATIVES, THP_RESULTS class FuanClinicalPictureLi...
cal-pictures', view_func=FuanClinicalPictureListView.as_view('fuan_clinical_picture_list') ) app.add_url_rule( '/fuan-clinical-pictures/<id>', view_func=FuanClinicalPictureDetailView.as_view('fuan_clinical_picture_detail') ) app.add_url_rule('/fuan-relatives', view_func=FuanRelat...
an_thp_result_list'))
luminousflux/lflux
lfluxproject/lsubscribe/forms.py
Python
mit
846
0.00591
from django import forms from django.db import models from .models import Subscription from django.utils.translation import ugettext as _ class SubscriptionForm(forms.ModelForm): class Meta: model = Subscription def clean(self): cleaned_data = super(Su
bscriptionForm, self).clean() if not cleaned_data.get('email','') and not cleaned_data.get('user_id',''): raise forms.ValidationError("need either email or user!") return cleaned_data class SubscriptionEmailForm(forms.ModelForm): class Meta: model = Subscription fields =...
widgets = { 'frequency': forms.widgets.RadioSelect(), 'object_id': forms.widgets.HiddenInput(), 'content_type': forms.widgets.HiddenInput(), }
simongregory/electron
tools/js2asar.py
Python
mit
1,415
0.013428
#!/usr/bin/env python import errno import os import shutil import subprocess import sys import tempfile SOURCE_ROOT = os.path.dirname(os.path.dirname(__file__)) def main(): archive = sys.argv[1] js_source_files = sys.argv[2:] output_dir = tempfile.mkdtemp() copy_js(js_source_files, output_dir) call_asar(...
mtree(output_dir) def copy_js(js_source_files, output_dir): for source_file in js_source_files: output_filename =
os.path.splitext(source_file)[0] + '.js' output_path = os.path.join(output_dir, output_filename) safe_mkdir(os.path.dirname(output_path)) shutil.copy2(source_file, output_path) def call_asar(archive, output_dir): js_dir = os.path.join(output_dir, 'lib') asar = os.path.join(SOURCE_ROOT, 'node_modules',...
jarn0ld/gnuradio
gr-audio/examples/python/dial_tone.py
Python
gpl-3.0
2,150
0.002326
#!/usr/bin/env python # # Copyright 2004,2005,2007,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at ...
utput", type="string", default="", help="pcm outpu
t device name. E.g., hw:0,0 or /dev/dsp") parser.add_option("-r", "--sample-rate", type="eng_float", default=48000, help="set sample rate to RATE (48000)") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() raise System...
posiputt/Sandbox
games.py
Python
mit
454
0.006608
import meistermind
def show_menu (games): print "Hello!" print "Choose your game or press Q and Enter to quit." for g in games: print "\t" + g + ") " + games[g] quit = False while not (quit): games = { "1": "Meistermind", "2": "No Game Here", } show_menu(games) choice = str(raw_input...
stermind.meistermind()
HiSPARC/topaz
130711_event_histogram/eventtime_histogram.py
Python
gpl-3.0
2,523
0.000793
import datetime import numpy as np from artist import Plot from sapphire import Station from sapphire.transformations.clock import datetime_to_gps, gps_to_datetime from get_aligned_eventtimes import get_aligned, get_station_numbers YEARS = range(2004, datetime.date.today().year + 1) YEARS_TICKS = np.array([datetim...
tion_numbers): n = Station(s).n_detectors() if n == 2: scaled_data[i] /= 1200. elif n == 4: scaled_data[i] /= 2500. scaled_data = np.where(scaled_data > 2., 2., scaled_data) return scaled_data def plot_histogram(data, timestamps, station_numbe
rs): """Make a 2D histogram plot of the number of events over time per station :param data: list of lists, with the number of events. :param station_numbers: list of station numbers in the data list. """ plot = Plot(width=r'\linewidth', height=r'1.3\linewidth') plot.histogram2d(data.T[::7][1:]...
kiniou/qtile
libqtile/xcbq.py
Python
mit
31,290
0.000352
# Copyright (c) 2009-2010 Aldo Cortesi # Copyright (c) 2010 matt # Copyright (c) 2010, 2012, 2014 dequis # Copyright (c) 2010 Philip Kranz # Copyright (c) 2010-2011 Paul Colomiets # Copyright (c) 2011 osebelin # Copyright (c) 2011 Mounier Florian # Copyright (c) 2011 Kenji_Takahashi # Copyright (c) 2011 Tzbob # Copyrig...
lets us passin a Font object, rather than Font.fid, for example. """ def __init__(self, obj): self.mmap = [] for i in dir(obj): if not i.startswith("_"): self.mmap.append((getattr(obj, i), i.lowe
r())) self.mmap.sort() def __call__(self, **kwargs): """ kwargs: keys should be in the mmap name set Returns a (mask, values) tuple. """ mask = 0 values = [] for m, s in self.mmap: if s in kwargs: val = kwargs.get(...
virtuald/pygi-composite-templates
gi_composites.py
Python
lgpl-2.1
9,156
0.000655
# # Copyright (C) 2015 Dustin Spicuzza <dustin@virtualroadside.com> # # This library 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 # version 2.1 of the License, or (at your option) any later ve...
"but was not present in template") % name warnings.warn(errmsg, GtkTemplateWarning) # TODO: Make it easier for IDE to introspect this class _Child(object): ''' Assign this to an attribute in your class definition and it will be replaced with a widget defined in the UI file when ...
' __slots__ = [] @staticmethod def widgets(count): ''' Allows declaring multiple widgets with less typing:: button \ label1 \ label2 = GtkTemplate.Child.widgets(3) ''' return [_Child() for _ in range(count)] cl...
kunalsharma05/django-project
django_project/migrations/0014_auto_20160710_1200.py
Python
bsd-3-clause
558
0.001792
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-07-10 12:00 from __future__ import unicode_literals from dja
ngo.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [
('django_project', '0013_auto_20160710_1124'), ] operations = [ migrations.AlterField( model_name='annotation', name='comment', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='django_project.Comment'), ), ]
tzpBingo/github-trending
codespace/python/tencentcloud/scf/v20180416/errorcodes.py
Python
mit
27,390
0.001814
# -*- coding: utf8 -*- # Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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...
# 函数在部署中,无法做此操作。 FAILEDOPERATION_FUNCTIONSTATUSERROR = 'FailedOperation.FunctionStatusError' # 当前函数版本状态无法进行此操作,请在版本状态为正常时重试。 FAILEDOPERATION_FUNCTIONVERSIONSTATUSNOTACTIVE = 'FailedOperation.FunctionVersionStatusNotActive' # 获取别名信息失败。 FAILEDOPERATION_GETALIAS = 'FailedOperation.GetAlias' # 获取函数代码地址失败。 FAILEDOPERATIO...
ration.InsufficientBalance' # 调用函数失败。 FAILEDOPERATION_INVOKEFUNCTION = 'FailedOperation.InvokeFunction' # 命名空间已存在,请勿重复创建。 FAILEDOPERATION_NAMESPACE = 'FailedOperation.Namespace' # 服务开通失败。 FAILEDOPERATION_OPENSERVICE = 'FailedOperation.OpenService' # 操作冲突。 FAILEDOPERATION_OPERATIONCONFLICT = 'FailedOperation.Operati...
CoderBotOrg/coderbot
test/pigpio_mock.py
Python
gpl-2.0
2,965
0.005059
import unittest.mock import time import logging import logging.handlers import coderbot logger = logging.getLogger() class PIGPIOMock(object): """Implements PIGPIO librar
y mock class PIGPIO is the library used to access digital General Purpose IO (GPIO), this mock class emulates the behaviour of the inputs used by the sonar sensors: a fake signal is triggered to emulate a 85.1 distance. Output (DC motor and Servo) are just no-op function, they implement basic parameters che...
mode): """mock set_mode""" pass def get_mode(self, pin_id): """mock get_mode""" return 0 def callback(self, pin_id, edge, callback): """mock callback""" self.callbacks[pin_id] = callback return self.Callback(pin_id) def write(self, pin_id, value): ...
PerroTron/HostilPlanet
lib/tiles.py
Python
gpl-2.0
5,826
0.002575
import pygame import tiles_basic from tile import * # NOTE: If you add new tiles, use t_init for regular tiles. # tl_init and tr_init are for tiles that take up only half of the # 16x16 tile, on the left or right side respectively. TILES = { # general purpose tiles 0x00: [t_init, [], None, ], ...
# electron 0x6E: [t_init, ['player'], tiles_basic.hit_dmg, 1, 1, 1, 1, ], # electron 0x6F: [t_init, ['player'], tiles_basic.hit_dmg, 1, 1, 1, 1, ], # electron 0x4A: [t_init, ['player'], tiles_basic.hit_dmg, 1, 1, 1, 1, ], # pinchos 0x4B: [t_init, ['player'], tiles_basic.hit_dmg, 1, 1, 1, 1, ], # ...
01112223330000000000000000']), # extra life (0x1C, [int(v) for v in '00000001112223330000000000000000']), # def (0x08, [int(v) for v in '00000000000000000000000111222333']), # cannon (0x18, [int(v) for v in '00000000000000000000000111222333']), # laser (0x28, [int(v) for v in '000000000000000000000...
vollov/django-template
django/esite/populate_auto.py
Python
mit
2,560
0.010938
import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'esite.settings') import django django.setup() from auto.models import Car # def add_car(make, model, km, year, color, eng, drive,trans, icolor): c = Car.objects.get_or_create(make=make, model=model, kilometers=km, year=year, color=color, engine_size=
eng, drivetrain=drive, transmition=trans, interanl_color=icolor) def populate(): # car = Car(make='Acura',model='TL', kilometers=74673, year=2012, color='White', engine_size=3.7, drivetrain='AWD', transmition='MA') add_car('Acura', 'TL', 74673, 2012, 'White', 3.7, 'AWD','MA','White') add_car('Volkswagen',...
'White') if __name__ == '__main__': print "Starting Car population script..." populate() # def populate(): # python_cat = add_cat('Python') # # add_page(cat=python_cat, # title="Official Python Tutorial", # url="http://docs.python.org/2/tutorial/") # # add_page(cat=pytho...
SelvorWhim/competitive
LeetCode/MaximumSubarray.py
Python
unlicense
588
0.003401
cl
ass Solution: # returns sum of contiguous non-empty subarray with greatest sum def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ sumCurr = 0 sumMax = -math.inf for i in range(len(nums)): sumCurr += nums[i] if su...
e one with the least absolute value will be returned sumMax = sumCurr if sumCurr < 0: sumCurr = 0 return sumMax
googleapis/python-websecurityscanner
samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_async.py
Python
apache-2.0
1,618
0.001854
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version
2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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. # # Generated code. DO NOT EDIT! # # Snippet for ListCrawledUrls # NOTE: This snippet has been automatically generated for illustra...
hzj123/56th
pombola/place_data/bin/import_place_data.py
Python
agpl-3.0
3,048
0.003609
#!/usr/bin/env python import sys import csv import os import decimal os.environ['DJANGO_SETTINGS_MODULE'] = 'pombola.settings' sys.path.append('../../../') sys.path.append('../../') from django.utils.text import slugify from pombola.core.models import Place from pombola.place_data.models import Entry place_kind_sl...
ind_slug, place_slug) continue try: data_row = Entry.objects.get(place=place) except Entry.DoesNotExist: data_row = Entry() data_row.place = place data_row.population_male = int(row['Male Population']) data_row.population_female = int(row['Female Population']) data_...
ighest']) data_row.gender_index = decimal.Decimal(row['Gender Ration Women:Men']) data_row.gender_index_rank = int(row['Women to Men Ratio Rank 1=Highest']) data_row.households_total = int(row['Number of Households']) data_row.average_household_size = decimal.Decimal(row['Average Houshold Size']) da...
dropbox/changes
changes/api/serializer/models/cluster.py
Python
apache-2.0
336
0
from changes.api.serializer import Crumbler, register from changes.models.node import Cluster @register(
Cluster) class ClusterCrumbler(Crumbler): def crumble(self, instance, attrs): return { 'id': instance.id.hex,
'name': instance.label, 'dateCreated': instance.date_created, }
klynton/freight
freight/utils/workspace.py
Python
apache-2.0
2,839
0
from __future__ import absolute_import import logging import os import shlex import shutil import sys import traceback from flask import current_app from subprocess import PIPE, Popen, STDOUT from uuid import uuid1 from freight.exceptions import CommandError class Workspace(obje
ct): log = logging.getLogger('workspace') def __init__(self, path, log=None): self.path = path if log is not None: self.log = log def whereis(self, program, env): for path in env.get('PATH', '').split(':'): if os.path.exists(os.path.join(path, program)) and ...
h, program)): return os.path.join(path, program) return None def _get_writer(self, pipe): if not isinstance(pipe, int): pipe = pipe.fileno() return os.fdopen(pipe, 'w') def _run_process(self, command, *args, **kwargs): stdout = kwargs.get('stdout', s...
datacode-taavi/python-spi
spi/ioctl_numbers.py
Python
mit
1,678
0.004768
""" Source: http://code.activestate.com/recipes/578225-linux-ioctl-numbers-in-python/ Linux ioctl numbers made easy size can be an integer or format string compatible with struct module for example include/linux/watchdog.h: #define WATCHDOG_IOCTL_BASE 'W' struct watchdog_info { __u32 options; ...
\ nr << _IOC_NRSHIFT | \ size << _IOC_SIZESHIFT def _IO(type, nr): return _IOC(_IOC_NONE, type, nr, 0) def _IOR(type, nr, size): return _IOC(_
IOC_READ, type, nr, size) def _IOW(type, nr, size): return _IOC(_IOC_WRITE, type, nr, size) def _IOWR(type, nr, size): return _IOC(_IOC_READ | _IOC_WRITE, type, nr, size)
USGSDenverPychron/pychron
pychron/experiment/notifier/user_notifier.py
Python
apache-2.0
6,871
0.001455
# # =============================================================================== # # Copyright 2014 Jake Ross # # # # 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.apa...
**ctx) # message = email_template(**mctx) # self._send(ctx.get('email'), subject, message) # # if ctx.get('use_group_email'): # pairs = ctx.get('group_emails') # if pairs: # names, addrs = pairs # self.info('Notifying user group names={}'.f...
for n, a in pairs: # self._send(a, subject, message) # # # def _events_default(self): # # print 'EVENTS DEFAULT' # # evts = [ExperimentEventAddition(id='pychorn.user_notifier.start_queue', # # action=self._start_queue, # # ...
sofianehaddad/ot-svn
python/test/t_Mixture_std.py
Python
mit
7,198
0.002779
#! /usr/bin/env python from openturns import * TESTPREAMBLE() RandomGenerator.SetSeed(0) try: # Instanciate one distribution object dimension = 3 meanPoint = NumericalPoint(dimension, 1.0) meanPoint[0] = 0.5 meanPoint[1] = -0.5 sigma = NumericalPoint(dimension, 1.0) sigma[0] = 2.0 sig...
ibution.getSample(size) print "oneSample first=", r
epr(oneSample[0]), " last=", repr(oneSample[size - 1]) print "mean=", repr(oneSample.computeMean()) print "covariance=", repr(oneSample.computeCovariance()) # Define a point point = NumericalPoint(distribution.getDimension(), 1.0) print "Point= ", repr(point) # Show PDF and CDF of point ep...
seung-lab/euclidean-distance-transform-3d
python/setup.py
Python
gpl-3.0
779
0.014121
import setuptools import sys import numpy as np # NOTE: If edt.cpp does not exist: # cython -3 --fast-fail -v --cplus edt.pyx extra_compile_args = [] if sys.platform == 'win32': extra_compile_args += [ '/std:c++11', '/O2' ] else: extra_compile_args += [ '-std=c++11', '-O3', '-ffast-math', '-pthread' ...
extra_compile_args=extra_compile_args, ), ], long_descripti
on_content_type='text/markdown', pbr=True )
abigailStev/stingray
stingray/largememory.py
Python
mit
34,861
0.000832
import os import random import string import warnings import numpy as np from astropy import log from astropy.io import fits import stingray from .events import EventList from .gti import cross_two_gtis from .io import high_precision_keyword_read from .lightcurve import Lightcurve from .utils import genDataPath HAS...
d(HDUList.header, "MJDREF"), compressor=compressor, overwrite=True, ) elif
HDUList.name == "GTI": # TODO: Needs to be generalized start, stop = HDUList.data["START"], HDUList.data["STOP"] gti = np.array(list(zip(start, stop))) main_data_group.create_dataset( name="gti", data=gti.flatten(), ...
vmendez/DIRAC
Core/scripts/dirac-configure.py
Python
gpl-3.0
20,061
0.037236
#!/usr/bin/env python ######################################################################## # $HeadURL$ # File : dirac-configure # Author : Ricardo Graciani ######################################################################## """ Main script to write dirac.cfg for a new DIRAC installation and initial downl...
g.setOptionValue( cfgInstallPath( 'SkipCAChecks' ), skipCAChecks ) return DIRAC.S_OK() def setSkipCADownload( optionValue ):
global skipCADownload skipCADownload = True DIRAC.gConfig.setOptionValue( cfgInstallPath( 'SkipCADownload' ), skipCADownload ) return DIRAC.S_OK() def setSkipVOMSDownload( optionValue ): global skipVOMSDownload skipVOMSDownload = True DIRAC.gConfig.setOptionValue( cfgInstallPath( 'SkipVOMSDownload' ), s...
rgayon/plaso
tests/output/json_out.py
Python
apache-2.0
4,842
0.002891
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the JSON output module.""" from __future__ import unicode_literals import json import os import sys import unittest from dfvfs.lib import definitions as dfvfs_definitions from dfvfs.path import factory as path_spec_factory from plaso.formatters import mana...
't
imestamp_desc': definitions.TIME_DESCRIPTION_UNKNOWN, 'username': 'root', } } event_body = self._output_writer.ReadOutput() # We need to compare dicts since we cannot determine the order # of values in the string. json_string = '{{ {0:s} }}'.format(event_body) json_dict = js...
adviti/melange
thirdparty/google_appengine/lib/webapp2/tests/extras_jinja2_test.py
Python
apache-2.0
3,283
0.000305
# -*- coding: utf-8 -*- import os import webapp2 from webapp2_extras import jinja2 import test_base current_dir = os.path.abspath(os.path.dirname(__file__)) template_path = os.path.join(current_dir, 'resources', 'jinja2_templates') compiled_path = os.path.join(current_dir, 'resources', '...
j = jinja2.g
et_jinja2(app=app) self.assertTrue(isinstance(j, jinja2.Jinja2)) def test_get_jinja2(self): app = webapp2.WSGIApplication() self.assertEqual(len(app.registry), 0) j = jinja2.get_jinja2(app=app) self.assertEqual(len(app.registry), 1) self.assertTrue(isinstance(j, jinj...
open-craft/xblock-poll
tests/utils.py
Python
agpl-3.0
708
0.002825
# Test mocks and helpers from __future__ import absolute_import from webob import Request f
rom xblock.runtime import DictKeyValueStore, KvsFieldData from xblock.test.tools import TestRuntime def make_request(body, method='POST'): """ Helper method to make request """ request = Request.blank('/') request.body = body.encode('utf-8') request.method = method return request # pylint...
*kwargs): field_data = kwargs.get('field_data', KvsFieldData(DictKeyValueStore())) super(MockRuntime, self).__init__(field_data=field_data)
tsl143/zamboni
mkt/abuse/models.py
Python
bsd-3-clause
3,973
0
import logging from django.conf import settings from django.db import models from mkt.site.mail import send_mail from mkt.site.models import ModelBase from mkt.users.models import UserProfile from mkt.webapps.models import Webapp from mkt.websites.models import Website log = logging.getLogger('z.abuse') class Abu...
user_name, obj.name, settings.SITE_URL, obj.get_url_path(), self.message) send_mail(subject, msg, recipient_list=recipient_list) @classmethod def recent_high_abuse_reports(cls, threshold, period, addon_id=None): """ Returns AbuseReport objects for the given thresho...
abuse_sql = [''' SELECT `abuse_reports`.*, COUNT(`abuse_reports`.`addon_id`) AS `num_reports` FROM `abuse_reports` INNER JOIN `addons` ON (`abuse_reports`.`addon_id` = `addons`.`id`) WHERE `abuse_reports`.`created` >= %s '''] params = [p...
CSC301H-Fall2013/ElectionSimulation
Code/Database/Build/build_lists.py
Python
mit
1,031
0.054316
if __name__ == '__main__': expenses_list = [] expenses = open('DummyExpense.csv', 'r') #Skip header expenses.readline() for line in expenses.readlines(): expenses_list.append([elem.rsplit("\r\n")[0] for elem in line.
split(',')]) expenses.close() ctracts_list = [] ctracts = open('DummyCT.csv', 'r') #Skip header ctracts.readline() tract = [] for line in ctracts.readlines(): tract = line.split(',') tract = [tract[0]] + tract[4:-1] ctracts_list.append(tract) ctracts.close() pstation_list = [] pstations = open('...
'r') #Skip header pstations.readline() for line in pstations.readlines(): pstation_list.append([elem.rsplit("\r\n")[0] for elem in line.split(',')]) pstations.close() links_list = [] links = open('DummyLink.csv', 'r') #Skip header links.readline() for line in links.readlines(): links_list.append([e...
rndusr/stig
stig/tui/scroll.py
Python
gpl-3.0
16,073
0.001058
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful # but...
= self._original_widget ow_size = self._get_original_widget_size(size) canv_full = ow.render(ow_size, focus) # Make full canvas editable canv = urwid.CompositeCanvas(canv_full) canv_cols, canv_rows = canv.cols(), canv.rows() if canv_cols <= maxcol: pad_widt...
if canv_rows <= maxrow: fill_height = maxrow - canv_rows if fill_height > 0: # Canvas is lower than available vertical space canv.pad_trim_top_bottom(0, fill_height) if canv_cols <= maxcol and canv_rows <= maxrow: # Canvas is small enou...
google/DAPLink-port
test/stress_tests/hid_usb_test.py
Python
apache-2.0
2,358
0.000424
# # DAPLink Interface Firmware # Copyright (c) 2016-2017, ARM Limited, All Rights Reserved # SPDX-License-Identifier: Apache-2.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...
print(msg) def hid_main(thread_index, board_id): global should_exit count = 0 try: device = pyocd.probe.pydapaccess.DAPAccess.get_device(board_id) while not should_exit: device.open() info = device.vendor(0) info = str(bytearray(info[1:1 + info[0]])) ...
%s" % (thread_index, count, _get_time(), time.strftime("%H:%M:%S"), board_id)) count += 1 except: sync_print("Thread %i exception board %s" % (thread_index, board_id)) with exit_cond: should_exit = 1 exit_con...
kennedyshead/home-assistant
homeassistant/components/yi/camera.py
Python
apache-2.0
5,013
0.000798
"""Support for Xiaomi Cameras (HiSilicon Hi3518e V200).""" import asyncio import logging from aioftp import Client, StatusCodeError from haffmpeg.camera import CameraMjpeg from haffmpeg.tools import IMAGE_JPEG, ImageFrame import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera fro...
the customized Yi FTP server.""" ftp = Client() try: await ftp.connect(self.host) await ftp.login(self.user, self.passwd) except (ConnectionRefusedError, StatusCodeError) as err: raise PlatformNotReady(err) from err try: await ftp.change_...
str(path): dirs.append(path) latest_dir = dirs[-1] await ftp.change_directory(latest_dir) videos = [] for path, _ in await ftp.list(): videos.append(path) if not videos: _LOGGER.info('Video folder "%s" empt...
openai/cleverhans
tests_tf/test_mnist_tutorial_keras.py
Python
mit
2,129
0.003758
# pylint: disable=missing-docstring import unittest import numpy as np # pylint bug on next line from tensorflow.python.client import device_lib # pylint: disable=no-name-in-module from cleverhans.devtools.checks import CleverHansTest HAS_GPU = 'GPU' in {x.device_type for x in device_lib.list_local_
devices()} class TestMNISTTutorialKeras(CleverHansTest): def test_mnist_tutorial_keras(self): import tensorflow as tf from cleverhans_tutorials import mnist_tutorial_keras # Run the MNIST tutorial on a dataset of reduced size test_dataset_indice
s = {'train_start': 0, 'train_end': 5000, 'test_start': 0, 'test_end': 333, 'nb_epochs': 2, 'testing': True} g = tf.Graph() with g.as_default(): np.random.seed(42) ...
zstackio/zstack-woodpecker
integrationtest/vm/multihosts/vm_snapshots/paths/xsky_path20.py
Python
apache-2.0
1,808
0.017699
import zstackwoodpecker.test_state as ts_header import os TestAction = ts_header.TestAction def path(): return dict(initial_formation="template5", checking_point=8, path_list=[ [TestAction.create_vm, 'vm1', ], [TestAction.create_volume, 'volume1', 'flag=scsi'], [TestAction.attach_volume, 'vm1', 'volume1'], ...
t1', 'vm1-snapshot6', 'volume1-snapshot6', 'volume2-snapshot6', 'vm1-backup1', 'volume1-backup1', 'volume2-backup1'] attached:['volume1', 'volume2', 'volu
me3'] Detached:[] Deleted:['vm2-snapshot5'] Expunged:[] Ha:[] Group: vm_snap3:['vm1-snapshot6', 'volume1-snapshot6', 'volume2-snapshot6']---vm1volume1_volume2 vm_snap1:['vm1-snapshot1', 'volume1-snapshot1', 'volume2-snapshot1', 'volume3-snapshot1']---vm1volume1_volume2_volume3 vm_backup1:['vm1-backup1', 'volume1-bac...
stratosphereips/Manati
manati/share_modules/whois_distance.py
Python
agpl-3.0
12,100
0.007686
#!/usr/bin/env python # # Copyright (c) 2017 Stratosphere Laboratory. # # This file is part of ManaTI Project # (see <https://stratosphereips.org>). It was created by 'Raul B. Netto <raulbeni@gmail.com>' # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Gene...
if expiration_date_a == expiration_date_a: return float(0) else: return float(1) elif creation_date_a and creation_date_b and not expiration_date_a and not expiration_date_b: if creation_date_a == creation_date_a: return float(0) else: ret...
not creation_date_a or not creation_date_b or not expiration_date_a or not expiration_date_b: return float(1) else: cd_a = get_date_aux(creation_date_a) ed_a = get_date_aux(expiration_date_a) cd_b = get_date_aux(creation_date_b) ed_b = get_date_aux(expiration_date_b) ...
tim-tang/arctic-bear
setup.py
Python
mit
1,115
0
# coding: utf-8 import arctic from
email.utils import parseaddr from setuptools import setup, find_packages kwargs = {} try: from babel.messages import frontend as babel kwargs['cmdclass'] = { 'extract_messages': babel.extract_messages, 'update_catalog': babel.update_catalog, 'compile_catalog': babel.compile_catalog, ...
tml', 'jinja2', { 'extensions': ( 'jinja2.ext.autoescape,' 'jinja2.ext.with_,' 'jinja2.ext.do,' ) }) ] } except ImportError: pass author, author_email = parseaddr(arctic.__author__) setup( name=...
UTSA-ICS/keystone-kerberos
keystone/contrib/revoke/core.py
Python
apache-2.0
9,529
0.000105
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
_id=None): self.revoke( model.RevokeEvent(user_id=user_id, role_id=role_id, domain_id=domain_id, project_id=project_id)) def revoke_by_user_and_project(self, user_id, project_id): self.revoke( ...
roject_id, role_id): self.revoke(model.RevokeEvent(project_id=project_id, role_id=role_id)) def revoke_by_domain_role_assignment(self, domain_id, role_id): self.revoke(model.RevokeEvent(domain_id=domain_id, role_id=role_id)) @cache.on_arguments(should_cache_fn=SHOULD_CACHE, ...
tseaver/google-cloud-python
bigquery/samples/tests/test_table_exists.py
Python
apache-2.0
1,098
0
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
istributed 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. from google.cloud import bigquery from .. import table_exists def test_t...
assert "Table {} is not found.".format(random_table_id) in out table = bigquery.Table(random_table_id) table = client.create_table(table) table_exists.table_exists(client, random_table_id) out, err = capsys.readouterr() assert "Table {} already exists.".format(random_table_id) in out
CompassionCH/compassion-switzerland
partner_communication_switzerland/wizards/child_order_picture.py
Python
agpl-3.0
4,752
0.00021
############################################################################## # # Copyright (C) 2016 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # #####################...
Generate child pictures with white frame and make a downloadable ZIP file or generate a report for printing. :param _print: Set to true for PDF generation instead of ZIP file. :return: Window Action """ sponsorships = self.sponsorship_ids[:NUMBER_LIMIT] if _print: ...
( "partner_communication_switzerland.report_child_picture") res = report.report_action( sponsorships.mapped("child_id.id"), config=False ) else: self.download_data = self._make_zip() res = { "type": "ir.actions.act_w...
psychopy/versions
psychopy/voicekey/signal.py
Python
gpl-3.0
1,069
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """Classes for signals to be sent upon voice-key trip events. """ from __future__ import absolute_import, print_function import threading class _BaseVoiceKeySignal(threading.Thread): """Class to support sending a signal up
on detection of an event. Non-blocking unless you .join() the thread. An adjustable `delay` allows a deferred start. Subclass and override `signal`.
""" def __init__(self, sec=0.010, delay=0, on=1, off=0): super(_BaseVoiceKeySignal, self).__init__(None, 'EventSignal', None) self.sec = sec self.delay = delay self.on = on self.off = off self.running = False # self.daemon = True self.id = None ...
Farthen/OTFBot
otfbot/plugins/ircClient/karma.py
Python
gpl-2.0
7,588
0.002899
# This file is part of OtfBot. # # OtfBot 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. # # OtfBot is distributed in the hope that it...
the GNU General Public License # along with OtfBot; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # # (c) 2007 by Alexander Schier # """ Track the karma of user supplied terms """ from otfbot.lib import chatMod import pickle import os def sorte...
on to return a [(value, key)] list from a dict""" items = [(k, v) for (v, k) in dict.items()] items.reverse() return items class Plugin(chatMod.chatMod): def __init__(self, bot): self.bot = bot self.karmas = {} #channel -> (what -> karma-struct) self.karmapaths = {} #path -> ...
yephper/django
tests/template_tests/filter_tests/test_make_list.py
Python
bsd-3-clause
1,654
0.004232
from django.template.defaultfilters import make_list from django.test import SimpleTestCase from django.test.utils import str_prefix from django.utils.safestring import mark_safe from ..utils import setup class MakeListTests(SimpleTestCase): """ The make_list filter can destroy existing escaping, s...
']")) @setup({'make_list02': '{{ a|make_list }}'}) def test_make_list02(self): output = self.engine.render_to_string('make_list02', {"a": mark_safe(
"&")}) self.assertEqual(output, str_prefix("[%(_)s&#39;&amp;&#39;]")) @setup({'make_list03': '{% autoescape off %}{{ a|make_list|stringformat:"s"|safe }}{% endautoescape %}'}) def test_make_list03(self): output = self.engine.render_to_string('make_list03', {"a": mark_safe("&")}) ...
0ffkilter/StunfiskBot
StunfiskBot.py
Python
mit
15,210
0.007692
import praw, argparse, sys, json, re, os, time, traceback from peewee import * from logins import * from var_dicts import * user_agent = "StunfiskHelperBot v0.1.1 by /u/0ffkilter" reddit = praw.Reddit(user_agent=user_agent) reddit.login(bot_name, bot_password) c_db = MySQLDatabase(database='stunbot', host='localhos...
lt else: return 'No Results Found\n\n' def gen_string(key): string = '* Generation ' + key[0] + ' through ' + learn_types[key[1]] if key[1] == 'l': string = string + ' at Level ' + key[2:] return string def stats_to_string(pokemon): string = '' for stat in stats: string ...
stat + ': ' + str(pokedex[pokemon]['baseStats'][stat]) + '\n\n' return string def get_last_set(sections): for i in range(len(sections)): try: if sections[i].index('Nature') == 0: return i except ValueError: pass return 3 def get_set_names(pokemon):...
cloudkick/libcloud
libcloud/storage/drivers/dummy.py
Python
apache-2.0
14,148
0.00417
# 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 use ...
bytes_used = 0 for container in self._containers: objects = self._containers[container]['objects'] for _, obj in objects.iteritems(): bytes_used += obj.size return { 'container_count': int(container_count), 'object_count': int(object_co...
int(bytes_used) } def list_containers(self): """ >>> driver = DummyStorageDriver('key', 'secret') >>> driver.list_containers() [] >>> container = driver.create_container(container_name='test container 1') >>> container <Container: name=test container 1, provi...
helenwarren/pied-wagtail
wagtail/wagtaildocs/views/documents.py
Python
bsd-3-clause
5,054
0.001979
from django.shortcuts import render, redirect, get_object_or_404 from django.contrib import messages from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.contrib.auth.decorators import permission_required from django.core.exceptions import PermissionDenied from django.utils.translation i...
t, id=document_id) if not doc.is_editable_by_user(request.user): raise PermissionDenied if request.POST: doc.delete() messages.success(request, _("Document '{0}' deleted.").format(doc.title
)) return redirect('wagtaildocs_index') return render(request, "wagtaildocs/documents/confirm_delete.html", { 'document': doc, })
jsilhan/dnf-plugins-extras
tests/test_repoclosure.py
Python
gpl-2.0
3,893
0.002312
# Copyright (C) 2015 Igor Gnatenko # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be us...
pport.command_run(self.c
md, args) self.assertEmpty(stdout.getvalue()) def test_pkg_option(self): args = ["--pkg", "foo"] self.cmd.base.add_remote_rpms([os.path.join(self.path, "noarch/foo-4-6.noarch.rpm")]) with mock.patch("sys.stdout", new_callable=dnf.pycomp.StringIO) as stdout: ...
prospwro/odoo
addons/irsid_edu/models/module_work.py
Python
agpl-3.0
13,057
0.013965
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution Addon # Copyright (C) 2009-2013 IRSID (<http://irsid.ru>), # Paul Korotkov (korotkov.paul@gmail.com). # # This program is free software: you can redistribute it...
related = 'time.stage', string = 'Stage', reado
nly = True, store = True, ) section = fields.Many2one( related = 'time.section', string = 'Section', readonly = True, store = True, ) subsection = fields.Many2one( related = 'time.subsection', string = 'Subsection', readonly = True, ...
google/pigweed
pw_build_mcuxpresso/py/pw_build_mcuxpresso/__main__.py
Python
apache-2.0
1,865
0
#!/usr/bin/env python3 # Copyright 2021 The Pigweed Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
required=True) project_parser = subparsers.add_parser( 'project', help='output components of an MCUXpresso project') project_parser.add_argument('manifest_filename', type=pathlib.Path) project_parser.add_argument('--include', type=str, action='append') project_parser.add_argument('--ex...
arser.parse_args() def main(): """Main command line function.""" args = _parse_args() if args.command == 'project': components.project(args.manifest_filename, include=args.include, exclude=args.exclude, path_prefix=a...
IronSlayer/bladeRF-Rpi2
bladeRF_transceiver1.py
Python
gpl-3.0
12,438
0.004181
#!/usr/bin/env python2 ################################################## # GNU Radio Python Flow Graph # Title: bladeRF_transceiver # Author: Renzo Chan Rios # Generated: Sun Mar 13 00:27:54 2016 ################################################## from gnuradio import analog from gnuradio import blocks from gnuradio i...
elf, symbole_rate): self.symbole_rate = symbole_rate self.set_samp_per_sym(int(self.samp_rate / self.symbole_rate)) self.set_samp_per_sym_source(((self.samp_rate/2/self.firdes_decim)*self.rat_interop/self.rat_decim) / self.symbole_rate) def get_samp_rate(sel
f): return self.samp_rate def set_samp_rate(self, samp_rate): self.samp_rate = samp_rate self.set_firdes_filter(firdes.low_pass(1,self.samp_rate/2, self.firdes_cuttoff, self.firdes_transition_width)) self.set_samp_per_sym(int(self.samp_rate / self.symbole_rate)) self.set_sam...
WebArchivCZ/Seeder
Seeder/www/urls.py
Python
mit
3,183
0.002199
from django.urls import path, re_path, include from django.utils.translation import ugettext_lazy as _ from . import views as www urlpatterns = [ re_path(r'^$', www.Index.as_view(), name='index'), re_path(_('^topic_collections_url$'), www.TopicCollections.as_view(), name='topic_collections'), r...
www.SubCategoryDetail.as_view(), name='sub_category_detail'), re_path(_('^change_list_view/(?P<list_type>visual|text)$'), www.ChangeListView.as_view(), name='change_list_view'), re_path(_('^keyword_url/(?P<slug>[\w-]+)$'), www.KeywordViews.as_view(), ...
rectView.as_view(), name='search_redirect'), re_path(_('^search_url/(?P<query>.*)'), www.SearchView.as_view(), name='search'), re_path(_('^www_source_url/(?P<slug>[\w-]+)$'), www.SourceDetail.as_view(), name='source_detail'), re_path(_('^www_nominate_url$'),...
dardevelin/rhythmbox-gnome-fork
plugins/lyrics/WinampcnParser.py
Python
gpl-2.0
3,373
0.024311
# -
*- Mode: python; coding: utf-8; tab-width: 8; indent-tabs-mode: t; -*- # # Copyright (C) 2007 Austin <austiny@sohu.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either v
ersion 2, or (at your option) # any later version. # # The Rhythmbox authors hereby grant permission for non-GPL compatible # GStreamer plugins to be used and distributed together with GStreamer # and Rhythmbox. This permission is above and beyond the permissions granted # by the GPL license by which Rhythmbox is cover...
modulo-/knoydart
api/api_0/apiRequest/Welcome.py
Python
apache-2.0
153
0
from
flask.ext import restful from . import api class W
elcome(restful.Resource): def get(self): return api.send_static_file('index.html')
YilunZhou/Klampt
Python/klampt/src/rootfind.py
Python
bsd-3-clause
3,866
0.016296
# This file was automatically generated by SWIG (http://www.swig.org). # Version 2.0.12 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. """ Python interface to KrisLibrary nonlinear, multidimensional root finding routines """ from sys import versi...
Same as findRoots, but with given bounds (xmin,xmax) """ return _rootfind.findRootsBounded(*args) def destroy(): """ destroy() destroys internal data structures destroys internal
data structures """ return _rootfind.destroy() # This file is compatible with both classic and new-style classes.
sander76/home-assistant
homeassistant/components/dte_energy_bridge/sensor.py
Python
apache-2.0
3,635
0.00055
"""Support for monitoring energy usage using the DTE energy bridge.""" import logging import requests import voluptuous as vol from homeassistant.components.sensor import ( PLATFORM_SCHEMA, STATE_CLASS_MEASUREMENT, SensorEntity, ) from homeassistant.const import CONF_NAME, HTTP_OK import homeassistant.hel...
) class DteEnergyBridgeSensor(SensorEntity): """Implementation of the DTE Energy Bridge sensors.""" _attr_state_class = STATE_CLASS_MEASUREMENT def __init__(self, ip_address, name, version): """Initialize the sensor.""" self._version = version if self._version == 1:
self._url = f"http://{ip_address}/instantaneousdemand" elif self._version == 2: self._url = f"http://{ip_address}:8888/zigbee/se/instantaneousdemand" self._name = name self._unit_of_measurement = "kW" self._state = None @property def name(self): """Retu...
himanshuo/osf.io
website/project/views/comment.py
Python
apache-2.0
8,683
0.000461
# -*- coding: utf-8 -*- import collections import httplib as http import pytz from flask import request from modularodm import Q from framework.exceptions import HTTPError from framework.auth.decorators import must_be_logged_in from framework.auth.utils import privacy_info_handle from framework.forms.utils import san...
alse): return [ serialize_comment(comment, auth, anonymous) for comment in getattr(record, 'commented', [])
] def kwargs_to_comment(kwargs, owner=False): comment = Comment.load(kwargs.get('cid')) if comment is None: raise HTTPError(http.BAD_REQUEST) if owner: auth = kwargs['auth'] if auth.user != comment.user: raise HTTPError(http.FORBIDDEN) return comment @must...
alexandrucoman/vbox-nova-driver
nova/utils.py
Python
apache-2.0
42,459
0.000377
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance wi...
tance admin passwords'), cfg.StrOpt('instance_usage_audit_period', default='month', help='Time period to generate instance usages for. ' 'Time period must be hour, day, month or year'), cfg.StrOpt('rootwrap_config', default="/etc/nova/rootwrap.co...
pt('tempdir', help='Explicitly specify the temporary working directory'), ] """ This group is for very specific reasons. If you're: - Working around an issue in a system tool (e.g. libvirt or qemu) where the fix is in flight/discussed in that community. - The tool can be/is fixed in some distribution...
cipriancraciun/extremely-simple-cluster-platform
components/py-messaging/sources/escp/messaging/rpc_testing.py
Python
gpl-3.0
2,789
0.062029
import Queue as queue import escp.messaging.rpc as rpc import escp.messaging.wrappers as wrappers import escp.tools.testing as testing from escp.messaging.wrappers_testing import _construct_wrapper @testing.fixture def needs_rpc_client (_test, member = 'client', session = 'session', callback_agent = None, callbac...
get = 'target', coder = 'coder', auto_initialize = True, auto_finalize = None) : return _needs_echo_server (_test, rpc.TargetServer, member, session, agent, target, coder, auto_in
itialize, auto_finalize) @testing.fixture def needs_port_echo_rpc_server (_test, member = 'server', session = 'session', agent = 'agent', port = 'port', coder = 'coder', auto_initialize = True, auto_finalize = None) : return _needs_echo_server (_test, rpc.PortServer, member, session, agent, port, coder, auto_initi...
MakarenaLabs/Orator-Google-App-Engine
orator/query/processors/sqlite_processor.py
Python
mit
424
0
# -*- coding: utf-8 -*- from .processor import QueryProcessor class SQLiteQueryProcessor(QueryProcessor): def process_column_listing(self, results): """ Process the results of a column listing query :param results: The query results :type results: dict :return:
The processed results :return: dict """ return map(lambda x: x['column_name'], results)
car3oon/saleor
saleor/site/models.py
Python
bsd-3-clause
811
0
from django.contrib.sites.models import _simple_domain_name_validator from django.db import models from django.utils.translation import pgettext_lazy from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class SiteSettings(models.Model): domain = models.CharField( pget...
ength=100, validators=[_simple_domain_name_validator], unique=True) name = models.CharField(pgettext_lazy('Site field', 'name'), max_length=50) header_text = models.CharField( pgettext_lazy('Site field', 'header text'), max_length=200, blank=True) description = models.CharField( pge...
gth=500, blank=True) def __str__(self): return self.name
Frostman/eho-horizon
openstack_dashboard/dashboards/project/routers/urls.py
Python
apache-2.0
1,319
0.000758
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012, Nachi Ueno, NTT MCL, 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...
import (AddInterfaceView, SetGatewayView) urlpatterns = patterns('horizon.dashboards.project.routers.views', url(r'^$', IndexView.as_view(), name='index'), url(r'^create/$', CreateView.as_view(), name='create'), url(r'^(?P<router_id>[^/]+)/$', DetailView.as_view(), name='detail'), url...
ace', AddInterfaceView.as_view(), name='addinterface'), url(r'^(?P<router_id>[^/]+)/setgateway', SetGatewayView.as_view(), name='setgateway'), )
aaschaer/globus-sdk-python
globus_sdk/transfer/response/base.py
Python
apache-2.0
407
0
import json from globus_sdk.response import GlobusHTTPResponse class TransferResponse(GlobusHTTPResponse): """ Base class for :class:`T
ransferClient <globus_sdk.TransferClient>` responses. """ def __str__(self): # Make printing responses more convenient. Relies on the # fact that Transf
er API responses are always JSON. return json.dumps(self.data, indent=2)
Guitar-Machine-Learning-Group/guitar-transcriber
dataset.py
Python
mit
2,586
0.001547
import os import numpy as np class Dataset(object): """ This class represents a dataset and consists of a list of SongData along with some metadata about the dataset """ def __init__(self, songs_data=None): if songs_data is None: self.songs_data = [] else: self...
elf.__x @x.setter def x(self, x): self.__x = x """ X [num_frames x num_features] is the feature matrix for t
he song """ @property def X(self): return self.__X @X.setter def X(self, X): if hasattr(self, 'Y') and self.Y.shape[0] != X.shape[0]: raise ValueError("Number of feature frames must equal number of label frames") self.__X = X """ Y [num_frames x num_pitc...
snava10/sqlRunner
websqlrunner/websqlrunner/wsgi.py
Python
apache-2.0
402
0
""" WSGI config for websqlrunner project. It exposes the WSGI callable as a module-le
vel variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi
_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "websqlrunner.settings") application = get_wsgi_application()
Gentux/etalage
etalage/__init__.py
Python
agpl-3.0
990
0
# -*- coding: utf-8 -*- # Etalage -- Open Data POIs portal # By: Emmanuel Raviart <eraviart@easter-eggs.com> # # Copyright (C) 2011, 2012 Easter-eggs # http://gitorious.org/infos-pratiques/etalage # # This file is part of Etalage. # # Etalage is free software; you can redistribute it and/or modify # it under the term...
>. """Web services for territories""" conf = {} # Dictionary updated by con
fig.environment.load_environment
richardliaw/ray
python/ray/tests/test_reference_counting_2.py
Python
apache-2.0
11,196
0
# coding: utf-8 import logging import os import signal import sys import numpy as np import pytest import ray import ray.cluster_utils from ray.test_utils import SignalActor, put_object, wait_for_condition SIGKILL = signal.SIGKILL if sys.platform != "win32" else signal.SIGTERM logger = logging.getLogger(__name__) ...
_condition( lambda: ray.worker.global_worker.core_worker.object_exists(obj)) else: wait_for_condition( lambda: not ray.worker.global_worker.core_worker.object_exists(obj) ) # Test t
hat an object containing object refs within it pins the inner IDs # recursively and for submitted tasks. @pytest.mark.parametrize("use_ray_put,failure", [(False, False), (False, True), (True, False), (True, True)]) def test_recursively_nest_ids(one_worker_100MiB, use_ray...
sdague/home-assistant
homeassistant/components/environment_canada/weather.py
Python
apache-2.0
8,104
0.000494
"""Platform for retrieving meteorological data from Environment Canada.""" import datetime import re from env_canada import ECData # pylint: disable=import-error import voluptuous as vol from homeassistant.components.weather import ( ATTR_FORECAST_CONDITION, ATTR_FORECAST_PRECIPITATION_PROBABILITY, ATTR_...
st(self): """Return the forecast array.""" return get_forecast(self.ec_data, self.forecast_type) def update(self):
"""Get the latest data from Environment Canada.""" self.ec_data.update() def get_forecast(ec_data, forecast_type): """Build the forecast array.""" forecast_array = [] if forecast_type == "daily": half_days = ec_data.daily_forecasts if half_days[0]["temperature_class"] == "...
pyspace/test
pySPACE/missions/nodes/splitter/all_train_splitter.py
Python
gpl-3.0
2,977
0.011085
""" Use all available data for training """ import itertools import log
ging from pySPACE.missions.nodes.base_node import BaseNode class AllTrainSplitterNode(BaseNode): """ Use all available data for training This node allows subsequent nodes to use all available labeled data for trai
ning. Accordingly, no data for testing is provided. **Parameters** **Exemplary Call** .. code-block:: yaml - node : All_Train_Splitter :Author: Jan Hendrik Metzen (jhm@informatik.uni-bremen.de) :Created: 2009/01/07 """ def __init__(self, non_pers...
sio2project/oioioi
oioioi/exportszu/utils.py
Python
gpl-3.0
6,333
0.000474
import csv import os import shutil import tarfile import tempfile from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.db.models import Q from django.utils.encoding import force_text from oioioi.filetracker.client import get_client from oioioi.filetracker.utils import dja...
oblem_short_name, s.score, ] def encode(obj): if obj is None: return 'NULL' else: return force_text(obj) index_csv.writerow([encode(col) for col in index_entry]) ...
s.submission_id, s.username, s.problem_short_name, s.solution_language, ) dest = os.path.join(files_dir, filename) submission_collector.get_submission_source(dest, s.source_file) with tarfile.open(fileobj=out_fil...
krull/docker-zenoss4
init_fs/usr/local/zenoss/ZenPacks/ZenPacks.zenoss.ZenJMX-3.12.1.egg/ZenPacks/zenoss/ZenJMX/tests/test_JMXDataSource.py
Python
gpl-3.0
960
0.001042
#####################################################
######################### # # Copyright (C) Zenoss, Inc. 2015, all rights reserved. # # This content is made available according to terms specified in # License.zenoss under the direc
tory where your Zenoss product is installed. # ############################################################################## from Products.ZenTestCase.BaseTestCase import BaseTestCase from ZenPacks.zenoss.ZenJMX.datasources.JMXDataSource import JMXDataSource class TestJMXDataSource(BaseTestCase): def afterSet...
jorisvandenbossche/DS-python-data-analysis
notebooks/_solutions/pandas_03a_selecting_data2.py
Python
bsd-3-clause
19
0.052632
m
ales['A
ge'].mean()
ChopChopKodi/pelisalacarta
python/main-classic/channels/peliculasaudiolatino.py
Python
gpl-3.0
9,331
0.013631
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Canal para peliculasaudiolatino # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import re import sys import urlparse from core im...
s.html", viewmode="movie")) itemlist.append( Item
(channel=item.channel, title="Recién actualizadas", action="peliculas", url="http://peliculasaudiolatino.com/recien-actualizadas.html", viewmode="movie")) itemlist.append( Item(channel=item.channel, title="Las más vistas", action="peliculas", url="http://peliculasaudiolatino.com/las-mas-vistas.html", viewmode="movi...
molly/GorillaBot
gorillabot/bot.py
Python
mit
16,845
0.003443
#!/usr/bin/env python3 # # Copyright (c) 2013-2016 Molly White # # 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, mod...
if type(msg) is Numeric: if msg.number == '311': # User info line = msg.body.split() botops
.update({op: {"user": line[1], "host": line[2]}}) self.logger.info( "Adding {0} {1} to bot ops".format(line[1], line[2],)) break elif msg.number == '318': # End of WHOIS ...
Kotzyk/Projekt-Blackjack
blackjack.py
Python
gpl-3.0
25,701
0.004655
""" Program do gry w Blackjack (a.k.a. Oczko) w języku Python przy użyciu biblioteki PyGame Projekt zaliczeniowy - Języki Skryptowe, Informatyka i Ekonometria, rok 1, WZ, AGH Autorzy: Joanna Jeziorek, Mateusz Koziestański, Katarzyna Maciocha III 2016 """ import random as rd import os import sys import pygame from pygam...
_deck.append(player_hand[-1]) return deck, played_deck, player_hand, dealer_hand def hit(deck, played_deck, hand): # Jeśli talia nie jest pusta,
daje graczowi kartę do ręki. if len(deck) < 2: deck, played_deck = return_played(deck, played_deck) hand.append(deck.pop(0)) played_deck.append(hand[-1]) return deck, played_deck, hand def value(hand): # Oblicza wartość kart w ręce. # Jeśli w ręce znajduje się as, a wartość przekracz...
gmarkall/COFFEE
doc/source/conf.py
Python
bsd-3-clause
7,963
0.006405
# -*- coding: utf-8 -*- # # COFFEE documentation build configuration file, created by # sphinx-quickstart on Tue Sep 30 11:25:59 2014. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All ...
ames. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to
# template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added...
youtube/cobalt
third_party/web_platform_tests/tools/html5lib/html5lib/tests/test_tokenizer.py
Python
bsd-3-clause
6,544
0.000458
from __future__ import absolute_import, division, unicode_literals import json import warnings import re from .support import get_data_files from html5lib.tokenizer import HTMLTokenizer from html5lib import constants class TokenizerTestParser(object): def __init__(self, initialState, lastStartTag=None): ...
len(token) == 4 or token[0] == "EndTag" and len(token) == 3): checkSelfClosing = True break if not checkSelfClosing: for token in receivedTokens: if token[0] == "StartTag" or token[0] == "EndTag": token.pop() if not ignoreErrorOrder ...
edTokens else: # Sort the tokens into two groups; non-parse errors and parse errors tokens = {"expected": [[], []], "received": [[], []]} for tokenType, tokenList in zip(list(tokens.keys()), (expectedTokens, receivedTokens)): for token in t...
madhurrajn/samashthi
startnow/request_processor.py
Python
bsd-3-clause
3,842
0.002603
import logging import simplejson import urllib
2 import datetime import urlparse from deploy import DEPLOY_STATUS from google.appengine.api import urlfetch import g
requests logging.basicConfig() logger = logging.getLogger(__name__) class RequestProcessor: def __init__(self, url_list): self.url_list = url_list self.duration_list = [] self.result = [] def process_atomic_request(self, (atime, url)): response = simplejson.load(urllib2.urlope...
eshijia/magnum
magnum/conductor/template_definition.py
Python
apache-2.0
21,199
0.000047
# Copyright 2014 Rackspace 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 ...
'swarm.yaml'), help=_('Location of template to build a swarm ' 'cluster on atomic.')), cfg.StrOpt('swarm_discovery_url_format', default=None, help=_('Format string
to use for swarm discovery url. ' 'Available values: bay_id, bay_uuid. ' 'Example: "etcd://etcd.example.com/\%(bay_uuid)s"')), cfg.BoolOpt('public_swarm_discovery', default=True, help=_('Indicates Swarm discovery should use public ' ...
chapel-lang/pychapel
module/ext/src/chapel/muahaha.py
Python
apache-2.0
444
0.011261
#!
/usr/bin/env python from __future__ import print_function import ctypes def main(): chpl = ctypes.cdll.LoadLibrary("chapel.so") chpl.chpl_library_init.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_char_p)] argv=(ctypes.c_char_p
*1)() argv[0] = "chapel" chpl.chpl_library_init(0, argv) print(chpl.nicestuff(1000, 1000, 20)) chpl.chpl_library_finalize() return chpl if __name__ == "__main__": main()
yanheven/ali-opensearch-sdk
opensearchsdk/tests/v2/test_search.py
Python
apache-2.0
1,190
0
import mock from opensearchsdk.apiclient.api_base import Manager from opensearchsdk.tests import base from opense
archsdk.v2.search import SearchManager class AppTest(base.TestCase): def setUp(self): super(AppTest, self).setUp() self.search_manager = SearchManager('', '') mock_send = mock.Mock() Manager.send_get = Manager.send_post = mock_send def test_search(self): # simple searc
h self.search_manager.search('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') body = dict(query='a', index_name='b', fetch_fields='c', qp='d', disable='e', first_formula_name='f', formula_name='g', summary='h') Manager.send_get.assert_called_with(body) # f...
iffy/norm
setup.py
Python
mit
737
0.006784
# Copyright (c) Matt Haggard. # See LICENSE for details. from distutils.core import setup import os, re def getVersion(): r_version = re.compile(r"__version__\s*=\s*'(.*?)'") base_init = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'norm/__init__.py') guts = open(base_init, 'r').read() m ...
author='Matt Haggard', author_email='haggardii@gmail.com', name='norm', version=getVersion(), packag
es=[ 'norm', 'norm.test', 'norm.orm', 'norm.orm.test', ], requires = [ 'Twisted', ] )
mmichie/luckystrike
luckystrike/util.py
Python
mit
1,107
0.009033
import config import random import re import string import sys import traceback from twisted.python import log
def generate_password(length = 12): """ Generate a random password, ASCII letters + digits only, default length 12 """ return ''.join(random.choice(string
.ascii_letters + string.digits) for _ in range(length)) def campNameToString(name): """ Translate Campfire String to one renderable on IRC for nicknames, or channels """ return re.sub('\s+', '_', name).lower() def channel_to_room(channel): """ Given an IRC channel, return a Campfire room objec...
avrong/timeago
setup.py
Python
mit
1,607
0.018738
# -*- coding: utf-8 -*- from distutils.core import setup from setuptools import find_packages LONGDOC = """ A very simple python library, used to format datetime with *** time ago statement. Install pip install timeago Usage import timeago, datetime d = datetime.datetime.now() + datetime.timedelta(seconds = 60...
ng Language :: Python :: 2', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Utilities' ], keywords = 'timeago, seconds ago, minutes ago, hours ago, just now', packages = find_packages('src'), package_dir = {'':'src'...
Return0Software/Flix-with-Friends
src/gtk-gui/SearchBar.py
Python
gpl-2.0
11,298
0.002655
import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk, GObject import random import re import datetime class GenrePop(Gtk.Popover): """Creates a popover to filter by genre""" __gsignals__ = { "genres-updated": (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE, (object,)) } def...
tr(x)) x -= 1 self.combo.set_active(datetime.datetime.now().year - db.oldest_year) label = Gtk.Label(label="Search for movies produced\nonly in the year above", justify=Gtk.Justification.CENTER) switchBox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, sp...
x(orientation=Gtk.Orientation.VERTICAL, margin=5, spacing=5) dateBox.add(self.combo) dateBox.add(switchBox) self.add(dateBox) def switch_cb(self, switch, state): self.emit("switch-updated", state) def combo_cb(self, combo): self.emit("year-updated", combo.get_active_te...
inveniosoftware/invenio-theme
invenio_theme/views.py
Python
mit
1,481
0
# -*- coding:
utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Invenio error handlers.""" from __future__ import absolute_import, print_function from flask i...
__ ) @blueprint.route('/') def index(): """Simplistic front page view.""" return render_template( current_app.config['THEME_FRONTPAGE_TEMPLATE'], ) def unauthorized(e): """Error handler to show a 401.html page in case of a 401 error.""" return render_template(current_app.config['THEME_40...
kg-bot/SupyBot
plugins/Holdem/config.py
Python
gpl-3.0
2,352
0.000425
### # Copyright (c) 2005, Jeremy Kelley # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions...
# derived from this software without specific prior written consent. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIM...
IMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED O...
nkremerh/cctools
resource_monitor/src/bindings/python3/example_simple_limit.py
Python
gpl-2.0
791
0.010114
import resource_monitor import sys import time @resource_monitor.monitored(limits = {'wall_time': 1e6}) # wall_time in microseconds def my_function(n): sys.stdout.write("waiting for {time} seconds...".format(time=n)) time.sleep(n) sys.stdout.write("done.\n") return n try: (output, resources) = ...
ResourceExh
austion as e: sys.stdout.write("\nGot expected exception <{err}>.\n".format(err=e)) except Exception as e: sys.stdout.write("\nGot exception <{err}>, but did not expect such error.\n".format(err=e)) sys.exit(1) sys.exit(0)
electricity345/community.csdt
src/community_csdt/community_csdt/src/models/pages/page.py
Python
mit
374
0.005348
import json import logging from community_csdt.src.models import database class Page(object): def __init__(self, parent, name): self.__parent__ = parent self.__name__ = name def __getitem__(self, key): log = logging.getLogger('csdt')
log.info("Page.__getitem__()")
log.debug("key = %s" % key) raise KeyError