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 |
|---|---|---|---|---|---|---|---|---|
streamlink/streamlink | src/streamlink/plugins/teamliquid.py | Python | bsd-2-clause | 1,128 | 0.000887 | """
$url teamliquid.net
$url tl.net
$type live
"""
import logging
import re
from urllib.parse import urlparse
from streamlink.plugin import Plugin, pluginmatcher
from streamlink.plugins.afreeca import AfreecaTV
from streamlink.plu | gins.twitch import Twitch
log = logging.getLogger(__name__)
@pluginmatcher(re.compile(
r"https?://(?:www\.)?(?:tl|teamliquid)\.ne | t/video/streams/"
))
class Teamliquid(Plugin):
def _get_streams(self):
res = self.session.http.get(self.url)
stream_address_re = re.compile(r'''href\s*=\s*"([^"]+)"\s*>\s*View on''')
stream_url_match = stream_address_re.search(res.text)
if stream_url_match:
stream_url =... |
koljanos/sga-lti | sga/backend/send_grades.py | Python | bsd-3-clause | 4,039 | 0.00099 | """"
This module handles sending grades back to edX
Most of this module is a python 3 port of pylti (github.com/mitodl/sga-lti)
and should be moved back into that library.
"""
import uuid
from xml.etree import ElementTree as etree
import oauth2
from django.conf import settings
class SendGradeFailure(Exception):
... | :param client: OAuth Client
:param url: outc | ome url
:return: response
"""
consumer = oauth2.Consumer(key=lti_key, secret=secret)
client = oauth2.Client(consumer)
import httplib2
http = httplib2.Http
# pylint: disable=protected-access
normalize = http._normalize_headers
def my_normalize(self, headers):
""" This func... |
sametmax/Django--an-app-at-a-time | ignore_this_directory/django/contrib/gis/gdal/srs.py | Python | mit | 11,540 | 0.00078 | """
The Spatial Reference class, represents OGR Spatial Reference objects.
Example:
>>> from django.contrib.gis.gdal import SpatialReference
>>> srs = SpatialReference('WGS84')
>>> print(srs)
GEOGCS["WGS 84",
DATUM["WGS_1984",
SPHEROID["WGS 84",6378137,298.257223563,
AUTHORITY... | t_wkt(srs_input)
return
elif isinstan | ce(srs_input, str):
try:
# If SRID is a string, e.g., '4326', then make acceptable
# as user input.
srid = int(srs_input)
srs_input = 'EPSG:%d' % srid
except ValueError:
pass
elif isinstance(srs_input, int):
... |
manqala/erpnext | erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py | Python | gpl-3.0 | 4,815 | 0.023261 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
# ERPNext - web based ERP (http://erpnext.com)
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, unittest
from frappe.utils import flt, ... | o": stock_reco.name}))
self.assertFalse(frappe.db.get_value("GL Entry",
{"voucher_type": "Stock Reconciliation", "voucher_no": stock_reco.name}))
set_perpetual_inventory(0)
def insert_existing_sle(self):
from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
make_stock_entry(... | ting_date="2012-12-25", posting_time="03:00", item_code="_Test Item",
source="_Test Warehouse - _TC", qty=15)
make_stock_entry(posting_date="2013-01-05", posting_time="07:00", item_code="_Test Item",
target="_Test Warehouse - _TC", qty=15, basic_rate=1200)
def create_stock_reconciliation(**args):
args = frap... |
andersbogsnes/blog | app/forms.py | Python | mit | 1,224 | 0.006536 | from flask_wtf import Form
from flask_wtf.file import FileRequired, FileAllowed, FileField
from wtforms import StringField, BooleanField, PasswordField, TextAreaField
from wtforms.validators import DataRequired, Email, Length
class SignUpForm(Form):
username = StringField('username', validators=[DataRequired(), L... | 50)])
remember_me = BooleanField('remember_me', default=False)
class PostForm(Form):
content = TextAreaField('content', validators=[DataRequired()])
class UploadPostForm(Form):
file = FileField('post', validators=[FileRequired(), FileAllowed(['md'], 'Only Markdown files!')])
| overwrite = BooleanField('overwrite', default=False)
|
imyeego/MLinPy | zh_cnn_text_classify/text_cnn.py | Python | mit | 3,414 | 0.045694 | import tensorflow as tf
import numpy as np
class TextCNN(object):
'''
A CNN for text classification
Uses and embedding layer, followed by a convolutional, max-pooling | and softmax layer.
'''
def __init__(
self, sequence_length, num_classes,
embedding_size, filter_sizes, num_filters, l2_reg_lambda=0.0):
# Placeholders for input, output, dropout
self.input_x = tf.placeholder(tf.float32, [None, sequence_length, embedding_size], name = "in... | num_classes], name = "input_y")
self.dropout_keep_prob = tf.placeholder(tf.float32, name = "dropout_keep_prob")
# Keeping track of l2 regularization loss (optional)
l2_loss = tf.constant(0.0)
# Embedding layer
# self.embedded_chars = [None(batch_size), sequence_size, embedding_si... |
sshwsfc/django-xadmin | xadmin/plugins/language.py | Python | bsd-3-clause | 1,002 | 0.003992 |
from django.conf import settings
from django.template import loader
from django.views.i18n import set_language
from xadmin.plugins.utils import get_context_dict
from xadmin.sites import site
from xadmin.views import BaseAdminPlugin, CommAdminView, BaseAdminView
class SetLangNavPlugin(BaseAdminPlugin):
def block... | del request.session['nav_menu']
return set_language(request)
if settings.LANGUAGES and 'django.middleware.locale.LocaleMiddleware' in settings.MIDDLEWARE_CLASSES:
site.register_plugin(SetLangNavPlugin, CommAdminView)
site.register_view(r'^i18n/setlang/$', SetLangView, 'set_langua | ge')
|
CobwebOrg/cobweb-django | projects/search_indexes.py | Python | mit | 4,143 | 0.003862 | # """SearchIndex classes for Django-haystack."""
from typing import List
from django.utils.html import format_html, mark_safe
from haystack import indexes
from projects.models import Project, Nomination, Claim
class ProjectIndex(indexes.SearchIndex, indexes.Indexable):
"""Django-haystack index of Project model.... | .CharField(model_attr='status', indexed=True, stored=True)
impact_factor = indexes.IntegerField(model_attr='impact_factor', indexed=True, stored=True)
tags = indexes.MultiValueField(indexed=True, null=True, stored=True)
subject_headings = indexes.MultiValueField(indexed=True, null=True, stored=True)
| # notes
unclaimed_nominations = indexes.IntegerField(model_attr='n_unclaimed', indexed=True, stored=True)
claimed_nominations = indexes.IntegerField(model_attr='n_claimed', indexed=True, stored=True)
held_nominations = indexes.IntegerField(model_attr='n_held', indexed=True, stored=True)
def get_mode... |
amrdraz/brython | www/src/Lib/encodings/iso8859_1.py | Python | bsd-3-clause | 13,483 | 0.021064 | """ Python Character Mapping Codec iso8859_1 generated from 'MAPPINGS/ISO8859/8859-1.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
def decode(self,i... | N
'\x05' # 0x05 -> ENQUIRY
'\x06' # 0x06 -> ACKNOWLEDGE
'\x07' # 0x07 -> BELL
'\x08' # 0x08 -> BACKSPACE
'\t' # 0x09 -> HORIZONTAL TABULATION
'\n' # 0x0A -> LINE FEED
'\x0b' # 0x0B -> VERTICAL TABULATION
'\x0c' # 0x0C -> FORM FEED
... | ATA LINK ESCAPE
'\x11' # 0x11 -> DEVICE CONTROL ONE
'\x12' # 0x12 -> DEVICE CONTROL TWO
'\x13' # 0x13 -> DEVICE CONTROL THREE
'\x14' # 0x14 -> DEVICE CONTROL FOUR
'\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE
'\x16' # 0x16 -> SYNCHRONOUS IDLE
'\x17' # 0x17 -... |
Anfauglith/iop-hd | test/functional/test_framework/script.py | Python | mit | 25,954 | 0.01021 | #!/usr/bin/env python3
# Copyright (c) 2015-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.
"""Functionality to build scripts, as well as SignatureHash().
This file is modified from python-ioplib.
... | b)
OP_12 = CScriptOp(0x5c)
OP_13 = CScriptOp(0x5d)
OP_14 = CScriptOp(0x5e)
OP_15 = CScriptOp(0x5f)
OP_16 = CScriptOp(0x60)
# control
OP_NOP = CScriptOp(0x61)
OP_VER = CScriptOp(0x62)
OP_IF = CScriptOp(0x63)
OP_NOTIF = CScriptOp(0x64)
OP_VERIF = CScriptOp(0x65)
OP_VERNOTIF = CScriptOp(0x66)
OP_ELSE = CScriptOp(0x67)
OP... | = CScriptOp(0x6a)
# stack ops
OP_TOALTSTACK = CScriptOp(0x6b)
OP_FROMALTSTACK = CScriptOp(0x6c)
OP_2DROP = CScriptOp(0x6d)
OP_2DUP = CScriptOp(0x6e)
OP_3DUP = CScriptOp(0x6f)
OP_2OVER = CScriptOp(0x70)
OP_2ROT = CScriptOp(0x71)
OP_2SWAP = CScriptOp(0x72)
OP_IFDUP = CScriptOp(0x73)
OP_DEPTH = CScriptOp(0x74)
OP_DROP = ... |
lustigerluke/motion-track | config.py | Python | mit | 1,176 | 0.005102 | # Config.py file for motion-track.py
# Display Settings
debug = True # Set to False for no data display
window_on = False # Set to True displays opencv windows (GUI desktop reqd)
diff_window_on = False # Show OpenCV image difference window
thresh_window_on = False # Show OpenCV image Threshold window
SHOW_C... | ment Status Window
# if gui_window_on=True then makes opencv window bigger
# Note if the window is larger than 1 then a reduced frame rate will occur
# Camera Settings
CAMERA_WIDTH = 320
CAMERA_HEIGHT = 240
big_w = int(CAMERA_WIDTH * WINDOW_BIGGER)
big_h = int(CAMERA... | otion Tracking Settings
MIN_AREA = 200 # excludes all contours less than or equal to this Area
THRESHOLD_SENSITIVITY = 25
BLUR_SIZE = 10
|
m110/grafcli | grafcli/commands.py | Python | mit | 8,828 | 0.000227 | import os
import re
import json
import shutil
import tarfile
import tempfile
from climb.config import config
from climb.commands import Commands, command, completers
from climb.exceptions import CLIException
from climb.paths import format_path, split_path, ROOT_PATH
from grafcli.documents import Document, Dashboard, R... | )
@command
@completers('path')
def mv(self, source, destination, match_slug=False):
if len(source) < 2:
raise CLIException("No destination provided")
destination = source.pop(-1)
destination_path = format_path(self._cli.current_path, destination)
for path in so... | = self._match_slug(document, destination_path)
self._resources.save(destination_path, document)
self._resources.remove(source_path)
self._cli.log("mv: {} -> {}", source_path, destination_path)
@command
@completers('path')
def rm(self, path):
path = format_path(... |
jcgoble3/luapatt | tests/test_lua1_basics.py | Python | mit | 6,266 | 0.009595 | # coding: utf-8
# Copyright 2015 Jonathan Goble
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, ... | 'a-') == ''
def test_full_match_minus():
assert luapatt.match('aaa', '^.-$') == 'aaa'
def test_asterisk_maxexpand():
assert luapatt.match('aabaaabaaabaaaba', 'b.*b') == 'baaabaaabaaab'
def test_minus_minexpand():
assert luapatt.match('aabaaabaaabaaaba', 'b.-b') == 'baaab'
def test_dot_plain_endanchor():
... | uapatt.match('alo xo', '.o$') == 'xo'
def test_class_x2_asterisk():
assert luapatt.match(' \n isto é assim', '%S%S*') == 'isto'
def test_class_asterisk_endanchor():
assert luapatt.match(' \n isto é assim', '%S*$') == 'assim'
def test_set_asterisk_endanchor():
assert luapatt.match(' \n isto é assim', '[a-z]*... |
phodal/iot-code | chapter2/gpio.py | Python | mit | 124 | 0 | import RPi.GPIO as | GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(5, GPIO.OUT)
GPIO.output(5, | GPIO.HIGH)
GPIO.output(5, GPIO.LOW)
|
anish/buildbot | master/buildbot/test/unit/test_revlinks.py | Python | gpl-2.0 | 5,555 | 0.00234 | # This file is part of B | uildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# L | icense as published by the Free Software Foundation, version 2.
#
# 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 shou... |
badp/ganeti | test/py/ganeti.rapi.client_unittest.py | Python | gpl-2.0 | 59,059 | 0.004809 | #!/usr/bin/python
#
# Copyright (C) 2010, 2011 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This p... | ._responses.insert(0, (code, response))
def CountPending(self):
return len(self._responses)
def GetLastHandler(self):
return self._last_handle | r
def GetLastRequestData(self):
return self._last_req_data
def FetchResponse(self, path, method, headers, request_body):
self._last_req_data = request_body
try:
(handler_cls, items, args) = self._mapper.getController(path)
# Record handler as used
_used_handlers.add(handler_cls)
... |
astrobin/astrobin | astrobin/tests/test_collection.py | Python | agpl-3.0 | 11,674 | 0.002998 | import re
import simplejson
from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import reverse
from astrobin.models import Collection, Image
from astrobin_apps_images.models import KeyValueTag
class CollectionTest(TestCase):
def setUp(self):
self.user = User.obj... | esponse = self.client.get(reverse('user_collectio | ns_list', args=(self.user.username,)))
self.assertContains(response, "This user does not have any collections")
self.client.logout()
# Owner, no collection
self.client.login(username='test', password='password')
response = self.client.get(reverse('user_collections_list', args=(s... |
danielhers/ucca | ucca/tests/test_constructions.py | Python | gpl-3.0 | 2,357 | 0.00594 | from collections import OrderedDict
import pytest
from ucca import textutil
from ucca.constructions import CATEGORIES_NAME, DEFAULT, CONSTRUCTIONS, extract_candidates
from .conftest import PASSAGES, loaded, loaded_valid, multi_sent, crossing, discontiguous, l1_passage, empty
"""Tests the constructions module functio... | args, **kwargs):
del args, kwargs
assert False, "Should not load spaCy when passage is pre-annotated"
def extract_and_check(p, constructions=None, expected=None):
d = OrderedDict((construction, [candidate.edge for candidate in candidates]) for construction, candidates in
extract_candid... | t None:
hist = {c.name: len(e) for c, e in d.items()}
assert hist == expected, " != ".join(",".join(sorted(h)) for h in (hist, expected))
@pytest.mark.parametrize("create, expected", (
(loaded, {'P': 1, 'remote': 1, 'E': 3, 'primary': 15, 'U': 2, 'F': 1, 'C': 3, 'A': 1, 'D': 1, 'L': 2, 'mwe': ... |
sibson/vncdotool | vncdotool/rfb.py | Python | mit | 35,587 | 0.005789 | """
RFB protocol implementattion, client side.
Override RFBClient and RFBFactory in your application.
See vncviewer.py for an example.
Reference:
http://www.realvnc.com/docs/rfbproto.pdf
(C) 2003 [email protected]
MIT License
"""
# flake8: noqa
import sys
import math
import zlib
import getpass
import os
from Crypto... | ---
# states used on connection startup
#------------------------------------------------------
def _handleInitial(self):
buffer = b''.join(self._packet)
if b'\n' in buffer:
version = 3.3
if buffer[:3] == b'RFB':
version_server = float(buffer[3:-1].re... | RTED_VERSIONS = (3.3, 3.7, 3.8)
if version_server == 3.889: # Apple Remote Desktop
version_server = 3.8
if version_server in SUPPORTED_VERSIONS:
version = version_server
else:
log.msg("Protocol version %.3f not s... |
mrwangxc/zstack-utility | zstackctl/zstackctl/ctl.py | Python | apache-2.0 | 302,359 | 0.005626 | #!/usr/bin/python
import argparse
import sys
import os
import subprocess
import signal
import getpass
import simplejson
from termcolor import colored
import ConfigParser
import StringIO
import functools
import time
import random
import string
from configobj import ConfigObj
import tempfile
import pwd, grp
import trace... | s:
if c not in cmdline:
is_find = False
break
if not is_find:
continue
return pid
except IOError:
continue
return None
def ssh_run_full(ip, cmd, params=[], pipe=True):
remote_path = '/tmp/%s.s... | ipt = '''/bin/bash << EOF
cat << EOF1 > %s
%s
EOF1
/bin/bash %s %s
ret=$?
rm -f %s
exit $ret
EOF''' % (remote_path, cmd, remote_path, ' '.join(params), remote_path)
scmd = ShellCmd('ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no %s "%s"' % (ip, script), pipe=pipe)
scmd(False)
return scmd
... |
HelloLily/hellolily | lily/hubspot/prefetch_objects.py | Python | agpl-3.0 | 2,414 | 0.000829 | from django.db.models import Prefetch, Case, When, Value, IntegerField, Q
from lily.accounts.models import Website, Account
from lily.integrations.models import Document
from lily.notes.models import Note
from lily.socialmedia.models import SocialMedia
from lily.tags.models import Tag
from lily.utils.models.models imp... | h(
looku | p='phone_numbers',
queryset=PhoneNumber.objects.filter(
status=PhoneNumber.ACTIVE_STATUS
).annotate(
custom_order=Case(
When(type='work', then=Value(1)),
When(type='mobile', then=Value(2)),
When(type='home', then=Value(3)),
When(type='other', then=... |
expectocode/Telethon | telethon/client/chats.py | Python | mit | 42,127 | 0.000688 | import asyncio
import inspect
import itertools
import string
import typing
from .. import helpers, utils, hints
from ..requestiter import RequestIter
from ..tl import types, functions, custom
if typing.TYPE_CHECKING:
from .telegramclient import TelegramClient
_MAX_PARTICIPANTS_CHUNK_SIZE = 200
_MAX_ADMIN_LOG_CHU... | ne
__enter__ = helpers._sync_enter
__exit__ = helpers._sync_exit
async def _update(self):
try:
while self._running:
await self._client(self._request)
await asyncio.sleep(self._delay)
except ConnectionError:
pass
except asyncio... | ns.messages.SetTypingRequest(
self._chat, types.SendMessageCancelAction()))
def progress(self, current, total):
if hasattr(self._action, 'progress'):
self._action.progress = 100 * round(current / total)
class _ParticipantsIter(RequestIter):
async def _init(self, entity... |
xairy/mipt-schedule-parser | msp/test/schedule_tests.py | Python | mit | 8,974 | 0.007132 | #!/usr/bin/python
#coding: utf-8
from __future__ import unicode_literals
import os
import unittest
import xlrd
import msp.schedule_parser as schedule_parser
__author__ = "Andrey Konovalov"
__copyright__ = "Copyright (C) 2014 Andrey Konovalov"
__license__ = "MIT"
__version__ = "0.1"
this_dir, this_filename = os.pat... | ertEqual(self.schedule.GetDepartmentRange(1), (13, 20))
self.assertEqual(self.schedule.GetDepartmentRange(2), (22, 32))
self.assertEqual(self.schedule.GetDepartmentRange(3), (34, 36))
self.assertEqual(self.schedule.GetDepartmentRange(4), (38, 43))
self.assertEqual(self.schedule.GetDepartmentRange(5), (4... | ntRange(8), (73, 77))
class DepartmentsRowTest(unittest.TestCase):
def setUp(self):
self.schedule = schedule_parser.Schedule()
self.schedule.Parse(SCHEDULE_PATH)
def runTest(self):
self.assertEqual(self.schedule.GetDepartmentsRow(), 3)
class HoursColumnTest(unittest.TestCase):
def setUp(self):
... |
ArtifexSoftware/mupdf | scripts/jlib.py | Python | agpl-3.0 | 81,616 | 0.004717 | import codecs
import doctest
import inspect
import io
import os
import platform
import re
import shutil
import subprocess
import sys
import textwrap
import time
import traceback
import types
def place( frame_record):
'''
Useful debugging function - returns representation of source position of
caller.
... |
global _log_text_line_start
text2 = ''
pos = 0
while 1:
if pos == len(text):
break
if not raw or _log_text_line_start:
text2 += prefix
nl = text.find('\n', pos)
if nl == -1:
text2 += text[pos:]
if not raw:
t... | pos = len(text)
else:
|
Iconik/eve-suite | src/model/static/inv/control_tower_resources.py | Python | gpl-3.0 | 1,085 | 0.00553 | from collections import namedtuple
from model.flyweight import Flyweight
from model.static.database import database
class ControlTowerResource(Flyweight):
def __init__(self,control_tower_type_id):
#prevents reinitializing
if "_inited" in self.__dict__:
return
self._inited = None... | self.resources = list()
resource_tuple = namedtuple("resource_tuple",
"resource_type_id purpose quantity min_security_level faction_id ")
for row in cursor:
self.resources.append(resource_tuple(
resource_type_id=row["resourceTypeID"],
purpose=... | |
voutilad/courtlistener | cl/corpus_importer/import_columbia/parse_opinions.py | Python | agpl-3.0 | 15,489 | 0.002066 | # -*- coding: utf-8 -*-
# Functions to parse court data in XML format into a list of dictionaries.
import hashlib
import os
import re
import xml.etree.cElementTree as ET
import dateutil.parser as dparser
from juriscraper.lib.string_utils import titlecase, harmonize, clean_string, CaseNameTweaker
from lxml import etre... | judges = find_judge_names(opinion['byline'])
info['opinions'].append({
'opinion': '\n'.join(last_texts),
'opinion_texts': last_texts,
'type': current_type,
'author': judges[0] if judges else None,
... | 'byline': opinion['byline'],
})
last_texts = []
if current_type == 'opinion':
info['judges'] = opinion['byline']
if last_texts:
relevant_opinions = [o for o in info['opinions'] if o['type'] == current_type]
... |
i-sultan/Smart-Trader | src/st_cache_handler.py | Python | gpl-3.0 | 3,536 | 0.009055 | """File to interact with cache folder to isolate cache handling functionality
from main controllers code.
The CacheHandler should only be accessed by controller classes.
"""
#.-------------------.
#| imports |
#'-------------------'
import os
import pickle
#.-------------------.
#| main ... | os.path.join('cache', folder, subfolder))
else:
# cleanup directory before saving new file. TODO: warn user if not empty.
| for file_name in self.get_filenames(folder, subfolder):
os.remove(os.path.join('cache', folder, subfolder, file_name))
location = os.path.join('cache', folder, subfolder, file)
self.pickle_object(location, instance)
return location
def save_df(self, folder, subf... |
aio-libs/aiohttp_session | aiohttp_session/memcached_storage.py | Python | apache-2.0 | 3,256 | 0 | import json
import uuid
from time import time
from typing import Any, Callable, Optional
import aiomcache
from aiohttp import web
from . import AbstractStorage, Session
class MemcachedStorage(AbstractStorage):
"""Memcached storage"""
def __init__( # type: ignore[no-any-unimported] # TODO: aiomcache
... | path: str = '/',
secure: Optional[bool] = None,
httponly: bool = True,
key_factory: Callable[[], str] = lambda: uuid.uuid4().hex,
encoder: Callable[[object], str] = json.dumps,
decoder: Callable[[str], Any] = json.loads
) -> None:
super().__init__(cookie_name=cookie_... | max_age=max_age, path=path, secure=secure,
httponly=httponly,
encoder=encoder, decoder=decoder)
self._key_factory = key_factory
self.conn = memcached_conn
async def load_session(self, request: web.Request) -> Session:
cookie... |
neurosynth/ACE | ace/__init__.py | Python | mit | 1,044 | 0.007663 | # emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 et:
"""ACE -- Automated Coordinate Extraction.
"""
__all__ = ["conf | ig", "database", "datatable", "exporter", "set_logging_level", "scrape", "sources", "tableparser", "tests", "__version__"]
import logging
import sys
import os
from version import __version__
def set_logging_level(level=None):
"""Set package-wide logging level
Args
level : Logging level constant from... | LOGLEVEL', 'warn')
logger.setLevel(getattr(logging, level.upper()))
return logger.getEffectiveLevel()
def _setup_logger(logger):
# Basic logging setup
console = logging.StreamHandler(sys.stdout)
console.setFormatter(logging.Formatter("%(levelname)-6s %(module)-7s %(message)s"))
logger.addHandle... |
robwarm/gpaw-symm | doc/tutorials/dipole_correction/submit.agts.py | Python | gpl-3.0 | 285 | 0 | def agts(queu | e):
d = queue.add('dipole.py', ncpus=4, walltime=60)
queue.add('plot.py', deps=d, ncpus=1, walltime=10,
creates=['zero.png', 'period | ic.png', 'corrected.png',
'slab.png'])
queue.add('check.py', deps=d, ncpus=1, walltime=10)
|
timopulkkinen/BubbleFish | tools/perf/page_sets/page_sets_unittest.py | Python | bsd-3-clause | 643 | 0.010886 | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-styl | e license that can be
# found in the LICENSE file.
import unittest
from telemetry.page import page_set
import page_sets
class PageSetsUnittest(unittest.TestCase):
"""Verfies that all the pagesets in this directory are syntactically valid."""
@staticmethod
def testPageSetsParseCorrectly():
filenames = page_... | PageSetFilenames()
for filename in filenames:
try:
page_set.PageSet.FromFile(filename)
except Exception, ex:
raise Exception("Pageset %s: %s" % (filename, str(ex)))
|
JulienMcJay/eclock | windows/Python27/Lib/site-packages/docutils/parsers/rst/directives/admonitions.py | Python | gpl-2.0 | 2,413 | 0.000414 | # $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $
# Author: David Goodger <[email protected]>
# Copyright: This module has been placed in the public domain.
"""
Admonition directives.
"""
__docformat__ = 'reStructuredText'
from docutils.parsers.rst import Directive
from docutils.parsers.rst import states, di... | )]
self.state.nested_parse(self.content, self.content_offset,
admonition_node)
return [admonition_node]
class Admonition(BaseAdmonition):
required_arguments = 1
node_class = nodes.admonition
class Attention(BaseAdmonition):
node_class = nodes.attention
... | onition):
node_class = nodes.danger
class Error(BaseAdmonition):
node_class = nodes.error
class Hint(BaseAdmonition):
node_class = nodes.hint
class Important(BaseAdmonition):
node_class = nodes.important
class Note(BaseAdmonition):
node_class = nodes.note
class Tip(BaseAdmonition):
... |
akosyakov/intellij-community | python/testData/debug/test_ignore_lib.py | Python | apache-2.0 | 84 | 0.011905 | from cale | ndar import setfirstwee | kday
stopped_in_user_file = True
setfirstweekday(15) |
hans-boden/pyws-fablab-lisbon | contribs/luis_mp/mm_proposal_wo_kivi.py | Python | unlicense | 1,919 | 0.008863 | # python3
"""
Mastermind without kivy - by Luis
merciless edited by hans
"""
import random
import re
class G():
valid_chars = '123456'
secret_len = 5
solved = '+' * secret_len
regex_str = "^[{0}]{{{1},{1}}}$".format(valid_chars, secret_len)
valid_input = re.compile(regex_str) # regular exp... | ion for user input
def main():
secret = answer_generator()
print('Enter your guess of {} of these symbols: ({})'
.format(G.secret_len, G.valid_chars))
while True:
user_seq = user_guess()
output = handle_game(secret, user_seq)
result_msg = ('{} -> {}')
p... | lved:
break
print('You have found the answer! Goodbye!')
def handle_game(answer, guess):
answer = list(answer) # no need to str() or to assign a new name
guess = list(guess)
output = ''
for i, ch in enumerate(guess):
if ch == answer[i]:
# eliminate hit... |
relic7/prodimages | python/jbmodules/image_processing/marketplace/multiprocmagick.py | Python | mit | 8,914 | 0.010433 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
import multiprocessing, time
class Consumer(multiprocessing.Process):
def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue
def run(self):
p... | ir):
import tempfile, shutil
# tmpfileobj, tmpfile_path = tempfile.mkstemp(suffix=".png")
self.img = img
self.rgbmean = rgbmean
self.destdir = destdir
#self.tmppngout = tempfile.mkstemp(suffix=".png")
def __call__(self):
| #import jbmodules
import os
import image_processing
from image_processing import marketplace, magick_tweaks
import image_processing.marketplace.magicColorspaceModAspctLoadFaster2 as magickProc2
#time.sleep(0.1) # pretend to take some time to do the work
import image_proc... |
glic3rinu/basefs | basefs/fs.py | Python | mit | 8,050 | 0.002733 | import os
import sys
import errno
import itertools
import logging
import stat
import threading
from fuse import FuseOSError, Operations
from . import exceptions, utils
from .keys import Key
from .logs import Log
from .views import View
logger = logging.getLogger('basefs.fs')
class ViewToErrno():
def __enter__... | def utimens(self, path, times=None):
# return os.utime(self._full_path(path), times)
# # File methods
# # ============
def open(self, path, flags):
node = self.get_node(pat | h)
id = int(node.entry.hash, 16)
if path not in self.cache:
self.cache[path] = node.content
self.dirty[path] = False
return id
def create(self, path, mode, fi=None):
self.cache[path] = b''
self.dirty[path] = True
return id(path)
def read(... |
vlna/another-py-invaders | another-py-invaders.py | Python | gpl-3.0 | 3,451 | 0.006375 | # import libraries
import math
import random
import pygame
from pygame.locals import *
pygame.init()
pygame.mixer.init()
width, height = 8 | 00, 600
screen = pygame.display.set_mode((width, height))
keys = [False, False, False, False]
player = | [100, 520]
invaders = []
bullets = []
bombs = []
rockets = []
rocketpieces = []
bgimg = pygame.image.load("g:/invaders/paragliding_2017_4_bsl-73.jpg")
invaderimg = pygame.transform.scale(pygame.image.load("g:/invaders/Space-Invaders-PNG-Clipart.png"), (64, 64))
playerimg = pygame.transform.scale(pygame.image.load("g... |
liqd/adhocracy4 | tests/filter/test_free_text_filter.py | Python | agpl-3.0 | 2,219 | 0 | import django_filters
import pytest
from django.core.exceptions import ImproperlyConfigured
from adhocracy4.filters.filters import FreeTextFilter
from adhocracy4.filters.views import FilteredListV | iew
from tests.apps.questions import models as question_models
class SearchFilterS | et(django_filters.FilterSet):
search = FreeTextFilter(
fields=['text']
)
class Meta:
model = question_models.Question
fields = ['search']
@pytest.fixture
def question_list_view():
class DummyView(FilteredListView):
model = question_models.Question
filter_set =... |
vinaymayar/python-game-workshop | lesson4/guess_game.py | Python | mit | 1,288 | 0.009317 | # Challenge: guess-number game infinite number of guesses
# The game: Guess the number game.
# In this game we will try to guess a random number between 0 and 100 generated
# by the computer. Depending on our guess, the computer will give us hints,
# whether we guessed too high, too low or if we guessed correctly.
#
# ... | hat counts the number of guesses.
# Increment it every time the user makes a guess and use control flow statements
# to see if they reached the limit!
# Don't worry about these lines.
from random import randint
secret_number = randint(0, 100)
while(True): # don't worry about this either, but be sure to follow the ind... | dd a print statement letting the user know they made the right guess.
break; # don't worry about this line, we will learn more about this, when we
# learn about loops!
elif ... # how can we check if the guess is too high?
# what should we do if the guess is too high?
else:
... |
ccpem/mrcfile | tests/test_mrcmemmap.py | Python | bsd-3-clause | 2,865 | 0.004538 | # Copyright (c) 2016, Science and Technology Facilities Council
# This software is distributed under a BSD licence. See LICENSE.txt.
"""
Tests for mrcmemmap.py
"""
# Import Python 3 features for future-proofing
from __future__ import (absolute_import, division, print_function,
unicode_literals... | th MrcMemmap(self.example_mrc_name) as mrc:
assert repr(mrc) == "MrcMemmap(' | {0}', mode='r')".format(self.example_mrc_name)
def test_exception_raised_if_file_is_too_small_for_reading_data(self):
"""Override test to change expected error message."""
with self.newmrc(self.temp_mrc_name, mode='w+') as mrc:
mrc.set_data(np.arange(24, dtype=np.int16).reshape(2, 3... |
PeterLValve/apitrace | specs/d3d9types.py | Python | mit | 30,033 | 0.001232 | ##########################################################################
#
# Copyright 2011 Jose Fonseca
# Copyright 2008-2009 VMware, Inc.
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to... | D", D3DBLEND),
("D3DRS_CULLMODE", D3DCULL),
("D3DRS_ZFUNC", D3DCMPFUNC),
("D3DRS_ALPHAREF", DWORD),
("D3DRS_ALPHAFUNC", D3DCMPFUNC),
("D3DRS_DITHERENABLE", BOOL),
("D3DRS_ALPHABLENDENABLE", BOOL),
("D3DRS_FOGENABLE", BOOL),
("D3DRS_SPECULARENABLE", BOOL),
| ("D3DRS_FOGCOLOR", D3DCOLOR),
("D3DRS_FOGTABLEMODE", D3DFOGMODE),
("D3DRS_FOGSTART", FLOAT_AS_DWORD),
("D3DRS_FOGEND", FLOAT_AS_DWORD),
("D3DRS_FOGDENSITY", FLOAT_AS_DWORD),
("D3DRS_RANGEFOGENABLE", BOOL),
("D3DRS_STENCILENABLE", BOOL),
("D3DRS_STENCILFAIL", D3DSTENCILOP),
("D3DRS_STE... |
gabriellmb05/trabalho-les | src/project_manager/migrations/0001_initial.py | Python | gpl-3.0 | 2,659 | 0.004137 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-06-02 20:34
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migratio... |
operations = [
migrations.CreateModel(
name='Credencial',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user_name', models.CharField(max_length=60, unique=True)),
('passwo... | Field(max_length=255)),
('token', models.CharField(blank=True, max_length=60, unique=True)),
('agente', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Ferramenta',
... |
LordPharaoh/typecat | typecat/display/fontbox.py | Python | mit | 1,483 | 0.00472 | import typecat.font2img as f2i
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class FontBox(Gtk.FlowBoxChild):
def set_text(self, arg1):
if type(arg1) is str:
self.text = arg1
if type(arg1) is int:
self.font_size = arg1
try:
... | tk.Image(halign=Gtk.Align.CENTER)
self.font.set_size(self.font_size)
self.image.set_from_pixbuf(f2i.multiline_gtk(self.text, self.font.pilfont, self. | size, background=self.bg, foreground=self.fg))
self.box.pack_start(self.image, True, False, 0)
self.frame.add(self.box)
self.show_all()
def __init__(self, font, text="Handgloves", size=(200, 150), font_size=75):
Gtk.FlowBoxChild.__init__(self)
self.frame = Gtk.Frame()
... |
smartshark/serverSHARK | smartshark/sparkconnector.py | Python | apache-2.0 | 2,541 | 0.00669 | import server.settings
import requests
import json
import re
class BatchJob(object):
def __init__(self, id, state, log):
self.id = id
self.state = state
self.log = log
def __str__(self):
return 'id: %s, state: %s, log: %s' % (self.id, self.state, '\n'.join(self.log))
class S... | staticmethod
def create_batch_object(data_dict):
return BatchJob(data_ | dict['id'], data_dict['state'], data_dict['log'])
#sc = SparkConnector()
#bj = sc.submit_batch_job('/home/ftrauts/Arbeit/spark/examples/src/main/python/pi.py')
#print(sc.get_log_from_batch_job(4, only_user_output=True)) |
cliffano/swaggy-jenkins | clients/python-aiohttp/generated/openapi_server/models/queue_left_item.py | Python | mit | 8,986 | 0.003116 | # coding: utf-8
from datetime import date, datetime
from typing import List, Dict, Type
from openapi_server.models.base_model_ import Model
from openapi_server.models.cause_action import CauseAction
from openapi_server.models.free_style_build import FreeStyleBuild
from openapi_server.models.free_style_project import... | QueueLeftItem.
:return: The actions of this QueueLeftItem.
:rtype: List[CauseAction]
"""
return self._actions
@actions.setter
def actions(self, actions):
"""Sets the actions of this QueueLeftItem.
:param actions: The actions of this QueueLeftItem.
:ty... | @property
def blocked(self):
"""Gets the blocked of this QueueLeftItem.
:return: The blocked of this QueueLeftItem.
:rtype: bool
"""
return self._blocked
@blocked.setter
def blocked(self, blocked):
"""Sets the blocked of this QueueLeftItem.
:par... |
CodeNameGhost/shiva | thirdparty/scapy/arch/bpf/__init__.py | Python | mit | 79 | 0 | # Gu | illaume Valadon <[email protected]>
"""
Scapy *BSD native support
"""
| |
ktan2020/legacy-automation | win/Lib/site-packages/selenium/webdriver/ie/__init__.py | Python | mit | 643 | 0 | #!/usr/bin/python
#
# Copyright 2008-2010 WebDriver committers
# Copyright 2008-2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE... | to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License f | or the specific language governing permissions and
# limitations under the License.
|
ldgit/remote-phpunit | tests/app/commands/test_file_command.py | Python | mit | 7,821 | 0.005114 | import unittest
from app.commands.file_command import FileCommand
class TestFileCommand(unittest.TestCase):
def setUp(self):
self.window = WindowSpy()
self.settings = PluginSettingsStub()
self.sublime = SublimeSpy()
self.os_path = OsPathSpy()
# SUT
self.command = ... | f.window)
| self.assertEqual('C:/path/to/root/path/to/file.php', self.window.file_to_open)
def test_open_source_file_works_with_backslashes(self):
self.settings.tests_folder = 'tests/unit'
self.command.open_source_file('C:\\path\\to\\root\\tests\\unit\\path\\to\\fileTest.php', self.window)
self.assert... |
kstilwell/tcex | tests/batch/test_attributes_1.py | Python | apache-2.0 | 1,808 | 0 | """Test the TcEx Batch Module."""
# third-party
import pytest
class TestAttributes:
"""Test the TcEx Batch Module."""
@pytest.mark.parametrize(
'name,description,attr_type,attr_value,displayed,source',
[
(
'pytest-adversary-i1-001',
'Attribute Testi... | ttr.displayed == displayed
assert attr.source == source
assert attr.type == attr_type
assert attr.value is None
# submit batch
batch.save(ti)
batch_status = batch.submit_all()
assert batch_status[0].get('status') == 'Completed'
assert batch_status[0].get(... | er()
|
KaranToor/MA450 | google-cloud-sdk/lib/surface/config/configurations/list.py | Python | apache-2.0 | 2,092 | 0.003824 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | configurations.
""",
'EXAMPLES': """\
To list all available configurations, run:
| $ {command}
""",
}
@staticmethod
def Args(parser):
base.PAGE_SIZE_FLAG.RemoveFromParser(parser)
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
configs = named_configs.ConfigurationStore.AllConfigs()
for _, config in sorted(configs.iteritems()):
props = p... |
muchu1983/104_cameo | test/unit/test_spiderForTECHORANGE.py | Python | bsd-3-clause | 1,235 | 0.008425 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu ([email protected])
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
"""
import unittest
import logging
from cameo.spiderForTECHORANGE import SpiderForTECHORANGE
"""
測試 抓取 TECHORANGE
"""
class SpiderFor... |
#收尾
def tearDown(self):
self.spider.quitDriver()
"""
#測試抓取 index page
def test_downloadIndexPage(self):
logging.info("SpiderForTECHORANGETest.test_downloadIndexPage")
self.spider.downloadIndexPage()
#測試抓取 tag page
def test_downloadTagPage(self):
log... | logging.info("SpiderForTECHORANGETest.test_downloadNewsPage")
self.spider.downloadNewsPage(strTagName=None)
#測試開始
if __name__ == "__main__":
unittest.main(exit=False)
|
eayunstack/neutron | neutron/tests/unit/agent/l3/test_agent.py | Python | apache-2.0 | 165,163 | 0.000121 | # Copyright 2012 VMware, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | 'device_id': _uuid()}]
self.ri_kwargs = {'agent_conf': self.conf,
'interface_driver': self.mock_driver}
def _process_router_instance_for_agent(self, agent, ri, router):
ri.router = router
if not ri.radvd:
ri.radvd = ra.DaemonMonitor(router['id'],
... | ri |
neuroidss/nupic.research | htmresearch/frameworks/location/location_network_creation.py | Python | agpl-3.0 | 17,520 | 0.005936 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2018, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | UniformLink", "",
srcOutput="dataOut", destInput="displacement")
# Link L6a to L4
network.link(L6aName, L4Name, "UniformLink", "",
srcOutput="activeCells", destInput="basalInput")
network.link(L6aName, L4Name, "UniformLink", "",
srcOutput="learnableCells", destInp | ut="basalGrowthCandidates")
# Link L4 feedback to L6a
network.link(L4Name, L6aName, "UniformLink", "",
srcOutput="activeCells", destInput="anchorInput")
network.link(L4Name, L6aName, "UniformLink", "",
srcOutput="winnerCells", destInput="anchorGrowthCandidates")
# Link reset sign... |
philiptzou/clincoded | src/clincoded/renderers.py | Python | mit | 7,833 | 0.000383 | from pkg_resources import resource_filename
from pyramid.events import (
BeforeRender,
subscriber,
)
from pyramid.httpexceptions import (
HTTPMovedPermanently,
HTTPPreconditionFailed,
HTTPUnauthorized,
HTTPUnsupportedMediaType,
)
from pyramid.security import forget
from pyramid.settings import a... | = stats.get('render_time', 0) + duration
request._stats_html_attribute = True
# Rendering huge pa | ges can make the node process memory usage explode.
# Ideally we would let the OS handle this with `ulimit` or by calling
# `resource.setrlimit()` from a `subprocess.Popen(preexec_fn=...)`.
# Unfortunately Linux does not enforce RLIMIT_RSS.
# An alternative would be to use cgroups, but that makes per-process limits
# ... |
tkaitchuck/nupic | lang/py/engine/__init__.py | Python | gpl-3.0 | 23,539 | 0.014741 | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditi... | gine, dtype + suffix)
arrayFactory.getType = getArrayType
if size:
a = arrayFactory(size)
else:
a = arrayFactory()
a._dtype = basicTypes[index]
return a
def ArrayRef(dtype):
return Array(dtype, None, True)
# -------------------------------------
#
# C O L L E C T I O N | W R A P P E R
#
# -------------------------------------
class CollectionIterator(object):
def __init__(self, collection):
self.collection = collection
self.index = 0
def next(self):
index = self.index
if index == self.collection.getCount():
raise StopIteration
self.index += 1
r... |
murarugeorgec/USB-checking | USB/USB_devices/usb_list.py | Python | gpl-3.0 | 11,203 | 0.015532 | #! /usr/bin/env python
#
# Copyright 2015 George-Cristian Muraru <[email protected]>
# Copyright 2015 Tobias Mueller <[email protected]>
# ... | GTK)
self.observer = MonitorObserver(self.device_monitor.monitor, callback = self.refresh,
name='monitor-observer')
Gtk.Window.__init__(self, title = "USBGnomento")
self.set_resizable(True)
self.set_border_width(10)
# Setting up the self.... | self.grid.set_row_homogeneous(True)
self.add(self.grid)
# Creating the ListStore model
self.usb_list = Gtk.ListStore(str, bool, str, str, str)
self.current_filter_usb = None
# Creating the filter, feeding it with the usb_list model
self.usb_filter = self.usb_l... |
RossBrunton/BMAT | users/migrations/0008_auto_20150712_2143.py | Python | mit | 379 | 0 | # - | *- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migr | ation(migrations.Migration):
dependencies = [
('users', '0007_settings_no_ads'),
]
operations = [
migrations.AlterModelOptions(
name='settings',
options={'verbose_name_plural': 'Settings'},
),
]
|
PragmaticMates/django-invoicing | invoicing/migrations/0021_invoice_related_document.py | Python | gpl-2.0 | 463 | 0 | # Generated by D | jango 2.0.6 on 2018-11-21 08:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('invoicing', '0018_invoice_attachments'),
# ('invoicing', '0020_auto_20181001_1025'),
]
operations = [
migrations.AddField(
model_name='i... | rue, max_length=100),
),
]
|
Yukarumya/Yukarum-Redfoxes | testing/firefox-ui/tests/puppeteer/test_security.py | Python | mpl-2.0 | 1,926 | 0 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from firefox_puppeteer import PuppeteerMixin
from firefox_puppeteer.errors import NoCertificateError
from marionette_har... | ozqa.com'
with self.marionette.using_context(self.marionette.CONTEXT_CONTENT):
self.marionette.navigate(url)
cert = self.browser.tabbar.tabs[0].certificate
self.assertIn(cert['co | mmonName'], url)
self.assertEqual(cert['organization'], 'Mozilla Corporation')
self.assertEqual(cert['issuerOrganization'], 'DigiCert Inc')
address = self.puppeteer.security.get_address_from_certificate(cert)
self.assertIsNotNone(address)
self.assertIsNotNone(address['city'])
... |
kaathleen/LeapGesture-library | DynamicGestures/dlib-18.5/python_examples/max_cost_assignment.py | Python | mit | 2,357 | 0.00891 | #!/usr/bin/python
# The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
#
#
# This simple example shows how to call dlib's optimal linear assignment problem solver.
# It is an implementation of the famous Hungarian algorithm and is quite fast, operating in
# O(N^3) time.
#
# COMPIL... | e, lets imagine we have 3 people and 3 jobs. We represent the amount of
# money each person will produce at each job with a cost matrix. Each row corresponds to a
# person and each column corresponds to a job. So for example, belo | w we are saying that
# person 0 will make $1 at job 0, $2 at job 1, and $6 at job 2.
cost = dlib.matrix([[1, 2, 6],
[5, 3, 6],
[4, 5, 0]])
# To find out the best assignment of people to jobs we just need to call this function.
assignment = dlib.max_cost_assignment(cost)
# T... |
Cheaterman/kivy | kivy/core/video/video_ffmpeg.py | Python | mit | 2,694 | 0.000371 | '''
FFmpeg video abstraction
========================
.. versionadded:: 1.0.8
This abstraction requires ffmpeg python extensions. We have made a special
extension that is used for the android platform but can also be used on x86
platforms. The project is available at::
http://github.com/tito/ffmpeg-android
The ... | video player.
Refer to the documentation of the ffmpeg-android project for more information
about the requirements.
'''
try:
import ffmpeg
except:
raise
from kivy.core.video import VideoBase
from kivy.graphics.texture import Texture
|
class VideoFFMpeg(VideoBase):
def __init__(self, **kwargs):
self._do_load = False
self._player = None
super(VideoFFMpeg, self).__init__(**kwargs)
def unload(self):
if self._player:
self._player.stop()
self._player = None
self._state = ''
... |
DocBO/mubosym | mubosym/interp1d_interface.py | Python | mit | 1,728 | 0.015046 | # -*- coding: utf-8 -*-
"""
Created on Sat May 16 18:33:20 2015
@author: oliver
"""
from sympy import symbols, lambdify, sign, re, acos, asin, sin, cos, bspline_basis
from matplotlib import pyplot as plt
from scipy.interpolate import interp1d
import numpy as np
def read_kl(filename):
with open(filename, 'r') a... | x != '']
inlist = [ x for x in inlist if x[0] != '#']
inlist = [x.split(' ') for x in inlist]
#print inlist
x_in = np.array([ float(x[0]) for x in inlist])
y_in = np.array([ float(x[1]) for x in inlist])
return x_in, y_in
class interp(object):
"""
The main connection between an ext... | zed by a number of points and the mubosym
After running the initialization the base-functions are setup (by means of optimized coefficients)
:param filename: the external file with a list of x y - values (table, separation sign is space), if filename is empty the function f11 is taken instead
:param ts... |
Danielhiversen/home-assistant | tests/components/plugwise/test_config_flow.py | Python | apache-2.0 | 13,553 | 0.000516 | """Test the Plugwise config flow."""
from unittest.mock import AsyncMock, MagicMock, patch
from plugwise.exceptions import (
ConnectionFailedError,
InvalidAuthentication,
PlugwiseException,
)
import pytest
from homeassistant import setup
from homeassistant.components.plugwise.const import (
API,
D... | ASSWORD,
CONF_PORT: DEFAULT_PORT,
CONF_USERNAME: TEST_USERNAME,
PW_TYPE: API,
}
assert len(mock_setup_entry.mock_calls) == 1
async def test_zeroconf_form(hass):
"""Test we get the form."""
await setup.async_setup_component(hass, "persistent_notification", {})
result = awai... | DOMAIN,
context={CONF_SOURCE: SOURCE_ZEROCONF},
data=TEST_DISCOVERY,
)
assert result["type"] == RESULT_TYPE_FORM
assert result["errors"] == {}
with patch(
"homeassistant.components.plugwise.config_flow.Smile.connect",
return_value=True,
), patch(
"homeassist... |
sparkica/simex-service | service.py | Python | gpl-2.0 | 1,442 | 0.021498 | from flask import Flask
from fla | sk.ext import restful
from flask.ext.restful import Resource, reqparse
from lxml import html
import urllib2
import json
app = Flask(__name__)
api = restful.Api(app)
parser = reqparse.RequestParser()
parser.add_argument('url', type=str, location='form')
parser.add_argument('xpath', type=str, location='form')
parser.... | args['xpath']
element_attribute = args['attribute']
result = self.parse_html(source_url, element_xpath, element_attribute)
results = {'elements': [{'value': result }]}
return json.dumps(results)
def get(self):
results = {'elements': [{'value':result}]}
return json.dumps(results)
def parse_html(self, s... |
TU-NHM/plutof-taxonomy-module | apps/taxonomy/tests/act_tests.py | Python | gpl-3.0 | 2,683 | 0.003354 | from django.test import TestCase
from apps.taxonomy.models import Act
from apps.taxonomy.tests import factories
from apps.taxonomy.tests.base import TaxonomyBaseTestMixin
class TestActCreation(TestCase):
def setUp(self):
super(TestActCreation, self).setUp()
factories.TaxonRankFactory(id=0)
... | m"
taxonnode.save()
self.assertEqual(Act.objects.filter(taxon_node=taxonnode, type="marked_as_synonym").count(), 1)
def test_create_change_to_basionym_act(self):
valid_name = factories.TaxonNodeFactory()
taxonnode = factories.TaxonNodeFactory(tree=valid_name.tree)
taxonnode.... | ssertEqual(Act.objects.filter(taxon_node=taxonnode, type="marked_as_basionym").count(), 1)
def test_create_change_nomen_status_act(self):
taxonnode = factories.TaxonNodeFactory()
taxonnode.nomenclatural_status = "established"
taxonnode.save()
self.assertEqual(Act.objects.filter(taxo... |
compatibleone/accords-platform | tools/codegen/OCCI/Backend.py | Python | apache-2.0 | 544 | 0.011029 | class Backend(object):
'''
Backend type with a plugi | n and zero or more parameters (Parameter functionality is TBD.
Links to categories handled by this backend
'''
def __init__(self, plugin, params):
self._plugin = plugin
self._params = params
self._categories = []
@property
def plugin(self):
return self._plugi... | rams
def add_category(self, category):
self._categories.append(category)
|
kyouko-taiga/tango | tango/transpilers/cpp.py | Python | apache-2.0 | 8,789 | 0.001252 | import hashlib
from tango.ast import *
from tango.builtin import Int, Double, String
from tango.types import FunctionType, NominalType, TypeUnion
def transpile(module, header_stream, source_stream):
transpiler = Transpiler(header_stream, source_stream)
transpiler.visit(module)
def compatibilize(name):
... | .format(node))
# FIXME This discriminator isn't good enough, as different
# signatures may have the same string representation, since
# their `__str__` implementation doesn't use full names.
discriminator = hashlib.sha1(str(discriminating_type).enc... | '_' + node.name + discriminator)
if isinstance(node, PrefixedExpression):
return '{}.{}({})'.format(
self.translate_type(node.operand.__info__['type']),
operator_translations[node.operator],
self.translate_expr(node.operand))
if isinstance(no... |
michaelwisely/django-competition | src/competition/views/competition_views.py | Python | bsd-3-clause | 1,178 | 0.000849 | from django.views.generic import ListView, DetailView
from django.core.exceptions import ObjectDoesNotExist
from competition.models.competition_model import Competition
class CompetitionListView(ListView):
"""Lists every single competition"""
| context_object_name = 'competitions'
model = Competition
template_name = 'competition/competition/competition_list.html'
paginate_by = 10
class CompetitionDetailView(DetailView):
"""Shows details about a particular competition"""
context_object_name = 'competition'
model = Competition
s... | tail.html'
def get_context_data(self, **kwargs):
context = super(CompetitionDetailView, self).get_context_data(**kwargs)
competition = self.object
user = self.request.user
context['user_registered'] = competition.is_user_registered(user)
context['user_team'] = None
t... |
eLBati/purchase-workflow | framework_agreement/model/pricelist.py | Python | agpl-3.0 | 3,558 | 0.000281 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Nicolas Bessi
# Copyright 2013, 2014 Camptocamp SA
#
# This program is free sof | tware: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WI... | RPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from dateti... |
ulisespereira/PereiraBrunel2016 | figure7/plotting.py | Python | gpl-2.0 | 5,736 | 0.043061 | import numpy as np
import matplotlib.pyplot as plt
from stimulus import *
from myintegrator import *
from functions import *
import matplotlib.gridspec as gridspec
import cPickle as pickle
#-------------------------------------------------------------------
#-------------------------------------------------------------... | jet'
fig = plt.figure(figsize=(19, 11))
gs = gridspec.GridSpec(2, 2)#height_ratios=[3,3,2])
gs.update(wspace=0.44,hspace=0.03)
gs0 = gridspec.GridSpec(2, 2)
gs0.update(wspace=0.05,hspace=0.4,left=0.54,right=1.,top=0.88,bottom | =0.1106)
#gs1.update(wspace=0.05,hspace=0.4,left=0.1245,right=1.,top=0.21,bottom=0.05)
# Excitatory and Inhibitory weights
ax1A = plt.subplot(gs[0,0])
ax1B = plt.subplot(gs[1,0])
#sequence
axSA = plt.subplot(gs0[1,0])
axPA = plt.subplot(gs0[1,1])
#stimulation
ax2B= plt.subplot(gs0[0,0])
ax2C= plt.subplot(gs0[0,1])
... |
jnsebgosselin/WHAT | gwhat/common/styles.py | Python | gpl-3.0 | 1,792 | 0.001117 | # -*- coding: utf-8 -*-
# Copyright © 2014-2018 GWHAT Project Contributors
# https://github.com/jnsebgosselin/gwhat
#
# This file is part of GWHAT (Ground-Water Hydrograph Analysis Toolbox).
# Licensed under the terms of the GNU General Public License.
# Standard library imports :
import platform
# Third party impo... | ux':
self.fontfamily = "Ubuntu"
# self.fontSize1.setPointSize(11)
# 17 = QtGui.QFrame.Box | QtGui.QFrame.Plain
# 22 = QtGui.QFrame.StyledPanel | QtGui.QFrame.Plain
# 20 = QtGui.QFrame.HLine | QtGui.QFr | ame.Plain
# 52 = QtGui.QFrame.HLine | QtGui.QFrame.Sunken
# 53 = QtGui.QFrame.VLine | QtGui.QFrame.Sunken
|
chrisglass/buildout-django_base_project | myproject/settings.py | Python | bsd-3-clause | 5,070 | 0.001578 | # Django settings for myproject project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '[email protected]'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
... | l operating systems.
# On Unix systems, a val | ue of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-i... |
moiseslorap/RIT | Intro to Software Engineering/Release 2/HealthNet/HealthNet/wsgi.py | Python | mit | 395 | 0 | """
WSGI config for HealthNet pro | ject.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/w | sgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "HealthNet.settings")
application = get_wsgi_application()
|
netantho/MozDef | tests/conftest.py | Python | mpl-2.0 | 2,263 | 0.028281 | import pytest
import tempfile
import os
import ConfigParser
def getConfig(optionname,thedefault,section,configfile):
"""read an option from a config | file or set a default
send 'thedefault' as the data class you want to get a string back
i.e. 'True' will return a string
True will return a bool
1 will return an int
"""
#getConfig('something','adefaultvalue')
retvalue=thedefault
opttype=type(thedefault)
if os.path... | ion,optionname):
if opttype==bool:
retvalue=config.getboolean(section,optionname)
elif opttype==int:
retvalue=config.getint(section,optionname)
elif opttype==float:
retvalue=config.getfloat(section,optionname)
else:
... |
stellaf/sales_rental | sale_rental/models/product.py | Python | gpl-3.0 | 2,194 | 0 | # -*- coding: utf-8 -*-
# Copyright 2014-2016 Akretion (http://www.akretion.com)
# @author Alexis de Lattre <[email protected]>
# Copyright 2016 Sodexis (http://sodexis.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp import models, fields, api, _
from openerp.exceptions imp... | 'product.product', 'rented_product_id',
string='Related Rental Services')
@api.one
@api.constrains('rented_product_id', 'must_have_dates', 'type', 'uom_id')
def _check_rental(self):
if self.rented_product_id and self.type != 'service':
raise ValidationError(_(
"T... | ental product '%s' must be of type 'Service'.")
% self.name)
if self.rented_product_id and not self.must_have_dates:
raise ValidationError(_(
"The rental product '%s' must have the option "
"'Must Have Start and End Dates' checked.")
% ... |
CloudifySource/cloudify-aws | setup.py | Python | apache-2.0 | 1,176 | 0 | ########
# Copyright (c) 2013 G | igaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law | or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
__author__ = 'Ganesh'
f... |
christophmark/bayesloop | bayesloop/fileIO.py | Python | mit | 947 | 0.002112 | #!/usr/bin/env python
"""
The following functions save or load instances of all `Study` types using the Python package `dill`.
"""
from __future__ import division, print_function
import dill
def save(filename, study):
"""
Save an instance | of a bayesloop study class to file.
Args:
filename(str): Path + filename to store bayesloop study
study: Instance of study class (Study, HyperStudy, etc.)
"""
with open(filename, 'wb') as f:
dill.dump(study, f, protocol=dill.HIGHEST_PROTOCOL)
print('+ Successfully saved current ... | ave() function.
Args:
filename(str): Path + filename to stored bayesloop study
Returns:
Study instance
"""
with open(filename, 'rb') as f:
S = dill.load(f)
print('+ Successfully loaded study.')
return S
|
pvarenik/PyCourses | model/group.py | Python | gpl-2.0 | 592 | 0.005068 | __author__ = 'pvarenik'
from sys import maxsize
class Group:
def __init__(self, name=None, header=None, footer=None, id=None):
self.name = name
self.header = header
self.footer = footer
self.id = id
| def __repr__(self):
return "%s,%s,%s,%s" % (self.id, self.name, self.header, self.footer)
def __eq__(self, other):
return (self.id is None or other.id is None or self.id == other.i | d) and self.name == other.name
def id_or_max(self):
if self.id:
return int(self.id)
else:
return maxsize |
brianmckinneyrocks/django-social-auth | contrib/tests/test_core.py | Python | bsd-3-clause | 5,521 | 0.00163 | # -*- coding: utf-8 -*-
import urlparse
from selenium import webdriver
from django.test import TestCase
from django.conf import settings
class BackendsTest(TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def tearDown(self):
self.driver.quit()
def url(self, path):
... | (TEST_FACEBOOK_PASSWORD)
self.driver.get(self.url('/login/facebook/'))
# We log in
username_field = self.driver.find_element_by_id('email')
username_field.send_keys(TEST_FACEBOOK_USER)
password_field = self.driver.find_elemen | t_by_id('pass')
password_field.send_keys(TEST_FACEBOOK_PASSWORD)
password_field.submit()
try:
self.driver.find_element_by_name('grant_clicked').click()
except:
pass
# We check the user logged in
heading = self.driver.find_element_by_id('heading')... |
Khan/reviewboard | reviewboard/attachments/admin.py | Python | mit | 582 | 0 | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from reviewboard.attachments.model | s import FileAttachment
class FileAttachmentAdmin(admin.ModelAdmin):
list_display = ('file', 'caption', 'mimetype',
'review_request_id')
list_display_links = ('file', 'caption')
search_fields = ('caption', 'mimetype')
def review_request_id(self, obj):
return obj.review_req... | eAttachmentAdmin)
|
SKIRT/PTS | evolve/genomes/nucleobases.py | Python | agpl-3.0 | 1,754 | 0.001711 | #!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... | ------------------------------------------------
class N | ucleoBases(G1DBase):
"""
NucleoBases genome
"""
__slots__ = ["nbases"]
# -----------------------------------------------------------------
def __init__(self, nbases):
"""
The initializator of the NucleoBases genome representation
"""
# Call the constructor ... |
SeedScientific/polio | datapoints/migrations/0039_auto__chg_field_region_region_code.py | Python | agpl-3.0 | 15,288 | 0.008242 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Region.region_code'
db.alter_column('region', 'region_... | ion', 'campaign']", 'unique_together': "(('indicator', 'region', 'campaign'),)", 'object_name': 'DataPoint', 'db_table': "'datapoint'"},
'campaign': ('django.db.mode | ls.fields.related.ForeignKey', [], {'to': u"orm['datapoints.Campaign']"}),
'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
u'id': ('djang... |
CKehl/pylearn2 | pylearn2/scripts/tutorials/convolutional_network/autoencoder.py | Python | bsd-3-clause | 201 | 0.004975 | from pylearn2.models.mlp import M | LP
class Autoencoder(MLP):
"""
An MLP whose output domain is the same as its input domain.
"""
def get_target_source(self):
retu | rn 'features'
|
tpeek/Copy-n-Haste | CopyHaste/cnh_profile/migrations/0002_auto_20150810_1822.py | Python | mit | 764 | 0.002618 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrati | ons
class Migration(migrations.Migration):
dependencies = [
('cnh_profile', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='cnhprofile',
name='website_url',
),
migrations.AddField(
model_name='cnhprofile',
... | bsite',
field=models.URLField(help_text=b'What is your website URL?', blank=True),
),
migrations.AlterField(
model_name='cnhprofile',
name='nickname',
field=models.CharField(help_text=b'What is your nickname', max_length=16, null=True, blank=True),
... |
jpshort/odoo | marcos_addons/marcos_stock/__openerp__.py | Python | agpl-3.0 | 2,134 | 0.001406 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2013-2015 Marcos Organizador de Negocios SRL http://marcos.do
# Write by Eneldo Serrata ([email protected])
#
# This program is free software: you can redistribute it and/or modify
# it un... | ater version.
#
# T | his 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General ... |
wallnerryan/quantum_migrate | quantum/agent/linux/external_process.py | Python | apache-2.0 | 3,644 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012 New Dream Network, LLC (DreamHost)
#
# 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/li... | e name for a given kind of config file."""
pids_dir = os.path.abspath(os.path.normpath(self.conf.external_pids))
if ensure_pids_dir and not os.path.isdir(pids_dir):
os.makedirs(pids_d | ir, 0755)
return os.path.join(pids_dir, self.uuid + '.pid')
@property
def pid(self):
"""Last known pid for this external process spawned for this uuid."""
file_name = self.get_pid_file_name()
msg = _('Error while reading %s')
try:
with open(file_name, 'r') ... |
google/eng-edu | ml/guides/text_classification/train_sequence_model.py | Python | apache-2.0 | 5,062 | 0 | """Module to train sequence model.
Vectorizes training and validation texts into sequences and uses that for
training a sequence model - a sepCNN model. We use sequence model for text
classification when the ratio of number of samples to number of words per
sample for the given dataset is very large (>~15K).
"""
from ... | equence model | on the given dataset.
# Arguments
data: tuples of training and test texts and labels.
learning_rate: float, learning rate for training model.
epochs: int, number of epochs.
batch_size: int, number of samples per batch.
blocks: int, number of pairs of sepCNN and pooling block... |
lig/pystardict | pystardict.py | Python | gpl-3.0 | 19,916 | 0.001308 | import gzip
import hashlib
import os
import re
import warnings
from struct import unpack
import six
class _StarDictIfo(object):
"""
The .ifo file has the following format:
StarDict's dict ifo file
version=2.4.2
[options]
Note that the current "version" string must be "2.4.2" or "3.0.0". If... | _config.get('website', '').strip()
self.description = _config.get('description', '').strip()
self.date = _config.get('date', '').strip()
self.sametypesequence = _config.get('sametypesequence', '').strip()
class _StarDictIdx(object):
"""
The .idx file is just a word list.
The wo... | one after the other:
word_str; // a utf-8 string terminated by '\0'.
word_data_offset; // word data's offset in .dict file
word_data_size; // word data's total size in .dict file
"""
def __init__(self, dict_prefix, container):
self._container = container
idx_file... |
aronparsons/spacewalk | backend/server/action/kickstart_guest.py | Python | gpl-2.0 | 4,321 | 0.001389 | #
# Copyright (c) 2008--2015 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a c... | raise InvalidAction(str(e)), None, sys.exc_info()[2]
log_debug(3, "Completed scheduling install of rhn-virtualization-guest!")
raise ShadowAction("Scheduled installation of RHN Virtualization Guest packages.")
def initiate(server_id, action_id, dry_run=0):
log_debug(3)
h = rhnSQL.prepare(_query_in... | :
raise InvalidAction("Kickstart action without an associated kickstart")
kickstart_host = row['kickstart_host']
virt_type = row['virt_type']
name = row['guest_name']
boot_image = "spacewalk-koan"
append_string = row['append_string']
vcpus = row['vcpus']
disk_gb = row['disk_gb']
... |
cocoaaa/ml_gesture | feature_selection.py | Python | mit | 14,963 | 0.026064 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 24 17:55:05 2015
@author: LLP-admin
"""
import os
import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.decomposition import PCA
#encoding
from sklearn.preprocessing import LabelEncoder
... | erset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
"""Returns the generator for powerset of the interable"""
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in xrange(len(s)+1))
##############################################################... | sts).
For example, given L = [1,2,3], it returns [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]].
This algorithm is memoized. Don't forget the memo (a dictionary) right above the definition
of this function.
"""
if frozenset(L) in memo:
pwrSet = memo[frozenset(L)];
else:
#Base... |
Bielicki/lcda | excel_upload/apps.py | Python | gpl-3.0 | 98 | 0 | from django.app | s import AppConfig
class ExcelUploadConfig(AppConfig):
na | me = 'excel_upload'
|
robacklin/sigrok | libsigrokdecode/decoders/z80/__init__.py | Python | gpl-3.0 | 1,313 | 0.009139 | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2014 Daniel Elstner <[email protected]>
##
## 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... | details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, see <http://www.gnu.org/licenses/>.
##
'''
The Zilog Z80 is an 8-bit microprocessor compatible with the Intel 8080.
In addition to the 8-bit data bus, this decoder requires the input signals
/M1 (mach... | /WR (write) to do its work. An explicit
clock signal is not required. However, the Z80 CPU clock may be used as
sampling clock, if applicable.
Notes on the Z80 opcode format and descriptions of both documented and
"undocumented" opcodes are available here:
http://www.z80.info/decoding.htm
http://clrhome.org/table... |
katyhuff/moose | python/MooseDocs/MooseApplicationSyntax.py | Python | lgpl-2.1 | 13,523 | 0.002884 | import os
import re
import copy
import collections
import logging
import MooseDocs
import collections
import subprocess
import yaml
log = logging.getLogger(__name__)
class PagesHelper(object):
"""
A helper class for checking if a markdown file is include in the 'pages.yml' file.
"""
def __init__(self,... | ages, default_flow_style=False)
def check(self, filename):
return filename in self.raw
@staticmethod
def create(root):
"""
Generated nested 'pages.yml' files.
"""
# Define the pages.yml file
pages = os.path.join(root, 'pages.yml')
content = []
... | directory
for item in os.listdir(root):
full = os.path.join(root, item)
txt = None
if os.path.isdir(full):
txt = '- {}: !include {}\n'.format(item, os.path.join(full, 'pages.yml'))
PagesHelper.create(full)
elif full.endswith('.md')... |
geokala/cloudify-agent | cloudify_agent/api/utils.py | Python | apache-2.0 | 10,561 | 0 | #########
# Copyright (c) 2015 GigaSpaces Technologies Ltd. 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... | TORY'
CLOUDIFY_DAEMON_USER_KEY = 'CLOUDIFY_DAEMON_USER'
@classmethod
def get_daemon_name(cls):
"""
Returns the name of the currently running daemon.
"""
return os.environ[cls.CLOUDIFY_DAEMON_NAME_KEY]
@classmethod
def get_daemon_storage_dir(cls):
"""
... | current daemon is stored under.
"""
return os.environ[cls.CLOUDIFY_DAEMON_STORAGE_DIRECTORY_KEY]
@classmethod
def get_daemon_user(cls):
"""
Return the user the current daemon is running under
"""
return os.environ[cls.CLOUDIFY_DAEMON_USER_KEY]
@staticmet... |
yochow/autotest | client/tests/isic/isic.py | Python | gpl-2.0 | 831 | 0.008424 | import os
from autotest_lib.client.bin import test, utils
class isic(test.test):
version = 2
# http://www.packetfactory.net/Projects/ISIC/isic-0.06.tgz
# + http://www.stardust.webpages.pl/files/crap/isic-gcc41-fix.patch
def initialize(self):
self.job.require_gcc()
self.job.setup_dep(... | arball = utils.unmap_url(self.bindir, tarball, self.tmpdir)
utils.extract_tarball_to_dir(tarball, self.srcdir)
os.chdir(self.srcdir)
utils.system('patch -p1 < ../build-fixes.patch')
utils.system('PREFIX=%s /deps/libnet/libnet/ ./configure' %self.autodir)
utils.system('make')
... | -p 10000000'):
utils.system(self.srcdir + '/isic ' + args)
|
reyoung/Paddle | python/paddle/fluid/tests/unittests/test_sequence_unpad_op.py | Python | apache-2.0 | 2,170 | 0 | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | xrange(1, x.shape[0]):
out = np.append(out, x[i, 0:self.length[i]], axis=0)
out_shape = (sum(self.length), )
if len(self.x_shape) == 2:
out_shape = out_shape + (1, )
else:
out_shape = out_shape + self.x_shape[2:]
self.i | nputs = {
'X': x,
'Length': np.array(self.length).astype('int64').reshape(-1, 1)
}
self.outputs = {'Out': (out.reshape(out_shape), out_lod)}
def setUp(self):
self.op_type = 'sequence_unpad'
self.init()
self.compute()
def test_check_output(self):
... |
carvalhodj/qunews | rabbitmq/receive.py | Python | apache-2.0 | 1,031 | 0.00291 | import pika
import sys
credentials = pika.PlainCredentials('qunews', 'qunews')
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', 5672, 'qunews_host', credentials))
channel = connection.channel()
channel.exchange_declare(exchange='qunews_data',
type='topic')
result =... | clare()
queue_name = result.method.queue
binding_keys = sys.argv[1:]
if not binding_keys:
sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0])
sys.exit(1)
for binding_key in binding_keys:
channel.queue_bind(exchange='qunews_data',
queue=queue_name,
r... | % (method.routing_key, body))
if body[0:2] == 'ef':
print("MAC comeca com 'ef'")
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()
|
djkonro/client-python | kubernetes/client/models/v1_container_state_waiting.py | Python | apache-2.0 | 3,830 | 0.000522 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.7.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
... | ssage.setter
def message(self, message):
"""
Sets the message of this V1ContainerStateWaiting.
Message regarding why the container is not yet running.
:param message: The message of this V1ContainerStateWaiting.
:type: str
"""
self._message = message
@p... | s not yet running.
:return: The reason of this V1ContainerStateWaiting.
:rtype: str
"""
return self._reason
@reason.setter
def reason(self, reason):
"""
Sets the reason of this V1ContainerStateWaiting.
(brief) reason the container is not yet running.
... |
yceruto/django-formapi | formapi/__init__.py | Python | mit | 348 | 0 | VERSION = (0, 0, 1, 'dev')
# Dynamically calculate the version based on VERSION tuple
if len(VERSION) > 2 and VERSION[2] is not None:
| if isinstance(VERSION[2], int):
str_version = "%s.%s.%s" % VERSION[:3]
| else:
str_version = "%s.%s_%s" % VERSION[:3]
else:
str_version = "%s.%s" % VERSION[:2]
__version__ = str_version
|
skmezanul/seahub | seahub/profile/models.py | Python | apache-2.0 | 3,686 | 0.003256 | from django.conf import settings
from django.db import models
from django.core.cache import cache
from django.dispatch import receiver
from seahub.base.fields import LowerCaseCharField
from seahub.profile.settings import EMAIL_ID_CACHE_PREFIX, EMAIL_ID_CACHE_TIMEOUT
from registration.signals import user_registered
cl... | (self, username, nickname, intro, lang_code=None):
"""Add or update user profile.
"""
try:
profile = self.get(user=username)
profile.nickname = nickname
profile.intro = intro
profile.lang_code = lang_code
except Profile.DoesNotExist:
... | name, nickname=nickname,
intro=intro, lang_code=lang_code)
profile.save(using=self._db)
return profile
def get_profile_by_user(self, username):
"""Get a user's profile.
"""
try:
return super(ProfileManager, self).get(user=username... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.