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
melrief/Hadoop-Log-Tools
hadoop/log/convert/libjobevent.py
Python
apache-2.0
1,665
0.032432
def parse_event(raw_event,preserve_backslash=False,preserve_dot=False): in_string = False words = [] d = {} key = None curr = [] for c in raw_event: if c == '\\' and not preserve_backslash: continue elif c == '"': in_string = not in_string elif c == ' ': if in_string: c...
se: word = ''.join(curr) if preserve_dot or word != '.': words.append( ''.join(curr) ) curr = [] elif c == '=': key = ''.join(curr) curr = [] else: curr.append(c) if in_string: curr.append(c) else: if key: d[key] = ''.join(curr) k...
nters(counters): raw_counter_families = counters[1:-1].split('}{') counter_families = {} for raw_family in raw_counter_families: splitted = raw_family.split('[') name,desc = decodeCounterKey( splitted[0] ) raw_counters = [s[:-1] if s[-1] == ']' else s for s in splitted[1:]] counters = {} for r...
kiwifb/numpy
numpy/core/tests/test_multiarray.py
Python
bsd-3-clause
244,600
0.000773
from __future__ import division, absolute_import, print_function import collections import tempfile import sys import shutil import warnings import operator import io import itertools import ctypes import os if sys.version_info[0] >= 3: import builtins else: import __builtin__ as builtins from decimal import D...
_equal(self.one.dtype, np.dtype(np.int_)) assert_equal(self.three.dtype, np.dtype(np.float_)) assert_equal(self.one.dtype.char, 'l') assert_equal(self.three.dtype.char, 'd') self.assertTrue(self.three.dtype.str[0] in '<>') assert_equal(self.one.dtype.str[1], 'i') assert_e...
_int_subclassing(self): # Regression test for https://github.com/numpy/numpy/pull/3526 numpy_int = np.int_(0) if sys.version_info[0] >= 3: # On Py3k int_ should not inherit from int, because it's not # fixed-width anymore assert_equal(isinstance(numpy_int, i...
shanot/imp
modules/core/test/test_surface_mover.py
Python
gpl-3.0
2,528
0.000396
import IMP import IMP.algebra import IMP.core import IMP.atom import IMP.test class Tests(IMP.test.TestCase): """Tests for SurfaceMover.""" def test_init(self): """Test creation of surface mover."""
m = IMP.Model() surf = IMP.core.Surface.setup_particle(IMP.Particle(m)) surf.set_coordinates_are_optimized(True) surf.set_normal_is_optimized(True) mv = IMP.core.SurfaceMover(
surf, 1, .1, 1.) mv.set_was_used(True) def test_propose_move(self): """Test proposing move alters center and normal.""" m = IMP.Model() surf = IMP.core.Surface.setup_particle(IMP.Particle(m)) n = surf.get_normal() c = surf.get_coordinates() surf.set_coordinat...
opendata-swiss/ckanext-geocat
ckanext/geocat/utils/search_utils.py
Python
agpl-3.0
5,592
0
from collections import namedtuple import ckan.plugins.toolkit as tk from ckan import model from ckan.model import Session import json OgdchDatasetInfo = namedtuple('OgdchDatasetInfo', ['name', 'belongs_to_harvester', 'package_id']) def get_organization_slug_for_harvest_source(harvest_s...
ras(extras, key): if extras: extras_reduced_to_key = [item.get('value') for item in extras if item.get('key') == key] if extras_reduced_to_key: return extras_reduced_to_key[0] return None def get_value_from_object_ex...
ces_to_ids(pkg_dict, pkg_info): existing_package = \ tk.get_action('package_show')({}, {'id': pkg_info.package_id}) existing_resources = existing_package.get('resources') existing_resources_mapping = \ {r['id']: _get_resource_id_string(r) for r in existing_resources} for resource in pkg_...
evernym/zeno
plenum/test/common/test_transactions.py
Python
apache-2.0
450
0
from plenum.commo
n.constants import NODE, NYM from plenum.common.transactions import PlenumTransactions def testTransactionsAreEncoded(): assert NODE == "0" assert NYM == "1" def testTransactionEnumDecoded(): assert PlenumTransactions.NODE.name == "NODE" assert PlenumTransactions.NYM.name == "NYM" def testTransact...
assert PlenumTransactions.NYM.value == "1"
amurzeau/streamlink-debian
src/streamlink/plugins/webtv.py
Python
bsd-2-clause
2,658
0.001129
import base64 import binascii import logging import re from Crypto.Cipher import AES from streamlink.plugin import Plugin, pluginmatcher from streamlink.plugin.api import validate from streamlink.stream.hls import HLSStream from streamlink.utils.crypto import unpad_pkcs5 from streamlink.utils.parse import parse_json ...
if variant: yield from variant.items() else: # and if that fails, try it as a plain HLS stream yield 'live', HLSStream(self.session, url, headers=headers) except OSError: ...
__ = WebTV
lincolnnascimento/crawler
crawler/wsgi.py
Python
apache-2.0
389
0.002571
""" WSGI conf
ig for crawler project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "crawler.settings") from django.core.wsgi import
get_wsgi_application application = get_wsgi_application()
Seairth/Orochi
assembler/__init__.py
Python
gpl-3.0
11,327
0.005562
import re from .state import State from .expression import ConstantExpression __all__ = ["assemble"] _const_parser = None def _evaluate_d(expression : str, state : State) -> int: value = _get_register(expression) or state.GetLabelAddress(expression) if not value: value = _const_parser.Evaluate(expr...
if name not in lang.registers else lang.registers[name] def assemble(source, binary_format="binary", hub_offset=0, syntax_version=1): global _const_parser state = State() pending = [] output = [] if binary_format != "raw": state.HubAddress = 0x10 else: sta
te.HubAddress = int(hub_offset) _const_parser = ConstantExpression(state) # PASS 1 for line in source: state.LineNumber += 1 if "'" in line: line = line[:line.index("'")] # remove comments if line == "" or str.isspace(line): # ignore empty line...
cheral/orange3
Orange/canvas/application/tests/test_schemeinfo.py
Python
bsd-2-clause
680
0.002941
from ...scheme import Scheme from ..schemeinfo import SchemeInfoDialog from ...gui import test class TestSchemeInfo(test.QAppTestCase): def test_scheme_info(self): scheme = Scheme(title="A Scheme", description="A String\n") dialog = SchemeInfoDialog() dialog.setScheme(scheme) stat...
status == dialog.Accepted: self.assertEqual(scheme.title.strip(), s
tr(dialog.editor.name_edit.text()).strip()) self.assertEqual(scheme.description, str(dialog.editor.desc_edit \ .toPlainText()).strip())
Onager/artifacts
tests/test_lib.py
Python
apache-2.0
1,770
0.00791
# -*- coding: utf-8 -*- """Shared functions and classes for testing.""" from __future__ import unicode_literals import os import shutil import tempfile import unittest class BaseTestCase(unittest.TestCase): """The base test case.""" _DATA_PATH = os.path.join(os.getcwd(), 'data') _TEST_DATA_PATH = os.path.joi...
atement.""" shutil.rmtree(self.name, True)
stefanv/aandete
app/lib/paste/script/templates.py
Python
bsd-3-clause
10,088
0.001685
from __future__ import print_function # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php import sys import os import inspect from . import copydir from . import command from paste.util.template import ...
rted_vars def read_vars(self, command=None): if self._read_vars is not None: return self._read_vars assert (not self.read_vars_from_templates or self.use_cheetah), ( "You can only read variables from templates if using Cheetah") if not self.read_vars_...
f.vars return self.vars vars = self.vars[:] var_names = [var.name for var in self.vars] read_vars = find_args_in_dir( self.template_dir(), verbose=command and command.verbose > 1).items() read_vars.sort() for var_name, var in read_vars: ...
amlyj/pythonStudy
2.7/crawlers/jkxy/jk_utils.py
Python
mit
4,771
0.002144
# -*- coding=utf-8 -*- import requests import os import json import sys import time reload(sys) sys.setdefaultencoding('utf8') download_base_url = 'http://www.jikexueyuan.com/course/video_download' cookie_map = 'gr_user_id=eb91fa90-1980-4500-a114-6fea026da447; _uab_collina=148758210602708013401536; connect.sid=s%3AsR...
载:%s 失败' % file_path return 500 else: print u'%s 请求失败,状态%d' % (download_url, response.status_code) return 500 except Exception, e: print u'%s 请求失败,\n异常信息:%s' % (download_ur
l, e) return 500 def create_dir(path): if not os.path.exists(path): try: os.makedirs(path) except Exception, e: print u'文件夹%s 创建失败;\n %s' % (path, e) else: print u'文件夹%s 已经存在' % path def parent_dir(path): if path[-1] == '/': path = path[0:-1] r...
rwl/PyCIM
CIM15/IEC61970/Informative/InfWork/Request.py
Python
mit
5,609
0.002318
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
self.corporateCode = corporateCode self._ErpQuoteLineItem = None self.ErpQuoteLineItem = ErpQuoteLineItem self._Projects = [] self.Projects = [] if Projects is None else Projects self._Organisation = None self.Organisation = Organisat
ion self._Works = [] self.Works = [] if Works is None else Works super(Request, self).__init__(*args, **kw_args) _attrs = ["actionNeeded", "priority", "corporateCode"] _attr_types = {"actionNeeded": str, "priority": str, "corporateCode": str} _defaults = {"actionNeeded": '', "prio...
google/uncertainty-baselines
experimental/single_model_uncertainty/flags.py
Python
apache-2.0
8,929
0.009184
# coding=utf-8 # Copyright 2022 The Uncertaint
y Baselines Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain
a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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 sp...
eladnoor/ms-tools
james/isotope_util.py
Python
mit
1,554
0.01287
# -*- coding: utf-8 -*- """ Created on Wed Sep 30 14:32:42 2015 @author: noore """ import numpy as np from scipy.misc import comb # comb(N,k) = The number of combinations of N things taken k at a time THETA = 0.011 # the natural abundance of 13C among the two isotopes (13C and 12C). def compute_fractions(counts): ...
isotope starting from M+0 Returns:
fractions - a list of values between 0..1 that represent the fraction of each isotope from the total pool, after correcting for the natural abundance of 13C """ N = len(counts)-1 F = np.matrix(np.zeros((N+1, N+1))) for i in range(N+1): for j...
jensonjose/utilbox
utilbox/os_utils/dir_utils.py
Python
mit
7,866
0.003051
""" Utility module to manipulate directories. """ import os import types import shutil __author__ = "Jenson Jose" __email__ = "jensonjose@live.in" __status__ = "Alpha" class DirUtils: """ Utility class containing methods to manipulate directories. """ def __init__(self): pass @staticme...
IFIED": str(last_modified_time), "SIZE": str(file_size), "NAME": str(os.path.basename(dir_path)), "PARENT_DIRECTORY": str(os.path.dirname(d
ir_path)), "FULL_PATH": str(dir_path)} return False
dhuang/incubator-airflow
airflow/providers/amazon/aws/operators/ecs.py
Python
apache-2.0
17,123
0.002686
# # 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...
ort sys from collections import deque from datetime import datetime from typing import Dict, Generator, Optional from botocore.waiter import Waiter from airflow.exceptions i
mport AirflowException from airflow.models import BaseOperator, XCom from airflow.providers.amazon.aws.exceptions import ECSOperatorError from airflow.providers.amazon.aws.hooks.base_aws import AwsBaseHook from airflow.providers.amazon.aws.hooks.logs import AwsLogsHook from airflow.typing_compat import Protocol, runtim...
ab9621/PogoLibrary
pogoInput.py
Python
gpl-3.0
17,129
0.021834
import numpy as np import warnings import subprocess import pogoFunctions as pF import pdb from PolyInterface import poly class PogoInput: def __init__(self, fileName, elementTypes, signals, historyMeasurement, nodes = None, ...
nDims=2, nDofPerNode = None, notes = None, runName = 'pogoJob',
nt = 100, dt = 1e-8, elementTypeRefs = None, materialTypeRefs = None, orientationRefs = None, elementParameters = None, materials = [[0,7e10,0.34,2700],], orientations = None, ...
mdakin/engine
build/android/gyp/generate_v14_compatible_resources.py
Python
bsd-3-clause
11,922
0.008136
#!/usr/bin/env python # # 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. """Convert Android xml resources to API 14 compatible. There are two reasons that we cannot just use API 17 attributes, so we are ge...
Start' : 'layout_alignLeft', 'layout_marginStart' : 'layout_marginLeft',
'layout_alignParentStart' : 'layout_alignParentLeft', 'layout_toStartOf' : 'layout_toLeftOf', 'paddingEnd' : 'paddingRight', 'drawableEnd' : 'drawableRight', 'layout_alignEnd' : 'layout_alignRight', ...
wandec/grr
gui/views.py
Python
apache-2.0
9,063
0.00982
#!/usr/bin/env python """Main Django renderer.""" import importlib import os import pdb import time from django import http from django import shortcuts from django import template from django.views.decorators import csrf import psutil import logging from grr import gui from grr.gui import api_call_renderers from ...
", 2)[-1] if not help_path: return AccessDenied("Error: Invalid help path.") try: user_record = aff4.FACTORY.Open( aff4.ROOT_URN.Add("users").Add(request.user), "GRRUser", token=BuildToken(request, 60)) settings = user_record.Get(user_record.Schema.GUI_SETTINGS) except IOError: s...
lp(help_path) else: # Serve prebuilt docs using static handler. To do that we have # to resolve static handler's name to an actual function object. static_handler_components = urls.static_handler.split(".") static_handler_module = importlib.import_module(".".join( static_handler_components[0:-...
bobobo80/python-crawler-test
web_get/webget.py
Python
mit
1,636
0.001906
""" 使用requests包装的页面请求 """ import requests from .headers import Headers from proxy import proxy class TimeoutException(Exception): """ 连接超时异常 """ pass class ResponseException(Exception): """ 响应异常 """ pass class WebRequest(object): """ 包装requests """ def __init__(sel...
页面post """ try: resp = requests.post(url, data=payload, headers=self.headers, proxies={'http': 'http://{}'.format(self.proxies)},
timeout=10) return self.check_response(resp) except Exception as e: self.network_error(e) def network_error(self, e): proxy.delete_proxy(self.proxies) print('error: {}'.format(e)) raise TimeoutException('timeout') def check_response(self, resp):...
Sventimir/src-depend
depend.py
Python
apache-2.0
4,469
0.00358
#! /usr/bin/python """Src-depend is a simple tool for sketching source code dependency graphs from source code itself. It iterates through all source code files in given directory, finds import statements and turns them into edges of a dependency graph. Uses graphviz for sketching graphs.""" import argparse import gra...
) plugin = getattr(import_obj, args['lang']) except ImportError: logging.error('Could not find plugin for {}!'.format(args['lang'])) return 1 files = find_source_files(args['target'], plugin.Module.filename_ext, is_excluded) for f in files: with open(f, 'r') as file: ...
odule(file, args['target']) plugin.Module.create_dependency_tree() if args['remove-redundant']: plugin.Module.remove_redundant_dependencies() graph = make_graph(*plugin.Module.registry) graph.format = args['format'] if not args['img_out'] is None: output = graph.render(args['img_ou...
davelab6/pyfontaine
fontaine/charsets/noto_glyphs/notosanssylotinagri_regular.py
Python
gpl-3.0
3,639
0.023633
# -*- coding: utf-8 -*- class Charset(object): common_name = 'NotoSansSylotiNagri-Regular' native_name = '' def glyphs(self): glyphs = [] glyphs.append(0x0039) #glyph00057 glyphs.append(0x0034) #uniA82A glyphs.append(0x0035) #uniA82B glyphs.append(0x0036) #glyp...
#uniA815 glyphs.append(0x001E) #uniA814 glyphs.append(0x0021) #uniA817 glyphs.append(0x0020) #uniA816 glyphs.append(0x001B) #uniA811
glyphs.append(0x001A) #uniA810 glyphs.append(0x001D) #uniA813 glyphs.append(0x001C) #uniA812 glyphs.append(0x0047) #glyph00071 glyphs.append(0x0041) #glyph00065 glyphs.append(0x004C) #uni09E7 glyphs.append(0x0044) #glyph00068 glyphs.append(0x0045) #glyph00...
Mappy/pycnikr
tests/test_pycnik.py
Python
lgpl-3.0
660
0.001515
""" This test illustrate how to generate an XML Mapnik style sheet from a pycnik style sheet written in Python. """ import os from pycnik import pycnik import artefact actual_xml_style_sheet = 'artefacts/style_sheet.xml' expected_xml_style_sheet = 'style_sheet.xml' class TestPycnik(artefact.TestCaseWithArtefacts): ...
pycnik.import_
style('style_sheet.py') pycnik.translate(python_style_sheet, actual_xml_style_sheet) with open(actual_xml_style_sheet) as actual, \ open(expected_xml_style_sheet) as expected: self.assertEquals(actual.read(), expected.read())
codeback/openerp-cbk_sale_commission_filter
__openerp__.py
Python
agpl-3.0
1,616
0.004337
# -*- encoding: utf-8 -*- ############################################################################## # # cbk_crm_information: CRM Information Tab # Copyright (c) 2013 Codeback Software S.L. (http://codeback.es) # @author: Miguel García <miguel@codeback.es> # @author: Javier Fuentes <javier@codeback....
e 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 General...
ng with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Sale Commission Filter', 'version': '0.1', 'author': 'Codeback Software', 'summary': '', 'description' : 'Añade campos para que los filtros ...
anish/buildbot
master/buildbot/test/unit/test_steps_package_rpm_rpmbuild.py
Python
gpl-2.0
5,421
0.001476
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
state_string='RPMBUILD') return self.runStep() def test_define(self): defines = [("a", "1"), ("b", "2")] self.setupStep(rpmbuild.RpmBuild(specfile="foo.spec", define=OrderedDict(defines)))
self.expectCommands( ExpectShell(workdir='wkdir', command='rpmbuild --define "_topdir ' '`pwd`" --define "_builddir `pwd`" --define "_rpmdir ' '`pwd`" --define "_sourcedir `pwd`" --define ' '"_specdir `pwd`" --define "_srcrpmdir ...
wscullin/spack
var/spack/repos/builtin/packages/py-markupsafe/package.py
Python
lgpl-2.1
2,130
0.000939
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
MA 02111-1307 USA ############################################################################## from spack import * class PyMarkupsafe(PythonPackage): """MarkupSafe is a library for Python that implements a unicode string that is aware of HTML escaping rules and can be used to implement automatic string ...
, the Pylons web framework and many more.""" homepage = "http://www.pocoo.org/projects/markupsafe/" url = "https://pypi.io/packages/source/M/MarkupSafe/MarkupSafe-1.0.tar.gz" import_modules = ['markupsafe'] version('1.0', '2fcedc9284d50e577b5192e8e3578355') version('0.23', 'f5ab3deee4c37cd6...
vicnet/weboob
modules/bp/pages/subscription.py
Python
lgpl-3.0
6,761
0.003108
# -*- coding: utf-8 -*- # Copyright(C) 2010-2018 Célande Adrien # # This file is part of a weboob module. # # This weboob module 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 ...
d.split('_')[0] return Attr('//select[@id="numeroCompteRechercher"]/option[contains(text(), "%s")]' % sub_id, 'value'
)(self.doc)
kevink1986/my-first-blog
handlers/signup.py
Python
apache-2.0
1,621
0
from base import BaseHandler from functions import * from models import User class SignupHandler(BaseHandler): """Sign up handler that is used to signup users.""" def get(self): self.render("signup.html") def post(self): error = False self.username = self.request.get("username") ...
ssword != self.password_check: template_vars['error_check'] = "Your passwords didn't match." error = True if not valid_email(self.email):
template_vars['error_email'] = "That's not a valid email." error = True if error: self.render('signup.html', **template_vars) else: u = User.register(self.username, self.password, self.email) ...
chrsrds/scikit-learn
sklearn/neighbors/__init__.py
Python
bsd-3-clause
1,176
0
""" The :mod:`sklearn.neighbors` module implements the k-nearest neighbors algorithm. """ from .ball_tree import BallTree from .kd_tree import KDTree from .dist_metrics import DistanceMetric from .graph import kneighbors_graph, radius_neighbors_graph from .unsupervised import NearestNeighbors from .classification impo...
'KNeighborsRegressor', 'NearestCentroid', 'NearestNeighbors', 'RadiusNeighborsClassifier', 'RadiusNeighborsRegressor', 'kneighbors_graph', 'radius_neighbors_graph', 'KernelDensity',
'LocalOutlierFactor', 'NeighborhoodComponentsAnalysis', 'VALID_METRICS', 'VALID_METRICS_SPARSE']
dhuang/incubator-airflow
docs/build_docs.py
Python
apache-2.0
19,953
0.002356
#!/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 # "Li...
argparse.RawTextHelpFormatter parser.add_argument( '--disable-checks', dest='disable_checks', action='store_true', help='Disables extra checks' ) parser.add_argument( "--package-filter", action="append", help=( "Filter specifying for which packages the documentati...
cumentation') parser.add_argument( '--spellcheck-only', dest='spellcheck_only', action='store_true', help='Only perform spellchecking' ) parser.add_argument( '--for-production', dest='for_production', action='store_true', help='Builds documentation for official releas...
rohinkumar/correlcalc
correlcalc/test.py
Python
mit
3,556
0.003375
# from fileios import * # msg = 'Enter Absolute Path to file: ' # f_name = raw_input(msg).strip() # # path = file_data_and_path(f_name) # if path != None: # print 'Path:',path # from Tkinter import Tk # from tkFileDialog import askopenfilename # # Tk().withdraw() # we don't want a full GUI, so keep the root wind...
print(filename) # try: # with open(filename, 'r') as f: # my_file = f.read() # return my_file # except FileNotFoundError: # print('No such file. Check file name and path and try again.') # # # x = get_filename('TEMPLATE') # print(x) # -*- cod...
"To add test methods. """ # from time import sleep # from halo import Halo # from time import time # # def rocket_launch(): # #spinner = Halo({'spinner': 'shark'}) # spinner = Halo({ # 'spinner': { # 'interval': 100, # 'frames': ['-', '\\', '|', '/', '-'] # } # }) # spinner.start() #...
zrax/pycdc
tests/input/unpack_empty.py
Python
gpl-3.0
45
0
[] = c y = [] for [] in x: BL
OCK
[] = []
seanherron/data-inventory
inventory_project/datasets/lookups.py
Python
mit
625
0.0032
from django.contrib.auth.models import User from selectable.base import ModelLookup from
selectable.registry import registry class UserLookup(ModelLookup): model = User search_fields = ( 'username__icontains', 'first_name__icontains', 'last_name__icontains', ) filters = {'is_active': T
rue, } def get_item_value(self, item): # Display for currently selected item return item.get_full_name() def get_item_label(self, item): # Display for choice listings return u"%s (%s)" % (item.username, item.get_full_name()) registry.register(UserLookup)
melon-li/tools
netem/statdata/statdelay.py
Python
apache-2.0
1,581
0.01265
#!/usr/bin/python #coding:utf-8 import os import sys import re def usage(): help_info="Usage: %s <recinfo_file> <sendinfo_file>" % sys.argv[0] print help_info def main(): try: recinfo_file=sys.argv[1] sendinfo_file=sys.argv[2] except: usage() sys.exit(-1) if ...
ecinfo_file does not exists!" usage() sys.exit(-1) delays = [] cnt = 0 with open(sendinfo_file, 'r') as sf: sinfo = sf.read() with open(recinfo_file, 'r') as rf: rl = rf.readline() while True: rl = rf.readline() if not rl: break ...
= '0': continue pattern = rl_list[0] + ".*?\n" result = re.search(pattern, sinfo) if result: sl = result.group() sl_list = sl.split() delay_time = int(rl_list[3]) - int(sl_list[3]) if delay_time == 0: ...
oudalab/phyllo
phyllo/extractors/gestafrancDB.py
Python
apache-2.0
6,972
0.005164
#http://www.thelatinlibrary.com/gestafrancorum.html #prose import sqlite3 import urllib import re from urllib.request import urlopen from bs4 import BeautifulSoup from phyllo.phyllo_logger import logger # functions are mostly made by Sarah Otts def add_to_database(verse_entries, db): logger.info("Adding {} entri...
entries.append(entry_dict) def get_verses(soup): # if there's nothing in the paragraph, return an empty array if len(soup.contents) == 0: return None para_text = soup.get_text() verses = re.split('\[?[0-9]+[A-Z]?\]?|\[[ivx]+\]', para_text) # "[x]" can contain arabic nu...
= [re.sub(r'^\s+', '', v) for v in verses] # remove whitespace verses = [re.sub(r'^\n', '', v) for v in verses] # remove \n verses = filter(lambda x: len(x) > 0, verses) verses = [v for v in verses] # print verses return verses def get_name_and_author_of_book(soup, url): # attempt to get it...
jacobgasyna/Hackathon2017
basics.py
Python
gpl-3.0
3,296
0.011229
# Copywrite © 2017 Joe Rogge, Jacob Gasyna and Adele Rehkemper #This file is part of Rhythm Trainer Pro. Rhythm Trainer Pro 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...
pen(enPath) #en = ImageTk.PhotoImage(enImage) #enButton = Button(sidebar, image=en, border
=0) #enButton.place(x=25, y=150) #enRestPath = 'EighthResticon.png' #enRestImage = Image.open(enRestPath) #enRest = ImageTk.PhotoImage(enRestImage) #enRestButton = Button(sidebar, image=enRest, border=0) #enRestButton.place(x=100, y=150) snPath = 'SixteenthNoteicon.png' snImage = Image.open(snPath) sn = ImageTk.Ph...
witlox/dcs
controller/ilm/consuela.py
Python
gpl-2.0
4,723
0.003176
import json import logging from logging.config import dictConfig import threading import pickle import redis import aws from settings import Settings def terminate_worker(worker_id, instance, client): result = aws.terminate_machine(instance) if result is None or len(result) == 0: logging.error('could...
(batch_job.state,
batch_job_id)) if batch_job.state == 'spawned' or batch_job.state == 'received' or batch_job.state == 'delayed': return True return False
bugsnag/bugsnag-python
bugsnag/wsgi/__init__.py
Python
mit
147
0
from typing import Dict from urllib.parse import quote def request_path(env: Dict): return quote('/' + env.get('PATH
_INFO', '').ls
trip('/'))
ritchyteam/odoo
addons/mail/mail_group.py
Python
agpl-3.0
12,895
0.004731
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010-today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms o...
('groups', 'Selected group of users')], 'Privacy', required=True, help='This group is visible by non members. \ Invisible groups can add members through the invite button.'), 'group_public_id': fields.many2one('res.groups', string='Authorized Group'), 'group_ids': fields.many2man...
help="Members of those groups will automatically added as followers. "\ "Note that they will be able to manage their subscription manually "\ "if necessary."), # image: all image fields are base64 encoded and PIL-supported 'image': fields.binary("Photo", ...
dmacvicar/spacewalk
backend/server/action_extra_data/reboot.py
Python
gpl-2.0
1,085
0.003687
# # Copyright (c) 2008--2011 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a c...
# granted to use or replicate Red Hat trademarks that are incorporated # in this software or its documentation. # # from spacewalk.common import rhnFlags from spacewalk.common.rhnLog import log_debug from spacewalk.server.rhnServer import server_kickstart # the "exposed" functions __rhnexport__ = ['reboot'] def reb...
update_kickstart_session(server_id, action_id, action_status, kickstart_state='restarted', next_action_type=None)
nataddrho/DigiCue-USB
Python3/src/venv/Lib/site-packages/pip/_internal/utils/parallel.py
Python
mit
3,327
0
"""Convenient parallelization of higher order functions. This module provides two helper functions, with appropriate fallbacks on Python 2 and on systems lacking support for synchronization mechanisms: - map_multiprocess - map_multithread These helpers work like Python 3's map, with two differences: - They don't gu...
closes properly.""" try: yield pool finally: # For Pool.imap*, close and join are needed # for the returned iterator to begin yielding. pool.
close() pool.join() pool.terminate() def _map_fallback(func, iterable, chunksize=1): # type: (Callable[[S], T], Iterable[S], int) -> Iterator[T] """Make an iterator applying func to each element in iterable. This function is the sequential fallback either on Python 2 where Pool.imap* ...
thegeorgeous/flask-cqlalchemy
examples/example_app_udt.py
Python
isc
509
0
from flask
import Flask from flask_cqlalchemy import
CQLAlchemy app = Flask(__name__) app.config['CASSANDRA_HOSTS'] = ['127.0.0.1'] app.config['CASSANDRA_KEYSPACE'] = "cqlengine" app.config['CASSANDRA_SETUP_KWARGS'] = {'protocol_version': 3} db = CQLAlchemy(app) class Address(db.UserType): street = db.columns.Text() zipcode = db.columns.Integer() class User...
nobukatsu/deep-learning-from-scratch
ch03/nn-3layer.py
Python
mit
894
0.008949
import numpy as np def init_network(): network = {} network['W1'] = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]])
network['b1'] = np.array([0.1, 0.2, 0.3]) network['W2'] = np.
array([[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]]) network['b2'] = np.array([0.1, 0.2]) network['W3'] = np.array([[0.1, 0.3], [0.2, 0.4]]) network['b3'] = np.array([0.1, 0.2]) return network def identity_function(x): return x def forward(network, x): W1, W2, W3 = network['W1'], network['W2'], ne...
schmit/intro-python-course
lectures/code/tuples_basics.py
Python
mit
65
0.046154
>
>> myTuple = (1, 2, 3) >>> myTuple[1] 2 >>> myTuple[1:3] (2, 3
)
jptomo/rpython-lang-scheme
rpython/translator/goal/translate.py
Python
mit
12,703
0.001889
#! /usr/bin/env pypy """ Command-line options for translate: See below """ import os import sys import py from rpython.config.config import (to_optparse, OptionDescription, BoolOption, ArbitraryOption, StrOption, IntOption, Config, ChoiceOption, OptHelpFormatter) from rpython.config.translationoption import (...
ec_dic = load_target(targetspec) if args and not targetspec_dic.get('take_options', False): log.WARNING("target specific arguments supplied but will be ignored: %s" % ' '.join(args)) # give the target the possibility to get its own configuration options # into the config if 'get_additional_con...
ons' in targetspec_dic: optiondescr = targetspec_dic['get_additional_config_options']() config = get_combined_translation_config( optiondescr, existing_config=config, translating=True) # show the target-specific help if --help was given show_help(...
usc-isi-i2/etk
etk/data_extractors/htiExtractors/misc.py
Python
mit
1,773
0.0141
def phone_num_lists(): """ Gets a dictionary of 0-9 integer values (as Strings) mapped to their potential Backpage ad manifestations, s
uch as "zer0" or "seven". Returns: dictionary of 0-9 integer values mapped to a list of strings containing the key's possible manifestations """ all_nums = {} all_nums['2'] = ['2', 'two'] all_nums['3'] = ['3', 'three'] all_nums['4'] = ['4', 'four', 'fuor'] all_nums['5'] = ['5', 'five', 'fith'] al...
_nums['7'] = ['7', 'seven', 'sven'] all_nums['8'] = ['8', 'eight'] all_nums['9'] = ['9', 'nine'] all_nums['0'] = ['0', 'zero', 'zer0', 'oh', 'o'] all_nums['1'] = ['1', 'one', '!' 'l', 'i'] return all_nums def phone_text_subs(): """ Gets a dictionary of dictionaries that each contain alphabetic number m...
Distrotech/bzr
bzrlib/testament.py
Python
gpl-2.0
9,034
0.001107
# Copyright (C) 2005 Canonical Ltd # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in ...
whitespace(self.revision_id): raise ValueError(self.revision_id) if contains_linebreaks(self.committer): raise ValueError(self.committer) def as_text_lines(self): """Yield text form as a sequence of lines. The result is returned in utf-8, becaus
e it should be signed or hashed in that encoding. """ r = [] a = r.append a(self.long_header) a('revision-id: %s\n' % self.revision_id) a('committer: %s\n' % self.committer) a('timestamp: %d\n' % self.timestamp) a('timezone: %d\n' % self.timezone) ...
jason-neal/companion_simulations
misc/starfish_tests/read_HDF5.py
Python
mit
215
0
# Test
reading hdf5 file that I created import numpy as np import Starfish from Starfish.grid_tools import HDF5Interface myHDF5 = HDF5Interface() wl = myHDF5.wl flux = myHDF5.load_flux(np.array([6100, 4
.5, 0.0]))
libvirt/autotest
frontend/tko/csv_encoder.py
Python
gpl-2.0
5,495
0.00364
import csv import django.http try: import autotest.common as common except ImportError: import common from autotest_lib.frontend.afe import rpc_utils class CsvEncoder(object): def __init__(self, request, response): self._request = request self._response = response self._output_rows ...
er return Unhan
dledMethodEncoder def encoder(request, response): EncoderClass = _get_encoder_class(request) return EncoderClass(request, response)
petrjasek/superdesk-core
content_api/companies/resource.py
Python
agpl-3.0
963
0
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this sourc
e code, or # at https://www.sourcefabric.org/superdesk/license from superdesk.resource import Resource from content_api import MONGO_PREFIX class CompaniesResource(Resource): """ Company schema """ schema = {
"name": {"type": "string", "unique": True, "required": True}, "sd_subscriber_id": {"type": "string"}, "is_enabled": {"type": "boolean", "default": True}, "contact_name": {"type": "string"}, "phone": {"type": "string"}, "country": {"type": "string"}, } datasource = {"s...
googleads/google-ads-python
google/ads/googleads/v9/services/services/income_range_view_service/client.py
Python
apache-2.0
18,971
0.001054
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
ult (that is, the first one # in the dictionary). return next(iter(cls._transport_registry.values())) class IncomeRangeViewServiceClient(metaclass=IncomeRangeViewServiceClientMeta): """Service to manage income range views.""" @staticmethod def _get_default_mtls_endpoint(api_endpoint): ...
. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint. """ ...
mozilla/standup
standup/status/tests/conftest.py
Python
bsd-3-clause
128
0
from django.core.cache import cache def pytest_r
untest_setup(item): # Clear the cache before every test cache
.clear()
richard-willowit/odoo
odoo/tests/__init__.py
Python
gpl-3.0
43
0
from . import common from .common import
*
DarrenBellew/CloudCompDT228-3
Lab3/CountingSundays.py
Python
mit
328
0.021341
'''import datetime daytime.MINYEAR = 1901 daytime.MAXYEAR = 2000 print(daytime.MAXYEAR)''' import cal
endar count = 0 year = 1901 endYear = 2001 month = 12 for x in range (year, endYear): for y in range (1, month+1): if cale
ndar.weekday(x,y,1) == calendar.SUNDAY: count = count+1 print("Count: " + str(count))
google-research/google-research
smurf/smurf_models/raft_update.py
Python
apache-2.0
8,034
0.003112
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
ncoder([flow, corr]) inp = tf.concat([inp, motion_features], axis=-1) net = self.gru([n
et, inp]) delta_flow = self.flow_head(net) if self.args.convex_upsampling: # Scale mask to balance gradients. paddings = [[0, 0], [1, 1], [1, 1], [0, 0]] pad_net = tf.pad(net, paddings) mask = .25 * self.mask(pad_net) else: mask = None return net, mask, delta_flow class...
manjaro/thus
thus/misc/keyboard_widget.py
Python
gpl-3.0
13,129
0.001371
#!/usr/bin/env python # -*- coding: utf-8 -*- # # keyboard_widget.py # # Copyright © 2012 Linux Mint (QT version) # Copyright © 2013 Manjaro (QT version) # Copyright © 2013-2015 Antergos (GTK version) # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General ...
, (0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0
x1b), (0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x2b), (0x54, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35), ()] } kb_106 = { "extended_return": True, "keys": [ (0x29, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, ...
krishna11888/ai
third_party/gensim/gensim/models/__init__.py
Python
gpl-2.0
1,920
0.004688
""" This package contains algorithms for extracting document representations from their raw bag-of-word counts. """ # bring model classes directly into package namespace, to save some typing from .hdpmodel import HdpModel from .ldamodel import LdaModel from .lsimodel import LsiModel from .tfidfmodel import TfidfModel ...
rmationABC): """ Remap feature ids to new values. Given a mapping between old ids and new ids (some old ids may be missing = these features are to be discarded), this will wrap a corpus so that iterating over `VocabTransform[corpus]` returns the same vectors but with the new ids. Old features ...
old2new = dict((oldid, newid) for newid, oldid in enumerate(ids_you_want_to_keep)) >>> vt = VocabTransform(old2new) >>> for vec_with_new_ids in vt[corpus_with_old_ids]: >>> ... """ def __init__(self, old2new, id2token=None): # id2word = dict((newid, oldid2word[oldid]) for oldid, newid ...
McIntyre-Lab/papers
fear_sem_sd_2015/scripts/haplotype_freqs.py
Python
lgpl-3.0
358
0.005587
#!/usr/bin/env python import numpy as
np import pandas as pd def build_allele_dict(): """ Take a sheet and build a dictionary with: [gene][allele] = count """ fname = '/h
ome/jfear/mclab/cegs_sem_sd_paper/from_matt/DSRP_and_CEGS_haps_1-6-15.xlsx' data = pd.ExcelFile(fname) dspr = data.parse('DSRP_haps') f1 = data.parse('CEGS_haps') data
jpardobl/django_sprinkler
setup.py
Python
bsd-3-clause
1,456
0.021291
import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name = 'django_sprinkler', version = '0.4', packages = ["django_...
velopers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WW...
tent', ], )
phyng/phyip
geodata/provinces_script.py
Python
mit
637
0.004926
# coding: utf-8 import sys reload(sys) sys.setdefaultencoding('utf-8') import json china = json.loads(open('china.json', 'r').read(
)) # slow new_provs = [] new_citys = [] for prov in china['children']: new_provs.append(prov['name']) for city in prov['children']: if city['name'] not in [u'市辖区', u'县', u'省直辖县级行政区划']: if c
ity['name'][-1] == '市': new_citys.append(city['name'][:-1]) else: new_citys.append(city['name']) print new_citys with open('citys.json', 'w') as f: f.write(json.dumps(new_citys, ensure_ascii=False, indent=4))
356255531/SpikingDeepRLControl
code/EnvBo/Q-Learning/Testing_Arm_4points/q_networks.py
Python
gpl-3.0
3,008
0.002992
#!/usr/bin/python import numpy as np import os import sys from keras.layers import Activation, Dense, Input from keras.layers.normalization import BatchNormalization from keras.models import Model, Sequential from keras.optimizers import RMSprop NUM_OF_HIDDEN_NEURONS = 100 QNETWORK_NAME = 'online_netw...
model.add(Dense(self.NUM_OF_HIDDEN_NEURONS)) model.add(Activation('relu')) model.add(Dense(self.NUM_OF_
ACTIONS)) model.add(Activation('linear')) model.compile(loss='mse', optimizer='rmsprop') filename = net_name+'/'+net_name if os.path.isfile(filename+str(0)+'.txt'): weights = model.get_weights() for i in xrange(len(weights)): loaded_weig...
kalahbrown/HueBigSQL
apps/jobbrowser/src/jobbrowser/models.py
Python
apache-2.0
22,026
0.009262
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
.status.setupProgress self.cleanupProgress = self.job.status.cleanupProgress if self.job.desiredMaps == 0: maps_percent_complete = 0 else: maps_percent_complete = int(round(float(self.job.finished
Maps) / self.job.desiredMaps * 100)) self.desiredMaps = self.job.desiredMaps if self.job.desiredReduces == 0: reduces_percent_complete = 0 else: reduces_percent_complete = int(round(float(self.job.finishedReduces) / self.job.desiredReduces * 100)) self.desiredReduces = self.job.desiredRed...
soumyanishan/azure-linux-extensions
VMBackup/main/fsfreezer.py
Python
apache-2.0
8,407
0.00904
#!/usr/bin/env python # # VM Backup extension # # Copyright 2014 Microsoft 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/licenses/LICENSE-2.0 # # U...
.version_info > (3,):
line = str(line, encoding='utf-8', errors="backslashreplace") else: line = str(line) if(line != ''): self.logger.log(line.rstrip(), True) else: break if(self.freeze_handler.child.returncode!=0)...
gypogypo/plugin.video.sneek
_Edit.py
Python
gpl-3.0
121
0.008264
import xbmcaddon MainBase
= 'http://164.132.106.213/da
ta/home/home.txt' addon = xbmcaddon.Addon('plugin.video.sneek')
spellrun/Neural-Photo-Editor
gan/models/ian_simple.py
Python
mit
8,119
0.045695
### Simple IAN model for use with Neural Photo Editor # This model is a simplified version of the Introspective Adversarial Network that does not # make use of Multiscale Dilated Convolutional blocks, Ternary Adversarial Loss, or an # autoregressive RGB-Beta layer. It's designed to be sleeker and to run on laptop GPUs ...
filter_size = [5,5], stride = [2,2], crop = (1,1), W = initmethod(0.02), nonlinearity = relu, name = 'dec_conv1' ),name = 'bnorm_dc1'),indices=slice(1,None),axis=2),indices=slice(1,None),axis=3) l_dec_conv2 = SL(SL(BN(TC2D( ...
W = initmethod(0.02), nonlinearity = relu, name = 'dec_conv2' ),name = 'bnorm_dc2'),indices=slice(1,None),axis=2),indices=slice(1,None),axis=3) l_dec_conv3 = SL(SL(BN(TC2D( incoming = l_dec_conv2, num_filters = 128, filter_size = [5,5], ...
google/citest
tests/json_predicate/map_predicate_test.py
Python
apache-2.0
7,327
0.003276
# 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 a...
MapPredicate(pred, min=min)(context, obj) if dump: print('MAP_RESULT:\n{0}\n'.format( JsonSnapshotHelper.ValueToEncodedJson(map_result))) if expect_map_result: self.assertEqual(expect_map_result, map_result) error_msg = '{expect_ok} != {
ok}\n{map_result}'.format( expect_ok=expect_ok, ok=map_result.__nonzero__(), map_result=map_result) self.assertEqual(expect_ok, map_result.__nonzero__(), error_msg) def test_map_predicate_good_1(self): context = ExecutionContext() aA = jp.PathPredicate('a', jp.STR_EQ('A')) aA_attempt...
NinjaMSP/crossbar
crossbar/adapter/mqtt/_events.py
Python
agpl-3.0
21,416
0.000654
##################################################################################### # # Copyright (c) Crossbar.io Technologies GmbH # # Unless a separate license agreement exists between you and Crossbar.io GmbH (e.g. # you have purchased a commercial license), the license terms below apply. # # Should you enter ...
= self._make_payload() header = build_header(10, (False, False, True, False), len(payload)) return header + payload
def _make_payload(self): """ Build the payload from its constituent parts. """ b = [] # Session identifier b.append(pack('uint:16', self.packet_identifier).bytes) for topic in self.topics: if not isinstance(topic, unicode): rais...
vitan/openrave
python/databases/kinematicreachability.py
Python
lgpl-3.0
20,281
0.015926
# -*- coding: utf-8 -*- # Copyright (C) 2009-2010 Rosen Diankov (rosen.diankov@gmail.com) # # 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 # ...
or pose in poses]) neighs[neighs>=self.numposes] -= self.numposes poses[:,4:] *= self.itransmult return neighs,dists def kFRSearch(self,pose,radiussq,k,eps): """returns distance squared""" pose[4:] *= self.transmult neighs,dists,kball = sel...
.nnposes.kFRSearch(pose,radiussq,k,eps) neighs[neighs>=self.numposes] -= self.numposes pose[4:] *= self.itransmult return neighs,dists,kball def kFRSearchArray(self,poses,radiussq,k,eps): """returns distance squared""" poses[:,4:] *= self.transmult ...
carthach/essentia
test/src/unittests/standard/test_idct.py
Python
agpl-3.0
2,364
0.015651
#!/usr/bin/env python # Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia 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 (FSF), e...
program. If not, see http://www.gnu.org/licenses/ from essentia_test import * class TestIDCT(TestC
ase): def testInvalidParam(self): self.assertConfigureFails(IDCT(), { 'inputSize': 0, 'outputSize': 2 }) self.assertConfigureFails(IDCT(), { 'inputSize': 6, 'outputSize': 0 }) def testRegression(self): # values from Matlab/Octave inputArray = [ 0.89442718, -0.60150099, -0.1207...
Kopachris/py-id003
protocol_analyzer.py
Python
bsd-3-clause
17,902
0.005307
#!/usr/bin/env python3 import os import sys src_dir = os.path.abspath('src/') sys.path.append(src_dir) sys.ps1 = '' sys.ps2 = '' import id003 import termutils as t import time import logging import configparser import threading import serial.tools.list_ports from serial.serialutil import SerialException from colle...
cur_opt += 1 else: t.set_pos(x, y) elif c == b'\r': # save and go back CONFIG['bv.optional'] = set_opts return elif c == b'\x1b': # escape, go back witho
ut saving return def direction_settin
mryanlam/f5-ansible
library/bigip_user.py
Python
gpl-3.0
18,876
0.000371
#!/usr/bin/python # -*- codin
g: utf-8 -*- # # Copyright 2017 F5 Networks Inc. # # This file is part of Ansible # # Ansible 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. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have rec...
ict-felix/stack
modules/resource/orchestrator/src/credentials/cred_util.py
Python
apache-2.0
16,348
0.00312
# ---------------------------------------------------------------------- # Copyright (c) 2010-2014 Raytheon BBN Technologies # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and/or hardware specification (the "Work") to # deal in the Work without restriction, including...
#self.root_cert_files = [root_cert_fileordir] else: raise Exception("Couldn't find Root certs in %s" % root_cert_fileordir) @classmethod def getCAsFileFromDir(cls, caCerts): '''Take a directory of CA certificates and concatenate them into a
single file suitable for use by the Python SSL library to validate client credentials. Existing file is replaced.''' if caCerts is None: raise Exception ('Missing caCerts argument') if os.path.isfile(os.path.expanduser(caCerts)): return caCerts if not os...
sysbot/trigger
trigger/utils/cli.py
Python
bsd-3-clause
9,769
0.001843
#coding=utf-8 """ Command-line interface utilities for Trigger tools. Intended for re-usable pieces of code like user prompts, that don't fit in other utils modules. """ __author__ = 'Jathan McCollum' __maintainer__ = 'Jathan McCollum' __email__ = 'jathan.mccollum@teamaol.com' __copyright__ = 'Copyright 2006-2012, AO...
return pwd.getpwuid(os.getuid())[0] def print_severed_head(): """ Prints a demon holding a severed head. Best used when things go wrong, like production-impacting network outages caused by fat-fingered ACL changes. Thanks to Jeff Sullivan for this best error message ever. """ print r""" ...
_( (~\ _ _ / ( \> > \ -/~/ / ~\ :; \ _ > /(~\/ || | | /\ ;\ |l _____ |; ( \/ > > _\\)\)\)/ ;;; `8o __-~ ~\ d| \ ...
cidadania/e-cidadania
src/apps/thirdparty/smart_selects/urls.py
Python
apache-2.0
1,198
0.003339
# -*- coding: utf-8 -*- # # Copyright (c) 2013 Clione Software # Copyright (c) 2010-2013 Cidadania S. Coop. Galega # # 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.or...
lter/(?P<app>[\w\-]+)/(?P<model>[\w\-]+)/(?P<manager>[\w\-]+)/(?P<field>[\w\-]+)/(?P<value>
[\w\-]+)/$', 'filterchain', name='chained_filter'), )
lispc/Paddle
python/paddle/trainer_config_helpers/tests/configs/test_cost_layers.py
Python
apache-2.0
1,402
0
from paddle.trainer_config_helpers import * settings(learning_rate=1e-4, batch_size=1000) seq_in = data_layer(name='input', size=200) labels = data_layer(name='labels', size=5000) probs = data_layer(name='probs', size=10) xe_label = data_layer(name='xe-label', size=10) hidden = fc_layer(input=seq_in, size=4) output...
=xe_label), huber_regression_cost( input=seq_in, label=labels), huber_classification_cost( input=data_layer( nam
e='huber_probs', size=1), label=data_layer( name='huber_label', size=1)), multi_binary_label_cross_entropy( input=probs, label=xe_label), sum_cost(input=hidden), nce_layer( input=hidden, label=labels))
sentriz/steely
steely/plugins/bible/main.py
Python
gpl-3.0
3,384
0.001182
import json import random import requests from plugin import create_plugin from message import SteelyMessage HELP_STR = """ Request your favourite bible quotes, right to the chat. Usage: /bible - Random quote /bible Genesis 1:3 - Specific verse /bible help - This help text Verses are specified in th...
if not is_valid_quote(book_i, chapter_i, verse_i): return "Verse or chapter out of range" return get_quote(book_i, chapter_i, verse_i) @plugin.listen(command='bible [book] [passage]') def passage_command(bot, message: SteelyMessage, **kwargs): if 'passage' not in kwargs: book = random.randr...
)) bot.sendMessage( get_quote(book, chapter, verse), thread_id=message.thread_id, thread_type=message.thread_type) else: bot.sendMessage( get_quote_from_ref(kwargs['book'], kwargs['passage']), thread_id=message.thread_id, thread_type=me...
sujith7c/py-system-tools
en_mod_rw.py
Python
gpl-3.0
636
0.031447
#!/usr/bin/python import os,sys,re #Check the OS Version RELEASE_FILE = "/etc/redhat-release" RWM_FILE = "/etc/httpd/conf.modules.d/00-base.conf" if os.path.isfile(RELEASE_FILE): f=open(RELEASE_FILE,"r") rel_list = f.rea
d().split() if rel_list[2] == "release" and tuple(rel_list[3].split(".")) < ('8','5'): print("so far good") else: raise("Unable to find the OS version") #Check Apache installed #TODO # #Test if the rewrite module file present if os.path.isfile(RWM_FILE): print("re write") ##print sys.version_info ##if sy...
akayunov/amqpsfw
lib/amqpsfw/application.py
Python
mit
6,761
0.002367
import logging import select import socket from collections import deque from amqpsfw import amqp_spec from amqpsfw.exceptions import SfwException from amqpsfw.configuration import Configuration amqpsfw_logger = logging.getLogger('amqpsfw') log_handler = logging.StreamHandler() formatter = logging.Formatter('%(ascti...
cessor(self): yield raise NotImplementedError def stop(self): log.debug('Stop application') self.buffer_in.clear() self.buffer_out.clear() self.status = self.STOPPED self.ioloop.stop() self.socket.close() def on_hearbeat(self, method): se...
self.stop() def on_channel_flow(self, method): # TODO if active=0 stop sending data self.write(amqp_spec.Channel.FlowOk(method.active)) def on_channel_close(self, method): self.write(amqp_spec.Channel.CloseOk()) method_mapper = { amqp_spec.Heartbeat: on_hearbeat, ...
JamesKBowler/networking_scripts
cisco/cisco_telnet_recon.py
Python
mit
1,465
0.006826
import telnetlib from time import sleep import re import os HOST_IPs = [ "172.16.1.253", "172.16.1.254" ] telnet_password = b"pass_here" enable_password = b"pass_here" show_commands_list = [ b"show run", b"show ip arp", b"show vlan", b"show cdp neighbors", b"show ip interface brief" b"sh...
telnet_password + b"\r\n") sleep(0.5) # Get host name from prompt and make a directory host_name = re.su
b( '\r\n',"",tn.read_very_eager().decode('ascii'))[:-1] if not os.path.exists(host_name): os.makedirs(host_name) # Log into enable mode tn.write(b"enable\r\n") tn.write(enable_password + b"\r\n") # Set terminal output to 0 tn.write(b"terminal length 0\r\n") tn.read...
jessekl/flixr
venv/lib/python2.7/site-packages/fabric/sftp.py
Python
mit
12,958
0.000772
from __future__ import with_statement import hashlib import os import posixpath import stat import re from fnmatch import filter as fnfilter from fabric.state import output, connections, env from fabric.utils import warn from fabric.context_managers import settings def _format_local(local_path, local_is_path): ...
d=""): sudo('cp -p "%s" "%s"' % (remote_path, target_path)) # The user should always own the copied file. sudo('chown %s "%s"' % (env.user, target_path)) # Only root and the user has the right to read the file sudo('chmod %o "%s"' % (0400, ...
write) # and then use Paramiko's getfo() directly getter = self.ftp.get if not local_is_path: local_path.seek(0) getter = self.ftp.getfo getter(remote_path, local_path) finally: # try to remove the temporary file after t...
PyQuake/earthquakemodels
code/cocobbob/coco/code-preprocessing/archive-update/extract_extremes.py
Python
bsd-3-clause
4,277
0.006079
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import argparse from cocoprep.archive_load_data import get_file_name_list, parse_archive_file_name, get_key_value, parse_range from cocoprep.archive_exceptions import PreprocessingException, PreprocessingWarning...
ine: instance = int(get_key_value(line
[1:], 'instance').strip(' \t\n\r')) count = 0 elif count > 1 or (len(line) == 0) or line[0] == '%': continue elif count == 0: extreme1 = line.split()[1:3] count = 1 ...
trivoldus28/pulsarch-verilog
tools/local/bas-release/bas,3.9-SunOS-i386/lib/python/lib/python2.4/distutils/file_util.py
Python
gpl-2.0
8,320
0.002404
"""distutils.file_util Utility functions for operating on single files. """ # This module should be kept compatible with Python 2.1. __revision__ = "$Id: file_util.py,v 1.17 2004/11/10 22:23:14 loewis Exp $" import os from distutils.errors import DistutilsFileError from distutils import log # for generating verbos...
_mode=1, preserve_times=1, update=0, link=None, verbose=0, dry_run=0): """Copy a file 'src' to 'dst'. If 'dst' is a directory, then 'src' is copied there with the
same name; otherwise, it must be a filename. (If the file exists, it will be ruthlessly clobbered.) If 'preserve_mode' is true (the default), the file's mode (type and permission bits, or whatever is analogous on the current platform) is copied. If 'preserve_times' is true (the default), the last-mo...
sxjscience/tvm
python/tvm/contrib/clang.py
Python
apache-2.0
3,361
0.000595
# 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 u...
ef find_clang(required=True): """Find clang in system. Parameters ---------- required : bool Whether it i
s required, runtime error will be raised if the compiler is required. Returns ------- valid_list : list of str List of possible paths. Note ---- This function will first search clang that matches the major llvm version that built with tvm """ cc_list = [] major ...
Serulab/Py4Bio
code/ch14/basiccircle.py
Python
mit
157
0
from bokeh.plotting import figure, output
_file, show p = figure(width=400, height=400) p.circle(2, 3, radi
us=.5, alpha=0.5) output_file('out.html') show(p)
danielwpz/soybean
src/util/optimizer.py
Python
mit
1,090
0.000917
class Optimizer: def __init
__(self, model, params=None): self.model = model if params: self.model.set_params(**params) self.params = self.model.get_params() self.__chain = list() def step(self, name, values, skipped=False): if not skipped: self.__chain.append({ ...
self.model.set_params(**self.params) # set previous best param results = [(evaluator(self.model.set_params(**{param['pname']: value})), value) for value in param['pvalues']] results = sorted(results, lambda a, b: -1 if a[0] < b[0] else 1) print param['pnam...
kreatorkodi/repository.torrentbr
plugin.video.yatp/site-packages/hachoir_core/field/field.py
Python
gpl-2.0
8,646
0.002429
""" Parent of all (field) classes in Hachoir: Field. """ from hachoir_core.compatibility import reversed from hachoir_core.stream import InputFieldStream from hachoir_core.error import HachoirError, HACHOIR_ERRORS from hachoir_core.log import Logger from hachoir_core.i18n import _ from hachoir_core.tools import makePr...
if self._parent: current = self._parent.root else: current = self if len(key) == 1: return current key = key[1:] else: current = self for part in key.split("/"): ...
current._getField(part, const) if field is None: raise MissingField(current, part) current = field return current raise KeyError("Key must not be an empty string!") def __getitem__(self, key): return self.getField(key, False) def ...
ssdi-drive/nuxeo-drive
nuxeo-drive-client/tests/test_long_path.py
Python
lgpl-2.1
3,664
0.000819
# coding: utf-8 import os import sys from nxdrive.logging_config import get_logger from nxdrive.utils import safe_long_path from tests.common_unit_test import UnitTestCase if sys.platform == 'win32': import win32api log = get_logger(__name__) # Number of chars in path c://.../Nuxeo.. is approx 96 chars FOLDER_...
1 = os.path.join(self.local_nxdrive_folder_1,
test_folder) self.assertTrue(len(self.local_nxdrive_folder_1) > 245) self.manager_1.unbind_all() self.engine_1 = self.manager_1.bind_server( self.local_nxdrive_folder_1, self.nuxeo_url, self.user_2, self.password_2, start_engine=False) self.engine_1...
ameyjadiye/nxweb
sample_config/python/hello.py
Python
lgpl-3.0
2,478
0.01937
from cgi import parse_qs, escape, FieldStorage import time import shutil def ping_app(environ, start_response): status = '200 OK' output = 'Pong!' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) ...
il.copyfileobj(item.file, fdst, 8192) if hasattr(item.file, 'close'): item.
file.close() else: result+='%s: value; %s\n' % (item.name, item.value) except Exception as e: result='multipart data parse failure: '+repr(e) else: start_response('200 OK', [('Content-Type', 'text/html;charset=utf-8')]) result=''' <form action="/py" method="post" enctype=...
linvictor88/vse-lbaas-driver
quantum/plugins/nicira/QuantumPlugin.py
Python
apache-2.0
104,734
0.000134
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Nicira, 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/lic...
import importutils from quantum.openstack.common import rpc from quantum.plugins.nicira.common import config # noqa from quantum.plugins.nicira.common import exceptions as nvp_exc from quantum.plugins.nicira.common import metadata_access as nvp_me
ta from quantum.plugins.nicira.common import securitygroups as nvp_sec from quantum.plugins.nicira.extensions import nvp_networkgw as networkgw from quantum.plugins.nicira.extensions import nvp_qos as ext_qos from quantum.plugins.nicira import nicira_db from quantum.plugins.nicira import nicira_networkgw_db as networkg...
tangentstorm/scenetool
spike/vue2svg.py
Python
mit
5,403
0.004442
""" vue2svg : spike/prototype for scenetool. generates an svg scene from VUE files specified on command line. usage: python3.2 vue2svg.py ../test/vue/*.vue https://github.com/tangentstorm/scenetool copyright (c) 2013 michal j wallace. available to the public under the MIT/x11 license. (see ../LICENSE) """ import o...
('parent ntype shape id ts x y w h text layer autosized' ' fill strokewidth strokecolor strokestyle textcolor' ' font id1 id2 p0x p0y p1x p1y ctrlcount arrowstate' ' c0x c0y c1x c1y').split( )) def walk(tree, parent=0): """ walk the tree recursively, e...
data """ children = tree.xpath('child') for child in children: row = VueData(*([parent] + [xp(child, path) for path in [ '@xsi:type', 'shape/@xsi:type', '@ID', '@created', '@x', '@y', ...
EmreAtes/spack
lib/spack/spack/test/cmd/find.py
Python
lgpl-2.1
3,528
0
############################################################################## # 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, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
s.explicit = True
q_args = query_arguments(args) assert q_args['explicit'] is True args.explicit = False args.implicit = True q_args = query_arguments(args) assert q_args['explicit'] is False @pytest.mark.db @pytest.mark.usefixtures('database', 'mock_display') def test_tag1(parser, specs): args = parser.pars...
vvladych/forecastmgmt
src/forecastmgmt/model/person.py
Python
unlicense
2,819
0.025186
__author__="vvladych" __date__ ="$09.10.2014 23:01:15$" from forecastmgmt.dao.db_connection import get_db_connection import psycopg2.extras from MDO import MDO from person_name import PersonName class Person(MDO): sql_dict={"get_all":"SELECT sid, common_name, birth_date, birth_place, person_uuid FROM fc_...
on, self).__init__(Person.sql_dict,sid,person_uuid) self.common_name=common_name self.birth_date=birth_date self.birth_place=birth_place if sid!=None: self.names=PersonName().get_all_for_foreign_key(self.sid) else:
self.names=[] def load_object_from_db(self,rec): self.common_name=rec.common_name self.birth_date=rec.birth_date self.birth_place=rec.birth_place self.uuid=rec.person_uuid self.names=PersonName().get_all_for_foreign_key(self.sid) def get_insert_dat...
OPM/opm-common
python/tests/test_field_props.py
Python
gpl-3.0
2,742
0.006929
import unittest import opm.io import numpy as np from opm.io.parser import Parser from opm.io.deck import DeckKeyword from opm.io.ecl_state import EclipseState try: from tests.utils import test_path except ImportError: from utils import test_path class TestFieldProps(unittest.TestCase): def assertClose...
ay = np.ones(324) actnum_kw = DeckKeyword( parser["ACTNUM"], int_array) deck.add(actnum_kw) self.spe3 = EclipseState(deck) self.props = self.spe3.field_props() def test_contains(self): p = self.props self.assertTrue('PORO' in p) self.assertFalse('NONO' in p) ...
e('PORV' in p) self.assertTrue('ACTNUM' in p) def test_getitem(self): p = self.props poro = p.get_double_array('PORO') self.assertEqual(324, len(poro)) self.assertEqual(0.13, poro[0]) self.assertTrue( 'PERMX' in p ) px = p.get_double_array('PERMX') p...
mmahnic/trac-tickethistory
tickethistory/test/workdays_t.py
Python
mit
4,805
0.028512
from ..workdays import * from datetime import datetime, timedelta from time import strptime import math import traceback tests=[] def test( fn ): tests.append(fn) return fn def runTests(): for t in tests: print t try: t() except Exception as e: print e trace...
es = estimate_end_workdays( d1, d2, total, remaining ) print "expected: %s, actual %s, %s" % (dexp, dres, _is_same_dt( dres, dexp, 3 ) ) if not _is_same_dt( dres, dexp ): print " diff:", dres - dexp # Monday 2017-03-06 d1 = dt.datetime(2017, 03
, 06, 8 ) d2 = dt.datetime(2017, 03, 13, 8 ) for done in xrange(1, 22, 5): dexp = d2 + dt.timedelta( weeks=done ) print done, dt.timedelta( weeks=done ), test( d1, d2, done+1, done, dexp ) runTests()
fasaxc/felix
calico/felix/test/test_frules.py
Python
apache-2.0
13,792
0.008338
# -*- coding: utf-8 -*- # Copyright 2014 Metaswitch Networks # # 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 applicab...
s = stub_ipsets @classmethod def tearDownClass(cls): # Reinstate the modules we overwrote frules.ipsets = cls.real_ipsets def setUp(self): stub_ipsets.reset() # Set the expecte
d IP tables state to be clean. expected_ipsets.reset() def create_ipsets(self, family): stub_ipsets.create("ipset_port", "hash:net,port", family) stub_ipsets.create("ipset_addr", "hash:net", family) stub_ipsets.create("ipset_icmp", "hash:net", family) expected_ipsets.create...
rgayon/l2tdevtools
tests/update.py
Python
apache-2.0
2,954
0.008463
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the update tool.""" from __future__ import unicode_literals import os import sys import unittest from tools import update from tests import test_lib @unittest.skipIf( os.environ.get('TRAVIS_OS_NAME') == 'osx', 'TLS 1.2 not supported by macOS on Tr...
self._PROJECT_NAME, self._PROJECT_VERSION)) self.assertEqual( package_versions.get(self._P
ROJECT_NAME, None), [self._PROJECT_VERSION, '1']) if __name__ == '__main__': unittest.main()
flying-sheep/omnitool
plugins/tombstone.py
Python
mit
1,209
0.01737
config = { "name": "Tombstone counter", # plugin name "type": "receiver", #plugin type "description": ["counts tombstones in a world"] #description } import database as db # import terraria database class Receiver(): # required class to be called by plugin manager def __init__(self): #do any ini...
re ready x = 0 #our counter variable for column in tiles: # tiles come as 2D list for tile in column: #so we need to get tiles like this if tile[0] == self.tile_id: #tile[0] is the tile_id x += 1 #increment counter for each found tombstone tile ...
of 4 "sub tiles" return False #signal plugin manager we are done and dont need any further data
nextBillyonair/compVision
AMX/Crystal/loop.py
Python
mit
1,215
0.015638
import cvlib angle = 0 angles = [] center = [] for i in range(24): #24 img = cvlib.load("findloop_%d.jpg" % angle) angles.append(angle) rng = cvlib.inRangeThresh(img, (20,30,20), (200,130,120)) rng = cvlib.bitNot(rng) cnt = cvlib.findContours(rng, thresh=250) if cvlib.area(cnt[0]) > cvlib.area(...
append(centroid[1]) cvlib.drawContour(img, crystal, thickness=10) cvlib.plotCentroid(img, crystal, radius=7) cvlib.display(img) cvlib.save(img, "found%d.jpg" % angle) angle += 15 cvlib.saveGraph(angles, center, "Y Coord Per Angle", "Angles in Degrees", "Original Data Coord", [0,360,0,400], filename...
Per Angle", "Angles in Degrees", "Y Coord Centroid Best Fit", [0,360,0,400], style="--", filename="fit.png") cvlib.makeGraph(angles, d["data"], "Y Coord Per Angle", "Angles in Degrees", "Y Coord Centroid", [0,360,0,400], style="r--") # X = - (MC/PEL) * A * sin(phase) # Y = - (MC/PEL) * A * cos(phase)
Hackfmi/Diaphanum
positions/migrations/0002_auto__del_positions__add_position.py
Python
mit
1,927
0.006227
# -*- 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): # Deleting model 'Positions' db.delete_table(u'positions_positions') # Adding model 'Position' ...
b.create_table(u'positions_positions', ( ('content', self.gf('django.db.models.fields.TextField')()), ('date', self.gf('django.db.models.fields.DateField')(default=datetime.datetime(2013, 8, 21, 0, 0))), (u'id', self.gf('django.db.models.
fields.AutoField')(primary_key=True)), ('title', self.gf('django.db.models.fields.CharField')(max_length=100)), )) db.send_create_signal(u'positions', ['Positions']) # Deleting model 'Position' db.delete_table(u'positions_position') models = { u'positions.posit...