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 |
|---|---|---|---|---|---|---|---|---|
phoenixsbk/kvmmgr | packaging/setup/plugins/ovirt-engine-rename/ovirt-engine/tools.py | Python | apache-2.0 | 3,586 | 0.002231 | #
# ovirt-engine-setup -- ovirt engine setup
# Copyright (C) 2013 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 r... | 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 License.
#
"""Tools configuration plugin."""
import os
import gettext
_ = lambda m: gettext.dgettext(message=m, domain='ovirt-engine-set... |
zombiezen/turbohvz | hvz/email.py | Python | gpl-3.0 | 6,348 | 0.002205 | #!/usr/bin/env python
#
# email.py
# TurboHvZ
#
# Copyright (C) 2008 Ross Light
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opt... | *kw)
turbomail.enqueue(new_message | )
return new_message
def send_generic_mail(recipients, subject, message):
"""
Conveniently sends a custom email.
This will immediately return if mail has been turned off. The sender is
set to the value of the configuration value ``hvz.webmaster_email``.
:Returns: The newly created me... |
liampauling/betfairlightweight | tests/test_scores.py | Python | mit | 3,269 | 0.00153 | import unittest
from unittest import mock
from betfairlightweight import APIClient
from betfairlightweight import resources
from betfairlightweight.endpoints.scores import Scores
from betfairlightweight.exceptions import APIError
from tests.tools import create_mock_json
class ScoresInit(unittest.TestCase):
def t... | 1
mock_response.assert_called_with(
"ScoresAPING/v1.0/listScores", {"updateKeys": mock_update_keys}, None
)
assert all(isinstance(event, resources.Score) | for event in response)
@mock.patch("betfairlightweight.endpoints.scores.Scores.request")
def test_list_incidents(self, mock_response):
mock = create_mock_json("tests/resources/incidents.json")
mock_response.return_value = (mock.Mock(), mock.json(), 1.3)
mock_update_keys = mock.Mock()
... |
morefigs/pymba | pymba/vimba_c.py | Python | mit | 17,849 | 0.001345 | from sys import platform as sys_plat
import platform
import os
from ctypes import *
if sys_plat == "win32":
def find_win_dll(arch):
""" Finds the highest versioned windows dll for the specified architecture. """
dlls = []
filename = 'VimbaC.dll'
# look in local working directory... | of the image
('pixelFormat', c_uint32),
# Width of an image
('width', c_uint32),
# Height of an image
('height', c_uint32),
# Horizontal offset of an image
('offsetX', c_uint32),
# Vertical offset of an image
('offsetY', c_uint32),
# Uni... | lass VimbaFeaturePersistSettings(NiceStructure):
_fields_ = [
('persistType', c_uint32),
('maxIterations', c_uint32),
('loggingLevel', c_uint32)]
_vimba_lib = dll_loader.LoadLibrary(vimbaC_path)
# ----- The below function signatures are defined in VimbaC.h -----
# callback for frame queu... |
Mischback/django-oweb | oweb/tests/views/item_update.py | Python | mit | 10,246 | 0.001952 | """Contains tests for oweb.views.updates.item_update"""
# Python imports
from unittest import skip
# Django imports
from django.core.urlresolvers import reverse
from django.test.utils import override_settings
from django.contrib.auth.models import User
# app imports
from oweb.tests import OWebViewTests
from oweb.models... | object=p).first( | )
self.client.login(username='test01', password='foo')
r = self.client.post(reverse('oweb:item_update'),
data={ 'item_type': 'building',
'item_id': b_pre.id,
'item_level': b_pre.level - 1 },
... |
nklapste/card-py-bot | card_py_bot/config.py | Python | mit | 4,162 | 0.00024 | """Emoji config functions"""
import json
import os
import re
from logging import getLogger
from card_py_bot import BASEDIR
__log__ = getLogger(__name__)
# Path where the emoji_config.json will be stored
EMOJI_CONFIG_PATH = os.path.join(BASEDIR, "emoji_config.json")
# Dictionary that is keyed by the Discord short em... | config json also return the dict that
created the json"""
emoji_config = dict()
for short_emoji_id in MANA_ID_DICT:
emoji_config[short_emoji_id] = {
"web_id": MANA_ID_DICT[short_emoji_id],
"discord_raw_id": | None
}
with open(EMOJI_CONFIG_PATH, "w") as file:
json.dump(emoji_config, file, indent=4)
return emoji_config
def load_mana_dict() -> dict:
"""Load the emoji config into a mana dict"""
try:
with open(EMOJI_CONFIG_PATH, "r") as file:
emoji_config = json.load(file)
... |
freakboy3742/pyxero | xero/basemanager.py | Python | bsd-3-clause | 16,413 | 0.001036 | from __future__ import unicode_literals
import json
import requests
import six
from datetime import datetime
from six.moves.urllib.parse import parse_qs
from xml.etree.ElementTree import Element, SubElement, tostring
from xml.parsers.expat import ExpatError
from .auth import OAuth2Credentials
from .exceptions import ... | lication/json"):
return response.content
return self._parse_api_response(response, self.name)
elif response.status_code == 204:
return response.content
elif response.status_code == 400:
try:
raise XeroBadR... | I response"
)
elif response.status_code == 401:
raise XeroUnauthorized(response)
elif response.status_code == 403:
raise XeroForbidden(response)
elif response.status_code == 404:
raise XeroNotFound(response)
... |
hannahkwarren/CLaG-Sp2016 | code-exercises-etc/section_xx_-misc/4-2.py | Python | mit | 419 | 0.004773 | def pbj_while(slices):
output = ''
while (slices > 0):
slices = slic | es - 2
if slices >= 2:
output += 'I am making | a sandwich! I have bread for {0} more sandwiches.\n'.format(slices / 2)
elif slices < 2:
output += 'I am making a sandwich! But, this is my last sandwich.'
return output
print pbj_while(int(raw_input('How many slices of bread do you have? ')))
|
InfiniteAlpha/profitpy | profit/neuralnetdesigner/train_test.py | Python | gpl-2.0 | 3,757 | 0.003194 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2007 Troy Melhase
# Distributed under the terms of the GNU General Public License v2
# Author: Troy Melhase <troy@gci.net>
import sys
from PyQt4.QtCore import QVariant
from PyQt4.QtGui import (QApplication, QFrame, QIcon,
QStandardIte... | TrainTree(QFrame, Ui_BreadFanTrainTree):
""" Tree view of a Session object.
"""
def __init__(self, pa | rent=None):
""" Constructor.
@param parent ancestor of this widget
"""
QFrame.__init__(self, parent)
self.setupUi(self)
connect = self.connect
def setupBasic(self, sender, newSignal):
self.connect(sender, newSignal, self.on_newBreadNet)
def on_newBreadN... |
samuelgarcia/python-neo | neo/test/iotest/test_igorio.py | Python | bsd-3-clause | 543 | 0 | """
Tests of neo.io.igorproio
"""
import unitte | st
try:
import igor
HAVE_IGOR = True
except ImportError:
HAVE_IGOR = False
from neo.io.igorproio import IgorIO
from neo.test.iotest.common_io_test import BaseTestIO
@unittest.skipUnless(HAVE_IGOR, "requires | igor")
class TestIgorIO(BaseTestIO, unittest.TestCase):
ioclass = IgorIO
entities_to_download = [
'igor'
]
entities_to_test = [
'igor/mac-version2.ibw',
'igor/win-version2.ibw'
]
if __name__ == "__main__":
unittest.main()
|
ekiwi/tinyos-1.x | contrib/ucb/tools/python/pytos/tools/Straw.py | Python | bsd-3-clause | 3,841 | 0.012757 | # "Copyright (c) 2000-2003 The Regents of the University of California.
# All rights reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose, without fee, and without written agreement
# is hereby granted, provided that the above copyright notice, the follow... | e = self.app.StrawM.msgDataSize.peek(address=nodeID, timeout=3) #find num bytes/msg
dataSize = response[0].v | alue['value'].value
numHops = self.app.enums.DRAIN_MAX_TTL - response[0].getParentMsg(self.app.enums.AM_DRAINMSG).ttl
self.app.StrawM.sendPeriod.poke(self.linkLatency * numHops * 1000, address=nodeID, responseDesired=False)
msgs = [0 for i in range(int(math.ceil(size/float(dataSize))))] #keep tr... |
dbcls/dbcls-galaxy | lib/galaxy/web/framework/helpers/__init__.py | Python | mit | 220 | 0.045455 | from webhelpers import *
from dat | etime import datetime
def time_ago( x ):
return | date.distance_of_time_in_words( x, datetime.utcnow() )
def iff( a, b, c ):
if a:
return b
else:
return c |
jredrejo/bancal | web2py/applications/bancal/modules/paises.py | Python | gpl-3.0 | 18,468 | 0.016688 | # coding: utf8
Paises=(
(4, 'AF', 'AFG', 93, 'Afganistán', 'Asia', '', 'AFN', 'Afgani afgano'),
(8, 'AL', 'ALB', 355, 'Albania', 'Europa', '', 'ALL', 'Lek albanés'),
(10, 'AQ', 'ATA', 672, 'Antártida', 'Antártida', '', '', ''),
(12, 'DZ', 'DZA', 213, 'Argelia', 'África', '', 'DZD', 'Dinar algerino'),
(16, 'AS', 'ASM', ... | ia'),
(360, 'ID', 'IDN', 62, 'Indonesia', 'Asia', '', 'IDR', 'Rupiah indonesia'),
(364, 'IR', 'IRN', 98, 'Irán', 'Asi | a', '', 'IRR', 'Rial iraní'),
(368, 'IQ', 'IRQ', 964, 'Iraq', 'Asia', '', 'IQD', 'Dinar iraquí'),
(372, 'IE', 'IRL', 353, 'Irlanda', 'Europa', '', 'EUR', 'Euro'),
(376, 'IL', 'ISR', 972, 'Israel', 'Asia', '', 'ILS', 'Nuevo |
genialis/resolwe | resolwe/flow/models/collection.py | Python | apache-2.0 | 3,575 | 0.000559 | """Resolwe collection model."""
from django.contrib.postgres.fields import ArrayField
from django.contrib.postgres.indexes import GinIndex
from django.contrib.postgres.search import SearchVectorField
from django.db import models, transaction
from resolwe.permissions.models import PermissionObject, PermissionQuerySet
... | se
except DirtyError:
self.descriptor_dirty = Tru | e
elif self.descriptor and self.descriptor != {}:
raise ValueError(
"`descriptor_schema` must be defined if `descriptor` is given"
)
super().save()
class CollectionQuerySet(BaseQuerySet, PermissionQuerySet):
"""Query set for ``Collection`` objects."""
@... |
Diti24/python-ivi | ivi/lecroy/lecroyWR204MXIA.py | Python | mit | 1,653 | 0.001815 | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2016 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... | driver"
def __init__(self, *args, **kwargs):
self.__dict__.setdefault('_instrument_id', 'WaveRunner 204MXi-A')
super(lecroy104MXiA, self).__init__(*args, **kwargs)
self._analog_channel_count = 4
self._digital_channel_count = 0
self._channel_count = self._analog_channel_co... | nels()
|
mantarayforensics/mantaray | Tools/Python/entropy_mr.py | Python | gpl-3.0 | 10,303 | 0.028827 | #!/usr/bin/env python3
#This program calculates the entropy for a file, files in a folder or disk image
#The user sets a reporting threshold
#########################COPYRIGHT INFORMATION############################
#Copyright (C) 2011 dougkoster@hotmail.com #
#This program is free software: you can r... | re.sub("'",'',file_name_print)
abs_file_path_print = re.sub('b\'','',str(abs_file_path_print))
abs_file_path_print = re.sub("'",'', abs_file_path_print)
#don't process link files
if not (os.path.islink(abs_file_path)):
#get file size
try:
file_size = os.path.getsize(abs_file_path)
exc... | :
try:
ent = calc_entropy(abs_file_path)
print("Filename: " + file_name + "\t" + "Entropy: " + ent)
export_file.write(ent + "," + str(file_name_print) + "," + str(file_size) + "," + str(abs_file_path_print) + "\n")
except:
print("Could not get entropy for file: " + abs_file... |
apinsard/funtoo-overlay | funtoo/scripts/merge-funtoo-staging.py | Python | gpl-2.0 | 14,296 | 0.020425 | #!/usr/bin/python3
import os
import sys
from merge_utils import *
xml_out = etree.Element("packages")
funtoo_staging_w = GitTree("funtoo-staging", "master", "repos@localhost:ports/funtoo-staging.git", root="/var/git/dest-trees/funtoo-staging", pull=False, xml_out=xml_out)
#funtoo_staging_w = GitTree("funtoo-staging-u... | ren't changes in these overlays, we don't.
shards = {
"perl" : GitTree("gentoo-perl-shard", "1fc10379b04cb4aaa29e824288f3ec22badc6b33", "repos@localhost:gentoo-perl-shard.git", pull=True),
"kde" : GitTree("gentoo-kde-shard", "cd4e1129ddddaa21df367ecd4f68aab894e57b31", "repos@localhost:gentoo-kde-shard.git", pull=Tru... | @localhost:ports/gentoo-gnome-shard.git", pull=True),
"x11" : GitTree("gentoo-x11-shard", "12c1bdf9a9bfd28f48d66bccb107c17b5f5af577", "repos@localhost:ports/gentoo-x11-shard.git", pull=True),
"office" : GitTree("gentoo-office-shard", "9a702057d23e7fa277e9626344671a82ce59442f", "repos@localhost:ports/gentoo-office-sha... |
yusufshakeel/Python-Project | example/expo.py | Python | mit | 55 | 0.036364 | #exponent
# | find | 2^n
n = input("Enter n: ")
print 2**n
|
lzjever/pullot | pullot/framebuffer.py | Python | mit | 2,966 | 0.020566 | # -*- coding: utf-8 -*-
# The MIT License (MIT)
# Copyright (c) 2015 Percy Li
# See LICENSE for details.
import struct
import threading
import copy
class FrameBuffer(object):
def __init__(self,decoder = None):
self.data_buffer = bytes([])
self.decoder = decoder
def s... |
return FrameBuffer.append_buffer(self,buf)
def pop_buf | fer (self):
with self.internal_lock:
return FrameBuffer.pop_buffer(self)
def get_buffer (self):
with self.internal_lock:
return copy.deepcopy( FrameBuffer.get_buffer(self) )
def clear_buffer (self):
with self.internal_lock:
return FrameBuff... |
fredreichbier/babbisch-ooc | babbisch_ooc/wraplib/utils.py | Python | mit | 279 | 0.007168 | import re
def pythonize_camelcase_name(name):
"""
GetProperty -> get_property
"""
de | f repl(match):
return '_' + match.group(0).lower()
s = re.sub(r'([A-Z])' | , repl, name)
if s.startswith('_'):
return s[1:]
else:
return s
|
jr55662003/My_Rosalind_solution | ProteinMass/PRTM.py | Python | gpl-3.0 | 450 | 0.026667 | '''
Given: A protein string PP of length at most 100 | 0 aa.
Return: The total weight of PP. Consult the monoisotopic mass table.
'''
def weight(protein):
# Build mass table from mass_table.txt
mass = {}
with open("mass_table.txt", "r") as m:
for line in m:
lst = line.split(" ")
mass[lst[0]] = floa | t(lst[1].rstrip())
# Calculate the mass of protein
total = 0
for aa in protein:
total += mass[aa]
return total
|
mipt-cs-on-python3/arithmetic_dragons | tournament.py | Python | gpl-3.0 | 1,950 | 0.004271 | # coding: utf-8
# license: GPLv3
from enemies import *
from hero import *
def annoying_input_int(message =''):
answer = None
while answer == None:
try:
answer = int(input(message))
except ValueError:
print('Вы ввели недопустимые символы')
return answer
def game_tou... | 'дракон!')
while dragon.is_alive() and hero.is_alive():
print('Вопрос:', dragon.question())
answer = annoying_input_int('Ответ:')
if dragon.check_answer(answer):
hero.attack(dragon)
| print('Верно! \n** дракон кричит от боли **')
else:
dragon.attack(hero)
print('Ошибка! \n** вам нанесён удар... **')
if dragon.is_alive():
break
print('Дракон', dragon._color, 'повержен!\n')
if hero.is_alive():
print('Поздр... |
ukch/online_sabacc | src/sabacc/api/viewhelpers.py | Python | gpl-3.0 | 494 | 0 | f | rom django.core.urlresolvers import reverse
import django.http
import django.utils.simplejson as json
import functools
def make_url(request, reversible):
return request.build_absolute_uri(reverse(reversible))
def json_output(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
output = f... | http.HttpResponse(json.dumps(output),
content_type="application/json")
return wrapper
|
pakodekker/oceansar | oceansar/ocs_io/processed.py | Python | gpl-3.0 | 3,344 | 0.000299 |
import time
from netCDF4 import Dataset
from oceansar.ocs_io import NETCDFHandler
class ProcFile(NETCDFHandler):
""" Processed raw data file generated by the OASIS Simulator
:param file_name: File name
:param mode: Access mode (w = write, r = read, r+ = read + append)
:param proc_dim: Pr... | data dime | nsions are needed when creating a new file!')
self.__file__.createDimension('ch_dim', proc_dim[0])
self.__file__.createDimension('pol_dim', proc_dim[1])
self.__file__.createDimension('az_dim', proc_dim[2])
self.__file__.createDimension('rg_dim', proc_dim[3])
... |
robertostling/bnas | bnas/regularize.py | Python | gpl-3.0 | 1,950 | 0.002564 | """Regularizations.
Each regularization method is implemented as a subclass of
:class:`Regularizer`,
where the constructor takes the hyperparameters, and the `__call__` method
constructs the symbolic loss expression given a parameter.
These are made for use with :meth:`Model.regularize`, but can also be used
directly... | rxiv.org/pdf/1511.08400v7.pdf>`_
"""
def __init__(self, penalty=50.0):
self.penalty = penalty
def __call | __(self, p, p_mask):
"""Compute the squared norm difference of a sequence.
Example
-------
>>> def loss(self, outputs, outputs_mask):
... # loss() definition from a custom Model subclass
... loss = super().loss()
... pred_states, pred_symbols = self(o... |
cpcloud/PyTables | mswindows/get_pytables_version.py | Python | bsd-3-clause | 300 | 0.003333 | # Print the version splitted in three components
import sys
verfile = sys.argv[1]
f = open(verfile)
version = f.read()
l = [a[0] for a in version.split('.') if a[0] in '0123456789']
# If | no revision, '0' is added
if len(l) == 2:
l.append('0')
for i in l:
print i,
f.close | ()
|
Karel-van-de-Plassche/bokeh | bokeh/io/notebook.py | Python | bsd-3-clause | 18,064 | 0.005314 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#---------------------------------------------------... | def doc(self | ):
return self._doc
# Adding this method makes curdoc dispatch to this Comms to handle
# and Document model changed events. If we find that the event is
# for a model in our internal copy of the docs, then trigger the
# internal doc with the event so that it is collected (until a
# call to ... |
ankitsejwal/Lyndor | run.py | Python | mit | 6,128 | 0.006538 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
''' Lyndor runs from here - contains the main functions '''
import sys, time, os
import module.message as message
import module.save as save
import module.cookies as cookies
import module.read as read
import install
import module.move as move
import module.draw as draw
im... | %H:%M") == read.download_time:
download_course(url)
return
print(f'Download will start at: {read.download_time} leave this window open.')
time.sleep | (60)
except KeyboardInterrupt:
sys.exit(message.colored_message(Fore.LIGHTRED_EX, "\n- Program Interrupted!!\n"))
def download_course(url):
''' download course '''
# Check for a valid url
if url.find('.html') == -1:
sys.exit(message.animate_characters(Fore.LIGHTRED_EX, draw... |
ufaks/website-addons | website_sale_available/__openerp__.py | Python | lgpl-3.0 | 501 | 0 | {
'name': "Sale only available products on Website",
'summary': """Sale only availabl | e products on Website""",
'version': '1.0.0',
'author': 'IT-Projects LLC, Ivan Yelizariev',
'license': 'GPL-3',
'category': 'Custom',
'website': 'https://yelizariev.github.io',
'images': ['images/available.png'],
'price': 9.00,
'currency': | 'EUR',
'depends': ['website_sale'],
'data': [
'website_sale_available_views.xml',
],
'installable': True,
}
|
Sbalbp/DIRAC | ResourceStatusSystem/Policy/JobRunningWaitingRatioPolicy.py | Python | gpl-3.0 | 2,447 | 0.042092 | """ JobRunningWaitingRatioPolicy
Policy that calculates the efficiency following the formula:
( running ) / ( running + waiting + staging )
if the denominator is smaller than 10, it does not take any decision.
"""
from DIRAC import S_OK
from DIRAC.ResourceStat... | take a decision'
return S_OK( result )
commandResult = commandResult[ 0 ]
if not commandResult:
result[ 'Status' ] = 'Unknown'
result[ 'Reason' ] = 'No values to take a decision'
return S_OK( result )
running = float( commandResult[ 'Running' ] )
waiting = float( commandResult... | a minimum amount of jobs to take a decision ( at least 10 pilots )
if total < 10:
result[ 'Status' ] = 'Unknown'
result[ 'Reason' ] = 'Not enough jobs to take a decision'
return S_OK( result )
efficiency = running / total
if efficiency < 0.4:
result[ 'Status' ] = 'Banned'
e... |
vlegoff/tsunami | src/test/boostrap/salle/etendue/complexe.py | Python | bsd-3-clause | 772 | 0 | complexe = importeur.salle.creer_etendue("complexe")
complexe.origine = (20, 20)
obstacle = importeur.salle.obstacles["falaise"]
coords = [
(20, 20),
(21, 20),
(22, 20),
(23, 20),
(24, 20),
(25, 20),
(20, 21),
(20, 22),
(20, 23),
(20, 24),
(20, 25),
(19, 25),
(19, 26... | , 28),
(21, 28),
(22, 28),
(23, 28),
(24, 28),
(24, 27),
(24, 26),
(23, 26),
(23, 25),
(23, 24),
(24, 24),
(25, 24),
(25, 23),
(23, 23),
(25, 22),
(22, 22),
(23, 22),
(25, 21),
]
for coord in coords:
complexe.ajouter_obstacle(coord, obsta | cle)
complexe.trouver_contour()
|
lhupfeldt/jenkinsflow | demo/jobs/hide_password_jobs.py | Python | bsd-3-clause | 545 | 0.00367 | # Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
f | rom framework import api_select
def create_jobs(api_type):
api = api_select.api(__file__, api_type)
api.flow_job()
api.job('passwd_args', exec_time=0.5, max_fai | ls=0, expect_invocations=1, expect_order=1,
params=(('s1', 'no-secret', 'desc'), ('passwd', 'p2', 'desc'), ('PASS', 'p3', 'desc')))
return api
if __name__ == '__main__':
create_jobs(api_select.ApiType.JENKINS)
|
anhstudios/swganh | data/scripts/templates/object/installation/faction_perk/turret/shared_block_sm.py | Python | mit | 460 | 0.047826 | #### NOTICE: THIS FILE IS AUTOG | ENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Installation()
result.template = "object/installation/faction_perk/turret/shared_block_sm.iff"
result.attribute_template_id = -1
result.stfName... | MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
dimitrius-brest/katalog-poseleniy-RP | converter-vkwiki2md/convert2md.py | Python | cc0-1.0 | 3,623 | 0.019257 | # -*- coding: utf-8 -*-
try:
f1 = open("input.txt","r",encoding="utf-8")
except IOError:
print("Не удалось найти входной файл input.txt")
try:
f2 = open("output.txt","w",encoding="utf-8")
except IOError:
print("Не удалось открыть выходной файл output.txt")
import re # импортируем модуль работы с регу... |
ssylk | a_name = ssylka.split("|")[1].replace(']]','') #выделяем имя ссылки
ssylka_new = ('['+ssylka_name+']('+'http://vk.com/'+ssylka_id+')')
stroka = stroka.replace(ssylka, ssylka_new) #заменяем старую ссылку на новую
# ---- Замена внешних ссылок [http**|**] ----
iskomoe2 = re.fi... |
inspectorbean/gasbuddy | home/views.py | Python | mit | 14,960 | 0.008757 | from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
import datetime, time, requests, re, os
import bs4
from django.contrib.admin.views.decorators import staff_member_required
from decimal import *
# Create your views here.
from .models import Ga... | y * first_cloud.last_price)
| if ninja_isk > site_isk:
ninja_isk = site_isk
m_per_s = ((units_15 / num) * first_cloud.volume) + ((rem_units / num) * sec_cloud.volume)
if m_per_s * num > (site.p_qty * site.p_gas.volume) + (site.s_qty * site.s_gas.volume) |
FrankNagel/qlc | src/webapp/quanthistling/quanthistling/tests/functional/test_book.py | Python | gpl-3.0 | 203 | 0.004926 | fr | om quanthistling.tests import *
class TestBo | okController(TestController):
def test_index(self):
response = self.app.get(url(controller='book', action='index'))
# Test response...
|
WaveBlocks/WaveBlocksND | WaveBlocksND/ObservablesMixedHAWP.py | Python | bsd-3-clause | 13,370 | 0.006806 | """The WaveBlocks Project
Compute some observables like norm, kinetic and potential energy
of Hagedorn wavepackets. This class implements the mixed case
where the bra does not equal the ket.
@author: R. Bourquin
@copyright: Copyright (C) 2014, 2016 R. Bourquin
@license: Modified BSD License
"""
from functools import... | energy :math:`\langle \Psi | T | \Psi^{\prime} \rangle`.
:type gradient: A :py:class:`Gradient` subclass instance.
"""
self._gradient = gradient
def overlap(self, pacbra, packet, *, component=None, summed=False):
r"""Calculate the overlap :math:`\langle \Psi | \Psi^{\p... | t :math:`\Psi` which takes part in the overlap integral.
:type pacbra: A :py:class:`HagedornWavepacketBase` subclass instance.
:param packet: The wavepacket :math:`\Psi^{\prime}` which takes part in the overlap integral.
:type packet: A :py:class:`HagedornWavepacketBase` subclass instance.
... |
crobinso/libvirt | scripts/hyperv_wmi_generator.py | Python | lgpl-2.1 | 10,347 | 0.001546 | #!/usr/bin/env python3
#
# hyperv_wmi_generator.py: generates most of the WMI type mapping code
#
# Copyright (C) 2011 Matthias Bolte <matthias.bolte@googlemail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by ... | ed for wsman unserialization of
response XML into the *_Data structs.
"""
header = "#define %s_RESO | URCE_URI \\\n" % self.name.upper()
header += " \"%s\"\n" % self.uri_info.resourceUri
header += "\n"
header += "struct _%s_Data {\n" % self.name
for property in self.properties:
header += property.generate_classes_header()
header += "};\n\n"
header += "SER_D... |
shrinidhi666/rbhus | tests/conversationBox.py | Python | gpl-3.0 | 1,444 | 0.025623 | #!/usr/bin/python
from PyQt4 import QtCore, QtGui
class Bubble(QtGui.QLabel):
def __init__(self,text):
super(Bubble,self).__init__(text)
self.setContentsMargins(5,5,5,5)
def paintEvent(self, e):
p = QtGui.QPainter(self)
p.setRenderHint(QtGui.QPainter.Antialiasing,True)
... | cerItem(1,1 | ,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Preferred))
hbox.addWidget(label)
if left is True:
hbox.addSpacerItem(QtGui.QSpacerItem(1,1,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Preferred))
hbox.setContentsMargins(0,0,0,0)
self.setLayout(hbox)
s... |
mfherbst/spack | var/spack/repos/builtin/packages/r-sva/package.py | Python | lgpl-2.1 | 1,827 | 0.000547 | ##############################################################################
# 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... | d LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it u | nder the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# 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.... |
kumar303/hawkrest | hawkrest/__init__.py | Python | bsd-3-clause | 7,011 | 0.000428 | import logging
import sys
import traceback
from django.conf import settings
from django.core.cache import cache
try:
from django.utils.module_loading import import_string
except ImportError:
# compatibility with django < 1.7
from django.utils.module_loading import import_by_path
import_string = import... | --------------------------------------------
def get_previous_by_last_login(self, *args, **kw):
raise NotImplementedError()
| def get_next_by_last_login(self, *args, **kw):
raise NotImplementedError()
def seen_nonce(id, nonce, timestamp):
"""
Returns True if the Hawk nonce has been seen already.
"""
key = '{id}:{n}:{ts}'.format(id=id, n=nonce, ts=timestamp)
if cache.get(key):
log.warning('replay attack?... |
Degustare/cleany | cleany/maps/translation.py | Python | gpl-3.0 | 1,115 | 0.001795 | # -*- coding: UTF-8 -*-
# translation.py
#
# Copyright (C) 2013 Cleany
#
# Author(s): Cédric Gaspoz <cga@cleany.ch>
#
# This file i | s part of cleany.
#
# Cleany 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.
#
# Cleany is distributed in the hope that it will be usef... | hould have received a copy of the GNU General Public License
# along with Cleany. If not, see <http://www.gnu.org/licenses/>.
# Stdlib imports
# Core Django imports
# Third-party app imports
from modeltranslation.translator import translator, TranslationOptions
# Cleany imports
#from .models import
# class Appe... |
1905410/Misago | misago/users/management/commands/createsuperuser.py | Python | gpl-2.0 | 6,267 | 0.001277 | """
Misago-native rehash of Django's createsuperuser command that
works with double authentication fields on user model
"""
import sys
from getpass import getpass
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand
from d... | ce_str("Enter displayed username: ")
raw_value = input(message).strip()
validate_username(raw_value)
username = raw_value
except Val | idationError as e:
self.stderr.write(e.messages[0])
while not email:
try:
raw_value = input("Enter E-mail address: ").strip()
validate_email(raw_value)
email = raw_value
... |
kdaily/altanalyze | methylation.py | Python | apache-2.0 | 11,047 | 0.023264 | ###ExonArray
#Copyright 2005-2008 J. David Gladstone Institutes, San Francisco California
#Author Nathan Salomonis - nsalomonis@gmail.com
#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... | header:
delimiter = -50
annot_export_object = open(annot_file,'w')
annot_export_object.write(string.join([t[0]]+t[delimiter:],'\t')+'\n')
else:
delimiter = len(header)
headers = t[1:delimiter]
firstLine = False
... | ues = map(lambda x: conFloat(x,t[1:delimiter]),t[1:delimiter])
if '' in beta_values:
print beta_values;sys.exit()
high = sum(betaHighCount(x,betaHigh) for x in beta_values)
low = sum(betaLowCount(x,betaLow) for x in beta_values)
#if rows<50: print hig... |
dongnizh/tika-python | tika/tests/tests_params.py | Python | apache-2.0 | 2,555 | 0.007828 | #!/usr/bin/env python2.7
# encoding: utf-8
# 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 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 WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#Reference
#https://docs... |
PaddlePaddle/Paddle | python/paddle/fluid/tests/unittests/test_exponential_op.py | Python | apache-2.0 | 7,870 | 0.000381 | # Copyright (c) 2021 PaddlePaddle 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 app... | st2.astype("float32")
hist2 = hist2 / float(data_np.size)
self.assertTrue(
np.allclose(
hist1, hist2, rtol=0.02),
"actual: | {}, expected: {}".format(hist1, hist2))
def test_check_grad_normal(self):
self.check_grad(
['X'],
'Out',
user_defined_grads=[np.zeros(
[1024, 1024], dtype=self.dtype)],
user_defined_grad_outputs=[
np.random.rand(1024, 1024).as... |
g-rauhoeft/scrap-cap | motioncapture/gui/GL/Shapes.py | Python | mit | 1,040 | 0.025 | from OpenGL import GL
import numpy as np
import math
def drawLine(start, end, color, width=1):
GL.glLineWidth(width)
GL.glColor3f(*color)
GL.glBegin(GL.GL_LINES)
GL.glVertex3f(*start)
GL.glVertex3f(*end)
GL.glEnd()
def drawCircle(center, radius, color, rotation=np.array([0,0,0]), axis=np.arra... | GL.glRotatef(rotation[2]*90,0,0,axis[2])
else:
GL.glRotatef(rotation*90,axis[0],axis[1],axis[2])
GL.glBegin(GL.GL_POLYGON)
steps = [i * ((math.pi*2)/sections) for i in range(sections)]
for i in steps:
GL.glVertex3f(math.cos(i)*radius, math.sin(i)*radius, 0,0)
GL.glEnd()
GL.glP... | re():
drawFunction(*args)
return closure |
ShapeNet/JointEmbedding | src/image_embedding_testing/extract_image_embedding.py | Python | bsd-3-clause | 1,866 | 0.010718 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import numpy as np
import argparse
from google.protobuf import text_format
#https://github.com/BVLC/caffe/issues/861#issuecomment-70124809
import matplotlib
matplotlib.use('Agg')
BASE_DIR = os.path.dirna | me(os.path.abspath(__file__))
sys.path.append(os.path.dirname(BASE_DIR))
from global_variables import *
from utilities_caffe import *
parser = argparse.ArgumentParser(description="Extract image embedding features for IMAGE input.")
parser.add_argument('--image', help='Path to input image (cropped)', required=True)
par... | 00)
parser.add_argument('--caffemodel', '-c', help='Path to caffemodel (will ignore -n option if provided)', required=False)
parser.add_argument('--prototxt', '-p', help='Path to prototxt (if not at the default place)', required=False)
parser.add_argument('--gpu_index', help='GPU index (default=0).', type=int, default=... |
SaturdayNeighborhoodHealthClinic/osler | referral/migrations/0001_initial.py | Python | gpl-3.0 | 5,790 | 0.004836 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2018-10-26 01:35
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('pttrack', '0006_referral_additional_fiel... | appointment?', max_length=1, null=True, verbose_name=b'Appointment attended?')),
('appointment_location', models.ManyToManyField(blank=True, help_text=b'Where did the patient make an appointment?', to='pttrack.ReferralLocation')),
('author', models.ForeignKey(on_delete=django.db.models.d... | ('contact_method', models.ForeignKey(help_text=b'What was the method of contact?', on_delete=django.db.models.deletion.CASCADE, to='pttrack.ContactMethod')),
('contact_status', models.ForeignKey(help_text=b'Did you make contact with the patient about this referral?', on_delete=django.db.mo... |
kencochrane/scorinator | scorinator/scorinator/settings/prod.py | Python | apache-2.0 | 2,973 | 0.001345 | import os
from .base import * # NOQA
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
)
DATABASES = {'default': dj_database_url.config()}
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.R... | mail-port
EMAIL_PORT = os.environ.get('MAILGUN_SMTP_PORT', None )
# See: https://docs.djangoproject.com/en/1.3/ref/settings/#email-subject-prefix
EMAIL_SUBJECT_PREFIX = '[Scorinator] '
# See: https://d | ocs.djangoproject.com/en/1.3/ref/settings/#email-use-tls
EMAIL_USE_TLS = True
# See: https://docs.djangoproject.com/en/1.3/ref/settings/#server-email
SERVER_EMAIL = EMAIL_HOST_USER
########## END EMAIL CONFIGURATION |
aisk/grumpy | third_party/pypy/_sha512.py | Python | apache-2.0 | 14,181 | 0.062125 | """
This code was Ported from CPython's sha512module.c
"""
import _struct as struct
SHA_BLOCKSIZE = 128
SHA_DIGESTSIZE = 64
def new_shaobject():
return {
'digest': [0]*8,
'count_lo': 0,
'count_hi': 0,
'data': [0]* SHA_BLOCKSIZE,
'local': 0,
'digestsize': 0
}
... | & 63)) | (x << (64 - (y & 63)))) & 0xffffffffffffffff
Ch = lambda x, y, z: (z ^ (x & (y ^ z)))
Maj = lambda x, y, z: (((x | y) & z) | (x & y))
S = lambda x, n: ROR64(x, n)
R = lambda x, n: (x & 0xffffffffffffffff) >> n
Sigma0 = lambda x: (S(x, 28) ^ S(x, 34) ^ S(x, 39))
Sigma1 = lambda x: (S(x, 14) ^ S(x, 18) ^ S(x, 4... | ^ S(x, 8) ^ R(x, 7))
Gamma1 = lambda x: (S(x, 19) ^ S(x, 61) ^ R(x, 6))
def sha_transform(sha_info):
W = []
d = sha_info['data']
for i in xrange(0,16):
W.append( (d[8*i]<<56) + (d[8*i+1]<<48) + (d[8*i+2]<<40) + (d[8*i+3]<<32) + (d[8*i+4]<<24) + (d[8*i+5]<<16) + (d[8*i+6]<<8) + d[8*i+7])
for ... |
ArcherSys/ArcherSys | Lib/configparser.py | Python | mit | 148,451 | 0.000626 | <<<<<<< HEAD
<<<<<<< HEAD
"""Configuration file parser.
A configuration file consists of sections, lead by a "[section]" header,
and followed by "name: value" entries, with continuations and such in
the style of RFC 822.
Intrinsic defaults can be specified by passing them into the
ConfigParser constructor as a dictio... | cates while reading from a single source (file, string or
dictionary). Default is True.
When `empty_lines_in_values' is False (default: True), each empty line
marks the end of an option. Otherwise, internal empty lines of
a multiline option are k | ept as part of the value.
When `allow_no_value' is True (default: False), options without
values are accepted; the value presented for these is None.
sections()
Return all the configuration section names, sans DEFAULT.
has_section(section)
Return whether the given section exis... |
nhtdata/pystrix | pystrix/ami/dahdi.py | Python | gpl-3.0 | 3,238 | 0.004941 | """
pystrix.ami.dahdi
=================
Provides classes meant to be fed to a `Manager` instance's `send_action()` function.
Specifically, this module provides implementations for features specific to the DAHDI technology.
Legal
-----
This file is part of pystrix.
pystrix is free software; you can redistribute it ... | er the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or F... | General Public License and
GNU Lesser General Public License along with this program. If not, see
<http://www.gnu.org/licenses/>.
(C) Ivrnet, inc., 2011
Authors:
- Neil Tallim <n.tallim@ivrnet.com>
The requests implemented by this module follow the definitions provided by
https://wiki.asterisk.org/
"""
from ami im... |
Locottus/Python | machines/python/stepperLeft.py | Python | mit | 1,515 | 0.031023 | import RPi.GPIO as GPIO
import time
from array import *
#configuracoin de pines del stepper bipolar
out1 = 11
out2 = 13
out3 = 15
out4 = 16
#delay value
timeValue = 0.005
#matriz de pines del stepper
outs = [out1,out2,out3,out4]
#secuencia para mover el stepper
matriz = [
[1,0,0,1],
[1,1,0,0],
[0,1,1,0... | o in outs:
GPIO.output(o,GPIO.LOW)
|
def setMatrizPins(pin,valor):
if (valor == 0):
GPIO.output(outs[pin],GPIO.LOW)
if (valor == 1):
GPIO.output(outs[pin],GPIO.HIGH)
def runForward():
i = 0
while (i < 4):
#print(matriz[i][0],matriz[i][1],matriz[i][2],matriz[i][3])
setMatrizPins(0,matriz[i][0])
set... |
Som-Energia/invoice-janitor | invoicing/f1fixing/import_error/errors.py | Python | agpl-3.0 | 15,081 | 0.006366 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import dateutil.parser
from models import F1ImportError, \
LectPool, \
codigoOrigen_to_O, \
O_to_codigoOrigen
IMP_ERRORS = {}
def register(cls_error):
name = cls_error.__name__
if name in IMP_ERRORS.keys():
return True
else:
... | e == e.error.data or TerminoEnergiaActiva.FechaHasta == e.error.data:
consumption = TerminoEnergiaActiva.Periodo[0].ValorEnergiaActiva
break
if not consumption:
raise Exception('{exception_tag}: Consumption not found'.format(**locals()))
if len(e.F1.root.Fa... | uras.FacturaATR) > 1 or len(e.F1.root.Facturas.FacturaATR.Medidas) > 1 :
raise Exception('{exception_tag}: Factura with multiple FacturaATR or Medidas'.format(**locals()))
# Backup
filename = os.path.join('/tmp', e.name)
e.F1.dump(filename)
for idx_ap, Aparato in enumerate(... |
crunchy-github/python-notifier | notifier/dispatch.py | Python | lgpl-2.1 | 2,535 | 0.015792 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Andreas Büsching <crunchy@bitkipper.net>
#
# a generic dispatcher implementation
#
# Copyright (C) 2006, 2007, 2009, 2010
# Andreas Büsching <crunchy@bitkipper.net>
#
# This library is free software; you can redistribute it and/or modify
# it under the terms of... | if not __dispatchers[val]:
continue
for | disp in __dispatchers[val][:]:
if not disp():
dispatcher_remove(disp)
if __dispatchers[True]:
return MIN_TIMER
else:
return None
def dispatcher_count():
global __dispatchers
return len(__dispatchers)
|
amadeusproject/amadeuslms | subjects/migrations/0013_auto_20170120_1610.py | Python | gpl-2.0 | 503 | 0.001988 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-01-20 19:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('subjects', '0012_auto_20170112_1408'),
]
operations = [
migrations.AlterField... | rbose_na | me='tags'),
),
]
|
ares/robottelo | tests/foreman/cli/test_template.py | Python | gpl-3.0 | 8,063 | 0 | # -*- encoding: utf-8 -*-
"""Test class for Template CLI
:Requirement: Template
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: CLI
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
from fauxfactory import gen_string
from robottelo.cli.base import CLIReturnCodeError
from robottelo.... | if operating system can be removed from a template
:id: b5362565-6dce-4770-81e1-4fe3ec | 6f6cee
:expectedresults: Operating system is removed from template
:CaseLevel: Integration
"""
template = make_template()
new_os = make_os()
Template.add_operatingsystem({
'id': template['id'],
'operatingsystem-id': new_os['id'],
})
... |
nagyistoce/netzob | src/netzob/Common/MMSTD/Dictionary/Memory.py | Python | gpl-3.0 | 8,119 | 0.006285 | # -*- coding: utf-8 -*-
#+---------------------------------------------------------------------------+
#| 01001110 01100101 01110100 01111010 01101111 01100010 |
#| |
#| Netzob : Inferring communication protocol... |
"""Constructor of Memory:
"""
# create logger with the given configuration
self.log = logging.getLogger('netzob.Common.MMSTD.Dictionary.Memory.py')
self.memory = dict()
self.temporaryMemory = dict()
self.memory_acces_cb = None
def setMemoryAccess_cb(self, cb... | a memory access"""
self.memory_acces_cb = cb
def duplicate(self):
"""Duplicates in a new memory"""
duplicatedMemory = Memory()
for k in self.memory.keys():
duplicatedMemory.memory[k] = self.memory[k]
duplicatedMemory.createMemory()
return duplicatedMemory... |
Injabie3/lui-cogs | welcome/welcome.py | Python | gpl-3.0 | 20,055 | 0.005335 | """Welcome cog
Sends welcome DMs to users that join the server.
"""
import os
import logging
import discord
from discord.ext import commands
from __main__ import send_cmd_help # pylint: disable=no-name-in-module
from cogs.utils.dataIO import dataIO
# Requires checks utility from:
# https://github.com/Rapp... | lf.bot.say("What would you like the welcome DM message to be?")
message = await self.bot.wait_for_message(timeout=60,
| author=ctx.message.author,
channel=ctx.message.channel)
if message is None:
await self.bot.say("No response received, not setting anything!")
return
if len(message.content) > 2048:
await self.bot.... |
Johnetordoff/osf.io | api_tests/nodes/views/test_node_children_list.py | Python | apache-2.0 | 30,028 | 0.001599 | import pytest
from api.base.settings.defaults import API_BASE
from framework.auth.core import Auth
from osf.models import AbstractNode, NodeLog
from osf.utils import permissions
from osf.utils.sanitize import strip_html
from osf_tests.factories import (
NodeFactory,
ProjectFactory,
OSFGroupFactory,
Reg... | NodeFactory(parent=private_project)
res = app.get(private_project_url, auth=user.auth)
assert len(res.json['data']) == 1
def test_node_children_list_does_not_include_deleted(
self, app, user, public_project, public_component,
component, public_project_url):
ch... | ect.save()
res = app.get(public_project_url, auth=user.auth)
assert res.status_code == 200
ids = [node['id'] for node in res.json['data']]
assert child_project._id in ids
assert 2 == len(ids)
child_project.is_deleted = True
child_project.save()
res = ap... |
hj3938/panda3d | direct/src/interval/FunctionInterval.py | Python | bsd-3-clause | 15,597 | 0.011092 | """FunctionInterval module: contains the FunctionInterval class"""
__all__ = ['FunctionInterval', 'EventInterval', 'AcceptInterval', 'IgnoreInterval', 'ParentInterval', 'WrtParentInterval', 'PosInterval', 'HprInterval', 'ScaleInterval', 'PosHprInterval', 'HprScaleInterval', 'PosHprScaleInterval', 'Func', 'Wait']
from... | FunctionInterval subclass for throwing events ###
class EventInterval(FunctionInterval):
# Initialization
def __init__(self, event, sentArgs=[]):
"""__init__(event, sentArgs)
"""
def sendFunc(event = event, sentArgs = sentArgs):
messenger.send(event, sentArgs)
# Crea... | cceptInterval(FunctionInterval):
# Initialization
def __init__(self, dirObj, event, function, name = None):
"""__init__(dirObj, event, function, name)
"""
def acceptFunc(dirObj = dirObj, event = event, function = function):
dirObj.accept(event, function)
# Determine n... |
cropleyb/pentai | pentai/gui/config.py | Python | mit | 737 | 0.004071 | from kivy.config import Config
from kivy.config import ConfigParser
import pentai.base.logger as log
import os
def config_instance():
return _config
def create_config_instance(ini_file, user_path):
global _config
ini_path = os.path.join(user_path, ini_file)
if not ini_file in os.listdir(user_path):... | ort shutil
shutil.copy(ini_file, ini_path)
els | e:
log.info("Loading ini file from %s" % ini_path)
_config = ConfigParser()
_config.read(ini_path)
log.info("Updating ini file from %s" % ini_file)
_config.update_config(ini_file)
# Don't need to write it back until something is changed.
return _config
|
tonychee7000/BtcChinaRT | btc.py | Python | gpl-3.0 | 7,964 | 0.002392 | #!/usr/bin/env python3
#
# Copyright (C) 2013 - Tony Chyi <tonychee1989@gmail.com>
#
# 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, or (at your option)
# any later version.
#
... | r.drawLine(self.width() * 0.10, self.height() * 0.05 * h, self.width(), self.height() * 0.05 * h)
def drawMouse(self, event, painter) | :
if self.mousePosit in QtCore.QRect(self.width() * 0.1, self.height() * 0.05, self.width() * 0.9, self.height() * 0.95):
painter.setPen(QtGui.QColor(255, 0, 255))
painter.drawLine(self.mousePosit.x(), self.height() * 0.05, self.mousePosit.x(), self.height())
painter.drawLine... |
omarayad1/cantkeepup | app/core/helpers.py | Python | mit | 1,103 | 0.029918 | from json import dumps # pragma: no cover
from sqlalchemy.orm import class_mapper # pragma: no cover
from app.models import User, Group # pragma: no cover
def serialize(obj, columns):
# then we return their values in a dict
return dict((c, getattr(obj, c)) for c in columns)
def queryAllToJson(model,conditions):
# ... | lized_objs = [
serialize(obj,columns)
for obj in model.query.filter_by(**conditions)
]
return dumps(serialized_objs)
def objectToJson(obj):
columns = [c.key for c in class_mapper(obj.__class__).columns]
serialized_obj = serialize(obj, columns)
return dumps(serialized_obj)
def getUserId(username):
user = Use... | r is None:
raise Exception('username %s not found in database' % username)
else:
return user.id
def getGroupId(groupname):
group = Group.query.filter_by(groupname=groupname).first()
if group is None:
raise Exception('groupname %s not found in database' % groupname)
else:
return group.id |
dcabalas/UNI | SN/Python/ocho.py | Python | gpl-3.0 | 301 | 0.013289 | class ocho:
def __init__(self):
self.cadena=''
def getString(self):
self.cadena = raw_input("Your desires are orders to me: | ")
def printString(self):
print "Here's your sentence: {cadena}".format(cadena=self.cadena)
oct = ocho()
oct.getString()
oct | .printString()
|
DigitalCampus/django-oppia | tests/reports/views/test_completion_rates.py | Python | gpl-3.0 | 1,385 | 0 | from django.urls import reverse
from oppia.test import OppiaTestCase
class CompletionRatesViewTest(OppiaTestCase):
fixtures = ['tests/test_user.json',
'tests/test_oppia.json',
'tests/test_quiz.json',
'tests/test_permissions.json',
'tests/test_cohort.... | user)
response = self.client.get(url)
| self.assertRedirects(response,
'/admin/login/?next=' + url,
302,
200)
|
pierre-chaville/automlk | automlk/utils/keras_wrapper.py | Python | mit | 2,073 | 0.00193 | import logging
log = logging.getLogger(__name__)
try:
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.normalization import BatchNormalization
from keras.layers.advanced_activations import PReLU, LeakyReLU
from keras.optimizers import A... | eras.utils import to_categorical
import_keras = True
except:
import_keras = False
log.info('could not import keras. Neural networks will not be used')
def keras_create_model(params, problem_type):
# creates a neural net model with params definition
log.info('creating NN structure')
model = S... | l()
for l in range(int(params['number_layers'])):
if l == 0:
model.add(Dense(units=params['units'], input_dim=params['input_dim']))
else:
model.add(Dense(units=params['units']))
model.add(Activation(params['activation']))
if params['batch_normalization']:
... |
Dklotz-Circle/security_monkey | security_monkey/common/route53.py | Python | apache-2.0 | 3,538 | 0.001696 | # Copyright 2014 Netflix, 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... | ning permissions and
# limitations under the License.
"""
.. module:: route53
:platform: Unix
:synopsis: Module contains a useful Route53 class.
.. version:: @VERSION@
.. author:: Kevin Glisson (kglisson@netflix.com), Patrick Kelley (patrick@netflix.com) @monkeysecurity
"""
import os
import re
import boto
... | mport boto.route53.record
from security_monkey import app
class Route53Service(object):
"""
Class provides useful functions of manipulating Route53 records
"""
def __init__(self, **kwargs):
super(Route53Service, self).__init__(**kwargs)
self.conn = boto.connect_route53()
... |
chimeno/wagtail | wagtail/wagtailsnippets/widgets.py | Python | bsd-3-clause | 1,643 | 0.001826 | from __future__ import absolute_import, unicode_literals
import json
from djan | go.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailadmin.widgets import AdminChooser
class | AdminSnippetChooser(AdminChooser):
target_content_type = None
def __init__(self, content_type=None, **kwargs):
if 'snippet_type_name' in kwargs:
snippet_type_name = kwargs.pop('snippet_type_name')
self.choose_one_text = _('Choose %s') % snippet_type_name
self.choose... |
CANTUS-Project/abbot | holy_orders/current.py | Python | gpl-3.0 | 6,147 | 0.003579 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#--------------------------------------------------------------------------------------------------
# Program Name: holy_orders
# Program Description: Update program for the Abbot Cantus API server.
#
# Filename: holy_orders/current.py
# Purpose:... | on should correspond
to the moment just before data are requested from Drupal.
'''
time = time.isoformat()
updates_db.cursor().execute('UPDATE rtypes SET upda | ted=? WHERE name=?;', (time, rtype))
updates_db.commit()
|
Lorquas/subscription-manager | test/fixture.py | Python | gpl-2.0 | 18,129 | 0.001655 | from __future__ import print_function, division, absolute_import
import difflib
import locale
import os
import pprint
import six
import sys
import tempfile
try:
import unittest2 as unittest
except ImportError:
import unittest
# just log py.warnings (and pygtk warnings in particular)
import logging
try:
... | locale.LC_ALL
locale.setlocale(category, new_locale)
try:
yield
finally:
locale.setlocale(category, old_locale)
class FakeLogger(object):
def __init__(self):
self.expected_msg = ""
self.msg = None
self.logged_exception | = None
def debug(self, buf, *args, **kwargs):
self.msg = buf
def error(self, buf, *args, **kwargs):
self.msg = buf
def exception(self, e, *args, **kwargs):
self.logged_exception = e
def set_expected_msg(self, msg):
self.expected_msg = msg
def info(self, buf, *ar... |
reinforceio/tensorforce | tensorforce/core/parameters/random.py | Python | apache-2.0 | 4,125 | 0.002182 | # Copyright 2020 Tensorforce Team. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | tddev</b> (<i>float > 0.0</i>) – Standard deviation
(<span style="color:#00C000"><b>default</b></span>: 1.0).</li>
</ul>
Uniform distribution:
<ul>
<li><b>minval</b> (<i>int / float</i>) – Lower bound
(<span style="color:#00C000"><b>def... | <li><b>maxval</b> (<i>float > minval</i>) – Upper bound
(<span style="color:#00C000"><b>default</b></span>: 1.0 for float,
<span style="color:#C00000"><b>required</b></span> for int).</li>
</ul>
name (string): <span style="color:#0000C0"><b>internal use</b></sp... |
cagdass/ml-easy-peer-grade | setup.py | Python | gpl-3.0 | 525 | 0.04381 | from distutils.core import setup
setup(
name = 'ml_easy_ | peer_grade',
packages = ['ml_easy_peer_grade'],
version = '0.18',
scripts=['bin/ml_easy_peer_grade'],
description = 'Ez peer grade your project members, exclusive to privileged Bilkent students',
author = 'Cuklahan Dorum',
author_email = 'badass@alumni.bilkent.edu.tr',
url = 'https://github.com/cagdass/m... | 'https://github.com/cagdass/ml-easy-peer-grade/tarball/0.1',
keywords = ['testing'],
classifiers = [],
)
|
makoshark/Mediawiki-Utilities | mw/api/collections/revisions.py | Python | mit | 8,519 | 0.006926 | import logging
from ...util import none_or
from ..errors import MalformedResponse
from .collection import Collection
logger = logging.getLogger("mw.api.collections.revisions")
class Revisions(Collection):
"""
A collection of revisions indexes by title, page_id and user_text.
Note that revisions of delet... | vids'] = | self._items(revids, type=int)
params['titles'] = self._items(titles)
params['pageids'] = self._items(pageids, type=int)
params['rvprop'] = self._items(properties, levels=self.PROPERTIES)
if revids == None: # Can't have a limit unless revids is none
params['r... |
HopeFOAM/HopeFOAM | ThirdParty-0.1/ParaView-5.0.1/VTK/Imaging/Core/Testing/Python/TestAllMaskBits.py | Python | gpl-3.0 | 3,568 | 0.002522 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
=========================================================================
Program: Visualization Toolkit
Module: TestNamedColorsIntegration.py
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.... | ===================================================================
'''
import vtk
import vtk.test.Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
class TestAllMaskBits(vtk.test.Testing.vtkTest):
def testAllMaskBits(self):
# This script calculates the luminance of an im... | # Image pipeline
image1 = vtk.vtkTIFFReader()
image1.SetFileName(VTK_DATA_ROOT + "/Data/beach.tif")
# "beach.tif" image contains ORIENTATION tag which is
# ORIENTATION_TOPLEFT (row 0 top, col 0 lhs) type. The TIFF
# reader parses this tag and sets the internal TIFF image
... |
mtils/sqliter | examples/testdata.py | Python | mit | 9,753 | 0.022147 |
from __future__ import print_function
dictData = [
{'forename':'Marc','surname':'Mine','age':35, 'tags':('family','work'),
'job':{'name':'Baker','category':'Business'},
'hobbies':[{'name':'swimming','period':7},
{'name':'reading','period':1}]},
... | name in select().from_(dictData).where(c('"family"').in_(c('tags'))):
print_func(name)
print_func('-------- SELECT FROM dictData WHERE job.name == "President"')
for name in select().from_(dictData).where(c('job.name') == 'President'):
print_func(name)
print_func('-------- SELECT FROM dictDa... | == "Business"')
for name in select().from_(dictData).where(c('job.category') == 'Business'):
print_func(name)
print_func('-------- SELECT FROM dictData WHERE job.category IN ("Business", "Social")')
for name in select().from_(dictData).where(c('job.category').in_('Business','Social')):
print... |
concurrence/concurrence | lib/concurrence/database/mysql/proxy.py | Python | bsd-3-clause | 3,790 | 0.007916 | # Copyright (C) 2009, Hyves (Startphone Ltd.)
#
# This module is part of the Concurrence Framework and is released under
# the New BSD License: http://www.opensource.org/licenses/bsd-license.php
from concurrence.timer import Timeout
from concurrence.database.mysql import ProxyProtocol, PacketReader, PACKET_READ_RESULT... | return n
def run(self):
while True:
state = self.protocol.state
if state in SERVER_STATES:
self.direction = self.SE | RVER_TO_CLIENT
self.readStream = self.serverStream
self.writeStream = self.clientStream
n = self.cycle(self.protocol.readServer)
elif state in CLIENT_STATES:
self.direction = self.CLIENT_TO_SERVER
self.readStream = self.clientSt... |
jhartz/masterchess | setup.py | Python | gpl-3.0 | 5,318 | 0.003197 | """
Setup/build script for MasterChess
For usage info, see readme.md
"""
import os, sys, subprocess
from distutils.dir_util import copy_tree
from setuptools import setup
from MasterChessGUI import __description__, __copyright__, __version__
def get_folder(path):
if isinstance(path, list):
return [get_fo... | ]
}
}
}
})
elif sys.platform == "win32" and "py2exe" in sys.argv:
import py2exe
options.update({
"setup_requires": ["py2exe"],
"data_files": DATA_FILES,
"windows": [
{
"script": "MasterChessGUI.py",
"i... | st this!!
}
]
})
if PY2EXE_BUNDLE:
options.update({
"options": {
"py2exe": {
"bundle_files": 1
}
},
"zipfile": None
})
else:
options.update({
"scripts": ["MasterChessGUI.py"],
... |
kittiu/sale-workflow | sale_exception/models/sale.py | Python | agpl-3.0 | 2,008 | 0 | # -*- coding: utf-8 -*-
# © 2011 Raphaël Valyi, | Renato Lima, Guewen Baconnier, Sodexis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models, fields
class ExceptionRule(models.Model):
_inherit = 'exception.rule'
rule_group = fields.Selection(
selection_add=[('sale', 'Sale')],
)
model = fields.S... | Sale order line'),
])
class SaleOrder(models.Model):
_inherit = ['sale.order', 'base.exception']
_name = 'sale.order'
_order = 'main_exception_id asc, date_order desc, name desc'
rule_group = fields.Selection(
selection_add=[('sale', 'Sale')],
default='sale',
)
@api.m... |
elbeardmorez/quodlibet | quodlibet/quodlibet/qltk/unity.py | Python | gpl-2.0 | 2,257 | 0 | # -*- coding: utf-8 -*-
# Copyright 2013 Christoph Reiter
#
# 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.
"""Everythi... | "Unity", ["7.0", "6.0", "5.0"])
from gi.repository import Unity
except (ValueError, ImportError):
is_unity = False
|
def init(desktop_id, player):
"""Set up unity integration.
* desktop_id: e.g. 'quodlibet.desktop'
* player: BasePlayer()
http://developer.ubuntu.com/api/devel/ubuntu-12.04/c/Unity-5.0.html
http://developer.ubuntu.com/api/devel/ubuntu-13.10/c/Unity-7.0.html
"""
if not is_unity:
re... |
jacksarick/My-Code | Events/CCC/2015/J4.py | Python | mit | 601 | 0.021631 | #Problem J4: Wait Time
inputarray = []
for i in range(input()):
inputarray.append(raw_input().split(" "))
#Number, total, lastwait, response
friendarray = []
ctime = 0
for i in range(len(inpu | tarray)):
if inputarray[i][0].lower() == "c":
ctime += inputarray[i][1]
if inputarray[i][0].lower() == "r":
friendlist = [friendarray[j][0] for j in range(len(friendarray))]
if (inputarray[i][1] not in friendlist):
friendarray.append([inputarray[i][0].lower(), 0, ])
else:
| location = friendlist.index(inputarray[i][1])
friendarray[location] = [inputarray[i][1], friendarray[location] + ]
|
alemonmk/pytgasu | pytgasu/upload/defparse.py | Python | gpl-3.0 | 2,873 | 0.001044 | # pytgasu - Automating creation of Telegram sticker packs
# Copyright (C) 2017 Lemon Lam <almk@rmntn.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# ... | image_path = def_file.with_name(image_filename)
if not _validate_image(image_path):
continue
if not emoji_seq:
emoji_seq = DEFAULT_EMOJI
| stickers.append((image_path, emoji_seq))
if not stickers:
print(ERROR_NO_STICKER_IN_SET)
return None
return set_title, set_short_name, stickers
def _validate_image(image_path):
"""
Check file existence, image is correct PNG,
dimension is 512x? or ?x512 and fi... |
PythonProgramming/Pandas-Basics-with-2.7 | pandas 5 - Column Operations (Basic mathematics, moving averages).py | Python | mit | 416 | 0.009615 | import pandas as pd
from pandas import DataFrame
df = pd.read_csv('sp500_ohlc.csv', index_col = 'Date', parse | _dates=True)
#notice what i did, since it is an object
df[ | 'H-L'] = df.High - df.Low
print df.head()
df['100MA'] = pd.rolling_mean(df['Close'], 100)
# must do a slice, since there will be no value for 100ma until 100 points
print df[200:210]
df['Difference'] = df['Close'].diff()
print df.head()
|
regular/talkshow | wrappers.py | Python | gpl-3.0 | 20,806 | 0.01341 | import weakref
from sys import getrefcount
import string
import talkshowConfig
style = talkshowConfig.config().parser.style
from talkshowLogger import logger
debug = logger.debug
info = logger.info
warn = logger.warn
#?? pyglet.options['audio'] = ('directsound', 'openal', 'silent')
from pyglet.gl import *
from pygl... | ht
glViewport(0, 0, width, height)
glMatrixMode(gl.GL_PROJECTION)
glLoadIdentity()
gluOrtho2D(0, width, 0, height);
glScalef(1, -1, 1);
glTranslatef(0, -height, 0);
glMatrixMode(gl.GL_MODELVIEW)
h = ... |
self.window.on_resize = on_resize
@self.window.event
def on_draw():
self.window.clear()
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_BLEND)
for x in self.__children__:
x.draw()
... |
blindsightcorp/rigor-webapp | plugins/percept_search_page/__init__.py | Python | bsd-2-clause | 9,018 | 0.028055 | from __future__ import division
import json
import urllib
from flask import request
from flask import render_template
from flask import abort
import jinja2
import rigor.config
import rigorwebapp.plugin
import rigorwebapp.utils
from rigorwebapp.utils import debug_detail, debug_main, debug_error
import rigorwebapp.aut... | Search
</div>
<form id="perceptSearchForm">
<div class="searchFormRow">
<div class="searchFormRowLabel">
Database
</ | div>
<select class="searchFormSelect" id="perceptSearchFormDbSelect">
{% for this_db_name in db_names %}
{% if this_db_name == db_name %}
<option value={{this_db_name}} selected>{{this_db_name}}</option>
{% else %}
<option value={{this_db_name}}>{{this_db_name}}</option>
... |
sheimi/os-benchmark | script/analysis/analysis.py | Python | gpl-3.0 | 3,736 | 0.005621 | #!/usr/bin/env python
from os import path
from collections import defaultdict
import math
root = path.dirname(path.dirname(path.dirname(__file__)))
result_dir = path.join(root, 'results')
def get_file_name(test):
test = '%s_result' % test
return path.join(result_dir, test)
def mean(l):
return float(sum(l... | .split(' ')[0]))
datas = [i for i in datas[:10000]]
print "%s mean: %f" % (test_name, mean(datas))
print "%s std dev: %f" % (test_name, std_dev(datas))
def run_proc_call_overhead_ana():
test_na | me = 'proc_call_overhead'
file_name = get_file_name(test_name)
datas = []
with open(file_name) as f:
for l in f:
if l.startswith('-'):
datas.append([])
continue
datas[-1].append(int(l.split(' ')[0]) * 1.0 / 10)
print "%s result:" % test_nam... |
pschmitt/home-assistant | homeassistant/components/airly/air_quality.py | Python | apache-2.0 | 3,907 | 0.000768 | """Support for the Airly air_quality service."""
from homeassistant.components.air_quality import (
ATTR_AQI,
ATTR_PM_2_5,
ATTR_PM_10,
AirQualityEntity,
)
from homeassistant.const import CONF_NAME
from .const import (
ATTR_API_ADVICE,
ATTR_API_CAQI,
ATTR_API_CAQI_DESCRIPTION,
ATTR_API_C... | nd_state(func):
"""Round state."""
def _decorator(self):
| res = func(self)
if isinstance(res, float):
return round(res)
return res
return _decorator
class AirlyAirQuality(AirQualityEntity):
"""Define an Airly air quality."""
def __init__(self, coordinator, name, unique_id):
"""Initialize."""
self.coordinator = coord... |
sandrafig/addons | calendar_event_meeting_reason/models/calendar_event.py | Python | agpl-3.0 | 488 | 0.004098 | # -*- coding: utf-8 -*-
from openerp import models, fields, api
class CalendarEvent(models.Model):
_inherit = 'calendar.event'
meeting_reason_id = fields.Many2one(
'calendar.event.meeting.reason',
| string="Meeting reason",
ondelete="restrict")
class | CalendarEventMeetingReason(models.Model):
_name = 'calendar.event.meeting.reason'
_description = 'Calendar Event Meeting Reason'
name = fields.Char('Reason', required=False, translate=True)
|
engineer0x47/SCONS | engine/SCons/Tool/mwcc.py | Python | mit | 6,841 | 0.003947 | """SCons.Tool.mwcc
Tool-specific initialization for the Metrowerks CodeWarrior compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
#
# Permission is he... | ## This function finds CodeWarrior by reading from the registry on
### Windows. Some other method needs to be implemented for other
### platforms, maybe something that calls | env.WhereIs('mwcc')
if SCons.Util.can_read_reg:
try:
HLM = SCons.Util.HKEY_LOCAL_MACHINE
product = 'SOFTWARE\\Metrowerks\\CodeWarrior\\Product Versions'
product_key = SCons.Util.RegOpenKeyEx(HLM, product)
i = 0
while True:
name = ... |
basp/neko | spikes/main.py | Python | mit | 2,241 | 0.002231 | # Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTW... | 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 1)
builtins = {'me': 123} # $tags: stub, example, todo
def eval_str(s, globals):
try:
r = eval(s, globals)
return str(r)
except Exception as e | :
return str(e)
def on_command(sender, args):
if args.key.vk != libtcod.KEY_ENTER:
return
s = text_field.get_text()
if match.starts_with(';', s):
r = eval_str(s[1:], builtins)
text_view.lines.append(str(r))
else:
tokens = tokenizer.tokenize(s)
cmd = comma... |
itbabu/django-oscar | src/oscar/apps/catalogue/admin.py | Python | bsd-3-clause | 3,190 | 0 | from django.contrib import admin
from treebeard.admin import TreeAdmin
from treebeard.forms import movenodeform_factory
from oscar.core.loading import get_model
AttributeOption = get_model('catalogue', 'AttributeOption')
AttributeOptionGroup = get_model('catalogue', 'AttributeOptionGroup')
Category = get_model('catal... | Product')
ProductAttribute = get_model('catalogue', 'ProductAttribute')
ProductAttributeValue = get_model('catalogue', 'ProductAttributeValue')
ProductCategory = get_model('catalogue', 'ProductCategory')
ProductClass = get_model('catalogue', 'ProductClass')
ProductImage = get_model('catalogue', 'ProductImage')
P | roductRecommendation = get_model('catalogue', 'ProductRecommendation')
class AttributeInline(admin.TabularInline):
model = ProductAttributeValue
class ProductRecommendationInline(admin.TabularInline):
model = ProductRecommendation
fk_name = 'primary'
raw_id_fields = ['primary', 'recommendation']
c... |
lezzago/LambdaMart | RegressionTree.py | Python | mit | 6,591 | 0.038082 | # regression tree
# input is a dataframe of features
# the corresponding y value(called labels here) is the scores for each document
import pandas as pd
import numpy as np
from multiprocessing import Pool
from itertools import repeat
import scipy
import scipy.optimize
node_id = 0
def get_splitting_points(args):
#... |
return best_split, best_children # return a tuple(attribute, value)
def split_children(data, label, key, split):
left_index = [index for index in xrange(len(data.iloc[:,key])) if data.iloc[index,key] < split]
right_inde | x = [index for index in xrange(len(data.iloc[:,key])) if data.iloc[index,key] >= split]
left_data = data.iloc[left_index,:]
right_data = data.iloc[right_index,:]
left_label = [label[i] for i in left_index]
right_label =[label[i] for i in right_index]
return left_data, left_label, right_data, right_label
def le... |
aherlihy/Monary | doc/conf.py | Python | apache-2.0 | 8,410 | 0.006183 | # -*- coding: utf-8 -*-
#
# Monary documentation build configuration file, created by
# sphinx-quickstart on Wed Jul 9 13:39:38 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... | links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_i | ndices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'monary', u'Monary Documentation',
[u'David J. C. Beach'], 1)
]
# If true, show UR... |
dpgaspar/Flask-AppBuilder | flask_appbuilder/charts/views.py | Python | bsd-3-clause | 17,665 | 0.000566 | import logging
from flask_babel import lazy_gettext
from .jsontools import dict_to_json
from .widgets import ChartWidget, DirectChartWidget
from ..baseviews import BaseModelView, expose
from ..models.group import DirectProcessData, GroupByProcessData
from ..security.decorators import has_access
from ..urltools import... | definition="",
**args
):
| height = height or self.height
widgets = widgets or dict()
joined_filters = filters.get_joined_filters(self._base_filters)
# check if order_column may be database ordered
if not self.datamodel.get_order_columns_list([order_column]):
order_column = ""
order_d... |
mjfarmer/scada_py | pymodbus/examples/common/asynchronous-client.py | Python | gpl-3.0 | 5,916 | 0.011663 | #!/usr/bin/env python
'''
Pymodbus Asynchronous Client Examples
--------------------------------------------------------------------------
The following is an example of how to use the asynchronous modbus
client implementation from pymodbus.
'''
#------------------------------------------------------------------------... | ne by specifying the `unit` parameter
# which defaults to `0x00`
#---------------------------------------------------------------------------#
def exampleRequests(client):
rr = client.read_coils(1, 1, unit=0x02)
#---------------------------------------------------------------------------#
# example requests
#---... | -------------------------------------------------------#
# simply call the methods that you would like to use. An example session
# is displayed below along with some assert checks. Note that unlike the
# synchronous version of the client, the asynchronous version returns
# deferreds which can be thought of as a handl... |
tiangolo/fastapi | tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py310.py | Python | mit | 3,293 | 0.000607 | import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py310
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"get": {
"responses": {
"200": {
... | "title": "Q",
"type": "array",
"items": {"type": "string"},
},
| "name": "q",
"in": "query",
}
],
}
}
},
"components": {
"schemas": {
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
... |
QuantumQuadrate/CsPyController | python/vaunix.py | Python | lgpl-3.0 | 9,955 | 0.012858 | from __future__ import division
"""
instek_pst.py
part of the CsPyController package for AQuA experiment control by Martin Lichtman
Handles sending commands to Instek PST power supplies over RS232.
created = 2015.07.09
modified >= 2015.07.09
"""
__author__ = 'Martin Lichtman'
import logging
logger =... | self.va = CDLL(CDLL_file)
if (self.testMode):
logger.warning("Warning: Vaunix in test mode. Set testMode=False in vaunix.py to turn off test mode.")
self.va.fnLMS_SetTestMode(self.testMode) #Test mode... this needs to be set False for actual run. Do not remove th... | elf, hdf5):
if self.enable:
if (not self.isInitialized):
self.initialize()
for i in self.motors:
#initialize serial connection to each power supply
i.initialize(self.va)
self.isInitialized = Tr... |
kaarl/pyload | module/plugins/hoster/XDCC.py | Python | gpl-3.0 | 7,856 | 0.006237 | # -*- coding: utf-8 -*-
import os
import re
import select
import socket
import struct
import time
from module.plugins.internal.Hoster import Hoster
from module.plugins.internal.misc import exists, fsjoin
class XDCC(Hoster):
__name__ = "XDCC"
__type__ = "hoster"
__version__ = "0.42"
__status__ ... | nmn)
| return
except socket.error, e:
if hasattr(e, "errno") and e.errno is not None:
err_no = e.errno
if err_no in (10054, 10061):
self.log_warning("Server blocked our ip, retry in 5 min")
self.wait(300)
... |
chintak/image-captioning | scripts/tfrecord_writer.py | Python | mit | 5,331 | 0.002626 | import os
import argparse
import tensorflow as tf
import numpy as np
import sys
sys.path.append('../')
from reader import flickr8k_raw_data
def make_example(image_feature, caption_feature, id):
# The object we return
ex = tf.train.SequenceExample()
# A non-sequential feature of our example
sequence_le... | on_tokens_dir, 'dump.txt'), 'w') as fp:
from pprint import pformat
fp.write("\n###### vocab######\n")
fp.write(pformat(vocab))
fp.write("\n###### tra | in ######\n")
rand_train_caps = {
'names': [train_caps['names'][i] for i in rand_idx],
'word_to_ids': [train_caps['word_to_ids'][i] for i in rand_idx],
}
fp.write(pformat([(n, w) for n, w in zip(
rand_train_caps['names'], rand_train_caps['word_to_ids'])]))
fp.write("\n###... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.