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
WQuanfeng/wagtail
wagtail/wagtailadmin/menu.py
Python
bsd-3-clause
4,777
0.002303
from __future__ import unicode_literals from django.forms import MediaDefiningClass, Media from django.forms.utils import flatatt from django.utils.text import slugify from django.utils.safestring import mark_safe from django.utils.six import text_type from django.utils.six import with_metaclass from wagtail.utils.c...
rl'
: self.url, 'classnames': self.classnames, 'attr_string': self.attr_string, 'menu_html': self.menu.render_html(request), 'label': self.label, 'request': request, 'active': self.is_active(request) }, request=request) admin_menu = Menu(regi...
atruberg/django-custom
tests/model_validation/models.py
Python
bsd-3-clause
614
0
from django.db import models class ThingItem(object): def __init__(self, value, display): self.value = value self.display = display def __iter__(self):
return (x for x in [self.value, self.display]) def __len__(self): return 2 class Things(object): def __iter__(self): return (x for x in [ThingItem(1, 2), ThingItem(3, 4)]) class ThingWithIterableChoices(models.Model): # Testing choices= Iterable of Iterables # See: https://co...
hansomesong/First_LISP_measurement
LISP-Sonar.py
Python
gpl-2.0
9,113
0.006145
#!/usr/bin/python # # $Id: LISP-Sonar.py 18 2014-10-06 13:23:37Z ggx $ # # -------------------------------Important Marks------------------------------- # Surprisingly, we found that when manually executing the current Python script, # the point symbol in file path is recognized,but not recognized when called via NEPI...
["DirsConfig"]["EIDListDirectory"].replace("$CURRENTDIR", CURRENTDIR) EIDListFile = Cfg["DirsConfig"]["EIDListFile"] SpawnTimeGap = Cfg["ThreadSpawn"]["TimeGap"] SpawnRandomization = Cfg["ThreadS
pawn"]["Randomization"] SpawnMaxThreads = Cfg["ThreadSpawn"]["MaxThreads"] LIGRequestTimeOut = Cfg["Lig"]["TimeOut"] LIGMaxRetries = Cfg["Lig"]["MaxTries"] LIGSrcAddr = Cfg["Lig"]["SourceAddress"] except KeyError: print '=====> Exiting! Configuration Error for '+str(sys.exc_value)+' in file '+Confi...
vorwerkc/pymatgen
pymatgen/io/abinit/tests/test_abiobjects.py
Python
mit
7,463
0.000804
# Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import os import warnings from pymatgen.core.structure import Structure from pymatgen.core.units import Ha_to_eV, bohr_to_ang from pymatgen.io.abinit.abiobjects import * from pymatgen.util.testing import PymatgenTest class ...
atoms_and_cell.to_abivars() # Test dict methods self.assertMSONable(atoms_and_cell) self.assertMSONable(atoms_only) class PPModelTest(PymatgenTest): def test_base(self): godby = PPModel.as_ppmodel("godby:12 eV") # print(godby) # print(repr(godby)) godby.to...
noppm = PPModel.get_noppmodel() self.assertFalse(noppm) self.assertTrue(noppm != godby) new_godby = PPModel.from_dict(godby.as_dict()) self.assertTrue(new_godby == godby) # Test pickle self.serialize_with_pickle(godby) # Test dict methods self.asser...
chienlieu2017/it_management
odoo/addons/point_of_sale/__manifest__.py
Python
gpl-3.0
2,501
0.0012
# -*- coding: utf-8 -*- # Part of Odoo. See LICEN
SE file for full copyright and licensing details. { 'name': 'Point of Sale', 'version': '1.0.1', 'category': 'Point Of Sale', 'sequence': 20, 'summary
': 'Touchscreen Interface for Shops', 'description': """ Quick and Easy sale process =========================== This module allows you to manage your shop sales very easily with a fully web based touchscreen interface. It is compatible with all PC tablets and the iPad, offering multiple payment methods. Product ...
zzz14/LOST-FOUND
wechat/wrapper.py
Python
gpl-3.0
10,069
0.002582
# -*- coding: utf-8 -*- # import datetime import hashlib import json import logging import random import string import time import urllib.request import xml.etree.ElementTree as ET from LostAndFound.settings import WECHAT_TOKEN, WECHAT_APPID, WECHAT_SECRET from django.http import Http404, HttpResponse from django.temp...
def reply_single_news(self, article): return self.reply_news([article]) def get_message(self, name, **data): if name.endswith('.html'): name = name[: -5] return get_template('
messages/' + name + '.html').render(dict( handler=self, user=self.user, **data )) def is_msg_type(self, check_type): return self.input['MsgType'] == check_type def is_text(self, *texts): return self.is_msg_type('text') and (self.input['Content'].lower() in texts) def i...
felix-dumit/campusbot
yowsup2/yowsup/layers/protocol_ib/layer.py
Python
mit
861
0.002323
from yowsup.layers import YowLayer, YowLayerEvent, YowProtocolLayer from .protocolentities import * class YowIbProtocolLayer(YowProtocolLayer): def __init__(self): handleMap = { "ib": (self.recvI
b, self.sendIb), "iq": (None, self.sendIb) } super(YowIbProtocolLayer, self).__init__(handleMap) def __str__(self): return "Ib Layer" def sendIb(self, entity): if enti
ty.__class__ == CleanIqProtocolEntity: self.toLower(entity.toProtocolTreeNode()) def recvIb(self, node): if node.getChild("dirty"): self.toUpper(DirtyIbProtocolEntity.fromProtocolTreeNode(node)) elif node.getChild("offline"): self.toUpper(OfflineIbProtocolEntity....
nesdis/djongo
tests/django_tests/tests/v22/tests/admin_scripts/app_waiting_migration/migrations/0001_initial.py
Python
agpl-3.0
434
0.002304
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel(
name='Bar',
fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ], ), ]
johntellsall/shotglass
dec/test_release.py
Python
mit
380
0
import datetime import release def test_release(): rel = release.Release("mysql-3.23.22-beta", "1234-05-06") print(vars(rel)) assert vars(rel) == { "raw_label": "mysql-3.23.22-beta", "raw_date": "1234-05-06", "majormin": "3.23", "pre": "mysql-", "pos
t": ".22-beta", "date": datetime.datetime(1234, 5, 6, 0, 0), }
lycheng/leetcode
others/count_primes.py
Python
mit
488
0
# -*- coding: utf-8 -*- class Solution(object): ''' https://leetcode.com/problems/c
ount-primes/ ''' def countPrimes(self, n): if n <= 2: return 0 is_prime = [True] * n ret = 0 for i in range(2, n): if not is_prime[i]: continue ret += 1 for m in range(2, n): if i * m >= n:
continue is_prime[i*m] = False return ret
cornell-brg/pymtl
pymtl/tools/integration/systemc_tests/sequential/RegIncrSC.py
Python
bsd-3-clause
446
0.049327
#======================================================
================= # RegIncrSC.py #======================================================================= from pymtl import * class RegIncrSC( SystemCModel ): sclinetrace = True def __init__( s ): s.in_ = InPort ( Bits(32) ) s.out = OutPort( Bits(32) ) s.set_ports({ "clk" : s.clk, ...
, "out" : s.out, })
nacc/autotest
client/tests/btreplay/btreplay.py
Python
gpl-2.0
4,454
0.003368
import time, os from autotest.client import test, os_dep, utils from autotest.client.shared import error class btreplay(test.test): version = 1 # http://brick.kernel.dk/snaps/blktrace-git-latest.tar.gz def setup(self, tarball = 'blktrace-git-latest.tar.gz'): tarball = utils.unmap_url(self.bindir,...
].strip('sytem').split(':') e = words[2].strip('elapsd').split(':') break systime = 0.0 for n in range(len(s)): i = (len(s)-1) - n systime += float(s[i]) * (60**n) elapsed = 0.0 for n in range(len(e)): i = (len(e)-1) - ...
line.split() if len(words) < 3: continue if words[0] == 'Q2C': q2c = float(words[2]) break self.write_perf_keyval({'time':elapsed, 'systime':systime, 'avg_q2c_latency':q2c})
lidan-fnst/samba
source4/torture/drs/python/replica_sync.py
Python
gpl-3.0
36,840
0.004642
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Tests various schema replication scenarios # # Copyright (C) Kamen Mazdrashki <kamenim@samba.org> 2011 # # 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 Fou...
res1 = self.ldb_dc2.search(base="<GUID
=%s>" % self.ou1, scope=SCOPE_BASE, attrs=["name"]) res2 = self.ldb_dc2.search(base="<GUID=%s>" % self.ou2, scope=SCOPE_BASE, attrs=["name"]) print res1[0]["name"][0] print res2[0]["name"][0] self.assertFalse('CNF:%s' % ...
ktan2020/legacy-automation
win/Lib/ntpath.py
Python
mit
18,605
0.002634
# Module 'ntpath' -- common operations on WinNT/Win95 pathnames """Common pathname manipulations, WindowsNT/95 version. Instead of importing this module directly, import os and refer to this module as os.path. """ import os import sys import stat import genericpath import warnings from genericpath impor...
pathname.
Makes all characters lowercase and all slashes into backslashes.""" return s.replace("/", "\\").lower() # Return whether a path is absolute. # Trivial in Posix, harder on the Mac or MS-DOS. # For DOS it is absolute if it starts with a slash or backslash (current # volume), or if a pathname after the volu...
richardcardona/learnpython-exercises
dirhelp.py
Python
apache-2.0
75
0.013333
#!/usr/bin/python import ur
llib print dir(urllib) hel
p(urllib.urlopen)
ilpianista/ansible
test/support/integration/plugins/modules/azure_rm_mariadbdatabase_info.py
Python
gpl-3.0
6,304
0.001904
#!/usr/bin/python # # Copyright (c) 2017 Zim Kalinowski, <zikalino@microsoft.com> # Copyright (c) 2019 Matti Ranta, (@techknowlogick) # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type AN...
self.log("Response : {0}".format(response)) except CloudError as e: self.fail("Error listing for server {0} - {1}".format(self.server_name, str(e))) if response is not None: for item in response: results.append(self.format_item(item)) return results ...
: d['name'], 'charset': d['charset'], 'collation': d['collation'] } return d def main(): AzureRMMariaDbDatabaseInfo() if __name__ == '__main__': main()
hmpf/nav
python/nav/web/messages/urls.py
Python
gpl-3.0
1,573
0.000636
# # Copyright (C) 2013 Uninett AS # # This file is part of Network Administration Visualized (NAV). # # NAV is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License version 3 as published by # the Free Software Foundation. # # This program is distributed in the hope...
url(r'^scheduled/$', views.planned, name='messages-planned'), url(r'^archive/$', views.historic, name='messages-historic'), url(r'^view/(?P<message_id>\d+)$', views.view, name='messages-view'), url(r'^expire/(?P<message_id>\d+)$', views.expire, name='messages-expire'), url(r'^followup/(?P<message_id...
MessagesFeed(), name='messages-rss'), ]
jpflori/mpir
yasm/tools/python-yasm/pyxelator/node.py
Python
gpl-3.0
8,966
0.019295
#!/usr/bin/env python """ cdecl.py - parse c declarations (c) 2002, 2003, 2004, 2005 Simon Burton <simon@arrowtheory.com> Released under GNU LGPL license. version 0.xx """ import string class Node(list): " A node in a parse tree " def __init__(self,*items,**kw): list.__init__( self, items ) ...
#assert node0 is not node1 #assert _node == self return _node # Done !! node = nodes[-1] items = itemss[-1] items.append(_node) # set idxs[-1] += 1
assert idxs[-1] == len(items) #assert idxs[-1] < len(node), str( (node,nodes,idxs,itemss) ) _node = node[ idxs[-1] ] # while idxs[-1]<len(node): if isinstance(_node,Node): # push nodes.append( _node ) idxs.app...
jfoote/vulture
vlib/analyzers/reproducibility.py
Python
mit
2,072
0.005309
import json, logging, os, re, subprocess, shlex from tools import get_category_by_status log = logging.getLogger() meta_files = ['Disassembly', 'Stacktrace', 'Registers', 'SegvAnalysis', 'ProcMaps', "BootLog" , "CoreDump", "BootDmesg", "syslog", "UbiquityDebug.gz", "Casper.gz", "UbiquityPar...
till interested out =
subprocess.check_output(["file", fpath]) ftype = out.split(":")[-1] if ftype.strip() == "empty": continue for tstr in ["ASCII", "text", "core file"]: if tstr in ftype: break else: # only runs...
chouseknecht/ansible-container
container/k8s/base_config.py
Python
lgpl-3.0
932
0.001073
# -*- coding: utf-8 -*- from __future__ import absolute_import from ..config import BaseAnsibleContainerConfig from ..utils.visibility import getLogger logger = getLogger(__name__) class K8sBaseConfig(BaseAnsibleContainerConfig): @property def image_namespace(self):
namespace = self.project_name if self._config.get('settings', {}).get('k8s_namespace', {}).get('name'): namespace = self._config['settings']['k8s_namespace']['name'] return namespace def set_env(self, env): super(K8sBaseConfig, self).set_env(env) if self._config.get('v...
for engine_name in self.remove_engines: if engine_name in self._config['volumes'][vol_key]: del self._config['volumes'][vol_key][engine_name]
rldotai/deepy
deepy/layers/recurrent.py
Python
mit
6,446
0.003258
#!/usr/bin/env python # -*- coding: utf-8 -*- from . import NeuralLayer from deepy.utils import build_activation, FLOATX import numpy as np import theano import theano.tensor as T from collections import OrderedDict OUTPUT_TYPES = ["sequence", "one"] INPUT_TYPES = ["sequence", "one"] class RNN(NeuralLayer): """ ...
= vector_core self._input_init = input_init self.persistent_state = persistent_state self.reset_state_for_input = reset_state_for_input self.batch_size = batch_size self._steps = steps self._go_backwards = go_backwards self._mask = mask.dimshuffle((1,0)) if mask ...
T_TYPES: raise Exception("Input type of RNN is wrong: %s" % input_type) if output_type not in OUTPUT_TYPES: raise Exception("Output type of RNN is wrong: %s" % output_type) if self.persistent_state and not self.batch_size: raise Exception("Batch size must be set for p...
philanthropy-u/edx-platform
common/djangoapps/util/testing.py
Python
agpl-3.0
6,042
0.001159
""" Utility Mixins for unit tests """ import json import sys from django.conf import settings from django.urls import clear_url_caches, resolve from django.test import TestCase from mock import patch from util.db import CommitOnSuccessManager, OuterAtomic class UrlResetMixin(object): """Mixin to reset urls.py ...
_count += 1 self.assertEqual(actual_count, expected_count) def reset_tracker(self): """ Reset the mock tracker in order to forget about old events. """ self.mock_tracker.reset_mock() def get_l
atest_call_args(self): """ Return the arguments of the latest call to emit. """ return self.mock_tracker.emit.call_args[0] class PatchMediaTypeMixin(object): """ Generic mixin for verifying unsupported media type in PATCH """ def test_patch_unsupported_media_type(self):...
Yayg/rift
tests/Acceptance_Tests/main.py
Python
mit
97
0
#! /u
sr/bin/env python2 import rift rift.init("main.so") print(rift.call(lib.main, rift.c_in
t))
greggy/pylessons
exam12.py
Python
lgpl-2.1
2,149
0.005573
# -*- coding: utf-8 -*- # -------------------------------------------------- # Задача 1 # -------------------------------------------------- """ Напишите функцию-генератор, которая будет принимать последовательность, где каждый элемент кортеж с двумя значениями (длинна катетов треугольника) и возвращать длинну гипотен...
----- # Задача 5 # -------------------------------------------------- """ Перепишите функции из задач 3 и 4 так, чтобы они стали генераторами. """ def myfilter2(fun, l): pass def myreduce21(fun, l): pass # -----------------
--------------------------------- # Задача 6 # -------------------------------------------------- """ Перепишите вашу реализацию функций filter и map из урока так, чтоб вторым аргументом принималось любое количество последовательностей. """
pre-commit/pre-commit
pre_commit/languages/coursier.py
Python
mit
2,157
0
from __future__ import annotations import contextlib import os from typing import Generator from typing import Sequence from pre_commit.envcontext import envcontext from pre_commit.envcontext import PatchesT from pre_commit.envcontext import Var from pre_commit
.hook import Hook from pre_commit.languages import helpers from pre_commit.prefix import Prefix from pre_commit.util import clean_path_on_failure ENVIRONMENT_DIR = 'coursier' get_default_version = helpers.basic_get_default_version healthy = helpers.basic_healthy
def install_environment( prefix: Prefix, version: str, additional_dependencies: Sequence[str], ) -> None: # pragma: win32 no cover helpers.assert_version_default('coursier', version) helpers.assert_no_additional_deps('coursier', additional_dependencies) envdir = prefix.path(help...
ColumbiaCMB/kid_readout
kid_readout/equipment/record_all_old.py
Python
bsd-2-clause
2,287
0.006996
import time import threading import logging import serial import io import sim900 import sys if __name__ == "__main__": #this is a bad file for recording the diode temps and voltages #eventually it will be merged with recording the resistance bridges #and actually use the sim900 file functions #cre...
sistance() rox1_temp = sim.get_temp() sim.close_sim921_1() print "rox1" time.sleep(1) sim.connect_sim921() rox2_res = sim.get_resistance() rox2_temp
= sim.get_temp() sim.close_sim921() #get rox3 info sim.connect_sim921_6() rox3_res = sim.get_resistance() rox3_temp = sim.get_temp() sim.close_sim921_6() print "rox2" time.sleep(1) #write it all to file ...
igboyes/virtool
tests/subtractions/test_files.py
Python
mit
775
0
import virtool.subtractions.files from sqlalchemy import select from virtool.subtractions.models import SubtractionFile async def test_create_subtraction_files(snapshot
, tmp_path, pg, pg_session): test_dir = tmp_path / "subtractions" / "foo" test_dir.mkdir(parents=True) test_dir.joinpath("subtraction.fa.gz").write_text("FASTA file") test_dir.joinpath("subtractio
n.1.bt2").write_text("Bowtie2 file") subtraction_files = ["subtraction.fa.gz", "subtraction.1.bt2"] await virtool.subtractions.files.create_subtraction_files( pg, "foo", subtraction_files, test_dir ) rows = list() async with pg_session as session: assert ( await sessio...
plotly/python-api
packages/python/plotly/plotly/validators/layout/_violinmode.py
Python
mit
516
0.001938
import _plotly_utils.basevalidators class ViolinmodeValidator(_plotly_utils.basevalidators.EnumeratedValidator): de
f __init__(self, plotly_name="violinmode", parent_name="layout", **kwargs): super(ViolinmodeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "info"), values=...
**kwargs )
dwwkelly/configs
srv/salt/laptop/config/ipython/profile_default/ipython_qtconsole_config.py
Python
gpl-2.0
23,719
0.003289
# Configuration file for ipython-qtconsole. c = get_config() #------------------------------------------------------------------------------ # IPythonQtConsoleApp configuration #------------------------------------------------------------------------------ # IPythonQtConsoleApp will inherit config from: BaseIPythonA...
and 'rich', which specifies a QTextEdit. # c.IPythonWidget.kind = 'plain' # Whether to ask for user confirmation when restarting ke
rnel # c.IPythonWidget.confirm_restart = True # The font size. If unconfigured, Qt will be entrusted with the size of the # font. # c.IPythonWidget.font_size = 0 # The editor command to use when a specific line number is requested. The string # should contain two format specifiers: {line} and {filename}. If this para...
DESHRAJ/fjord
fjord/base/views.py
Python
bsd-3-clause
6,831
0
import logging import socket from functools import wraps from django.conf import settings from django.http import ( Http404, HttpResponse, HttpResponseForbidden, HttpResponseRedirect ) from django.shortcuts import render from django.utils.http import is_safe_url from django.views.decorators.cache impor...
xc)) return False finally: s.close() def dev_or_authorized(func): """Show view for admin and developer instances, else 404""" @wraps(func) def _dev_or_authorized(request, *args, **kwargs): if
(request.user.is_superuser or settings.SHOW_STAGE_NOTICE or settings.DEBUG): return func(request, *args, **kwargs) raise Http404 return _dev_or_authorized ERROR = 'ERROR' INFO = 'INFO' @dev_or_authorized @never_cache def monitor_view(request): """View f...
trdean/grEME
gr-video-sdl/python/video_sdl/__init__.py
Python
gpl-3.0
1,138
0.004394
# Copyright 2012 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. # ...
pe 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 Public License # along with GNU Radio; see the file COPYING. ...
turns this directory into a Python package import os try: from video_sdl_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from video_sdl_swig import *
JayvicWen/Crawler
3che/crawler.py
Python
mit
4,816
0.004156
#!/usr/bin/env python #encoding:utf-8 import os import sys import requests import MySQLdb from bs4 import BeautifulSoup from bs4 import SoupStrainer if len(sys.argv) != 4: print 'Invalid parameters!' exit(1) print '=' * 60 print 'start:', sys.argv aim_category_id = int(sys.argv[1]) start_point = (int(sys.ar...
20 == 0: if connection: connection.commit() connection.close() cursor.close() connection = MySQLdb.connect(host='', user='', passwd='', db='', port=3306, charset='utf8') cursor = connection.cursor() sql_cnt += 1 cursor.execute('insert into san_che(`c...
ecord['url'])) def login(): login_path = '/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1' session.post(base_url + login_path, {'username': username, 'password': password}) def enter_directory(name): if immediate_download: if not os.path.exists(name): ...
srohatgi/cloud
huntnet/manage.py
Python
apache-2.0
250
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os
.environ.setdefault("DJANGO_SETTINGS_MODULE", "huntnet.settings") from django.core.management import execute_from_command_li
ne execute_from_command_line(sys.argv)
edofic/ggrc-core
src/ggrc_risks/models/threat.py
Python
apache-2.0
847
0.004723
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models.mixins import CustomAttributable, BusinessObject, Timeboxed from ggrc.models.object_document import Documentable from ggrc.models.object_person import Personable from ggr...
ct, db.Model
): __tablename__ = 'threats' _aliases = { "contact": { "display_name": "Contact", "filter_by": "_filter_by_contact", }, "secondary_contact": None, "url": "Threat URL", }
mozillazg/chendian-plus
chendian/member/migrations/0008_auto_20150502_1013.py
Python
mit
697
0.002869
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('member', '0007_auto_20150501_2
124'), ] operations = [ migrations.AddField( model_name='member', name='avatar', field=models.URLField(default='https://dn-tmp.qbox.me/chendian/cat_mouse_reading.jpg', verbose_name='\u5934\u50cf', blank=True), ), migrations.AlterField( mod...
s.TextField(default='', verbose_name='\u4e2a\u4eba\u4ecb\u7ecd', blank=True), ), ]
MattD830/Python-INFO1-CE9990
graphpaper2.py
Python
gpl-3.0
968
0.007231
""" I came up with this the first try. So, that's why this is posted in duplicate. """ import sys try: columns = int(input("How many columns? ")) rows = int(input("How many rows? ")) tall = int(input("How tall should the boxes be? "))
wide = int(input("How wide should the boxes be? ")) except Exception as e: print(e) print("You have fail") print("Try type valid integer") sys.exit(1) i = 0 j = 0 k = 0 m = 0 while j <= rows: print("+",end="") while k < columns: while i < wide: print("-",end="") ...
e m < tall: print("|",end="") while k < columns: print(" "*wide,end="") print("|",end="") k += 1 k = 0 m += 1 print("\r") m = 0 j += 1 sys.exit(0)
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractTranslasiSanusiMe.py
Python
bsd-3-clause
550
0.034545
def extractTranslasiSanusiMe(item): ''' Parser for 'translasi.sanusi.me' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'
].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous',
'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
kingvuplus/PKT-gui2
lib/python/Screens/CCcamInfo.py
Python
gpl-2.0
51,455
0.030609
# -*- coding: UTF-8 -*- # CCcam Info by AliAbdul from base64 import encodestring from os import listdir, remove, rename, system, path from enigma import eListboxPythonMultiContent, eTimer, gFont, loadPNG, RT_HALIGN_RIGHT, getDesktop from Components.ActionMap import ActionMap, NumberActionMap from Components.config im...
list): MenuList.__init__(self, list, False, eListboxPythonMultiContent) self.l.setItemHeigh
t(20) self.l.setFont(0, gFont("Regular", 18)) self.l.setFont(1, gFont("Regular", 32)) def CCcamListEntry(name, idx): screenwidth = getDesktop(0).size().width() res = [name] if idx == 10: idx = "red" elif idx == 11: idx = "green" elif idx == 12: idx = "yellow" elif idx == 13: idx = "blue" elif idx ==...
Osmose/normandy
recipe-server/normandy/recipes/migrations/0034_recipe_revisions.py
Python
mpl-2.0
3,780
0.002646
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2016-11-28 13:41 # flake8: noqa from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import normandy.recipes.validators class Migration(mi...
ring': ['-enabled', '-latest_revision__updated']}, ), migrations.RemoveField(
model_name='recipe', name='approval', ), migrations.DeleteModel( name='Approval', ), migrations.DeleteModel( name='ApprovalRequest', ), migrations.DeleteModel( name='ApprovalRequestComment', ), migrati...
OpenTreeOfLife/gcmdr
collect_study_ids.py
Python
bsd-2-clause
537
0.007449
""" Creates a list of studies currently being used for synthesis. """ import re #from stephen_desktop_conf import * from microbes import studytreelist as m
icrobelist from plants import studytreelist as plantslist from metazoa import studytreelist as metalist from fungi import studytreelist as fungilist studytreelist = [] studytreelist.extend(plantslist) studytreelist.extend(metalist) studytreelist.extend(fungilist) studytreelist.extend(microbelist) for i in studytreeli...
int studyid+".json"
Intel-bigdata/swift
test/unit/common/test_client.py
Python
apache-2.0
15,155
0.000264
# Copyright (c) 2010-2011 OpenStack, LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
eption(unittest.TestCase): def test_is_exception(self):
self.assertTrue(issubclass(c.ClientException, Exception)) def test_format(self): exc = c.ClientException('something failed') self.assertTrue('something failed' in str(exc)) test_kwargs = ( 'scheme', 'host', 'port', 'path', 'q...
epam/DLab
infrastructure-provisioning/src/general/scripts/os/jupyter_dataengine_create_configs.py
Python
apache-2.0
7,919
0.003283
#!/usr/bin/python # ***************************************************************************** # # Copyright (c) 2016, EPAM SYSTEMS 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 # #...
affe/python:/home/{2}/pytorch/build:\"|\' > /tmp/{0}/kernel_var.json". format(args.cluster_name, kernel_path, args.os_user)) local('sudo mv /tmp/{}/kernel_var.json '.format(args.cluster_name) + kernel_path) local('mkdir -p ' + ke
rnels_dir + 'py3spark_' + args.cluster_name + '/') kernel_path = kernels_dir + "py3spark_" + args.cluster_name + "/kernel.json" template_file = "/tmp/{}/pyspark_dataengine_template.json".format(args.cluster_name) with open(template_file, 'r') as f: text = f.read() text = text.replace('CLUSTER_NA...
LumPenPacK/NetworkExtractionFromImages
win_build/nefi2_win_amd64_msvc_2015/site-packages/networkx/algorithms/approximation/tests/test_dominating_set.py
Python
bsd-2-clause
2,410
0
#!/usr/bin/env python from nose.tools import ok_ from nose.tools import eq_ import networkx as nx from networkx.algorithms.approximation import min_weighted_dominating_set from networkx.algorithms.approximation import min_edge_dominating_set class TestMinWeightDominatingSet: def test_min_weighted_dominating_set(...
0: 9, 9: 0}) eq_(min_weighted_dominating_set(G), {9}) def test_min_edge_dominating_set(self): graph = nx.path_graph(5) dom_set = min_edge_dominating_set(graph) # this is a crappy way to test, but good enough for now. for edge in graph.edges_iter(): if edge in do...
r dom_edge in dom_set: found |= u == dom_edge[0] or u == dom_edge[1] ok_(found, "Non adjacent edge found!") graph = nx.complete_graph(10) dom_set = min_edge_dominating_set(graph) # this is a crappy way to test, but good enough for now. for edge in gr...
kevcooper/bitcoin
test/functional/blockchain.py
Python
mit
5,880
0.00068
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test RPCs related to blockchainstate. Test the following RPCs: - gettxoutsetinfo - getdifficul...
h = node.getblockhash(199) header = node.getblockheader(besthash) assert_equal(header['hash'], besthash) assert_equal(header['height'], 200) assert_equal(header['confirmations'], 1) assert_equal(header['previousblockhash'],
secondbesthash) assert_is_hex_string(header['chainwork']) assert_is_hash_string(header['hash']) assert_is_hash_string(header['previousblockhash']) assert_is_hash_string(header['merkleroot']) assert_is_hash_string(header['bits'], length=None) assert isinstance(header['tim...
NewpTone/stacklab-cinder
cinder/tests/fake_flags.py
Python
apache-2.0
1,721
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compli...
Driver') conf.set_default('connection_type', 'fake') conf.set_default('fake_rabbit', True) conf.set_default('rpc_backend', 'cinder.openstack.common.rpc.impl_fake') conf.set_default('iscsi_num_targets', 8) conf.set_default('verbose', Tru
e) conf.set_default('sql_connection', "sqlite://") conf.set_default('sqlite_synchronous', False) conf.set_default('policy_file', 'cinder/tests/policy.json') conf.set_default('xiv_proxy', 'cinder.tests.test_xiv.XIVFakeProxyDriver')
BenHewins/influxdb-python
influxdb/tests/server_tests/base.py
Python
mit
2,621
0
# -*- coding: utf-8 -*- """Define the base module for server test.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import sys from influxdb.tests import using_pypy from influxdb.tests.server_tests.influxdb_instanc...
b.dataframe_client import DataFrameClient def _setup_influxdb_server(inst): inst.influxd_inst = InfluxDbInstance( inst.influxdb_template_conf, udp_enabled=getattr(inst, 'influxdb_udp_enabled', False), ) inst.cli = InfluxDBClient('localhost', inst.influxd_inst...
if not using_pypy: inst.cliDF = DataFrameClient('localhost', inst.influxd_inst.http_port, 'root', '', database='db') def _teardown_influxdb_server(inst): ...
facetothefate/contrail-controller
src/analytics/test/utils/mockredis/mockredis/mockredis.py
Python
apache-2.0
5,634
0.002662
#!/usr/bin/env python # # Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. # # # mockredis # # This module helps start and stop redis instances for unit-testing # redis must be pre-installed for this to work # import os import signal import subprocess import logging import socket import time import red...
me.sleep(1) else: done = True logging.info('Redis ready') return True def stop_redis(port, password=None): ''' Client uses this function to stop an instance of redis This will only work for redis instances that were started by this module Arguments: cport : The Clien...
Redis(host='localhost', port=port, db=0, password=password) r.shutdown() del r redisbase = "/tmp/redis.%s.%d/" % (os.getenv('USER', 'None'), port) output, _ = call_command_("rm -rf " + redisbase) def replace_string_(filePath, findreplace): "replaces all findStr by repStr in file filePath" print...
githubfun/lphw
gothonweb/bin/gothon_app.py
Python
mit
1,131
0.005305
import web from gothonweb import map urls = ( '/game', 'GameEngine', '/', 'Index', ) app = web.application(urls, globals()) #little hack so that debug mode works with sessions if web.config.get('_session') is None: store = web.session.DiskStore('sessions') session = web.session.Session(app, store, ...
if session.room:
session.room = session.room.go(form.action) web.seeother("/game") if __name__ == "__main__": app.run()
benschmaus/catapult
dashboard/dashboard/dump_graph_json.py
Python
bsd-3-clause
6,621
0.005437
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a web interface for dumping graph data as JSON. This is meant to be used with /load_from_prod in order to easily grab data for a graph to a loca...
DumpAnomalyDataForSheriff(self): """Dumps Anomaly data for all sheriffs. Request parameters: sheriff: Sheriff name. num_points: Max number of Row entities (optional). num_alerts: Ma
x number of Anomaly entities (optional). Outputs: JSON array of encoded protobuf messages, which encode all of the datastore entities relating to one test (including Master, Bot, TestMetadata, Row, Anomaly and Sheriff entities). """ sheriff_name = self.request.get('sheriff') num_point...
cjaymes/pyscap
src/scap/model/oval_5/sc/unix/EntityItemEncryptMethodType.py
Python
gpl-3.0
1,167
0.001714
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP 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. # # PySCAP is ...
be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PAR
TICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PySCAP. If not, see <http://www.gnu.org/licenses/>. import logging from scap.model.oval_5.sc.EntityItemType import EntityItemType logger = logging.getLogger(__n...
ZeitOnline/zeit.content.gallery
setup.py
Python
bsd-3-clause
1,113
0
from setuptools import setup, find_packages setup( name='zeit.content.gallery', version='2.9.2.dev0', author='gocept, Zeit Online', author_email='zon-backend@zeit.de', url='http://www.zeit.de/', description="vivi Content-Type Portraitbox", packages=find_packages('src'), package_dir={''...
.interface', 'zope.publisher', 'zope.security', 'zope.testing', ], entry_points={ 'fanstatic.libraries': [ 'zeit_content_gallery=zeit.content.gallery.brows
er.resources:lib', ], }, )
ioanpocol/superdesk-ntb
server/ntb/scanpix/scanpix_datalayer.py
Python
agpl-3.0
13,055
0.001762
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014, 2015, 2016 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license ...
'subscription': # small hack for SDNTB-250 data['subscription'] = 'punchcard' for criterion in req.get('post_filter', {}).get('and', {}): if 'range' in cr
iterion: start = None end = None filter_data = criterion.get('range', {}) if 'firstcreated' in filter_data: created = criterion['range']['firstcreated'] if 'gte' in created: start = created['...
Clinical-Genomics/scout
scout/commands/base.py
Python
bsd-3-clause
4,404
0.001589
"""Code for CLI base""" import logging import pathlib import click import coloredlogs import yaml from flask.cli import FlaskGroup, with_appcontext # General, logging from scout import __version__ from scout.commands.convert import convert from scout.commands.delete import delete from scout.commands.download import d...
.find_root().params.get("loglevel") log_format = None coloredlogs.install(level=log_level, fmt=log_format) LOG.info("Running scout version %s
", __version__) LOG.debug("Debug logging enabled.") @click.pass_context def get_app(ctx=None): """Create an app with the correct config or with default app params""" loglevel() # Set up log level even before creating the app object # store provided params into a options variable options = ctx.f...
enoex/kafka-python
setup.py
Python
apache-2.0
404
0
from distutils.core import setup setup( name="kafka-python", version=
"0.1-alpha", author="David Arthur", au
thor_email="mumrah@gmail.com", url="https://github.com/mumrah/kafka-python", packages=["kafka"], license="Copyright 2012, David Arthur under Apache License, v2.0", description="Pure Python client for Apache Kafka", long_description=open("README.md").read(), )
InTraffic/TSTK
TSTK/dispatcher.py
Python
gpl-3.0
20,467
0.004886
import logging import signal import socket import configparser import importlib.machinery import serial import copy import zmq class Dispatcher(object): """ Superclass for all Dispatchers. This is the part of the simulator that handles the connections. """ def __init__(self, dispatcher_type, dispatche...
ss for Serial connections""" SERIAL_PARITY = {'none':serial.PARITY_NONE , 'even':serial.PARITY_EVEN , 'odd':serial.PARITY_ODD , 'mark':serial.PARITY_MARK , 'space':serial.PARITY_SPACE} SERIAL_STOPBITS= {'one':serial.STOPBITS_ONE ,
'onePointFive': serial.STOPBITS_ONE_POINT_FIVE, 'two':serial.STOPBITS_TWO } default_timeout = 60000 def __init__(self, dispatcher_type, dispatcher_id): Dispatcher.__init__(self, dispatcher_type, dispatcher_id) self.repeater_socket = None ...
biomodels/BIOMD0000000045
BIOMD0000000045/model.py
Python
cc0-1.0
427
0.009368
import os path = os.path.dirname(os.path.realpath(__file__)) sbmlFilePath = os.path.join(path, 'BIOMD0000000045.xml') with open(sbmlFilePath,'r') as f: sbmlString = f.read() def module_exists(module_name): try: __import__(module_name) except Imp
ortError: return False else: return True if module_exists('libsbml'): import
libsbml sbml = libsbml.readSBMLFromString(sbmlString)
luo2chun1lei2/AgileEditor
vc/src/ViewLog.py
Python
gpl-2.0
6,715
0.010425
#-*- coding:utf-8 -*- ''' 显示命令的输出结果。 ''' import threading from gi.repository import Gtk, Gdk, GObject, GLib, GtkSource, Pango from VcEventPipe import * class ViewLog: ''' 显示日志。 1,来了新命令,是否更新当前的日志。 2,命令来了新的日志,并显示后,是否滚动。 ''' # 设定一个栏目的枚举常量。 ( COLUMN_TAG_LINE_NO, # 行号 COLUMN_TAG...
O:没有移动到最后) editor.scroll_to_iter(iter_, 0.25, False
, 0.0, 0.5)
ParuninPavel/lenta4_hack
vkapp/bot/dao/newsDAO.py
Python
mit
1,222
0.005728
from vkapp.bot.models import Blogger, News, AdminReview, Publication from .usersDAO import get_or_create_blogger from datetime import datetime, timedelta, time def new_news(link, media, uid, pic): blogger = get_or_create_blogger(uid) news = News(link=link, blogger=blogger, media=media, pic=pic) news.save(...
datetime.combine(today, time()) today_end = datetime.combine(tomorrow, time()) news = News.objects.filter(blogger__vk_user__vk_id=uid).filter(date_time__lte=today_end, da
te_time__gte=today_start) return news def news_by_blogger(uid): blogger = get_or_create_blogger(uid) news = News.objects.filter(blogger=blogger) return news def get_news_review_rating(news): review = AdminReview.objects.filter(news=news) if len(review)==0: return 0 else: re...
chteuchteu/Freebox-OS-munin
fields.py
Python
gpl-2.0
4,648
0.000215
from modes import * # mode_traffic field_rate_down = 'rate_down' field_bw_down = 'bw_down' field_rate_up = 'rate_up' field_bw_up = 'bw_up' # mode_temp field_cpum = 'cpum' field_cpub = 'cpub' field_sw = 'sw' field_hdd = 'hdd' # mode_fan_speed field_fan_speed = 'fan_speed' # mode_xdsl field_snr_down = 'snr_down' fiel...
cast_packets = 'rx_unicast_packets' field_tx_unicast_packets = 'tx_unicast_packets' field_rx_broadcast_packets = 'rx_broadcast_packets' field_tx_broadcast_packets = 'tx_broadcast_packets' # mode wifi-
stations field_stations = 'stations' # mode wifi-bytes field_wifi_rx_bytes = 'rx_bytes' field_wifi_tx_bytes = 'tx_bytes' fields = { mode_traffic: [ field_rate_down, field_bw_down, field_rate_up, field_bw_up ], mode_temp: [ field_cpum, field_cpub, fie...
Rinoahu/debias
lib/debias.py
Python
gpl-3.0
49,496
0.022204
#!/usr/bin/ """ """ from __future__ import print_function from __future__ import division import networkx as nx import sys from networkx.algorithms import bipartite from operator import itemgetter import matplotlib.pyplot as plt import argparse import pickle as cp import math import numpy as np from numpy import percen...
publications which deal with less than -d <number> of proteins This program creates a bipartite graph with one set as the GO terms and the other set as the references and cross links them with the GO_TERMS as weights to the edges. This function can be used to select a cut off based on number of annota...
nnotated by a reference. It is recommended that the protein cut-off, i.e. -cprot, be used instead of the annotations cutoff. Since it is relevant for a reference to provide more annotations to fewer proteins than to work with a lot of proteins. """ mapping = [] for attnid in data: per_annotation...
Yatekii/backdoor
register_service.py
Python
agpl-3.0
4,477
0.00134
import argparse from models import Service from models import Base import helpers import traceback import sys import os import importlib import shutil @helpers.handle_dbsession() def prepare_service_db(sqlsession, name, desc, models, uses_blueprint): s = sqlsession.query(Service).filter_by(name=name).first() ...
h or len(args.path) < 1: print('Please specify at least one service to import') else: for p in args.path: if register_service(p): print('Successfully registered new service %s' % p)
else: print('Failed to register service %s' % p) # prepare_service_db('basics', 'Basic services and commands', ( # ('text', 'txt', Type.text, '.', (('2345', 'adsd'), ('2345', 'adsd'), ('2345', 'adsd'))), # ('int', 'd', Type.int, '', ()), # ...
Hugoo/Prologin
2008 - Machine/suite.py
Python
mit
678
0.00885
import sys def suite(n,s): p = -1 fin = '' c = 0 for i in range(0,n+1): if i == n: if s[i-1]==p: fin = fin+str(c)+str(p) else: fin = fin+str(c)+str(p) p = s[i] c = 1 break ...
c = 1 else: if s[i]==p: c = c+1 else: fin = fin+str(c)+str(p) p = s[i] c = 1 print fin return if __name__ == '_
_main__': n = int(raw_input()) s = raw_input() suite(n,s)
andreisavu/django-jack
jack/beanstalk/forms.py
Python
apache-2.0
291
0.006873
from django
import forms class PutForm(forms.Form): body = forms.CharField(widget=forms.Textarea()) tube = forms.CharField(initial='
default') priority = forms.IntegerField(initial=2147483648) delay = forms.IntegerField(initial=0) ttr = forms.IntegerField(initial=120)
knoguchi/druid
docs/_bin/get-milestone-prs.py
Python
apache-2.0
3,551
0.005069
#!/usr/bin/env python3 # 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 "Lic...
search_url = "https://api.github.com/search/issues?q=type:pr+is:merged+is:closed+repo:apache/incubator-druid+SHA:{}" resp = requests.get(search_url.format(commit_id), auth=(github_username, os.environ["GIT_TOKEN"])) resp_json = resp.json() milestone_found = False closed_pr_nums...
ne): print("Could not get PRs for commit ID {}, resp: {}".format(commit_id, resp_json)) continue for pr in resp_json["items"]: closed_pr_nums.append(pr["number"]) milestone = pr["milestone"] if milestone is not None: milestone_found = ...
synthicity/activitysim
activitysim/examples/example_estimation/scripts/infer.py
Python
agpl-3.0
28,331
0.003565
# ActivitySim # See full license in LICENSE.txt. import sys import os import logging import yaml import numpy as np import pandas as pd from activitysim.abm.models.util import tour_frequency as tf from activitysim.core.util import reindex from activitysim.abm.models.util import canonical_ids as cid logger = loggin...
= alts.astype(np.int8) # - NARROW return alts tours = tours[tours.tour_catego
ry == 'non_mandatory'] alts = read_alts() tour_types = list(alts.columns.values) # tour_frequency is index in alts table alts['alt_id'] = alts.index # actual tour counts (may exceed counts envisioned by alts) unconstrained_tour_counts = pd.DataFrame(index=persons.index) for tour_type in t...
samuell/luigi
examples/foo.py
Python
apache-2.0
1,501
0.000666
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
yield Bar(i) class Bar(luigi.Task): task_namespace = 'examples' num = luigi.IntParameter() def run(self): time.sleep(1) self.output().open('w').close() def output(self): """ Returns the target output for this task. :return: the target output for this ...
ect (:py:class:`~luigi.target.Target`) """ time.sleep(1) return luigi.LocalTarget('/tmp/bar/%d' % self.num)
dwt2c/Schoogle
Schoogle/Schoogle/spiders/O_Spider.py
Python
gpl-2.0
3,037
0.029964
from __future__ import absolute_import from scrapy.spiders import Spider from scrapy.selector import Selector from scrapy import Request import sys from Schoogle.items import O_Item from sys import getsizeof from datetime import datetime import time import re mport string def reduce(text): return "".join([c for c in...
sed to flesh out our O_Item object # @yield(1): this returns a single object each time next( this object ) is called # first parse yields all items # @yield(2): this is completed only after we have yielded an object from this webpage, it will # recursively call
parse on all links in a web page def parse(self,response): # here we use scrapy's request object to catch all invalid links when parsing our documnet try: links = response.xpath('//@href').extract() for link in links: try: req = Request(link,callback = self.parse) except ValueError: pass # ...
kylebegovich/ProjectEuler
Python/Solved/Page1/Problem24.py
Python
gpl-3.0
663
0.006033
import math curr = 0 goal = 1000000 potential_nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] output_num = [] if __name__ == '__main__': for i in xrange(10, 0, -1): print (curr, i, "outer loop") for j in xra
nge(i + 1): print (curr, j, "inner loop") temp = math.factorial(i - 1) * j + curr if temp >= goal: print (temp) curr += (math.factorial(i - 1) * (j-1)) print (curr, goal, i, j) output_num.append(potential_nums[j-1]) ...
ak print output_num # SOLVED : 2783915460
open-craft-guild/blueberrypy
src/blueberrypy/config.py
Python
bsd-3-clause
18,173
0.002091
import collections import difflib import inspect import logging import os.path import warnings import os import importlib import cherrypy import yaml from yaml import load try: from yaml import CLoader as Loader except ImportError: from yaml import Loader json = None for pkg in ['ujson', 'yajl', 'simplejson'...
ed to !FirstOf tag must be not None') def _setup_loader(self): self.register_tag('!EnvVar', self._tag_env_var) self.register_tag('!FirstOf', self._tag_first_of) def __init__(self, config_dir=None, app_config=None, logging_config=None, webassets_env=None, environmen...
If `app_config` or `logging_config` or `webassets_env` are given, they will be used instead of the configuration files found from `config_dir`. If `environment` is given, it must be an existing CherryPy environment. If `environment` is `production`, and `config_dir` is given, the `prod` ...
GullyAPCBurns/bolinas
extractor_cansem/extractor_cansem.py
Python
mit
3,342
0.012567
import argparse import sys import os from annotated_set import loadData from data_structures import CanonicalDerivation from canonical_parser import CanonicalParser from derivation_tree import DerivationTree from conversion.ghkm2tib import ghkm2tib #from lib.amr.dag import Dag class ExtractorCanSem: def __init_...
15 -MaxUnalignedRHS 15" % (args.text_path,args.parse_path,
args.align_path) java_opts="-Xmx%s -Xms%s -cp %s/ghkm.jar:%s/lib/fastutil.jar -XX:+UseCompressedOops"%(mem,mem,args.ghkmDir,args.ghkmDir) os.system("java %s edu.stanford.nlp.mt.syntax.ghkm.RuleExtractor %s > %s" % (java_opts,ghkm_opts,args.ghkm_path)) print "Converting GHKM rules to Tiburon for...
insomnia-lab/calibre
src/calibre/gui2/widgets2.py
Python
gpl-3.0
1,547
0.003232
#!/usr/bin/env python # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' from c
alibre.gui2.complete2 import LineEdit from calibre.gui2.widgets import history class HistoryL
ineEdit2(LineEdit): max_history_items = None def __init__(self, parent=None, completer_widget=None, sort_func=lambda x:None): LineEdit.__init__(self, parent=parent, completer_widget=completer_widget, sort_func=sort_func) @property def store_name(self): return 'lineedit_history_'+self....
h3llrais3r/SickRage
sickchill/oldbeard/providers/pretome.py
Python
gpl-3.0
5,958
0.003021
import re import traceback from urllib.parse import quote from requests.utils import dict_from_cookiejar from sickchill import logger from sickchill.helper.common import convert_size, try_int from sickchill.oldbeard import tvcache from sickchill.oldbeard.bs4_parser import BS4Parser from sickchill.providers.torrent.To...
ing("Invalid username or password or pin. Check your settings") return True def login(self): if any(dict_from_cookiejar(self.session.cookies).values()): return True lo
gin_params = {"username": self.username, "password": self.password, "login_pin": self.pin} response = self.get_url(self.urls["login"], post_data=login_params, returns="text") if not response: logger.warning("Unable to connect to provider") return False if re.search("Use...
hj3938/panda3d
direct/src/showbase/Transitions.py
Python
bsd-3-clause
17,107
0.009002
"""Undocumented Module""" __all__ = ['Transitions'] from panda3d.core import * from direct.gui.DirectGui import * from direct.interval.LerpInterval import LerpColorScaleInterval, LerpColorInterval, LerpScaleInterval, LerpPosInterval from direct.interval.MetaInterval import Sequence, Parallel from direct.interval.Func...
= model self.imagePos = pos if model: self.alphaOff = Vec4(1, 1, 1, 0) self.alphaOn =
Vec4(1, 1, 1, 1) model.setTransparency(1) self.lerpFunc = LerpColorScaleInterval else: self.alphaOff = Vec4(0, 0, 0, 0) self.alphaOn = Vec4(0, 0, 0, 1) self.lerpFunc = LerpColorInterval self.irisTaskName = "irisTask" self.fadeTaskName ...
sekikn/ambari
ambari-common/src/main/python/ambari_commons/repo_manager/generic_manager.py
Python
apache-2.0
7,285
0.009746
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this ...
r ignoredRepo in ignore_repos: if self.name_match(ignoredRepo, repo): ignore = True if not ignore: repo_list.append(repo) return repo_list def get_installed_pkgs_by_repo(self, repos, ignore_packages, installed_packages): """ Get all the installed packages from the repos l...
remove = [] for repo in repos: sub_result = [] for item in installed_packages: if repo == item[2]: sub_result.append(item[0]) packages_from_repo = list(set(packages_from_repo + sub_result)) for package in packages_from_repo: keep_package = True for ignorePackage ...
shinznatkid/rupture
rupture/rupture.py
Python
mit
6,405
0.002186
# -*- coding: utf-8 -*- ''' Rupture version 1.4.0 build 5 ''' from bs4 import BeautifulSoup import datetime import requests import socket import pickle import time import ssl from .utils import six from requests.adapters import HTTPAdapter from requests.packages.urllib3.poolmanager import PoolManager cl...
pools=connections, maxsize=maxsize, block=block,
ssl_version=ssl.PROTOCOL_TLSv1) if not getattr(self.session, 'is_patch', False): self.session.is_patch = True self.session.mount('https://', SSLAdapter())
django-de/django-de-v2
django_de/apps/authors/urls.py
Python
bsd-3-clause
348
0.017241
from django.conf.urls.defaults import * from django_de.apps.authors.models import Author urlpatterns = patterns('django.views.generic.list_detail', (r'
^$', 'object_list', dict( queryset = Author.objects.order_by('name', 'slug'), template_object_name = 'author', allow_empty=Tr
ue, ), ) )
seleniumbase/SeleniumBase
examples/github_test.py
Python
mit
1,290
0
from seleniumbase import BaseCase class GitHubTests(BaseCase): def test_github(self): # Selenium can trigger GitHub's anti-automation system: # "You have triggered an abuse detection mechanism." # "Please wait a few minutes before you try again." # To avoid this automation blocker,...
get_new_driver( agent="""Mozilla/5.0 """ """AppleWeb
Kit/537.36 (KHTML, like Gecko) """ """Chrome/Version 96.0.4664.55 Safari/537.36""" ) self.open("https://github.com/search?q=SeleniumBase") self.slow_click('a[href="/seleniumbase/SeleniumBase"]') self.click_if_visible('[data-action="click:signup-prompt#dismiss"]') ...
spacewiki/spacewiki
spacewiki/test/ui_test.py
Python
agpl-3.0
718
0.001393
from spacewiki.app import create_app from spacewiki import model from spacewiki.test import create_test_app import unittest class UiTestCase(unittest.TestCase): def setUp(self): self._app = create_test_app() with self._ap
p.app_context(): model.syncdb() self.app = self._app.test_client() def test_index(self): self.assertEqual(self.app.
get('/').status_code, 200) def test_no_page(self): self.assertEqual(self.app.get('/missing-page').status_code, 200) def test_all_pages(self): self.assertEqual(self.app.get('/.all-pages').status_code, 200) def test_edit(self): self.assertEqual(self.app.get('/index/edit').status_cod...
maru-sama/pyblosxom
Pyblosxom/tests/test_tags.py
Python
mit
2,822
0.003898
####################################################################### #
This file
is part of Pyblosxom. # # Copyright (C) 2010-2011 by the Pyblosxom team. See AUTHORS. # # Pyblosxom is distributed under the MIT license. See the file # LICENSE for distribution details. ####################################################################### import tempfile import shutil import os from Pyblosxom.t...
AlexeyKruglov/Skeinforge-fabmetheus
skeinforge_application/skeinforge_plugins/profile_plugins/winding.py
Python
agpl-3.0
2,079
0.011544
""" This page is in the table of contents. Winding is a script to set the winding profile for the skeinforge chain. The displayed craft sequence is the sequence in which the tools craft the model and export the output. On the winding dialog, clicking the 'Add Profile' button will duplicate the selected profile and gi...
nses/agpl.html' def getCraftSequence(): "Get the winding craft sequence." return 'cleave preface coil flow feed home lash fillet limit unpause alteration export'.split() def getNewRepository(): 'Get new repository.' return WindingRepository() class WindingRepository: "A c
lass to handle the winding settings." def __init__(self): "Set the default settings, execute title & settings fileName." skeinforge_profile.addListsSetCraftProfile( getCraftSequence(), 'free_wire', self, 'skeinforge_application.skeinforge_plugins.profile_plugins.winding.html') def main(): "Display the export di...
Telestream/telestream-cloud-python-sdk
telestream_cloud_qc_sdk/telestream_cloud_qc/models/header_byte_count_test.py
Python
mit
4,912
0
# coding: utf-8 """ Qc API Qc API # noqa: E501 The version of the OpenAPI document: 3.0.0 Contact: cloudsupport@telestream.net Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from telestream_cloud_qc.configuration import Configuration class...
_error': 'reject_on_error', 'checked': 'checked' } def __init__(self, header_bytes=None, reject_on_error=None, checked=None, local_vars_configuration=None): # noqa: E501
"""HeaderByteCountTest - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._header_bytes = None self._reject_on_error = None ...
blaze33/django
tests/regressiontests/views/tests/debug.py
Python
bsd-3-clause
22,564
0.001197
# -*- coding: utf-8 -*- # This coding header is significant for tests, as the debug view is parsing # files to search for such a header to decode the source file content from __future__ import absolute_import, unicode_l
iterals import inspect import os import sys from django.conf import settings from django.core import mail from django.core.files.uploadedfile
import SimpleUploadedFile from django.core.urlresolvers import reverse from django.test import TestCase, RequestFactory from django.test.utils import (override_settings, setup_test_template_loader, restore_template_loaders) from django.utils.encoding import force_text from django.views.debug import ExceptionReport...
Eksmo/calibre
src/calibre/gui2/dialogs/quickview_ui.py
Python
gpl-3.0
3,673
0.003539
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/gugu/w/calibre/src/calibre/gui2/dialogs/quickview.ui' # # Created: Thu Jul 19 23:32:31 2012 # by: PyQt4 UI code generator 4.9.1 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _f...
yout, 3, 0, 1, 2) self.retranslateUi(Quickview) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), Quickview.reject) QtCore.QMetaObject.connectSlotsByName(Quickview) def retranslateUi
(self, Quickview): Quickview.setWindowTitle(_("Quickview")) self.items_label.setText(_("Items")) self.search_button.setText(_("Search")) self.search_button.setToolTip(_("Search in the library view for the selected item"))
gdgellatly/OCB1
addons/web/controllers/main.py
Python
agpl-3.0
69,619
0.003433
# -*- coding: utf-8 -*- import ast import base64 import csv import glob import itertools import logging import operator import datetime import hashlib import os import re import simplejson import time import urllib import urllib2 import urlparse import xmlrpclib import zlib from xml.etree import ElementTree from cStri...
Apache License, Version 2.0 """ def subber(match): """ Substitution callback """ groups = match.groups() return ( groups[0] or groups[1] or groups[2] or groups[3] or (groups[4] and '\n') or (groups[5] and ' ') or ...
s[7] and ' ') or '' ) result = re.sub( r'([^\047"/\000-\040]+)|((?:(?:\047[^\047\\\r\n]*(?:\\(?:[^\r\n]|\r?' r'\n|\r)[^\047\\\r\n]*)*\047)|(?:"[^"\\\r\n]*(?:\\(?:[^\r\n]|\r?\n|' r'\r)[^"\\\r\n]*)*"))[^\047"/\000-\040]*)|(?:(?<=[(,=:\[!&|?{};\r\n]' r')(?:[\000-\01...
jeffrimko/Qprompt
tests/script_test_1.py
Python
mit
3,045
0.004598
"""Test that arguments passed to a script Menu.main(loop=True) execute properly.""" ##==============================================================# ## SECTION: Imports # ##==============================================================# from testlib import * ##===========...
self.assertFalse(op.exists("foo")) self.a
ssertFalse(op.exists("bar")) self.assertFalse(op.exists("caz")) def tearDown(self): self._cleanup() def test_script_1(self): result = os.system("python %s x" % SCRIPT) self.assertEqual(0, result) self.assertFalse(op.exists("foo")) self.assertFalse(op.exists("bar...
SmartElect/SmartElect
register/tests/test_views.py
Python
apache-2.0
21,018
0.001523
from io import StringIO import csv from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from django.core.files.base import ContentFile from django.test import TestCase from django.urls import reverse from django.utils.timezone import now from register.forms impo...
_add_dupe_shows_form_error(self): number = get_random_phone_number() self.factory(phone_number=number) form = self.form(data={'phone_number': number}) self.assertFalse(form.is_valid())
self.assertIn('Duplicate value for phone number', list(form.errors.values())[0]) def test_phone_number_cant_start_with_2180(self): "Ensures the local prefix '0' isn't accidentally included in the phone number" number = '218091234124' form = self.form(data={'phone_number': number}) ...
fake-name/ReadableWebProxy
WebMirror/processor/fonts/FontTables.py
Python
bsd-3-clause
18,234
0.033074
PREDEFINED_FONT_MAPS = { ( (193, 0), (193, 1462), (297, 104), (297, 1358), (930, 104), (930, 1358), (1034, 0), (1034, 1462), ) : {'char' : '�', 'name' : 'glyph00000'}, ( (115, 276), (115, 804), (287, 518), (291, 653), (292, 325), (305, 805), (376, 1116), (396, -20), (462, 977), (477, 125),...
739, 1399), (782, 1532), ) : {'char' : 'f', 'name' : 'glyph00017'}, ( (23, 1096), (197, 1096), (322, 0), (359, 467), (414, 251), (422, 176), (430, 176), (441, 233), (490, 414), (508, 467), (514, 0), (709, 1096), (721, 641), (751, 736), (791, 911), (799, 911), (851, 702), (870, 643), (889, 1...
95), (1161, 178), (1169, 178), (1173, 214), (1208, 364), (1268, 0), (1399, 1096), (1571, 1096), ) : {'char' : 'w', 'name' : 'glyph00018'}, ( (176, -492), (176, 1096), (311, 1096), (330, 141), (334, 946), (342, -492), (342, -41), (342, 45), (342, 141), (342, 318), (342, 549), (342, 586), (342, 9...
niemmi/algolib
algolib/sort/merge_sort.py
Python
bsd-3-clause
2,137
0
"""Two different implementations of merge sort. First one is the standard sort that creates the result to new list on each level. Second one is an in-place sort that uses two alternating buffers and offsets to limit memory usage to O(2n). """ def sort(lst): """Standard merge sort. Args: lst: List to ...
]) return res def helper(lst, buf, start, stop, to_buf): """Helper function for in-place sort with alternating buffers. Args: lst: List to sort buf: Buffer to store the results start: Start index stop: Stop index to_buf: Boolean flag telling w
here result should be written to. In case of True result should be written to buf, if False then result should be written to l. """ length = stop - start if length <= 1: if to_buf and length == 1: buf[start] = lst[start] return mid = start + length //...
Ksynko/django-crm
sample_project/external_apps/ajax_select/setup.py
Python
bsd-3-clause
387
0.005168
#!
/usr/bin/env python from distutils.core import setup setup(name='Ajax Select', version='1.0', description='Django-jQuery jQuery-powered auto-complete fields for ForeignKey and ManyToMany fields', author='Crucial Felix', author_email='crucialfelix@gmail.com', url='http://code.google.com/p...
], )
RichDijk/eXe
exe/engine/package.py
Python
gpl-2.0
77,805
0.004679
# -*- coding: utf-8 -*- # =========================================================================== # eXe # Copyright 2004-2006, University of Auckland # Copyright 2006-2008 eXe Project, http://eXeLearning.org/ # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU G...
elif i.attrMap['class']=="CasestudyIdevice": idevice = burstIdevice('Case Study', i, node) elif i.attrMap['class']=="MultichoiceIdevice": idevice = burstIdevice('Multi-choice', i, node) elif i.attrMap['class']=="MultiSelectIdevice": ...
node) elif i.attrMap['class']=="TrueFalseIdevice": idevice = burstIdevice('True-False Question', i, node) else: # NOTE: no custom idevices burst yet, # nor any deprecated idevices.
miptliot/edx-platform
lms/djangoapps/teams/api_urls.py
Python
agpl-3.0
1,464
0
"""Defines the URL routes for the Team API.""" from django.conf import settings from django.conf.urls import patterns, url from .views import ( MembershipDetailView, MembershipListView, TeamsDetailView, TeamsListView, TopicDetailView, TopicListView ) TEAM_ID_PATTERN = r'(?P<team_id>[a-z\d_-]+...
ngs.COURSE_ID_PATTERN, ), TopicDetailView.as_view(), name="topics_detail" ), url( r'^v0/team_membership/$', MembershipListView.as_view(), name="team_membership_list" ), url( r'^v0/team_membership/{team_id_pattern},{username_pattern}$'.
format( team_id_pattern=TEAM_ID_PATTERN, username_pattern=settings.USERNAME_PATTERN, ), MembershipDetailView.as_view(), name="team_membership_detail" ) )
Ninjakow/TrueSkill
lib/pytba/test/api_test.py
Python
gpl-3.0
1,080
0.001852
import unittest from pytba import VERSION from pytba import api as client class TestApiMethods(unittest.TestCase): def setUp(self): client.set_api_key("WesJordan", "PyTBA-Unit-Test", VERSION) def test__tba_get(self): # Query with proper key should succeed team = client.tba_get('team/f...
self.assertEqual(len(event.teams), 75) self.assertEqual(event.info['name'], 'Tesla Division') self.assertEqual(len(event.matches), 140)
self.assertEqual(event.rankings[1][1], '2056') def test__team_matches(self): matches = client.team_matches('frc2363', 2016) self.assertEqual(len(matches), 62) self.assertEqual(matches[-1]['alliances']['opponent']['score'], 89) if __name__ == '__main__': unittest.main()
veltri/DLV2
tests/parser/aggregates.max.propagation.7.test.py
Python
apache-2.0
213
0
input = """ a(1). a(2) | a(3). ok1 :- #max{V:a(V)} = 3. b(3). b(1) | b(2). o
k2 :- #max{V:b(V)} = 3. """ output = ""
" a(1). a(2) | a(3). ok1 :- #max{V:a(V)} = 3. b(3). b(1) | b(2). ok2 :- #max{V:b(V)} = 3. """
DayGitH/Python-Challenges
DailyProgrammer/20120209C.py
Python
mit
1,271
0.004721
''' we all know the classic "guessing game" with higher or lower prompts. lets do a role reversal; you create a program that will guess numbers between 1-100, and respond appropriately based on whether users say that the number is too high or too low. Try to make a program that can guess your number based on
user input and great code! ''' import random import numpy got_answer = False max = 100 min =
0 try_count = 0 while not got_answer: try_count += 1 num = -1 while (num > 1) or (num < 0): num = .125 * numpy.random.randn() + 0.5 print(num) guess = int(((max - min) * num) + min) print('1. Higher') print('2. Correct!') print('3. Lower') print('\nIs your number {}...
BollMose/daynote
test_sht.py
Python
apache-2.0
132
0.015152
import sht21 with sht21.SHT21(1) as sht21: print "temp: %s"%sht2
1.read_temperature() print "humi: %s"%sht21
.read_humidity()
swapnilgt/percPatternDiscovery
rlcs/preAnalysisRun.py
Python
agpl-3.0
1,024
0.06543
import os import sys from src import impl as rlcs import utils as ut import analysis as anls import matplotlib.pyplot as plt import logging import pickle as pkl import time config = ut.loadConfig('config') sylbSimFolder=config['sylbSimFolder'] transFolder=config['transFolder'] lblDir=config['lblDir'] onsDir=config['o...
','KI','TA','TA','KI','NA'],['TA','TA','KI','TA','TA','KI','TA','TA','KI','TA','TA','KI','TA','TA','KI','TA'], ['TA','KI','TA','TA','KI','TA','TA','KI'], ['TA','TA','KI','TA','TA','KI'], ['TA', 'TA','KI', 'TA'],['KI', 'TA', 'TA', 'KI'], ['TA','TA','KI','NA'],
['DHA','GE','TA','TA']] queryLenCheck = [4,6,8,16] for query in queryList: if len(query) not in queryLenCheck: print 'The query is not of correct length!!' sys.exit() masterData = ut.getAllSylbData(tPath = transFolder, lblDir = lblDir, onsDir = onsDir) res = anls.getPatternsInTransInGTPos(masterD...
tqchen/tvm
python/tvm/tir/buffer.py
Python
apache-2.0
9,009
0.001332
# 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 u...
r implied. See the License for the # specific language governing permissions and limitations # under the License. """Abstraction for array data structures.""" from numbers import Integral import tvm._ffi from tvm._ffi.base import string_types from tvm.runtime import Object, convert from tvm.i
r import PrimExpr, PointerType, PrimType from . import _ffi_api @tvm._ffi.register_object("tir.Buffer") class Buffer(Object): """Symbolic data buffer in TVM. Buffer provide a way to represent data layout specialization of data structure in TVM. Do not construct directly, use :py:func:`~decl_buffer` ...
perfidia/selearea
tests/seleareaTest.py
Python
mit
2,350
0.00383
#-*- coding: utf-8 -*- ''' Created on 23 mar 2014 @author: mariusz @author: tomasz ''' import unittest from selearea import get_ast, get_workareas class seleareaTest(unittest.TestCase): def get_fc_pages(self): urls = { "http://fc.put.poznan.pl", "http://fc.put.poznan.pl/re...
ailed: work area found on identical pages.") def test_get_ast_fc_count(self): asts = self.get_fc_pages()
self.assertEqual(3, len(asts), "AssertionFailed: count for fc pages.") def test_get_workarea_fc_content(self): asts = self.get_fc_pages() workareas = get_workareas(asts) xpath = str("//html[@class='js']/body/div[@id='right']/div[@id='content']") self.assertEqual(xpath, workar...
SoftwareDefinedBuildings/smap
python/smap/smapconf.py
Python
bsd-2-clause
3,347
0.008664
""" Copyright (c) 2011, 2012, Regents of the University of California 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 l...
rd): return not logging.Filter.filter(self, record) def start_logging(): observer = log.PythonLoggingObserver() observer.start() for logtype, config in LOGGING.iteritems(): if logtype == "raven": from raven.handlers.logging import SentryHandler lvl = getattr(logging...
handler = SentryHandler(config["dsn"]) handler.setLevel(lvl) # don't try to log sentry errors with sentry handler.addFilter(InverseFilter('sentry')) logging.getLogger().addHandler(handler) print "Starting sentry logging [%s] with destination %s"% ...
liangdas/mqantserver
client/mqtt_chat_client.py
Python
apache-2.0
2,416
0.021183
# -*- coding: utf-8 -*- ''' Created on 17/2/16. @author: love ''' import paho.mqtt.client as mqtt import json import ssl def on_connect(client, userdata, flags, rc): print("Connected with result code %d"%rc) client.publish("Login/HD_Login/1", json.dumps({"userName": user, "passWord": "Hello,anyone!"}),qos=0,re...
t_reqs=ssl.CERT_REQUIRED, # tls_version=ssl.PROTOCOL_TLSv1, ciphers=None) client.connect(HOST, 3563, 60) #client.loop_forever() user = raw_input("请输入用户名:") client.user_data_set(user) client.loop_start() while True: s = raw_input("请先输入'join'加入房间,然后输入任意聊天字符:\n
") if s: if s=="join": client.publish("Chat/HD_JoinChat/2", json.dumps({"roomName": "mqant"}),qos=0,retain=False) elif s=="start": client.publish("Master/HD_Start_Process/2", json.dumps({"ProcessID": "001"}),qos=0,retain=False) elif s=="sto...