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 |
|---|---|---|---|---|---|---|---|---|
GeneralizedLearningUtilities/SuperGLU | python_module/stomp/test/basic_test.py | Python | mit | 7,571 | 0.004095 | import os
import signal
import time
import unittest
import stomp
from stomp import exception
from stomp.backward import monotonic
from stomp.listener import TestListener
from stomp.test.testutils import *
class TestBasicSend(unittest.TestCase):
def s | etUp(self):
conn = stomp.Connection(get_default_host())
listener = TestListener('123')
conn.set_listener('', listener)
conn.start()
conn.connect(get_default_user(), get_default_password(), wait=True)
self.conn = conn
self.listener = listener
self.t... | if self.conn:
self.conn.disconnect(receipt=None)
def test_basic(self):
queuename = '/queue/test1-%s' % self.timestamp
self.conn.subscribe(destination=queuename, id=1, ack='auto')
self.conn.send(body='this is a test', destination=queuename, receipt='123')
sel... |
krishauser/Klampt | Python/klampt/io/html.py | Python | bsd-3-clause | 7,673 | 0.009384 | """An exporter that converts scenes / animations to shareable HTML files.
"""
from klampt import *
from klampt.model import trajectory
from klampt import robotsim
import json
import pkg_resources
_title_id = '__TITLE__'
_scene_id = '__SCENE_JSON__'
_path_id = '__PATH_JSON__'
_rpc_id = '__RPC_JSON__'
_compressed_id = ... | or):
self.sim = world
self.world = world.world
| self.last_t = world.getTime()
else:
self.sim = None
self.world = world
if self.world is not None:
self.scene = robotsim.ThreeJSGetScene(self.world)
def animate(self,time=None,rpc=None):
"""Updates the path from the world. If the world wasn't a simulator,... |
tsdmgz/ansible | test/units/plugins/test_plugins.py | Python | gpl-3.0 | 3,565 | 0.000842 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... | f fake_glob(path):
# if path == 'test | /*':
# return ['test/foo', 'test/bar', 'test/bam']
# elif path == 'test/*/*'
# m._paths = None
# mock_glob = MagicMock()
# mock_glob.return_value = []
# with patch('glob.glob', mock_glob):
# pass
def assertPluginLoaderConfigBecomes(self, arg, ... |
danialbehzadi/Nokia-RM-1013-2.0.0.11 | webkit/Tools/Scripts/webkitpy/tool/steps/revertrevision.py | Python | gpl-3.0 | 1,769 | 0.001696 | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and th... | HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN C | ONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from webkitpy.tool.steps.abstractstep import AbstractStep
class RevertRevision(AbstractStep):
def run(self, state):
self._tool.... |
syncrypt/client | syncrypt/models/bundle.py | Python | gpl-3.0 | 6,725 | 0.00223 | import hashlib
import logging
import os
import posixpath
from typing import Optional
import trio
import umsgpack
from sqlalchemy import Column, ForeignKey, Integer, LargeBinary, String, orm
from sqlalchemy.orm import relationship
from syncrypt.exceptions import InvalidBundleKey, InvalidBundleMetadata
from syncrypt.pi... | ODO: on POSIX systems, the path conversion could be skipped for performance
relp | ath = posixpath.join(*splitpath(relpath))
return relpath.encode(self.vault.config.encoding, 'surrogateescape')
def decode_path(self, relpath):
"Decodes a POSIX path in bytes into a relative path"
# TODO: on POSIX systems, the path conversion could be skipped for performance
if isins... |
UtrechtUniversity/yoda-portal | connman.py | Python | gpl-3.0 | 2,062 | 0.004365 | #!/usr/bin/env python3
__copyright__ = 'Copyright (c) 2021, Utrecht University'
__license__ = 'GPLv3, see LICENSE'
import threading
import time
TTL = 60 * 30
class Session(object):
def __init__(self, sid, irods):
| """Session object storing the iRODS session object.
:param sid: Flask s | ession identifier
:param irods: iRODS session
"""
self.sid = sid
self.irods = irods
self.time = time.time()
self.lock = threading.Lock()
def __del__(self):
self.irods.cleanup()
print('[gc/logout]: Dropped iRODS session of session {}'.format(self.s... |
emonty/pyos | samples/cloud_blockstorage/create_snapshot.py | Python | apache-2.0 | 1,828 | 0.000547 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c)2012 Rackspace US, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.ap... | mport os
import sys
import pyos
import pyos.exceptions as exc
pyos.set_setting("identity_type", "rackspace")
creds_file = os.path.expanduser("~/.rackspace_cloud_credentials")
pyos.set_credential_file(creds_file)
cbs = pyos.cloud_blockstorage
vol_name = pyos.utils.random_ascii(length=8)
vol = cbs.create(name="sample_v... | ume", size=500, volume_type="SATA")
snap = vol.create_snapshot("sample_snap")
print("Volume:", vol)
print("Snapshot:", snap)
print()
print("You have to wait until the snapshot finishes being created before")
print("it can be deleted. Press Ctrl-C to interrupt.")
try:
pyos.utils.wait_until(snap, "status", "availab... |
Gebesa-Dev/Addons-gebesa | suppliers_incidences/models/supplier_incident.py | Python | agpl-3.0 | 1,923 | 0 | # -*- coding: utf-8 -*-
# © <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import api, _, fields, models
class SupplierIncident(models.Model):
_name = 'supplier.incident'
_inherit = ['mail.thread']
_description = "Suppliers Incidences"
_order =... | ways')
partner_id = fields.Many2one(
'res.partner',
string=_('Supplier'),
track_visibility='onchange')
user_id = fields.Many2one(
'res.users',
string=_('Rep | orts'),
default=lambda self: self._uid,
track_visibility='onchange')
company_id = fields.Many2one(
'res.company',
string=_('Company'),
default=lambda self: self.env['res.company']._company_default_get(
'supplier_incident'),
track_visibility='always')
... |
cnewcome/sos | sos/plugins/processor.py | Python | gpl-2.0 | 1,568 | 0 | # 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 hope that it will be useful,
# but... | have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
from sos.plugins import Plugin, RedHatPlugin, UbuntuPlugin, DebianPlugin
class Processor(Plugin, RedHatPlugin, UbuntuPlugin, DebianPlugin):
... | processor'
profiles = ('system', 'hardware', 'memory')
files = ('/proc/cpuinfo',)
packages = ('cpufreq-utils', 'cpuid')
def setup(self):
self.add_copy_spec([
"/proc/cpuinfo",
"/sys/class/cpuid",
"/sys/devices/system/cpu"
])
self.add_cmd_outpu... |
subuser-security/subuser | subuserlib/classes/exceptions.py | Python | lgpl-3.0 | 318 | 0.025157 | # -*- coding: utf-8 -*-
"""
This is a collection of excep | tions which are raised throughout the sourcecode.
"""
#external imports
#import ...
#internal imports
#import ..
class ImageBuildException(Exception):
"""
This exception is raised any time an image fails to build and subuser is not at fault.
"""
| pass
|
jackbrucesimpson/DBee | src/analyse_db.py | Python | mit | 896 | 0.006696 | #!/usr/bin/env python3
import sys
import datetime
import random
import numpy as np
import pandas as pd
from beehaviour.experiment import Experiment
np.random.seed(1)
def parse_experiment_numbers(experiment_numbers_str):
experiment_numbers_list_str = experiment_numbers_str.split(',')
experiment_numbers = [in... | n experiment_numbers_list_str]
return experiment_numbers
def main():
all_hive_ids = parse_experiment_numbers(sys.argv[1])
for hive_id in all_hive_ids:
experiment = Experiment(hive_id)
for day_num, day_grouped_bees in enumerate(experiment.day_grouped_bees):
experiment.calculate... | _night_metrics(day_num)
output_df = pd.DataFrame(experiment.logger.output)
output_df.to_csv('{}{}_output.csv'.format(experiment.output_dir, experiment.hive_id), index=False)
if __name__ == "__main__":
main()
|
GregorR/RetroArch | github-contributors.py | Python | gpl-3.0 | 2,716 | 0.011782 | #!/usr/bin/python3
#
# Get list of repo contributors from GitHub using v4 GraphQL API
#
# Copyright (C) 2018 - Brad Parker
#
# 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 t... | = 'libretro'
repoName = 'RetroArch'
### END SETTINGS ###
######
lines = []
def get_contributors(after=None):
global lines
headers = {'Authorization': 'bearer ' + TOKEN}
url = 'https://api.github.com/graphql'
dataStr = """{
repository(owner: \"""" + orgName + """\", name: \"""" + repoName + """\") {
"""
... | """\") {
"""
else:
dataStr += """
mentionableUsers(first: 100) {
"""
dataStr += """
edges {
node {
name
login
}
cursor
}
}
}
}
"""
d = {'query': dataStr}
data = json.dumps(d).encode('utf-8')
req = Request(url, data... |
robertbarrett/eventsottawabot | eventsOttawaBot.py | Python | mit | 7,649 | 0.005752 | #!/bin/python
import praw
import re
import os
import sqlite3
import time
from config_bot import *
import datetime
header = "Type|Artist(s)/Event|Venue|Price|Time\n---|---|---|---|---|---|---|\n"
footer1 = "------------------------\n[Link to next week's draft post]("
footer2 = "). If you know of something awesome hap... | code starts here
if not os.path.isfile("config_bot.py"):
print "You must c | reate a config file with your username and password."
exit(1)
# http://pythonforengineers.com/build-a-reddit-bot-part-2-reply-to-posts/
verifyTablesExist()
threadVal = raw_input('Please enter Reddit thread to be watched: ')
user_agent = ("/r/EventsOttawa automation for /u/SergeantAlPowell")
r = praw.Reddit(... |
psiq/gdsfactory | pp/components/cdc.py | Python | mit | 3,663 | 0.003276 | from typing import Callable, Tuple, Optional
import numpy as np
import picwriter.components as pc
from pp.components.waveguide_template import wg_strip
from pp.picwriter2component import picwriter2component
import pp
from pp.component import Component
@pp.autoname
def cdc(
length: float = 30.0,
gap: float =... | fins=fins,
fin_size=fin_size,
contradc_wgt=contradc_wgt,
port=port_midpoint,
direction=direction,
)
component = picwriter2component(c)
pp.port.rename_ports_by_orientation(component)
return component |
if __name__ == "__main__":
import pp
c = cdc()
print(c.ports.keys())
pp.show(c)
|
jgbarah/GrimoireLib | vizgrimoire/GrimoireUtils.py | Python | gpl-3.0 | 24,306 | 0.007735 | # -*- coding: utf-8 -*-
#
#!/usr/bin/env python
#
# Copyright (C) 2014 Bitergia
#
# 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 option) any late... | eTimeSeries({})
dates.pop('id')
dates[period] = []
dates = completePeriodIds(dates, period, startdate, enddate)
# Remove zeros
dates['date'] | = [d for d in dates['date'] if d != 0]
dates['unixtime'] = [d for d in dates['unixtime'] if d != 0]
return dates
# Convert a R data frame to a python dictionary
def dataFrame2Dict(data):
dict_ = {}
# R start from 1 in data frames
for i in range(1,len(data)+1):
# Get the columns data fra... |
int-0/aftris | render.py | Python | gpl-3.0 | 2,746 | 0.001092 | #!/usr/bin/env python
import pygame
from pygame.locals import color
import resources
import basic as theme
class Render(object):
def __init__(self, game):
self.__game = game
scr_size = (self.__game.size[0] * theme.BRICK_SIZE + 4,
self.__game.size[1] * theme.BRICK_SIZE + 4)
... | * theme.BRICK_SIZE,
| (y + self.__game.player_position[1]) * theme.BRICK_SIZE))
return self.surface
|
ktbs/ktbs | lib/rdfrest/__init__.py | Python | lgpl-3.0 | 1,998 | 0.000501 | # -*- coding: utf-8 -*-
# This file is part of RDF-REST <http://champin.net/2012/rdfrest>
# Copyright (C) 2011-2012 Pierre-Antoine Champin <pchampin@liris.cnrs.fr> /
# Françoise Conil <francoise.conil@liris.cnrs.fr> /
# Universite de Lyon <http://www.universite-lyon.fr>
#
# RDF-REST is free software: yo... | descripription, refer to [Champin2013]_.
RDF-REST provides a python abstraction of REST resources,
so that client code can handle and mix local and remote resources
in a completely transparent way.
In a nutshell, a RESTful application is made of a set of *resources*, which:
* are identified by a URI,
* expose a uni... | REST:
* the uniform interface of resources is defined by :class:`.cores.ICore`;
* RDF is used as a unifying model to represent resource's states (with the
RDFLib_ library);
* :mod:`.serializers` and :mod:`.parsers` provide an extensible framework for
supporting multiple formats.
.. _RDFLib: http://rdflib.readthed... |
jmosky12/huxley | huxley/core/migrations/0006_auto__add_unique_countrypreference_school_country.py | Python | bsd-3-clause | 8,701 | 0.008275 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding unique constraint on 'CountryPreference', fields ['school', 'country']
... | , 'null': 'True', 'blank': 'True'})
},
u'core.committee': {
'Meta': {'object_name': 'Committee', 'db_table': "u'committee'"},
'countries': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['core.Country']", 'through': u"orm['core.Assignment']", 'symmetrical': '... | ax_length': '128'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '8'}),
'special': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
u'core.conference':... |
open-synergy/account-invoicing | stock_picking_invoice_product_group/__init__.py | Python | agpl-3.0 | 163 | 0 | # -*- coding: utf-8 - | *-
# Copyright 2016 Alex Comba - Agile Business Group
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from . impor | t wizards
|
gazpachoking/Flexget | flexget/components/rejected/remember_rejected.py | Python | mit | 5,404 | 0.00148 | from __future__ import unicode_literals, division, absolute_import
import logging
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from datetime import datetime, timedelta
from sqlalchemy import and_
from flexget import plugin
from flexget.event import event
from flexget.manager import... | lta(remember_time)
message = 'Remembering rejection of `%s`' % entry['title']
if remember_time:
message += ' for %i minutes' % (remember_time.seconds / 60)
log.info(message)
entry['remember_rejected'] = remember_time or remember
@plugin.priority(plugin.PRIORITY_LAST)
... | with Session() as session:
for entry in task.all_entries:
if not entry.get('remember_rejected'):
continue
expires = None
if isinstance(entry['remember_rejected'], timedelta):
expires = datetime.now() + entry['remember_r... |
facebookresearch/faiss | tests/test_binary_hashindex.py | Python | mit | 6,617 | 0.000151 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
import numpy as np
import faiss
from common_faiss_tests import make_binary_dataset
def bitvec_shuffle(a, order):
n, d =... | aiss.IndexBinaryMultiHash(dim, nhash, int(dim/nhash))
random_hash_codes = np.random.randint(0, 256, (
num_million * int(1 | e6), int(dim/8))).astype("uint8")
index1.add(random_hash_codes)
faiss.write_index_binary(index1, "/tmp/tmp.faiss")
index2 = faiss.read_index_binary("/tmp/tmp.faiss")
"""
|
monkeython/loremipsum | docs/conf.py | Python | bsd-3-clause | 6,020 | 0.000332 | # -*- coding: utf-8 -*-
#
# Python musiXmatch documentation build configuration file, created by
# sphinx-quickstart on Mon Mar 28 22:28:39 2011.
#
# 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 f... | will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# | html_file_suffix = None
|
get9/monkeyshines | robotsparser.py | Python | apache-2.0 | 1,038 | 0.000963 | import requests
import logging
from fetcher import fetch
from os.path import join
from urlobj import URLObj
from urllib.pa | rse import urljoin, urlsp | lit, urlunsplit
class RobotsParser:
def __init__(self, domain):
self.domain = domain
# Check if the file even exists first.
def exists(self):
resp = fetch(URLObj(join(self.domain, 'robots.txt')))
return (resp is not None) and (resp.status_code == requests.codes.ok)
# Actually ... |
heyost/django-skeleton | manage.py | Python | gpl-2.0 | 376 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 | -*-
#
# mdfjr - manage.py
#
# Created by PyCharm.
# User: fajar
# Date: 5/13/17
# Time: 3:50 PM
#
#
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settin | gs")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
benfitzpatrick/rose | metomi/rose/suite_engine_proc.py | Python | gpl-3.0 | 22,663 | 0 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (C) 2012-2019 British Crown (Met Office) & Contributors.
#
# This file is part of Rose, a framework for meteorological suites.
#
# Rose is free software: you can redistribute it and/or modify
# it under t... | ble global configuration."""
def __str__(s | elf):
engine, key, value = self.args
return ("%s global configuration incompatible to Rose: %s=%s" %
(engine, key, value))
class SuiteNotRunningError(Exception):
"""An exception raised when a suite is not running."""
def __str__(self):
return "%s: does not appear to b... |
jorgeslima/files_copier | modules/Files/Parser.py | Python | mit | 5,096 | 0.008438 | #!/usr/bin/pyton3.5
"""Handles the parse of the files. Scans a dir and generate the database of files to be copied"""
import time
from pathlib import Path
from ftputil import FTPHost
from paramiko import Transport,SFTPClient
from stat import S_ISDIR
from modules.DbHandler.DbHandler import DbHandler
class FilesParser(... | urce):
self.database = DbHandler()
self.dir_id = None
self.source = source
self.sftp = None
self.transport = None
source_type = source.get('type')
if not source_type:
print("Type of copy is n | ot defined in the config source section. Please fix this problem and try again")
exit(0)
def parse_files(self):
"""Main class method"""
source = self.source
if source.get('type') == 'local':
self.parse_local_host_files(source.get('path'))
return True
... |
elishowk/django-poser | poser/tests/views.py | Python | agpl-3.0 | 3,972 | 0.002769 | from __future__ import with_statement
from poser.api import create_page
from poser.apphook_pool import apphook_pool
from poser.test_utils.testcases import SettingsOverrideTestCase
from poser.test_utils.util.context_managers import SettingsOverride
from poser.views import _handle_no_page, details
from django.conf import... | rver/')
url = one.get_absolute_url | ()
request = self.get_request(url)
response = details(request, url.strip('/'))
self.assertEqual(response.status_code, 302)
def test_login_required(self):
create_page("page", "nav_playground.html", published=True,
login_required=True)
request = se... |
lsbardel/python-stdnet | tests/all/query/get_field.py | Python | bsd-3-clause | 5,457 | 0.002932 | '''Test query.get_field method for obtaining a single field from a query.'''
from stdnet.utils import test, zip, is_string
from examples.models import Instrument, ObjectAnalytics,\
AnalyticData, Group, Fund
from examples.data import FinanceTest, INSTS_TYPES, CCYS_TYPES
class Test... | nt')
result = yield qs.all()
self.assertTrue(result)
for r in result:
self.assertTrue(type(r), int)
def testFilter(self):
models = self.mapper
qs = models.position.query().get_field('instrument')
qi = models.instrument.filter(id=qs)
inst... | s = yield qs.all()
self.assertTrue(inst)
self.assertTrue(len(ids) >= len(inst))
idset = set(ids)
self.assertEqual(len(idset), len(inst))
self.assertEqual(idset, set((i.id for i in inst)))
class generator(test.DataGenerator):
sizes = {'tiny': (2,10),
'... |
choderalab/brokenyank | src/yank/__init__.py | Python | lgpl-3.0 | 294 | 0.003401 | """
YANK, a package for alchemical free energy calculations using OpenMM
"""
__author__ = "John D. Chodera"
__lice | nse__ = "GPL"
__maintainer__ = "John D. Chodera"
__email__ = "jchodera@gmail.com"
__version__ = "1.0beta"
from yank import Yank
import analysis
__all__ = ['Yank', 'analysis' | ]
|
danic96/Practica1 | Practica1/Aplicacio/admin.py | Python | mit | 274 | 0 | from django.contrib import admin
# Register your models here.
from Apl | icacio.models import Movie, Character, Location, Team, Power
admin.site.register(Movie)
admin.site.register(Character)
admin.site.register(Location)
admin.site | .register(Team)
admin.site.register(Power)
|
dreadatour/Cactus | cactus/utils/filesystem.py | Python | bsd-3-clause | 1,397 | 0 | import os
import shutil
import tempfile
from contextlib import contextmanager
from cactus.utils.helpers import map_apply
def mkdtemp():
return tempfile.mkdtemp(dir=os.environ.get("TEMPDIR"))
def fileList(paths, relative=False, folders=False):
""" |
Generate a recursive list of files from a given path.
"""
if not isinstance(paths, list):
paths = [paths]
files = []
for path in paths:
for fileName in os.listdir(path):
if fileName.startswith('.'):
continue
filePath = os.path.join(path, ... | nd(filePath)
files += fileList(filePath)
else:
files.append(filePath)
if relative:
files = map_apply(lambda x: x[len(path) + 1:], files)
return files
@contextmanager
def alt_file(current_file):
"""
Create an alternate file next to an existi... |
frozenjava/RobotSimulator | setup.py | Python | gpl-2.0 | 394 | 0 | #
# setup.py
# Josh Artuso
# Setup file to install the jbot module
#
from distutils.core import setup
setup(name='jBot',
version='1.2',
description='Educational robot simulator',
author='Josh Artuso',
url='https://github.com/frozenjava/RobotSimulator',
packages=['jbot'],
| packa | ge_dir={'jbot': 'jbot'},
package_data={'jbot': ['images/*.png']}
)
|
alexwhb/simple-python-chat-server | client.py | Python | mit | 1,667 | 0.0012 | __author__ = 'Alexander Black'
import socket
import select
import sys
def prompt():
sys.stdout.write("> ")
sys.stdout.flush()
class Client(object):
def __init__(self):
self.host = sys.argv[1]
self.port = int(sys.argv[2])
self.sock = None
self.connect_to_server()
def ... | data = sock.recv(4096)
if not data:
print '\nDisconnected from chat server'
sys.exit()
else:
# print data
sys.stdout.write(data)
prompt()
... | __name__ == '__main__':
client = Client()
|
googleglass/mirror-catfacts-python | push/handler.py | Python | apache-2.0 | 3,418 | 0.006729 | # Copyright (C) 2014 Google 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 writ... | er for push cron job."""
def get(self):
"""Retrieve all users and add taskqueue to poll Twitter feed."""
body = {
'text': util.get_cat_fact(),
'notification': {'level': 'DEFAULT | '}
}
# Limit 50 requests per batch request.
batch_requests = []
count = BATCH_REQUEST_COUNT
for user_settings in self.entities_to_process():
request = self._get_cat_fact_insert_request(
user_settings.key().name(), body)
if request:
if count >= BATCH_REQUEST_COUNT:
... |
Erotemic/local | git_tools/git_branch_relationships.py | Python | gpl-3.0 | 2,945 | 0.001019 | #!/usr/bin/env python
import itertools as it
import ubelt as ub
def check_relationships(branches):
ancestors = {b: set() for b in branches}
length = len(branches) * (len(branches) - 1)
for b1, b2 in ub.ProgIter(it.combinations(branches, 2), length=length):
ret = ub.cmd('git merge-base --is-ancest... | jon/viame/master jon/viame/next master dev/tracking-framework
viame/master viame/query-wip viame/tracking-work
viame/master-no-pybind viame/master-w-pytorch
"
"""
# branches = [x.strip() for x in '''
# jon/viame/master
# jon/viame/next
# ... | viame/master
# viame/query-wip
# viame/tracking-work
# viame/master-no-pybind
# viame/master-w-pytorch
# '''.splitlines() if x.strip()]
import sys
argv = sys.argv[1:]
branches = []
for item in argv:
for sub in it... |
asposeslides/Aspose_Slides_Java | Plugins/Aspose-Slides-Java-for-Python/tests/WorkingWithPresentation/PptToPptx/PptToPptx.py | Python | mit | 397 | 0.007557 | __author__ = 'fahadadeel'
import jpype
import os.path
from WorkingW | ithPresentation import PptToPptx
asposeapispath = os.path.join(os.path.abspath("../../../"), "lib")
print "You need to put your Aspose.Slides for Java APIs .jars in this folder:\n"+asposeapispath
jpy | pe.startJVM(jpype.getDefaultJVMPath(), "-Djava.ext.dirs=%s" % asposeapispath)
testObject = PptToPptx('data/')
testObject.main() |
CMPUT404Team/CMPUT404-project-socialdistribution | cmput404project/cmput404project/urls.py | Python | apache-2.0 | 1,075 | 0.00093 | """cmput404project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
... | views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: fro | m django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from rest_framework import routers
from service import views
urlpatterns = [
... |
selfbus/development-tools | test-case-generator/STG/Program.py | Python | gpl-3.0 | 8,523 | 0.035903 | # -*- coding: utf-8 -*-
# Copyright (C) 2015-2021 Martin Glueck All rights reserved
# Neugasse 2, A--2244 Spannberg, Austria. martin@mangari.org
# #*** <License> ************************************************************#
# This module is free software; you can redistribute it and/or modify
# it under the terms of th... | )
# end def Parameter_Ref
def Parameter (self, id) :
return self.get \
| (id, "Parameter", Parameter, static = self)
# end def Parameter_Ref
def Parameter_Type (self, id) :
return self.get \
(id, "ParameterType", Parameter_Type, static = self)
# end def Parameter_Type
def Memory (self, id) :
result = self.get \
(id, "Absolut... |
lekshmideepu/nest-simulator | testsuite/pytests/test_connect_helpers.py | Python | gpl-2.0 | 10,549 | 0 | # -*- coding: utf-8 -*-
#
# test_connect_helpers.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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 Li... | into larger bins.
Return values
-------------
2D array. The four columns contain degree,
expected number of observation, actual number observations, and
the number of bins combined.
'''
n = len_source_pop if fan == 'in' else len_target_pop
n_p = len_target_pop if fan ==... | data_front = []
cumexp = 0.0
bins_combined = 0
for degree in range(mid):
cumexp += scipy.stats.binom.pmf(degree, n, p) * n_p
bins_combined += 1
if cumexp < e_min:
if degree == mid - 1:
if len(data_front) == 0:
raise RuntimeWarning('N... |
hanshoi/kapsi-git-manager | tests/test_authentication.py | Python | mit | 761 | 0.005256 | import pytest
from flask_httpauth import HTTPBasicAuth
from kapsi_git_manager.kgm import app
from kapsi_git_manager import authentication as auth
password = "password"
username = "username"
def test_auth_simple():
""" this is the idiot test to check whether anything in you auth system works. """
assert is... | ) == F | alse
|
GoogleCloudPlatform/declarative-resource-client-library | python/services/sql/user.py | Python | apache-2.0 | 6,762 | 0.000592 | # Copyright 2020 Google 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 required by applicable law o... | .project = Primitive.from_proto(res_proto.project)
res.instance = Primitive.from_proto(res_proto.instance)
res.sqlserver_user_details = UserSqlserverUserDetails.from_proto(
res_proto.sqlserver_user_details
)
res.type = UserTypeEnum.from_proto(res_proto.type)
res.etag ... | class UserSqlserverUserDetails(object):
def __init__(self, disabled: bool = None, server_roles: list = None):
self.disabled = disabled
self.server_roles = server_roles
@classmethod
def to_proto(self, resource):
if not resource:
return None
res = user_pb2.SqlUser... |
USGSDenverPychron/pychron | pychron/options/group/base_group_options.py | Python | apache-2.0 | 1,645 | 0 | # ===============================================================================
# Copyright 2015 Jake Ross
#
# 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 for the specific language governing permissions and
# limitations under the License.
# ===============================================================================
# ============= enthought library imports =======================
from __future__ import absolute_import
from traits.api import HasTraits, Int, ... | BaseGroupOptions(HasTraits):
group_id = Int
color = Color
alpha = Range(0, 100, 70)
use_fill = Bool(True)
line_color = Color
line_width = Int(1)
bind_colors = Bool(True)
edit_button = Button
def _color_changed(self):
if self.bind_colors:
self.line_color = self.... |
jkonecki/autorest | AutoRest/Generators/Python/Python.Tests/AcceptanceTests/complex_tests.py | Python | mit | 14,727 | 0.004822 | # --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ""Software""),... | sult = client.basic_operations.get_not_provided()
self.assertIsNone(basic_result)
# GET basic/invalid
with self.assertRaises(DeserializationError):
client.basic_operations.get_invalid()
"""
COMPLEX TYPE WITH PRIMITIVE PROPERTIES
"""
# GET primitive/i... | ual(2, intResult.field2)
# PUT primitive/integer
intRequest = IntWrapper(field1=-1, field2=2)
client.primitive.put_int(intRequest)
# GET primitive/long
longResult = client.primitive.get_long();
self.assertEqual(1099511627775, longResult.field1)
self.assertEqual(... |
ebilionis/variational-reformulation-of-inverse-problems | vuq/_first_order_entropy_approximation.py | Python | gpl-2.0 | 1,888 | 0.002648 | """
A first order approximation to the entropy.
Author:
Ilias Bilionis
Date:
6/3/2014
"""
__all__ = ['FirstOrderEntropyApproximation']
import numpy as np
from . import MixtureOfMultivariateNormals
from . import EntropyApproximation
class FirstOrderEntropyApproximation(EntropyApproximation):
"""
... | __(name=name)
def eval(self, q):
"""
Evaluate only the entropy (no derivatives).
"""
assert isinstance(q, MixtureOfMultivariateNormals)
w = q.w
mu = q.mu
log_q = q(mu)
S0 = -np.sum(w * log_q) + 0.5 * q.num_dim
return S0
def __call__(self,... | and the derivatives.
"""
# Sanity check
assert isinstance(q, MixtureOfMultivariateNormals)
w = q.w
mu = q.mu
log_q, grad_x_log_q, grad_mu_log_q, grad_C_log_q = q.log_q_grad_x_mu_and_C(mu)
# The approximation (TODO: is it ok to add the last term?)
S0 = -np.... |
langcog/wordbank | instruments/schemas/German_WS.py | Python | gpl-2.0 | 77,978 | 0.007425 | from django.db import models
from instruments.base import BaseTable
class German_WS(BaseTable):
item_1_choices = [('produces', 'produces')]
item_1 = models.CharField(max_length=8, choices=item_1_choices, null=True)
item_2_choices = [('produces', 'produces')]
item_2 = models.CharField(max_length=8, cho... | es=item_58_choices, null=True)
item_59_choices = [('produces', 'produces')]
item_59 = models.CharField(max | _length=8, choices=item_59_choices, null=True)
item_60_choices = [('produces', 'produces')]
item_60 = models.CharField(max_length=8, choices=item_60_choices, null=True)
item_61_choices = [('produces', 'produces')]
item_61 = models.CharField(max_length=8, choices=item_61_choices, null=True)
item_62_c... |
sumonchai/ToughRADIUS | toughradius/manage/radiusd.py | Python | agpl-3.0 | 16,110 | 0.009381 | #!/usr/bin/env python
# coding=utf-8
import datetime
import os
import six
import msgpack
import toughradius
from txzmq import ZmqEndpoint, ZmqFactory, ZmqPushConnection, ZmqPullConnection
from twisted.internet import protocol
from twisted.internet import reactor
from twisted.internet.threads import deferToThread
from t... | cache_key("radius_user_trace"),fetch_result, expire=3600))
def user_exists(self,username):
def fetch_result():
table = models.TrAccount.__table__
with self.db_engine.begin() as conn:
val = conn.execute(table.select().where(
table.c.account_number=... | and Storage(val.items()) or None
return self.mcache.aget(account_cache_key(username),fetch_result, expire=3600) is not None
def log_trace(self,host,port,req,reply=None):
if not self.is_trace_on():
return
if not self.user_exists(req.get_user_name()):
return
t... |
wufangjie/leetcode | 621. Task Scheduler.py | Python | gpl-3.0 | 393 | 0 | from collections import | Counter
class Solution(object):
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
count = Counter(tasks)
theMax = max(count.values())
return max(len( | tasks), ((theMax - 1) * (n + 1)
+ sum(v == theMax for v in count.values())))
|
swoopla/compose | tests/unit/cli/command_test.py | Python | apache-2.0 | 3,080 | 0.000978 | # ~*~ encoding: utf-8 ~*~
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import pytest
import six
from compose.cli.command import get_config_path_from_options
from compose.config.environment import Environment
from compose.const import IS_WINDOWS_PLATFORM
from tests import m... | = [b'\xe5\xb0\xb1\xe5\x90\x83\xe9\xa5\xad/docker-compose.yml']
opts = {'--file': paths}
environment = Environment.from_env_file('.')
assert get_config_path_from_options(
'.', opts, environment
) == ['就吃 | 饭/docker-compose.yml']
@pytest.mark.skipif(six.PY3, reason='Env values in Python 3 are already Unicode')
def test_unicode_path_from_env(self):
with mock.patch.dict(os.environ):
os.environ['COMPOSE_FILE'] = b'\xe5\xb0\xb1\xe5\x90\x83\xe9\xa5\xad/docker-compose.yml'
environment = ... |
SatoshiNakamotoGeoscripting/SatoshiNakamotoGeoscripting | Final_assignment/main.py | Python | mit | 2,489 | 0.021695 | # -*- coding: utf-8 -*-
"""
Date: 2/2/2017
Team: Satoshi Nakamoto
@Authors: Alex Levering and Hector Muro
Non-standard dependencies:
* Twython
* NLTK
* Folium
* Geocoder
* psycopg2
TO DO BEFOREHAND:
The following steps are non-automatable and have to be performed manually.
* Have the NLTK vader lexicon locally (nltk... | created
tweet_table_name = "tweets", # Output table where the Tw | eets are stored
gather_data = True, # When True: Will gather data from the Twitter stream
search_terms = ["Trump"], # Twitter terms to search for
l... |
Elico-Corp/openerp-7.0 | procurement_supply_ext/__openerp__.py | Python | agpl-3.0 | 730 | 0.009602 | # -*- coding: utf-8 -*-
# © 2014 Elico Corp (https://www.elico-corp.com)
# Licence AGPL-3.0 or later(http://www.gnu.org/licenses/agpl.html)
{
'name' : 'Procurement Supply Ext',
'version' : '7.0.1.0.0',
'author': 'Elico Corp',
'website': 'www.elico-corp.com',
'category' : 'Generic Modules/Producti... | Default value is from product when confirm the sale order.
""",
'update_xml': | [
'procurement_supply_ext_views.xml',
],
'installable': True,
'active': False,
'certificate': False,
}
|
hatchetation/freeipa | tests/test_ipalib/__init__.py | Python | gpl-3.0 | 843 | 0 | # Authors:
# Jason Gerard DeRose <jderose@redhat.com>
#
# Copyright (C) 2008 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, ei... | at it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS F | OR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Sub-package containing unit tests for `ipalib` package.
"""
|
ashneo76/dynip | app.py | Python | mit | 3,009 | 0.002326 | #!/usr/bin/python
from flask import Flask, request
from flask_debugtoolbar import DebugToolbarExtension
from linode import api as l
from cloudflare import CloudFlare as CF
import os
import yaml
config = yaml.load(open('config.yml'))
app = Flask(__name__)
app.debug = config['DYN_DEBUG'] == '1'
if app.debug:
app.confi... | if d['DOMAIN'] == root:
domain_id = d['DOMAINID']
status = -1
if domain_id != -1:
# found a domain_id
res = linode.domain_resource_list(domainid=domain_id)
found = False
resource_id = -1
| for r in res:
if r['TYPE'] == rec_type and r['NAME'] == name:
found = True
resource_id = r['RESOURCEID']
break
if found and resource_id != -1:
linode.domain_resource_update(domainid=domain_id,
res... |
dkm/airspace-checker | airspace/parser.py | Python | gpl-3.0 | 1,404 | 0.000713 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# airspace checker
# Copyright (C) 2010 Marc Poulhiès
#
# 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 option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more... | e received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import antlr3
from OpenAirLexer import OpenAirLexer
from OpenAirParser import OpenAirParser
from OpenAirWalker import OpenAirWalker
def parse(filename):
finput = open(filename)
linput... |
dallascard/guac | core/word_vectors/make_char_vectors.py | Python | apache-2.0 | 1,322 | 0.000756 | from ..util import defines
from ..util import dirs
from ..util i | mport file_handling as fh
input_filename = dirs.get_processed_text_file()
data = fh.read_json(input_filename)
output_dir = fh.makedirs(defines.resources_clusters_dir, 'input')
output_filename = fh.m | ake_filename(output_dir, 'chars', 'txt')
char_lists = {}
for key, line in data.items():
#line = normalizer.fix_basic_punctuation(line)
chars = list(line)
char_lists[key] = chars
with open(output_filename, 'w') as output_file:
for key, chars in char_lists.items():
output_file.write(' '.join(cha... |
sameera2004/xray-vision | xray_vision/messenger/mpl/__init__.py | Python | bsd-3-clause | 5,498 | 0.000364 | # ######################################################################
# Copyright (c) 2014, Brookhaven Science Associates, Brookhaven #
# National Laboratory. All rights reserved. #
# #
# Redistribution and use in ... | = MPLDisplayWidget()
self._fig = self._display._fig
# set a default view
self._view = AbstractMPLDataView(fig=self._fig)
#@QtCore.Slot(colors.Normalize)
def sl_update_norm(self, new_norm):
"""
Updates the normalization function used for the color mapping
"""
... | ore.Slot(colors.Colormap)
def sl_update_cmap(self, cmap):
"""
Updates the color map. Currently takes a string, should probably be
redone to take a cmap object and push the look up function up a layer
so that we do not need the try..except block.
"""
try:
... |
darkfeline/animanager | animanager/__init__.py | Python | gpl-3.0 | 726 | 0 | # Copyright (C) 2015-2016 Allen Li
#
# This file is part of Anima | nager.
#
# Animanager 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.
#
# Animanager is distributed in the hope that it will be useful,... | R PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Animanager. If not, see <http://www.gnu.org/licenses/>.
__version__ = '0.12.0'
|
borisoop/AtEar | module/NetBIOS.py | Python | apache-2.0 | 3,922 | 0.005864 | __author__ = 'root'
import random, socket, time, select
import struct, string, re
import types, errno
class NetBIOS():
def __init__(self, broadcast=True, listen_port=0):
self.broadcast = broadcast
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.HEADER_STRUCT_FORMAT = '>HH... | def _pollForQueryPacket(self, wait_trn_id, timeout):
end_time = time.time() + timeout
while True:
try:
_timeout = end_time - time.time()
if _timeout <= 0:
return None
ready, _, _ = select.select([ self.sock.fileno() ], [ ... | om(0xFFFF)
if len(data) == 0:
return None
trn_id, ret = self.decodeIPQueryPacket(data)
if trn_id == wait_trn_id:
return ret
except select.error, ex:
if type(ex) is types.TupleType:
i... |
mzdaniel/oh-mainline | vendor/packages/Django/tests/regressiontests/middleware_exceptions/urls.py | Python | agpl-3.0 | 437 | 0.002288 | # coding: utf-8
from django.conf.urls.defaul | ts import *
import views
urlpatterns = patterns('',
(r'^view/$', views.normal_view),
(r'^not_found/$', views.not_found),
(r'^error/$', views.server_error),
(r'^null_view/$', views.null_view),
(r'^permission_denied/$', views.permiss | ion_denied),
(r'^template_response/$', views.template_response),
(r'^template_response_error/$', views.template_response_error),
)
|
kellpossible/VoxelEditor | PythonScript/addon-voxel-painter.py | Python | mit | 29,381 | 0.005037 | """
addon-voxel-painter.py
Copyright (c) 2013 Luke Frisken
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge,... | only)"""
#for obj in context.visible_objects:
#if obj.type == 'MESH':
#yield (obj, obj.matrix_world.copy())
#if obj.dupli_type != 'NONE':
#obj.dupli_list_create(scene)
#for dob in obj.dupli_list:
... | def intersect_mesh(self, obj):
"""run a boolean intersect operation between a mesh object and the voxel
and the resultant mesh is parented to the voxel"""
select_none(bpy.context)
self.select()
print("Active:", bpy.context.active_object)
print("Object:", bpy.context.obj |
tcmitchell/geni-tools | src/gcf/geni/am/am2.py | Python | mit | 40,593 | 0.002217 | #----------------------------------------------------------------------
# Copyright (c) 2011-2016 Raytheon BBN Technologies
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including ... | uthorizer import *
from .am_method_context import AMMethodContext
from ...gcf_version import GCF_VERSION
# See sfa/trust/rights.py
# These are names of operations
# from the rights.py privilege_table
# Credentials may list privileges that
# map to these operations, giving the caller permission
# to perform the functio... | enewsliver'
CREATESLIVERPRIV = 'createsliver'
DELETESLIVERPRIV = 'deleteslice'
SLIVERSTATUSPRIV = 'getsliceresources'
SHUTDOWNSLIVERPRIV = 'shutdown'
# Publicid format resource namespace. EG Resource URNs
# will be <namespace>:resource:<resourcetype>_<resourceid>
# This is something like the name of your AM
# See gen-... |
jakirkham/volumina | volumina/volumeEditor.py | Python | lgpl-3.0 | 10,423 | 0.012376 | ###############################################################################
# volumina: volume slicing and editing library
#
# Copyright (C) 2011-2014, the ilastik developers
# <team@ilastik.org>
#
# This program is free software; you can redistribute it and/or
# modify it und... | useVTK = False
#*******************************************************************************
# V o l u m e E d i t o r *
#*******************************************************************************
class VolumeEditor( QObject ):
newImage | View2DFocus = pyqtSignal()
shapeChanged = pyqtSignal()
@property
def showDebugPatches(self):
return self._showDebugPatches
@showDebugPatches.setter
def showDebugPatches(self, show):
for s in self.imageScenes:
s.showTileOutlines = show
self._showDebugPatches = sho... |
fsquillace/pycious | pycious/lib/web.py | Python | gpl-2.0 | 3,481 | 0.014938 | #!/usr/bin/python3
import subprocess
from xml.dom import minidom
import imaplib
from pycious.lib.common import singleton
class Mail:
def __init__(self, username, password,\
server='imap.gmail.com', port=993):
"""
It returns -1 if there is no connection otherwise it returns
... | e, self.password = username, password
self.server, self.port = server, port
# Define the connection object | to None
self.M = None
def __connect(self):
self.M=imaplib.IMAP4_SSL(self.server , self.port)
#First field is imap login (gmail uses login with
#domain and '@' character), second - password
self.M.login(self.username, self.password)
def __call__(self):
... |
ev3dev/u-boot | tools/dtoc/dtb_platdata.py | Python | gpl-2.0 | 20,178 | 0.000595 | #!/usr/bin/python
# SPDX-License-Identifier: GPL-2.0+
#
# Copyright (C) 2017 Google, Inc
# Written by Simon Glass <sjg@chromium.org>
#
"""Device tree to platform data class
This supports converting device tree data to C structures definitions and
static data.
"""
import collections
import copy
import sys
import fdt... | is a list of integers.
PhandleInfo = collections.namedtuple('PhandleInfo', ['max_args', 'args'])
|
def conv_name_to_c(name):
"""Convert a device-tree name to a C identifier
This uses multiple replace() calls instead of re.sub() since it is faster
(400ms for 1m calls versus 1000ms for the 're' version).
Args:
name: Name to convert
Return:
String containing the C version of thi... |
Debian/openjfx | modules/web/src/main/native/Tools/Scripts/webkitpy/tool/steps/commit_unittest.py | Python | gpl-2.0 | 3,257 | 0.002456 | # Copyright (C) 2012 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | exception.
step = Commit(tool, options)
state = {
"changed_files": [filename + "XXX"],
}
tool.executive = MockExecutive(should_log=True, should_throw_when_run=False)
expected_logs = "Committed r49824: <http://trac.webkit.org/changeset/49824>\n"
capture.assert... | les": ["platform/chromium/" + filename],
}
expected_logs = """MOCK run_and_throw_if_fail: ['mock-check-webkit-style', '--diff-files', 'platform/chromium/%s'], cwd=/mock-checkout
Committed r49824: <http://trac.webkit.org/changeset/49824>
""" % filename
capture.assert_outputs(self, step.run, [stat... |
mxOBS/deb-pkg_trusty_chromium-browser | tools/telemetry/telemetry/core/backends/chrome/cros_unittest.py | Python | bsd-3-clause | 4,953 | 0.009489 | # 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.
import logging
from telemetry import decorators
from telemetry.core import exceptions
from telemetry.core import util
from telemetry.core.backends.chrome im... | and when
logged out"""
with self._CreateBrowser() as b:
self.assertEquals(1, len(b.tabs))
self.assertTrue(b.tabs[0].url)
self.assertTrue(self._IsCryptohomeMounted())
# TODO(achuith): Remove dependency on /home/chronos/user.
chronos_fs = self._ | cri.FilesystemMountedAt('/home/chronos/user')
self.assertTrue(chronos_fs)
if self._is_guest:
self.assertEquals(chronos_fs, 'guestfs')
else:
crypto_fs = self._cri.FilesystemMountedAt(
self._cri.CryptohomePath(self._username))
self.assertEquals(crypto_fs, chronos_fs)
... |
johnnyliu27/openmc | openmc/data/data.py | Python | mit | 15,739 | 0.000127 | import itertools
from math import sqrt
import os
import re
from warnings import warn
# Isotopic abundances from Meija J, Coplen T B, et al, "Isotopic compositions
# of the elements 2013 (IUPAC Technical Report)", Pure. Appl. Chem. 88 (3),
# pp. 293-306 (2013). The "representative isotopic abundance" values from
# col... | .01601, 'Er166': 0.33503,
'Er167': 0.22869, 'Er168': 0.26978, 'Er170': 0.1491,
'Tm169': 1.0, 'Yb168': 0.001 | 23, 'Yb170': 0.02982,
'Yb171': 0.14086, 'Yb172': 0.21686, 'Yb173': 0.16103,
'Yb174': 0.32025, 'Yb176': 0.12995, 'Lu175': 0.97401,
'Lu176': 0.02599, 'Hf174': 0.0016, 'Hf176': 0.0526,
'Hf177': 0.186, 'Hf178': 0.2728, 'Hf179': 0.1362,
'Hf180': 0.3508, 'Ta180': 0.0001201, 'Ta181': 0.9998799,
'W180':... |
repotvsupertuga/tvsupertuga.repository | script.module.openscrapers/lib/openscrapers/sources_openscrapers/en/to_be_fixed/no_sources/downflix.py | Python | gpl-2.0 | 3,106 | 0.00161 | # -*- coding: utf-8 -*-
# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######.
# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....##
# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.... | ....##...##........##
# .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....##
# ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######.
"""
OpenScrapers Project
This p | rogram is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
b... |
miceno/django-categories | categories/migrations/0001_initial.py | Python | apache-2.0 | 3,406 | 0.005872 | # -*- coding: utf-8 -*-
from django.db import models, migrations
import django.core.files.storage
import mptt.fields
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Category',
... | =[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('object_id', models.PositiveIntegerField(verbose_name='object id')),
(' | relation_type', models.CharField(help_text="A generic text field to tag a relation, like 'leadphoto'.", max_length='200', null=True, verbose_name='relation type', blank=True)),
('category', models.ForeignKey(verbose_name='category', to='categories.Category')),
('content_type', models.For... |
gentoo/identity.gentoo.org | okupy/accounts/views.py | Python | agpl-3.0 | 36,590 | 0.000355 | # vim:fileencoding=utf8:et:ts=4:sts=4:sw=4:ft=python
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import (login as _login, logout as _logout,
authenticate)
from django.core.mail import send_mail
from django.core.urlresolvers import rever... | password'
+ ' again to perform this action')
else:
if request.user.is_verified():
return redirect(next)
login_form = OTPForm()
is_otp = True
if login_form is None:
login_form = login_ | form_class()
if is_otp or strong_auth_req:
ssl_auth_form = None
ssl_auth_uri = None
ssh_auth_command = None
else:
encrypted_id = sessionrefcipher.encrypt(request.session)
# TODO: it fails when:
# 1. site is accessed via IP (auth.127.0.0.1),
# 2. HTTP use... |
jkonecki/autorest | AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flattened_product.py | Python | mit | 2,348 | 0.002129 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | ning_state_values': {'key': 'properties.provisioningStateValues', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(self, id=None, type=None, tags=None, location=None, name=None, pname=None, flattened_product_type=None, provisioning_s | tate_values=None, provisioning_state=None, **kwargs):
super(FlattenedProduct, self).__init__(id=id, type=type, tags=tags, location=location, name=name, **kwargs)
self.pname = pname
self.flattened_product_type = flattened_product_type
self.provisioning_state_values = provisioning_state_va... |
bank-netforce/netforce | netforce_account/netforce_account/models/account_credit_alloc.py | Python | mit | 9,494 | 0.003476 | # Copyright (c) 2012-2015 Netforce Co. Ltd.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... | journal_id = settings.purchase_journal_id.id
if not journal_id:
raise Exce | ption("Purchases journal not found")
move_vals = {
"journal_id": journal_id,
"date": inv.date,
"narration": desc,
}
lines = []
use_ratio = obj.amount / cred.amount_total
cur_total = get_model("currency").convert(... |
kontron/python-hpi | examples/resources.py | Python | lgpl-2.1 | 3,793 | 0.002109 | # Copyright (c) 2014 Kontron Europe GmbH
#
# This library is free softw | are; you can redistribute it and/or
# modify it under the terms | of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or ... |
tailhook/tilenol | tilenol/layout/examples.py | Python | mit | 657 | 0.001522 | from .tile import Split, Stack, TileStack
class Tile(Split):
class left(Stack):
weight = 3
priority = 0
limit = 1
class right(TileStack):
pas | s
class Max(Split):
class main(Stack):
tile = False
class InstantMsg(Split):
class left(TileStack): # or maybe not tiled ?
weight = 3
class roster(Stack):
limit = 1
priority = 0 # probably roster created first
class Gimp(Split):
class toolbox(Stack):
li... | 0
class dock(Stack):
limit = 1
size = 324
|
pombredanne/parakeet | benchmarks/2d_convolution.py | Python | bsd-3-clause | 773 | 0.019405 | import parakeet
import numpy as np
from timer import compare_perf
def clamp(i, offset, maxval):
j = max(0, i + offset)
return min(j, maxval)
def reflect(pos, offset, bound):
idx = pos+offset
return m | in(2*(bound-1)-idx,max(idx,-idx))
def conv(x, weights, mode=clamp):
sx = x.shape
sw = weights.shape
result = np.zeros_like(x)
for i in xrange(sx[0]):
for j in xrange(sx[1]):
for ii in xrange(sw[0]):
for jj in xrange(sw[1]):
idx = mode(i,ii-sw[0]... | (300,300)
x = np.random.randn(*xsize)
wsize = (5,5)
w = np.random.randn(*wsize)
compare_perf(conv, [x,w])
|
malaterre/ITK | Wrapping/Generators/Python/Tests/lazy.py | Python | apache-2.0 | 1,068 | 0.002809 | #==========================================================================
#
# Copyright NumFOCUS
#
# 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... |
import itk
# Test PEP 366 compliance of LazyITKModule
assert(itk.__package__ == 'itk')
from itk import ITKCommon
assert(ITKCommon.__package__ == 'itk')
# Test pickling used bash Dask
try:
import cloudpickle
itkpickled = cloudpickle.dumps(itk)
| cloudpickle.loads(itkpickled)
except ImportError:
pass
|
jochenklar/reader2 | feeds/management/commands/fetch.py | Python | apache-2.0 | 1,002 | 0.000998 | import datetime
import sys
from django.utils.timezone import utc, now
from django.core.management.base import BaseCommand
from feeds.models import Feed, Meta
from feeds.exceptions import FeedException
class Command(BaseCommand):
help = 'Fetches the items from all stored feeds.'
def handle(self, *args, **opt... | - datetime.timedelta(days=60))).exclude(pk__in=list(keep)).delete()
# if everything went well set the updated field
meta = Meta.load()
meta.updat | ed = datetime.datetime.utcnow().replace(tzinfo=utc)
meta.save()
|
kartoza/geonode | geonode/notifications_helper.py | Python | gpl-3.0 | 3,847 | 0 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2017 OSGeo
#
# 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 ... | y if notifications are not installed.
"""
if has_notifications:
# queue for further processing if required
if settings.PINAX_NOTI | FICATIONS_QUEUE_ALL:
return queue_notification(*args, **kwargs)
try:
return notifications.models.send(*args, **kwargs)
except Exception:
logging.exception("Could not send notifications.")
return False
def queue_notification(*args, **kwargs):
if has_n... |
chirpradio/chirpradio-volunteers | chirp/volunteers/_ui_test_/meetings.py | Python | mit | 1,128 | 0.006206 |
"""This is a stub view that can be used to
develop or test the M | eeting Tracker JavaScript
functionality without hitting the actual database.
"""
from django.template import Context, loader
from django.http import HttpResp | onse
from chirp.utils import as_json
def meetings_dev(request):
t = loader.get_template('meetings.html')
c = Context({
'extra_js_scripts': [
'/local_site_media/js/chirp/meetings_stub_urls.js'
],
'title':'Meeting Attendance Tracker'
})
return HttpResponse(t.render(c))... |
DaisukeMiyamoto/visualize_silkmothbrain | draw_mothbrain.py | Python | mit | 7,186 | 0.005706 | import vtk
import math
def get_screenshot(renWin, filename):
renWin.Render()
w2if = vtk.vtkWindowToImageFilter()
w2if.SetInput(renWin)
w2if.Update()
writer = vtk.vtkPNGWriter()
writer.SetFileName(filename)
writer.SetInput(w2if.GetOutput())
writer.Write()
renWin.Render()
##########... | tk.vtkSmoothPolyDataFilter())
objs_smoother[-1].SetInputConnection(objs[-1].GetOutputPort())
objs_smoother[-1].SetNumberOfIterations(50)
transforms_filter.append(vtk.vtkTransformPolyDataFilter())
transforms_filter[-1].SetTransform(transform)
transforms_filter[-1].SetInputConnection(objs_smoother[-1... | -1].Update()
objs_mapper.append(vtk.vtkPolyDataMapper())
objs_mapper[-1].SetInputConnection(transforms_filter[-1].GetOutputPort())
objs_mapper[-1].SetLookupTable(lut)
objs_actor.append(vtk.vtkActor())
objs_actor[-1].SetMapper(objs_mapper[-1])
rgb = [0.8, 0.8, 0.8]
#lut.GetColor((i / float(l... |
mishravikas/geonode-permissions | setup.py | Python | gpl-3.0 | 5,146 | 0.004858 | #########################################################################
#
# 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 version 3 of the License, or
#... | pecific installation
# locations. See here for an explanation:
# http://groups.google.com/group/comp.lang.python/browse_thread/thread/35ec7b2fed36eaec/2105ee4d9e8042cb
for scheme in INSTALL_SCHEMES.values():
scheme['data'] = scheme['purelib']
# Compile the list of packages available, because distutils doesn't have... | [], []
root_dir = os.path.dirname(__file__)
if root_dir != '':
os.chdir(root_dir)
geonode_dir = 'geonode'
for dirpath, dirnames, filenames in os.walk(geonode_dir):
# Ignore dirnames that start with '.'
for i, dirname in enumerate(dirnames):
if dirname.startswith('.'): del dirnames[i]
if '__init... |
ericdill/bluesky | bluesky/tests/test_suspenders.py | Python | bsd-3-clause | 7,631 | 0.000131 | import pytest
from functools import partial
from bluesky.preprocessors import suspend_wrapper
from bluesky.suspenders import (SuspendBoolHigh,
SuspendBoolLow,
SuspendFloor,
SuspendCeil,
Suspen... | e
from .utils import _fabricate_asycio_event
@pytest.mark.parametrize(
'klass,sc_args,start_val,fail_val,resume_val,wait_time',
[(SuspendBoolHigh, (), 0, 1, 0, .2),
(SuspendBoolLow, (), 1, 0, 1, .2),
(SuspendFloor, (.5,), 1, 0, 1, .2),
(SuspendCeil, (.5,), 0, 1, 0, .2),
(SuspendWhenOutside... | , .2),
((SuspendInBand, True), (.5, 1.5), 1, 0, 1, .2), # renamed to WhenOutsideBand
((SuspendOutBand, True), (.5, 1.5), 0, 1, 0, .2)]) # deprecated
def test_suspender(klass, sc_args, start_val, fail_val,
resume_val, wait_time, RE, hw):
sig = hw.bool_sig
try:
klass, deprec... |
iyounus/incubator-systemml | src/main/python/systemml/converters.py | Python | apache-2.0 | 11,072 | 0.006503 | #-------------------------------------------------------------
#
# 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... | d.DataFrame(X)
pd2 = pd.DataFrame(y, columns=['label'])
pdf = pd.concat([pd1, pd2], axis=1)
inputColumns = ['C' + str(i) for i in pd1.columns]
outputColumns = inputColumns + ['label']
else:
pdf = pd.DataFrame(X)
inputColumns = ['C' + str(i) for i in pdf.columns | ]
outputColumns = inputColumns
assembler = VectorAssembler(inputCols=inputColumns, outputCol='features')
out = assembler.transform(sparkSession.createDataFrame(pdf, outputColumns))
if y is not None:
return out.select('features', 'label')
else:
return out.select('features')
def _... |
geier/icalendar | src/icalendar/tests/test_encoding.py | Python | bsd-2-clause | 3,224 | 0 | # -*- coding: utf-8 -*-
from icalendar.tests import unittest
import datetime
import icalendar
import os
import pytz
class TestEncoding(unittest.TestCase):
def test_create_from_ical(self):
directory = os.path.dirname(__file__)
with open(os.path.join(directory, 'encoding.ics'), 'rb') as fp:
... | , 0, 0))
)
event.add(
'dtend',
pytz.utc.localize(datetime.datetime(2010, 10, 10, 12, 0, 0))
)
event.add(
'created',
pytz.utc.localize(datetime.datetime(2010, 10, 10, 0, 0, 0))
)
event.add('uid', u'123456')
event.add(... | Ü äöü €')
event.add(
'description',
u'icalendar should be able to de/serialize non-ascii.'
)
event.add('location', u'Tribstrül')
cal.add_component(event)
ical_lines = cal.to_ical().splitlines()
cmp = b'PRODID:-//Pl\xc3\xb6n\xc3\xab.org//NONSGML pl... |
nrz/ylikuutio | external/bullet3/examples/pybullet/gym/pybullet_envs/deep_mimic/learning/ppo_agent.py | Python | agpl-3.0 | 15,769 | 0.006278 | import numpy as np
import copy as copy
try:
import tensorflow.compat.v1 as tf
except Exception:
import tensorflow as tf
from pybullet_envs.deep_mimic.learning.pg_agent import PGAgent
from pybullet_envs.deep_mimic.learning.solvers.mpi_solver import MPISolver
import pybullet_envs.deep_mimic.learning.tf_util as TFUti... | ):
actor_weight_decay = 0 if (
self.ACTOR_WEIGHT_DECAY_KEY not in json_data) else json_data[self.ACTOR_WEIGHT_DECAY_KEY]
critic_weight_decay = 0 if (
self.CRITIC_WEIGHT_DECAY_KEY not in json_data) else json_data[self.CRITIC_WEIGHT_DECAY_KEY]
norm_val_diff = self.val_norm.normalize_tf(self.t... | f.val_norm.normalize_tf(
self.critic_tf)
self.critic_loss_tf = 0.5 * tf.reduce_mean(tf.square(norm_val_diff))
if (critic_weight_decay != 0):
self.critic_loss_tf += critic_weight_decay * self._weight_decay_loss('main/critic')
norm_tar_a_tf = self.a_norm.normalize_tf(self.a_tf)
self._norm_... |
pierce403/EmpirePanel | lib/common/listeners.py | Python | bsd-3-clause | 26,210 | 0.006944 | """
Listener handling functionality for Empire.
Handles listener startup from the database, listener
shutdowns, and maintains the current listener
configuration.
"""
import http
import helpers
from pydispatch import dispatcher
import hashlib
import sqlite3
class Listeners:
def __init__(self, MainMenu, args=... | '] = parts[0]
else:
self.options['Port']['Value'] = "80"
|
return True
elif option == "CertPath":
self.options[option]['Value'] = value
host = self.options["Host"]['Value']
# if we're setting a SSL cert path, but the host is specific at http
if host.startswith("http:"):
self.options["Host"]['... |
glomex/gcdt | gcdt/kumo_start_stop.py | Python | mit | 17,372 | 0.001669 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from .gcdt_logging import getLogger
from .utils import all_pages
from .kumo_core import stack_exists
log = getLogger(__name__)
def _stop_ec2_instances(awsclient, ec2_instances, wait=True):
"""Helper to stop ec2 instances.
By def... | get_service_cluster_desired_count(
template, parameters, service['LogicalResourceId'])
log.debug('cluster: %s' % cluster)
response = client_ecs.update_service(
cluster=cluster,
service=service['PhysicalResourceId'],
desiredCount=0
| )
def _start_ecs_services(awsclient, services, template, parameters, wait=True):
"""Helper to set desiredCount of ECS services back to its template value
Docs here: http://docs.aws.amazon.com/cli/latest/reference/ecs/update-service.html
:param awsclient:
:param services:
:param template: the clo... |
shamanu4/netmiko | netmiko/cisco/cisco_xr_ssh.py | Python | mit | 5,165 | 0.003291 | from __future__ import print_function
from __future__ import unicode_literals
import re
from netmiko.cisco_base_connection import CiscoSSHConnection
class CiscoXrSSH(CiscoSSHConnection):
def session_preparation(self):
"""Prepare the session after the connection has been established."""
self.set... | d" in output:
| output += self.send_command_timing('no\n', strip_prompt=False, strip_command=False)
if self.check_config_mode():
raise ValueError("Failed to exit configuration mode")
return output
@staticmethod
def normalize_linefeeds(a_string):
"""Convert '\r\n','\r\r\n', ... |
schleichdi2/OPENNFR-6.0-CORE | bitbake/lib/toaster/toastergui/tablefilter.py | Python | gpl-2.0 | 9,426 | 0.001804 | #
# ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
# BitBake Toaster Implementation
#
# Copyright (C) 2015 Intel Corporation
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# pub... | mediately, resetting criteria
# on the QuerysetFilter
try:
date_from_str, date_to_str = params.split(',')
except ValueError:
self.criteria = None
return
# one of the values required for the filter is missing, so set
# it to the one which was s... | self.field,
date_from_str,
date_to_str
)
def to_jso |
google/eclipse2017 | common/image_sorter.py | Python | apache-2.0 | 702 | 0 | #
# Copyright 2017 Google 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... | d 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.
de | f pick_image(complete_images):
complete_images.sort(key=lambda x: x["image_datetime"])
return complete_images[-1]
|
mdwhatcott/OsAdapters | osadapt/command.py | Python | mit | 2,015 | 0.005955 | import os
import sys
import string
import contextlib
from subprocess import Popen, PIPE
check_output = None
def replace_check_output(command_args, **kwargs):
kwargs['stdout'] = PIPE
return Popen(' '.join(command_args), **kwargs).stdout.read()
try:
from subprocess import check_output
except ImportError:
... | tion):
initial = os.getcwd()
try:
os.chdir(location)
yield
finally:
os.chdir(init | ial)
|
lnielsen/invenio | invenio/legacy/weblinkback/webinterface.py | Python | gpl-2.0 | 12,093 | 0.006367 | # -*- coding: utf-8 -*-
## Comments and reviews for records.
## This file is part of Invenio.
## Copyright (C) 2011 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of th... | CFG_SITE_LANG, \
CFG_SITE_RECORD, \
CFG_WEBLINKBACK_TRACKBACK_ENABLED
from invenio.legacy.search_engine import guess_primary_collection_of_a_record, \
c | reate_navtrail_links, \
get_colID
from invenio.legacy.webpage import pageheaderonly, pagefooteronly
from invenio.legacy.websearch.adminlib import get_detailed_page_tabs
from invenio.modules.access.engine import acc_authorize_action
import invenio.legacy.template
webstyle_templates = in... |
thaim/ansible | lib/ansible/modules/network/fortios/fortios_system_custom_language.py | Python | mit | 9,447 | 0.001376 | #!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# 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 Lic... | - present
- absent
system_custom_language:
description:
- Configure custom languages.
default: null
type: dict
suboptions:
comments:
description:
- Comment.
type: str
filename:
... | required: true
type: str
'''
EXAMPLES = '''
- hosts: localhost
vars:
host: "192.168.122.40"
username: "admin"
password: ""
vdom: "root"
ssl_verify: "False"
tasks:
- name: Configure custom languages.
fortios_system_custom_language:
host: "{{ host }}"
username: ... |
JBonsink/GSOC-2013 | tools/ns-allinone-3.14.1/ns-3.14.1/src/visualizer/visualizer/__init__.py | Python | gpl-3.0 | 79 | 0.012658 |
from core import start, regis | ter_plugin, | set_bounds, add_initialization_hook
|
peterbe/moztrap | moztrap/model/library/migrations/0008_auto__add_field_case_priority.py | Python | bsd-2-clause | 25,572 | 0.007156 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Case.priority'
db.add_column('library_case', 'priority',
self.gf('djan... | rue', 'on_delete': 'models.SET_NULL', 'to': "orm['auth.User']"}),
'created_on': ('djang | o.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 6, 24, 0, 0)'}),
'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'+ |
Baloc/TouSIX-Manager | tousix_manager/Administration/adminsite.py | Python | gpl-3.0 | 1,145 | 0 | # Copyright 2015 Rémy Lapeyrade <remy at lapeyrade dot net>
# Copyright 2015 LAAS-CNRS
#
#
# This file is part of TouSIX-Manager.
#
# TouSIX-Manager 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 Founda... | n 3 of the License, or
# (at your option) any later version.
#
# TouSIX-Manager 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 PARTIC | ULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with TouSIX-Manager. If not, see <http://www.gnu.org/licenses/>.
from django.contrib.admin import AdminSite
class TouSIXAdmin(AdminSite):
"""
Special ad... |
italopaiva/your.car | yourcar/car/migrations/0001_initial.py | Python | bsd-2-clause | 2,468 | 0.004862 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-06 02:47
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operation... | created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateTimeField(verbose_name='date changed')),
('mileage', models.IntegerField(default=0, val | idators=[django.core.validators.MinValueValidator(0)])),
('car', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='car.Car')),
],
),
migrations.CreateModel(
name='Refuel',
fields=[
('id', models.AutoField(auto_created=T... |
hamuchiwa/AutoRCCar | computer/model_training.py | Python | bsd-2-clause | 709 | 0 | __author__ = 'zhengwang'
from model import load_data, NeuralNetwork
input_size = 120 * 320
data_path = "training_data/*.npz"
X_train, X_valid, y_train, y | _valid = load_data(input_size, data_path)
# train a neural network
layer_sizes = [input_size, 32, 4]
nn = NeuralNetwork()
nn.create(layer_sizes)
nn.train(X_train, y_train)
# evaluate on train data
train_accuracy = nn.evaluate(X_train, y_train)
print("Train accuracy: ", "{0:.2f}%".format(train_accuracy * 100))
# eval... | ation data
validation_accuracy = nn.evaluate(X_valid, y_valid)
print("Validation accuracy: ", "{0:.2f}%".format(validation_accuracy * 100))
# save model
model_path = "saved_model/nn_model.xml"
nn.save_model(model_path)
|
xiaoxq/apollo | modules/tools/open_space_visualization/open_space_roi_visualizer.py | Python | apache-2.0 | 3,303 | 0.000606 | #!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo 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... | _roi_boundary_x, unrotated_roi_boundary_y, roi_boundary_x, roi_boundary_y,
parking_spot_x, parking_spot_y, end_pose,
xy_boundary, origin_pose):
print("open_space_roi fail")
result_unrotated_roi_boundary_x = []
result_unrotated_roi_boundary_y = []
result_ro... | ary = []
result_origin_pose = []
print("vertices of obstacles")
for i in range(0, 10):
result_unrotated_roi_boundary_x.append(float(unrotated_roi_boundary_x[i]))
result_unrotated_roi_boundary_y.append(float(unrotated_roi_boundary_y[i]))
result_roi_boundary_x.append(float(roi_boundary_x[i]))
result_roi_... |
nbari/my-sandbox | python/exercices/phonelist/phonelist.py | Python | bsd-3-clause | 1,342 | 0.000745 | """
run using python phonelist.py
input your data when done type Ctrl-D, Ctrl-C or blank line
"""
import signal
import sys
def check_consistent(phone_list):
print phone_list
if phone_list:
phone_list.sort(key=len)
prefix = None
for phone in phone_list:
prefix = phon | e_list.pop(0)
if [p for p in phone_list if p.startswith(prefix)]:
return False
return True
def get_input():
t = 0
c = 0
pl | = []
while True:
line = sys.stdin.readline().strip()
if line == 'exit' or not line:
break
if line.isdigit():
if int(line) < 40:
if pl and not c:
"""
process previous lists
"""
... |
paxos-bankchain/subconscious | tests/base.py | Python | mit | 634 | 0 | import aioredis
import asyncio
from unittest import TestCase
class BaseTestCase(TestCase):
def setUp(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(None)
db_co = aioredis.create_redis(
address=('localhos | t', 6379),
db=13,
loop=self.loop,
encoding='utf-8',
)
self.db = self.loop.run_until_complete(db_co)
def tearDown(self):
async def delete_all():
async for k in self.db.iscan(match='*Test*', count=100):
await self.db.delete(k)
... | l_complete(delete_all())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.