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 |
|---|---|---|---|---|---|---|---|---|
mapycz/python-mapnik | test/python_tests/query_tolerance_test.py | Python | lgpl-2.1 | 1,397 | 0.000716 | import os
from nose.tools import eq_
import mapnik
from .utilities import execution_path, run_all
def setup():
# All of the paths used are relative, if we run the tests
# from another directory we need to chdir()
os.chdir(execution_path('.'))
if 'shape' in mapnik.DatasourceCache.plugin_names():
de... | _width, srs)
_map.layers.append(lyr)
# zoom determines tolerance
_map.zoom_all()
_map_env = _map.envelope()
tol = (_map_env.maxx - _map_env.minx) / _width * 3
# 0.046875 for arrows.shp and zoom_all
eq_(tol, 0.046875)
# check point really exists
x, ... | + tol * 0.9
features = _map.query_point(0, x, y)
eq_(len(list(features)), 1)
# check outside tolerance limit
x = 2.0 + tol * 1.1
features = _map.query_point(0, x, y)
eq_(len(list(features)), 0)
if __name__ == "__main__":
setup()
exit(run_all(eval(x) for x in dir(... |
IljaGrebel/OpenWrt-SDK-imx6_HummingBoard | staging_dir/host/lib/scons-2.3.5/SCons/Tool/aixc++.py | Python | gpl-2.0 | 2,413 | 0.002072 | """SCons.Tool.aixc++
Tool-specific initialization for IBM xlC / Visual Age C++ compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# Permission is h... | oftware, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be inclu | ded
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLD... |
guoqiao/django-nzpower | nzpower/migrations/0001_initial.py | Python | mit | 981 | 0.001019 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(m | igrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Company',
fields=[
('id', mode | ls.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(unique=True, max_length=100)),
('slug', models.SlugField(unique=True, blank=True)),
('site', models.URLField(null=True, blank=True)),
('rate',... |
datastax/python-driver | tests/integration/cloud/test_cloud.py | Python | apache-2.0 | 10,950 | 0.003288 | # Copyright DataStax, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... |
def test_support_overriding_auth_provider(self):
try:
self.connect(self.creds, auth_provider=PlainTextAuthProvider('invalid', 'invalid'))
except:
pass # this will fail soon when sni_single_endpoint is updated
self.assertIsInstance(self.cluster.auth_provider, PlainTe... | h_provider.username, 'invalid')
self.assertEqual(self.cluster.auth_provider.password, 'invalid')
def test_error_overriding_ssl_context(self):
with self.assertRaises(ValueError) as cm:
self.connect(self.creds, ssl_context=SSLContext(PROTOCOL_TLS))
self.assertIn('cannot be specif... |
ktonon/GameSoup | gamesoup/matches/models.py | Python | mit | 520 | 0.003846 | from django.core.urlresolvers import reverse
from django.db import models
from gamesoup.games.model | s import *
class Match(models.Model):
game = models.ForeignKey(Game)
state = models.TextField(blank=True)
def __unicode__(self):
return self.game.name
class Meta:
verbose_name_plural = 'Matches'
def play_link(self):
return '<a href="%s">play< | /a>' % reverse('matches:play_match', args=[self.id])
play_link.short_description = 'Play'
play_link.allow_tags = True
|
domenkozar/pip | tests/test_vcs_git.py | Python | mit | 3,904 | 0.001281 | from mock import patch
from pip.vcs.git import Git
from tests.test_pip import (reset_env, run_pip,
_create_test_package,)
from tests.git_submodule_helpers import (
_change_test_package_submodule,
_pull_in_submodule_changes_to_module,
_create_test_package_with_submodule,
)
d... | g_path, expect_stderr=True)
git = Git()
result = git.get_branch_revs(version_pkg_path)
assert result == {'master': commit, 'branch0.1': commit}
@patch('pip.vcs.git.Git.get_tag_revs')
@patch('pip.vcs.git.Git.get_branch_revs')
def test_check_rev_options_should_handle_branch_name(branches_revs_mock,
... | tags_revs_mock):
branches_revs_mock.return_value = {'master': '123456'}
tags_revs_mock.return_value = {'0.1': '123456'}
git = Git()
result = git.check_rev_options('master', '.', [])
assert result == ['123456']
@patch('pip.vcs.git.Git.get_tag_revs')
@patch('pi... |
blond-admin/BLonD | __EXAMPLES/main_files/EX_07_Ions.py | Python | gpl-3.0 | 6,437 | 0.010253 | # coding: utf8
# Copyright 2014-2017 CERN. This software is distributed under the
# terms of the GNU General Public Licence version 3 (GPL Version 3),
# copied verbatim in the file LICENCE.md.
# In applying this licence, CERN does not waive the privileges and immunities
# granted to it by virtue of its status as an I... | phi_s_test = rf_param | s.phi_s #: *Synchronous phase
omega_RF_d_test = rf_params.omega_rf_d #: *Design RF frequency of the RF systems in the station [GHz]*
omega_RF_test = rf_params.omega_rf #: *Initial, actual RF frequency of the RF systems in the station [GHz]*
phi_RF_test = rf_params.omega_rf #: *Initial, actual RF phase of each harmonic... |
OSSHealth/ghdata | workers/insight_worker/setup.py | Python | mit | 1,388 | 0.003602 | #SPDX-License-Identifier: MIT
import io
import os
import re
from setuptools import find_packages
fro | m setuptools import setup
def read(filename):
filename = os.path.join(os.path.dirname(__file__), filename)
text_type = type(u"")
with io.open(filename, mode="r", encoding='utf-8') as fd:
return re.sub(text_type(r':[a-z]+:`~?(.*?)`'), text_type(r'``\1``'), fd.read())
setup(
name="insight_worker... | ins.com",
description="Augur Worker that discovers and stores data anomalies",
packages=find_packages(exclude=('tests',)),
install_requires=[
'Flask==1.1.4',
'Flask-Cors==3.0.10',
'Flask-Login==0.5.0',
'Flask-WTF==0.14.3',
'requests==2.22.0',
'psycopg2-binary=... |
VirusTotal/misp-modules | misp_modules/modules/expansion/ipasn.py | Python | agpl-3.0 | 2,208 | 0.002266 | # -*- coding: utf-8 -*-
import json
from . import check_input_attribute, standard_error_message
from pyipasnhistory import IPASNHistory
from pymisp import MISPAttribute, MISPEvent, MISPObject
misperrors = {'error': 'Error'}
mispattributes = {'input': ['ip-src', 'ip-dst'], 'format': 'misp_standard'}
moduleinfo = {'ver... | : ('ip-src', 'subnet-announced')}
print(values)
for last_seen, response in values['response'].items():
asn = MISPObject('asn')
a | sn.add_attribute('last-seen', **{'type': 'datetime', 'value': last_seen})
for feature, attribute_fields in mapping.items():
attribute_type, object_relation = attribute_fields
asn.add_attribute(object_relation, **{'type': attribute_type, 'value': response[feature]})
asn.add_refere... |
rajegannathan/grasp-lift-eeg-cat-dog-solution-updated | python-packages/mne-python-0.10/examples/stats/plot_cluster_stats_evoked.py | Python | bsd-3-clause | 2,991 | 0 | """
=======================================================
Permutation F-test on sensor data with 1D cluster level
=======================================================
One tests if the evoked response is significantly different
between conditions. Multiple comparison problem is addressed
with cluster level permuta... | exclude='bads')
event_id = 1
reject = dict(grad=4000e-13, eog=150e-6)
epochs1 = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), reject=reject)
condition1 = epochs1.get_data() # as 3D matrix
event_id = 2
epochs2 = mne.Epochs(raw, events, event_id, tmin, tma... | |
zstackio/zstack-woodpecker | integrationtest/vm/multihosts/vm_snapshots/paths/xsky_path9.py | Python | apache-2.0 | 2,040 | 0.015196 | import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():
return dict(initial_formation="template5", checking_point=8, path_list=[
[TestAction.create_vm, 'vm1', ],
[TestAction.create_volume, 'volume1', 'flag=scsi'],
[TestAction.attach_volume, 'vm1', 'volume1'],
... | ot5'],
[TestAction.create_vm_backup, 'vm1', 'vm1-backup1'],
[TestAction.create_vm_snapshot, 'vm1', 'vm1-snapshot9'],
[TestAction.create_vm_backup, 'vm1', 'vm1-backup5'],
[TestAction.delete_volume_snapshot, 'vm1-snapshot5'],
[TestAction.migrate_vm, 'vm1'],
[TestAction.delete_vm_s | napshot, 'vm1-snapshot1'],
])
'''
The final status:
Running:['vm1']
Stopped:[]
Enadbled:['volume1-snapshot5', 'volume2-snapshot5', 'volume3-snapshot5', 'vm1-snapshot9', 'volume1-snapshot9', 'volume2-snapshot9', 'volume3-snapshot9', 'vm1-backup1', 'volume1-backup1', 'volume2-backup1', 'volume3-backup1', 'vm1-backup5'... |
soylentdeen/CIAO-commissioning-tools | sandbox/dumpModalBasis.py | Python | mit | 275 | 0 | import scipy
import numpy
import matplotlib.pyplot as pyplot
import pyfits
import VLTTools
ciao = | VLTTools.VLTConnection(simulate=False)
ciao.get_InteractionMatrices | ()
ciao.dumpCommandMatrix(nFiltModes=10)
print "This is where we will Compute the Modal Basis from the IMs"
|
ujdhesa/unisubs | utils/tests/multiqueryset.py | Python | agpl-3.0 | 4,283 | 0.000467 | # -*- coding: utf-8 -*-
# Amara, universalsubtitles.org
#
# Copyright (C) 2013 Participatory Culture Foundation
#
# 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
#... | lf):
qs = list(Video.objects.all())
qs = qs + qs + qs
mqs = MultiQuerySet(Video.objects.all(),
Video.objects.all(),
Vid | eo.objects.all())
self.assertEqual(qs[0:3],
list(mqs[0:3]),
"MQS[:3] failed.")
self.assertEqual(qs[0:6],
list(mqs[0:6]),
"MQS[:6] (entire range) failed.")
self.assertEqual(qs[0:7],
... |
google/ml_collections | ml_collections/config_flags/examples/define_config_dataclass_basic.py | Python | apache-2.0 | 1,322 | 0.004539 | # Copyright 2022 The ML Collections 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... | Mapping[str, Any]
tuple: Sequence[int]
config = MyConfig(
field1=1,
field2='tom',
nested={'field': 2.23},
tuple=(1, 2, 3),
)
_CONFIG = config_flags.DEFINE_config_dataclass('my_ | config', config)
def main(_):
print(_CONFIG.value)
if __name__ == '__main__':
app.run(main)
|
Micronaet/micronaet-mx8 | mx_pick_in/__openerp__.py | Python | agpl-3.0 | 1,557 | 0.001285 | ###############################################################################
#
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
# This program is free software: you can redistribute | it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any | later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of ... |
jobdash/semantic | semantic/units.py | Python | mit | 4,744 | 0.000211 | import re
import quantities as pq
from numbers import NumberService
class ConversionService(object):
__exponents__ = {
'square': 2,
'squared': 2,
'cubed': 3
}
def _preprocess(self, input):
def handleExponents(input):
m = re.search(r'\bsquare (\w+)', input)
... | :
"""Carries out a conversio | n (represented as a string) and returns the
result as a human-readable string.
Args:
input (str): Text representing a unit conversion, which should
include a magnitude, a description of the initial units,
and a description of the target units to which the qua... |
rsalmaso/django-babeljs | babeljs/execjs/runtime.py | Python | mit | 8,806 | 0.000908 | # -*- coding: utf-8 -*-
# Copyright (C) 2007-2018, Raffaele Salmaso <[email protected]>
# Copyright (c) 2012 Omoto Kenji
# Copyright (c) 2011 Sam Stephenson
# Copyright (c) 2011 Josh Peek
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation... | epoints(str):
r"""
>>> encode_unicode_codepoints("a") == 'a'
| True
>>> ascii = ''.join(chr(i) for i in range(0x80))
>>> encode_unicode_codepoints(ascii) == ascii
True
>>> encode_unicode_codepoints('\u4e16\u754c') == '\\u4e16\\u754c'
True
"""
codepoint_format = '\\u{0:04x}'.format
def codepoint(m):
return codepoint_format(ord(m.group(0)))
... |
philanthropy-u/edx-platform | common/test/acceptance/tests/lms/test_account_settings.py | Python | agpl-3.0 | 21,442 | 0.002798 | # -*- coding: utf-8 -*-
"""
End-to-end tests for the Account Settings page.
"""
from datetime import datetime
from unittest import skip
import pytest
from bok_choy.page_object import XSS_INJECTION
from pytz import timezone, utc
from common.test.acceptance.pages.common.auto_auth import AutoAuthPage, FULL_NAME
from com... | t settings page.
"""
shard = 8
def test_link_on_dashboard_works(self):
"""
Scenario: Verify that the "Account" link works from the dashboard.
Given that I am a registered user
And I visit my dashboard
And I click on "Account" in the top drop down
Then I sho... | ings page
"""
self.log_in_as_unique_user()
dashboard_page = DashboardPage(self.browser)
dashboard_page.visit()
dashboard_page.click_username_dropdown()
self.assertIn('Account', dashboard_page.username_dropdown_link_text)
dashboard_page.click_account_settings_link(... |
itielshwartz/BackendApi | lib/pyasn1_modules/rfc1157.py | Python | apache-2.0 | 3,309 | 0.001511 | #
# SNMPv1 message syntax
#
# ASN.1 source from:
# http://www.ietf.org/rfc/rfc1157.txt
#
# Sample captures from:
# http://wiki.wireshark.org/SampleCaptures/
#
from pyasn1.type import univ, namedtype, namedval, tag
from pyasn1_modules import rfc1155
class Version(univ.Integer):
namedValues = namedval.NamedValues(
... | rmatConstructed, 0)
)
class GetNextRequestPDU(_RequestBase):
tagSet = _RequestBase.tagSet.tagImplicitly(
tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1)
)
class GetResponsePDU(_RequestBase):
tagSet = _RequestBase.tagSet.tagImplicitly(
tag.Tag(tag.tagClassContext, tag.tagFor... | mplicitly(
tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 3)
)
class TrapPDU(univ.Sequence):
componentType = namedtype.NamedTypes(
namedtype.NamedType('enterprise', univ.ObjectIdentifier()),
namedtype.NamedType('agent-addr', rfc1155.NetworkAddress()),
namedtype.NamedTyp... |
kwlzn/pants | tests/python/pants_test/engine/test_storage.py | Python | apache-2.0 | 4,071 | 0.012282 | # coding=utf-8
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import unittest
from... | .
written = kvs.put(self.TEST_KEY, self.TEST_VALUE)
self.assertTrue(written)
self.assertEquals(self.TEST_VALUE, kvs.get(self.TEST_KEY).getvalue())
# Write the same key again will not overwrite.
se | lf.assertFalse(kvs.put(self.TEST_KEY, self.TEST_VALUE))
def test_storage(self):
with closing(self.storage) as storage:
key = storage.put(self.TEST_PATH)
self.assertEquals(self.TEST_PATH, storage.get(key))
with self.assertRaises(InvalidKeyError):
self.assertFalse(storage.get(self.TEST_K... |
DoubleCiti/mongodb-migrations | mongodb_migrations/base.py | Python | gpl-3.0 | 967 | 0.004137 | import pymongo
class BaseMigration(object):
def __init__(se | lf,
host='127.0.0.1',
port='27017',
database=No | ne,
user=None,
password=None,
url=None):
if url and database and user is not None: #provide auth_database in url (mongodb://mongohostname:27017/auth_database)
client = pymongo.MongoClient(url, username=user, password=password)
self.db = ... |
codebox/algorithms | test_graph_topological_ordering.py | Python | mit | 943 | 0.020148 | import unittest
from graph_search import Graph
from graph_topological_ordering import find_topological_order
class TestGraphTopologicalOrdering(unittest.TestCase):
def check_labels(self, graph, smaller, larger):
self.assertTrue(graph.get_node(smaller).label < graph.get_node(larger).label)
| def test_1(self):
graph = Graph([[0,1],[0,2],[1,3],[2,3]], True)
find_top | ological_order(graph)
self.check_labels(graph, 0, 1)
self.check_labels(graph, 0, 2)
self.check_labels(graph, 1, 3)
self.check_labels(graph, 2, 3)
def test_2(self):
graph = Graph([[0,1],[1,2],[1,3],[2,4],[3,5]], True)
find_topological_order(graph)
self.check... |
oscaro/django-oscar-adyen | tests/test_requests.py | Python | bsd-3-clause | 3,128 | 0.001598 | from django.conf import settings
from django.test import TestCase, override_settings
from freezegun import freeze_time
from adyen.gateway import MissingFieldException
from adyen.scaffold import Scaffold
TEST_RETURN_URL | = 'https://www.example.com/checkout/return/adyen/'
EXPECTED_FIELDS_LIST = [
{'type': 'hidden', 'name': 'currencyCode', 'value': 'EUR'},
{'type': 'hidden', 'name': 'merchantAccount', 'value': settings.ADYEN_IDENTIFIER},
{'type': 'hidden', 'name': 'merchantReference', 'value': '00000000123'},
{'type': '... | {'type': 'hidden', 'name': 'merchantSig', 'value': 'kKvzRvx7wiPLrl8t8+owcmMuJZM='},
{'type': 'hidden', 'name': 'paymentAmount', 'value': '123'},
{'type': 'hidden', 'name': 'resURL', 'value': TEST_RETURN_URL},
{'type': 'hidden', 'name': 'sessionValidity', 'value': '2014-07-31T17:20:00Z'},
{'type': 'hidd... |
vint21h/django-po2xls | tests/management/commands/test_po-to-xls.py | Python | gpl-3.0 | 1,479 | 0.002705 | # -*- coding: utf-8 -*-
# django-po2xls
# tests/management/commands/test_po-to-xls.py
import os
import pathlib
from typing import List
from importlib import import_module
from django.test import TestCase
# po-to-xls management command imported on the fly
# because we can't import something from the module that co... | nClass()
def test_convert(self) -> None:
"""convert method must write converted data to .xls files for chosen locale.""" # noqa: D403,E501
Command().convert(locale="uk")
self.assertTrue(
expr=pathlib.Path("po2xls/locale/uk/LC_MESSAGES/django.xls").exists()
)
def t... | d().handle()
self.assertTrue(
expr=pathlib.Path("po2xls/locale/en/LC_MESSAGES/django.xls").exists()
)
self.assertTrue(
expr=pathlib.Path("po2xls/locale/uk/LC_MESSAGES/django.xls").exists()
)
|
maldun/EasyShells | MidSurface.py | Python | lgpl-2.1 | 2,382 | 0.011335 | # EasyShells Module - API for easier Shell Model Construction in Salome
# MidSurface.py: Mid surface extraction for EasyShells module
#
# Copyright (C) 2013 Stefan Reiterer - [email protected]
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser ... | points_upper[i][j])*0.5 \
for j in range(length_u)] \
| for i in range(length_v)]
def parallel_midsurface(lower_face, upper_face, lower_deg = 2, upper_deg = 5):
"""
Determines the midsurface of 2 parallel
surfaces. Hereby parallel means that they
share the same normal direction. It is assumed
that both normals point outwards.
"""
points_u = ar... |
Theragon/kupfer | kupfer/plugin/vim/__init__.py | Python | gpl-3.0 | 423 | 0.009456 | __kupfer_name__ = _("Vim")
__kupfer_sources__ = ("RecentsSource", "ActiveVim", )
__kupfer_actions__ = ("InsertInVi | m", )
__description__ = _("Recently used documen | ts in Vim")
__version__ = "2011-04"
__author__ = "Plugin: Ulrik Sverdrup, VimCom: Ali Afshar"
def initialize_plugin(name):
global RecentsSource
global ActiveVim
global InsertInVim
from kupfer.plugin.vim.plugin import RecentsSource, ActiveVim, InsertInVim
|
crpurcell/friendlyVRI | arrays/array_data/ATCA/mk_ATCA_array_configs.py | Python | mit | 3,761 | 0.003191 | #!/usr/bin/env python
telescope = "ATCA"
latitude_deg = -30.312906
diameter_m = 22.0
import os
import sys
from util_misc import ascii_dat_read
#-----------------------------------------------------------------------------#
def main():
# Read the station lookup table
col, dummy = ascii_dat_read("ATCA_statio... | = %f\n" % diameter_ | m)
FH.write("\n")
FH.write("# Antenna coordinates (offset E, offset N)\n")
FH.write("%f, %f\n" % (statDict[A1][0], statDict[A1][1]))
FH.write("%f, %f\n" % (statDict[A2][0], statDict[A2][1]))
FH.write("%f, %f\n" % (statDict[A3][0], statDict[A3][1]))
FH.write("%f, %f\n" % (... |
vaniakosmos/memes-reposter | apps/rss/admin.py | Python | mit | 1,262 | 0.001585 | from datetime import timedelta
from django.contrib import admin
from django.db.models import Case, Value, When
from django.utils import timezone
from .models import Channel, Post, RssFeed
@admin.register(Channel)
class ChannelAdmin(admin.ModelAdmin):
list_display = ('__str__', 'title', 'username', 'publish_pict... | eryset.update(active=True)
def deactivate(self, request, queryset):
queryset.update(active=False)
def toggle_active(self, request, queryset):
queryset.update(active=Case(When(active=True, then=Value(False)), default=Value(True)))
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
l... | _days(self, post: Post):
five_days_before = timezone.now() - timedelta(days=5)
return post.created < five_days_before
older_then_five_days.boolean = True
|
JohnCEarls/AUREA | scripts/testScripts/testTFIDF.py | Python | agpl-3.0 | 1,566 | 0.009579 | from tfidf import *
import psycopg2
import psycopg2.extensions
import math
def cos_sim(A,B):
def dot_product(a,b):
sum = 0.0
for key in a.keys():
if key in b:
sum += a[key]*b[key]
return sum
return dot_product(A,B)/(math.sqrt(dot_product(A,A)) * math.sqrt(dot_... | )
conn = psycopg2.connect("host=localhost dbname=SOFTFile user=AUREA password=AUREA")
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
c = conn.cursor()
qry = "SELECT dataset_id, dataset_title, dataset_description \
FROM dataset"
#WHERE dataset_id < 20"
c.execute(qry)
documentList = []... | .close()
vectors = []
print "gotDocs"
for x in range(len(documentList)):
words = {}
for word in documentList[documentNumber].split(None):
words[word] = tfidf(word,documentList[documentNumber],documentList)
#for item in sorted(words.items(), key=itemgetter(1), reverse=True):
# print "%f <= %s... |
Tomcuzz/OctaHomeAutomation | Api/ciscophone.py | Python | mit | 3,020 | 0.036755 | from django.shortcuts import render
from SharedFunctions.models import *
from Lights.models import *
def HandlePhoneRequest(request):
area = request.GET.get('area', 'None')
if area == 'None':
return PhoneHomePage(request)
elif area == 'lights':
if request. | GET.get('room', 'None') != 'None':
if request.GET.get('light', 'None') != 'None':
if request.GET.get('command', 'None') != 'None':
return PhoneLightSetRGBPage(request)
else:
return PhoneLightPage(request)
else:
return PhoneLightsPage(request)
else:
return PhoneLightsRoomPage(request)
e... | cophone&area=alarm'},
{'title':'Temperature', 'address':'?page=ciscophone&area=temp'}]
return render(request, 'OctaHomeApi/PhoneMenu.html', {'Items':items, 'Prompt':'Please Select A Service'}, content_type="text/xml")
def PhoneLightsRoomPage(request):
items = [{'title':'All Rooms', 'address':'?page=ciscophone&are... |
dtschan/weblate | weblate/accounts/tests/test_models.py | Python | gpl-3.0 | 1,853 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2016 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eith... | self.assertEqual(user.groups.count(), 1)
def test_none(self):
AutoGr | oup.objects.all().delete()
user = self.create_user()
self.assertEqual(user.groups.count(), 0)
def test_matching(self):
AutoGroup.objects.create(
match='^.*@weblate.org',
group=Group.objects.get(name='Guests')
)
user = self.create_user()
self.a... |
burmanm/gather_agent | gather_agent/gather_agent.py | Python | apache-2.0 | 5,283 | 0.005111 | import Queue
import handlers
import inspect
import threading
import pkgutil
import os
import sys
import imp
from gatherer import Gatherer
import signal
import platform
import ConfigParser
class GatherAgent(object):
"""
A simple layer between inputs (gatherers) and output (handler) using a simple
implementa... | self.load_partial_config('Handlers')
handler_specific_config = self.load_partial_config('Handlers', handler_cls)
handler_specific_config.update(handler_generic_config | )
for o, _ in self.load_classes_list('handlers'):
if o.__name__ == handler_cls:
obj = o(handler_specific_config)
return obj
def start_gatherers(self, instances, handler):
"""
Creates new threads for each gatherer running the gatherer's run() meth... |
akhmadMizkat/odoo | addons/project_issue_sheet/__openerp__.py | Python | gpl-3.0 | 850 | 0.002353 | # -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Timesheet on Issues',
'version': '1.0',
'category': 'Project Management',
| 'description': """
This module adds the Timesheet support for the Issues/Bugs Management in Project.
=================================================================================
Worklogs can be maintained to signify number of hours spent by users to handle an issue.
""",
'website': 'https://... | : [
'project_issue_sheet_view.xml',
'security/ir.model.access.csv',
'security/portal_security.xml',
],
'demo': [],
'installable': True,
'auto_install': False,
}
|
prefetchnta/questlab | bin/x64bin/python/37/Lib/nntplib.py | Python | lgpl-2.1 | 44,234 | 0.000701 | """An NNTP client class based on:
- RFC 977: Network News Transfer Protocol
- RFC 2980: Common NNTP Extensions
- RFC 3977: Network News Transfer Protocol (version 2)
Example:
>>> from nntplib import NNTP
>>> s = NNTP('news')
>>> resp, count, first, last, name = s.group('comp.lang.python')
>>> print('Group',... | ods by Kevan Heydon
# Incompatible changes from the 2.x nntplib:
# - all commands are encoded as UTF-8 data | (using the "surrogateescape"
# error handler), except for raw message data (POST, IHAVE)
# - all responses are decoded as UTF-8 data (using the "surrogateescape"
# error handler), except for raw message data (ARTICLE, HEAD, BODY)
# - the `file` argument to various methods is keyword-only
#
# - NNTP.date() re... |
hale36/SRTV | sickbeard/providers/strike.py | Python | gpl-3.0 | 3,919 | 0.003572 | # Author: matigonkas
# URL: https://github.com/SiCKRAGETV/sickrage
#
# This file is part of SickRage.
#
# SickRage 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... | self.minseed, self.minleech = 2 * [None]
def isEnabled(self):
return self.enabled
def _doSearch(self, search_strings, search_mode='eponly', epcount=0, age=0, epObj=None):
results = []
items = {'Season': [], 'Episode': [], 'RSS': []}
for mode in search_strings.keys(): ... | logger.log(u"Search Mode: %s" % mode, logger.DEBUG)
for search_string in search_strings[mode]:
if mode != 'RSS':
logger.log(u"Search string: " + search_string.strip(), logger.DEBUG)
searchURL = self.url + "api/v2/torrents/search/?category=TV&phras... |
vritant/subscription-manager | test/test_lock.py | Python | gpl-2.0 | 6,575 | 0.000608 | import os
import subprocess
import sys
import tempfile
import threading
import time
import unittest
from subscription_manager import lock
class TestLock(unittest.TestCase):
lf_name = "lock.file"
def setUp(self):
self.tmp_dir = self._tmp_dir()
self.other_process = None
def _tmp_dir(self)... | lf = lock.Lock(lock_path)
res = lf.acquire(blocking=False)
self.assertTrue(res)
# always blocks, needs eventloop/threads
# def test_lock_drive_full_blocking(self):
# lock_path = "/dev/full"
# lf = lock.Lock(lock_path)
# res = lf.acquire(blocking=True)
# log.debug(res)
# ... | blocking=False)
# self.assertFalse(res)
# run this module's main in a subprocess to grab a lock from a different
# pid.
def main(args):
lock_file_path = args[1]
test_lock = lock.Lock(lock_file_path)
# could return a useful value, so the thread communicating with
# it could notice it couldn't g... |
MeanEYE/Sunflower | sunflower/icons.py | Python | gpl-3.0 | 3,797 | 0.025283 | from __future__ import absolute_import
from builtins import filter
import os
import sys
import zipfile
from gi.repository import Gtk, Gio, GdkPixbuf, GLib
from sunflower.common import UserDirectory, get_user_directory, get_static_assets_directory
class IconManager:
"""Icon manager class provides easy and abstract ... | harddisk'
# create a list of icons and f | ilter non-existing
icon_list = icons.split(' ')
icon_list = list(filter(self.has_icon, icon_list))
# if list has items, grab first
if len(icon_list) > 0:
result = icon_list[0]
return result
def set_window_icon(self, window):
"""Set window icon"""
# check system for icon
if self.has_icon('sunflowe... |
r2k0/flask-apps | mega-tut/app/views.py | Python | mit | 2,555 | 0.005479 | """
the handlers that respond to requests from browsers or clients.
Each view function is mapped to one or more request URLs.
"""
from flask import render_template, flash, redirect, session, url_for, reqeust, g
from flask.ext.login import login_user, logout_user, current_user, login_required
from app import app, db, l... | 'body': 'I want bacon!'
}
]
return render_template('index.html',
title='Home',
user=user,
posts=posts)
@app.route('/login', methods=['GET', 'POST'])
@oid.loginhandler
def login():
if g.user is not None a... | (url_for('index'))
form = LoginForm()
if form.validate_on_submit():
session['remember_me'] = form.remember_me.data
return oid.try_login(form.openid.data, ask_for=['nickname', 'email'])
return render_template('login.html',
title='Sign In',
... |
datyayu/cemetery | [Python][Django] Rest framework tutorial/snippets/urls.py | Python | mit | 314 | 0 | from django.conf.urls import url, in | clude
from snippets.views import SnippetViewSet, UserViewSet
from rest_f | ramework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'snippets', SnippetViewSet)
router.register(r'users', UserViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
|
OpenParking/Open-Parkinig---Edison | source/touh.py | Python | gpl-2.0 | 1,004 | 0.000996 | import time
import pyupm_ttp223 as ttp223
import requests
import json
url = "http://requestb.in/1mj62581?inspect"
headers = {'content-type': 'application/json'}
touch1 = ttp223.TTP223(4)
touch1Pressed = False
touch2 = ttp223.TTP223(8)
touch2Pressed = False
def sendInfo(touch, tId, Pressed):
if touch.isPressed()... | f not Pressed:
print "Send Info"
Pressed = True
data = {"Id": "AI", "Espacio": tId, "Disponible": False}
data = json.dumps(data)
requests.post(url, params=data, headers=headers)
else:
if Pressed:
print "Send Info"
Pressed = ... | rs)
return Pressed
while True:
touch1Pressed = sendInfo(touch1, 1, touch1Pressed)
touch2Pressed = sendInfo(touch2, 2, touch2Pressed)
time.sleep(1)
del touch1
del touch2
|
abilian/abilian-core | src/abilian/web/tags/__init__.py | Python | lgpl-2.1 | 244 | 0 | """" | ""
from __future__ import annotations
from flask import Flask
from .criterion import TagCriterion
from .extension import TagsExtension
__all__ = ["TagsExtension", "TagCriterion"]
def register_plugin(app: Flask):
Tag | sExtension(app)
|
mariosky/evo-drawings | venv/lib/python2.7/site-packages/django/db/backends/__init__.py | Python | agpl-3.0 | 47,905 | 0.001232 | import datetime
import time
from django.db.utils import DatabaseError
try:
from django.utils.six.moves import _thread as thread
except ImportError:
from django.utils.six.moves import _dummy_thread as thread
from collections import namedtuple
from contextlib import contextmanager
from django.conf import setti... | # NAME, USER, etc. It's called `settings_dict` instead of `settings`
# to disambiguate it from Django settings modules.
self.connection = None
self.queries = []
self.settings_dict = settings_dict
self.alias = alias
self.use_debug_cursor = | None
# Savepoint management related attributes
self.savepoint_state = 0
# Transaction management related attributes
self.autocommit = False
self.transaction_state = []
# Tracks if the connection is believed to be in transaction. This is
# set somewhat aggressiv... |
xTVaser/Schoolwork-Fall-2016 | Thesis/Parser/main.py | Python | gpl-3.0 | 526 | 0.001901 | import easygui
from os import listdir
from os.path import isfile, join
# Import Custom Libraries
from libs.requestStripper import *
file_path = "/home/tyler/Documents/Thesis Testing"
print(file_path)
files = [f for f in listd | ir(file_path) if isfile(join(file_path, f))]
for i, value in enumerate(files):
files[i] = fi | le_path + "/" + files[i]
print(files)
lines = []
for f in files:
gatherStrings(lines, f)
newFile = open(file_path+"/"+"compiledRequests", "w")
exportFile(lines, newFile)
newFile.close()
|
Symmetry-Innovations-Pty-Ltd/Python-2.7-for-QNX6.5.0-x86 | usr/pkg/lib/python2.7/shutil.py | Python | mit | 18,302 | 0.002186 | """Utility functions for copying and archiving files and directory trees.
XXX The functions | here don't copy the resource fork or other metadata on Mac.
"""
import os
import sys
import stat
from os.path import abspath
import fnmatch
import collections
import errno
try:
from pwd import getpwnam
except ImportError:
getpwnam = None
try:
from grp import getgrnam
except Imp | ortError:
getgrnam = None
__all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2",
"copytree", "move", "rmtree", "Error", "SpecialFileError",
"ExecError", "make_archive", "get_archive_formats",
"register_archive_format", "unregister_archive_format"]
class Err... |
ua-snap/downscale | old/old_bin/downscaling_launcher.py | Python | mit | 3,849 | 0.043128 | #!/usr/bin/python2
import os, glob
os.chdir( '/workspace/Shared/Tech_Projects/ALFRESCO_Inputs/project_data/CODE/tem_ar5_inputs' | )
base_dir = '/workspace/Shared/Tech_Projects/ESGF_Data_Access/project_data/data/prepped'
output_base_dir = '/workspace/Shared/Tech_Projects/ALFRESCO_Inputs/project_data/TEM_Data/downscaled'
cru_base_dir = '/workspace/Shared/Tech_Projects/ALFRESCO_Inputs/project_data/TEM_Data/cru_ts20/akcan'
for root, dirs, files in o... | variable = os.path.split( root )
path, model = os.path.split( path )
# this gets rid of any .xml or .txt files that may be living amongst the NetCDF's
files = [ fn for fn in files if fn.endswith( '.nc' ) ]
for fn in files:
print 'running %s' % fn
# split out the sub_dirs to have both model_name and var... |
50wu/gpdb | gpMgmt/bin/gppylib/test/unit/test_unit_compare_segment_guc.py | Python | apache-2.0 | 8,167 | 0.003061 | from mock import *
from .gp_unittest import *
from gpconfig_modules.compare_segment_guc import MultiValueGuc
from gpconfig_modules.database_segment_guc import DatabaseSegmentGuc
from gpconfig_modules.file_segment_guc import FileSegmentGuc
class CompareSegmentGucTest(GpTestCase):
def setUp(self):
row = ['c... | self.assertEqual(self.subject.report_fail_format(),
["[context: contentid] [dbid: dbid] [name: guc_name] [value: sql_value | file: file_value]"])
def test_report_fail_format_file_segment_guc_only(self):
self.subject.db_seg_guc = None
row = ['contentid', 'guc_name', 'prima... | entid', 'guc_name', 'mirror_value', "dbid2"]
self.subject.set_mirror_file_segment(FileSegmentGuc(row))
self.assertEqual(self.subject.report_fail_format(),
["[context: contentid] [dbid: dbid1] [name: guc_name] [value: primary_value]",
"[context: content... |
havardgulldahl/perpetual-yearcal | models.py | Python | mit | 1,783 | 0.011223 | # encoding: utf-8
# The MIT License (MIT)
# Copyright (c) 2014 Håvard Gulldahl
# 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
#... | ckground = ndb.StringProperty()
colorId = ndb.StringProperty()
category = ndb.StringProperty() # 'calendar' or 'event'
title = ndb.StringProperty()
class CalendarPrettyTitle(ndb.Model):
cal_id = ndb.StringProperty()
pretty_title = ndb.StringProperty()
class UserSetup(ndb.Model):
user = ndb.UserProperty()
... | th_token_secret')
timestamp = ndb.DateTimeProperty(auto_now=True)
|
WesCoomber/dataFlowGraphProjecto | presentgetBothNodesEdges.py | Python | mit | 22,404 | 0.010266 | import re, sys
import functools
import graphviz as gv
from graphviz import Source
bad_words = [ 'jns', 'js', 'jnz', 'jz', 'jno', 'jo', 'jbe', 'jb', 'jle', 'jl', 'jae', 'ja', 'jne loc', 'je', 'jmp', 'jge', 'jg', 'SLICE_EXTRA', 'SLICE_ADDRESSING', '[BUG]', 'SLICE_VERIFICATION', 'syscall', '#PARAMS_LOG']
instrEdges = []... | h()
nodes = instrNodes
edges = instrEdges
#nodes = testNodes
#edges = testEdges
print(nodes)
print(edges)
def add_nodes(graph):
for n in nodes:
graph.node(n, label = str(n) + '(' + str(new_dict[n]) + ')')
return graph
def add_edges(graph):
for e in edges:
graph.edge(*e)
return graph
... | s
#Accumulator Counter Data Base Stack Pointer Stack Base Pointer Source Destination
EAX = ['R','R','R','R']
ECX = ['R','R','R','R']
EDI = ['R','R','R','R']
EDX = ['R','R','R','R']
EBX = ['R','R','R','R']
ESP = ['R','R','R','R']
EBP = ['R','R','R','R']
ESI = ['R','R','R','R']
EDI = ['R','R','R','R']
... |
fanout/django-eventstream | django_eventstream/urls.py | Python | mit | 96 | 0 | from django.urls import path
fr | om . import views
urlpatterns = [
| path('', views.events),
]
|
City-of-Bloomington/green-rental | scripts/helpers.py | Python | agpl-3.0 | 22,169 | 0.011728 | """
*2014.09.10 16:10:05
DEPRECATED!!!!
please use building.models.search_building and building.models.make_building
instead of the make_unit and make_building functions found here...
out of date.
"""
import sys, os, json, codecs, re
sys.path.append(os.path.dirname(os.getcwd()))
from geopy import geocoders, distan... | onf import settings
#settings.configure(rrsettings)
os.environ.setdefault("DJANGO | _SETTINGS_MODULE", "rentrocket.settings")
from building.models import Building, Parcel, BuildingPerson, Unit
from person.models import Person
def parse_person(text):
"""
take a string representing all details of a person
and try to parse out the different details for that person...
usually it's a com... |
danielru/pySDC | playgrounds/deprecated/acoustic_1d_imex/ploterrorconstants.py | Python | bsd-2-clause | 3,326 | 0.02285 | import numpy as np
from matplotlib import pyplot as plt
from pylab import rcParams
from matplotlib.ticker import ScalarFormatter
from subprocess import call
fs = 8
order = np.array([])
nsteps = np.array([])
error = np.array([])
# load SDC data
file = open('conv-data.txt', 'r')
while True:
line = file.readline... | 5
fig = plt.figure()
for ii in range(0,3):
plt.semilogy(nsteps_plot_sdc[ii,:], errconst_sdc[ii,:], shape_sdc[ii], markersize=fs, color=color[ii], label='SDC('+str(int(order_plot[ii]))+')')
plt.semilogy(nsteps_plot_rk[ii,:], errconst_rk[ii,:], shape_rk[ii], markersize=fs-2, color=color[ii], label='IMEX('+str(int(o... | f time steps', fontsize=fs)
plt.ylabel('Estimated error constant', fontsize=fs, labelpad=2)
plt.xlim([0.9*np.min(nsteps_plot_sdc), 1.1*np.max(nsteps_plot_sdc)])
plt.ylim([1e1, 1e6])
plt.yticks([1e1, 1e2, 1e3, 1e4, 1e5, 1e6],fontsize=fs)
plt.xticks([20, 30, 40, 60, 80, 100], fontsize=fs)
plt.gca().get_xaxis().get_major_... |
eldarion/django-trending | trending/managers.py | Python | bsd-3-clause | 1,033 | 0.000968 | import datetime
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.db.models import Sum
from django.contrib.contenttypes.models impo | rt ContentType
class Tr | endingManager(models.Manager):
def trending(self, model, days=30, kind=""):
views = self.filter(
viewed_content_type=ContentType.objects.get_for_model(model),
views_on__gte=datetime.date.today() - datetime.timedelta(days=days),
kind=kind
).values(
"vi... |
KODeKarnage/script.sub.missing | resources/lib/thetvdbapi.py | Python | gpl-3.0 | 10,006 | 0.006696 | """
thetvdb.com Python API
(c) 2009 James Smith (http://loopj.com)
(c) 2014 Wayne Davison <[email protected]>
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 2 of the License, or
(at... | uld have received a copy of the GNU General Public License
along with this pro | gram. If not, see <http://www.gnu.org/licenses/>.
"""
import urllib
import datetime
import random
import re
import copy
import xml.parsers.expat as expat
from cStringIO import StringIO
from zipfile import ZipFile
class TheTVDB(object):
def __init__(self, api_key='2B8557E0CBF7D720', language = 'en', want_raw = F... |
pandel/Marlin | buildroot/share/scripts/createTemperatureLookupMarlin.py | Python | gpl-3.0 | 6,204 | 0.009349 | #!/usr/bin/python
"""Thermistor Value Lookup Table Generator
Generates lookup to temperature values for use in a microcontroller in C format based on:
http://en.wikipedia.org/wiki/Steinhart-Hart_equation
The main use is for Arduino programs that read data from the circuit board described here:
http://reprap.org/wiki/... |
print "//////////////////////////////////////////////////////////////////////////////////////"
print "// WARNING: negative coefficient 'c'! Something may be wrong with the measurements! //"
print "/////////////////////////////////////////////// | ///////////////////////////////////////"
c = -c
self.c1 = a # Steinhart-Hart coefficients
self.c2 = b
self.c3 = c
self.rp = rp # pull-up resistance
def resol(self, adc):
"Convert ADC reading into a resolution"
... |
deepmind/acme | acme/utils/counting.py | Python | apache-2.0 | 4,636 | 0.003883 | # python3
# Copyright 2018 DeepMind Technologies Limited. 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 re... | f key.startswith(f'{self._prefix}_')])
return counts
def save(self) -> Mapping[str, Mapping[str, Number]]:
return {'counts': self._counts, 'cache': self._cache}
def restore(self, state: Mapping[str, Mapping[str, Number]]):
# Force a sync, if necessary, on the next get_counts call.
self._last_sync_... | ith prefixed keys.
Args:
dictionary: dictionary to return a copy of.
prefix: string to use as the prefix.
Returns:
Return a copy of the given dictionary whose keys are replaced by
"{prefix}_{key}". If the prefix is the empty string it returns the given
dictionary unchanged.
"""
if prefix:
... |
jlaurelli/movie_organizer | movie_organizer/settings.py | Python | mit | 2,681 | 0 | """
Django settings for movie_organizer project.
Generated by 'django-admin startproject' using Django 1.8.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Bu... | sors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'movie_organizer.wsgi.a | pplication'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_C... |
sensidev/serpisori | app/__init__.py | Python | mit | 26 | 0 | _ | _author__ = 'lucifurtu | n'
|
silberman/Deep-OSM | src/download_labels.py | Python | mit | 4,752 | 0.016204 | '''
Extract Ways from OSM PBF files
'''
import osmium as o
import json, os, requests, sys, time
import shapely.wkb as wkblib
# http://docs.osmcode.org/pyosmium/latest/intro.html
# A global factory that creates WKB from a osmium geometry
wkbfab = o.geom.WKBFactory()
# set in Dockerfile as env variable
GEO_DATA_DIR = ... | _highway(self, w):
is_highway = False
is_big = False
name = ''
highway_type = None
for tag in w.tags:
if tag.k == 'name':
name = tag.v
# and tag.v in ['primary', 'secondary', 'tertiary', 'trunk']
if tag.k == 'highway':
highway_type = tag.v
... | # print "tag {} {}".format(t.k, t.v)
#except:
# print("exception, weird lanes designation {}".format(tag.v))
# or not is_big
if not is_highway:
return
if not highway_type in self.types:
self.types.append(highway_type)
way_dict = {'visible': w.visib... |
vivisect/synapse | synapse/lib/splice.py | Python | apache-2.0 | 2,652 | 0.000754 | import tempfile
import synapse.common as s_common
import synapse.lib.msgpack as s_msgpack
_readsz = 10000000
def splice(act, **info):
'''
Form a splice event from a given act name and info.
Args:
act (str): The name of the action.
**info: Additional information about the event.
... | nvertOldSplice(mesg)
| tmp.write(s_msgpack.en(mesg))
tmp.seek(0)
fd.seek(0)
data = tmp.read(_readsz)
while data:
fd.write(data)
data = tmp.read(_readsz)
fd.truncate()
|
HackBulgaria/Odin | courses/south_migrations/0003_auto__chg_field_course_start_time__chg_field_course_end_time.py | Python | agpl-3.0 | 1,387 | 0.005047 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Course.start_time'
db.alter_column(u'courses_course', ... | .models.fields.DateField')())
# Changing field 'Course.end_time'
db.alter_column(u'courses_course', 'end_time', self.gf('django.db.models.fields.DateField')())
def backwards(self, orm):
# Changing field 'Course.start_time'
db.alter_column(u'courses_course', 'start_time', self.gf('... | urses_course', 'end_time', self.gf('django.db.models.fields.TimeField')())
models = {
u'courses.course': {
'Meta': {'object_name': 'Course'},
'description': ('django.db.models.fields.TextField', [], {}),
'end_time': ('django.db.models.fields.DateField', [], {}),
... |
mfraezz/osf.io | tests/test_registrations/test_retractions.py | Python | apache-2.0 | 43,805 | 0.003196 | """Tests related to retraction of public registrations"""
import datetime
from rest_framework import status as http_status
import mock
import pytest
from django.utils import timezone
from django.db import DataError
from nose.tools import * # noqa
from framework.auth import Auth
from framework.exceptions import Perm... | days=10)),
for_existing_registration=True
)
self.registration.save()
assert_true(self.registration.is_pending_embargo)
embargo_approval_token = self.registration.embargo.approval_state[self.user._id]['approval_token']
self.registration.embargo.approve_embargo(self.us... | embargo)
assert_true(self.registration.embargo_end_date)
self.registration.retract_registration(self.user)
self.registration.save()
assert_true(self.registration.is_pending_retraction)
retraction_approval_token = self.registration.retraction.approval_state[self.user._id]['appro... |
ejconlon/iwantaride | postit.py | Python | mit | 1,204 | 0.004153 | #!/usr/bin/env python
# ./postit.py http://localhost:5000/db/loadpost users fixtures/users.txt
# alternately, if you are running locally, visit
# http://localhost | :5000/db/loadfixture/users/users.txt
# to drop the db go to
# http://localhost:5000/db/drop
# to show the db go to
# http://localhost:5000/db/show
import urllib, urllib2, httplib
def post(url, schema, key, value):
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/pla... | nection(req.get_host())
params = urllib.urlencode({key: value})
print params
connection.request('POST', req.get_selector(),
params, headers)
response = connection.getresponse()
print response.status, response.reason
data = response.read()
connection.close()
def splitl... |
watchdogpolska/poradnia | poradnia/users/migrations/0023_auto_20220103_1354.py | Python | mit | 618 | 0.001618 | # Generated by Django 2.2.25 on 2022-01-03 12:54
from django.db import migration | s, models
class Migration(migrations.Migration):
dependencies = [
("users", "0022_auto_20191015_0510"),
]
operations = [
migrations.AlterField(
model_name="user",
name="notify_unassigned_letter",
field=models.Boolean | Field(
default=False,
help_text="Whether or not to notify user about any letter in case without anybody who can reply to client",
verbose_name="Defaults to reply in cases",
),
),
]
|
systers/hyperkitty | hyperkitty/tests/_test_caching.py | Python | gpl-3.0 | 9,926 | 0.004332 | # -*- coding: utf-8 -*-
# flake8: noqa
import unittest
import datetime
import uuid
from urllib.error import HTTPError
from mock import Mock
from mailman.email.message import Message
from mailman.interfaces.archiver import ArchivePol | icy
#import kittystore.utils
#from kittystore import get_store
#from kittystore.caching import mailman_user
#from kitt | ystore.test import FakeList, SettingsModule
class ListCacheTestCase(unittest.TestCase):
def setUp(self):
self.store = get_store(SettingsModule(), auto_create=True)
kittystore.utils.MM_CLIENT = Mock()
def tearDown(self):
self.store.close()
kittystore.utils.MM_CLIENT = None
... |
kmarius/qutebrowser | qutebrowser/browser/webengine/webenginetab.py | Python | gpl-3.0 | 37,530 | 0.00008 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2016-2018 Flori | an Bruhin (The Compiler) <[email protected]>
| #
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in... |
itaiag/blackjack | blackjack.py | Python | apache-2.0 | 17,936 | 0.004014 | #!/usr/bin/env python
from random import Random
colors_support = True
try:
from colorama import init, Fore
init()
except:
colors_support = False
print "For colors install colorama"
hint_table = \
{('5',): {'A': 'h', '10': 'h', '3': 'h', '2': 'h', '5': 'h', '4': 'h', '7': 'h', '6': 'h', '9': '... | ', '5': 'd', '4': 'd', '7': 'h', '6': 'd', '9': 'h', '8': 'h'},
('7', 'A'): {'A': 'h', '10': 'h', '3': 'd', '2': 's', '5': 'd', '4': 'd', '7': 's', '6': 'd', '9': 'h', '8': 's'},
('8', 'A'): {'A': | 's', '10': 's', '3': 's', '2': 's', '5': 's', '4': 's', '7': 's', '6': 's', '9': 's', '8': 's'},
('9', 'A'): {'A': 's', '10': 's', '3': 's', '2': 's', '5': 's', '4': 's', '7': 's', '6': 's', '9': 's', '8': 's'},
('A', 'A'): {'A': 'h', '10': 'h', '3': 'h', '2': 'h', '5': 'h', '4': 'h', '7': 'h', '6': 'h... |
scikit-multilearn/scikit-multilearn | skmultilearn/cluster/networkx.py | Python | bsd-2-clause | 6,829 | 0.003075 | from __future__ import absolute_import
import community
import networkx as nx
from networkx.algorithms.community import asyn_lpa_communities
import numpy as np
from .base import LabelGraphClustererBase
from .helpers import _membership_to_list_of_communities
class NetworkXLabelGraphClusterer(LabelGraphClustererBase)... | the networkx Graph object containing the graph representation of graph builder's adjacency matrix and weights
weights_ : { 'weight' : list of values | in edge order of graph edges }
edge weights stored in a format recognizable by the networkx module
References
----------
If you use this clusterer please cite the igraph paper and the clustering paper:
.. code :: latex
@unknown{networkx,
author = {Hagberg, Aric and Swart, ... |
macwis/simplehr | candidates/migrations/0027_auto_20171227_1432.py | Python | gpl-3.0 | 507 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2017-12-27 14:3 | 2
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('candidates', '0026_auto_20171227_1429'),
]
operations = [
migrations.RemoveField(
model_name='candidate',
name='location',
... | ',
name='location',
),
]
|
tiborsimko/invenio-records-restapi | invenio_records_rest/utils.py | Python | gpl-2.0 | 7,700 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""General utility functions module."""
from functools import partial
import six
fr... | er=getter)
def to_python(self, value):
"""Resolve PID value."""
return LazyPIDValue(self.resolver, value)
class PIDPathConverter(PIDConverter, PathConverter):
"""PIDConverter with support for path-like (with slashes) PID values.
This class is a custom routing converter defining the 'PID'... | rg/docs/0.12/routing/#custom-converters.
Use ``pidpath`` as a type in the route patter, e.g.: the use of a route
decorator: ``@blueprint.route('/record/<pidpath(recid):pid_value>')``,
will match and resolve a path containing a DOI: ``/record/10.1010/12345``.
"""
|
Drhealsgood/learning_django | polls/views.py | Python | mit | 1,526 | 0.006553 | # Create your views here.
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from django.views import generic
from polls.mode... | uest, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# display voting form
return render(request, 'polls/detail.html', | {
'poll':p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results',args=(p.id,)))
|
kensonman/webframe | models.py | Python | apache-2.0 | 46,692 | 0.029256 | # -*- coding: utf-8 -*-
# File: webframe/models.py
# Author: Kenson Man <[email protected]>
# Date: 2020-10-17 12:29
# Desc: Provide the basic model for webframe
from datetime import datetime
from deprecation import deprecated
from django.conf import settings
from django.core.serializers.json import Dja... | return rst
def impDict(self, data, **kwargs):
'''
The method to import from dictionary.
'''
if not Dictable.META_TYPE in data: raise TypeError('This is not the dictionary created by expDict. No type information found')
if not isinstance(self, getClass(data[Dictable.META_TYPE])): raise T... | ictable.META_VERS]: raise IOError('Version mismatched. Requesting %s but %s'%(getattr(self, Dictable.META_VERS), data[Dictable.META_VERS]))
for f in self.__class__._meta.get_fields():
if isinstance(f, models.Field):
n=f.name
v=parseVal(f, data.get(n, None))
setattr(self, n, v)
... |
samupl/simpleERP | apps/contacts/models.py | Python | mit | 6,028 | 0.003484 | from django.db import models
from django.utils.translation import ugettext_lazy as _, ugettext_lazy
from django_countries import countries
from django_countries.fields import CountryField
COUNTRIES = [(ugettext_lazy(name), code) for (name, code) in list(countries)]
class Company(models.Model):
# Company credenti... | .CharField(_('Postal code'), max_length=10, null=True, blank=True)
address_country = CountryField(max_length=512, null=True, blank=True)
@property
def company(se | lf):
return '{company} (NIP: {nip}, REGON: {regon})'.format(
company=self.company_name,
nip=self.company_nip,
regon=self.company_regon
)
@property
def address_country_verbose(self):
return countries.countries[self.address_country]
def __str__(sel... |
seamless-distribution-systems/galilei | galieli-netdata-installer/netdata/python.d/nsd.chart.py | Python | gpl-3.0 | 3,581 | 0.002793 | # -*- coding: utf-8 -*-
# Description: NSD `nsd-control stats_noreset` netdata python.d module
# Author: <383c57 at gmail.com>
from base import ExecutableService
import re
# default module values (can be overridden per job in `config`)
priority = 60000
retries = 5
update_every = 30
# charts order (can be overridden... | 'incremental'],
['num_type_TYPE252', 'AXFR', 'incremental'],]},
'rcode': {
'options': [
None, "return code", 'queries/s', 'return code', 'nsd.rcode', 'stacked'],
'lines': [
['num_rcode_NOERROR', 'NO | ERROR', 'incremental'],
['num_rcode_FORMERR', 'FORMERR', 'incremental'],
['num_rcode_SERVFAIL', 'SERVFAIL', 'incremental'],
['num_rcode_NXDOMAIN', 'NXDOMAIN', 'incremental'],
['num_rcode_NOTIMP', 'NOTIMP', 'incremental'],
['num_rcode_REFUSED', 'REFUSED', 'incr... |
INCF/lib9ML | nineml/abstraction/dynamics/visitors/validators/base.py | Python | bsd-3-clause | 2,819 | 0 | """
This file contains the DynamicsValidator class for validating component
:copyright: Copyright 2010-2017 by the NineML Python team, see AUTHORS.
:license: BSD-3, see LICENSE for details.
"""
from builtins import object
from nineml.visitors.validators import NoDuplicatedObjectsValidator
from .general import (
Ti... | EventDynamicsValidator(component_class,
**kwargs)
CheckNoLHSAssignmentsToMathsNamespaceDynamicsValidator(component_class,
| **kwargs)
if validate_dimensions:
DimensionalityDynamicsValidator(component_class, **kwargs)
|
mmirabent/sniffle | generate_connections.py | Python | apache-2.0 | 1,066 | 0.002814 | import socket
# List of the top 25 sites according t | o Alexa
websites = [ "Google.com",
"Facebook.com",
"Youtube.com",
"Baidu.com",
"Yahoo.com",
"Amazon.com",
"Wikipedia.org",
"Qq.com",
"Twitter.com",
"Google.co.in",
"Taobao.com | ",
"Live.com",
"Sina.com.cn",
"Linkedin.com",
"Yahoo.co.jp",
"Weibo.com",
"Ebay.com",
"Google.co.jp",
"Yandex.ru",
"Blogspot.com",
"Vk.com",
"Hao123.com",
"T.co",
... |
benthomasson/django-tastypie-swagger | tastypie_swagger/utils.py | Python | bsd-2-clause | 499 | 0 | from urlparse import urljoin
from django.conf import settings
def trailing_slash_or_none():
| """
Return a slash or empty string based on tastypie setting
"""
if getattr(settings, 'TASTYPIE_ALLOW_MISSING_SLASH', False):
return ''
return '/'
def urljoin_forced(base, path, **kwargs):
"""
urljoin base with path, except append '/' to base i | f it doesnt exist
"""
base = base.endswith('/') and base or '%s/' % base
return urljoin(base, path, **kwargs)
|
felipegerard/arte_mexicano_antiguo | felipegerard/entregable/itm/itm/similarity_functions.py | Python | agpl-3.0 | 629 | 0.041335 | from collections import defaultdict
# Regresar similitudes de un objeto index en un diccionario
def index2dict(index, file_list, num_sims=5):
file_list = [i.replace('.txt','') for i | in file_list]
sims = {} #defaultdict(dict)
for i, idx in enumerate(index):
s = []
for j in range(len(file_list)):
s.append({
'name':file_list[j],
'similarity':float(idx[j])
}) # idx[j] es un numpy.float32 y no es compatible con JSON. Por eso lo hacemos float normal
s = sorted(s, key = lambda ite... | _sims]
sims[file_list[i]] = {
i:s[i]
for i in range(len(s))
}
return sims
|
sencha/chromium-spacewalk | build/android/gyp/create_device_library_links.py | Python | bsd-3-clause | 3,509 | 0.014249 | #!/usr/bin/env python
#
# Copyright 2013 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.
"""Creates symlinks to native libraries for an APK.
The native libraries should have previously been pushed to the device (in
option... | BRARIES_DIR=%(apk_libraries_dir)s; '
'STRIPPED_LIBRARIES_DIR=%(target_dir)s; '
'. %(script_device_path)s'
) % {
'apk_libraries_dir': apk_libraries_dir,
'target_dir': options.target_dir,
'script_devic | e_path': options.script_device_path
}
RunShellCommand(device, trigger_cmd)
def main():
parser = optparse.OptionParser()
parser.add_option('--apk', help='Path to the apk.')
parser.add_option('--script-host-path',
help='Path on the host for the symlink script.')
parser.add_option('--script-dev... |
theofilis/elasticsearch-engine | elasticsearch_engine/manager.py | Python | gpl-2.0 | 20,982 | 0.001716 | from django.db import connections
from django.db.models.manager import Manager as DJManager
from django.db.utils import DatabaseError
from bson.objectid import ObjectId
import re
from .utils import dict_keys_to_str
try:
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
except ImportE... | # self.order_by(*self._document._meta | ['ordering'])
return self._cursor_obj.clone()
@classmethod
def _lookup_field(cls, document, fields):
"""
Looks for "field" in "document"
"""
if isinstance(fields, (tuple, list)):
return [document._meta.get_field_by_name((field == "pk" and "id") or field)[0] ... |
gborri/SickRage | tests/test_xem.py | Python | gpl-3.0 | 2,900 | 0.01 | #!/usr/bin/env python2.7
# Author: echel0n <[email protected]>
# URL: https://sickrage.ca
#
# This file is part of SickRage.
#
# SickRage 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 t... | (curShow)
except Exception:
| pass
def loadFromDB(self):
"""
Populates the showList with shows from the database
"""
for s in [s['doc'] for s in sickrage.app.main_db.db.all('tv_shows', with_doc=True)]:
try:
curShow = TVShow(int(s["indexer"]), int(s["indexer_id"]))
... |
whutch/cwmud | cwmud/core/commands/communication/__init__.py | Python | mit | 246 | 0 | # -*- coding: utf-8 -*-
"""Communication commands package."""
# Part of Clockw | ork MUD Server (https://github.com/whutch/cwmud)
# | :copyright: (c) 2008 - 2017 Will Hutcheson
# :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt)
|
superdesk/superdesk-core | apps/archive/news.py | Python | agpl-3.0 | 767 | 0 | """
News resource
=============
It is an alias for archive without filtering out published items.
"""
from superdesk.resource import build_custom_hateoas
from apps.archive.archive import ArchiveResource, ArchiveService
from apps.ar | chive.common import CUSTOM_HATEOAS
class NewsResource(ArchiveResource):
datasource = ArchiveResource.datasource.copy()
datasource.update(
{
"source": "archive",
"elasti | c_filter": {"bool": {"must_not": {"term": {"version": 0}}}},
}
)
resource_methods = ["GET"]
item_methods = []
class NewsService(ArchiveService):
def enhance_items(self, items):
super().enhance_items(items)
for item in items:
build_custom_hateoas(CUSTOM_HATEOAS, ite... |
tangyanhan/homesite | manage_videos/urls.py | Python | mit | 370 | 0.016216 | from django.conf.urls import url
from . import views
app_name='manage'
urlpatterns = [
url(r'^index/$', views.index, name='index'),
url(r'^db/(\w+)/$', view | s.db, name='db'), |
url(r'^import/index/$', views.import_index, name='import'),
url(r'^import/dir/$', views.import_dir, name='import-dir'),
url(r'^import/status/', views.import_status, name='import-status')
]
|
alxgu/ansible | lib/ansible/plugins/lookup/passwordstore.py | Python | gpl-3.0 | 11,134 | 0.003413 | # (c) 2017, Patrick Deelman <[email protected]>
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
lookup: passwordstore
vers... | ] = value
except (ValueError, AssertionError) as e:
raise AnsibleError(e)
# check and convert values
try:
for key in ['create', 'returnall', 'overwrite', 'backup', 'nosymbols']:
if not isinstance(self.paramvals[key], bool):
... | ) as e:
raise AnsibleError(e)
if not isinstance(self.paramvals['length'], int):
if self.paramvals['length'].isdigit():
self.paramvals['length'] = int(self.paramvals['length'])
else:
raise AnsibleError("{0} is not a corre... |
cortedeltimo/SickRage | sickbeard/clients/transmission_client.py | Python | gpl-3.0 | 5,187 | 0.00135 | # coding=utf-8
# Author: Mr_Orange <[email protected]>
# URL: https://sickrage.github.io
#
# This file is part of SickRage.
#
# SickRage 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 ... | re
from base64 import b64encode
import sickbeard
from sickbeard.clients.generic import GenericClient
class TransmissionAPI(GenericClient):
def __init__(self, host=None, username=None, passw | ord=None):
super(TransmissionAPI, self).__init__('Transmission', host, username, password)
self.url = '/'.join((self.host.rstrip('/'), sickbeard.TORRENT_RPCURL.strip('/'), 'rpc'))
def _get_auth(self):
post_data = json.dumps({'method': 'session-get', })
try:
self.respo... |
opennetworkinglab/spring-open | scripts/perf-scripts/generate_flows.py | Python | apache-2.0 | 2,622 | 0.017162 | #! /usr/bin/env python
# -*- Mode: python; py-indent-offset: 4; tab-width: 8; indent-tabs-mode: t; -*-
#
# A script for generating a number of flows.
#
# The output of the script should be saved to a file, and the flows from
# that file should be added by the following command:
#
# web/add_flow.py -f filename
#
# N... | pprint.PrettyPrinter(indent=4)
## Worker Functions ##
def log_error(txt):
print '%s' % (txt)
def debug(txt):
if DEBUG:
print '%s' % (txt)
if __name__ == "__main__":
usage_msg = "Generate a number of flows by using a | pre-defined template.\n"
usage_msg = usage_msg + "\n"
usage_msg = usage_msg + "NOTE: This script is work-in-progress. Currently all flows are within same\n"
usage_msg = usage_msg + "pair of switch ports and contain auto-generated MAC-based matching conditions.\n"
usage_msg = usage_msg + "\n"
usage_msg = usag... |
jmesteve/saas3 | openerp/addons/hr_contract/hr_contract.py | Python | agpl-3.0 | 4,997 | 0.005803 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | te_start'] > contract['date_end']:
return False
return True
_constraints = [
(_check_dates, 'Error! Contract start-date must be less than contract end-date.', ['date_start', 'date_end'])
]
# vim:expandtab:smartindent:tabstop=4:s | ofttabstop=4:shiftwidth=4:
|
nidhididi/CloudBot | cloudbot/event.py | Python | gpl-3.0 | 15,182 | 0.003557 | import asyncio
import enum
import logging
import concurrent.futures
logger = logging.getLogger("cloudbot")
@enum.unique
class EventType(enum.Enum):
message = 0
action = 1
# TODO: Do we actually want to have a 'notice' event type? Should the NOTICE command be a 'message' type?
notice = 2
join = 3
... | be left out if you specify a `base_event`.
:param bot: The CloudBot instance this event was triggered from
:param conn: The Client instance this event was triggered from
:param hook: The hook this event will be passed to
:param base_event: The base event that this event is based on. If... | arguments are ignored
:param event_type: The type of the event
:param content: The content of the message, or the reason for an join or part
:param target: The target of the action, for example the user being kicked, or invited
:param channel: The channel that this action took place in
... |
scompo/money | money/money.py | Python | bsd-3-clause | 3,277 | 0.01007 | from time import localtime, gmtime, strftime, strptime
from os.path import expanduser, join
from pprint import pprint
from decimal import *
def scrivi_movimento(path, m):
with open(path, 'a') as f:
f.write(m['tipo'] + m['valore'])
f.write(';')
f.write(m['data'])
f.write(';')
... | ) [oggi]: ')
if d == '':
d | = strftime("%d/%m/%Y", localtime())
return d
def leggi_ora():
o = input('ora (HH:MM) [adesso]: ')
if o == '':
o = strftime('%H:%M', localtime())
return o
def leggi_descrizione():
d = input('descrizione () []: ')
return d
def leggi_movimento():
tipo = leggi_tipo()
valore = legg... |
firstprayer/monsql | setup.py | Python | mit | 371 | 0.013477 | from setuptools import setup, find_package | s
setup(name='monsql',
version='0.1.7',
packages = find_packages(),
author='firstprayer',
author_email='[email protected]',
description='MonSQL - Mongodb-style way for using mysql.',
url='https://github.com/firstprayer/monsql | .git',
install_requires=[
'MySQL-python'
],
)
|
AdmiralenOla/Scoary | scoary/vcf2scoary.py | Python | gpl-3.0 | 8,390 | 0.005364 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Script to search vcf files for mutations within specific coordinates
# Input:
# -A vcf file
#
# Output:
# -A Roary-like file with mutations sorted in rows, strains as columns and presence/absence in cells
# -Columns: Chromosome, Position, variant (eg C->T), type (eg mis... | ,
help='Force overwriting of output file. (If it already '
'exists)')
parser.add_argument(
'vcf',
action='store',
metavar='<VCF_file>',
help='The VCF file to con | vert to Roary/Scoary format')
args = parser.parse_args()
if args.types is not "ALL":
args.types = args.types.split(",")
if os.path.isfile(args.out) and not args.force:
sys.exit("Outfile already exists. Change name of outfile or "
"run with --force")
if not os.path.isfi... |
reyoung/SlideGen2 | slidegen2/yaml_formatter.py | Python | mit | 933 | 0.001072 | from yaml import load_all
try:
from yaml import CLoader as Loader
except ImportError:
print("Using pure python YAML loader, it may be slow.")
from yaml import Loader
from iengine import IDocumentFormatter
__author__ = 'reyoung'
class YAMLFormatter(IDocumentFormatter):
def __init__(self, fn=None, con... | content = load_all(f, Loade | r=Loader)
else:
self.__content = load_all(content, Loader=Loader)
def get_command_iterator(self, *args, **kwargs):
for item in self.__content:
yield YAMLFormatter.__process_item(item)
@staticmethod
def __process_item(item):
if isinstance(item, dict) and len(... |
hydroshare/hydroshare | hs_access_control/migrations/0033_auto_20220217_2304.py | Python | bsd-3-clause | 756 | 0.002646 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2022-02-17 23:04
from __future__ import unicode_literals
from django.db import migrations, models
import theme | .utils
class Migration(migrations.Migration):
dependencies = [
('hs_access_control', '0032_auto_20210607_2027'),
]
operations = [
migrations.AlterField(
model_name='community',
name='picture',
field=models.ImageField(blank=True, null=True, upload_to=th... | mageField(blank=True, null=True, upload_to=theme.utils.get_upload_path_group),
),
]
|
yunify/qingcloud-cli | qingcloud/cli/iaas_client/actions/alarm_policy/add_alarm_policy_actions.py | Python | apache-2.0 | 2,067 | 0.000968 | # =========================================================================
# Copyright 2012-present Yunify, Inc.
# -------------------------------------------------------------------------
# Licensed under the Apache License, V | ersion | 2.0 (the "License");
# you may not use this work except in compliance with the License.
# You may obtain a copy of the License in the LICENSE file, or 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 distribute... |
Ilias95/lib389 | lib389/__init__.py | Python | gpl-3.0 | 123,763 | 0.000525 | # --- BEGIN COPYRIGHT BLOCK ---
# Copyright (C) 2015 Red Hat, Inc.
# All rights reserved.
#
# License: GPL (version 3 or any later version).
# See LICENSE for details.
# --- END COPYRIGHT BLOCK ---
"""The lib389 module.
IMPORTANT: Ternary operator syntax is unsupported on RHEL5
x if cond else y #don't!
... | # print "Received search reference: "
# pprint.pprint(data[-1][1])
# data.pop() # remove the last non-entry element
return objtype, [Entry(x) for x in data]
else:
raise TypeError("unknown data type %s returned b... | elif name.startswith('add'):
# the first arg is self
# the second and third arg are the dn and the data to send
# We need to convert the Entry into the format used by
# python-ldap
ent = args[0]
if isinstance(ent, Entry):
retur... |
matrix65537/lab | leetcode/permutations/permutation2.py | Python | mit | 785 | 0.003822 | #!/usr/bin/env python
#coding:utf8
class Solution(object):
def permuteUnique(self, nums):
length = len(nums)
if length == 0:
return [[]]
rlists = [[nums[0]]]
for i in range(1, length):
tlists = []
for L in rlists:
| v = nums[i]
for j in range(i + 1):
lcopy = L[::]
lcopy.insert(j, v)
tlists.append(lcopy)
rlists = tlists
d = {}
for L in | rlists:
d[tuple(L)] = True
return map(lambda x: list(x), d.keys())
def main():
nums = [1, 1, 2]
s = Solution()
rlists = s.permuteUnique(nums)
for L in rlists:
print L
if __name__ == '__main__':
main()
|
GluuFederation/community-edition-setup | schema/generator.py | Python | mit | 8,810 | 0.000908 | #!/usr/bin/env python3
"""
A Module containing the classes which generate schema files from JSON.
"""
import json
def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class K:
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
retu... | ass: subschema\ncn: schema\n"
for attr in self.data['attributeTypes']:
attr_str = "attributeTypes: ( {} NAME ".format(self._getOID(attr))
if len(attr['names']) > 1:
namestring = ''
for name in attr['names']:
namestring += "'{}' ".forma... | elif len(attr['names']) == 1:
attr_str += "'{}'".format(attr['names'][0])
else:
print("Invalid attribute data. Doesn't define a name")
if 'desc' in attr:
attr_str += "\n DESC '{}'".format(attr['desc'])
if 'equality' in attr:
... |
evernym/plenum | plenum/server/consensus/ordering_service.py | Python | apache-2.0 | 109,275 | 0.00205 | import itertools
import logging
import time
from _sha256 import sha256
from collections import defaultdict, OrderedDict, deque
from functools import partial
from typing import Tuple, List, Set, Optional, Dict, Iterable, Callable
from orderedset._orderedset import OrderedSet
from sortedcontainers import SortedList
fro... | enum.common.timer import TimerService, RepeatingTimer
from plenum.common.txn_util import get_payload_digest, get_payload_data, get_seq_no, get_txn_time
from plenum.common.types import f
from plenum.common.util import compare_3PC_keys, updat | eNamedTuple, SortedDict, getMaxFailures, mostCommonElement, \
get_utc_epoch, max_3PC_key, reasonForClientFromException
from plenum.server.batch_handlers.three_pc_batch import ThreePcBatch
from plenum.server.consensus.consensus_shared_data import ConsensusSharedData
from plenum.server.consensus.batch_id import Batch... |
orbitfp7/horizon | openstack_dashboard/test/api_tests/network_tests.py | Python | apache-2.0 | 34,720 | 0 | # Copyright 2013 NEC Corporation
#
# 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 ag... | ITHOUT
# 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 collections
import copy
import itertools
import uuid
from django import http
from django.test.utils import override_settings
... | ip_pools
from openstack_dashboard import api
from openstack_dashboard.test import helpers as test
class NetworkClientTestCase(test.APITestCase):
def test_networkclient_no_neutron(self):
self.mox.StubOutWithMock(api.base, 'is_service_enabled')
api.base.is_service_enabled(IsA(http.HttpRequest), 'ne... |
google-research/lag | libml/layers.py | Python | apache-2.0 | 18,151 | 0.001598 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | * n, W * n).
"""
s, ts = x.shape, tf.shape(x)
if order == NCHW:
| x = tf.reshape(x, [-1, s[1] // (n ** 2), n, n, ts[2], ts[3]])
x = tf.transpose(x, [0, 1, 4, 2, 5, 3])
x = tf.reshape(x, [-1, s[1] // (n ** 2), ts[2] * n, ts[3] * n])
elif order == NHWC:
x = tf.reshape(x, [-1, ts[1], ts[2], n, n, s[3] // (n ** 2)])
x = tf.transpose(x, [0, 1, 3, 2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.