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
quecolectivo/server
djangoserver/quecolectivo/api/admin.py
Python
gpl-3.0
211
0.009479
from django.con
trib.gis import admin from .models import Line, Point, Polygon, Roads @admin.register(Line, Point, Polygon, Roads) class OSMAdmin(admin.OSMGeoAdmin): fields = ('wa
y', 'osm_id', 'ref', 'name')
VeeSot/blog
auth/views.py
Python
gpl-2.0
2,792
0.0015
import asjson from flask.views import MethodView from functools import wraps from flask.ext.mongoengine.wtf import model_form from flask import request, render_template, Blueprint, redirect, abort, session, make_response from .models import User, SessionStorage from mongoengine import DoesNotExist auth = Blueprint('au...
ser = username record.session_key = session_id record.save() # And redirect to admin-panel return response else: raise DoesNotExist except DoesNotExist: return abort(401) ...
правлять могут в виде атрибута заголовков cookies = request.cookies if not cookies: # Ничего не нашли на первой иттерации.Попробуем вытащить из заголовка try: cookies = asjson.loads(request.headers['Set-Cookie']) except KeyError: pass if ...
raeeschachar/edx-e2e-mirror
regression/pages/studio/studio_home.py
Python
agpl-3.0
2,009
0
""" Dashboard page for Studio """ from edxapp_acceptance.pages.studio.index import DashboardPage from bok_choy.promise import BrokenPromise from regression.pages.studio import BASE_URL from regression.pages.lms import BASE_URL_LMS class DashboardPageExtended(DashboardPage): """ This class is an extended class...
on """
course_names = self.q(css='.course-link h3') for vals in course_names: if course_title in vals.text: vals.click() return raise BrokenPromise('Course title not found') def click_logout_button(self): """ Clicks username drop down than l...
dhp-denero/LibrERP
report_aeroo_ooo/installer.py
Python
agpl-3.0
6,702
0.008207
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (c) 2008-2012 Alistek Ltd (http://www.alistek.com) All Rights Reserved. # General contacts <[email protected]> # # WARNING: This program as such is intended to be used by professional...
a def check(self, cr, uid, ids, context=None): config_obj = self.pool.get('oo.config') data = self.read(cr, uid, ids, ['host','port','ooo_restart_cmd'])[0] del data['id'] config_id = config_obj.search(cr, 1, [], context=context) if config_id: config_obj.write(cr,...
st_temp.odt', mode='rb') file_data = fp.read() DC = netsvc.Service._services.setdefault('openoffice', \ OpenOffice_service(cr, data['host'], data['port'])) with aeroo_lock: DC.putDocument(file_data) DC.saveByStream() ...
github/codeql
python/ql/test/query-tests/Classes/overwriting-attribute/overwriting_attribute.py
Python
mit
451
0.015521
#Attribute set in both superclass and subclass class C(object): def __init__(self): self.var = 0 cla
ss D(C): def __init__(self): self.var = 1 # self.var will be overwritten C.__init__(self) #Attribute set in both superclass and subclass
class E(object): def __init__(self): self.var = 0 # self.var will be overwritten class F(E): def __init__(self): E.__init__(self) self.var = 1
b0nk/botxxy
src/tpb.py
Python
gpl-2.0
241
0.016598
import feedparser def getLatest(): feed = feedparser.parse("http://
rss.thepiratebay.se/0") title = feed['entries'][0]['title'] link = feed['entries'][0]['comments']
.replace('http://', 'https://') return "%s - %s" % (title, link)
MiracleWong/PythonBasic
PythonExcel/testExcel.py
Python
mit
471
0.012739
#!/usr/bin/python #-*- co
ding: utf-8 -*- from xlrd import open_workbook x_data1=[] y_data1=[] wb = open_workbook('phase_detector.xlsx') for s in wb.sheets(): print 'Sheet:',s.name for row in range(s.nrows): print 'the row is:',row+1 values = [] for col in range(s.ncols): values.append(s.cell(row,col)...
) print x_data1 print y_data1
MilkyWeb/dyndns
install.py
Python
mit
881
0.010216
#!/usr/bin/python3 import sys import os def printUsage(): sys.exit('Usage: %s server|client' % sys.argv[0]) if ((len(sys.argv)!=2) or (sys.argv[1] != 'client') and (sys.argv[1] != 'server')): printUsage() print("Generating daemon script\n") fileContents = open('dyndns.sh').read( os.path.getsize('dyndns.sh') ) fi...
) fileContents = fileCo
ntents.replace('{VERSION}', sys.argv[1]) fileContents = fileContents.replace('{USER}', os.getlogin()) print("Writing daemon script in /etc/init.d\n") daemonPath = '/etc/init.d/dyndns' daemon = open(daemonPath, 'w') daemon.write(fileContents) daemon.close() print('Changing permissions\n') os.chmod(daemonPath, 0o755) ...
leprikon-cz/leprikon
leprikon/views/journals.py
Python
bsd-3-clause
5,762
0.001736
from django.http import Http404 from django.shortcuts import get_object_or_404 from django.urls.base import reverse_lazy as reverse from django.utils.translation import ugettext_lazy as _ from ..forms.journals import JournalEntryForm, JournalForm, JournalLeaderEntryForm from ..models.journals import Journal, JournalEn...
journal_form.html" title = _("Change journal") class JournalDeleteView(DeleteView): model = Journal title = _("Delete journal") message = _("Journal has been deleted.") def get_queryset(self): qs = super().get_queryset()
if not self.request.user.is_staff: qs = qs.filter(subject__leaders=self.request.leader) return qs def get_object(self): obj = super().get_object() if obj.all_journal_entries: raise Http404() return obj def get_question(self): return _("Do...
shrekshao/Polyhedron3D
assets/models/test/txt2json_parser.py
Python
mit
8,122
0.006156
import json from sets import Set from sys import maxint import math # tmp hacky functions for vec3 def norm2 (a): return dot(a, a) def dot ( a, b ): return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] def area (a, b, c): u = [ b[0] - a[0], b[1] - a[1], b[2] - a[2] ] v = [ c[0] - a[0], c[1] - a[1], c[2] -...
(self, filename_edge_vertex, filename_edge_to_force_face, filename_edge_ex): f_edge_vertex = open(filename_edge_vertex) edges = self.diagramJson.json['form']['edges'] for line
in f_edge_vertex: edge = line.strip().split('\t') e = edges[edge[0]] = {} e['vertex'] = edge[1:] # e['external'] = False # print edge[0], e['vertex'] # print edges f_edge_vertex.close() v2fa = self.diagramJson.json['form']['v...
ssinger/skytools-cvs
python/setadm.py
Python
isc
159
0.012579
#! /usr/bin/env python import sys, pgq.setadmin if __name__ == '__main__': script = pgq.setadmin.SetAdmin('set_admi
n', sys.argv[1:]) script.
start()
wheldom01/privacyidea
privacyidea/lib/auth.py
Python
agpl-3.0
4,375
0
# -*- coding: utf-8 -*- # # 2015-11-03 Cornelius Kölbel <[email protected]> # Add check if an admin user exists # 2014-12-15 Cornelius Kölbel, [email protected] # Initial creation # # (c) Cornelius Kölbel # Info: http://www.privacyidea.org # # This code is free software; you can redistr...
eck the password of the user against the userstore if user_obj.check_password(password): user_auth = True # If the realm is in the SUPERUSER_REALM then the authorization rol
e # is risen to "admin". if user_obj.realm in superuser_realms: role = ROLE.ADMIN return user_auth, role, details
TAXIIProject/django-taxii-services
tests/test_query_handler.py
Python
bsd-3-clause
3,576
0.003356
# Copyright (c) 2014, The MITRE Corporation. All rights reserved. # For license information, see the LICENSE.txt file from __future__ import absolute_import from django.conf import settings from django.test import Client, TestCase class TETestObj(object): def __init__(self, target, expected_stubs, expected_oper...
= TETestObj(target='STIX_Package/STIX_Header/Handling/Marking/Marking_Structure/Terms_Of_Use', expected_stubs=[ '/stix:STIX_Package/stix:STIX_Header/stix:Handling/marking:Marking/marking:Marking_Structure/' 'terms:Terms_Of_Use', ...
, ]) l_wc_002 = TETestObj(target='*/STIX_Header/Title', expected_stubs=['/*/stix:STIX_Header/stix:Title', ]) l_wc_003 = TETestObj(target='**/@cybox_major_version', expected_stubs=['//@cybox_major_version',]) m_wc_001 = TETestObj(target='STIX_Package/*/Title', ...
rcgee/oq-hazardlib
openquake/hazardlib/gsim/akkar_bommer_2010.py
Python
agpl-3.0
21,696
0.003134
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2012-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the Licen...
d in table 1, p. 200. """ stddevs = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL: stddevs.append(C['SigmaTot'] + np.zeros(num_sites)) elif stddev_type =...
zeros(num_sites)) elif stddev_type == const.StdDev.INTER_EVENT: stddevs.append(C['tau'] + np.zeros(num_sites)) return stddevs def _compute_magnitude(self, rup, C): """ Compute the first term of the equation described on p. 199: ``b1 + b2 * M + b3 * M**2`...
robrocker7/h1z1map
server/players/migrations/0002_player_last_updated.py
Python
apache-2.0
442
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('
players', '0001_initial'), ] operations = [ migrations.AddField( model_name='player', name='last_updated', field=models.DateTimeField(null=True, blank=True),
preserve_default=True, ), ]
Snergster/virl-salt
openstack/nova/files/mitaka/nova+network+neutronv2+api.py
Python
gpl-2.0
90,885
0.000275
# Copyright 2012 OpenStack Foundation # All Rights Reserved # Copyright (c) 2012 NEC Corporation # # 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/lic...
ions for a few common ones plugins = ['password', 'v2password', 'v3password'] for name in plugins: plugin = ks_loading.get_plugin_loader(name)
for plugin_option in ks_loading.get_auth_plugin_conf_options(plugin): for option in opts: if option.name == plugin_option.name: break else: opts.append(plugin_option) opts.sort(key=lambda x: x.name) return [(NEUTRON_GROUP, opts)] def...
JarnoRFB/qtpyvis
qtgui/panels/__init__.py
Python
mit
122
0
from .activation
s import ActivationsPanel from .experiments import ExperimentsPanel from .occlusio
n import OcclusionPanel
chimkentec/KodiMODo_rep
script.module.libtorrent/python_libtorrent/python_libtorrent/functions.py
Python
gpl-3.0
5,308
0.008855
#-*- coding: utf-8 -*- ''' python-libtorrent for Kodi (script.module.libtorrent) Copyright (C) 2015-2016 DiMartino, srg70, RussakHH, aisman 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 t...
elf.dest_path, 'libtorrent.so'), dest) return True def android_workaround(self, new_dest_path): for libname in get_libname(self.platform): libpath=os.path.join(self.dest_path, libname) size=str(os.path.getsize(libpath)) new_libpath=os.path.join(new_dest_path, lib...
if not xbmcvfs.exists(new_libpath): xbmcvfs.copy(libpath, new_libpath) log('Copied %s -> %s' %(libpath, new_libpath)) else: new_size=str(os.path.getsize(new_libpath)) if size!=new_size: xbmcvfs.delete(new_libpath) ...
varenius/salsa
USRP/usrp_gnuradio_dev/plot_array_file.py
Python
mit
2,472
0.016181
import matplotlib.pyplot as plt import numpy as np import sys import time import scipy.signal as sig infile = sys.argv[1] indata = np.load(infile) spec = indata[0] samp_rate = indata[1] fftsize = indata[2] center_freq = indata[3] # MHz halffft = int(0.5*fftsize) freqs = 0.5*samp_rate*np.array(range(-halffft,halffft)...
.4-2, 0.01], [1425, 0.01], [1424.4-1.8, 0.01], [1424.4+0.5845, 0.01], [1424.4+0.483, 0.005],
] flags = [] #plt.plot(spec) for item in RFI: RFI_freq = item[0] RFI_width = item[1] ch0_freq = center_freq - 0.5*samp_rate ind_low = int(np.floor((RFI_freq-0.5*RFI_width - ch0_freq)/delta_nu)) ind_high = int(np.ceil((RFI_freq+0.5*RFI_width - ch0_freq)/delta_nu)) if ind_low>0 and ind_high<len...
Spiderlover/Toontown
otp/distributed/OtpDoGlobals.py
Python
mit
3,475
0.000288
from direct.distributed.MsgTypes import * OTP_DO_ID_SERVER_ROOT = 4007 OTP_DO_ID_FRIEND_MANAGER = 4501 OTP_DO_ID_LEADERBOARD_MANAGER = 4502 OTP_DO_ID_SERVER = 4600 OTP_DO_ID_UBER_DOG = 4601 OTP_CHANNEL_AI_AND_UD_BROADCAST = 4602 OTP_CHANNEL_UD_BROADCAST = 4603 OTP_CHANNEL_AI_BROADCAST = 4604 OTP_NET_MSGR_CHANNEL_ID_ALL...
96 OTP_DO_ID_TOONTOWN_NON_REPEATABLE_RANDOM_SOURCE = 4697 OTP_DO_ID_AI_TRADE_AVATAR = 4698 OTP_DO_ID_TOONTOWN_WHITELIST_MANAGER = 4699 OTP_DO_ID_PIRATES_MATCH_MAKER = 4700 OTP_DO_ID_PIRATES_GUILD_MANAGER = 4701 OTP_DO_ID_PIRATES_AWARD_MAKER = 4702 OTP_DO_ID_PIRATES_CODE_REDEMPTION = 4703 OTP_DO_ID_PIRATES_SETTINGS_MANA...
705 OTP_DO_ID_PIRATES_CREW_MATCH_MANAGER = 4706 OTP_DO_ID_PIRATES_AVATAR_ACCESSORIES_MANAGER = 4710 OTP_DO_ID_TOONTOWN_CPU_INFO_MANAGER = 4713 OTP_DO_ID_TOONTOWN_SECURITY_MANAGER = 4714 OTP_DO_ID_SNAPSHOT_DISPATCHER = 4800 OTP_DO_ID_SNAPSHOT_RENDERER = 4801 OTP_DO_ID_SNAPSHOT_RENDERER_01 = 4801 OTP_DO_ID_SNAPSHOT_RENDE...
hkociemba/RubiksCube-TwophaseSolver
package_src/twophase/client_gui2.py
Python
gpl-3.0
12,351
0.00421
# ################ A simple graphical interface which communicates with the server ##################################### # While client_gui only allows to set the facelets with the mouse, this file (client_gui2) also takes input from the # webcam and includes sliders for some opencv parameters. from tkinter import * ...
############## # ######################################### functions to set the slider values ######################################### def set_rgb_L(val): vision_params.rgb_L = int(val) def set_orange_L(val): vision_params.orange_L = int(val) def set_orange_H(val): vision_params.orange_H = int(val) ...
arams.blue_H = int(val) def set_sat_W(val): vision_params.sat_W = int(val) def set_val_W(val): vision_params.val_W = int(val) def set_sigma_C(val): vision_params.sigma_C = int(val) def set_delta_C(val): vision_params.delta_C = int(val) def transfer(): """Transfer the facelet colors detecte...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractDreamstlTumblrCom.py
Python
bsd-3-clause
761
0.027595
def extractDreamstlTumblrCom(item): ''' Parser for 'dreamstl.tumblr.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('the s ranks that i raised', 'The S-Ranks that I Raised', ...
, ('the s ranks that i\'ve raised', 'The S-Ranks that I Raised', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return b
uildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
mbourqui/django-publications-bootstrap
publications_bootstrap/admin/__init__.py
Python
mit
358
0
# -
*- coding: utf-8 -*- from django.contrib import admin from .catalogadmin import CatalogAdmin from .publicationadmin import PublicationAdmin from .typeadmin import TypeAdmin from ..models import Type, Catalog, Publication admin.site.register(Type, T
ypeAdmin) admin.site.register(Catalog, CatalogAdmin) admin.site.register(Publication, PublicationAdmin)
bitmovin/bitcodin-python
bitcodin/test/input/testcase_get_non_existent_input.py
Python
unlicense
614
0
__author__ = 'Dominic Miglar <[email protected]>' import unittest from bitcodin import get_input
from bitcodin.exceptions import BitcodinNotFoundError from bitcodin.test.bitcodin_test_case import BitcodinTestCase class GetNonExistentInputTestCase(BitcodinTestCase): def setUp(self): super(GetNonExistentInputTestCase, self).setUp() def runTest(self): with self.assertRaises(BitcodinNotFound...
nExistentInputTestCase, self).tearDown() if __name__ == '__main__': unittest.main()
olympiag3/olypy
tests/unit/test_olymap_item.py
Python
apache-2.0
5,307
0.000942
import olymap.item def test_get_animal(): tests = ( ({}, None), ({'IT': {'an': ['1']}}, True)
, ({'IT': {'an': ['0']}}, None), ({'IT': {'de': ['1']}}, None), ({'IM': {'an':
['1']}}, None), ) for box, answer in tests: assert olymap.item.get_animal(box) == answer def test_get_attack_bonus(): tests = ( ({}, 0), ({'IM': {'ab': ['60']}}, 60), ({'IM': {'ab': ['0']}}, 0), ({'IM': {'de': ['60']}}, 0), ({'IT': {'ab': ['60']}}, 0), ...
ooici/eeagent
eeagent/eeagent_exceptions.py
Python
apache-2.0
337
0.002967
# Copyright 2013 University of Chicago class EEAgentParameterException(Exception
): def __init__(self, message): Exception.__init__(self, message) class EEAgentUnauthorizedException(Exception): pass class EEAgentSupDException(Exception): def __init__(self, message):
Exception.__init__(self, message)
gangadhar-kadam/verve_live_frappe
frappe/model/base_document.py
Python
mit
15,292
0.029362
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe, json, sys from frappe import _ from frappe.utils import cint, flt, now, cstr, strip_html from frappe.model import default_fields from frappe.model.naming import set...
values = "
, ".join(["%s"] * len(columns)) ), d.values()) except Exception, e: if e.args[0]==1062: if self.meta.autoname=="hash": self.name = None self.db_insert() return type, value, traceback = sys.exc_info() frappe.msgprint(_("Duplicate name {0} {1}").format(self.doctype, self.name)) rai...
ljx0305/ice
python/test/Ice/facets/TestI.py
Python
gpl-2.0
1,190
0.006723
# ********************************************************************** # # Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # ***********************************************************...
I): def callD(self, current=None): return "D" class EI(Test.E): def callE(self, current=None): return "E" class FI(Test.F, EI): def callF(self, current=None): return "F" class GI(Test.G): def __init__(self, communicator): self._communicator = communicator def shut...
GI.__init__(self, communicator) def callH(self, current=None): return "H"
mfraezz/osf.io
website/project/views/register.py
Python
apache-2.0
10,365
0.002605
# -*- coding: utf-8 -*- from rest_framework import status as http_status import itertools from flask import request from framework import status from framework.exceptions import HTTPError from framework.flask import redirect # VOL-aware redirect from framework.auth.decorators import must_be_signed from website.arc...
ret = _view_project(node, auth, primary=True) my_meta = serialize_meta_schema(meta_schema) if has_anonymous_link(node, auth): for indx, schema_page in enumerate(my_meta['schema']['pages']): for idx, schema_question in enumerate(schema_page['questions']):
if schema_question['title'] in settings.ANONYMIZED_TITLES: del my_meta['schema']['pages'][indx]['questions'][idx] ret['node']['registered_schema'] = serialize_meta_schema(meta_schema) return ret else: status.push_status_message( 'You have been redir...
GreenBlast/Linger
LingerActions/StopProcessAndChildrenAction.py
Python
mit
1,242
0.005636
import LingerActions.LingerBaseAction as lingerActions class StopProcessAndChildrenAction(lingerActions.LingerBaseAction): """Logging that there was a change in a file"
"" def __init__(self, configuration): super(StopProcessAndChildrenAction, self).__init__(configuration) # Fields self.process_adapter = self.configuration['process_adapter'] def get_process_adapter(self): return self.get_adapter_by_uuid(self.process_adapter) def ac...
.get_process_adapter().stop_with_all_children() class StopProcessAndChildrenActionFactory(lingerActions.LingerBaseActionFactory): """StopProcessAndChildrenActionFactory generates StopProcessAndChildrenAction instances""" def __init__(self): super(StopProcessAndChildrenActionFactory, self).__init__() ...
protochron/aurora
src/main/python/apache/thermos/cli/commands/status.py
Python
apache-2.0
4,163
0.010569
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under ...
VALUES_TO_NAMES.get(last_run.state, 'Unknown'))) print() matchers = map(re.compile, args or ['.*']) active = [] finished = [] for root in path_detector.get_paths(): detector = TaskDetector(root) active.extend((detector, t_id) for _, t_id in detector.get_task_ids(state='active') if any(p...
shed') if any(pattern.match(t_id) for pattern in matchers)) found = False if options.only is None or options.only == 'active': if active: print('Active tasks:') found = True for detector, task_id in active: format_task(detector, task_id) print() if options.only is Non...
IronLanguages/ironpython3
Tests/compat/sbs_simple_ops.py
Python
apache-2.0
17,059
0.013424
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the Apache 2.0 License. # See the LICENSE file in the project root for more information. from common import * import testdata class oldstyle: def __init__(self, value): self.value = valu...
her def __imod__(self, other): return self.value % other def __idivmod__(self, other): return divmod(self.value, other) def __ipow__(self, other): return self.value ** other def __ilshift__(self, other): return self.value << other def __irshift__(self, other): r...
def __iand__(self, other): return self.value & other def __ixor__(self, other): return self.value ^ other def __ior__(self, other): return self.value | other class newstyle_notdefined(object): def __init__(self, value): self.value = value def __repr__(self): ...
tooringanalytics/pyambiguity
m2py.py
Python
mit
1,433
0.001396
#!/usr/bin/env python ''' Debug & Test support for matplot to python conversion. ''' import os import numpy as np from scipy.io import loadmat def dmpdat(s, e): """ Dump a data structure with its name & shape. Params: ------- s: str. The name of the structure e: expression. An expression to dump. ...
thon_err', e) np.savetxt(os.path.join("check_d
ata", t, s) + '_matlab_err', mat) print("FAILED check on expr: %s, signal: %s" % (s, t)) #hbrk() return is_equal
antoinecarme/pyaf
tests/model_control/detailed/transf_RelativeDifference/model_control_one_enabled_RelativeDifference_PolyTrend_Seasonal_Minute_ARX.py
Python
bsd-3-clause
167
0.047904
import tests.model_control.test_ozone_custom
_models_enabled as testmod testmod.build_model( ['RelativeDifference'] , ['PolyTrend'] , ['Seasonal_Minute'] , ['ARX
'] );
edmorley/django
tests/admin_widgets/test_autocomplete_widget.py
Python
bsd-3-clause
5,005
0.000999
from django import forms from django.contrib.admin.widgets import AutocompleteSelect from django.forms import ModelChoiceField from django.test import TestCase, override_settings from django.utils import translation from .models import Album, Band class AlbumForm(forms.ModelForm
): class Meta: model = Album fields = ['band', 'featuring'] widgets = { 'band': AutocompleteSelect( Album._meta.get_field('band').remote_field,
attrs={'class': 'my-class'}, ), 'featuring': AutocompleteSelect( Album._meta.get_field('featuring').remote_field, ) } class NotRequiredBandForm(forms.Form): band = ModelChoiceField( queryset=Album.objects.all(), widget=Aut...
Andrew-Dickinson/FantasyFRC
customMechanize/_googleappengine.py
Python
gpl-2.0
26,831
0.001565
"""HTTP related handlers. Note that some other HTTP handlers live in more specific modules: _auth.py, _gzip.py, etc. Copyright 2002-2006 John J Lee <[email protected]> This code is free software; you can redistribute it and/or modify it under the terms of the BSD or ZPL 2.
1 licenses (see the file COPYING.txt included with the distribution). """ import time, htmlentitydefs, logging, \ fakesocket, urllib2, urllib, httplib, sgmllib from urllib2 import URLError, HTTPError, BaseHandler from cStri
ngIO import StringIO from _clientcookie import CookieJar from _headersutil import is_html from _html import unescape, unescape_charref from _request import Request from _response import closeable_response, response_seek_wrapper import _rfc3986 import _sockettimeout debug = logging.getLogger("mechanize").debug debug_r...
JunctionAt/JunctionWWW
config/badges.py
Python
agpl-3.0
862
0
BADGES = [ { 'badge_id': 'tech', 'img_pa
th': '/static/img/badges/wrench.svg',
'name': 'Junction Technical Staff', 'description': 'Actively serves on Junction staff', 'priority': 2000 }, { 'badge_id': 'staff', 'img_path': '/static/img/badges/award_fill.svg', 'name': 'Junction Staff', 'description': 'Actively serves on Junction staff'...
AustereCuriosity/astropy
astropy/samp/web_profile.py
Python
bsd-3-clause
5,804
0.000689
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from ..extern.six.moves.urllib.parse import parse_qs from ..extern.six.moves.urllib.request import urlopen from ..extern.six.moves import input f...
self.send_header('Access-Control-Allow-Credentials', 'true') else: # Simple method self.send_header('Access-Control-Allow-Origin', self.headers.get('Origin')) self.send_header('Access-Control-Allow-Headers', 'Content-Type') ...
jokajak/itweb
data/env/lib/python2.6/site-packages/repoze.who_testutil-1.0.1-py2.6.egg/tests/fixture/__init__.py
Python
gpl-3.0
729
0.001372
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2009, Gustavo Narea <[email protected]>. # All Rights Reserved. # # This software is subject to the provisions of the BSD-like license at # http://www.repoze.org/LICENSE.txt. A copy of t
he license should accompany # this distribution. THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL # EXPRESS OR IMPLIED WARRANTIES AR
E DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND # FITNESS FOR A PARTICULAR PURPOSE. # ############################################################################## """Fixture collection for the test suite."""
claudiob/pypeton
pypeton/files/django/deploy/django_wsgi_production.py
Python
mit
344
0.026163
import os, sys PATH = os.path.join(os.path.dirname(__file__), '..') sys.path += [ os.path.join(PATH, 'project/apps'), os.path.join(PATH, 'project'), os.path.join(PATH, '..'), PATH] os.envir
on['DJANGO_SETTINGS_MODULE'] = 'project.settings.production' import dj
ango.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler()
jtraver/dev
python3/globals/test1.py
Python
mit
308
0.003247
#!/usr/bin/env python3 from framework import do_exit, get_globals, main def do_work(): glo
bal g_test_import global globals1 print("do_work") globals1 = get_globals() g_test_import = globals1["g_test_import"] print("do_work: g_test_import
= %s" % str(g_test_import)) main(do_work)
jithinbp/SEELablet
SEEL/SENSORS/SHT21.py
Python
gpl-3.0
2,349
0.063857
from __future__ import print_function from numpy import int16 import time def connect(route,**args): ''' route can either be I.I2C , or a radioLink instance ''' return SHT21(route,**args) class SHT21(): RESET = 0xFE TEMP_ADDRESS = 0xF3 HUMIDITY_ADDRESS = 0xF5 selected=0xF3 NUMPLOTS=1 PLOTNAMES = ['Data'] ...
mperature' def __init__(self,I2C,**args): self.I2C=I2C self.ADDRESS = args.get('address',self.ADDRESS) self.name = 'Humidity/Temperature' ''' try: print ('switching baud to 400k') self.I2C.configI2C(400e3) except: print ('FAILED TO CHANGE BAUD RATE') ''' self.params={'selectParameter':['temper...
,'humidity']} self.init('') def init(self,x): self.I2C.writeBulk(self.ADDRESS,[self.RESET]) #soft reset time.sleep(0.1) def rawToTemp(self,vals): if vals: if len(vals): v = (vals[0]<<8)|(vals[1]&0xFC) #make integer & remove status bits v*=175.72; v/= (1<<16); v-=46.85 return [v] return F...
ruibarreira/linuxtrail
usr/lib/python3/dist-packages/softwareproperties/gtk/DialogAdd.py
Python
gpl-3.0
3,128
0.005754
# dialog_add.py.in - dialog to add a new repository # # Copyright (c) 2004-2005 Canonical # 2005 Michiel Sikkes # # Authors: # Michael Vogt <[email protected]> # Michiel Sikkes <[email protected]> # Sebastian Heinlein <[email protected]> # # This program is free softw...
ering the raw apt line """ self.sourceslist = sourceslist self.parent = parent self.datadir = datadir # gtk stuff setup_ui(self, os.path.join(datadir, "gtkbuilder", "dialog-add.ui
"), domain="software-properties") self.dialog = self.dialog_add_custom self.dialog.set_transient_for(self.parent) self.entry = self.entry_source_line self.button_add = self.button_add_source self.entry.connect("changed", self.check_line) # Create an example deb line from the currently used ...
enthought/etsproxy
enthought/util/equivalence.py
Python
bsd-3-clause
56
0
# proxy
mod
ule from codetools.util.equivalence import *
kvas-it/cli-mock
tests/test_creplay.py
Python
mit
1,051
0
def test_default_log(creplay, testlog): ret = creplay('echo', 'foo', creplay_args=[], cwd=testlog.dirname) assert ret.success assert ret.stdout == 'foo\n' assert ret.stderr == '' def test_echo_n(creplay, logfile): ret = creplay('echo', '-n', 'foo') assert ret.success assert ret.stdout == '...
st_record_replay(crecord, tmpdir, logfile, testlog): ret = crecord('creplay', '-l', testlog.strpath, 'foo') assert ret.success assert ret.stdout == 'foo\nbaz\n' assert ret.stderr == 'bar\n' lines = set(logfile.read().split('\n')[1:-1]) # Unfortunately the order can get messed up. assert line...
foo', '! bar', '> baz', '= 0'}
kasmith/cbmm-project-christmas
ContainmentAnalysis/parseData.py
Python
mit
2,805
0.003565
import os, json iflnm = os.path.join('..','psiturk-rg-cont','trialdata.csv') oflnm = "rawdata.csv" with open(iflnm, 'rU') as ifl, open(oflnm, 'w') as ofl: ofl.write('WID,Condition,Trial,TrialBase,Class,ContainmentType,ContainmentLevel,TrialNum,MotionDirection,Response,RT,Goal,Switched,RawResponse,WasBad\n') f...
lace("\"\"", "\"")) if isinstance(dat[5], bool): trnm, order, rt, rawresp, mottype, wassw, score, realgoal, wasbad, cond = dat trspl = trnm.split('_') dowrite = True trbase = trspl[0] + '_' + trspl[1] tnum = trspl[1] if trspl[0] == 'regular...
conttype = "NA" contlevel = "NA" else: trclass = "contained" conttype = trspl[0] contlevel = trspl[2] if not wassw: wassw = "False" if rawresp == 201: actresp = "R" ...
rusenask/mirage
stubo/__init__.py
Python
gpl-3.0
585
0.005128
""" stubo ~~~~~ Stub-O-Matic - Enable automat
ed testing by mastering system dependencies. Use when reality is simply not good enough. :copyright: (c) 2015 by OpenCredo. :license: GPLv3, see LICENSE for more details. """ import os import sys version = "0.8.3" version_info = tuple(version.split('.')) def stubo_path(): # Find folder that th...
.__file__)) def static_path(*args): return os.path.join(stubo_path(), 'static', *args)
aljungberg/pyle
pyle.py
Python
bsd-3-clause
5,025
0.004776
#!/usr/bin/env python # -*- coding: utf-8 -*- """Pyle makes it easy to use Python as a replacement for command line tools such as `sed` or `perl`. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from future impor...
read') else file) as in_file: for num, line in enumerate(in_file.readlines()):
was_whole_line = False if line[-1] == '\n': was_whole_line = True line = line[:-1] expr = "" try: for expr in expressions: words = [word.strip() ...
jonian/kickoff-player
apis/streams.py
Python
gpl-3.0
6,137
0.017598
from operator import itemgetter from lxml import html from fuzzywuzzy import fuzz from helpers.utils import cached_request, thread_pool, replace_all class StreamsApi: def __init__(self, data, cache): self.data = data self.cache = cache def get(self, url='', ttl=3600): base_url = 'livefootballol.me'...
f, "/channels/")]'): name = link.text_content() name = self.parse_name(name) chann.append(name) if chann: items.append({ 'event': event, 'channels': chann }) except (IndexError, ValueError): pass return items def get_events(self): links = self.get_events_pag...
urn items def save_events(self): fixtures = self.data.load_fixtures(today_only=True) events = self.get_events() items = [] for fixture in fixtures: channels = self.get_fixture_channels(events, fixture) streams = self.data.get_multiple('stream', 'channel', channels) for strea...
quangnguyen-asnet/python-django
mymenu/mymenu/wsgi.py
Python
mit
389
0
""" WSGI config for mymenu project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this f
ile, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.cor
e.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mymenu.settings") application = get_wsgi_application()
jazkarta/edx-platform-for-isc
cms/djangoapps/contentstore/views/item.py
Python
agpl-3.0
49,511
0.003716
"""Views for items (modules).""" from __future__ import absolute_import import hashlib import logging from uuid import uuid4 from datetime import datetime from pytz import UTC import json from collections import OrderedDict from functools import partial from static_replace import replace_static_urls from xmodule_modi...
store.views.helpers import is_unit, xblock_studio_url, xblock_primary_child_category, \ xblock_type_display_name, get_parent_xblock from contentstore.views.preview import get_preview_fragment from edxmako.shortcuts import render_to_string from models.settings.course_gradi
ng import CourseGradingModel from cms.lib.xblock.runtime import handler_url, local_resource_url from opaque_keys.edx.keys import UsageKey, CourseKey from opaque_keys.edx.locator import LibraryUsageLocator from cms.lib.xblock.authoring_mixin import VISIBILITY_VIEW __all__ = [ 'orphan_handler', 'xblock_handler', 'xb...
aragos/tichu-tournament
python/openpyxl/drawing/colors.py
Python
mit
11,201
0.002053
from __future__ import absolute_import # Copyright (c) 2010-2016 openpyxl from openpyxl.compat import basestring, unicode from openpyxl.descriptors.serialisable import Serialisable from openpyxl.descriptors import ( Alias, Typed, Integer, Set, MinMax, ) from openpyxl.descriptors.excel import Perce...
NestedInteger(allow_none=True) greenMod = NestedInteger(allow_none=True) blue = NestedInteger(allow_none=True) blueOff = NestedInteger(allow_none=True) blueMod = NestedInteger(allow_none=True) gamma = Typed(expected_type=Transform, allow_none=True) invGamma = Typed(expected_type=Transform, allow...
val = Set(values=(["bg1", "tx1", "bg2", "tx2", "accent1", "accent2", "accent3", "accent4", "accent5", "accent6", "hlink", "folHlink", "phClr", "dk1", "lt1", "dk2", "lt2", ])) lastClr = Typed(expected_type=RGB, allow_none=True) __elements__ = ('tint', 'shade', 'com...
mylokin/servy
servy/utils/dsntool.py
Python
mit
4,496
0.001779
import collections import re import urlparse class DSN(collections.MutableMapping): ''' Hold the results of a parsed dsn. This is very similar to urlparse.ParseResult tuple. http://docs.python.org/2/library/urlparse.html#results-of-urlparse-and-urlsplit It exposes the following attributes: ...
if url.query: for k, kv in urlparse.parse_qs(url.
query, True, True).iteritems(): if len(kv) > 1: options[k] = kv else: options[k] = kv[0] self.scheme = scheme self.hostname = url.hostname self.path = url.path self.params = url.params self.query = options ...
Yellowen/Sharamaan
bin/bootstrap_creator.py
Python
gpl-2.0
327
0
import virtualenv import textwrap output = virtualenv.create_bo
otstrap_script(textwr
ap.dedent(""" import os, subprocess def after_install(options, home_dir): subprocess.call([join(home_dir, 'bin', 'pip'), 'install', 'ipython', 'django', 'psycopg2']) """)) f = open('bootstrap.py', 'w').write(output)
pschoenfelder/named-dates
tests/test_day_of_nth_weekday.py
Python
mit
2,862
0
import pytest from named_dates.named_dates import\ day_of_nth_weekday, NoNthWeekdayError # For reference throughout these tests, October 1, 2015 is # a Thursday (weekday = 3). def test_weekday_equals_first_of_month(): # Tests that day_of_nth_weekday works when the requested weekday is the # first weekday...
# Tests that day_of_nth_weekday works when the requested weekday is # less than the first weekday of the month. assert day_of_nth_weekday(2015, 10, 1, nth=1) == 6 assert day_of_nth_weekday(2015, 10, 1, nth=2) == 13 assert day_of_nth_weekday(2015, 10, 1, nth=3) == 20 assert day_of_nth_weekday(20...
, 1, nth=4) == 27 with pytest.raises(NoNthWeekdayError): day_of_nth_weekday(2015, 10, 1, nth=5) def test_from_end(): # October 31 is a Saturday (day 5) assert day_of_nth_weekday(2015, 10, 5, nth=1, from_end=True) == 31 assert day_of_nth_weekday(2015, 10, 5, nth=2, from_end=True) == 24 asse...
eduardoedson/scp
usuarios/forms.py
Python
mit
8,823
0
from crispy_forms.helper import FormHelper from crispy_forms.layout import Fieldset, Layout from django import forms from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password from django.core.exceptions impo...
ername=usuario.username, email=usuario.email) u.set_password(self.cleaned_data['password']) u.is_active = True u.groups.add(get_or_create_g
rupo(self.cleaned_data['tipo'].descricao)) u.save() usuario.user = u usuario.save() return usuario class UsuarioEditForm(ModelForm): # Primeiro Telefone primeiro_tipo = forms.ChoiceField( widget=forms.Select(), choices=TIPO_TELEFONE, label=_('Tipo Tele...
asascience-open/chisp1_wps
wps/models.py
Python
gpl-3.0
3,153
0.012369
from django.db import models # Create your models here. class Server(models.Model): # Server title = models.CharField(max_length=1000, help_text="Server Title", blank=False) abstract = models.CharField(max_length=2000, help_text="Server Abstract", blank=True) keywords = models.CharField(max_length=...
fferings for this station through SOS endpoint", blank=True) stream_gauge_parameters = models.CharField(max_length=50000, help_text="Comma separated list of observedProperty parameters for this station through SOS endpoint", blank=True) stream_gauge_x = models.DecimalField(help_text="Longitude or X coodinate", ...
_text="Latitude or Y coordinate", blank=True, max_digits=20, decimal_places=8) def __unicode__(self): return self.stream_gauge_id
ResearchSoftwareInstitute/MyHPOM
hs_modflow_modelinstance/forms.py
Python
bsd-3-clause
27,274
0.003886
from django.forms import ModelForm from django import forms from crispy_forms import layout from crispy_forms.layout import Layout, HTML from hs_core.forms import BaseFormHelper, Helper from hs_core.hydroshare import users from hs_modelinstance.models import ModelOutput, ExecutedBy from hs_modflow_modelinsta...
System: </td><td></td></tr> <tr><td>Url: </td><td></td></tr> </table> </div> """), ) kwargs['element_name_label'] = 'Model Program used for execution' super(ExecutedByFormHelper, self).__init__(allow_edit, res_short_id, element_id
, element_name, layout, *args, **kwargs) class ExecutedByForm(ModelForm): def __init__(self, allow_edit=True, res_short_id=None, element_id=None, *args, **kwargs): super(ExecutedByForm, self).__init__(*args, **kwargs) # set mpshort id to ...
JonasWallin/BayesFlow
examples/article1/article_simulated_estimate_mpi.py
Python
gpl-2.0
8,046
0.048223
''' run with ex: mpiexec -n 10 python article_simulated_estimate_
mpi.py Created on Jul 11, 2014 @author: jonaswallin ''' from __future__ import division import time import scipy.spatial as ss import article_simulatedata from mpi4py import MPI import numpy as np import BayesFlow as bm import matplotlib import matplotlib.pyplot as plt import numpy.random as npr import BayesFlow.plot...
cker as ticker from article_plotfunctions import plotQ_joint, plotQ, plot_theta folderFigs = "/Users/jonaswallin/Dropbox/articles/FlowCap/figs/" sim = 10**2 nCells = 1500 thin = 2 nPers = 80 save_fig = 0 Y = [] #### # COLLECTING THE DATA #### if MPI.COMM_WORLD.Get_rank() == 0: # @UndefinedVariable Y,act_komp, mu...
tst-ahernandez/earthenterprise
earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/common/utils.py
Python
apache-2.0
12,945
0.01151
#!/usr/bin/env python # # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
fo.f_bavail / BYTES_PER_MEGABYTE def Uid(): """Returns a uid for identifying a globe building sequence.""" return "%d_%f" % (os.getpid(), time.time()) def GlobesToText(globes, template, sort_item, reverse=False, is_text=False): """Fills in globe template for each globe and returns as array of strings.""" re...
sort the lower case version of the text. if is_text: items = sorted(globes.iteritems(), key=lambda globe_pair: globe_pair[1][sort_item].lower(), reverse=reverse) # If it is NOT text, use default less than comparison. else: items = sorted(globes.iteritems(), ...
EmreAtes/spack
var/spack/repos/builtin/packages/editres/package.py
Python
lgpl-2.1
1,739
0.000575
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL-CODE-64...
Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Editres(AutotoolsPackage): """Dynamic resource editor for ...
individual/app/editres-1.0.6.tar.gz" version('1.0.6', '310c504347ca499874593ac96e935353') depends_on('libxaw') depends_on('libx11') depends_on('libxt') depends_on('libxmu') depends_on('pkgconfig', type='build') depends_on('util-macros', type='build')
shu-mutou/pecan-swagger
tests/test_utils.py
Python
bsd-3-clause
10,382
0.000096
import unittest from pecan_swagger import utils class TestUtils(unittest.TestCase): def test_swagger_build(self): from .resources import example_app expected = { "swagger": "2.0", "info": { "version": "1.0", "title": "example_app" ...
KARAMATSU', '3.CHOROMATSU', '4.ICH
IMATSU', '5.JUSHIMATSU', '6.TODOMATSU' ], "type": "string" }, "message_size": { "m...
bitmotive/flask-boilerplate
tests/test_basics.py
Python
mit
705
0
import unittest from flask import current_app from app import create_app, db class BasicsTestCase(unittest.Tes
tCase): # Runs before each test def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() # Runs after each test def tearDown(self): db.session.remove() db.drop_all() self....
e sure the app is running with TESTING config def test_app_is_testing(self): self.assertTrue(current_app.config['TESTING'])
ingadhoc/odoo-law-tracking
law_tracking_x/commission_treatment.py
Python
agpl-3.0
4,111
0.006568
# -*- coding: utf-8 -*- #######
####################################################################### # # Law Follow Up # Copyright (C) 2013 Sistemas ADHOC # No email # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Sof...
n the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along wi...
c0710204/edx-platform
lms/envs/test.py
Python
agpl-3.0
12,700
0.002756
""" This config file runs the simplest dev environment using sqlite, and db-based sessions. Assumes structure: /envroot/ /db # This is where it'll write the database file /edx-platform # The location of this repo /log # Where we're going to write log files """ # We intentionally define lot...
(course_dir, COMMON_TEST_DATA_ROOT / course_dir) for course_dir in os.listdir(COMMON_TEST_DATA_ROOT) if os.path.isdir(COMMON_TEST_DATA_ROOT / course_dir) ] # Avoid having to run collectstatic before the unit test suite # If we don't add these settings, then Django templates that can't # find pipelined assets w...
Error. # http://stackoverflow.com/questions/12816941/unit-testing-with-django-pipeline STATICFILES_STORAGE='pipeline.storage.NonPackagingPipelineStorage' PIPELINE_ENABLED=False update_module_store_settings( MODULESTORE, module_store_options={ 'fs_root': TEST_ROOT / "data", }, xml_store_options=...
Mercy-Nekesa/sokoapp
sokoapp/utils/admin.py
Python
mit
1,954
0.006141
from django.contrib import admin from django.contrib.contenttypes import generic from models import Attribute, BaseModel from django.utils.translation import ugettext_lazy as _ class MetaInline(generic.GenericTabularInline): model = Attribute extra = 0 class BaseAdmin(admin.ModelAdmin): """ def get_re...
ieldsets(request, obj) fs[0][1]['fields'].remove('created_by') fs[0][1]['fields'].remove('last_updated_by') fs.ext
end([(_('Other informations'), {'fields':['created_by','last_updated_by'], 'classes':['collapse']})]) return fs def changelist_view(self, request, extra_context=None): if request.user.has_perm('%s.can_view_deleted' % self.model._meta.app_label): if not "deleted_flag" in self.list_filter...
waseem18/oh-mainline
vendor/packages/Django/tests/regressiontests/settings_tests/tests.py
Python
agpl-3.0
12,386
0.00113
import os import warnings from django.conf import settings, global_settings from django.core.exceptions import ImproperlyConfigured from django.http import HttpRequest from django.test import SimpleTestCase, TransactionTestCase, TestCase, signals from django.test.utils import override_settings from django.utils import...
self.assertEqual('http://static.foo.com/', self.settings_module.STATIC_URL) def test_no_end_slash(self): """ An ImproperlyConfigured exception is raised if the value doesn't end in a slash. """ with self.assertRaises(ImproperlyConfigured): ...
with self.assertRaises(ImproperlyConfigured): self.settings_module.MEDIA_URL = 'http://media.foo.com' with self.assertRaises(ImproperlyConfigured): self.settings_module.STATIC_URL = '/foo' with self.assertRaises(ImproperlyConfigured):
ICShapy/shapy
shapy/scene.py
Python
mit
5,133
0.011884
# This file is part of the Shapy Project. # Licensing information can be found in the LICENSE file. # (C) 2015 The Shapy Team. All rights reserved. import StringIO from pyrr.objects import Quaternion, Matrix44, Vector3, Vector4 class Scene(object): """Class representing a whole scene.""" class Object(object): ...
= obj.edges[abs(v[0])] e1 = obj.edges[abs(v[1])] e2 = obj.edges[abs(v[2])] v0 = obj.verts[e0[0] if v[0] >= 0 else e0[1]] v1 = obj.verts[e1[0] if v[1] >= 0 else e1[1]]
v2 = obj.verts[e2[0] if v[2] >= 0 else e2[1]] v0 = obj.model * Vector4([v0[0], v0[1], v0[2], 1.0]) v1 = obj.model * Vector4([v1[0], v1[1], v1[2], 1.0]) v2 = obj.model * Vector4([v2[0], v2[1], v2[2], 1.0]) a = v1 - v0 b = v2 - v0 n = Vector3([a.x, a.y, a.z]).cross(V...
vim-scripts/Vim-SQL-Workbench
resources/py/lib/__init__.py
Python
gpl-3.0
30
0
__author__ = 'Cos
min Popescu'
christianurich/VIBe2UrbanSim
3rdparty/opus/src/inprocess/bhylee/hlcm_parcel_estimation.py
Python
gpl-2.0
6,635
0.008742
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from urbansim.configs.hlcm_estimation_config import HLCMEstimationConfig from psrc_parcel.configs.baseline_estimation import BaselineEstimation from opus_core.session_configuration import Sessio...
["models_configuration"]["household_location_choice_model"]["controller"]["prepare_for_estimate"]["arguments"]["join_datasets"] = 'True' self["models_configuration"]["household_location_choice_model"]["controller"]["prepare_for_estimate"]["arguments"]["index_to_unplace"] = 'None' self["models_configur...
troller"]["prepare_for_estimate"]["arguments"]["filter"] = "'household.move == 1'"#None #"'psrc.household.customized_filter'" self["models_configuration"]["household_location_choice_model"]["controller"]["init"]["arguments"]['filter'] = "'urbansim_parcel.building.is_residential'" # self["datasets_to_pr...
brenns10/social
social/accounts/github.py
Python
bsd-3-clause
2,234
0.000895
""" **GitHubAccount** Represents an account at GitHub. - Matches a link that looks like it goes to a GitHub profile page. - Returns the "your site" URL from the user's GitHub profile. - Use on the command line: ``github:username``. """ from __future__ import print_fu
nction, division import re import requests from lxml import html from .
import Account _URL_RE = re.compile(r'https?://(www.)?github.com/(?P<username>\w+)/?\Z') class GitHubAccount(Account): def __init__(self, username=None, url=None, **_): if username is not None: self._username = username elif url is not None: match = _URL_RE.match(url) ...
luqasz/mcm
tests/integration/test_compare.py
Python
gpl-2.0
4,109
0.010465
# -*- coding: UTF-8 -*- import pytest from mc
m.comparators import UniqueKeyComparator, SingleElementComparator, OrderedComparator from mcm.datastructures import CmdPathRow @pytest.fixture def compare_data(request): single = { 'wanted':CmdPathRow({"primary-ntp":"1.1.1.1"}),
'present':CmdPathRow({"primary-ntp":"213.222.193.35"}), 'difference':CmdPathRow({"primary-ntp":"1.1.1.1"}), } default = { 'wanted':CmdPathRow({'name':'admin', 'group':'read'}), 'present':CmdPathRow({'name':'admin', 'group':'full', '.id':'*2'}), 'extra':CmdPathRow({'name':'oper...
simplicitylab/doc2source
modules/loader_parsers.py
Python
gpl-2.0
2,064
0.001453
""" Module that handles the loading of parsers written by Glenn De Backer < glenn at simplicity dot be> License: GPLv2 """ import glob import os class LoaderParsers(object): """ Parsers loader class """ def __init__(self): """ Default constructor """ self.available_parsers = {} ...
_class = self.validate_parser(parser_class) if is_valid_parser_class: # store class object in dictionary available_parsers self.available_parsers[parser_name] = parser_class() e
lse: raise Exception("Parser %s is invalid parser" % parser_name) def get_local_parsers(self): """ Get parsers """ for py_file_path in glob.glob("modules/parsers/*.py"): # get basename python_file = os.path.basename(py_file_path) # skip init python f...
openstack-infra/project-config
roles/copy-wheels/files/wheel-indexer.py
Python
apache-2.0
4,718
0
#!/usr/bin/env python3 # # Copyright 2020 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 agreed to in writing, software # distributed u...
e the # License for the specific language governing permissions and limitations # under the License. # # Final all .whl files in a directory, and make a index.html page # in PEP503 (https://www.python.org/dev/peps/pep-0503/) format import argparse import datetime import email import hashlib import html import logging...
youtube/cobalt
third_party/web_platform_tests/tools/py/doc/example/genhtmlcss.py
Python
bsd-3-clause
426
0.014085
import py html = py.xml.html class my(html): "a custom style" class body(
html.body): style = html.Style(font_size = "120%") class h2(html.h2): style = html.Style(background = "grey") class p(html.p): style = html.Style(font_weight="bold") doc = my.html( my.head(), my.body( my.h2("hello world"), my.p("bold as bold can") )
) print doc.unicode(indent=2)
lino-framework/welfare
lino_welfare/projects/gerd/tests/dumps/18.8.0/cal_recurrentevent.py
Python
agpl-3.0
3,162
0.099937
# -*- coding: UTF-8 -*- logger.info("Loading 15 objects to table cal_recurrentevent...") # fields: id, start_date, start_time, end_date, end_time, name, user, every_unit, every, monday, tuesday, wednesday, thursday, friday, saturday, sunday, max_events, event_type, description loader.save(create_cal_recurrentevent(1,da...
False,False,False,None,1,u'')) loader.save(create_cal_recurrentevent(11,date(2013,5,9),None,None,None,['Christi Himmelfahrt', 'As
cension', 'Ascension of Jesus'],None,u'E',1,False,False,False,False,False,False,False,None,1,u'')) loader.save(create_cal_recurrentevent(12,date(2013,5,20),None,None,None,['Pfingsten', 'Pentec\xf4te', 'Pentecost'],None,u'E',1,False,False,False,False,False,False,False,None,1,u'')) loader.save(create_cal_recurrentevent(1...
mercycorps/TolaTables
silo/migrations/0014_formulacolumnmapping.py
Python
gpl-2.0
815
0.002454
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2017-06-16 19:25 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Mig
ration(migrations.Migration): dependencies = [ ('silo', '0013_deletedsilos'), ] operations = [ migrations.CreateModel( name='FormulaColumnMapping', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=Fal
se, verbose_name='ID')), ('mapping', models.TextField()), ('operation', models.TextField()), ('column_name', models.TextField()), ('silo', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='silo.Silo')), ], ), ]
belleandindygames/league
league/champ_chooser/urls.py
Python
mit
756
0.006614
from django.conf import settings from django.conf.urls import url from .views import get_summoner_v3, live_match, test_something, live_match_detail, FrontendAppView, Api
LiveMatch, ChampionInfoView urlpatterns = [ url(r'^summoner/', get_summoner_v3, name='summoner_lookup'), url(r'^live/$',
live_match, name='live_match'), url(r'^live/([a-zA-Z0-9]+)/(.+)/$', live_match_detail, name='live-match-detail'), url(r'^api/live/([a-zA-Z0-9]+)/(.+)/$', ApiLiveMatch.as_view(), name='api-live-match'), url(r'api/champions/$', ChampionInfoView.as_view(), name='api-champion-info'), url(r'^summonerprofile/...
MadMac/PyTetris
src/main/main.py
Python
mit
1,650
0.004848
import pygame, sys, os, random from classes import * from pygame.locals import * blocksFile = "blocks.txt" thisBlock = "" allBlocks = [] boardWidth = 15 boardHeight = 20 gameOver = False # Make all the blocks which are in file "blocks.txt" file = open(blocksFile, "r") while file: line = file.readline() if l...
nge(len(allBlocks))].getStyle(), gameBoard) pygame.time.Clock
() pygame.time.set_timer(pygame.USEREVENT + 1, 150) pygame.time.set_timer(pygame.USEREVENT + 2, 1000) #Game loop while gameOver == False: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: gameOver = True elif event.type == KEYDOWN and event.key == K_ESCA...
MissionCriticalCloud/marvin
marvin/cloudstackAPI/resetPasswordForVirtualMachine.py
Python
apache-2.0
24,253
0.00099
"""Resets the password for virtual machine. The virtual machine must be in a "Stopped" state and the template must already support this feature for this command to take effect. [async]""" from baseCmd import * from baseResponse import * class resetPasswordForVirtualMachineCmd (baseCmd): typeInfo = {} def __i...
al machine""" self.serviceofferingname = None self.typeInfo['serviceofferingname'] = 'string' """State of the Service from LB rule""" self.servicestate = None
self.typeInfo['servicestate'] = 'string' """the state of the virtual machine""" self.state = None self.typeInfo['state'] = 'string' """an alternate display text of the template for the virtual machine""" self.templatedisplaytext = None self.typeInfo['templatedisplaytext...
5monkeys/blues
blues/java.py
Python
mit
1,149
0.001741
""" Java ==== Installs Java, currently restricted to version 7. **Fabric environment:** .. code-block:: yaml blueprints:
- blues.java """ from fabric.decorators import task from refabric.api import run, info from refabric.context_managers import sudo from . import debian __all__ = ['setup'] @task def setup(): """ Install Java """ install() def install(): with sudo(): lbs_release = debian.lbs_relea...
ct true', 'shared/accepted-oracle-license-v1-1 seen true') package = 'oracle-java7-installer' elif lbs_release >= '16.04': package = 'default-jdk' elif lbs_release >= '14.04': package = 'openjdk-7-jdk' else: ...
apache/allura
Allura/allura/tests/test_tasks.py
Python
apache-2.0
28,836
0.001149
# 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 (t...
the event task has been persisted: assert M.MonQTask.query.get(task_name='allura.tasks.event_tasks.event', args=['my_event4']) def test_compound_error(self): t = raise_exc.post() with LogCapture(level=logging.ERROR) as l, \ mock.patch.dict(tg.config, {'monq.raise_errors': Fa...
assert_equal(l.records[0].name, 'allura.model.monq_model') msg = l.records[0].getMessage() assert_in("AssertionError('assert 0'", msg) assert_in("AssertionError('assert 5'", msg) assert_in(' on job <MonQTask ', msg) assert_in(' (error) P:10 allura.tests.test_tasks.raise_exc ', ...
Conedy/Conedy
testing/network/expected/sum_setDirected.py
Python
gpl-2.0
76
0
00000 0
output/setDirected.py.err 13678 1 output/setDirec
ted.py.out
furious-luke/django-ajax
django_ajax/decorators.py
Python
mit
2,485
0.000805
""" Decorators """ from __future__ import unicode_literals from functools import wraps from django.http import HttpResponseBadRequest from django.utils.decorators import available_attrs from django_ajax.shortcuts import render_to_json def ajax(function=None, mandatory=True, **ajax_kwargs): """ Decorator wh...
ecorators: @ajax @login_required @require_POST def my_view(request): pass # if request user is not authenticated then the @login_required # decorator redirect to
login page. # will send {'status': 302, 'statusText': 'FOUND', 'content': '/login'} # if request method is 'GET' then the @require_POST decorator return # a HttpResponseNotAllowed response. # will send {'status': 405, 'statusText': 'METHOD NOT AL...
googleapis/python-dialogflow
samples/generated_samples/dialogflow_v2beta1_generated_entity_types_delete_entity_type_sync.py
Python
apache-2.0
1,440
0.000694
# -*- coding: utf-8 -*- # Copyright 2022 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...
dependency, execute the following: # python3 -m pip install google-cloud-dialogflow # [START dialogflow_v2beta1_generated_EntityTypes_DeleteEntityType_sync] from google.cloud import dialogflow_v2beta1 def sample_delete_entity_type(): # Create a client client = dialogflow_v2beta1.EntityTypesClient() #...
_type(request=request) # [END dialogflow_v2beta1_generated_EntityTypes_DeleteEntityType_sync]
rohitwaghchaure/frappe
frappe/email/queue.py
Python
mit
16,756
0.028408
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe import HTMLParser import smtplib, quopri from frappe import msgprint, throw, _ from frappe.email.smtp import SMTPServer, get_outgoing_email_account from frappe.email...
Add email to sending queue (Email Queue) :param recipients: List of recipients. :param sender: Email sender. :param subject: Email subject. :param message: Email message. :param reference_doctype: Reference DocType of caller document. :param reference_name: Reference name of caller document. :param send_priorit...
scribe_params: additional params for unsubscribed links. default are name, doctype, email :param attachments: Attachments to be sent. :param reply_to: Reply to be captured here (default inbox) :param in_reply_to: Used to send the Message-Id of a received email back as In-Reply-To. :param send_after: Send this email...
arenadata/ambari
ambari-server/src/main/resources/scripts/configs.py
Python
apache-2.0
13,921
0.014726
#!/usr/bin/env python ''' Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License")...
operties.find('value') final = properties.find('final') if name != None: name_text = name.text if name.text else "" else: logger.warn("No name is found for one of the properties in {0}, ignoring it".format(path))
continue if value != None: value_text = value.text if value.text else "" else: logger.warn("No value is found for \"{0}\" in {1}, using empty string for it".format(name_text, path)) value_text = "" if final != None: final_text = final.text if final.text else "" properties_att...
peter1000/SpeedIT
SpeedIT/ProfileIT.py
Python
bsd-3-clause
7,430
0.012115
""" Profile module """ from operator import itemgetter from cProfile import Profile from SpeedIT.ProjectErr import Err from SpeedIT.Utils import ( format_time, get_table_rst_formatted_lines ) def _profile_it(func, func_positional_arguments, func_keyword_arguments, name, profileit__max_slashes_fileinfo, profile...
functions) - number_of_calls: the number of calls - func_txt: provides the respective data of each function """ all_final_lines = [] for func_name, (function_, func_positional_arguments, func_keyword_arguments) in sorted(func_dict.items()): if use_func_name: name = getattr(func...
ments, name, profileit__max_slashes_fileinfo, profileit__repeat) table = sorted(table, key=itemgetter('func_time'), reverse=True) compare_reference = summary_dict['total_time'] if compare_reference == 0: # add ranking ect... for idx, dict_ in enumerate(table): dict_['com...
goddardl/gaffer
python/GafferSceneUI/SceneSwitchUI.py
Python
bsd-3-clause
2,393
0.009611
########################################################################## # # Copyright (c) 2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistrib...
cific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PART
ICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRU...
cloudify-cosmo/cloudify-plugins-common
cloudify/tests/test_context.py
Python
apache-2.0
26,770
0
######## # Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #
Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # * See the License for the specific language governing permissions and # * limitations under the...
from cloudify_rest_client.exceptions import CloudifyClientError from cloudify.utils import create_temp_folder from cloudify.decorators import operation from cloudify.manager import NodeInstance from cloudify.workflows import local from cloudify import constants, state, context, exceptions, conflict_handlers import cl...
yeleman/snisi
snisi_maint/management/commands/entities_to_cascades.py
Python
mit
2,414
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) import logging from django.core.management.base import BaseCommand from optparse import make_option from py3compat import PY2 from...
is_bko = region.name == 'BAMAKO' for cercle in AEntity.objects.filter(parent=region): logger.info(cercle) for commune in AEntity.objects.filter(parent=cercle): logger.info(commune) if not is_bko: csv_writer.write...
'cercle_commune': cercle.name, 'commune_quartier': commune.name }) continue for vfq in AEntity.objects.filter(parent=commune): for v in (region, cercle, commune, vfq): ...
joergullrich/virl-lab
library/ntc_reboot.py
Python
gpl-3.0
6,997
0.001572
#!/usr/bin/env python # Copyright 2015 Jason Edelman <[email protected]> # Network to Code, 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/LI...
'host', 'username', 'password', 'platform']], supports_check_mode=False ) if not HAS_PYNTC: module.fail_json(msg='pyntc Pyth
on library not found.') platform = module.params['platform'] host = module.params['host'] username = module.params['username'] password = module.params['password'] ntc_host = module.params['ntc_host'] ntc_conf_file = module.params['ntc_conf_file'] transport = module.params['transport'] ...
peterbe/headsupper
headsupper/base/migrations/0001_initial.py
Python
mpl-2.0
2,093
0.002389
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migr
ations import django.utils.timezone import jsonfield.fields from django.conf imp
ort settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Payload', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=F...
blackmad/snippets
models/group.py
Python
apache-2.0
556
0.017986
from flask_sqlalchemy import SQLAlche
my from sqlalchemy import Table, Column, Integer, ForeignKey from sqlalchemy.orm import relationship from models.base import Base, get_or_create db = SQLAlchemy() class Group(Base): __tablename__ = 'group' id = db.Column(db.String(50), unique=True, primary_key=True) subscribers = db.relationship('GroupSubscri...
k_populates='group') def __init__(self, id): self.id = id @property def name(self): return self.id
ygenc/onlineLDA
wikirandom.py
Python
gpl-3.0
5,021
0.00478
# wikirandom.py: Functions for downloading random articles from Wikipedia # # Copyright (C) 2010 Matthew D. Hoffman # # 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 Lic...
all = re.sub(r'==\s*[Ss]ource\s*==.*', '', all) all = re.sub(r'==\s*[Rr]eferences\s*==.*', '', all) al
l = re.sub(r'==\s*[Ee]xternal [Ll]inks\s*==.*', '', all) all = re.sub(r'==\s*[Ee]xternal [Ll]inks and [Rr]eferences==\s*', '', all) all = re.sub(r'==\s*[Ss]ee [Aa]lso\s*==.*', '', all) all = re.sub(r'http://[^\s]*', '', all) all = re.sub(r'\[\[Image:.*?\]\]', '', all) ...
openstack/compute-hyperv
compute_hyperv/nova/conf.py
Python
apache-2.0
3,933
0
# Copyright 2017 Cloudbase Solutions Srl # 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 r...
By default, instances will be saved, which ' 'adds a disk overhead. Changing this option will not ' 'affect existing instances.'), cfg.IntOpt('instance_live_migration_timeout', default=300, min=0, help='Number of seconds to wait...
'live migrated (Only applies to clustered instances ' 'for the moment).'), cfg.IntOpt('max_failover_count', default=1, min=1, help="The maximum number of failovers that can occur in the " "failover_period timeframe per VM. Once a...
be-ndee/bubi-lang
tests/test_default_mapper.py
Python
mit
1,127
0
import unittest import os from bubi.mapper import DefaultMapper class DefaultMapperTestCase(unittest.TestCase): def setUp(self): self.mapper = DefaultMapper(colorize=False) self.color_mapper = DefaultMapper(colori
ze=True) # test the map
method without color def test_mapping(self): self.assertEquals(self.mapper.map('a'), '+') self.assertEquals(self.mapper.map('z'), '+') self.assertEquals(self.mapper.map('0'), '-') self.assertEquals(self.mapper.map('9'), '-') self.assertEquals(self.mapper.map('\n'), '\n') ...
vasiliykochergin/euca2ools
euca2ools/commands/iam/listaccountpolicies.py
Python
bsd-2-clause
3,688
0
# Copyright 2009-2015 Eucalyptus Systems, Inc. # # Redistribution and use of this software in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions ...
BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BU
SINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from requestbuilder import Arg from requestbuilder.response...
vrde/logstats
logstats/base.py
Python
mit
3,761
0.000532
'''Base module to handle the collection and the output of statistical data.''' import logging import time import multiprocessing as mp import queue from collections import Counter log = logging.getLogger(__name__) current_milli_time = lambda: int(round(time.time() * 1000)) def is_number(val): '''Function to ch...
ats = Counter() else: delta = current_milli_time(
) - self.last stats = self.get_stats(delta) if stats: self.emit(self.format_msg(stats)) self.last = current_milli_time()
rob-nn/python
first_book/message_analyzer.py
Python
gpl-2.0
365
0.005479
# Message Analyzer # Demonstrates the len() function and the in oper
ator message = input("Enter a message: ") print("\nThe length of your message is:", len(message)) print("\nThe most common letter in the English language, 'e',") if "e" in message: print("is in your message.") else: print("is not in your message.") input("\n\nPress the en
ter key to exit.")