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
NelleV/pyconfr-test
symposion/proposals/templatetags/proposal_tags.py
Python
bsd-3-clause
2,245
0.0049
from django import template from symposion.proposals.models import AdditionalSpeaker register = template.Library() class AssociatedProposalsNode(template.Node): @classmethod def handle_token(cls, parser, token): bits = token.split_contents() if len(bits) == 3 and bits[1] == "as": ...
context[self.context_var] = None return u"" @register.tag def pending_proposals(parser, token): """ {% pending_proposals as pending_proposals %} """ return PendingProposalsNode.handle_token(parser, token) @register.tag def associated_proposals(parser, token): """ {% assoc...
e_token(parser, token)
nis-sdn/odenos
src/main/python/org/o3project/odenos/core/manager/component_manager.py
Python
apache-2.0
5,084
0.00059
# -*- coding:utf-8 -*- # Copyright 2015 NEC Corporation. # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License...
er_components(self, components): self.register_remote_objects(components) types = ",".join(self.remote_object_classes.keys()) self._object_property.set_property(C
omponentManager.COMPONENT_TYPES, types) def _add_rules(self): rules = [] rules.append({RequestParser.PATTERN: r"^component_types/?$", RequestParser.METHOD: Request.Method.GET, RequestParser.FUNC: self._do_get_com...
darth-dodo/what_2_watch
test.py
Python
mit
759
0.02108
import re # cat_list = ['Programming','Trending on Reddit','Trailers','Stand-up'] # def urlify(ip): # # Remove all non-word characters (everything except numbers and letters) # only_num_and_letters = re.sub(r'[^\w\d\s]','',ip) # # Replace all runs of whitespace with a single dash # output = re.sub(r'...
2,3,4,4,5,5,6,6,7,7,8,9] amt = 4 def randomizer(amt,zipped_list): amt = int(amt) op_list = [] while len(op_list) < amt:
pass rand_value = choice(zipped_list) if rand_value not in op_list: op_list.append(rand_value) return op_list print randomizer(5,a)
indrz/indrz
indrz/users/urls.py
Python
gpl-3.0
1,054
0.001898
from django.urls import url, include, path from rest_framework import routers from users import views # router = routers.DefaultRouter() # router.register(r'users', views.UserViewSet) # router.register(r'groups', views.GroupViewSet) # # # Wire up our API using automatic URL routing. # # Additionally, we include login ...
', include('rest_framework.urls', namespace='rest_framework')) # ] # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals urlpatterns = [ url( regex=r'^$', view=views.UserListView.as_view(), name='list' ), url( regex=r'^~redirect/$', view=...
' ), url( regex=r'^~update/$', view=views.UserUpdateView.as_view(), name='update' ), ]
brandicted/nefertari-es
tests/test_documents.py
Python
apache-2.0
35,116
0.000057
import pytest from mock import patch, Mock, call from nefertari.json_httpexceptions import ( JHTTPBadRequest, JHTTPNotFound, ) from .fixtures import ( simple_model, id_model, story_model, person_model, tag_model, parent_model) from nefertari_es import documents as docs from nefertari_es import fields ...
.value) def test_getattr_id_none(self, id_model): item = id_model() assert item._id is None item.meta['id'] = 123 assert item._id == 123 @patch('nefertari_es.documents.BaseDocument._load_related') def
test_getattr_load_rel(self, mock_load, story_model): story = story_model() story.author mock_load.assert_called_once_with('author') @patch('nefertari_es.documents.BaseDocument._load_related') def test_getattr_raw(self, mock_load, story_model): story = story_model(author=1) ...
dolaCmeo/quick_flask
flask_site/user/__init__.py
Python
mit
49
0
# -
*- coding: utf-8 -*-# __
author__ = 'dolacmeo'
MithileshCParab/HackerRank-10DaysOfStatistics
Problem Solving/Data Structure/Trie/no_prefix_set.py
Python
apache-2.0
2,190
0.010959
# Enter your code here. Read input from STDIN. Print output to STDOUT class Node: def __init__(self, letter): self.letter = letter
self.children = {} self.isWord = False class Trie: def __init__(self): self.root = Node("*") def buildTrie(self, word): curr_node = self.root for idx, char in enumerate(word): if curr_node.isWord: return word elif idx == len(word)-...
rd elif char not in curr_node.children: curr_node.children[char] = Node(char) curr_node = curr_node.children[char] curr_node.isWord = True if __name__ == "__main__": trie = Trie() wordsDict = {} isGoodSet = True n = int(input()) for i in range(n): ...
eduNEXT/edx-platform
openedx/core/djangoapps/course_live/migrations/0001_initial.py
Python
agpl-3.0
3,720
0.004839
# Generated by Django 3.2.12 on 2022-02-23 08:07 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import model_utils.fields import opaque_keys.edx.django.models import simple_history.models class Migration(migrations.Migration): ...
er')), ('history_id', models.AutoField(primary_key=True, serialize=False)), ('history_date', models.DateTimeField()), ('his
tory_change_reason', models.CharField(max_length=100, null=True)), ('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)), ('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+...
Gustavo6046/ChatterBot
docs/conf.py
Python
bsd-3-clause
6,225
0.00241
# -*- coding: utf-8 -*- # # ChatterBot documentation build configuration file, created by # sphinx-quickstart on Mon May 9 14:38:54 2016. import sys import os import sphinx_rtd_theme from datetime import datetime # Insert the project root dir as the first element in the PYTHONPATH. # This lets us ensure that the so...
le = 'sphinx' # -- Options for HTML output ---------------------------------------------- html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme,...
_only': True } html_show_sourcelink = False # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. html_logo = '../graphics/banner.png' # The name of an image file (relative...
Matusf/django-konfera
runtests.py
Python
mit
2,158
0
import sys try: from django.conf import settings from django.test.utils import get_runner settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", } }, TEMPLATES=[ ...
teError: pass else: setup() except ImportError: import traceback traceback.print_exc() msg = "To fix this error, run: pip install -r requirements.txt" raise ImportError(msg) def run_tests(*test_args): if not test_args: test_args = ['konfera.tests', 'payments.tests'] ...
test_runner = TestRunner() failures = test_runner.run_tests(test_args) if failures: sys.exit(bool(failures)) if __name__ == '__main__': run_tests(*sys.argv[1:])
kbrebanov/ansible-modules-extras
packaging/os/homebrew.py
Python
gpl-3.0
28,076
0.000712
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Andrew Dunham <andrew@du.nham.ca> # (c) 2013, Daniel Jaouen <dcj24@cornell.edu> # (c) 2015, Indrajit Raychaudhuri <irc+code@indrajit.com> # # Based on macports (Jimmy Tang <jcftang@gmail.com>) # # This module is free software: you can redistribute it and/or modify ...
s.path import re from ansible.module_utils.six import iteritems # exceptions -------------------------------------------------------------- {{{ class HomebrewException(Exception): pass # /exceptions ------------------------------------------------------------- }}} # utils --------------------------------------...
chars = filter(None, (line.split('#')[0].strip() for line in lines)) group = r'[^' + r''.join(chars) + r']' return re.compile(group) # /utils ------------------------------------------------------------------ }}} class Homebrew(object): '''A class to manage Homebrew packages.''' # class regexes ...
zerothi/sisl
sisl/physics/tests/test_spin.py
Python
mpl-2.0
4,252
0.002352
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/. import pytest import math as m import numpy as np from sisl import Spin pytestmark = [pytest.mark.physics, pytest.ma...
]) x = np.array([1, -1, 1, -1, 0, 0, 0, 0, 0, 0]) assert np.allclose(x, (np.conj(W)*S.X.dot(W.T).T).sum(1).real) y = np.array([0, 0, 0, 0, 1, -1, 1, -1, 0, 0]) assert np.allclose(y, (np.conj(W)*np.dot(S.Y, W.T).T).sum(1).real) z = np.array([0, 0, 0, 0, 0, 0, 0, 0, 1, -1]) assert np.allclose(z...
mport pickle as p S = Spin('nc') n = p.dumps(S) s = p.loads(n) assert S == s
mitsei/dlkit
tests/resource/test_managers.py
Python
mit
26,397
0.002652
"""Unit tests of resource managers.""" import pytest from ..utilities.general import is_never_authz, is_no_authz, uses_cataloging, uses_filesystem_only from dlkit.abstract_osid.osid import errors from dlkit.abstract_osid.type.objects import TypeList as abc_type_list from dlkit.primordium.id.primitives import Id fro...
RVICE_MEMCACHE']) def resource_manager_class_fixture(request): # Implemented from resource.ResourceManager request.cls.service_config = request.param request.cls.svc_mgr = Runtime().get_service_manager( 'RESOURCE', implementation=request.cls.service_config) if not is_never_authz(request....
form = request.cls.svc_mgr.get_bin_form_for_create([]) create_form.display_name = 'Test Bin' create_form.description = 'Test Bin for resource manager tests' catalog = request.cls.svc_mgr.create_bin(create_form) request.cls.catalog_id = catalog.get_id() request.cls.receiver = Noti...
marcelometal/python-semanticversion
tests/django_test_app/__init__.py
Python
bsd-2-clause
941
0
# -*- coding: utf-8 -*- # Copyright (c) 2012-2014 The python-semanticversion project # This code is distributed under the two-clause BSD License. try: # pragma: no cover import django from django.conf import settings django_loaded = True except ImportError: # pragma: no cover django_loaded = False ...
ect.com/en/dev/releases/1.7/#app-loading-
changes if django.VERSION >= (1, 7): from django.apps import apps apps.populate(settings.INSTALLED_APPS)
gurch101/portfolio-manager
setup.py
Python
mit
973
0.001028
"""stockretriever""" from setuptools import setup setup( name='portfolio-manager', version='1.0', description='a web app that keeps track of your investment portfolio', url='https://github.com/gurch101/portfolio-manager', author='Gurchet Rai', author_email='gurch101@gmail.com', license='MI...
se :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7' ], keywords='investme
nt portfolio', dependency_links=['https://github.com/gurch101/StockScraper/tarball/master#egg=stockretriever-1.0'], zip_safe=True, setup_requires=[ 'stockretriever==1.0', 'Flask==0.10.1', 'passlib==1.6.2', 'schedule==0.3.2', 'requests==2.2.1' ] )
leowa/django_informixdb
django_informixdb/compiler.py
Python
apache-2.0
1,808
0.001106
from django.db.models.sql import compiler class SQLCompiler(compiler.SQLCompiler): def as_sql(self, with_limits=True, with_col_aliases=False, subquery=False): if with_limits and self.query.low_mark == self.query.high_mark: return '', () raw_sql, fields = super(SQLCompiler, self).as_sql...
return raw_sql.replace(r'%s', '?'), fields def _list2tuple(arg): return tuple(arg) if isinstance(arg, list) else arg class SQLInsertCompiler(compiler.SQLInsertCompiler, SQLCompiler): def as_sql(self): result = super(SQLInsertCompil
er, self).as_sql() return [(ret[0].replace(r'%s', '?'), _list2tuple(ret[1])) for ret in result] class SQLAggregateCompiler(compiler.SQLAggregateCompiler, SQLCompiler): def as_sql(self): result = super(SQLAggregateCompiler, self).as_sql() return result[0].replace(r'%s', '?'), result[1] cl...
neilbrown/susman
dnotify.py
Python
gpl-2.0
3,660
0.003552
#!/usr/bin/env python # class to allow watching multiple files and # calling a callback when any change (size or mtime) # # We take exclusive use of SIGIO and maintain a global list of # watched files. # As we cannot get siginfo in python, we check every file # every time we get a signal. # we report change is size, m...
self.callbacks = newlist for f in self.files:
f.check() def cancel(self, victim): if victim in self.files: self.files.remove(victim) class file(): def __init__(self, fname, callback): self.name = fname try: stat = os.stat(self.name) except OSError: self.ino = 0 self.s...
marcellodesales/svnedge-console
svn-server/lib/suds/xsd/query.py
Python
agpl-3.0
6,451
0.002945
# This program is free software; you can redistribute it and/or modify # it under the terms of the (LGPL) GNU Lesser General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will ...
if reject: log.debug('result %s, rejected by\n%s', Repr(result), self) return reject def result(self, result): """ Query result post processing. @param result: A query result. @type result: L{sxbase.SchemaObject} """ if result is None: ...
esult)) self.history.append(result) return result class BlindQuery(Query): """ Schema query class that I{blindly} searches for a reference in the specified schema. It may be used to find Elements and Types but will match on an Element first. This query will also find builtins. ""...
esc/pybuilder
build.py
Python
apache-2.0
6,011
0.001497
#!/usr/bin/env python # # -*- coding: utf-8 -*- # # This file is part of PyBuilder # # Copyright 2011-2015 PyBuilder Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # ...
_environment", True) project.set_propert
y('flake8_break_build', True) project.set_property('flake8_include_test_sources', True) project.set_property('flake8_include_scripts', True) project.set_property('flake8_max_line_length', 130) project.set_property('frosted_include_test_sources', True) project.set_property('frosted_include_scripts',...
sizzlelab/pysmsd
extras/webob/__init__.py
Python
mit
82,534
0.001648
from cStringIO import StringIO import sys import cgi import urllib import urlparse import re import textwrap from Cookie import BaseCookie from rfc822 import parsedate_tz, mktime_tz, formatdate from datetime import datetime, date, timedelta, tzinfo import time import calendar import tempfile import warnings from webob....
return timedelta(0) def tzname(self, dt): return 'UTC' def __repr__(self): return 'UTC' UTC = _UTC() def html_escape(s): """HTML-escape a string or object This converts any non-string objects passed into it to strings (actually, using ``unicode()``). All values returned a...
non-unicode strings (using ``&#num;`` entities for all non-ASCII characters). None is treated specially, and returns the empty string. """ if s is None: return '' if not isinstance(s, basestring): if hasattr(s, '__unicode__'): s = unicode(s) else: ...
aaxelb/osf.io
osf/migrations/0055_update_metaschema_active.py
Python
apache-2.0
594
0.001684
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-14 14:32 from __future__ import unicode_literals from django.db import migrati
ons from osf.models import MetaSchema from website.project.metadata.schemas import LATEST_SCHEMA_VERSION def update_metaschema_active(*args, **kwargs): MetaSchema.objects.filter(schema_version__lt=LATEST_SCHEMA_VERSION).update(active=False) class Migration(migrations.Migration): dependencies = [ (...
_metaschema_active, ), ]
alexryndin/ambari
ambari-server/src/main/resources/common-services/AMBARI_INFRA/0.1.0/package/scripts/setup_infra_solr.py
Python
apache-2.0
5,041
0.004761
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this ...
create_parents=True, recursive_ownership=True ) File(params.infra_solr_log, mode=0644, owner=params.infra_solr_user,
group=params.user_group, content='' ) File(format("{infra_solr_conf}/infra-solr-env.sh"), content=InlineTemplate(params.solr_env_content), mode=0755, owner=params.infra_solr_user, group=params.user_group ) File(format("{infra_solr_datadir...
team-vigir/vigir_behaviors
vigir_flexbe_states/src/vigir_flexbe_states/moveit_predefined_pose_state.py
Python
bsd-3-clause
13,581
0.030705
#!/usr/bin/env python import rospy import actionlib from flexbe_core import EventState, Logger from vigir_flexbe_states.proxy import ProxyMoveitClient """ Created on 04/13/2014 @author: Philipp Schillinger """ class MoveitPredefinedPoseState(EventState): """ Uses moveit to go to one of the pre-defined poses. -...
+2.65, -1.40, -0.20, -0.90, -1.54]}, 156: {'group': 'r_arm_group', 'joints': [+0.32, +0.90, +2.20, -1.30, +0.50, -1.00, -1.80]}, 157: {'grou
p': 'r_arm_group', 'joints': [0.45, 1.0, 2.1, -1.3, 0.5, -0.8 , -0.8]} } self._poses['thor_mang'] = dict() self._poses['thor_mang']['left'] = { 1: {'group': 'l_arm_group', 'joints': [0.785385646194622, -0.281153767716932, 0.000600782658167331, -1.57080884130538, -0.25205140042963, 0.01563815008...
apaku/jenkinstray
jenkinstray/jenkinsjob.py
Python
bsd-2-clause
3,238
0.005559
# -*- coding: utf-8 -*- # Copyright (c) 2014, Andreas Pakulat <apaku@gmx.de> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright n...
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 INTERRUPTION) ...
kermitfr/kermit-webui
src/webui/platforms/jboss/operations.py
Python
gpl-3.0
3,848
0.013773
''' Created on Nov 8, 2011 @author: mmornati ''' from webui.abstracts import ContextOperation from webui import settings from webui.core import kermit_modules from guardian.shortcuts import get_objects_for_user from webui.agent.models import Agent, Action class JbossDeployContextMenu(ContextOperation): def g...
es)==1 def get_enabled(self, user): if not user.is_superuser: agents = get_objects_for_user(user, 'use_agent', Agent).filter(enabled=True, name="jboss") if len(agents)==1: action = get_objects_for_user(user, 'use
_action', Action).filter(agent=agents[0], name="deploy") return action and len(action)==1 else: return False else: return True class JbossRedeployContextMenu(ContextOperation): def get_operations(self): context_menu_ops = [] ...
jolyonb/edx-platform
lms/djangoapps/grades/tests/test_services.py
Python
agpl-3.0
12,114
0.002311
""" Grades Service Tests """ from datetime import datetime import ddt import pytz from freezegun import freeze_time from lms.djangoapps.grades.constants import GradeOverrideFeatureEnum from lms.djangoapps.grades.models import ( PersistentSubsectionGrade, PersistentSubsectionGradeOverride, PersistentSubsecti...
modified=override_obj.modified, score_deleted=False, score_db_table=ScoreDatabaseTableEnum.overrides ) ) override_history = PersistentSubsectionGradeOverrideHistory.objects.filter(override_id=override_obj.id).first() self._verify_override_...
TE) def test_override_subsection_grade_no_psg(self): """ When there is no PersistentSubsectionGrade associated with the learner and subsection to override, one should be created. """ earned_all_override = 2 earned_graded_override = 0 self.service.override_sub...
tbursztyka/python-elf
elf/program.py
Python
lgpl-3.0
5,074
0.019511
""" Copyright (C) 2008-2013 Tomasz Bursztyka This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program ...
: (0x60000000 + 0x4), 'PT_HP_CORE_PROC' : (0x60000000 + 0x5), 'PT_HP_CORE_LOADABLE' : (0x60000000 + 0x6), 'PT_HP_CORE_STACK' : (0x60000000 + 0x7), 'PT_HP_CORE_SHM' : (0x60000000 + 0x8), 'PT_HP_CORE_MMF' : (0x60000000 + 0x9), 'PT_HP_PARALLEL' : (0x60000000 + 0x10), ...
ASTBIND' : (0x60000000 + 0x11), 'PT_HP_OPT_ANNOT' : (0x60000000 + 0x12), 'PT_HP_HSL_ANNOT' : (0x60000000 + 0x13), 'PT_HP_STACK' : (0x60000000 + 0x14), 'PT_PARISC_ARCHEXT' : 0x70000000, 'PT_PARISC_UNWIND' : 0x70000001, 'PT_ARM_EXIDX' : 0x70000001, 'PT_I...
rosspalmer/bitQuant
bitquant/sql/setup.py
Python
mit
857
0.002334
import clss import os def setup_sql(): menu() s = clss.sql() s.meta.create_all(s.eng) def menu(): txt = open('auth_sql', 'w') print print '-----SQL Database setup-----' print print '=Select SQL type=' print ' (1) sqlite' print ' (2) MySQL' print typ = int(raw_input('...
rint
if typ == 1: file_path = str(raw_input('Location/Database Name: ')) + '\n' txt.write(str(typ) + '\n') txt.write(file_path) if typ == 2: host = str(raw_input('Host: ')) + '\n' user = raw_input('Username: ') + '\n' password = raw_input('Password: ') + '\n' na...
persandstrom/home-assistant
homeassistant/components/binary_sensor/bmw_connected_drive.py
Python
apache-2.0
8,080
0
""" Reads vehicle status from BMW connected drive portal. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.bmw_connected_drive/ """ import asyncio import logging from homeassistant.components.binary_sensor import BinarySensorDevice from home...
ectedDriveEntity. """ return False @property def unique_id(self): """Return the unique ID of the binary sensor
.""" return self._unique_id @property def name(self): """Return the name of the binary sensor.""" return self._name @property def device_class(self): """Return the class of the binary sensor.""" return self._device_class @property def is_on(self): ...
claudyus/LXC-Web-Panel
tests/utils.py
Python
mit
755
0.002649
import subprocess import unittest import os class TestCmdLine(unittest.TestCase): """ Those tests are against the lwp command lines """ def test_01_generate_secret(self): assert not os.path.exists('/etc/lwp/session_secret') assert not os.path.exists('/etc/lwp/lwp.conf') subpr...
ate-session-secret', shell=True) assert os.path.exists('/etc/lwp/session_se
cret') def test_02_exit_if_no_config(self): assert not os.path.exists('/etc/lwp/lwp.conf') try: subprocess.check_call('python bin/lwp', shell=True) except subprocess.CalledProcessError as e: assert e.returncode if __name__ == '__main__': unittest.main()
uw-it-aca/django-panopto-scheduler
scheduler/views/api/space.py
Python
apache-2.0
1,252
0
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from scheduler.views.rest_dispatch import RESTDispatch from uw_r25.spaces import get_spaces, get_space_by_id import logging
logger = logging.getLogger(__name__) class Space(RESTDispatch): def __init__(self): self._space_list_cache_timeout = 1 # timeout in hours def get(self, request, *args, **kwargs): space_id = kwargs.get('space_id') if (space_id):
return self._get_space_details(space_id) else: params = {} for q in request.GET: params[q] = request.GET.get(q) return self._list_spaces(params) def _get_space_details(self, space_id): space = get_space_by_id(space_id) return s...
bung87/django-html5-boilerplate
project_name/urls/base.py
Python
mit
417
0.004796
from django.conf.urls import patterns, include, url from django.contrib import admin fro
m django.views.generic import TemplateView admin.autodiscover() urlpatterns = patterns('', # Home Page -- Replace as you prefer url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.u...
)
zayfod/pyfranca
pyfranca/ast.py
Python
mit
15,502
0.000387
""" Franca abstract syntax tree representation. """ from abc import ABCMeta from collections import OrderedDict class ASTException(Exception):
def __init__(self, message):
super(ASTException, self).__init__() self.message = message def __str__(self): return self.message class Package(object): """ AST representation of a Franca package. """ def __init__(self, name, file_name=None, imports=None, interfaces=None, typecollections=None...
KnightHawk3/packr
packr/api/contact.py
Python
mit
4,011
0
import re from datetime import datetime from flask import current_app as app from flask_jwt import current_identity from flask_restplus import Namespace, Resource, fields, reqparse from sqlalchemy.exc import IntegrityError from packr.models import Message api = Namespace('contact', description='Opera...
tParser(bundl
e_errors=True) req_parse.add_argument('id', type=int, required=True, help='No id provided', location='json') args = req_parse.parse_args() id = args.get('id') if id == 0: return {'message': {'id': 'No id provide...
zhangf911/common
test/dev/system_resource_names_test.py
Python
mit
936
0.001068
import unittest from biicode.common.dev.system_resource_names import SystemResourceNames from biicode.common.dev.system_id import SystemID class SystemResourceNamesTest(unittest.TestCase): def setUp(self): self.sut = SystemResourceNames(SystemID("open_gl", "CPP")) def test_add_names(self): s...
self.assertListEqual(self.sut.names, ["stdio"]) def test_serialize(self):
self.assertIsInstance(self.sut.serialize(), dict) def test_eq_true(self): self.assertTrue(self.sut.__eq__(self.sut)) self.assertTrue(self.sut.__eq__(SystemResourceNames(SystemID("open_gl", "CPP")))) def test_eq_false(self): system_resource_names = SystemResourceNames(SystemID(...
claudelee/bilibili-api
danmu-Delay/danmu_delay.py
Python
mit
966
0.045894
# 对ass弹幕文件进行延时。。。 # 为什么会有这个需求呢?因为妈蛋ffmpeg剪切ts视频失败啊!! # 只好弹幕来配合了。。。 # 如果以后经常遇到。。再整理得好用一些。。。 # 酱~ import re def t_delay(h,m,s,delay): s += delay; if s >= 60: s -= 60 m += 1 if m >= 60: m -= 60 h += 1 return [h,m,s] filename = r'in.ass
' delay = 30; fid = open('out.ass','w') for line in open(filename): t = re.findall(r'^(Dialogue: 2,)(\d+):(\d+):(\d+)\.(\d+),(\d+):(\d+):(\d+)\.(.*)$',line) if len(t) == 0: fid.write(line) else: t = t[0] [h,m,s] = t_delay(int(t[1]),int(t[2]),int(t[3]),delay)
fid.write('%s%d:%.2d:%.2d.%s,'%(t[0],h,m,s,t[4])) [h,m,s] = t_delay(int(t[5]),int(t[6]),int(t[7]),delay) fid.write('%d:%.2d:%.2d.%s\n'%(h,m,s,t[8])) fid.close(); print "finished!!"
landlab/landlab
landlab/components/detachment_ltd_erosion/__init__.py
Python
mit
200
0
from .generate_detachment_ltd_erosion import DetachmentLt
dErosion from .generate_erosion_by_depth_slope import DepthSlopeProductErosion __all__ = ["DetachmentLtdErosion", "Dep
thSlopeProductErosion"]
mic4ael/indico
indico/core/db/sqlalchemy/custom/natsort.py
Python
mit
1,070
0.001869
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from sqlalchemy import DDL, text SQL_FUNCTION_NATSORT = ''' ...
WHERE routine_schema = 'indico' AND routine_nam
e = 'natsort' """ count = connection.execute(text(sql)).scalar() return not count def create_natsort_function(conn): DDL(SQL_FUNCTION_NATSORT).execute_if(callable_=_should_create_function).execute(conn)
fernandog/osmc
package/mediacenter-addon-osmc/src/script.module.osmcsetting.updates/resources/lib/update_service.py
Python
gpl-2.0
47,883
0.03425
# Standard Modules import apt from datetime import datetime import decimal import json import os import Queue import random import socket import subprocess import sys import traceback # Kodi Modules import xbmc import xbmcaddon import xbmcgui # Custom modules __libpath__ = xbmc.translatePath(os.path.join(xbmcaddon.Ad...
osmc_update_checks' # if the file is present, then suppress further update checks and show the notification if os.path.isfile(self.block_update_file): self.skip_update_check = True # if the user has suppressed icon notification of updates and
has chosen not to install the updates # its their own damned fault if osmc never get updated if not self.s['suppress_icon']: self.window.setProperty('OSMC_notification', 'true') else: self.skip_update_check = False # check for the external update failed fail_check_file = '/var/tmp/.osmc_failed_u...
florianfesti/boxes
boxes/generators/unevenheightbox.py
Python
gpl-3.0
4,609
0.003688
#!/usr/bin/env python3 # Copyright (C) 2013-2018 Florian Festi # # 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....
self.trapezoidWall(y, h1, h2, [b, "f", edge_types[1], "f"], move="right")
self.trapezoidWall(x, h2, h3, [b, "F", edge_types[2], "F"], move="right") self.trapezoidWall(y, h3, h0, [b, "f", edge_types[3], "f"], move="right") with self.saved_context(): if b != "e": self.rectangularWall(x, y, "ffff", move="up") if self.lid: ...
Serulab/Py4Bio
code/ch14/scatter.py
Python
mit
618
0.004854
from bokeh.charts import Scatter, output_file, show x = [1, 2, 3, 4, 5, 6, 7, 8] y = [2.1, 6.45, 3, 1.4, 4.55, 3.85, 5.2, 0.7] z = [.5, 1.1, 1.9, 2.5, 3.1, 3.9
, 4.85, 5.2] species = ['cat', 'cat', 'cat', 'dog', 'dog', 'dog', 'mouse', 'mouse'] country = ['US', 'US', 'US', 'US', 'UK', 'UK', 'BR', 'BR'] df = {'time': x, 'weight 1': y, 'weight 2': z, 'species':species, 'country': country} scatter = Scatter(df, x='time', y='weight 1', color='country', marker='species', ...
ile('scatter.html') show(scatter)
croxis/SpaceDrive
spacedrive/renderpipeline/rplibs/colorama/ansitowin32.py
Python
mit
9,904
0.001918
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. import re import sys import os from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style from .winterm import WinTerm, WinColor, WinStyle from .win32 import windll, winapi_test winterm = None if windll is not None: winterm = WinT...
ences into win32 calls? if convert is None: convert = conversion_supported and not is_stream_closed(wrapped) and is_a_tty(wrapped) self.convert = convert # dict of ansi codes to win32 functions and parameters
self.win32_calls = self.get_win32_calls() # are we wrapping stderr? self.on_stderr = self.wrapped is sys.stderr def should_wrap(self): ''' True if this class is actually needed. If false, then the output stream will not be affected, nor will win32 calls be issued...
eladhoffer/seq2seq.pytorch
seq2seq/models/modules/weight_drop.py
Python
mit
1,803
0.003882
# Taken from https://github.com/salesforce/awd-lstm-lm/blob/master/weight_drop.py import torch from torch.nn import Parameter from functools import wraps class WeightDrop(torch.nn.Module): def __init__(self, module, weights, dropout=0, variational=False): super(WeightDrop, self).__init__() self.mod...
ubclass(type(self.module), torch.nn.RNNBase): self.module.flatten_parameters = self._dummy for name_w in self.weights: print('Applying weight drop of {} to {}'.format(self.dropout, name_w))
w = getattr(self.module, name_w) del self.module._parameters[name_w] self.module.register_parameter(name_w + '_raw', Parameter(w.data)) def _setweights(self): for name_w in self.weights: raw_w = getattr(self.module, name_w + '_raw') w = None if ...
jdanbrown/pydatalab
legacy_tests/kernel/sql_tests.py
Python
apache-2.0
7,834
0.003957
# Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
ment\n\nfoo="bar"\nSELECT 3 AS x', m) self.assertEquals(query, m.__dict__[TestCases._SQL_MODULE_MAIN]) self.assertEquals(query, m.__dict__[TestCases._SQL_MODULE_LAST]) self.assertEquals('SELECT 3 AS x', m.__dict__[TestCases._SQL_MODULE_MAIN].sql) self.assertEquals('SELECT 3 AS x', m.__dict__[TestCases._...
SELECT "1")\nSELECT * FROM q1', 'INSERT DataSet.Table (Id, Description)\nVALUES(100,"TestDesc")', 'INSERT DataSet.Table (Id, Description)\n' 'SELECT * FROM UNNEST([(200,"TestDesc2"),(300,"TestDesc3")])' 'INSERT DataSet.Table (Id...
Azure/azure-sdk-for-python
sdk/powerbiembedded/azure-mgmt-powerbiembedded/azure/mgmt/powerbiembedded/models/power_bi_embedded_management_client_enums.py
Python
mit
660
0
# coding=u
tf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause ...
----------------------------- from enum import Enum class AccessKeyName(str, Enum): key1 = "key1" key2 = "key2" class CheckNameReason(str, Enum): unavailable = "Unavailable" invalid = "Invalid"
jteehan/cfme_tests
cfme/tests/configure/test_log_depot_operation.py
Python
gpl-2.0
12,788
0.00305
# -*- coding: utf-8 -*- """ Tests used to check the operation of log collecting. Author: Milan Falešník <mfalesni@redhat.com> Since: 2013-02-20 """ from datetime import datetime import fauxfactory import pytest import re from cfme import test_requirements from cfme.configure import configuration as configure from ut...
.gen_alphanumeric(), uri=uri, username=log_depot.credentials["username"], password=log_depot.credentials["password"] ) log_depo
t.create() yield log_depot log_depot.clear() def check_ftp(ftp, server_name, server_zone_id): server_string = server_name + "_" + str(server_zone_id) with ftp: # Files must have been created after start with server string in it (for ex. EVM_1) zip_files = ftp.filesystem.search(re.compi...
blorenz/btce-api
samples/cancel-orders.py
Python
mit
1,343
0.006701
#!/usr/bin/python import sys import btceapi # This sample shows use of a KeyHandler. For each API key in the file # passed in as the first argument, all pending orders for the specified # pair and type will be canceled. if len(sys.argv) < 4: print "Usage: cancel_orders.py <key file> <pair> <order type>" pri...
ist of orders for the given pair, and cancel the ones # with the correct order type. orders = t.orderList(pair = pair) for o in orders: if o.type == order_type: print " Canceling %s %s order for %f @ %f" % (pair, order_type, o.amount, o.r
ate) t.cancelOrder(o.order_id) if not orders: print " There are no %s %s orders" % (pair, order_type) except Exception as e: print " An error occurred: %s" % e
syci/ingadhoc-odoo-addons
hr_timesheet_project/__openerp__.py
Python
agpl-3.0
591
0
# -*- coding: utf-8 -*- { 'name': 'Time Tracking', 'version': '1.0',
'category': 'Human Resources', 'sequence': 23, 'description': """ This module implements a timesheet system. ========================================== """, 'author': 'OpenERP SA', 'webs
ite': 'http://www.openerp.com', 'images': ['images/hr_timesheet_lines.jpeg'], 'depends': ['hr_timesheet', 'project'], 'data': [ ], 'demo': [], 'test': [ ], 'installable': True, 'auto_install': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
andrewsy97/Treehacks
websocket/websocket/_app.py
Python
mit
10,379
0.002794
""" websocket - WebSocket client library for Python Copyright (C) 2010 Hiroki Ohtani(liris) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, ...
""" Higher level of APIs are provided. The interface is like JavaScript WebSocket object. """ def __init__(self, url, header=[], on_open=None, on_message=None, on_error=None, on_close=None, on_ping=None, on_pong=None, on_cont_message=None, ...
ue, get_mask_key=None, cookie=None, subprotocols=None, on_data=None): """ url: websocket url. header: custom header for websocket handshake. on_open: callable object which is called at opening websocket. this function has one argument. The argu...
arruda/amao
AMAO/apps/Corretor/models/retorno.py
Python
mit
2,633
0.012952
# -*- coding: utf-8 -*- from django.db import models from Corretor.base import CorretorException from Corretor.base import ExecutorException from Corretor.base import CompiladorException from Corretor.base import ComparadorException from Corretor.base import LockException from model_utils import Choices class Retorn...
tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" # print ">>altera_dados" # print ">>isinstance(erroException,CorretorException)",isinstance(erroException,CorretorException) i
f sucesso == True: # print ">>retorno.successful()" tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" elif isinstance(erroException,CorretorException): # print "erro: %s" % erroException.message if isinstance(erroException,ExecutorExceptio...
vlukes/sfepy
examples/linear_elasticity/linear_elastic_damping.py
Python
bsd-3-clause
1,983
0.013111
r""" Time-dependent linear elasticity with a simple damping. Find :math:`\ul{u}` such that: .. math:: \int_{\Omega} c\ \ul{v} \cdot \pdiff{\ul{u}}{t} + \int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) = 0 \;, \quad \forall \ul{v} \;, where .. math:: D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\...
' : 101, 'adapt_fun' : adapt_time_step, 'verbose' : 1, }), }) ls = solver
s['ls'] ls[1].update({'use_presolve' : True}) functions = { 'ebc_sin' : (ebc_sin,), }
pcrews/rannsaka
mysql/mysql_demo.py
Python
apache-2.0
3,820
0.012565
import commands import time import MySQLdb from locust import Locust, events, task, TaskSet def show_tables(self): print "Running show_tables..." print self.client.query("SHOW TABLES IN mysql", name="SHOW TABLES") def mysql_user(self): print "Running show users..." pr...
""" on_start is called when a Locust start before any
task is scheduled """ self.id = str(self.locust).split('object at')[1].strip().replace('>','') tasks = {three_table_join: 10, two_table_join: 5, city_select: 3, country_select: 1 } class MariadbLocust(Locust): """ This is the abstract Lo...
uwosh/CCDET-CBRF
ccdet.py
Python
gpl-2.0
8,257
0.004844
import csv import logging import transaction DIRNAME = "/opt/Plone-4.3/zeocluster/Extensions/" FILENAME = "ccdet.dat" MAXROWS = 100000000 TRANSSIZE = 50 TRANSSIZE_FOR_READING = 5000 FOLDERID = 'cbrf-folder' logger = logging.getLogger('ccdet_mem') html_escape_table = { "&": "&amp;", } def html_escape(text):...
just starting #last_person_object.setText(last_person_object.getText() + '</table>')
pass # check if need to create a new person object or can edit an existing person object if not allrecs.has_key(current_person_id): allrecs[current_person_id] = {} #logger.info('created new person id %s' % curr...
MarcosCommunity/odoo
comunity_modules/stock_no_negative/model/product.py
Python
agpl-3.0
1,270
0
# -*- coding: utf-8 -*- # # # OpenERP, Open Source Management Solution # Copyright (c) 2015 Vauxoo - http://www.vauxoo.com/ # All Rights Reserved. # info Vauxoo (info@vauxoo.com) # # Coded by: Luis Torres (luis_t@vauxo
o.com) # # # 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 S
oftware Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero G...
AartGoossens/athletic_pandas
tests/algorithms/test_heartrate_models.py
Python
mit
701
0
import pandas as pd import pytest from athletic_pandas.algorithms import heartrate_models def test_heartrate_model(): heartrate = pd.Series(range(50)) power = pd.Series(range(0, 100, 2)) model, predictions = heartrate_models.heartrate_model(heartrate, power) assert mo
del.params['hr_rest'].value == 0.00039182374117378518 assert model.params['hr_max'].value == 195.75616175
654685 assert model.params['dhr'].value == 0.49914432620946803 assert model.params['tau_rise'].value == 0.98614419733274383 assert model.params['tau_fall'].value == 22.975975612579408 assert model.params['hr_drift'].value == 6.7232899323328612 * 10**-5 assert len(predictions) == 50
jumpstarter-io/ceph-deploy
ceph_deploy/hosts/rhel/pkg.py
Python
mit
260
0
from ceph_deploy.util import pkg_managers def install(distro, packages): return pkg_managers.yum( distro.conn,
packages ) def remove(distro, packages):
return pkg_managers.yum_remove( distro.conn, packages )
arosenberg01/asdata
settings.py
Python
mit
279
0.003584
import os DATABASE = { 'drivername': os.environ['NBA_DB_DRIVER'], 'host': os.env
iron['NBA_DB_HOST'], 'port': os.environ['NBA_DB_P
ORT'], 'username': os.environ['NBA_DB_USER'], 'password': os.environ['NBA_DB_PW'], 'database': os.environ['NBA_DB_NAME'], }
securestate/king-phisher
king_phisher/client/widget/managers.py
Python
bsd-3-clause
17,478
0.023058
#!/usr/bin/env python # -*- coding: utf-8 -*- # # king_phisher/client/widget/managers.py # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # n...
ve(active) class MenuManager(object): """ A class that wraps :py:class:`Gtk.Menu` objects and facilitates managing their respective items. """ __slots__ = ('menu', 'items') def __init__(self, menu=None): """ :param menu: An optional menu to start with. If a menu is specified it is used as is, otherwise a ...
sed and is set to be visible using :py:meth:`~Gtk.Widget.show`. :type menu: :py:class:`Gtk.Menu` """ if menu is None: menu = Gtk.Menu() menu.show() self.menu = menu self.items = collections.OrderedDict() def __getitem__(self, label): return self.items[label] def __setitem__(self, label, menu_it...
gpfinley/ensembles
scripts/remove_extraneous_extensions.py
Python
apache-2.0
664
0.00753
""" Renames files in a directory (command line argument) to not have intermediate extensions. Works for cTAKES xmi or xml files if the original file extension has been retained. """ import re import subprocess import sys import os try: d = sys.argv[1] except: print('usage:\npython ' + sys.argv[0] + ' <path-...
put(["ls", d]).split("\n") files = [f for f in files if len(f) and 'TypeSystem' not in f]
for f in files: oldname = f newname = re.sub('(\....)+(\.xm[il])', '\\2', oldname, flags=re.IGNORECASE) subprocess.call(['mv', os.path.join(d, oldname), os.path.join(d, newname)])
pwnbus/scoring_engine
scoring_engine/checks/rdp.py
Python
mit
410
0
from scoring_en
gine.engine.basic_check import BasicCheck, CHECKS_BIN_PATH class RDPCheck(BasicCheck): required_properties = [] CMD = CHECKS_BIN_PATH + '/rdp_check {0} {1} {2} {3}' def command_format(self, properties): account = self.get_random_account(
) return ( account.username, account.password, self.host, self.port, )
paetzke/consolor
tests/test_consolor.py
Python
bsd-2-clause
3,238
0
# -*- coding: utf-8 -*- """ consolor Copyright (c) 2013-2014, Friedrich Paetzke (f.paetzke@gmail.com) All rights reserved. """ from __future__ import print_function from consolor import BgColor, Color, get_line try: from unittest.mock import call, patch except ImportError: from mock import call, patch def...
Red two', '\x1b[0m'), call('None')]) @patc
h('tests.test_consolor.mockable_print') def test_print_concat_bgcolor(mocked_print): mockable_print(BgColor.Red, 'Red') mockable_print('Red two') mockable_print(BgColor.Cyan, 'None') mockable_print(BgColor.Reset) mocked_print.assert_has_calls([call('\x1b[41;1m', 'Red'), ...
takeshineshiro/nova
nova/tests/unit/virt/hyperv/test_vmutilsv2.py
Python
apache-2.0
11,758
0
# Copyright 2014 Cloudbase Solutions Srl # # 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 ...
s._conn.CIM_BaseMetricDefinition.return_value = [ metric_def] self._vmutils.enable_vm_metrics_collection(self._FAKE_VM_NAME) calls = [mock.call(Name=def_name) for def_name
in [self._vmutils._METRIC_AGGR_CPU_AVG, self._vmutils._METRIC_AGGR_MEMORY_AVG]] self._vmutils._conn.CIM_BaseMetricDefinition.assert_has_calls(calls) calls = [] for i in range(len(fake_metric_def_paths)): calls.append(mock.call( Subj...
Bobbyshow/Avoid
screen/menu.py
Python
unlicense
923
0.010834
#-*- coding: utf-8 -*- import pygame.key from pygame.font import Font from lib.base_
screen import BaseScreen, ChangeScreenException from pygame.locals import K_SPACE as SPACE class MenuScreen(BaseScreen): def init_entities_before(self, surfac
e): self.font = Font(None, 30) self.textImg = self.font.render( 'Press SPACE to BEGIN !', 1, (255,255,255) ) surface.blit(self.textImg, (200,200)) def execute(self, surface): if pygame.key.get_pressed()[SPACE] == 1: raise Chang...
pavlenko-volodymyr/codingmood
codemood/social/migrations/0004_auto__chg_field_post_link.py
Python
mit
4,577
0.007865
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'Post.link' db.alter_column(u'social_post', 'link', self.gf('django.db.models.fields.URLFi...
'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fi...
, 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('d...
Galexrt/zulip
zerver/tests/test_muting.py
Python
apache-2.0
4,650
0.00086
import ujson from django.http import HttpResponse from mock import p
atch from typing import Any, Dict from zerver.lib.test_classes import ZulipTestCase from zerver.lib.stream_topic import StreamTopicTarget from zerver.models import ( get_realm, get_stream, get_stream_recipient, get_user, Recipient, UserProfile, ) from zerver.lib
.topic_mutes import ( add_topic_mute, get_topic_mutes, topic_is_muted, ) class MutedTopicsTests(ZulipTestCase): def test_user_ids_muting_topic(self): # type: () -> None hamlet = self.example_user('hamlet') cordelia = self.example_user('cordelia') realm = hamlet.realm ...
mrklein/vtk-plot
plot-vtk.py
Python
unlicense
2,344
0
#!/usr/bin/env python def load_velocity(filename): import os if not os.path.exists(filename): return None from numpy import zeros from vtk import vtkPolyDataReader, vtkCellDataToPointData reader = vtkPolyDataReader() reader.SetFileName(filename) reader.ReadAllVectorsOn() rea...
) # Extracting triangulation information triangles = data.GetPolys().GetData() points = data.GetPoints() # Mapping data
: cell -> point mapper = vtkCellDataToPointData() mapper.AddInputData(data) mapper.Update() mapped_data = mapper.GetOutput() # Extracting interpolate point data udata = mapped_data.GetPointData().GetArray(0) ntri = triangles.GetNumberOfTuples()/4 npts = points.GetNumberOfPoints() n...
dimagi/commcare-hq
corehq/form_processor/tests/test_sql_update_strategy.py
Python
bsd-3-clause
8,947
0.001229
from django.test import TestCase from freezegun import freeze_time from unittest.mock import patch from testil import eq from corehq.util.soft_assert.core import SoftAssert from casexml.apps.case.exceptions import ReconciliationError from casexml.apps.case.xml.parser import CaseUpdateAction, KNOWN_PROPERTIES from core...
DOMAIN = 'update-strategy-test-' + uuid.uuid4().hex USER_ID = 'mr_wednesday_' @classmethod def setUpClass(cls): super(SqlUpdateStrategyTest, cls).setUpClass() FormProcessorTestUtils.delete_all_sql_forms() FormProcessorTestUtils.delete_all_sql_cases() @classmethod def te...
_all_sql_forms() FormProcessorTestUtils.delete_all_sql_cases() super(SqlUpdateStrategyTest, cls).tearDownClass() @patch.object(SoftAssert, '_call') def test_reconcile_transactions(self, soft_assert_mock): """ tests a transanction with an early client date and late server date """ ...
elopezga/ErrorRate
ivi/agilent/agilentDSA91204A.py
Python
mit
1,632
0.004289
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2012-2014 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the...
o whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED T...
IGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from .agilent90000 import * class agilentDSA91204A(agilent90000): "Agilent Infiniium DSA...
Philippe12/external_chromium_org
tools/telemetry/telemetry/core/backends/chrome/extension_dict_backend.py
Python
bsd-3-clause
2,641
0.008709
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import re import weakref from telemetry.core import extension_page from telemetry.core.backends.chrome import inspector_backend class ExtensionN...
onObject(extension_id) assert extension_object self._extension_dict[extension_id] = extension_object return extension_object def __contains__(self, extension_id): return extension_id in self.GetExtensionIds() @staticmethod def _ExtractExtensionId(url): m = re.match(r"(chrome-extension://...
rl' not in extension_info: return None return ExtensionDictBackend._ExtractExtensionId(extension_info['url']) def _CreateExtensionObject(self, extension_id): extension_info = self._FindExtensionInfo(extension_id) if not extension_info or not 'webSocketDebuggerUrl' in extension_info: raise Ext...
liqd/adhocracy3.mercator
src/adhocracy_meinberlin/adhocracy_meinberlin/resources/kiezkassen.py
Python
agpl-3.0
1,552
0
"""Mercator proposal.""" from adhocracy_core.resources import add_resource_type_to_registry from adhocracy_core.resources import process from adhocracy_core.resources import proposal from adhocracy_core.sheets.geo import IPoint from adhocracy_core.sheets.geo import ILocationReference from adhocracy_core.sheets.image im...
ue, extended_sheets=( ILocationReference, IImageR
eference, ), default_workflow='kiezkassen', ) def includeme(config): """Add resource type to content.""" add_resource_type_to_registry(proposal_meta, config) add_resource_type_to_registry(proposal_version_meta, config) add_resource_type_to_registry(process_meta, config)
plotly/plotly.py
packages/python/plotly/plotly/validators/cone/_cmid.py
Python
mit
443
0
import _plotly_utils.basevalidators class CmidValidator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, p
lotly_name="cmid", parent_name="cone", **kwargs): super(CmidValidator, self).__init__( plotly_name=plotly_n
ame, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), implied_edits=kwargs.pop("implied_edits", {}), **kwargs )
cs411sp15vmnjhtdw/MeetU
CS411Project/urls.py
Python
mit
837
0
"""CS411Project URL Configuration The `urlpatterns` list routes URLs to views. Fo
r more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a...
URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from meetu import urls as m...
mattr555/AtYourService
main/migrations/0011_auto__add_index_organization_name__add_index_userevent_date_end__add_i.py
Python
mit
8,705
0.007007
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding index on 'Organization', fields ['name'] db.create_index('main_organization', ['name']) # ...
', [], {'ma
x_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'main.event': { ...
nwjs/chromium.src
third_party/android_deps/libs/org_apache_maven_wagon_wagon_http_shared/3pp/fetch.py
Python
bsd-3-clause
1,402
0.000713
#!/usr/bin/env python # Copyright 2021 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This is generated, do not edit. Update BuildConfigGenerator.groovy and # 3ppFetch.template instead. from __future__ import print_fun...
ext = '.jar' elif _FILE_URL.endswith('.aar'): ext = '.aar' else: raise Exception('Unsupported extension for %s' % _FILE_URL) partial_manifest = { 'url': [_FILE_URL], 'name': [_FILE_NAME], 'ext': ext, } prin
t(json.dumps(partial_manifest)) def main(): ap = argparse.ArgumentParser() sub = ap.add_subparsers() latest = sub.add_parser("latest") latest.set_defaults(func=lambda _opts: do_latest()) download = sub.add_parser("get_url") download.set_defaults( func=lambda _opts: get_download_url(o...
maartenbreddels/vaex
tests/ml/sklearn_test.py
Python
mit
11,265
0.002929
import pytest import vaex pytest.importorskip("sklearn") from vaex.ml.sklearn import Predictor, IncrementalPredictor import numpy as np # Regressions from sklearn.linear_model import LinearRegression, Ridge, Lasso, SGDClassifier, SGDRegressor from sklearn.svm import SVR from sklearn.ensemble import AdaBoostRegressor,...
f_test = df.ml.
train_test_split(test_size=0.1, verbose=False) features = df_train.column_names[:4] target = 'class_' incremental = IncrementalPredictor(model=SGDClassifier(loss='log', learning_rate='constant', eta0=0.01), features=features, ta...
Oliver-Lab/snakemakelib-oliver
snakemakelib_oliver/odo/geo.py
Python
mit
333
0
import re from blaze import resource, DataFrame impo
rt pandas as pd from snakemakelib.odo.pandas import annotate_by_uri @resource.register('.+fastq.summary') @annotate_by_uri def resource_fastqc_summary(uri, **kwargs): with open(ur
i): data = pd.read_csv(uri, sep=",", index_col=["fileName"]) return DataFrame(data)
metno/satistjenesten
setup.py
Python
mit
1,107
0.009033
from setuptools import setup from setuptools import find_packages import os requirements = ['numpy', 'netCDF4', 'pyresample', 'pyyaml', 'pillow', 'rasterio'] readme_contents = "" setup( name='satistjenesten', version=0.5, ...
n='Istjenesten satellite processing suite', packages=['satistjenesten'], data_files=[os.pa
th.join(os.path.dirname(__file__), 'test_data', 'DroidSans.ttf')], long_description=readme_contents, install_requires=requirements, test_suite='tests', scripts=['scripts/amsr2_mosaic.py', 'scripts/mitiff2geotiff.py', 'scripts/mitiff_mosaic.py'], classifiers=[ 'Development Status ::...
Grassboy/plugin.video.plurkTrend
youtube_dl/extractor/gamekings.py
Python
mit
1,331
0.003005
import re from .common import InfoExtractor class GamekingsIE(InfoExtractor): _VALID_URL = r'http://www\.gamekings\.tv/videos/(?P<name>[0-9a-z\-]+)' _TEST = { u"url": u"http://www.gamekings.tv/videos/phoenix-wright-ace-attorney-dual-destinies-review/", u'file': u'20130811.mp4', # MD5 ...
mobj = re.match(self._VALID_URL, url) name = mobj.group('name') webpage = self._download_webpage(url, name) video_url = self._og_search_video_url(webpage) video = re.search(r'[0-9]+', video_url) video_id = video.g
roup(0) # Todo: add medium format video_url = video_url.replace(video_id, 'large/' + video_id) return { 'id': video_id, 'ext': 'mp4', 'url': video_url, 'title': self._og_search_title(webpage), 'description': self._og_search_descriptio...
DePierre/owtf
install/install.py
Python
bsd-3-clause
10,142
0.003352
#!/usr/bin/env python import os import sys import time import platform import argparse from datetime import datetime from space_checker_utils import wget_wrapper import ConfigParser def create_directory(directory): """Create parent directories as necessary. :param directory: (~str) Path of directory to be ...
all_using_pip(requirements_file): """Install pip libraries as mentioned in a requirements file. :param requirements_file: (~str) Path to requirements file - in which libraries are listed. :retur
n: True - if installation successful, and False if not. """ # Instead of using file directly with pip which can crash because of single library return run_command("sudo -E pip2 install --upgrade -r %s" % requirements_file) def install_restricted_from_cfg(config_file): """Install restricted tools and d...
ncliam/serverpos
openerp/addons/report_webkit/webkit_report.py
Python
agpl-3.0
16,744
0.005256
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2010 Camptocamp SA (http://www.camptocamp.com) # All Right Reserved # # Author : Nicolas Bessi (Camptocamp) # Contributor(s) : Florent Xicluna (Wingo SA) # # WARNING: This program as such is intended...
'wkhtmltopdf'] command.append('--quiet') # default to UTF-8 encoding. Use <meta charset="latin-1"> to override. command.extend(['--encoding', 'utf-8']) if header : with tempfile.NamedTemporaryFile(suffix=".head.html", delete=Fals...
tml(header.encode('utf-8'))) file_to_del.append(head_file.name) command.extend(['--header-html', head_file.name]) if footer : with tempfile.NamedTemporaryFile(suffix=".foot.html", delete=False) as foot_file: foot_fi...
zedlander/flake8-commas
test/data/keyword_before_parenth_form/py2_bad.py
Python
mit
273
0
# Requires trailing commas in
Py2 but syntax error in Py3k def True( foo ): True( foo ) def Fa
lse( foo ): False( foo ) def None( foo ): None( foo ) def nonlocal ( foo ): nonlocal( foo )
exter/pycover
tools/timed_wrapper.py
Python
mit
386
0.015544
# __author__ = 'Exter' from functools import wraps import time def timed(f): @wraps(f) def wrapper(*args, **kwds): current_milli_time = lambda: int(round(time.time() * 1000)) start = current_milli_time() result = f(*
args, **kwds) elapsed = current_milli_time() - start print "%s too
k %d ms to finish" % (f.__name__, elapsed) return result return wrapper
jml/flocker
flocker/common/_net.py
Python
apache-2.0
1,289
0
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Network utilities. """ from ipaddr import IPAddress import netifaces def ipaddress_from_string(ip_address_string): """ Parse an IPv4 or IPv6 address string and return an IPAddress instance. Remove the "embedded scope id" from IPv6 addr...
for address_family in (netifaces.AF_INET, netifaces.AF_INET6): family_addresses = addresses.get(address_family) if not family_addresses: continue for address in family_addresses: ips.add(ipaddress_from_string(address['addr']))
return ips
danabauer/app-on-openstack
code/worker/deploy.py
Python
mit
331
0
#!/usr/bin/e
nv python import os from watermark.config import config as conf from watermark import connect config_name = os.getenv('WM_CONFIG_ENV') or 'default' config = conf[config_name]() conn = connect.get_connection(config) conn.message.create_queue(name=config.NAME) print("{name} queue created".format(name=config.N
AME))
NixaSoftware/CVis
venv/lib/python2.7/site-packages/pandas/io/sas/sasreader.py
Python
apache-2.0
2,558
0.000391
""" Read SAS sas7bdat or xport files. """ from pandas import compat from pandas.io.common import _stringify_path def read_sas(filepath_or_buffer, format=None, index=None, encoding=None, chunksize=None, iterator=False): """ Read SAS files stored as either XPORT or SAS7BDAT format files. Param...
"a format string") filepath_or_buffer = _stringify_path(filepath_or_buffer) if not isinstance(filepath_or_buffer, compat.string_types): raise ValueError(buffer_error_msg) try: fname = filepath_or_buffer.lower() if fname.endswith(".xpt"): ...
at" else: raise ValueError("unable to infer format of SAS file") except: pass if format.lower() == 'xport': from pandas.io.sas.sas_xport import XportReader reader = XportReader(filepath_or_buffer, index=index, encoding=enc...
QuanticPotato/vcoq
plugin/coq.py
Python
gpl-2.0
3,667
0.035451
import xml.etree.ElementTree as XMLFactory import subprocess import os import signal import utils from buffers import Text, Color class CoqManager: def __init__(self, WM): # The coqtop process self.coqtop = None # The string return by 'coqtop --version' self.coqtopVersion = '' # The windows manager insta...
es (query) ..") def sendChunk(self, chunk): xml = XMLFactory.Element('call') xml.set('val', 'interp') xml.set('id', '0') xml.text = chunk.decode('utf-8') response = self.sendXML(xml) if response != None: if response.get('val') == 'good': #response_info = response.find('string') #if not response...
# rep = Text(response_info.text) # self.windowsManager.output.updateWindowContent("Console", rep, True) return True elif response.get('val') == 'fail': err = Text(str(response.text)) err.setColor(Color.red) self.windowsManager.output.updateWindowContent("__Console__", err, True) else: uti...
kosior/eventful
eventful/events/tests/factories.py
Python
mit
2,221
0.00045
import factory from django.contrib.auth.models import User from django.utils import timezone from events.models import Event, EventInvite from userprofiles.models import FriendRequest class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User class Params: join_event = No...
= 'future': return timezone.now() + timezone.timedelta(hours=24)
elif obj.past_or_future == 'past': return timezone.now() - timezone.timedelta(hours=24) created_by = factory.SubFactory(UserFactory) title = 'Event title' start_date = factory.LazyAttribute(lambda o: EventFactory._get_date_time(o)) class FriendshipFactory(factory.DjangoModelFactory): ...
go2net/PythonBlocks
components/propertyeditor/QPropertyModel.py
Python
mit
7,747
0.013037
from PyQt4 import QtCore, QtGui from components.propertyeditor.Property import Property from components.RestrictFileDialog import RestrictFileDialog from PyQt4.QtCore import * from PyQt4.QtGui import * import sys, os class QPropertyModel(QtCore.QAbstractItemModel): def __init__(self, parent): super(QProp...
ent == None): parent = self.rootItem for item in parent.childItems: if(item.name == name): return item return None def headerData (self, section, orientation, role) : if (orientation == QtCore.Qt.Horizontal and role == QtCore....
return "Property" elif (section == 1) : return "Value" return None # QtCore.QVariant(); def flags (self, index ): if (not index.isValid()): return QtCore.Qt.ItemIsEnabled; item = index.internalPointer(); ...
OpenAssets/openassets
openassets/protocol.py
Python
mit
19,047
0.002888
# -*- coding: utf-8; -*- # # The MIT License (MIT) # # Copyright (c) 2014 Flavien Charlon # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associat
ed documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SO...
LEEClab/LS_CORRIDORS
old_versions/before_v1_0_0/log_def.py
Python
gpl-2.0
2,333
0.045864
import os from datetime import datetime os.chdir(r"E:\__data_2015\___john\Desenvolvimentos\aplications\Aplicacoes_grass\LSCorridors\___dados_cortados_teste_desenvolvimento") now = datetime.now() # INSTANCE day_start=now.day month_start=now.month year_start=now.year hour_start=now.hour # GET START HOUR minuts_start=n...
d=now.hour # GET end HOUR minuts_end=now.minute #GET end MINUTS second_end=now.second #GET end seconds txt_log.write("End time : Year "+`year_end`+"-Month "+`month_end`+"-Day "+`day_end`+" ---- time: "+`hour
_end`+":"+`minuts_end`+":"+`second_end`+"\n") diference_time=`month_end - month_start`+" month - "+`abs(day_end - day_start)`+" Day - "+" Time: "+`abs(hour_end - hour_start)`+":"+`abs(minuts_end - minuts_start)`+":"+`abs(second_end - second_start)` txt_log.write("Processing time : "+diference_time+"\n\n") txt_log.wri...
philotas/opencaster
tutorials/psi-generation/firstsdt.py
Python
gpl-2.0
2,269
0.032613
#! /usr/bin/env python # # Copyright (C) 2008 Lorenzo Pal
lara, l.pallara@avalpa.com # # 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) an
y later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # ...
tgbugs/pyontutils
ilxutils/ilxutils/database_client.py
Python
mit
2,525
0.00198
from collections import defaultdict import pandas as pd import pickle from sqlalchemy import create_engine, inspect, Table, Column from sqlalchemy.engine.url import make_url from sys import exit class DatabaseClient: """ Takes care of the database pass opening to find the url and can query the respected ...
k_size = 100000 offset = 0 data = defaultdict(lambda : defaultdict(list)) with open(output, 'wb') as outfile: query = query.replace(';', '') query += """ LIMIT {chunk_size} OFFSET {offs
et};""" while True: print(offset) query = query.format( chunk_size=chunk_size, offset=offset ) df = pd.read_sql(query, self.engine) pickle.dump(df, outfile) offset += chunk...
timeyyy/orchestra.nvim
rplugin/python3/orchestra/util.py
Python
unlicense
7,671
0.001825
import os import wave import platform import threading from functools import wraps import time import pyaudio CUSTOMCMDS = (), AUTOCMDS = ( 'BufNewFile', 'BufReadPre', 'BufRead', 'BufReadPost', 'BufReadCmd', 'FileReadPre', 'FileReadPost', 'FileReadCmd', 'FilterReadPre', 'FilterReadPost', 'StdinReadPre', ...
args) except Exception: return False def get_audio_parts(file): ''' see orchestra.__init__.ensemble ''' def plus1(file): path, ext = os.path.splitext(file) split = path.split('_') old_num = etb(int, split[-1]) if not old_num: split.append('1') ...
parts.append(file) part = plus1(file) while os.path.exists(part): parts.append(part) part = plus1(part) return parts class InMemoryWriter(list, object): """ simplify editing files On creation you can read all contents either from: an open file, a list a path/...
pypa/warehouse
warehouse/search/queries.py
Python
apache-2.0
3,381
0.000592
# Licensed under the Apache L
icense, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is
distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from elasticsearch_dsl import Q SEARCH_FIELDS = [ "author", "author_email", "descri...
patmun/pynetdicom
netdicom/DIMSEprovider.py
Python
mit
4,422
0.000678
# # Copyright (c) 2012 Patrice Munger # This file is part of pynetdicom, released under a modified MIT license. # See the file license.txt included with this distribution, also # available at http://pynetdicom.googlecode.com # import DIMSEmessages import DIMSEparameters from DIMSEmessages import DIMSEMessage fro...
age() if primitive.__class__ == DIMSEparameters.C_GET_ServiceParameters: if primitive.MessageID is not None: dimse_msg = DIMSEmessages.C_GET_RQ_Message()
else: dimse_msg = DIMSEmessages.C_GET_RSP_Message() if primitive.__class__ == DIMSEparameters.C_MOVE_ServiceParameters: if primitive.MessageID is not None: dimse_msg = DIMSEmessages.C_MOVE_RQ_Message() else: dimse_msg = DIMSEmessages.C_MOVE...
TinEye/tineyeservices_python
tineyeservices/mobileengine_request.py
Python
mit
1,115
0
# -*- coding: utf-8 -*- # Copyright (c) 2018 TinEye. All rights reserved worldwide. from .matchengine_request import MatchEngineRequest class MobileEngineRequest(MatchEngineRequest): """ Class to send requests to a MobileEngine API. Adding an image using data: >>> from tineyeservices import Mob...
t(api_url='http://localhost/rest/') >>> image = Image(filepath='/path/to/image.jpg') >>> api.add_image(images=[image]) {u'error': [], u'method': u'add', u'result': [], u'status': u'ok'} Searching for an image using an image URL: >>> api.search
_url(url='https://tineye.com/images/meloncat.jpg') {'error': [], 'method': 'search', 'result': [{'filepath': 'match1.png', 'score': '97.2', 'overlay': 'overlay/query.png/match1.png[...]'}], 'status': 'ok'} """ def __repr__(self): ...
FNNDSC/roi_tag
roi_gcibs.py
Python
mit
37,159
0.010603
#!/usr/bin/env python ''' 'roi_gcibs.py' compares two groups informed by an a priori bootstrap analysis. ''' import os import sys import argparse import tempfile, shutil import json import pprint import copy from collections import defaultdict from _common import systemMisc a...
f._str_pval,
self._str_statFunc, self._str_surface, self._str_hemi) def namespec(self, *args): ''' Return the namespec based on internal pipeline._str_* variables. ''' str_sep = "-" ...
dims/heat
heat/db/sqlalchemy/migrate_repo/versions/043_migrate_template_versions.py
Python
apache-2.0
2,285
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
sion = Session() meta = sqlalchemy.MetaData(bind=migrate_engine) templ_table = sqlalchemy.Table('raw_template', meta, autoload=True) raw_templates = templ_table.select().execute() # NOTE (sdake) 2014-04-24 is the date of the Icehouse release
. It is # possible that folks could continue to make errors in their templates # right up until the release of Icehouse. For stacks with version dates # in the future, they remain unlistable. This is to prevent future # breakage when new versions come out patch_date = time.strptime('2014-04-24', ...
kubeflow/kubeflow
py/kubeflow/kubeflow/ci/notebook_servers/notebook_server_jupyter_scipy_tests.py
Python
apache-2.0
1,826
0.001095
""""Argo Workflow for testing notebook-server-jupyter-scipy OCI image""" from kubeflow.kubef
low.ci import workflow_utils from kubeflow.testing import argo_build_util class Builder(workflow_utils.ArgoTestBuilder): def __init__(self, name=None, namespace=None, bucket=None, test_target_name=None, **kwargs): super().__init__(name=name, namespace=namespace, bucket=bucket, ...
workflow = self.build_init_workflow(exit_dag=False) task_template = self.build_task_template() # Test building notebook-server-jupyter-scipy image using Kaniko dockerfile = ("%s/components/example-notebook-servers" "/jupyter-scipy/Dockerfile") % self.src_dir con...
ssamot/vgdl_competition
src/server/db_utils.py
Python
gpl-3.0
3,033
0.012199
#!/usr/bin/python # Python DB APIs: #for more: http://www.mikusa.com/python-mysql-docs/index.html #and more: http://zetcode.com/db/mysqlpython/ #and else: http://mysql-python.sourceforge.net/MySQLdb.html import MySQLdb as mdb import itertools from pprint import pprint import ConfigParser def db_connect(properties_fil...
Gets all game info from a given game ID. Data returned in a dictionary. def get_game_info(db, game_id): #This cursor allows access as in a dictionary: cur = db.cursor(mdb.cursors.DictCursor) cur.execute
("SELECT * from games where game_id = %s", (game_id)) game_data = cur.fetchone() return game_data # Gets all info from all levels given a game ID. Data returned in array. def get_levels_from_game(db, game_id): #This cursor allows access as AN ARRAY: cur = db.cursor() cur.execute("SELECT * f...