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 |
|---|---|---|---|---|---|---|---|---|
jdemel/gnuradio | gnuradio-runtime/python/gnuradio/gr/exceptions.py | Python | gpl-3.0 | 311 | 0.006431 | from __future__ im | port unicode_literals
#
# Copyright 2004 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
class NotDAG (Exception):
"""Not a directed acyclic graph"""
pass
cla | ss CantHappen (Exception):
"""Can't happen"""
pass
|
ywangd/stash | tests/misc/test_cowsay.py | Python | mit | 2,613 | 0.001531 | # -*- coding: utf-8 -*-
from stash.tests.stashtest import StashTestCase
class CowsayTests(StashTestCase):
"""tests for cowsay"""
def test_help(self):
"""test help output"""
output = self.run_command("cowsay --help", exitcode=0)
self.assertIn("cowsay", output)
self.assertIn("--... | tput"""
output = self.run_command("cowsay Hello, World!", exitcode=0)
self.assertIn("Hello, World!", output)
| self.assertNotIn("test", output)
self.assertEqual(output.count("<"), 1)
self.assertEqual(output.count(">"), 1)
def test_stdin_read(self):
"""test 'echo test | cowsay' printing 'test'"""
output = self.run_command("echo test | cowsay", exitcode=0)
self.assertIn("test", outpu... |
nicain/dipde_dev | dipde/internals/internalpopulation.py | Python | gpl-3.0 | 20,747 | 0.010604 |
# Copyright 2013 Allen Institute
# This file is part of dipde
# dipde 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.
#
# dipde is di... | ver
# Voltage edges and leak matrix construction
self.edges = util.get_v_edges(self.v_min, self.v_max, self.dv)
# Different leak matrice | s for different solvers:
self.leak_flux_matrix_dict = {}
self.leak_flux_matrix_dict['dense'] = util.leak_matrix(self.edges, self.tau_m)
# Backward Euler sparse:
lfm_csrbe = sps.eye(np.shape(self.leak_flux_matrix_dict['dense'])[0], format='csr') - self.simulation.dt*self.leak_fl... |
opencobra/memote | src/memote/experimental/growth.py | Python | apache-2.0 | 2,835 | 0.000353 | # -*- coding: utf-8 -*-
# Copyright 2018 Novo Nordisk Foundation Center for Biosustainability,
# Technical University of Denmark.
#
# 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
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRAN... | ecific language governing permissions and
# limitations under the License.
"""Provide an interface for growth experiments."""
from __future__ import absolute_import
import logging
from pandas import DataFrame
from memote.experimental.experiment import Experiment
__all__ = ("GrowthExperiment",)
LOGGER = logging.... |
lastralab/Statistics | Specialization/Personal/Rtopy.py | Python | mit | 484 | 0.002066 | # -*- coding: utf-8 -*- |
#!/usr/bin/python
# Author: Tania M. Molina
# UY - 2017
# MIT License
import math
import numpy as np
import pandas as pd
from scipy import stats
from scipy.stats import norm
import scipy.stats as stats
import scipy.stats as st
import matplotlib
import matplotlib.pyplot as plt
import re
import scipy.stats
import matplo... | rame = pd.DataFrame(data)
|
korepwx/tfsnippet | tests/examples/utils/test_mlresult.py | Python | mit | 1,216 | 0 | import os
import unittest
import numpy as np
from tfsnippet.examples.utils import MLResults
from tfsnippet.utils import TemporaryDirectory
def head_of_file(path, n):
with open(path, 'rb') as f:
return f.read(n)
class MLResultTestCase(unittest.TestCase):
def test_imwrite(self):
with Tempor... | ryDirectory() as tmpdir:
results = MLResults(tmpdir)
im = np.zeros([32, 32], dtype=np.uint8)
im[16:, ...] = 255
results.save_image('test.bmp', im)
file_path = | os.path.join(tmpdir, 'test.bmp')
self.assertTrue(os.path.isfile(file_path))
self.assertEqual(head_of_file(file_path, 2), b'\x42\x4d')
results.save_image('test.png', im)
file_path = os.path.join(tmpdir, 'test.png')
self.assertTrue(os.path.isfile(file_path))
... |
66eli77/kolibri | kolibri/logger/test/test_api.py | Python | mit | 13,270 | 0.003693 | """
Tests that ensure the correct items are returned from api calls.
Also tests whether the users with permissions can create logs.
"""
import csv
import datetime
import uuid
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from kolibri.auth.mo... | nge(3)]
self.facility.add_admin(self.admin)
self.payload = {'user': self.user.pk,
'content_id': uuid.uuid4().hex,
'channel_id': uuid.uuid4().hex,
'kind': 'video',
'start_timestamp': str(datetime.date | time.now())}
def test_contentsessionlog_list(self):
self.client.login(username=self.admin.username, password=DUMMY_PASSWORD, facility=self.facility)
response = self.client.get(reverse('contentsessionlog-list'))
expected_count = ContentSessionLog.objects.count()
self.assertEqual(len(... |
benregn/cookiecutter-django-ansible | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/config/settings.py | Python | bsd-3-clause | 15,037 | 0.001796 | # -*- coding: utf-8 -*-
"""
Django settings for {{cookiecutter.project_name}} project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the pro... | 'south', # Database migration helpers:
'crispy_forms', # Form layouts
'avatar', # for user avatars
'django_exten | sions', # usefull django extensions
)
# Apps specific for this project go here.
LOCAL_APPS = (
'users', # custom users app
# Your stuff: custom apps go here
)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_... |
openstack/rally | rally/common/db/migrations/env.py | Python | apache-2.0 | 1,541 | 0 | # Copyright (c) 2016 Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | ined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
engine = ... | rget_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
run_migrations_online()
|
jzitelli/python-gltf-experiments | OpenVRRenderer.py | Python | mit | 4,971 | 0.004828 | from ctypes import c_float, cast, POINTER
import numpy as np
import OpenGL.GL as gl
import openvr
from openvr.gl_renderer import OpenVrFramebuffer as OpenVRFramebuffer
from openvr.gl_renderer import matrixForOpenVrMatrix as matrixForOpenVRMatrix
from openvr.tracked_devices_actor import TrackedDevicesActor
import g... | indFramebuffer(gl.GL_FRAMEBUFFER, 0)
def process_input(self):
pass
# state = self.vr_system.getControllerState(1)
# if state and state.rAxis[1].x > 0.05:
# self.vr_system.triggerHapticPulse(1, 0, int(3200 * state.rAxis[1].x))
# state = self.vr_system.getControllerState(2... | tem.pollNextEvent(self.vr_event):
# if self.vr_event.eventType == openvr.VREvent_ButtonPress:
# pass #print('vr controller button pressed')
# elif self.vr_event.eventType == openvr.VREvent_ButtonUnpress:
# pass #print('vr controller button unpressed')
def shu... |
gfyoung/pandas | pandas/core/generic.py | Python | bsd-3-clause | 387,628 | 0.000689 | from __future__ import annotations
import collections
from datetime import timedelta
import functools
import gc
import json
import operator
import pickle
import re
from typing import (
TYPE_CHECKING,
Any,
AnyStr,
Callable,
Hashable,
Literal,
Mapping,
Sequence,
cast,
overload,
)
... | ing[Hashable, Any] | None = None,
):
# copy kwarg is retained for mypy compat, is not used
object.__setattr__(self, "_is_copy", None)
object.__setattr__(self, "_mgr", data)
object. | __setattr__(self, "_item_cache", {})
if attrs is None:
attrs = {}
else:
attrs = dict(attrs)
object.__setattr__(self, "_attrs", attrs)
object.__setattr__(self, "_flags", Flags(self, allows_duplicate_labels=True))
@classmethod
def _init_mgr(
cls,
... |
stack-of-tasks/rbdlpy | tutorial/lib/python2.7/site-packages/OpenGL/WGL/ARB/robustness_application_isolation.py | Python | lgpl-3.0 | 867 | 0.008074 | '''OpenGL extension ARB.robustness_application_isolation
This module customises the behaviour of the
OpenGL.raw.WGL.ARB.robustness_application_isolation to provide a more
Python-friendly API
The official definition of this extension is available here:
http://ww | w.opengl.org/registry/specs/ARB/robustness_application_isolation.txt
'''
from OpenGL import platform, constant, arrays
from OpenGL import extensions, wrapper
import ctypes
from OpenGL.raw.WGL import _types, _glgets
from OpenGL.raw. | WGL.ARB.robustness_application_isolation import *
from OpenGL.raw.WGL.ARB.robustness_application_isolation import _EXTENSION_NAME
def glInitRobustnessApplicationIsolationARB():
'''Return boolean indicating whether this extension is available'''
from OpenGL import extensions
return extensions.hasGLExtension... |
edx/edx-organizations | organizations/models.py | Python | agpl-3.0 | 2,793 | 0.002148 | """
Database ORM models managed by this Django app
Please do not integrate directly with these models!!! This app currently
offers one programmatic API -- api.py for direct Python integration.
"""
import re
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation i... | e_name='Course ID')
organization = models.ForeignKey(Organization, db_index=True, on_delete=models.CASCADE)
active = models.BooleanField(default=True)
history = HistoricalRecords()
class Meta:
""" Meta class for this Django model """
unique_together = (('course_id', 'organization'),)
... | verbose_name = _('Link Course')
verbose_name_plural = _('Link Courses')
|
jadsonjs/DataScience | DeepLearning/keras/hello_world.py | Python | apache-2.0 | 12 | 0.083333 | im | port keras | |
froyobin/ceilometer | ceilometer/tests/ipmi/test_manager.py | Python | apache-2.0 | 1,263 | 0 | # Copyright 2014 Intel Corp.
#
# Author: Zhai Edwin <edwin.zhai@intel.com>
#
# 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 requi... | manager.py
"""
from ceilometer.ipmi import manager
from ceilometer.tests import agentbase
import mock
from oslotest import base
class TestManager(base.BaseTestCase):
@mock.patch('ceilometer.pipeline.setup_pipeline', mock.MagicMock())
def test_load_plugins(self):
mgr = manager.AgentManager()
... | f.assertIsNotNone(list(mgr.pollster_manager))
class TestRunTasks(agentbase.BaseAgentManagerTestCase):
@staticmethod
def create_manager():
return manager.AgentManager()
def setUp(self):
self.source_resources = True
super(TestRunTasks, self).setUp()
|
kdj0c/onepagepoints | onepagebatch.py | Python | mit | 17,621 | 0.002213 | #!/usr/bin/env python3
"""
Copyright 2017 Jocelyn Falempe kdj0c@djinvi.net
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
use, cop... | ) for yunit in yunits]
upgrades = [UpgradeGroup(up_group, self) for up_group in yupgrades]
for unit in units:
unit.SetFactionCost(self.getFactionCost(unit))
for g, group in enumerate(upgrades):
affected_units = [unit for unit in units if unit.name in group.units]
... | fected_units:
unit.upgrades.append(group)
for upgrade in group:
upgrade.Cost(affected_units)
pages = yfaction.get('pages')
if len(pages) == 1:
spRules = yfaction.get('specialRules', None)
psychics = yfaction.get('psychics', None)
... |
nicolasm/lastfm-export | queries/tops.py | Python | mit | 6,184 | 0.000809 | from lfmconf.lfmconf import get_lastfm_conf
query_play_count_by_month = """
select * from view_play_count_by_month v
where substr(v.yr_month, 1, 4) =
"""
query_top_with_remaining = """
with top as (
{query_top}
),
total_count as (
{query_play_count}
)
select t.*
from t... | unt(p.id) as play_count
from play p
where 1 = 1
{condition}
group by p.track_name, p.artist_name, p.album_name
order by count(p.id) desc
"""
query_play_count = """
select count(p.id) as play_count
from play p
where 1 = 1
{condition}
"""
conf = get_lastfm_conf()
dbms = conf['lastfm'... | t_by_month():
if dbms == 'mysql':
return query_play_count_by_month + '%s'
elif dbms == 'sqlite':
return query_play_count_by_month + '?'
def build_query_play_count_for_duration(duration):
condition = build_duration_condition(duration)
return query_play_count.format(condition=condition)
... |
epinna/tplmap | plugins/engines/dot.py | Python | gpl-3.0 | 2,139 | 0.013558 | from utils.strings import quote
from plugins.languages import javascript
from utils.loggers import log
from utils import rand
import base64
import re
class Dot(javascript.Javascript):
def init(self):
self.update_actions({
'render' : {
'render': '{{=%(code)s}}',
... | t_os': """global.process.mainModule.require('os').platform()""",
},
'execute' : {
| 'call': 'evaluate',
'execute': """global.process.mainModule.require('child_process').execSync(Buffer('%(code_b64)s', 'base64').toString());"""
},
'execute_blind' : {
# The bogus prefix is to avoid false detection of Javascript instead of doT
'call'... |
sentriz/steely | steely/plugins/flirty.py | Python | gpl-3.0 | 1,575 | 0.001297 | '''Dirty talk like you're in Dundalk'''
import random
import re
import string
__author__ = ('iandioch')
COMMAND = 'flirt'
PHRASES = [
"rawr~, {s}{sep}",
"{s}, big boy{sep}",
"{s} xo",
"{s} bb{sep}",
"babe, {s}{sep}",
"hey xxx {s}{sep}",
"{s} xxx",
"{s} xx",
"{s} xo",
"{s} xoxo... | ssage):
if len(message) <= 1:
return ''
for sep in '.!?':
s, sepfound, after = message.partition(sep)
numspace = len(s) - len(s.lstrip())
s = ' ' * numspace + \
random.choice(PHRASES).format(s=s.lstri | p().lower(), sep=sepfound)
return s + flirt(after)
return message
def main(bot, author_id, message, thread_id, thread_type, **kwargs):
message = bot.fetchThreadMessages(thread_id=thread_id, limit=2)[1]
sauce = flirt(message.text)
bot.sendMessage(sauce, thread_id=thread_id, thread_type=thread_t... |
tiborsimko/invenio-ext | invenio_ext/jasmine/registry.py | Python | gpl-2.0 | 2,838 | 0.000705 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 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 your option) any... | c.js/*.js files."""
for root, dirs, files in os.walk(root):
for name in files:
if Jasm | ineSpecsAutoDiscoveryRegistry.pattern.match(name):
filename = os.path.join(root, name)
filepath = "{0}/{1}".format(
pkg,
filename[len(base) + 1:]
)
self.register(filename, key=filepath)
d... |
Huyuwei/tvm | tests/python/relay/test_vm.py | Python | apache-2.0 | 17,272 | 0.003648 | # 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... | relay.Function([x], z)
x_data = np.random.rand(1 | 2,).astype('float32')
res = veval(f, x_data)
tvm.testing.assert_allclose(res.asnumpy(), np.split(x_data, 3, axis=0)[0])
def test_id():
x = relay.var('x', shape=(10, 10), dtype='float64')
f = relay.Function([x], x)
x_data = np.random.rand(10, 10).astype('float64')
mod = relay.Module()
mod["m... |
tajkhan/pluto-pocc | annotations/module/loop/submodule/permut/transformator.py | Python | gpl-3.0 | 4,926 | 0.003857 | #
# Contain the transformation procedure
#
import sys
import module.loop.ast
#-----------------------------------------
def __makeForLoop(id, lbound, ubound, stride, loop_body):
'''Generate a for loop:
for (id=lbound; id<=ubound; id=id+stride)
loop_body'''
init_exp = None
test_exp = ... | it,
module.loop.ast.BinOpExp.EQ_ASGN)
return module.loop.ast.ForStmt(init_exp, test_exp, iter_exp, loop_body.replicate())
#------- | ----------------------------------
def transform(stmt, arg_info):
'''Perform code transformation'''
# extract argument information
loop_order, = arg_info
# get rid of compound statement that contains only a single statement
while isinstance(stmt, module.loop.ast.CompStmt) and len(stmt.stmts) == 1... |
ShaolongHu/Nitrate | tcms/testcases/tests.py | Python | gpl-2.0 | 5,924 | 0 | import unittest
from django.test.client import Client
from django.forms import ValidationError
from fields import MultipleEmailField
class CaseTests(unittest.TestCase):
def setUp(self):
self.c = Client()
self.case_id = 12345
self.status_codes = [301, 302]
def test_cases(self):
... | python(value)
self.assertEqual(pyobj, [])
def test_clean(self):
value = 'cqi@redhat.com'
data = self.field.clean(value)
self.assertEqual(data, ['cqi@redhat.com'])
value = 'cqi@redhat.com,cqi@gmail.com'
data = self.field.clean(value)
self.assertEqual(data... | \n'
data = self.field.clean(value)
self.assertEqual(data, ['cqi@redhat.com', 'cqi@gmail.com'])
value = ',cqi,cqi@redhat.com, \n,cqi@gmail.com, '
self.assertRaises(ValidationError, self.field.clean, value)
value = ''
self.field.required = True
self.assertRaises(V... |
AzamYahya/shogun | examples/undocumented/python_modular/graphical/converter_spe_helix.py | Python | gpl-3.0 | 2,562 | 0.007026 | """
Shogun demo
Fernando J. Iglesias Garcia
This example shows the use of dimensionality reduction methods, mainly
Stochastic Proximity Embedding (SPE), although Isomap is also used for
comparison. The data selected to be embedded is an helix. Two different methods
of SPE (global and local) are applied showing that t... | global method outperforms
the | local one in this case. Actually the results of local SPE are fairly poor
for this input. Finally, the reduction achieved with Isomap is better than the
two previous ones, more robust against noise. Isomap exploits the
parametrization of the input data.
"""
import math
import mpl_toolkits.mplot3d as mpl3
import numpy... |
fubarwrangler/atlassim | simulation.py | Python | gpl-2.0 | 6,264 | 0.003033 | #!/usr/bin/python
import computefarm as cf
from computefarm.farm import depth_first, breadth_first
import random
import logging
import numpy as np
HOUR = 60 * 60
default_queue_properties = {
'grid': { 'num': 0, 'mem': 750, 'avg': HOUR, 'std': 0.6 * HOUR},
'prod': { 'num': 0, 'avg': 8 * HOUR, 'std... | in call | backs by the GUI
def _set_neg_df(self):
self.farm.set_negotiatior_rank(depth_first)
def _set_neg_bf(self):
self.farm.set_negotiatior_rank(breadth_first)
def _init_stat(self, hist_size):
""" Statistics are kept in a constant-size numpy array that is updated
periodically
... |
vhelin/wla-dx | doc/sphinx/globalindex.py | Python | gpl-2.0 | 2,896 | 0.002762 | # Note: Modified by Neui (Note: sphinx.util.compat.Directive is deprecated)
#
# Copyright (C) 2011 by Matteo Franchin
#
# T | his file 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.
#
# This file is distributed in the hope that it will be useful,
# b... | e
# GNU General Public License for more details.
#
# A copy of the GNU General Public License is available at
# <http://www.gnu.org/licenses/>.
from sphinx.builders.singlehtml import SingleFileHTMLBuilder
from docutils import nodes
from docutils.parsers.rst import Directive, directives
import re
class globalind... |
mindbody/API-Examples | SDKs/Python/swagger_client/models/resource.py | Python | bsd-2-clause | 3,703 | 0.00027 | # coding: utf-8
"""
MINDBODY Public API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
impor... | """Sets | the name of this Resource.
The name of the resource. # noqa: E501
:param name: The name of this Resource. # noqa: E501
:type: str
"""
self._name = name
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in s... |
webcube/django-hyperadmin | hyperadmin/tests/test_sites.py | Python | bsd-3-clause | 360 | 0.008333 | from django.utils import unittest
from django.contrib import admin
from hyperadmin.sites import ResourceSite
class SiteTestCa | se(unittest.TestCase):
def test_install_from_admin_site(self):
site = ResourceSite()
admin.autodiscover()
site.install_models_from_site(admin.site)
self.assertTrue(s | ite.registry)
|
openstack-infra/project-config | tools/projectconfig_ruamellib.py | Python | apache-2.0 | 1,722 | 0 | # Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | in line:
newlines.append(line)
else:
newlines.append(line[2:])
return '\n'.join(newlines)
def dump(self, data, *args, **kwargs):
if isinstance(data, list):
kwargs['transform'] = self.tr
self.yaml.dump(data, *args, **kwargs)
_yaml = ... | urn _yaml.load(*args, **kwargs)
def dump(*args, **kwargs):
return _yaml.dump(*args, **kwargs)
|
primiano/depot_tools | tests/gclient_test.py | Python | bsd-3-clause | 36,329 | 0.003854 | #!/usr/bin/env python
# Copyright (c) 2012 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.
"""Unit tests for gclient.py.
See gclient_smoketest.py for integration tests.
"""
import Queue
import copy
import logging
import ... | URL(self, _):
return self.url
class GclientTest(trial_dir.TestCase):
def setUp(self):
super(GclientTest, self).setUp()
se | lf.processed = Queue.Queue()
self.previous_dir = os.getcwd()
os.chdir(self.root_dir)
# Manual mocks.
self._old_createscm = gclient.gclient_scm.CreateSCM
gclient.gclient_scm.CreateSCM = self._createscm
self._old_sys_stdout = sys.stdout
sys.stdout = gclient.gclient_utils.MakeFileAutoFlush(sys.... |
GbalsaC/bitnamiP | XBlock/xblock/test/test_fields.py | Python | agpl-3.0 | 26,030 | 0.000845 | """
Tests for classes extending Field.
"""
# Allow accessing protected members for testing purposes
# pylint: disable=W0212
from mock import Mock
import unittest
import datetime as dt
import pytz
import warnings
import math
import textwrap
import itertools
from contextlib import contextmanager
import ddt
from xblo... | stBlock(runtime, scope_ids=Mock(spec=ScopeIds))
block.field_x = arg
return block.field_x
|
@contextmanager
def assertDeprecationWarning(self, count=1):
"""Asserts that the contained code raises `count` deprecation warnings"""
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always", DeprecationWarning)
yield
self.assertEquals... |
Endika/l10n-spain | l10n_es_aeat_vat_prorrate/__openerp__.py | Python | agpl-3.0 | 812 | 0 | # -*- coding: utf-8 -*-
# (c) 2015 Antiun Ingeniería | S.L. - Pedro M. Baeza
# (c) 2015 AvanzOSC - Ainara Galdona
# License AGPL-3 - See http://www.gnu | .org/licenses/agpl-3.0
{
"name": "AEAT - Prorrata de IVA",
"version": "8.0.2.0.0",
"license": "AGPL-3",
"author": "AvanzOSC, "
"Antiun Ingeniería S.L., "
"Serv. Tecnol. Avanzados - Pedro M. Baeza, "
"Odoo Community Association (OCA)",
"website": "https://gi... |
mogoweb/webkit_for_android5.1 | webkit/Source/WebKit2/Scripts/webkit2/messages_unittest.py | Python | apache-2.0 | 24,676 | 0.002432 | # Copyright (C) 2010 Apple 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:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | in enumerate(message.parameters):
self.assertEquals(parameter.type, expected_message['parameters'][index][0])
self.assertEquals(parameter.name, expected_message['parameters'][index][1])
if message.reply_parameters != None:
for index, parameter in enumerate(message.reply_para... | ters):
self.assertEquals(parameter.type, expected_message['reply_parameters'][index][0])
self.assertEquals(parameter.name, exp |
dax/jmc | src/jmc/model/tests/account.py | Python | gpl-2.0 | 54,705 | 0.007502 | # -*- coding: utf-8 -*-
##
## test_account.py
## Login : <dax@happycoders.org>
## Started on Wed Feb 14 08:23:17 2007 David Rousselie
## $Id$
##
## Copyright (C) 2007 David Rousselie
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as publi... | _test((False, False, False), \
lambda self, email: \
self.account.get_decoded_part(email, None),
u"Not encoded single part")
test_get_decoded_part_encoded = \
make_test((True, False, False),
lambda self, email: \
... | so-8859-15' charset (éàê)")
test_format_message_summary_not_encoded = \
make_test((False, False, True),
lambda self, email: \
self.account.format_message_summary(email),
(u"From : not encoded from\nSubject : not encoded subject\n\n",
... |
merenlab/anvio | anvio/migrations/profile/v26_to_v27.py | Python | gpl-3.0 | 2,866 | 0.007676 | #!/usr/bin/env python
# -*- coding: utf-8
import sys
import argparse
from ete3 import Tree
import anvio.db as db
import anvio.utils as utils
import anvio.terminal as terminal
from anvio.errors import ConfigError
run = terminal.Run()
progress = terminal.Progress()
current_version, next_version = [x[1:] for x in __n... | _type'] == 'newick':
newick = Tree(layer_orders[order_name]['data_value'], format=1)
newick = newick.write(format=2)
profile_db._exec("""UPDATE %s SET "data_value" = ? WHERE "data_key" LIKE ?"" | " % layer_orders_table_name, (newick, order_name))
# set the version
profile_db.remove_meta_key_value_pair('version')
profile_db.set_version(next_version)
# bye
profile_db.disconnect()
progress.end()
run.info_single('Your profile db is now %s. Aww, yisss.' % next_version, nl_after=1, nl_b... |
McDermott-Group/LabRAD | LabRAD/Measurements/General/data_processing.py | Python | gpl-2.0 | 2,679 | 0.008959 | import numpy as np
import warnings
def mean_time(t, min_threshold=0, max_threshold=1253):
"""
Take a switch probability result array from the PreAmp timer, and
compute mean switching time using the specified thresholds. Timing
data is assumed to be a numpy array.
"""
t = t[np.logical_and(t... | p.vectorize(_threshold)
return threshold_vectorized(t)
def corr_coef_from_outcomes(outcomes):
"""
Comp | ute correrlation coefficient from an array of switching
outcomes.
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return np.corrcoef(outcomes[0,:], outcomes[1,:])[0,1]
def software_demod(t, freq, Is, Qs):
"""
Demodulate I and Q data in software. This method uses
... |
ppolewicz/ant-colony | antcolony/ant_move.py | Python | bsd-3-clause | 3,648 | 0.006853 | from edge import DummyEdgeEnd
from simulation_event import AbstractSimulationEvent
from stats import TripStats
class AbstractAntMove(AbstractSimulationEvent):
def __init__(self, ant, origin, destination, end_time, pheromone_to_drop, trip_stats):
self.ant = ant
self.origin = origin
self.dest... | elf.pheromone_to_drop)
if not self.destination.point.is_anthill() and self.destination.point.food > 0 and not self.ant.food: # ant has found the food
changed.append(self.destination.point)
self.trip_stats.food_found()
self.destination.point.food -= 1
self.ant.food... | stination.point.is_anthill(): # ant has returned to the anthill
if self.ant.food: # with food
changed.append(self.destination.point)
self.destination.point.food += self.ant.food
self.trip_stats.back_home()
new_ant = self.ant.__class__(self.ant.... |
JustinWingChungHui/okKindred | custom_user/admin.py | Python | gpl-2.0 | 3,150 | 0.00381 | '''
from https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#specifying-a-custom-user-model
'''
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.utils.translation import gette... | eationForm(forms.ModelForm):
"""
A form for creating new users. Includes all the required
fields, plus a repeated password.
"""
password1 = forms.CharField(label=_('Password'), widget=forms.PasswordInput)
| password2 = forms.CharField(label=_('Password confirmation'), widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email',)
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = sel... |
strizhechenko/twitterbots | memes_zaebali.py | Python | gpl-3.0 | 857 | 0.001167 | # coding: utf-8
__author__ = "@strizhechenko"
import sys
from morpher import Morpher
from twitterbot_utils import Twibot
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
bot = Twibot()
morphy = Morpher()
def tweets2words(tweets):
string = " ".join([tweet.text for tweet ... | o_tweets():
print 'New tick'
words = tweets2word | s(bot.fetch_list(list_id=217926157))
for word in words:
tweet = morphy.word2phrase(word)
bot.tweet(tweet)
print 'post', tweet.encode('utf-8')
@sched.scheduled_job('interval', hours=24)
def do_wipe():
print 'Wipe time'
bot.wipe()
if __name__ == '__main__':
do_tweets()
if '-... |
cemsbr/python-openflow | pyof/v0x04/controller2switch/group_mod.py | Python | mit | 2,734 | 0 | """Modify Group Entry Message."""
from enum import IntEnum
from pyof.foundation.base import GenericMessage
from pyof.foundation.basic_types import (
FixedTypeList, Pad, UBInt8, UBInt16, UBInt32)
from pyof.v0x04.common.header import Header, Type
from pyof.v0x04.controller2switch.common import Bucket
__all__ = ('Gr... | =Type.OFPT_GROUP_MOD)
command = UBInt16(enum_ref=GroupModCommand)
group_type = UBInt8()
#: Pad to 64 bits.
pad = Pad(1)
group_id = UBInt32()
buckets | = ListOfBuckets()
def __init__(self, xid=None, command=None, group_type=None, group_id=None,
buckets=None):
"""Create a GroupMod with the optional parameters below.
Args:
xid (int): Header's transaction id. Defaults to random.
command (GroupModCommand): One... |
g-weatherill/catalogue_toolkit | eqcat/catalogue_query_tools.py | Python | agpl-3.0 | 60,867 | 0.001824 | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# LICENSE
#
# Copyright (c) 2015 GEM Foundation
#
# The Catalogue Toolkit 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 ... | atabase Query Tools
"""
import h5py
import re
import numpy as np
import pandas as pd
from copy import copy, deepcopy
from datetime import datetime, date, time
from collections import OrderedDict
import matplotlib
import matplotlib.dates as mdates
import matplotlib.gridspec as gridspec
i | mport matplotlib.pyplot as plt
from matplotlib.colors import Normalize, LogNorm
import eqcat.utils as utils
from eqcat.regression_models import function_map
from matplotlib.path import Path
from scipy import odr
from eqcat.isf_catalogue import (Magnitude, Location, Origin,
Event, ISFCat... |
nakamura9/deploy_ad_server | client/omxplayer/myomx.py | Python | mit | 4,075 | 0.004663 | import socket
from subprocess import Popen, PIPE, STDOUT
import os
import time
import string
import requests
import json
import omxplayer
class UnsupportedFileTypeException(Exception):
'''Raised if the file type is not among the list of supported types'''
pass
class FileNotFoundException(Exception):
'''... | f._player.duration() - self._player.position()
if remaining < 1:
current = self._playlist.index(self._player.get_source())
if current < len(self._playlist) - 2:
next = self._playlist[current + 1]
else: next = self._playlist[0]
... | self._player.load(next)
|
andydrop/x17papertrail | abook2pdf.py | Python | gpl-3.0 | 3,106 | 0.027688 | from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.rl_config import defaultPageSize
from reportlab.lib.units import cm
import operator
import os
import ConfigParser
import string
config = ConfigP... | onFirstPage=Pa | ges, onLaterPages=Pages)
go(buchstabe)
|
ant9000/websup | cli/db.py | Python | gpl-3.0 | 1,581 | 0.003163 | import sqlite3
class Database:
def __init__(self, dbfile, page_rows=100):
self.dbfile = dbfile
self.page_rows = page_rows
self.conn = sqlite3.connect(self.dbfile)
self.conn.row_factory = sqlite3.Row
cursor = self.conn.cursor()
cursor.execute(
"CREATE TAB... | T COUNT(*) FROM messages").fetchone()[0]
return n
def messages(self, offset=0):
cursor = self.conn.cursor()
rows = cursor.execute(
"SELECT * FROM messages "
"ORDER BY timestamp DESC "
"LIMIT ? "
"OFFSET ?",
[self.page_rows, offset]... | item.item_type == 'message':
timestamp = item.content['timestamp']
message = item.asJson()
cursor = self.conn.cursor()
cursor.execute(
"INSERT INTO messages VALUES (?,?)",
[timestamp, message]
)
self.conn.commit()... |
FunTimeCoding/directory-tools | directory_tools/application.py | Python | mit | 269 | 0 | from flask import Flask |
from os.path import expanduser
def create_app():
app = Flask(__name__)
app.config.from_pyfile(expanduser('~/.directory-tools.py'))
from directory_tools.frontend import frontend |
app.register_blueprint(frontend)
return app
|
planrich/pypy-simd-benchmark | vec.py | Python | gpl-3.0 | 1,851 | 0.002161 |
import array
class vec(object):
@staticmethod
def sized(size, type='d'):
return vec([0] * size, type)
@staticmethod
def of(content, type='d'):
return vec(content, type)
def __init__(self, content, type='d'):
self.size = len(content)
self.type = type
self.a... | ption("size mismatch! %d != %d" % (self.size,other.size))
i = 0
while i < self.size:
result.array[i] = self.array[i] - other.array[i]
i += 1
return result
def __mul__(self, other):
return self.mul(other)
def mul(self, other, out=None):
assert isi... | lf.size, self.type)
if self.size != other.size:
raise Exception("size mismatch! %d != %d" % (self.size,other.size))
i = 0
while i < self.size:
result.array[i] = self.array[i] * other.array[i]
i += 1
return result
|
gorocacher/payload | payload/api/config.py | Python | apache-2.0 | 954 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2013 PolyBeacon, 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... | er express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Server Specific Configurations
server = {
'port': '9859',
'host': '0.0.0.0',
}
# Pecan Application Configurations
app = {
| 'root': 'payload.api.controllers.root.RootController',
'modules': ['payload.api'],
'static_root': '%(confdir)s/public',
'template_path': '%(confdir)s/payload/api/templates',
}
|
hfeeki/cmdln | test/cmdln_main2.py | Python | mit | 421 | 0.011876 | #!/usr/bin/env python
"""
$ python cmdln_main2.py
Thi | s is my shell.
$ python cmdln_main2.py foo
hello from foo
"""
import sys
import cmdln
class Shell(cmdln.RawCmdln):
"This is my shell."
name = "shell"
def do_foo(self, argv | ):
print("hello from foo")
if __name__ == "__main__":
shell = Shell()
retval = shell.cmd(sys.argv[1:]) # just run one command
sys.exit(retval)
|
beslave/space-king | space_king/models/user.py | Python | gpl-3.0 | 1,986 | 0 | # coding: utf-8
from libs.redis_storage import db1
class User(object):
def __init__(self, **kwargs):
pk = kwargs.get('pk') or db1.incr('new_user_id')
kwargs['pk'] = pk
db1.hmset('user::{}'.format(pk), kwargs)
super(User, self). | __setattr__('pk', pk)
super(User, self).__setattr__(
'__info__',
db1.hgetall(self.db_key) or {}
)
for k, v in self.__info__.iteritems():
self.__info__[k] = v.decode('utf-8')
@property
def short_info(self):
return {field: getattr(self, field) f... | s',
'last_update'
]}
@property
def db_key(self):
return 'user::{}'.format(self.pk)
@property
def fio(self):
return u'{} {}'.format(self.last_name or u'', self.first_name or u'')
@property
def battles(self):
return int(self.__info__.get('battles', 0)... |
scith/htpc-manager_ynh | sources/modules/mylar.py | Python | gpl-3.0 | 9,922 | 0.001008 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import cherrypy
import htpc
import logging
import requests
from cherrypy.lib.auth2 import require, member_of
from urllib import urlencode
from json import loads
from htpc.helpers import get_image, serve_template, fix_basepath
from StringIO import StringIO
from contextlib ... | gIO()) as f: |
f = StringIO()
f.write(getfile)
return cherrypy.lib.static.serve_fileobj(f.getvalue(), content_type='application/x-download', disposition=None, name=name, debug=False)
except Exception as e:
self.logger.error('Failed to download %s %s %s' % (name, iss... |
gear/motifwalk | research/src/mane/custom_layers.py | Python | mit | 1,273 | 0.013354 | """Custom keras layers
"""
# Coding: utf-8
# File name: custom_layer.py
# Created: 2016-07-24
# Description:
## v0.0: File created. MergeRowDot layer.
from __future__ import division
from __future__ import print_function
__author__ = "Hoang Nguyen"
__email__ = "hoangnt@ai.cs.titech.ac.jp"
from keras import backend a... | ent wise merge mul and take sum along
the second axis.
"""
##################################################################### __init__
def __init__(self, layers=None, **kwargs):
"""
Init function.
"""
super(RowDot, self).__init__(layers=None, **kwargs)
################### | ###################################################### call
def call(self, inputs, **kwargs):
"""
Layer logic.
"""
print('Inputs 0 shape: %s' % str(inputs[0].shape))
print('Inputs 1 shape: %s' % str(inputs[1].shape))
l1 = inputs[0]
l2 = inputs[1]
output = K.batch_dot(inputs[0], inputs[... |
chuckchen/spark | python/pyspark/pandas/tests/data_type_ops/test_complex_ops.py | Python | apache-2.0 | 13,290 | 0.002859 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | f_cols:
for other_col in self.array_df_cols:
self.assertRaises(TypeError, lambda: psdf[col] % psdf[other_col | ])
def test_pow(self):
self.assertRaises(TypeError, lambda: self.psser ** "x")
self.assertRaises(TypeError, lambda: self.psser ** 1)
psdf = self.array_psdf
for col in self.array_df_cols:
for other_col in self.array_df_cols:
self.assertRaises(TypeError, l... |
shingonoide/odoo | addons/account_asset/account_asset.py | Python | agpl-3.0 | 29,332 | 0.008557 | # -*- encoding: 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 G... | 'company_id': lambda self, cr, uid, context: self.pool.get('res.company')._company_default_get(cr, uid, 'account.asset. | category', context=context),
'method': 'linear',
'method_number': 5,
'method_time': 'number',
'method_period': 12,
'method_progress_factor': 0.3,
}
def onchange_account_asset(self, cr, uid, ids, account_asset_id, context=None):
res = {'value':{}}
if accou... |
sysadminmatmoz/ingadhoc | stock_multic_fix/__openerp__.py | Python | agpl-3.0 | 1,568 | 0.001276 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar)
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Pu... | ; 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 the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
... | version': '8.0.1.0.1',
'category': 'Warehouse Management',
'sequence': 14,
'summary': '',
'description': """
Stock Multic Fix
==================================
""",
'author': 'ADHOC SA',
'website': 'www.adhoc.com.ar',
'license': 'AGPL-3',
'images': [
],
'depends': [
... |
ToBaer94/PygameTowerDefense | buttons/sell_button.py | Python | lgpl-3.0 | 221 | 0.004525 | from button import Button
class SellButton(Button):
d | ef __init__(self, image, x, y, parent):
super(SellButton, self).__init__(image, x, y, parent)
def get_clicked( | self):
self.parent.sell_tower() |
googleapis/python-domains | samples/generated_samples/domains_v1_generated_domains_delete_registration_sync.py | Python | apache-2.0 | 1,539 | 0.00065 | # -*- coding: utf-8 -*-
# Copyright 2022 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir | ed by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permis | sions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for DeleteRegistration
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute ... |
htygithub/bokeh | bokeh/charts/conftest.py | Python | bsd-3-clause | 1,071 | 0.000934 | """Defines chart-wide shared test fixtures."""
import numpy as np
import pandas as pd
im | port pytest
from bokeh.sampledata.autompg import autompg
class TestData(object):
"""Contains properties with easy access to data used across tests."""
def __init__(self):
self.cat_list = ['a', 'c', 'a', 'b']
self.list_data = [[1, 2, 3, 4], [2, 3, 4, 5]]
self.array_data = [np.array(ite... | elf.dict_data = {'col1': self.list_data[0],
'col2': self.list_data[1]}
self.pd_data = pd.DataFrame(self.dict_data)
self.records_data = self.pd_data.to_dict(orient='records')
self.auto_data = autompg
@pytest.fixture(scope='module')
def test_data():
return TestData(... |
aaugustin/websockets | example/deployment/haproxy/app.py | Python | bsd-3-clause | 616 | 0 | #!/usr/bin/env python
import asyncio
import os
import signal
import websockets
async def echo(websocket):
async for message in websocket:
await websocket.send(message)
async def main(): |
# Set the stop condition when receiving SIGTERM.
loop = asyncio.get_running_loop()
stop = loop.create_future()
loop.add_signal_handler(signal.SIGTERM, stop.set_result, None)
async with websockets.serve(
echo,
host="localhost",
port=8000 + int(os.environ["SUPERVISOR_PROCESS_... | ,
):
await stop
if __name__ == "__main__":
asyncio.run(main())
|
MicroTrustRepos/microkernel | src/l4/pkg/python/contrib/Demo/scripts/pi.py | Python | gpl-2.0 | 928 | 0.005388 | #! /usr/bin/env python
# Print digits of pi forever.
#
# The algorithm, using Python's 'long' integers ("bignums"), works
# with continued fractions, and was conceived by Lambert Meertens.
#
# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
# published by Prentice-Hall (UK) Ltd., 1990.
import... | # Next approximation
p, q, k = k*k, 2L*k+1L, k+1L
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b | 1
# Print common digits
d, d1 = a//b, a1//b1
while d == d1:
output(d)
a, a1 = 10L*(a%b), 10L*(a1%b1)
d, d1 = a//b, a1//b1
def output(d):
# Use write() to avoid spaces between the digits
# Use str() to avoid the 'L'
sys.stdout.write(str(d))
# F... |
mtlchun/edx | cms/djangoapps/contentstore/views/videos.py | Python | agpl-3.0 | 12,550 | 0.001594 | """
Views related to the video upload feature
"""
from boto import s3
import csv
from uuid import uuid4
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseNotFound
from django.utils.translation import ugettext as _, ugettext_noop... | items from the original video dict and
converting all keys and values to UTF-8 encoded string objects,
because the CSV module doesn't play well with unicode objects.
"""
# Translators: This is listed as the duration for a video that has not
# yet reached the point in its processi... | y the servers where its
# duration is determined.
duration_val = str(video["duration"]) if video["duration"] > 0 else _("Pending")
ret = dict(
[
(name_col, video["client_video_id"]),
(duration_col, duration_val),
(added_col, video["crea... |
meganlkm/do-cli | do_cli/commands/cmd_list.py | Python | mit | 689 | 0.001451 | import click
from do_cli.contexts import CTX
from do_cli.commands.common import host_commands
@click.command('list')
@click.option('-f', '--force-refresh', is_flag=True, help='Pull data from the API')
@click.option('-h', '--host-names', help='Comma separated list of host names')
@CTX
def cli(ctx, force_refresh, host_... | es):
"""
Show minimal data for droplets
--host-names -h Comma separated list of host names
Show minimal data for specific droplets
"""
if ctx.verbose:
click.echo("Show minimal data for | droplets")
click.echo(host_commands(ctx, force_refresh, host_names))
if ctx.verbose:
click.echo('---- cmd_list done ----')
|
liffiton/ATLeS | src/web/controller_analyze.py | Python | mit | 6,534 | 0.00153 | import base64
import csv
import io
import multiprocessing
import numpy as np
import sys
from collections import defaultdict
from io import StringIO
from pathlib import Path
# Import matplotlib ourselves and make it use agg (not any GUI anything)
# before the analyze module pulls it in.
import matplotlib
matplotlib.use... | keys=all_keys, stats=stats)
@get('/stats/')
def get_stats():
trackrels = request.query.tracks.split('|')
exp_type = request.query.exp_type
stats = []
all_keys = set()
for trackrel in trackrels:
curstats = {}
curstats['Track file'] = trackrel
try:
processor = p... | _stats_single_table(include_phases=True))
if exp_type:
curstats.update(processor.get_exp_stats(exp_type))
except (ValueError, IndexError):
# often 'wrong number of columns' due to truncated file from killed experiment
raise(TrackParseError(trackrel, sys.exc_in... |
fiston/abaganga | project/payment/models.py | Python | mit | 932 | 0.001073 | # project/models.py
from project import db
from project.uuid_gen import id_column
class Payment(db.Model):
id = id_column()
email = db.Column(db.String(255), unique=False, nullable=False)
names = db.Column(db.String(255), unique=False, nullable=False)
cardNumber = db.Column(db.String(255), unique=Fals... | ullable=False)
status = db.Column(db.Boolean, nullable=False, default=False)
def __init_ | _(self, email, names, card_number, phone, amount, object_payment, status=False):
self.names = names
self.email = email
self.cardNumber = card_number
self.phone = phone
self.amount = amount
self.object_payment = object_payment
self.status = status
|
dtudares/hello-world | yardstick/yardstick/benchmark/scenarios/availability/monitor/monitor_command.py | Python | apache-2.0 | 3,388 | 0 | ##############################################################################
# Copyright (c) 2015 Huawei Technologies Co.,Ltd. and others
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, ... | MonitorOpenstackCmd(basemonitor.BaseMonitor):
"""docstring for MonitorApi"""
__monitor_type__ = "openstack-cmd"
def setup(self):
self.connection = None
node_name = self._config.get("host", None)
if node_na | me:
host = self._context[node_name]
ip = host.get("ip", None)
user = host.get("user", "root")
key_filename = host.get("key_filename", "~/.ssh/id_rsa")
self.connection = ssh.SSH(user, ip, key_filename=key_filename)
self.connection.wait(timeout=600)... |
Singularmotor/auto_test_lexian | auto_test_lexian/test_case/delaytest_38.py | Python | mit | 544 | 0.012868 | #coding=utf-8
from selenium import webdriver
import pymysql
import unittest,time
from selenium.webdriver.common.keys import Keys
p | rint("test36")
wf = webdriver.Firefox()
mark_01=0
n=0
wf.get("http://192.168.17.66:8080/LexianManager/html/login.html")
wf.find_element_by_xpath(".//*[@id='login']").click()
time.sleep(1)
wf.find_element_by_xpath(".//*[@id='leftMenus']/div[8]/div[1]/div[2]/a[2]").click()
time.sleep(1)
wf.find_element_by_xpath(".//*[@id... | v[2]/ul/li[2]/a").click()
time.sleep(1)
wf.switch_to_frame("manager")
|
iwm911/plaso | plaso/formatters/android_calls.py | Python | apache-2.0 | 1,199 | 0.005004 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual authors.
#
# Licensed under the Apache License, Version 2.0 (the "Lice | nse");
# 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 WARR... | OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Formatter for Android contacts2.db database events."""
from plaso.lib import eventdata
class AndroidCallFormatter(eventdata.ConditionalEventFormatter):
"""... |
chromium/chromium | third_party/tflite_support/src/tensorflow_lite_support/examples/task/text/desktop/python/bert_nl_classifier_demo.py | Python | bsd-3-clause | 1,817 | 0.003853 | # Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ort inspect
import os.path as _os_path
import subprocess
import sys
from absl import app
from absl import flags
FLAGS = flags.FLAGS
flags.DEFINE_string('model_path', None, 'Model Path')
flags.DEFINE_string('text', None, 'Text to Predict')
# Required flag.
flags.mark_flag_as_required('model_path')
flags.mark_flag_as_... | ))),
'../bert_nl_classifier_demo')
def classify(model_path, text):
"""Classifies input text into different categories.
Args:
model_path: path to model
text: input text
"""
# Run the detection tool:
subprocess.run([
_BERT_NL_CLASSIFIER_NATIVE_PATH + ' --model_path=' + model_path +
... |
eljost/pysisyphus | pysisyphus/tsoptimizers/TRIM.py | Python | gpl-3.0 | 1,861 | 0.001075 | # [1] https://doi.org/10.1016/0009-2614(91)90115-P
# Helgaker, 1991
import numpy as np
from scipy.optimize import newton
from pysisyphus.tsoptimizers.TSHessianOptimizer import TSHessianOptimizer
class TRIM(TSHessianOptimizer):
def optimize(self):
energy, gradient, H, eigvals, eigvecs, resetted = s... | tas)
# Transform to original basis
step = eigvecs * zetas
step = step.sum(axis=1)
return step
def get_step_norm(mu):
return np. | linalg.norm(get_step(mu))
def func(mu):
return get_step_norm(mu) - self.trust_radius
mu = 0
norm0 = get_step_norm(mu)
if norm0 > self.trust_radius:
mu, res = newton(func, x0=mu, full_output=True)
assert res.converged
self.log(f"Using leve... |
njanirudh/Python-DataStructures | linked_list.py | Python | mit | 2,365 | 0.009334 |
class Node:
def __init__(self,val):
self.value = val
self.nextNode = None
def getValue(self):
return self.value
def getNextNode(self):
return self.nextNode
def setValue(self,val):
self.value = val
def setNextNode(sel | f,nxtNode):
self.nextNode = nxtNode
"""
Linked List (LL)
Following are the basic operations supported by a list :-
1. Add − Adds an element at the beginning of the list.
2. Deletion − Deletes an element at the beginning of the list.
3. Display − Displays the complete list.
4. Search − Searches an element usi... | se' depending on the size of the LL
def isEmpty(self):
if(self.head == None):
return True
else:
return False
# Add a node to the head of the LL
def add(self,value):
temp = Node(value)
temp.setNextNode(self.head)
self.head = temp
# gives the to... |
thrisp/flails | tests/test_app/blueprints/private/views.py | Python | mit | 2,266 | 0.005296 | from flask.ext.flails import FlailsView
from flask import render_template, redirect, url_for, request
#from config import db
import models
import forms
class PrivatePostView(FlailsView):
def private_post_index(self):
object_list = models.Post.query.all()
return render_template('post/index.slim', ob... | query.get(ident)
form = forms.CommentForm()
return render_template('post/show.slim', post=post, form=form)
def private_post_new(self):
form = forms.PostForm()
if form.validate_on_submit():
post = models.Post(form.name.data, form.title.data, form.content.data)
... | st)
#db.session.commit()
return redirect(url_for('post.index'))
return render_template('post/new.slim', form=form)
def private_post_edit(self, ident):
post = models.Post.query.get(ident)
form = forms.PostForm(request.form, post)
if form.validate_on_submit():
... |
opendatakosovo/municipality-procurement-api | mcp/views/map.py | Python | gpl-2.0 | 4,266 | 0.000703 | from flask import Response
from flask.views import View
from bson import json_util
from mcp import mongo
class Map(View):
def dispatch_request(self, komuna, viti):
json = mongo.db.procurements.aggregate([
{
"$match": {
"komuna.slug": komuna,
... | "numriKontratave": "$numriKontratave",
"_id": 0
}
}
])
json_min_max | = mongo.db.procurements.aggregate([
{
"$match": {
"komuna.slug": komuna,
"viti": viti,
"kompania.selia.slug": {'$ne': ''}
}
},
{
"$group": {
"_id": {
... |
markflyhigh/incubator-beam | sdks/python/apache_beam/transforms/window.py | Python | apache-2.0 | 18,159 | 0.007324 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | d_value import WindowedValue
__all__ = [
'TimestampCombiner',
'WindowFn',
'BoundedWindow',
'IntervalWindow',
'TimestampedValue',
'GlobalWindow',
'NonMergingWindowFn',
'GlobalWindows',
'FixedWindows',
'SlidingWindows',
'Sessions',
| ]
# TODO(ccy): revisit naming and semantics once Java Apache Beam finalizes their
# behavior.
class TimestampCombiner(object):
"""Determines how output timestamps of grouping operations are assigned."""
OUTPUT_AT_EOW = beam_runner_api_pb2.OutputTime.END_OF_WINDOW
OUTPUT_AT_EARLIEST = beam_runner_api_pb2.Output... |
karaambaa/RGB-LED-Server | server.py | Python | apache-2.0 | 15,826 | 0.006824 | #!/usr/bin/env python
# import all needed libraries
import sys
import time
import sockjs.tornado
from tornado import web, ioloop
from sockjs.tornado import SockJSRouter, SockJSConnection
import pigpio
import subprocess
import os
import signal
from thread import start_new_thread
import random
import colorsys
import pya... | number fudging to make it look better
# here - probably want to avoid | high values of
# all because it will be white
# (Emphasise/Reduce bass, mids, treble)
l[i] *= float(equalizer[i])
l[i] = (l[i] * 256) - 1
# Use new val if > previous max
if l[i] > self.max[i]:
self.max[... |
fredmorcos/attic | projects/plantmaker/plantmaker-main/src/benchmark/evaluatorperf.py | Python | isc | 3,570 | 0.020728 | from time import time
from benchmark import Benchmark
from optimizer.optimizer import Optimizer
from optimizer.simulator import Simulator
from optimizer.evaluator import Evaluator
from extra.printer import pprint, BLUE
class EvaluatorPerf(Benchmark):
def __init__(self, plant, orderList, testNumber):
Benchmark.__... | ate(schedules[0])
t = time() - t
self.addCairoPlotTime(t)
self.addGnuPlotTime(i, t)
i | += 1
class EvaluatorOrdersPerf(EvaluatorPerf):
def __init__(self, plant, orderList, testNumber):
EvaluatorPerf.__init__(self, plant, orderList, testNumber)
self.testName = "NumberOfOrders"
self.startValue = 2
def bench(self):
orders = self.orderList.orders[:]
self.orderList.orders = []
... |
casetext/flask-http-forwarding | setup.py | Python | mit | 1,109 | 0.000902 | # -*- coding: utf-8 -*-
import os
from setuptools import setup, find_packages
EXCLUDE_FROM_PACKAGES = ['test_*',]
VERSION = "1.1.0"
INSTALL_REQUIRES = [
'requests',
'Flask'
]
TESTS_REQUIRE = [
'nose',
'httpretty'
]
setup(
name='Flask-HTTP-Forwarding',
version=VERSION,
url='http://www.gi... |
license='MIT',
packages=find_packages(exclude=EXCLUDE_FROM_PACKA | GES),
include_package_data=True,
install_requires=INSTALL_REQUIRES,
tests_require=TESTS_REQUIRE,
test_suite="nose.collector",
platforms='any',
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
... |
cetinkaya/pastefromhtml | htmlcdparser.py | Python | gpl-3.0 | 19,903 | 0.006079 | # Copyright 2014 Ahmet Cetinkaya
# This file is part of pastefromhtml.
# pastefromhtml 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.... | f.inside_tag == "td" or self.inside_tag == "dt" or self.inside_tag == "dd") and not (tag == "a" a | nd (self.inside_tag == "b" or self.inside_tag == "strong" or self.inside_tag == "i" or self.inside_tag == "em" or self.inside_tag == "u" or self.inside_tag == "ins" or self.inside_tag == "mark" or self.inside_tag == "strike" or self.inside_tag == "del") and self.zim_str.endswith(self.beg[self.inside_tag])):
... |
narfman0/helga-github-meta | setup.py | Python | gpl-3.0 | 1,198 | 0 | from s | etuptools import setup, find_packages
from helga_github_meta import __version__ as version
setup(
name='helga-github-meta',
version=version,
description=('Provide information for github related m | etadata'),
classifiers=[
'Development Status :: 4 - Beta',
'Topic :: Communications :: Chat :: Internet Relay Chat',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: S... |
Nocks/ReadBooks | library/admin.py | Python | mit | 199 | 0 | from django.contrib import admin
from library.models import Author | , Book, Genre, Review
admin.site.register(Author)
admin.site.register(Book)
admin.site.register(Genre)
admin.si | te.register(Review)
|
kulapard/projecteuler.net | python/problem_11.py | Python | mit | 2,670 | 0.000749 | # -*- coding: utf-8 -*-
"""
Largest product in a grid
https://projecteuler.net/problem=11
"""
GRID = """
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 | 49 13 36 65
52 70 95 | 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 1... |
testbed/testbed | testbed/db/djconfig/settings/__init__.py | Python | gpl-3.0 | 359 | 0.002786 | from split_settings.tools import optional, include
include(
'components/base.py',
'components/pagination.py',
optional('components/global.py'),
##
# Local should be after product.py because if default value has no | t
# been defi | ned in the DATABASE dictionary then it must be defined.
'components/local.py',
scope=globals()
)
|
fstagni/DIRAC | tests/Integration/Resources/Storage/Test_Resources_GFAL2StorageBase.py | Python | gpl-3.0 | 14,328 | 0.008305 | """
This integration tests will perform basic operations on a storage element, depending on which protocols are available.
It creates a local hierarchy, and then tries to upload, download, remove, get metadata etc
Potential problems:
* it might seem a good idea to simply add tests for the old srm in it. It is not :-)
... | arated list of plugin to test (defautl all)
""" % Script.scriptName)
Script.parseCommandLine()
# [SEName, <plugins>]
posArgs = Script.getPositionalArgs()
if not posArgs:
Script.showHelp()
sys.exit(1)
from DIRAC import gLogger
from DIRAC.Core.Utilities.Adler import fileAdler
from DIRAC.Core.Utilities.File impo... | DIRAC.ConfigurationSystem.Client.Helpers.Registry import getVOForGroup
#### GLOBAL VARIABLES: ################
# Name of the storage element that has to be tested
gLogger.setLevel('DEBUG')
STORAGE_NAME = posArgs[0]
# Size in bytes of the file we want to produce
FILE_SIZE = 5 * 1024 # 5kB
# base path on the storage ... |
myyyy/wechatserver | wechatclient/test/test.py | Python | mit | 1,796 | 0.001134 | # -*- coding:utf-8 -*-
import tornado.web
from wechatpy.parser import parse_message
from wechatpy import WeChatClient
TOKEN = '123456'
APPID = 'wxecb5391ec8a58227'
SECRET = 'fa32576b9daa6fd020c0104e6092196a'
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
class BaseHandler(object):
def get_client(self):
... | },
{
"type": "view",
"name": "故事",
"url": "http://wufazhuce. | com/"
},
{
"type": "view",
"name": "再见",
"url": "http://byetimes.com/"
},
{
"type": "view",
... |
EmreAtes/spack | var/spack/repos/builtin/packages/prodigal/package.py | Python | lgpl-2.1 | 1,761 | 0.000568 | ##############################################################################
# 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... | Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Prodigal(MakefilePackage):
"""Fast, reliable protein-coding gene prediction for prokaryotic
genomes."""
homepage = "https://github.com/hyat... | l"
url = "https://github.com/hyattpd/Prodigal/archive/v2.6.3.tar.gz"
version('2.6.3', '5181809fdb740e9a675cfdbb6c038466')
def install(self, spec, prefix):
make('INSTALLDIR={0}'.format(self.prefix), 'install')
def setup_environment(self, spack_env, run_env):
run_env.prepend_path('... |
wetneb/dissemin | backend/tests/test_citeproc.py | Python | agpl-3.0 | 26,785 | 0.003136 | import os
import pytest
import responses
from datetime import date
from datetime import datetime
from datetime import timedelta
from urllib.parse import parse_qs
from urllib.parse import urlparse
from django.conf import settings
from django.utils import timezone
from backend.citeproc import CiteprocError
from backe... | The list of authors must not be empty
"""
citeproc['author'] = []
with pytest.raises(CiteprocAuthorError):
self.test_class. | _get_authors(citeproc)
def test_get_authors_no_list(self, citeproc):
"""
author in citeproc must be a list
"""
del citeproc['author']
with pytest.raises(CiteprocAuthorError):
self.test_class._get_authors(citeproc)
def test_get_authors_invalid_author(self, mo... |
google/pigweed | pw_tokenizer/py/pw_tokenizer/__main__.py | Python | apache-2.0 | 687 | 0 | # Copyright 2020 The Pigweed 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
#
# https://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
# WARRANTIES OR CON... | "Runs the main function in detokenize.py."""
from pw_tokenizer import detokenize
detokenize.main()
|
DONIKAN/django | tests/migrations2/test_migrations_2/0001_initial.py | Python | bsd-3-clause | 627 | 0 | # -*- codi | ng: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("migrations", "000 | 2_second")]
operations = [
migrations.CreateModel(
"OtherAuthor",
[
("id", models.AutoField(primary_key=True)),
("name", models.CharField(max_length=255)),
("slug", models.SlugField(null=True)),
("age", models.IntegerF... |
Chronister/ananas | ananas/run.py | Python | mit | 2,535 | 0.007495 | #!/usr/bin/env python3
import os, sys, signal, argparse, configparser, traceback, time
from contextlib import closing
from ananas import PineappleBot
import ananas.default
# Add the cwd to the module search path so that we can load user bot classes
sys.path.append(os.getcwd())
bots = []
def shutdown_all(signum, fram... | ntParser(description="Pineapple comma | nd line interface.", prog="ananas")
parser.add_argument("config", help="A cfg file to read bot configuration from.")
parser.add_argument("-v", "--verbose", action="store_true", help="Log more extensive messages for e.g. debugging purposes.")
parser.add_argument("-i", "--interactive", action="store_true", he... |
alexforencich/verilog-ethernet | tb/eth_mac_1g_gmii_fifo/test_eth_mac_1g_gmii_fifo.py | Python | mit | 7,506 | 0.001066 | #!/usr/bin/env python
"""
Copyright (c) 2020 Alex Forencich
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 use, copy, modify, merg... | .rx.send(test_frame)
for test_data in test_frames:
rx_frame = await tb.axis_sink.recv()
assert rx_frame.tdata == test_data
assert | rx_frame.tuser == 0
assert tb.axis_sink.empty()
await RisingEdge(dut.rx_clk)
await RisingEdge(dut.rx_clk)
async def run_test_tx(dut, payload_lengths=None, payload_data=None, ifg=12, speed=1000e6):
tb = TB(dut, speed)
tb.gmii_phy.rx.ifg = ifg
tb.dut.ifg_delay <= ifg
tb.set_speed(speed... |
abhishekpathak/recommendation-system | recommender/server/settings/celery_conf.py | Python | mit | 695 | 0.001439 | # -*- coding: utf-8 -*-
from celery import Celery
f | rom server import config
""" Celery configuration module.
"""
def make_celery(app):
""" Flask integration with celery. Taken from
http://flask.pocoo.org/docs/0.12/patterns/celery/
"""
celery = Celery(app.import_name, backend=config.CELERY_RESULT_BACKEND,
broker=config.CELERY_BROK... | True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
return celery
|
mercycorps/TolaTables | silo/migrations/0030_auto_20170915_0828.py | Python | gpl-2.0 | 1,103 | 0.00272 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-09-15 15:28
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('silo', '0029_auto_20170915_0810'),
]
opera | tions = [
migrations.RemoveField(
model_name='silo',
name='workflowlevel1',
),
migrations.AddField(
model_name='silo',
name='workflowlevel1',
field=models.ManyToManyField(blank=True, null=True, to='silo.WorkflowLevel1'),
),
... | (blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='silo.WorkflowLevel1'),
),
migrations.AlterField(
model_name='workflowlevel2',
name='workflowlevel1',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='silo.WorkflowLevel1')... |
synergeticsedx/deployment-wipro | common/djangoapps/edxmako/shortcuts.py | Python | agpl-3.0 | 7,383 | 0.00149 | # Copyright (c) 2008 Mikeal Rogers
#
# 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... | y given named marketing links are configured.
"""
return any(is_marketing_link_set(name) for name in names)
def is_marketing_link_set(name):
"""
Returns a boolean if a given named marketing link is configured.
"""
enable_mktg_site = configuration_helpers.get_value(
'ENABLE_MKTG_SITE'... | ble_mktg_site:
return name in marketing_urls
else:
return name in settings.MKTG_URL_LINK_MAP
def marketing_link_context_processor(request):
"""
A django context processor to give templates access to marketing URLs
Returns a dict whose keys are the marketing link names usable with the
... |
lymingtonprecision/maat | ansible/name_generator.py | Python | mit | 1,321 | 0.004542 | import random
import re
import vsphere_inventory as vsphere
from os.path import join, dirname
try:
import json
except ImportError:
import simplejson as json
def readNamesFrom(filepath):
with open(filepath) as f:
return f.readlines()
def randomName(lefts, rights):
left = random.choice(lefts).... |
def nodeExists(knownNames, name):
matches = [n for n in knownNames if re.match(name + '(\.|$)', n)]
return len(matches) > 0
def generateName(knownNames):
leftSides = readNamesFrom(join(dirname(__file__), 'names', 'lefts.txt'))
rightSides = readNamesFrom(join(dirname(__file__), 'names', 'rights.txt'))... | generate a new, unique, name after 10 attempts')
exit(2)
if __name__ == '__main__':
parser = vsphere.argparser()
args = parser.parse_args()
vs = vsphere.vsphereConnect(args.server, args.user, args.password)
vimSession = vsphere.vimLogin(vs)
vms = vsphere.vmsAtPath(vs, vimSession, args.pat... |
esdalmaijer/PyGaze | pygaze/libsound.py | Python | gpl-3.0 | 1,025 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of PyGaze - the open-source toolbox for eye tracking
#
# PyGaze is a Python module for easily creating gaze contingent experiments
# or other software (as well as non-gaze | contingent experiments/software)
# Copyright (C) 2012-2013 Edwin S. Dalmaijer
#
# 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, ei | ther 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 General Public License f... |
yossisolomon/assessing-mininet | matlab-to-python.py | Python | gpl-2.0 | 7,459 | 0.024668 | # Autogenerated with SMOP version 0.23
# main.py ../../assessing-mininet/MATLAB/load_function.m ../../assessing-mininet/MATLAB/process_complete_test_set.m ../../assessing-mininet/MATLAB/process_single_testfile.m ../../assessing-mininet/MATLAB/ProcessAllLogsMain.m
from __future__ import division
from numpy import arang... | i > 1):
pktloss[jj]=pktloss[jj] + matrix[ii] - matrix[ii - 1] - 1
jitter[jj]=mean(cat(jitter[jj],(t_conv[ii] - t_conv[ii - 1])))
bitrate=bitrate / 125000
return_matrix=matlabarray(cat(bitrate.T,delay.T,jitter.T,pktloss.T))
subplot(2,2,1)
bitrate_u=copy(bitrate)
plot(a... | bitrate_u[1:jj - 1],'-')
title('Throughput')
xlabel('time [s]')
ylabel('[Mbps]')
axis(cat(0,max(t_conv),0,round_(max(bitrate_u) * 1.125)))
grid('on')
subplot(2,2,2)
plot(arange(0,len(delay) - 1),delay,'-')
title('Delay')
xlabel('time [s]')
ylabel('[ms]')
axis(cat(0,max(t_conv... |
dknlght/dkodi | src/script.module.resolveurl/lib/resolveurl/plugins/oogly.py | Python | gpl-2.0 | 1,391 | 0.001438 | """
Plugin for ResolveURL
Copyright (C) 2020 gujal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the Licens | e, 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 General Public License for more details.
You should have received a copy of the GNU ... | not, see <http://www.gnu.org/licenses/>.
"""
from resolveurl.plugins.__resolve_generic__ import ResolveGeneric
from resolveurl.plugins.lib import helpers
class OoglyResolver(ResolveGeneric):
name = "oogly.io"
domains = ['oogly.io']
pattern = r'(?://|\.)(oogly\.io)/(?:embed-)?([0-9a-zA-Z]+)'
def get... |
hidat/audio_pipeline | audio_pipeline/util/format/Vorbis.py | Python | mit | 6,254 | 0.003997 | from audio_pipeline.util import Tag
import re
from audio_pipeline.util import Exceptions
class BaseTag(Tag.Tag):
def extract(self):
super().extract()
if self._value is not None:
self._value = self._value[0]
def set(self, value=Tag.CurrentTag):
if value is not Tag.CurrentT... | ag(name | , name, tags)
if not tag.value:
serialization_name = re.sub("\s", "_", name)
under_tag = BaseTag(name, serialization_name, tags)
tag.value = under_tag.value
tag.save()
return tag
|
cloudiirain/onigiri | onigiri/views.py | Python | gpl-3.0 | 235 | 0.008511 | from django.http impo | rt Http404
from django.shortcuts import render
from directory.forms import SearchForm
def home(request):
searchform = SearchForm()
return render(request, 'onigiri | /index.html', {'searchform' : searchform})
|
lumiere-lighting/lumiere-node-raspberry-pi | lumiere.old.py | Python | mit | 2,222 | 0.011701 | #!/usr/bin/env python
from raspledstrip.ledstrip import *
from raspledstrip.animation import *
from raspledstrip.color import Color
import requests
import json
import time
import sys
import traceback
# Things that should be configurable
ledCount = 32 * 5
api = 'http://lumiere.lighting/'
waitTime = 6
class Lumiere:
... | elf.current['colors'][x % length]))
for li, l in enumerate(ledArray):
self.ledArray.append(Color(l[0], l[1], l[2]))
def queryLights(self):
"""
Make request to API.
"""
r = requests.get('%sapi/colors' % (self.base_url))
self.current = r.json()
# Only update if new record
if se... |
def hex_to_rgb(self, value):
"""
Turns hex value to RGB tuple.
"""
value = value.lstrip('#')
lv = len(value)
return tuple(int(value[i:i+lv/3], 16) for i in range(0, lv, lv/3))
if __name__ == '__main__':
lumiere = Lumiere()
lumiere.listen()
|
hydroshare/hydroshare | hs_script_resource/tests/test_script_resource.py | Python | bsd-3-clause | 7,034 | 0.004265 |
from django.test import TestCase, TransactionTestCase
from django.contrib.auth.models import Group, User
from django.http import HttpRequest, QueryDict
from hs_core.hydroshare import resource
from hs_core import hydroshare
from hs_script_resource.models import ScriptSpecificMetadata, ScriptResource
from hs_script_re... | ment_name="ScriptSpecificMetadata",
request=request)
self.assertTrue(data["is_valid"])
request.POST = None
data = script_metadata_pre_update_handl | er(sender=ScriptResource,
element_name="ScriptSpecificMetadata",
request=request)
self.assertFalse(data["is_valid"])
def test_bulk_metadata_update(self):
# here we are testing the update() method of... |
bbglab/adventofcode | 2017/iker/day25.py | Python | mit | 7,429 | 0.002692 | """
--- Day 25: The Halting Problem ---
Following the twisty passageways deeper and deeper into the CPU, you finally reach the core of the computer. Here, in the expansive central chamber, you find a grand apparatus that fills the entire room, suspended nanometers above your head.
You had always imagined CPUs to be ... | containing rules about what to do based on the current value under the cursor.
Each slot on the tape has two possible values: 0 (the starting value for all slots) an | d 1. Based on whether the cursor is pointing at a 0 or a 1, the current state says what value to write at the current position of the cursor, whether to move the cursor left or right one slot, and which state to use next.
For example, suppose you found the following blueprint:
Begin in state A.
Perform a diagnostic c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.