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
faircloth-lab/data-theme
_plugins/jekyll-rst/directives.py
Python
mit
3,665
0.005457
# Define a new directive `code-block` (aliased as `sourcecode`) that uses the # `pygments` source highlighter to render code in color. # # Incorporates code from the `Pygments`_ documentation for `Using Pygments in # ReST documents`_ and `Octopress`_. # # .. _Pygments: http://pygments.org/ # .. _Using Pygments in Re...
= HtmlFormatter() # Construct cache filename cache_file = None content_text = u'\n'.join(self.content) cache_file_name = '%s-%s.html' % (lexer_name, md5.new(content_text).hexdigest()) cached_path = os.path.join(PYGMENTS_CACHE_DIR, cache_fil
e_name) # Look for cached version, otherwise parse if os.path.exists(cached_path): cache_file = open(cached_path, 'r') parsed = cache_file.read() else: parsed = highlight(content_text, lexer, formatter) # Strip pre tag and everything outside it ...
qdulab/OEMS
student/tests.py
Python
mit
3,632
0.000826
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase from django.test.client import Client from django.test.utils import override_settings @override_settings(AUTHENTICATION_BACKENDS= ('django.contrib.auth.backends.ModelBackend',))...
self.assertTrue(self.student.profile) self.assertEqual(self.student.profile.school_id, '') self.assertEqual(self.student.profile.grade, '') self.assertEqual(self.student.profile.class_num, '') self.assertEqual(self.student.profile.phone_num, '') self.assertEqual(self.stud...
esponse = self.client.post(reverse('update_student_profile'), {'school_id': 'school_id', 'grade': 'grade', 'major': 'major', 'class_num': 'class_num', ...
Onirik79/aaritmud
data/proto_items/carrozzone-zingaro/carrozzone-zingaro_item_cumulo-stracci.py
Python
gpl-2.0
2,398
0.01586
# -*- coding: utf-8 -*- #= DESCRIZIONE ================================================================= # Qui l'idea è che l'oggetto sia una numero di canovacci a costituire l'item # l'oggetto vede diminuire il suo peso man mano che si prelvano canovacci # quando il peso scende sotto una certa soglia l'oggetto è rim...
= FUNZIONI ==================================================================== def before_try_to_get(entity, target, location, behavioured): matasse_db = {1: "carrozzone-zingaro_item_canovaccio-01-macchiato", 2: "carrozzone-zing
aro_item_canovaccio-01-pulito", 3: "carrozzone-zingaro_item_canovaccio-01-usurato", 4: "carrozzone-zingaro_item_canovaccio-02-macchiato", 5: "carrozzone-zingaro_item_canovaccio-02-pulito", 6: "carrozzone-zingaro_item_canovaccio-02-usurato"} ...
coopernurse/radiator
test/helper.py
Python
mit
4,183
0.001913
import os import sys import logging import base64 import time from radiator import Broker from radiator.reactor import GeventReactor def getenv(key, default): if os.environ.has_key(key): return os.environ[key] else: return default class ScenarioLogHandler(logging.Handler): errors = [] ...
part = min(total, 200) for i in range(part): t = reactor.start_client(lambda c: self.start_consumer(c, i)) gl.append(t) for t in gl: self.reactor.join(t) total
-= part self.millis = int((time.time() - start) * 1000) def start_producer(self, c): msg = "" for i in range(0, 1024): msg += "z" self.base_msg = msg for i in range(0, self.msg_count): body = "%d - %s" % (i, msg) c.send(self.dest_name, b...
jasonwee/asus-rt-n14uhp-mrtg
src/lesson_language_tools/dis_simple.py
Python
apache-2.0
19
0
m
y_di
ct = {'a': 1}
noroutine/ansible
lib/ansible/modules/cloud/amazon/elb_target_group.py
Python
gpl-3.0
29,144
0.004598
#!/usr/bin/python # Copyright: Ansible Project # 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 ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], ...
lancer." health_check_path: description: - The ping path
that is the destination on the targets for health checks. The path must be defined in order to set a health check. required: false health_check_interval: description: - The approximate amount of time, in seconds, between health checks of an individual target. required: false health_check_timeout:...
gamechanger/kafka-python
test/fixtures.py
Python
apache-2.0
9,197
0.001305
import logging import os import os.path import shutil import subprocess import tempfile import time from six.moves import urllib import uuid from six.moves.urllib.parse import urlparse # pylint: disable=E0611,F0401 from test.service import ExternalService, SpawnedService from test.testutil import get_open_port log =...
_run_class_args("org.apache.zookeeper.ZooKeeperMain",
"-server", "%s:%d" % (self.zk_host, self.zk_port), "create", "/%s" % self.zk_chroot, "kafka-python") env = self.kafka_run_class_env() proc = subprocess.Po...
Tesora/tesora-tempest
tempest/api/compute/test_extensions.py
Python
apache-2.0
2,079
0
# Copyright 2012 OpenStack Foundation # 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 requ...
r implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_log import log as logging from tempest.api.compute import base from tempest import config from tempest import test CONF = config.CONF LOG = logging.getLogger(__name__) class Extension...
t): @test.idempotent_id('3bb27738-b759-4e0d-a5fa-37d7a6df07d1') def test_list_extensions(self): # List of all extensions if len(CONF.compute_feature_enabled.api_extensions) == 0: raise self.skipException('There are not any extensions configured') extensions = self.extensions...
AlexHung780312/SmilNN
example/cdssm_pred.py
Python
mit
3,956
0.008595
# -*- coding: utf-8 -*- import numpy as np import scipy.sparse as sp from scipy.sparse import lil_matrix from nltk.tokenize import RegexpTokenizer from keras import backend as K from keras.models import Sequential from keras.engine.topology import Layer from keras.constraints import unitnorm from keras.regularizers imp...
2) for row, (word, tag) in enumerate(train_tri): for n, w in enumerate(word): for tri in w: X_train[row, n, dictionary.index(tri)] = 1.0 for row, (word, tag) in enumerate(test_tri): for n, w in enumerate(word): for tri in w: X_test[row, n, dictionary.index(tri)] = 1.0 # ...
e(train_tri): y_train[row, 1 if tag=='pos' else 0] = 1.0 for row, (tri, tag) in enumerate(test_tri): y_test[row, 1 if tag=='pos' else 0] = 1.0 # http://research.microsoft.com/apps/pubs/default.aspx?id=256230 model = Sequential() model.add(Convolution1D(1000, 3, activation='tanh', W_regularizer=l1l2(l1=0.01, l2...
amol9/mayloop
mayloop/imported/twisted/internet_protocol.py
Python
mit
7,110
0.00225
# -*- test-case-name: twisted.test.test_factories,twisted.internet.test.test_protocol -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Standard implementations of Twisted protocol-related interfaces. Start here if you are looking to write a new protocol implementation for Twisted. The ...
et.interfaces.ITransport}. Override C{connectionLost} to be notified when the connection ends. Some subcla
sses exist already to help you write common types of protocols: see the L{twisted.protocols.basic} module for a few of them. """ def logPrefix(self): """ Return a prefix matching the class name, to identify log messages related to this protocol instance. """ return s...
masashi-y/myccg
src/py/biaffine.py
Python
mit
4,058
0.005421
import math import numpy as np from chainer import cuda from chainer.functions.connection import linear from chainer import link from chainer import functions as F from chainer import initializer from chainer.initializers.normal import HeNormal from chainer.initializers.constant import Constant from chainer.initialize...
ializer, scale=1.0): self.initializer = initializer self.scale = scale dtype = getattr(initializer, 'dtype', None) super(Identity, self).__init__(dtype) def __call__(self, array): self.initializer(array) array *= self.scale class Biaffine(link.Link):
def __init__(self, in_size, wscale=1, initialW=None, initial_bias=None): super(Biaffine, self).__init__() self._W_initializer = _get_initializer( initialW, math.sqrt(wscale)) self._initialize_params(in_size) def _initialize_params(self, in_size): sel...
mchughmk/react-django
backend/api/migrations/0001_initial.py
Python
mit
1,092
0.002747
# -*- coding: utf-8 -*- # Generated
by Django 1.11 on 2017-04-28 22:05 from __future__ import unicode_
literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Country', fields=[ ('id', models.AutoField(auto_c...
gloryofrobots/obin
arza/types/scope.py
Python
gpl-2.0
13,255
0.000754
from arza.types import space, plist, environment from arza.types.root import W_Root from arza.misc import platform from arza.types import api from arza.runtime import error from arza.builtins import lang_names ABSENT = platform.absent_index() class Symbols: def __init__(self, literals): self.literals = l...
x(name)) return self.imports.insert(name, func) def get_import_index(self, name): return api.get_index(self.imports, name)
def has_import(self, name): return api.contains_b(self.imports, name) ########################### def add_function(self, symbol, idx): self.functions.insert(symbol, space.newint(idx)) def get_function(self, symbol): idx = api.lookup(self.functions, symbol, space.newvoid()) ...
Blahhhhh/python-calamari-client
demo.py
Python
mit
5,490
0.004007
#!/usr/bin/env python #-*- coding: utf-8 -*- import sys import logging from calamari_client import LOG, CalamariAPIv1Connection, CalamariAPIv2Connection CALAMARI_HOST = 'http://127.0.0.1/' CALAMARI_USERNAME = 'root' CALAMARI_PASSWORD = 'root' def add_stdout_handler(logger): logger.setLevel(logg...
ter_list()[0]['id'] # fqdn = v2_connection.server_list()[0]['fqdn'] # # print v2_connection.iops_data(fsid, time_from='-12hour') # # print v2_connection.disk_usage_data(fsid) # # print v2_connection.server_cpu_data(fqdn) # #
print v2_connection.server_loadavg_data(fqdn) # # print v2_connection.server_memory_data(fqdn) # # server_cpu_id = v2_connection.graphite_metrics_find('servers.%s.cpu.*' % fqdn)[0]['id'] # # print v2_connection.server_cpu_detail_data(server_cpu_id) # # server_disk_id = v2_connection.graphite_met...
mivanov/editkit
editkit/pages/templatetags/pages_tags.py
Python
gpl-2.0
6,764
0.000887
from django import template from django.template.loader_tags import BaseIncludeNode from django.template import Template from django.conf import settings from pages.plugins import html_to_template_text, SearchBoxNode from pages.plugins import LinkNode, EmbedCodeNode from pages import models from django.utils.text impo...
de(parser, token) def is_quoted(text): ret
urn text[0] == text[-1] and text[0] in ('"', "'") @register.tag(name='embed_code') def do_embed_code(parser, token): nodelist = parser.parse(('endembed_code',)) parser.delete_first_token() return EmbedCodeNode(nodelist) @register.tag(name='searchbox') def do_searchbox(parser, token): try: ta...
kadircet/CENG
334/the2t/generator.py
Python
gpl-3.0
1,322
0.026475
import random as rand import sys MAXDOCK=100 MAXSHIP=500 MAXCARG=10000 MAXTIME=100 MSHPCAP=100 MAXRLEN=100 if len(sys.argv)>1: MAXDOCK = sys.argv[1] if len(sys.argv)>2: MAXSHIP = sys.argv[2] if len(sys.argv)>3: MAXCARG = sys.argv[3] Nd = rand.randint(2,MAXDOCK) Ns = rand.randint(1,MAXSHIP) Nc = rand.randin...
= (route[-1]+1)%Nd if route[-1]==org: print "GENERATION FAILED :-(" sys.exit(1) for i in range(L-1): n = rand.randint(0,Nd-1) org = n while n==route[-1] or dockCap[n]<=1: n = (n+1)%Nd i
f n==org: print "GENERATION FAILED :-(" sys.exit(1) route.append(n) dockCap[route[-1]]-=1 print rand.randint(1,MAXTIME), rand.randint(1,MSHPCAP), rand.randint(1,MAXTIME), L, " ".join(map(str,route)) for i in range(Nc): src = rand.randint(0,Nd-1) dst = rand.randin...
huggingface/transformers
src/transformers/models/detr/convert_detr_original_pytorch_checkpoint_to_pytorch.py
Python
apache-2.0
13,570
0.004937
# coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # 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...
weig
ht", f"encoder.layers.{i}.final_layer_norm.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.norm2.bias", f"encoder.layers.{i}.final_layer_norm.bias")) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (f"transformer.decoder....
dbarsam/python-vsgen
vsgen/__init__.py
Python
mit
841
0
# -*- coding: utf-8 -*- """ Main __init__.py for the vsgen package """ import pkg_resources try: pkg = pkg_resources.get_distribution("vsgen") __version__ = pkg.v
ersion except pkg_resources.DistributionNotFound: __version__ = "0.0.0.0" from vsgen.solution import VSGSolution from vsgen.project import VSGProject from vsgen.register import VSGRegisterable, VSGRegisterCommand from vsgen.writer import VSGWriter, VSGWritable, VSGWriteCommand from vsgen.suite import VSGSuite from...
, 'VSGProject', 'VSGRegisterable', 'VSGRegisterCommand', 'VSGWriter', 'VSGWritable', 'VSGWriteCommand', 'VSGSuite', 'VSGLogger', 'VSGTimer', 'VSGConfigParser' ]
dkorogodin/python_mantis
helpers/soap.py
Python
apache-2.0
1,072
0.003731
from helpers.basehelper import BaseHelper from suds.client import Client from suds import WebFault from model.project import Project class SoapHelper(BaseHelper): def __init__(self, app): self.app = app self.client = Client(self.app.base_url + self.app.config['soap']['url']) def can_login(se...
projects_list = [] try: soap_list = self.client.service.mc_projects_get_user_accessible(username, password) for project in soap_list: projects_list.append( Project(id=project["id"], name=project["name"], status=project["status"]["name"], ...
n projects_list except WebFault as ex: return ex
emencia/emencia-crma
crma/views.py
Python
gpl-2.0
1,158
0
# -*- coding: utf-8 -*- # Django from django.views.generic import View, TemplateView from django.shortcuts import redirect from django.core.urlresolvers import reverse from django.shortcuts import get_object_or_404 # CRMA from .models import Subscription, EmailScheduler from .models import cancel_subscription from .u...
=key) cancel_subscription(subs_info) return redirect(reverse(self.success_url)) class ViewWebMail(View): template_name = 'crma/mail_viewer.html' def get(self, request, *args, **kwargs): # Read the schedule item scheduler_id = decode_id(kwargs['scheduler_id']) token = ...
, token=token, template=self.template_name)
pybae/etc
CodeForces/492A.py
Python
mit
129
0
#!/usr/bin/env python n = int(input()) cou
nt =
0 i = 1 while count <= n: i += 1 count += i * (i - 1) / 2 print(i - 2)
lowRISC/opentitan
util/design/gen-mubi.py
Python
apache-2.0
416
0.004808
#!/usr/bin/env python3 # Copyright lowRISC contributors. # Licensed un
der the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 r"""Converts mubi mako templates """ from mubi import prim_mub
i from secded_gen import format_c_files def main(): prim_mubi.gen() c_path = prim_mubi.get_c_path() format_c_files(c_path, c_path) if __name__ == "__main__": main()
gregkorte/Python-Koans
python3/koans/about_monkey_patching.py
Python
mit
1,426
0.002104
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Related to AboutOpenClasses in the Ruby Koans # from runner.koan import * class AboutMonkeyPatching(Koan): class Dog: def bark(self): return "WOOF" def test_as_defined_dogs_do_bark(self): fido = self.Dog() self.assertEqual...
o an existing class. def test_after_patching_dogs_can_both_wag_and_bark(self): def wag(self): return "HAPPY" self.Dog.wag = wag fido = self.Dog() self.assertEqual('HAPPY', fido.wag()) self.assertEqual('WOOF', fido.bark()) # ----------------------------------------------...
def test_most_built_in_classes_cannot_be_monkey_patched(self): try: int.is_even = lambda self: (self % 2) == 0 except Exception as ex: err_msg = ex.args[0] self.assertRegex(err_msg, "can't set attributes of built-in/extension type 'int'") # --------------------...
jdavisp3/twisted-intro
twisted-client-8/get-poetry.py
Python
mit
4,824
0.000829
# This is the Twisted Get Poetry Now! client, version 8.0 import optparse, sys from twisted.internet import defer from twisted.internet.protocol import Protocol, ClientFactory from twisted.protocols.basic import NetstringReceiver def parse_args(): usage = """usage: %prog [options] [hostname]:port ... This is t...
d, self.deferred = self.deferred, None d.callback(poem) def clientConnectionLost(self, _, reason): if self.deferred is not None: d, self.deferred = self.deferred, None
d.errback(reason) clientConnectionFailed = clientConnectionLost class TransformProxy(object): """ I proxy requests to a transformation service. """ def __init__(self, host, port): self.host = host self.port = port def xform(self, xform_name, poem): facto...
supervacuo/pinry
pinry/core/tests/api.py
Python
bsd-2-clause
10,976
0.001002
import mock from django_images.models import Thumbnail from taggit.models import Tag from tastypie.exceptions import Unauthorized from tastypie.test import ResourceTestCase from .helpers import ImageFactory, PinFactory, UserFactory from ..models import Pin, Image from ...users.models import User __all__ = ['ImageRe...
u'height': thumbnail.height, }, u'square': { u'image': unicode(square.image.url), u'width': square.width, u'height': square.height, }, }) class PinResourceTest(ResourceTestCase): def setUp(self): supe
r(PinResourceTest, self).setUp() self.user = UserFactory(password='password') self.api_client.client.login(username=self.user.username, password='password') @mock.patch('requests.get', mock_requests_get) def test_post_create_url(self): url = 'http://testserver/mocked/logo.png' p...
sauloal/cnidaria
scripts/venv/lib/python2.7/site-packages/cogent/parse/kegg_taxonomy.py
Python
mit
3,470
0.005476
#!/usr/bin/env python __author__ = "Jesse Zaneveld" __copyright__ = "Copyright 2007-2012, The Cogent Project" __credits__ = ["Jesse Zaneveld", "Rob Knight"] __license__ = "GPL" __version__ = "1.5.3" __maintainer__ = "Jesse Zaneveld" __email__ = "zaneveld@gmail.com" __status__ = "Development" from sys import argv from...
line = line.rstrip() if not line: continue if line.startswith('#'): #line defining taxonomic level hashes, name = line.split(None, 1) name = name.strip() level = len(hashes) if level == len(taxonomy_stack): #new entry at same level ...
l: assume sequential taxonomy_stack.append(name) else: #level must be less than stack length: truncate del taxonomy_stack[level:] taxonomy_stack[level-1] = name else: #line defining an individual taxonomy entry fields = map(strip, line....
rahulunair/nova
nova/db/sqlalchemy/api_migrations/migrate_repo/versions/058_cell_mapping_add_disabled.py
Python
apache-2.0
974
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
# License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Boolean from sqlalchemy import Column from sqlalchemy import MetaData from sqlalchemy import Table def upgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine cell_m...
, default=False))
pnavarro/neutron
neutron/tests/base.py
Python
apache-2.0
13,886
0
# Copyright 2010-2011 OpenStack Foundation # 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 ap...
me in self: return self[name] rais
e AttributeError(_("Unknown attribute '%s'.") % name) class DietTestCase(testtools.TestCase): """Same great taste, less filling. BaseTestCase is responsible for doing lots of plugin-centric setup that not all tests require (or can tolerate). This class provides only functionality that is common acro...
pisskidney/leetcode
medium/31.py
Python
mit
1,015
0
#!/usr/bin/python from typing import List """ 31. Next Permutation https://leetcode.com/problems/next-permutation/ """ class Solution: def nextPermutation(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ best = None for i in r...
if (nums[i] < nums[j] and nums[j]
< smallest): smallest = nums[j] best = i, j if not best: nums[:] = sorted(nums) else: i, j = best nums[i], nums[j] = nums[j], nums[i] nums[:] = nums[:i+1] + sorted(nums[i+1:]) def main(): sol = Solution() ...
cablehead/vanilla
tests/unit/test_http.py
Python
mit
9,078
0
import json import gc import pytest import vanilla import vanilla.http # TODO: remove import logging logging.basicConfig() class TestHTTP(object): def test_get_body(self): h = vanilla.Hub() serve = h.http.listen() @h.spawn def _(): conn = serve.recv() ...
def test_put(self): h = vanilla.Hub() serve = h.http.listen() @h.spawn def _(): conn = serve.recv() for request in conn: request.reply( vanilla.http.Status(200
), {}, request.method+request.consume()) uri = 'http://localhost:%s' % serve.port conn = h.http.connect(uri) response = conn.put('/').recv() assert response.status.code == 200 assert response.consume() == 'PUT' response = conn.pu...
louyihua/edx-platform
lms/djangoapps/instructor_task/tests/test_integration.py
Python
agpl-3.0
27,741
0.003461
""" Integration Tests for LMS instructor-initiated background tasks. Runs tasks on answers to course problems to validate that code paths actually work. """ import json import logging from mock import patch from nose.plugins.attrib import attr import textwrap from celery.states import SUCCESS, FAILURE from django.co...
coring_option_problem(self): """Run
rescore scenario on option problem""" # get descriptor: problem_url_name = 'H1P1' self.define_option_problem(problem_url_name) location = InstructorTaskModuleTestCase.problem_location(problem_url_name) descriptor = self.module_store.get_item(location) # first store answ...
bbengfort/financial-analysis
finances/settings.py
Python
mit
6,172
0.006967
# finances.settings # The common Django setting
s for the Finance Analysis project. # # Author: Benjamin Bengfort <bengfort@cs.umd.edu> # Created: Tue Jan 19 20:43:16 2016 -0500 # # Copyright (C) 2015 Bengfort.com # For license information, see LICENSE.txt # # ID: settings.py [] benjamin@bengfort.com $ """ Django settings for finances project. Generated by 'dja...
BartoszMakowski/typer
typer/core/migrations/0003_auto_20171015_1341.py
Python
apache-2.0
657
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-10-15 13:41 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrati
ons.Migration): dependencies = [ ('core', '0002_wallet_template'), ] operations = [ migrations.AddField( model_name='wallet', name='description', field=models.TextField(blank=True), ), migrations.AddField( model_name='wallet',...
ult=False, ), ]
alexandreferreira/namesearch-example
namesearch/pagination.py
Python
gpl-2.0
948
0.001055
from collections import OrderedDict from rest_framework import pagination from rest_framework.response import Response __author__ = 'alexandreferreira' class DetailPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): return Response(OrderedDict([ ('count', sel...
e_number()), ('has_previous', self.page.has_previous()), ('current', self.page.number), ('results', data) ])) def get_next_page_number(self): if not self.page.has_next(): return self.page.number return self.page.
next_page_number() def get_previous_page_number(self): if not self.page.has_previous(): return 1 return self.page.previous_page_number()
dealnews/nagios-server-addons
plugins/brick_status_event_handler.py
Python
gpl-2.0
2,494
0
#!/usr/bin/python # brick_status_event_handler.py Event handler for Brick status # Service. Reschedules the check for volume status service whenever a # brick status changes. # Copyright (C) 2014 Red Hat Inc # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General...
Volume Status - %s" % args.volume cmdStr = "[%
s] %s;%s;%s;%s\n" % (now, command, hostName, volumeStatusService, now) submit_external_command.submitExternalCommand(cmdStr) sys.exit(utils.PluginStatusCode.OK)
johncsnyder/SwiftKitten
cffi/testing/cffi1/test_commontypes.py
Python
mit
918
0.004357
impor
t py, os, cffi, re import _cffi_backend def getlines(): try: f = open(os.path.join(os.path.dirname(cffi.__file__), '..', 'c', 'commontypes.c')) except IOError: py.test.skip("cannot find ../c/commontypes.c") lines = [line for line in f.readlines() if line.strip...
] f.close() return lines def test_alphabetical_order(): lines = getlines() assert lines == sorted(lines) def test_dependencies(): r = re.compile(r'EQ[(]"([^"]+)",(?:\s*"([A-Z0-9_]+)\s*[*]*"[)])?') lines = getlines() d = {} for line in lines: match = r.search(line) if ma...
diharaw/EmoLib
scripts/preprocess/1_partition.py
Python
mit
2,329
0.015028
import glob import math import shutil import os import sys if len(sys.argv) == 1: print("usage: partition.py <raw_dataset_folder> <train_percentage> <test_percentage>") sys.exit() kTRAINING_SET_PERCENTAGE = int(sys.argv[2]) kTEST_SET_PERCENTAGE = int(sys.argv[3]) # Delete directory if exists if os.path.exist...
NED" %sys.argv[1]) # Cre
ate directory os.makedirs("%s/2 - PARTITIONED" %sys.argv[1]) def partition_sizes(size, train, test): dataset_size = size training_set_size = 0 test_set_size = 0 validation_set_size = 0 training_set_size = int(round(dataset_size * (train / 100.0))) remainder = dataset_size - training_set_size ...
palaniyappanBala/thug
src/DOM/W3C/HTML/HTMLAllCollection.py
Python
gpl-2.0
453
0.00883
#!/usr/bin/env p
ython import sys import os sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))) from .HTMLCollection import HTMLCollection from NodeList import NodeList class HTMLAllCollection(HTMLCollection): def __init__(self, doc, nodes): HTMLCollection.__init__(self, doc, nodes) ...
)] return NodeList(self.doc, s)
cavestruz/L500analysis
caps/migration/config.py
Python
mit
663
0.019608
#!/usr/bin/python simulatio
n = "L500_NR_tracers" dirs = {"sim_root_dir" : "/home
/fas/nagai/kln26/group_scratch/L500_NR_tracers", "db_dir" : "..", "halo_catalog_dir" : "HC.500", "profiles_dir" : "profiles", "logs_dir" : "logs" } hc_radius = "500c" halo_list_radii = ["200m", "500c", "200c", "vir"] h_inverse = {"in_profiles": True, "in_halo_catalog" : True,...
cbeloni/pychronesapp
backend/apps/chamado_app/chamado_model.py
Python
mit
1,060
0.009434
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from googl
e.appengine.ext import ndb from gaegraph.model import Node #from gaeforms.ndb import property class Chamado(Node): empresa = ndb.StringProperty(required=True) start_date = ndb.StringProperty() id_ordem = ndb.I
ntegerProperty(required=True) end_date = ndb.StringProperty() tipo = ndb.StringProperty() status = ndb.StringProperty() responsavel = ndb.StringProperty() chamado = ndb.StringProperty(required=True) tempo_dev = ndb.IntegerProperty(required=True) @classmethod def query_by_id_orde...
sixty-north/fixedpointtest
fixedpoint/fixedpoint.py
Python
mit
20,028
0.002646
import operator from fractions import Fraction, gcd from functools import lru_cache from numbers import Real, Integral, Rational, Complex from math import trunc, frexp, log10, log2, isnan, isinf, floor from itertools import count from fixedpoint.qformat import QFormat def lowest_set_bit(x): """The lowest set bi...
elif isinstance(other, Real):
return poly(float(other), float(self)) elif isinstance(other, Complex): return poly(complex(other), complex(self)) return NotImplemented rop.__name__ = '__r{}__'.format(poly.__name__) rop.__doc__ = mono.__doc__ return op, rop def _add(a, b): assert isinstance(...
luwei14/ShapeAnalyzer
shapeanalyzer/transform.py
Python
mit
27
0
'
''
Geometry Transform '''
mvz/vb2py
vb2py/vbdebug.py
Python
bsd-3-clause
199
0
""
"Set up logging""" from vb2py import vbclasses from vb2py import logger # For logging output and debugging _vb_debug_log = logger.getLogger("vb2PyApp") vbclasses.D
ebug._logger = _vb_debug_log
jaycee/theblues
theblues/identity_manager.py
Python
lgpl-3.0
5,196
0
import base64 import json import logging try: from urllib import quote except ImportError: from urllib.parse import quote from theblues.errors import ( InvalidMacaroon, ServerError, ) from theblues.utils import ( ensure_trailing_slash, make_request, DEFAULT_TIMEOUT, ) class IdentityManage...
roon'] json_macaroon = json.dumps(macaroon) except (KeyError, UnicodeDecodeError) as err: raise InvalidMacaroon( 'Invalid macaroon from discharger: {}'.format(err.message)) return base64.urlsafe_b64encode(json_macaroon.encode('utf-8')) def discharge_token(se...
n for a user. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @return The resulting base64 encoded discharged token. """ url = '{}discharge-token-for-user?username={}'.format( self.url, quote(username)) logg...
houssemFat/MeeM-Dev
teacher/apps/accounts/apps.py
Python
mit
178
0.022472
from django.apps import AppConfig class AppConfig(AppConfig): lab
el =
'teacher_apps_accounts' name = 'teacher.apps.accounts' verbose_name = "teacher accounts apps"
illicitonion/givabit
src/givabit/webapp/signup_page.py
Python
apache-2.0
1,031
0.00291
from givabit.backend.errors import AlreadyExistsException from givabit.backend.user import User from givabit.backend.user_repository import UserRepository from givabit.webapp.base_page import BasePage from givabit.webapp.url import Url class SignupPage(BasePage): def __init__(self, request, response, user_reposito...
self.user_repo = user_repository if user_repository is not None else UserRepository() def get(self): self.write_template('signup', {'title': 'Givabit - Sign up'}) def post(self): POST = self.request.POST email = POST['email'] user = User(email=email) try: ...
response = self.redirect(Url().for_page('signedup')) return response except AlreadyExistsException: self.write_template('signup', {'title': 'Givabit - Sign up', 'success': False, 'error': 'User already exists'})
JulyKikuAkita/PythonPrac
cs15211/3Sum.py
Python
apache-2.0
11,548
0.014288
__source__ = 'https://leetcode.com/problems/3sum/' # https://github.com/kamyu104/LeetCode/blob/master/Python/3sum.py # Time: O(n^2) # Space: O(1) # # Description: Leetcode # 15. 3Sum # # Given an array S of n integers, # are there elements a, b, c in S such that a + b + c = 0? # Find all unique triplets in the array w...
sorted(nums), [], 0 while i < len(nums) -2: j, k = i + 1, len(nums) -1 while j < k: if nums[i] + nums[j] + nums[k] < 0: j += 1 elif nums[i] + nums[j] + nums[k] > 0: k -= 1 else: re...
pend([nums[i], nums[j], nums[k]]) j , k = j + 1, k - 1 while j < k and nums[j] == nums[j - 1]: j += 1 while j < k and nums[k] == nums[k + 1]: k -= 1 i += 1 while i < len(nums) - 2 and nums...
huggingface/transformers
src/transformers/models/speech_encoder_decoder/convert_mbart_wav2vec2_seq2seq_original_to_pytorch.py
Python
apache-2.0
14,669
0.003136
# coding=utf-8 # Copyright 2021 The HuggingFace Inc. team. # # 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/licen
ses/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...
okenizer, MBartConfig, MBartForCausalLM, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, Wav2Vec2Config, Wav2Vec2FeatureExtractor, Wav2Vec2Model, logging, ) logging.set_verbosity_info() logger = logging.get_logger(__name__) MAPPING = { "post_extract_proj": "feature_projecti...
michaelborck/earthmine-qgis
qgisplugin/earthmine/earthmine_qgis.py
Python
gpl-2.0
33,806
0.001094
# -*- coding: utf-8 -*- import copy import json import math from functools import partial from PyQt4.QtCore import QSettings, QTranslator, qVersion, QCoreApplication, pyqtSignal, QObject, pyqtSlot, Qt, QUrl, \ QRectF, SIGNAL, QPointF, QLineF from PyQt4.QtGui import QAction, QIcon, QPainter, QPen, QBrush, QColor, ...
self.poi
nts[1:]) for start, end in it: yield self.segment(start, end) def segment(self, start, end): startlength = start.distance(end) height = height_diff(end, start) length = math.sqrt(startlength ** 2 + height ** 2) return dict(length=startlength, adjusted=length, hei...
gbrmachado/treeherder
treeherder/model/tasks.py
Python
mpl-2.0
6,207
0.001289
import os from celery import task from django.conf import settings from django.core.management import call_command from treeherder.model.error_summary import load_error_summary from treeherder.model.exchanges import TreeherderPublisher from treeherder.model.models import Repository from treeherder.model.pulse_publish...
ublisher(self): """ Attempt to get the publisher. """ # Create publisher, if username and password is pr
esent if not self.publisher and settings.PULSE_EXCHANGE_NAMESPACE: self.publisher = TreeherderPublisher( namespace=settings.PULSE_EXCHANGE_NAMESPACE, uri=settings.PULSE_URI, schemas=PULSE_SCHEMAS ) return self.publisher pulse_conn...
googleads/google-ads-python
examples/reporting/get_keyword_stats.py
Python
apache-2.0
3,872
0
#!/usr/bin/env python # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
ics.impressions, metrics.clicks, metrics.cost_micros FROM keyword_view WHERE segments.date DURING LAST_7_DAYS AND campaign.advertising_channel_
type = 'SEARCH' AND ad_group.status = 'ENABLED' AND ad_group_criterion.status IN ('ENABLED', 'PAUSED') ORDER BY metrics.impressions DESC LIMIT 50""" # Issues a search request using streaming. search_request = client.get_type("SearchGoogleAdsStreamRequest") search_request.cus...
RasaHQ/rasa_nlu
rasa/shared/core/training_data/story_writer/yaml_story_writer.py
Python
apache-2.0
14,146
0.001131
from collections import OrderedDict from pathlib import Path from typing import ( Any, Dict, List, Text, Union, Optional, ) from ruamel import yaml from ruamel.yaml.comments import CommentedMap from ruamel.yaml.scalarstring import DoubleQuotedScalarString, LiteralScalarString import rasa.share...
the existing story file. is_test_story: Identifies if the stories should be exported in test stories format. """ result = self.stories_to_yaml(story_steps, is_test_story) if is_appendable and KEY_STORIES in result:
result = result[KEY_STORIES] rasa.shared.utils.io.write_yaml(result, target, True) def stories_to_yaml( self, story_steps: List[StoryStep], is_test_story: bool = False ) -> Dict[Text, Any]: """Converts a sequence of story steps into yaml format. Args: story_st...
amm042/pypakutil
examples/paksock.py
Python
gpl-3.0
10,096
0.013174
import socket import logging import string import time import threading import multiprocessing import Queue import select import pakbus def hexdump(pkt): return " ".join(["{:02x}".format(ord(x)) for x in pkt]) # # Quote PakBus packet # def quote(pkt): pkt = string.replace(pkt, '\xBC', '\xBC\xDC') # quote \xB...
[]) if self.shutdown_evt._flag in rlist: self.log.info("Got shutdown request") try: if self.tx_queue._reader in rlist: x = self.tx_queue.get() ...
st: # receive b = s.recv(2048) prd.recv(b) except ValueError as vmsg: logging.error("Decoding packet failed: {}".format(msg)) break # break reconnects soc...
louistin/fullstack
Python/http/post_python3.py
Python
mit
475
0.012632
#!/usr/bin/python3 # Filename: post_python3.py import urllib.parse import httplib2 http = httplibs.Http() url = 'www.example.com/login' body = {'USERNAME': 'foo', 'PASSWORD': 'bar'} header
s = {'Content-Type': 'application/x-www-form-urlencoded'} response, content = http.request(url, 'POST', headers = headers, body = urllib) headers = {'Cookie': response['set-cookie']} url = 'http://www.example
.com/home' response, content = http.request(url, 'GET', headers = headers)
rlopez93/seq-assembly-2
euler.py
Python
mit
7,441
0.000538
#! /usr/bin/env python2 import networkx as nx """ Find an eulerian path """ # Copyright (C) 2015 by # Edwardo S. Rivera <edwardo.rivera@upr.edu> # All rights reserved. ?? # BSD license. ?? __author__ = """\n""".join(['Edwardo Rivera <edwardo.rivera@urp.edu>']) __all__ = ['find_eulerian_path'] def find...
't have an Euler Path.") # is odd and we a
ppend it. else: check_odd.append(vertex) # undirected case else: if deg % 2 != 0: # if we have more than 2 odd nodes, # we do a raise (no euler path) if len(check_odd) > 2: ...
Harmon758/discord.py
discord/types/sticker.py
Python
mit
2,414
0
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz 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, merg...
: Snowflake cover_sticker_id: Snowflake description: str banner_asset_id: Snowflake class _CreateGuildStickerOptional(TypedDict, total=False): description: str class CreateGuildSticker(_CreateGuildStickerOptional): name: str tags: str class EditGuildStic
ker(TypedDict, total=False): name: str tags: str description: str class ListPremiumStickerPacks(TypedDict): sticker_packs: List[StickerPack]
js0701/chromium-crosswalk
tools/telemetry/telemetry/internal/results/chart_json_output_formatter.py
Python
bsd-3-clause
3,098
0.004842
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import collections import itertools import json from telemetry.internal.results import output_formatter from telemetry.value import summary as summary_modul...
summary_values): """Produces a dict for serialization to Chart JSON format from raw values. Chart JSON is a transformation of the basic Telemetry JSON format that removes the page map, summarizes the raw values, and organizes the results by chart and
trace name. This function takes the key pieces of data needed to perform this transformation (namely, lists of values and a benchmark metadata object) and processes them into a dict which can be serialized using the json module. Design doc for schema: http://goo.gl/kOtf1Y Args: page_specific_values: lis...
gablg1/PerfKitBenchmarker
perfkitbenchmarker/errors.py
Python
apache-2.0
3,525
0.008794
# Copyright 2014 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 agr...
(VirtualMachine.VirtualMachineError): """An error raised when VM is running but not SSHable.""" pass class RestConnectionError(Error): pass class IpParsingError(Error): pass class UserSetupError(Error): pass class ThreadException(Error): pass class CalledProcessException(Error): ...
jectCredentialException(Error): pass class RunError(Error): pass class Resource(object): """Errors related to resource creation and deletion.""" class RetryableCreationError(Error): pass class RetryableDeletionError(Error): pass
sassoftware/conary
conary/build/packagepolicy.py
Python
apache-2.0
195,877
0.001797
# # Copyright (c) SAS Institute Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
g # on each config file ('ComponentSpec', policy.REQUIRED_SUBSEQUENT), ) invariantinclusions = [ '%(sysconfdir)s/', '%(taghandlerdir)s/'] invariantexceptions = [ '%(userinfodir)s/', '%(groupinfodir)s' ] def doFile(self, filename): m = self.recipe.magic[filename] if m and...
ple), and tag handlers # can be ELF or shell scripts; we just want tag handlers # to be config files if they are shell scripts. # Just in case it was not intentional, warn... if self.macros.sysconfdir in filename: self.info('ELF file %s found in config dir...
vladimir-ipatov/ganeti
lib/luxi.py
Python
gpl-2.0
17,598
0.008126
# # # Copyright (C) 2006, 2007, 2011, 2012, 2014 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...
ata: raise ConnectionClosedError("Connection closed while reading") new_msgs = (self._buffer + data).split(constan
ts.LUXI_EOM) self._buffer = new_msgs.pop() self._msgs.extend(new_msgs) return self._msgs.popleft() def Call(self, msg): """Send a message and wait for the response. This is just a wrapper over Send and Recv. """ self.Send(msg) return self.Recv() def Close(self): """Close ...
ballouche/navitia
source/jormungandr/tests/ptref_tests.py
Python
agpl-3.0
34,004
0.003206
# encoding: utf-8 # Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility ...
ot_null(response, 'vehicle_journeys') for vj in vjs: is_valid_vehicle_journey(vj, depth_check=0) def test_vj_depth_2(self): """default depth is 1""" response = self.query_region("v1/vehicle_journeys?depth=2") vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs: is_valid_vehicle_journey(vj, depth_check=2) def test_vj_depth_3(self): """default depth is 1""" response = self.query_region("v1/vehicle_journeys?depth=3") vjs = get_not_null(response, 'vehicle_journeys') for vj in vjs: is_valid_vehicle_j...
atvcaptain/enigma2
lib/python/Screens/EventView.py
Python
gpl-2.0
14,735
0.028504
# -*- coding: utf-8 -*- from __future__ import print_function from time import localtime, mktime, time, strftime from enigma import eEPGCache, eTimer, eServiceReference, ePoint from Screens.Screen import Screen from Screens.ChoiceBox import ChoiceBox from Components.ActionMap import ActionMap from Components.Button i...
rseEvent, AFTEREVENT from Screens.TimerEntry import TimerEntry from Plugins.Plugin import PluginDescriptor from Tools.BoundFunction import boundFunction import six class EventViewContextMenu(Screen): def __init__(self, session, menu): Screen.__init__(self, sessi
on) self.setTitle(_('Eventview menu')) self["actions"] = ActionMap(["OkCancelActions"], { "ok": self.okbuttonClick, "cancel": self.cancelClick }) try: if config.skin.primary_skin.value.startswith('MetrixHD/'): count = 0 for entry in menu: menu[count] = (" " + entry[0], entry...
sergiusens/snapcraft
tests/unit/__init__.py
Python
gpl-3.0
10,138
0.000789
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2015-2018 Canonical Ltd # # This program 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 ...
t.internal.project_loader import grammar_processing from tests import fake_servers, fixture_setup from tests.file_utils import get_snapcraft_path class ContainsList(list): def __eq__(self, other): return all([i[0] in i[1] for i in zip(self, other)]) class MockOptions: def __init__( self, ...
urce_branch=None, source_tag=None, source_subdir=None, source_depth=None, source_commit=None, source_checksum=None, disable_parallel=False, ): self.source = source self.source_type = source_type self.source_depth = source_depth self.sou...
fandrefh/AnjoMeu
anjo/campaign/migrations/0003_auto__del_field_campaign_photo__add_field_campaign_image.py
Python
gpl-2.0
1,508
0.005968
# -*- 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): # Deleting field 'Campaign.photo' db.delete_column(u'campaign_campaign', ...
ign', 'photo', self.gf('cloudinary.models.CloudinaryField')(default=0, max_length=100), keep_default=False) # Deleting field 'Campaign.ima
ge' db.delete_column(u'campaign_campaign', 'image') models = { u'campaign.campaign': { 'Meta': {'object_name': 'Campaign'}, 'goal': ('django.db.models.fields.DecimalField', [], {'max_digits': '15', 'decimal_places': '2'}), u'id': ('django.db.models.fields.AutoFi...
isfon/AmigosAire
AmigosAire/AmigosAire/sitemaps.py
Python
mit
720
0.0125
from django.contrib.sitemaps import Sitemap from django.core.urlresolvers import reverse from datetime import datetime from apps.main.models import Servicios class VueloSitemap(Sitemap): changefreq = 'never' priority = 0.5 def items(self)
: return Servicios.objects.all() def lastmod(self,obj): return datetime.now() def location(self,obj): return '/plan/%s'%obj.slug class SitesSitemap(Sitemap): def __init__(self,names):
self.names = names def items(self): return self.names def changefreq(self,obj): return 'weekly' def lastmod(self,obj): return datetime.now() def location(self,obj): return reverse(obj)
collective/collective.machinelearning
collective/machinelearning/behaviors.py
Python
gpl-2.0
729
0
""" Behaviours for Machine Learning. """ from zope import schema from plone.supermodel import model from plone.autoform.interfaces import IFormFieldProvider from zope.interface import alsoProvides from collective.machinelearning import _ class IMachine
Learning(model.Schema): """ Behavior interface to make a Dexterity type support Machine Learning """ model.fieldset('machinelearning', label=_(u"Learning"), fields=['machineLearningCluster', ] ) machineLearningCluster = schema.Int( t...
ider)
ikn/fsmanage
fsmanage/actionexec.py
Python
gpl-3.0
6,502
0.002153
from .item import ROOT from .history import HistoryEvent, History class ActionManager: """Group together actions and manage running them. :arg op_manager: :class:`OperationManager <fsmanage.opexec.OperationManager>` to run operations with. To make actions available for executing, call :meth:`add_actions`. ...
et them as the currently selected items. """ pass def action_manager_support_state (manager): """Add support for generi
c state storage to an :class:`ActionManager`. Supports: :class:`StateActionTarget <fsmanage.action.StateActionTarget>`. The state is a :class:`dict`. :arg manager: :class:`ActionManager` instance. """ pass class NavigationHistoryEvent (HistoryEvent): """History event corresponding to a change to the curre...
pynayzr/pynayzr
test/test_cropper.py
Python
mit
1,540
0
# -*- coding: utf-8 -*-
from PIL import Image import unittest from pynayzr.cropper import crop, ttv, ftv, sets class TestCropBase(unittest.TestCase): def test_blank_base(self): base = crop.CropBase('base') self.assertEqual(base.name, 'base') self.assertEqual(base.image, None) self.assertEqual(base.title_b...
Equal(base.subtitle_box, None) self.assertEqual(base.source_box, None) class TestTTVCropper(unittest.TestCase): def setUp(self): self.p = ttv.TTVCropper('tests/imgs/ttv/main_01.jpg') def test_crop_title(self): self.assertIsInstance(self.p.title(), Image.Image) def test_crop_subti...
NorfairKing/sus-depot
shared/shared/vim/dotvim/bundle/YouCompleteMe/run_tests.py
Python
gpl-2.0
1,761
0.049972
#!/usr/bin/env python import os import subprocess import os.path as p import sys DIR_OF_THIS_SCRIPT = p.dirname( p.abspath( __file__ ) ) DIR_OF_THIRD_PARTY = p.join( DIR_OF_THIS_SCRIPT, 'third_party' ) DIR_OF_YCMD_THIRD_PARTY = p.join( DIR_OF_THIRD_PARTY, 'ycmd', 'third_party' ) python_path = [] for folder in os.lis...
'PYTHONPATH' ] ) os.environ[ 'PYTHONPATH' ] = os.pathsep.join( python_path ) sys.path.insert( 1, p.abspath( p.join( DIR_OF_YCMD_THIRD_PARTY, 'argparse' ) ) ) import argparse def RunFlake8(): print( 'Running flake8' ) subprocess.check_call( [ 'flake8', '--select=F,C9...
p-build', action = 'store_true', help = 'Do not build ycmd before testing.' ) return parser.parse_known_args() def BuildYcmdLibs( args ): if not args.skip_build: subprocess.check_call( [ sys.executable, p.join( DIR_OF_THIS_SCRIPT, 'third_party', 'ycmd', 'build.py' ) ] )...
pankajp/pyface
pyface/grid/api.py
Python
bsd-3-clause
140
0.007143
import logging loggi
ng.warn('DEPREC
ATED: pyface.grid, ' 'use pyface.ui.wx.grid instead.') from pyface.ui.wx.grid.api import *
deepfield/ibis
ibis/expr/rules.py
Python
apache-2.0
10,938
0
import collections import enum from itertools import starmap, product import six from ibis.compat import suppress import ibis.util as util import ibis.common as com import ibis.expr.types as ir import ibis.expr.schema as sch import ibis.expr.datatypes as dt try: from cytoolz import curry, compose, identity exce...
'Arg passes neither of the following rules: {}'.format(rules_formatted) ) @validator def all_of(inners, arg): """All of the inner valudators must pass. The order of inner validators matters. Parameters ---------- inners : List[validator] Functions are applied from right to left ...
rced by inner validators to the appropiate types """ return compose(*inners)(arg) @validator def isin(values, arg): if arg not in values: raise ValueError( 'Value with type {} is not in {!r}'.format(type(arg), values) ) if isinstance(values, dict): # TODO check for mapping...
badock/nova
nova/tests/objects/test_flavor.py
Python
apache-2.0
10,207
0
# Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
flavor) def test_create_with_projects(self): context = self.context.elevated() flavor = flavor_obj.Flavor() flavor.name = 'm1.foo' flavor.extra_specs = fake_flavor['extra_specs'] flavor.projects = ['project-1', '
project-2'] db_flavor = dict(fake_flavor, projects=list(flavor.projects)) with mock.patch.multiple(db, flavor_create=mock.DEFAULT, flavor_access_get_by_flavor_id=mock.DEFAULT ) as methods: methods['flavor_create'].return_val...
kreuks/liven
bot/config.py
Python
apache-2.0
140
0
import json
with open('bot/config.json', 'r') as f: _config = json.load(f) config
= _config['config'] name = _config['name']
t4ec/blog
blog/__init__.py
Python
mit
110
0.009091
from flask import Flask app =
Flask(__name__) app.config.from_object('blog.config') from blog
import views
taxipp/ipp-macro-series-parser
ipp_macro_series_parser/agregats_transports/parser_cleaner_prix_carburants.py
Python
gpl-3.0
8,939
0.009956
""" Created on Tue Jul 21 13:57:18 2015 @author: thomas.douenne """ import pandas as pd from ipp_macro_series_parser.config import Config parser = Config() transports_directory = parser.get('data', 'transports_directory') prix_annuel_carburants = parser.get('data', 'prix_annuel_carburants_90_2014') prix_mensuel_c...
name(columns = {'Super SP95.1': 'super_95_ttc'}, inplace = True) data_frame.rename(columns = {'Super SP98': 'super_98_ht'}, inplace = True)
data_frame.rename(columns = {'Super SP98.1': 'super_98_ttc'}, inplace = True) return data_frame prix_mensuel_carburants = prix_carburants_parser(prix_mensuel_carburants) prix_annuel_carburants = prix_carburants_parser(prix_annuel_carburants) def prix_carburants_cleaner_90_96(data_frame): data_frame = d...
skosukhin/spack
var/spack/repos/builtin/packages/r-reportingtools/package.py
Python
lgpl-2.1
3,429
0.000583
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-COD
E-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our not
ice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARR...
weidnem/IntroPython2016
Solutions/Session07/class_html_render/run_html_render.py
Python
unlicense
5,392
0.001855
#!/usr/bin/env python """ a simple script can run and test your html rendering classes. Uncomment the steps as you add to your rendering. """ from io import StringIO # importing the html_rendering code with a short name for easy typing. import html_render as hr # reloading in case you are running this in iPython #...
s 6 example") ) # body.append(hr.P("Here is a paragraph of text -- there could be more of them, " # "but this is enough to show that we can do some text", # style="text-align: center; font-style: oblique;")) # body.append(hr.Hr()) # list = hr.Ul(id="TheList", style="line-height:200%")...
t.append( hr.Li("This is the second item", style="color: red") ) # item = hr.Li() # item.append("And this is a ") # item.append( hr.A("http://google.com", "link") ) # item.append("to google") # list.append(item) # body.append(list) # page.append(body) # render_page(page, "test_html_output7.html") # # Step 8 # ###...
o3project/ryu-oe
ryu/ofproto/oxm_fields.py
Python
apache-2.0
12,359
0.00259
# Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2013 YAMAMOTO Takashi <yamamoto at valinux co jp> # # 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...
Int8 = IntDescr(8) Int32 = IntDescr(32) # -------------------------- Fujitsu code start ----------------------------- # For optical enhancing Int5 = IntDescr(5) Int14 = IntDescr(14
) # -------------------------- Fujitsu code end ------------------------------- class MacAddr(TypeDescr): size = 6 to_user = addrconv.mac.bin_to_text from_user = addrconv.mac.text_to_bin class IPv4Addr(TypeDescr): size = 4 to_user = addrconv.ipv4.bin_to_text from_user = addrconv.ipv4.text_to_...
fxia22/ASM_xf
PythonD/lib/python2.4/site-packages/link/pyldap/ldapurl.py
Python
gpl-2.0
11,775
0.021571
""" ldapurl - handling of LDAP URLs as described in RFC 2255 written by Michael Stroeder <michael@stroeder.com> See http://python-ldap.sourceforge.net for details. \$Id: ldapurl.py,v 1.32 2003/05/26 07:49:07 stroeder Exp $ Python compability note: This module only works with Python 2.0+ since 1. string methods are u...
}).items(): self[k]=v def __setitem__(self,name,value): """ value Either LDAPUrlExtension instance, (cri
tical,exvalue) or string'ed exvalue """ assert isinstance(value,LDAPUrlExtension) assert name==value.extype self.data[name] = value def values(self): return [ self[k] for k in self.keys() ] def __str__(self): return ','.join(map(str,self.values())) def __repr__(s...
cmtm/networkx
networkx/algorithms/shortest_paths/tests/test_weighted.py
Python
bsd-3-clause
25,025
0.002158
from __future__ import division from nose.tools import assert_equal from nose.tools import assert_false from nose.tools import assert_raises from nose.tools import raises import networkx as nx from networkx.utils import pairwise def validate_path(G, s, t, soln_len, path): assert_equal(path[0], s) assert_equ...
, 'v', 8, P['v']) assert_equal(D['v'], 8) # uses lower weight of 2 on u<->x edge validate_path(GG, 's', 'v', 8, nx.dijkstra_path(GG,
's', 'v')) assert_equal(nx.dijkstra_path_length(GG, 's', 'v'), 8) validate_path(self.XG2, 1, 3, 4, nx.dijkstra_path(self.XG2, 1, 3)) validate_path(self.XG3, 0, 3, 15, nx.dijkstra_path(self.XG3, 0, 3)) assert_equal(nx.dijkstra_path_length(self.XG3, 0, 3), 15) validate_path(self.X...
hangoutsbot/hangups
hangups/schemas.py
Python
mit
12,831
0
"""pblite message schemas and related enums.""" # Stop pylint from complaining about enums: # pyline: disable=too-few-public-methods import enum from hangups.pblite import Message, Field, RepeatedField, EnumField ############################################################################## # Enums ###############...
('conversation_id', CONVERSATION_ID), ('type_', EnumField(ConversationType)), ('name', Field(is_optional=True)), ('self_conversation_state', Message( (None, Field(is_optional=True)), (None, Field(is_optional=True)), (None, Field(is_optional=True)), (None, Field(is_optional=...
('self_read_state', Message( ('participant_id', USER_ID), ('latest_read_timestamp', Field()), )), ('status', EnumField(ClientConversationStatus)), ('notification_level', EnumField(ClientNotificationLevel)), ('view', RepeatedField( EnumField(Client...
dmayrand/Clients-for-actionKATA
python/rpiinfo.py
Python
mit
265
0.022989
import os def get_temperature()
: # “Returns the temperature in degrees C” try: res = os.popen('vcgencmd measure_temp').readline() return(res.replace("temp=","").replace("'C\n","")) exc
ept: return "Failed to get Temperature"
menghanY/LeetCode-Python
Array/RemoveDuplicatesfromSortedArray.py
Python
mit
841
0.011891
# Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
# # Do not allocate extra space for another array, you must do this in place with constant memory. # # For example, # Given input array nums = [1,1,2], # # Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. # h...
discuss.leetcode.com/topic/68445/python-with-two-pointers class Solution(object): def removeDuplicates(self, nums): originLen = len(nums) if originLen == 0 : return 0 i,j = 1,1 while i < originLen : if nums[i] != nums[i - 1] : nums[j] = nums[i] ...
lwerdna/alib
py/logic/BoolExpr.py
Python
gpl-3.0
16,510
0.036463
#!/usr/bin/python #------------------------------------------------------------------------------ # # This file is a part of autils. # # Copyright 2011-2016 Andrew Lamoureux # # autils is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Fr...
eived a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # #------------------------------------------------------------------------------ # idea is to represent a boolean expression as a hierarchy, a tree # # contains abstract BoolExpr # # and implementing...
be # in a tree like fashion (perhaps descending to find values, etc.) class BoolExpr: def __init__(self): self.subexprs = [] # can multiply (and) this expression with another (return parent and gate) def __mul__(self, rhs): if not rhs: return self if type(rhs) == type("string"): rhs = BoolParser(rhs) ...
vault/bugit
viewer/views.py
Python
mit
3,804
0.008149
from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.ut...
t_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None:
return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def...
andyaguiar/tornado
tornado/httputil.py
Python
apache-2.0
29,700
0.000202
#!/usr/bin/env python # # Copyright 2009 Facebook # # 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 a...
f[self._last_key] + new_par
t) else: name, value = line.split(":", 1) self.add(name, value.strip()) @classmethod def parse(cls, headers): """Returns a dictionary from HTTP header text. >>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n") >>> sorted(h.i...
keli78/pocolm
scripts/get_word_counts.py
Python
apache-2.0
3,255
0.006144
#!/usr/bin/env python # we're using python 3.x style print but want it to work in python 2.x, from __future__ import print_function im
port re, os, argparse, sys, math, warnings from collections import defaultdict try: # since gzip will only be needed if there are gzipped files, accept import gzip # failure to import it. except: pass parser = argparse.ArgumentParser(des
cription="Extracts word counts from a data directory " "and creates a count directory with similar structure. " "Input directory has *.txt, counts directory has *.counts. " "Format of counts files is 'count word', e.g. '1...
sidecars/python-quickbooks
tests/unit/test_cdc.py
Python
mit
2,796
0.034692
import unittest try: from mock import patch except ImportError: from unittest.mock import patch from quickbooks.cdc import change_data_capture from quickbooks.objects import Invoice, Customer from quickbooks import QuickBooks from datetime import datetime class ChangeDataCaptureTest(unittest.TestCase): def setUp(s...
ke_request): make_request.return_value = self
.cdc_json_response.copy() cdc_response = change_data_capture([Invoice, Customer], "2017-01-01T00:00:00") self.assertEquals(1, len(cdc_response.Customer)) self.assertEquals(2, len(cdc_response.Invoice)) @patch('quickbooks.client.QuickBooks.make_request') def test_change_data_capture_with_timestamp(self, make_r...
what-studio/gauge
recipes/namedgauge.py
Python
bsd-3-clause
5,860
0
# -*- coding: utf-8 -*- """A recipe to implement named gauge. Named gauge keeps momenta and their names. You can manipulate a specific momentum by the name you named. Test it by `py.test <http://pytest.org/>`_: .. sourcecode:: console $ py.test recipes/namedgauge.py """ from collections import namedtuple from ti...
rt g.get(1) == 55 # the past was forgotten. assert g.get(5) == 55 # but the gauge remembers the effect from the past. assert g.get(10) == 65 assert g.get(20) == 55 def test_multiple_momenta(): import pytest g = NamedGauge(50, 100, at=0) g.add_mome
ntum(+1, since=0, until=10, name='foo') g.add_momentum(-1, since=1, until=11, name='bar') g.add_momentum(-1, since=1, until=11, name='baz') assert g.velocity(5) == -1 g.pop_momentum_by_name('foo') assert g.velocity(5) == -2 with pytest.raises(ValueError): g.remove_momentum(-1, since=1, u...
rayman42003/INF123-VVPilot
Server.py
Python
mit
8,498
0.010238
from network import * import pygame, random, Serialize from Logic import Logic from Ship import Ship from ServerSideController import ServerSideController def respawn_func(ship): ship.location = (320, 240) ship.rect.center = ship.location ship.velocity = (0, 0) ship.direction = 0 def random_respaw...
TICKS, 'speed' : SPEED, 'bspeed' : BULLET_SPEED, 'maxvelo' : VELOCITY_CAP, 'angular' : ANGULAR_VELOCITY, 'current' : logic.c
urrent_tick, 'id' : player_ship.id}}) #logic.onLogicUpdate+=self.onLogicUpdate handlers.append(self) # def onLogicUpdate(self, logic): # pass # # msg = {'update': # # {'ships': [Serialize.serializeShip(ship) for ship in logic.ship_...
artwr/airflow
tests/api/common/experimental/test_mark_tasks.py
Python
apache-2.0
23,260
0.001505
# -*- coding: utf-8 -*- # # 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 #...
the # specific language governing permissions and limitations # under the License. import unittest import time from datetime import datetime from airflow import config
uration, models from airflow.api.common.experimental.mark_tasks import ( set_state, _create_dagruns, set_dag_run_state_to_success, set_dag_run_state_to_failed, set_dag_run_state_to_running) from airflow.utils import timezone from airflow.utils.db import create_session, provide_session from airflow.utils.dates i...
LeMeteore/boomer2
note/admin.py
Python
bsd-2-clause
153
0
from djan
go.contrib import admin from note.models import Note, My
User # Register your models here. admin.site.register(Note) admin.site.register(MyUser)
bamford/control
control/camera.py
Python
gpl-2.0
9,476
0.001583
import wx import threading import time from datetime import datetime import numpy as np from scipy.stats import norm from logevent import * # simulate obtaining images for testing simulate = False if not simulate: # http://www.ascom-standards.org/Help/Developer/html/N_ASCOM_DeviceInterface.htm try: i...
h s
elf.exptime_lock: self.exptime = exptime def GetExpTime(self): with self.exptime_lock: return self.exptime def Log(self, text): wx.PostEvent(self.parent, LogEvent(text=text)) def TakeImage(self, exptime): image = None image_time = datetime.utcnow() ...
victoredwardocallaghan/pygments-main
pygments/lexers/web.py
Python
bsd-2-clause
168,630
0.00169
# -*- coding: utf-8 -*- """ pygments.lexers.web ~~~~~~~~~~~~~~~~~~~ Lexers for web-related languages and markup. :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re import copy from pygments.lexer import RegexLexer, ExtendedReg...
', 'Mask
Lexer', 'ZephirLexer'] class JavascriptLexer(RegexLexer): """ For JavaScript source code. """ name = 'JavaScript' aliases = ['js', 'javascript'] filenames = ['*.js', ] mimetypes = ['application/javascript', 'application/x-javascript', 'text/x-javascript', 'text/javascript...
nohona/cron-crm
usr/local/certbot/certbot/tests/account_test.py
Python
gpl-3.0
7,861
0.000636
"""Tests for certbot.account.""" import datetime import json import os import shutil import stat import unittest import mock import pytz from acme import jose from acme import messages from certbot import errors from certbot.tests import util from certbot.tests.util import TempDirTestCase KEY = jose.JWKRSA.load(...
.account.AccountMemoryStorage.""" def setUp(self): from certbot.account import AccountMemoryStorage self.storage = AccountMemoryStorage() def test_it(self):
account = mock.Mock(id="x") self.assertEqual([], self.storage.find_all()) self.assertRaises(errors.AccountNotFound, self.storage.load, "x") self.storage.save(account, None) self.assertEqual([account], self.storage.find_all()) self.assertEqual(account, self.storage.load("x")) ...
Lucasfeelix/ong-joao-de-barro
accounts/models.py
Python
mit
2,153
0.000469
# coding=utf-8 import re from django.db import models from django.contrib.auth.models import AbstractBaseUser, UserManager from django.contrib.auth.models import PermissionsMixin from django.core import validators class User(AbstractBaseUser, PermissionsMixin): ''' Modelo para sobreescrever o admin do Django....
te para ser criado novo modelo com base em seu User personalizado. ''' username = models.CharField('Usuário', max_length=30, unique=True, validators=[validators.RegexValidator( re.compile('^[\w.@+-]+$'),
'Informe um nome de usuário válido. ' 'Este valor deve conter apenas letras' ', números e os caracteres: @/./+/-/_' ' .', 'invalid') ], h...
HybridF5/tempest_debug
tempest/tests/lib/fake_auth_provider.py
Python
apache-2.0
1,268
0
# Copyright 2014 Hewlett-Packard Development Company, L.P. # 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...
ict or {} self.credentials = FakeCredentials(creds_dict) self.fake_base_url = fake_base_url
def auth_request(self, method, url, headers=None, body=None, filters=None): return url, headers, body def base_url(self, filters, auth_data=None): return self.fake_base_url or "https://example.com" class FakeCredentials(object): def __init__(self, creds_dict): for key in creds_dict....
datapythonista/pandas
pandas/tests/frame/methods/test_sort_index.py
Python
bsd-3-clause
29,983
0.000767
import numpy as np import pytest import pandas as pd from pandas import ( CategoricalDtype, CategoricalIndex, DataFrame, Index, IntervalIndex, MultiIndex, Series, Timestamp, ) import pandas._testing as tm class TestDataFrameSortIndex: def test_sort_index_and_reconstruction_doc_exa...
3]}, index=MultiIndex( levels=[["a", "b"], ["aa", "bb"]], codes=[[0, 0, 1, 1], [0, 1
, 0, 1]] ), ) result = df.sort_index() assert result.index.is_monotonic tm.assert_frame_equal(result, expected) # reconstruct result = df.sort_index().copy() result.index = result.index._sort_levels_monotonic() assert result.index.is_monotoni...
MarkusH/django-classy-settings
tests/test_env.py
Python
bsd-2-clause
1,670
0
import os import unittest import cbs class TestEnv(unittest.TestCase): def setUp(self): os.environ.clear() cbs.DEFAULT_ENV_PREFIX = '' def test_retrieve_from_method(self): class Settings: @cbs.env def SETTING(self): return 'bar' self.a...
viron['DJANGO_SETTING'] = 'foo' self.assertEqual(Settings().SETTING, 'foo') def test_retrieve_from_env_specifying_prefix(self): class Settings: @cbs.env(prefix='DJANGO_') def SETTING(self): return 'bar' os.environ['DJANGO_SETTING'] = 'foo' se...
class Settings: @cbs.env def SETTING(self): return 'bar' os.environ['DJANGO_SETTING'] = 'foo' self.assertEqual(Settings().SETTING, 'foo') def test_refer_to_other_setting(self): class Settings: OTHER = True @cbs.env ...
palisadoes/switchmap-ng
switchmap/cli/stop.py
Python
apache-2.0
2,137
0
#!/usr/bin/env python3 """switchmap CLI functions for 'stop'. Functions to stop daemons
""" # Main python libraries import sys # Switchmap-NG imports from switchmap.utils import general from switchmap.main.agent import Agent, AgentAPI, AgentDaemon from switchmap.constants import ( API_EXECUTABLE, API_GUNICORN_AGENT, POLLER_EXECUTAB
LE) def run(args): """Process 'stop' command. Args: args: Argparse arguments Returns: None """ # Show help if no arguments provided if args.qualifier is None: general.cli_help() # Process 'show api' command if args.qualifier == 'api': api(args) e...