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 |
|---|---|---|---|---|---|---|---|---|
tijme/angularjs-sandbox-escape-scanner | acstis/Scanner.py | Python | mit | 5,980 | 0.002007 | # -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2017 Tijme Gommers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to... | acstis.helpers.BrowserHelper import BrowserHelper
from acstis.actions.TraverseUrlAction import TraverseUrlAction
from acstis.actions.FormDataAction import FormDataAction
from acstis.actions.QueryDataAction import QueryDataAction
from nyawc.http.Handler import Handler as HTTPHandler
class Scanner:
"""The Scanner s... | __actions list(:class:`acstis.actions.BaseAction`): The actions to perform on the queue item.
__driver (:class:`acstis.Driver`): Used to check if we should stop scanning.
__verify_payload (bool): Verify if the payload was executed.
__queue_item (:class:`nyawc.QueueItem`): The queue item t... |
mircealungu/Zeeguu-Core | tools/tag_topics_in_danish.py | Python | mit | 1,205 | 0.00249 | import zeeguu_core
from zeeguu_core.model import Article, Language, LocalizedTopic
session = zeeguu_core.db.session
counter = 0
languages = Language.available_lang | uages()
languages = [Language.find('da')]
for language in languages:
articles = Article.query.filter(Article.language == language).order_by(Article.id.desc()).all()
loc_topics = LocalizedTopic.all_for_language(language)
total_articles = len(articles)
for article in articles:
counter += 1
... | loc_topic in loc_topics:
if loc_topic.matches_article(article):
article.add_topic(loc_topic.topic)
print(f" #{loc_topic.topic_translated}")
print("")
session.add(article)
if counter % 1000 == 0:
percentage = (100 * counter / total_article... |
jureslak/racunalniske-delavnice | fmf/python_v_divjini/projekt/test/test_game.py | Python | gpl-2.0 | 1,623 | 0.000616 | from tictactoe import game, player
import unittest
from unittest import mock
class GameTest(unittest.TestCase):
def setUp(self):
self.num_of_players = 2
self.width = 3
self.height = 3
self.game = game.Game(2, 3, 3)
def test_init(self):
self.assertEqual(self.game.board,... | = ['Luke', 'x', 'Leia', 'o']
with mock.patch('builtins.input', side_effect=inpu | t_seq):
self.game.setup()
input_seq = ['2', '5', '3', '1', '9', '6', '7', '4']
with mock.patch('builtins.input', side_effect=input_seq):
self.game.play_round()
finished, winner = self.game.board.finished()
self.assertTrue(finished)
self.assertEqual(winne... |
nuccdc/scoring_engine | scoring_engine/engine/serializers.py | Python | mit | 1,320 | 0.000758 | '''
'''
from rest_framework import serializers
import models
class PluginSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Plugin
fields = ('id', 'name', )
class ScoredServiceSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models... | = models.Service
fields = ('id', 'scored_service', 'address', 'port', 'team', ' | credentials', 'results')
read_only_fields = ('results', )
class CredentialSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Credential
fields = ('id', 'username', 'password', 'service')
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class... |
jabber-at/hp | hp/account/migrations/0006_notifications.py | Python | gpl-3.0 | 1,200 | 0.0025 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-14 12:09
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):
dependencies = [
('account', '0005_user_last_... | ue)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='notifications', serialize=False, to | =settings.AUTH_USER_MODEL)),
('account_expires', models.BooleanField(default=False, help_text='Accounts are deleted if they are not used for a year. Warn me a week before mine would be deleted.')),
('gpg_expires', models.BooleanField(default=False, help_text='Warn me a week before any of... |
sirkubax/ansible | lib/ansible/module_utils/cloudstack.py | Python | gpl-3.0 | 13,783 | 0.004136 | # -*- coding: utf-8 -*-
#
# (c) 2015, René Moser <mail@renemoser.net>
#
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the aut... | if not value:
value = self.module.params.get(fallback_key)
return value
# TODO: for backward compatibility only, remove i | f not used anymore
def _has_changed(self, want_dict, current_dict, only_keys=None):
return self.has_changed(want_dict=want_dict, current_dict=current_dict, only_keys=only_keys)
def has_changed(self, want_dict, current_dict, only_keys=None):
for key, value in want_dict.iteritems():
... |
witten/borgmatic | borgmatic/borg/list.py | Python | gpl-3.0 | 3,343 | 0.003889 | import logging
from borgmatic.borg.flags import make_flags, make_flags_from_arguments
from borgmatic.execute import execute_command
logger = logging.getLogger(__name__)
# A hack to convince Borg to exclude archives ending in ".checkpoint". This assumes that a
# non-checkpoint archive name ends in a digit (e.g. from... | urn archive
lock_wait = storage_config.get('lock_wait', None)
full_command = (
(local_path, 'list')
+ (('--info',) if logger.getEffectiveLevel() == logging.INFO else ())
+ (('--debug', '--show-rc') if logger.isEnabledFor(logging.DEBUG) else ())
+ make_flags('remote-path', remot... | ke_flags('last', 1)
+ ('--short', repository)
)
output = execute_command(full_command, output_log_level=None, borg_local_path=local_path)
try:
latest_archive = output.strip().splitlines()[-1]
except IndexError:
raise ValueError('No archives found in the repository')
logger.... |
uber-common/opentracing-python-instrumentation | tests/opentracing_instrumentation/test_boto3.py | Python | mit | 6,158 | 0 | import datetime
import io
import boto3
import mock
import pytest
import requests
import testfixtures
from botocore.exceptions import ClientError
from opentracing.ext import tags
from opentracing_instrumentation.client_hooks import boto3 as boto3_hooks
DYNAMODB_ENDPOINT_URL = 'http://localhost:4569'
S3_ENDPOINT_URL... | rs_table(dynamodb):
dynamodb.create_table(
TableName='users',
KeySchema=[{
'AttributeName': 'username',
'Key | Type': 'HASH'
}],
AttributeDefinitions=[{
'AttributeName': 'username',
'AttributeType': 'S'
}],
ProvisionedThroughput={
'ReadCapacityUnits': 9,
'WriteCapacityUnits': 9
}
)
@pytest.fixture
def dynamodb_mock():
import moto
... |
jpartogi/DOSBox.py | tests/filesystem/directory.py | Python | gpl-3.0 | 733 | 0.004093 | import unittest
from dosbox.filesystem.dire | ctory import *
class DirectoryTestCase(unittest.TestCase):
def setUp(self):
self.root_dir = Directory("root")
self.sub_dir1 = Directory("subdir1")
def test_path(self):
self.root_dir.add(self.sub_dir1)
self.assertEqual(self.sub_dir1.parent, self.root_dir)
self.assertEqu... | dd(subdir)
self.assertEqual(subdir.parent, self.root_dir)
self.root_dir.remove(subdir)
self.assertEqual(subdir.parent, None)
def test_number_of_contained_file_system_item(self):
return NotImplemented |
saymedia/SaySpider | saymedia/saymedia/settings.py | Python | mit | 1,287 | 0.001554 | # -*- coding: utf-8 -*-
# Scrapy settings for saymedia project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'saymedia'
SPIDER_MODULES = ['saymedia.spiders']
N... | a.pipelines.DatabaseWriterPipeline': 0,
}
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'SEO Spider (+http://www.say | media.com)'
DATABASE = {
'USER': 'YOUR_DATABASE_USER',
'PASS': 'YOUR_DATABASE_PASS',
}
FIREBASE_URL = "YOUR_FIREBASE_URL"
try:
# Only used in development environments
from .local_settings import *
except ImportError:
pass |
plotly/plotly.py | packages/python/plotly/plotly/validators/histogram2d/_histfunc.py | Python | mit | 487 | 0.002053 | import _plotly_utils.basevalidators
class HistfuncValidator(_plotly_ | utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="histfunc", parent_name="histogram2d", **kwargs):
super(HistfuncValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
va... | .pop("values", ["count", "sum", "avg", "min", "max"]),
**kwargs
)
|
sistason/pa3 | src/pa3_frontend/pa3_django/pa3_web/subscription_sms_handling.py | Python | gpl-3.0 | 411 | 0.007299 |
from django.http im | port HttpResponse, JsonResponse
from pa3_web.models import Subscriber
#
# Example of a subscription client
#
def delete_subscriber(phone_number):
[sub.delete() for sub in Subscriber.objects.filter(protocol='sms',
identifier=phone_number)]
return Ht | tpResponse(200)
def notify(subscriber):
# Send Notifying SMS
return |
nrebhun/FileSponge | src/filesponge.py | Python | mit | 2,647 | 0.0068 | #!/usr/bin/env python
import subprocess, os, sys, argparse
parser = argparse.ArgumentParser()
parser.add_argument("directory", help="First target directory for evaluation")
parser.add_argument("directories", nargs='+', help="All other directories to be evaluated")
parser.add_argument("-o", "--output", help="Output des... | print("Identical files:\n%s" % (commonList))
def isolateTargetFiles(commonList):
targetFiles = []
for line in commonList.split('\n'):
targetFiles.append(line.split()[0])
return targetFiles
def generateRsyncInclusionString(targetFiles):
inclusions = ''
for item in targetFiles:
inc... | urn inclusions
def writeInclusionListToDisk(targetFiles):
outfile = open('commonFiles.txt', 'w')
for item in targetFiles:
outfile.write("%s\n" % item)
def usage():
dirList = []
outputDir = None
if args.output:
outputDir = args.output or None
if args.directory:
dirList... |
nachandr/cfme_tests | cfme/fixtures/screenshots.py | Python | gpl-2.0 | 1,470 | 0.001361 | """Taking screenshots inside tests!
If you want to take a screenshot inside your test, just do it like this:
.. code-block:: python
def test_my_test(take_screenshot):
# do something
take_screenshot("Particular name for the screenshot")
# do something else
"""
import fauxfactory
import py... | t_hook
from cfme.fixtures.pytest_store import store
from cfme.utils.browser import take_screenshot as take_browser_screenshot
from cfme.utils.log import logger
@pytest.fixture(scope="function")
def take_screenshot(request):
item = request.node
def _take_screenshot(name):
logger | .info(f"Taking a screenshot named {name}")
ss, ss_error = take_browser_screenshot()
g_id = fauxfactory.gen_alpha(length=6)
if ss:
fire_art_test_hook(
item, 'filedump',
description=f"Screenshot {name}", file_type="screenshot", mode="wb",
... |
choozm/mamakstallinvestor-stockquote | populate_myportfolio.py | Python | mit | 6,849 | 0.019711 | import os
import datetime
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'invest.settings')
import django
django.setup()
from myportfolio.models import Investor, Portfolio, AssetClass, STOCKS, BONDS,\
ALTERNATIVES, Security, Transaction, Account
def populate():
investor1 = add_investor(name='David Lim',
... | asset_type=BONDS)
p1.target_asset_allocation[a1.id] = 0.3
p1.target_asset_allocation[a2.id] = 0.3
p1.target_asset_allocation[a3.id] = 0.4
p1.save()
s1 = add_security(asset_class=a1,
name='Vanguard Total Stock ETF',
symbol='... | exchange='NYSE',
expense_ratio_percent=0.1,
last_trade_price=100.05)
ac1 = add_account(owner=investor1,
name='SCB SGD',
description='SGD trading account')
ac2 = add_account(owner=investor1,
nam... |
MrSami/sandbox | alpagu/restate/apps.py | Python | mit | 89 | 0 | from dja | ngo.apps import AppConfig
|
class RestateConfig(AppConfig):
name = 'restate'
|
galaxy-iuc/parsec | parsec/commands/groups/delete_group_user.py | Python | apache-2.0 | 466 | 0 | import click
from parsec.cli import pass_context, json_loads
from parsec.decorators import custom_exception, json_output
@click.command('delete_group_user')
@click.argument("group_id", type=str)
@click.argument("user_id", type=str)
@pass_context
@custom_exception
@json_output
def cli(ctx, group_id, user_id):
"""R... | ut:
The user which was removed
"""
return ctx.gi.grou | ps.delete_group_user(group_id, user_id)
|
anhstudios/swganh | data/scripts/templates/object/mobile/shared_dressed_doak_sif.py | Python | mit | 441 | 0.047619 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_doak | _sif.iff"
result.attribute_template_id = 9
result.stfName("npc_name","human_base_male")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | |
amwelch/a10sdk-python | a10sdk/core/logging/logging_disable_partition_name.py | Python | apache-2.0 | 1,271 | 0.009441 | from a10sdk.common.A1 | 0BaseClass import A10BaseClass
class DisablePartitionName(A10BaseClass):
"""Class Description::
.
Class disable-partition-name supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param disable_partition_name: {"description"... | rtition-visibility": "shared", "default": 0, "type": "number", "format": "flag", "optional": true}
:param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"}
:param DeviceProxy: The device proxy for REST op... |
googleapis/python-aiplatform | .sample_configs/param_handlers/delete_specialist_pool_sample.py | Python | apache-2.0 | 714 | 0.001401 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "Li | cense");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT W... | ef make_name(name: str) -> str:
# Sample function parameter name in delete_specialist_pool_sample
name = name
return name
|
lovelysystems/pyjamas | library/pyjamas/ui/CheckBox.py | Python | apache-2.0 | 3,250 | 0.003077 | # Copyright 2006 James Tauber and contributors
#
# 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 agre... | tatic
def getUniqueID(self):
global _CheckBox_unique_id
_CheckBox_unique_id += 1
return _CheckBox_unique_id;
def getHTML(self):
return DOM.getInnerHTML(self.labelElem)
def getName(self):
return DOM.getAttribute(self.inputElem, "name")
def getText(self):
... | d):
DOM.setBooleanAttribute(self.inputElem, "checked", checked)
DOM.setBooleanAttribute(self.inputElem, "defaultChecked", checked)
def isChecked(self):
if self.isAttached():
propName = "checked"
else:
propName = "defaultChecked"
return DOM.getBoolean... |
mozilla/remoteobjects | remoteobjects/dataobject.py | Python | bsd-3-clause | 9,792 | 0.000511 | # Copyright (c) 2009-2010 Six Apart Ltd.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions an... | ed from or encoded as a dictionary.
DataObject subclasses should be de | clared with their different data
attributes defined as instances of fields from the `remoteobjects.fields`
module. For example:
>>> from remoteobjects import dataobject, fields
>>> class Asset(dataobject.DataObject):
... name = fields.Field()
... updated = fields.Datetime()
... ... |
wagtail/wagtail | wagtail/images/api/fields.py | Python | bsd-3-clause | 1,340 | 0.001493 | from collections import OrderedDict
from rest_framework.fields import Field
from ..models import SourceImageIOError
class ImageRenditionField(Field):
"""
A field that generates a rendition with the specified filter spec, and serialises
details of that rendition.
Example:
"thumbnail": {
... | thumbnail = image.get_rendition(self.filter_spec)
return OrderedDict(
[
| ("url", thumbnail.url),
("width", thumbnail.width),
("height", thumbnail.height),
("alt", thumbnail.alt),
]
)
except SourceImageIOError:
return OrderedDict(
[
("erro... |
openstack/stacktach-shoebox | shoebox/disk_storage.py | Python | apache-2.0 | 6,327 | 0 | # Copyright (c) 2014 Dark Secret Software Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | ble_schema, BOR_MAGIC_NUMBER, version)
def _check_eof(self, expected, actual):
if actual < expected:
raise EndOfFile()
def load_preamble(self, file_handle):
raw = file_handle.read(self.preamble_size)
self._check_eof(self.preamble_size, len(raw))
header = struct.unpa... | ning of Record marker")
return header[1]
class Version1(Version0):
# Version 1 SCHEMA
# ----------------
# i = metadata block length
# i = raw notification block length
# i = 0x00000000 EOR
# Metadata dict block
# i = number of strings (N) - key/value = 2 strings
# N * i = len... |
uw-dims/tupelo | docs/source/conf.py | Python | bsd-3-clause | 10,490 | 0.006292 | # -*- coding: utf-8 -*-
#
# Tupelo documentation build configuration file, created by
# sphinx-quickstart on Fri Jan 9 09:29:36 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
# autogenerated file.
# |
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
from sphinx import __version__
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# doc... | te, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions co... |
syci/domsense-agilebg-addons | account_followup_choose_payment/__init__.py | Python | gpl-2.0 | 1,092 | 0.000916 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2011 Agile Business Group sagl (<http://www.agilebg.com>)
# Copyright (C) 2011 Domsense srl (<http://www.domsense.com>)
#
# This program is free software: you can redistribute it and/or ... | implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have re | ceived a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import wizard
import followup
import account_move_line
import account_followup
|
pycontw/pycontw2016 | src/sponsors/migrations/0006_sponsor_conference.py | Python | mit | 579 | 0.001727 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-05-02 15:41
from __future__ import unicode_literals
from django.d | b import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sponsors', '0005_auto_20160530_1255'),
]
operations = [
migrations.AddField(
model_name='sponsor',
name='conference',
field= | models.SlugField(choices=[('pycontw-2016', 'PyCon Taiwan 2016'), ('pycontw-2017', 'PyCon Taiwan 2017')], default='pycontw-2017', verbose_name='conference'),
),
]
|
EmreAtes/spack | var/spack/repos/builtin/packages/libhio/package.py | Python | lgpl-2.1 | 2,974 | 0.001009 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | 5 variant a default
#
variant('hdf5', default=True, description='Enable HDF5 support')
depends_on("json-c")
depends_on("bzip2")
depends_on("pkgconfig", type="build")
depends_on('mpi')
#
# libhio depends on hdf5+mpi if hdf5 is being used since it
# autodetects the presence of an MPI... | depends_on('hdf5+mpi', when='+hdf5')
#
# wow, we need to patch libhio
#
patch('0001-configury-fix-a-problem-with-bz2-configury.patch', when="@1.4.1.0")
patch('0001-hdf5-make-docs-optional.patch', when="@1.4.1.0")
def autoreconf(self, spec, prefix):
autoreconf = which('autoreconf')
... |
dcf21/4most-4gp | src/pythonModules/fourgp_speclib/fourgp_speclib/tests/test_spectrum_library_sql.py | Python | mit | 7,484 | 0.004009 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Unit tests for all SQL implementations of spectrum libraries.
"""
from os import path as os_path
import uuid
import unittest
import numpy as np
import fourgp_speclib
class TestSpectrumLibrarySQL(object):
"""
This class is a mixin which adds lots of standard... |
for x in x_values:
input_spectrum = fourgp_speclib.Spectrum(wavelengths=np.arange(size),
values=np.random.random(size),
| value_errors=np.random.random(size),
metadata={"origin": "unit-test",
"x_value": alphabet[x:x + 3]})
self._lib.insert(input_spectrum, "x_{}".format(x))
# Search for spectra with ... |
tseaver/google-cloud-python | tasks/google/cloud/tasks_v2beta2/gapic/cloud_tasks_client.py | Python | apache-2.0 | 93,412 | 0.002516 | # -*- coding: utf-8 -*-
#
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | file
@classmethod
def location_path(cls, project, location):
"""Return a fully-qualified location string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}",
project=project,
location=location,
| )
@classmethod
def project_path(cls, project):
"""Return a fully-qualified project string."""
return google.api_core.path_template.expand(
"projects/{project}", project=project
)
@classmethod
def queue_path(cls, project, location, queue):
"""Return a fully... |
DevilSeven7/PDFManager | PDFManager/UI.py | Python | gpl-2.0 | 8,592 | 0.018506 | from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
from PDFManager.PDFMangerFacade import PDFMangerFacade
class PDFManager_UI:
def __init__(self):
self.i= -1;
self.files=[]
self.root = Tk()
self.root.title('PDFManager')
... | except IndexError:
messagebox.showwarning("Attenzione","Nessun elemento selezionato")
self.__controlla__()
def __unisci__(self):
try:
name = filedialog.asksaveasfilename(filetypes=[("PDF file",".pdf")])
if(name.endswith('.pdf') == False):
na... | :
messagebox.showwarning("Attenzione",e)
def __svuota__(self):
self.files = []
self.list_file.delete(*self.list_file.get_children())
def dividi(self):
try:
pos = self.list_file.selection()[0]
posizione = self.list_file.index(pos)
phat = fil... |
bendk/thesquirrel | events/tests/test_forms.py | Python | agpl-3.0 | 7,189 | 0.000556 | # thesquirrel.org
#
# Copyright (C) 2015 Flying Squirrel Community Space
#
# thesquirrel.org 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 la... | event = EventFactory()
instance = None
data = {
'type': '1M' if not empty_type else '',
'start_date': '1/1/2015',
'we': True if not no_days else False,
'end_date': '2/1/2015',
'start_time': '16:30',
'end_time': '18:30',
... | lf):
form = self.make_form_with_data()
assert form.is_valid()
event = EventFactory()
repeat = form.save(event)
assert repeat.event == event
def test_one_weekday_required(self):
form = self.make_form_with_data(no_days=True)
assert not form.is_valid()
def ... |
openwisp/django-x509 | tests/manage.py | Python | bsd-3-clause | 252 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJA | NGO_SETTINGS_MODULE', 'openwisp2.settings' | )
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
LLNL/spack | var/spack/repos/builtin/packages/py-pickleshare/package.py | Python | lgpl-2.1 | 764 | 0.003927 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level | COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyPickleshare(PythonPackage):
"""Tiny 'shelve'-like database with concurrency | support"""
pypi = "pickleshare/pickleshare-0.7.4.tar.gz"
version('0.7.5', sha256='87683d47965c1da65cdacaf31c8441d12b8044cdec9aca500cd78fc2c683afca')
version('0.7.4', sha256='84a9257227dfdd6fe1b4be1319096c20eb85ff1e82c7932f36efccfe1b09737b')
depends_on('python@2.7:2.8,3:', type=('build', 'run'))
... |
sbrichards/rockstor-core | src/rockstor/smart_manager/data_collector.py | Python | gpl-3.0 | 15,176 | 0.00112 | """
Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor 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 la... | ):
self.ppid = os.getpid()
self.sleep_time = 1
self._num_ts_records = 0
super(ProcRetreiver, self).__init__()
def _save_wrapper(self, ro):
ro.save()
self._num_ts_records = self._num_ts_records + 1
def _truncate_ts_data(self, max_records=settings.MAX_TS_RECORDS):... | DiskStat and ShareUsage, ServiceStatus
Discard all records older than last max_records.
"""
ts_models = (CPUMetric, LoadAvg, MemInfo, PoolUsage, DiskStat,
ShareUsage, ServiceStatus)
try:
for m in ts_models:
try:
latest_... |
benspaulding/django-epio-example | example/apps/things/admin.py | Python | bsd-3-clause | 661 | 0 | from django.contrib import admin
from django.utils.translation imp | ort ugettext_lazy as _
from example.apps.things.models import Thing
class ThingAdmin(admin.ModelAdmin):
fieldsets = (
(None, {
'fields': ('name', 'slug', 'image', 'description'),
}),
(_(u'Dates'), | {
'fields': ('created', 'modified'),
'classes': ('collapse', ),
}),
)
list_display = ('name', 'slug')
list_filter = ('created', 'modified')
prepopulated_fields = {'slug': ('name', )}
readonly_fields = ('created', 'modified')
search_fields = ('name', 'slug')
admi... |
JohnLZeller/dd-agent | checks.d/docker.py | Python | bsd-3-clause | 18,138 | 0.003418 | # stdlib
import urllib2
import urllib
import httplib
import socket
import os
import re
import time
from urlparse import urlsplit
from util import json
from collections import defaultdict
# project
from checks import AgentCheck
from config import _is_affirmative
EVENT_TYPE = SOURCE_TYPE_NAME = 'docker'
CGROUP_METRICS... | ")
return running_containers, ids_to_names
def _prepare_filters(self, instance):
# The reasoning is to check exclude first, so we can skip if there is no exclude
if not instance.get("exclude"):
return False
# Compile regex
| instance["exclude_patterns"] = [re.compile(rule) for rule in instance.get("exclude", [])]
instance["include_patterns"] = [re.compile(rule) for rule in instance.get("include", [])]
return True
def _is_container_excluded(self, instance, tags):
if self._tags_match_patterns(tags, instance.get... |
ScreamingUdder/mantid | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransformToIqt.py | Python | gpl-3.0 | 13,257 | 0.002263 | # pylint: disable=no-init,too-many-instance-attributes
from __future__ import (absolute_import, division, print_function)
from mantid.simpleapi import *
from mantid.api import (PythonAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty,
ITableWorkspaceProperty, PropertyMode, Progress)
from manti... | t. Default=-0.5')
self.declareProperty(name='EnergyMax', defaultValue=0.5,
doc='Maximum energy for fit. Default=0.5')
self.declareProperty(name='BinReductionFactor', defaultValue=10.0,
doc='Decr | ease total number of spectrum points by this ratio through merging of '
'intensities from neighbouring bins. Default=1')
self.declareProperty(ITableWorkspaceProperty('ParameterWorkspace', '',
direction=Direction.Output,
... |
henrytao-me/openerp.positionq | addons/positionq/pq_salary/pq_thang_luong.py | Python | agpl-3.0 | 1,548 | 0.007175 | # -*- coding: utf-8 -*-
from openerp.osv import osv, fields
from openerp.tools.translate import _
import logging
from datetime import datetime
from openerp.osv.fields import datetime as datetime_field
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT
from unidecode import unidecode
i... | e': lambda *x: 1,
'user_id': la | mbda self, cr, uid, context = None: uid,
}
_sql_constraints = [
]
def create(self, cr, uid, vals, context=None):
self.pool.get('pq.redis').clear_all(cr, uid)
return super(pq_thang_luong, self).create(cr, uid, vals, context)
def write(self, cr, uid, ids, vals, context=None)... |
christianurich/VIBe2UrbanSim | 3rdparty/opus/src/opus_core/datasets/interaction_dataset.py | Python | gpl-2.0 | 33,528 | 0.007904 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington
# See opus_core/LICENSE
from opus_core.resources import Resources
from opus_core.misc import take_choices, do_id_mapping_dict_from_array
from opus_core.misc import DebugPrin... | f.attribute_boxes = {}
self.attribute_names = []
self.debug = self.resources.get("debug", 0)
if not isinstance(self.debug, DebugPrinter):
self.debug = DebugPrinter(self.debug)
self.resources.check_obligatory_keys(["dataset1", "dataset2"])
self.dataset1 = self.r... | ("index2", None)
self.dataset_name = self.resources.get("dataset_name", None)
if self.dataset_name == None:
self.dataset_name = self.dataset1.get_dataset_name() + '_x_' + self.dataset2.get_dataset_name()
self._primary_attribute_names=[]
self.index1_mapping = {}
... |
jucapoco/baseSiteGanttChart | jcvrbaseapp/apps.py | Python | mit | 97 | 0 | from djang | o.apps import AppConfig
class JcvrbaseappConfig(AppConfig):
| name = 'jcvrbaseapp'
|
flyingSprite/spinelle | common/utility/image_downloader.py | Python | mit | 707 | 0.004243 |
from common.utility.utils import FileUtils
default_resource_path = '/Users/Fernando/Develop/ | downloader'
def get_image(image_hash):
"""
Download huaban image by image hash code.
Such as get_image('3058ff7398b8b725f436c6c7d56f60447468034d2347b-fGd8hd')
:param image_hash: Image hash code.
:return: None
"""
# Download normal auto size iamge.
url_normal = f'http://img.hb.aicdn.c... | e(url_normal, f'{default_resource_path}/normal/{image_hash}.jpg')
# Download 236px width size iamge.
url_fw236 = f'http://img.hb.aicdn.com/{image_hash}_fw236'
FileUtils.save_file(url_fw236, f'{default_resource_path}/fw236/{image_hash}.jpg')
|
saltzm/yadi | tests/test_yadi.py | Python | bsd-3-clause | 367 | 0.00545 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_yadi
--------------------------- | -------
Tests for `yadi` module.
"""
import unittest
from yadi import yadi
class TestYadi(unittest.TestCase):
def setUp(self):
pass
def test_something(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest | .main() |
wasade/qiime | qiime/truncate_reverse_primer.py | Python | gpl-2.0 | 7,049 | 0.000284 | #!/usr/bin/env python
# File created February 29, 2012
from __future__ import division
__author__ = "William Walters"
__copyright__ = "Copyright 2011, The QIIME Project"
__credits__ = ["William Walters", "Emily TerAvest"]
__license__ = "GPL"
__version__ = "1.8.0-dev"
__maintainer__ = "William Walters"
__email__ = "Wil... | log_data['sample_id_not_found'] += 1
output_fp.write('>%s\n%s\n' % (label, seq))
log_data['seqs_written'] += 1
continue
mm_tests = {}
for rev_primer in curr_rev_primer:
rev_primer | _mm, rev_primer_index =\
local_align_primer_seq(rev_primer, seq)
mm_tests[rev_primer_mm] = rev_primer_index
rev_primer_mm = min(mm_tests.keys())
rev_primer_index = mm_tests[rev_primer_mm]
if rev_primer_mm > primer_mismatches:
if truncate_option == "trun... |
valtech-mooc/edx-platform | lms/djangoapps/bulk_email/tests/test_course_optout.py | Python | agpl-3.0 | 4,696 | 0.003012 | # -*- coding: utf-8 -*-
"""
Unit tests for student optouts from course email
"""
import json
from mock import patch, Mock
from django.core import mail
from django.core.management import call_command
from django.core.urlresolvers import reverse
from django.conf import settings
from student.tests.factories import UserF... | tory.create()
self.student = UserFactory.create()
CourseEnrollmentFactory.create(user=self.student, course_id=self.course.id)
# load initial content (since we don't run migrations as part of tests):
call_command("loaddata", "course_email_template.json")
self.client.login(userna... | email', kwargs={'course_id': self.course.id.to_deprecated_string()})
self.success_content = {
'course_id': self.course.id.to_deprecated_string(),
'success': True,
}
def navigate_to_email_view(self):
"""Navigate to the instructor dash's email view"""
# Pull up... |
praw-dev/praw | praw/models/trophy.py | Python | bsd-2-clause | 1,987 | 0.001007 | """Represent the :class:`.Trophy` class."""
from typing import TYPE_CHECKING, Any, Dict, Union
from .base import PRAWBase
if TYPE_CHECKING: # pragma: no cover
import praw
class Trophy(PRAWBase):
"""Represent a trophy.
End users should not instantiate this class directly. :meth:`.Redditor.trophies` can... | .. include:: ../../typical_attributes.rst
=============== ===================================================
Attribute Description
=============== ===================================================
``award_id`` The ID of the trophy (sometimes ``None``).
``description`` The description | of the trophy (sometimes ``None``).
``icon_40`` The URL of a 41x41 px icon for the trophy.
``icon_70`` The URL of a 71x71 px icon for the trophy.
``name`` The name of the trophy.
``url`` A relevant URL (sometimes ``None``).
=============== ====================================... |
PepperPD/edx-pepper-platform | lms/djangoapps/instructor_task/tasks_helper.py | Python | agpl-3.0 | 18,210 | 0.005327 | """
This file contains tasks that are designed to perform background operations on the
running state of a course.
"""
import json
from time import time
from sys import exc_info
from traceback import format_exc
from celery import current_task
from celery.utils.log import get_task_logger
from celery.signals import wor... | ontaining the following keys:
'exception': type of exception object
'message': error message from exception object
'traceback': traceback inf | ormation (truncated if necessary)
Once the exception is caught, it is raised again and allowed to pass up to the
task-running level, so that it can also set the failure modes and capture the error trace in the
result object that Celery creates.
"""
# get the InstructorTask to be updated. If this... |
Manewing/pyAmbient | pyambient.py | Python | mit | 7,575 | 0.00462 | #!/usr/bin/python
from pygame import mixer
from threading import Timer
from random import randint
from xml.etree import ElementTree as XmlEt
import argparse
from utils import LOGGER
from sounds import SoundPool
# @brief constrain - constrains x to interval [mi, ma]
def constrain(x, mi, ma):
return min(ma, max(m... | self.spool = spool
for soundcfg in root.findall("Sound"):
sfile = soundcfg.get("file")
| base = float(soundcfg.get("base"))
drift = float(soundcfg.get("drift"))
self.sounds.append((sfile, base, drift))
LOGGER.logInfo("'{}': [{}] +/- ({})".format(sfile, base, drift))
# @brief __load - loads the actual ambient, delayed until it is started
def __load(s... |
openstack/tacker | tacker/vnfm/monitor_drivers/ping/ping.py | Python | apache-2.0 | 3,250 | 0.000615 | #
# 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
# ... | ts')),
cfg.IntOpt('retry', default=1,
help=_('Number of ping retries'))
]
cfg.CONF.register_opts(OPTS, 'monitor_ping')
def config_ | opts():
return [('monitor_ping', OPTS)]
class VNFMonitorPing(abstract_driver.VNFMonitorAbstractDriver):
def get_type(self):
return 'ping'
def get_name(self):
return 'ping'
def get_description(self):
return 'Tacker VNFMonitor Ping Driver'
def monitor_url(self, plugin, con... |
Q2MM/q2mm | q2mm/filetypes.py | Python | mit | 123,627 | 0.002912 | #!/usr/bin/env python
"""
Handles importing data from the various filetypes that Q2MM uses.
Schrodinger
-----------
When importing Schrodinger files, if the atom.typ file isn't in the directory
where you execute the Q2MM Python scripts, you may see this warning:
WARNING mmat_get_atomic_num x is not a valid atom typ... | log(1, '>>> energy: {}'.format(energy))
return energy
else:
raise Exception("Awww bummer! I can't find the energy "
"in {}!".format(path))
class TinkerHess(File):
def __init__(self, path):
super(TinkerHess, self).__init__(path)
self._hessi... | logger.log(10, 'READING: {}'.format(self.filename))
hessian = np.zeros([self.natoms * 3, self.natoms * 3], dtype=float)
logger.log(5, ' -- Creatting {} Hessian Matrix.'.format(
hessian.shape))
with open(self.path, 'r') as f:
lines = f.read()
... |
superdesk/superdesk-core | tests/enqueue_test.py | Python | agpl-3.0 | 1,353 | 0.002217 | from unittest.mock import patch
from superdesk.tests import TestCase
from apps.publish.enqueue.enqueue_service import EnqueueService
class NoTakesEnqueueTestCase(TestCase):
def setUp(self):
super().setUp()
self.product_ids = self.app.data.insert(
"products",
[
... |
self.subscriber_ids = self.app.data.insert(
"subscribers",
[
{"name": "digi", "subscriber_type": "digital", "is_targetable": True, "products": self.product_ids},
],
)
self.desk_ids = self.app.data.insert(
"desks",
[
... | def test_resend_no_takes(self):
doc = {"_id": "test"}
subscribers = [s for s in self.app.data.find_all("subscribers")]
subscriber_codes = self.service._get_subscriber_codes(subscribers)
with patch.object(self.service, "_resend_to_subscribers") as resend:
with patch.object(s... |
arista-eosext/rphm | setup.py | Python | bsd-3-clause | 3,002 | 0.001332 | # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# Copyright (c) 2014, Arista Networks, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# Redistributions of source code must reta... | the various commands
that operate on your modules do the right thing.
'''
import os
from glob import glob
from setuptools import setup, find_packages
from rphm import __version__, __author__
def find_modules(pkg):
''' Find the modules that belong in this package. '''
modules = [pkg]
for dirname, di... | ath.join(dirname, subdirname))
return modules
INSTALL_ROOT = os.getenv('VIRTUAL_ENV', '')
CONF_PATH = INSTALL_ROOT + '/persist/sys'
INSTALL_REQUIREMENTS = [
'jsonrpclib'
]
TEST_REQUIREMENTS = [
'mock'
]
setup(
name='rphm',
version=__version__,
description='EOS extension to gen... |
ooz/ICFP2015 | src/game.py | Python | mit | 8,981 | 0.001225 | #!/usr/bin/python
# coding: utf-8
import copy
import json
from lcg import LCG
class Game(object):
def __init__(self, json_file):
super(Game, self).__init__()
with open(json_file) as f:
json_data = json.load(f)
self.ID = json_data["id"]
self.units = [Unit(json_u... | [y]) + " "
buf.append(line)
return "\n".join(buf)
# TODO: refactor movement code
def move_e(self):
if self.unit is None:
return ""
unit_copy = copy.deepcopy(self.unit)
unit_copy.move_e()
cbp = unit_copy.can_be_placed(self)
if cbp == Unit.M... | return "e"
elif cbp == Unit.MV_LOCKED:
self.lock()
return "c"
else:
return ""
def move_w(self):
if self.unit is None:
return ""
unit_copy = copy.deepcopy(self.unit)
unit_copy.move_w()
cbp = unit_copy.can_be_pl... |
ncdesouza/bookworm | env/lib/python2.7/site-packages/pip/index.py | Python | gpl-3.0 | 40,408 | 0.002203 | """Routines related to PyPI, indexes"""
import sys
import os
import re
import mimetypes
import posixpath
from pip.log import logger
from pip.util import Inf, normalize_name, splitext, is_prerelease
from pip.exceptions import (DistributionNotFound, BestVersionAlreadyInstalled,
InstallationE... | self.dependency_links.extend(links)
def _sort | _locations(self, locations):
"""
Sort locations into "files" (archives) and "urls", and return
a pair of lists (files,urls)
"""
files = []
urls = []
# puts the url for the given file path into the appropriate list
def sort_path(path):
url = pa... |
Vvucinic/Wander | venv_2_7/lib/python2.7/site-packages/Django-1.9-py2.7.egg/django/core/management/commands/createcachetable.py | Python | artistic-2.0 | 4,389 | 0.00319 | from django.conf import settings
from django.core.cache import caches
from django.core.cache.backends.db import BaseDatabaseCache
from django.core.management.base import BaseCommand, CommandError
from django.db import (
DEFAULT_DB_ALIAS, connections, models, router, transaction,
)
from django.db.utils import Databa... | if f.primary_key:
field_output.append("PRIMARY KEY")
elif f.unique:
field_output.append("UNIQUE")
if f.db_index:
unique = "UNIQUE " if f.unique else ""
index_output.append("CREATE %sINDEX %s ON %s (%s);" %
... | put.append(" ".join(field_output))
full_statement = ["CREATE TABLE %s (" % qn(tablename)]
for i, line in enumerate(table_output):
full_statement.append(' %s%s' % (line, ',' if i < len(table_output) - 1 else ''))
full_statement.append(');')
full_statement = "\n".join(full_... |
tsl143/addons-server | src/olympia/reviewers/tests/test_models.py | Python | bsd-3-clause | 63,568 | 0.000031 | # -*- coding: utf-8 -*-
from datetime import datetime, timedelta
import json
import mock
import time
from django.conf import settings
from django.core import mail
from olympia import amo
from olympia.abuse.models import AbuseReport
from olympia.access.mod | els import Group, GroupUser
from olympia.activity.models import ActivityLog
from olympia.amo.tests import TestCase
from olympia.amo.tests import (
addon_factory, file_factory, user_factory, version_factory)
from olympia.addons.models import (
Addon, AddonApprovalsCou | nter, AddonReviewerFlags, AddonUser)
from olympia.files.models import FileValidation
from olympia.ratings.models import Rating
from olympia.reviewers.models import Whiteboard
from olympia.versions.models import (
Version, version_uploaded)
from olympia.files.models import File, WebextPermission
from olympia.reviewe... |
michelp/xodb | xodb/snowball/french/__init__.py | Python | mit | 2,426 | 0 | # -*- coding: utf-8 -*-
stopwords = """
| A French stop word list. Comments begin with vertical bar. Each stop
| word is at the start of a line.
au | a + le
aux | a + les
avec | with
ce | this
ces | these
dans | with
de | of
des ... | m)
mais | but
me | me
même | same; as in moi-même (myself) etc
mes | me (pl)
moi | me
mon | my (masc)
ne | not
nos | our (pl)
notre | our
nous | we
on | one
ou | where
par ... | el
que | that
qui | who
sa | his, her (fem)
se | oneself
ses | his (pl)
son | his, her (masc)
sur | on
ta | thy (fem)
te | thee
tes | thy (pl)
toi | thee
ton | thy (masc)
t... |
libracore/erpnext | erpnext/hr/doctype/leave_allocation/leave_allocation.py | Python | gpl-3.0 | 9,271 | 0.02373 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import flt, date_diff, formatdate, add_days, today, getdate
from frappe import _
from frappe.model.document import Docum... | days - 1) if expiry_days else self.to_date
args = dict(
leaves=self.unused_leaves,
from_date=self.from_date,
to_date= min(getdate(end_date), getdate(self.to_date)),
is_carry_forward=1
)
create_leave_ledger_entry(self, args, submit)
args = dict(
leaves=self.new_leaves_allocated,
from_da... | on(from_date, leave_type, employee):
''' Returns document properties of previous allocation '''
return frappe.db.get_value("Leave Allocation",
filters={
'to_date': ("<", from_date),
'leave_type': leave_type,
'employee': employee,
'docstatus': 1
},
order_by='to_date DESC',
fieldname=['name', 'from_... |
Brain888/OpenMineMods | GUI/Downloader.py | Python | agpl-3.0 | 4,748 | 0.001053 | from PyQt5.QtCore import QThread, pyqtSignal
from API.CurseAPI import CurseAPI, CurseFile, CurseModpack
from PyQt5.QtWidgets import *
from GUI.Strings import Strings
strings = Strings()
translate = strings.get
class FileDownloaderWindow(QWidget):
def __init__(self, file: str, curse: CurseAPI, path: str, fname=F... | t, name="bar2")
def __init__(self, file: CurseFile, curse: CurseAPI, pack: CurseModpack):
super().__init__()
self.file = file
self.curse = curse
self.pack = pack
def download(self) | :
self.pack.install(self.file, self.setLabel.emit, self.bar1.emit, self.bar2.emit)
self.done.emit()
self.terminate()
|
envoyproxy/envoy | tools/api_proto_breaking_change_detector/detector.py | Python | apache-2.0 | 5,354 | 0.002615 | """ Protocol Buffer Breaking Change Detector
This tool is used to detect "breaking changes" in protobuf files, to
ensure proper backwards-compatibility in protobuf API updates. The tool
can check for breaking changes of a single API by taking 2 .proto file
paths as input (before and after) and outputting a bool `is_br... | tools.api_proto_breaking_change_detector.buf_utils import check_breaking, pull_buf_deps
from tools.api_proto_breaking_change_detector.detector_errors import ChangeDetectorError
class ProtoBreakingChangeDetector(object):
"""Ab | stract breaking change detector interface"""
def run_detector(self) -> None:
"""Run the breaking change detector to detect rule violations
This method should populate the detector's internal data such
that `is_breaking` does not require any additional invocations
to the breaking ch... |
egabancho/invenio | invenio/legacy/bibmatch/engine.py | Python | gpl-2.0 | 64,532 | 0.005067 | ## This file is part of Invenio.
## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2014, 2015 CERN.
##
## Invenio 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... | ecords
-3 --print-fuzzy print records that match the longest words in existing records
-b --batch-output=(filename). filename.new will be new records, filename.matched will be matched,
filename.ambiguous will be ambiguous, filename.fuzzy will be fuzzy match
-t --text-marc-output transform the output to text-m... | ons:
-n --noprocess Do not print records in stdout.
-i, --input use a named file instead of stdin for input
-v, --verbose=LEVEL verbose level (from 0 to 9, default 1)
-r, --remote=URL match against a remote Invenio installation (Full URL, no trailing '/')
... |
tangfeixiong/packstack | packstack/plugins/mysql_001.py | Python | apache-2.0 | 5,760 | 0.009028 | """
Installs and configures MySQL
"""
import uuid
import logging
from packstack.installer import validators
from packstack.installer import utils
from packstack.modules.ospluginutils import getManifestTemplate, appendManifestFile
# Controller object will be initialized from main flow
controller = None
# Plugin nam... | hosts.add(config.get('CONFIG_NOVA_VNCPROXY_HOST').strip())
| hosts.add(config.get('CONFIG_NOVA_CONDUCTOR_HOST').strip())
hosts.add(config.get('CONFIG_NOVA_SCHED_HOST').strip())
if config['CONFIG_NEUTRON_INSTALL'] != 'y':
dbhosts = split_hosts(config['CONFIG_NOVA_NETWORK_HOSTS'])
hosts |= dbhosts... |
Debian/openjfx | modules/web/src/main/native/Tools/QueueStatusServer/handlers/updatestatus.py | Python | gpl-2.0 | 3,275 | 0.001527 | # Copyright (C) 2013 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the... | results_file = self.request.get("results_file")
queue_status.results_file = db.Blob(str(results_file))
return queue_status
def post(self):
queue_status = self._queue_status_from_request()
queue_status.put()
RecordBotEvent.record_activity(queue_status.queue_name, queue_... | atus.bot_id)
self.response.out.write(queue_status.key().id())
|
Jumpscale/jumpscale_core8 | lib/JumpScale/data/params/Params.py | Python | apache-2.0 | 5,825 | 0.000687 | from JumpScale import j
"""
Provides the Params object and the ParamsFactory that is used in the Q-Tree
"""
class ParamsFactory:
"""
This factory can create new Params objects
"""
def __init__(self):
self.__jslocation__ = "j.data.params"
def get(self, dictObject={}):
"""
... | nt check it is already in dict and if not add
e.g. args=self.expandParamsAsDict(id=1,name="test")
will return a dict with id & name and these values unless if they were set in the params already
can further use it as follows:
params.result=infomgr.getInfoWithHeaders(**args)
full... | None)
args["start"]=j.data.time.getEpochAgo(args["start"])
args["stop"]=j.data.time.getEpochFuture(args["stop"])
params.result=j.apps.system.infomgr.extensions.infomgr.addInfo(**args)
"""
params = self
params2 = params.getDict()
if "paramsExtra" in params and ... |
gtesei/fast-furious | dataset/images2/simple_classification.py | Python | mit | 1,266 | 0.011848 | import mahotas as mh
from sklearn import cross_validation
from sklearn.linear_model.logistic import LogisticRegression
import numpy as np
from glob import glob
from edginess import edginess_sobel
#basedir = 'simple-dataset'
basedir = 'simple-dataset/'
def features_for(im):
im = mh.imread(im,as_grey=True).astype(... | cv=5)
print('Accuracy (5 fold x-val) with Logistic Regrssion [std features]: {}%'.format(0.1* round(1000*scores.mean())))
scores = cross_validation.cross_val_score(LogisticRegression(), np.hstack([np.atleast_2d(sobels).T,features]), labels, cv=5).mean()
print('Accuracy (5 fold x-val) with | Logistic Regrssion [std features + sobel]: {}%'.format(0.1* round(1000*scores.mean())))
|
youtube/cobalt | third_party/devtools/scripts/build/build_debug_applications.py | Python | bsd-3-clause | 2,246 | 0.000894 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright 20 | 16 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.
"""
Builds applications in debug mode:
- Copies the module directories into their destinations.
- Copies app.html as-is.
"""
from os import path
from os.path import join
i... | :
input_path_flag_index = argv.index('--input_path')
input_path = argv[input_path_flag_index + 1]
output_path_flag_index = argv.index('--output_path')
output_path = argv[output_path_flag_index + 1]
build_stamp_index = argv.index('--build_stamp')
build_stamp_path = argv[bu... |
gasparmoranavarro/TopoDelProp | forms/frmIntrodDatos.py | Python | gpl-2.0 | 8,916 | 0.003141 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:/Qgs18/apps/qgis/python/plugins/TopoDelProp/forms_ui/frmIntrodDatos.ui'
#
# Created: Fri Nov 09 12:38:15 2012
# by: PyQt4 UI code generator 4.8.6
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtC... | idget.setGeometry(QtCore.QRect(750, 70, 221, 341))
self.listWidget.setTo | olTip(QtGui.QApplication.translate("frmIntrodDatos", "Seleccione el valor a introducir en la tabla", None, QtGui.QApplication.UnicodeUTF8))
self.listWidget.setStatusTip(_fromUtf8(""))
self.listWidget.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.listWidget.setAutoScroll(True)... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2021_05_01/operations/_peer_express_route_circuit_connections_operations.py | Python | mit | 9,496 | 0.004844 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | 'str'),
'circuitName': self._serialize.url("circuit_name", circuit_name, 'str'),
'peeringName': self._serialize.url("peering_name", peering_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
'subscriptionId': self._serialize.ur... | g.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')... |
Elizaveta239/PyDev.Debugger | tests_python/resources/_debugger_case_breakpoint_remote_no_import.py | Python | epl-1.0 | 406 | 0.009852 | if __name__ == '__main | __':
import os
import sys
port = int(sys.argv[1])
root_dirname = os.path.dirname(os.path.dirname(__file__))
if root_dirname not in sys.path:
sys.path.append(root_dirname)
print('before pydevd.settrace')
breakpoi | nt(port=port) # Set up through custom sitecustomize.py
print('after pydevd.settrace')
print('TEST SUCEEDED!')
|
open-synergy/opnsynid-hr | hr_employee_job_family_from_contract/__openerp__.py | Python | agpl-3.0 | 676 | 0 | # -*- coding: utf-8 -*-
# Copyright 2019 OpenSynergy Indonesia
# Copyright 2022 PT. Simetri Sinergi Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
# pylint: disable=locally-disabled, manifest-required-author
{
"name": "Employee Job Family From Contract",
"version": "8.0.1.0.0", |
"category": "Human Resource",
"website": "https://simetri | -sinergi.id",
"author": "OpenSynergy Indonesia, PT. Simetri Sinergi Indonesia",
"license": "AGPL-3",
"installable": True,
"depends": [
"hr_employee_data_from_contract",
"hr_job_family_modelling",
],
"data": [
"views/hr_contract_views.xml",
],
}
|
flipchan/LayerProx | versions/offthewire_version/marionette_tg/client.py | Python | apache-2.0 | 3,635 | 0.004402 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import random
sys.path.append('.')
from twisted.internet import reactor
from twisted.python import log
from . import driver
from . import multiplexer
from . import record_layer
from . import updater
from . import dsl
from . import conf
EVENT_LOOP_FREQUENCY_S ... | )
self.reload_ = False
| self.driver_.reset()
reactor.callLater(EVENT_LOOP_FREQUENCY_S, self.execute, reactor)
def process_cell(self, cell_obj):
payload = cell_obj.get_payload()
if payload:
stream_id = cell_obj.get_stream_id()
try:
self.streams_[stream_id].srv_queue.pu... |
Communities-Communications/cc-odoo | addons/website_sale/models/sale_order.py | Python | agpl-3.0 | 10,347 | 0.007055 | # -*- coding: utf-8 -*-
import random
from openerp import SUPERUSER_ID
from openerp.osv import osv, orm, fields
from openerp.addons.web.http import request
class sale_order(osv.Model):
_inherit = "sale.order"
def _cart_qty(self, cr, uid, ids, field_name, arg, context=None):
res = dict()
for ... | s['order_id'] = order_id
if values.get('tax_id') != None:
values['tax_id'] = [(6, 0, values['tax_id'])]
return values
def _cart_update(self, cr, uid, ids, product_id=None, line_id=None, add_qty=0, set_qty=0, context=None, **kwargs):
""" Add or set product quantity, add_qty can b... | in self.browse(cr, uid, ids, context=context):
if line_id != False:
line_ids = so._cart_find_product_line(product_id, line_id, context=context, **kwargs)
if line_ids:
line_id = line_ids[0]
# Create line if no line with product_id can be locat... |
ebattenberg/Lasagne | lasagne/tests/test_objectives.py | Python | mit | 9,755 | 0 | import mock
import numpy as np
import theano
import pytest
class TestObjectives:
@pytest.fixture
def input_layer(self, value):
from lasagne.layers import InputLayer
shape = np.array(value).shape
x = theano.shared(value)
return InputLayer(shape, input_var=x)
@pytest.fixture... | aggregation='sum')
assert result.eval() == 6
# Multinomial NLL sum is (0*0 + 1*0 + 1*1) + (2*0 + 2*1 + 0*0)
# + (3*0 + 0*0 + 3*1) = 6
# Mean is 2
result = self.get_loss(categorical_crossentropy, output, target_2d,
aggregation='mean')
... | put, target_2d,
aggregation='sum')
assert result.eval() == 6
# Masked NLL sum is 2 + 3 = 5
result_with_mask = self.get_masked_loss(categorical_crossentropy,
output, target_1hot,
... |
recognai/spaCy | spacy/lang/ru/lemmatizer.py | Python | mit | 6,860 | 0.000729 | # coding: utf8
from ...symbols import (
ADJ, DET, NOUN, NUM, PRON, PROPN, PUNCT, VERB, POS
)
from ...lemmatizer import Lemmatizer
class RussianLemmatizer(Lemmatizer):
_morph = None
def __init__(self):
super(RussianLemmatizer, self).__init__()
try:
from pymorphy2 import MorphAn... | 'ADJF': 'ADJ',
'ADJS': 'ADJ',
'ADVB': 'ADV',
'Apro': 'DET',
'COMP': 'ADJ', # C | an also be an ADV - unchangeable
'CONJ': 'CCONJ', # Can also be a SCONJ - both unchangeable ones
'GRND': 'VERB',
'INFN': 'VERB',
'INTJ': 'INTJ',
'NOUN': 'NOUN',
'NPRO': 'PRON',
'NUMR': 'NUM',
'NUMB': 'NUM',
'PNC... |
jtakayama/makahiki-draft | makahiki/apps/widgets/smartgrid_design/migrations/0001_initial.py | Python | mit | 15,933 | 0.007218 | # encoding: 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 model 'DesignerTextPromptQuestion'
db.create_table('smartgrid_design_designertextpromptquestion',... | ('image', self.gf('django.db.models.fields.files.ImageField')(max_length=255, null=True, blank=True)),
('video_id', self.gf('django.db.models.fields.CharField')(max_length=200, null=True, blank=True)),
('video_source', | self.gf('django.db.models.fields.CharField')(max_length=20, null=True, blank=True)),
('embedded_widget', self.gf('django.db.models.fields.CharField')(max_length=50, null=True, blank=True)),
('description', self.gf('django.db.models.fields.TextField')()),
('type', self.gf('django.db.m... |
florian-dacosta/stock-logistics-warehouse | stock_reserve/__openerp__.py | Python | agpl-3.0 | 2,185 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2013 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | erved a quantity of products which bring the virtual
stock below the minimum, the orderpoint will be triggered and new
purchase orders will be generated. It also implies that the max may be
exceeded if the reservations are canceled.
Contributors
------------
* G | uewen Baconnier <guewen.baconnier@camptocamp.com>
* Yannick Vaucher <yannick.vaucher@camptocamp.com>
""",
'depends': ['stock',
],
'demo': [],
'data': ['view/stock_reserve.xml',
'view/product.xml',
'data/stock_data.xml',
'security/ir.model.access.csv',
],
'auto_i... |
novafloss/django-compose-settings | tests/fixtures/my_app/settings/post.py | Python | mit | 161 | 0 | import __settings__
from __sett | ings__ import INSTALLED_APPS
assert hasattr(__settings__, 'BASE_DIR'), 'BASE_DIR required' |
INSTALLED_APPS += (
'post',
)
|
Toilal/rebulk | rebulk/test/test_validators.py | Python | mit | 2,170 | 0.00553 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=no-self-use, pointless-statement, missing-docstring, invalid-name,len-as-condition
from functools import partial
from rebulk.pattern import StringPattern
from ..validators import chars_before, chars_after, chars_surround, validators
chars = ' _.'
left ... | dxxx"))
assert len(matches) == 0
matches = list(StringPattern("word", validator=right).matches("xxxword.xxx"))
assert len(matches) == 1
matches = list(StringPattern("word", validator=right).matches("xxxword"))
assert len(mat | ches) == 1
def test_surrounding_chars():
matches = list(StringPattern("word", validator=surrounding).matches("xxxword xxx"))
assert len(matches) == 0
matches = list(StringPattern("word", validator=surrounding).matches("xxx.wordxxx"))
assert len(matches) == 0
matches = list(StringPattern("word", ... |
wengzhilai/family | iSoft/dal/QueryDal.py | Python | bsd-3-clause | 3,612 | 0.000573 | from iSoft.entity.model import db, FaQuery
import math
import json
from iSoft.model.AppReturnDTO import AppReturnDTO
from iSoft.core.Fun import Fun
import re
class QueryDal(FaQuery):
def __init__(self):
pass
def query_findall(self, pageIndex, pageSize, criterion, where):
relist, is_succ = Fun... | %(Value)s " % search)
sql = "SELECT * FROM ({0}) T{1}{2}".format(
| sql,
" WHERE " + " AND ".join(whereArr) if len(whereArr) > 0 else "",
" ORDER BY " + " , ".join(orderArr) if len(orderArr) > 0 else "",
)
jsonStr = re.sub(r'\r|\n| ', "", db_ent.QUERY_CFG_JSON)
jsonStr = re.sub(r'"onComponentInitFunction"((.|\n)+?)},', "", jsonSt... |
PredictionIO/open-academy | KairatAshim/pio_assignment2/problem2/problem2.py | Python | apache-2.0 | 1,046 | 0.013384 | import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
import math
import scipy.special as sps
mean = 0
variance = 1
sigma = math.sqrt(variance)
def drawSampleNormal(sampleSize):
samples = np.random.normal(me | an, sigma, sampleSize)
count, bins, ignored = plt.hist(samples, 80, normed=True)
plt.plot(bins,mlab.normpdf(bins,mean,sigma))
plt.show()
plt.savefig("normal_" + str(sampleSize) + "_samples.png")
plt.clf()
drawSampleNormal(20)
drawSampleNormal(50)
drawSampleNormal(100)
drawSampleNorma | l(500)
alpha = 7.5
beta = 10
def drawSampleGamma(sampleSize):
samples = np.random.gamma(alpha, beta, sampleSize)
count, bins, ignored = plt.hist(samples, 80, normed=True)
pdf = bins**(alpha-1)*(np.exp(-bins/beta) / (sps.gamma(alpha)*beta**alpha))
plt.plot(bins, pdf, linewidth=2, color='r')
plt.s... |
marinkaz/orange3 | Orange/widgets/tests/test_settings_handler.py | Python | bsd-2-clause | 7,342 | 0 | from io import BytesIO
import os
import pickle
from tempfile import mkstemp
import unittest
from unittest.mock import patch, Mock
import warnings
from Orange.widgets.settings import SettingsHandler, Setting, SettingProvider
class SettingHandlerTestCase(unittest.TestCase):
@patch('Orange.widgets.settings.SettingPr... | lize(widget, {'setting': 5})
provider.initialize.assert_called_once_with(widget, {'default': 42,
'setting': 5})
# Pickled data
reset_provider()
handler.initia | lize(widget, pickle.dumps({'setting': 5}))
provider.initialize.assert_called_once_with(widget, {'default': 42,
'setting': 5})
def test_initialize_component(self):
handler = SettingsHandler()
handler.defaults = {'default': 42}
... |
campagnola/acq4 | acq4/pyqtgraph/exporters/SVGExporter.py | Python | mit | 17,330 | 0.011541 | from .Exporter import Exporter
from ..python2_3 import asUnicode
from ..parametertree import Parameter
from ..Qt import QtGui, QtCore, QtSvg, QT_LIB
from .. import debug
from .. import functions as fn
import re
import xml.dom.minidom as xml
import numpy as np
__all__ = ['SVGExporter']
class SVGExporter(Exporter):
... | ype': 'float', 'value': tr.height(), 'limits': (0, Non | e)},
#{'name': 'viewbox clipping', 'type': 'bool', 'value': True},
#{'name': 'normalize coordinates', 'type': 'bool', 'value': True},
{'name': 'scaling stroke', 'type': 'bool', 'value': False, 'tip': "If False, strokes are non-scaling, "
"which means that they appear the... |
n3wb13/OpenNfrGui-5.0-1 | lib/python/Plugins/Extensions/MediaPortal/additions/porn/x2search4porn.py | Python | gpl-2.0 | 7,051 | 0.032203 | # -*- coding: utf-8 -*-
from Plugins.Extensions.MediaPortal.plugin import _
from Plugins.Extensions.MediaPortal.resources.imports import *
from Plugins.Extensions.MediaPortal.resources.keyboardext import VirtualKeyBoardExt
CONFIG = "/usr/lib/enigma2/python/Plugins/Extensions/MediaPortal/additions/additions.xml"
clas... | ediaportal.showgrauzone.value and gz == "1":
pass
else:
mod = eval("config.mediaportal." + x.get("confopt") + ".value")
if mod:
exec("self.genreliste.append((\""+x.get("name").replace("&","&")+"\", None))")
self.genreliste.sort(key=lambda t : t[0].lower())
self.keyLocked = Fa... | self.suchString = self.suchString.rstrip()
conf = xml.etree.cElementTree.parse("/usr/lib/enigma2/python/Plugins/Extensions/MediaPortal/additions/additions.xml")
for x in conf.getroot():
if x.tag == "set" and x.get("name") == 'additions':
root = x
for x in root:
if x.tag == "plugin":
if x.get("typ... |
PlotWatt/webipy | examples/ex1.py | Python | bsd-3-clause | 1,406 | 0 | import webipy
import numpy as np
import matplotlib.pyplot as plt
import pylab
import pandas as pd
pylab.rcParams['figure.figsize'] = (15, 11)
@webipy.exports
def plot(x, n=4):
"""
Demo of scatter plot on a polar axis.
Size increases radially in this example and color increases with angle
"""
N = ... | )
ax.plot(X, C)
ax.plot(X, S)
return pd.DataFrame({'X': X, 'sine': S, 'cos': C})
@webipy.exports
def sine1(x):
"""
simple sine wave with x points
uses bokeh
"""
from bokeh import mpl
X = np.linspace(-np.pi, np.pi, int(x), endpoint=True)
C, S = np.cos(X), np.sin(X)
ax = plt.... | int "non_bool1:", non_bool1, "non_bool2", non_bool2
print "bools"
print "x:", x, "y:", y
|
rokuz/omim | tools/python/generate_local_ads_symbols.py | Python | apache-2.0 | 1,823 | 0.002194 | #!/usr/bin/env python
import os
import sys
PREFIX_DELIMITER = '_'
def enumerate_symbols(symbols_folder_path):
symbols = []
for filename in os.listdir(symbols_folder_path):
parts = os.path.splitext(filename)
if parts[1] == ".svg":
symbols.append(parts[0])
return symbols
def ... | sys.exit(-1)
target_path = ''
if len(sys.argv) >= 3:
target_path = sys.argv[2]
output_name = os.path.join(target_path, 'local_ads_symbols.txt');
if os.path.exists(output_name):
os.remove(output_name)
paths = ['style-clear', 'style-night']
symbols = []
for folder_path ... | if symbols != s:
raise ValueError('Different symbols set in folders' + str(paths))
else:
symbols = s
check_symbols(symbols)
with open(output_name, "w") as text_file:
for symbol in symbols:
text_file.write(symbol + '\n')
|
palindromed/data-structures | src/test_graph.py | Python | mit | 10,017 | 0.000399 | import pytest
# TODO: use same globals for reverse operations such as add, remove
GRAPHS = [
({},
[],
[]),
({'nodeA': {}},
['nodeA'],
[]),
({'nodeA': {'nodeB': 'weight'},
'nodeB': {}},
['nodeA', 'nodeB'],
[('nodeA', 'nodeB')]),
({'nodeA': {'nodeB': 'weight'},
'... | 'nodeY': {}}),
({'nodeA': {'nodeB': 'weight'},
'nodeB': {'nodeA': 'weight'}},
'nodeA',
| 'nodeB',
{'nodeA': {'nodeB': 'weight'},
'nodeB': {'nodeA': 'weight'}}),
({'nodeA': {'nodeB': 'weight', 'nodeC': 'weight'},
'nodeB': {'nodeA': 'weight'},
'nodeC': {'nodeA': 'weight', 'nodeC': 'weight'}},
'nodeB',
'nodeC',
{'nodeA': {'nodeB': 'weight', 'nodeC': 'weight'},
... |
momingsong/ns-3 | bash-py-gp/baseline_picdata.py | Python | gpl-2.0 | 12,175 | 0.012238 | import sys
import os
#For baseline and redundacy-detecion to prepare message size picture
def MessageSize(typePrefix, directory):
wf = open("%(typePrefix)s-msgsize.data"%vars(), "w")
wf.write("#Suggest Filename: %(typePrefix)s-message.data\n#Data for drawing message overall size in different Amount/Redunda... | if line[0:2] == logcontent or line[0:3] == logcontent | :
info = line.split(' ')
for x in info:
if x[0:2] == "Ho":
nonce = x.split(':')[1]
if(msgcount[mms].has_key(nonce)):
msgcount[mms][nonce]["r"] += 1
... |
rodrigofaccioli/2pg_cartesian | scripts/analysis/compute_rmsd_pdb_files.py | Python | apache-2.0 | 1,725 | 0.029565 | """
Routines to compute RMSD of all PROT_IND_ files
These | routines were developed by:
Rodrigo Antonio Faccioli - rodrigo.faccioli@usp.br / rodrigo.faccioli@gmail.com
Leandro Oliveira Bortot - leandro.bortot@usp.br / leandro.obt@gmail.com
"""
import os
import sys
from collections import OrderedDict
native = "1VII.pdb"
path_gromacs ="/home/faccioli/Programs/gmx-4.... | emporary_rmsd.xvg 2>/dev/null"
""" This function obtains all pdb files
in mypath
"""
def get_PROT_IND_files_pdb(mypath):
only_pdb_file = []
for root, dirs, files in os.walk(mypath):
for file in files:
#if file.endswith(".pdb"):
if file.find("PROT_IND_") >=0:
f_path = os.path.join(root,file)
onl... |
RRCKI/pilot | castorSvcClassSiteMover.py | Python | apache-2.0 | 16,969 | 0.005187 | import os
import commands
import re
import SiteMover
from futil import *
from PilotErrors import PilotErrors
from pUtil import tolog, readpar, verifySetupCommand
from time import time
from FileStateClient import updateFileState
from timed_command import timed_command
class castorSvcClassSiteMover(SiteMover.SiteMover... | updateFileState(lfn, workDir, jobId, mode="transfer_mode", state="file_stager", type="input")
else:
updateFileState(lfn, workDir, jobId, mode="transfer_mode", state="remote_io", type="input")
return error.ERR_DIRECTIOFILE, pilotErrorDiag
... | tolog("Normal file transfer")
# Now need to find the service class associated with the file.
# If we |
fatihzkaratana/intranet | backend/intranet/tests/api.py | Python | apache-2.0 | 7,125 | 0.012351 | # -*- coding: utf-8 -*-
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
import json
from intranet.models import User, Project, Part, STATE_CREATED
class Test(TestCase):
@classmethod
def setUpClass(self):
self.c = Client()
Use... | rtEqual(response.status_code,200)
json_response = json.loads(response.content)
self.assertEqual(json_response['valid'], False)
response = self.c.get(reverse('api:imputation-list'), {'token_auth': self.token_auth, 'day':3, 'part':self.part.id, 'project' | : self.project.id})
self.assertEqual(response.status_code,200)
json_response = json.loads(response.content)
self.assertEqual(len(json_response['imputations']), 1)
response = self.c.get(reverse('api:imputation-list'), {'token_auth': self.token_auth, 'day':1, 'part':self.part.id, 'project... |
japsu/voitto | tappio/models.py | Python | gpl-3.0 | 2,774 | 0.001081 | # Voitto - a simple yet efficient double ledger bookkeeping system
# Copyright (C) 2010 Santtu Pajukanta <santtu@pajukanta.fi>
#
# 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 ... | unts is not None else []
class Event(object):
def __init__(self, number, date, description="", entries=None):
self.number = number
self.date = date
| self.description = description
self.entries = entries if entries is not None else []
class Entry(object):
def __init__(self, account_number, cents):
self.account_number = account_number
self.cents = cents
|
chop-dbhi/varify-data-warehouse | vdw/assessments/migrations/0007_auto__add_unique_assessment_user_sample_result.py | Python | bsd-2-clause | 20,310 | 0.008567 | # -*- 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 unique constraint on 'Assessment', fields ['user', 'sample_result']
db.create_unique('assessment', ... | , {'related_name': "'mother'", 'to': "orm['assessments.ParentalResult']"}),
'notes': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'pathogenicity': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['assessments.Pathogenicity']"}),
'sample_... | }),
'sanger_requested': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'sanger_result': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['assessments.SangerResult']", 'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.Forei... |
zcarwile/quixotic_webapp | quixotic_webapp/settings.py | Python | gpl-3.0 | 3,517 | 0.001137 | """
Django settings for quixotic_webapp project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
i... | E = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddlewa... | _URLCONF = 'quixotic_webapp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template... |
dhuang/incubator-airflow | airflow/timetables/interval.py | Python | apache-2.0 | 3,585 | 0.000558 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | gRunInfo.interval(start=start, end=end)
class CronDataIntervalTimetable(_DataIntervalTimetable):
"""Timetable that schedules data intervals with a cron expression.
This corresponds to ``schedule_interval=<cron>``, where ``<cron>`` is either
| a five/six-segment representation, or one of ``cron_presets``.
Don't pass ``@once`` in here; use ``OnceTimetable`` instead.
"""
def __init__(self, cron: str, timezone: datetime.tzinfo) -> None:
self._schedule = CronSchedule(cron, timezone)
class DeltaDataIntervalTimetable(_DataIntervalTimeta... |
jpelias/pyTelegramBotAPI | tests/test_telebot.py | Python | gpl-2.0 | 7,077 | 0.002685 | # -*- coding: utf-8 -*-
import sys
sys.path.append('../')
import time
import pytest
import os
import telebot
from telebot import types
from telebot import util
should_skip = 'TOKEN' and 'CHAT_ID' not in os.environ
if not should_skip:
TOKEN = os.environ['TOKEN']
CHAT_ID = os.environ['CHAT_ID']
@pytest.mar... | TeleBot('')
msg = self.create_text_message(r'lambda_text')
@bot.message_hand | ler(func=lambda message: r'lambda' in message.text)
def command_url(message):
msg.text = 'got'
bot.process_new_messages([msg])
time.sleep(1)
assert msg.text == 'got'
def test_message_handler_lambda_fail(self):
bot = telebot.TeleBot('')
msg = self.create_... |
uskudnik/ggrc-core | src/tests/ggrc_workflows/notifications/test_enable_disable_notifications.py | Python | apache-2.0 | 7,378 | 0.010165 | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: miha@reciprocitylabs.com
# Maintained By: miha@reciprocitylabs.com
import random
from tests.ggrc import TestCase
from freezegun import freeze_time
... | ser.email, notif_data)
with freeze_time("20 | 15-01-29 13:39:20"):
_, notif_data = notification.get_todays_notifications()
self.assertNotIn(user.email, notif_data)
@patch("ggrc.notification.email.send_email")
def test_enabled_notifications(self, mock_mail):
with freeze_time("2015-02-01 13:39:20"):
_, wf = self.wf_generator.generate_work... |
bdaroz/the-blue-alliance | helpers/location_helper.py | Python | mit | 24,876 | 0.003136 | import json
import logging
import math
import re
import tba_config
import urllib
from difflib import SequenceMatcher
from google.appengine.api import memcache, urlfetch
from google.appengine.ext import ndb
from models.location import Location
from models.sitevar import Sitevar
from models.team import Team
class Loc... | ot location_info:
# logging.warning("Falling back to location only for team {}".format(team.key.id()))
geocode_result = cls.google_maps_geocode_async(team.location).get_result()
if geocode_result:
location_info = cls.construct_location_info_async(geocode_result[0], au... | k to city/country only for team {}".format(team.key.id()))
city_country = u'{} {}'.format(
team.city if team.city else '',
team.country if team.country else '')
geocode_result = cls.google_maps_geocode_async(city_country).get_result()
if geocode_result... |
benjspriggs/tumb-borg | tumb_borg/process.py | Python | apache-2.0 | 1,044 | 0.01341 | #!/usr/bin/env python3
delineator = "//"
hashtag = "#"
# generate poems from a file
# out: list of poem lines
def generate_poems(filename):
g = []
# get to the first poem in the file
with open(filename, 'r') as f:
for line in f:
line = line.rstrip()
if line | .startswith( delineator ) and g:
yield g
g = []
if line:
g.append(line)
yield g
# | convert a list of strings
# into a poem dictionary
def to_dictionary(poem_lines):
d = {}
d['content'] = []
d['tags'] = []
tags = []
for line in poem_lines:
if line.startswith( delineator ):
d['title'] = line.lstrip( delineator ).strip()
elif line.startswith( hashtag ):
... |
wolfgangz2013/rt-thread | bsp/at91sam9g45/rtconfig.py | Python | apache-2.0 | 3,724 | 0.008861 | import os
ARCH = 'arm'
CPU = 'arm926'
# toolchains options
CROSS_TOOL = 'gcc'
#------- toolchains path -------------------------------------------------------
if os.getenv('RTT_CC'):
CROSS_TOOL = os.getenv('RTT_CC' | )
if CROSS_TOOL == 'gcc':
PLATFORM = 'g | cc'
EXEC_PATH = r'D:\arm-2013.11\bin'
elif CROSS_TOOL == 'keil':
PLATFORM = 'armcc'
EXEC_PATH = 'C:/Keil_v5'
elif CROSS_TOOL == 'iar':
PLATFORM = 'iar'
EXEC_PATH = 'C:/Program Files (x86)/IAR Systems/Embedded Workbench 7.2'
if os.getenv('RTT_EXEC_PATH'):
EXEC_PATH = os.getenv('RTT_EXEC_PATH')
#BUILD = 'debu... |
kaankizilagac/sozluk | sozluk/topics/signals.py | Python | mit | 412 | 0.002427 | # | -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
def check_junior(sender, instance, created, **kwargs):
# from .models import Entry # avoid circled import
if created and instance.user.junior:
total_entry = sender.objects.filt | er(user=instance.user).count()
if total_entry >= 2:
instance.user.junior = False
instance.user.save()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.