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
dmchu/selenium_gr_5
tests/day_6/hw_day_6_task_12.py
Python
apache-2.0
3,837
0.002085
import os from faker import Faker import pytest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.select import Select from selenium.webdriver.support.wait import WebDr
iverWait from selenium.webdriver.support import expected_conditions as EC from wheel.signatures import assertTrue @pytest.fixture def driver(request): wd = webdriver.Chrome() wd.implicitly_wait(2) request.addfinalizer(wd.quit) return wd def test_add_new_product(driver): wait = WebDriverWait(driv...
nt_by_name("password").send_keys("admin") driver.find_element_by_name("login").click() wait.until(EC.title_is("My Store")) menu = driver.find_element_by_id("box-apps-menu") menu.find_element(By.LINK_TEXT, "Catalog").click() add_new_product = driver.find_element(By.LINK_TEXT, "Add New Product") ...
xyuanmu/XX-Net
python3.8.2/Lib/curses/__init__.py
Python
bsd-2-clause
3,800
0.002105
"""curses The main package for curses support for Python. Normally used by importing the package, and perhaps a particular module inside it. import curses from curses import textpad curses.initscr() ... """ from _curses import * import os as _os import sys as _sys # Some constants, most notably the AC...
tscr(): import _curses, curses # we call setupterm() here because it raises an error # instead of calling exit() in error cases. setupterm(term=_os.environ.get("TERM", "unknown"), fd=_sys.__stdout__.fileno()) stdscr = _curses.init
scr() for key, value in _curses.__dict__.items(): if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'): setattr(curses, key, value) return stdscr # This is a similar wrapper for start_color(), which adds the COLORS and # COLOR_PAIRS variables which are only available after start_color() is # ...
plotly/plotly.py
packages/python/plotly/plotly/validators/histogram2dcontour/line/_width.py
Python
mit
469
0.002132
import _plotly_utils.basevalidators class WidthValidator(_plotly_utils.bas
evalidators.NumberValidator): def __init__( self, plotly_name="width", parent_name="histogram2dcontour.line", **kwargs ): super(WidthValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "style+colorbars...
min=kwargs.pop("min", 0), **kwargs )
cheekujodhpur/ae320
a1/eps.py
Python
mit
112
0.008929
#!/usr/bin/env
python #To find epsilon of machine eps = 1.0 while 1.0+eps > 1.0: eps =
eps/2.0 print eps
VVS1864/SAMoCAD
src/grab_object.py
Python
apache-2.0
2,345
0.029299
# -*- coding: utf-8; -*- def lapping2(par, select): #Выделение/снятие выделения рамкой if par.lappingFlag == True:#Если кончание выделения par.c.delete(par.rect)#Удалить прямоугольник выделения par.rect = None par.ex = par.rectx par.ey = par.recty par.ex2 = par.rectx2 ...
y2=par.ey c = par.c.find_overlapping(x1,y1,x2,y2) par.mass_collektor(c, select) else: x1=par.ex2 x2=par.ex if par.ey<par.ey2: y1=par.ey y2=par.ey2 else: y1=par.ey2 ...
у par.mass_collektor(c, select)#Добавить полученное в коллекцию par.colObj()#Пересчитать количество объектов par.lappingFlag = False par.c.unbind_class(par.c, "<Motion>")#Вернуть события в исходное состояние #par.c.tag_bind('sel', "<Button-1>", par.collektor_sel) #p...
elyezer/robottelo
tests/foreman/api/test_host.py
Python
gpl-3.0
51,434
0
# -*- encoding: utf-8 -*- """Unit tests for the ``hosts`` paths. An API reference can be found here: http://theforeman.org/api/apidoc/v2/hosts.html :Requirement: Host :CaseAutomation: Automated :CaseLevel: Acceptance :CaseComponent: API :TestType: Functional :CaseImportance: High :Upstream: No """ from fauxfac...
host = host.update(['owner_type']) self.assertEqual(host.owner_type, owner_type) @run_only_on('sat') @tier1 def test_positive_create_with_name(self): """Create a host with different names and
minimal input parameters :id: a7c0e8ec-3816-4092-88b1-0324cb271752 :expectedresults: A host is created with expected name :CaseImportance: Critical """ for name in valid_hosts_list(): with self.subTest(name): host = entities.Host(name=name).create()...
kartoza/geonode
geonode/tasks/tests.py
Python
gpl-3.0
1,025
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 ...
f.a
dm_pw = "admin"
mike-tr-adamson/python-driver
tests/integration/standard/test_udts.py
Python
apache-2.0
25,583
0.002306
# Copyright 2013-2015 DataStax, 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 writi...
l('bob', row.b.name) self.assertTrue(type(row.b) is User1) # use the same UDT name in a different keyspace s.set_keyspace("udt_test_register_before_connecting2") s.execute("INSERT INTO mytable (a, b) VALUES (%s, %s)", (0, User2('Texas', True))) result = s.execute("SELECT b FROM ...
self.assertEqual(1, len(result)) row = result[0] self.assertEqual('Texas', row.b.state) self.assertEqual(True, row.b.is_cool) self.assertTrue(type(row.b) is User2) c.shutdown() def test_can_insert_prepared_unregistered_udts(self): """ Test the insertion ...
reuvenderay/PythonProjects
enterInfo.py
Python
mit
1,339
0.003734
__author__ = 'Reuven' import sys class GetInfo(): def __init__(self): self.u_name = "" self.age = "" self.uid = "" def get_name(self): while self.u_name.isalpha() is F
alse: self.u_name = raw_input("Please enter your name:")[:20] if self.u_name == "exit" or self.u_name == "quit": sys.exit() return self.u_name def get_age(self): while self.age.isdigit() is False or int(self.age) not in range(1, 120): self.age = r...
sys.exit() return self.age def get_user_id(self): while len(self.uid) != 6 or self.uid.isdigit() is False or int(self.uid) not in range(1, 1000000): self.uid = raw_input("Please enter your User ID:") if self.uid == "exit" or self.uid == "quit": sys.exi...
XiMuYouZi/PythonDemo
Web/zhihu/error/__init__.py
Python
mit
88
0.011364
from flask import Blueprint error = Blueprint('error', __name__, ) from . import vie
w
us-ignite/us_ignite
us_ignite/snippets/tests/models_tests.py
Python
bsd-3-clause
1,160
0.000862
from nose.tools import eq_, ok_ from django.test import TestCase from us_ignite.snippets.models import Snippet from us_ignite.snippets.tests import fixtures class TestSnippetModel(TestCase): def tearDown(self): Snippet.objects.all().delete() def get_instance(self): data = { 'nam...
ippet.DRAFT) eq_(instance.url, 'http://us-ignite.org/') eq_(instance.url_text, '') eq_(instance.body, '') eq_(instance.image, '') eq_(instance.is_featured, False) ok_(instance.created) ok_(instance.modified) eq_(instance.slug, 'featured') ok_(insta...
instance = fixtures.get_snippet(name='About page') eq_(instance.title, 'About page')
ardi69/pyload-0.4.10
pyload/plugin/crypter/LinkSaveIn.py
Python
gpl-3.0
707
0.015559
# -*- coding: utf-8 -*- from pyload.plugin.internal.SimpleDereferer import SimpleDereferer class LinkSaveIn(SimpleDereferer): __name = "LinkSaveIn" __type = "crypt
er" __version = "2.03" __pattern = r'https?://(?:www\.)?linksave\.in/\w+' __config = [("use_subfolder" , "bool", "Save package to subfolder" , True), ("subfolder_per_pack", "bool", "Create a subfolder for each package", True)] __description = """LinkSave.in decrypter p...
FLINE_PATTERN = r'>(Error )?404 -'
gustavofonseca/oai-pmh
oaipmh/entities.py
Python
bsd-2-clause
1,659
0.001211
from collections import namedtuple RepositoryMeta = namedtuple('RepositoryMeta', '''repositoryName baseURL protocolVersion adminEmail earliestDatestamp deletedRecord granularity''') OAIRequest = namedtuple('OAIRequest', '''verb identifier metadataPrefix set resumptionToken from_ until''') ...
core.org/documents/1999/07/02/dces/ sample = { 'ridentifier': <str>, 'datestamp': <datetime>, 'setspec': <List[str]>, 'title': <List[Tuple[str, s
tr]]>, 'creator': <List[str]>, 'subject': <List[Tuple[str, str]]>, 'description': <List[Tuple[str, str]]>, 'publisher': <List[str]>, 'contributor': <List[str]>, 'date': <List[datetime]>, 'type': <List[str]>, 'format': <List[str]>, 'identifier': <List[str]>, 'source': <List[str]>,...
diofant/diofant
diofant/tests/integrals/test_quadrature.py
Python
bsd-3-clause
20,443
0.000587
from diofant import Rational from diofant.integrals.quadrature import (gauss_chebyshev_t, gauss_chebyshev_u, gauss_gen_laguerre, gauss_hermite, gauss_jacobi, gauss_laguerre, gauss_legendre) __...
w] == [ '0.29540897515091934', '1.1816359006036774', '0.29540897515091934'] x, w = gauss_hermite(4, 17) assert [str(r) for r in x] == [ '-1.6506801238857846', '-0.52464762327529032', '0.52464762327529032', '1.6
506801238857846' ] assert [str(r) for r in w] == [ '0.081312835447245177', '0.80491409000551284', '0.80491409000551284', '0.081312835447245177' ] x, w = gauss_hermite(5, 17) assert [str(r) for r in x] == [ '-2.0201828704560856', '-0.95857246461381851'...
alzeih/ava
ava_core/organize/signals.py
Python
gpl-3.0
1,780
0.005056
# Django Imports from django.db.models.signals import post_save from django.dispatch import receiver # Python Imports from logging import getLogger # Local Imports from .models import Person, PersonAttribute, PersonIdentifier, PersonIdentifierAttribute, GroupIdentifier, \ GroupIdentifierAttribute # Logging logger ...
ze_person_post_save') if created: logger.debug('Signal Fired' ' - organize::signal_ava_organize_person_post_save') attribute = PersonAttribute.objects.create(person=instance) attribute.save() @receiver(post_save, sender=PersonIdentifier) def
signal_ava_organize_person_identifier_post_save(sender,created, instance, **kwargs): logger.debug('Signal Called' '- organize::signal_ava_organize_person_identifier_post_save') if created: logger.debug('Signal Fired' ' - organize::signal_ava_organize_person_identifi...
1065865483/0python_script
four/Webdriver/Mouse_action.py
Python
mit
603
0.008696
from selenium import webdriver from time import sleep from selenium.webdriver.common.action_chains import ActionChains driver = webdriver.Firefox() driver.get("https://www.baidu.com/") driver.maximize_window() driver.find_element_by_id("kw").send_keys("python") element=driver.find_element_by_id("kw") #双击操作 ActionChain...
ver).double_click(element).perform() sleep(2) #右击鼠标操作 ActionChains(driver).context_click(element).perform() sleep(2) #鼠标悬停 above=driver.find_element_by_css_selector(".pf") ActionChains(driver).move_to_element(a
bove).perform() sleep(2) driver.quit()
torchhound/projects
codeGolf/find1.py
Python
gpl-3.0
368
0.065217
#written for
http://codegolf.stackexchange.com/questions/79207/minimize-those-ones def find1(num): z = 10 y = 11 while True: if num%z==0: if num/2 <= y/2: print(num) break else: print(num/y+num%y) break z += 10 def main(): cases = [0,7,121,72,1000,2016] for th in range(0,5): find1(cases[th - 1]) ...
main()
davidszotten/pytest-django
tests/test_django_configurations.py
Python
bsd-3-clause
3,011
0
"""Tests which check the various ways you can set DJANGO_SETTINGS_MODULE I
f these tests fail you probably forgot to install django-configurations. """ import pytest pytest.importorskip('configurations') try: import configurations.importer configurations except ImportError as e: if 'LaxOptionParser' in e.args[0]: pytest.skip('This version of django-configurations is inco...
h Django: ' # noqa 'https://github.com/jezdez/django-configurations/issues/65') # noqa BARE_SETTINGS = ''' from configurations import Settings class MySettings(Settings): # At least one database must be configured DATABASES = { 'default': { 'ENGINE': 'django.db.backen...
vikraman/gentoostats
server/kwd.py
Python
gpl-3.0
1,062
0.017891
import helpers from config import render, db class Keyword(object): def GET(self): keyword_count = db.query('SELECT KEYWORD,\ COUNT(DISTINCT IPKEY) AS PACKAGES,\ COUNT(DISTINCT UUID) AS HOSTS\ FROM GLOBAL_KEYWORDS NATURAL JOIN KEYWORDS\ NATUR...
# generate plot x_ticklabels = keyword_data.keys() y_values = [ keyword_data[k]['PACKAGES'] for k in x_ticklabels ] keyword_plot = helpers.barchart(title = 'Installed packages per keywo
rd', x_label = 'Keyword', y_label = 'Number of Packages', x_ticklabels = x_ticklabels, y_values = y_values) return render.keyword(keyword_data, keyword_plot)
guildai/guild
examples/separating-inputs-and-outputs/downstream.py
Python
apache-2.0
185
0
import os # Ensure directory for model. if not os.path.exists("models"): os.mkdir("mode
ls") # Write model. with open("models/checkpoint.txt", "w") as
f: f.write("downstream")
onkelpit/i3pystatus
i3pystatus/moon.py
Python
mit
2,598
0.000385
from i3pystatus import IntervalModule, formatp import datetime import math import decimal import os from i3pystatus.core.util import TimeWrapper dec = decimal.Decimal class MoonPhase(IntervalModule): """ Available Formatters status: Allows for mapping of current moon phase - New Moon: - Waxin...
mat", ("status", "Current moon phase"), ("illum", "Percentage
that is illuminated"), ("color", "Set color"), ) format = "{illum} {status}" interval = 60 * 60 * 2 # every 2 hours status = { "New Moon": "NM", "Waxing Crescent": "WaxCres", "First Quarter": "FQ", "Waxing Gibbous": "WaxGib", "Full Moon": "FM", ...
ifuding/Kaggle
SVPC/Code/philly/leak_cols.py
Python
apache-2.0
43,679
0.007509
LEAK_LIST = [ ['f190486d6', '58e2e02e6', 'eeb9cd3aa', '9fd594eec', '6eef030c1','15ace8c9f', 'fb0f5dbfe', '58e056e12', '20aa07010', '024c577b9','d6bb78916', 'b43a7cfd5', '58232a6fb', '1702b5bf0', '324921c7b', '62e59a501', '2ec5b290f', '241f0f867', 'fb49e4212', '66ace2992','f74e8f13d', '5c6487af1', '963a49cdc', '26fc93...
', '42cf36d73', '9f494676e', '1c68ee044', 'a728310c8', '612bf9b47', '105233ed9', 'c18cc7d3d', 'f08c20722'] ,['266525925', '4b6dfc880', '2cff4bf0c', 'a3382e205', '6488c8200', '547d3135b', 'b46191036', '453128993', '2
599a7eb7', '2fc60d4d9', '009319104', 'de14e7687', 'aa31dd768', '2b54cddfd', 'a67d02050', '37aab1168', '939cc02f5', '31f72667c', '6f951302c', '54723be01', '4681de4fd', '8bd53906a', '435f27009', 'f82167572', 'd428161d9', '9015ac21d', 'ec4dc7883', '22c7b00ef', 'd4cc42c3d', '1351bf96e', '1e8801477', 'b7d59d3b5', 'a459b5f7d...
canvasnetworks/canvas
website/canvas/migrations/0104_auto__add_field_userwarning_comment.py
Python
bsd-3-clause
16,380
0.007143
# 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 'UserWarning.comment' db.add_column('canvas_userwarning', 'comment', self.gf('django.db.mod...
ntent']"}), 'reply_text': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'blank': 'True'}), 'score': ('django.db.models.fields.FloatField', [], {'default': '0', 'db_index': 'True'}), 'timestamp': ('can
vas.util.UnixTimestampField', [], {'default': '0'}), 'visibility': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'canvas.commentflag': { 'Meta': {'object_name': 'CommentFlag'}, 'comment': ('django.db.models.fields.related.ForeignKey', [], {'related...
TamiaLab/PySkCode
tests/tests_tags/tests_textmodifiers.py
Python
agpl-3.0
3,824
0.003138
""" SkCode text modifiers tag definitions test code. """ import unittest from skcode.etree import RootTreeNode from skcode.tags import ( LowerCaseTextTreeNode, UpperCaseTextTreeNode, CapitalizeTextTreeNode, DEFAULT_RECOGNIZED_TAGS_LIST ) from skcode.tags.textmodifiers import TextModifierBaseTreeNode ...
Node() tree_node = root_tree_node.new_child('capit
alize', CustomTextModifierTreeNode) self.assertEqual('tEst', tree_node.render_text('tEst'))
llange/pynag
examples/Plugins/check_load.py
Python
gpl-2.0
1,986
0.01007
# check_load.py - Check load average. Thresholds can be specified from the commandline # Import PluginHelper and some utility constants from the Plugins module from pynag.Plugins import PluginHelper,ok,warning,critical,unknown # Create an instance of PluginHelper() helper = PluginHelper() # Optionally, let helper ha...
l='load1',value=load1) helper.add_metric(label='load5',value=load5) helper.add_metric(label='load15',value=load15) helper.add_metric(label='running_processes',value=running) helper.add_metric(label='total_processes',value=total) # By default assume everything is ok. Any thresholds specified with --threshold can overwr...
her # built-in or added via --threshold from the command-line helper.check_all_metrics() # Print out plugin information and exit nagios-style helper.exit()
prarthitm/edxplatform
openedx/core/lib/api/permissions.py
Python
agpl-3.0
6,295
0.002065
""" API library for Django REST Framework permissions-oriented workflows """ from django.conf import settings from django.http import Http404 from rest_framework import permissions from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey from student.roles import CourseStaffRole, CourseInstr...
"""Permission that checks to see if the user is global or course staff, permitting only read-only access if they are not. """ def has_object_permission(self, request, view, obj): return (request.user.is_staff or CourseStaffRole(obj.course_id).has_user(request.user) or ...
taffOrOwner(permissions.BasePermission): """ Permission that allows access to admin users or the owner of an object. The owner is considered the User object represented by obj.user. """ def has_object_permission(self, request, view, obj): return request.user.is_staff or obj.user == request....
plotly/plotly.py
packages/python/plotly/plotly/validators/bar/error_x/_valueminus.py
Python
mit
447
0.002237
import _plotly_utils.base
validators class ValueminusValidator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, plotly_name="valueminus", parent_name="bar.error_x", **kwargs): super(ValueminusValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=...
Abdoctor/behave
examples/async_step/features/steps/async_steps35.py
Python
bsd-2-clause
373
0.002681
# -- REQUIRES: Python >= 3.5 from behave import step from behave.api.async_step import async_run_until_complete impo
rt asyncio @step('an async-step waits {duration:f} seconds') @async_run_until_complete async def step_async_step_waits_seconds_py35(context, duration): """Simple example of a coroutine as async-step (in Python 3.5)""
" await asyncio.sleep(duration)
citassa1985/youtube-dl
youtube_dl/extractor/vimeo.py
Python
unlicense
28,337
0.001871
# encoding: utf-8 from __future__ import unicode_literals import json import re import itertools from .common import InfoExtractor from ..compat import ( compat_HTTPError, compat_urlparse, ) from ..utils import ( encode_dict, ExtractorError, InAdvancePagedList, int_or_none, RegexNotFoundEr...
/56015672#at=0', 'md5': '8879b6cc097e987f02484baf890129e5', 'info_dict': { 'id': '56015672', 'ext': 'mp4', 'title': "youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550", 'description': 'md5:2d3305bad981a06ff79f...
'uploader_id': 'user7108434', 'uploader': 'Filippo Valsorda', 'duration': 10, }, }, { 'url': 'http://vimeopro.com/openstreetmapus/state-of-the-map-us-2013/video/68093876', 'md5': '3b5ca6aa22b60dfeeadf50b72e44ed82', 'n...
amol-/tgext.utils
tgext/utils/ajax.py
Python
mit
414
0
f
rom tg import request, abort, override_template from tg.decorators import before_validate, before_render @before_validate def ajax_only(*args, **kwargs): if not request.is_xhr: abort(400) def ajax_expose(template): @before_render def _ajax_expose(*args, **kwargs): if request.is_xhr: ...
xpose
pmacosta/pexdoc
tests/support/pinspect_support_module_1.py
Python
mit
5,165
0.00213
# pinspect_support_module_1.py # Copyright (c) 2013-2019 Pablo Acosta-Serafini # See LICENSE for details # pylint: disable=C0103,C0111,C0411,C0412,C0413,R0201,R0205,R0903,W0212,W0621 from __future__ import print_function import sys import pexdoc.exh import pexdoc.pcontracts import tests.support.pinspect_support_module...
set_obj, tests.support.pinspect_support_module_3.deleter,
) return ClosureClass class ClassWithPropertyDefinedViaLambdaAndEnclosure(object): """Class with lambda for property function and enclosed function to define prop.""" def __init__(self): # noqa: D107 self._clsvar = None clsvar = property( lambda self: self._clsvar + 10, t...
shaded-enmity/custodia
setup.py
Python
gpl-3.0
712
0
#!/usr/bin/python # # Copyright (C) 2015 Custodia project Contributors, for licensee see COPYING from distutils.core import setup setup( name='custodia', version='0.1.0', license='GPLv3+', maintainer='Custodia
project Contributors', maintainer_email='simo@redhat.com', url='https://github.com/latchset/custodia', packages=['custodia', 'custodia.httpd', 'custodia.store', 'custodia.message', 'custodia.kubernetes'], data_files=[('share/man/man7', ["man/custodia.7"]), ('share/doc/cust...
, ('share/doc/custodia/examples', ['custodia.conf']), ], scripts=['custodia/custodia'] )
ufjfeng/leetcode-jf-soln
python/223_rectangle_area.py
Python
mit
1,071
0.014006
""" Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectangle is defined by its bottom left
corner and top right corner as shown in the figure. ![Example layout] (https://leetcode.com/static/images/problemset/rectangle_area.png) Assume that the total area is never beyond the maximum possible value of int. Credits: Special thanks to @mithmatt for adding this proble
m, creating the above image and all test cases. """ class Solution(object): def computeArea(self, A, B, C, D, E, F, G, H): """ :type A: int :type B: int :type C: int :type D: int :type E: int :type F: int :type G: int :type H: int :...
zentralopensource/zentral
tests/inventory/test_clean_ip_address.py
Python
apache-2.0
814
0
from django.test import SimpleTestCase from zentral.contrib.inventory.utils import clean_ip_address class CleanIPAddressTestCase(SimpleTestCase): def test_ipv4(se
lf): for value, result in ((
None, None), (123, None), ("127.0.0.1 ", "127.0.0.1"), (" 10.12.13.17 ", "10.12.13.17"), ("127.0000.0.1", None)): self.assertEqual(clean_ip_address(value), result) def test_ipv6(self)...
pferreir/indico-backup
bin/utils/VSGuideHTMLFix.py
Python
gpl-3.0
4,708
0.006372
# -*- coding: utf-8 -*- ## ## ## This file is part of Indico. ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). ## ## Indico is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; eith...
yref(self, ref): self._out.write("&%s" % ref) if htmlentitydefs.entitydefs.has_key(ref): self._out.write(";") def handle_charref(self, ref): self._out.write("&#%s;" % ref) def handle_pi(self, text): self._out.write("<?%s>" % text) def handle_decl(self, text): ...
ess(ihelpPath + "VideoServices/IndicoUserGuide_VS/index.html") p.process(ihelpPath + "VideoServices/EventManagerUserGuide_VS/index.html") p.process(ihelpPath + "VideoServices/ServerAdminUserGuide_VS/index.html") p.process(ihelpPath + "VideoServices/VSAdminUserGuide_VS/index.html")
luterien/madcyoa
main/views.py
Python
apache-2.0
321
0.015576
from django.sho
rtcuts import render, redirect from django.core.urlresolvers import reverse def test(request): return render(request, "test.html", {"data": "unknown!"}) def index(request): if request.user.is_authenticated(): return redirect(reverse("my-stories"))
return render(request, "main/index.html", {})
odrling/peony-twitter
docs/conf.py
Python
mit
10,839
0
# -*- coding: utf-8 -*- # # Peony documentation build configuration file, created by # sphinx-quickstart on Tue Aug 30 16:36:34 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All...
earch_language = 'en' # A dictionary with options for the search language support, empty by default. # 'ja' uses this config value. # 'zh' user can custom change `ji
eba` dictionary path. # # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # # html_search_scor
sorig/shogun
examples/undocumented/python/modelselection_grid_search_krr.py
Python
bsd-3-clause
4,752
0.016204
#!/usr/bin/env python # # This software is distributed under BSD 3-clause license (see LICENSE file). # # Authors: Heiko Strathmann from numpy import array from numpy.random import seed, rand from tools.load import LoadMatrix lm=LoadMatrix() traindat = lm.load_numbers('../data/fm_train_real.dat') testdat = lm.load_nu...
as type min=-1 max=1 type=R_EXP step=1.5 base=2 tau.build_values(min, max, type, step, base) # gaussian kernel with width gaussian_kernel=GaussianKernel() # pr
int all parameter available for modelselection # Dont worry if yours is not included but, write to the mailing list #gaussian_kernel.print_modsel_params() param_gaussian_kernel=ModelSelectionParameters("kernel", gaussian_kernel) gaussian_kernel_width=ModelSelectionParameters("log_width"); gaussian_...
nCoda/macOS
.eggs/py2app-0.14-py2.7.egg/py2app/bootstrap/setup_pkgresource.py
Python
gpl-3.0
453
0
def _setup_pkgresources(): import pkg_resources import os import plistlib pl = plistlib.readPlist(os.path.join( os.path.dirname(os.getenv('RESOURCEPATH')), "Info.plist")) app
name = pl.get('CFBundleIdentifier') if appname is None: appname = pl['CFBundleDisplayName'] path = os.path.expanduser('~/Library/Caches/%s/python-eggs' % (appname,)) pkg_reso
urces.set_extraction_path(path) _setup_pkgresources()
collects/VTK
Examples/Infovis/Python/random3d.py
Python
bsd-3-clause
847
0.004723
from vtk import * source = vtkRandomGraphSource() source.SetNumberOfVertices(150) source.SetEdgeProbability(0.01) source.SetUseEdgeProbability(True) source.SetStartWithTree(True) view = vtkGraphLayoutView() view.AddRepresentationFromInputConnection(source.GetOutputPort()) view.SetVertexLabelArrayName("vertex id") vie...
o3D() # Left mouse button causes 3D rotate instead of zoom view.SetLabelPlacementModeToNoOverlap() theme = vtkViewTheme.CreateMellowTheme() theme.SetCellColor(.2,.2,.6) theme.SetLineWidth(2) theme.SetPointSize(10) view.ApplyViewTheme(theme) theme.FastDelete() view.GetRenderWindow().SetSize(600, 600) view.ResetCamera(...
.GetInteractor().Start()
helixyte/everest_nosql
everest_nosql/tests/test_aggregates.py
Python
mit
1,812
0.003311
""" This file is part of the everest project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. Created on Nov 27, 2013. """ from everest_nosql.aggregate import NoSqlAggregate import pytest from everest.querying.specifications import desc from everest.querying.specifications import eq from...
agg = class_entity_repo.get_aggregate(IMyEntity) agg.add(ent0)
agg.add(ent1) agg.add(ent2) assert len(list(agg.iterator())) == 3 agg.filter = eq(**{'parent.text_ent':'222'}) assert len(list(agg.iterator())) == 1 agg.filter = None assert len(list(agg.iterator())) == 3 # TODO: Nested attribute ordering does not work with...
chapmanbe/pymitools
pymitools/ontologies/metadataCollector.py
Python
apache-2.0
8,067
0
"""Includes MetadataCollector class. Responsible for keeping track of when widget values change or are selected. """ import ipywidgets as widgets from IPython.display import display import requests class MetadataCollector: """Handle information inside the widgets.""" def __init__(self, topic, ontologies, ...
fo stores keywords as keys and bioportal # results as values
self._results_info = dict() # self._final_results stores only the info for added words self._final_results = dict() self._selected = None self._ready = False results_name = topic + " results:" self._search_input_widget = widgets.Text(description=topic, ...
BytesGalore/RIOT
tests/pkg_tinycbor/tests/01-run.py
Python
lgpl-2.1
474
0
#!/usr/bin/env py
thon3 # Copyright (C) 2016 Kaspar Schleiser <kaspar@schleiser.de> # Copyright (C) 2016 Takuo Yonezawa <Yonezawa-T2@mail.dnp.co.jp> # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. import sys from t...
_main__": sys.exit(run(testfunc))
cncdnua/cncdnua
cncdnua/cncdnua/urls.py
Python
mit
405
0.002469
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autod
iscover() urlpatterns = patterns
( '', url(r'', include('frontpage.urls')), url(r'^auth/', include('social.apps.django_app.urls', namespace='social')), url(r'^admin/', include(admin.site.urls)), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'), )
yoga30696/Coursera-Using-databases-with-python
Week 3/tracks/tracks.py
Python
gpl-3.0
2,704
0.011834
import xml.etree.ElementTree as ET import sqlite3 conn = sqlite3.connect('trackdb.sqlite') cur = conn.cursor() # Make some fresh tables using executescript() cur.executescript(''' DROP TABLE IF EXISTS Artist; DROP TABLE IF EXISTS Album; DROP TABLE IF EXISTS Track; DROP TABLE IF EXISTS Genre; CREATE TABLE Artist ( ...
TEXT UNIQUE ); CREATE TABLE Album ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, artist_id INTEGER, title TEXT UNIQUE ); CREATE TABLE Track ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, title TEXT UNIQUE, album_id INTEGER, genre_id INTEGER,
len INTEGER, rating INTEGER, count INTEGER ); ''') fname = raw_input('Enter file name: ') if ( len(fname) < 1 ) : fname = 'Library.xml' # <key>Track ID</key><integer>369</integer> # <key>Name</key><string>Another One Bites The Dust</string> # <key>Artist</key><string>Queen</string> def lookup(d, key): found ...
kevindkeogh/qbootstrapper-flask
qbflask/__init__.py
Python
mit
401
0.002494
#!/usr/bin/python3 '''qbootstraper main application ''' from flask import Flask from flask_wtf import csrf app = Flask(__name__) c
srf.CSRFProtect().init_app(app) # enable CSRF protection from qbflask.views import * app.config.update(dict( DATABASE='qbflask.db', DEBUG=True, SECRET_KEY='secret',
USERNAME='admin', PASSWORD='admin' )) if __name__ == '__main__': app.run()
grimmjow8/ansible
test/units/executor/test_play_iterator.py
Python
gpl-3.0
18,831
0.001062
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # A
nsible is free softwa
re: 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 distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without ev...
unterweg/peanoclaw
supermucIBMMPIConfiguration.py
Python
bsd-3-clause
431
0.018561
# # Definitions for compiling with IBM-MPI on SuperMUC # def getMPIIncludes(): return ['/opt/ibmhpc/pecurrent/mpich2/intel/include64'] def g
etMPILibrarypaths(): return ['/opt/ibmhpc/pecurrent/mpich2/intel/lib64', '/opt/ibmhpc/pecurrent/mpich2/../pempi/intel/lib64', '/opt/ibmhpc/pecurrent/ppe.pami/intel/lib64/pami64'] def getMPILibraries(): return ['cxxmpich', 'pthread', 'mpich', 'opa', 'mpl', 'dl',
'poe', 'pami']
rozofs/rozofs
tests/IT/IT.py
Python
gpl-2.0
44,593
0.047294
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import os.path import subprocess import time import re import shlex from display_array import * from optparse import OptionParser fileSize=int(4) loop=int(32) process=int(8) EXPOR
T_SID_NB=int(8) STORCLI_SID_NB=int(8) nbGruyere=int(256) stopOnFailure=Tru
e fuseTrace=False DEFAULT_MNT="mnt1_1_g0" ALL_MNT="mnt1_1_g0,mnt2_1_g0,mnt3_1_g0,mnt4_1_g0" mnts=DEFAULT_MNT mnt="" DEFAULT_RETRIES=int(20) tst_file="tst_file" device_number="" mapper_modulo="" mapper_redundancy="" vid="" list_cid=[] list_sid=[] list_host=[] hunic=[] inverse=2 forward=3 safe=4 #______________________...
gudnithor4/ThrounHugb
plot.py
Python
mit
1,664
0.006707
import math import matplotlib.pyplot as plt import numpy import reiknivelar def plot_framtidarvirdi(eign, timabil, vextir): vaxtabrot = vextir/100.0 plotData = [] fig1 = plt.figure() for manudur in range(0,timabil+1): plotData.append(eign*(math.pow((1+vaxtabrot), manudur))) plt.plot(plotDa...
w() def plot_reglulegurspar(greidsla, timabil, vextir): v = vextir/100.0 vex = v/12.0 plotData = [] fig2 = plt.figure() for manudur in range(0, timabil+1): plotD
ata.append((greidsla / vex)*((math.pow((1 + vex), manudur)) - 1)) plt.plot(plotData,linewidth=2, color='r') plt.ylabel(u"Krónur") plt.xlabel(u"Mánuðir") fig2.canvas.set_window_title('Reglulegur sparnaður') plt.show() def plot_hofudstols_ryrnun(hofudstoll, timabil, vextir, verdbolga, manadarGreidsl...
Meuh-Factory/womoobox
settings.py
Python
gpl-2.0
490
0.006122
# Configuration # Generate key with specific length and chars import string KEY_LENGTH = 50 KEY_REF_SETS = string.ascii_letters + string.digits # When getting last Moos to init map MAX_NUMBER_OF_INITIAL_MOO = 25 # When getting last Moos from last call MAX_NUMBER_OF_MOO = 25 # Do not accept more than 1 (same animal)...
nutes # Supported languages SUPPORTED_LANGUAGES = ( 'fr',
'en', ) DEFAULT_LANGUAGE = SUPPORTED_LANGUAGES[1]
mostaphaRoudsari/Honeybee
src/Honeybee_EnergyPlus NoMass Opaque Material.py
Python
gpl-3.0
5,463
0.011715
# # Honeybee: A Plugin for Environmental Analysis (GPL) started by Mostapha Sadeghipour Roudsari # # This file is part of Honeybee. # # Copyright (c) 2013-2020, Mostapha Sadeghipour Roudsari <mostapha@ladybug.tools> # Honeybee is free software; you can redistribute it and/or modify # it under the terms of the GNU G...
if _roughness_ != None: _roughness = _roughness_.upper() else: _roughness = None if _roughness == None or _roughness == "VERYROUGH" or _roughness == "ROUGH" or _roughness == "MEDIUMROUGH" or _roughness == "MEDIUMSMOOTH" or _roughness == "SMOOTH" or _roughness == "VERYSMOOTH": pass else: checkData ...
False warning = "_roughness_ is not valid." print warning ghenv.Component.AddRuntimeMessage(w, warning) return checkData def main(name, roughness, R_Value, thermAbsp, solAbsp, visAbsp): if roughness == None: roughness = "Rough" if thermAbsp == None: thermAbsp = 0.9 if...
jimporter/bfg9000
test/integration/languages/test_java.py
Python
bsd-3-clause
2,704
0
import glob import os from .. import * @skip_if('java' not in test_features, 'skipping java tests') @skip_if_backend('msbuild') class TestJava(IntegrationTest): def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'java'), install=True, *args, **kwargs)...
ir(self.srcdir) cleandir(self.builddir) self.assertOutput( ['java', '-jar', os.path.join(self.libdir, 'program.jar')], 'hello from java!\n' ) @skip_if('gcj' not in test_features, 'skipping gcj tests') class TestGcj(IntegrationTest): def __init__(self, *args, **kwarg...
'gcj')}, *args, **kwargs) def test_build(self): self.build('program') self.assertOutput([executable('program')], 'hello from java!\n') @skip_if('java' not in test_features, 'skipping java tests') @skip_if_backend('msbuild') class TestJavaLibrary(IntegrationTest): def...
mattpitkin/corner.py
corner/tests/test_hist2d.py
Python
bsd-2-clause
2,349
0
# -*- coding: utf-8 -*- from __future__ import division, print_function import numpy as np import matplotlib.pyplot as pl from m
atplotlib.testing.decorators import image_comparison import corner def _run_hist2d(nm, N=50000, seed=1234, **kwargs):
# Generate some fake data. np.random.seed(seed) x = np.random.randn(N) y = np.random.randn(N) fig, ax = pl.subplots(1, 1, figsize=(8, 8)) corner.hist2d(x, y, ax=ax, **kwargs) @image_comparison(baseline_images=["cutoff"], extensions=["png"]) def test_cutoff(): _run_hist2d("cutoff", range=[(0, ...
kingvuplus/rr
lib/python/Plugins/Extensions/DVDBurn/ProjectSettings.py
Python
gpl-2.0
11,215
0.027463
from Screens.Screen import Screen from Screens.ChoiceBox import ChoiceBox from Screens.InputBox import InputBox from Screens.MessageBox import MessageBox from Screens.HelpMenu import HelpableScreen from Components.ActionMap import HelpableActionMap, ActionMap from Components.Sources.List import List from Components.Sou...
rogress import Progress from Components.FileList import FileList from Tools.Directories import fileExists, resolveFilename, SCOPE_PLUGINS, SCOPE_FONTS, SCOPE_HDD from Components.config import config, getConfigListEntry from Components.ConfigList import ConfigListScreen class FileBrowser(Screen, HelpableScreen): def ...
r, this allows individual skinning self.skinName = ["FileBrowser_DVDBurn", "FileBrowser" ] HelpableScreen.__init__(self) self.scope = scope pattern = "" self.configRef = configRef currDir = "/" if self.scope == "project": currDir = self.getDir() pattern = "(?i)^.*\.(ddvdp\.xml)" elif self.scope =...
iwm911/plaso
plaso/parsers/sqlite_plugins/interface.py
Python
apache-2.0
10,505
0.006092
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2012 The Plaso Project Authors. # Please see the AUTHORS file for details on individual authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the L...
}'.format(unused_row)) class SQLiteDatabase(object): """A simple wrapper for opening up a SQLite
database.""" # Magic value for a SQLite database. MAGIC = 'SQLite format 3' _READ_BUFFER_SIZE = 65536 def __init__(self, file_entry): """Initializes the database object. Args: file_enty: the file entry object. """ self._file_entry = file_entry self._temp_file_name = '' self._o...
yishinli/emc2
src/emc/usr_intf/axis/scripts/image-to-gcode.py
Python
lgpl-2.1
26,563
0.00832
#!/usr/bin/python ## image-to-gcode 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. image-to-gcode is distributed in the hope ## ...
span.reverse()
yield True, span def reset(self): pass class Convert_Scan_Downmill: def __init__(self, slop = sin(pi / 18)): self.slop = slop def __call__(self, primary, items): for span in group_by_sign(items, self.slop, operator.itemgetter(2)): if amax([it[2] for it in span]) > 0...
leyyin/university-SE
school/util.py
Python
mit
110
0
def is_integer(nr): try: int(nr) return True except ValueError:
return False
FreedomCoop/valuenetwork
account/admin.py
Python
agpl-3.0
1,314
0
from django.contrib import admin from account.models import ( Account, AccountDeletion, EmailAddress, PasswordExpiry, PasswordHistory, SignupCode, ) class SignupCodeAdmin(admin.ModelAdmin): list_display = ["code", "max_uses", "use_count", "expiry", "created"] search_fields = ["code",...
p"] list_filter = ["user"] ordering = ["user__username", "-timestamp"] admin.site.register(Account, AccountAdmin) admin.site.register(SignupCode, SignupCodeAdmin) admin.site.register(AccountDeletion, AccountDeletionAdmin) admin.site.register(EmailAddress, EmailAddressAdmin) admin.site.register(PasswordExpiry,...
n) admin.site.register(PasswordHistory, PasswordHistoryAdmin)
ZachAnders/MPServices
mpservices.py
Python
bsd-2-clause
1,761
0.034072
#!/usr/bin/python import sys import osxdaemons COL_RED = "\033[91m" COL_GRN = "\033[92m" COL_END = "\033[0m" load_actions = ["up", "on", "load", "start"] unload_actions = ["down", "off", "unload", "stop"] ACTIONS = {act:"load" for act in load_actions} ACTIONS.update({act:"unload" for act in unload_actions}) def u...
f service_action(service, action): action = match_action(action) if action: print(action.title() + "ing service: " + service) return osxdaemons.do(service, action) else: print("Wtf I don't know how to " + action + ".") usage() return -1 def print_services(): running_daemons = osxdaemons
.get_running_daemons() for daemon in osxdaemons.get_all_daemons(): outs = daemon + " "*(60-len(daemon)) if daemon in running_daemons: col = COL_GRN status = "RUNNING" else: col = COL_RED status = "NOT RUNNING" print(outs + col + status + COL_END) def main(): if len(sys.argv) == 1: print_service...
pdehaye/theming-edx-platform
common/lib/xmodule/xmodule/combined_open_ended_module.py
Python
agpl-3.0
21,389
0.003974
import logging from lxml import etree from pkg_resources import resource_string from xmodule.raw_module import RawDescriptor from .x_module import XModule from xblock.core import Integer, Scope, String, List, Float, Boolean from xmodule.open_ended_grading_classes.combined_open_ended_modulev1 import CombinedOpenEndedV...
nEndedV1Descriptor from collections import namedtuple from .fields import Date, Timedelta import textwrap log = logging.getLogger("mitx.courseware") V1_SETTINGS_ATTRIBUTES = [ "display_name", "max_attempts", "graded", "accept_file_upload", "skip_spelling_checks", "due", "graceperiod", "weight", "min_to_calibr...
grader_count", "required_peer_grading", ] V1_STUDENT_ATTRIBUTES = ["current_task_number", "task_states", "state", "student_attempts", "ready_to_reset", "old_task_states"] V1_ATTRIBUTES = V1_SETTINGS_ATTRIBUTES + V1_STUDENT_ATTRIBUTES VersionTuple = namedtuple('VersionTuple', ['descriptor', '...
paymill/paymill-python
paymill/services/checksum_service.py
Python
mit
5,102
0.004509
# coding=utf-8 from ..models.checksum import Checksum from ..models.address import Address from ..models.shopping_cart_item import ShoppingCartItem from ..models.shopping_cart import ShoppingCart from .paymill_service import PaymillService import json __author__ = 'yalnazov' class ChecksumService(PaymillService): ...
usable_payment_description=None, items=None,
shipping_address=None, billing_address=None, app_id=None, client_id=None): """Creates new transaction/payment Checksum :param str checksum_type: Type of request verified by this checksum :param int amount: Amount (in cents) which will be charged :param str currency: ISO 4...
aspic2/ZombieScript
tests/main_tests.py
Python
mit
110
0
'''Sorry, I never got around to writing tests.''' f
rom nose.tools
import * from zombiescript import main
Buchhold/QLever
misc/fix_nt_file.py
Python
apache-2.0
554
0.016245
import sys def fix(element): if element and element[0] == '<': new = '<' for c in element[1:-1]: if c == '<':
new += '&lt' elif c == '>': new += '&gt'
else: new += c new += '>' return new else: return element for line in open(sys.argv[1]): cols = line.strip().split('\t') if len(cols) != 4 or cols[3] != '.': sys.err.write('Ignoring malformed line: ' + line) else: # for now only touch subject for efficiency reasons. cols[...
redhat-openstack/heat
heat/tests/test_template_format.py
Python
apache-2.0
7,015
0
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version:
2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml....
andrewkaufman/gaffer
python/GafferTest/NumericBookmarkSetTest.py
Python
bsd-3-clause
4,620
0.042208
########################################################################## # # Copyright (c) 2019, Cinesite VFX Ltd. 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 ...
ARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT...
UWPCE-PythonCert/IntroPython2016
students/sheree/session_03/homework/LPTHW-EXC-16.py
Python
unlicense
1,164
0.005155
#this is exercize 16 on page 59 of the LPTHW pdf #exercise 16 - reading and writing files # we're using arguments here, the arg is a filename var from sys import argv # argv standard options for filename script, filename = argv # print the file name we passed #
print an option to exit # print an option to continue, ie: return for yes print("We're going to erase %r.
") % filename print("If you don't want that, hit CTRL-C (^c).") print("If you do want that, hit RETURN.") # getting input with a ? prompt raw_input("?") # printing a status message # setting target to file I don't understand the w here print("Opening the file...") target = open(filename, "w") # W IS FOR WRITE APPARENTL...
trevor/calendarserver
txweb2/test/test_http.py
Python
apache-2.0
47,272
0.00404
from __future__ import nested_scopes import time, sys, os from zope.interface import implements from twisted.trial import unittest from txweb2 import http, http_headers, responsecode, iweb, stream from txweb2 import channel from twisted.internet import reactor, protocol, address, interfaces, utils from twisted.int...
RawHeaders("If-Match", ('*',)) self.checkPreconditions(request, response, True, responsecode.OK) self.checkPreconditions(request, response, False, responsecode.PRECONDITION_FAILED, entityExists=False) # Ask for tag, but no
etag set. request.headers.setRawHeaders("If-Match", ('"frob"',)) self.checkPreconditions(request, response, False, responsecode.PRECONDITION_FAILED) ## Actually set the ETag header out_headers.setHeader("ETag", http_headers.ETag('foo')) out_headers.setHeader("Last-Modified", 94...
jalonsob/Informes
vizgrimoire/metrics/__init__.py
Python
gpl-3.0
766
0.001305
# -*- coding: utf-8 -*- # # Copyright (C) 2012-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) an
y later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Publ...
e - Suite 330, Boston, MA 02111-1307, USA. #
probml/pyprobml
scripts/cifar_viz_tf.py
Python
mit
1,065
0
# Based on # https://github.com/tensorflow/docs/blob/master/site/en/tutorials/keras/basic_classification.ipynb # (MIT License) import superimport from __future__ import absolute_import, division, print_function from tensorflow import keras import tensorflow as tf import numpy as np import matplotlib.pyplot as plt i...
t_images, test_labels) = data.load_data() # print(np.shape(train_images)) # print(np.shape(test_images)) # For CIFAR: # (50000, 32, 32, 3) # (10000, 32, 32, 3) class_names = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'] plt.figure(figsize=(10, 10)) for i in range(2...
ave_fig("cifar10-data.pdf") plt.show()
KNNSpeed/hockeylauncher
Adafruit-Motor-HAT-Python-Library/examples/StackingTest.py
Python
mit
2,575
0.017864
#!/usr/bin/python from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor, Adafruit_StepperMotor import time import atexit import threading import random # bottom hat is default address 0x60 bottomhat = Adafruit_MotorHAT(addr=0x60) # top hat has A0 jumper closed, so its address 0x61 tophat = Adafruit_MotorHA...
ottomhat.getMotor(4).run(Adafruit_MotorHAT
.RELEASE) atexit.register(turnOffMotors) myStepper1 = bottomhat.getStepper(200, 1) # 200 steps/rev, motor port #1 myStepper2 = bottomhat.getStepper(200, 2) # 200 steps/rev, motor port #2 myStepper3 = tophat.getStepper(200, 1) # 200 steps/rev, motor port #1 myStepper1.setSpeed(60) # 60 RPM myStepper2.setSpee...
bcoca/ansible-modules-extras
cloud/centurylink/clc_group.py
Python
gpl-3.0
17,070
0.001172
#!/usr/bin/python # # Copyright (c) 2015 CenturyLink # # 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 la...
- name: Create Server Group hosts: localhost gather_facts: False connection: local tasks: - name: Create / Verify a Server Group at CenturyLink Cloud clc_group: name: 'My Cool Server Group' parent: 'Default Group' state: present register: clc - name: debug deb...
ocal tasks: - name: Delete / Verify Absent a Server Group at CenturyLink Cloud clc_group: name: 'My Cool Server Group' parent: 'Default Group' state: absent register: clc - name: debug debug: var=clc ''' RETURN = ''' group: description: The group information ...
CentralLabFacilities/pepper_behavior_sandbox
pepper_behavior/skills/turn_base_without.py
Python
gpl-3.0
394
0.025381
import smach import rospy import actionlib im
port tf import math class TurnWithoutMovebase(smach.State): def __init__(self, controller, angle): self.controller = controller self.angle = angle smach.State.__init__(self, outcomes=['success']) def execute(self, userdata): msg = '0:0:' + str(math.radians(self.angle)) self.contro
ller.publish(msg) return 'success'
rnixx/kivy
kivy/tests/test_filechooser_unicode.py
Python
mit
3,716
0.000552
# -*- coding: utf-8 -*- # XXX: please be careful to only save this file with an utf-8 editor import unittest import pytest from kivy import platform unicode_char = chr class FileChooserUnicodeTestCase(unittest.TestCase): def setUp(self): self.skip_test = platform == 'macosx' or platform == 'ios' ...
remove(f) for f in self.exitsfiles: remove(f) for f in self.bfiles: remove(
f) rmdir(self.basepathu) except: pass
xsm110/Apache-Beam
sdks/python/apache_beam/utils/counters.py
Python
apache-2.0
6,154
0.005362
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
this method returns hence the returned iterable may be stale. """ with self._lock: return self.counters.values() def get_aggregator_values(self, aggregator_or_name): """Returns dict of step names to values of the aggregator.""" with self._lock: return get_aggregator_values( ...
def get_aggregator_values(aggregator_or_name, counter_dict, value_extractor=None): """Extracts the named aggregator value from a set of counters. Args: aggregator_or_name: an Aggregator object or the name of one. counter_dict: a dict object of {name: value_wrapper} value_extr...
pmarti/pyclutter
clutter/keysyms.py
Python
lgpl-2.1
30,005
0.0001
# -*- Mode: Python; py-indent-offset: 4 -*- # pyclutter - Python bindings for Clutter # Copyright (C) 2006 Emmanuele Bassi # # clutter/keysyms.py: list of keysyms. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by ...
e = 0xFE50 dead_acute = 0xFE51 dead_circumflex = 0xFE52 dead_tilde = 0xFE53 dead_macron = 0xFE54 dead_breve = 0xFE55 dead_abovedot = 0xFE56
dead_diaeresis = 0xFE57 dead_abovering = 0xFE58 dead_doubleacute = 0xFE59 dead_caron = 0xFE5A dead_cedilla = 0xFE5B dead_ogonek = 0xFE5C dead_iota = 0xFE5D dead_voiced_sound = 0xFE5E dead_semivoiced_sound = 0xFE5F dead_belowdot = 0xFE60 First_Virtual_Screen = 0xFED0 Prev_Virtual_Screen = 0xFED1 Next_Virtual_Screen = 0x...
google/TaglessCRM
src/plugins/pipeline_plugins/utils/__init__.py
Python
apache-2.0
601
0.001664
# python3 # coding=utf-8 # Copyright 2020 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either ex
press or implied. # See the License for the specific language governing permissions and # limitations under the License.
gpodder/mygpo-feedservice
manage.py
Python
agpl-3.0
254
0
#!/us
r/bin/env python import os import sys if __
name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "feedservice.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
leapcode/leap_pycommon
src/leap/common/events/zmq_components.py
Python
gpl-3.0
5,662
0.000177
# -*- coding: utf-8 -*- # zmq.py # Copyright (C) 2015, 2016 LEAP # # 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. # # T...
import TxAuthenticator from leap.common.events.auth import TxAuthenticationRequest except ImportError: pass from txzmq.connection import ZmqEndpoint, ZmqEndpointType from leap.common.config import flags, get_path_prefix from leap.common.zmq_utils i
mport zmq_has_curve from leap.common.zmq_utils import maybe_create_and_get_certificates from leap.common.zmq_utils import PUBLIC_KEYS_PREFIX logger = logging.getLogger(__name__) ADDRESS_RE = re.compile("^([a-z]+)://([^:]+):?(\d+)?$") LOCALHOST_ALLOWED = '127.0.0.1' class TxZmqComponent(object): """ A twist...
leighpauls/k2cro4
third_party/WebKit/Tools/Scripts/webkitpy/common/lru_cache_unittest.py
Python
bsd-3-clause
3,651
0.001917
#!/usr/bin/env python # Copyright (C) 2011 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 ...
the following disclaimer # in the documentation and/or other materials provided with the # distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A ...
SCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON...
ufeslabic/parse-facebook
lib_output.py
Python
mit
6,654
0.021491
#!/usr/bin/env python # -*- coding: utf-8 -*- import csv, sys, subprocess from lib_time import * # returns the given float number with only 2 decimals and a % appended def float_to_percentage(float_number): return("%0.2f" % float_number +"%") # normalize the dictionary with the word count to generate the wordcloud d...
e_writer.writerow(column_titles) for item in ordered_list: f
ile_writer.writerow([item[0], item[1]]) csvfile.close() def comments_timeline(): list_datetime_commments = [] with open('comments.tab', 'rt', encoding="utf8") as csvfile: csv_in = csv.reader(csvfile, delimiter='\t') next(csv_in) for line in csv_in: str_raw_time = line[3] temp_datetime = datetime.dateti...
ligo-cbc/pycbc
pycbc/tmpltbank/option_utils.py
Python
gpl-3.0
57,143
0.004777
# Copyright (C) 2013 Ian W. Harry # # 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 t...
that are defined in that group. """ option_list = option_group._group_actions command_lines = [] for option in option_list: option_strings = option.option_strings for string in option_strings: if string.startswith('--'): command_lines.append(string) r...
er instance. """ def match_type(s): err_msg = "must be a number between 0 and 1 excluded, not %r" % s try: value = float(s) except ValueError: raise argparse.ArgumentTypeError(err_msg) if value <= 0 or value >= 1: raise argparse.ArgumentTypeEr...
mdsitton/pract2d
pract2d/core/context.py
Python
bsd-2-clause
1,065
0.002817
import sdl2 as sdl class Context(object): def __init__(self, major, minor, msaa=2): self.major = major self.minor = minor self.msaa = msaa self.context = None self._window = None sdl.SDL_GL_SetAttribute(sdl.SDL_GL_DOUBLEBUFFER, 1) sdl.SDL_GL_SetAttribute(s...
ON, major) sdl.SDL_GL_SetAttribute(sdl.SDL_GL_CONTEXT_MINOR_VERSION, minor) sdl.SDL_GL_SetAttribute(sdl.SDL_GL_CONTEXT_PROFILE_MASK, sdl.SDL_GL_CONTEXT_PROFILE_CORE) if msaa < 0: sdl.SDL_GL_SetAttribute(sdl.SDL_GL_MULTISAMPLEBUFFERS, 1) sdl.SDL_GL_SetAttribute(sdl.SDL_G...
sdl.SDL_GL_DeleteContext(self.context) @property def window(self): return self._window @window.setter def window(self, win): self._window = win if self.context == None: # Create context if not already created self.context = sdl.SDL_GL_CreateContext(self...
HEP-DL/root2hdf5
root2hdf5/plugins/larcv/segment.py
Python
gpl-3.0
1,556
0.025064
from root2hdf5.data_types.base import BaseData import numpy as np import logging class SegmentData(BaseData): logger = logging.getLogger('root2hdf5.data_types.segment') tree_name = 'image2d_segment_hires_crop_tree' def __init__(self, _file, output_file): super(SegmentData, self).__init__(_file) from lar...
3_name'] = 'pixelX' self.dataset.attrs['index4_name'] = 'pixelY' self.buffer = np.ndarray((10,3,576,576), dtype='H') self.buffer_index=0 def process_branch(self, branch): for layer in range(3): layerimage = self.array_converter(branch.at(la
yer)) layerimage.resize(576,576) self.buffer[self.buffer_index, layer] = layerimage self.buffer_index+=1 if self.event_index %10==0: self.buffer_index=0 self.dataset.resize( (self.event_index+10,3,576,576) ) self.dataset[self.event_index:self.event_index+10,:,:,:] = self.buffer
heinrichgh/fintrack
app/forms.py
Python
gpl-2.0
1,523
0.004596
__author__ = 'heinrich' from flask.ext.wtf import Form from wtforms import StringField, PasswordField, FloatField, DateField, SelectField from wtforms.validators import DataRequired, EqualTo, Email import datetime class RegisterForm(Form): email = StringField('Email', validators=[DataRequired(), Email()]) pas...
', validators=[DataRequired()]) passwordConfirm = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password', 'Passwords did not match')]) name = StringField('Name', validators=[DataRequired()]) surname = StringField('Surname') class LoginForm(Form): email = StringField('Email', ...
taRequired()]) date = DateField('Date', validators=[DataRequired()], default=datetime.date.today()) incomeType = SelectField('Income Type', validators=[DataRequired()], coerce=int) class IncomeTypeForm(Form): type = StringField('Income Type', validators=[DataRequired()]) class ExpenditureForm(Form): ...
hsr-ba-fs15-dat/opendatahub
src/main/python/hub/serializers.py
Python
mit
6,460
0.002786
# -*- coding: utf-8 -*- # Get rid of "FormatSerializer:Method 'create' is abstract in class 'BaseSerializer' but is not overridden" # FormatSerializer is read only anyway # pylint: disable=abstract-method from __future__ import unicode_literals from rest_framework import serializers from rest_framework.reverse import...
rue, context={'request': request}) return serializer.data class FileGroupSerializer(serializers.HyperlinkedModelSerializer, RelatedTransformationMixin): files = FileSerializer(many=True, read_only=True) urls = UrlSerializer(many=True, read_only=True) document = DocumentSerializer(read_only=True) ...
formations = serializers.SerializerMethodField() data = serializers.HyperlinkedIdentityField('filegroupmodel-data') token = serializers.HyperlinkedIdentityField('filegroupmodel-token') preview = serializers.HyperlinkedIdentityField('filegroupmodel-preview') class Meta(object): """ Meta class f...
WCCCEDU/twitter-commons
src/python/twitter/common/rpc/finagle/__init__.py
Python
apache-2.0
1,073
0
# ================================================================================================== # Copyright 2013 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi...
icable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITH
OUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ================================================================================================== from twitter.common.rpc.finagle.protocol impor...
MMShreyas/AVL-Trees
avl.py
Python
gpl-3.0
4,346
0.015416
import bst def height(node): if node is None: return -1 else: return node.height def update_height(node): node.height = max(height(node.left), height(node.right)) + 1 class AVL(bst.BST): """ AVL binary search tree implementation. Supports insert, find, and delete-min operations in O(l...
print "Rebalancing Left Subtree of",node.key
if height(node.left.left) >= height(node.left.right): print "Height of left Subtree",height(node.left.left),">=","Height of Right Subtree",height(node.left.right) print "Applying Right Rotate at",node.key self.right_rotate(node) ...
bittssystem/version3
dashboard.py
Python
mit
4,121
0.000485
""" This file was generated with the customdashboard management command and contains the class for the main dashboard. To activate your index dashboard add the following to your settings.py:: GRAPPELLI_INDEX_DASHBOARD = 'version3.dashboard.CustomIndexDashboard' """ from django.utils.translation import ugettext_la...
end(modules.Group( # _('Group: Administration & Applications'), # column=1, # collapsible=True, # children = [ # modules.AppList( # _('Administration'), # column=1,
# collapsible=False, # models=('django.contrib.*',), # ), # modules.AppList( # _('Applications'), # column=1, # css_classes=('collapse closed',), # exclude=('django.contrib.*'...
rtfd/readthedocs.org
readthedocs/oauth/migrations/0008_add-project-relation.py
Python
mit
565
0.00177
# -*- coding: utf-8 -*- # Generated by Django 1.9.12 on 2017-03-22 20:10 import
django.db.models.deletion from django.db import migra
tions, models class Migration(migrations.Migration): dependencies = [ ('oauth', '0007_org_slug_nonunique'), ] operations = [ migrations.AddField( model_name='remoterepository', name='project', field=models.OneToOneField(blank=True, null=True, on_delete...
oadam/proprio
bank_import/views.py
Python
mit
9,434
0.000318
from django.shortcuts import render from django.contrib.auth.decorators import login_required from forms import GenerateForm, SubmitForm from django.http import HttpResponse, Http404, HttpResponseBadRequest from django.utils.translation import ugettext as _, ugettext_lazy from django.db import transaction from main.mod...
data = form.c
leaned_data submit_mapping(data['file']) return HttpResponse(_("import is successful").capitalize()) class TenantPaymentMapper: type = 'tenant_payment' caption = ugettext_lazy('Tenant payment') def __init__(self): tenants = Tenant.objects.all().order_by('name') self.tenants = {t.i...
rogerscristo/BotFWD
env/lib/python3.6/site-packages/telegram/inline/inlinequeryresultdocument.py
Python
mit
4,538
0.002644
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2017 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This
program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser 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 Lesser Publ...
slyfocks/pigs
shortcodes.py
Python
apache-2.0
1,664
0.001803
from itertools import product, islice from joblib import Parallel, delayed import json import requests from requests.exceptions import ConnectionError, Timeout from simplejson import JSONDecodeError import string CLIENT_ID = 'a48b4d0f6e0745e2ba68902a1f68f8d5' URL = 'https://api.instagram.com/oembed/media/?url=http://i...
tcode, verbose=verbose) for shortco
de in generate()) data = [entry for entry in data if entry] + list(prev_data.items()) with open('codes.json', 'w') as writefile: json.dump(dict(data), writefile, indent=4, sort_keys=True, separators=(',', ': ')) if __name__ == "__main__": validate()
chengjunjian/kpush
backend/kpush/share/extensions.py
Python
mit
176
0
# -*- coding: utf-8 -*- """ 所有的插
件,只是生成,初始化统一放到applicat
ion里 """ from flask_admin import Admin admin = Admin(template_mode='bootstrap3')
phenoxim/nova
nova/tests/unit/cmd/test_baseproxy.py
Python
apache-2.0
3,676
0.000272
# Copyright 2015 IBM Corp. # # 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, so...
eturn_value=None) @mock.patch('nova.console.websocketproxy.NovaWebSocketProxy.start_server') def test_proxy(self, mock_start, mock_init, mock_gmr, mock_log, m
ock_exists): baseproxy.proxy('0.0.0.0', '6080') mock_log.assert_called_once_with(baseproxy.CONF, 'nova') mock_gmr.mock_assert_called_once_with(version) mock_init.assert_called_once_with( listen_host='0.0.0.0', listen_port='6080', source_is_ipv6=False, cert='self.p...
timothyparez/PyBitmessage
src/bitmessageqt/retranslateui.py
Python
mit
900
0.005556
from os import path from PyQt4 import QtGui from debug import logger import widgets class RetranslateMixin(object): def retranslateUi(self): defaults = QtGui.QWidget() widgets.load(self.__class__.__name__.lower() + '.ui', defaults) for attr, value in defaults.__dict__.iteritems(): ...
allable(setTextMethod): getattr(self, attr).setText(getattr(defaults,
attr).text()) elif isinstance(value, QtGui.QTableWidget): for i in range (value.columnCount()): getattr(self, attr).horizontalHeaderItem(i).setText(getattr(defaults, attr).horizontalHeaderItem(i).text()) for i in range (value.rowCount()): ...
ati-ozgur/KDD99ReviewArticle
HelperCodes/create_table_metaDatasetsUsed.py
Python
mit
1,724
0.011021
import ReviewHelper import pandas as pd df = ReviewHelper.get_pandas_data_frame_created_from_bibtex_file() # find problematic ones df[df.metaDatasetsUsed.isnull()] list1 = df.metaDatasetsUsed.str.split(",").tolist() df1 = pd.DataFrame(list1) for i in range(df1.columns.size): df1[i] = df1[i].str.strip() stac...
s > 3] table_content_inside="" list_ids_dataset_names = ["KDD99","NSL-KDD","DARPA","Kyoto","ISCX"] table_content_inside="" for dataset_name in greater_than.index: dataset_count = greater_than[dataset_name] dataset_name_in_table = dataset_name dataset_name_in_table = dataset_name if(dataset_name in...
& {dataset_count} \\\\ \n".format( dataset_name = dataset_name_in_table ,dataset_count = dataset_count ) table_content_inside = table_content_inside + line table_content_start = """ \\begin{table}[!ht] \\centering \\caption{ \\textbf{Most used Datasets}. * denotes IDS datasets. Datas...
unnikrishnankgs/va
venv/lib/python3.5/site-packages/tensorflow/contrib/keras/api/keras/applications/xception/__init__.py
Python
bsd-2-clause
1,148
0.002613
# Copyright 2016 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...
re # 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.
# ============================================================================== """Xception Keras application.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.keras.python.keras.applications.xception import decode_predictions fro...
srkiyengar/NewGripper
src/shutter.py
Python
mit
509
0.011788
impo
rt serial import struct import time # j = 2 means open, j = 1 means close shutter def command_shutter(port, j): # first, start the serial port to communicate with the arduino if port.isOpen(): print "port open" port.write(struct.pack('>B', j))
return 1 else: return 0 #while(1 == 1): #cover_or_not = int(input('Enter a number. 1 will cover the Lenses of the NDI, while 2 will open the blinds.')) #data.write(struct.pack('>B',cover_or_not))
ArcherSys/ArcherSys
skulpt/test/run/t54.py
Python
mit
21
0.047619
a,b = "OK" print a+
b