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
pongem/python-bot-project
appengine/standard/conftest.py
Python
apache-2.0
1,150
0
# Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os # Import py.test hooks and fixtures for App Engine from gcp.testing.appengine import ( login, pytest_configure, ...
ytest_ignore_collect(path, config): """Skip App Engine tests in python 3 or if no SDK is available.""" if 'appengine/standard' in str(path): if six.PY3: return True if 'GAE_SDK_PATH' not in os.environ: return True return False
endlessm/chromium-browser
chrome/browser/resources/unpack_pak_test.py
Python
bsd-3-clause
1,132
0.0053
#!/usr/bin/env python # Copyright 2018 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 unpack_pak import unitte
st class UnpackPakTest(unittest.TestCase): def testMapFileLine(self): self.assertTrue(unpack_pak.ParseLine(' {"path.js", IDR_PATH}')) def testGzippedMapFileLine(self): self.assertTrue(unpack_pak.ParseLine(' {"path.js", IDR_PATH, false}')
) self.assertTrue(unpack_pak.ParseLine(' {"path.js", IDR_PATH, true}')) def testGetFileAndDirName(self): (f, d) = unpack_pak.GetFileAndDirName( 'out/build/gen/foo/foo.unpak', 'out/build/gen/foo', 'a/b.js') self.assertEquals('b.js', f) self.assertEquals('out/build/gen/foo/foo.unpak/a', d) ...
bstroebl/QGIS
python/plugins/GdalTools/tools/extentSelector.py
Python
gpl-2.0
7,022
0.026915
# -*- coding: utf-8 -*- """ *************************************************************************** extentSelector.py --------------------- Date : December 2010 Copyright : (C) 2010 by Giuseppe Sucameli Email : brush dot tyler at gmail dot com *********...
) self.showRect(self.startPoint, self.endPoint) def showRect(self, startPoint, endPoint): self.rubberBand.reset( True ) # t
rue, it's a polygon if startPoint.x() == endPoint.x() or startPoint.y() == endPoint.y(): return point1 = QgsPoint(startPoint.x(), startPoint.y()) point2 = QgsPoint(startPoint.x(), endPoint.y()) point3 = QgsPoint(endPoint.x(), endPoint.y()) point4 = QgsPoint(endPoint.x(), startPoin...
quentinlautischer/291MiniProject2
src/rgxHandler.py
Python
apache-2.0
3,349
0.01284
import re class rgxHandler: # Taken from https://www.safaribooksonline.com/library/view/python-cookbook-2nd/0596007973/ch01s19.html linetitles = ["product/productId: ", "product/title: ", "product/price: ", "review/userId: ", "review/profileName: ", "review/helpfulness: ", "review/score: ", "review/time: ", "...
.append(review[quotes[q]+1:quotes[q+1]] + '\n') if q+1 == len(quotes)-1: break while commas[c] < quotes[q+1]:
c += 1 q+=2 else: #print(review[quotes[q]+1:quotes[q+1]] + '\n') rtnlines.append(review[quotes[q]+1:quotes[q+1]] + '\n') q+=2 if q == len(quotes): break i += 1 i = 0 ...
abzaloid/maps
django-project/bin/django-admin.py
Python
mit
161
0
#!/Users/patron/De
sktop/maps/django-project/bin/python from django.core import management if __name__ == "__main__": management.execute_from_command_line()
Cangjians/pycangjie
tests/__init__.py
Python
lgpl-3.0
6,379
0.000314
# Copyright (c) 2013 - The pycangjie authors # # This file is part of pycangjie, the Python bindings to libcangjie. # # pycangjie is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the ...
th methods like test_a(), test_b(), etc..., in other words, one method per potential Cangjie input code. Well, not
quite, because that would be 12356630 methods (the number of strings composed of 1 to 5 lowercase ascii letters), and even though my laptop has 8Go of RAM, the test process gets killed by the OOM killer. :) So we cheat, and use libcangjie's wildcard support, so that we only generate 26 + 26^2 = 702 met...
TheShellLand/pies
v3/Libraries/xml/xml-parse.py
Python
mit
321
0
#!/usr/bin/env python # -*- coding: utf8 -*- import xml.etree.ElementTree as ET from pprint import ppri
nt filename = 'GeoLogger.gpx' def main(): tree = ET.parse(filename) root = tree.getroot()
pprint(root.tag) pprint(root.attrib) pprint(root.findtext('.')) if __name__ == "__main__": main()
pschmitt/home-assistant
tests/helpers/test_script.py
Python
apache-2.0
46,540
0.000645
"""The tests for the Script component.""" # pylint: disable=protected-access import asyncio from contextlib import contextmanager from datetime import timedelta import logging from unittest import mock import pytest import voluptuous as vol # Otherwise can't test just this file (import order issue) from homeassistant...
PT_SCHEMA( [ { "service": "test.script", "data_temp
late": {"fire": "{{ fire1 }}", "listen": "{{ listen1 }}"}, }, { "service": "test.script", "data_template": {"fire": "{{ fire2 }}", "listen": "{{ listen2 }}"}, }, ] ) script_obj = script.Script(hass, sequence, script_mode="parallel", max...
jainaman224/zenodo
zenodo/modules/deposit/minters.py
Python
gpl-2.0
2,471
0
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2016 CERN. # # Zenodo is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later v...
"Persistent identifier minters.""" from __future__ import absolute_import from invenio_pidstore.models import PersistentIdentifier, PIDStatus, \ RecordIdentifier def zenodo_concept_recid_minter(record_uuid=None, data=None): """Mint the Concept RECID. Reserves the Concept RECID for the record. """ ...
D, ) data['conceptrecid'] = conceptrecid.pid_value return conceptrecid def zenodo_deposit_minter(record_uuid, data): """Mint the DEPID, and reserve the Concept RECID and RECID PIDs.""" if 'conceptrecid' not in data: zenodo_concept_recid_minter(data=data) recid = zenodo_reserved_record...
southpawtech/TACTIC-DEV
src/pyasm/biz/file.py
Python
epl-1.0
34,859
0.008721
########################################################### # # Copyright (c) 2005, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permi...
ethod(remove_file_code) # DEPRERECATED def extract_file_co
de(file_path): p = re.compile(r'_(\w{%s})\.' % File.PADDING) m = p.search(file_path) if not m: return 0 groups = m.groups() if not groups: return 0 else: file_code = groups[0] # make sure there are only alpha/numberic chara...
mozilla/telemetry-analysis-service
tests/test_stats.py
Python
mpl-2.0
1,163
0.00086
# This Source Code Form is subject to the terms of the Mozilla
Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. from atmo.stats.models import Metric def test_metrics_record(now, one_hour_ago): Metric.record("metric-key
-1") Metric.record("metric-key-2", 500) Metric.record("metric-key-3", data={"other-value": "test"}) Metric.record("metric-key-4", created_at=one_hour_ago, data={"other-value-2": 100}) m = Metric.objects.get(key="metric-key-1") assert m.value == 1 assert m.created_at.replace(microsecond=0) == no...
lkostler/AME60649_project_final
moltemplate/moltemplate/src/nbody_by_type_lib.py
Python
bsd-3-clause
18,422
0.0057
#!/usr/bin/env python # Author: Andrew Jewett (jewett.aij at g mail) # http://www.chem.ucsb.edu/~sheagroup # License: 3-clause BSD License (See LICENSE.TXT) # Copyright (c) 2012, Regents of the University of California # All rights reserved. import sys from nbody_graph_search import * #from collections impo...
e for example between the angle formed between three consecutively bonded atoms (named, 1, 2, 3, for example), and the angle between the same atoms in reverse order (3, 2, 1). However both triplets of atoms will be returned by the subgraph- matching algorithm when searching for ALL 3-body interac...
his is a function which sorts the atoms and bonds in a way which is consistent with the type of N-body interaction being considered. The atoms (and bonds) in a candidate match are rearranged by the canonical_order(). Then the re-ordered list of atom and bond ids is tested against the list of atom/bon...
rorychatt/GPCook
gpcook/modules/documentation.py
Python
mit
88
0
def generate_documentat
ion(): print("generate_doc
umentation Stub") return True
michel-cf/Propeller-WebIDE
projects/forms.py
Python
lgpl-3.0
1,061
0
from django import forms from django.core.exceptions import ValidationError from projects.models import Project class CreateProjectForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): self.u
ser = user super(CreateProjectForm, self).__init__(*args, **kwargs) def clean_name(self): return self.cleaned_data['name'].strip() def clean_code(self): code = self.cleaned_data['code'].strip().lower().replace(' ', '_') if Project.objects.filter(user=self.user, code=
code).exists(): raise ValidationError('A project with this code already exists') return code class Meta: model = Project fields = ['name', 'code', 'public'] class CreateProjectFormBasic(forms.Form): name = forms.CharField(label='Name', max_length=255) code = forms.Slug...
interlegis/atendimento
solicitacoes/models.py
Python
gpl-3.0
2,330
0
# -*- coding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from usuarios.models import Usuario class Sistema(models.Model): sigla = models.CharField(verbose_name=_('Sigla'), max_length=10) nome = models.CharField(verbose_name=_('Nome Sistema'), ...
meField(auto_now_add=True, verbose_name=_('Data de criação')) descricao = models.TextField(blank=True, null=True,
verbose_name=_('Descrição')) osticket = models.CharField(blank=True, null=True, max_length=256, verbose_name=_('Código Ticket')) class Meta: verbose_name = _('Solicitação de Novo Serviço...
hrayr-artunyan/shuup
shuup/admin/views/select.py
Python
agpl-3.0
2,842
0.001407
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django.apps import apps from ...
f init_search_fields(self, cls): self.search_fields = [] key = "%sname" % ("translations__" if hasattr(cls, "translat
ions") else "") self.search_fields.append(key) if issubclass(cls, Contact): self.search_fields.append("email") if issubclass(cls, Product): self.search_fields.append("sku") self.search_fields.append("barcode") user_model = get_user_model() if i...
evenmarbles/mlpy
mlpy/tools/log.py
Python
mit
9,057
0.001877
from __future__ import division, print_function, absolute_import import os import logging from datetime import datetime from ..modules.patterns import Singleton class SilenceableStreamHandler(logging.StreamHandler): def __init__(self, *args, **kwargs): super(SilenceableStreamHandler, self).__init__(*arg...
og level for a handler. Parameters --------
-- mid : str The module id of the logger
talon-one/talon_one.py
talon_one/models/session.py
Python
mit
5,860
0
# coding: utf-8 """ Talon.One API The Talon.One API is used to manage applications and campaigns, as well as to integrate with your application. The operations in the _Integration API_ section are used to integrate with our platform, while the other operations are used to manage applications and campaigns. #...
self._token = None self._created = None self.discriminator = None self.user_id = user_id self.token = token self.created = created @property def user_id(self)
: """Gets the user_id of this Session. # noqa: E501 The ID of the user of this session # noqa: E501 :return: The user_id of this Session. # noqa: E501 :rtype: int """ return self._user_id @user_id.setter def user_id(self, user_id): """Sets the user_i...
sleepers-anonymous/zscore
useful_scripts/timezones.py
Python
mit
292
0.017123
from django.utils impor
t timezone t = timezone.get_current_timezone() for s in Sleep.objects.all(): if timezone.is_aware(s.start_time): s.start_time = timezone.make_naive(s.start_time, t) if timezone.is_aware(s.end_time):
s.end_time = timezone.make_naive(s.end_time,t) s.save()
VirusTotal/content
Tests/Marketplace/marketplace_services.py
Python
mit
150,166
0.004761
import base64 import fnmatch import glob import json import os import re import shutil import stat import subprocess import urllib.parse import warnings from datetime import datetime, timedelta from distutils.util import strtobool from distutils.version import LooseVersion from typing import Tuple, Any, Union, List, Di...
_name = pack_name self._pack_path = pack_path self._status = None self._public_storage_path = "" self._remove_files_list = [] # tracking temporary files, in order to delete in later step self._server_min_version = "99.99.99" # initialized min version self._latest_versio...
user_metadata function self._hidden = False # initialized in load_user_metadata function self._description = None # initialized in load_user_metadata function self._display_name = None # initialized in load_user_metadata function self._user_metadata = None # initialized in load_user_...
SCPR/firetracker
calfire_tracker/migrations/0027_auto__add_field_wildfiredisplaycontent_content_type.py
Python
gpl-2.0
11,098
0.007839
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'WildfireDisplayContent.content_type' db.add_column('calfire_tracker_wildfiredisplaycontent',...
Field', [], {'max_length': '140', 'null': 'True', 'blank': 'True'}), 'historical_narrative': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'injuries': ('dja
ngo.db.models.fields.CharField', [], {'max_length': '2024', 'null': 'True', 'blank': 'True'}), 'last_saved': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'last_scraped': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), ...
rspavel/spack
var/spack/repos/builtin/packages/py-distributed/package.py
Python
lgpl-2.1
1,699
0.002943
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for de
tails. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyDistributed(PythonPackage): """Distributed scheduler for Dask"""
homepage = "https://distributed.dask.org/" url = "https://pypi.io/packages/source/d/distributed/distributed-2.10.0.tar.gz" version('2.10.0', sha256='2f8cca741a20f776929cbad3545f2df64cf60207fb21f774ef24aad6f6589e8b') version('1.28.1', sha256='3bd83f8b7eb5938af5f2be91ccff8984630713f36f8f66097e531a63f...
hfp/tensorflow-xsmm
tensorflow/contrib/tensorrt/test/reshape_transpose_test.py
Python
apache-2.0
6,477
0.003705
# Copyright 2018 The TensorFlow Authors. 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 applica...
ims], output_names=[output_name], expected_output_dims=[tuple(input_dims)]) def ExpectedEnginesToBuild(self, run_params): """Return the expected engines to build.""" return { "TRTEngineOp_0": ["reshape-%d" % i for i in range(7)] +
["reshape-%d/shape" % i for i in range(7)] } def ShouldRunTest(self, run_params): """Whether to run the test.""" return (not trt_test.IsQuantizationMode(run_params.precision_mode) and not run_params.dynamic_engine) class TransposeTest(trt_test.TfTrtIntegrationTestBase): def ...
zookeepr/zookeepr
zkpylons/tests/functional/conftest.py
Python
gpl-2.0
3,543
0.007056
import pytest import sys import logging from sqlalchemy import create_engine import zk.model.meta as zkmeta import zkpylons.model.meta as pymeta from zkpylons.config.routing import make_map from paste.deploy import loadapp from webtest import TestApp from paste.fixture import Dummy_smtplib from .fixtures import Co...
xture def app(): wsgiapp = loadapp('config:'+ini_filename, relative_to=".") app = TestApp(wsgiapp) yield app class DoubleSession(object): # There is an issue with the zkpylons -> zk migration # Some files use zk.model, which uses zk.mo
del.meta.Session # Some files use zkpylons.model, which uses zkpylons.model.meta.Session # Some files use relative paths, which means you can kinda guess at it # The best way around this is to configure both Session objects # But then operations frequently have to be applied to both # This class wra...
truevision/django_banklink
django_banklink/models.py
Python
bsd-3-clause
1,291
0.035631
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User TRANSACTION_STATUS = ( ('P', _('pending')), ('F', _('failed')), ('C', _('complete')), ) class Transaction(models.Model): user = models.ForeignKey(User, blank = True, null...
last_modified = models.DateTimeField(auto_now = True) status = models.CharField(_("status"), max_length = 1, default = 'P') redirect_after_success = models.Ch
arField(max_length = 255, editable = False) redirect_on_failure = models.CharField(max_length = 255, editable = False) def __unicode__(self): return _("transaction %s " % self.pk) class Meta: verbose_name = _("transaction") ordering = ['-last_modified']
ArneBachmann/tagsplorer
tagsplorer/__main__.py
Python
mpl-2.0
183
0.010929
# codi
ng=utf-8 ''' tagsPlorer package entry point (C) 2021-2021 Arne Bachmann https://github.com/ArneBachmann/tagsplorer ''' from tagsplorer import tp tp.Main().par
se_and_run()
diegojromerolopez/djanban
src/djanban/apps/journal/migrations/0002_auto_20160926_0155.py
Python
mit
819
0.002442
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-09-25 23:55 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('journal', '0001_initial'), ] operation
s = [ migrations.CreateModel(
name='JournalEntryTag', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=64, verbose_name='Name')), ], ), migrations.AddField( model_...
xArm-Developer/xArm-Python-SDK
setup.py
Python
bsd-3-clause
1,795
0.000557
#!/usr/bin/env python3 # Software License Agreement (BSD License) # # Copyright (c) 2017, UFactory, Inc. # All rights reserved. # # Author: Vinman <[email protected]> import os from distutils.util import convert_path try: from setuptools import setup, find_packages except ImportError: from distutils.core ...
('xarm/version.py') with open(os.path.join(os.getcwd(), ver_path)) as ver_file: exec(ver_file.read(), main_ns) version = main_ns['__version__'] # long_description = open('README.rst').read() long_description = 'long description for xArm-Python-SDK' with open(os.path.join(os.getcwd(), 'requirements.txt')) as f: ...
', description='Python SDK for xArm', packages=find_packages(), author_email='[email protected]', install_requires=requirements, long_description=long_description, license='MIT', zip_safe=False )
frasern/ADL_LRS
lrs/tests/AgentTests.py
Python
apache-2.0
3,199
0.012504
import json import base64 from django.test import TestCase from django.core.urlresolvers import reverse from django.conf import settings from ..views import register, agents from ..models import Agent class AgentTests(TestCase): @classmethod def setUpClass(cls): print "\n%s" % __name__ def setUp...
(reverse(register),form, X_Experience_API_Version=settings.XAPI_VERSION) def test_get_no_agents(self): agent = json.dumps({"name":"me","mbox":"mailto:[email protected]"}) response = self.client.get(reverse(agents), {'agent':agent}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSIO...
response.content, "Error with Agent. The agent partial did not match any agents on record") def test_get(self): a = json.dumps({"name":"me","mbox":"mailto:[email protected]"}) Agent.objects.retrieve_or_create(**json.loads(a)) response = self.client.get(reverse(agents), {'agent':a}, Authorizati...
gecos-team/gecosws-agent
gecosfirstlogin_lib/Window.py
Python
gpl-2.0
3,073
0.000651
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- # This file is part of Guadalinex # # This software is free software; you can redistr
ibute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implie...
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 with this package; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA __au...
15Mpedia/15Mpedia-scripts
completa-circulos-podemos.py
Python
gpl-3.0
4,844
0.020544
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2014 emijrp # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later versio...
n\* \[\[Lista de nodos de Podemos\]\]\r\n\r\n", ur"== Véase también ==\n* [[Podemos]]\n* [[Lista de círculos de Podemos]]\n\n", newtext) if wtext != newtext: wikipedia.showDiff(wtext, newtext) page.put(newtext, u"BOT - Unificando círculos") #imagen if not re.sea...
twitter = twitter[0].split(',')[0].strip() f = urllib.urlopen("https://twitter.com/%s" % twitter) html = unicode(f.read(), 'utf-8') imageurl = re.findall(ur"data-resolved-url-large=\"(https://pbs.twimg.com/profile_images/[^\"]+)\"", html) if imageurl: ...
BansheeMediaPlayer/bockbuild
packages/atk.py
Python
mit
68
0.073529
G
nomeXzPackage ('atk', version_major = '2.16', version_minor = '0')
zarafagroupware/zarafa-zsm
tests/tests_authorization.py
Python
agpl-3.0
11,327
0.002472
# Copyright 2012 - 2013 Zarafa B.V. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License, version 3, # as published by the Free Software Foundation with the following additional # term according to sec. 7: # # According to sec. 7 of the ...
.verify_iterable(tens, [self.ten_bikes,
self.ten_cars]) ## Harry sees no tenants tens = self.s_bikes_harry.all_tenant() self.assertEqual(0, len(tens), u'Incorrect number of tenants.') ##
Jspsun/LEETCodePractice
Python/NumberOfIslands.py
Python
mit
834
0
class Solution(object): def numIslands(self, grid): """ :type grid: List[List[str]] :rtype:
int """ count = 0 for r in range(len(grid)): for c in range(len(grid[0])): if grid[r][c] == "1": self.clearIsland(grid, r, c) count += 1 return count def clearIsland(self, grid, r, c): grid[r][c] = "0" ...
and(grid, r + 1, c) if c > 0 and grid[r][c - 1] == "1": self.clearIsland(grid, r, c - 1) if c < len(grid[0]) - 1 and grid[r][c + 1] == "1": self.clearIsland(grid, r, c + 1) return
jasonlvhit/whoops
whoops/wsgilib/wsgi_server.py
Python
mit
3,279
0.00061
import sys from io import BytesIO from whoops.httplib.http_server import HttpServer from whoops import ioloop class WSGIServer(HttpServer): def __init__(self, ioloop, address): super(WSGIServer, self).__init__(ioloop, address) self.app = None self.environ = None self.result = Non...
env["SERVER_HOST"] = self.host env["SERVER_PORT"] = self.port if "content-type" in self.header: env["CONTENT_TYPE"] = self.header.get("content-type") if "content-length" in self.header: env["CONTENT_LENGTH"] = self.header.get("content-length") for key, value ...
tup_environ(self): self.setup_cgi_environ() env = self.environ = self.cgi_environ.copy() env["wsgi.input"] = BytesIO(self.request_body) env["wsgi.errors"] = sys.stdout env["wsgi.version"] = self.wsgi_version env["wsgi.run_once"] = self.wsgi_run_once env["wsgi.url...
takus/dd-agent
utils/service_discovery/zookeeper_config_store.py
Python
bsd-3-clause
3,661
0.001639
# (C) Datadog, Inc. 2016 # All rights reserved # Licensed under Simplified BSD License (see LICENSE) # std import logging from kazoo.client import KazooClient, NoNodeError from utils.service_discovery.abstract_config_store import AbstractConfigStore, KeyNotFound DEFAULT_ZK_HOST = '127.0.0.1' DEFAULT_ZK_PORT = 2181 D...
.settings.get('port')), read_only=True, ) self.client.start() return self.client def client_read(self, path, **kwargs): """Retrieve a value from a Zookeeper key.""" try: if kwargs.get('watch', False): return self.recursive_...
# we use it in _populate_identifier_to_checks results = [] self.recursive_list(path, results) return results else: res, stats = self.client.get(path) return res.decode("utf-8") except NoNodeError: ra...
MikaelSchultz/dofiloop-sentinel
sentinel/device/admin.py
Python
mit
1,293
0.001547
from django.contrib import admin from .models import SnmpDevice, SnmpDeviceMessage, PingHistory # Register your models here. class SnmpDeviceAdmin(admin.ModelAdmin): fields = [ 'name', 'hostname', 'status', 'ping_mode', 'ping_port', 'snmp_template', 'snmp_port', 'snmp_community', 'snmp_system_con...
en', 'ping_last_tried', 'snmp_last_tried', 'snmp_last_poll', 'snmp_logged_on_users' ] readonly_fields = ( 'ping_last_seen', 'ping_last_tried', 'snmp_last_tried', 'snmp_last_poll' ) list_display = [ 'name', 'hostname', 'snmp_logged_on_users' ] class Sn
mpDeviceMessageAdmin(admin.ModelAdmin): fields = ( 'snmp_device', 'status', 'message_choice', 'resolved', 'resolved_by' ) class PingHistoryAdmin(admin.ModelAdmin): fields = [ 'snmp_device', 'online', 'timestamp' ] readonly_fields = [ 'timestamp', ] list_display = ...
manhhomienbienthuy/scikit-learn
benchmarks/bench_plot_randomized_svd.py
Python
bsd-3-clause
17,938
0.000557
""" Benchmarks on the power iterations phase in randomized SVD. We test on various synthetic and real datasets the effect of increasing the number of power iterations in terms of quality of approximation and running time. A number greater than 0 should help with noisy matrices, which are characterized by a slow spectr...
label, xy=(x, y), xytext=(0, -20), textcoords="offset points", ha="right",
va="bottom", ) plt.legend(loc="upper right") plt.suptitle(title) plt.ylabel("norm discrepancy") plt.xlabel("running time [s]") def scatter_time_vs_s(time, norm, point_labels, title): plt.figure() size = 100 for i, l in enumerate(sorted(norm.keys())): if l...
NYUCCL/psiTurk
tests/test_tasks.py
Python
mit
3,640
0.003571
import pytest CODEVERSION = '0.0.1' NEW_CODEVERSION = '0.0.2' @pytest.fixture() def campaign(): from psiturk.models import Campaign parameters = { 'codeversion': CODEVERSION, 'mode': 'sandbox', 'goal': 100, 'minutes_between_rounds': 1, 'assignments_per_round': 10, ...
mpaign,
'job_id': campaign.campaign_job_id } from psiturk.experiment import app mocker.patch.object(app.apscheduler, 'remove_job', lambda *args, **kwargs: True) import psiturk.tasks mocker.patch.object(psiturk.models.Participant, 'count_completed', lambda *args, **kwargs: camp...
facebookexperimental/eden
eden/scm/tests/test-treestate.py
Python
gpl-2.0
9,519
0
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. from __future__ import absolute_import import itertools import os import posixpath import random import tempfile import unittest import silenttestru...
def testsaveas(self): treepath = os.path.join(testtmp, "saveas") tree = treestate.treestate(treepath, 0) tree.insert("a", 1, 2, 3, 4, None)
tree.setmetadata(b"1") tree.flush() tree.insert("b", 1, 2, 3, 4, None) tree.remove("a") treepath = "%s-savedas" % treepath tree.setmetadata(b"2") rootid = tree.saveas(treepath) tree = treestate.treestate(treepath, rootid) self.assertFalse("a" in ...
pombredanne/invenio-old
modules/bibclassify/lib/bibclassify_microtests.py
Python
gpl-2.0
7,289
0.005076
# -*- coding: utf-8 -*- """Module for running microtests on how well the extraction works - this module is STANDALONE safe""" import ConfigParser import glob import traceback import codecs import bibclassify_config as bconfig import bibclassify_engine as engine log = bconfig.get_logger("bibclassify.microtest") de...
s.path.join(os.path.dirname(os.path.abspath(__file__)), "../../../etc/bibclassify/microtest*.cfg"))) run(test_paths) elif (len(sys.argv) > 1): for p in sys.argv[1:]: if p[0] == os.path.sep: # absolute path test_paths....
f we shall prepend rootdir first = p.split(os.path.sep)[0] if os.path.exists(first): #probably relative path test_paths.append(p) elif (os.path.join(bconfig.CFG_PREFIX, first)): #relative to root test_paths.append(os.path.join(bconf...
ajaniv/equitymaster
equity_master/common.py
Python
gpl-2.0
3,296
0.01426
#/usr/bin/env python # -#- coding: utf-8 -#- # # equity_master/common.py - equity master common classes # # standard copy right text # # Initial version: 2012-04-02 # Author: Amnon Janiv """ .. module:: equity_master/common :synopsis: miscellaneous abstract classes and other core constructs .. moduleauthor...
.ERROR, tmpl, *args, **kwargs) def fatal( self, exc_class, logger, tmpl, *args, **kwar
gs): """Log and exit""" pass class LoggingMixin(object): """Log utilities abstraction """ def log( self, logger, severity, tmpl, *args, **kwargs ): util.log(logger, severity, tmpl, *args, **kwargs) def debug( ...
beni55/djangolint
project/lint/parsers.py
Python
isc
1,186
0
import ast import os class Parser(object): """ Find all *.py files inside `repo_path` and parse its
into ast nodes. If file has syntax errors SyntaxError object will be returned except ast node. """ def __init__(self, repo_path): if not os.path.isabs(repo_path): raise ValueError('Repository path is not absolute: %s' % repo_path) self.repo_path = repo_path def walk(s...
e paths to all *.py files inside `repo_path` directory. """ for root, dirnames, filenames in os.walk(self.repo_path): for filename in filenames: if filename.endswith('.py'): yield os.path.join(root, filename) def relpath(self, path): return os...
hemebond/kapua
forms.py
Python
gpl-3.0
7,905
0.031883
# coding=UTF-8 # Copyright 2011 James O'Neill # # This file is part of Kapua. # # Kapua 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 Sof
tware Foundation, either version 3 of the License, or # (at your option) any later version. # # Kapua 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 ...
You should have received a copy of the GNU General Public License # along with Kapua. If not, see <http://www.gnu.org/licenses/>. from django.utils.translation import ugettext as _ from django.db import models #adapted from http://www.djangosnippets.org/snippets/494/ #using UN country and 3 char code list from http...
pmneila/morphsnakes
test_morphsnakes.py
Python
bsd-3-clause
5,724
0
import numpy as np from morphsnakes import (morphological_chan_vese, morphological_geodesic_active_contour, inverse_gaussian_gradient, circle_level_set, checkerboard_level_set) from numpy.testing import assert_array_equal import pytest def ga...
init_level_set=ls) def test_morphsnakes_black(): img = np.zeros((11, 11)) ls = circle_level_set(img.shape, (5, 5), 3) ref_zeros = np.zeros(img.shape, dtype=np.int8) ref_ones = np.ones(img.shape, dtype=np.int8) acwe_ls = morphological
_chan_vese(img, iterations=6, init_level_set=ls) assert_array_equal(acwe_ls, ref_zeros) gac_ls = morphological_geodesic_active_contour(img, iterations=6, init_level_set=ls) assert_array_equal(gac_ls, ref_zeros) gac_ls2 = morphological_geodesic_active_...
cgwalters/pykickstart
tests/commands/user.py
Python
gpl-2.0
4,536
0.005291
# # Martin Gracik <[email protected]> # # Copyright 2009 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, modify, # copy, or redistribute it subject to the terms and conditions of the GNU # General Public License v.2. This program is distributed in the hope that it # will be use...
_TestCase.runTest(self) # pass self.assert_parse("user --name=user --lock --plaintext", "user --name=user --lock\n") self.assert_parse("user --name=user --lock", "user --name=user --lock\n") self.assert_parse("user --name=user --plaintext", "user --name=user\n") # fail class ...
lf.assert_parse("user --name=user --gecos=\"User Name\"", "user --name=user --gecos=\"User Name\"\n") class F19_TestCase(F12_TestCase): def runTest(self): # run F12 test case F12_TestCase.runTest(self) # pass self.assert_parse("user --name=user --gid=500", "user --name=user --gid=5...
calaldees/libs
python3/calaldees/loop.py
Python
gpl-3.0
2,814
0.002843
import time DEFAULT_SLEEP_FACTOR = 0.8 class Loop(object): class LoopInterruptException(Exception): pass def __ini
t__(self, fps, timeshift=0, sleep_factor=DEFAULT_SLEEP_FACTOR): """ Sleep factor could be set to 1.0? as python 3.5 respects time better """ self.set_period(fps, timeshift) self.profile_timelog = [] self.sleep_factor = sleep_factor def set_period(self, fps, timeshift...
tart_time = time.time() - timeshift self.previous_time = time.time() - self.period # Previous time is one frame ago to trigger immediately return self.period def get_frame(self, timestamp): return int((timestamp - self.start_time) // self.period) def is_running(self): return s...
chriscz/pySorter
setup.py
Python
gpl-3.0
1,350
0.001481
import os import sys from setuptools import setup, find_packages, Command from commands import * tests_require=['pytest-cov', 'pytest', 'testfixtures'] setup( name=name, version=read_version(), description='A regex based file organizer', long_description=open(os.path.join(base_dir, 'description.txt')...
ee', author_email='[email protected]', packages=find_packages(), setup_requires=['pytest-runner'], tests_require=tests_require, include_package_data=True, zip_safe=False, cmdclass={ 'test': PyTestCommand, 'coverage': CoverageCommand, 'bump': BumpVersionCommand, ...
test=['pytest', 'testfixtures', 'pytest-cov'], ), classifiers=[ "Development Status :: 4 - Beta", "Environment :: Console", "License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)", "Topic :: Utilities", "Programming Language :: Python :: 2.7", "...
tmtowtdi/MontyLacuna
lib/lacuna/buildings/boring/ssld.py
Python
mit
213
0.032864
from lacuna.building import MyBuilding class ssld(MyBuilding): path = 'ssld' def __init__( self, client, body_id:int = 0, building_id:int = 0 ): super()._
_init
__( client, body_id, building_id )
vstoykov/django-cms
cms/middleware/toolbar.py
Python
bsd-3-clause
5,441
0.001838
# -*- coding: utf-8 -*- """ Edit Toolbar middleware """ from cms.utils.conf import get_cms_setting from cms.toolbar.toolbar import CMSToolbar from cms.utils.i18n import force_language from django.contrib.admin.models import LogEntry, ADDITION, CHANGE from menus.menu_pool import menu_pool from django.http import HttpRes...
d_url(), 'delete_url': placeholder.get_delete_url(instance.pk), 'move_url': placeholder.get_move_url(), } original_context.update(data) plugin_class = instance.get_plugin_class() template = plugin_class.frontend_edit_template output = render_to_string(template, original_c...
ddleware(object): """ Middleware to set up CMS Toolbar. """ def process_request(self, request): """ If we should show the toolbar for this request, put it on request.toolbar. Then call the request_hook on the toolbar. """ edit_on = get_cms_setting('CMS_TOOLBAR_U...
hopshadoop/hops-util-py
hops/experiment_impl/parallel/grid_search.py
Python
apache-2.0
4,463
0.005602
""" Gridsearch implementation """ from hops import hdfs, tensorboard, devices from hops.experiment_impl.util import experiment_utils from hops.experiment import Direction import threading import six import time import os def _run(sc, train_fn, run_id, args_dict, direction=Direction.MAX, local_logdir=False, name="no...
args_dict: direction: local_logdir: name: Returns: """ app_id = str(sc.applicationId) num_executions = 1 if direction.upper() != Direction.MAX and direction.upper() != Direction.MIN: raise ValueError('Invalid direction ' + direction + ', must be Direction...
raise ValueError('Length of each function argument list must be equal') num_executions = len(arg_lists[i]) #Each TF task should be run on 1 executor nodeRDD = sc.parallelize(range(num_executions), num_executions) #Make SparkUI intuitive by grouping jobs sc.setJobGroup(os.environ['ML_ID'...
datamachine/twx
docs/conf.py
Python
mit
10,106
0.006333
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # TWX documentation build configuration file, created by # sphinx-quickstart on Sat Jun 27 15:07:02 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autoge...
efault. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #m
odindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The t...
xyuanmu/you-get
src/you_get/extractors/kakao.py
Python
mit
1,771
0.002823
#!/usr/bin/env python from ..common import * from .universal import
* __all__ = ['kakao_download'] def kakao_download(url, output_dir='.', info_only=False, **kwargs): json_request_url = 'https://videofarm.daum.net/controller/api/closed/v1_2/IntegratedMovieData.json?vid={}' # in this implementation playlist not supported so use url_without_playlist # if want to support ...
t(url) try: vid = re.search(r"<meta name=\"vid\" content=\"(.+)\">", page).group(1) title = re.search(r"<meta name=\"title\" content=\"(.+)\">", page).group(1) meta_str = get_content(json_request_url.format(vid)) meta_json = json.loads(meta_str) standard_preset = meta_json[...
falbassini/googleads-dfa-reporting-samples
python/v2.0/download_floodlight_tag.py
Python
apache-2.0
1,952
0.004098
#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specifi
c language governing permissions and # limitations under the License. """This example downloads activity tags for a given floodlight activity.""" import argparse import sys from apiclient import sample_tools from oauth2client import client # Declare command-line flags. argparser = argparse.ArgumentParser(add_help=F...
zgoda/zakwasy
tests/test_sddetails.py
Python
mit
2,004
0.001996
from flask import url_for from tests import ZKWTestCase from zkw.models import Sourdough, User class SourdoughDetailsPageTests(ZKWTestCase): def setUp(self): super(SourdoughDetailsPageTests, self).setUp() self.user_1 = User.get_by_email('[email protected]') self.active_sd = Sourdough.q...
self.inact
ive_sd = Sourdough.query.filter_by(name='inactive').first() self.inactive_sd_url = url_for('sd.details', sourdough_id=self.inactive_sd.id) def test_anon_inactive_page(self): """ Test what anonymous user sees when she tries to access inactive sourdough page. Expected outcome: HTTP 4...
uranusjr/django
tests/postgres_tests/test_json.py
Python
bsd-3-clause
13,888
0.001368
import datetime import uuid from decimal import Decimal from django.core import checks, exceptions, serializers from django.core.serializers.json import DjangoJSONEncoder from django.forms import CharField, Form, widgets from django.test.utils import isolate_apps from django.utils.html import escape from . import Pos...
l=False), [self.objs[7], self.objs[8]] ) def test_contains(self): self.assertSequenceEqual( JSONModel.objects.filter(field__contains={'a': 'b'}), [self.objs[7], self.objs[8]] ) def test_contained_by(self): self.assertSequenceEqual( ...
6], self.objs[7]] ) def test_has_key(self): self.assertSequenceEqual( JSONModel.objects.filter(field__has_key='a'), [self.objs[7], self.objs[8]] ) def test_has_keys(self): self.assertSequenceEqual( JSONModel.objects.filter(field__has_keys=['a...
vacancy/TensorArtist
tartist/plugins/trainer_enhancer/progress.py
Python
mit
1,402
0.003566
# -*- coding:utf8 -*- # File : progress.py # Author : Jiayuan Mao # Email : [email protected] # Date : 2/26/17 # # This file is part of TensorArtist. from tartist.core.utils.thirdparty import get_tqdm_defaults import tqdm import numpy as np def enable_epoch_progress(trainer): pbar = None def epoch_...
'.format(trainer.runtime['error']) for k in sorted(out.keys()): v = out[k] if isinstance(v, (str, int, float, np.ndarray, np.float32, np.float64, np.int32, np.int64)): try: v = float(v) desc += ', {}={:.4f}'.format(k, v) ...
trainer): nonlocal pbar pbar.close() pbar = None trainer.register_event('iter:after', epoch_progress_on_iter_after, priority=25) trainer.register_event('epoch:after', epoch_progress_on_epoch_after, priority=5)
uperetz/AstroTools
fitter/_modeling.py
Python
apache-2.0
2,367
0.00338
from scipy.optimize import curve_fit from n
umpy import log, isnan class NotAModel(Exception): pass def chisq(self, result=None): if result is None: result = self.result return ((self.data.cts(row=True)-result)**2/self.data.errors(row=True)**2).sum() def cstat(self, result): if result is None: result = self.result data =...
a.counts result = result*self.data.exposure C = result+data*(log(data)-log(result)-1) return 2*C[~isnan(C)].sum() def reduced_chisq(self): return self.chisq(self.result)/(len(self.data.channels)-len(self.getThawed())) def append(self, *args): for model in args: try: model._ca...
merlin-lang/kulfi
experiments/testbed/results/plot/sort.py
Python
lgpl-3.0
989
0.005056
#!/usr/bin/env python import sys, argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, action='store', dest='input', default=None, help="Input file") args = parser.parse_args() stats = dict() if args.input is None: print "Error: No input fi...
for line in in_file.readlines(): time = int(line.split()[0]) tx_bytes = int(line.split()[1])
stats[time] = tx_bytes stats = sorted(stats.items()) start_time = stats[0][0] prev_tx = stats[0][1] no_traffic_flag = True for time, tx_bytes in stats: if no_traffic_flag: if tx_bytes > (prev_tx+100000): no_traffic_flag = False start_time, ...
Moth-Tolias/LetterBoy
backend/jumbles nontrobo/jumbles nontrobo.py
Python
gpl-3.0
4,226
0.018462
"""return a jumbled version of a string. eg, the lazy hamster is jumping becomes the lzay hmasetr si jmunipg shuffles insides of words. """ import random import string #okay, so this will be the jmuble algorythim #variables, passed #string_to_jumble = "" #yeah #jumble_mode = true # do u switch words of t...
acter now #print(i) print(len(word)+100) #jumble it #random.shuffle(current_word) #add to the new string for char in current_word: string_to_return += char #add the last lettr ...
ctuation_[string_words.index(word)] print(punctuation_[string_words.index(word)]) #flush the string current_word.clear() #next word! print(string_to_return) print(punctuation_) #done #string_jumble("a0boop1boop3boop4boop5hey") st...
BedrockDev/Sunrin2017
Software/Web Programming/Project07/exam_03.py
Python
mit
91
0
ali
st = ['Micheal', 'Franklin', 'Trevor'] for i in alist: print "Happy birthday, " + i
google/orbit
third_party/conan/recipes/grpc/conanfile.py
Python
bsd-2-clause
5,670
0.002822
from conans import ConanFile, CMake, tools from conans.errors import ConanInvalidConfiguration import os import shutil import time import platform class grpcConan(ConanFile): name = "grpc" version = "1.27.3" description = "Google's RPC library and framework." topics = ("conan", "grpc", "rpc") url ...
cmake.definitions["gRPC_BUILD_GRPC_RUBY_PLUGIN"] = "OFF" cmake.definitions["gRPC_BUILD_GRPC_NODE_PLUGIN"] = "OFF" # tell grpc to use the find_package versions cmake.definitions['gRPC_CARES_PROVIDER'] = "package" cmake.definitions['gRPC_ZLIB_PROVIDER'] = "package" cmake....
und for https://github.com/grpc/grpc/issues/11068 cmake.definitions['gRPC_GFLAGS_PROVIDER'] = "none" cmake.definitions['gRPC_BENCHMARK_PROVIDER'] = "none" # Compilation on minGW GCC requires to set _WIN32_WINNTT to at least 0x600 # https://github.com/grpc/grpc/blob/109c570727c3089fef655...
TheAspiringHacker/Asparserations
bootstrap/parser_gen.py
Python
mit
13,102
0.004427
#!/usr/bin/python3 import argparse import collections import json import string import sys header_template = """ #ifndef ASPARSERATIONS_GENERATED_${class_name}_H_ #define ASPARSERATIONS_GENERATED_${class_name}_H_ #include <array> #include <map> #include <memory> #include <set> #include <utility> #include <vector> $h...
$namespace::Lexer_State $namespace::next(const $namespace::Lexer_State& ls) { $namespace::Lexer_State ls_prime = { ls.end, ls.end, ls.lines, ls.last_newline }; return ls_prime; } $namespace::Node::Node(const $payload& payload, const $namespace::Lexer_State& state) : m_pa...
& payload, std::vector<std::unique_ptr<Node>> children) { if(children.empty()) throw std::runtime_error("Zero children," "call Node(const char*, const char*) instead"); m_payload = payload; m_children = std::move(children); m_state = $namespace::Lexer_Stat...
indictranstech/omnitech-frappe
frappe/desk/doctype/note/test_note.py
Python
mit
225
0.013333
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors and Contributors # See license.txt import frappe import unittest test_records = frappe.get_test_records('Note') class TestNo
te(unittest.TestCase): pa
ss
koreiklein/fantasia
lib/common_formulas.py
Python
gpl-2.0
3,977
0.023887
# Copyright (C) 2013 Korei Klein <[email protected]> from calculus.enriched import formula, constructors, endofunctor from calculus.basic import formula as basicFormula from lib.common_symbols import leftSymbol, rightSymbol, relationSymbol, domainSymbol, inputSymbol, outputSymbol, functionPairsSymbol from lib imp...
))) def IsFunction(f): return constructors.Always(constructors.Holds(f, common_vars.function)) InDomain = formula.InDomain Equal = formula.Equal Identical = formula.Identical def InductionBase(var, claim): return claim.substituteVariable(var, common_vars.zero) def InductionStep(var, claim): newVar = var.rela...
wVar, common_vars.natural)], constructors.Implies([claim.substituteVariable(var, newVar)], claim.updateVariables().substituteVariable(var, variable.ApplySymbolVariable(newVar, common_vars.S)))) def InductionHypotheses(var, claim): return constructors.And([InductionBase(var, claim), InductionStep(var, c...
jesseengel/magenta
magenta/common/__init__.py
Python
apache-2.0
1,001
0
# Copyright 2019 The Magenta Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
he License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Imports objects into the top-level common namespace.""" from __future__ import absolute_im...
port Nade from .sequence_example_lib import count_records from .sequence_example_lib import flatten_maybe_padded_sequences from .sequence_example_lib import get_padded_batch from .sequence_example_lib import make_sequence_example from .tf_utils import merge_hparams
pradyunsg/Py2C
py2c/tree/tests/test_visitors.py
Python
bsd-3-clause
5,659
0.00053
"""Unit-tests for `tree.visitors` """ from py2c import tree from py2c.tree import visitors from py2c.tests import Test, data_driven_test from nose.tools import assert_equal # TEST:: Add non-node fields # ============================================================================= # Helper classes # ==============...
BasicNodeReplacement(tree.Node): _fields = [] class BasicNodeWithListReplacement(tree.Node): _fields = [] class BasicNodeDeletable(tree.Node): _fields = [] class ParentNode(tree.Node): _fields = [ ('child', tree.Node, 'OPTIONAL'), ] class ParentNodeWithChildrenList(tree.Node): ""...
------------------------------------------- # Concrete Visitors used for testing # ----------------------------------------------------------------------------- class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor): def __init__(self): super().__init__() self.visited = [] def generic_...
TwilioDevEd/api-snippets
twiml/voice/sms/sms-2/sms-2.6.x.py
Python
mit
207
0
from twilio.twiml.voice_response import Vo
iceResponse, Say, Sms response = VoiceResponse() response.say('Our store is located at 123 Easy St.') response.sms('Store Location: 123 Easy St.
') print(response)
markrages/ble
profiles/hrm_service.py
Python
mit
1,438
0.013908
#!/usr/bin/python import ble import uuids OPCODE_RESET_EXPENDED=1 class HeartRateService(ble.Service): uuid=uuids.heart_rate class HeartRateControlPoint(ble.Characteristic): uuid=uuids.heart_rate_control_point def reset_expended(self): opcode = OPCODE_RESET_EXPENDED self.va...
e = value.pop(0) e += 256*value.pop(0) meas['energy_expended'] = e if rr_present: rr = [] while value: rr_val = value.pop(0) rr_val += 256*value.pop(0) rr_val /= 102
4. rr.append(rr_val) meas['rr'] = rr return meas
recognai/spaCy
spacy/tests/lang/de/test_exceptions.py
Python
mit
1,230
0.000814
# coding: utf-8 """Test that tokenizer exceptions and emoticons are handles correctly.""" from __future__ import unicode_literals import pytest @pytest.mark.parametrize('text', ["auf'm", "du's", "über'm", "wir's"]) def test_de_tokenizer_splits_contractions(de_tokenizer, text): tokens = de_tokenizer(text) a...
"d.h.", "Jan.", "Dez.", "Chr."]) def test_de_tokenizer_handles_abbr(de_tokenizer, text): tokens = de_tokenizer(text) assert len(tokens) == 1 def test_de_tokenizer_handles_exc_in_text(de_tokenizer): text = "Ich bin z.Zt. im Ur
laub." tokens = de_tokenizer(text) assert len(tokens) == 6 assert tokens[2].text == "z.Zt." assert tokens[2].lemma_ == "zur Zeit" @pytest.mark.parametrize('text,norms', [("vor'm", ["vor", "dem"]), ("du's", ["du", "es"])]) def test_de_tokenizer_norm_exceptions(de_tokenizer, text, norms): tokens = d...
msfrank/mandelbrot
test/mock_transport.py
Python
gpl-3.0
1,546
0.000647
import asyncio from mandelbrot.transport import * class MockTransport(Transport): def mock_create_item(self, path, item): raise NotImplementedError() @asyncio.coroutine def create_item(self, path, item): return self.mock_create_item(path, item) def mock_replace_item(self, path, item...
lf, path, matchers, count, last): return self.mock_get_collection(path, matchers, count, last) def mock_delete_collection(self, path, params): raise NotImplementedError() @asyncio.coroutine def delete_co
llection(self, path, params): return self.mock_delete_collection(path, params)
kerel-fs/skylines
tests/api/schemas/user_test.py
Python
agpl-3.0
2,586
0.000773
from collections import OrderedDict from datetime import datetime from skylines.api import schemas def test_user_schema(test_user): """:type test_user: skylines.model.User""" data, errors = schemas.user_schema.dump(test_user) assert not errors assert isinstance(data, OrderedDict) assert data.ke...
test_user.id asse
rt data['name'] == test_user.name assert data['first_name'] == test_user.first_name assert data['last_name'] == test_user.last_name assert data['email'] == test_user.email_address assert data['tracking_key'] == ('%X' % test_user.tracking_key) assert data['tracking_delay'] == test_user.tracking_delay...
msultan/msmbuilder
msmbuilder/project_templates/msm/timescales-plot.py
Python
lgpl-2.1
1,908
0.004193
"
""Plot implied timescales vs lagtime {{header}} """ # ? include "plot_header.template" # ? from "plot_macros.template" import xdg_open with context import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt sns.set_style('ticks') colors = sns.color_palette() ## Load timescale...
len([x for x in timescales.columns if x.startswith('timescale_')]) ## Implied timescales vs lagtime def plot_timescales(ax): for i in range(n_timescales): ax.scatter(timescales['lag_time'], timescales['timescale_{}'.format(i)], s=50, c=colors[0], ...
creasyw/IMTAphy
documentation/doctools/tags/0.2/sphinx/directives.py
Python
gpl-2.0
31,058
0.002222
# -*- coding: utf-8 -*- """ sphinx.directives ~~~~~~~~~~~~~~~~~ Handlers for additional ReST directives. :copyright: 2007-2008 by Georg Brandl. :license: BSD. """ import re import sys import string import posixpath from os import path from docutils import nodes from docutils.parsers.rst import d...
targetid = 'index-%s' % env.index_num env.index_num += 1 targetnode = nodes.target('', '', ids=[targ
etid]) state.document.note_explicit_target(targetnode) indexnode = addnodes.index() indexnode['entries'] = ne = [] for entry in arguments: entry = entry.strip() for type in entrytypes: if entry.startswith(type+':'): value = entry[len(type)+1:].strip() ...
OTL/jps
test/test_serialize.py
Python
apache-2.0
697
0
import json import time import jps class MessageHolder(object): def __init__(self): self.saved_msg = [] def __call__(self, msg): self.saved_msg.append(msg) def test_pubsub_with_serialize_json(): holder = MessageHolder() sub = jps.Subscriber('/serialize_hoge1', holder, ...
serializer=json.dumps) time.sleep(0.1) obj = {'da1': 1, 'name': 'hoge'} pub.publish(obj) time.sleep(0.1) sub.spin_once() assert len(holder.sa
ved_msg) == 1 assert holder.saved_msg[0]['da1'] == 1 assert holder.saved_msg[0]['name'] == 'hoge'
wooey/django-djangui
wooey/conf/project_template/urls/user_urls.py
Python
bsd-3-clause
353
0.005666
from os import environ from django.conf.urls import include, url from django.conf import settings from django.conf.urls
.static import static from .wooey_urls import * if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STA
TIC_URL, document_root=settings.STATIC_ROOT)
jorik041/Veil-Evasion
modules/payloads/ruby/meterpreter/rev_http.py
Python
gpl-3.0
2,371
0.012231
""" Custom-written pure ruby meterpreter/reverse_http stager. TODO: better randomization Module built by @harmj0y """ from modules.common import helpers class Payload: def __init__(self): # required options self.description = "pure windows/meterpreter/reverse_http stager, no shellcode" ...
000\n" payloadCode += "\t\tpt = $v.call(0,(sc.length > 0x1000 ? sc.length : 0x1000), 0x1000, 0x40)\n" payloadCode += "\t\tx = $r.call(pt,sc,sc.length)\n" payloadCode += "\t\tx = $w.c
all($c.call(0,0,pt,0,0,0),0xFFFFFFF)\n" payloadCode += "\tend\nend\n" payloadCode += "uri = URI.encode(\"http://%s:%s/#{ch()}\")\n" % (self.required_options["LHOST"][0], self.required_options["LPORT"][0]) payloadCode += "uri = URI(uri)\n" payloadCode += "ij(Net::HTTP.get(uri))" ...
NicovincX2/Python-3.5
Algorithmique/Algorithme/Algorithme numérique/Algorithme d'Euclide étendu/extended_euclidean_algorithm.py
Python
gpl-3.0
1,258
0.00159
# -*- coding: utf-8 -*- import os # Author: Sam Erickson # Date: 2/23/2016 # # Program Description: This program gives the integer coefficients x,y to the # equation ax+by=gcd(a,b) given by the extended Euclidean Algorithm. def extendedEuclid(a, b): """ Preconditions - a and b are both positive integers. ...
[b % a, 1, b,
-1 * (b // a), a]] while b % a > 0: b, a = a, b % a euclidList.append([b % a, 1, b, -1 * (b // a), a]) if len(euclidList) > 1: euclidList.pop() euclidList = euclidList[::-1] for i in range(1, len(euclidList)): euclidList[i][1] *= euclidList[i - 1][3] ...
MTgeophysics/mtpy
mtpy/gui/SmartMT/visualization/strike.py
Python
gpl-3.0
3,575
0.003077
# -*- coding: utf-8 -*- """ Description: Usage: Author: YingzhiGou Date: 21/08/2017 """ from mtpy.gui.SmartMT.Components.FigureSetting import Font from mtpy.gui.SmartMT.Components.PlotParameter import FrequencyTolerance, Rotation from mtpy.gui.SmartMT.gui.plot_control_guis import PlotControlStrike fr...
(self._parameter_ui) self._font_ui.hide_weight() self._font_ui.hide_color() self._parameter_ui.add_figure_groupbox(self._font_ui) self._parameter_ui.end_of_parameter_components() self.update_ui() self._params = None def plot(self): # set up params s...
self._rotation_ui.get_rotation_in_degree(), 'period_tolerance': self._tolerance_ui.get_tolerance_in_float(), 'plot_range': self._plot_control_ui.get_plot_range(), 'plot_type': self._plot_control_ui.get_plot_type(), 'plot_tipper': self._plot_control_ui.get_plot_tipper(), ...
tstenner/bleachbit
windows/setup_py2exe.py
Python
gpl-3.0
20,767
0.000626
""" BleachBit Copyright (C) 2008-2020 Andrew Ziem https://www.bleachbit.org This program is free s
oftware: you can redistribute it and/or modi
fy it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ...
InakiZabala/odoomrp-wip
stock_packaging_info/__openerp__.py
Python
agpl-3.0
1,532
0
# -*- encoding: utf-8 -*- ############################################################################## # # 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...
"Pedro M. Baeza <pedr
[email protected]>", "Ana Juaristi <[email protected]>" ], "category": "Custom Module", "summary": "", "data": [ "views/stock_view.xml", ], "installable": True, "auto_install": False, }
studybuffalo/studybuffalo
study_buffalo/hc_dpd/migrations/0012_align_with_hc_20220301_2.py
Python
gpl-3.0
620
0
# pylint: disable=missing-module-docstring, missing-class-docstring from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hc_dpd', '0011_align_with_h
c_20220301'), ] operations = [ migrations.AlterField( model_name='company', name='company_name', field=models.CharField(blank=True, max_length=80, null=True), ), migrations.AlterField( model_n
ame='company', name='street_name', field=models.CharField(blank=True, max_length=80, null=True), ), ]
smeerten/ssnake
src/safeEval.py
Python
gpl-3.0
2,736
0.00402
#!/usr/bin/env python3 # Copyright 2016 - 2021 Bas van Meerten and Wouter Franssen # This file is part of ssNake. # # ssNake 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, o...
nv["globals"] = None env["__name__"] = None env["__file__"] = None env["__builtins__"] = {'None': None, 'False': False, 'True':True} # None env["slice"] = slice if length is not None: env["length"] = length if x is not None: env["x"] = x inp = re.sub('([0-9]+)[kK]', '\g<1>*10...
ype == 'FI': #single float/int type if isinstance(val, (float, int)) and not np.isnan(val) and not np.isinf(val): return val return None if Type == 'C': #single complex number if isinstance(val, (float, int, complex)) and not np.isnan(val) and not np.isinf(va...
andialbrecht/sqlparse
sqlparse/filters/aligned_indent.py
Python
bsd-3-clause
5,110
0
# # Copyright (C) 2009-2020 the sqlparse authors and contributors # <see AUTHORS file> # # This module is part of python-sqlparse and is released under # the BSD License: https://opensource.org/licenses/BSD-3-Clause from sqlparse import sql, tokens as T from sqlparse.utils import offset, indent class AlignedIndentFi...
columns being selected identifiers = list(tlist.get_identifiers()) identifiers.pop(0) [tlist.insert_before(token, self.nl()) for token in identifiers] self._process_default(tlist) def _process_case(
self, tlist): offset_ = len('case ') + len('when ') cases = tlist.get_cases(skip_ws=True) # align the end as well end_token = tlist.token_next_by(m=(T.Keyword, 'END'))[1] cases.append((None, [end_token])) condition_width = [len(' '.join(map(str, cond))) if cond else 0 ...
danmergens/mi-instrument
mi/dataset/parser/pco2a_a_dcl.py
Python
bsd-2-clause
10,120
0.003063
#!/usr/bin/env python """ @package mi.dataset.parser.pco2a_a_dcl @file marine-integrations/mi/dataset/parser/pco2a_a_dcl.py @author Sung Ahn @brief Parser for the pco2a_a_dcl dataset driver This file contains code for the pco2a_a_dcl parser and code to produce data particles. For instrument telemetered data, there is...
_PATTERN += START_METADATA # Metadata record starts with '[' METADATA_PATTERN += ANY_CHARS_REGEX # followed by text METADATA_PATTERN += END_METADATA # followed by ']' METADATA_PATTERN += ANY_CHARS_REGEX # followed by more text METADATA_PATTERN += END_OF_LINE_REGEX # metadata record ends with LF METADATA_MATCHER = ...
N) # Sensor data record: # Timestamp Date<space>Time<space>SensorData # where SensorData are comma-separated unsigned integer numbers SENSOR_DATA_PATTERN = TIMESTAMP + SPACE_REGEX # dcl controller timestamp SENSOR_DATA_PATTERN += SHARP + START_GROUP + SENSOR_DATE + SPACE_REGEX # sensor date SENSOR_DATA_PATTERN +...
reschly/cryptopals
prob1.py
Python
apache-2.0
3,439
0.018028
#!/usr/bin/env python # Written against python 3.3.1 # Matasano Problem 1 # Convert hex to base64 # Example hex: 49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d # Example base64: SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t import base64 impo...
5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2'...
6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff',] def base64toRaw(b64): raw = base64.b64decode(b64); return raw; def rawToBase64(raw): b64 = base64.b64encode(raw); return b64; def hexToRaw(hx): raw = binascii.unhexlify(hx); return raw; def rawToHex(raw): #hx =...
biggihs/python-pptx
tests/test_presentation.py
Python
mit
8,885
0
# encoding: utf-8 """ Test suite for pptx.presentation module. """ from __future__ import ( absolute_import, division, print_function, unicode_literals ) import pytest from pptx.parts.coreprops import CorePropertiesPart from pptx.parts.presentation import PresentationPart from pptx.parts.slide import NotesMaste...
lled_once_with( prs._element.xpath('p:sldMasterIdLst
')[0], prs ) assert slide_masters is slide_masters_ assert prs._element.xml == expected_xml def it_can_save_the_presentation_to_a_file(self, save_fixture): prs, file_, prs_part_ = save_fixture prs.save(file_) prs_part_.save.assert_called_once_with(file_) # fixtu...
quickresolve/accel.ai
flask-aws/lib/python2.7/site-packages/ebcli/lib/elbv2.py
Python
mit
2,545
0.005108
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
nce_healths #map of instance_id => [target group health descrpitions] def get_target_group_healths(target_group_arns): results = {} for arn in target_group_arns: try: results[arn] = _make_api_call('describe_target_health', TargetGroupArn=arn) except ServiceError as e: if...
th descrpitions]
gusevfe/snakemake
tests/test14/qsub.py
Python
mit
319
0
#!/usr/bin/env python3 import sys import os import random from snakemake.utils import read_job_properties jobscript = sys.argv[1] j
ob_properties
= read_job_properties(jobscript) with open("qsub.log", "w") as log: print(job_properties, file=log) print(random.randint(1, 100)) os.system("sh {}".format(jobscript))
HWDexperte/ts3observer
ts3observer.py
Python
mit
2,869
0.004183
#!/usr/bin/env python import os, argparse, logging from ts3observer.cli import CommandLineInterface as Cli from ts3observer.gui import GraphicalUserInterface as Gui from ts3observer.utils import path from ts3observer.exc import CriticalException, ShutDownException, print_traceback, print_buginfo class Dispatcher(obj...
as e: print_traceback() logging.critical('{}: {}'.format(e.
__class__.__name__, str(e))) print_buginfo() if __name__ == '__main__': _run() else: raise Exception('Please, run this script directly!')
billingstack/python-fakturo
fakturo/core/client.py
Python
apache-2.0
2,138
0.000468
import logging import requests from fakturo.core import exceptions, utils LOG = logging.getLogger(__name__) class BaseClient(object): def __init__(self, url=None): url.rstrip('/') self.url = url self.requests = self.get_requests() def get_requests(self, headers={}, args_hooks=[],...
, *args, **kw):
path = path.lstrip('/') if path else '' url = self.url + '/' + path LOG.debug('Wrapping request to %s' % url) wrapper = kw.get('wrapper', None) # NOTE: If we're passed a wrapper function by the caller, pass the # requests function to it along with path and other args... ...
caktus/rapidsms
rapidsms/contrib/locations/utils.py
Python
bsd-3-clause
1,402
0
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 from rapidsms.utils.modules import try_import from .forms import LocationForm from .models import Location def get_model(name): """ """ for type in Location.subclasses(): if type._meta.module_name == name: return type raise Sta...
""" parts = model.__module__.split(".") parts[parts.index("models")] = "forms" module_name = ".".join(parts) form_name = model.__name__ + "Form" module = try_
import(module_name) if module is not None: form = getattr(module, form_name, None) if form is not None: return form meta_dict = LocationForm.Meta.__dict__ meta_dict["model"] = model return type( form_name, (LocationForm,), { "Meta": type("Meta",...
SEL-Columbia/commcare-hq
corehq/apps/dashboard/views.py
Python
bsd-3-clause
1,502
0.001997
from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.utils.decorators import method_decorator from django.utils.translation import ugettext_noop from corehq import toggles from corehq.apps.domain.views import DomainViewMixin, LoginAndDomainMixin from corehq.apps.hqwebap...
, **kwargs) @property def main_context(self): context = super(BaseDashboardView, self).main_context context.update({ 'domain': self.domain, }) return context @property def page_url(self):
return reverse(self.urlname, args=[self.domain]) class NewUserDashboardView(BaseDashboardView): urlname = 'dashboard_new_user' page_title = ugettext_noop("HQ Dashboard") template_name = 'dashboard/dashboard_new_user.html' @property def page_context(self): return { }
activityworkshop/Murmeli
test/test_torclient.py
Python
gpl-2.0
3,296
0.002124
'''Module for testing the tor client''' import unittest import os import time import socks from murmeli import system from murmeli.torclient import TorClient from murmeli.message import ContactRequestMessage class FakeMessageHandler(system.Component): '''Handler for rece
iving messages from Tor''' def __init__(self, sys): system.Component.__init__(self, sys, system.System.COMPNAME_MSG_HANDLER) self.messages = [] def receive(self, msg): '''Receive an incoming message''' if msg: self.messages.append(msg) class TorTest(unittest.TestCa...
): '''Test sending non-valid and valid data to the listener''' sys = system.System() tordir = os.path.join("test", "outputdata", "tor") os.makedirs(tordir, exist_ok=True) tor_client = TorClient(sys, tordir) sys.add_component(tor_client) self.assertTrue(tor_client....
epeios-q37/epeios
tools/xdhq/wrappers/PYH/XDHqXML.py
Python
agpl-3.0
1,921
0.023425
""" MIT License Copyright (c) 2018 Claude SIMON (https://q37.info/s/rmnmqd49) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights ...
pushTag = push_tag def pop_tag(self): self._xml += "<" popTag = pop_tag def put_attribute(self,name,value): self._xml += "A" self._write(name)
self._write(str(value)) putAttribute = put_attribute def put_value(self,value): self._xml += "V" self._write(str(value)) putValue = put_value def put_tag_and_value(self,tag,value): self.pushTag(tag) self.putValue(value) self.popTag() putTagAndValue = put_tag_and_value def to...
chronossc/notes-app
notes/migrations/0001_initial.py
Python
mit
993
0.002014
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-03-23 02:11 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Note', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.Ch...
('slug', models.SlugField(unique=True)), ('note', models.TextField()), ('favorited', models.BooleanField(default=False)), ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='notes', to=settings.AUTH_USER_MODEL)), ],...
jakobluettgau/feo
tapesim/components/FileManager.py
Python
gpl-3.0
2,010
0.004478
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (C) 2015 Jakob Luettgau # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any l...
ecks if file exists""" if name in self.files: return self.files[name] else: return False def scan(self, entry): """Scan the data structure for a entry
""" pass def update(self, name, tape=None, size=None, pos=0): # create entry if not existent if not (name in self.files): self.files[name] = {} # set fields idividually if tape != None: self.files[name]['tape'] = tape if size != No...
thormuller/yescoin2
share/qt/extract_strings_qt.py
Python
mit
1,873
0.005873
#!/usr/bin/python ''' Extract _("...") strings for translation and convert to Qt4 stringdefs so that they can be picked up by Qt lin
guist. ''' from subprocess import Popen, PIPE import glob import operator import os import sys OUT_CPP="qt/yescoinstrings.cpp" EMPTY=['""'] def parse_po(text): """ Parse 'po' format produced by xgettext. Return a list of (msgid,msgstr) tuples. """ messages = [] msgid = [] msgstr = [] i...
ine.startswith('msgid '): if in_msgstr: messages.append((msgid, msgstr)) in_msgstr = False # message start in_msgid = True msgid = [line[6:]] elif line.startswith('msgstr '): in_msgid = False in_...
cuttlefishh/papers
vibrio-fischeri-transcriptomics/code/python/totalannotation_v1-1.py
Python
mit
12,403
0.048859
#!/usr/bin/env python import urllib import sys import os ##### totalannotation.py by DJ Barshis ##### This script takes an input fasta file of sequence names and sequences, and blast results files of blasts against ##### nr (parsed .txt with 1 hit per line) and swissprot and tremble (in -outfmt 7) uniprot databases ...
niqueprotIDs #this line calls the uniprot reading function uniprotIDs, uniquesforflats=read_uniprot(sys.argv[4], sys.argv[5]) print 'downloading flat files ...' #this loop downloads all the uniprot flat files for
the list of unique uniprotIDs that was parsed from the blast results for key, value in uniquesforflats.items(): if os.pa
Ircam-Web/mezzanine-organization
organization/projects/migrations/0088_auto_20190703_1035.py
Python
agpl-3.0
1,401
0.001428
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-07-03 08:35 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('organization_projects', '0087_auto_20190619_2052'), ] operations = [ migrations.Alt...
s'}, ), migrations.AlterModelOptions( name='projectpage', options={'permissions': (('user_add', 'Mezzo - User - User can add its own content'),
('user_edit', 'Mezzo - User - User can edit its own content'), ('user_delete', 'Mezzo - User - User can delete its own content'), ('team_add', 'Mezzo - User - Team can add its own content'), ('team_edit', "Mezzo - Team - User can edit his team's content"), ('team_delete', "Mezzo - Team - User can delete his team's cont...