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 |
|---|---|---|---|---|---|---|---|---|
roninek/python101 | docs/pygame/life/code1a.py | Python | mit | 5,039 | 0.001628 | # coding=utf-8
import pygame
import pygame.locals
class Board(object):
"""
Plansza do gry. Odpowiada za rysowanie okna gry.
"""
def __init__(self, width, height):
"""
Konstruktor planszy do gry. Przygotowuje okienko gry.
:param width: szerokość w pikselach
... | _size)
position = (x * self.box_size, y * self.box_size)
color = (255, 255, 255)
thickness = 1
pygame.draw.rect(surface, color, pygame.locals.Rect(pos | ition, size), thickness)
def alive_cells(self):
"""
Generator zwracający współrzędne żywych komórek.
"""
for x in range(len(self.generation)):
column = self.generation[x]
for y in range(len(column)):
if column[y] == ALIVE:
# jeśli komórka jest żywa ... |
getsentry/zeus | zeus/migrations/340d5cc7e806_index_artifacts.py | Python | apache-2.0 | 705 | 0.001418 | """index_artifacts
Revision ID: 340d5cc7e806
Revises: af3f4bdc27d1
Create Date: 2019-08-09 12:37:50.706914
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "340d5cc7e806"
down_revision = "af3f4bdc27d1"
branch_labels = ()
depends_on = None
def upgrade():
# ... | ated by Alembic - please adjust! ###
op.drop_index(" | idx_artifact_job", table_name="artifact")
# ### end Alembic commands ###
|
myt00seven/svrg | para_gpu/tools.py | Python | mit | 2,391 | 0.000836 | import os
import numpy as np
def save_weights(layers, weights_dir, epoch):
for idx in range(len(layers)):
if hasattr(layers[idx], 'W'):
layers[idx].W.save_weight(
weights_dir, 'W' + '_' + str(idx) + '_' + str(epoch))
if hasattr(layers[idx], 'W0'):
layers[id... | weights_dir, 'b' + '_' + str(idx) + '_' + str(epoch))
| if hasattr(layers[idx], 'b0'):
layers[idx].b0.save_weight(
weights_dir, 'b0' + '_' + str(idx) + '_' + str(epoch))
if hasattr(layers[idx], 'b1'):
layers[idx].b1.save_weight(
weights_dir, 'b1' + '_' + str(idx) + '_' + str(epoch))
def load_weights(layers,... |
gusDuarte/software-center-5.2 | softwarecenter/ui/gtk3/review_gui_helper.py | Python | lgpl-3.0 | 55,851 | 0.00222 | # -*- coding: utf-8 -*-
# Copyright (C) 2009 Canonical
#
# Authors:
# Michael Vogt
#
# 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; version 3.
#
# This program is distributed in the hope that... | r"
class GRatingsAndReviews(GObject.GObject):
""" Access ratings&reviews API as a gobject """
__gsignals__ = {
# send when a transmit is started
"transmit-start": (GObject.SIGNAL_RUN_LAST,
GObject.TYPE_NONE,
(GObject.TYPE_PYOBJECT, ),
... | AST,
GObject.TYPE_NONE,
(GObject.TYPE_PYOBJECT, ),
),
# send when a transmit failed
"transmit-failure": (GObject.SIGNAL_RUN_LAST,
GObject.TYPE_NONE,
(GObject.T... |
lgritz/OpenShadingLanguage | testsuite/regex-reg/run.py | Python | bsd-3-clause | 2,682 | 0.011186 | #!/usr/bin/env python
# Copyright Contributors to the Open Shading Language project.
# SPDX-License-Identifier: B | SD-3-Clause
# https://github.com/AcademySoftwareFoundation/OpenShadingLanguage
######################
#Uniform result
# | #########################
#Uniform subject, uniform pattern#
command += testshade("-t 1 -g 64 64 -od uint8 u_subj_u_pattern -o cout uu_out.tif")
#Uniform subject, varying pattern#
command += testshade("-t 1 -g 64 64 -od uint8 u_subj_v_pattern -o cout uv_out.tif")
#Varying subject, uniform pattern#
command += testsha... |
piksels-and-lines-orchestra/inkscape | share/extensions/grid_cartesian.py | Python | gpl-2.0 | 14,264 | 0.01998 | #!/usr/bin/env python
'''
Copyright (C) 2007 John Beard john.j.beard@gmail.com
##This extension allows you to draw a Cartesian grid in Inkscape.
##There is a wide range of options including subdivision, subsubdivions
## and logarithmic scales. Custom line widths are also possible.
##All elements are grouped with simi... | eral Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
'''
import inkex
import simplestyle, sys
from math import *
def draw_SVG_line(x... | roke': '#000000', 'stroke-width':str(width), 'fill': 'none' }
line_attribs = {'style':simplestyle.formatStyle(style),
inkex.addNS('label','inkscape'):name,
'd':'M '+str(x1)+','+str(y1)+' L '+str(x2)+','+str(y2)}
inkex.etree.SubElement(parent, inkex.addNS('path','svg'), li... |
slashdd/sos | sos/report/plugins/docker_distribution.py | Python | gpl-2.0 | 1,334 | 0 | # Copyright (C) 2017 Red Hat, Inc. Jake Hunsaker <jhunsake@redhat.com>
# 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 for further information.
from sos.report.plugins import Plugin, RedHat | Plugin
class DockerDistribution(Plugin):
short_desc = 'Docker Distribution'
plugin_name = "docker_distribution"
profiles = ('container',)
def setup(self):
self.add_copy_spec('/etc/docker-distribution/')
self.add_journal('docker-distribution')
conf = self.path_join('/etc/docke... |
KingSpork/sporklib | algorithms/binarySearch.py | Python | unlicense | 670 | 0.055224 | def binarySearch(someList, target):
lo = 0
hi = len(someList)
while lo+1 < hi:
test = (lo + hi) / 2
if someList[test] > target:
hi = test
else:
lo = test
if someList[lo] == target:
return lo
else:
return -1
import random
def quickSort(someList):
listSize = len(someList)
... | listSize-1))
for element in someList:
if element <= pivot:
less.append(element)
else:
greater.append(element)
retList = quickSort(less) + [pivot] + quickSort(greater)
#print("Return list:");print(retList)
return re | tList |
danieka/churchplanner | planner/functional_tests.py | Python | gpl-3.0 | 1,831 | 0.03337 | from selenium import webdriver
from django.test import LiveServerTestCase, TestCase
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
import datetime
from planner.models import Participation, Event, Occurrence, EventType, Role
from django.contrib.auth.models import User
import pytz
import time
tz ... | time.sleep(10)
print(t)
assert 'Testevenemang' in t
if __name__ | == '__main__':
unittest.main() |
Falkonry/falkonry-python-client | test/TestDatastream.py | Python | mit | 35,686 | 0.00737 | import os
import unittest
import random
import xmlrunner
host = os.environ['FALKONRY_HOST_URL'] # host url
token = os.environ['FALKONRY_TOKEN'] # auth token
class TestDatastream(unittest.TestCase):
def setUp(self):
self.created_datastreams = []
self.fclient = FClient(host=host, token=token... | gnal.get_valueIdentifier(), 'Invalid value identifier after object creation')
self.assertEqual(signalResponse.get_signalIdentifier(), signal.get_signalIdentifier(), 'Invalid signal identifier after object creation')
timeResponse = fieldResponse.get_time()
self.assertEqual(isinstance(... | chemas.Time), True, 'Invalid time object after creation')
|
pelgoros/kwyjibo | kwyjibo/views.py | Python | gpl-3.0 | 4,918 | 0.005696 |
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
from django.http import HttpResponseForbidden
from django.shortcuts import redirect, render
from django.views.generic import View
from django.views.generic.b... | a['password'])
user.save()
else:
bad_password = True
return render(request, 'registration/change_password.html', {
'form': form,
'bad_password': bad_password
})
login(request, user)
... | {'form': form, })
def logout_page(request):
"""
Log users out and re-direct them to the main page.
"""
logout(request)
return redirect('index')
|
acsone/Arelle | arelle/plugin/validate/ESEF/Const.py | Python | apache-2.0 | 19,152 | 0.00282 | '''
Created on June 6, 2018
Filer Guidelines: esma32-60-254_esef_reporting_manual.pdf
@author: Workiva
(c) Copyright 2022 Workiva, All rights reserved.
'''
try:
import regex as re
except ImportError:
import re
from arelle.ModelValue import qname
from arelle.XbrlConst import all, notAll, hypercubeDimension,... | full_ifrs-cor_[0-9-]{10}[.]xsd|"
"http://www.esma.europa.eu/taxonomy/[0-9-] | {10}/esef_all.xsd"
)
DefaultDimensionLinkroles = ("http://www.esma.europa.eu/xbrl/role/cor/ifrs-dim_role-990000",)
LineItemsNotQualifiedLinkrole = "http://www.esma.europa.eu/xbrl/role/cor/esef_role-999999"
qnDomainItemTypes = {qname("{http://www.xbrl.org/dtr/type/non-numeric}nonnum:domainItemType"),
... |
RUB-NDS/PRET | helper.py | Python | gpl-2.0 | 21,528 | 0.019595 | #!/usr/bin/env python3
# -*- co | ding: utf-8 -*-
from __future__ import print_function
# python standard library
from socket import socket
import sys, os, re, stat, math, time, datetime
import importlib
# third party modules
try: # unicode monkeypatch for win | doze
import win_unicode_console
win_unicode_console.enable()
except:
msg = "Please install the 'win_unicode_console' module."
if os.name == 'nt': print(msg)
try: # os independent color support
from colorama import init, Fore, Back, Style
init() # required to get colors on windoze
except ImportError:
msg ... |
Markcial/salty | salty/api.py | Python | mit | 1,918 | 0.000521 | import nacl.exceptions
import nacl.utils
import nacl.secret
from salty.config import encoder, Store
from salty.exceptions import NoValidKeyFound, DefaultKeyNotSet
__all__ = ['new', 'current', 'select', 'add_secret', 'get_secret', 'encrypt', 'decrypt']
def _new():
return encoder.encode(nacl.utils.random(nacl.se... | key).decrypt(name, encoder=encoder)
store = Store(default_key=_new().decode())
# public api
def new():
return _new()
def current(key=None):
if key is None:
return store.current
store.add_key(bytes(key, 'utf8'), current=True)
return | True
def select(pos):
store.set_current(pos)
return True
def add_secret(name, raw):
msg = _encrypt(bytes(raw, 'utf8'), bytes(store.current, 'utf8'))
store.add_secret(name, msg)
return True
def get_secret(name):
msg = store.get_secret(name)
return _decrypt(bytes(msg, 'utf8'))
def ... |
Yelp/pootle | pootle/apps/pootle_store/migrations/0001_initial.py | Python | gpl-3.0 | 7,129 | 0.005611 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
import translate.storage.base
import pootle_store.fields
import pootle.core.mixins.treeitem
import pootle.core.storage
from django.conf import settings
class ... | , editable=False, to='pootle_translationproject.TranslationProject')),
],
options={
'ordering': ['pootle_path'],
},
bases=(models.Model, pootle.core.mixins.treeitem.CachedTreeItem, translate.storage.base.TranslationStore),
),
migrations.Run... | ',
name='pootle_path',
field=models.CharField(unique=True, max_length=255, verbose_name='Path', db_index=True)
),
migrations.CreateModel(
name='Unit',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, p... |
iLoop2/ResInsight | ThirdParty/Ert/devel/python/python/ert/enkf/summary_key_matcher.py | Python | gpl-3.0 | 1,882 | 0.007439 | from ert.cwrap import CWrapper, BaseCClass
from ert.enkf import ENKF_LIB
from ert.util import StringList
class SummaryKeyMatcher(BaseCClass):
def __init__(self):
c_ptr = SummaryKeyMatcher.cNamespace().alloc()
super(SummaryKeyMatcher, self).__init__(c_ptr)
def addSummaryKey(self, key):
... | ree = cwrapper.prototype("void summary_key_matcher_free(summary_key_matcher)")
SummaryKeyMatcher.cNamespace().size = cwrapper.prototype("int summary_key_matcher_get_size(summary_key_matcher)")
SummaryKeyMatcher.cNamespace().add_key = cwrapper.prototype("void summary_key_matcher_add_summary_key(summary_key_matcher, c... | yMatcher.cNamespace().keys = cwrapper.prototype("stringlist_obj summary_key_matcher_get_keys(summary_key_matcher)")
SummaryKeyMatcher.cNamespace().is_required = cwrapper.prototype("bool summary_key_matcher_summary_key_is_required(summary_key_matcher, char*)")
|
ledtvavs/repository.ledtv | script.tvguide.Vader/resources/lib/dateutil/rrule.py | Python | gpl-3.0 | 64,642 | 0.000155 | # -*- coding: utf-8 -*-
"""
The rrule module offers a small, complete, and very fast, implementation of
the recurrence rules documented in the
`iCalendar RFC <https://tools.ietf.org/html/rfc5545>`_,
including support for caching of results.
"""
import itertools
import datetime
import calendar
import re
import sys
try:... | =None):
if n == 0:
raise ValueError("Can't create weekday with n==0")
super(weekday, self).__init__(wkday, n)
MO, TU, WE, TH, FR, SA, SU = weekdays = tuple(weekday(x) for x in range(7))
def _invalidates_cache | (f):
"""
Decorator for rruleset methods which may invalidate the
cached length.
"""
def inner_func(self, *args, **kwargs):
rv = f(self, *args, **kwargs)
self._invalidate_cache()
return rv
return inner_func
class rrulebase(object):
def __init__(self, cache=False):
... |
angr/angr | angr/analyses/vtable.py | Python | bsd-2-clause | 4,142 | 0.002897 | import logging
from ..analyses import AnalysesHub
from . import Analysis, CFGFast
l = logging.getLogger(name=__name__)
class Vtable:
"""
This contains the addr, size and function addresses of a Vtable
"""
def __init__(self, vaddr, size, func_addrs=None):
self.vaddr = vaddr
... | # check if it is also a function, if so then it is possibly a vtable start
if self.is_func | tion(possible_func_addr):
new_vtable = self.create_extract_vtable(
cur_addr, sec.memsize
)
if new_vtable is not None:
list_vtables.append(new_vtable)
return... |
cloudify-cosmo/cloudify-manager | tests/integration_tests/resources/dsl/plugin_tests/plugins/mock-plugin/mock_plugin/ops.py | Python | apache-2.0 | 940 | 0 | # ***************************************************************************
# * Copyright (c) 2016 GigaSpaces Technologies Ltd. All rights reserved
# *
# * Licen | sed 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://w | ww.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 ... |
ajbc/lda-svi | generalrandom.py | Python | gpl-3.0 | 8,782 | 0.00353 | # wikirandom.py: Functions for downloading random articles from Wikipedia
#
# Copyright (C) 2010 Matthew D. Hoffman
#
# 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 Lic... | nd(int(tokens[1]))
self.terms.add(int(tokens[0]))
| self.docs.append((wordids, wordcts))
self.D = len(self.docs)
#''The first, wordids, says what vocabulary tokens are present in
#each document. wordids[i][j] gives the jth unique token present in
#document i. (Dont count on these tokens being in any particular
#order.)
... |
skylines-project/skylines | tests/api/views/clubs/read_test.py | Python | agpl-3.0 | 1,643 | 0 | from tests.api import auth_for
from tests.data import add_fixtures, clubs, users
def test_lva(db_session, client):
lva = clubs.lva(owner=users.john())
add_fixtures(db_session, lva)
res = client.get("/clubs/{id}".format(id=lva.id))
assert res.status_code == 200
assert res.json == {
"id": l... | ": lva.owner.id, "name": lva.owner.name},
}
def test_sfn(db_session, client):
sfn = clubs.sfn()
add_fixtures(db_session, sfn)
res = client.get("/clubs/{id}".format(id=sfn.id))
assert res.status_code == 200
assert res.json == {
u"id": sfn.id,
u"name": u"Sportflug Niederberg",
... | site": None,
u"isWritable": False,
u"owner": None,
}
def test_writable(db_session, client):
lva = clubs.lva()
john = users.john(club=lva)
add_fixtures(db_session, lva, john)
res = client.get("/clubs/{id}".format(id=lva.id), headers=auth_for(john))
assert res.status_code == 200... |
diofeher/django-nfa | django/contrib/localflavor/pl/forms.py | Python | bsd-3-clause | 5,591 | 0.004114 | """
Polish-specific form helpers
"""
import re
from django.newforms import ValidationError
from django.newforms.fields import Select, RegexField
from django.utils.translation import ugettext_lazy as _
class PLVoivodeshipSelect(Select):
"""
A select widget with list of Polish voivodeships (administrative prov... |
def clean(self,value):
super(PLNationalBusinessRegisterField, self).clean(value)
if not self.has_valid_checksum(value):
raise ValidationError(self.error_messages['checksum'])
return u'%s' % | value
def has_valid_checksum(self, number):
"""
Calculates a checksum with the provided algorithm.
"""
multiple_table_7 = (2, 3, 4, 5, 6, 7)
multiple_table_9 = (8, 9, 2, 3, 4, 5, 6, 7)
result = 0
if len(number) == 7:
multiple_table = multiple_tab... |
Willempie/Artificial_Intelligence_Cube | logic/handling/panel_action.py | Python | apache-2.0 | 5,455 | 0.005683 | from gui_items import *
from objects.xml.xml_step import Step
class ActionPanel:
def __init__(self, display):
self.steps = []
self.display = display
# new ACTION panel (textbox met draaien, knop voor het uitvoeren van de draaien)
self.panel = self.display.gui_items.add_panel(450,... | cube_turnable_checkbox.GetSelection()))
# undo button
undo_button = cube_action_gui_items.gen_button("Undo last input", 0,0)
undo_button.Bind(wx.EVT_BUTTON, self.__undo)
# add elements to box_sizers
output_siz | er.Add(self.cube_action_textbox, 0, wx.ALL, 5)
output_sizer.Add(cube_action_button, 0, wx.ALL, 5)
output_sizer.Add(cube_reset_textbox_button, 0, wx.ALL, 5)
output_sizer.Add(undo_button, 0, wx.ALL, 5)
axes_sizer.Add(x_button, 0, wx.ALL, 1)
axes_sizer.Add(y_button, 0, wx.ALL, 1)
... |
ellisonbg/pyzmq | zmq/tests/test_version.py | Python | lgpl-3.0 | 1,970 | 0.003553 | #-----------------------------------------------------------------------------
# Copyright (c) 2010-2012 Brian Granger, Min Ragan-Kelley
#
# This file is part of pyzmq
#
# Distributed under the terms of the New BSD License. The full license is in
# the file COPYING.BSD, distributed as part of this software.
#-----... | ERSION_EXTRA in vs2)
def test_pyzmq_version_info(self):
info = zmq.pyzmq_version_info()
self.assertTrue(isinstance(info, tuple))
for n in info[:3]:
self.assertTrue(isinstance(n, int))
if version.VERSION_EXTRA:
self.assertEqual(len(info), 4)
self.a... | tTrue(isinstance(info, tuple))
for n in info[:3]:
self.assertTrue(isinstance(n, int))
def test_zmq_version(self):
v = zmq.zmq_version()
self.assertTrue(isinstance(v, str))
|
RIEI/tongue | TongueD/StreamThread.py | Python | gpl-2.0 | 1,400 | 0.013571 | __author__ = 'sysferland'
import argparse, subprocess, os
parser = argparse.ArgumentParser()
parser.add_argument('-feed', help='feed name')
parser.add_argument('-ffserver', help='ffserver IP and PORT')
parser.add_argument('-source', help='video source path if DVD Raw the path to the VIDEO_TS folder')
parser.add_argume... | r.add_argument('-binpath', help='ffmpeg bin path')
args = parser.parse_args()
videofile = os.path.normpath(args.source)
#dt_to = datetime.time(00,20,00)
#dt_delta = datetime.time(00,00,30)
#seek_to = datetime.timedelta(hours=dt_to.hour,minutes=dt_to.minute,seconds=dt_to.second)
#seek_delta = datetime.timedelta(hour... | :00:00"
other_options = "-ss " + str(seek_to_fast)
options = "-ss "+ str(seek_delta) # +" -trellis 1 -lmax 42000 "
ffm_output = " http://"+args.ffserver+"/"+args.feed
command = args.binpath + "ffmpeg -threads 2 "+ other_options +" -i " + videofile.replace("'", "\\'").replace(" ", "\\ ").replace("-", "\-").replace("&... |
MackZxh/OCA-Choice | server-tools/auth_supplier/tests/test_auth_supplier.py | Python | lgpl-3.0 | 852 | 0 | # -*- coding: utf-8 -*-
# (c) 2015 Antiun Ingeniería S.L. - Sergio Teruel
# (c) 2015 Antiun Ingeniería S.L. - Carlos Dauden
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp.tests.common import TransactionCase
class TestSAuthSupplier(TransactionCase):
def setUp(self):
super(T... | set_param('auth_signup.allow_uninvited', 'True')
def test_user_signup(self):
values = {
'login': 'test@test.com',
'name': 'test',
'password': '1234',
'account_type': 'supplier'
}
user | _obj = self.env['res.users']
user = user_obj.browse(user_obj._signup_create_user(values))
self.assertTrue(user.partner_id.supplier)
|
hzj123/56th | pombola/votematch/admin.py | Python | agpl-3.0 | 754 | 0.01061 | from django.contrib import admin
import models
from pombola.slug_helpers.admin import StricterSlugFieldMixin
class QuizAdmin(StricterSlugFieldMixin, admin.ModelAdmin):
prepopulated_fields = {"slug": ["name"]}
class StatementAdmin(admin.ModelAdmin):
pass
class PartyAdmin(admin.ModelAdmin):
pass
class S... | n.ModelAdmin):
pass
class SubmissionAdmin(admin.ModelAdmin):
pass
class AnswerAdmin(admin.ModelAdmin):
pass
admin.site.register(models.Quiz, QuizAdmin)
admin.site.register(models.Statem | ent, StatementAdmin)
admin.site.register(models.Party, PartyAdmin)
admin.site.register(models.Stance, StanceAdmin)
admin.site.register(models.Submission, SubmissionAdmin)
admin.site.register(models.Answer, AnswerAdmin)
|
rholy/dnf-plugins-core | plugins/generate_completion_cache.py | Python | gpl-2.0 | 2,729 | 0 | # coding=utf-8
# generate_completion_cache.py - generate cache for dnf bash completion
# Copyright © 2013 Elad Alfassa <elad@fedoraproject.org>
# 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 Lice... | nerate cache of available packages '''
# We generate | this cache only if the repos were just freshed or if the
# cache file doesn't exist
fresh = False
for repo in self.base.repos.iter_enabled():
if repo.metadata is not None and repo.metadata.fresh:
# One fresh repo is enough to cause a regen of the cache
... |
nansencenter/nansat | nansat/mappers/mapper_opendap_sentinel1.py | Python | gpl-3.0 | 4,824 | 0.004561 | # Name: mapper_opendap_sentinel1.py
# Purpose: Nansat mapping for ESA Sentinel-1 data from the Norwegian ground segment
# Author: Morten W. Hansen
# Licence: This file is part of NANSAT. You can redistribute it or modify
# under the terms of GNU General Public License, v.3
# ... | + np.timedelta64(int(sec), 's').astype('m8[s]')) for sec in ds_time]).astype('M8[s]')
return ds_datetimes
def get_geotransform(self):
""" Return fake and temporary geotransform. This will be replaced by gcps in
Sentinel1.__init__
"""
xx = self.ds.variables['lon... | eturn xx[0], xx[1]-xx[0], 0, yy[0], 0, yy[1]-yy[0]
|
dhalperi/beam | sdks/python/apache_beam/utils/urns.py | Python | apache-2.0 | 4,265 | 0.00422 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | via pickling.
"""
inspect.currentframe().f_back.f_locals['to_runner_api_parameter'] = (
lambda self, context: (
pickle_urn, wrappe | rs_pb2.BytesValue(value=pickler.dumps(self))))
cls.register_urn(
pickle_urn,
wrappers_pb2.BytesValue,
lambda proto, unused_context: pickler.loads(proto.value))
def to_runner_api(self, context):
"""Returns an SdkFunctionSpec encoding this Fn.
Prefer overriding self.to_runner_api_p... |
hiteshagrawal/python | info/bkcom/problem8.py | Python | gpl-2.0 | 635 | 0.034646 | #!/usr/bin/python
import sys
""" My input is 2234,2234,765,2,3,44,44,55,33,33,2,33,33,33
my o/p
2234:2,765,2,3,44:2,55,33:2,2,33:3"""
my_input = sys.argv[1]
#my_input = "1,7,2234,2234,765,2,3,44,44,55,33,33,2,33,33,33,33,1"
my_list = my_input.split(",")
my_str = ""
#print my_list
init = my_list[0]
count = 0
final | _list = []
for i in my_list:
if i == init:
count += 1
else:
#print init, count
my_str = my_str + "," + "%s:%s" %(init,count)
count = 1
init = i
#print init, count
my_str = my_str + "," + "%s:%s" %(init,c | ount)
print my_str.replace(":1","")[1:]
#final_list = zip(my_numbers,my_count)
#print final_list
|
miyataken999/weblate | weblate/trans/views/reports.py | Python | gpl-3.0 | 6,538 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# 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, eith... | urn JsonResponse(data=data, safe=False)
if form.cleaned_data['style'] == 'html':
start = (
'<table>\n<tr><th>Name</th><th>Email</th>'
'<th>Words</th><th>Count</th></tr>'
| )
row_start = '<tr>'
cell_name = cell_email = cell_words = cell_count = u'<td>{0}</td>\n'
row_end = '</tr>'
mime = 'text/html'
end = '</table>'
else:
heading = ' '.join([
'=' * 40,
'=' * 40,
'=' * 10,
'=' * 10,
]... |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-0.96/django/core/handler.py | Python | bsd-3-clause | 289 | 0.00346 | # This modu | le is DEPRECATED!
#
# You should no longer be pointing your mod_python configuration
# at "django.core.handler".
#
# Use "django.core.handlers.modpython" instead.
from django.core | .handlers.modpython import ModPythonHandler
def handler(req):
return ModPythonHandler()(req)
|
aio-libs/aiomysql | aiomysql/sa/engine.py | Python | mit | 6,916 | 0 | # ported from:
# https://github.com/aio-libs/aiopg/blob/master/aiopg/sa/engine.py
import asyncio
import aiomysql
from .connection import SAConnection
from .exc import InvalidRequestError, ArgumentError
from ..utils import _PoolContextManager, _PoolAcquireContextManager
from ..cursors import (
Cursor, Deserializati... | ss)
for cursor_class in deprecated_cursor_classes
):
raise ArgumentError('SQLAlchemy engine does not support '
'this cursor class')
coro = _create_engine(m | insize=minsize, maxsize=maxsize, loop=loop,
dialect=dialect, pool_recycle=pool_recycle,
compiled_cache=compiled_cache, **kwargs)
return _EngineContextManager(coro)
async def _create_engine(minsize=1, maxsize=10, loop=None,
dialect=_diale... |
StuntsPT/pyRona | helper_scripts/geste2lfmm.py | Python | gpl-3.0 | 2,430 | 0 | #!/usr/bin/python3
# Copyright 2018 Francisco Pina Martins <f.pinamartins@gmail.com>
# This file is part of geste2lfmm.
# geste2 | lfmm 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.
# geste2lfmm is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See t... |
thebjorn/fixedrec | fixedrec/utils.py | Python | mit | 2,032 | 0.001476 | # -*- coding: utf-8 -*-
"""Utility functions.
"""
from collections import OrderedDict
from .bsd_checksum import bsd_checksum # make name available from this module
def n_(s, replacement='_'):
"""Make binary fields more readable.
"""
if isinstance(s, (str, unicode, bytearray)):
return s.replace('... | ne in sizes:
nonesize = slen - sum(v for v in sizes if v is not None)
sizes = [v or nonesize for v in sizes]
ndxs = [sizes[0]]
cur = 1
while cur < len(sizes) - 1:
ndxs.append(ndxs[-1] + sizes[cur])
cur += 1
return split_string(s, *ndxs)
class pset(OrderedDict):
"""A... | han your
terminal).
"""
def __repr__(self):
return '{%s}' % ', '.join('%s: %r' % (str(k), str(v))
for k,v in self.items())
def __str__(self):
return "{\n%s\n}" % ',\n'.join(' %s: %r' % (str(k), str(v))
for k,... |
reo7sp/vk-text-likeness | vk_text_likeness/logs.py | Python | apache-2.0 | 889 | 0.003375 | import inspect
import time
from collections import defaultdict
_method_time_logs = defaultdict(list)
|
def log_method_begin():
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
caller_name = "{}: {}".format(calframe[1].filename.split('/')[-1], calframe[1].function)
_method_time_logs[caller_name].append(time.time())
print("{}: begin".format(caller_name))
def log_metho... | ct.getouterframes(curframe, 2)
caller_name = "{}: {}".format(calframe[1].filename.split('/')[-1], calframe[1].function)
if caller_name in _method_time_logs:
logs = _method_time_logs[caller_name]
if len(logs) > 0:
print("{}: end ({:.3}s)".format(caller_name, time.time() - logs[-1]))
... |
arcward/ticketpy | ticketpy/query.py | Python | mit | 13,726 | 0.003643 | """Classes to handle API queries/searches"""
import requests
from ticketpy.model import Venue, Event, Attraction, Classification
class BaseQuery:
"""Base query/parent class for specific serach types."""
#: Maps parameter names to parameters expected by the API
#: (ex: *market_id* maps to *marketId*)
a... | :param sort: Sort method
:param include_test: ['yes', 'no', 'only'] to include test objects in
results. Default: *no*
:param page: Page to return (default: 0)
:param size: Page size (default: 20)
:param locale: Locale (default: *en*)
| :param kwargs: Additional search parameters
:return:
"""
# Combine universal parameters and supplied kwargs into single dict,
# then map our parameter names to the ones expected by the API and
# make the final request
search_args = dict(kwargs)
search_arg... |
warwick-one-metre/opsd | warwick/observatory/operations/actions/superwasp/park_telescope.py | Python | gpl-3.0 | 1,410 | 0.001418 | #
# This file is part of opsd.
#
# opsd 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.
#
# opsd is distributed in the hope that it wil... | ers import tel_stop, tel_park
class ParkTelescope(TelescopeAction):
"""Telescope action to park the telescope"""
def __init__(self, log_name):
super().__init__('Park Telescope', log_name, {})
def run_thread(self):
"""Thread that runs t | he hardware actions"""
if not tel_stop(self.log_name):
self.status = TelescopeActionStatus.Error
return
if not tel_park(self.log_name):
self.status = TelescopeActionStatus.Error
return
self.status = TelescopeActionStatus.Complete
|
dgholz/dung | dung/command/wait.py | Python | mit | 226 | 0.00885 | import argparse
class Wait(object):
@st | aticmethod
def add_parser(parser):
parser.add_parser('wait')
def __init__(self, dung):
self.dung = dung
| def run(self):
self.dung.wait_for_it()
|
vyacheslav-bezborodov/skt | stockviewer/stockviewer/db/main.py | Python | mit | 142 | 0.028169 | import dbman | ager
def main(args, config):
db = dbmanager.dbma | nager(config.find('dbmanager'))
if args.make_migration:
db.make_migration()
|
unix4you2/practico | mod/pam/pam_nativo.py | Python | gpl-3.0 | 891 | 0.030303 | #!/usr/bin/env python
import sys
import PAM
from getpass import getpass
def pam_conv(auth, query_list, userData):
resp = []
for i in range(len(query_list)):
query, type = query_list[i]
if type == PAM.PAM_PROMPT_ECHO_ON:
val = raw_input(query)
resp.append((val, 0))
elif type == PAM | .PAM_PROMPT_ECHO_OFF:
val = getpass(query)
resp.append((val, 0))
elif type == PAM.PAM_PROMPT_ERROR_MSG or type == PAM.PAM_PROMPT_TEXT_INFO:
print query
resp.append(('', 0))
else:
return None
return resp
service = 'passwd'
if len(sys.argv) == 2:
user = sys.argv[1]
else:
user = None
aut | h = PAM.pam()
auth.start(service)
if user != None:
auth.set_item(PAM.PAM_USER, user)
auth.set_item(PAM.PAM_CONV, pam_conv)
try:
auth.authenticate()
auth.acct_mgmt()
except PAM.error, resp:
print 'Go away! (%s)' % resp
except:
print 'Internal error'
else:
print 'Good to go!'
|
mheap/ansible | lib/ansible/modules/network/nxos/nxos_interface.py | Python | gpl-3.0 | 26,385 | 0.001819 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
DOCUMENTATION = """
---
module: nxos_interfac... |
description:
- "LLDP neighbor port to which given interface C(name) is connected."
version_added: 2.5
aggregate:
description: List of Interfaces definitions.
version_added: 2.5
state:
description:
- Specify desired state of the resource.
default: present
choices:... | operational state arguments.
default: 10
"""
EXAMPLES = """
- name: Ensure an interface is a Layer 3 port and that it has the proper description
nxos_interface:
name: Ethernet1/1
description: 'Configured by Ansible'
mode: layer3
- name: Admin down an interface
nxos_interface:
name: Ethernet2/1... |
ciudadanointeligente/deldichoalhecho | ddah_web/tests/instance_template_tests.py | Python | gpl-3.0 | 3,123 | 0.004483 | from django.test import TestCase, RequestFactory
from ddah_web.models import DDAHTemplate, DDAHInstanceWeb
from ddah_web import read_template_as_string
from ddah_web.views import MoustacheTemplateResponse
class InstanceTemplateTestCase(TestCase):
'''There is a template which contains the html to be represented us... | templates/default.html')
self.default_template_flat_page = read_template_as_string('instance_templates/default_flat_page.html')
self.default_template_footer = read_template_as_string('instance_templates/partials/footer.html')
self.default_template_head = read_template_as_string('instance_templat... | s/header.html')
self.default_template_style = read_template_as_string('instance_templates/partials/style.html')
def test_create_a_template(self):
template = DDAHTemplate.objects.create()
self.assertEquals(template.content, self.default_template)
self.assertEquals(template.flat_page_... |
anchore/anchore-engine | anchore_engine/analyzers/modules/31_file_package_verify.py | Python | apache-2.0 | 2,520 | 0.001587 | #!/usr/bin/env python3
import json
import os
import sys
import anchore_engine.analyzers.utils
analyzer_name = "file_package_verify"
try:
config = anchore_engine.analyzers.utils.init_analyzer_cmdline(
sys.argv, analyzer_name
)
except Exception as err:
print(str(err))
sys.exit(1)
imgname = con... | ile_package_metadata(unpackdir, record)
result = anchore_engine.analyzers.utils.rpm_get_file_package_metadata_from_squashtar(
unpackdir, squashtar
)
except Exception as err:
raise Exception("ERROR: " + | str(err))
elif flavor == "DEB":
try:
# result = deb_get_file_package_metadata(unpackdir, record)
result = anchore_engine.analyzers.utils.dpkg_get_file_package_metadata_from_squashtar(
unpackdir, squashtar
)
except Exception as err:
rai... |
vollov/py-lab | src/mongodb/__init__.py | Python | mit | 1,550 | 0.007097 | # -*- coding: utf-8 -*-
import sys,pymongo
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
from bson.code import Code
class MongoDBConfig:
def __init__(self, db_name, host):
self._db_name= db_name
self._host = host
class MongoDB:
'''Use mongo_client for a pooled m... | assert db_handler.connection == self.connection
with self.connection.start_request():
result = db_handler[collection_name].find_one(query)
return result
def removeAll(self, collection_name):
db_handler = self.connection[self.db_name]
assert db_handler.connection... | tion_name].remove()
|
ericbean/RecordSheet | test/test_jsonapp.py | Python | gpl-3.0 | 5,052 | 0.005542 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2015 Eric Beanland <eric.beanland@gmail.com>
# This file is part of RecordSheet
#
# RecordSheet 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, ... | enerate a Integrity exception serverside
#def test_generic_post_invalid_attr():
# response = app.post_json('/accounts/1', {'desc':1}, status=404)
# assert response.content_type == 'application/json'
############################### | ################################################
def test_journal_put():
posts = [{'amount':100, 'account_id':'TEST01'},
{'amount':-100, 'account_id':'TEST02', 'memo':'testing'}]
data = {'memo':'test journal entry',
'datetime':'2016-06-05 14:09:00-05',
'posts':posts}
... |
d120/kifplan | oplan/migrations/0008_auto_20160503_1910.py | Python | agpl-3.0 | 2,321 | 0.002155 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-05-03 17:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('oplan', '0007_auto_20160503_1638'),
]
operations = [
migrations.RemoveField(... | en)'),
),
migratio | ns.RemoveField(
model_name='aktermin',
name='constraintBeforeEvents',
),
migrations.AddField(
model_name='aktermin',
name='constraintBeforeEvents',
field=models.ManyToManyField(related_name='constraint_must_be_before_this', to='oplan.AKTermin',... |
OCA/stock-logistics-warehouse | stock_vertical_lift_server_env/models/__init__.py | Python | agpl-3.0 | 36 | 0 | from . | import vertical_lift_shuttle
| |
acutesoftware/worldbuild | worldbuild/world_builder.py | Python | gpl-2.0 | 2,333 | 0.014145 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# world_builder.py
class BuildMap(object):
"""
Base class to actually build a map which is defined
by the 'World' object or Grid (to be decided).
This can mean printing the grid, display as image,
create the map in Minecraft or create in other virtual
... | "
struct_data = details of coords to fill, make
style = details on colours, textures, if applicable
The assert checks that both are NOT strings, but should
be iterable lists / dicts or subclasses of
"""
assert not isinstance(struct_data, str)
| assert not isinstance(style, str)
self.struct_data = struct_data
self.style = style
def __str__(self):
res = ''
res += 'BuildMap ' + '\n'
if type(self.struct_data) is list:
for l in self.struct_data:
res += 'data:' + str(l) + '\n'
... |
ahmadpriatama/Flask-Simple-Ecommerce | appname/__init__.py | Python | bsd-2-clause | 1,969 | 0.001016 | #! ../env/bin/python
from flask import Flask
from webassets.loaders import PythonLoader as PythonAssetsLoader
from appname import assets
from appname.models import db
from appname.controllers.main import main
from appname.controllers.categories import categories
from appname.controllers.products import products
from ... | the different asset bundles
assets_env.init_app(app)
with app.app_context():
assets_env.load_path = [
os.path.join(os.path.join(os.path.dirname(__file__), os.pardir), 'node_modules'),
os.path.join(os.path.dirname(__file__), 'static'),
]
assets_loader = PythonAssetsLoa... | e, bundle)
# register our blueprints
app.register_blueprint(main)
app.register_blueprint(categories)
app.register_blueprint(products)
app.register_blueprint(catalogs)
return app
|
tochikuji/chainer-libDNN | libdnn/autoencoder.py | Python | mit | 4,929 | 0.000406 | # coding: utf-8
# Simple chainer interfaces for Deep learning researching
# For autoencoder
# Author: Aiga SUZUKI <ai-suzuki@aist.go.jp>
import chainer
import chainer.functions as F
import chainer.optimizers as Opt
import numpy
from libdnn.nnbase import NNBase
from types import MethodType
from abc import abstractmetho... | (N)
su | m_error = 0.
for i in range(0, N, batchsize):
x_batch = x_data[perm[i:i + batchsize]]
self.optimizer.zero_grads()
err = self.validate(x_batch, train=True)
err.backward()
self.optimizer.update()
sum_error += float(chainer.cuda.to_cpu(err... |
c17r/catalyst | src/mountains/__init__.py | Python | mit | 465 | 0 | """
mount | ains
~~~~~~~~~
Takes a CSV file either via local or HTTP retrieval and outputs information about the mountains according to spec.
Originally a programming skills check for a particular position. I've get it updated to current python versions
as well as packaging and testing methodologies.
:copyright: 2016-2017 Chr... | * # noqa
|
fegonda/icon_demo | code/web/server.py | Python | mit | 3,926 | 0.018849 | import tornado.ioloop
import tornado.web
import socket
import os
import sys
import time
import signal
# import datetime
import h5py
from datetime import datetime, date
import tornado.httpserver
from browserhandler import BrowseHandler
from annotationhandler import AnnotationHandler
from projecthandler import Proje... | th': 'resources/css/'}),
(r'/uikit/(.*)', tornado.web.StaticFileHandler, {'path': 'resources/uikit/'}),
(r'/images/(.*)', tornado.web.StaticFileHandler, {'path': 'resources/images/'}),
(r'/open-iconic/(.*)', tornado.web.StaticFileHandler | , {'path': 'resources/open-iconic/'}),
(r'/input/(.*)', tornado.web.StaticFileHandler, {'path': 'resources/input/'}),
(r'/train/(.*)', tornado.web.StaticFileHandler, {'path': 'resources/input/'}),
(r'/validate/(.*)', tornado.web.StaticFileHandler, {'path': 'resources/input/'}),
#(... |
aronsky/home-assistant | homeassistant/components/nx584/binary_sensor.py | Python | apache-2.0 | 4,476 | 0 | """Support for exposing NX584 elements as sensors."""
import logging
import threading
import time
from nx584 import client as nx584_client
import requests
import voluptuous as vol
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_OPENING,
DEVICE_CLASSES,
PLATFORM_SCHEMA,
BinarySensorEn... | ol.Optional(CONF_ZONE_TYPES, default={}): ZONE_TYPES_SCHEMA,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the NX584 binary sensor platform."""
host = config.get(CONF_HOST)
| port = config.get(CONF_PORT)
exclude = config.get(CONF_EXCLUDE_ZONES)
zone_types = config.get(CONF_ZONE_TYPES)
try:
client = nx584_client.Client(f"http://{host}:{port}")
zones = client.list_zones()
except requests.exceptions.ConnectionError as ex:
_LOGGER.error("Unable to co... |
nandhp/youtube-dl | youtube_dl/extractor/yandexmusic.py | Python | unlicense | 8,328 | 0.001817 | # coding: utf-8
from __future__ import unicode_literals
import re
import hashlib
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
ExtractorError,
int_or_none,
float_or_none,
sanitized_Request,
urlencode_postdata,
)
class YandexMusicBaseIE(InfoExtractor):
... | -domain': 'music.yandex.ru',
'overembed': 'false',
'sign': mu.get('authData', {}).get('user', {}).get('sign'),
'strict': 'true',
}))
request.add_header('Referer', url)
request.add_header('X-Requested-With', 'XMLHttpReque... | ng missing tracks JSON', fatal=False)
if missing_tracks:
tracks.extend(missing_tracks)
return self.playlist_result(
self._build_playlist(tracks),
compat_s |
mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/sklearn/isotonic.py | Python | mit | 14,061 | 0 | # Authors: Fabian Pedregosa <fabian@fseoane.net>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Nelle Varoquaux <nelle.varoquaux@gmail.com>
# License: BSD 3 clause
import numpy as np
from scipy import interpolate
from scipy.stats import spearmanr
from .base import BaseEstimator, TransformerMixi... | or right bound.
f_ : function
The stepwise interpolating function that covers the domain `X_`.
Notes
-----
Ties are broken using the secondary method from Leeuw, 1977.
Refere | nces
----------
Isotonic Median Regression: A Linear Programming Approach
Nilotpal Chakravarti
Mathematics of Operations Research
Vol. 14, No. 2 (May, 1989), pp. 303-308
Isotone Optimization in R : Pool-Adjacent-Violators
Algorithm (PAVA) and Active Set Methods
Leeuw, Hornik, Mair
J... |
noironetworks/neutron | neutron/extensions/l3_ext_gw_mode.py | Python | apache-2.0 | 820 | 0 | # Copyright 2013 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
#
# Unless required by ... | the specific language governing permissions and limitations
# under the License.
from neutron_lib.api.definitions import l3_ext_gw_mode as apidef
from neutron_lib.api import extensions
| class L3_ext_gw_mode(extensions.APIExtensionDescriptor):
api_definition = apidef
|
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247971765/PyKDE4/kdeui/KColorChooserMode.py | Python | gpl-2.0 | 508 | 0.009843 | # encoding: utf-8
# module PyKDE4.kdeui
# from /usr/lib/python3/dist-packages/PyKDE4/kdeui.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import PyKDE4.kdecore as __PyKDE4_kdecore
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtGui as __PyQt4_QtGui
import PyQt4.QtSvg as __PyQt4_QtSvg
fr... | oserMode(int):
# no doc
def __init__(self, *args, **kwargs): # | real signature unknown
pass
__dict__ = None # (!) real value is ''
|
florentbr/SeleniumBasic | FirefoxAddons/build-implicit-wait.py | Python | bsd-3-clause | 3,005 | 0.009318 |
"""Script to build the xpi add-in for firefox
Usage : python build-implicit-wait.py "x.x.x.x"
"""
import os, re, sys, shutil, datetime, zipfile, glob
CD = os.path.dirname(os.path.abspath(__file__))
SRC_DIR = CD + r'\implicit-wait'
OUT_DIR = CD + r'\bin'
RDF_PATH = CD + r'\implicit-wait\install.rdf'
def main(args):... | , input):
return input
class ZipFile(zipfile.ZipFile):
def __init__(cls, file, mode):
zipfile.ZipFile.__init__(cls, file, mode)
| def add(self, path):
for item in glob.glob(path):
if os.path.isdir(item):
self.add(item + r'\*');
else:
self.write(item)
if __name__ == '__main__':
main(sys.argv[1:])
|
friendly-of-python/flask-online-store | flask_online_store/views/admin/order.py | Python | mit | 396 | 0.005051 | from flask import Blueprint, render_template, session, redirect, url_for, reque | st, flash, g, jsonify, abort
#from flask_login import requires_login
admin_order = Blueprint('admin_order', __name__)
@admin_order.route('/')
def index():
pass
@admin_order.route('/new', methods=['GET', 'POST'])
def new():
pass
@admin_ord | er.route('/edit', methods=['GET', 'POST'])
def edit():
pass
|
guardicore/monkey | monkey/infection_monkey/telemetry/scan_telem.py | Python | gpl-3.0 | 537 | 0.001862 | from common.common_consts.telem_categories import TelemCategoryEnum
from infection_monkey.telemetry.base_telem import BaseTelem
class ScanTelem(BaseTele | m):
def __init__(self, machine):
"""
Default scan telemetry constructor
:param machine: Scanned machine
"""
super(ScanTelem, self).__init__()
self.machine = machine
telem_category = TelemCategoryEnum.SCAN
def get_data(self):
return {"machine": self.m... | dict(), "service_count": len(self.machine.services)}
|
browseinfo/odoo_saas3_nicolas | addons/website_sale/tests/test_ui.py | Python | agpl-3.0 | 963 | 0.015576 | import openerp.addons.website.tests.test_ui as test_ui
def load_tests(loader, base, _):
base.addTest(test_ui.WebsiteUiSuite(test_ui.full_path(__file__,'website_sale-add_product-test.js'),
{'redirect': '/page/website.homepage'}))
base.addTest(test_ui.WebsiteUiSuite(test_ui.full_path(__file__,'website_sa... | in | saas-3 and debug it directly in trunk.
# Tech Saas & AL agreement
# base.addTest(test_ui.WebsiteUiSuite(test_ui.full_path(__file__,'website_sale-sale_process-test.js'), {'path': '/', 'user': None}))
return base |
fidals/refarm-site | pages/migrations/0003_auto_20160909_0747.py | Python | mit | 467 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-09-09 07:47
from __future__ import unicode_literals
from django.db import mig | rations, models
class Migration(migrations.Migration):
dependencies = [
('pages', '0002_auto_20160829_1730'),
]
operations = [
migrations.AlterField(
model_name='page',
name='cont | ent',
field=models.TextField(blank=True, default='', null=True),
),
]
|
rrwick/Unicycler | unicycler/blast_func.py | Python | gpl-3.0 | 5,533 | 0.004518 | """
Copyright 2017 Ryan Wick (rrwick@gmail.com)
https://github.com/rrwick/Unicycler
This module contains functions relating to BLAST, which Unicycler uses to rotate completed circular
replicons to a standard starting point.
This file is part of Unicycler. Unicycler is free software: you can redistribute it and/or mod... | .misc import load_fasta
from . import log
class CannotFindStart(Exception):
pass
def find_start_gene(sequence, start_genes_fasta, identity_threshold, coverage_threshold, blast_dir,
makeblastdb_path, tblastn_path):
"""
This fun | ction uses tblastn to look for start genes in the sequence. It returns the first gene
(using the order in the file) which meets the identity and coverage thresholds, as well as
the position of that gene (including which strand it is on).
This function assumes that the sequence is circular with no overlap.
... |
mapzen/vector-datasource | integration-test/421-zoos-z13.py | Python | mit | 609 | 0 | # -*- encoding: utf-8 -*-
from shapely.wkt import loads as wkt_loads
import dsl
from . import FixtureTest
class ZoosZ13(FixtureTest):
def test_zoo_appears_at_z13(self):
# Zoo Montana, Billings, MT
self.generate_fixtures(dsl.way(2274329294, wkt_loads('POINT (-108.620965329915 45.7322965681428)'), {... | ber': u'2100', u'name': u'Zoo Montana', u'addr:city': u'Billings, MT 59106', u'source': u'openst | reetmap.org', u'tourism': u'zoo', u'addr:street': u'S. Shiloh Road'})) # noqa
self.assert_has_feature(
13, 1624, 2923, 'pois',
{'kind': 'zoo'})
|
kins912/giantcellsim | giantcellsim_motifoutput.py | Python | mit | 3,105 | 0.02963 | import csv
from giantcellsim_trial import giantcellsim_trial
import itertools
import numpy
def flatten(items, seqtypes=(list, tuple)): # used for flattening lists
for i, x in enumerate(items):
while isinstance(items[i], seqtypes):
items[i:i+1] = items[i]
return items
def giantcellsim_moti... | fs / float(total) for motifs,total in itertools.izip(nr_motifs,nr_strands)]
strands_freq = [strands / float(max_strand_nr*numCells) for strands in nr_strands]
cells_with_freq = [cells / float(numCells) for cells in nr_cells_with_motif]
writer.writerow(motif_freq)
writer.writerow(strands_freq)
writer.wri... | q)
if trial == 0:
motif_freq_aggregate = motif_freq
strands_freq_aggregate = strands_freq
cells_with_freq_aggregate = cells_with_freq
nr_strands_per_time = nr_strands
else:
motif_freq_aggregate = [list(round_data) for round_data in zip(motif_freq_aggregate,motif_freq)]
strands_freq_aggreg... |
GovReady/readthedocs.org | readthedocs/rtd_tests/base.py | Python | mit | 3,856 | 0.001037 | import os
import shutil
import logging
from collections import OrderedDict
from mock import patch
from django.conf import settings
from django.test import TestCase
log = logging.getLogger(__name__)
class RTDTestCase(TestCase):
def setUp(self):
self.cwd = os.path.dirname(__file__)
self.build_dir ... | ssertIn('{0}-current_step'.format(self.wizard_class_slug),
response.content)
# We use camelCase on purpose here to conform with unittest's naming
# conventions.
def assertWizardFailure(self, response, field, match=None): # noqa
'''Assert field threw a validation error
... | lidation error
'''
self.assertEqual(response.status_code, 200)
self.assertIn('wizard', response.context)
self.assertIn('form', response.context['wizard'])
self.assertIn(field, response.context['wizard']['form'].errors)
if match is not None:
error = response.co... |
petervanderdoes/wger | wger/gym/migrations/0002_auto_20151003_1944.py | Python | agpl-3.0 | 1,061 | 0.002828 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import datetime
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('gym', '0001_initial'),
... | Field(max_length=10, verbose_name='ZIP code', blank=True, null=True),
),
migrations.AlterField(
model_name='gymconfig',
name='weeks_inactive',
field=models.PositiveIntegerField(help_text='Number of weeks since the last time a user logged his presence to be considered ... | =4, verbose_name='Reminder inactive members'),
),
]
|
regisf/geocluster | geocluster/geoconvertion.py | Python | mit | 1,701 | 0 | # -*- coding: utf-8 -*-
# Geocluster - A simple and naive geo cluster
# (c) Régis FLORET 2014 and later
#
def convert_lat_from_gps(value):
"""
Convert a lattitude from GPS coordinate to decimal degrees
:param value: The lattitude as a float between 0 and -90
:return: The lattitude in decimal degrees
... | de as a float
:return: The longitude in decimal degrees
"""
assert (isinstance(value, (int, float)))
return value if value > 0 else 180 + abs(value)
def convert_lat_from_degrees(value):
"""
Convert a longitude from decimal degrees to GPS coordinate
:param value: The longitude as a float
... | ce(value, (int, float)))
if value > 180:
raise ValueError("Lattitude in degrees can't be greater than 180")
elif value < 0:
raise ValueError("Lattitude in degrees can't be lesser than 0")
return value if value < 90 else 90 - value
def convert_lng_from_degrees(value):
"""
Convert ... |
letsencrypt/letsencrypt | tools/pip_install_editable.py | Python | apache-2.0 | 629 | 0.00159 | #!/usr/bin/env python
# pip installs pac | kages in editable mode using pip_install.py
#
# cryptography is currently using this script in their CI at
# https://github.com/pyca/cryptography/blob/a02fdd60d98273ca34427235c4ca96687a12b239/.travis/downstream.d/certbot.sh#L8-L9.
# We should try to remember to keep their repo updated if we make any changes
# to this s... | ew_args.append(arg)
pip_install.main(new_args)
if __name__ == '__main__':
main(sys.argv[1:])
|
dimagi/commcare-hq | corehq/apps/smsbillables/migrations/0022_pinpoint_gateway_fee_amount_null.py | Python | bsd-3-clause | 485 | 0.002062 | from django. | db import migrations
from corehq.apps.smsbillables.management.commands.bootstrap_gateway_fees import (
bootstrap_pinpoint_gateway,
)
def add_pinpoint_gateway_fee_for_migration(apps, schema_editor):
bootstrap_pinpoint_gateway(apps)
class Migration(migrations.Migration):
dependencies = [
('smsbi... | ns.RunPython(add_pinpoint_gateway_fee_for_migration),
]
|
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247972723/gtk/_gtk/Arrow.py | Python | gpl-2.0 | 6,743 | 0.002818 | # encoding: utf-8
# module gtk._gtk
# from /usr/lib/python2.7/dist-packages/gtk-2.0/gtk/_gtk.so
# by generator 1.135
# no doc
# imports
import atk as __atk
import gio as __gio
import gobject as __gobject
import gobject._gobject as __gobject__gobject
from Misc import Misc
class Arrow(Misc):
"""
Object GtkArr... | widget, or -1 if natural request should be used
height-request -> gint: Height request
Override for height request of the widget, or -1 if natural request should be used
visible -> gboolean: Visible
Whether the widget is visible
sensitive -> gboolean: Sensitive
Whether the widg... | ean: Application paintable
Whether the application will paint directly on the widget
can-focus -> gboolean: Can focus
Whether the widget can accept the input focus
has-focus -> gboolean: Has focus
Whether the widget has the input focus
is-focus -> gboolean: Is focus
Whe... |
JeffHeard/sondra | sondra/auth/collections.py | Python | apache-2.0 | 11,035 | 0.007431 | import datetime
import bcrypt
import rethinkdb as r
from sondra.api.expose import expose_method, expose_method_explicit
from sondra.auth.decorators import authorized_method, authorization_required, authentication_required, anonymous_method
from sondra.collection import Collection
from .documents import Credentials, R... | n(password) < 6:
raise ValueError("Password too short")
def user_data(self,
username: str,
email: str,
loca | le: str='en-US',
password: str=None,
family_name: str=None,
given_name: str=None,
names: list=None,
active: bool=True,
roles: list=None,
confirmed_email: bool=False
) -> str:
"""Create a new user
Args:
u... |
krisys/SpojBot | src/spojbot/bot/models.py | Python | mit | 6,922 | 0.002023 | from django.db import models
from django.contrib.auth.models import User
import requests
from datetime import datetime
from BeautifulSoup import BeautifulSoup
import re
SPOJ_ENDPOINT = "http://www.spoj.com/status/%s/signedlist/"
class SpojUser(models.Model):
user = models.OneToOneField(User)
spoj_handle = mo... | oints.group()
try:
self.points = float(re.search("\d+.\ | d+", points).group())
except:
self.points = float(re.search("\d+", points).group())
soup = BeautifulSoup(response.text)
stats = soup.find("table", {"class": "problems"})
for index, row in enumerate(stats.findAll('tr')):
if index == 0:
continue
... |
RCoon/CodingBat | Python/String_1/make_tags.py | Python | mit | 576 | 0.005208 | # The web is built with | HTML strings like "<i>Yay</i>" which draws Yay as
# italic text. In this example, the "i" tag makes <i> and </i> which surround
# the word "Yay". Given tag and word strings, create the HTML string with tags
# around the word, e.g. "<i>Yay</i>".
# make_tags('i', 'Yay') --> '<i>Yay</i>'
# make_tags('i', 'Hello') --> '<... | ake_tags('i', 'Yay'))
print(make_tags('i', 'Hello'))
print(make_tags('cite', 'Yay'))
|
markflyhigh/incubator-beam | sdks/python/apache_beam/testing/benchmarks/chicago_taxi/trainer/task.py | Python | apache-2.0 | 5,417 | 0.009599 | # Copyright 2019 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | dir',
help="""\
Directory under which which the serving model (under /serving_model_dir)\
and the tf-mode-analysis model (under /eval_model_dir) will be written\
""",
required=True)
parser.add_argument(
'--eval-fi | les',
help='GCS or local paths to evaluation data',
nargs='+',
required=True)
# Training arguments
parser.add_argument(
'--job-dir',
help='GCS location to write checkpoints and export models',
required=True)
# Argument to turn on all logging
parser.add_argument(
'--ver... |
echohenry2006/tvb-library | tvb/basic/traits/util.py | Python | gpl-2.0 | 6,354 | 0.003777 | # -*- coding: utf-8 -*-
#
#
# TheVirtualBrain-Scientific Package. This package holds all simulators, and
# analysers necessary to run brain-simulations. You can use it stand alone or
# in conjunction with TheVirtualBrain-Framework Package. See content of the
# documentation-folder for more details. See also http://ww... | '_base_classes'):
bases = cls._base_classes
else:
bases = []
sublcasses = [opt for opt in self if ((issubclass(opt, cls) or cls in opt.__bases__)
and not inspect.isabstract(opt) and opt.__name__ not in bases)]
return sublcas... | ives in the given rst string
It converts them in html text that will be interpreted by mathjax
The parsing is simplistic, not a rst parser.
Wraps .. math :: body in \[\begin{split}\end{split}\]
"""
# doc = text | math
BEGIN = r'\[\begin{split}'
END = r'\end{split}\]'
in_math = False #... |
kenyaapps/loaderio | loaderio/resources/servers.py | Python | mit | 207 | 0.043478 | from loaderio.resources.client import Client
class Servers(Client):
"""
| """
def __init__(self, api_key):
Client.__init__(self, api_key)
pass
d | ef list(self):
return self.request('GET', 'servers') |
SmartJog/sjconf | sjconfparts/type.py | Python | lgpl-2.1 | 16,215 | 0.001788 | import re
import sjconfparts.excep | tions
class Error(sjconfparts.exceptions.Error):
pass
class ConversionError(Error):
pass
class ConversionList:
"""Custom list imp | lementation, linked to the related Conf.
Each modification of the list will auto-update the string representation
of the list directly in the Conf object, via a call to
self.conversion_method().
Nowadays this is considered ugly (maybe it wasn't back in 2008 with Python 2.5?),
but no one wants nor ... |
cadithealth/genemail | genemail/modifier/base.py | Python | mit | 2,085 | 0.009592 | # -*- coding: utf-8 -*-
#------------------------------------------------------------------------------
# file: $Id$
# auth: Philip J Grabner <grabner@cadit.com>
# date: 2013/07/31
# copy: (C) Copyright 2013 Cadit Health Inc., All Rights Reserved.
| #------------------------------------------------------------------------------
#------------------------------------------------------------------------------
class Modifier(object):
#----------------------------------------------------------------------------
def modify(self, mailfrom, recipients, data):
''... | ding.
:Parameters:
mailfrom : str
the SMTP-level `MAILFROM` command argument.
recipients : { list, tuple }
an iterable of the SMTP-level `RCPTTO` command arguments.
data : { str, email.MIMEMessage }
represents the SMTP-level `DATA` command argument, and can
either be a subcla... |
ic-hep/DIRAC | src/DIRAC/FrameworkSystem/Service/ProxyManagerHandler.py | Python | gpl-3.0 | 18,027 | 0.003162 | """ ProxyManager is the implementation of the ProxyManagement service in the DISET framework
.. literalinclude:: ../ConfigTemplate.cfg
:start-after: ##BEGIN ProxyManager:
:end-before: ##END
:dedent: 2
:caption: ProxyManager options
"""
from DIRAC import gLogger, S_OK, S_ERROR
from DIRAC.Cor... | LimitedDelegation <- permits downloading only limited proxies
* PrivateLimitedDelegation <- permits downloading only limited proxies for one self
"""
credDict = self.getRemoteCredentials()
result = self.__checkProperties(userDN, userGroup)
if not result["OK"]:
... | alue"]
self.__proxyDB.logAction("download proxy", credDict["DN"], credDict["group"], userDN, userGroup)
return self.__ |
noironetworks/neutron | neutron/plugins/ml2/drivers/agent/capabilities.py | Python | apache-2.0 | 1,161 | 0 | # Copyright 2016 Hewlett Packard Enterprise Development LP
#
# 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 o... | ND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from neutron_lib.callbacks import events
from neutron_lib.callbacks import registry
def notify_init_event(agent_type, agent):
"""Notify init event for the specifie | d agent."""
registry.publish(agent_type, events.AFTER_INIT, agent)
def register(callback, agent_type):
"""Subscribe callback to init event for the specified agent.
:param agent_type: an agent type as defined in neutron_lib.constants.
:param callback: a callback that can process the agent init event.
... |
root-mirror/root | bindings/pyroot/cppyy/cppyy/python/cppyy/_stdcpp_fix.py | Python | lgpl-2.1 | 524 | 0 | import sys
# It may be that the inter | preter (wether python or pypy-c) was not linked
# with C++; force its loading before doing anything else (note that not
# linking with C++ spells trouble anyway for any C++ libraries ...)
if 'linux' in sys.platform and 'GCC' in sys.version:
# TODO: check executable to see whether linking indeed didn't happen
im... | |
mr-karan/Udacity-FullStack-ND004 | Project1/projects/movieServer/app.py | Python | mit | 2,980 | 0.034564 | from flask import Flask
app = Flask(__name__)
from media import Movie
from flask import render_template
import re
@app.route('/')
def index():
'''View function for index page.'''
toy_story = Movie(title = "Toy Story 3", trailer_youtube_url ="https://www.youtube.com/watch?v=QW0sjQFpXTU",
poster_image_url="https... | XkFtZTcwMDA5Mzg3OA@@._V1_UX182_CR0,0,182,268_AL_.jpg",
storyline='''The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.''')
dark_knight = Movie(title = "The Dark Knight ", trailer_youtube_url ="https://www.youtube.com/watch?v=EXeTwQWrcwY",
p... | ps://images-na.ssl-images-amazon.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_UX182_CR0,0,182,268_AL_.jpg",
storyline='''Set within a year after the events of Batman Begins, Batman, Lieutenant James Gordon, and new district attorney Harvey Dent successfully begin to round up the criminals'''... |
shrinidhi666/rbhus | rbhusUI/lib/rbhusPipeSubmitRenderMod.py | Python | gpl-3.0 | 30,076 | 0.003757 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'rbhusPipeSubmitRenderMod.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _f... | ghtForWidth())
self.comboRenderer.setSizePolicy(sizePolicy)
self.comboRenderer.setObjectName(_fromUtf8("comboRenderer"))
self.gridLayout.addWidget(self.comboRenderer, 12, 1, 1, 1)
self.labelAfterTime = QtGui.QLabel(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.Q... | belAfterTime.sizePolicy().hasHeightForWidth())
self.labelAfterTime.setSizePolicy(sizePolicy)
self.labelAfterTime.setObjectName(_fromUtf8("labelAfterTime"))
self.gridLayout.addWidget(self.labelAfterTime, 17, 0, 1, 1)
self.pushSubmit = QtGui.QPushButton(self.centralwidget)
sizePolicy = QtGui.QSizePoli... |
urielka/shaveet | shaveet/gc.py | Python | mit | 925 | 0.027027 | #std
import logging
#3rd
from gevent import Greenlet,sleep
#shaveet
from shaveet.config import MAX_CLIENTS_GC,CLIENT_GC_INTERVAL
from shaveet.lookup import all_clients,discard_client
logger = logging.getLogger("shaveet.gc")
class ClientGC(Greenlet):
"""
this greenthread collects the clients that are no longer act... | clien | t_id,client in all_clients().iteritems():
if not client.is_active():
logger.debug("ClientGC:collecting id:%s,ts:%d,waiting:%s",client.id,client.ts,client.is_waiting)
discard_client(client)
#process in chuncks of MAX_CLIENTS_GC,sleep(0) means yeild to next greenlet
client_proc... |
planetlabs/datalake-api | setup.py | Python | apache-2.0 | 2,140 | 0 | # Copyright 2015 Planet Labs, 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 wr... | planetlab | s/datalake-api',
version=get_version(),
description='datalake_api ingests datalake metadata records',
author='Brian Cavagnolo',
author_email='brian@planet.com',
packages=['datalake_api'],
install_requires=[
'pyver>=1.0.18',
'memoized_property>=1.0.2',
's... |
airbnb/superset | superset/migrations/versions/732f1c06bcbf_add_fetch_values_predicate.py | Python | apache-2.0 | 1,455 | 0.002062 | # 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... | rt sqlalchemy as sa
from alembic import op
def upgrade():
op.add_column(
"datasources",
sa.Column("fetch_values_from", sa.String(length=100), nullable=True),
| )
op.add_column(
"tables",
sa.Column("fetch_values_predicate", sa.String(length=1000), nullable=True),
)
def downgrade():
op.drop_column("tables", "fetch_values_predicate")
op.drop_column("datasources", "fetch_values_from")
|
mhbu50/erpnext | erpnext/hr/doctype/employee_advance/employee_advance.py | Python | gpl-3.0 | 8,463 | 0.025996 | # Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import flt, nowdate
import erpnext
from erpnext.accounts.doctype.journal_entry.journal_entry import ge... | cher = %s
and party_type = 'Employee'
and party = %s
""", (self.name, self.employee), as_dict=1)[0].paid_amount
return_amount = frappe.db.sql("""
select ifnull(sum(credit), 0) as return_amount
from `tabGL Entry`
where against_voucher_type = 'Employee Advance'
and voucher_type != 'Expense Claim... | and party_type = 'Employee'
and party = %s
""", (self.name, self.employee), as_dict=1)[0].return_amount
if paid_amount != 0:
paid_amount = flt(paid_amount) / flt(self.exchange_rate)
if return_amount != 0:
return_amount = flt(return_amount) / flt(self.exchange_rate)
if flt(paid_amount) > self.adv... |
AddonScriptorDE/plugin.video.dtm_tv | default.py | Python | gpl-2.0 | 6,186 | 0.032368 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib,urllib2,re,xbmcplugin,xbmcgui,sys,xbmcaddon
pluginhandle = int(sys.argv[1])
settings = xbmcaddon.Addon(id='plugin.video.dtm_tv')
translation = settings.getLocalizedString
language=""
language=settings.getSetting("language")
if language=="":
settings.openSettin... | anguage")
if language=="0":
| language="DE"
elif language=="1":
language="EN"
def cleanTitle(title):
return title.replace("\\u00c4","Ä").replace("\\u00e4","ä").replace("\\u00d6","Ö").replace("\\u00f6","ö").replace("\\u00dc","Ü").replace("\\u00fc","ü").replace("\\u00df","ß").strip()
def index():
addDir(translation(30001),"LATEST... |
mephasor/mephaBot | addons/onlineRadio.py | Python | gpl-3.0 | 5,202 | 0.002169 | import discord
import re
import urllib.request
import xml.etree.ElementTree as ET
radio = {}
radioNames = {}
radioWhosPlaying = {}
radioNowPlaying = ''
playerStatus = 0
defaultChannel = ''
voice = ''
async def botWhatIsPlaying(client, message):
if playerStatus is 0:
await client.send_message(message.chann... | = open('cfg/radio.cfg').readlines()
# for line in configFile:
# tmp = line.split(', ')
# radio[tmp[0]] = tmp[1].rstrip('\n')
# radioNames[tmp[0]] = tmp[2].rstrip('\n')
# commands['!'+tmp[0]] = botPlayRadio
| # radioWhosPlaying[tmp[0]] = [tmp[3], tmp[4].rstrip('\n')]
defaultChannel = config.getDefaultChannel()
data = open('cfg/radio.xml').read()
root = ET.fromstring(data)
for station in root:
cmd = station.find('command').text
name = station.get('name')
strURL = station.find('s... |
chihongze/girlfriend | girlfriend/util/validating.py | Python | mit | 4,999 | 0.000236 | # coding: utf-8
"""参数验证相关工具
"""
import re
import ujson
import types
import numbers
from girlfriend.util.lang import args2fields
from girlfriend.exception import InvalidArgumentException
class Rule(object):
|
"""描述参数验证规则,并执行验证过程
"""
@args2fields()
def __init__(self, name,
type=None,
required=False, min=None, max=None,
regex=None, logic=None, default=None):
"""
:param name 参数名称,通常用于错误提示
:param required 如果为True,那么参数是必须的
... | 么为该参数最小值(等于此值算合法)
:param max 同上
:param regex 正则验证
:param type 类型验证,多个参数可以传递元组
:param logic 谓词函数,满足更加复杂的业务验证需要,比如查查数据库邮箱是否存在等等
该谓词函数并非返回True和False,如果有错误,那么返回错误消息的字符串,
如果没有错误,那么直接返回None
:param default 该项的默认值
... |
TomasTomecek/sen | sen/tui/buffer.py | Python | mit | 10,717 | 0.001306 | import logging
from sen.docker_backend import DockerContainer, RootImage
from sen.exceptions import NotifyError
from sen.tui.commands.base import Command
from sen.tui.views.disk_usage import DfBufferView
from sen.tui.views.help import HelpBufferView, HelpCommandView
from sen.tui.views.main import MainListBox
from sen.... |
def process_realtime_event(self, event):
if event.get("id", None) == self.docker_image.object_id:
self.widget.refresh()
class ContainerInfoBuffer(Buffer):
description = "Detailed info about selected container presented in a slick dashboard."
keybinds = {
"enter": "display-inf... | refresh",
"i": "inspect",
}
def __init__(self, docker_container, ui):
"""
:param docker_container:
:param ui: ui object so we refresh
"""
self.docker_container = docker_container
self.display_name = docker_container.short_name
self.widget = Contai... |
Azure/azure-sdk-for-python | sdk/keyvault/azure-keyvault-keys/tests/test_crypto_client.py | Python | mit | 41,908 | 0.003508 | # ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import codecs
from datetime import datetime
import hashlib
import os
import time
try:
from unittest import mock
except ImportError:
import mock
from azure.core... | d=_to_bytes(
"627c7d24668148fe2252c7fa649ea8a5a9ed44d75c766cda42b29b660e99404f0e862d4561a6c95af6a83d213e0a2244b03cd28576473215073785fb067f015da19084ade9f475e08b040a9a2c7ba00253bb8125508c9df140b75161d266be347a5e0f6900fe1d8bbf78ccc25eeb37e0c9d188d6e1fc15169ba4fe12276193d7779 | 0d2326928bd60d0d01d6ead8d6ac4861abadceec95358fd6689c50a1671a4a936d2376440a41445501da4e74bfb98f823bd19c45b94eb01d98fc0d2f284507f018ebd929b8180dbe6381fdd434bffb7800aaabdd973d55f9eaf9bb88a6ea7b28c2a80231e72de1ad244826d665582c2362761019de2e9f10cb8bcc2625649"
),
p=_to_bytes(
"00d1deac... |
google-research/accelerated_gbm | solve_libsvm_instances.py | Python | mit | 4,858 | 0.004323 | # Copyright 2020 The Google Authors. All Rights Reserved.
#
# Licensed under the MIT License (the "License");
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN... | _iteration=method.best_iteration))
if params.loss == "L2Loss":
loss = F.L2Loss(params.use_hessian)
elif params.loss == "LogisticLoss":
| loss = F.LogisticLoss(params.use_hessian)
print("The mean loss of prediction is:",
np.mean(loss.loss_value(np.array(y_pred), np.array(y_test))))
if __name__ == "__main__":
app.run(main)
|
r0h4n/commons | tendrl/commons/tests/test_init.py | Python | lgpl-2.1 | 17,194 | 0 | import __builtin__
import etcd
from etcd import Client
import importlib
import inspect
import maps
from mock import MagicMock
from mock import patch
import os
import pkgutil
import pytest
import yaml
from tendrl.commons import objects
import tendrl.commons.objects.node_context as node
from tendrl.commons import Tendr... | 'tendrl.commons.objects.alert'),
('block_device',
'tendrl.commons.objects.block_device'),
('cluster',
'tendrl.commons.objects.cluster'),
('cluster_alert',
| 'tendrl.commons.objects.cluster_alert'),
('cluster_alert_counters',
'tendrl.commons.objects.cluster_alert_counters'),
('cluster_node_alert_counters',
'tendrl.commons.objects.cluster_node_alert_counters'),
('cluster_node_context',
'tendrl.commons.objects.cluster_nod... |
whyDK37/py_bootstrap | samples/context/do_with.py | Python | apache-2.0 | 269 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from contextlib import contextm | anager
@contextmanager
def log(name):
| print('[%s] start...' % name)
yield
print('[%s] end.' % name)
with log('DEBUG'):
print('Hello, world!')
print('Hello, Python!')
|
akiellor/selenium | py/test/selenium/webdriver/common/correct_event_firing_tests.py | Python | apache-2.0 | 5,557 | 0.003599 | #!/usr/bin/python
# Copyright 2008-2010 WebDriver committers
# Copyright 2008-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-... |
if type(self.driver) == 'remote':
return lambda x: None
else:
return func(self)
return testMethod
class CorrectEventFiringTests(unittest.TestCase):
def testShouldFireClickEventWhenClicking(self):
self._loadPage("javascriptPage")
self._clickOnElementWhic... | ed("click")
def testShouldFireMouseDownEventWhenClicking(self):
self._loadPage("javascriptPage")
self._clickOnElementWhichRecordsEvents()
self._assertEventFired("mousedown")
def testShouldFireMouseUpEventWhenClicking(self):
self._loadPage("javascriptPage")
... |
bameda/lektor | tests/test_editor.py | Python | bsd-3-clause | 1,424 | 0 | def test_basic_editor(scratch_tree):
sess = scratch_tree.edit('/')
assert sess.id == ''
assert sess.path == '/'
assert sess.record is not None
assert sess['_model'] == 'page'
assert sess['title'] == 'Index'
assert sess['body'] == 'Hello World!'
sess['body'] = 'A new body'
sess.com... | to change this, we only want the fields that
# changed compared to the base to be included.
with open(sess.get_fs_path(alt='de' | )) as f:
assert f.read().splitlines() == [
'body: Hallo Welt!'
]
scratch_pad.cache.flush()
item = scratch_pad.get('/', alt='de')
assert item['_slug'] == ''
assert item['title'] == 'Index'
assert item['body'].source == 'Hallo Welt!'
assert item['_model'] == 'page'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.