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
biln/airflow
airflow/example_dags/example_python_operator.py
Python
apache-2.0
1,774
0.000564
# -*- coding: utf-8 -*- # # 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 ...
anguage governing permissions and # limitations under the License. from __future__ import print_function from builtins import range from airflow.operators import PythonOperator from airflow.models import DAG from datetime import datetime, timedelta import time from pprint import pprint seven_days_ago = datetime.combi...
, datetime.min.time()) args = { 'owner': 'airflow', 'start_date': seven_days_ago, } dag = DAG( dag_id='example_python_operator', default_args=args, schedule_interval=None) def my_sleeping_function(random_base): '''This is a function that will run within the DAG execution''' time.sleep(random...
CSCI1200Course/csci1200OnlineCourse
modules/data_source_providers/rest_providers.py
Python
apache-2.0
14,940
0.000268
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
description='Sets of lessons providing course content') reg.add_property(schema
_fields.SchemaField( 'lesson_id', 'Unit ID', 'integer', description='Key uniquely identifying which lesson this is')) reg.add_property(schema_fields.SchemaField( 'unit_id', 'Unit ID', 'integer', description='Key uniquely identifying unit lesson is in')) re...
chrisxue815/leetcode_python
problems/test_0844_stack.py
Python
unlicense
744
0
import unittest import utils def remove_backspace(s): result = [] for ch in s: if ch == '#': if result: result.pop() else: result.append(ch) return result # O(n) time. O(n) space. Stack. class Solution: def backspaceCompare(self, S: str, T: str...
self.assertEqual(case.expected, actual, msg=args) if __name__ == '__main__': unittest.main()
KarlTDebiec/MDclt
primary/raw.py
Python
bsd-3-clause
7,794
0.016295
# -*- coding: utf-8 -*- # MDclt.primary.raw.py # # Copyright (C) 2012-2015 Karl T Debiec # All rights reserved. # # This software may be modified and distributed under the terms of the # BSD license. See the LICENSE file for details. """ Classes for transfer of data from raw text files to h5 .. todo: - L...
""" Prepares and returns next Block of analysis """ if len(self.infiles) == 0: raise StopIteration() else: block_infiles = self.infiles[:self.infiles_per_block] block_slice = slice(self.start_index, self.start_index + len(block_...
les) * self.frames_per_file, 1) self.infiles = self.infiles[self.infiles_per_block:] self.start_index += len(block_infiles) * self.frames_per_file return Raw_Block(infiles = block_infiles, output = self.outputs[0], ...
weaver-viii/h2o-3
h2o-py/tests/testdir_algos/rf/pyunit_iris_nfoldsRF.py
Python
apache-2.0
616
0.016234
import sys sys
.path.insert(1, "../../../") import h2o def iris_nfolds(ip,port): iris = h2o.import_file(path=h2o.locate("smalldata/iris/iris.csv")) model = h2o.random_forest(y=iris[4], x=iris[0:4], ntrees=50, nfolds=5) model.show() # Can specify both nfolds >= 2 and validation = H2OParsedData at once ...
[0:4], ntrees=50, nfolds=5) assert True except EnvironmentError: assert False, "expected an error" if __name__ == "__main__": h2o.run_test(sys.argv, iris_nfolds)
apache/incubator-airflow
airflow/config_templates/default_webserver_config.py
Python
apache-2.0
4,695
0.000639
# # 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...
AUTH_LDAP # from airflow.www.fab_security.manager import AUTH_OAUTH # from airflow.www.fab_security.manager import AUTH_OID # from airflow.www.fab_security.manager import AUTH_REMOTE_USER basedir = os.path.abspath(os.path.dirname(__file__)) # Flask-WTF flag for CSRF WTF_CSRF_ENABLED = True # ----------------------...
------------------------------------- # For details on how to set up each of the following authentication, see # http://flask-appbuilder.readthedocs.io/en/latest/security.html# authentication-methods # for details. # The authentication type # AUTH_OID : Is for OpenID # AUTH_DB : Is for database # AUTH_LDAP : Is for LD...
almeidapaulopt/erpnext
erpnext/payroll/doctype/payroll_entry/payroll_entry.py
Python
gpl-3.0
29,720
0.026447
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from dateutil.relativedelta import relativedelta from frappe import _ from frappe.desk.reportview import get_filters_cond, get_match_cond from frappe.model.document import Document from...
l_struct, cond, self.end_date, self.payroll_payable_account) emp_list = remove_payrolled_employees(emp_list, self.start_date, self.end_date) return emp_list def make_filters(self): filters = frappe._dict() filters['company'] = self.company filters['branch'] = self.branch filters['department'] = self.dep...
signation return filters @frappe.whitelist() def fill_employee_details(self): self.set('employees', []) employees = self.get_emp_list() if not employees: error_msg = _("No employees found for the mentioned criteria:<br>Company: {0}<br> Currency: {1}<br>Payroll Payable Account: {2}").format( frappe.bo...
Diagon/CFApp
cakefactory/tests.py
Python
mit
79
0
# Write unit
tests to perform before implementation # Create your tests here
.
tuskar/tuskar-ui
horizon/tables/base.py
Python
apache-2.0
54,322
0.000295
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # ...
ounter = 0 transform = None name = None verbose_name = None status_choices = ( ('enabled', True), ('true', True), ('up', True), ('active', True), ('on', True), ('none', None), ('unknown', None), ('', None), ('disabled', False), ...
False), ('false', False), ('inactive', False), ('off', False), ) def __init__(self, transform, verbose_name=None, sortable=True, link=None, allowed_data_types=[], hidden=False, attrs=None, status=False, status_choices=None, display_choices=None, ...
argilo/contest-sdr
blade_rx.py
Python
gpl-3.0
14,830
0.009171
#!/usr/bin/env python2 # -*- coding: utf-8 -*- ################################################## # GNU Radio Python Flow Graph # Title: Blade Rx # Generated: Wed Jun 8 20:57:16 2016 ################################################## if __name__ == '__main__': import ctypes import sys if sys.platform.star...
map(i, colors[i]) self.if_waterfall.set_line_alpha(i, alphas[i]) self.if_waterfall.set_intensity_range(-120, 0) self._if_waterfall_win = sip.wrapin
stance(self.if_waterfall.pyqwidget(), Qt.QWidget) self.top_grid_layout.addWidge
jasonsahl/LS-BSR
tools/isolate_uniques_BSR.py
Python
gpl-3.0
1,944
0.00463
#!/usr/bin/env python """extract only the unique IDs from a BSR matrix""" from __future__ import print_function from optparse import OptionParser import sys import os def test_file(option, opt_str, value, parser): try: with open(value): setattr(parser.values, option.dest, value) except IOError: ...
s.exit() def filter_uniques(matrix, threshold): outfile = open("uniques_BSR_matrix", "w") with open(matrix) as in_matrix: firstLine = in_matrix.readline() outdata = [] with open(matrix) as in_matrix: for line in in_matrix: fields = line.split() totals = len(field...
for x in fields[1:]: try: if float(x)>=float(threshold): presents.append(fields[0]) except: pass if int(len(presents))<int(2): outdata.append(fields[0]) outfile.write(line) out...
dnlmc/fp
fp_scrape3.py
Python
mit
207
0.004831
import r
e # extract all <p> tags friend17 = friendsoup17.find_all('p') # remove html tags friend17clean = [] for i in range(len(friend17)): friend17clean.append(re.sub('<[^>]+>', '', friend17[i
]))
jballanc/openmicroscopy
components/tools/OmeroWeb/omeroweb/webstart/urls.py
Python
gpl-2.0
1,117
0.011638
#!/usr/bin/env python # -*- coding: utf-8 -*- # # # # Copyright (c) 2008 University of Dundee. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # publish
ed by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero...
s program. If not, see <http://www.gnu.org/licenses/>. # # Author: Aleksandra Tarkowska <A(dot)Tarkowska(at)dundee(dot)ac(dot)uk>, 2008. # # Version: 1.0 # from django.conf.urls import * from omeroweb.webstart import views urlpatterns = patterns('django.views.generic.simple', url( r'^$', views.index, name="we...
hva/warehouse
warehouse/skill/api/resources/product.py
Python
mit
1,071
0.001867
from tastypie import fields from tastypie.resources import ModelResource from warehouse.skill.api.meta import MetaBase from warehouse.skill.models import Product product_weight = 'SELECT SUM(weight) FROM skill_operation WHERE product_id = skill_product.id' product_len = 'SELECT SUM(len) FROM
skill_operation WHERE product_id = skill_product.id' class ProductResource(ModelResource): taxonomy_id = fields.IntegerField(attribute='taxonomy_id', null=True)
weight = fields.FloatField(attribute='weight', null=True) len = fields.FloatField(attribute='len', null=True) class Meta(MetaBase): queryset = Product.objects.all().extra(select={ 'weight': product_weight, 'len': product_len }) resource_name = 'product' ...
manthey/girder
plugins/authorized_upload/plugin_tests/upload_test.py
Python
apache-2.0
5,434
0.001656
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright 2016 Kitware 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 cop...
TOKEN_SCOPE_AUTHORIZED_UPLOAD, 'authorized_upload_folder_%s' % self.privateFolder['_id'] })
# Make sure this token doesn't let us upload into a different folder params = { 'parentType': 'folder', 'parentId': self.publicFolder['_id'], 'name': 'hello.txt', 'size': 11, 'mimeType': 'text/plain' } resp = self.request(path=...
gkabbe/cMDLMC
mdlmc/LMC/MDMC.py
Python
gpl-3.0
10,013
0.001398
# coding=utf-8 from abc import ABCMeta import logging from typing import Iterator import numpy as np from mdlmc.topo.topology import NeighborTopology from ..misc.tools import remember_last_element from ..LMC.output import CovalentAutocorrelation, MeanSquareDisplacement from ..cython_exts.LMC.PBCHelper import AtomBo...
yield sweep, delta_frame, kmc_time def xyz_output(self, particle_type: str = "H"): for f, t, frame in self: particle_positions = frame[self.donor_atoms][self.occupied_sites] particle_positions.atom_names = particle_type yield frame.append(particle_positions) def obs...
-------- reset_frequency: int print_frequency: int Returns ------- """ kmc_iterator = iter(self) donor_sites = self.donor_atoms current_frame_number, current_time, frame = next(kmc_iterator) autocorr = CovalentAutocorrelation(self.lattice) ...
paulrouget/servo
tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/wptmanifest/tests/test_static.py
Python
mpl-2.0
2,669
0.001499
import pytest import sys import unittest from ..backends import static # There aren't many tests here because it turns out to be way more convenient to # use test_serializer for the majority of cases @pytest.mark.xfail(sys.version[0] == "3", reason="wptmanifest.parser doesn't support py3") class ...
data = """ key: value [Heading 1] other_key: if a == 1: value_1 if a == 2: value_2 value_3 """ manifest = self.compile(data, {"a": 3}) children = list(item for item in manifest.iterchildren()) section = children[0] self.assertEquals(section.get("other_key"), "value...
1 if a[0] == "ab"[0]: value_2 """ manifest = self.compile(data, {"a": "1"}) self.assertEquals(manifest.get("key"), "value_1") manifest = self.compile(data, {"a": "ac"}) self.assertEquals(manifest.get("key"), "value_2") def test_get_4(self): data = """key: if not a: valu...
varun-verma11/CodeDrill
djangoSRV/djangoSRV/urls.py
Python
bsd-2-clause
4,085
0.002448
from django.conf.urls import patterns, include, url from django.contrib import admin from teacher import * from Views.teacher_view import get_teacher_view, get_overview, get_year_overview, get_class_overview, get_assignment_overview from Views.set_exercise import get_set_exercise_page, send_exercise_to_class, get_view_...
nt), url(r'^authenticate_teacher/$', authenticate_teacher), url(r'^student-login/$', student_login), url(r'^teacher-login/$', teacher_login), url(r'^register-student/$', register_student), url(r'^register-teacher/$', register_teacher), url(r'^student-view/$', get_student_view), url(r'^submit...
)/$', submit_student_code), url(r'^code-single-exercise/(\d+)/$', single_exercise_view), url(r'^student-grades/$', student_grades_view), url(r'^logout/$', logout_user), url(r'^view-spec/$', view_spec), url(r'^check-username/$', check_user_name_exists), url(r'^student/test/self-defined/$', run_se...
skkeeper/linux-clicky
linux_clicky/play_sound.py
Python
mit
691
0.005806
#!/usr/bin/env python2 # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 2 -*- # Author: Fábio André Damas <skkeeper at gmail dot com> from threading import Thread from subprocess import Popen, PIPE class PlaySound(Thread): def __init__(self, filename, volume): Thread.__init__(self) self...
rue) # TODO: Test if limits the number of clicks p.wait() if p.returncode != 0: print '\033[1;31mWe found a error with SoX, did you install it?\033[1;m' p.s
tderr.read()
batxes/4Cin
Six_zebra_models/Six_zebra_models_final_output_0.1_-0.1_13000/Six_zebra_models8148.py
Python
gpl-3.0
13,920
0.025216
import _surface import chimera try: import chimera.runCommand except: pass from VolumePath import markerset as ms try: from VolumePath import Marker_Set, Link new_marker_set=Marker_Set except: from VolumePath import volume_path_dialog d= volume_path_dialog(True) new_marker_set= d.new_marker_set marker_set...
s=new_marker_set('particle_2 geometr
y') marker_sets["particle_2 geometry"]=s s= marker_sets["particle_2 geometry"] mark=s.place_marker((4346, -175.265, 10569.5), (0.7, 0.7, 0.7), 681.834) if "particle_3 geometry" not in marker_sets: s=new_marker_set('particle_3 geometry') marker_sets["particle_3 geometry"]=s s= marker_sets["particle_3 geometry"] ma...
CingHu/neutron-ustack
neutron/extensions/loadbalancer.py
Python
apache-2.0
19,800
0.000303
# Copyright 2012 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless req...
ort abc from oslo.config import cfg import six from neutron.api import extensions from neutron.api.v2 import attributes as attr from neutron.api.v2 import base from neutron.api.v2 import resource_helper from neutron.common import exceptions as qexception from neutron import manager from neutron.plugins.common import ...
or equal to timeout") class NoEligibleBackend(qexception.NotFound): message = _("No eligible backend for pool %(pool_id)s") class VipNotFound(qexception.NotFound): message = _("Vip %(vip_id)s could not be found") class VipExists(qexception.NeutronException): message = _("Another Vip already exists for...
shidarin/AT-DiceRoller
modules/criticalInjuries.py
Python
gpl-3.0
29,380
0.013104
#!/usr/bin/kivy # Critical Injury Module # By Sean Wallitsch, 2013/08/20 # Built in Modules from random import randint from time import strftime # For timestamping history log # Kivy Modules from kivy.app import App # Base App Class from kivy.adapters.listadapter import ListAdapter # For History list from kivy.uix....
me = "Fearsome Wound" elif roll >= 46: name = "Head Ringer" elif roll >= 41: name = "Bowled Over" elif roll >= 36: name = "Stinger" elif roll
>= 31: name = "Stunned" elif roll >= 26: name = "Discouraging Wound" elif roll >= 21: name = "Off-Balance" elif roll >= 16: name = "Distracted" elif roll >= 11: name = "Sudden Jolt" elif roll >= 6: name = "Slowed Down" else: name = "Minor ...
rackerlabs/qonos
qonos/db/sqlalchemy/migrate_repo/versions/008_add_index_to_schedules.py
Python
apache-2.0
1,187
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2014 Rackspace Hosting # # 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-...
rue) index = Index(INDEX_NAME, schedules.c.n
ext_run) index.drop(migrate_engine)
Gebesa-Dev/Addons-gebesa
purchase_order_o2o_procurement/models/__init__.py
Python
agpl-3.0
148
0
# -*- coding: utf-8 -*- # © 2017 Cesar Barron
Bautista # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from . import purcha
se
plotly/python-api
packages/python/plotly/plotly/tests/test_orca/test_orca_server.py
Python
mit
5,402
0.001111
from unittest import TestCase import plotly.io as pio import subprocess import os from distutils.version import LooseVersion import requests import time import psutil import pytest import plotly.graph_objects as go # Fixtures # -------- from plotly.io._orca import find_open_port, which, orca_env @pytest.fixture() d...
assert pio.orca.status.port is not None assert pio.orca.status.pid is not None server_port = pio.orca.status.port server_pid = pio.orca.status.pid # Make sure server has time to start up time.sleep(10) # Check that server process number is valid assert
psutil.pid_exists(server_pid) # Build server URL server_url = "http://localhost:%s" % server_port # ping server assert ping_pongs(server_url) # shut down server pio.orca.shutdown_server() # Check that server process number no longer exists assert not psutil.pid_exists(server_pid) ...
elarsonSU/egret
egret.py
Python
gpl-3.0
7,045
0.021008
# egret.py: Command line interface for EGRET # # Copyright (C) 2016-2018 Eric Larson and Anna Kirk # [email protected] # # This file is part of EGRET. # # 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...
t = "outputFile", help = "output file name") parser.add_option("-d", "--debug", action = "store_true", dest = "debugMode", default = False, help = "display debug info") parser.add_option("-s", "--stat", action = "store_true", dest = "statMode", default = False, help = "display stats") parser.add_option("-g", "-...
default = False, help = "only show named groups") opts, args = parser.parse_args() # check for valid command lines if opts.fileName != None and opts.regex != None: print("Cannot specify both a regular expression and input file") sys.exit(-1) # get the regular expression descStr = "" if opts.fileName != None: ...
sisidra/scalegrease
setup.py
Python
apache-2.0
415
0.004819
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup setup(name='
scalegrease', version='1', url='https://github.com/spotify/scalegrease', description='A tool chain for executing batch processing jobs', packages=['scalegrease'], data_files=[('/etc', ['conf/scalegrease.json'])], scripts=[
'bin/greaserun', 'bin/greaseworker' ] )
steveb/heat
heat/engine/resources/openstack/mistral/workflow.py
Python
apache-2.0
27,192
0.000037
# # 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 # ...
ow level."), support_status=support.SupportStatus(version='5.0.0'), schema={ ON_SUCCE
SS: properties.Schema( properties.Schema.LIST, _('List of tasks which will run after ' 'the task has completed successfully.') ), ON_ERROR: properties.Schema( properties.Schema.LIST, _('...
thomashuang/white
white/controller/admin/extend.py
Python
gpl-2.0
1,282
0.0039
#!/usr/bin/env python # 2015 Copyright (C) White # # 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 2 of the License. #
# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along ...
TeamAADGT/CMPUT404-project-socialdistribution
service/posts/views.py
Python
apache-2.0
15,357
0.004558
import requests from django.db.models import Q from rest_framework import viewsets, views, generics, mixins, status, filters from rest_framework.decorators import list_route from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from service.authentication.node_basic import...
10-937d032d6875", "github": "" }, "categories": [ "1", "2", "3" ], "comments": [], "published": "2017-04-11T06:14:48.290000Z", "id":...
d-4567-a93d-e3e80356b9ab", "visibility": "PUBLIC", "visibleTo": [], "unlisted": false, "next": "http://127.0.0.1:8000/service/posts/d10a7f31-10ed-4567-a93d-e3e80356b9ab/comments", "count": 0, "size": 5 ...
alisaifee/flask-limiter
flask_limiter/contrib/__init__.py
Python
mit
28
0
""
"Contributed 'recipes'
"""
Bernardo-MG/dice-notation-python
dice_notation/dice.py
Python
mit
3,766
0
# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod from random import randint """ Dice classes. These are just plain dice, not dice notation, even thought they may be used for handling that too. The classes in this file will allow creating and using dice and rollable entities, which are able to generat...
raise NotImplementedError('The roll method must be implemented') class Dice(object): """ A group of dice, all with the same number of sides. Such a group is just composed of a quantity of dice, and their number of sides. Both the quantity and the number of sides are expected to be positive, a...
mber of sides which a die may physically have are limited by the rules of geometry, but there is no reason to take care of that. """ def __init__(self, quantity, sides): super(Dice, self).__init__() self._quantity = quantity self._sides = sides def __str__(self): re...
bcgov/gwells
app/backend/wells/migrations/0108_auto_20200213_1741.py
Python
apache-2.0
3,936
0.003049
# Generated by Django 2.2.10 on 2020-02-13 17:41 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wells', '0107_auto_20200116_2328'), ] operations = [ migrations.AlterField( model_name='activi...
er', null=True, on_delete=django.db.models.deletion.PROTECT, related_name='lithologydescription_set', to='wells
.ActivitySubmission'), ), migrations.AlterField( model_name='lithologydescription', name='well', field=models.ForeignKey(blank=True, db_column='well_tag_number', null=True, on_delete=django.db.models.deletion.PROTECT, related_name='lithologydescription_set', to='wells...
Hironsan/natural-language-preprocessings
tests/test_padding.py
Python
mit
3,501
0
import unittest from numpy.testing import assert_allclose from preprocessings.padding import pad_sequences, pad_char_sequences class TestPadding(unittest.TestCase): def test_pad_sequences(self): a = [[1], [1, 2], [1, 2, 3]] # test padding b = pad_sequences(a, maxlen=3, padding='pre') ...
[[0, 1], [1, 2], [2, 3]]) b = pad_sequences(a, maxlen=2, truncating='post') assert_allclose(b, [[0, 1], [1, 2], [1, 2]]) # test value b = pad_sequence
s(a, maxlen=3, value=1) assert_allclose(b, [[1, 1, 1], [1, 1, 2], [1, 2, 3]]) def test_pad_sequences_vector(self): a = [[[1, 1]], [[2, 1], [2, 2]], [[3, 1], [3, 2], [3, 3]]] # test padding b = pad_sequences(a, maxlen=3, padding='pre') assert_allclo...
backupManager/pyflag
src/plugins_old/NetworkForensics/ProtocolHandlers/POP.py
Python
gpl-2.0
9,518
0.015444
""" This module implements features specific for POP Processing """ # Michael Cohen <[email protected]> # Gavin Jackson <[email protected]> # # ****************************************************** # Version: FLAG $Version: 0.87-pre1 Date: Thu Jun 12 00:48:38 EST 2008$ # ************************...
valid pop command """ class POP: """ Class managing the pop connecti
on information """ def __init__(self,fd): self.fd=fd self.dispatcher={ "+OK" :self.NOOP, "-ERR" :self.NOOP, "DELE" :self.NOOP, "QUIT" :self.NOOP, } self.username='' self.password='' self.files=[] def read_m...
AlexBoogaard/Sick-Beard-Torrent-Edition
sickbeard/providers/bithdtv.py
Python
gpl-3.0
11,100
0.011622
################################################################################################### # Author: Jodi Jones <[email protected]> # URL: https://github.com/VeNoMouS/Sick-Beard # # This file is part of Sick Beard. # # Sick Beard is free software: you can redistribute it and/or modify # it under the terms of t...
rdate"])).replace('-', '.') search_string.append(ep_string) else: for show_name in set(show_name_helpers.allPossibleShowNames(show)): ep_string = show_name_helpers.sanitizeSceneName(show_name) +' '+ sickbeard.config.naming_ep_type[2]
% {'seasonnumber': season, 'episodenumber': int(sqlEp["episode"])} search_string.append(ep_string) return search_string ################################################################################################### def _get_episode_search_strings(se...
deathglitch/metarigging
python/metarig/cogcomponent.py
Python
mit
7,363
0.011544
import pymel.core as pm import component import keyablecomponent import metautil.nsutil as nsutil import metautil.miscutil as miscutil import metautil.rigutil as rigutil import rigging class CogComponent(keyablecomponent.KeyableComponent): LATEST_VERSION = 1 @staticmethod def create(metanode_parent, s...
iscutil.bake(objects = objects, time = (start_time, end_time)) return def _find_attach_point(self, location): return self.get_grips()[-1] def remove(self, bake = False): '''remove everything about this rig implementation''' if bake: self.
bake_to_skeleton() grip_group = self.get_ctrls_group() dnt_group = self.get_do_not_touch() pm.delete([self, dnt_group, grip_group]) return
daniel-j/lutris
lutris/util/yaml.py
Python
gpl-3.0
853
0
"""Utility functions for YAML handling""" # pylint: disable=no-member import yaml from lutris.util.log import logger from lutris.util.system import path_exists def read_yaml_from_file(filename): """Read filename and return parsed yaml""" if not path_exists(filename): return {} with open(filename...
parser.ParserError):
logger.error("error parsing file %s", filename) yaml_content = {} return yaml_content def write_yaml_to_file(filepath, config): if not filepath: raise ValueError("Missing filepath") yaml_config = yaml.dump(config, default_flow_style=False) with open(filepath, "w") as filehandle...
irgmedeiros/folhainvest
tests/context.py
Python
bsd-2-clause
107
0.018692
# -*- coding: utf-8 -*- import sys import os sys.path.insert(0, os.path.abspath('..
')) import fol
hainvest
yanweifu/reweighted-ws
learning/models/tests/test_nade.py
Python
agpl-3.0
797
0.005019
import unittest import numpy as np import theano import theano.tensor as T from test_rws import RWSLayerTest, RWSTopLayerTest # Unit Under Test from learning.models.nade import NADE,
NADETop #----------------------------------------------------------------------------- class TestNADETop(RWSTopLayerTest, unittest.TestCase): def setUp(self): self.n_samples = 10 self.layer = NADETop( n_X=8, n_hid=8, ) s...
ss TestNADE(RWSLayerTest, unittest.TestCase): def setUp(self): self.n_samples = 10 self.layer = NADE( n_X=16, n_Y=8, n_hid=8, ) self.layer.setup()
jucimarjr/IPC_2017-1
lista08/lista08_lista01_questao05.py
Python
apache-2.0
1,357
0.006752
#-----------------------------------------------
----------------------------------------------------------------------- # Introdução a Programação de Computadores - IPC # Universidade do Estado do Amazonas - UEA # Prof. Jucimar Jr # Antonio Diego Furtado da Silva 1715310004 # João Victor de Cordeiro 1515140036 # Matheus de Oliveira...
eddiejessup/clustrous
clustrous/cluster.py
Python
bsd-3-clause
5,950
0
import numpy as np from scipy.cluster import hierarchy as hc from clustrous._periodic_cluster import get_cluster_list def cluster(r, r_max): """ Group a set of points into distinct sets, based on their Euclidean distance. Uses the single-linkage criterion, meaning that if the distance between two ...
k: float Clumpiness measure. """ return np.sum(_clumpiness(clust_sizes, float(clust_sizes.sum()))) def _get_labels(linked_list): """Convert clusters represented as a linked list into a labels array. For example, `[1, 0, 2, 3]` represents a system where the firs
t two samples are in a single cluster, because the first points to the second, then the second points to the first. The last two point to themselves, and are thus in a cluster with a single sample. This function converts such a list into an array of integers, whose entries begin at zero and increas...
vitan/blaze
blaze/json.py
Python
bsd-3-clause
566
0.0053
from __future__ import absolute_import, division, print_function import json from toolz import map, partial import gzip from .resource import reso
urce __all__ = 'resource', @resource.register('.*\.json') def resource_json(uri, open=open): f = open(uri) try: data = json.load(f) f.close() return data except ValueError: f = open(uri) data = map(json.loads, f) return data @resource.register('.*\.json.gz...
en, mode='rt'))
somewun/Calcwylator
Calcwylator.py
Python
gpl-3.0
4,221
0.007818
#Calcwylator using Python 3 and tkinter print("""Calcwylator Version 0.1.0 Copyright (C) 2016 Somewun This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.""") f...
gebox import * #menu functions def About(): showinfo("Help", "This is
a simple calculator using Python 3 and Tkinter. \nThis is going to be the help information.") def license(): showinfo("License", """Calcwylator, a simple lightweight calculator. Version 0.1.0. Copyright (C) 2016 Somewun This program is free software: you can redistribute ...
artemrizhov/pymorphy
example.py
Python
mit
1,319
0.00453
#coding: utf-8 import re import pymorphy import pymorphy.utils text = u''' Сяпала Калуша по напушке и увазила бутявку. И волит: — Калушата,
калушаточки! Бутявка! Калушата присяпали и бутявку стрямкали. И подудонились. А Калуша волит: — Оее, оее! Бутявка-то некузявая! Калушата бутявку вычучили. Бутявка вздребезнулась, сопритюкнулась и усяпала с напушки. А Калуша волит: — Бутявок не трямкают. Бутявки дюбые и зюмо-зюмо некузявые. От бутявок дудонятся. А бутя...
+-]',re.U) words = r.split(text.upper()) # тут нужно прописать путь до папки со словарями morph = pymorphy.get_morph('dicts/converted/ru') for word in words: if word: print word info = morph.get_graminfo(word) for form in info: pymorphy.utils.pprint(form)
mschwager/CTFd
CTFd/admin/challenges.py
Python
apache-2.0
7,890
0.002155
from flask import current_app as app, render_template, request, redirect, jsonify, url_for, Blueprint from CTFd.utils import admins_only, is_admin, unix_time, get_config, \ set_config, sendmail, rmdir, create_image, delete_image, run_image, container_status, container_ports, \ container_stop, container_start, g...
ll() json_data = {'tags': []} for x in tags: json_data['tags'].append({'id': x.id, 'chal': x.chal, 'tag': x.tag}) return jsonify(json_data) @admin_challenges.route('/admin/chal/new', methods=['GET', 'POST']) @admins_only def admin_create_chal(): if request.method == 'POST': ...
# Create challenge chal = Challenges(request.form['name'], request.form['desc'], request.form['value'], request.form['category'], int(request.form['chaltype'])) if 'hidden' in request.form: chal.hidden = True else: chal.hidden = False max_attempts = req...
antoinecarme/pyaf
tests/artificial/transf_RelativeDifference/trend_Lag1Trend/cycle_0/ar_/test_artificial_32_RelativeDifference_Lag1Trend_0__100.py
Python
bsd-3-clause
273
0.084249
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ =
'D', seed = 0, t
rendtype = "Lag1Trend", cycle_length = 0, transform = "RelativeDifference", sigma = 0.0, exog_count = 100, ar_order = 0);
ahmedaljazzar/edx-platform
lms/djangoapps/courseware/module_render.py
Python
agpl-3.0
49,790
0.002752
""" Module rendering """ import hashlib import json import logging from collections import OrderedDict from functools import partial from completion.models import BlockCompletion from completion import waffle as completion_waffle from django.conf import settings from django.contrib.auth.models import User from django...
as_access from courseware.entrance_exams import user_can_skip_entrance_exam, user_has_passed_entrance_exam from courseware.masquerade import ( MasqueradingKeyValueStore, filter_displayed_blocks, is_masquerading_as_specific_student, setup_masquerade ) from courseware.model_data import DjangoKeyValueStore...
import SCORE_PUBLISHED from lms.djangoapps.lms_xblock.field_data import LmsFieldData from lms.djangoapps.lms_xblock.models import XBlockAsidesConfig from lms.djangoapps.lms_xblock.runtime import LmsModuleSystem from lms.djangoapps.verify_student.services import XBlockVerificationService from openedx.core.djangoapps.boo...
chaen/DIRAC
Core/Utilities/Graphs/__init__.py
Python
gpl-3.0
4,843
0.050795
""" DIRAC Graphs package provides tools for creation of various plots to provide graphical representation of the DIRAC Monitoring and Accounting data The DIRAC Graphs package is derived from the GraphTool plotting package of the CMS/Phedex Project by ... <to be added> """ from __future__ import print_func...
defaults = graph_large_prefs graph =
Graph() graph.makeGraph( data, common_prefs, defaults, prefs ) graph.writeGraph( fileName, 'PNG' ) return DIRAC.S_OK( {'plot':fileName} ) def __checkKW( kw ): if 'watermark' not in kw: kw[ 'watermark' ] = "%s/DIRAC/Core/Utilities/Graphs/Dwatermark.png" % DIRAC.rootPath return kw def barGraph( data, file...
metacloud/molecule
setup.py
Python
mit
12,584
0
#! /usr/bin/env python # Copyright (c) 2019 Red Hat, Inc. # Copyright (c) 2015-2018 Cisco Systems, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including w...
) ) def verify_required_python_runtime(s): @functools.wraps(s) def sw(**attrs): try: validate_required_python_or_fail(attrs.get('python_requires')) except Runtim
eError as re: sys.exit('{} {!s}'.format(attrs['name'], re)) return s(**attrs) return sw setuptools.setup = ignore_unknown_options(setuptools.setup) setuptools.setup = verify_required_python_runtime(setuptools.setup) try: from configparser import ConfigParser, No...
jeremiah-c-leary/vhdl-style-guide
vsg/rules/package_body/rule_501.py
Python
gpl-3.0
563
0
from vsg.rules import token_case from vsg import token lTokens = [] lTokens.append(token.package_body.body_keyword) class rule_501(token_case): ''' This rule checks the **body** keyword has proper case. |configuring_uppercase_and_lowercase_rules_link| **Violation**
.. code-block:: vhdl packa
ge BODY FIFO_PKG is **Fix** .. code-block:: vhdl package body FIFO_PKG is ''' def __init__(self): token_case.__init__(self, 'package_body', '501', lTokens) self.groups.append('case::keyword')
c4fcm/CivilServant
tests/test_stylesheet_experiment_controller.py
Python
mit
19,514
0.014861
import pytest import os, yaml ## SET UP THE DATABASE ENGINE TEST_DIR = os.path.dirname(os.path.realpath(__file__)) BASE_DIR = os.path.join(TEST_DIR, "../") ENV = os.environ['CS_ENV'] = "test" from mock import Mock, patch import unittest.mock import simplejson as json import sqlalchemy from sqlalchemy import create_e...
stylesheet.return_value = stylesheet r.set_stylesheet.return_value = {"errors":[]} patch('praw.') experiment_name = "stylesheet_experiment_test" with open(os.path.join(BASE_
DIR,"config", "experiments", experiment_name + ".yml"), "r") as f: experiment_config = yaml.full_load(f)['test'] controller = StylesheetExperimentController(experiment_name, db_session, r, log) for condition in ['special', 'normal']: for arm in ["arm_0", "arm_1"]: assert (controller...
a-parhom/edx-platform
pavelib/paver_tests/test_paver_pytest_cmds.py
Python
agpl-3.0
7,433
0.00444
""" Tests for the pytest paver commands themselves. Run just this test with: paver test_lib -t pavelib/paver_tests/test_paver_pytest_cmds.py """ import unittest import os import ddt from pavelib.utils.test.suites import SystemTestSuite, LibTestSuite from pavelib.utils.envs import Env XDIST_TESTING_IP_ADDRESS_LIST = ...
, processes=3) assert suite.cmd == self._expected_command(system, test_id, "LibTestSuite", processes=3) @ddt.data('common/lib/xmodule', 'pavelib/paver_tests') def test_LibTestSuite_with_xdist(self, system): test_id = 'tests'
suite = LibTestSuite(system, test_id=test_id, xdist_ip_addresses=XDIST_TESTING_IP_ADDRESS_LIST) assert suite.cmd == self._expected_command(system, test_id, "LibTestSuite", xdist_ip_addresses=XDIST_TESTING_IP_ADDRESS_LIST) @ddt.data('common/lib/xmodule',...
apache/bloodhound
bloodhound_multiproduct/tests/resource.py
Python
apache-2.0
14,341
0.000768
# -*- coding: utf-8 -*- # # 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 (...
p(self): ProductResourceTestCase.setUp(self) self.global_env.path = os.path.join(tempfile.gettempdir(), 'trac-tempenv') if os.path.exists(self.global_env.path): shutil.rmtree(self.global_env.path) os.mkdir(self.global_env.path) ...
xt', StringIO(''), 0) attachment = Attachment(self.env1, 'ticket', 1) attachment.description = 'Product Bar' attachment.insert('foo.txt', StringIO(''), 0) self.resource = resource.Resource('ticket', 1).child('attachment', 'foo.txt') def tea...
Passw/gn_GFW
build/android/gyp/proguard.py
Python
gpl-3.0
3,458
0.011857
#!/usr/bin/env python # # Copyright 201
3 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import optparse import os import sys from util import build_utils from util import proguard_util _DANGEROUS_OPTIMIZATIONS = [ "class/unboxing/enum", # See crb
ug.com/625992 "code/allocation/variable", # See crbug.com/625994 "field/propagation/value", "method/propagation/parameter", "method/propagation/returnvalue", ] def _ParseOptions(args): parser = optparse.OptionParser() build_utils.AddDepfileOption(parser) parser.add_option('--proguard-path', ...
wireservice/csvkit
csvkit/utilities/csvsort.py
Python
mit
2,282
0.003067
#!/usr/bin/env python import agate from csvkit.cli import CSVKitUtility, parse_column_identifiers class CSVSort(CSVKitUtility): description = 'Sort CSV files. Like the Unix "sort" command, but for tabular data.' def add_arguments(self): self.argparser.add_argument( '-n', '--names', dest...
order_by(column_ids, reverse=self.args.reverse) t
able.to_csv(self.output_file, **self.writer_kwargs) def launch_new_instance(): utility = CSVSort() utility.run() if __name__ == '__main__': launch_new_instance()
h2oai/h2o-dev
h2o-py/h2o/h2o.py
Python
apache-2.0
72,871
0.005201
# -*- encoding: utf-8 -*- """ h2o -- module for using H2O services. :copyright: (c) 2016 H2O.ai :license: Apache License Version 2.0 (see LICENSE for details) """ from __future__ import absolute_import, division, print_function, unicode_literals import logging import os import warnings import webbrowser import type...
ra_classpath=None, jvm_custom_args=None, bind_to_localhost=True, **kwargs): """ Attempt to connect to a local server, or if not successful start a new server and connect to it. :param url: Full URL of the server to connect
to (can be used instead of `ip` + `port` + `https`). :param ip: The ip address (or host name) of the server where H2O is running. :param port: Port number that H2O service is listening to. :param name: cloud name. If None while connecting to an existing cluster it will not check the cloud name. ...
Crystalnix/serverauditor-sshconfig
termius/porting/providers/securecrt/parser.py
Python
bsd-3-clause
3,259
0
# -*- coding: utf-8 -*- """Module with SecureCRT parser.""" from os.path import expanduser class SecureCRTConfigParser(object): """SecureCRT xml parser.""" meta_sessions = ['Default'] def __init__(self, xml): """Construct parser instance.""" self.xml = xml self.tree = {} def...
if identity is None: return None identity_filename = self.get_element_by_name( list(identity), 'Identity Filename V2' ) if not self.check_attribute(identity_filename):
return None path = identity_filename.text.split('/') public_key_name = path[-1].split('::')[0] private_key_name = public_key_name.split('.')[0] if path[0].startswith('$'): path.pop(0) path.insert(0, expanduser("~")) path[-1] = public_key_name pu...
CapitalD/taplist
migrations/versions/34223fdff008_.py
Python
mit
807
0.002478
"""empty message Revision ID: 34223fdff008 Revises: b4bcea5528b6 Create Date: 2017-08-22 10:19:27.959749 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '34223fdff008' down_revision = 'b4bcea5528b6' branch_labels = None depends_on = None def upgrade(): # ...
.Integer(), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_co
lumn('person', 'default_location') op.drop_column('person', 'default_brewery') # ### end Alembic commands ###
fragglet/midisnd
midi.py
Python
isc
4,962
0.018541
#!/usr/bin/env python # # Copyright (c) 2015, Simon Howard # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND TH...
"Orchestra Hit", "Trumpet", "Trombone", "Tuba", "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax", "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet", "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle"...
, "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass + lead)", "Pad 1 (new age)", "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)", "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)", "FX 4 (atmosphere)", "FX 5 (brightn...
Tancata/phylo
ALE/gene_originations_at_node.py
Python
mit
1,475
0.006102
#from ALE reconciliations, print a list of gene fams originating at a node with P > 0.5. #python gene_copies_at_node.py reconciliation_file_dir node_number protein_outputfile import re, os, sys directory = sys.argv[1] node = int(sys.argv[2]) predicted_proteome_output_file = sys.argv[3] ancestral_threshold = 0.5 total...
for file in os.listdir(directory) if file.endswith("uml_rec")] print "GeneFam\tCopies" for file in to_parse: name_fields = re.split("faa", file) fam_name = '' representative_name = '' fam_name = name_fields[0] + "faa" representative_name = name_fields[0] + "_representative.fa" inh = open(direct...
if fields[0] == "S_internal_branch" and int(fields[1]) == node: print fam_name + "\t" + str(fields[-2]) total_num_gene_originations += float(fields[-2]) #if above the threshold for including in the node protein content reconstruction, do so now if float(f...
hellhovnd/dentexchange
dentexchange/apps/employer/urls.py
Python
bsd-3-clause
3,483
0.012346
# -*- coding:utf-8 -*- from django.conf.urls import patterns, url from django.core.urlresolvers import reverse_lazy from libs.decorators import login_required_for, EMPLOYER, EMPLOYEE from membership.decorators import enforce_membership from .decorators import enforce_business from . import views urlpatterns = pattern...
enforce_membership( views.AddNewPostingFormView.as_view()))), name='add_new_posting'), url(r'^practice_profile/posting/edit/(?P<pk
>\d+)/$', login_required_for(EMPLOYER)( enforce_business( enforce_membership( views.EditPostingFormView.as_view()))), name='edit_posting'), url(r'^practice_profile/posting/delete/$', login_required_for(EMPLOYER)( enforce_business( enforce_membership( ...
mwrlabs/veripy
contrib/rfc3736/builder.py
Python
gpl-3.0
1,149
0.007833
from scapy.all import * from scapy.layers import dhcp6 from time import time def duid(ll_addr): return DUID_LLT(lladdr=ll_addr, timeval=time()) def ias(requested, iface, T1=None, T2=None): return map(lambda r: __build_ia(r, iface, T1, T2), requested) def opti
ons(requested): return map(__build_option_by_code, requested) def __build_ia(request, iface, T1=None, T2=None): ia = reques
t.__class__(iaid=request.iaid, T1=(T1 == None and request.T1 or T1), T2=(T2 == None and request.T2 or T2)) ia.ianaopts.append(DHCP6OptIAAddress(addr=str(iface.global_ip()), preflft=300, validlft=300)) return ia def __build_option_by_code(code): opt = __option_klass_by_code(code)() if isinstance(opt,...
crobinso/virt-manager
virtinst/domain/launch_security.py
Python
gpl-2.0
1,325
0.001509
from ..xmlbuilder import XMLBuilder, XMLProperty class DomainLaunchSecurity(XMLBuilder): """ Class for generating <launchSecurity> XML element """ XML_NAME = "launchSecurity" _XML_PROP_ORDER = ["type", "cbitpos", "reducedPhysBits", "policy", "session", "dhCert"] type = XMLPropert...
True) reducedPhysBits = XMLProperty("./reducedPhysBits", is_int=True) policy = XMLProperty("./policy") session = XMLProperty("./session") dhCert = XMLProperty("./dhCert") kernelHashes = XMLProperty("./@kernelHashes", is_yesno=True) def _set_defaults_sev(self, guest): if not guest.os.is_...
rmware, # if missing, let's use 0x03 which, according to the table at # https://libvirt.org/formatdomain.html#launchSecurity: # (bit 0) - disables the debugging mode # (bit 1) - disables encryption key sharing across multiple guests if self.policy is None: self.policy...
Joacchim/Comix
src/archive.py
Python
gpl-2.0
20,550
0.001265
# coding=utf-8 """archive.py - Archive handling (extract/create) for Comix.""" from __future__ import absolute_import import cStringIO import os import re import sys import tarfile import threading import zipfile import gtk try: from py7zlib import Archive7z except ImportError: Archive7z = None # ignore it....
" <i>unrar</i> program installed in order " "to read RAR (.cbr) files.")) dialog.run() dialog.destroy() return None proc = process.Process([_rar_exec, 'vb', '-p-', '--', src]) ...
beagles/neutron_hacking
neutron/plugins/oneconvergence/plugin.py
Python
apache-2.0
11,208
0.000446
# Copyright 2014 OneConvergence, 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 requir...
net_id) self.nvsdlib.delete_network(network, subnets) def creat
e_subnet(self, context, subnet): if subnet['subnet']['ip_version'] == IPv6: raise nexception.InvalidInput( error_message="NVSDPlugin doesn't support IPv6.") neutron_subnet = super(OneConvergencePluginV2, self).create_subnet(context, subnet) ...
Iconik/eve-suite
src/model/static/crt/relationship.py
Python
gpl-3.0
1,456
0.00206
from model.flyweight import Flyweight
from model.static.database import database class Relationship(Flyweight): def __init__(self, relationship_id): #prevents reinitializing if "_inited" in self.__dict__: return self._inited = None #prevents reinitializing self.relationship_id = relationship_id ...
hone() self.parent_id = row["parentID"] self.parent_type_id = row["parentTypeID"] self.parent_level = row["parentLevel"] self.child_id = row["childID"] cursor.close() self._parent = None self._parent_type = None self._child = None def get_parent(se...
he7d3r/ores
ores/score_request.py
Python
mit
3,803
0.000526
import json class ScoreRequest: def __init__(self, context_name, rev_ids, model_names, precache=False, include_features=False, injection_caches=None, model_info=None, ip=None): """ Construct a ScoreRequest from parameters. :Parameters: context...
"include_features={0!r}".format(self.include_features), "injection_caches={0!r}".format(self.injection_caches), "ip={0!r}".format(self.ip), "model_info={0!r}".format(self.model_info)])) de
f to_json(self): return { 'context': self.context_name, 'rev_ids': list(self.rev_ids), 'model_names': list(self.model_names), 'precache': self.precache, 'include_features': self.include_features, 'injection_caches': self.injection_caches, ...
kenrick95/airmozilla
airmozilla/roku/views.py
Python
bsd-3-clause
5,212
0
from django.contrib.sites.models import RequestSite from django.shortcuts import render from django.conf import settings from django.db.models import Q from django.core.urlresolvers import reverse from airmozilla.main.models import Channel, Event from airmozilla.main.views import is_contributor from airmozilla.base.ut...
r = {} privacy_exclude = {} if request.user.is_active: if is_contributor(request.user): privacy_exclude = {'privacy': Event.PRIVACY_COMPANY} else: privacy_filter = {'privacy': Event.PRIVACY_PUBLIC} if privacy_filter: events = events.filt
er(**privacy_filter) elif privacy_exclude: events = events.exclude(**privacy_exclude) events = events.order_by('-start_time') paged = paginate(events, 1, 100) return render_channel_events(paged, request) def trending_feed(request): events = get_featured_events( None, # across all...
desihub/desisurvey
py/desisurvey/tiles.py
Python
bsd-3-clause
19,547
0.000409
"""Manage static information associated with tiles, programs and passes. Each tile has an assigned program name. The program names (DARK, BRIGHT) are predefined in terms of conditions on the ephemerides, but not all programs need to be present in a tiles file. Pass numbers are arbitrary integers and do not need to be ...
Array of MJD to use. If mask is None, then should have length ``self.ntiles``. Otherwise, should have a value per non-zero entry in the mask. mask : array or None Boolean mask of which tiles to perform the calculation for. Returns ------- array ...
"" mjd = np.atleast_1d(mjd) if len(mjd) == 0: return np.zeros(0, dtype='f8') tt = Time(mjd, format='mjd', location=desisurvey.utils.get_location()) lst = tt.sidereal_time('apparent').to(u.deg).value ha = lst - self.tileRA[mask] return self.airmass(ha, mask=ma...
belokop/indico_bare
indico/modules/rb/models/aspects_test.py
Python
gpl-3.0
1,299
0.00154
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico 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 (a...
ted in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # a
long with Indico; if not, see <http://www.gnu.org/licenses/>. from indico.modules.rb.models.aspects import Aspect pytest_plugins = 'indico.modules.rb.testing.fixtures' def test_default_on_startup(dummy_location, db): aspect = Aspect(name=u'Test', center_latitude='', center_longitude='', zoom_level=0, top_left_...
badloop/SickRage
lib/tvdb_api/tvdb_cache.py
Python
gpl-3.0
7,781
0.003984
#!/usr/bin/env python2 #encoding:utf-8 #author:dbr/Ben #project:tvdb_api #repository:http://github.com/dbr/tvdb_api #license:unlicense (http://unlicense.org/) """ urllib2 caching handler Modified from http://code.activestate.com/recipes/491261/ """ from __future__ import with_statement __author__ = "dbr/Ben" __versio...
if exists_in_cache( self.cache_location, request.get_full_url(), self.max_age ): return CachedResponse( self.cache_location, request.get_full_url(), set_cache_header = True ) else: return None d...
request and the status code starts with 2 (200 OK etc) it caches it and returns a CachedResponse """ if (request.get_method() == "GET" and str(response.code).startswith("2") ): if 'x-local-cache' not in response.info(): # Response is not cached ...
codeadict/kushillu
kushillu/views.py
Python
mit
8,944
0.001789
import datetime import uuid import pytz import os import time from django.contrib.sites.shortcuts import get_current_site from django.core.servers.basehttp import FileWrapper from django.views.decorators.csrf import csrf_exempt from django.core.urlresolvers import reverse, resolve from django.db.models import FieldDoes...
ck(self.request, self.object) if self.object.complete: self.status = 202 if self.object.process_log
: self.object.process_log = self.object.process_log.replace(self.object.project.github_token, '<github token>') return super(BuildDetails, self).get_context_data(**kwargs) build_details_ajax = login_required(BuildDetails.as_view(...
UdK-VPT/Open_eQuarter
mole3x/extensions/acqu_berlin/fbinter_wfs_buildings_alk.py
Python
gpl-2.0
6,104
0.012615
# -*- coding: utf-8 -*- from qgis.core import NULL from mole3.project import config from mole3.oeq_global import OeQ_get_bld_id, isnull from qgis.PyQt import QtGui, QtCore def load(self=None): self.load_wfs() return True def preflight(self=None): from mole3.project import config from qgis.PyQt.QtCor...
features = layer.getFeatures() layer.startEditing() for i in features: i[config.building_id_key] = OeQ_get_bld_id() layer.updateFeature(i) layer.commitChanges() return True def evaluation(self=None, parameters={},feature=None): from qgis.PyQt.QtCore import QVariant from qgis...
oordinateReferenceSystem ar = NULL per = NULL id = NULL flr = NULL usage = NULL kind = NULL gkn = NULL da_engine=QgsDistanceArea() #print (QgsCoordinateReferenceSystem(int(config.project_crs.split(':')[-1]))) #print(QgsCoordinateReferenceSystem.EpsgCrsId) #da_engine.setSource...
lukaszb/nose-alert
nosealert/tests/test_plugin.py
Python
bsd-2-clause
1,067
0.000937
import unittest from mock import Mock from nosealert.plugin import AlertPlugin from nosealert.notifications import Notification class TestAlertPlugin(unittest.TestCase): def setUp(self): self.plugin = AlertPlugin() def test_get_notification_success(self): result = Mock( failures=...
ails(self): result = Mock( failures=[1, 2], errors=[3], testsRun=5, ) self.assertEqual(self.plugin.get_notification(result), Notification( fails=2, errors=1, total=5, )) def test_finalize_sends_notification(sel...
ification = Mock() result = Mock() self.plugin.get_notification = Mock(return_value=notification) self.plugin.finalize(result) notification.send.assert_called_once_with()
1tush/reviewboard
reviewboard/admin/validation.py
Python
mit
1,557
0.000642
from __future__ import unicode_literals from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ def validate_bug_tracker(input_url): """ Validates that an issue tracker URI string contains one `%s` Python format specification type (no other types are supporte...
t TypeError: raise ValidationError([ _("The URL '%s' is not valid because it contains a format " "
character. For bug trackers other than 'Custom Bug Tracker', " "use the base URL of the server. If you need a '%%' character, " "prepend it with an additional '%%'.") % input_url])
ThiefMaster/indico
indico/modules/events/reminders/forms.py
Python
mit
5,113
0.004694
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from wtforms.fields import BooleanField, SelectField, TextAreaField from wtforms.validators import DataReq...
raise ValidationError(_('At least one type of recipient is required.')) def validate_schedule_type(self, field): # Be graceful and allow a reminder that's in the past but on the same day. # It will be sent immediately but that way we are a little bit more user-friendly if field.data =...
return scheduled_dt = self.scheduled_dt.data if scheduled_dt is not None and scheduled_dt.date() < now_utc().date(): raise ValidationError(_('The specified date is in the past')) @generated_data def scheduled_dt(self): if self.schedule_type.data == 'absolute': ...
nachandr/cfme_tests
cfme/scripting/release.py
Python
gpl-2.0
6,579
0.00304
#!/usr/bin/env python3 import re import sys from collections import defaultdict from datetime import datetime from datetime import timedelta import click import github import tabulate from cfme.utils.conf import docker REPO_NAME = "ManageIQ/integration_tests" MASTER = 'master' HEADERS = ['PR', 'Labels', 'Author',...
cts old_date = old_release.created_at # add to start datetime else it will include the commit for the release, not part of the diff old_date = old_date + timedelta(seconds=5) if release == MASTER: new_date = datetime.now() else: new_date = release.created_at pulls = gh.search_is...
( "", # empty query string, required positional arg type="pr", repo=REPO_NAME, merged=f'{old_date.isoformat()}..{new_date.isoformat()}', # ISO 8601 datetimes for range ) prs = [] pr_nums_without_label = [] for pr in pulls: prs.append(pr) for label in pr...
SSNico/XLParser
lib/Irony/Irony.Samples/SourceSamples/fib.py
Python
mpl-2.0
97
0.123711
def fib (n): if n < 2: return 1
else: return fib (n -
1) + fib(n - 2) fib(34)
DedMemez/ODS-August-2017
parties/PartyCogActivity.py
Python
apache-2.0
29,414
0.002618
# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.parties.PartyCogActivity from panda3d.core import CollideMask, CollisionHandler, CollisionHandlerEvent, CollisionNode, CollisionSphere, NodePath, Point3, TextNode, Texture from direct.interval.MetaInterval import Sequence, Parallel, Track from direc...
re(reskinTexture, 100) self.enable() def _initArenaDoors(self): self._arenaDoors = (self.arena.find('**/doorL'), self.arena.find('**/doorR')) arenaDo
orLocators = (self.arena.find('**/doorL_locator'), self.arena.find('**/doorR_locator')) for i in xrange(len(arenaDoorLocators)): arenaDoorLocators[i].wrtReparentTo(self._arenaDoors[i]) self._arenaDoorTimers = (self.createDoorTimer(PartyGlobals.TeamActivityTeams.LeftTeam), self.createDoo...
hexforge/pulp_db
experiments/tries/comparison/datrie/bench/speed.py
Python
apache-2.0
9,330
0.004089
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals, division import random import string import timeit import os import zipfile import datrie def words100k(): zip_name = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'words100k.txt.zip...
ata.values())', ' ops/sec', 1, 1), ('keys()', 'list(data.keys())', ' ops/sec', 1, 1), ('items()', 'list(data.items())', ' ops/sec', 1, 1), ] common_setup = """ from __main__ import create_trie, WORDS100k, NON_WORDS100k, MIXED_WORDS100k, datrie from __main__ import PREFIXES_3_1k, PREFIXES_5_1k, ...
= ['ыва', 'xyz', 'соы', 'Axx', 'avы']*200 """ dict_setup = common_setup + 'data = dict((word, 1) for word in words); empty_data=dict()' trie_setup = common_setup + 'data = create_trie(); empty_data = datrie.Trie(ALPHABET)' for test_name, test, descr, op_count, repeats in tests: t_dict = timeit.Tim...
rkq/cxxexp
third-party/src/boost_1_56_0/libs/geometry/doc/make_qbk.py
Python
mit
6,060
0.016337
#! /usr/bin/env python # -*- coding: utf-8 -*- # =========================================================================== # Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. # Copyright (c) 2008-2012 Bruno Lalande, Paris, France. # Copyright (c) 2009-2012 Mateusz Loskot ([email protected]), Lon...
k" def run_command(command): if os.system(command) != 0: raise Exception("Error running %s" % command) def remove_all_files(dir): if os.path.exists(dir): for f in os.listdir(dir): os.remove(dir+f) def call_doxygen(): os.chdir("doxy") remove_all_files("doxygen_output/xml/")...
ion)) def model_to_quickbook(section): run_command(cmd % ("classboost_1_1geometry_1_1model_1_1" + section.replace("_", "__"), section)) def model_to_quickbook2(classname, section): run_command(cmd % ("classboost_1_1geometry_1_1model_1_1" + classname, section)) def struct_to_quickbook(section): run_comman...
maurizi/otm-core
opentreemap/treemap/migrations/0009_restructure_replaceable_terms.py
Python
agpl-3.0
1,359
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def replace_terms_forward(apps, schema_editor): Instance = apps.get_model("treemap", "Instance") instances = Instance.objects.filter(config__contains='\"terms\":') for instance in instances: terms = i...
"terms\":') for instance in instances: terms = instance.config.terms
if (('Resource' in terms and isinstance(terms['Resource'], dict))): terms['Resources'] = terms['Resource.plural'] terms['Resource'] = terms['Resource.singular'] instance.save() class Migration(migrations.Migration): dependencies = [ ('treemap', '0...
51reboot/actual_09_homework
03/huxianglin/FileCopy.py
Python
mit
1,225
0.013875
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------- 因为不确定需要拷贝的文件是什么格式,所以使用二进制读取文件并拷贝到目的文件。 为了解决拷贝大文件的时候机器内存不足,设定了每次读取文件的字节数,该字节数可以自己设置。 ------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------- ''' def CopyFile(SrcFile,DestFile,TmpSize): SF=open(SrcFile,'rb') DF=open(DestFile,'wb') try: while True: Tmp=SF.read(TmpSize) if not Tmp: break ...
MiltosD/CEF-ELRC
metashare/utils.py
Python
bsd-3-clause
4,061
0.002955
''' This file holds globally useful utility classes and functions, i.e., classes and functions that are generic enough not to be specific to one app. ''' import logging import os import re import sys from datetime import tzinfo, timedelta from django.conf import settings # Setup logging support. LOGGER = l
ogging.getLogger(__name__) LOGGER.addHandler(settings.LOG_HANDLER) # try to import the `fcntl` module for locking support through the `Lock` class # below try:
import fcntl except ImportError: LOGGER.warn("Locking support is not available for your (non-Unix?) system. " "Using multiple processes might not be safe.") def get_class_by_name(module_name, class_name): ''' Given the name of a module (e.g., 'metashare.resedit.admin') and the name of a c...
Juniper/neutron
neutron/plugins/ryu/db/api_v2.py
Python
apache-2.0
8,246
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Isaku Yamahata <yamahata at private email ne jp> # 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 #...
unnel_key >= :last_key ' # 'ORDER BY new_key LIMIT 1) ' # # 'ORDER BY new_key LIMIT 1' # ).params(last_key=last_key).one() try: new_key = session.query("new_key").from_statement( # If last_key + 1 isn't used, it's the result 'SE...
'FROM (SELECT :last_key + 1 AS new_key) q1 ' 'WHERE NOT EXISTS ' '(SELECT 1 FROM tunnelkeys WHERE tunnel_key = :last_key + 1) ' ).params(last_key=last_key).one() except orm_exc.NoResultFound: new_key = session.query("new_key").from_statement...
danielrd6/ifscube
cubetools.py
Python
gpl-3.0
39,584
0.008034
""" Functions for the analysis of integral field spectroscopy. Author: Daniel Ruschel Dutra Website: https://github.com/danielrd6/ifscube """ from numpy import * import pyfits as pf import spectools as st import matplotlib as mpl import matplotlib.pyplot as plt from scipy.integrate import trapz from copy import deepc...
(z) of the source, if no Doppler correction has been applied to the spectra yet. vortab : string Name of the file con
taining the Voronoi binning table Returns: -------- Nothing. """ if len(pf.open(fitsfile)) == 2: dataext, hdrext = 1,0 elif len(pf.open(fitsfile)) == 1: dataext, hdrext = 0,0 self.data = pf.getdata(fitsfile,ext=dataext) self.head...
tailhook/zerogw
examples/tabbedchat/tabbedchat/redis.py
Python
mit
2,974
0.003026
"""Redis client protocol We have own redis wrapper because redis-py does not support python3. We also don't want another dependency """ import socket def encode_command(buf, parts): add = buf.extend add(('*%d\r\n' % len(parts)).encode('ascii')) for part in parts: if isinstance(part, str): ...
elif ch == 36: # b'$' ln = int(line[1:]) if ln < 0: return None res = self._read_slice(ln) ass
ert self._read_line() == b'' return res else: raise NotImplementedError(ch) def _read_line(self): while True: idx = self._buf.find(b'\r\n') if idx >= 0: line = self._buf[:idx] del self._buf[:idx+2] retur...
lucyparsons/OpenOversight
OpenOversight/app/utils.py
Python
gpl-3.0
21,683
0.001245
from typing import Optional from future.utils import iteritems from urllib.request import urlopen from io import BytesIO import boto3 from botocore.exceptions import ClientError import botocore import datetime import hashlib import os import random import sys from traceback import format_exc from distutils.util impo...
rm.first_name.data, last_name=form.last_name.data, middle_initial=form.middle_initial.data, suffix=form.suffix.data, race=form.race.data, gender=form.gender.data, birth_year=form.birth_yea...
ployment_date.data, department_id=form.department.data.id) db.session.add(officer) db.session.commit() if form.unit.data: officer_unit = form.unit.data else: officer_unit = None assignment = Assignment(baseofficer=officer, star_no=f...
gjsun/MPack
MPack_Core/utils/test.py
Python
mit
153
0.045752
import nu
mpy as np from .cosmology import * from ..Ks_Mstar_Estimate import zmeans def func1(x): return x * c_light def func2
(x): return x + zmeans
fastmonkeys/kuulemma
tests/views/auth/test_activate_account.py
Python
agpl-3.0
2,656
0
# -*- coding: utf-8 -*- # Kuulemma # Copyright (C) 2014, Fast Monkeys Oy # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later...
Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import pytest from flask import url_for from kuulemma.models import User from kuulemma.serializers import account_activation_serializer fr
om tests.factories import UserFactory @pytest.mark.usefixtures('database') class ActivateAccountTest(object): @pytest.fixture def user(self): return UserFactory() @pytest.fixture def activation_hash(self, user): return account_activation_serializer.dumps(user.email) @pytest.fixtu...
ossobv/asterisklint
asterisklint/app/vall/app_originate.py
Python
gpl-3.0
1,348
0
# AsteriskLint -- an Asterisk PBX config syntax checker # Copyright (C) 2018 Walter Doekes, OSSO B.V. # # 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...
censes/>. from ..base import E_APP_ARG_BADOPT, App, AppArg class AppOrExten(AppArg): def validate(self, arg, where): if arg not in ('app', 'exten'): E_APP_ARG_BADOPT( where, argno=self.argno, app=self.app, opts=arg) class Originate(App): def __init__(self): super(...
Arg('arg1'), AppArg('arg2'), AppArg('arg3'), AppArg('timeout')], min_args=3) def register(app_loader): app_loader.register(Originate())
ballotify/django-backend
ballotify/apps/api_v1/streams/permissions.py
Python
agpl-3.0
335
0.002985
from rest_framework.permissions import BasePermission, SAFE_METHODS class IsOwnerOrReadOnly(BasePermission): """ Check if request is safe or
authenticated user is owner. """ def has_object_permission(self, request, view, obj): return request.method in SAFE_METHODS or view.get_stream().owner == request.use
r
nmartensen/pandas
pandas/core/indexes/base.py
Python
bsd-3-clause
141,427
0.000035
import datetime import warnings import operator import numpy as np from pandas._lib
s import (lib, index as libindex, tslib as libts, algos as libalgos, join as libjoin, Timestamp, Timedelta, ) from pandas._libs.lib import is_datetime_array from pandas.compat import range, u from pandas.compat.numpy import function as nv from
pandas import compat from pandas.core.dtypes.generic import ( ABCSeries, ABCMultiIndex, ABCPeriodIndex, ABCDateOffset) from pandas.core.dtypes.missing import isna, array_equivalent from pandas.core.dtypes.common import ( _ensure_int64, _ensure_object, _ensure_categorical, _ensure_plat...
themutt/plastex
plasTeX/Packages/hyperref.py
Python
mit
4,885
0.012078
#!/usr/bin/env python """ Implementation of the hyperref package TO DO: - \autoref doesn't look for \*autorefname, it only looks for \*name - Layouts - Forms optional parameters """ from plasTeX import Command, Environment from plasTeX.Base.LaTeX.Crossref import ref, pageref from nameref import Nameref, nameref imp...
hypertarget macro """ unicode = '' class phantomsection(Command): pass class autoref(Command): args = 'label:idref' class pdfstringdef(Command): args = 'macroname:string tex:string' class textorpdfstring(Command):
args = 'tex:string pdf:string' class pdfstringdefDisableCommands(Command): args = 'tex:string' class hypercalcbp(Command): args = 'size:string' # Forms class Form(Environment): args = '[ parameters:dict ]' class TextField(Command): args = '[ parameters:dict ] label' class CheckBox(Command): ...
bm424/churchmanager
migrations/0002_church_wide_crop.py
Python
mit
641
0.00156
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2016-12-22 12:05 from __future__ import unicode_literals
from django.db import migrations import image_cropping.fields class Migration(migrations.Migration): dependencies = [ ('churchmanager', '0001_initial'), ] operations = [ migrations.AddField( model_name='church', name='wide_crop', field=image_cropping....
age_field=False, size_warning=False, verbose_name='wide crop'), ), ]
cing/ChannelAnalysis
ChannelAnalysis/CoordAnalysis/Grouping.py
Python
mit
9,522
0.005146
#!/usr/bin/python ############################################################################### # # This script produces state labels for all ionic states in MDAnalysis output # based on coordination integers and groups these according to a passed # regular expression. Though, the passed state_labels could be any num...
ctory data') parser.add_argument( '-m', dest='max_ions', type=int, required=True, help='the maximum number of ions in the channel to consider') parser.add_argument( '-c', dest='num_cols', type=int, default=13, help='the number of columns per ion in the input') parser.add_argument( '-remo...
f frames to remove from the start of the data') parser.add_argument( '-s', dest='sort_col', type=int, default=3, help='a zero inclusive column number to sort your row on, typically x,y,z') parser.add_argument( '-sc', dest='sort_cut', type=float, default=0.0, help='a value on the sort_col range t...
cleac/bool_to_algeb
lab/exceptions.py
Python
mit
359
0
class Pa
rsingException(Exception): def __init__(self, message, *args, **kargs): super().__init__(message, *args, **kargs) class OperatorNotFoundError(Exception): def __init__(self, operator, *args, **kargs): super().__init__( 'Operator "{}" not found'.format(operator), *args, ...
**kargs )
mmboulhosa/lulacoin
share/qt/extract_strings_qt.py
Python
mit
2,052
0.004386
#!/usr/bin/python ''' Extract _("...") strings for translation and convert to Qt4 stringdefs so that they can be picked up by Qt linguist. ''' from subprocess import Popen, PIPE import glob import operator import os OUT_CPP="src/qt/lulacoinstrings.cpp" EMPTY=['""'] def parse_po(text): """ Parse 'po' format pr...
alse in_msgstr = False for line in text.split('\n'): line = line.rstrip('\r') if line.startswith('msgid '): if in_msgstr: messages.append((msgid, msgstr)) in_msgstr = False # message start in_msgid = True msgid = [...
tartswith('msgstr '): in_msgid = False in_msgstr = True msgstr = [line[7:]] elif line.startswith('"'): if in_msgid: msgid.append(line) if in_msgstr: msgstr.append(line) if in_msgstr: messages.append((msgid, ...
mlesicko/automaticpoetry
forms/markov.py
Python
mit
1,023
0.061584
import wordtools import random from forms.form import Form class MarkovForm(Form): def __init__(self): self.data={} self.data[""]={} self.limiter=0 def validate(self,tweet): cleaned = wordtools.clean(tweet) if wordtools.validate(cleaned) and len(cleaned)>=2: return cleaned else: return None def...
word in self.data[lastWord]: total+=self.data[lastWord][word] choice = random.randint(0,total-1) total = 0 for word in self.data[lastWord]: total+=self.data[lastWord][word] if total>choice: lastWor
d=word s+=word+" " break if lastWord=="": break return s.lower()