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 |
|---|---|---|---|---|---|---|---|---|
kate-harrison/west | west/data_management.py | Python | gpl-2.0 | 23,067 | 0.00065 | from abc import ABCMeta, abstractmethod, abstractproperty
from ruleset import Ruleset
from device import Device
from propagation_model import PropagationModel
from region import Region
from boundary import Boundary
from data_map import DataMap2D, DataMap3D, DataMap2DWithFixedBoundingBox
from population import Populatio... | f not _is_class( | e_type):
raise TypeError("Expected type must be a class (got '%s' "
"instead)." % str(expected_types))
if _is_class(obj):
cls = obj
else:
cls = obj.__class__
is_wrong_type = True
for e_type in expected_types:
... |
richardliaw/ray | rllib/tests/test_local.py | Python | apache-2.0 | 696 | 0 | import unittest
import ray
from ray.rllib | .agents.pg import PGTrainer, DEFAULT_CONFIG
from ray.rllib.utils.test_utils import framework_iterator
class LocalModeTest(unittest.TestCase):
def setUp(self) -> None:
ray.init(local_mode=True)
def tearDown(s | elf) -> None:
ray.shutdown()
def test_local(self):
cf = DEFAULT_CONFIG.copy()
cf["model"]["fcnet_hiddens"] = [10]
cf["num_workers"] = 2
for _ in framework_iterator(cf):
agent = PGTrainer(cf, "CartPole-v0")
print(agent.train())
agent.stop(... |
axxiao/toby | ax/wrapper/sqlalchemy.py | Python | mit | 1,716 | 0.004662 | """
The wrapper for Postgres through SQLAchemy
__author__ = "Alex Xiao <http://www.alexxiao.me/>"
__date__ = "2018-11-03"
__version__ = "0.1"
Version:
0.1 (03/11/2018 AX) : init
"""
from urllib.parse import quote_plus
from sqlalchemy import create_engine, text
import pandas
from ax.log import ge... | db='toby', encoding='utf8'):
self._uri = '{}://{}:{}@{}:{}/{}'
if not self._connection or self._connection.closed:
self._connection = create_engine(self._uri.format(db_type, quote_plus(user), quote_plus(password), host,
port, db),... | self._connection.closed:
self._connection = create_engine(self._uri, client_encoding=self._encoding).connect()
def query(self, sql, **options):
return pandas.read_sql(text(sql), self._connection, **options)
def execute(self, sql):
self.logger.info('Executing:' + sql)
... |
1ookup/RATDecoders | BlueBanana.py | Python | gpl-2.0 | 3,304 | 0.030266 | #!/usr/bin/env python
'''
BlueBanana Rat Config Decoder
'''
__description__ = 'BlueBanana Rat Config Extractor'
__author__ = 'Kevin Breen http://techanarchy.net http://malwareconfig.com'
__version__ = '0.1'
__date__ = '2014/04/10'
#Standard Imports Go Here
import os
import sys
import string
from zipfile import ZipFi... | nfig figure out where to dump it out.
if config == None:
print "[+] Config not found"
sys.exit()
#if you gave me two args im going to assume the 2nd arg is where you want to save the file
if len(args) == 2:
print "[+] Writing Config to file {0}".format(args[1])
with open(args[1], 'a') as outFile:
for key,... | Value: {1}\n".format(key,clean_value))
# if no seconds arg then assume you want it printing to screen
else:
print "[+] Printing Config to screen"
for key, value in sorted(config.iteritems()):
clean_value = filter(lambda x: x in string.printable, value)
print " [-] Key: {0}\t Value: {1}".format(key,clean_v... |
marook/minecraft-world-io | src/test/marook_test/minecraft_test/tag_test/test_entities.py | Python | gpl-3.0 | 1,426 | 0.002805 | #!/usr/bin/env python
#
# Copyright 2011 Markus Pielmeier
#
# This file is part of minecraft-world-io.
#
# minecraft-world-io 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... | tities import SkeletonParser
from marook.minecraft.tag.entities import SheepParser
class SkeletonParserTest(unittest.TestCase):
def testParseSkeleton(self):
with open(os.path.join('etc', 'dumps', 'skeleton.dump'), 'r') as f:
p = SkeletonParser()
s = p.readEntity(f)
... | st.TestCase):
def testParseSheep(self):
with open(os.path.join('etc', 'dumps', 'sheep.dump'), 'r') as f:
p = SheepParser()
s = p.readEntity(f)
# TODO check sheep attributes
|
rokuz/omim | tools/android/set_up_android.py | Python | apache-2.0 | 3,533 | 0.016417 | #!/usr/bin/python
import os, sys, shutil, collections
from optparse import OptionParser
# Fix for python 2
try:
input = raw_input
except NameError:
pass
def find_recursive(root, subpath, maxdepth=4):
queue = collections.deque([(root, 0)])
if 'PATH' in os.environ:
envpath = os.environ['PATH'].split(':')
... | h)
if path and os.path.isfi | le(test):
return os.path.abspath(path)
else:
print('Could not find {0}, not an {1} path.'.format(test, title))
sys.exit(1)
def write_local_properties(sdkDir, ndkDir):
content = ''.join([x + '\n' for x in [
'# Autogenerated file',
'# Do not add it to version control',
'sdk.dir={0}'.for... |
getnikola/nikola | nikola/plugins/task/copy_files.py | Python | mit | 2,163 | 0.000463 | # -*- coding: utf-8 -*-
# Copyright © 2012-2022 Roberto Alsina and others.
# 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 t... | WARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | AUTHORS
# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""Copy static files into the output folder."""
import os
from nikola.pl... |
gemelkelabs/timing_system_software | server_py_files/utilities/timing_diagram.py | Python | mit | 5,170 | 0.00793 |
import pdb
class TimingDiagram:
def print_diagram(self, xtsm_object):
pdb.set_trace()
seq = xtsm_object.XTSM.getActiveSequence()
cMap=seq.getOwnerXTSM().getDescendentsByType("ChannelMap")[0]
#channelHeir=cMap.createTimingGroupHeirarchy()
#channelRes=cMap.findTiming... | None ':
previous_edge.value = 0
if is_found:
if current_edge.value > previous_edge.value:
s += '^' + str('%7s' % str(current_edge.value))
else:
s += 'v' + str('%7s' % str(current_edge.value))
... | previous_edge = current_edge
else:
s += '|' + '.'*7
s = s + '|' + str('%7s' % str(current_edge.holding_value))
print s
s = "Time (ms)".rjust(longest_name) + '|' + str('%7s' ... |
wolverineav/neutron | neutron/_i18n.py | Python | apache-2.0 | 1,355 | 0 | # All Rights Reserved.
#
# Licensed under the Apache Licens | e, 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.
import o... |
cts-admin/cts | cts/home/migrations/0005_auto_20170524_0700.py | Python | gpl-3.0 | 708 | 0.001412 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-05-24 07:00
from __future__ import unicode_literals
from django.db import migrations
import wa | gtail.core.blocks
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('home', '0004_auto_20170524_0608'),
]
operations = [
migrations.RemoveField(
model_name='homepage',
name='content',
),
migrations.AddField(
... | cks.CharBlock()), ('paragraph', wagtail.core.blocks.RichTextBlock())), blank=True),
),
]
|
geekoftheweek/disk-treemap | treemap.py | Python | mit | 2,734 | 0.001829 | #!/usr/bin/env python
'''
Creates an html treemap of disk usage, using the Google Charts API
'''
import json
import os
import subprocess
import sys
def memoize(fn):
stored_results = {}
def memoized(*args):
try:
return stored_results[args]
except KeyError:
result = store... | oot))
return json.dumps(result)
def main(args):
'''Populates an html template using JSON-formatted output from the
Linux 'du' utility and prints the result'''
html = '''
<html>
<head>
<script type="text/javascript" | src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["treemap"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTab... |
GNOME/orca | test/keystrokes/firefox/ui_role_tree.py | Python | lgpl-2.1 | 5,957 | 0.002686 | #!/usr/bin/python
"""Test of tree output using Firefox."""
from macaroon.playback import *
import utils
sequence = MacroSequence()
sequence.append(PauseAction(3000))
sequence.append(KeyComboAction("<Alt>b"))
sequence.append(KeyComboAction("Return"))
sequence.append(KeyComboAction("Tab"))
sequence.append(KeyComboAct... | der",
["BRAILLE LINE: 'Firefox application Library frame Book | marks Menu expanded TREE LEVEL 2'",
" VISIBLE: 'Bookmarks Menu expanded TREE LEV', cursor=1",
"SPEECH OUTPUT: 'expanded'"]))
sequence.append(utils.StartRecordingAction())
sequence.append(KeyComboAction("KP_Enter"))
sequence.append(utils.AssertPresentationAction(
"6. Basic Where Am I",
["BRAILLE... |
madzebra/BitSend | qa/rpc-tests/zmq_test.py | Python | mit | 3,224 | 0.006514 | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitsend Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test ZMQ interface
#
from test_framework.test_framework import BitsendTestFramework
from test_framew... | for x in range(0,n*2):
msg = self.zmqSubSocket.recv_multipart()
| topic = msg[0]
body = msg[1]
if topic == b"hashblock":
zmqHashes.append(bytes_to_hex_str(body))
msgSequence = struct.unpack('<I', msg[-1])[-1]
assert_equal(msgSequence, blockcount+1)
blockcount += 1
for x in range(0,n):... |
AustinHartman/randomPrograms | stringRep.py | Python | gpl-3.0 | 148 | 0.006757 | string = (input("What | is your string?\n"))
string.replace('K', 'M'[max])
string.replace('O', 'Q'[max])
string.replace('E', 'G'[ | max])
print(string) |
mrnamingo/vix4-34-enigma2-bcm | lib/python/Components/ServiceScan.py | Python | gpl-2.0 | 7,567 | 0.037531 | from enigma import eComponentScan, iDVBFrontend
from Components.NimManager import nimmanager as nimmgr
from Tools.Transponder import getChannelNumber
class ServiceScan:
Idle = 1
Running = 2
Done = 3
Error = 4
Errors = {
0: _("error starting scanning"),
1: _("error while scanning"),
2: _("no resource manag... | _9 : "8/9", tp.FEC_3_5 : "3/5", tp.FEC_4_5 : "4/5",
tp.FEC_9_10 : "9/10", tp.FEC_None : "NONE" }.get(tp.fec, ""))
elif tp_type == iDVBFrontend.feCable:
network = _("Cable")
tp = transponder.getDVBC()
tp_text = "DVB-C %s %d / %d / %s" %( { tp.Modulation_Auto : "AUTO",
tp.Modulation_... | 6" }.get(tp.modulation, ""),
tp.frequency,
tp.symbol_rate/1000,
{ tp.FEC_Auto : "AUTO", tp.FEC_1_2 : "1/2", tp.FEC_2_3 : "2/3",
tp.FEC_3_4 : "3/4", tp.FEC_5_6 : "5/6", tp.FEC_7_8 : "7/8",
tp.FEC_8_9 : "8/9", tp.FEC_3_5 : "3/5", tp.FEC_4_5 : "4/5", tp.FEC_9_10 : "9/10", tp.FEC_None :... |
numerai/submission-criteria | tests/benchmark_base.py | Python | apache-2.0 | 1,174 | 0.000852 | import statistics
from datetime import datetime
class Benchmark():
def __init__(self, n_runs: int = 5, print_checkpoint: bool = True):
self.n_runs = n_runs
self.print_checkpoint = print_checkpoint
@staticmethod
def log(message: str) -> None:
print('[%s] - %s' % (datetime.now(), m... | s, min: %.2f%s' % (
statistics.median(times), unit, statistics.mean(times), unit,
statistics.stdev(times), max(times), unit, min(times), unit)
def start(self, suffix: str = None):
if suffix is None:
suffix = '...'
else:
suffix = ': ' + suffix
... | k()
def benchmark(self):
raise NotImplementedError('method benchmark() not implemented yet')
|
twitterdev/twitter-python-ads-sdk | twitter_ads/targeting.py | Python | mit | 998 | 0 | # Copyright (C) 2015 Twitter, Inc.
"""Container for all targeting related logic used by the Ads API SDK."""
from twitter_ads.http import Request
from twitter_ads.resou | rce import resource_property, Resource, Persistence
from twitter_ads import API_VERSION
from twitter_ads.utils import FlattenParams
import json
class AudienceEstimate(Resource, Persistence):
PROPERTIES = {}
RESOURCE = '/' + API_VERSION + '/accounts/ | {account_id}/audience_estimate'
@classmethod
@FlattenParams
def load(klass, account, params):
resource = klass.RESOURCE.format(account_id=account.id)
headers = {'Content-Type': 'application/json'}
response = Request(account.client,
'post',
... |
TecnoSalta/bg | mezzanine/utils/device.py | Python | bsd-2-clause | 2,013 | 0 | from __future__ import unicode_literals
def device_from_request(request):
"""
Determine's the device name from the request by first looking for an
overridding cookie, and if not found then matching the user agent.
Used at both the template level for choosing the template to load and
also at the ca... | return ""
def templates_for_device(request, templates):
"""
Given a template name (or list of them), returns the template names
as a list, with each name prefixed with the device directory
inserted before it's associate default in the list.
"""
from mezzanine.conf import settings
if not i... | ):
templates = [templates]
device = device_from_request(request)
device_templates = []
for template in templates:
if device:
device_templates.append("%s/%s" % (device, template))
if settings.DEVICE_DEFAULT and settings.DEVICE_DEFAULT != device:
default = "%s/%... |
rocktavious/pyversion | setup.py | Python | mit | 107 | 0 | f | rom setuptools import setup
setup(
setup_requires=['pbr', ],
pbr=T | rue,
auto_version="PBR",
)
|
maui-packages/calamares | src/modules/fstab/main.py | Python | gpl-3.0 | 5,216 | 0.000767 | #!/usr/bin/env python3
# encoding: utf-8
# === This file is part of Calamares - <http://github.com/calamares> ===
#
# Copyright 2014, Aurélien Gâteau <agateau@kde.org>
#
# Calamares is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# t... | rtition):
name = os.path.basename(partition["device"])
return re.sub("[0-9]+$", "", | name)
class FstabGenerator(object):
def __init__(self, partitions, root_mount_point, mount_options,
ssd_extra_mount_options):
self.partitions = partitions
self.root_mount_point = root_mount_point
self.mount_options = mount_options
self.ssd_extra_mount_options = ssd_extr... |
manojgudi/sandhi | modules/gr36/gnuradio-core/src/lib/filter/generate_gr_fir_sysconfig_generic.py | Python | gpl-3.0 | 4,373 | 0.011891 | #!/bin/env python
# -*- python -*-
#
# Copyright 2003,2009 Free Software Foundation, Inc | .
#
# This file is part of GNU Radio
#
# GNU Radio 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.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or ... |
microelly2/geodata | geodat/import_osm.py | Python | lgpl-3.0 | 23,641 | 0.05022 | # -*- coding: utf-8 -*-
#-------------------------------------------------
#-- osm map importer
#--
#-- microelly 2016 v 0.4
#--
#-- GNU Lesser General Public License (LGPL)
#-------------------------------------------------
'''import data from openstreetmap'''
#http://api.openstreetmap.org/api/0.6/map?bbox=11.74182,... | todict import parse
#\endcond
#------------------------------
#
# microelly 2016 ..
#
#------------------------------
import time
## get the elevation height of a single point
def getHeight(b,l):
''' get height | of a single point with latitude b, longitude l'''
anz=0
while anz<4:
source="https://maps.googleapis.com/maps/api/elevation/json?locations="+str(b)+','+str(l)
try:
response = urllib2.urlopen(source)
except:
response = urllib.request.urlopen(source)
ans=response.read()
if ans.find("OVER_QUERY_LI... |
mkacik/bcc | tools/uobjnew.py | Python | apache-2.0 | 5,131 | 0.000974 | #!/usr/bin/python
# @lint-avoid-python-3-compatibility-imports
#
# | uobjnew Summarize object allocations in high-level languages.
# For Linux, uses BCC, eBPF.
#
# USAGE: uobjnew [-h] [-T TOP] [-v] {java,ruby,c} pid [interval]
#
# Copyright 2016 Sasha | Goldshtein
# Licensed under the Apache License, Version 2.0 (the "License")
#
# 25-Oct-2016 Sasha Goldshtein Created this.
from __future__ import print_function
import argparse
from bcc import BPF, USDT
from time import sleep
examples = """examples:
./uobjnew java 145 # summarize Java allocations in ... |
marshmallow-code/apispec | tests/test_yaml_utils.py | Python | mit | 908 | 0.001116 | import pytest
from apispec import yaml_utils
def test_load_yaml_from_docstring():
def f():
"""
Foo
bar
baz quux
---
herp: 1
derp: 2
"""
result = yaml_utils.load_yaml_from_docstring(f.__doc__)
assert result == {"herp": 1, "derp": 2}
... | l_utils.load_yaml_from_docstring(docstring) == {}
@pytest.mark.parametrize("docstring", (None, "", "---"))
def test_load_operations_from_docstring_empty_docstring(docstring):
assert yaml_util | s.load_operations_from_docstring(docstring) == {}
def test_dict_to_yaml_unicode():
assert yaml_utils.dict_to_yaml({"가": "나"}) == '"\\uAC00": "\\uB098"\n'
assert yaml_utils.dict_to_yaml({"가": "나"}, {"allow_unicode": True}) == "가: 나\n"
|
Advait-M/Tetros | src/Tetros.py | Python | gpl-3.0 | 64,805 | 0.001836 | #!/usr/bin/env python
"""This is a game called Tetros made with Tkinter graphics (quite similar to Tetris)."""
# Import modules
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
from tkinter.ttk import *
import random
import math
import time
import cmath
import copy
import sys
import w... | s screen)
quitB = Button(
root,
text="Quit Tetros",
command=lambda: endAll())
res | tartB = Button(
root,
text="Restart Tetros",
command=lambda: restart())
# Initialize variables and objects needed for the instructions screen
menubar = Menu(root)
menuB = Menu(menubar, tearoff=0)
menuB.add_command(label="Save Progress", command=lambda: save())
menuB.add_command(label="Load From File", comm... |
EricHripko/TheQuestOfTin | tqot/animation.py | Python | gpl-3.0 | 2,600 | 0.000385 | import pygame.time
class Animation:
"""
Class that defines simple looped frame-by-frame animations
on art-assets and plays them when prompted to.
"""
def __init__(self, sprite):
"""
Create a new animation.
:param sprite: Asset sprite that will play the animation.
:... | uration = pygame.time.get_ticks()
# Check whether the loop is needed
if self.cur | rent == len(self.frames):
self.current = 0
def invalidate(self):
"""
Update the current frame displayed by the animation.
Internal routine necessary to be carried out after the
animation flow was manually altered.
"""
(state, duration) = self.frames[self.... |
valentingalea/vinyl-shelf-finder | pantilthat/finder.py | Python | mit | 2,511 | 0.024691 | #!/usr/bin/env python
import pantilthat
import time
import sys
import math
import servo_ranges
def tick():
time.sleep(0.010)
class Shelf(object):
def __init__(self, num, start, end, tilt):
self.count = num; # num of records
self.pan_start = start; # degress +
self.pan_end = end; # degrees -
self.tilt_pos =... | return int(math.degrees(angle))
max_shelves = 5
shelves = [
Shelf(42, 24, -29, -68),
Shelf(68, 24, -28, -40),
Shelf(80, 26, -25, 0),
Shelf(88, 25, -26, +40),
Shelf(68, 26, -26, +65)
]
# sanity checks
if len(sy | s.argv) != 3:
print "Usage: <shelf id> <shelf pos>\n"
exit()
# setup
servo_ranges.calibrate()
# read last cmd
orig_pan = pantilthat.get_pan()
orig_tilt = pantilthat.get_tilt()
print "found pan: %i; tilt: %i" % (orig_pan, orig_tilt)
# get args
in_id = int(sys.argv[1])
in_id = (in_id - 1) % max_shelves # convert to ... |
gangadharkadam/v5_erp | erpnext/setup/page/setup_wizard/install_fixtures.py | Python | agpl-3.0 | 12,019 | 0.018055 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
def install(country=None):
records = [
# address template
{'doctype':"Address Template", "country": count... | , 'department_name': _('Accounts')},
{'doctype': 'Department', 'department_name': _('Marketing')},
{'doctype': 'Department', 'department_name': _('Sale | s')},
{'doctype': 'Department', 'department_name': _('Purchase')},
{'doctype': 'Department', 'department_name': _('Operations')},
{'doctype': 'Department', 'department_name': _('Production')},
{'doctype': 'Department', 'department_name': _('Dispatch')},
{'doctype': 'Department', 'department_name': _('Customer... |
DailyActie/Surrogate-Model | 01-codes/numpy-master/doc/source/conf.py | Python | mit | 9,985 | 0.001202 | # -*- coding: utf-8 -*-
from __future__ import division, absolute_import, print_function
import os
import re
import sys
# Check Sphinx version
import sphinx
if sphinx.__version__ < "1.0.1":
raise RuntimeError("Sphinx 1.0.1 or newer required")
needs_sphinx = '1.0'
# ---------------------------------------------... | r = 'Written by the NumPy community'
latex_documents = [
('reference/index', 'numpy-ref.tex', 'NumPy Reference',
_stdauthor, 'manual'),
('user/index', 'numpy-user.tex', 'NumPy User Guide',
_stdauthor, 'manual'),
]
# The name of an image file (relative to this di | rectory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# Additional stuff for the LaTeX preamble.
latex_preamble = r'''
\usepackage{amsmath}
\DeclareUnicodeCharacter{00A0}{\nobreakspac... |
kbrebanov/ansible | lib/ansible/plugins/action/ce.py | Python | gpl-3.0 | 3,950 | 0.002025 | #
# (c) 2016 Red Hat Inc.
#
# 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) any later version.
#
# Ansible is d... | connection plugin %s' % pc.connection, pc.remote_addr)
connection = self._shared_loader_obj.connection_loader.get('persistent', pc, sys.stdin)
socket_path = connection.run()
display.vvvv('socket_path: %s' % socket_pat | h, pc.remote_addr)
if not socket_path:
return {'failed': True,
'msg': 'unable to open shell. Please see: ' +
'https://docs.ansible.com/ansible/network_debug_troubleshooting.html#unable-to-open-shell'}
# make sure we are in t... |
damianmoore/photo-manager | tests/factories.py | Python | agpl-3.0 | 2,156 | 0.000464 | from pathlib import Path
from django.utils import timezone
import factory
from photonix.accounts.models import User
from photonix.photos.models import Library, LibraryUser, Photo, PhotoFile, Tag, PhotoTag, Task
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
username ... | da o: timezone.now())
class TagFactory(factory.django.DjangoModelFactory):
class Meta:
model = Ta | g
library = factory.SubFactory(LibraryFactory)
name = factory.Sequence(lambda n: f'Tag {n}')
class PhotoTagFactory(factory.django.DjangoModelFactory):
class Meta:
model = PhotoTag
photo = factory.SubFactory(PhotoFactory)
tag = factory.SubFactory(TagFactory)
class TaskFactory(factory.dj... |
atlab/attorch | attorch/regularizers.py | Python | mit | 3,598 | 0.002779 | import numpy as np
import torch
import torch.nn as nn
from itertools import product
from torch.nn import functional as F
#import pytorch_fft.fft as fft
# def laplace():
# return np.array([[0.25, 0.5, 0.25], [0.5, -3.0, 0.5], [0.25, 0.5, 0.25]]).astype(np.float32)[None, None, ...]
def laplace():
return np.arr... | k1, k2).pow(2) * weights).mean() / 2
class LaplaceL23d(nn.Module):
"""
Laplace r | egularizer for a 2D convolutional layer.
"""
def __init__(self):
super().__init__()
self.laplace = Laplace3d()
def forward(self, x):
ic, oc, k1, k2, k3 = x.size()
return self.laplace(x.view(ic * oc, 1, k1, k2, k3)).pow(2).mean() / 2
class FlatLaplaceL23d(nn.Module):
"... |
Therp/stock-logistics-warehouse | __unported__/stock_available_immediately/__openerp__.py | Python | agpl-3.0 | 1,363 | 0 | # -*- coding: utf-8 -*-
#
#
# Author: Guewen Baconnier
# Copyright 2010-2012 Camptocamp SA
# Copyright (C) 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
#... | stock.
Immediately usable is computed : Quantity on Hand - Outgoing Stock.
""",
"website": "http://tinyerp.com/module_account.html",
"category": "Generic Modules/Stock",
"data": ["product_view.xml",
],
"active": False,
'installable' | : False
}
|
msanatan/organise | run.py | Python | mit | 36 | 0 | from organise i | mport app
app. | run()
|
aurex-linux/virt-manager | virtManager/engine.py | Python | gpl-2.0 | 41,820 | 0.001124 | #
# Copyright (C) 2006, 2013 Red Hat, Inc.
# Copyright (C) 2006 Daniel P. Berrange <berrange@redhat.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 2 of the License, or
# (... | imer = None
self.last_timeout = 0
self.systray = None
self.delete_dialog = None
self.application = Gtk.Application(
application_id="com.redhat.virt-manager",
| flags=0)
self.application.connect("activate", self._activate)
self._appwindow = Gtk.Window()
self._tick_counter = 0
self._tick_thread_slow = False
self._tick_thread = threading.Thread(name="Tick thread",
target=sel... |
keelerm84/powerline | powerline/segments/plugin/ctrlp.py | Python | mit | 2,722 | 0.031227 | # vim:fileencoding=utf-8:noet
try:
import vim
except ImportError:
vim = object() # NOQA
from powerline.bindings.vim import getbufvar
from powerline.segments.vim import window_cached
@window_cached
def ctrlp(pl, side):
'''
Highlight groups used: ``ctrlp.regex`` or ``background``, ``ctrlp.prev`` or ``background... | 'regex',
'highlight_group': ['ctrlp.regex', 'background'],
})
segments += [
{
'contents': prev + ' ',
'highlight_group': ['ctrlp.prev', 'background'],
'draw_inner_divider': True,
'priority': 40,
},
{
'contents': item,
'highlight_group': ['ctrlp.item', 'file_name'],
'draw_inner_divide... | },
]
if marked != '-':
segments.append({
'contents': marked,
'highlight_group': ['ctrlp.marked', 'background'],
'draw_inner_divider': True,
})
return segments
def ctrlp_stl_right_main(pl, focus, byfname, regex, prev, item, next, marked):
'''
Highlight groups used: ``ctrlp.focus`` or ``background... |
domi-id/across | across/res.py | Python | mit | 2,378 | 0.002103 | #!/usr/bin/env python3
import os
from construct import Adapter, Const, GreedyBytes, Int32ul, Struct, this
from .common import ZeroString, PreallocatedArray, test_folder, mkdir_p
from .encryption import EncryptedBlock
RES_ENCRYPTION = 23, 9782, 3391, 31
# noinspection PyPep8,PyUnresolvedReferences
ResourceEntry = ... | eFileAdapter(RawResourceFile)
def unpack_res(file_path, dir_path):
with open(file_path) as f:
| data = f.read()
res = ResourceFile.parse(data)
mkdir_p(dir_path)
for file_name, file_data in res.items():
with open(os.path.join(dir_path, file_name), "wb") as f:
f.write(file_data)
def pack_res(dir_path, file_path):
res_content = {}
for root, dirs, files in os.walk(di... |
DailyActie/Surrogate-Model | 01-codes/OpenMDAO-Framework-dev/openmdao.test/src/openmdao/test/plugins/foo2/foo.py | Python | mit | 162 | 0 | cl | ass Comp1Plugin(object):
def __init__(self):
self.version = '1.4'
class Comp2Plugin(ob | ject):
def __init__(self):
self.version = '1.4'
|
JustinWingChungHui/electionleaflets | electionleaflets/apps/people/models.py | Python | mit | 1,603 | 0.001871 | from django.db import models
from constituencies.models import Constituency
from uk_political_parties.models import Party
from elections.models import Election
class Person(models.Model):
name = models.CharField(blank=False, max_length=255)
remote_id = models.CharField(blank=True, max_length=255, null=True)... | lank=True, null=True)
source_name = models.CharField(blank=True, max_length=100)
image_url = models.URLField(blank=True, null=True)
elections = models.ManyToManyField(Election)
parties = models.ManyToManyField(Party, through='PartyMemberships')
constituencies = models.ManyToManyField(Constituency, t... | es')
@property
def current_party(self):
parties = self.partymemberships_set.filter(membership_end=None)
if parties:
return parties[0]
@property
def current_election(self):
return self.elections.filter(active=True)[0]
@property
def current_constituency(self... |
fedorlol/Tolyan | bot/__main__.py | Python | gpl-3.0 | 36 | 0 | from bot.server impo | rt main
main | ()
|
saisankargochhayat/algo_quest | hackerearth/segment_tree_problem.py | Python | apache-2.0 | 1,757 | 0.036426 | import math
class segment_tree():
def __init__(self,a):
self.a = a
self.root = self.build(0,len(a)-1)
def build(self,left,right):
if left == right:
node = {}
node['value'] = self.a[left]
node['left'] = None
node['right'] = None
... | _value,mid+1,right)
node['value'] = min(node['left']['value'] , node['right']['value'])
def query(self,root,start,end,left,right):
if start>right or end<left:
return float('inf')
if start<=left and right<=end:
return root['value']
mid = int((left+right)/2)... | lit(' ')))
s = segment_tree(a)
for i in range(q):
query,left,right = input().split(' ')
left,right = int(left)-1,int(right)-1
if query == 'q':
print(s.query(s.root,left,right,0,n-1))
else:
s.update(s.root,left,right+1,0,n-1)
|
yanchen036/tensorflow | tensorflow/contrib/distributions/python/ops/bijectors/weibull.py | Python | apache-2.0 | 5,266 | 0.003608 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | is the same dtype and is
broadcastable with `scale`.
This is `k` in `Y = g(X) = 1 - exp((-x / l) ** k)`.
validate_args: Python `bool` indicating whether arguments should be
checked for correctness.
name: Python `str` name given to ops managed by this object.
"""
self._graph_p... | ith self._name_scope("init", values=[scale, concentration]):
self._scale = ops.convert_to_tensor(scale, name="scale")
self._concentration = ops.convert_to_tensor(
concentration, name="concentration")
check_ops.assert_same_float_dtype([self._scale, self._concentration])
if validate_args... |
jaymin-panchal/zang-python | zang/inboundxml/elements/play.py | Python | mit | 599 | 0 | # -*- coding: utf-8 -*-
"""
zang.inboundxm | l.elemen | ts.play
~~~~~~~~~~~~~~~~~~~
Module containing `Play` inbound xml element
"""
from zang.inboundxml.elements.base_node import BaseNode
class Play(BaseNode):
_allowedContentClass = ()
def __init__(self, url, loop=None):
if url is None:
raise TypeError
self._value = url
self... |
skycucumber/Messaging-Gateway | webapp/venv/lib/python2.7/site-packages/twisted/words/test/test_jabbersasl.py | Python | gpl-2.0 | 8,748 | 0.002743 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from zope.interface import implements
from twisted.internet import defer
from twisted.trial import unittest
from twisted.words.protocols.jabber import sasl, sasl_mechanisms, xmlstream, jid
from twisted.words.xish import domish
NS_XMPP_SASL = 'urn... | self.xmlstream.dataReceived("<stream:stream xmlns='jabber:client' "
"xmlns:stream='http://etherx.jabber.org/st | reams' "
"from='example.com' id='12345' version='1.0'>")
self.init = DummySASLInitiatingInitializer(self.xmlstream)
def test_onFailure(self):
"""
Test that the SASL error condition is correctly extracted.
"""
failure = domish.Element(('urn:ietf:param... |
LuisUrrutia/hackerrank | python/introduction/python-arithmetic-operators.py | Python | mit | 126 | 0.007937 | if __name_ | _ == '__main__':
a = int(raw_input())
b = int(raw_input())
print a + b
print a - b
| print a * b
|
wcmitchell/insights-core | insights/parsers/manila_conf.py | Python | apache-2.0 | 1,598 | 0.001252 | """
Manila configuration - file ``/etc/manila/manila.conf``
================ | =======================================
The Manila configuration file is a standard '.ini' file and this parser uses
the ``IniConfigFile`` class to read it.
Sample configuration::
[DEFAULT]
osapi_max_limit = 1000
osapi_share_base_URL = <None>
use_forwarded_for = false
api_paste_config = api-past... | ar/lib/manila
scheduler_topic = manila-scheduler
share_topic = manila-share
share_driver = manila.share.drivers.generic.GenericShareDriver
enable_v1_api = false
enable_v2_api = false
[cors]
allowed_origin = <None>
allow_credentials = true
expose_headers = Content-Type,Cache-Con... |
fightingwalrus/gerbmerge | gerbmerge/jobs.py | Python | gpl-3.0 | 52,296 | 0.015049 | #!/usr/bin/env python
"""
This module reads all Gerber and Excellon files and stores the
data for each job.
--------------------------------------------------------------------
This program is licensed under the GNU General Public License (GPL)
Version 3. See http://www.fsf.org for details of the license.
Rugged Ci... | \*') # Drawing command, Y is implied
drawY_pat = re.compile(r'Y([+-]?\d+)D0?([123])\*') # Drawing command, X is implied
format_pat = re.compile(r'%FS(L|T)?(A|I)(N\d+)?(X\d\d)(Y\d\d)\*%') # Format statement
layerpol_pat = re.compile(r'^%LP[CD]\*%') # Layer polarity (D=dark, C=clear)
# Circul... | drawing commands (from Protel)
cdrawXY_pat = re.compile(r'X([+-]?\d+)Y([+-]?\d+)I([+-]?\d+)J([+-]?\d+)D0?([123])\*')
cdrawX_pat = re.compile(r'X([+-]?\d+)I([+-]?\d+)J([+-]?\d+)D0?([123])\*') # Y is implied
cdrawY_pat = re.compile(r'Y([+-]?\d+)I([+-]?\d+)J([+-]?\d+)D0?([123])\*') # X is implied
IgnoreList = ( \
#... |
sailfish-sdk/sailfish-qtcreator | tests/system/suite_tools/tst_codepasting/test.py | Python | gpl-3.0 | 11,988 | 0.004922 | ############################################################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the co... | pasteLine,
"Verify that line in list of pastes contains the descripti | on")
except:
if protocol == NAME_PBCA:
test.xfail("%s does not list the pasted snippet on time" % NAME_PBCA)
elif not skippedPasting:
test.fail("Could not find id '%s' in list of pastes from %s" % (pasteId, protocol))
foundSnippet = False
... |
olivierlemasle/murano | murano/tests/unit/dsl/test_statics.py | Python | apache-2.0 | 4,079 | 0 | # Copyright (c) 2016 Mirantis, 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... |
def test_call_static_method_on_class_name(self):
self.assertEqual(123, self._runner.testCallStaticMethodOnClassName())
def test_call_static_method_on_class_name_with_ns(self):
self.assertEqual(
123, self._runner.testCallStaticMethodOnClassNameWithNs())
def test_call_static_met... | runner.testCallStaticMethodFromAnotherMethod())
def test_static_this(self):
self.assertIsInstance(
self._runner.testStaticThis(), dsl_types.MuranoTypeReference)
def test_no_access_to_instance_properties(self):
self.assertRaises(
exceptions.NoPropertyFound,
s... |
RensaProject/nodebox_linguistics_extended | nodebox_linguistics_extended/parser/nltk_lite/contrib/paradigm.py | Python | gpl-2.0 | 24,313 | 0.00473 | # Natural Language Toolkit: Paradigm Visualisation
#
# Copyright (C) 2005 University of Melbourne
# Author: Will Hardy
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
# Front end to a Python implementation of David
# Penton's paradigm visualisation model.
# Author:
#
# Run: To run, first load a... | t += "<table cellspacing=\"0\" cellpadding=\"0\">"
output += result.getHTML()
output += "</table>\n"
output += '</body></html>\n'
els | e:
output = result.getText()
except:
output = None
print "--no output--"
return
# Print to terminal if output is set, otherwise to file
if self.output == "term":
print output
else:
print "Output written to file:", s... |
aron-bordin/kivy | kivy/core/window/__init__.py | Python | mit | 57,469 | 0.000331 | # pylint: disable=W0611
# coding: utf-8
'''
Window
======
Core class for creating the default Kivy window. Kivy supports only one window
per application: please don't try to create more than one.
'''
__all__ = ('Keyboard', 'WindowBase', 'Window')
from os.path import join, exists
from os import getcwd
from kivy.core... | e
# currently taken from pygame.key. But when a new provider will be
# used, it must do the translation to these keycodes too.
keycodes = {
# specials keys
'backspace': 8, 'tab': 9, 'enter': 13, 'rshift': 303, 'shift': 304,
'alt': 308, 'rctrl': 306, 'lctrl': 305,
'super': 309... | 'pagedown': 281, 'end': 279, 'home': 278, 'left': 276, 'up':
273, 'right': 275, 'down': 274, 'insert': 277, 'delete': 127,
'numlock': 300, 'print': 144, 'screenlock': 145, 'pause': 19,
# a-z keys
'a': 97, 'b': 98, 'c': 99, 'd': 100, 'e': 101, 'f': 102, 'g': 103,
'h': 104, 'i': ... |
EDRN/CancerDataExpo | src/edrn.rdf/edrn/rdf/upgrades.py | Python | apache-2.0 | 2,788 | 0.002154 | # encoding: utf-8
# Copyright 2013–2017 California Institute of Technology. ALL RIGHTS
# RESERVED. U.S. Government Sponsorship acknowledged.
from .setuphandlers import publish
from edrn.rdf import DEFAULT_PROFILE
from plone.dexterity.utils import createContentInContainer
from edrn.rdf.labcascollectionrdfgenerator impo... | ing https://edrn.jpl.nasa.gov/cancerdataexpo/ so we could take
# immediate advantage of the new data without cutting a new release.
# This is provided just in case there is a disaster and we need to
# re-release.
portal = setupTool.getSite()
if 'rdf-generators' in list(portal.keys()):
rdfGen... | personGenerator = rdfGenerators['person-generator']
if 'staff_status' not in list(personGenerator.keys()):
predicate = createContentInContainer(
personGenerator,
'edrn.rdf.literalpredicatehandler',
title='Staff_Status',
... |
nihilus/src | pywraps/py_choose.py | Python | bsd-3-clause | 1,595 | 0.016928 |
#<pycode(py_choose)>
class Choose:
"""
Choose - class for choose() with callbacks
"""
def __init__(self, list, title, flags=0, deflt=1, icon=37):
self.list = list
self.title = title
self.flags = flags
self.x0 = -1
self.x1 = -1
self.y0 = -1
self.y1 = -1
self.width = -1
self... | = deflt
self.icon = icon
# HACK: Add a circular reference for non-modal choosers. This prevents the GC
# from collecting the class object the | callbacks need. Unfortunately this means
# that the class will never be collected, unless refhack is set to None explicitly.
if (flags & Choose2.CH_MODAL) == 0:
self.refhack = self
def sizer(self):
"""
Callback: sizer - returns the length of the list
"""
return len(self.list)
def ge... |
zhangyage/Python-oldboy | day13/Django_study/manage.py | Python | apache-2.0 | 255 | 0 | #!/usr/ | bin/env python
import os
import sys
if __name__ == "__ | main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Django_study.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
hawkphantomnet/leetcode | PathSum/Solution.py | Python | mit | 625 | 0.0048 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
| class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root == None:
return False
if root.val == sum and root.left == None and root.right == None:
return True
left = ... | ft, sum - root.val)
right = self.hasPathSum(root.right, sum - root.val)
return (left or right)
|
AmandaMoen/AmandaMoen | code/session06/run_html_render.py | Python | gpl-2.0 | 5,015 | 0.004786 | #!/usr/bin/env python
"""
a simple script can run and test your html rendering classes.
Uncomment the steps as you add to your rendering.
"""
import codecs
import cStringIO
# importing the html_rendering code with a short name for easy typing.
import html_render as hr
## writing the file out:
def render(page, fil... | e could be more of them, but this is enough to show that we can do some text")
page.append(u"And here is another piece | of text -- you should be able to add any number")
render(page, u"test_html_output1.html")
# ## Step 2
# ##########
# page = hr.Html()
# body = hr.Body()
# body.append(hr.P(u"Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text"))
# body.append(hr.P(u"An... |
kinow-io/kinow-python-sdk | kinow_client/models/widget_home_rail.py | Python | apache-2.0 | 5,545 | 0.000361 | # coding: utf-8
"""
Server API
Reference for Server API (REST/Json)
OpenAPI spec version: 2.0.6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class WidgetHomeRail(object):
"""
NOTE: This class is au... | "
Gets the label of this WidgetHomeRail.
:return: The label of this WidgetHomeRail.
:rtype: list[I18nField]
"""
return self._label
@label.setter
def label(self, label):
"""
Sets the label of this WidgetHomeRail.
:param label: The label of this W... | ist[I18nField]
"""
self._label = label
@property
def type(self):
"""
Gets the type of this WidgetHomeRail.
:return: The type of this WidgetHomeRail.
:rtype: str
"""
return self._type
@type.setter
def type(self, type):
"""
... |
MDXDave/ModernWebif | plugin/controllers/models/owibranding.py | Python | gpl-2.0 | 15,558 | 0.03349 | # -*- coding: utf-8 -*-
##############################################################################
# 2014 E2OpenPlugins #
# #
# This file is open source software; you can redistribute... | rn 0
value = tpm.computeSignature(random)
result = decrypt_block(value, l3k)
if result is None:
return 0
if result [80:88 | ] != random:
return 0
return 1
except:
return 0
def getAllInfo():
info = {}
brand = "unknown"
model = "unknown"
procmodel = "unknown"
orgdream = 0
if tpmloaded:
orgdream = tpm_check()
if fileExists("/proc/stb/info/hwmodel"):
brand = "DAGS"
f = open("/proc/stb/info/hwmodel",'r')
procmodel = f... |
mtholder/pyraphyletic | phylesystem_api/tests.py | Python | bsd-2-clause | 7,707 | 0.001946 | """Unittests that do not require the server to be running an common tests of responses.
The TestCase here just calls the functions that provide the logic to the ws views with DummyRequest
objects to mock a real request.
The functions starting with `check_...` are called with UnitTest.TestCase instance as the first
ar... | hylesystem_api.views import push_failure
pf = push_failure(request)
check_pu | sh_failure_response(self, pf)
def test_doi_import(self):
"""Make sure that fetching from DOI generates a valid study shell."""
doi = "10.3732/ajb.0800060"
document = import_nexson_from_crossref_metadata(doi=doi,
ref_string=None,
... |
liorvh/grab | setup.py | Python | mit | 1,293 | 0 | from setuptools import setup, find_packages
import os
ROOT = os.path.dirname(os.path.realpath(__file__))
setup(
name='grab',
version='0.6.22',
description='Web Scraping Framework',
long_description=open(os.path.join(ROOT, 'README.rst')).read(),
url='http://grablib.org',
author='Gregory Petukho... | eywords="pycurl multicurl curl network parsing grabbing scraping"
" lxml xpath data mining",
classifiers=(
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementatio... | on/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Internet :: WWW... |
cloudify-cosmo/softlayer-python | SoftLayer/CLI/snapshot/list.py | Python | mit | 1,122 | 0 | """List iSCSI Snapshots."""
# :license: MIT, see LICENSE for more details.
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.CLI import helpers
from SoftLayer import utils
import click
@click.command()
@click.argument('iscsi-identifier')
@environment.pass_env... | eId,createDate,type', id=iscsi_id)
snapshots = [utils.NestedDict(n) for n in snapshots]
table = formatting.Table(['id', 'createDate', 'name', 'description'])
for snapshot in snapshots:
table.add_row([
snapshot['par | tnerVolumeId'],
snapshot['createDate'],
snapshot['type']['name'],
snapshot['type']['description'],
])
return table
|
ajventer/ezdm | ezdm_libs/all_characters.py | Python | gpl-3.0 | 1,127 | 0.000887 | from .frontend import JSON_Editor, mode, Page
from . import frontend
from .character import Character
from .util import load_json, debug
class CHARACTERS(JSON_Editor):
def __init__(self):
self._name = 'character'
JSON_Editor.__init__(self)
self._icons = 'avatars'
self._obj = Charac... | stdata)
else:
char = frontend.campaign.current_char()
return self.view(char.name())
def view(self, item):
page = Page()
if not item:
page.error('No item specified')
return page.render()
try:
debug('try %s/%s' % (self._name,... | (item, self._name))
return page.render()
c = Character(json)
rendered = {}
rendered['json'] = c.render()
return page.tplrender('json_viewer.tpl', rendered)
|
marbindrakon/eve-wspace | evewspace/search/registry.py | Python | apache-2.0 | 3,019 | 0.002981 | # Eve W-Space
# Copyright 2014 Andrew Austin and contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | [model] = search
def _autodiscover(registry):
import copy
from django.conf import settings
from importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Attempt to import app's search... |
import_module('%s.searches' % app)
except:
registry = before_import_registry
if module_has_submodule(mod, 'searches'):
raise
registry = SearchRegistry()
def autodiscover():
_autodiscover(registry)
def register(model, name, search_field, queryset=None):
... |
ypersyntelykos/GitSavvy | core/git_mixins/checkout_discard.py | Python | mit | 589 | 0 | class CheckoutDiscardMixin():
def discard_all_unstaged(self):
"""
Any changes that are not staged or committed will be reverted
to their state in HEAD. Any new files will be deleted.
"""
self.git("clean", "-df")
se | lf.git("checkout", "--", ".")
def checkout_file(self, fpath):
"""
Given an absolute path or path relative to the repo's r | oot, discard
any changes made to the file and revert it in the working directory
to the state it is in HEAD.
"""
self.git("checkout", "--", fpath)
|
INTechSenpai/moon-rover | debug_tools/python_debug_console/AsciiSerial.py | Python | gpl-3.0 | 11,638 | 0.003268 | import serial
import serial.tools.list_ports
import copy
import numpy as np
import math
import random
class AsciiSerial:
def __init__(self):
self._graphsChannels = {'graph1': None, 'graph2': None, 'graph3': None, 'graph4': None}
self._enChannels = {'graph1': False, 'graph2': False, 'graph3': Fals... | 'graph2': competeConfig['graph2']['channel'],
'graph3': competeConfig['graph3']['channel'],
' | graph4': competeConfig['graph4']['channel']}
newEnabledList = {'graph1': competeConfig['graph1']['enable'],
'graph2': competeConfig['graph2']['enable'],
'graph3': competeConfig['graph3']['enable'],
'graph4': competeConfig['graph4']['e... |
vpadillar/pventa | reporte/migrations/0002_auto_20161110_0819.py | Python | mit | 504 | 0.001984 | # -*- coding: u | tf-8 -*-
# Generated by Django 1.9.1 on 2016-11-10 08:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('reporte', '0001_initial'),
]
operatio | ns = [
migrations.AlterField(
model_name='reporteproducto',
name='tipo',
field=models.IntegerField(choices=[(1, 'Diaria'), (2, 'Semana'), (3, 'Mensual'), (4, 'Anual')]),
),
]
|
betterclever/susi_linux | main/renderer/configuration_window.py | Python | apache-2.0 | 8,711 | 0 | import os
from pathlib import Path
import gi
import logging
from gi.repository import Gtk
import json_config
from .login_window import LoginWindow
TOP_DIR = os.path.dirname(os.path.abspath(__file__))
config = json_config.connect('config.json')
gi.require_version('Gtk', '3.0')
class WatsonCredentialsDialog(Gtk.Dia... | et_active(2)
else:
self.tts_combobox.set_active(0)
config['default_tts'] = 'google'
def init_stt_combobox(self):
default_stt = config['default_stt']
if default_stt == 'google':
self.stt_co | mbobox.set_active(0)
elif default_stt == 'watson':
self.stt_combobox.set_active(1)
elif default_stt == 'bing':
self.stt_combobox.set_active(2)
else:
self.tts_combobox.set_active(0)
config['default_tts'] = 'google'
def init_auth_switch(self):
... |
mkoistinen/django-filer | filer/admin/imageadmin.py | Python | bsd-3-clause | 1,629 | 0 | # -*- coding: utf-8 -*-
from django import forms
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.utils.translation import ugettext as _
from filer.admin.fileadmin import FileAdmin
from filer.models import Image
class ImageAdminForm(forms.ModelForm):
subject_location = forms.Ch... | nstead of ".".
# javascript would parse that to an integer.
return '%.6F' % self.instance.sidebar_image_ratio()
else:
return ''
class Meta:
model = Image
exclude = ()
class Media:
css = {
# 'all': (settings.MEDIA_URL + 'filer/css/... |
}
js = (
static('filer/js/raphael.js'),
static('filer/js/focal_point.js'),
)
class ImageAdmin(FileAdmin):
form = ImageAdminForm
ImageAdmin.fieldsets = ImageAdmin.build_fieldsets(
extra_main_fields=('author', 'default_alt_text', 'default_caption',),
extra_... |
tejo-esperanto/pasportaservo | core/middleware.py | Python | agpl-3.0 | 6,047 | 0.002481 | from django.conf import settings
from django.contrib.auth.views import (
LoginView, LogoutView, redirect_to_login as redirect_to_intercept,
)
from django.core.exceptions import PermissionDenied, ValidationError
from django.template.response import TemplateResponse
from django.urls import Resolver404, resolve, rever... | # so it is immediately fetched from the database.
request.user.consent_required = [polic | y.first()]
if request.user.consent_required[0] is None:
raise RuntimeError("Service misconfigured: No user agreement was defined.")
if trouble_view.func.view_class != AgreementView:
return redirect_to_intercept(
request.get_... |
amol-/tgext.matplotrender | setup.py | Python | mit | 1,201 | 0.003331 | from setuptools import setup, find_packages
import sys, os
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst')).read()
except IOError:
README = ''
version = "0.0.1"
TEST_REQUIREMENTS = [
'numpy',
'pillow',
'webtest'
]
setup(
name='tgext.matpl... | action=list_classifiers
keywords='turbogears2.extension',
author='Alessandro Molina',
author_email='amol@turbogears.org',
url='https://github.com/amol-/tgext.matplotrender',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
namespace_packages = ['tgext'],
... | >= 2.3.8",
'matplotlib'
],
extras_require={
# Used by Travis and Coverage due to setup.py nosetests
# causing a coredump when used with coverage
'testing': TEST_REQUIREMENTS,
},
entry_points="""
# -*- Entry points: -*-
"""
)
|
cloudify-cosmo/cloudify-manager-blueprints | components/python/scripts/bootstrap_validate.py | Python | apache-2.0 | 1,334 | 0 | #!/usr/bin/env python
from os.path import join, dirname
from cloudify import ctx
ctx.download_resource(
join('components', 'utils.py'),
join(dirname(__file__), 'utils.py'))
import utils # NOQA
# Most images already ship with the following packages:
#
# python-setuptools
# python-backports
# python-b... | nclude these libraries in the
# manager resources package. Until then, we only validate that they're
# preinstalled, and if not - instruct the user to install them.
missing_packages = set()
for pkg in ['python-setuptools',
'python-backports',
'python-backports-ssl_match_hostname']:
ctx.log... | d:
missing_packages.add(pkg)
if missing_packages:
ctx.abort_operation('Prerequisite packages missing: {0}. '
'Please ensure these packages are installed and '
'try again'.format(', '.join(missing_packages)))
|
kirillzhuravlev/atrex | Software/gaussfitter.py | Python | lgpl-3.0 | 23,723 | 0.024702 | """
===========
gaussfitter
===========
.. codeauthor:: Adam Ginsburg <adam.g.ginsburg@gmail.com> 3/17/08
Latest version available at <http://code.google.com/p/agpy/source/browse/trunk/agpy/gaussfitter.py>
"""
import numpy
from numpy.ma import median
from numpy import pi
#from scipy import optimize,stats,pi
from mpfi... | o...
# also, circles don't rotate.
else:
mylist = mylist + [width]
return mylist
def twodgaussian(inpars, circle=False, rotate=True, vheight=True, shape=None):
"""Returns a 2d gaussian function of the form:
x' = numpy.cos(rota) * x - numpy. | sin(rota) * y
y' = numpy.sin(rota) * x + numpy.cos(rota) * y
(rota should be in degrees)
g = b + a * numpy.exp ( - ( ((x-center_x)/width_x)**2 +
((y-center_y)/width_y)**2 ) / 2 )
inpars = [b,a,center_x,center_y,width_x,width_y,rota]
(b is background height, a is... |
EduPepperPDTesting/pepper2013-testing | lms/djangoapps/reportlab/graphics/widgets/grids.py | Python | agpl-3.0 | 18,133 | 0.013511 | #Copyright ReportLab Europe Ltd. 2000-2016
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/graphics/widgets/grids.py
__version__='3.3.0'
from reportlab.lib import colors
from reportlab.lib.validators import isNumber, isColorOrNone, isB... | ositions where to place lines."
w, h = self.width, self.height
if isX:
length = w
else:
length = h
if self.deltaSteps:
r = [start + self.delta0]
i = 0
while 1:
if r[-1] > start + length:
... |
r = frange(start + self.delta0, start + length, self.delta)
r.append(start + length)
if self.delta0 != 0:
r.insert(0, start)
#print 'Grid.makeLinePosList() -> %s' % r
return r
def makeInnerLines(self):
# inner grid lines
group = ... |
LTD-Beget/sprutio-rpc | lib/FileManager/workers/ftp/createCopy.py | Python | gpl-3.0 | 6,690 | 0.003101 | import os
import time
import traceback
from lib.FileManager.FM import REQUEST_DELAY
from lib.FileManager.workers.baseWorkerCustomer import BaseWorkerCustomer
class CreateCopy(BaseWorkerCustomer):
def __init__(self, paths, session, *args, **kwargs):
super(CreateCopy, self).__init__(*args, **kwargs)
... | = {
'percent': round(float(len(success_paths)) / float(len(copy_paths)), 2),
'text': str(
int(round(float(len(success_paths)) / float(len(copy_paths)), 2) * 100)) + '%'
}
self.on_run... | t_tick = time.time() + REQUEST_DELAY
except Exception as e:
self.logger.error("Error copy file %s , error %s" % (str(source_path), str(e)))
error_paths.append(source_path)
result = {
"success": success_paths,
"errors":... |
charettes/django-mutant | mutant/contrib/boolean/models.py | Python | mit | 610 | 0 | from __future__ import unicode_literals
from django.db.models import fields
from django.uti | ls.translation import ugettext_lazy as _
from ...models.field import FieldDefinition
class _BooleanMeta:
defined_field_category = _('Boolean')
class BooleanFieldDefinition(FieldDefinition):
class Me | ta(_BooleanMeta):
app_label = 'boolean'
proxy = True
defined_field_class = fields.BooleanField
class NullBooleanFieldDefinition(FieldDefinition):
class Meta(_BooleanMeta):
app_label = 'boolean'
proxy = True
defined_field_class = fields.NullBooleanField
|
hzlf/openbroadcast | website/apps/ashop/migrations/0015_auto__add_field_hardwarerelease_medium.py | Python | gpl-3.0 | 23,666 | 0.007817 | # encoding: 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 'Hardwarerelease.medium'
db.add_column('ashop_hardwarerelease', 'medium', self.gf('django.d... | _name': 'Release'},
'catalognumber': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'created': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}),
| 'excerpt': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'extra_artists': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['alibrary.Profession']", 'null': 'True', 'through': "orm['alibrary.ReleaseExtraartists']", 'blank': 'True'})... |
SunDwarf/Jokusoramame | jokusoramame/plugins/misc.py | Python | gpl-3.0 | 5,938 | 0.000168 | import random
import re
from io import BytesIO
from typing import Awaitable, List
import matplotlib.pyplot as plt
import seaborn as sns
from curio.thread import async_thread
from curious.commands import Context, Plugin
from curious.commands.decorators import autoplugin, ratelimit
from yapf.yapflib.style import CreateP... | 3,
"": 30
}
PREFIXES = {
"Alt-": 1,
"Bio-": 1,
"Taoist ": 2,
"Left ": 3,
"Post-": 3,
"Anarcha-": 3,
"Avant Garde ": 3,
"Eco-": 4,
"Communal ": 6,
"Afro-": 8,
"Ethno-": 8,
"Ultra-": 8,
"Neo-": 10,
"Pan-": 10,
"Anti-": 10,
"Paleo-": 10,
"Techno-": 1... | ": 10,
"Crypto-": 12,
"Anarcho-": 12,
"National ": 12,
"Orthodox ": 12,
"": 40
}
IDEOLOGIES = {
"Posadism": 1,
"Sexualism": 1,
"Kemalism": 2,
"Unruheism": 2,
"Distributism": 2,
"Titoism": 3,
"Putinism": 3,
"Makhnovism": 3,
"Georgism": 4,
"Keynesian": 4,
"... |
brandonPurvis/osf.io | tests/test_notifications.py | Python | apache-2.0 | 59,970 | 0.003035 | import collections
import datetime
import mock
import pytz
from babel import dates, Locale
from schema import Schema, And, Use, Or
from modularodm import Q
from modularodm.exceptions import NoResultsFound
from nose.tools import * # noqa PEP8 asserts
from framework.auth import Auth
from framework.auth.core import Use... | auth)
s.reload()
# assert that user is removed from the subscription entirely
for n in constants.NOTIFICATION_TYPES:
assert_false(self.node.creator in getattr(s, n))
class TestRemoveContributor(OsfTestCase):
def setUp(self):
super(OsfTestCase, self).setUp()
sel... | factories.UserFactory()
self.project.add_contributor(contributor=self.contributor, permissions=['read'])
self.project.save()
self.subscription = factories.NotificationSubscriptionFactory(
_id=self.project._id + '_comments',
owner=self.project
)
self.subs... |
ferriman/SSandSP | pyxel-test/venv/lib/python3.8/site-packages/pyxel/editor/octave_bar.py | Python | gpl-3.0 | 1,129 | 0.000886 | import pyxel
from pyxel.ui import Widget
from .constants import OCTAVE_BAR_BACKGROUND_COLOR, OCTAVE_BAR_COLOR
class OctaveBar(Widget):
def __init__(self, parent, x, y):
super().__init__(parent, x, y, 4, 123)
self.add_event_handler("mouse_down", self.__on_mouse_down)
self.add_event_handle... | "
def __on_draw(self):
pyxel.rect(self | .x, self.y, self.width, self.height, OCTAVE_BAR_BACKGROUND_COLOR)
x = self.x + 1
y = self.y + 1 + (3 - self.parent.octave) * 24
pyxel.rect(x, y, 2, 47, OCTAVE_BAR_COLOR)
|
bezhermoso/powerline | tests/test_segments.py | Python | mit | 79,449 | 0.022501 | # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import sys
import os
from functools import partial
from collections import namedtuple
from time import sleep
from platform import python_implementation
from powerline.segments import shell, tmux, pdb, i... | tents': 'sigsegv+core', 'hig | hlight_groups': ['exit_fail'], 'draw_inner_divider': True},
{'contents': '0', 'highlight_groups': ['exit_success'], 'draw_inner_divider': True}
])
def test_jobnum(self):
pl = Pl()
segment_info = {'args': Args(jobnum=0)}
self.assertEqual(shell.jobnum(pl=pl, segment_info=segment_info), None)
self.assertEqu... |
gwpy/gwpy | gwpy/timeseries/io/wav.py | Python | gpl-3.0 | 3,595 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) Duncan Macleod (2017-2020)
#
# This file is part of GWpy.
#
# GWpy 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)... | le`, `str`
the file object or filename to write to
scale : `float`, optional
the factor to apply to scale the data to (-1.0, 1.0),
pass `scale=1` to not apply any scale, otherwise
the data will be auto-scaled
See also
--------
scipy.io.wavfile.write
for details ... | = TimeSeries([1, 2, 3, 4, 5])
>>> t = TimeSeries.write('test.wav')
"""
fsamp = int(series.sample_rate.decompose().value)
if scale is None:
scale = 1 / numpy.abs(series.value).max()
data = (series.value * scale).astype('float32')
return wavfile.write(output, fsamp, data)
def is_wav(orig... |
Ichimonji10/robottelo | tests/foreman/cli/test_filter.py | Python | gpl-3.0 | 6,479 | 0 | # -*- encoding: utf-8 -*-
"""Test for Roles CLI
@Requirement: Filter
@CaseAutomation: Automated
@CaseLevel: Acceptance
@CaseComponent: CLI
@TestType: Functional
@CaseImportance: High
@Upstream: No
"""
from robottelo.cli.base import CLIReturnCodeError
from robottelo.cli.factory import (
make_filter,
make... | 'id': filter_['id'],
'permissions': new_perms
})
filter_ = Filter.info({'id': filter_['id']})
self.assertEqual(
set(filter_['permissions'].split(", ")),
set(new_perms)
| )
@tier1
def test_positive_update_role(self):
"""Create a filter and assign it to another role.
@id: 2950b3a1-2bce-447f-9df2-869b1d10eaf5
@Assert: Filter is created and assigned to new role.
"""
filter_ = make_filter({
'role-id': self.role['id'],
... |
nifannn/HackerRank | Practice/Python/Strings/string_validators.py | Python | mit | 281 | 0.007117 | if __name__ == '__main__':
s = input()
is_list = list(zip(*[[c.isalnum(), c.is | alpha(), c.isdigit(), c.islower(), c.isupper()] for c in s]))
print_list = [True if True in is_result else False for is_result in is_list]
for result in print_list:
| print(result)
|
crosswalk-project/crosswalk-test-suite | embeddingapi/embedding-api-android-tests/inst.apk.py | Python | bsd-3-clause | 3,916 | 0.001277 | #!/usr/bin/env python
import os
import shutil
import glob
import time
import sys
import subprocess
from optparse import OptionParser, make_option
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PARAMETERS = None
ADB_CMD = "adb"
def doCMD(cmd):
# Do not need handle timeout in this short script, let tool... | except Exception as e:
print "Got wrong option: %s, exit ..." % e
sys.exit(1)
if not PARAMETERS.device:
(return_code, output) = doCMD("adb devices")
for line in output:
if str.find(line, "\tdevice") != -1:
PARAMETERS.device = line.split("\t")[0]
... | device:
print "No device found"
sys.exit(1)
if PARAMETERS.binstpkg and PARAMETERS.buninstpkg:
print "-i and -u are conflict"
sys.exit(1)
if PARAMETERS.buninstpkg:
if not uninstPKGs():
sys.exit(1)
else:
if not instPKGs():
sys.exit(1)
... |
baverman/fmd | fmd/run.py | Python | mit | 262 | 0.007634 | def run():
import sys, os
try:
| uri = sys.argv[1]
except IndexError:
uri = os.getcwd()
import gtk
from .app import App
from uxie.utils import idle
application = App()
idle(application.open, uri)
| gtk.main()
|
Diti24/python-ivi | ivi/agilent/agilentE4431B.py | Python | mit | 1,495 | 0.001338 | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2014-2016 Alex Forencich
Permission is hereby grante | d, 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, publish, distribute, sublicense, and/or s | ell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KI... |
gitaarik/jazzchords | apps/users/admin.py | Python | gpl-3.0 | 213 | 0 | from django.contrib import admi | n
from .models import User
class UserAdmin(admin.ModelAdmin):
list_display = ('username', 'email', 'is_active', 'is_staff', 'validated')
admin.site.register(User, UserAdmin)
| |
hiway/micropython | tests/basics/list_slice_assign.py | Python | mit | 622 | 0.017685 | # test slices; on | ly 2 argument version supported by Micro Python at the moment
x = list(range(10))
# Assignment
l = list(x)
l[1:3] = [10, 20]
print(l)
l = list(x)
l[1:3] = [10]
print(l)
l = list(x)
l[1:3] = []
print(l)
l = list(x)
del l[1:3]
print(l)
l = list(x)
l[:3] = [10, 20]
print(l)
l = list(x)
l[:3] = []
print(l)
l = list(x)
de... | ssign a tuple
l = [1, 2, 3]
l[0:1] = (10, 11, 12)
print(l)
# RHS of slice must be an iterable
try:
[][0:1] = 123
except TypeError:
print('TypeError')
|
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.2/Lib/test/test_concurrent_futures.py | Python | mit | 20,163 | 0.000893 | import test.support
# Skip tests if _multiprocessing wasn't built.
test.support.import_module('_multiprocessing')
# Skip tests if sem_open implementation is broken.
test.support.import_module('multiprocessing.synchronize')
# import threading after _multiprocessing to raise a more revelant error
# message: "No module n... | ror,
self.executor.submit,
pow, 2, 5)
class ThreadPoolShutdownTest(ThreadPoolMixin, ExecutorShutdownTest):
def _prime_executor(self):
pass
def test_threads_terminate(self):
self.executor.submit(mul, 21, 2)
self.executor.submit(mul, 6... | n()
for t in self.executor._threads:
t.join()
def test_context_manager_shutdown(self):
with futures.ThreadPoolExecutor(max_workers=5) as e:
executor = e
self.assertEqual(list(e.map(abs, range(-5, 5))),
[5, 4, 3, 2, 1, 0, 1, 2, 3, 4])
... |
the-zebulan/CodeWars | katas/kyu_4/ip_validation.py | Python | mit | 276 | 0 | from re import compile, match
REGEX = compile(r'((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}'
r'(25[0-5]|2[0-4]\d|1\d\d|[ | 1-9]\d|\d)$')
def is_valid_IP(strng):
""" is_valid_ip == PEP8 (forced mixedCase by CodeWars | ) """
return bool(match(REGEX, strng))
|
seblabbe/slabbe | slabbe/graph_directed_IFS.py | Python | gpl-2.0 | 26,146 | 0.004171 | # -*- coding: utf-8 -*-
r"""
Graph-directed iterated function system (GIFS)
See [JK14]_ or [BV20]_ or
- http://larryriddle.agnesscott.org/ifs/ifs.htm
- https://encyclopediaofmath.org/wiki/Iterated_function_system
We allow the functions to be contracting or not. When the functions are
inflations, it allows to represe... | e ({},{}):".format(a,b))
print(f)
@classmethod
def from_one_dimensional_substitution(cls, m):
r"""
Return the GIFS defined by a unidimensional primitive
substitution
INPUT:
- ``m`` -- WordMorphism, primitive substitution
EXAMPLES::
sag... | irectedIteratedFunctionSystem as GIFS
sage: m = WordMorphism('a->ab,b->a')
sage: g = GIFS.from_one_dimensional_substitution(m)
sage: g
GIFS defined by 3 maps on
Vector space of dimension 1 over
Number Field in root with defining polynomial x^2 - x ... |
Stanford-Online/edx-analytics-data-api-client | analyticsclient/tests/test_course_summaries.py | Python | apache-2.0 | 1,471 | 0.00136 | import ddt
from analyticsclient.tests import (
APIListTestCase,
APIWithPostableIDsTestCase,
ClientTestCase
)
@ddt.ddt
class CourseSummariesTests(APIListTestCase, APIWithPostableIDsTestCase, ClientTestCase):
endpoint = 'course_summaries'
id_field = 'course_ids'
_LIST_PARAMS = frozenset([
... | order',
])
_INT_PARAMS = frozenset([
'page',
'page_size',
])
_ALL_PARAMS = _LIST_PARAMS | _STRING_PARAMS | _INT_PARAMS
other_params = _ALL_PARAMS
# Test URL encoding (note: '+' is not handled right by httpretty, but it works in practice)
_TEST_STRING = 'Aa1_-:/* '
@ddt.... | S, ''),
(_INT_PARAMS, 1),
(_INT_PARAMS, 0),
(frozenset(), None),
)
@ddt.unpack
def test_all_parameters(self, param_names, param_value):
"""Course summaries can be called with all parameters."""
params = {param_name: None for param_name in self._ALL_PARAMS}
par... |
protwis/protwis | contactnetwork/management/commands/build_distance_representative.py | Python | apache-2.0 | 2,958 | 0.006423 | from django.core.management.base import BaseCommand, CommandError
from django.core.management import call_command
from django.conf import settings
from django.db import connection
from django.db.models import Q, F
from contactnetwork.distances import *
from protein.models import ProteinFamily
import time
import scipy
... | def handle(self, *args, **options):
self.receptor_representatives()
def receptor_representatives(self):
print('Script to decide dis | tance representative for a state/receptor combination. Lowest average distance to all other structures for the same receptor/state')
structures = Structure.objects.all().prefetch_related(
"pdb_code",
"state",
"protein_conformation__protein__parent__family")
distinct... |
mag6367/Cracking_the_Coding_Interview_Python_Solutions | chapter3/stack.py | Python | mit | 418 | 0.057416 | # Stack implementation
class S | tack (object):
def __init__ (self):
self.stack = []
def push (self, data):
se | lf.stack.append(data)
def peek (self):
if self.isEmpty():
return None
return self.stack[-1]
def pop (self):
if self.isEmpty():
return None
return self.stack.pop()
def isEmpty (self):
return len(self.stack) == 0
def __str__ (self):
return ' '.join(str(x) for x in self.stack)
|
shawnhermans/cyborgcrm | cyactivities/apps.py | Python | bsd-2-clause | 192 | 0.010417 | from django.apps import AppConfig
class ActivityConfig(AppConfig):
name = 'cyactivities'
verbose_name = 'Cyborg Activities'
def ready(self):
| import cyacti | vities.signals
|
richardcornish/django-paywall | regwall/tests/articles/migrations/0001_initial.py | Python | bsd-3-clause | 1,053 | 0.003799 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-14 17:20
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateMode... | _length=255, verbose_name='Headline')),
| ('slug', models.SlugField(max_length=255, unique=True, verbose_name='Slug')),
('body', models.TextField(verbose_name='Body')),
('pub_date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='Pub date')),
],
options={
... |
NeuroDataDesign/seelviz | seelviz/brainalign.py | Python | apache-2.0 | 3,476 | 0.006617 | import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from ndreg import *
import ndio.remote.neurodata as neurodata
import nibabel as nb
refToken = "ara_ccf2"
refImg = imgDownload(refToken)
imgShow(refImg)
plt.savefig("refImg_initial.png", bbox_inches='tight')
imgShow(refImg, vmax=500)
plt.savefig("... | ons=100, useMI=True, verbose=True)
inImg_affine = imgApplyAffine(inImg, affine, size=refImg.GetSize())
imgShow(inImg_affine, vmax=500)
plt.savefig("inImg_affine.png", bbox_inches='tight')
inImg_ds = img | Resample(inImg_affine, spacing=spacing)
(field, invField) = imgMetamorphosisComposite(inImg_ds, refImg_ds, alphaList=[0.05, 0.02, 0.01], useMI=True, iterations=100, verbose=True)
inImg_lddmm = imgApplyField(inImg_affine, field, size=refImg.GetSize())
imgShow(inImg_lddmm, vmax = 500)
imgShow(inImg_lddmm, vmax=500, newF... |
lektor/lektor | tests/test_i18n.py | Python | bsd-3-clause | 252 | 0 | import impor | tlib
import lektor.i18n
def test_loading_i18n_triggers_no_warnings(recwarn):
importlib.reload(lektor.i18n)
for warning in recwarn.list:
print(warning) # debugging: display warnings on stdou | t
assert len(recwarn) == 0
|
RockinRobin/seednetwork | seedlibrary/forms.py | Python | mit | 6,875 | 0.0224 | from django import forms
from seednetwork.forms import SeedNetworkBaseForm
from seedlibrary.models import Event
GRAIN_CHOICES = (
('-','-'),
('amaranth','Amaranth'),
('barley', 'Barley'),
('buckwheat', 'Buckwheat'),
('corn', 'Corn'),
# ('kaniwa', 'Kaniwa'),
('mil... | ('triticale', 'Triticale'),
('wheat', 'Wheat'),
)
GRAIN_SUBCATEGORIES = (
('-','-'),
('grain', 'Amaranth: Grain'),
('leaf', 'Amaranth: Leaf'),
('grain and leaf', 'Amaranth: Grain and Leaf'),
('common', 'Barley: Common'),
('hulless','Barley: Hulless'),
('common', 'Buckwhea... | y', 'Buckwheat: Tartary'),
('dent', 'Corn: Dent'),
('flint', 'Corn: Flint'),
('flour', 'Corn: Flour'),
('popcorn', 'Corn: Popcorn'),
('sweet', 'Corn: Sweet'),
('finger', 'Millet: Finger'),
('foxtail', 'Millet: Foxtail'),
('pearl', 'Millet: Pearl'),
('proso', 'Millet: Proso'),
... |
AloneRoad/waskr | waskr/database.py | Python | mit | 2,723 | 0.011017 | import os
import sqlite3
from time import time, strftime, gmtime
from waskr.config import options
import log
# Fixes Database Absolute Location
FILE_CWD = os.path.abspath(__file__)
FILE_DIR = os.path.dirname(FILE_CWD)
DB_FILE = FILE_DIR+'/waskr.db'
# Engines Supported
engines_supported = ['sqlite', 'mongodb']
cla... | fromlist=['None'])
else:
engine = __import__('waskr.engines.sqlite',
fromlist=['None']) # fall backs to sqlite3
return engine
def _check_module(self, module):
if module not in engines_supported:
re... |
return True
def insert(self, stats):
self.stats.insert(stats)
def last_insert(self):
return self.stats.last_insert()
def apps_nodes(self):
return self.stats.apps_nodes()
def response_time(self, minutes):
return self.stats.response_time(minut... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.