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
Videoclases/videoclases
quality_control/views/control_views.py
Python
gpl-3.0
1,076
0.001859
from django.contrib.auth.decorators import user_passes_test from django.utils.decorators import method_decorator from django.views.generic.base import TemplateView def in_students_group(user): if user: return user.groups.filter(name='Alumnos').exists() return False def in_teachers_group(user): i...
**kwargs) # form = CrearTareaForm() # context['crear_homework_form'] = form # context['cours
es'] = self.request.user.teacher.courses.filter(year=timezone.now().year) # context['homeworks'] = Homework.objects.filter(course__in=context['courses']) return context @method_decorator(user_passes_test(in_teachers_group, login_url='/')) def dispatch(self, *args, **kwargs): return supe...
javrasya/watchdog
tests/__init__.py
Python
apache-2.0
951
0.001052
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com> # Copyright 2012 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 # # ...
nguage governing permissions and # limitations under the License. from sys import version_info from os import name as OS_NAME __all__= ['unittest', 'skipIfNtMove'] if version_info < (2, 7): import unitt
est2 as unittest else: import unittest skipIfNtMove = unittest.skipIf(OS_NAME == 'nt', "windows can not detect moves")
krujos/strava-private-to-public
private-to-public.py
Python
apache-2.0
3,601
0.002499
""" Really could have implemented this all in javascript on the client side... """ from __future__ import print_function import requests from flask import Flask, redirect, url_for, request, session, abort, jsonify import os import sys import logging import json STRAVA_CLIENT_ID = 1367 Flask.get = lambda self, path: s...
= requests.post(url, data=data) app.logger.info("Login post returned %d" % response.status_code) app.logger.debug(response.json()) session['token'] = response.json()['access_token'] athlete = response.json()['athlete'] session['athlete_id'] = athlete['id'] session['athlete_name'] = athlete['fir...
"name": session['athlete_name']}) except KeyError: abort(404) @app.get('/login') def login(): return "https://www.strava.com/oauth/authorize?client_id=%s&response_type=code&redirect_uri=%s&scope=view_private,write" \ % (STRAVA_CLIENT_ID, redirect_url) @app.get('/rides/<page>...
wieden-kennedy/django-haikus
setup.py
Python
bsd-3-clause
1,122
0.008021
#/usr/bin/env python import os from setuptools import setup, find_packages ROOT_DIR = os.path.dirname(__file__) SOURCE_DIR = os.path.join(ROOT_DIR) setup( name="django_haikus", description="Some classes for finding haik
us in text", author="Grant Thomas", author_email="grant.thomas@wk.com", url="https://github.com/wieden-kennedy/django_haikus", version="0.0.1", dependency_links = ['http://github.com/wieden-kennedy/haikus/tarball/master#egg=haikus'], install_requires=["nltk","django>=1.3.1","redis","requests","e...
", "django-picklefield"], packages=['django_haikus'], zip_safe=False, include_package_data=True, classifiers=[ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Development Status :: 4 - Beta", "Envi...
eayunstack/ceilometer
ceilometer/api/app.py
Python
apache-2.0
3,764
0
# # 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/licenses/LICENSE-2.0 # # Unless required by applicable law...
ecan_config=None): # FIXME: Replace DBHook with a hooks.TransactionHook app_hooks = [hooks.ConfigHook(), hooks.DBHook(), hooks.NotifierHook(), hooks.TranslationHook()] pecan_config = pecan_config or { "app": { 'root': 'ceilometer.api.co...
tController', 'modules': ['ceilometer.api'], } } pecan.configuration.set_config(dict(pecan_config), overwrite=True) # NOTE(sileht): pecan debug won't work in multi-process environment pecan_debug = CONF.api.pecan_debug if CONF.api.workers and CONF.api.workers != 1 and pecan_deb...
Koala-Kaolin/pyweb
src/__main__.py
Python
gpl-3.0
42
0
#!/usr/bin/python3 import gu
i gui.m
ain()
chapman-phys227-2016s/hw-1-seama107
adaptive_trapezint.py
Python
mit
1,279
0.013292
#!/usr/bin/python import math def trapezint(f, a, b, n) : """ Just for testing - uses trapazoidal approximation from on f from a to b with n
trapazoids """
output = 0.0 for i in range(int(n)): f_output_lower = f( a + i * (b - a) / n ) f_output_upper = f( a + (i + 1) * (b - a) / n ) output += (f_output_lower + f_output_upper) * ((b-a)/n) / 2 return output def second_derivative_approximation(f, x, h = .001): """ Approximates the sec...
imphil/fusesoc
tests/test_capi1.py
Python
gpl-3.0
10,310
0.012512
import difflib import os import pytest from fusesoc.core import Core def compare_fileset(fileset, name, files): assert name == fileset.name for i in range(len(files)): assert files[i] == fileset.file[i].name def test_core_info(): tests_dir = os.path.dirname(__file__) cores_root = os.path.join...
'FILES_ROOT' :
'dummyroot' } result = core.get_scripts("dummyroot", flags) expected = {} if flags['target'] == 'sim': sections = ['post_run', 'pre_build', 'pre_run'] else: if flags['is_toplevel']: env['SYSTEM_ROOT'] = core.files_root sect...
prefetchnta/questlab
bin/x64bin/python/37/Lib/distutils/version.py
Python
lgpl-2.1
12,688
0.001497
# # distutils/version.py # # Implements multiple version numbering conventions for the # Python Module Distribution Utilities. # # $Id$ # """Provides classes to represent module version numbers (one class for each style of version numbering). There are currently two such classes implemented: StrictVersion ...
2.7.2.2 1.3.a4 1.3pl1 1.3c4 The rationale for this version numbering system will be explained in the distutils documentation. """ version_re = re.compile(r'^(\d+) \. (\d+) (\. (\d+))? ([ab](\d+))?$', re.VERBOSE | re.ASCII) de...
atch(vstring) if not match: raise ValueError("invalid version number '%s'" % vstring) (major, minor, patch, prerelease, prerelease_num) = \ match.group(1, 2, 4, 5, 6) if patch: self.version = tuple(map(int, [major, minor, patch])) else: ...
mbayon/TFG-MachineLearning
venv/lib/python3.6/site-packages/django/core/management/utils.py
Python
mit
3,739
0.001337
from __future__ import unicode_literals import os import sys from subprocess import PIPE, Popen from django.apps import apps as installed_apps from django.utils import six from django.utils.crypto import get_random_string from django.utils.encoding import DEFAULT_LOCALE_ENCODING, force_text from .base import Command...
T_KEY setting value. """ chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)' return get_random_string(50, chars) def parse_apps_and_model_label
s(labels): """ Parse a list of "app_label.ModelName" or "app_label" strings into actual objects and return a two-element tuple: (set of model classes, set of app_configs). Raise a CommandError if some specified models or apps don't exist. """ apps = set() models = set() for labe...
akhileshpillai/treeherder
treeherder/etl/pulse_consumer.py
Python
mpl-2.0
4,116
0
import logging from django.conf import settings from kombu import (Exchange, Queue) from kombu.mixins import ConsumerMixin from treeherder.etl.common import fetch_json from treeherder.etl.tasks.pulse_tasks import (store_pulse_jobs, store_pulse_resultset...
f.consumers = [] self.queue = None config = settings.PULSE_DATA_INGESTION_CONFIG if not config: raise ValueError("PULSE_DATA_INGESTION_CONFIG is required for the " "JobConsumer c
lass.") self.queue_name = "queue/{}/{}".format(config.username, queue_suffix) def get_consumers(self, Consumer, channel): return [ Consumer(**c) for c in self.consumers ] def bind_to(self, exchange, routing_key): if not self.queue: self.queue = Queue( ...
cbeauvais/zAWygzxkeSjUBGGVsgMGTF56xvR
survox_api/resources/library/sample_dnc.py
Python
mit
5,130
0.002534
import os import json from ...resources.base import SurvoxAPIBase from ...resources.exception import SurvoxAPIRuntime, SurvoxAPINotFound from ...resources.valid import valid_url_field class SurvoxAPIDncList(SurvoxAPIBase): """ Class to manage DNC lists. """ def __init__(self, base_url=None, headers=...
ble named: {name}'.format(name=self.name)) if not description and not realtime: raise SurvoxAPIRuntime('No properties passed to set fo
r DNC named: {name}'.format(name=self.name)) changes = {} if description and description != dnc['description']: changes['description'] = description if realtime and realtime != dnc['realtime']: changes['realtime'] = realtime if changes: return self.a...
dgraph-io/pydgraph
pydgraph/__init__.py
Python
apache-2.0
849
0.001178
# Copyright 2018 Dgraph Labs, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file exce
pt 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, eithe...
issions and # limitations under the License. from pydgraph.proto.api_pb2 import Operation, Payload, Request, Response, Mutation, TxnContext,\ Check, Version, NQuad, Value, Facet, Latency from pydgraph.client_stub import * from pydgraph.client import * from pydgraph.txn import * from pydgraph.errors import *
shirishgoyal/crowdsource-platform
crowdsourcing/migrations/0093_merge.py
Python
mit
334
0
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-06-09 22:16 from __future__ import unicode_literals from django.db import migr
ations class Migration(migrations.Migration): dependencies = [ ('crowdsourcing', '0092_merge'),
('crowdsourcing', '0092_auto_20160608_0236'), ] operations = [ ]
rodricios/crawl-to-the-future
crawlers/Way-Back/waybacktrack.py
Python
gpl-2.0
7,577
0.006071
"""waybacktrack.py Use this to extract Way Back Machine's url-archives of any given domain! TODO: reiterate entire design! """ import time import os import urllib2 import random from math import ceil try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO from lxml import htm...
specify 'dir_name' value") if dir_path is DATASET_DIR: dir_path = os.path.join(dir_path, domain + '/') if not os.path.exists(dir_path): #raise IOError("[Errno 2] No such file or directory: '" + dir_path + "'") # this part is shady os.makedirs(dir_path) if not isinstance...
"Directory - third arg. - path must be a string.") ia_year_url = ARCHIVE_DOMAIN + "/web/" + str(year) + \ "*/http://" + domain + "/" ia_parsed = html.parse(ia_year_url) domain_snapshots = list(set(ia_parsed.xpath('//*[starts-with(@id,"' + ...
OpenBeta/beta
tests/test_api_routes.py
Python
gpl-3.0
1,343
0.001489
import json from apiserver.model import Route import utils def test_post(app, apiusers, db, default_headers, post_geojson): with app.test_client() as client: res = client.get('/routes?api_key=' + apiusers['valid'].api_key, default_headers['get']) assert res.status_code == 200 ret = post_g...
latlng={}&r={}'.format(latlng, radius) res = client.get('/routes?api_key=' + good_key + query_str, default_headers['get']) assert res.status_code == 200 actual_json = json.loads(res.data) assert len(actual_json['features']) > 0, "
Expect 1 route" actual_route = Route(actual_json['features'][0]) expected = Route(ret2['expected']['features'][0]) assert actual_route == expected, "Expect route to be equal"
Endika/manufacture
mrp_sale_info/__init__.py
Python
agpl-3.0
165
0
# -*- coding: utf-8 -
*- # © 2016 Antiun Ingenieria S.L. - Javie
r Iniesta # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from . import models
opendatateam/udata
udata/tests/api/test_swagger.py
Python
agpl-3.0
763
0
import json from flask import url_for from flask_restplus import schemas from udata.tests.helpers import assert200 class SwaggerBlueprintTest: modules = [] def test_swagger_resource_type(self, api): respons
e = api.get(url_for('api.specs')) assert200(response) swagger = json.loads(response.data) expected = swagger['paths']['/datasets/{dataset}/resources/'] expected = expected['put']['responses']['200']['schema']['type'] assert expected == 'array' de
f test_swagger_specs_validate(self, api): response = api.get(url_for('api.specs')) try: schemas.validate(response.json) except schemas.SchemaValidationError as e: print(e.errors) raise
tomhenderson/ns-3-dev-git
src/topology-read/bindings/modulegen__gcc_LP64.py
Python
gpl-2.0
251,206
0.014602
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) ...
or*', u'ns3::AttributeConstructionList::CIterator*') typehandlers.add_type_alias(u'std::list< ns3::AttributeConstructionList::Item > const_iterator&', u'ns3::AttributeConstructionList::CIterator&') ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network'...
s=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_mo...
tjcsl/cslbot
cslbot/commands/botspam.py
Python
gpl-2.0
1,606
0.001868
# Copyright (C) 2013-2018 Samuel Damashek, Peter Foley, James Forcier, Srijay Kasturi, Reed Koser, Christopher Reffett, and Tris Wilson # # 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 v...
SE. See the # GNU General Public License for more detai
ls. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from random import choice from ..helpers.command import Command from ..helpers.misc import get_fortu...
MartinHjelmare/home-assistant
homeassistant/components/nanoleaf/light.py
Python
apache-2.0
6,951
0
"""Support for Nanoleaf Lights.""" import logging import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_HS_COLOR, ATTR_TRANSITION, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_TRANSIT...
the icon to use in the frontend, if any.""" return ICON @property def is_on(self): """Return true if light is on.""" return self._state @property def hs_color(self): """Return the color in HS.""" return self._hs_color @property def suppor
ted_features(self): """Flag supported features.""" return SUPPORT_NANOLEAF def turn_on(self, **kwargs): """Instruct the light to turn on.""" brightness = kwargs.get(ATTR_BRIGHTNESS) hs_color = kwargs.get(ATTR_HS_COLOR) color_temp_mired = kwargs.get(ATTR_COLOR_TEMP) ...
riverloopsec/beekeeperwids
beekeeperwids/drone/daemon.py
Python
gpl-2.0
8,678
0.005646
#!/usr/bin/python import sys import plugins import flask import argparse import os import urllib2, urllib import threading import time import socket import subprocess import random import json import signal import traceback from uuid import uuid4 as generateUUID from killerbee import kbutils from beekeeperwids.utils.e...
ata) = self.startPlugin(plugin,channel) if error ==
None: pluginObject = data else: return (error,data) try: self.logutil.log('Tasking Plugin: ({0}, ch.{1}) with Task {2}'.format(plugin, channel, uuid)) success = pluginObject.task(uuid, parameters) if success == False: ...
BirkbeckCTP/janeway
src/proofing/models.py
Python
agpl-3.0
9,317
0.001717
__copyright__ = "Copyright 2017 Birkbeck, University of London" __author__ = "Martin Paul Eve & Andy Byers" __license__ = "AGPL v3" __maintainer__ = "Birkbeck Centre for Technology and Publishing" from django.db import models from django.utils import timezone from events import logic as event_logic from utils import ...
urnal): """ Checks if this round can have another proofreader. :param journal: Journal object :return: Boolean, True or False """ limit = setting_handler.get_setting( 'general', 'max_proofreaders', journal, ).processed_value ...
ount() if current_num_proofers >= limit: return False return True class ProofingTask(models.Model): round = models.ForeignKey(ProofingRound) proofreader = models.ForeignKey('core.Account', null=True, on_delete=models.SET_NULL) assigned = models.DateTimeField(default=t...
IBMStreams/streamsx.health
samples/HealthcareJupyterDemo/package/healthdemo/utils.py
Python
apache-2.0
2,562
0.015613
# Licensed Materials - Property of IBM # Copyright IBM Corp. 2016, 2017 class DataAlreadyExistsError(RuntimeError): def __init__(self, label): self.message = str("Data with label '%s' already exists and cannot be added" % (label)) def get_patient_id(d): return d['patient']['identifier'] def get_index_...
r(label=label) else: v =
{'label' : label, 'valueCoordinateData' : {'values' : coords}} d['data'].append(v)
liber118/pyFRED
src/fred_rules.py
Python
apache-2.0
11,958
0.005101
#!/usr/bin/env python # encoding: utf-8 ## Python impl of JFRED, developed by Robby Garner and Paco Nathan ## See: http://www.robitron.com/JFRED.php ## ## 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...
print "ERROR: cannot parse rule description", rule_lines sys.exit(1) else:
if isinstance(rule, FuzzyRule): fuzzy_dict[rule.name] = rule else: rule_dict[rule.name] = rule
zyoohv/zyoohv.github.io
code_repository/tencent_ad_contest/tencent_contest/model/main.py
Python
mit
1,329
0.000752
#! /usr/bin/python3 def main(): try: while True:
line1 = input().strip().split(' ') n = int(line1[0]) name_list = [] num_list = [0] for i in range(1, len(line1)): if i % 2 == 1: name_list.append(line1[i]) else: num_list.append(int(line1[...
ns = [0 for _ in range(len(num_list))] m = int(input()) for i in range(len(num_list) - 1, 0, -1): ans[i] = m % num_list[i] m = int(m / num_list[i]) ans[0] = m add = 0 if ans[1] * 2 >= num_list[1]: add...
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
orcid_api/models/contributor_orcid.py
Python
mit
3,922
0.00051
# coding: utf-8 """ ORCID Member No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: Latest Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import r...
if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) ...
__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, ContributorOrcid): return False return self.__dict__ == other.__dict_...
obmarg/toolz
toolz/itertoolz/recipes.py
Python
bsd-3-clause
1,295
0
import itertools from .core import frequencies from
..compatibility import map def countby(func, seq): """ Count elements of a collection by a key function >>> countby(len, ['cat', 'mouse', 'dog']) {3: 2, 5: 1} >>> def iseven(x): return x % 2 == 0 >>> countby(iseven, [1, 2, 3]) # doctest:+SKIP {True: 1, False: 2} See Also: gr
oupby """ return frequencies(map(func, seq)) def partitionby(func, seq): """ Partition a sequence according to a function Partition `s` into a sequence of lists such that, when traversing `s`, every time the output of `func` changes a new list is started and that and subsequent items are coll...
cheungpat/sqlalchemy-utils
sqlalchemy_utils/primitives/weekdays.py
Python
bsd-3-clause
1,866
0
import six from sqlalchemy_utils.utils import str_coercible from .weekday import Week
Day @str_coercible class WeekDays(object): def __init__(self, bit_string_or_week_days): if isinstance(bit_string_or_week_days, six.string_types): self._days = set() if len(bit_string_or_week_days) != WeekDay.NUM_WEEK_DAYS: raise ValueError( 'Bit...
string must be {0} characters long.'.format( WeekDay.NUM_WEEK_DAYS ) ) for index, bit in enumerate(bit_string_or_week_days): if bit not in '01': raise ValueError( 'Bit string may only con...
joefutrelle/pocean-core
pocean/tests/dsg/trajectoryProfile/test_trajectoryProfile_cr.py
Python
mit
4,960
0.000605
import os import unittest from dateutil.parser import parse as dtparse import numpy as np from pocean.dsg import ContiguousRaggedTrajectoryProfile import logging from pocean import logger logger.level = logging.INFO logger.handlers = [logging.StreamHandler()] class TestContinousRaggedTrajectoryProfile(unittest.Tes...
) def test_crtp_dataframe(self): with ContiguousRaggedTrajectoryProfile(self.single) as s: s.to_dataframe() with ContiguousRaggedTrajectoryProfile(self.multi) as m: m.to_dataframe() with ContiguousRaggedTrajectoryProfile(self.missing_time) as t: t.to_da...
def test_crtp_calculated_metadata(self): with ContiguousRaggedTrajectoryProfile(self.single) as st: s = st.calculated_metadata() assert s.min_t == dtparse('2014-11-25 18:57:30') assert s.max_t == dtparse('2014-11-27 07:10:30') assert len(s.trajectories) == 1 ...
NemesisRE/ACE3
tools/deploy.py
Python
gpl-2.0
1,499
0.002668
#!/usr/bin/env python3 #########################
########### # ACE3 automatic deployment script # # ================================ # # This is not meant to be run # # directly! # #################################### import os import sys import shutil import traceback import
subprocess as sp from pygithub3 import Github TRANSLATIONISSUE = 367 TRANSLATIONBODY = """**How to translate ACE3:** https://github.com/acemod/ACE3/blob/master/documentation/development/how-to-translate-ace3.md {} """ REPOUSER = "acemod" REPONAME = "ACE3" REPOPATH = "{}/{}".format(REPOUSER,REPONAME) USERNAME = "AC...
kottenator/django-compressor-toolkit
tests/integration_tests/test_views.py
Python
mit
3,738
0.002943
import re from django.core.urlresolvers import reverse def test_view_with_scss_file(client, precompiled): """ Test view that renders *SCSS file* that *imports SCSS file from another Django app*. :param client: ``pytest-django`` fixture: Django test client :param precompiled: custom fixture that asse...
*. :param client: ``pytest-django`` fixture: Django test client :param precompiled: custom fixture that asserts pre-compiled content """ response = client.get(reverse('es6-file')) assert response.status_code == 200 assert precompiled('app/scripts.js', 'js') == (
'(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==' '"function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=' 'new Error("Cannot find module \'"+o+"\'");throw f.code="MODULE_NOT_FOUND",f}' 'var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var...
amahabal/PySeqsee
farg/core/ui/gui/__init__.py
Python
gpl-3.0
7,857
0.005982
# Copyright (C) 2011, 2012 Abhijit Mahabal # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later version. # # This program is distribu...
m farg.core.question.question import BooleanQuestion from farg.core.ui.gui.central_pane import CentralPane import farg.flags as farg_flags class RunForNSteps(threading.Thread): """Runs controller for up
to n steps. This does not update the GUI directly; It however results in changing the state of the attribute "controller" that it holds. This is shared by the GUI and used to update itself. Before each step, checks that we have not been asked to pause. """ def __init__(self, *, controller, gui, num_st...
opencobra/cobrapy
src/cobra/test/test_io/test_annotation_format.py
Python
gpl-2.0
944
0
from os.path import join import pytest from cobra.io import load_json_model, write_sbml_model def test_load_json_model_valid(data_directory, tmp_path): """Test loading a valid annotation from JSON.""" path_to_file = join(data_directory, "valid_annotation_format.json") model = load_json_model(path_t
o_file) expected = { "bigg.reaction": [["is", "PFK26"]], "kegg.reaction": [["is", "R02732"]], "rhea": [["is", "15656"]], } for metabolite in model.metabolites: assert metabolite.annotation == expected path_to_output = join(str(tmp_path), "valid_annotation_output.xml") ...
eError""" path = join(data_directory, "invalid_annotation_format.json") with pytest.raises(TypeError): model = load_json_model(path)
Tesora-Release/tesora-trove
trove/tests/scenario/runners/database_actions_runners.py
Python
apache-2.0
9,910
0
# Copyright 2015 Tesora 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 a...
self, expected_exception=exceptions.BadRequest, expected_http_code=400): self.assert_databases_create_failure( self.instance_info.id, {'name': ''}, expected_exception, expected_http_code) def run_existing_database_create( self, expected_exception=excep...
_failure( self.instance_info.id, self.first_db_def, expected_exception, expected_http_code) def assert_databases_create_failure( self, instance_id, serial_databases_def, expected_exception, expected_http_code): self.assert_raises( expected_excepti...
nikesh-mahalka/cinder
cinder/volume/drivers/dell/dell_storagecenter_iscsi.py
Python
apache-2.0
7,849
0
# Copyright 2015 Dell 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 agree...
# If there is a d
ata structure issue then detail the exception # and bail with a Backend Exception. except Exception as error: LOG.error(error) raise exception.VolumeBackendAPIException(error) # We get here because our mapping is none or we have no valid iqn to # ...
rayhu-osu/vcube
valet/migrations/0004_auto_20170801_1622.py
Python
mit
418
0
#
-*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-08-01 20:22 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('valet', '0003_sequence_driver'), ] operations = [ migrations.RenameMode...
acevest/acecode
learn/python/try.py
Python
gpl-2.0
456
0.013158
#!/usr/bin/python # -*- coding: utf-8 -*- # ----------------------------------------
---------------------------------- # File Name: try.py # Author: Zhao Yanbai # Wed Dec 28 21:41:17 2011 # Descr
iption: none # -------------------------------------------------------------------------- try: s = input("Enter an integer: ") n = int(s) print "valid integer entered: ", n except NameError as nerr: print nerr except ValueError as verr: print verr
fnaum/rez
src/rez/vendor/attr/_funcs.py
Python
lgpl-3.0
9,725
0
from __future__ import absolute_import, division, print_function import copy from ._compat import iteritems from ._make import NOTHING, _obj_setattr, fields from .exceptions import AttrsAttributeNotFoundError def asdict( inst, recurse=True, filter=None, dict_factory=dict, retain_collection_types...
``recurse`` is ``True``. :rtype: return type of *tuple_factory* :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class. .. versionadded:: 16.2.0 """ attrs = fields(inst.__class__) rv = [] retain = retain_collection_types # Very long. :/ for ...
a, v): continue if recurse is True: if has(v.__class__): rv.append( astuple( v, recurse=True, filter=filter, tuple_factory=tuple_factory, ...
anhstudios/swganh
data/scripts/templates/object/tangible/veteran_reward/shared_antidecay.py
Python
mit
459
0.045752
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION
FOR EXA
MPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/veteran_reward/shared_antidecay.iff" result.attribute_template_id = -1 result.stfName("item_n","veteran_reward_antidecay") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return resul...
jorisvandenbossche/pandas
pandas/core/arrays/boolean.py
Python
bsd-3-clause
23,248
0.000559
from __future__ import annotations import numbers from typing import ( TYPE_CHECKING, overload, ) import warnings import numpy as np from pandas._libs import ( lib, missing as libmissing, ) from pandas._typing import ( ArrayLike, AstypeArg, Dtype, DtypeObj, npt, type_t, ) from...
buflist[1]], offset=arr.offset ).to_numpy(zero_copy_only=False) if arr.null_count != 0: mask = pyarrow.BooleanArray.from_buffers( arr.type, len(arr), [None, buflist[0]], offset=arr.offset ).to_numpy(zero_copy_only=False) mask =...
bool_arr = BooleanArray(data, mask) results.append(bool_arr) if not results: return BooleanArray( np.array([], dtype=np.bool_), np.array([], dtype=np.bool_) ) else: return BooleanArray._concat_same_type(results) def _get_common_dt...
andymckay/addons-server
src/olympia/zadmin/tests/test_views.py
Python
bsd-3-clause
77,618
0.000013
# -*- coding: utf-8 -*- import csv import json from cStringIO import StringIO from datetime import datetime from django.conf import settings from django.core import mail from django.core.cache import cache import mock from pyquery import PyQuery as pq from olympia import amo from olympia.amo.tests import TestCase fr...
=amo.FIREFOX.id, version=self.version).update( max=AppVersion.objects.get(application=1, version='3.7a1pre')) self.application_version = self.version.apps.all()[0] self.application = self.application_version.application
self.min = self.application_version.min self.max = self.application_version.max self.curr_max = self.appversion('3.7a1pre') self.counter = 0 self.old_task_user = settings.TASK_USER_ID settings.TASK_USER_ID = self.creator.id def tearDown(self): settings.TASK_USE...
OLAPLINE/TM1py
TM1py/Utils/MDXUtils.py
Python
mit
10,016
0.002895
import warnings class DimensionSelection: """ Instances of this class to be passed to construct_mdx function """ SUBSET = 1 EXPRESSION = 2 ITERABLE = 3 def __init__(self, dimension_name, elements=None, subset=None, expression=None): warnings.warn( f"class DimensionSelecti...
ion_from_mdx_set_or_tuple(mdx_columns) titles = read_dimension_composition_from_mdx_set_or_tuple(mdx_where) return cube, rows, columns, titles def read_dimension_composition_from_mdx_set_or_tuple(mdx): warnings.warn( f"Module MdxUtils will be deprecated. Use https://github.com/cubewise-code/mdxpy...
t no where statement if len(mdx_without_spaces) == 0: return [] # case for tuples mdx statement on rows or columns if mdx_without_spaces[1] == '(' and mdx_without_spaces[-2] == ')': return read_dimension_composition_from_mdx_tuple(mdx) # case for where mdx statement elif mdx_without_...
fclesio/learning-space
Python/textract_extraction.py
Python
gpl-2.0
1,358
0.002209
import boto3 import numpy as np import time import json import os import pandas as pd name = 'Flavio C.' root_dir = '/document/' file_name = 'augmented-data.png' # Get all files in directory meine_id_kartes = os.listdir(root_dir) # get the results client = boto3.client( service_name='textract', region_name='...
i = json.dumps(i) i = json.loads(i) try: meine_id_karte_text.append(i['Text']) except: pass meine_id_karte_card_info.append((meine_id_karte, meine_id_kart
e_text)) except: pass df_legible = pd.DataFrame(meine_id_karte_card_info) df_legible.to_csv('normal-karte.csv') print(df_legible)
BetterCollective/thumbor
tests/loaders/test_http_loader.py
Python
mit
7,414
0.00054
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com timehome@corp.globo.com from os.path import abspath, join, dirname from preggy import expect ...
.to_be_null() expect(result.successful).to_be_false() def test_return_body_if_valid(self): response_mock = ResponseMock(body='body', code=200) callback_mock = mock.Mock() ctx = Context(None, None, None) loader.return_contents(response_mock, 'some-url', callback_mock, ctx) ...
expect(result.buffer).to_equal('body') def test_return_upstream_error_on_body_none(self): response_mock = ResponseMock(body=None, code=200) callback_mock = mock.Mock() ctx = Context(None, None, None) loader.return_contents(response_mock, 'some-url', callback_mock, ctx) ...
jakubbrindza/gtg
GTG/gtk/browser/browser.py
Python
gpl-3.0
61,395
0.000016
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # t...
ytags_dialog = ModifyTagsDialog(tag_completion, self.req) self.calendar = GTGCalendar() self.calendar.set_transient_for(self.window) self.calendar.connect("date-changed", self.on_date_changed) def init_tags_sidebar(self): """ initializes the tagtree (left area with tags and ...
self.tv_factory.tags_treeview(self.tagtree) # Tags treeview self.tagtreeview.get_selection().connect('changed', self.on_select_tag) self.tagtreeview.connect('button-press-event', self.on_tag_treeview_button_press_e...
tkasp/osmose-backend
analysers/Analyser_Osmosis.py
Python
gpl-3.0
28,447
0.005765
#-*- coding: utf-8 -*- ########################################################################### ## ## ## Copyrights Frederic Rodrigo 2011 ## ## ...
lf.dump_class(self.classs)
try: self.analyser_osmosis_common() finally: self.error_file.analyser_end() if self.classs_change != {}: self.logger.log(u"run osmosis change an
hzlf/openbroadcast
website/tools/suit/watch_less.py
Python
gpl-3.0
1,306
0
import sys import os import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler, FileModifiedEvent class LessCompiler(FileSystemEventHandler): def __init__(self, source): self.source = source FileSystemEventHandler.__init__(self) def compile_css(s...
destination = sys.argv[2] cmd = 'lessc %s > %s -x' % (source, os.path.abspath(destination)) print(cmd) os.system(cmd) def on_any_event(self, event): if '__' not in event.src_path and isinstance(event, FileModifiedEvent): self.compile_css() if __name__ == "__m...
) source = os.path.abspath(sys.argv[1]) event_handler = LessCompiler(source) # Run once at startup event_handler.compile_css() observer = Observer() observer.schedule(event_handler, os.path.dirname(source), recursive=True) observer.start() try: while True: time.sleep...
mortada/tensorflow
tensorflow/python/ops/rnn.py
Python
apache-2.0
44,560
0.004129
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ze, state_size]`. state_size: The `cell.state_size` associated with the state. skip_conditionals: Python bool, whether to skip using the conditional calculations. This is useful for `dynamic_rnn`, where the input tensor matches `max_sequence_length`, and using conditionals just slows everythi...
`) as given by the pseudocode above: final_output is a `Tensor` matrix of shape [batch_size, output_size] final_state is either a single `Tensor` matrix, or a tuple of such matrices (matching length and shapes of input `state`). Raises: ValueError: If the cell returns a state tuple whose leng...
ondrejkajinek/pyGrim
example/server.py
Python
mit
1,308
0.000765
# coding: utf8 from pygrim import Server as WebServer from routes import Routes from test_iface import Test from uwsgidecorators import postfork as postfork_decorator # from pygrim.components.session import FileSessionStorage # to create custom session handler, view, etc: """ class MySessionClass(SessionStorage): ...
gs) def postfork(self): # for all interfaces call postfork to ensure all will be called for cls in inheritance: pfork = getattr(cls, "postfork", None) if pfork: pfork(self) # Dynamicaly creating type. # It allows me to do the trick with inheritance in po
stfork without # using inspect Server = type("Server", inheritance, { "__init__": __init__, "postfork": postfork }) # naming instance of Server as application # can bee seen in configfile in section uwsgi->module=server:application # server is filename and application is method (uwsgi will do __call__ o...
betoesquivel/PLYpractice
testingParser.py
Python
mit
1,412
0.003541
import parser import logging def test(code): log = logging.getLogger() parser.parser.parse(code, tracking=True) print "Programa con 1 var y 1 asignacion bien: " s = "program id; var beto: int; { id = 1234; }" test(s) print "Original: \n{0}".format(s) print "\n" print "Programa con 1 var mal: " s = "program ;...
int "\n" print "Programa con var mal: " s = "program id; var beto int; { id = 1234; }" test(s) print "Original: \n{0}".format(s) print "\n" print "Programa con var mal: " s = "program id; var beto: int { id = 1234; }" test(s); print "Original: \n{0}".format(s) print "\n" print "Programa con var mal: " s = "program i...
: int; { id = 1234; }" test(s) print "Original: \n{0}".format(s) print "\n" print "Programa con bloque vacio bien: " s = "program id; var beto: int; { }" test(s) print "Original: \n{0}".format(s) print "\n" print "Programa con bloque lleno y estatuto mal: " s = "program id; var beto: int; { id = 1234; id2 = 12345 }"...
masiqi/douquan
member/urls.py
Python
mit
478
0.002092
from django.conf.urls.defaults import * urlpatterns = patterns('member.views', url(r'^$', 'login', name='passport_index'), url(r'^register/$', 'register', name='passpor
t_register'), url(r'^login/$', 'login', name='passport_login'), url(r'^logout/$', 'logout', name='passport_logout'), url(r'^active/$', 'active', name='passport_active'), url(r'^forget/$', 'forge
t', name='passport_forget'), url(r'^profile/$', 'profile', name='passport_profile'), )
mvaled/sentry
tests/sentry/api/validators/sentry_apps/test_image.py
Python
bsd-3-clause
966
0
from __future__ import absolute_import from sentry.testutils import TestCase from .util import invalid_schema from sentry.api.validators.sentry_apps.schema import validate_component class TestImageSchemaValidation(TestC
ase): def setUp(self): self.schema = { "type": "image", "url": "https://example.com/image.gif", "alt": "example video", } def test_valid_schema(self):
validate_component(self.schema) @invalid_schema def test_missing_url(self): del self.schema["url"] validate_component(self.schema) @invalid_schema def test_invalid_url(self): self.schema["url"] = "not-a-url" validate_component(self.schema) def test_missing_alt(self...
sashakames/COG
cog/forms/forms_project.py
Python
bsd-3-clause
9,756
0.005638
from cog.models import * from django.forms import ModelForm, ModelMultipleChoiceField, NullBooleanSelect from django.db import models from django.contrib.admin.widgets import FilteredSelectMultiple from django import forms from django.forms import ModelForm, Textarea, TextInput, Select, SelectMultiple, FileInput, Check...
class Meta: model = Project fields = ('short_name', 'long_name', 'author', 'description', 'parents', 'peers', 'logo', 'logo_url', 'activ
e', 'private', 'shared', 'dataSearchEnabled', 'nodesWidgetEnabled', 'site', 'maxUploadSize') class ContactusForm(ModelForm): # overridden validation method for project short name def clean_projectContacts(self): value = self.cleaned_data['projectContacts'] i...
nisavid/bedframe
bedframe/auth/http/_basic/_connectors.py
Python
lgpl-3.0
1,567
0.000638
"""Connectors""" __copyright__ = "Copyright (C) 2014 Ivan D Vasin" __docformat__ = "restructuredtext" import abc as _abc import re as _re from ... import plain as _plain from .. import _std as _std_http _BASIC_USER_TOKENS = ('user', 'password') class HttpBasicClerk(_std_http.HttpStandardClerk): """An authen...
ets(self, upstream_affordances, downstream_affordances): return (_plain.PlainAuth.PROVISIONS,) class HttpBasicScanner(_std_http.HttpStandardScanner): """An authentication scanner for HTTP Basic authentication""" __metaclass__ = _abc.ABCMeta _AUTHORIZATION_HEADER_RE = \ _re.c
ompile(r'\s*Basic\s*(?P<creds_base64>[^\s]*)') _BASIC_USER_TOKENS = _BASIC_USER_TOKENS def _outputs(self, upstream_affordances, downstream_affordances): return (self._BASIC_USER_TOKENS,) def _provisionsets(self, upstream_affordances, downstream_affordances): return (_plain.PlainAuth.PROVI...
pyfa-org/Pyfa
gui/builtinContextMenus/droneSplitStack.py
Python
gpl-3.0
3,081
0.002597
import re # noinspection PyPackageRequirements import wx import gui.fitCommands as cmd import gui.mainFrame from gui.contextMenu import ContextMenuSingle from service.fit import Fit _t = wx.GetTranslation class DroneSplitStack(ContextMenuSingle): def __init__(self): self.mainFrame = gui.mainFrame.Main...
r) self.input.Bind(wx.EVT_TEXT_ENTER, self.processEnter) self.SetSizer(bSizer1) self.CenterOnParent() self.Fit() def processEnter(self, evt): self.EndModal(wx.ID_OK) # checks to make sure it's valid number @staticme
thod def onChar(event): key = event.GetKeyCode() acceptable_characters = "1234567890" acceptable_keycode = [3, 22, 13, 8, 127] # modifiers like delete, copy, paste if key in acceptable_keycode or key >= 255 or (key < 255 and chr(key) in acceptable_characters): event.Ski...
c22n/ion-channel-ABC
docs/examples/hl1/data/ikr/data_ikr.py
Python
gpl-3.0
6,863
0.009617
import numpy as np ### Digitised data for HL-1 i_Kr channel. # I-V curves. def IV_Toyoda(): """Data points in IV curve for i_Kr. Data from Figure 1E from Toyoda 2010. Reported as mean \pm SEM from 10 cells. """ x = [-80, -70, -60, -50, -40, -30, -20, -10, 0, 10, 20, 30, 40] y = np.asarray([0...
= np.asarray([4.430675707271462, 6.125789104512478, 7.817005689346161, 3.1291403631829553, 13.027043
878107747, 15.63011456628476, 30.095082222741894, 45.460213545320016, 64.47665809367948, 69.81918790429427]) N = 10 sem = np.asarray([15.372924947393017, 17.068038344634147, 18.759254929467716, 14.979346894240507, 23.05743901488586, 26.572363806406315, 40.12158054711244...
jackemoore/cfclient-gps-2-ebx-io
lib/cflib/crazyflie/ablock.py
Python
gpl-2.0
17,198
0.005815
#!/usr/bin/env python # -*- coding: utf-8 -*- # # || ____ _ __ # +------+ / __ )(_) /_______________ _____ ___ # | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ # # Copyright (C) 20...
lenNext = lineLen - 2 i = 0 while i < lenNext : block = block + data[iData] iData += 1 i += 1 if lenNext > 0 : block = block + "\n" lenLast -= lenNext i = 0 while i < lenLast : block = block + data[iDat...
] iData += 1 i += 1 block = block + "<>\n" print len(block) self.putFile(block, add) def get_int_len(self, val, base): value = val if value < 0: value = - value l = 1 while value > base - 1: l += 1 v...
OmniaGM/spark-training
quiz/quiz1/quiz.py
Python
mit
628
0.007962
#!/usr/bin/env python old_new_salaries = [
# (old_salary, new_salary) (2401, 2507), (2172, 2883), (2463, 2867), (2462, 3325), (2949, 2974), (2713, 3109), (2778, 3771), (2596, 3045), (2819, 2848), (2974, 3322), (2539, 2790), (2440, 3051), (2526, 3240), (2869, 3635), (2341, 2495), (2197, 2897), (2706, 2782), (2
712, 3056), (2666, 2959), (2149, 2377) ] def is_high_raise(r): return r > 500 raises = map( lambda ss: ss[1] - ss[0] , old_new_salaries) high_raises = filter(is_high_raise, raises) total_high_raises = reduce(lambda a,b: a + b, high_raises) print "total high raises: %s" % total_high_raises
1kastner/analyse_weather_data
interpolation/interpolator/prepare/neural_network_single_group_filtered.py
Python
agpl-3.0
3,132
0.002554
""" prepare prediction: filtered pws -> filtered pws Uses: PROCESSED_DATA_DIR/neural_networks/training_data_filtered.csv """ import os import random import logging import platform import pandas from filter_weather_data.filters import StationRepository from filter_weather_data import get_repository_parameters from f...
ata"]["position"] station_df['lat'] = position["lat"] station_df['lon'] = position["lon"] joined_stations.append(station_df.join(eddh_df, how="left")) common_df = pandas.concat(joined_stations) common_df.sort_index(inplace=True) common_df = fill_missing_eddh_values(common_df) com...
y = StationRepository(*get_repository_parameters( RepositoryParameter.ONLY_OUTDOOR_AND_SHADED )) station_dicts = station_repository.load_all_stations( start_date, end_date, # limit=5, # for testing purposes limit_to_temperature=False ) random.shuffle(station_dic...
gljohn/meterd
meterd/parser/currentcost.py
Python
gpl-3.0
1,012
0.003953
''' Module ''' import re import logging class CurrentCost: ''' Class ''' ''' def __init__(self, data=None, logger=None): ''' Method ''' self._data = data self.logger = logger or logging
.getLogger(__name__) self.time = None self.uid = None self.value = None ''' def parse_data(self): ''' Method ''' try: '''#http://www.marcus-povey.co
.uk - USED REGEX REGEX!''' uidregex = re.compile('<id>([0-9]+)</id>') valueregex = re.compile('<watts>([0-9]+)</watts>') timeregex = re.compile('<time>([0-9\.\:]+)</time>') self.value = str(int(valueregex.findall(self._data)[0])) self.time = timeregex.findall(...
openhatch/new-mini-tasks
vendor/packages/Django/tests/regressiontests/admin_scripts/complex_app/models/foo.py
Python
apache-2.0
148
0.006757
from django.db import models class Foo(models.Model): name = models.CharField(ma
x_length=5) class Meta: app_label = 'complex_app'
lahwaacz/qutebrowser
scripts/dev/misc_checks.py
Python
gpl-3.0
5,504
0.000182
#!/usr/bin/env python3 # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as pu...
y_py=True): with tokenize.open(fn) as f: for line in f: if any(line.startswith(c * 7) for c in '<>=|'): print("Found conflict marker
in {}".format(fn)) ok = False print() return ok except Exception: traceback.print_exc() return None def main(): parser = argparse.ArgumentParser() parser.add_argument('checker', choices=('git', 'vcs', 'spelling'), help="Which ...
fanglinfang/myuw
myuw/test/dao/canvas.py
Python
apache-2.0
1,890
0
from django.test import TestCase from django.test.client import RequestFactory from myuw.dao.canvas import get_indexed_data_for_regid from myuw.dao.canvas import get_indexed_by_decrosslisted from myuw.dao.schedule import _get_schedule from myuw.dao.term import get_current_quarter FDAO_SWS = 'restclients.dao_implement...
cs = data['2013,spring,PHYS,121/A'] self.assertEquals(physics.course_url, 'https://canvas.uw.edu/courses/149650') train = data['2013,spring,TRAIN,100/A'] self.assertEquals(train.course_url, 'https://canvas.uw.edu/courses/
249650')
adereis/avocado
avocado/utils/archive.py
Python
gpl-2.0
7,118
0.00014
# 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 program is distributed in the hope that it will be useful, # bu...
self.filename) return attr = info.external_attr >> 16 if attr & stat.S_IFLNK == stat.S_IFLNK: dst = os.path.join(dst_dir, path) src = open(dst, 'r').read() os.remove(dst) os.symlink(src, dst)...
ode != 436: # If mode is stored and is not default os.chmod(dst, mode) def close(self): """ Close archive. """ self._engine.close() def is_archive(filename): """ Test if a given file is an archive. :param filename: file to test. :return: `True` if...
PXke/invenio
invenio/legacy/bibcatalog/templates.py
Python
gpl-2.0
3,365
0.009807
## Thi
s file is part of Invenio. ## Copyright (C) 2009, 2010, 2011 CERN. ## ## Invenio 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. ## ...
S FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Invenio BibCatalog HTML ...
Cue/greplin-twisted-utils
src/greplin/net/dnsCache.py
Python
apache-2.0
2,900
0.01069
# Copyright 2011 The greplin-twisted-utils Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
local cache to improve performance.""" implements(interfaces.IResolverSimple) def __init__(self, original, timeout = 60, useFallback = True): self._original = original self._timeout = timeout self._fallback = {} if useFallback else None self._cache = lazymap.DeferredMap(self.__fetchHost) self....
ats = { 'miss': collections.defaultdict(int), 'hit': collections.defaultdict(int), 'error': collections.defaultdict(int), 'fallback': collections.defaultdict(int), } def __fetchHost(self, args): """Actually fetches the host name.""" return self._original.getHostByName(*args).addC...
SRLKilling/sigma-backend
data-server/django_app/sigma_core/admin.py
Python
agpl-3.0
3,213
0.008092
from django.contrib import admin from dj
ango.contrib.auth.models import Group as AuthGroup from sigma_core.models.user import User from sigma_core.models.group import Group from sigma_core.models.group_member import GroupMember from sigma_core.models.group_field impor
t GroupField from sigma_core.models.group_field_value import GroupFieldValue from sigma_core.models.group_invitation import GroupInvitation from sigma_core.models.participation import Participation from sigma_core.models.publication import Publication from sigma_core.models.event import Event from sigma_core.models.sha...
boris-savic/python-furs-fiscal
demos/invoice_demo.py
Python
mit
1,878
0.004792
import pytz from datetime import datetime from decimal import Decimal from furs_fiscal.api import FURSInvoiceAPI # Path to our .p12 cert
file P12_CERT_PATH = 'demo_podjetje.p12' # Password for out .p12 cert file P12_
CERT_PASS = 'Geslo123#' class InvoiceDemo(): def demo_zoi(self): """ Obtaining Invoice ZOI - Protective Mark of the Invoice Issuer Our Invoice Number on the Receipt is: 11/BP101/B1 Where: * 11 - Invoice Number * BP101 - Business premise ID * B1...
toomanyjoes/mrperfcs386m
test/gen.py
Python
mit
26,543
0.029951
#!/usr/bin/py
thon import xml.dom.minidom import sys from optparse import OptionParser import random from hadoop_conf import * chunk_size = [] def xml_children(node, children_name): """return list of node's children nodes with name of children_name""" return node.getElementsByTagName(children_name) def xml_text(node): retur...
: """probably encoded in utf-8, be careful.""" return xml_text(xml_children(node, child_name)[0]) class empty_t: pass class hnode_t: """HDFS node for a HDFS tree. 5-level hierarchy: rack_group (multiple identical racks), rack, node_group (multiple identical nodes), node, and disk. disk should be initiated with ...
antoinecarme/pyaf
tests/artificial/transf_None/trend_Lag1Trend/cycle_5/ar_/test_artificial_128_None_Lag1Trend_5__100.py
Python
bsd-3-clause
260
0.088462
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.
process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 5, transform = "None", sigma = 0.0, exog_count = 100, ar_order = 0)
;
rhyolight/nupic.son
app/soc/views/user.py
Python
apache-2.0
4,262
0.005397
# Copyright 2011 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # ht
tp://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 permiss
ions and # limitations under the License. """Module for the User related pages.""" import os from django.conf.urls import url as django_url from soc.logic import accounts from soc.logic import cleaning from soc.models.user import User from soc.views import base from soc.views.forms import ModelForm class UserCrea...
f-apolinario/BFTStorageService
server/StorageService.py
Python
mit
750
0.025333
import xmlrpclib from SimpleXMLRPCServer import SimpleXMLRPCServer import json import KV
SHandler as handler with open('config.json') as d: config = json.load(d) ip = config['ip'] port = int(config['port']) def write(key, value): global handler return handler.write(key,value) def delete(key): global handler return handler.delete(key) def list(): global handler return handler.list() def read...
ister_function(write, "write") server.register_function(delete, "delete") server.register_function(list, "list") server.register_function(read, "read") server.serve_forever()
plotly/python-api
packages/python/plotly/plotly/tests/test_core/test_px/test_px_functions.py
Python
mit
11,286
0.00124
import plotly.express as px import plotly.graph_objects as go from numpy.testing import assert_array_equal import numpy as np import pandas as pd import pytest def _compare_figures(go_trace, px_fig): """Compare a figure created with a go trace and a figure created with a px function call. Check that all value...
(df, path=path, values="values") assert fig.data[0].branchvalues == "total" assert fig.data[0].values[-1] == np.sum(values) # Values passed fig
= px.sunburst(df, path=path, values="values") assert fig.data[0].branchvalues == "total" assert fig.data[0].values[-1] == np.sum(values) # Continuous colorscale fig = px.sunburst(df, path=path, values="values", color="values") assert "coloraxis" in fig.data[0].marker assert np.all(np.array(fig....
nouiz/pydy
examples/Kane1985/Chapter5/Ex9.3.py
Python
bsd-3-clause
3,590
0.002237
#!/usr/bin/env pyt
hon # -*- coding: utf-8 -*- """Exercise 9.3 from Kane 1985.""" from __future__ impor
t division from sympy import cos, diff, expand, pi, solve, symbols from sympy.physics.mechanics import ReferenceFrame, Point from sympy.physics.mechanics import dot, dynamicsymbols from util import msprint, subs, partial_velocities from util import generalized_active_forces, potential_energy g, m, Px, Py, Pz, R, t = ...
manfredmacx/django-convo
convo/Convo.py
Python
mit
2,261
0.037152
""" Util class """ from django.forms import ModelForm, CharField, URLField, BooleanField from django.db import models from models import Entry def getForm(
user): """ If no form is passed in to new/edit views, use this one """ class _Form(ModelForm): class Meta: model = Entry fields = ('title', 'body',) def save(self, force_insert=False, force_update=False, commit=True): m = super(ModelForm, self).save(commit=False) import bleach TAGS = ['b', 'em', 'i...
y'], tags=TAGS) if commit: m.save() return m class _AdminForm(ModelForm): published = BooleanField(required = False, initial = False) class Meta: model = Entry fields = ('title', 'body', 'published') class _AnonForm(ModelForm): owner_if_anonymous = CharField(max_length = 150, label="Name") ur...
dragondjf/musicplayertest
constant.py
Python
gpl-2.0
1,831
0.004369
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 Deepin, Inc. # 2011 Hou Shaohui # # Author: Hou Shaohui <houshao55@gmail.com> # Maintainer: Hou ShaoHui <houshao55@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Ge...
d warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this
program. If not, see <http://www.gnu.org/licenses/>. from nls import _ CONFIG_FILENAME = "config" PROGRAM_NAME = "deepin-music-player" PROGRAM_VERSION = "2.0" PROGRAM_NAME_LONG = _("Deepin Music") PROGRAM_NAME_SHORT = _("DMusic") DEFAULT_TIMEOUT = 10 DEFAULT_FONT_SIZE = 9 AUTOSAVE_TIMEOUT = 1000 * 60 * 5 # 5min #...
TeppieC/M-ords
mords_backend/mords_backend/wsgi.py
Python
mit
404
0
""" WSGI config for mords_backend project. 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.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE",
"mords_backend.settings") application = get_wsgi_application()
montanier/pandora
docs/tutorials/01_src/tutorial_pyPandora.py
Python
lgpl-3.0
2,012
0.011928
#!/usr/bin/python3 import os, sys, random pandoraPath = os.getenv('PANDORAPATH', '/usr/local/
pandora') sys.path.append(pandoraPath+'/bin') sys.path.append(pandoraPath+'/lib') from pyPandora import Config, World, Agent, SizeInt class MyAgent(Agent): gatheredResources = 0 def __init__(self, id): Agent.__init__( self, id) print('constructing agent: ',self
.id) def updateState(self): print('updating state of: ',self.id) newPosition = self.position newPosition._x = newPosition._x + random.randint(-1,1) newPosition._y = newPosition._y + random.randint(-1,1) if self.getWorld().checkPosition(newPosition): ...
svn2github/pyopt
pyOpt/pyGCMMA/__init__.py
Python
gpl-3.0
112
0.017857
#!/usr/bin/env p
ytho
n try: from pyGCMMA import GCMMA __all__ = ['GCMMA'] except: __all__ = [] #end
ingenieroariel/geonode
geonode/groups/tests.py
Python
gpl-3.0
22,844
0.000175
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 ...
layer.get_self_resource() in self.bar.resources( resource_type='layer')) self.assertTrue( map.get_self_resource() not in self.bar.resources( resource_type='layer')) # Revoke permissions on the layer from the self.bar group layer.set_permissions("{}"...
def test_perms_info(self): """ Tests the perms_info function (which passes permissions to the response context). """ # Add test to test perms being sent to the front end. layer = Layer.objects.all()[0] layer.set_default_permissions() perms_info = layer.get_al...
alanjw/GreenOpenERP-Win-X86
python/Lib/site-packages/_xmlplus/dom/html/HTMLTextAreaElement.py
Python
agpl-3.0
4,989
0.005813
######################################################################## # # File Name: HTMLTextAreaElement # # ### This file is automatically generated by GenerateHtml.py. ### DO NOT EDIT! """ WWW: http://4suite.com/4DOM e-mail: support@4suite.com Copyright (c) 2000 Fourthought Inc, USA. All Ri...
ent.__init__(self, ownerDocument, nodeName) ### Attribute Methods ### def _get_accessKey(self): retur
n self.getAttribute("ACCESSKEY") def _set_accessKey(self, value): self.setAttribute("ACCESSKEY", value) def _get_cols(self): value = self.getAttribute("COLS") if value: return int(value) return 0 def _set_cols(self, value): self.setAttribute("COLS", str...
gramps-project/addons-source
GenealogyTree/gt_ancestor.py
Python
gpl-2.0
6,685
0.003141
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2017-2018 Nick Hall # # 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) a...
stributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General
Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # """ LaTeX Genealogy Tree ancestor report """ #------------------------...
eifuentes/kaggle_whats_cooking
train_word2vec_rf.py
Python
mit
1,909
0.002095
""" train supervised classifier with what's cooking recipe data objective - determine recipe type categorical value from 20 """ import time from features_bow import * from features_word2vec import * from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifie...
nts['train']['features_matrix'] # standardize features aka mean ~ 0, std ~ 1 if std: scaler = StandardScaler() scaler.fit(X_train) X_train = scaler.transform(X_train) # random forest su
pervised classifier time_0 = time.time() clf = RandomForestClassifier(n_estimators=100, max_depth=None, n_jobs=n_jobs, random_state=random_state, verbose=verbose) # perform cross validation cv_n_fold = 8 print 'cross validating %s ways...' % cv_n_fold scores_cv = cross_val_score(clf, X_t...
memphis-iis/GLUDB
tests/testpkg/module.py
Python
apache-2.0
123
0
from gludb.simple import DBObject, Field @D
BObject(table_name='TopData') class TopDat
a(object): name = Field('name')
google/ghost-userspace
experiments/scripts/shenango.py
Python
apache-2.0
4,128
0.009205
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
thermore, for the CFS experiments, the worker threads sleep on a futex when they do not have work rather than spin so that CFS gives the Antagonist threads a chance to run. """ from typing import Sequence from absl import app from experiments.scripts.options import CfsWaitType from experiments.scripts.options import C...
tions import GetAntagonistOptions from experiments.scripts.options import GetGhostOptions from experiments.scripts.options import GetRocksDBOptions from experiments.scripts.options import Scheduler from experiments.scripts.run import Experiment from experiments.scripts.run import Run _NUM_CPUS = 8 _NUM_CFS_WORKERS = _...
Knapsacks/power-pi-v2
facebook-messenger-bot/app.py
Python
mit
5,321
0.004326
# -*- coding: utf-8 -*- from flask import Flask, request from fbmq import Page, QuickReply, Attachment, Template import requests, records, re, json from flask_restful import Resource, Api token = '<auth token here>' metricsData = {} macid = 111111111111 pg = Page(token) import time db = records.Database('mysql://<user>...
er_id, "Hey %s, please send me your MAC ID" % user) else: pg.typing_on(sender_id) quick_replies = [ {'title': 'Charging status', 'payload': 'charge_stat'}, {'title': 'Last saved', 'payload': 'l_saved'}
, {'title': 'Total saving', 'payload': 'c_saved'}, ] pg.send(sender_id, "What do you want to know?", quick_replies=quick_replies) @pg.callback(['charge_stat', 'l_saved', 'c_saved']) def doer(payl, event): global macid global metricsData sender_id = event.sender_id pg.typing_on...
gustavofonseca/packtools
tests/test_schematron_1_3.py
Python
bsd-2-clause
181,171
0.000746
# coding: utf-8 from __future__ import unicode_literals import unittest import io from lxml import isoschematron, etree from packtools.catalogs import SCHEMAS SCH = etree.parse(SCHEMAS['sps-1.3']) def TestPhase(phase_name, cache): """Factory of parsed Schematron phases. :param phase_name: the phase name ...
l-meta> </front> </article> """ sample = io.BytesIO(sample.encode('utf-8')) self.assertFalse(self._run_validation(sample)) def test_case3(self): """ presence(@nlm-ta) is False presence(@publisher-id) is True ...
RSP </journal-id> </journal-meta> </front> </article> """ sample = io.BytesIO(sample.encode('utf-8')) self.assertTrue(self._run_validation(sample)) def test_case4(self): ...
abhinavjain241/acousticbrainz-server
db/test/test_data.py
Python
gpl-2.0
14,021
0.003994
from db.testing import DatabaseTestCase, TEST_DATA_PATH import db.exceptions import db.data import os.path import json import mock import copy class DataDBTestCase(DatabaseTestCase): def setUp(self): super(DataDBTestCase, self).setUp() self.test_mbid = "0dad432b-16cc-4bf0-8961-fd31d124b01b" ...
patch("db.data.sanity_check_data") @mock.patch("db.data.write_low_level") @mock.patch("d
b.data.clean_metadata") def test_submit_low_level_data_missing_keys(self, clean, write, sanity): """Check that hl write raises an error if some required keys are missing""" clean.side_effect = lambda x: x sanity.return_value = ["missing", "key"] with self.assertRaises(db.exceptions....
rickmer/rephone
tests/test_views.py
Python
agpl-3.0
1,721
0.001162
from . import RephoneTest from re import match class TestViews(RephoneTest): def test_index(self): with self.client: response = self.client.get('/') assert response.status_code == 303 def test_outbound(self): with self.client: response = self.client.post('...
_NUMBER'] = '+4940123456789' response = self.client.post('/outbound/1') assert response.status_code == 200 assert match(r'.*<Dial><Number>\+49401
23456789</Number></Dial>.*', str(response.get_data())) def test_bias_alteration_audience_1(self): index_0_before = self.app.random[1][0] index_1_before = self.app.random[1][1] self.app.random.add_sample(audience_id=1, respondent_id=1) index_0_after = self.app.random[1][0] in...
linuxdeepin/deepin-media-player
src/widget/playlistview.py
Python
gpl-3.0
11,382
0.00541
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2012 ~ 2013 Deepin, Inc. # 2012 ~ 2013 Hailong Qiu # # Author: Hailong Qiu <356752238@qq.com> # Maintainer: Hailong Qiu <356752238@qq.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of ...
, e.x, e.y, e.w, e.h, color_info ) elif e.motion_items == e.item: e.text_color = "#FFFFFF" text_size=9 color_info = [(0, (color, 0.2)), (1, (color, 0.2))
] draw_vlinear(e.cr, e.x, e.y, e.w, e.h, color_info ) else: e.text_color = "#FFFFFF" text_size=9 # text = e.text.decode("utf-8") one_width = self.list_view.columns[0].width ...
Data2Semantics/linkitup
linkitup/linkedlifedata/plugin.py
Python
mit
2,673
0.014964
''' Created on 26 Mar 2013 @author: hoekstra ''' from flask.ext.login import login_required import requests from linkitup import app from linkitup.util.baseplugin import plugin from linkitup.util.provenance import provenance LLD_AUTOCOMPLETE_URL = "http://linkedlifedata.com/autocomplete.json" @app.route('/linke...
match_uri = h['uri']['namespace'] + h['uri']['localName'] web_uri = match_uri display_uri = h['label'] id_base = h['uri']['localName']
if 'types' in h: if len(h['types']) > 0 : types = ", ".join(h['types']) else : types = None elif 'type' in h: types = h['type'] else : types = None ...
onshape-public/onshape-clients
python/onshape_client/oas/models/btp_conversion_function1362.py
Python
mit
14,003
0.000428
# coding: utf-8 """ Onshape REST API The Onshape REST API consumed by all clients. # noqa: E501 The version of the OpenAPI document: 1.113 Contact: api-support@onshape.zendesk.com Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import re # noqa: F401 im...
n1362(ModelComposed): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a d...
is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_...
bgribble/mfp
mfp/builtins/oscutils.py
Python
gpl-2.0
3,258
0.012277
#! /usr/bin/env python ''' oscutils.py -- Open Sound Control builtins for MFP Copyright (c) 2013 Bill Gribble <grib@billgribble.com> ''' from ..processor import Processor from ..mfp_app import MFPApp from ..bang import Uninit class OSCPacket(object): def __init__(self, payload): self.payload = payloa...
def trigger(self): if self.inlets[2] is not Uninit: self.path = self.inlets[2] self.inlets[2] = Uninit if self.inlets[1] is not
Uninit: if isinstance(self.inlets[1], str): parts = self.inlets[1].split(":") self.host = parts[0] if len(parts) > 1: self.port = int(parts[1]) elif isinstance(self.inlets[1], (float, int)): self.port = int(self...
andreaso/ansible
lib/ansible/modules/database/mysql/mysql_replication.py
Python
gpl-3.0
13,039
0.001534
#!/usr/bin/python # -*- coding: utf-8 -*- """ Ansible module to manage mysql replication (c) 2013, Balazs Pocze <banyek@gawker.com> Certain parts are taken from Mark Theunissen's mysqldb module This file is part of Ansible Ansible is free software: you can redistribute it and/or modify it under the terms of the GNU...
t24 import get_exception def get_master_status(cursor): cursor.execute("SHOW MASTER STATUS") mast
erstatus = cursor.fetchone() return masterstatus def get_slave_status(cursor): cursor.execute("SHOW SLAVE STATUS") slavestatus = cursor.fetchone() return slavestatus def stop_slave(cursor): try: cursor.execute("STOP SLAVE") stopped = True except: stopped = False r...
castelao/CoTeDe
tests/fuzzy/test_fuzzyfy.py
Python
bsd-3-clause
2,666
0.001125
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ """ import numpy as np from numpy.testing import assert_allclose from cotede.fuzzy import fuzzyfy CFG = { "output": { "low": {"type": "trimf", "params": [0.0, 0.225, 0.45]}, "medium": {"type": "trimf", "...
um": {"type": "trapmf", "params": [0.07, 0.2, 2, 6]}, "high": {"type": "smf", "params": [2, 6]}, }, "f2": { "weight": 1, "low": {"type": "zmf", "params": [3, 4]}, "medium": {"type": "trapmf", "params": [3, 4, 5, 6]}, "high": {"type": "smf", "pa...
1.5]}, "medium": {"type": "trapmf", "params": [0.5, 1.5, 3, 4]}, "high": {"type": "smf", "params": [3, 4]}, }, }, } def test_fuzzyfy(): features = {"f1": np.array([1.0]), "f2": np.array([5.2]), "f3": np.array([0.9])} rules = fuzzyfy(features, **CFG) assert_allclose(ru...
jacobajit/ion
intranet/apps/feedback/models.py
Python
gpl-2.0
374
0
# -*- coding: utf-8 -*- from django.db import models from ..users.models import User class Feedb
ack(models.Model): user = models.ForeignKey(User) comments = models.CharField(max_length=50000) date = models.DateTimeField(auto_now=True) class Meta: ordering = ["-date"] def __str__(self): return "{} - {}".format(self.user, s
elf.date)
swiftstack/swift
test/unit/account/test_server.py
Python
apache-2.0
135,836
0
# Copyright (c) 2010-2012 OpenStack Foundation # # 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 agree...
f.logger) self.ts = make_timestamp_iter() def tearDown(self): """Tear down for testing swift.account.server.AccountController""" try: rmtree(self.testdir_base) except OSError as err: if err.errno != errno.ENOENT: raise def test_init(self)...
'devices': self.testdir, 'mount_check': 'false', } AccountController(conf, logger=self.logger) self.assertEqual(self.logger.get_lines_for_level('warning'), []) conf['auto_create_account_prefix'] = '-' AccountController(conf, logger=self.logger) self....
harej/requestoid
authentication.py
Python
mit
819
0
from . import config from django.shortcuts import render from mwoauth import ConsumerToken, Handshaker, tokens def requests_handshaker(): consumer_key = config.OAUTH_CONSUMER_KEY consumer_secret = config.OAUTH_CONSUMER_SECRET consumer_token = ConsumerToken(consumer_key, consumer_secret) return Handsha...
consumer_token) def get_username(request): handshaker = requests_handshaker() if 'access_token_key' in request.session: access_key = request.session['access_token_key'].encode('utf-8
') access_secret = request.session['access_token_secret'].encode('utf-8') access_token = tokens.AccessToken(key=access_key, secret=access_secret) return handshaker.identify(access_token)['username'] else: return None
TrampolineRTOS/trampoline
goil/build/libpm/python-makefiles/default_build_options.py
Python
gpl-2.0
3,374
0.02786
#!/usr/bin/python # -*- coding: utf-8 -*- #----------------------------------------------------------------------------------------------------------------------* # # Options for all compilers # #----------------------------------------------------------------------------------------------------------------------*...
formOptions return result #----------------------------------------------------------------------------------------------------------------------* # # Objective C+
+ compiler options # #----------------------------------------------------------------------------------------------------------------------* def ObjectiveCpp_CompilerOptions (platformOptions): result = platformOptions return result #--------------------------------------------------------------------------------...