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
openstack/vitrage-dashboard
vitrage_dashboard/entities/urls.py
Python
apache-2.0
728
0
# Copyright 2015 IBM Corp. # # 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, sof...
der 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. from django.conf.urls import url from vitrage_dashboard.entit
ies import views urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), ]
polyaxon/polyaxon
platform/polycommon/polycommon/options/conf_subscriptions/stats.py
Python
apache-2.0
721
0
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the L
icense. # 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. # S...
import conf from polycommon.options.registry import stats conf.subscribe(stats.StatsDefaultPrefix)
WangWenjun559/Weiss
summary/sumy/sklearn/feature_selection/base.py
Python
apache-2.0
4,186
0
# -*- coding: utf-8 -*- """Generic feature selection mixin""" # Authors: G. Varoquaux, A. Gramfort, L. Buitinck, J. Nothman # License: BSD 3 clause from abc import ABCMeta, abstractmethod from warnings import warn import numpy as np from scipy.sparse import issparse, csc_matrix from ..base import TransformerMixin f...
` is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If
`indices` is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector. """ mask = self._get_support_mask() return mask if not indices else np.where(mask)[0] @abstractmethod def _get_support_mask(self): ...
RafaAguilar/archi2mongodb
archimate2mongodb/pkg/utils/__init__.py
Python
mit
88
0.011364
# -*- coding: utf-8 -*- """Parse Archimate X
ML Exchange File Format into a MongoDB DB""
"
tobes/jukebox
schema.py
Python
gpl-2.0
4,534
0.007278
import os import sqlalchemy as sa from sqlalchemy.orm import sessionmaker, relation from sqlalchemy.ext.declarative import declarative_base import datetime # database setup Base = declarative_base() # define the tables class Song(Base): __tablename__ = 'so
ng' id = sa.Column(sa.Integer, primary_key=True) path = sa.Column(sa.Unicode(assert_unicode = False)) title = sa.Column(sa.Unicode(as
sert_unicode = False)) unknown = sa.Column(sa.Boolean) track = sa.Column(sa.Integer) length = sa.Column(sa.Integer) unknown = sa.Column(sa.Boolean) mimetype = sa.Column(sa.Text) album_id = sa.Column(sa.Integer, sa.ForeignKey('album.id')) artist_id = sa.Column(sa.Integer, sa.ForeignKey('artis...
feigaochn/leetcode
p12_integer_to_roman.py
Python
mit
1,010
0
# author: Fei Gao # # Integer To Roman # # Given an integer, convert it to a roman numeral. # Input is guaranteed to be within the range from 1 to 3999. class Solution: # @return a string def intToRoman(self, n): roman_numeral_map = ( ('M', 1000), ('CM', 900), ('D'...
('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5), ('IV', 4),
('I', 1)) result = '' for numeral, integer in roman_numeral_map: while n >= integer: result += numeral n -= integer return result def main(): solver = Solution() tests = [] for test in tests: print(test) print(...
iliastsi/gac
testsuite/driver/runtests.py
Python
mit
8,165
0.002449
# # (c) Simon Marlow 2002 # import sys import os import string import getopt import platform import time import re from testutil import * from testglobals import * # Readline sometimes spews out ANSI escapes for some values of TERM, # which result in test failures. Thus set TERM to a nice, simple, safe # value. os....
path = re.sub('([a-zA-Z]):', '/cygdr
ive/\\1', path) path = re.sub('\\\\', '/', path) os.environ['PATH'] = os.pathsep.join([path, os.environ.get("PATH", "")]) else: # darwin os.environ['DYLD_LIBRARY_PATH'] = os.pathsep.join([path, os.environ.get("DYLD_LIBRARY_PATH", "")]) glo...
Osmose/walt
walt.py
Python
mit
4,090
0.000978
#!/usr/bin/env python """ Convert a series of images to a CSS animation. Outputs an image file containing the frames of the animation and an HTML file with sample CSS for embedding the animation on a pag
e. Usage: walt FILENAMES... [options] Options: --help Show this screen. --version Show version. --verbose Output extra information during run. --out-image <filename> Filename for composite image. [default: walt.png] --out-html <filename> Filename for sample HT...
le HTML. [default: walt] --duration <duration> Duration of the animation. Defaults to a value that ensures 24fps. """ import os.path from docopt import docopt from PIL import Image, ImageChops __version__ = '0.1' with open(os.path.join(os.path.dirname(__file__), 'sample_template.html'...
theplue/honeypot
plugins/https_plugin.py
Python
mit
6,418
0.002805
from plugin_template import Template from BaseHTTPServer import BaseHTTPRequestHandler from sqlalchemy import Column, Integer, String, DateTime from base import Base import json import datetime import logging import ssl from OpenSSL import crypto from ConfigParser import SafeConfigParser from os.path import exists, joi...
ate_cert(self, cert_file, key_file): if os.path.isfile(cert_file) and os.path.isfile(key_file): print 'already exist' return cert_file, key_file k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, 2048) cert = crypto.X509() cert.get_subject().C = "US" ...
"CO" cert.get_subject().L = "Denver" cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(365*24*60*60) cert.set_issuer(cert.get_subject()) cert.set_pubkey(k) cert.sign(k, 'sha1') open(join(cert_file), 'w').write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert...
LynnHo/AttGAN-Tensorflow
scripts/align.py
Python
mit
5,555
0.00414
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse from functools import partial from multiprocessing import Pool import os import re import cropper import numpy as np import tqdm # ============================================================...
img_crop) tformed_landmarks.shape = -1 name_landmark_str = ('%s' + ' %.1f' * n_landmark * 2) % ((name, ) + tuple(tformed_landmarks)) succeed = True break except: succeed = False if succeed: return name_landmark_str else: print(...
total=len(img_names))) pool.close() pool.join() landmarks_path = os.path.join(save_dir, 'landmark.txt') with open(landmarks_path, 'w') as f: for name_landmark_str in name_landmark_strs: if name_landmark_str: f.write(name_landmark_str + '\n')
echopen/PRJ-medtec_sigproc
echopen-leaderboard/bootcamp/activities/views.py
Python
mit
1,362
0
from django.shortcuts import render from bootcamp.activities.models import Notification from django.http import HttpResponse from django.contrib.auth.decorators import login_required from bootcamp.decorators import ajax_required @login_required def notifications(request): user = request.user notifications = N...
bjects.filter(to_user=user, is_read=False) for notification in unread: notification.is_read = True notification.save() return render(request, 'activities/notifications.html',
{'notifications': notifications}) @login_required @ajax_required def last_notifications(request): user = request.user notifications = Notification.objects.filter(to_user=user, is_read=False)[:5] for notification in notifications: notification.is_rea...
ponty/EasyProcess
tests/test_fast/test_unicode.py
Python
bsd-2-clause
3,252
0.001538
import sys from easyprocess import EasyProcess from easyprocess.unicodeutil import split_command OMEGA = "\u03A9" python = sys.executable def platform_is_win(): return sys.platform == "win32" def py_minor(): return sys.version_info[1] def test_str(): assert EasyProcess("ls -la").call().return_code ...
yte cmd = [python, "-c", "import sys;sys.stdout.buffer.write(b'\\x92')"] p = EasyProcess(cmd).call() assert p.return_code == 0 assert p.stdout == "" # 0xFF must never appear in a valid UTF-8 sequence cmd = [python, "-c", "import sys;sys.stdout.buffer
.write(b'\\xFF')"] p = EasyProcess(cmd).call() assert p.return_code == 0 assert p.stdout == ""
isudox/leetcode-solution
python-algorithm/leetcode/problem_1449.py
Python
mit
2,700
0
"""1449. Form Largest Integer With Digits That Add up to Target https://leetcode.com/problems/form-largest-integer-with-digits-that-add-up-to-target/ """ from functools import lru_cache from typing import List class Solution: def largest_numb
er(self, cost: List[int], target: int) -> str: def compare(a: str, b: str) -> bool: return a > b if len(a) == len(b) else len(a) > len(b) @lru_cache(None) def dfs(x: int) -> str: if x == 0: return '' res = '0' for i in range(len(co...
- cost[i]) if ret != '0': ret = str(i + 1) + ret if compare(ret, res): res = ret return res return dfs(target) def largest_number3(self, cost: List[int], target: int) -> str: def gt(a: str, ...
marshallhumble/Euler_Groovy
Coding_Bat/Python/Warmup_1/near_hundred.py
Python
mit
932
0.017167
#!/usr/bin/env python """ Given an int n, return Tru
e if it is within 1
0 of 100 or 200. Note: abs(num) computes the absolute value of a number. near_hundred(93) == True near_hundred(90) == True near_hundred(89) == False """ def near_hundred(n): return 190 <= abs(n) <= 210 or 90 <= abs(n) <= 110 def test_function(): assert near_hundred(93) == True assert near_hundred(90) =...
joewalnes/idea-community
plugins/hg4idea/testData/bin/hgext/hgk.py
Python
apache-2.0
11,681
0.001455
# Minimal support for git commands on an hg repository # # Copyright 2005, 2006 Chris Mason <mason@suse.com> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. '''browse the repository in a graphical way The hgk extension allows bro...
except EOFError: break else: break # git rev-tree is a confusing thing. You can supply a number of # commit sha1s on the command line, and it walks the commit history # telling you which commits are reachable from the supplied ones via # a bitmask based on arg position. # ...
i = count l = [0] * 100 chunk = 100 while True: if chunk > i: chunk = i i = 0 else: i -= chunk for x in xrange(chunk): if i + x >= count: l[chunk - x:] = [0] * (chunk...
batermj/algorithm-challenger
code-analysis/programming_anguage/python/source_codes/Python3.5.9/Python-3.5.9/Lib/test/test_wsgiref.py
Python
apache-2.0
27,734
0.008293
from unittest import mock from test import support from test.test_httpservers import NoLogRequestHandler from unittest import TestCase from wsgiref.util import setup_testing_defaults from wsgiref.headers import Headers from wsgiref.handlers import BaseHandler, BaseCGIHandler, SimpleHandler from wsgiref import util from...
pp(status)) self.assertTrue(out.endswith( b"A server error occurred. Please contact the administrator."
)) self.assertEqual(err.splitlines()[-2], exc_message) def test_wsgi_input(self): def bad_app(e,s): e["wsgi.input"].read() s("200 OK", [("Content-Type", "text/plain; charset=utf-8")]) return [b"data"] out, err = run_amock(validator(bad_app)) ...
ELNOGAL/alimentacion
product_lot_sequence/product.py
Python
agpl-3.0
2,187
0
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2014 Pexego (<www.pexego.es>). All Rights Reserved # $Omar Castiñeira Saavedra$ # # This program is free software: you can redistribute it ...
ut WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU
General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## """add lot sequence field in products""" ...
piton-package-manager/piton
piton/lib/inquirer/questions.py
Python
mit
3,684
0
# -*- coding: utf-8 -*- """ Module that implements the questions types """ import json from . import errors def question_factory(kind, *args, **kwargs): for clazz in (Text, Password, Confirm, List, Checkbox): if clazz.kind == kind: return clazz(*args, **kwargs) raise errors.UnknownQuesti...
def validate(self, current): try: if self._solve(self._validate, current): return except Exception: pass raise errors.ValidationError(current) def _solve(self, prop, *args, **kwargs): if callable(prop): return prop(self.answers, ...
tion): kind = 'password' class Confirm(Question): kind = 'confirm' def __init__(self, name, default=False, **kwargs): super(Confirm, self).__init__(name, default=default, **kwargs) class List(Question): kind = 'list' class Checkbox(Question): kind = 'checkbox'
Fullbiter/EECS-293
pa12-13/airville/src/actor.py
Python
gpl-3.0
489
0
# Kevin Nash (kjn33) # EECS 293 # Assignment 12
from entity import Entity class Actor(Entity): """ A game entity that can act and be acted upon """ def __init__(self): """ Actors follow Entity initialization, are given a null location """ super(Actor, self).__init__() self.location = None def act(self...
mozilla-services/shavar
shavar/tests/test_parse.py
Python
mpl-2.0
9,123
0
import io from shavar.exceptions import ParseError from shavar.parse import ( parse_downloads, parse_gethash, parse_file_source, parse_dir_source) from shavar.types import ( Chunk, ChunkList, Downloads, DownloadsListInfo, LimitExceededError) from shavar.tests.base import ( DELTA...
tEqual(p, d) # empty list
w/ MAC p = parse_downloads(dummy("acme-malware-shavar;mac")) d = Downloads() d.append(DownloadsListInfo("acme-malware-shavar", wants_mac=True)) self.assertEqual(p, d) # with size p = parse_downloads(dummy("s;200\nacme-malware-shavar;")) d = Downloads(200) ...
jledbetter/openhatch
mysite/search/migrations/0021_remove_icon_for_profile_since_we_realized_we_do_not_need_it.py
Python
agpl-3.0
3,787
0.008978
# This file is part of OpenHatch. # Copyright (C) 2009 OpenHatch, Inc. # # 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 Software Foundation, either version 3 of the License, or # (at your option) any later v...
efault': 'None', 'max_length': '100', 'null': 'True'}), 'icon_raw': ('django.db.models.fields.files.ImageField', [], {'default': 'None', 'max_length': '100', 'null': 'True'}), 'icon_smaller_for_badge': ('dj
ango.db.models.fields.files.ImageField', [], {'default': 'None', 'max_length': '100', 'null': 'True'}), 'icon_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.model...
Damnever/Chat-Room
handlers/__init__.py
Python
bsd-3-clause
535
0.001869
# -*-
coding: utf-8 -*- import os import importlib import pkgutil def load_urls(urls=None, attr='urls'): if urls is None: urls = list() # pkg_name = os.path.dirname(__file__) pkg_path = os.path.abspath(os.path.dirname(__file__)) pkg_name = os.path.basename(pkg_path) for _, name, ispkg in pkgut...
, attr)) return urls urls = load_urls()
endlisnis/weather-records
updateAccuWeather.py
Python
gpl-3.0
1,064
0.004699
#!/usr/bin/python3 # -*- coding: utf-8 -*-import stations import datetime import random import stations import os now = datetime.date.today() curMonth = datetime.date(now.year, now.month, 1) nextMonth = datetime.date(now.year+curMonth.month//12, (now.month%12)+1, 1) for city, info in stations.city.items(): if inf...
l "http://www.accuweather.com/en/ca/{cityName}/k1s/{monthName}-weather/{info.accuweatherStationId}?monyr={monthStr}&v
iew=table" && break; done'.format(**locals()))
hasgeek/funnel
rqinit.py
Python
agpl-3.0
362
0.002762
from urllib.parse i
mport urlsplit from funnel import app REDIS_URL = app.config.get('REDIS_URL', 'redis://redis:6379/0') # REDIS_URL is not taken by setup_default_arguments function of rq/scripts/__init__.py # so, parse that into pieces and give it r = urlsplit(REDIS_URL) REDIS_HOST = r.hostname REDIS_PORT = r.port REDIS_PASSWORD = r...
password REDIS_DB = 0
IntelLabsEurope/infrastructure-repository
monitoring_service/agents_consumer.py
Python
apache-2.0
4,373
0.000457
# Copyright 2015 Intel 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 # # Unless required by applicable law or agreed to in wri...
_section_map('RabbitMQ', config)['rb_host'] rb_port = config_section_map('RabbitMQ', config)['rb_port'] agents_queue = config_section_map('RabbitMQ', config)['agents_queue'] self.conn_string = 'amqp://' + \ rb_usr + ':' \ + rb_pwd + '@' \ ...
+ rb_port + '/%2F' self.queue = agents_queue self.graph_db = graph_db def consume_agents(self): """ Start the listener of the agents queue """ queue_name = self.queue parameters = pika.URLParameters(self.conn_string) connection = p...
TaskEvolution/Task-Coach-Evolution
taskcoach/taskcoachlib/thirdparty/pubsub/core/arg1/__init__.py
Python
gpl-3.0
648
0.001543
''' This is not really a package init file, it is only here to simplify the packaging and installation of pubsub.core's protocol-specific subfolders by setuptools. The python modules in this folder are automatically made part of pubsub.core via pubsub.core's __p
ath__. Hence, this should not be imported directly, it is part of pub
sub.core when the messaging protocol is "arg1" (and not usable otherwise). :copyright: Copyright since 2006 by Oliver Schoenborn, all rights reserved. :license: BSD, see LICENSE.txt for details. ''' msg = 'Should not import this directly, used by pubsub.core if applicable' raise RuntimeError(msg)
qedsoftware/commcare-hq
custom/fri/urls.py
Python
bsd-3-clause
191
0.005236
from django.conf.urls import url from custom.fri.views impo
rt upload_message_bank urlpatterns = [ url(r'^upload_message_bank/$', upload_message_bank, name='fri_upload_message_b
ank'), ]
karthikvadla16/spark-tk
regression-tests/sparktkregtests/testcases/frames/frame_inspect_test.py
Python
apache-2.0
4,394
0.000695
# vim: set encoding=utf-8 # Copyright (c) 2016 Intel 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 # # Unless require...
e 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. # """Tests frame.inspect() """ impor
t unittest import sys import os from sparktkregtests.lib import sparktk_test class FrameInspectTest(sparktk_test.SparkTKTestCase): def setUp(self): """Build test frame""" super(FrameInspectTest, self).setUp() dataset = self.get_file("movie_user_5ratings.csv") schema = [("src", in...
stoq/kiwi
tests/test_python.py
Python
lgpl-2.1
3,893
0
# -*- coding: utf-8 -*- import unittest from kiwi.python import AttributeForwarder, slicerange, enum, strip_accents class SliceTest(unittest.TestCase): def genlist(self, limit, start, stop=None, step=None): if stop is None: stop = start start = None return list(slicerang...
' in repr(Color.RED), repr(Color.RED)) self.assertTrue(int(Color.RED) is not None) def testComparision(self): self.assertEqual(Color.RED, 0) self.assertNotEqual(Color.RED, 1) self.assertNotEqual(Color.RED, -1) self.assertNotEqual(Color.RED, Color.GREEN) self.assertNo...
def testNew(self): yellow = Color(3, 'YELLOW') self.assertTrue(isinstance(yellow, Color)) self.assertEqual(Color.YELLOW, yellow) self.assertRaises(ValueError, Color, 3, 'AGAIN') self.assertRaises(ValueError, Color, 4, 'RED') class AttributeForwarderTest(unittest.TestCase): ...
frankrousseau/weboob
modules/bouygues/pages/compose.py
Python
agpl-3.0
1,560
0.001923
# -*- coding: utf-8 -*- # Copyright(C) 2010-2011 Christophe Benz # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it und
er the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # weboob 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 Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with weboob. If not,...
hemalchevli/TwitterBot
twitter.py
Python
gpl-2.0
155,437
0.007025
#!/usr/bin/env python # # vim: sw=2 ts=2 sts=2 # # Copyright 2007 The Python-Twitter Developers # # 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-...
on library" # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl, parse_qs except ImportError: from cgi import parse_qsl, parse_qs try: from hashlib import md5 except ImportE
rror: from md5 import md5 import oauth2 as oauth CHARACTER_LIMIT = 140 # A singleton representing a lazily instantiated FileCache. DEFAULT_CACHE = object() REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https...
escorciav/amcs211
hw5/hw5_1.py
Python
bsd-2-clause
3,638
0.01017
from numpy import any, array, array_str, concatenate, dot
, intersect1d from numpy import nonzero, ravel,
setdiff1d, zeros from numpy.linalg import lstsq, norm def active_constraints(A, b, x): """Return a set of active constraints """ dx = b - dot(A, x) if any(dx > 0): raise ValueError('x is infeasible') return nonzero(dx == 0)[0] def get_starting_point(A, b): raise NotImplementedError('Y...
byteknacker/fcc-python-vagrant
python/python_test/test_modules/django_test.py
Python
bsd-3-clause
555
0.007207
from subprocess import
call, check_output from locale import getpreferredencoding class TestDjango: """ Test if Django and its libraries are properly installed inside venv """ def django_version(self): """ Returns current version of Django """ output = check_output(['python', '-c', 'import django; print(django.get_v...
oding()).strip() def test_django_version(self): """ Checks that Django is latest stable """ assert self.django_version() == '1.9.6'
suutari-ai/shoop
shuup_tests/admin/test_multishop_setting.py
Python
agpl-3.0
1,030
0.001942
# This file is part of Shuup. # # Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of
this source tree. import pytest from django.test import override_settings from shuup.admin.modules.shops.views.edit import ShopEditView from shuup.testing.factories i
mport get_default_shop from shuup.testing.utils import apply_request_middleware from shuup.utils.excs import Problem @pytest.mark.django_db def test_multishop_edit_view(rf, admin_user): get_default_shop() request = apply_request_middleware(rf.get("/"), user=admin_user) view = ShopEditView(request=request...
lightbase/cocar-agente
cocar/tests/test_discover.py
Python
gpl-2.0
2,936
0.000683
#!/bin/env python # -*- coding: utf-8 -*- __author__ = 'eduardo' import unittest import os import os.path import cocar.tests from ..session import Host, SnmpSession, NmapSession from ..model import network from .. import utils class TestDiscover(unittest.TestCase): """ Testa descoberta de ativos de rede util...
utfile = self.data_dir + "/" + self.localhost + ".xml" session = NmapSession(
host=self.localhost, outfile=outfile ) result = session.scan() assert result # Tenta achar o arquivo assert (os.path.isfile(outfile)) def test_scan_rede_full(self): """ Realiza busca em todos os IP's da rede e grava resultados num arquivo específ...
sunze/py_flask
venv/lib/python3.4/site-packages/celery/tests/backends/test_cache.py
Python
mit
9,216
0
from __future__ import absolute_import import sys import types from contextlib import contextmanager from kombu.utils.encoding import str_to_bytes from celery import signature from celery import states from celery import group from celery.backends.cache import CacheBackend, DummyClient from celery.exceptions import...
is not None: sys.modules['pylibmc'] = prev class test_get_best_memcache(AppCase, MockCacheMixin): def test_pylibmc(self): with self.mock_pylibmc(): with reset_modules('celery.backends.cache'): from celery.backends import cache cache._imp = [Non...
libmc') def test_memcache(self): with self.mock_memcache(): with reset_modules('celery.backends.cache'): with mask_modules('pylibmc'): from celery.backends import cache cache._imp = [None] self.assertEqual(cache.get_bes...
doirisks/dori
models/10.1001:archinte.167.10.1068/config_gener_a.py
Python
gpl-3.0
6,742
0.016612
# -*- coding: utf-8 -*- # a template for making config.json files for functions #import pprint #pp = pprint.PrettyPrinter(indent=4) config = {} # human and machine readable names for the model config['id'] = {} config['id']['DOI'] = '10.1001/archinte.167.10.1068' # DOI tag '99.99...
m' # name of specific model 'Demo Model' config['id']['yearofpub'] = '2007' # year of publication '2100' config['id']['authors'] = ['Wilson, W.F.'] # population constraints config['population'] = {} config['population']['must'] = [''] config['population']['
mustnot'] = ['Type 2 Diabetes Mellitus'] config['population']['mustCUI'] = [''] # CUIs for necessary ['C0810085'] config['population']['mustnotCUI'] = ['C1832387'] # CUIs for unacceptable ['C1512018'] # human and machine readable input descriptions config['input'] = {} config['input']['name'] =...
MaximilianDenninger/mllib
mllib/basics/converter.py
Python
mit
3,141
0.006686
import numpy as np from .datastructure import DataStructure from . import utilities def convert_data_for_combined(data, current_type, desired_type, len_of_x): if current_type == desired_type: return data if DataStructure.is_valid(desired_type) and DataStructure.is_combined(current_type): if Da...
x, :] = data new_data[len_of_x:, :] = labels return new_data elif DataStructure.is_column(current_type) and DataStructure.is_column(desired_type): # combine data new_data = np.zeros([data.shape[0], data.shape[1] + labels.shape[1]]) new_data[:,...
return new_data else: # last option (both change) switched_type = DataStructure.switch_combine_separate(current_type) temp_combined = convert_data_for_separated(data, labels, current_type, switched_type, ...
firebase/grpc-SwiftPM
src/python/grpcio_tests/tests_aio/interop/methods.py
Python
apache-2.0
17,437
0.000344
# Copyright 2019 The gRPC 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 cop
y 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 i
s 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. """Implementations of interoperability test methods.""" import argparse import asyncio import enum import ...
DreamSourceLab/DSView
libsigrokdecode4DSL/decoders/lpc/__init__.py
Python
gpl-3.0
941
0.012752
## ## This file is pa
rt of the libsigrokdecode project. ## ## Copyright (C) 2012 Uwe Hermann <uwe@hermann-uwe.de> ## ## 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...
n the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not...
edux300/research
cnns/__init__.py
Python
apache-2.0
76
0.026316
#This is a necessary file. Please do not delete. I a
m s
till learning python.
yacloud-io/teleport
examples/etcd/gen.py
Python
apache-2.0
778
0.008997
import base64 from subprocess import call template = '{"kind":"node","version":"v2","metadata":{"name":"%s","labels":{"group":"gravitational/devc"}},"spec":{"addr":"%s","hostname":"%s","cmd_labels":{"kernel":{"period":"5m0s","command":["/bin/uname","-r"],"result":"4.15.0-32-generic"}},"rotation":{"current_id":"","s
tarted":"0001-01-01T00:00:00Z","grace_period":"0s","last_rotated":"0001-01-01T00:00:00Z","schedule":{"update_clients":"0001-01-01T00:00:00Z","update_servers":"0001-01-01T00:00:00Z","standby":"0001-01-01T00:00:00Z"}}}}' for i in range(1, 4000):
node = template % ("node-%d" % i, "127.0.0.%d:3022" %i, "planet-%d"%i) call(['./etcdctl.sh', 'set', '/teleport/namespaces/default/nodes/node-%d'%i, base64.b64encode(node)]) print "set node %i" % i
ohio813/python-ntfs
examples/indxparse/indxparse.py
Python
apache-2.0
5,458
0.001099
""" Clone of INDXParse.py that processes an entire file system. """ import logging from ntfs.volume import FlatVolume from ntfs.BinaryParser import Mmap from ntfs.filesystem import NTFSFilesystem from ntfs.mft.MFT import AttributeNotFoundError from ntfs.mft.MFT import ATTR_TYPE from ntfs.mft.MFT import MREF from ntfs....
t Exception as e: g_logger.warning("Failed to output entry: %s", e) for e in get_directory_index_inactive_entries(fs, directory): try: print(formatter({ "active": False, "path": directory.get_full_path(), "en...
rectories(fs, directory, visitor): """ `visitor` is a function that accepts two parameters: a FileSystem and a Directory this function applies the function `visitor` to each directory in the file system recursively. """ visitor(fs, directory) for d in directory.get_directories(): ...
shuqin/pystudy
pystudy/basic/to100.py
Python
gpl-3.0
4,575
0.006995
import random import sys sys.setrecursionlimit(10000) UPLIMIT = 10000 NUMBERS = 500 NUMBER_RANGE = (1,UPLIMIT/4) def randNums(n): return [randGen(NUMBER_RANGE[0], NUMBER_RANGE[1]) for i in range(n)] def randGen(start, end): return random.randint(start, end) def solve(numlist): if UPLIMIT >= 1000 and...
') f_res.write('Used numbers: %s, UnMatched numbers: %d.\n' % (usedNums, len(unMatchedNums))) f_res.write('origin: %d , final: %d\n' % (len(numlist), len(finalNumList))) for e in finalNumList:
numlist.remove(e) if len(numlist) > 0: f_res.write('Not Occurred numbers: ' + str(numlist)) f_res.close() def to100(numlist): newnumlist = copylist(numlist) (finalResults, unMatchedNums) = solve(newnumlist) newnumlist = copylist(numlist) printResult(finalResults, unMatche...
mabuchilab/Instrumental
instrumental/drivers/motion/kinesis.py
Python
gpl-3.0
2,416
0.002897
# -*- coding: utf-8 -*- # Copyright 2016-2020 Christopher Rogers, Dodd Gray, and Nate Bogdanowicz """ Driver for controlling Thorlabs Kinesis devices. """ from __future__ import division import atexit from importlib import import_module from ...log import get_logger from ...util import to_str from .. impo...
Lazily load required device-specific modules def list_instruments(): NiceTLI.BuildDeviceList() serial_num
s = to_str(NiceTLI.GetDeviceListExt()).strip(',').split(',') return [ParamSet(cls, serial=serial) for cls,serial in ((_try_get_class(sn), sn) for sn in serial_nums) if cls] def initialize_simulations(): """Initialize a connection to the Simulation Manager, which must already be ...
capoe/espressopp.soap
src/integrator/LangevinThermostat.py
Python
gpl-3.0
1,956
0.011759
# Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of t...
. function:: espressopp.integrator.LangevinThermostat(system) :param system: :type system: """ from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import *
from _espressopp import integrator_LangevinThermostat class LangevinThermostatLocal(ExtensionLocal, integrator_LangevinThermostat): def __init__(self, system): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): cxxinit(self, integrator_La...
hootnot/oanda-api-v20
oandapyV20/contrib/requests/stoplossorder.py
Python
mit
2,841
0
# -*- coding: utf-8 -*- from .baserequest import BaseRequest from oandapyV20.types import TradeID, PriceValue from oandapyV20.definitions.orders import TimeInForce, OrderType class StopLossOrderRequest(BaseRequest): """create a StopLossOrderRequest. StopLossOrderRequest is used to build the body for a StopL...
rform the request >>> rv = client.request(r) >>> print(json.dumps(rv, indent=4)) >>> ... """ super(StopLossOrderRequest, self
).__init__() # allowed: GTC/GFD/GTD if timeInForce not in [TimeInForce.GTC, TimeInForce.GTD, TimeInForce.GFD]: raise ValueError("timeInForce: {}".format(timeInForce)) # by default for a STOP_LOSS order self._data...
obi-two/Rebelion
data/scripts/templates/object/building/poi/shared_tatooine_swoop_large4.py
Python
mit
452
0.04646
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Building() result.template
= "object/building/poi/shared_tatooine_swoop_large4.iff" result.attr
ibute_template_id = -1 result.stfName("poi_n","base_poi_building") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
japaric/eulermark.rs
problems/010/010.py
Python
apache-2.0
1,006
0.003976
LIMIT = 2000000 SIZE = (LIMIT - 1) // 2 def f(): ans = 2 sieve = [False] * SIZE for i in range(0, SIZE): if not sieve[i]: p = 2 * i + 3 ans += p for j in range(p * p, LIMIT, 2 * p): sieve[(j - 3) // 2] = T
rue return ans import ctypes import sys CLOCK_MONOTONIC = 1 class timespec(ctypes.Structure): _fields_ = [ ('tv_sec', ctypes.c_long), ('tv_nsec', ctypes.c_long) ] librt = ctypes.CDLL('librt.so.1') clock_gettime = librt.clock_gettime clock_gettime.argtypes = [ctypes.c_int, ctypes.POINTE...
len(sys.argv) == 1: print(f()) elif len(sys.argv) == 2: start, end = timespec(), timespec() iters = int(sys.argv[1]) clock_gettime(CLOCK_MONOTONIC, ctypes.pointer(start)) for _ in range(0, iters): f() clock_gettime(CLOCK_MONOTONIC, ctypes.pointer(end)) print(to_ns(end) - to_ns(sta...
imvu/bluesteel
app/logic/mailing/models/__init__.py
Python
mit
100
0
""
" Automatic Init file """ from app.log
ic.mailing.models.StackedMailModel import StackedMailEntry
ArcAwe/hazc
hazc_device.py
Python
mit
6,518
0.006444
#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd....
except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].exec
ute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longms...
becm/meson
mesonbuild/scripts/yelphelper.py
Python
apache-2.0
5,816
0.002235
# Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to ...
r): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.
log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.sp...
Twinters007/robotpy-wpilib-utilities
robotpy_ext/common_drivers/xl_max_sonar_ez.py
Python
bsd-3-clause
2,749
0.006912
""" These are a set of drivers for the XL-MaxSonar EZ series of sonar modules. The devices have a few different ways of reading from them, and the these drivers attempt to cover some of the methods """ import wpilib from . import driver_base from . import units class MaxSonarEZPulseWidth(wpilib.SensorBase, driver_ba...
param channel: The analog input index which is wired to the analog output pin (pin 3) on the sensor. :param output_units: The Unit instance specifying the format of value to return """ #Save value self.output_units = output_units #Setup the analog input self.analog = wp...
super().__init__() def free(self): """Delete (free) the analog input for the sonar sensor""" self.analog.free() def get(self): """Return the current sonar sensor reading, in the units specified from the constructor""" centimeters = self.analog.getVoltage()/.0049 ...
tradebyte/paci
paci/packages/cli_helper.py
Python
mit
8,172
0.001717
import sys import time import subprocess import os from halo import Halo from log_symbols import LogSymbols from ter
mcolor import colored from paci.packages.shell import Shell DELAY = 0.1 # time to wait for I/O to finish DEBUG = False or bool(os.environ.get("debug")) def debug_execute(cmd, cwd=None): """Runs a command in debug mode and returns it's output Parameters ---------- cmd : str The shell comman...
ptional The path to the working directory. Returns ------- A generator of the stdout with the results of the command. """ print("Executing command: " + ' '.join(cmd)) popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, universa...
tpeek/Copy-n-Haste
CopyHaste/cnh_scores/urls.py
Python
mit
660
0
from django.conf.urls import url from django.contrib.auth.decorators import login_required from .views import MatchScoreView, ScoreFormView, UserScoreView urlpatterns = [ url( r'^$', login_required( UserScoreView.as_view(template_name='scores.html') ), name='scores' ...
ScoreFormView.as_view(template_name='scores.html') ), name='score_form' ), url( r'^match_score$', login_required(
MatchScoreView.as_view(template_name='match_score.html') ), name='match_score' ), ]
curiosityio/taiga-docker
taiga-back/taiga-back/taiga/searches/serializers.py
Python
mit
2,043
0
# Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net> # This program is free software: you can redistribute it and/or mo...
tasks.models import Task from taiga.projects.wiki.models import WikiPage class IssueSearchResultsSerializer(IssueSerializer): class Meta: model = Issue fields = ('id', 'ref', 'subject', 'status', 'assigned_to') class
TaskSearchResultsSerializer(TaskSerializer): class Meta: model = Task fields = ('id', 'ref', 'subject', 'status', 'assigned_to') class UserStorySearchResultsSerializer(UserStorySerializer): class Meta: model = UserStory fields = ('id', 'ref', 'subject', 'status', 'total_points...
microsoft/O-CNN
pytorch/ocnn/resnet.py
Python
mit
1,194
0.00335
import torch import ocnn class ResNet(torch.nn.Module): def __init__(self, depth, channel_in, nout, resblk_num): super(ResNet, self).__init__() self.depth, self.channel_in = depth, channel_in channels = [2 ** max(11 - i, 2) for i in range(depth + 1)] channels.append(channels[depth]) self.conv1 ...
# drop torch.nn.Linear(channels[3], nout)) # fc def forward(self, octree): data = ocnn.octree_pro
perty(octree, 'feature', self.depth) assert data.size(1) == self.channel_in data = self.conv1(data, octree) for i in range(len(self.resblocks)): data = self.resblocks[i](data, octree) data = self.pools[i](data, octree) data = self.header(data) return data
churchill-lab/bam2ec
bam2ec/emase_file.py
Python
isc
1,789
0.002795
# -*- coding: utf-8 -*- import logging from collections import OrderedDict import emase LOG = logging.getLogger('BAM2EC') def in
t_to_list(c, size): ret = [0]*size for i in xrange(0, size): if (c & (1 << i)) != 0: ret[i] = 1 return ret def list_to_int(l): c = 0 for i, onoff in enumerate(l): if onoff == 1: c |= 1 << i return c class EMASE: def
__init__(self, filename=None): self.filename = filename self._target_list = [] self._target_dict = OrderedDict() self._haplotypes_list = [] self._haplotypes_dict = OrderedDict() # Version 0 self._reads_list = [] self._reads_dict = OrderedDict() ...
netkraken/analyzer
src/unittest/python/testhelper.py
Python
apache-2.0
299
0.003344
def myAssertDictEqual(a, b): dictAInB(a, b) dictAInB(b, a) def dictAInB(a, b):
for akey, avalue in a.items(): bvalue = b.get(akey) if akey in b: if avalue == bvalue: continue raise Exception("%s[
%s] != [%s]" % (akey, avalue, bvalue))
ArcherSys/ArcherSys
skulpt/src/lib/wave.py
Python
mit
67
0
raise NotImplemen
tedError("wave is not yet implemented in Skul
pt")
Richard-Mathie/cassandra_benchmark
vendor/github.com/datastax/python-driver/tests/unit/test_exception.py
Python
apache-2.0
2,375
0.004211
# Copyright 2013-2016 DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
rrect output string """ consistency_str = self.extract_consistency(repr(Unavailable("Unavailable
Message", consistency=None))) self.assertEqual(consistency_str, 'Not Set') for c in ConsistencyLevel.value_to_name.keys(): consistency_str = self.extract_consistency(repr(Unavailable("Timeout Message", consistency=c))) self.assertEqual(consistency_str, ConsistencyLevel.value_to_name...
libravatar/libravatar
libravatar/tools/test_views.py
Python
agpl-3.0
4,299
0.004652
# Copyright (C) 2011, 2016 Francois Marier <francois@libravatar.org> # # This file is part of Libravatar # # Libravatar is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, ...
p, result) class ToolsTestCase(TestCase): def setUp(self): pass # Nothing to do def testIpLookup(self): self.assertTrue(match_regexp(lookup_ip_address('www.google.com', False), r'^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'))
self.assertTrue(match_regexp(lookup_ip_address('ipv6.google.com', True), r'^[0-9a-f:]+$')) def testFullEmailLookup(self): c = Client() response = c.post('/tools/check/', {'email': 'person@example.com', 'size': '80'}) self.assertEquals(response.status_code, 200) self.assertTrue...
jwass/mixpandas
mixpandas.py
Python
mit
7,355
0.003127
""" mixpandas.py A library to request data from Mixpanel's Raw Data Export API """ import datetime import hashlib import urllib.request, urllib.parse, urllib.error import time try: import json except ImportError: import simplejson as json import pandas as pd VERSION = '2.0' # Mixpanel API version date_form...
ptional Returned DataFrame will only contain the specified parameters exclude_mp: Filter out Mixpanel-specific data. default True
Filter out event properties that begin with '$' or 'mp_'. These properties are automatically inserted by Mixpanel and indicate things like region, OS, etc. For more information, see: https://mixpanel.com/docs/api-documentation/exporting-raw-data-you-inserted-into-mixpanel """ ...
sonaht/ansible
lib/ansible/modules/source_control/git.py
Python
gpl-3.0
45,468
0.002199
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # # 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...
neral Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'core'} DOCUMENTATION = ''' --- module: git author: - "Ansible Core Team" - "Michael DeHaan" version_added: "0.0.1" short_description: Deploy software (or files) from git checkouts d...
kdaily/altanalyze
OBO_import.py
Python
apache-2.0
30,390
0.024712
###OBO_import #Copyright 2005-2008 J. David Gladstone Institutes, San Francisco California #Author Nathan Salomonis - nsalomonis@gmail.com #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 Softwar...
as one parent, one parent can have many children
children = e
defshine/cleanblog
run.py
Python
mit
127
0.007874
from app import create_app app = create
_app() if __name__ == "__main__": app.run(host="0.0.0.0", port=5
000, debug=True)
chop-dbhi/biorepo-portal
registration/views.py
Python
bsd-2-clause
3,005
0.002995
from django.shortcuts import redirect from django.shortcuts import render from django.views.decorators.cache import never_cache from django.contrib.auth.decorators import permission_required from django.contrib.auth.decorators import login_required from registration.backends import get_backend def register(request, ba...
e, {'form': form}) @never_cache def verify(request, backend='default', template_name='registration/registration_verify.html', **kwargs): backend = get_backend(backend) profile = backend.get_profile(request, **kwargs) if profile: # check to see if moderation for this profile is required and whether...
profile): moderation_required = True backend.verify(request, profile, **kwargs) else: moderation_required = False # attempt to activate this user backend.activate(request, profile, **kwargs) else: moderation_required = None return rend...
MOA-2011/enigma2-plugin-extensions-openwebif
plugin/controllers/views/web/gettags.py
Python
gpl-2.0
5,093
0.010799
#!/usr/bin/env python ################################################## ## DEPENDENCIES import sys import os import os.path try: import builtins as builtin except ImportError: import __builtin__ as builtin from os.path import getmtime, exists import time import types from Cheetah.Version import MinCompatib...
getattr(self._CHEETAH__filtersLib, filterName)(self).filter write(u'''<?xml version="1.0" encoding="UTF-8"?> <e2tags> ''') for tag in VFFSL(SL,"tags",True): # generated from line 4, col 2 write(u'''\t\t<e2tag>''') _v = VFFSL(SL,"tag",Tr
ue) # u'$tag' on line 5, col 10 if _v is not None: write(_filter(_v, rawExpr=u'$tag')) # from line 5, col 10. write(u'''</e2tag> ''') write(u'''</e2tags> ''') _filter = self._CHEETAH__currentFilter = _orig_filter_91099948 ######################################## ...
GoogleCloudPlatform/training-data-analyst
blogs/gcp_forecasting/tf_module/trainer/task.py
Python
apache-2.0
2,729
0.012825
import argparse import json import os import shutil from .model import train_and_evaluate if __name__ == "__main__": parser = argparse.ArgumentParser() # File arguments parser.add_argument( "--train_file_pa
ttern", help="GCS location to read training data.", required=True ) parser.add_argument( "--eval_file_pattern", help="GCS location to read evaluation data.", required=True ) parser.add_argument( "--output_dir", help="GCS location to write checkpoints and export models."...
) parser.add_argument( "--job-dir", help="This model ignores this field, but it is required by gcloud.", default="junk" ) # Sequence shape hyperparameters parser.add_argument( "--seq_len", help="Number of timesteps to include in each example.", type=int, default=30 ...
zhiyue/owllook
owllook/spiders/qidian_ranking.py
Python
apache-2.0
3,084
0.001338
#!/usr/bin/env python import time from talonspider import Spider, Item, TextField, AttrField from talonspider.utils import get_random_user_agent import os os.environ['MODE'] = 'PRO' from owllook.database.mongodb import MotorBase from owllook.utils.tools import async_callback class RankingItem(Item): target_item ...
(css_select='div.book-list>ul>li') def tal_more(self, more): return "http:" + more class NameItem(Item): top_name = TextField(css_select='h4>a') other_name = TextField(css_select='a.name') class QidianRankingSpider(
Spider): start_urls = ["http://r.qidian.com/?chn=" + str(url) for url in [-1, 21, 1, 2, 22, 4, 15, 6, 5, 7, 8, 9, 10, 12]] headers = { "User-Agent": get_random_user_agent() } set_mul = True qidian_type = { '-1': '全部类别', '21': '玄幻', '1': '奇幻', '2': '武侠', ...
egabancho/logbook
tests/ui/test_views.py
Python
mit
502
0
# -*- coding: utf-8 -*- # # Copyright (C) 2018 Esteban J. G. Gabancho. # # LogBook is free software; you can redistribute it and/or modify it # under the terms of the M
IT License; see LICENSE file for more details. """Views tests.""" from __f
uture__ import absolute_import, print_function from flask import url_for def test_ping(client): """Test the ping view.""" resp = client.get(url_for('logbook.ping')) assert resp.status_code == 200 assert resp.get_data(as_text=True) == 'OK'
feststelltaste/software-analytics
demos/20180731_Munich/ausi/portfolio.py
Python
gpl-3.0
1,400
0.010714
#!/usr/bin/env python # -*- encoding: utf-8 -*- import matplotlib.pyplot as plt def plot_diagram(plot_data, x, y, size='Size'): fig, ax = plt.subplots() ax = plot_data.plot.scatter( x, y, s=plot_data[size] * 100, alpha=0.7, title="Portfolio-Analyse", figsi...
ata[x].max()*1/4, plot_data[y].max()*3/4, "Strengths", ha="center", fontsize=24) ax.text(plot_data[x].max()*3/4, plot_data[
y].max()*3/4, "Weaknesses", ha="center", fontsize=24) ax.text(plot_data[x].max()*1/4, plot_data[y].max()*1/4, "Opportunities", ha="center", fontsize=24) ax.text(plot_data[x].max()*3/4, plot_data[y].max()*1/4, "Threats", ha="center", fontsize=24) for k, v in plot_data[[x, y]].iterrows(): ax.anno...
jayrav13/ical_dict
setup.py
Python
mit
497
0.042254
from
distutils.core import setup setup( name = 'ical_dict', packages = ['ical_dict'], version = '0.2', description = 'A Python library to convert an .ics file into a Dictionary object.', author = 'Jay Ravaliya', author_email = 'jayrav13@gmail.com', url = 'https://github.com/jayrav13/ical_dict', ...
son', 'dictionary', 'python'], classifiers = [], )
Tehsmash/networking-cisco
networking_cisco/plugins/cisco/l3/rpc/l3_router_cfg_agent_rpc_cb.py
Python
apache-2.0
7,134
0.000561
# Copyright 2014 Cisco Systems, 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 requir...
g agent. :param context: contains user information :param host: originator of callback :param router_ids: list of router ids to return information about :param hosting_device_ids: list of hosting device ids to get routers for. :returns: a list of routers with their h...
= ( self._l3plugin.list_active_sync_routers_on_hosting_devices( adm_context, host, router_ids, hosting_device_ids)) except AttributeError: routers = [] LOG.debug('Routers returned to Cisco cfg agent@%(agt)s:\n %(routers)s', {'agt': host, ...
rg3/youtube-dl
youtube_dl/extractor/pinterest.py
Python
unlicense
7,598
0.001316
# coding: utf-8 from __future__ import unicode_literals import json import re from .common import InfoExtractor from ..compat import compat_str from ..utils import ( determine_ext, float_or_none, int_or_none, try_get, unified_timestamp, url_or_none, ) class PinterestBaseIE(InfoExtractor): ...
title') or video_id).strip()
urls = [] formats = [] duration = None if extract_formats: for format_id, format_dict in data['videos']['video_list'].items(): if not isinstance(format_dict, dict): continue format_url = url_or_none(format_dict.get('url')) ...
LLNL/spack
var/spack/repos/builtin/packages/py-azure-keyvault-secrets/package.py
Python
lgpl-2.1
996
0.003012
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class PyAzureKeyvaultSecrets(PythonPackage): """Microsoft Azure Key Vault Secrets Client Library for Python.""" ...
-azure-core@1.2.1:1', type=('build', 'run')) depends_on('py-msrest@0.6.0:', type=('build', 'run')) depends_on('py-azure-keyvault-nspkg', when='^python@:2', type=('build',
'run')) depends_on('py-enum34@1.0.4:', when='^python@:3.3', type=('build', 'run')) depends_on('py-typing', when='^python@:3.4', type=('build', 'run'))
WebCampZg/conference-web
voting/migrations/0003_votetoken.py
Python
bsd-3-clause
880
0.002273
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-08-28 17:08 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ mig
rations.swappable_dependency(settings.AUTH_USER_MODEL), ('voting', '0002_auto_20150813_2010'), ] operations = [ migrations.CreateModel( name='VoteToken', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='...
oOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
mo-g/iris
lib/iris/tests/unit/fileformats/pp/test__field_gen.py
Python
gpl-3.0
5,006
0
# (C) British Crown Copyright 2013 - 2015, Met Office # # This file is part of Iris. # # Iris 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 l...
ss Test(tests.IrisTest): @contextlib.contextmanager def mock_for_field_gen(self, fields): side_effect_fields = list(fields)[:] def make_pp_field_override(*args): # Iterates over the fields passed to this context manager, # until there are no more, upon whi
ch the np.fromfile # returns an empty list and the while loop in load() is # broken. result = side_effect_fields.pop(0) if not side_effect_fields: np.fromfile.return_value = [] return result if six.PY3: open_func = 'builtin...
nozuono/calibre-webserver
src/calibre/gui2/tweak_book/polish.py
Python
gpl-3.0
2,555
0.005479
#!/usr/bin/env python # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' from functools import partial from PyQt4.Qt import ( QTextBrowser, QVBox...
nBox.Cancel) d.l.addWidget(d.bb)
d.bb.rejected.connect(d.reject) d.bb.accepted.connect(d.accept) if d.exec_() != d.Accepted: raise Abort() ans['remove_unused_classes'] = tprefs['remove_unused_classes'] = c.isChecked() def get_customization(action, name, parent): ans = CUSTOMIZATION.copy() try: if action == 'rem...
indictranstech/focal-erpnext
patches/v4_0/update_users_report_view_settings.py
Python
agpl-3.0
443
0.009029
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GN
U General Public License v3. See license.txt from __future__ import unicode_literals from frappe.model import update_users_report_view_settings from erpnext.patches.v4_0.fields_to_be_renamed import rename_map def execute(): for dt, field_list in rename_map.items(): for field in field_list: update_users_report_...
])
plotly/python-api
packages/python/plotly/plotly/validators/scattermapbox/_texttemplate.py
Python
mit
527
0
import _plotly_utils.basevalidators class TexttemplateValidator(_plotly_utils.base
validators.StringValidator): def __init__( self, plotly_name="texttemplate", parent_name="scattermapbox", **kwargs ): super(TexttemplateValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name,
array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "info"), **kwargs )
garthylou/Libreosteo
libreosteoweb/migrations/0007_auto_20150123_0851.py
Python
gpl-3.0
2,744
0.005831
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('libreosteoweb', '0006_examination_status_reason'), ] operations = [ migrations.CreateModel( name='Invoice', ...
('paiment_mode', models.CharField(max_length=10, verbose_name='Paiment mode')), ('header', models.TextField(verbose_name='Header', blank=True)), ('therapeut_name', models.TextField(verbose_name='Therapeut')), ('therapeut_firstname', models.TextField(verbose_name='T...
('location', models.TextField(verbose_name='Location')), ('number', models.TextField(verbose_name='Number')), ('patient_family_name', models.CharField(max_length=200, verbose_name='Family name')), ('patient_riginal_name', models.CharField(max_length=200, ...
eepp/barectf
barectf/cli.py
Python
mit
5,869
0.000682
# The MIT License (MIT) # # Copyright (c) 2014-2016 Philippe Proulx <pproulx@efficios.com> # # 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 ...
s # 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 port...
E WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT 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 O...
luboslenco/cyclesgame
blender/arm/material/make_depth.py
Python
lgpl-3.0
7,521
0.003457
import bpy import arm.material.cycles as cycles import arm.material.mat_state as mat_state import arm.material.mat_utils as mat_utils import arm.material.make_skin as make_skin import arm.material.make_inst as make_inst import arm.material.make_tess as make_tess import arm.material.make_particle as make_particle import...
f con_depth.is_elem('tex1'): vert.add_out('vec2 texCoord1') ## vs only, remove out vert.add_uniform('float texUnpack', link='_texUnpack') vert.write_attrib('texCoord1 = tex1 * texUnpack;') if con_depth.is_elem('col'): vert.add_out('vec3 vcolor'...
tion += wnormal * disp;') if shadowmap: vert.add_uniform('mat4 LVP', '_lightViewProjectionMatrix') vert.write('gl_Position = LVP * vec4(wposition, 1.0);') else: vert.add_uniform('mat4 VP', '_viewProjectionMatrix') vert.write('gl_Pos...
cmcneil/lilguys
guytracker/admin.py
Python
gpl-2.0
137
0
from guytracker.models import Li
lguy, Chapter from django.contrib import admin admin.site.register(Lilguy) admin.site.register(Chapt
er)
EnduranceIndia/ratelimitd
ProfileLookups/HTTPLookup.py
Python
apache-2.0
1,328
0.002259
""" Copyright 2015 Sai Gopal 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 dist...
if ttl != 0: RedisConn.Redis_Master.setex('HTTPLookupProfile_' + key, profile, ttl) except Exception as e: Logger.log('H
TTPLookup Error : %s Message : %s' % (type(e), e.args)) profile = 'default' return profile def __init__(self, url): self.url = url
kartyboyz/n64-img-processing
testing/test_start.py
Python
mit
1,854
0.007551
import unittest import cv2 as cv import numpy as np import detection from test_utils import * class StartTest(unittest.TestCase): def setUp(self): self.detector = detection.BeginRace(masks_dir='./masks/start/', freq=1, ...
t in rv['events']: self.assertEqual(event['event_type'], 'Lap') self.assertEqual(event['event_subtype'], 'BeginRace') self
.assertEqual(event['info'], 'BeginRace') def test_start_FailCase(self): rv = video_loop('./testing/start/FailCase/FailCase.mov', self.detector, [(4, 317), (0, 237)], self.detector.detector_states) self.assertEqual(len(rv['events']), 0) if __name__ == '__main__': unittest.main()
hackerbot/DjangoDev
django/template/loaders/eggs.py
Python
bsd-3-clause
2,307
0.0013
# Wrapper for loading templates from eggs via pkg_resources.resource_string. from __future__ import unicode_literals import warnings from django.apps import apps from django.template.base import Origin, TemplateDoesNotExist from django.utils import six from django.utils.deprecation import RemovedInDjango21Warning fr...
For every installed app, it tries to get the resource (app, template_name). """ warnings.warn( 'The load_template_sources() method is deprecated. Use ' 'get_template() or get_contents() instead.', RemovedInDjango21Warning, ) for origin in self.get_t...
rces(template_name): try: return self.get_contents(origin), origin.name except TemplateDoesNotExist: pass raise TemplateDoesNotExist(template_name)
Uli1/mapnik
scons/scons-local-2.4.0/SCons/Variables/PathVariable.py
Python
lgpl-2.1
5,646
0.000886
"""SCons.Variables.PathVariable This file defines an option type for SCons implementing path settings. To be used whenever a a user-specified path override should be allowed. Arguments to PathVariable are: option-name = name of this option on the command line (e.g. "prefix") option-help = help string for optio...
o, 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 TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 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 C...
denys-duchier/Scolar
ZopeProducts/exUserFolder/Plugins.py
Python
gpl-2.0
1,784
0.019058
# # # (C) Copyright 2001 The Internet (Aust) Pty Ltd # ACN: 082 081 472 ABN: 83 082 081 472 # All Rights Reserved # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ...
MAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # Author: Andrew Milton <akm@the...
raphaelvalentin/Utils
functions/system.py
Python
gpl-2.0
3,297
0.017288
import re, time, os, shutil, string from subprocess import Popen, PIPE, STDOUT from random import randint, seed __all__ = ['find', 'removedirs', 'source', 'tempfile', 'copy', 'rm', 'template, template_dir'] def find(path='.', regex='*', ctime=0): r = [] regex = str(regex).strip() if regex == '*': regex = ...
if force and os.path.isdir(dest): # not good for speed rm(dest) shutil.copytree(src, dest) except OSError as e: # if src is not a directory if e.errno == errno.EN
OTDIR: shutil.copy(src, dest) else: print('%s not copied. Error: %s'%(src, e)) def template(src, dest, substitute={}): with open(src) as f: s = string.Template(f.read()) o = s.safe_substitute(substitute) with open(dest, 'w') as g: g.write(o) def template...
stormi/tsunami
src/secondaires/diligence/__init__.py
Python
bsd-3-clause
4,815
0.000627
# -*-coding:Utf-8 -* # Copyright (c) 2014 LE GOFF Vincent # All rights reserved. # # Redistribution and use in sourc
e and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright n...
lder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IM...
woodem/woo
obsolete/examples/baraban/baraban.py
Python
gpl-2.0
2,018
0.031715
#!/usr/bin/python # -*- coding: utf-8 -*- import time ## PhysicalParameters Density=2400 frictionAngle=radians(35) tc = 0.001 en = 0.3 es = 0.3 ## Import wall's geometry params=utils.getViscoelasticFromSpheresInteraction(tc,en,es) facetMat=O.materials.append(ViscElMat(frictionAngle=frictionAngle,**params)) # **param...
aban.stl',color=(1,0,0),material=facetMat)) ## Spheres sphereRadius = 0.2 nbSpheres = (10,10,10) #nbSpheres = (50,50,50) for i in range(nbSpheres[0]): for j in range(nbSpheres[1]): for k in range(nbSpheres[2]): x = (i*2 - nbSpheres[0])*sphereRadius*1.1 y = (j*2 - nbSpheres[1])*sphere...
es[2])*sphereRadius*1.1 s=utils.sphere([x,y,z],sphereRadius,material=sphereMat) O.bodies.append(s) ## Timestep O.dt=.2*tc ## Engines O.engines=[ ## Resets forces and momenta the act on bodies ForceResetter(), ## Using bounding boxes find possible body collisions. InsertionSor...
ejucovy/django-opendebates
opendebates/migrations/0019_sitemode.py
Python
apache-2.0
1,059
0.002833
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import datetime import caching.base class Migration(migrations.Migration): dependencies = [ ('opendebates', '0018_flag_note'), ] operations = [ migrations.CreateModel( na...
els.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('show_question_votes', models.BooleanField(default=True)), ('show_total_votes', models.BooleanField(default=True)), ('allow_sorting_by_votes', models.BooleanField(default=True)), ...
'debate_time', models.DateTimeField(default=datetime.datetime(2099, 1, 1, 0, 0), help_text=b'Enter time that debate starts in timezone America/New_York')), ], bases=(caching.base.CachingMixin, models.Model), ), ]
Southpaw-TACTIC/Team
src/python/Lib/site-packages/PIL-1.1.7-py2.6-win32.egg/_imagingtk.py
Python
epl-1.0
288
0.034722
d
ef __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__,'_imagingtk.pyd') __loader__ = None; del __bootstrap__, __loader__ imp.load_dynamic(__name__,__file__) __boo
tstrap__()
Samweli/inasafe
safe/impact_functions/generic/classified_polygon_people/metadata_definitions.py
Python
gpl-3.0
4,644
0
# coding=utf-8 """InaSAFE Disaster risk tool by Australian Aid - Classified Polygon on Land Cover Metadata
Definitions. Contact : ole.moller.nielsen@gmail.com .. note:: 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. ...
ties import OrderedDict from safe.impact_functions.impact_function_metadata import \ ImpactFunctionMetadata from safe.definitions import ( area_name_field, area_id_field, exposure_population, hazard_all, hazard_category_single_event, hazard_category_multiple_event, generic_vector_hazard_...
baylee/django
tests/messages_tests/base.py
Python
bsd-3-clause
14,082
0.000639
from django import http from django.contrib.messages import constants, get_level, set_level, utils from django.contrib.messages.api import MessageFailure from django.contrib.messages.constants import DEFAULT_LEVELS from django.contrib.messages.storage import base, default_storage from django.contrib.messages.storage.ba...
: super(override_settings_tags, self).enable() # LEVEL_T
AGS is a constant defined in the # django.contrib.messages.storage.base module, so after changing # settings.MESSAGE_TAGS, we need to update that constant too. self.old_level_tags = base.LEVEL_TAGS base.LEVEL_TAGS = utils.get_level_tags() def disable(self): super(override_se...
ntt-sic/nova
nova/api/openstack/compute/contrib/flavormanage.py
Python
apache-2.0
3,894
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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...
a.api.openstack import extensions from nova.api.openstack import wsgi from nova.compute import flavors from nova import exception from nova.openstack.common.gettextutils import _ authorize = extensions.extension_authorizer('compute', 'flavormanage') class FlavorManageController(wsgi.Controller): """ The Fla...
ler, self).__init__() @wsgi.action("delete") def _delete(self, req, id): context = req.environ['nova.context'] authorize(context) try: flavor = flavors.get_flavor_by_flavor_id( id, ctxt=context, read_deleted="no") except exception.NotFound as e: ...
jwatson/dotfiles
config/coc/extensions/node_modules/coc-python/pythonFiles/refactor.py
Python
mit
10,906
0.002751
# Arguments are: # 1. Working directory. # 2. Rope folder import difflib import io import json import os import sys import traceback try: import rope from rope.base import libutils from rope.refactor.rename import Rename from rope.refactor.extract import ExtractMethod, ExtractVariable import rope....
ange.ChangeContents): self.changes.append( Change(item.resource.real_path, ChangeType.EDIT, get_diff(item))) else: raise Exception('Unknown Change') class ExtractVariableRefactor(BaseRefactoring): def __init__(self, project, resource, name="Extract ...
name, progressCallback) self._newName = newName self._startOffset = startOffset self._endOffset = endOffset self._similar = similar self._global = global_ def onRefactor(self): renamed = ExtractVariable( self.project, self.resource, sel...
handroll/handroll
handroll/site.py
Python
bsd-2-clause
3,736
0
# Copyright (c) 2017, Matt Layman """The website model""" import os from handroll import template from handroll.exceptions import AbortError from handroll.i18n import _ class Site(object): """A Site represents a handroll site source. This class contains validation logic to confirm that a directory is a...
skipping items that should be skipped."""
for dirpath, dirnames, filenames in os.walk(self.path): # Prevent work on the output or templates directory. # Skip the template. if dirpath == self.path: if self.OUTPUT in dirnames: dirnames.remove(self.OUTPUT) if template.TE...