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 |
|---|---|---|---|---|---|---|---|---|
tanglei528/horizon | openstack_dashboard/test/api_tests/lbaas_tests.py | Python | apache-2.0 | 16,445 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013, Big Switch Networks, 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... | nection_limit'],
'admin_state_up': vip1['admin_state_up']
}
neutronclient.create_vip({'vip': vipform_data}).AndReturn(vipform_data)
self.mox.ReplayAll()
form_data = dict(vipform_data)
form_data['address'] = ""
ret_val = api.lbaas.... | test_vip_list(self):
vips = {'vips': [{'id': 'abcdef-c3eb-4fee-9763-12de3338041e',
'address': '10.0.0.100',
'name': 'vip1name',
'description': 'vip1description',
'subnet_id': '12381d38-c3eb-4fee-9763-12de333... |
nevil-brownlee/pypy-libtrace | doc/examples/copy-icmp6.py | Python | gpl-3.0 | 961 | 0.004162 |
# test-icmp6.py: count types of icmp6 packets
# Copyright (C) 2016, Nevil Brownlee, U Auckland | CAIDA | Wand
from plt_testing import *
from array import *
icmp_info = {} # Empty dictionary
t = get_example_trace('icmp6-sample.pcap')
out_uri = 'pcapfile:icmp6-out.pcap'
of = plt.output_trace(out_uri)
of.start_outpu... | continue
it = icmp6.type
if it in icmp_info:
icmp_info[it] += 1
else:
icmp_info[it] = 1
if icmp_info[it] <= 4:
of.write_packet(pk | t)
t.close()
of.close_output()
print "%d packets examined\n" % (n)
print "icmp6 types = ",
for type in sorted(icmp_info):
print "%d: %d " % (type, icmp_info[type]),
print
|
SnowRomance/CMDB | app/migrations/0007_auto_20161228_1021.py | Python | gpl-3.0 | 869 | 0.001151 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-12-28 02:21
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0006_auto_20161228_1016'),
]
operations = [
| migrations.AlterField(
model_name='hostrequest',
name='lease_time',
field=models.IntegerField(default=30),
),
migrations.A | lterField(
model_name='idc',
name='create_time',
field=models.DateField(default=datetime.datetime(2016, 12, 28, 10, 21, 52, 541000), verbose_name='\u521b\u5efa\u65f6\u95f4'),
),
migrations.AlterField(
model_name='lease',
name='lease_time',
... |
NetASM/NetASM-python | netasm/netasm/core/optimize.py | Python | gpl-2.0 | 2,688 | 0.001488 | # ################################################################################
# ##
# ## https://github.com/NetASM/NetASM-python
# ##
# ## File:
# ## optimize.py
# ##
# ## Project:
# ## NetASM: A Network Assembly Language for Programmable Dataplanes
# ##
# ## Author:
# ## Muhammad Shahbaz
#... | append(optimize_Code(_code))
instruction.codes = codes
elif isinstance(instruction, I.ATM):
instruction.code = optimize_Code(instruction.code)
elif isinstance(instruction, I.SEQ):
instruction.code = optimize_Code(inst | ruction.code)
return _optimize_Code(code)
def optimize_Policy(policy):
policy.code = optimize_Code(policy.code)
return policy
@time_usage
def optimize_Policy__time_usage(policy):
return optimize_Policy(policy) |
smpss91341/2016springcd_aG8 | users/a/g8/setup.py | Python | agpl-3.0 | 297 | 0.003367 | from setuptools import setu | p
setup(name='KMOL 2016 project',
version='1.0',
description='OpenShift App',
author='KMOL',
author_email='course@mde.tw',
url='https://www.python.org/community/sigs/current/distutils-sig',
| install_requires=['Flask>=0.10.1'],
)
|
elianerpereira/gtg | GTG/tests/test_interruptible.py | Python | gpl-3.0 | 2,149 | 0.000465 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Getting Things GNOME! - a personal organizer for the GNOME desktop
# Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau
#
# This program is free software: you can redistribute it and/or modify it under
# t... | -------------------------------
""" Tests for interrupting cooperative threads """
from threading import Thread, Event
import time
import un | ittest
from GTG.tools.interruptible import interruptible, _cancellation_point
class TestInterruptible(unittest.TestCase):
""" Tests for interrupting cooperative threads """
def test_interruptible_decorator(self):
""" Tests for the @interruptible decorator. """
self.quit_condition = False
... |
opennode/nodeconductor | waldur_core/users/migrations/0001_squashed_0004.py | Python | mit | 3,908 | 0.005885 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.utils.timezone
import model_utils.fields
from django.conf import settings
from django.db import migrations, models
import waldur_core.core.fields
import waldur_core.structure.models
class Migration(migrations.Migration):
replaces = [... | ',
max_length=50)),
('created_by',
models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+',
to=settings.AUTH_USER_MODEL)),
('customer', mod... | omer', verbose_name='organization')),
('project', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,
related_name='invitations', to='structure.Project')),
],
options={
'abstract': Fal... |
cmos3511/cmos_linux | python/op/op_site/proj_checker/views.py | Python | gpl-3.0 | 442 | 0.004525 | from rest_framework import generics
from .models import Proj
from .serializers import ProjSerializer
| # Create your views here.
class ProjList(generics.ListCreateAPIView):
"""be report project list"""
queryset = Proj.objects.all()
serializer_class = ProjSerializer
class ProjDetail(generics.RetrieveUpdateDestroyAPIView):
"""be report project detail"""
queryset = Proj.objects.all()
serialize | r_class = ProjSerializer
|
zlsa/io_object_mu | import_mu.py | Python | gpl-2.0 | 13,186 | 0.003337 | # vim:ts=4:et
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 your option) any later version.
#
# This prog... | Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# <pep8 compliant>
from struct import unpack
import os.path
from math import pi, sqrt
import bpy
from bpy_extras.object_utils import object_data_add
from mathutils import Vector,Matrix,Quaternion
from .mu import MuEnum, Mu, MuColliderMesh, MuCo | lliderSphere, MuColliderCapsule
from .mu import MuColliderBox, MuColliderWheel
from .shader import make_shader
from . import collider, properties
def create_uvs(mu, uvs, mesh, name):
uvlay = mesh.uv_textures.new(name)
uvloop = mesh.uv_layers[name]
for i, uvl in enumerate(uvloop.data):
v = mesh.loop... |
mupi/tecsaladeaula | core/tests/test_views.py | Python | agpl-3.0 | 13,951 | 0.00423 | # -*- coding: utf-8 -*-
import pytest
from model_mommy import mommy
from conftest import create_user
from core.models import Class, Course
@pytest.mark.django_db
def test_lesson(admin_client):
lesson = mommy.make('Lesson', slug='lesson', status='published')
response = admin_client.get('/course/' + lesson.cou... | ofessor_username='coordinator_professor', role='coordinator')
assistant_professor = assign_professor_to_course(course, new_professor_username='assistant_professor',
role='assistant')
klass = mommy.make('Class', name='Old class name', course=course, assistan... | ass.id) + '/',
{'name': 'New class name', 'assistant': assistant_professor.id})
# A página redireciona para outro lugar em caso de sucesso
assert response.status_code == 302
changed_class = Class.objects.get(id=klass.id)
assert changed_class.name == 'New class name'
@pyte... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247971765/apt_pkg/Cdrom.py | Python | gpl-2.0 | 1,751 | 0.006853 | # encoding: utf-8
# module apt_pkg
# from /usr/lib/python3/dist-packages/apt_pkg.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
"""
Classes and functions wrapping the apt-pkg library.
The apt_pkg module provides several classes and functions for accessing
the functionality provided by the apt-pkg library. Typica... |
class Cdrom(object):
"""
Cdrom()
Cdrom objects can be used to identify Debian installation media and to
add them to /etc/apt/sources.list.
"""
def add(self, progress): # real signature unknown; restored from __doc__
| """
add(progress: apt_pkg.CdromProgress) -> bool
Add the given CD-ROM to the sources.list. Return True on success;
raise an error on failure or return False.
"""
return False
def ident(self, progress): # real signature unknown; restored from __doc__
"... |
apsarath/pyNN | model/crl/deepcorrnet2.py | Python | apache-2.0 | 24,479 | 0.007394 | __author__ = 'Sarath'
from pyNN import *
import time
from pyNN.optimization.optimization import *
from pyNN.util.Initializer import *
import pickle
class DeepCorrNet2(object):
def init(self, numpy_rng, theano_rng=None, l_rate=0.01, optimization="sgd", tied=False, n_visible_left=None, n_visible_right=None, n_hidd... | b_prime_right3, n_hidden2)
self.optimizer.register_variable("b_prime_right3",1,n_hidden2)
if input_left is None:
sel | f.x_left = T.matrix(name='x_left')
else:
self.x_left = input_left
if input_right is None:
self.x_right = T.matrix(name='x_right')
else:
self.x_right = input_right
if tied:
self.params = [self.W_left, self.W_right, self.b_left, self.b_ri... |
vasily-v-ryabov/pywinauto | pywinauto/tests/miscvalues.py | Python | bsd-3-clause | 4,700 | 0.001064 | # GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or with... | the distribution.
#
# * Neither the name of pywinauto nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMP... | NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SU... |
drallensmith/neat-python | neat/reporting.py | Python | bsd-3-clause | 5,924 | 0.002363 | """
Makes possible reporter classes,
which are triggered on particular events and may provide information to the user,
may do something else such as checkpointing, or may do both.
"""
from __future__ import division, print_function
import time
from neat.math_util import mean, stdev
from neat.six_util import itervalue... | set):
ng = len(population)
ns = len(species_set.species)
if self.show_species_detail:
print('Population of {0:d} members in {1:d} species:'.format(ng, ns))
sids = list(iterkeys(species_set.species))
sids.sort()
print(" ID age size fitness ad... | a = self.generation - s.created
n = len(s.members)
f = "--" if s.fitness is None else "{:.1f}".format(s.fitness)
af = "--" if s.adjusted_fitness is None else "{:.3f}".format(s.adjusted_fitness)
st = self.generation - s.last_improved
... |
tuwiendsg/MELA | MELA-Extensions/MELA-ComplexCostEvaluationService/tests/mela-clients/emulateCost.py | Python | apache-2.0 | 719 | 0.044506 | import urllib, urllib2, sys, httplib
url = "/MELA/REST_WS"
#HOST_IP="128.130.172.191:8180"
newName="EventProcessingTopology_STRATEGY_MELA_COS | T_RECOMMENDATION_EFFICIENCY_Larger_VMs"
HOST_IP="localhost:8480"
if __name__=='__main__':
connection = httplib.HTTPConnection(HOST_IP)
description_file = open("./20hstruct_LAST_ADDED_LARGER_VMS.xml", "r")
body_content = description_file.read()
headers={
| 'Content-Type':'application/xml; charset=utf-8',
'Accept':'application/json, multipart/related'
}
connection.request('PUT', url+'/service/emulate/'+newName, body=body_content,headers=headers,)
result = connection.getresponse()
print result.read()
|
rabipanda/tensorflow | tensorflow/contrib/tpu/python/ops/tpu_ops.py | Python | apache-2.0 | 3,909 | 0.005628 | # Copyright 2017 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... | EED_DTYPES:
raise TypeError(
"{} is not a supported TPU infeed type. Supported types are: "
"{}".format(dtype, list(_SUPPORTED_INFEED_DTYPES)))
return gen_tpu_ops.infeed_dequeue_tuple(dtypes, shapes, name=name)
# pylint: enable=redefined-outer-name
else:
# We have already built ... | t need this
pass
|
pprett/statsmodels | examples/tsa/ex_dates.py | Python | bsd-3-clause | 1,296 | 0.001543 | """
Using dates with timeseries models
"""
import statsmodels.api as sm
import numpy as np
import pandas
# Getting started
# ---------------
data = sm.datasets.sunspots.load()
# Right now an annual date series must be datetimes at the end of the year.
from datetime import datetime
dates = sm.tsa.datetools.dates_fro... | ut-of-samp | le prediction
pred = pandas_ar_res.predict(start='2005', end='2015')
print pred
# Using explicit dates
# --------------------
ar_model = sm.tsa.AR(data.endog, dates=dates, freq='A')
ar_res = ar_model.fit(maxlag=9, method='mle', disp=-1)
pred = ar_res.predict(start='2005', end='2015')
print pred
# This just returns a... |
shawnadelic/shuup | shuup/admin/modules/manufacturers/views/list.py | Python | agpl-3.0 | 872 | 0 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django.utils.translation impor... | ws import PicotableListView
from shuup.core.models import Manufacturer
class Manufa | cturerListView(PicotableListView):
model = Manufacturer
default_columns = [
Column(
"name",
_(u"Name"),
sort_field="name",
display="name",
filter_config=TextFilter(
filter_field="name",
placeholder=_("Filter by n... |
alphagov/notifications-api | migrations/versions/0133_set_services_sms_prefix.py | Python | mit | 1,045 | 0 | import os
from app import config
"""
Revision ID: 0133_set_services_sms_prefix
Revises: 0132_add_sms_prefix_setting
Create Date: 2017-11-03 15:55:35.657488
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
revision = '0133_set_services_sms_prefix'
down_revision = '0132_add... | rvices set prefix_sms = False
where id i | n (
select service_id from service_sms_senders
where is_default = True and sms_sender != '{}'
)
""".format(default_sms_sender))
def downgrade():
op.execute("""
UPDATE services set prefix_sms = null
""")
|
BontaVlad/ExpirationDate | expirationDate/persons/constants.py | Python | mit | 599 | 0 | from django.utils.translation import ugettext_lazy as _
class PersonGender():
NOT_SPECIFIED = 0
MALE = 1
FEMALE = 2
GENDER_OPTIONS = (
| (NOT_SPECIFIED, _('Not specified')),
(MALE, _('Male')),
(FEMALE, _('Female')),
)
class PersonReligion():
NOT_SPECIFIED = 0
CHRISTIANITY = 1
ISLAM = 2
HINDUISM = 3
BUDDHISM = 4
RELIGION_OPTION | S = (
(NOT_SPECIFIED, _('Not specified')),
(CHRISTIANITY, _('Christianity')),
(ISLAM, _('Islam')),
(HINDUISM, _('Hinduism')),
(BUDDHISM, _('Buddhism')),
)
|
ContextLab/hypertools | examples/chemtrails.py | Python | mit | 575 | 0 | # -*- coding: utf-8 -*-
"""
============ | =================
Chemtrails
=============================
The past trajectory of an animated plot can be visualized with the chemtrails
argument. This displays a low | opacity version of the trace behind the
current points being plotted. This can be used in conjunction with the
precog argument to plot a low-opacity trace of the entire timeseries.
"""
# Code source: Andrew Heusser
# License: MIT
# import
import hypertools as hyp
# load example data
geo = hyp.load('weights_avg')
#... |
jiangzhuo/kbengine | kbe/src/lib/python/Lib/test/test_codecmaps_tw.py | Python | lgpl-3.0 | 831 | 0.00361 | #
# test_codecmaps_tw.py
# Codec mapping tests | for ROC encodings
#
from test import support
from test import multibytecodec_support
import unittest
class TestBIG5Map(multibytecodec_support.TestBase_Mapping,
| unittest.TestCase):
encoding = 'big5'
mapfileurl = 'http://www.unicode.org/Public/MAPPINGS/OBSOLETE/' \
'EASTASIA/OTHER/BIG5.TXT'
class TestCP950Map(multibytecodec_support.TestBase_Mapping,
unittest.TestCase):
encoding = 'cp950'
mapfileurl = 'http://www.unic... |
singer-io/singer-python | tests/test_statediff.py | Python | apache-2.0 | 2,807 | 0.002494 | import unittest
import singer.statediff as statediff
from singer.statediff import Add, Remove, Change
class TestPaths(unittest.TestCase):
def test_simple_dict(self):
self.assertEqual(
[(('a',), 1),
(('b',), 2)],
statediff.paths({'a': 1, 'b': 2}))
def test_nested_... | self.assertEqual(
[Add(('a',), 1)],
statediff.diff(None, {'a': 1}))
def test_null_input_for_new(self):
self.assertEqual(
[Remove(('a',), 1)],
statediff.diff({'a': 1}, None))
def test_null_input_for_both(self):
self.assertEqual([], statediff.... | Change(('b',), None, 2)],
statediff.diff({'a': 1, 'b': None},
{'a': None, 'b': 2}))
|
wjo1212/aliyun-log-python-sdk | aliyun/log/logclient_core.py | Python | mit | 6,959 | 0.003592 | import six, json
from .logclient_operator import list_more
from .logexception import LogException
from .pluralize import pluralize
from .common_response import *
DEFAULT_MAX_LIST_PAGING_SIZE = 500
def create_entity(entity_name, root_resource=None):
def fn(self, project, detail):
""" Create {en... |
if hasattr(detail, 'to_json'):
detail = detail.to_json()
body_str = six.b(json.dumps(detail))
elif isinstance(detail, six.binary_type):
body_str = detail
elif isinstance | (detail, six.text_type):
body_str = detail.encode('utf8')
else:
body_str = six.b(json.dumps(detail))
(resp, header) = self._send("POST", project, body_str, resource_path, params, headers)
return GetEntityResponse(header, resp)
fn.__name__ = 'create_' + entit... |
sejust/pykit | modutil/__init__.py | Python | mit | 168 | 0 | from .modutil impo | rt (
submodules,
submodule_tree,
submodule_leaf_tree,
)
__all__ = [
"su | bmodules",
"submodule_tree",
"submodule_leaf_tree",
]
|
eResearchSA/reporting-unified | unified/apis/__init__.py | Python | apache-2.0 | 10,242 | 0.000683 | import uuid
import requests
import logging
import logging.handlers
import flask_restful
from functools import wraps
from flask import request
from flask_cors import CORS
from flask_restful import Resource, reqparse
from sqlalchemy.orm.relationships import RelationshipProperty
from .. import db, app
from ..models im... | ssion.split(".", 2)
column | = getattr(model, key, None)
if isinstance(column.property, RelationshipProperty):
column = getattr(model, key + "_id", None)
if op == "in":
query_filter = column.in_(value.split(","))
else:
attr = None
for candidate in ["%s", "%s_", "__%s__"]:
if hasattr(column, c... |
thopiekar/Uranium | UM/Scene/SceneNodeDecorator.py | Python | lgpl-3.0 | 934 | 0.009636 | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
## The point of a SceneNodeDecorator is that it can be added to a SceneNode, where it then provides decorations
# Decorations are functions of a SceneNodeDecorator that can be called (except for function | s already defined
# in SceneNodeDecorator).
# \sa SceneNode
class SceneNodeDecor | ator:
def __init__(self, node = None):
super().__init__()
self._node = node
def setNode(self, node):
self._node = node
def getNode(self):
return self._node
## Clear all data associated with this decorator. This will be called before the decorator is removed
... |
mozilla/addons-server | src/olympia/devhub/tests/test_views_validation.py | Python | bsd-3-clause | 22,989 | 0.000957 | import json
from copy import deepcopy
from datetime import datetime
from django.core.files.storage import default_storage as storage
from django.urls import reverse
from unittest import mock
import waffle
from pyquery import PyQuery as pq
from olympia import amo
from olympia.addons.models import Addon, AddonUser
fr... | 0
self. | client.logout()
assert self.client.head(url).status_code == 302
class TestUploadErrors(UploadMixin, TestCase):
fixtures = ('base/addon_3615', 'base/users')
def setUp(self):
super().setUp()
self.user = UserProfile.objects.get(email='regular@mozilla.com')
self.client.login(email... |
zhu913104/KMdriod | gapathplanning.py | Python | mit | 5,686 | 0.006184 | """
Visualize Genetic Algorithm to find the shortest path for travel sales problem.
Visit my tutorial website for more: https://morvanzhou.github.io/tutorials/
"""
import matplotlib.pyplot as plt
import numpy as np
START_POINT = list(input("請輸入起始點"))
PASS_POINT = input("輸入要經過的點")
PASS_POINT = PASS_POINT.split(" ")
#... | , 'color': 'red'})
plt.xlim((-0.1, 1.1))
plt.ylim((-0.1, 1.1))
plt.p | ause(0.0000000000000000000000000000001)
ga = GA(DNA_size=len(PASS_POINT), cross_rate=CROSS_RATE, mutation_rate=MUTATE_RATE, pop_size=POP_SIZE,start_point=START_POINT)
env = TravelSalesPerson(N_CITIES)
for generation in range(N_GENERATIONS):
lx, ly = ga.translateDNA(ga.pop, env.city_position)
fitness, tot... |
InUrSys/PescArt2.0 | GeneratedFiles/ui_codificadores_POT.py | Python | gpl-3.0 | 3,813 | 0.0021 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/Users/chernomirdinmacuvele/Documents/workspace/PscArt2.0.X/UserInt/ui_codificadores_POT.ui'
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
... | self.PTEComentarios.setObjectName("PTEComentarios")
self.gridLayout.addWidget(self.PTEComentarios, 3, 1, 1, 1)
self.CHBActivo = QtWidgets.QCheckBox(Form)
self.CHBActivo.setObjectName("CHBActivo")
self.gridLayout.addWidget(self.CHBActivo, 4, 1, 1, 1)
self.splitter = QtWidgets.QSpl... | e("splitter")
self.PBGuardar = QtWidgets.QPushButton(self.splitter)
self.PBGuardar.setText("")
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(":/newPrefix/Icons/002-save.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.PBGuardar.setIcon(icon)
self.PBGuardar.setObjectNa... |
bashrc/zeronet-debian | src/src/Tor/TorManager.py | Python | gpl-2.0 | 10,295 | 0.001651 | import logging
import re
import socket
import binascii
import sys
import os
import time
import gevent
import subprocess
import atexit
from Config import config
from Crypt import CryptRsa
from Site import SiteManager
from lib.PySocks import socks
from gevent.coros import RLock
from util import helper
from Debug import... | from lib.PySocks import socks
self.port = 49051
self.proxy_port = 49050
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", self.proxy_port)
if os. | path.isfile(self.tor_exe): # Already, downloaded: sync mode
self.startTor()
else: # Not downloaded yet: Async mode
gevent.spawn(self.startTor)
def startTor(self):
if sys.platform.startswith("win"):
try:
if not os.path.isf... |
ubiquitypress/rua | src/manager/admin.py | Python | gpl-2.0 | 496 | 0 | from django.contrib import admin
from .models import (
Group,
GroupMembership,
)
class GroupAdm | in(admin.ModelAdmin):
list_display = ('name', 'group_type', 'active', 'sequence')
list_filter = ('active',)
search_fields = ('name',)
class GroupMembershipAdmin(admin.ModelAdmin):
list_display = ('group', 'user', 'added', 's | equence')
admin_list = [
(Group, GroupAdmin),
(GroupMembership, GroupMembershipAdmin),
]
[admin.site.register(*t) for t in admin_list]
|
thinkopensolutions/odoo-saas-tools | saas_portal_async/__openerp__.py | Python | lgpl-3.0 | 459 | 0 | # -*- coding: utf-8 -*-
{
'name': 'SaaS Portal Asynchronous database creation',
'version': '1.0.0',
'author': 'IT-Projects LLC',
"s | upport": "apps@it-projects.info",
'website' | : "https://it-projects.info",
'license': 'GPL-3',
'category': 'SaaS',
'depends': [
'base',
'saas_portal',
'connector',
],
'installable': False,
'application': False,
'data': [
'views/wizard.xml',
],
}
|
zaneb/heat-convergence-prototype | scenarios/update_interrupt_create.py | Python | apache-2.0 | 673 | 0.001486 | def check_resource_count(expected_count):
test.assertEqual(expected_count, len(reality.all_resources()))
example_template = Template({
'A': RsrcDef({}, []),
'B': RsrcDef({'a': '4alpha'}, ['A']),
'C': RsrcDef({'a': 'foo'}, ['B']),
'D': RsrcDef({'a': 'bar'}, ['C']),
})
engine.create_stack('foo', exam... | ate)
engine.noop(1)
example_template2 = Template({
'A': | RsrcDef({}, []),
'B': RsrcDef({'a': '4alpha'}, ['A']),
'C': RsrcDef({'a': 'blarg'}, ['B']),
'D': RsrcDef({'a': 'wibble'}, ['C']),
})
engine.update_stack('foo', example_template2)
engine.call(check_resource_count, 2)
engine.noop(11)
engine.call(verify, example_template2)
|
softglow/samplecheck | samplecheck.py | Python | gpl-3.0 | 1,713 | 0.008757 | #!/usr/bin/env python3
import argparse
import struct
import sys
SPC_START_OFFSET = 0x100
SPC_RAM_SIZE = 0x10000
INST_TBL = 0x6C00
INST_ENTRY_LEN = 0x6
SAMPLE_TBL = 0x6D00
SAMPLE_ENTRY_LEN = 0x4
SAMPLE_MAX_ID = 0x4F # completely arbitrary limit
class InstrEntry (object):
srcn = None
adsr = N... | return struct.pack("<BHBH", self.srcn, self.adsr, self.gain, self.pitch_adj)
def __str__ (self):
m = "InstrEntry<srcn={0 | :02X} adsr={1:04X} gain={2:02X} pitch_adj={3:04X}"
return m.format(self.srcn, self.adsr, self.gain, self.pitch_adj)
def parse_fp (f):
ram = f.read(SPC_START_OFFSET)
ram = f.read(SPC_RAM_SIZE)
signatures = []
ptr = INST_TBL
for inst in range(0x2a):
entry = InstrEntry.dec... |
openstax/openstax-cms | pages/migrations/0006_auto_20201105_1620.py | Python | agpl-3.0 | 631 | 0.001585 | # Generated by Django 3.0.4 on 2020-11-05 22:20
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtaildocs', '0010_document_file_hash'),
('pages', '0005_auto_20201105_1414'),
]
operations = [
mi | grations.AlterField(
model_name='llphpage',
name='book_cover',
field=models.For | eignKey(blank=True, help_text='The book cover to be shown on the website.', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtaildocs.Document'),
),
]
|
hbiyik/tribler | src/tribler-core/tribler_core/modules/metadata_store/community/request.py | Python | lgpl-3.0 | 1,680 | 0.002381 | from ipv8.requestcache import RandomNumberCache
from tribler_core.utilities.unicode import hexlify
class SearchRequestCache(RandomNumberCache):
"""
This request cache keeps track of all outstanding search requests within the GigaChannelCommunity.
"""
def __init__(self, request_cache, uuid, peers):
... | pass
def process_peer_response(self, peer):
"""
Returns whether to process this response from | the given peer in the community. If the peer response has
already been processed then it is skipped. Moreover, if all the responses from the expected peers are received,
the request is removed from the request cache.
:param peer: Peer
:return: True if peer has not been processed before, ... |
euclidjda/dnn-quant | scripts/deep_mlp_model.py | Python | apache-2.0 | 7,953 | 0.020118 | # Copyright 2016 Euclidean Technologies Management LLC 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 requi... | eshape( tf.concat(self._train_mask, 0 ),
[num_unrollings, batch_size] ) ),
self._seq_lengths,seq_axis=1,batch_axis=0),axis=1)[0]
valid_mask = tf.unstack(tf.reverse_sequence(tf.transpose(
tf.reshape( tf.concat(self._valid_mask, 0),
[num_unrollings, batch_s | ize] ) ),
self._seq_lengths,seq_axis=1,batch_axis=0),axis=1)[0]
train_loss = tf.multiply(agg_loss, train_mask)
valid_loss = tf.multiply(agg_loss, valid_mask)
self._loss = self._train_loss = train_loss
self._valid_loss = valid_loss
self._train_evals = tf.reduce_sum( train_mask )... |
metacloud/molecule | test/unit/model/v2/test_schema.py | Python | mit | 1,235 | 0 | # Copyright (c) 2015-2018 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software withou | t restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# T | he above copyright notice and this permission notice shall be included 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... |
jittat/ku-eng-direct-admission | application/views/__init__.py | Python | agpl-3.0 | 25 | 0 | from | form_views import | *
|
task123/AutoTT | scriptsForTesting/steeringTest.py | Python | mit | 823 | 0.001215 | import TCP
import Steering
import Motor
import time
"""
add
print "right speed: " + str(right_speed)
print "left speed: " + str(left_speed)
under
def receive_message(self, type, message):
if (type == "Gyro" | and self.stop == False):
and comment out
self.motors.set_right_speed(right_speed)
self.motors.set_left_speed(left_speed)
too test with driving the Mo | tor class
"""
autoTTCommunication = TCP.AutoTTCommunication(12345)
trip_meter = Motor.TripMeter()
motors = Motor.Motor(trip_meter)
steering = Steering.SteeringWithIOSGyro(motors)
autoTTCommunication.gyro_recv = steering
autoTTCommunication.stop_cont_recv = steering
autoTTCommunication.send_message("Gyro", "0.2")
time... |
richardtran415/pymatgen | pymatgen/transformations/advanced_transformations.py | Python | mit | 88,505 | 0.001955 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module implements more advanced transformations.
"""
import logging
import math
import warnings
from fractions import Fraction
from itertools import groupby, product
from math import gcd
from string im... | ict,
charge_balance_species=None,
order=True,
):
"""
Performs multiple fractional substitutions on a transmuter.
Args:
sp_to_replace: species to be replaced
r_fraction: fraction of that specie to replace
substitution_dict: dictionary of th... | "V", "Cr", "Ta", "N", "Nb"],
5: ["Ru", "W", "Mn"]
}
The number is the charge used for each of the list of elements
(an element can be present in multiple lists)
charge_balance_species: If specified, will balance the charge on
th... |
Learn-Android-app/buck | src/com/facebook/buck/json/buck_test.py | Python | apache-2.0 | 11,264 | 0.00071 | from buck import format_watchman_query_params, glob_internal, LazyBuildEnvPartial
from buck import subdir_glob, BuildFileContext
from pathlib import Path, PurePosixPath, PureWindowsPath
import os
import shutil
import tempfile
import unittest
class FakePathMixin(object):
def glob(self, pattern):
return sel... | s; it's hard to add more without
# changing that class. So we use a wrapper function to diddle with
# F | akePath's members.
result = fake_path_class(path)
result.glob_results = {}
for pattern, paths in glob_results.iteritems():
result.glob_results[pattern] = [result / fake_path_class(p) for p in paths]
return result
class TestBuckPlatformBase(object):
def test_glob_includes_simple(self):
... |
cpacia/Subspace | subspace/__init__.py | Python | mit | 179 | 0.005587 | """
Subspace is a modified implementation of the | Kademlia protocol for `Twist | ed <http://twistedmatrix.com>`_.
"""
version_info = (0, 2)
version = '.'.join(map(str, version_info))
|
markofu/security_monkey | security_monkey/watchers/rds/rds_security_group.py | Python | apache-2.0 | 5,590 | 0.001073 | # Copyright 2016 Bridgewater Associates
#
# 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 appli... | dict where the keys are a tuple containing the
location of the exception and the value is the actual exception
"""
self.prep_for_slurp()
@iter_account_region(index=self.index, accounts=self.accounts, service_name='rds')
def slurp_items(**kwargs):
item_list = []
... | '] = exception_map
app.logger.debug("Checking {}/{}/{}".format(self.index,
kwargs['account_name'], kwargs['region']))
sgs = self.get_all_dbsecurity_groups(**kwargs)
if sgs:
app.logger.debug("Found {} {}".format(... |
yw-fang/readingnotes | machine-learning/Matthes-crash-course/chapt09/scripts/user_03.py | Python | apache-2.0 | 1,263 | 0.009516 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Yue-Wen FANG'
__maintainer__ = "Yue-Wen FANG"
__email__ = 'fyuewen@gmail.com'
__license__ = 'Apache License 2.0'
__creation_date__= 'Dec. 28, 2018'
"""
9-3. Users: Make a class called User . Create two attributes called first_name and last_name, and then cre... | f.gender = gender
self.age = age
self.email = email # if no email is sp | ecified, the default will be used
def describe_use(self):
print('The profile of ' + self.name + ":")
print('Gender: ', self.gender)
print('Age: ', self.age)
print('Email: ', self.email)
Tiantian_Li = User('Tiantian', 'Li', 'Male', '20', email='Li@cn')
Tiantian_Li.describe_use()
|
smallyear/linuxLearn | salt/salt/states/boto_vpc.py | Python | apache-2.0 | 30,718 | 0.002637 | # -*- coding: utf-8 -*-
'''
Manage VPCs
=================
.. versionadded:: 2015.8.0
Create and destroy VPCs. Be aware that this interacts with Amazon's services,
and so may incur charges.
This module uses ``boto``, which can be installed via package, or pip.
This module accepts explicit vpc credentials but can als... | omment'] = 'Failed to create VPC: {0}.'.format(r['error']['message'])
return ret
_describe = __salt__['boto_vpc.describe'](r['id'], region=region, key=key,
keyid=keyid, profile=profile)
ret['changes']['old'] = {'vpc': None}
ret['chang... | one, key=None, keyid=None, profile=None):
'''
Ensure VPC with passed properties is absent.
name
Name of the VPC.
tags
A list of tags. All tags must match.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
pr... |
SaschaMester/delicium | tools/chrome_proxy/integration_tests/chrome_proxy_benchmark.py | Python | bsd-3-clause | 6,825 | 0.016703 | # Copyright 2014 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.
from common.chrome_proxy_benchmark import ChromeProxyBenchmark
from integration_tests import chrome_proxy_measurements as measurements
from integration_tests... | page_set = pagesets.VideoComparePageSet
@classmethod
def Name(cls):
return 'chrome_proxy_benchmark.video.compare'
@benchmark.Enabled('desktop')
class ChromeProxyVideoFrames(benchmark.Benchmark):
"""Check for video frames similar to original video."""
tag = 'video'
test = measurements.ChromeProxyInstru... | led('desktop')
class ChromeProxyVideoAudio(benchmark.Benchmark):
"""Check that audio is similar to original video."""
tag = 'video'
test = measurements.ChromeProxyInstrumentedVideoValidation
page_set = pagesets.VideoAudioPageSet
@classmethod
def Name(cls):
return 'chrome_proxy_benchmark.video.audio'
|
ThomasMiconi/nupic.research | projects/sequence_prediction/discrete_sequences/plotPerturbExperiment.py | Python | agpl-3.0 | 3,263 | 0.005516 | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate licen | se for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# 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 Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. I... |
DrKylstein/gfxtools | nesimage.py | Python | mit | 5,828 | 0.007378 | #! /usr/bin/python3
import sys
import argparse
import itertools
from PIL import Image
if __name__ == '__main__':
argparser = argparse.ArgumentParser()
argparser.add_ar | gument('input')
argparser.add_argument('palette',type=argparse.FileType('wb'))
argparser.add_argument('pattern',type=argparse.FileType('wb'))
argparser.add_argument('name',type=argparse.FileType('wb'))
argparser.add_argument('attribute',type=argparse.FileType('wb'))
argparser.add_argument('-O','--op... | on='store_true')
args = argparser.parse_args()
image = Image.open(args.input)
palette = set()
tiles = set()
attribute_colors = []
for ay in range(15):
attribute_colors.append([])
for ax in range(16):
colors = set()
for ny in [ay*2+i fo... |
ivannotes/luigi | test/namespace_test.py | Python | apache-2.0 | 1,739 | 0.00345 | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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/license | s/LICE | NSE-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 CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the Lic... |
yoavfrancis/KeepItUp | KeepItUp/harddrive_enumerator.py | Python | mit | 1,589 | 0.003776 | import win32api
import os
import sys
import subprocess
import logging
from itertools import izip_longest
#itertools recipe
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
def harddrive_enumer... | DriveName, VolumeName) - eg. ("D:", "Samsung Station")
"""
logger = logging.getLogger("keepitup")
drive | sDetailedList = []
if sys.platform == "win32":
logger.debug("Enumerating win32 hard drives")
getDrivesProc = subprocess.Popen('wmic logicaldisk where drivetype=3 get name, VolumeName /format:list',
shell=True,
stdout=s... |
oczkers/pdeo | tests/databases/test_sql.py | Python | gpl-3.0 | 407 | 0 | #!/usr/bin/env py | thon
# -*- coding: utf-8 -*-
"""Tests for pdeo.database.sql"""
import unittest
# import responses
from pdeo.databases import sql
# if version_info[0] == 2: # utf8 for python2
# from codecs import open
class PdeoDatabaseSqlTestCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(sel... | sql.Database
|
yugangw-msft/azure-cli | src/azure-cli/azure/cli/command_modules/resource/parameters.py | Python | mit | 474 | 0.00211 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in | the project root for license information.
# --------------------------------------------------------------------------------------------
from enum import Enum
class TagUpdateOperation(str, Enum):
merge = "M | erge"
replace = "Replace"
delete = "Delete"
|
lcrees/twoq | twoq/ordering.py | Python | bsd-3-clause | 2,474 | 0 | # -*- coding: utf-8 -*-
'''twoq ordering mixins'''
from threading import local
from itertools import product, groupby
from random import choice, shuffle, sample
from twoq.support import zip_longest, imap
class RandomMixin(local):
'''random mixin'''
def choice(self):
'''random choice of/from incomi... | xt():
iterable = list(self._iterable)
shuffle(iterable)
return self._xtend(iterable)
class OrderMixin(local):
'''order mixin'''
def group(self):
'''
group incoming things, optionally using current call for key function
| '''
call_, list_ = self._call, list
with self._context():
return self._xtend(imap(
lambda x: [x[0], list_(x[1])], groupby(self._iterable, call_)
))
def grouper(self, n, fill=None):
'''
split incoming things into sequences of length `n`, us... |
deerwalk/voltdb | tests/sqlcoverage/normalizer/not-a-normalizer.py | Python | agpl-3.0 | 2,364 | 0.002538 | #!/usr/bin/env python
# This file is part of VoltDB.
# Copyright (C) 2008-2017 VoltDB Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitati... | geReport import generate_html_reports
def safecmp(x, y):
"""Calls the 'standard' safecmp function, which performs a comparison
similar to cmp, including iterating over lists, but two None values
are considered equal, and a T | ypeError is avoided when a None value
and a datetime are corresponding members of a list.
"""
return NotANormalizer.safecmp(x,y)
def normalize(table, sql):
"""Do nothing other than returning the table.
"""
return NotANormalizer.normalize(table, sql)
def compare_results(suite, seed, statemen... |
klapper/nagios-plugins-mq | check_mq_channel.py | Python | mit | 5,483 | 0.010213 | #!/usr/bin/python
import getopt
import sys
import pymqi, CMQC, CMQCFC
STATE_OK = 0
STATE_WARNING = 1
STATE_CRITICAL = 2
STATE_UNKNOWN = 3
def usage():
print """Usage: rbh_check_mq_channel_status -H <HostName> -g <QMGRName> -p <PortNumber> -a <ChannelName for connection> -t <ChannelName for test>"""
def show_hel... | echannel
"""
def exit_with_state(exit_code):
global qmgr
try:
qmgr.disconnect()
except:
pass
sys.exit(exit_code)
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "hH:g:p:a:t:", ["help", "host","qmgr=","port=","channel-name=","channel-name-conn="])
except | getopt.GetoptError, err:
print str(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
hostName=None
qmgrName=None
portNumber=1414
channelNameConn=None
channelNameTest=None
for o, a in opts:
if o in ("-h", "--help"):
show_he... |
tcstewar/opengl_texture_rendering | sparkle/main_raster.py | Python | gpl-2.0 | 3,315 | 0.00181 | import time
from PyQt4 import QtGui, QtCore, QtOpenGL
from PyQt4.QtOpenGL import QGLWidget
import OpenGL.GL as gl
import OpenGL.arrays.vbo as glvbo
import numpy as np
import raster
import slider
import draw_texture
import qt_helpers
raster_width = 1024
raster_height = 64
raster_n_neurons = 64
spikes_per_frame = 5
c... | ow, self).__init__()
# initialize the GL widget
self.widget = GLPlotWidget()
# put the window at the screen position (100, 100)
self.setGeometry(100, 100, self.widget.width, self.widget.height)
self.setCentralWidget(self.widget)
self.show()
# ... | ow the window
win = qt_helpers.create_window(TestWindow)
|
Ictp/indico | indico/tests/python/unit/util.py | Python | gpl-3.0 | 5,388 | 0.002598 | # -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; eith... | e session.
# If this changes, assign a avatar mock object here
session.user = None
def _context_request(self | ):
self._startRequest()
with self._make_app_request_context():
self._mock_session_user()
setLocale('en_GB')
yield
self._endRequest()
class IndicoTestCase(unittest.TestCase, FeatureLoadingObject):
"""
IndicoTestCase is a normal TestCase on steroids. ... |
jbassen/edx-platform | lms/djangoapps/courseware/tabs.py | Python | agpl-3.0 | 10,813 | 0.001665 | """
This module is essentially a broker to xmodule/tabs.py -- it was originally introduced to
perform some LMS-specific tab display gymnastics for the Entrance Exams feature
"""
from django.conf import settings
from django.utils.translation import ugettext as _, ugettext_noop
from courseware.access import has_access
f... | EATURES.get('ENABLE_TEXTBOOK') and parent_is_enabled
@classmethod
def items(cls, course):
| for index, textbook in enumerate(course.textbooks):
yield SingleTextbookTab(
name=textbook.title,
tab_id='textbook/{0}'.format(index),
view_name=cls.view_name,
index=index
)
class PDFTextbookTabs(TextbookTabsBase):
"""
... |
CMUSV-VisTrails/WorkflowRecommendation | vistrails/packages/persistence_exp/__init__.py | Python | bsd-3-clause | 2,337 | 0.0184 | ###############################################################################
##
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "Redistribution and use in source and binary forms, with or without
## modification, ... | names of its
## contributors may be used to endorse or promote products derived from
## this software without specific prior written permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
## THE IM... | GHT HOLDER OR
## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
## OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
##... |
probcomp/bdbcontrib | examples/satellites/build_bdbs.py | Python | apache-2.0 | 9,056 | 0.002761 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2010-2016, MIT Probabilistic Computing Project
#
# 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.apac... | = out_file_name('satellites', '-logscores.pdf')
log('writing diagnostic plot to %s' % plot_file_name)
_fig = bdbcontrib.crosscat_utils.plot_crosscat_chain_diagnostics(
bdb, 'logscore', | 'satellites_cc')
plt.savefig(plot_file_name)
final_metadata_file = out_file_name('satellites', '-meta.txt')
report(bdb_file, final_metadata_file,
echo=True, plot_file_name=plot_file_name)
snapshot()
while cur_iter_ct < num_iters:
execute('ANALYZE satellites_cc FO... |
sergiusens/snapcraft | snapcraft/internal/project_loader/grammar_processing/_part_grammar_processor.py | Python | gpl-3.0 | 4,927 | 0 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2017 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the h... | >>> processor = PartGrammarProcessor(
... plugin=plugin,
... properties={},
... project=snapcraft.project.Project(), |
... repo=repo)
>>> processor.get_build_packages()
{'foo'}
Source example:
>>> from unittest import mock
>>> import snapcraft
>>> plugin = mock.Mock()
>>> plugin.properties = {'source': [{'on amd64': 'foo'}, 'else fail']}
>>> processor = PartGrammarProcessor(
... plugin=pl... |
GoogleCloudPlatform/professional-services | examples/bq-email-exports/tests/send_email_function/test_main.py | Python | apache-2.0 | 2,421 | 0.000413 | # 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, ... | NS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unit tests for send email function"""
import os
import sys
import pytest
sys.path.append(os.path.realpath(os.path.dirname(__file__) + "../.."))
from send_email_function ... | onment variables"""
monkeypatch.setenv("SIGNED_URL", "True")
monkeypatch.setenv("FROM_EMAIL", "sender@gmail.com")
monkeypatch.setenv("TO_EMAILS", "recepient@gmail.com")
monkeypatch.setenv("EMAIL_SUBJECT", "BigQuery email export")
monkeypatch.setenv("SENDGRID_API_KEY", "SG.key")
monkeypatch.seten... |
github/codeql | python/ql/test/library-tests/taint/dataflow/test.py | Python | mit | 2,191 | 0.016431 |
def test1():
SINK(SOURCE)
def test2():
s = SOURCE
SINK(s)
def | source():
return SOURCE
def sink(arg):
SINK(arg)
def test3():
t = source()
SINK(t)
def test4():
t = SOURCE
sink(t)
def test5():
t = source()
sink(t)
def test6(cond):
if cond:
t = "Safe"
else:
t = SOURCE
if cond:
SINK(t)
def test7(cond):
if c... | E
else:
t = "Safe"
if cond:
SINK(t)
def source2(arg):
return source(arg)
def sink2(arg):
sink(arg)
def sink3(cond, arg):
if cond:
sink(arg)
def test8(cond):
t = source2()
sink2(t)
#False positive
def test9(cond):
if cond:
t = "Safe"
else:
... |
TheWeiTheTruthAndTheLight/senior-design | src/json_io.py | Python | mit | 7,324 | 0.005188 | """
json_io.py
Functions related to reading/writing/mapping json
"""
import json
import ijson
from re import sub
from datetime import datetime
from os import listdir, SEEK_END
from sys import exc_info, stdout
from random import choice, randrange
from nlp import feature
TWEET_LINK_RE = "https://t.co/(\w)+"
TWEET_HAND... | indenting. Set to false for streaming friendlier format
"""
if old_format:
with open(path, 'w') as fp:
json.dump(lst, fp, sort_keys=True, indent=4)
else:
with open(path, 'w') as fp:
for i, tweet in enumerate(lst):
js | on.dump({"text": tweet["text"], "id": tweet['id'], "media": tweet["media"], "urls": tweet["urls"]}, fp)
if i != len(lst) - 1:
fp.write('\n')
def merge_json_filenames(json_lst):
"""
Return filename encapsulating date range of passed in jsons
ex: merge_json_filnames(["path... |
demisto/content | Packs/CrowdStrikeIntel/Integrations/CrowdStrikeFalconIntel_v2/CrowdStrikeFalconIntel_v2.py | Python | mit | 23,184 | 0.002459 | import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
from datetime import datetime, timezone
from typing import Union, Any, Dict
from dateparser import parse
import urllib3
import traceback
# Disable insecure warnings
urllib3.disable_warnings()
''' GLOBAL VARIABLES '''
... |
params['filter'] = query if q | uery else self.build_filter_query(args)
return assign_params(**params)
def build_filter_query(self, args: Dict[str, str]) -> str:
"""
Builds the filter query in Falcon Query Language (FQL)
:param args: Cortex XSOAR args
:return: The query
"""
filter_query: st... |
HybridF5/tempest_debug | tempest/services/identity/v2/json/endpoints_client.py | Python | apache-2.0 | 1,870 | 0 | # Copyright 2016 Red Hat, 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, ... | }
post_body = json.dumps({'endpoint': post_body})
resp, body = self.post('/endpoints', post_body)
self.expected_success(200, resp.status)
body = json | .loads(body)
return rest_client.ResponseBody(resp, body)
def list_endpoints(self):
"""List Endpoints - Returns Endpoints."""
resp, body = self.get('/endpoints')
self.expected_success(200, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body... |
austinharris/gem5-riscv | src/arch/x86/isa/insts/general_purpose/input_output/string_io.py | Python | bsd-3-clause | 4,418 | 0 | # Copyright (c) 2007-2008 The Hewlett-Packard Development Company
# All rights r | eserved.
#
# The license below extends only to copyright in the | software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality of the software
# licensed hereunder. You may use the software subject to the license
# terms below provided t... |
panrobot/ishneECGviewer | ecgReader.py | Python | gpl-2.0 | 7,145 | 0.012596 | import sys
from datetime import datetime, timedelta
from array import array
from numpy import hsplit, asarray
class ECG:
'''Checks validity of selected .ecg file. If it is valid .ecg file creates an instance with all the data stored in .ecg file'''
def __init__(self, filename, enc='cp1250'):
'''Defaul... | teorder='little', signed=True))
#date of file creation as [dd,mm,yy]
dof = list()
for i in rang | e(0,3):
dof.append(int.from_bytes(ecgFile.read(2), byteorder='little', signed=True))
self.dateOfFileCreation = datetime(dor[2], dor[1], dor[0])
#testStart - time of test begining HH:MM:SS
testStart = list()
for i in range(0,3):
testStart.ap... |
ecreall/lagendacommun | lac/content/processes/social_applications_management/definition.py | Python | agpl-3.0 | 3,478 | 0.008051 | # Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
from dace.processdefinition.processdef import ProcessDefinition
from dace.processdefinition.activitydef import ActivityDefinition
from dace.processdefinition.gatewaydef ... | cation],
description=_("Add a social application"),
title=_("Add a social application"),
groups=[]),
| seeapplication = ActivityDefinition(contexts=[SeeApplication],
description=_("See the application"),
title=_("See the application"),
groups=[]),
editapplication = ActivityDefini... |
aluminiumgeek/goodbye-mihome | mihome.py | Python | bsd-2-clause | 4,258 | 0.001879 | import binascii
import code
import importlib
import json
import psycopg2
import readline
import socket
import struct
import sys
import time
from Crypto.Cipher import AES
from datetime import datetime
from multiprocessing import Process
from threading import Thread
import config
from plugins import sensor_ht, magnet, y... | timed out: {}:{}".format(address.decode(), port))
finally:
sock.close()
return data
def get_key():
"""Get current gateway key"""
cipher = AES.new(config.MIHOME_GATEWAY_PASSWORD, AES.MODE_CBC, IV)
encrypted = cipher.encrypt(get_store().get('gateway_token'))
return binascii.hexlify(encry... | ell = code.InteractiveConsole(vars)
shell.interact()
sys.exit()
Thread(target=web_app).start()
for app_name in config.ENABLED_APPS:
try:
app = importlib.import_module('apps.{}'.format(app_name))
except ImportError as e:
print('Could not import app "{}": ... |
nigeljonez/newpyfibot | modules/module_oraakkeli.py | Python | bsd-3-clause | 459 | 0.010893 |
import urllib
def command_oraakkeli(bot, user, channel, args):
"""Asks a question from the oracle (http://www.lintukoto.net/viihde/oraakkeli/)"""
if not args: return
args = urllib.quote_plus(args)
answer = getUrl(" | http://www.lintukoto.net/viihde/oraakkeli/index.php | ?kysymys=%s&html=0" % args).getContent()
answer = unicode(answer)
answer = answer.encode("utf-8")
return bot.say(channel, "Oraakkeli vastaa: %s" % answer)
|
nvladimus/zebrascope_targets | MultiviewRegistration/PymageJ-devel/pymagej/roi.py | Python | mit | 24,830 | 0.002416 | """
PymageJ Copyright (C) 2015 Jochem Smit
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 your option) any later version.
This program is distributed in the... | @property
def width(self):
return self.x_coords.max() - self.x_coords.min() + 1
@property
def height(self):
return self.y_coords.max() - self.y_coords.min() + 1
@property
def area(self | ):
raise NotImplementedError("Freeline area not implemented")
def __len__(self):
return len(self.x_coords)
class ROINoRoi(ROIObject):
type = 'no_roi'
@property
def area(self):
return 0
class ROIFreehand(ROIObject):
type = 'freehand'
def __init__(self, top, left, x_... |
fbrei/aind | planning/my_air_cargo_problems.py | Python | mit | 11,755 | 0.003318 | from aimacode.logic import PropKB
from aimacode.planning import Action
from aimacode.search import (
Node, Problem,
)
from aimacode.utils import expr
from lp_utils import (
FluentState, encode_state, decode_state,
)
from my_planning_graph import PlanningGraph
class AirCargoProblem(Problem):
def __init__(s... | for p in self.planes:
for c in self.cargos:
pr | econd_pos = [
expr("At({}, {})".format(c,a)),
expr("At({}, {})".format(p,a)),
]
precond_neg = []
effect_add = [
expr("In({}, {})".format(c,p)),
... |
shoopio/shoop | shuup_tests/campaigns/test_catalog_campaign_admin.py | Python | agpl-3.0 | 7,668 | 0.002347 | # This file is part of Shuup.
#
# Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
# test that admin actually saves catalog
from __future__ import unicode_literals
import d... | ews import CatalogCampaignEditView
from shuup.campaigns.models.campaigns import CatalogCampaign
from shuup.testing.factories import get_default_shop
from shuup.testing.utils import apply_request_middleware
DEFAULT_CONDITION_FORMS = [
"shuup.campaigns.admin_module.forms:ContactGroup | ConditionForm",
"shuup.campaigns.admin_module.forms:ContactConditionForm",
]
DEFAULT_FILTER_FORMS = [
"shuup.campaigns.admin_module.forms:ProductTypeFilterForm",
"shuup.campaigns.admin_module.forms:ProductFilterForm",
"shuup.campaigns.admin_module.forms:CategoryFilterForm",
]
DEFAULT_EFFECT_FORMS = [
... |
dud225/incubator-airflow | airflow/operators/pig_operator.py | Python | apache-2.0 | 1,716 | 0.001166 | import logging
import re
from airflow.hooks import PigCliHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class PigOperator(BaseOperator):
"""
Executes pig script.
:param pig: the pig latin script to be executed
:type pig: string
:param pig_cli_con... | _id: reference to the Hive database
:type pig_cli_conn_id: string
:param pigparams_jinja_translate: when True, pig params-type templating
${var} gets translated into jinja-type templating {{ var }}. Note that
you may want to use this along with the
``DAG(user_defined_macros=myargs)`` par... | rams_jinja_translate: boolean
"""
template_fields = ('pig',)
template_ext = ('.pig', '.piglatin',)
ui_color = '#f0e4ec'
@apply_defaults
def __init__(
self, pig,
pig_cli_conn_id='pig_cli_default',
pigparams_jinja_translate=False,
*args, **kwargs):... |
googleapis/python-service-control | samples/generated_samples/servicecontrol_v1_generated_service_controller_check_async.py | Python | apache-2.0 | 1,437 | 0.000696 | # -*- 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 required by applicable law or... | illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-service-control
# [START servicecontrol_v1_generated_ServiceContr | oller_Check_async]
from google.cloud import servicecontrol_v1
async def sample_check():
# Create a client
client = servicecontrol_v1.ServiceControllerAsyncClient()
# Initialize request argument(s)
request = servicecontrol_v1.CheckRequest(
)
# Make the request
response = await client.chec... |
0x00/web.py-jinja2-pyjade-bootstrap | app.py | Python | apache-2.0 | 331 | 0.036254 | import sys
sys.path.append("helper")
import web
from helper import session
web.config.debug = False
urls = (
"/", "c | ontroller.start.index | ",
"/1", "controller.start.one",
"/2", "controller.start.two",
)
app = web.application(urls, globals())
sessions = session.Sessions()
if __name__ == "__main__":
app.run()
|
rajarammallya/melange | melange/tests/unit/test_extensions.py | Python | apache-2.0 | 1,657 | 0.000604 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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/l... | License for the specific language governing permissions and limitations
# under the License.
from lxml import etree
import routes
import unittest
import webtest
from melange import tests
from melange.common import config
from melange.common import wsgi
class TestExtensions(unittest.TestCase):
def test_exten... | options, None)
test_app = webtest.TestApp(app)
response = test_app.get("/extensions.xml")
root = etree.XML(response.body)
self.assertEqual(root.tag.split('extensions')[0],
"{http://docs.openstack.org/melange}")
class Extens... |
ericjang/pyN | pyn_examples/6_AxEx_neuron.py | Python | bsd-2-clause | 496 | 0.042339 | import os,sys
parentdir = os.path.dirname(os.path.dirnam | e(os.path.abspath(__file__)))
sys.path.insert(0,parentdir)
from pyN import *
single_neuron = AdExPopulation(name='neuron', N=1)
brain = Network(populations=[single_neuro | n])
stim = [{'start':10,'stop':100,'mV':14,'neurons':[0]}]
results = brain.simulate(experiment_name='Single AdEx Neuron',T=100,dt=0.25,integration_time=30,I_ext={'neuron':stim}, save_data='../data/', properties_to_save=['v','w','psc','I_ext'])
save_plots(results,'./')
|
tokyo-jesus/wampum | user/private_views/_change_password.py | Python | gpl-3.0 | 152 | 0.013158 | # -*- coding: utf-8 -*-
from django.views.generic import FormView
class ChangePassword(FormView):
pass
chang | e_p | assword = ChangePassword.as_view() |
roshantha9/AbstractManycoreSim | src/util_scripts/ccpbased_remapping_random_params_generation.py | Python | gpl-3.0 | 2,693 | 0.026365 | import random
import numpy as np
import pprint
import sys
def generate_random_params(max_rumtime_mins = 2880, param_seed = 1234):
random.seed(param_seed)
np.random.seed(param_seed)
# duration
TIME_TAKEN_FOR_ONE_SIMULATION = 40 # minutes
# params we are concerened about
#CLUST... | rand_LATENESS_RATIO = random.choice(LATENESS_RATIO)
rand_LOAN_AMOUNT = random.choice(LOAN_AMOUNT)
perm_key = "perm_" + \
str(rand_CLUSTER_SIZE) + "_" + \
str(rand_REMAP_PERIOD) + "_" + \
... | fname_param_prefix = str(rand_CLUSTER_SIZE) + \
"_" + str(rand_REMAP_PERIOD) + \
"_" + str(rand_LOAN_AMOUNT)
if (perm_key not in list_of_patterns):
list_of_patterns[perm_key] = {
... |
graphql-python/gql | tests/test_graphqlws_exceptions.py | Python | mit | 7,525 | 0.00093 | import asyncio
from typing import List
import pytest
from gql import Client, gql
from gql.transport.exceptions import (
TransportClosed,
TransportProtocolError,
TransportQueryError,
)
from .conftest import WebSocketServerHelper
# Marking all tests in this file with the websockets marker
pytestmark = pyt... | '"payload":{{"errors":['
'{{"message":"Cannot query field \\"bloh\\" on type \\"Continent\\".",'
'"locations":[{{"line":4,"column":5}}],'
'"ex | tensions":{{"code":"INTERNAL_SERVER_ERROR"}}}}]}}}}'
)
invalid_query1_server = [invalid_query1_server_answer]
@pytest.mark.asyncio
@pytest.mark.parametrize("graphqlws_server", [invalid_query1_server], indirect=True)
@pytest.mark.parametrize("query_str", [invalid_query_str])
async def test_graphqlws_invalid_query(
... |
namhyung/uftrace | tests/t036_replay_filter_N.py | Python | gpl-2.0 | 1,056 | 0.000947 | #!/usr/bin/e | nv python
from runtest import TestBase
class TestCase(TestBase):
def __init__(self):
TestBase.__init__(self, 'namespace', lang="C++", result="""
# DURATION TID FUNCTION
[ 7102] | main() {
2.697 us [ 7102] | operator new();
0.842 us [ 7102] | ns::ns1::foo::foo();
[ ... | s::ns1::foo::bar2();
2.169 us [ 7102] | } /* ns::ns1::foo::bar1 */
1.215 us [ 7102] | free();
3.897 us [ 7102] | } /* ns::ns1::foo::bar */
1.865 us [ 7102] | operator delete();
0.274 us [ 7102] | operator new();
0.115 us [ 7102] | ns::ns2::foo::foo();
1.566 us [ 7102] | ns::ns2::f... |
amelmquist/chrono | src/demos/python/demo_particleclones.py | Python | bsd-3-clause | 5,706 | 0.015247 | #-------------------------------------------------------------------------------
# Name: demo_python_3
#
# This file shows how to create and populate the ChParticleClones object.
# Also, shows how to use POV ray for postprocessing, thanks to the
# utility functions in the unit_POSTPROCESS of Chrono::Engine.
#
#-... | /my_state")
pov_exporter.SetPictureFilebase("anim/picture")
pov_exporter.SetCamera(chrono.ChVectorD(0.2,0.3,0.5), chrono.ChVectorD(0,0,0), 35)
pov_exporter.SetLight(chrono.ChVectorD(-2,2,-1), chrono.ChColor(1.1,1.2,1.2), True)
pov_exporter.SetPictureSize(640,480)
pov_exporter.SetAmbientLight(chrono.ChColor(2,2,2))
#... | '
light_source{ <1,3,1.5> color rgb<1.1,1.1,1.1> }
Grid(0.05,0.04, rgb<0.7,0.7,0.7>, rgbt<1,1,1,1>)
''')
# Tell which physical items you want to render
pov_exporter.AddAll()
# Tell that you want to render the contacts
pov_exporter.SetShowContacts(True,
postprocess.ChPovRay.SYMBOL_VECTOR_... |
bazelbuild/rules_python | gazelle/testdata/relative_imports/package2/module4.py | Python | apache-2.0 | 40 | 0 | def function4():
| re | turn "function4"
|
intelligent-agent/redeem | tests/gcode/test_M201.py | Python | gpl-3.0 | 3,414 | 0.010838 | from __future__ import absolute_import
from .MockPrinter import MockPrinter
import mock
from random import random
class M201_Tests(MockPrinter):
def setUp(self):
self.printer.path_planner.native_planner.setAcceleration = mock.Mock()
self.printer.axis_config = self.printer.AXIS_CONFIG_XY
self.printer.sp... | "][i]
self.assertEqual(expected, result,
axis + ": expected {:.0f} but got {:.0f}".format(expected, result))
def test_gcodes_M201_CoreXY(self):
self.printer.axis_config = self.printer.AXIS_CONFIG_CORE_XY
while True: # account for remote possibility of two equal random numbers... | != test_data["values"]["Y"]:
break
self.assertEqual(
test_data["call_args"][0], test_data["call_args"][1],
"For CoreXY mechanics, X & Y values must match. But X={}, Y={} (mm/min / 3600)".format(
test_data["call_args"][0], test_data["call_args"][1]))
def test_gcodes_M201_H_be... |
Hybrid-Cloud/badam | patches_tool/aws_patch/aws_deps/libcloud/test/dns/test_google.py | Python | apache-2.0 | 7,924 | 0.000883 | # 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 ... | cts_project_name_managedZones_example_com_FILTER_ZONES(
self, method, url, body, headers):
body = self.fixtures.load('zone.json')
retu | rn (httplib.OK, body, {}, httplib.responses[httplib.OK])
if __name__ == '__main__':
sys.exit(unittest.main())
|
arnaudsj/milk | milk/supervised/knn.py | Python | mit | 1,620 | 0.006173 | # -*- coding: utf-8 -*-
# Copyright (C) 2008-2011, Luis Pedro Coelho <luis@luispedro.org>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
#
# License: MIT. See COPYING.MIT file in the milk distribution
from __future__ import division
from collections import defaultdict
import numpy as np
from .base import supervised... | se):
features = np.asanyarray(features)
labels = np.asanyarray(labels)
if copy_features:
features = features.copy()
labels = labels.copy()
features2 = np.sum(features**2, axis=1)
return kNN_model(self.k, features, features2, labels)
class kNN_model(superv... | self.labels = labels
def apply(self, features):
features = np.asanyarray(features)
diff2 = np.dot(self.features, (-2.)*features)
diff2 += self.f2
neighbours = diff2.argsort()[:self.k]
labels = self.labels[neighbours]
votes = defaultdict(int)
for L in labels:
... |
johnmcilwain/cdnetworks | api_example_python.py | Python | apache-2.0 | 5,957 | 0.008058 | # ********************************************************************************************************************************* #
# Name: api_example_python.py #
# Desc: full api example ... | # Change to your desired APIKEY (website)
TRAFFICDATA = '&fromDate=20170201&toDate=20170201&timeInterval=1' # Change to your desired graph date/time
GRAPHFILE = 'api_example_python_graph' # Change to your desired graph filename
APIENDPOINT | = 'https://openapi.cdnetworks.com/api/rest/' # Don't change
APIFORMAT = '&output=json' # Don't change
API_SUCCESS = 0 # Don't change
# Command: LOGIN : send login, receive list of service groups (logial g... |
habagat/hugot214 | LexerParser.py | Python | gpl-3.0 | 9,650 | 0.023316 | from ply import lex, yacc
class Lexer:
reserved = {
#'ikawna' : 'IF',
#'syapala' : 'ELSE',
#'akona' : 'ELSEIF',
#'kamipa' : 'WHILE',
#'ibalik' : 'RETURN',
'tayona' : 'MAIN',
'ayokona' : 'END',
... | #'maslovemosya' : 'LEQ',
#'maslovekita' : 'GEQ',
#'pataskami' : 'EQ',
#'lamangsiya' : 'NEQ',
#'basted' : 'NOT',
#'ot' : 'OR',
#'at' : 'AND',
}
tokens = [
'INT','FLOAT', 'EOL','ID','STRING',
'PLUS','... | OMMA',
#'OPENBRACE','CLOSEBRACE'
] + list(reserved.values())
#tokens += reserved.values()
def t_ID(self, t):
r'[a-zA-Z_][a-zA-Z_0-9]*'
t.type = Lexer.reserved.get(t.value,'ID') # Check for reserved words
# redis is case sensitive in hash keys but we want the sql t... |
mffiedler/svt | openshift_tooling/node_tuning_operator/nto_test_custom_tuning.py | Python | apache-2.0 | 5,119 | 0.003907 | #!/usr/bin/env python
from utils import *
########################################################
# Test: Node Tuning Operator: custom tuning is working #
##################################################### | ###
# Changes: #
# skordas: #
# Updating Test Case to work with OCP 4.4 #
########################################################
def cleanup():
print("Cleaning after test")
execute_command("oc delete tuned n... | ion:
print_title("Node Tuning Operator: Custom tuning is working")
# Getting all nodes
print_step("Gathering information about nodes")
nodes = execute_command("oc get nodes --no-headers -o=custom-columns=NAME:.metadata.name").split("\n")
del nodes[-1]
passed("List of nodes:\n" + str(nodes))
... |
greencoder/hopefullysunny-django | forecasts/management/commands/send_daily_forecasts.py | Python | mit | 1,298 | 0.007704 | # -*- coding: utf-8 -*-
import sys
import datetime
from django.core.management.base import BaseCommand, CommandError
from django.core.cache import cache
from registrations.models import Registration
from forecasts import handlers
from forecasts.lib.forecast import Forecast
class Command(BaseCommand):
def handl... | lter(status=1, latitude__isnull=False,
longitude__isnull=False):
cache_key = "%.2f,%.2f" % (registration.latitude, registration.longitude)
forecasts_list = cache.get(cache_key)
# If we don't have a value, it was not found in the cache. Look up and cache it | .
if not forecasts_list:
forecasts_list = Forecast.get_forecast(registration.latitude, registration.longitude)
print "Caching the fetched forecasts for %s" % cache_key
cache.set(cache_key, forecasts_list, 3600)
success = handlers.send_forecast_ema... |
PhilLidar-DAD/geonode | geonode/layers/admin.py | Python | gpl-3.0 | 3,475 | 0.000288 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2012 OpenPlans
#
# 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 versio... | title', 'abstract', 'purpose',)
filter_horizontal = ('contacts',)
date_hierarchy = 'date'
readonly_fields = ('uuid', 'typename', 'workspace')
form = LayerAdminForm
class AttributeAdmin(admin.ModelAdmin):
model = Attribute
list_display_links = ('id',)
list_display = (
'id',
... | list_filter = ('layer', 'attribute_type')
search_fields = ('attribute', 'attribute_label',)
class StyleAdmin(admin.ModelAdmin):
model = Style
list_display_links = ('sld_title',)
list_display = ('id', 'name', 'sld_title', 'workspace', 'sld_url')
list_filter = ('workspace',)
search_fields = ('na... |
ChristinaZografou/sympy | sympy/polys/tests/test_polytools.py | Python | bsd-3-clause | 106,569 | 0.001314 | """Tests for user-friendly public interface to polynomial functions. """
from sympy.polys.polytools import (
Poly, PurePoly, poly,
parallel_poly_from_expr,
degree, degree_list,
LC, LM, LT,
pdiv, prem, pquo, pexquo,
div, rem, quo, exquo,
half_gcdex, gcdex, invert,
subresultants,
resu... | cancel, reduced, groebner,
GroebnerBasis, is_zero_dimensional,
_tor | ational_factor_list,
to_rational_coeffs)
from sympy.polys.polyerrors import (
MultivariatePolynomialError,
ExactQuotientFailed,
PolificationFailed,
ComputationFailed,
UnificationFailed,
RefinementFailed,
GeneratorsNeeded,
GeneratorsError,
PolynomialError,
CoercionFailed,
... |
elkeschaper/hts | hts/plate/plate.py | Python | gpl-2.0 | 35,353 | 0.006082 | # (C) 2015, 2016 Elke Schaper
"""
:synopsis: The Plate Class.
.. moduleauthor:: Elke Schaper <elke.schaper@isb-sib.ch>
"""
import itertools
import logging
import pickle
import random
import re
import string
import GPy
import numpy as np
im | port pylab
import scipy.stats
import hts.data_tasks.gaussian_processes
from hts.data_tasks import prediction
from hts.plate_data import plate_data, data_issue, meta_data, plate_layout, readout
KNOWN_DATA_TYPES = ["plate_layout", "readout", "data_issue", "config_data"]
LETTERS = list(string.ascii_uppercase) + ["".join... | itertools.product(string.ascii_uppercase, string.ascii_uppercase)]
MAX_WIDTH = 48
MAX_HEIGHT = 32
TRANSLATE_HUMANREADABLE_COORDINATE = {(LETTERS[cc[0]], str(cc[1] + 1)): cc for cc in
itertools.product(range(MAX_HEIGHT), range(MAX_WIDTH))}
TRANSLATE_COORDINAT... |
opendroid-Team/enigma2-4.1 | lib/python/Tools/KeyBindings.py | Python | gpl-2.0 | 4,901 | 0.030402 | keyBindings = { }
from keyids import KEYIDS
from Components.config import config
from Components.RcModel import rc_model
keyDescriptions = [{
KEYIDS["BTN_0"]: ("UP", "fp"),
KEYIDS["BTN_1"]: ("DOWN", "fp"),
KEYIDS["KEY_OK"]: ("OK", ""),
KEYIDS["KEY_UP"]: ("UP",),
KEYIDS["KEY_DOWN"]: ("DOWN",),
KEYIDS["KEY_... | EY_NEXTSONG"]: ("FASTFORWARD",),
KEYIDS["KEY_CHANNELUP"]: ("BOUQUET+",),
KEYIDS["KEY_CHANNELDOWN"]: ("BOUQUET-",),
KEYIDS["KEY_0"]: ("0",),
KEYIDS["KEY_1"]: ("1",),
KEYIDS["KEY_2"]: ("2",),
KEYIDS["KEY_3"]: ("3",),
KEYIDS["KEY_4"]: ("4",),
KEYIDS["KEY_5"]: ("5",),
KEYIDS["KEY_6"]: ("6",),
KEYIDS["KE... | ]: ("RECORD",)
},
]
def addKeyBinding(domain, key, context, action, flags):
keyBindings.setdefault((context, action), []).append((key, domain, flags))
# returns a list of (key, flags) for a specified action
def queryKeyBinding(context, action):
if (context, action) in keyBindings:
return [(x[0], x[2]) for x in k... |
ksmaheshkumar/gitfs | gitfs/views/read_only.py | Python | apache-2.0 | 1,744 | 0 | # Copyright 2014 PressLabs SRL
#
# 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,... | useOSError(ENOTSUP)
def open(self, path, flags):
write_flags = (os.O_WRONLY | os.O_RDWR | os.O_APPEND | os.O_TRUNC
| os.O_CREAT)
if write_flags & flags:
raise FuseOSError(EROFS)
return 0
def create(self, path, fh):
raise FuseOSError(EROFS | )
def write(self, path, fh):
raise FuseOSError(EROFS)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
return 0
def flush(self, path, fh):
return 0
def release(self, path, fh):
return 0
def access(self, path, amode):
if amode... |
nayas360/pyterm | bin/set.py | Python | mit | 1,471 | 0 | # set command to set global variables
from lib.utils import *
def _help():
usage | = '''
Usage: set [options] (var) [value]
[options]:
-h Print this help.
-del (var) Delete variable
(var) if defined.
where (var) is a valid
global variable
if [value] is not given,
current value is returned
'''
print(usage)
def main(argv):
if '-h' in argv:
_h... | more
# argv.pop(0) #remove arg
# to show all vars
if len(argv) < 1:
for i in prop.vars():
print(i, ' = ', prop.get(i))
return
if '-del' in argv:
try:
var = argv[1]
# detect system vars
if var == 'save_state' or var == 'c_char':
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.