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
larrybradley/astropy
astropy/wcs/tests/test_wcsprm.py
Python
bsd-3-clause
27,671
0.000217
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst import gc import locale import re from packaging.version import Version import pytest import numpy as np from numpy.testing import assert_array_equal, assert_array_almost_equal from astropy.io import fits from astropy.wcs import...
, 1]] asse
rt w.cd.dtype == float assert w.has_cd() is True assert_array_equal(w.cd, [[1, 0], [0, 1]]) del w.cd assert w.has_cd() is False def test_cd_missing(): w = _wcs.Wcsprm() assert w.has_cd() is False with pytest.raises(AttributeError): w.cd def test_cd_missing2(): w = _wcs.Wcsprm...
Property404/OSIR
server/admin/xcrypt.py
Python
gpl-3.0
1,528
0.081806
#!/usr/bin/env python import base64 from os import urandom from sys import argv _XOR_KEY_SIZE=8 #xor two strings def xor_str(s1,s2): #print([a for a in s2]); return bytearray(s1[i]^s2[i%_XOR_KEY
_SIZE] for i in range(len(s1))) #xor msg with random key, encode in b64 def encrypt(msg): msg+=bytearray([msg[0]^msg[len(msg)-1]]) key=urandom(_XOR_KEY_SIZE); return (base64.b64encode((key+xor_str(msg,key))))+b"="; #Undo encrypt def decrypt(msg): try: msg=base64.b64decode(msg) except base64.binascii.Error: ...
"File not in base64"); exit(1); rmsg=xor_str(bytearray(i for i in msg[_XOR_KEY_SIZE::]),msg[0:_XOR_KEY_SIZE]); if(rmsg[0] ^ rmsg[-2]==rmsg[-1]):return rmsg[0:-1] print("Integrity check failed"); exit(1); #Make encrypted file def encrypt_file(fname,oname): fp=open(fname,"rb"); ftext=fp.read(); fp.close(); fp...
kgiusti/gofer
test/unit/messaging/test_consumer.py
Python
lgpl-2.1
6,743
0
# Copyright (c) 2014 Red Hat, Inc. # # This software is licensed to you under the GNU General Public # License as published by the Free Software Foundation; either version # 2 of the License (GPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or implied, # including the impl...
consumer = ConsumerThread(node, url) consumer.reader = Mock() consumer.reader.close.side_effect = ValueError # test consumer.close() # validation
consumer.reader.close.assert_called_once_with() @patch('gofer.messaging.consumer.sleep') def test_open_exception(self, sleep): url = 'test-url' node = Node('test-queue') consumer = ConsumerThread(node, url) consumer.reader = Mock() consumer.reader.open.side_effect = [Val...
MatthewDaws/OSMDigest
notebooks/convert_to_db.py
Python
mit
249
0.052209
import sys sys.path.insert(0, "..") import osmdigest.sqlite as sq import os for x
in sq.convert_gen(os.path.join("..","..","..","data","california-latest.osm.xz"), os.path.join("..","..","..","data","califor
nia-latest.db")): print(x)
b0ttl3z/SickRage
sickbeard/postProcessor.py
Python
gpl-3.0
58,238
0.004499
# coding=utf-8 # Author: Nic Wolfe <nic@wolfeden.ca> # URL: https://sickrage.github.io # Git: https://github.com/SickRage/SickRage.git # # This file is part of SickRage. # # SickRage 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...
arranty 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 SickRage. If not, see <http://www.gnu.org/licenses/>. # pylint: disable=too-many-lines from __future__ import print...
ction, unicode_literals import fnmatch import os import re import stat import subprocess import adba import six import sickbeard from sickbeard import common, db, failed_history, helpers, history, logger, notifiers, show_name_helpers from sickbeard.helpers import verify_freespace from sickbeard.name_parser.parser im...
shaunharker/DSGRN
src/DSGRN/SubdomainGraph.py
Python
mit
5,940
0.008081
### SubdomainGraph.py ### Shaun Harker ### 2018-03-25 ### MIT LICENSE from pychomp import * import datetime from itertools import product from math import log2 from DSGRN._dsgrn import * class SubdomainGraph: def complex(self): return self.cc def diagram(self): return self.digraph.adjacencie...
dim = self.wallnormal(wall) return self.cc.right(self.cc.right(wall,dim),dim) ## labelling def
leftlabel(self): return 1 def rightlabel(self): return 2 def isLeftBoundingWall(self, wall): normdim = self.wallnormal(wall) return self.cc.leftfringe(wall) def isRightBoundingWall(self, wall): normdim = self.wallnormal(wall) return self.cc.rightfri...
deployed/django
tests/timezones/tests.py
Python
bsd-3-clause
55,059
0.002034
from __future__ import unicode_literals import datetime import re import sys from unittest import skipIf import warnings from xml.dom.minidom import parseString try: import pytz except ImportError: pytz = None from django.core import serializers from django.core.urlresolvers import reverse from django.db.mod...
20, 30, tzinfo=EAT) with self.assertRaises(ValueError): Event.objects.create(dt=dt) def test_auto_now_and_auto_now_add(self): now = datetime.datetime.now
() past = now - datetime.timedelta(seconds=2) future = now + datetime.timedelta(seconds=2) Timestamp.objects.create() ts = Timestamp.objects.get() self.assertLess(past, ts.created) self.assertLess(past, ts.updated) self.assertGreater(future, ts.updated) se...
anti-social/elasticmagic
elasticmagic/ext/asyncio/index.py
Python
apache-2.0
5,855
0
from ...index import BaseIndex class AsyncIndex(BaseIndex): async def get_es_version(self): return await self._cluster.get_es_version() async def get_compiler(self): return await self._cluster.get_compiler() async def get( self, doc_or_id, doc_cls=None, doc_type=None, source=...
( self, docs, doc_type=None, source=None, realtime=None, routing=None, preference=None, refresh=None, **kwargs ): return await self._cluster.multi_get( docs, index=self._name, doc_type=doc_type, source=source, realtime=realtime, routing=routing, preference=pre...
timeout=None, search_type=None, query_cache=None, terminate_after=None, scroll=None, stats=None, **kwargs ): return await self._cluster.search( q, index=self._name, doc_type=doc_type, routing=routing, preference=preference, timeout=timeout, search_typ...
debomatic/debomatic
Debomatic/process.py
Python
gpl-3.0
6,727
0
# Deb-o-Matic # # Copyright (C) 2011-2021 Luca Falavigna # # Author: Luca Falavigna <dktrkranz@debian.org> # # 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; version 3 of the License. # # This pr...
logging import basicConfig as log, error,
getLogger, info from signal import signal, SIGINT, SIGTERM from sys import stdin, stdout, stderr from threading import Timer as _Timer from time import sleep from Debomatic import dom from .exceptions import DebomaticError class Process: def __init__(self): pass def _daemonize(self): try: ...
yaybu/touchdown
touchdown/frontends/__init__.py
Python
apache-2.0
761
0
# Copyright 2014 Isotoma Limited # # 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...
issions and # limitations under the License. from .cloudwatch import CloudWatchFrontend from .console import ConsoleFrontend from .multi import MultiFrontend __all__ = ["CloudWatchFronte
nd", "ConsoleFrontend", "MultiFrontend"]
yancz1989/cancer
Qi/img_mask_gen.py
Python
mit
2,636
0.024659
#!/usr/bin/python3 import config as cfg import SimpleITK as sitk import numpy as np import csv from glob import glob import pandas as pd from tqdm import tqdm import tools import os def mk
dir(d): try: os.makedirs(d) except: pass df_node = pd.read_csv(cfg.root+"annotations.csv") # Getting list of image file
s for subset in range(10): print("processing subset ",subset) luna_subset_path = os.path.join(cfg.root,"data","subset{}".format(subset)) file_list=sorted(glob(os.path.join(luna_subset_path,"*.mhd"))) #print(file_list) output_path = os.path.join(cfg.root,'img_mask', 'subset{}'.format(subset)) mk...
DataDog/airbrakepy
airbrakepy/__init__.py
Python
apache-2.0
142
0.014085
from me
tadata import version as __version__ from metadata import source_url as __source_url__ from metadata import app_name as __app_nam
e__
sol/pygments
tests/test_shell.py
Python
bsd-2-clause
4,709
0.000425
# -*- coding: utf-8 -*- """ Basic Shell Tests ~~~~~~~~~~~~~~~~~ :copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import unittest from pygments.token import Token from pygments.lexers import BashLexer, BashSessionLexer class BashTest(unit...
ist(self.lexer.get_tokens(fragment)))
def testShortVariableNames(self): fragment = u'x="$"\ny="$_"\nz="$abc"\n' tokens = [ # single lone $ (Token.Name.Variable, u'x'), (Token.Operator, u'='), (Token.Literal.String.Double, u'"'), (Token.Text, u'$'), (Token.Literal.Strin...
krishauser/Klampt
Python/klampt/math/autodiff/pytorch.py
Python
bsd-3-clause
6,627
0.015995
import klampt.math.autodiff.ad as ad import torch,numpy as np class TorchModuleFunction(ad.ADFunctionInterface): """Converts a PyTorch function to a Klamp't autodiff function class.""" def __init__(self,module): self.module=module self._eval_params=[] torch.set_default_dtype(torch.float...
= t if name not in fterminals: raise ValueError("Invalid terminal %s, function call %s only has terminals %s"%(name,str(func),str(terminals))) else: try: if len(terminals) != func.n_args(): raise ValueError("Invalid number of t...
tion %s expects %d"%(str(func),func.n_args())) except NotImplementedError: pass return ADModule(func,terminals)
mazvv/travelcrm
travelcrm/resources/resources_types.py
Python
gpl-3.0
643
0
# -*-coding: utf-8 -*- from zope.interface import implementer from ..interfaces import ( IResourceType, ) from ..resources import (
Resour
ceTypeBase, ) from ..lib.utils.common_utils import translate as _ @implementer(IResourceType) class ResourcesTypesResource(ResourceTypeBase): __name__ = 'resources_types' @property def allowed_assign(self): return True @property def allowed_permisions(self): permisions = ( ...
uqyge/combustionML
FPV_ANN_pureResNet/FPV_resnet_fullycoupled.py
Python
mit
5,137
0.009733
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import tensorflow as tf from keras.models import Model from keras.layers import Dense, Input from keras.callbacks import ModelCheckpoint from resBlock import res_block_org from data_r...
on, stage=1, block='a', bn=batch_norm) x = res_block_org(x, n_neuron, stage=1, block='b', bn=batch_norm) x = res_block_org(x, n_neuron, stage
=1, block='c', bn=batch_norm) #x = res_block(x, n_neuron, stage=1, block='d', bn=batch_norm) predictions = Dense(dim_label, activation='linear')(x) model = Model(inputs=inputs, outputs=predictions) model.compile(loss='mse', optimizer='adam', metrics=['accuracy']) # get the model summary model.summary() # checkpoint ...
eunchong/build
scripts/slave/recipe_modules/ios/test_api.py
Python
bsd-3-clause
1,200
0.009167
# Copyright 2015 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. from copy import deepcopy from recipe_engine import recipe_test_ap
i class iOSTestApi(recipe_test_api.RecipeTestApi): @recipe_test_api.mod_test_data @staticmethod def build_config(config): return deepcopy(config) def make_test_build_config(self, config): return self.build_config(config) @recipe_test_api.mod_test_data @staticmethod def parent_build_config(confi...
'Mac OS X Version': '1.2.3', 'Xcode Version': '6.7.8', 'Xcode Build Version': '5D342509a', 'Xcode SDKs': [ 'fake sdk 1.0', 'fake sdk 1.1', 'fake sdk 2.0', ], }) def test_results(self): return self.m.json.output({ 'links': { 'fake URL text': 'fa...
anhstudios/swganh
data/scripts/templates/object/tangible/deed/event_perk/shared_rebel_3x10_honorguard_deed.py
Python
mit
487
0.045175
#### 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 = Tangible() result.template = "object/tangible/deed/event_perk/shared_rebel_3x10_honorguard_deed.iff" result.attribute_template...
lt
ajhalme/kbsim
KBGUI.py
Python
gpl-3.0
16,260
0.009102
import pygame from pygame.locals import * import sys; sys.path.insert(0, "./lib/") from pgu import gui from Vec2d import * ## ## KBSimulation graphics ## class KBGUI(gui.container.Container): def __init__(self, module): ## Module self.module = module self.config = mo...
r bot if (self.dmode): degree = self.module.linkc[a.secretID] if (degree == 0): a.view.color = self.config['botcolorbase0']
elif (degree == 1): a.view.color = self.config['botcolorbase1'] elif (degree == 2): a.view.color = self.config['botcolorbase2'] else: a.view.color = self.config['botcolorbasex'] a.view...
rmanoni/mi-instrument
mi/instrument/nortek/aquadopp/ooicore/test/test_driver.py
Python
bsd-2-clause
28,532
0.004802
""" @package mi.instrument.nortek.aquadopp.ooicore.test.test_driver @author Rachel Manoni @brief Test cases for ooicore driver USAGE: Make tests verbose and provide stdout * From the IDK $ bin/test_driver $ bin/test_driver -u $ bin/test_driver -i $ bin/test_driver -q * From pyon ...
return sample_as_hex.decode('hex') velocity_particle = [{'value_id': Aqua
doppDwVelocityDataParticleKey.TIMESTAMP, 'value': '26/11/2012 22:10:19'}, {'value_id': AquadoppDwVelocityDataParticleKey.ERROR, 'value': 0}, {'value_id': AquadoppDwVelocityDataParticleKey.ANALOG1, 'value': 0}, {'value_id': AquadoppDwVelocityDataParticleKey....
pombredanne/bokeh
bokeh/charts/tests/test_stats.py
Python
bsd-3-clause
818
0.00489
import pytest from bokeh.charts.stats import Bins from bokeh.models import ColumnDataSource import pandas as pd @pytest.fixture def ds(test_data): return ColumnDataSource(test_data.auto_data) def test_explicit_bin_count(ds): b = Bins(source=ds, column='mpg', bin_cou
nt=2) assert len(b.bins) == 2 def test_a
uto_bin_count(ds): b = Bins(source=ds, column='mpg') assert len(b.bins) == 12 # this should test it still matches # http://stats.stackexchange.com/questions/114490/optimal-bin-width-for-two-dimensional-histogram # with iterables with the same value b = Bins(values=[5,5,5,5,5], bin_count=None) ...
FedoraScientific/salome-paravis
test/VisuPrs/MeshPresentation/F1.py
Python
lgpl-2.1
1,515
0.00198
# Copyright (C) 2010-2014 CEA/DEN, EDF R&D # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library ...
icense for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.c...
# This case corresponds to: /visu/MeshPresentation/F1 case # Create Mesh Presentation for all data of the given MED file import sys from paravistest import datadir, pictureext, get_picture_dir from presentations import CreatePrsForFile, PrsTypeEnum import pvserver as paravis # Create presentations myParavis = para...
tedder/ansible-modules-core
system/systemd.py
Python
gpl-3.0
14,880
0.003965
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Brian Coca <bcoca@ansible.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 the License...
"InactiveEnterTimestampMonotonic": "0", "InactiveExitTimestamp": "Sun 2016-05-15 18:28:49 EDT", "Inactiv
eExitTimestampMonotonic": "8135942", "JobTimeoutUSec": "0", "KillMode": "process", "KillSignal": "15", "LimitAS": "18446744073709551615", "LimitCORE": "18446744073709551615", "LimitCPU": "18446744073709551615", "LimitDATA": "18446744073...
ninegrid/dotfiles-vim
bundle/vim-orgmode/ftplugin/orgmode/liborgmode/documents.py
Python
unlicense
7,913
0.028687
# -*- coding: utf-8 -*- """ documents ~~~~~~~~~ TODO: explain this :) """ from UserList import UserList from orgmode.liborgmode.base import MultiPurposeList, flatten_list, Direction, get_domobj_range from orgmode.liborgmode.headings import Heading, HeadingList class Document(object): u""" Representation of a...
self._tag_column = value return locals() tag_column = property(**tag_column()) def init_dom(self, heading=Heading): u""" Initialize all headings in document - build DOM. This method should be call prior to accessing the document. :returns: self """ def init_heading(_h): u""" :returns the initial...
# * Heading 1 <- heading # * Heading 1 <- sibling # or # * Heading 2 <- heading # * Heading 1 <- parent's sibling if not new_heading or \ new_heading.level <= _h.level: break # * Heading 1 <- heading # * Heading 2 <- first child # * Heading 2 <- another child new_hea...
colour-science/colour
colour/algebra/regression.py
Python
bsd-3-clause
1,998
0
""" Regression ========== Defines various objects to perform regression: - :func:`colour.algebra.least_square_mapping_MoorePenrose`: *Least-squares* mapping using *Moore-Penrose* inverse. References ---------- - :cite:`Finlayson2015` : Finlayson, G. D., MacKiewicz, M., & Hurlbert, A. (2015). Color Correc...
on Image Processing, 24(5), 1460-1470. doi:10.1109/TIP.2015.2405336 """ from __future__ import annotations import numpy as np from colour.hints import ArrayLike, NDArray __author__ = "Colour Developers" __copyright__ = "Copyright
2013 Colour Developers" __license__ = "New BSD License - https://opensource.org/licenses/BSD-3-Clause" __maintainer__ = "Colour Developers" __email__ = "colour-developers@colour-science.org" __status__ = "Production" __all__ = [ "least_square_mapping_MoorePenrose", ] def least_square_mapping_MoorePenrose(y: Arra...
youtube/cobalt
third_party/llvm-project/lldb/third_party/Python/module/pexpect-2.4/examples/bd_serv.py
Python
bsd-3-clause
10,471
0.001528
#!/usr/bin/env python """Back door shell server This exposes an shell terminal on a socket. --hostname : sets the remote host name to open an ssh connection to. --username : sets the user name to login with --password : (optional) sets the password to login with --port : set the local port for th...
ork #1 failed: (%d) %s\n" % (e.errno, e.strerror)) sys.exit(1) # Decouple from parent environment. os.chdir("/") os.umask(0) os.setsid() # Do second fork. try: pid = os.fork() if pid > 0: sys.exit(0) # Exit second parent. except OSError as e: s...
# Now I am a daemon! # Redirect standard file descriptors. si = open(stdin, 'r') so = open(stdout, 'a+') se = open(stderr, 'a+', 0) os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) # I now return as the da...
mrakitin/sirepo
tests/template/srw_generate_data/nsls-ii-hxn-beamline-ssa-closer.py
Python
apache-2.0
36,110
0.004957
#!/usr/bin/env python import os try: __IPYTHON__ import sys del sys.argv[1:] except: pass import srwl_bl import srwlib import srwlpy import srwl_uti_smp def set_optics(v=None): el = [] pp = [] names = ['S1', 'S1_HCM', 'HCM', 'HCM_DCM_C1', 'DCM_C1', 'DCM_C2', 'DCM_C2_HFM', 'HFM', 'After_H...
# CRL2: crl 34.15m el.append(srwlib.srwl_opt_setup_CRL( _foc_plane=v.op_CRL2_foc_plane, _delta=v.op_CRL2_delta, _at
ten_len=v.op_CRL2_atten_len, _shape=v.op_CRL2_shape, _apert_h=v.op_CRL2_apert_h, _apert_v=v.op_CRL2_apert_v, _r_min=v.op_CRL2_r_min, _n=v.op_CRL2_n, _wall_thick=v.op_CRL2_wall_thick, _xc=v.op_CRL2_x, ...
cherry-hyx/hjb-test
pluginsAgent/RichAPM/packages/dictconfig.py
Python
artistic-2.0
22,792
0.000219
# # Copyright (C) 2009-2013 Vinay Sajip. See LICENSE.txt for details. # import logging.handlers import re import sys try: basestring except NameError: basestring = str try: StandardError except NameError: StandardError = Exception IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I) def valid_ident(s...
result.key = key return result def pop(self, key, defaul
t=None): value = dict.pop(self, key, default) result = self.configurator.convert(value) if value is not result: if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key ...
borg-project/borg
borg/experiments/simulate_runs.py
Python
mit
6,090
0.009031
"""@author: Bryan Silverthorn <bcs@cargo-cult.org>""" import os.path import csv import uuid import sklearn import condor import borg logger = borg.get_logger(__name__, default_level = "INFO") class PortfolioMaker(object): def __init__(self, portfolio_name, bins = 60): name_parts = portfolio_name.split(":...
"-": makers = map(SolverMaker, t
rain_data.solver_names) else: makers = [PortfolioMaker(run["portfolio_name"])] for maker in makers: for (train_fold_data, test_fold_data) in data_sets: yield (simulate_run, [run, maker, train_fold_data, test_fold_data]) with borg.util.ope...
tejal29/pants
tests/python/pants_test/backend/codegen/tasks/test_antlr_gen.py
Python
apache-2.0
4,507
0.007544
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re ...
te_antlr4_test(self.PARTS['dir'].replace('/', '.')) def test_derived_package_invalid(self): self.create_file(relpath='{srcroot}/{dir}/sub/not_read.g4'.format(**self.PARTS), contents='// does not matter') self.add_to_build_file('{srcroot}/{dir}/BUILD'.format(**self.PARTS), dedent(''' ...
ead.g4'], ) '''.format(**self.PARTS))) with self.assertRaises(AntlrGen.AmbiguousPackageError): self.execute(self.create_context())
zuun77/givemegoogletshirts
leetcode/python/714_best-time-to-buy-and-sell-stock-with-transaction-fee.py
Python
apache-2.0
335
0.002985
class Solution: def maxProfit(self, prices, fee): dp = [[-prices[0]], [0]] for i in range(1, len(prices)): dp[0].append(max(dp[0][i-1], dp[1][i-1]-prices[i])) dp[1].append(max(dp[0][i-1]+pr
ices[i]-fee, dp[1][i-1])) return dp[1][-1] print(Solution().maxProfit([1, 3, 2
, 8, 4, 9], 2))
TU-Berlin/mathosphere
pomlp/lib/latex2mathml/setup.py
Python
apache-2.0
1,134
0.001764
from distutils.core import setup VERSION = open('VERSION').read() setup( name='latex2mathml', version=VERSION, packages=['latex2mathml'], url='https://github.com/Code-ReaQtor/latex2mathml', download_url='https://github.com/Code-ReaQtor/latex2mathml/tarball/{}'.format(VERSION), license='MIT', ...
, author_email='ronmarti18@gmail.com', description='Pure Python library for LaTeX to MathML conversion.', long_description=open('README.rst').read(), keywords=[], classifiers=['Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Topic :: Soft...
'Programming Language :: Python :: 3', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Text Processing :: Markup :: HTML', 'Topic :: Text Processing :: Markup :: LaTeX'], package_data={'latex2mathml': ['unimathsymbols.txt']} )
simsor/PyWeb
tests/test.py
Python
gpl-3.0
260
0.038462
#!/usr/bin/python from PyWeb import * from template import * #f
rom PyWebDynamic import * class TEST: def __init__(self): self.p = PyWeb
("test.html") self.p.addTemplate(myTemplate) self.p.createPage() if __name__ == "__main__": ttestsst = TEST()
mysociety/yournextmp-popit
official_documents/urls.py
Python
agpl-3.0
376
0
from __future__ import unicode_literals from django.conf.urls import url from . import views urlpatterns = [ url(r'^upload/elec
tion/(?P<election>[^/]+)/post/(?P<post_id>[^/]+)/$', views.CreateDocumentView.as_v
iew(), name='upload_document_view'), url(r'^(?P<pk>\d+)/$', views.DocumentView.as_view(), name='uploaded_document_view'), ]
cmsdaq/hltd
lib/cx_Oracle-7.1/samples/tutorial/clob_string.py
Python
lgpl-3.0
1,342
0.005961
#------------------------------------------------------------------------------ # clob_string.py (Section 7.2) #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # Copyright (c) 2017, 2018, Oracle and/or its af...
r(ord('A') + i) longString += char * 250 cur.execute("insert into testclobs values
(:1, :2)", (i + 1, "String data " + longString + ' End of string')) con.commit() def OutputTypeHandler(cursor, name, defaultType, size, precision, scale): if defaultType == cx_Oracle.CLOB: return cursor.var(cx_Oracle.LONG_STRING, arraysize = cursor.arraysize) con.outputtypehandler = Outpu...
AjabWorld/ajabsacco
ajabsacco/wsgi_staging.py
Python
apache-2.0
401
0.002494
""" WSGI config for ajabsacco project. It exposes the WSGI callable as a modu
le-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ajabsacco.settings.staging") from django.core.wsg
i import get_wsgi_application application = get_wsgi_application()
ghchinoy/tensorflow
tensorflow/contrib/stateless/python/kernel_tests/stateless_random_ops_test.py
Python
apache-2.0
1,641
0.001219
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
, stateless_random_ops.stateless_random_uniform) self.assertIs(stateless.stateless_random_normal, stateless_random_ops.stateless_random_normal) self.assertIs(stateless.stateless_truncated_normal, stateless_random_o
ps.stateless_truncated_normal) self.assertIs(stateless.stateless_multinomial, stateless_random_ops.stateless_multinomial) if __name__ == '__main__': test.main()
afajl/sy
setup.py
Python
bsd-3-clause
1,024
0.000977
# -*- coding: utf-8 -*- import os try: from setuptools import setup except ImportError: from distutils.core import setup import sy, sy.path setup( name='sy', version=sy.__version__, url='http://sy.afajl.com',
license='BSD', author='Paul Diaconescu', author_email='p@afajl.com', description='Simple tools for system administration tasks', long_description=sy.path.slurp('README.rst'), classifiers=[ 'Development Status :: 3 - Alpha',
'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python', 'Topic :: System :: Systems Administration', 'Topic :: Software Development :: Libraries :: Python Mo...
wooga/airflow
airflow/secrets/metastore.py
Python
apache-2.0
1,888
0.00053
# # 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 copyrigh
t ownership. The ASF licenses this file # to you 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 b
y applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Objects relating...
surekap/fabric-recipes
fabfile/ntp_client.py
Python
gpl-3.0
2,215
0.008126
#!/bin/env python """ ####################################################################### # # # Copyright (c) 2012, Prateek Sureka. All Rights Reserved. # # This module provides an idempotent mechanism to remotely configure # # ntp sync...
not is_debian_or_ubuntu(): print red("Cannot deploy to non-debian/ubuntu host: %s" % env.host) return import apt apt.ensure(tzdata="latest") return run("cp -f /usr/share/zoneinfo/%s /etc/localtime" % timezone) @task def
configure(server=config.get("ntp_client", {}).get("ntp_server", "")): """ Configure NTP sync to server. """ if not is_debian_or_ubuntu(): print red("Cannot deploy to non-debian/ubuntu host: %s" % env.host) return # Upload configuration params = {'server':server} reconfigure...
CLPeters/DeFFNetIzer
rClickclass.py
Python
apache-2.0
12,183
0.019617
#m04405a12:02 class to provide Tk right click menu #import rClickclass as rC #then do something like u = rC.rClick(root, "Pmwdemo") #before root.mainlooop() #add ,name= 'lbb' to any listbox to avoid an error with paste on those #later versions will detect and disable those menu items #should be a way to create the men...
ble & Listbox to all # and if possible automate the test somehow # also have to show how to subclass and change nclst & config # # at least to prove all the binds are taking place. # # tested with win98 py2.33 from python.org # - Tix_test() Tix is in
the help, I can import but error's # - PMW_test() works # - anygui_test() sets Tk backend, rClick up but copy ineffective # probably it does something with the clicpboard # or forgets to set the ^c binds on listbox? # - TK_test() works def Tix_tes...
google/init2winit
init2winit/model_lib/models.py
Python
apache-2.0
4,094
0.00171
# coding=utf-8 # Copyright 2022 The init2winit 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 la...
vit.DEFAULT_HPARAMS), } def get_model(model_name): """Get the corresponding model class based on the model string. API: mode
l_builder, hps = get_model("fully_connected") ... modify/parse hparams model = model_builder(hps, num_classes) Args: model_name: (str) e.g. fully_connected. Returns: The model architecture (currently a flax Model) along with its default hparams. Raises: ValueError if model is unrecognized. ...
NateV/GrammarDev
grammar_dev/grammars/case_info_grammar.py
Python
gpl-2.0
2,165
0.005548
from parsimonious import Grammar from parsimonious import NodeVisitor from grammar_dev.grammars.CustomNodeVisitorFactory import CustomVisitorFactory grammars = [ r""" # Nonterminals case_info = (new_line? assigned_filed_initiated the_rest) / (new_line? line assigned_filed_initiated the_rest) / ...
Initiation Date: 01/03/2011" date_initiated_date = date &new_line the_rest = line* # Silent helper nonterminals (don't include in list of terminals) line = single_content_char* new_line? date = number forward_slash number forward_slash number # S
ilent Terminals (should be consumed and not returned. Don't include # in list of terminals.) judge_assigned_label = "Judge Assigned:" date_filed_label = "Date Filed:" date_initiated_label = "Initiation Date:" # Loud Terminals (include in list of terminals) number = ~"[0-9]"+ forward_slash = "/" single_content_char = ...
cjaymes/pyscap
src/scap/model/oval_5/VariableIdPattern.py
Python
gpl-3.0
978
0.001022
# Copyright 2016 Casey Jaym
es # This file is part of PySCAP. # # PySCAP 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. # # PySCAP is distributed in the hope tha...
AR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PySCAP. If not, see <http://www.gnu.org/licenses/>. import logging from scap.model.xs.StringType import StringType logger = logging.getLogger(__name__) class Variabl...
TEDICpy/write-it
nuntium/migrations/0010_auto__chg_field_outboundmessage_status.py
Python
gpl-3.0
4,921
0.007519
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'OutboundMessage.status' db.alter_column(u'nuntium_outboundmessage', 'status', self.gf('dj...
ed.ForeignKey', [], {'to': u"orm['c
ontactos.Contact']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'message': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['nuntium.Message']"}), 'status': ('django.db.models.fields.CharField', [], {'default': "'ready'", 'max_length':...
dstufft/bcrypt
tests/test_bcrypt.py
Python
apache-2.0
6,744
0.006228
import os import mock import pytest import bcrypt def test_gensalt_basic(monkeypatch): urandom = mock.Mock(return_value=b"0000000000000000") monkeypatch.setattr(os, "urandom", urandom) assert bcrypt.gensalt() == b"$2a$12$KB.uKB.uKB.uKB.uKB.uK." @pytest.mark.parametrize(("rounds", "expected"), [ (4...
juoecpG/7IzcH1AkmqKi.lIZMVIOLClWAk."), ]) def test_hashpw_existing(password, hashed): assert bcrypt.hashpw(password, hashed) == hashed def test_hashpw_invalid(): with pytest.raises(ValueError): bcrypt.hashpw(b"password", b"$2z$04$cVWp4XaNU8a4v1uMRum2SO") def test_hashpw_str_password(): with pyte...
hashpw_str_salt(): with pytest.raises(TypeError): bcrypt.hashpw(b"password", bcrypt.text_type("$2a$04$cVWp4XaNU8a4v1uMRum2SO"))
dariomangoni/chrono
src/demos/python/solidworks/demo_SW_irrlicht.py
Python
bsd-3-clause
3,109
0.013509
#------------------------------------------------------------------------------ # Name: pychrono example # Purpose: # # Author: Alessandro Tasora # # Created: 1/01/2019 # Copyright: (c) ProjectChrono 2019 #------------------------------------------------------------------------------ import pychrono...
directory containing various assets (meshes, textures, data files) # is automatically set, relative to the default location of this demo. # If running from a different directory, you must change the path to the data directory with: #chrono.SetChronoDataPath('path/to/data') # ----------------------------------------...
load a mechanism from file) my_system = chrono.ChSystemNSC() # Set the collision margins. This is expecially important for very large or # very small objects (as in this example)! Do this before creating shapes. chrono.ChCollisionModel.SetDefaultSuggestedEnvelope(0.001); chrono.ChCollisionModel.SetDefaultSuggested...
havard024/prego
venv/bin/pilfont.py
Python
mit
1,043
0.003835
#!/var/www/django/treeio/venv/bin/python # # The Python Imaging Library # $Id$ # # PIL raster font compiler # # history: # 1997-08-25 fl created # 2002-03-10 fl use "from PIL import" # from __future__ import print_function VERSION = "0.4" import glob, sys # drivers from PIL import BdfFontFile from PIL import Pc...
(0) p = BdfFontFile.BdfFontFile(fp)
p.save(f) except (SyntaxError, IOError): print("failed") else: print("OK")
JonnaStalring/AZOrange
azorange/trainingMethods/AZorngConsensus.py
Python
lgpl-3.0
34,765
0.010326
""" AZorngonsensus Module to build a Consensus model. """ import glob import string import os,sys import AZBaseClasses import orange,Orange import sys import re import pickle from cStringIO import StringIO from tokenize import generate_tokens from AZutilities import dataUtilities #from AZutilities import miscUtilitie...
return None else: #Try to get the imputeData, basicStat from a model that have it! if hasattr(classifiers[-1], "basicStat") and classifiers[-1].basicStat and not self.basicStat: self.basicStat = classifiers[-1].ba...
self.NTrainEx = len(trainingData) if hasattr(classifiers[-1], "imputeData") and classifiers[-1].imputeData and not self.imputeData: self.imputeData = classifiers[-1].imputeData return Consensu...
TheOtherDays/todmisc-songops
setup.py
Python
gpl-3.0
471
0.002123
f
rom setuptools import setup setup(name='todmisc-songops', version='0.1', description='The Other Days Music and Instrument Sound Converter, LSDJ song operations', url='https://github.com/TheOtherDays/todmisc-songops', author='The Other Days (http://theotherdays.net)', author_email='theothe...
DomBennett/pG-lt
tests/test_tools_download.py
Python
gpl-2.0
8,457
0.000355
#! /bin/usr/env python # D.J. Bennett # 26/05/2014 """ Tests for download tools. """ import unittest import pickle import logging import os import pglt.tools.download_tools as dtools # DIRS working_dir = os.path.dirname(__file__) # DUMMIES # expected terms and term search results t1_term = '(txid1[PORGN]) OR txid2[...
ate_findgeneinseq(self): # change gene names for test gene_names = self.downloader.gene_names self.downloader.gene_names = ['COI'] res = self.downloader._findGeneInSeq(self.record) self.downloader.gene_names = gene_name
s # I know that the COI sequence is 1545bp (5350..6894) # (http://www.ncbi.nlm.nih.gov/nuccore/AM711897.1) self.assertEqual(len(res), 1545) def test_downloader_private_parse(self): # seq3, a list of SeqRecords of which the third is the right # size and contains no Ns ...
CharlesZhong/hupu_miner
miner/miner/settings.py
Python
apache-2.0
821
0.003654
# -*- coding: utf-8 -*- # Scrapy settings for miner project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'miner' SPIDER_MODULES = ['miner.spiders'] NEWSPIDER_...
identifying yourself (and your website) on the user-agent #USER_AGENT = 'miner (+http://www.yourdomain.com)' ITEM_PIPELINES = { BOT_NAME+'.pipelines.BXJDailyPostDigestPipeline': 300, BOT_NAME+'.pipelines.BXJPostDigestDuplicatesPipeline': 301, BOT_NAME+'.pipelines.BXJPostDigestJsonWirterPipeline': 302,
BOT_NAME+'.pipelines.BXJPostDigestMongoPipeline': 303, } MONGODB_URI = "localhost" MONGODB_PORT = 27017 MONGODB_DB = "HupuMiner"
thespacedoctor/fundamentals
fundamentals/mysql/sqlite2mysql.py
Python
gpl-3.0
10,966
0.002462
#!/usr/local/bin/python # encoding: utf-8 """ Take a sqlite database file and copy the tables within it to a MySQL database Usage: sqlite2mysql -s <pathToSettingsFile> <pathToSqliteDB> [<tablePrefix>] Options: pathToSqliteDB path to the sqlite database file tablePrefix a string to prefix...
e the ``fundamentals`` package (`see tutorial here <http://fundamentals.readthedocs.io/en/latest/#tutorial>`_). To convert and import the content of a sqlite database into MySQL run the following: .. todo:: - add a tutorial about ``sqlite2mysql`` to documentation ```python from fundamentals...
ix="external" ) converter.convert_sqlite_to_mysql() ``` """ # Initialisation def __init__( self, log, pathToSqlite, tablePrefix="", settings=False, dbConn=False ): self.log = log log.debug("instansi...
google-research/adamatch
semi_supervised_domain_adaptation/baseline.py
Python
apache-2.0
7,016
0.002851
# Copyright 2019 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
logit_sx_weak, logit_sx_strong = logit_sx[::2], logit_sx[1::2] xe = 0.5 * (objax.functional.loss.cross_entropy_logits(logit_sx_weak, sy).mean() + objax.functional.loss.c
ross_entropy_logits(logit_sx_strong, sy).mean()) wd = 0.5 * sum((v.value ** 2).sum() for k, v in train_vars.items() if k.endswith('.w')) loss = xe + self.params.wd * wd return loss, {'losses/xe': xe, 'losses/wd': wd} gv = objax.GradValues(loss_function, train_vars) ...
jaredly/codetalker
tests/parse/optional.py
Python
mit
720
0.009722
#!/usr/bin/env python from codetalker.pgm import Grammar from codetalker.pgm.tokens import * from codetalker.pgm.special import * def start(rule): rule | plus(value) def value(rule): rule | ([ID], STRING) g = Grammar(start=start, tokens=[ID, STRING, WHITE], ignore=[WHITE]) def test_one(): tree = g.get_...
t('"string" "string" "strin" ') assert len(tree) == 3 def test_onother(): st = '"string" "string" "strin" ' tree = g.process(st) assert str(tree) == st def test_two(): tree = g.get_ast('one "two" three "four" five "six"') assert len(tree) == 3 def test_three(): tree = g.get_ast('"one" two...
"four" five "six"') assert len(tree) == 4 # vim: et sw=4 sts=4
ngageoint/scale
scale/source/test/configuration/test_source_data_file.py
Python
apache-2.0
4,106
0.004384
from __future__ import unicode_literals import datetime import django from django.utils.timezone import now from django.test import TransactionTestCase from mock import call, patch from job.seed.metadata import SeedMetadata from source.configuration.source_data_file import SourceDataFileParseSaver from storage.model...
False)} calls = [call(self.source_file_1.id, data, parse_datetime(started), parse_datetime(ended), types, new_workspace_path)] SourceDataFileParseSaver().save_parse_results_v6(metadata) self.assertEqual(mock_save.call_count, 1) mock_save.assert_has_calls(calls, any_order=Tr
ue)
google/prog-edu-assistant
python/colab/preamble.py
Python
apache-2.0
4,093
0.012949
# This is helper cell that defines code checking (testing) function Check() # Please run it once, but you do not need to understand it. import re import sys import jinja2 from IPython.core import display from prog_edu_assistant_tools.magics import report, autotest, CaptureOutput from google.colab import _message as goo...
n None notebook = GetNotebook() # 1. Find the first cell with specified exercise ID. found = False for (i, cell) in enumerate(notebook['cells']): if _get_exercise_id(cell) == exercise_id: found = True break if not found: raise Exception(f'exercise {exercise_id} not
found') submission_source = ''.join(cell['source']) # extract the submission cell submission_source = re.sub(r'^%%(solution|submission)[ \t]*\n', '', submission_source) # cut %%solution magic inlinetests = {} if 'metadata' in cell and 'inlinetests' in cell['metadata']: inlinetests = cell['metadata']['inl...
sdrdis/iarpa_contest_submission
chain.py
Python
mit
1,327
0.012811
''' This the main code for running the chain. It is quite straightforward: it runs chain_pairwise_pc and chain_merge_pcs (with a few additional logs...) ''' import chain_pairwise_pc import chain_merge_pcs import time from params import * import sys import os import os.path import shutil import numpy as np import resou...
for arg in sys.argv: if (arg == 'skip_align'): skip_align = True start
_time = time.time() times = [start_time] if not is_debug_mode: shutil.rmtree(tmp_path, True) if not os.path.exists(tmp_path): os.makedirs(tmp_path) chain_pairwise_pc.run(kml_path, images_paths) register_time(times) chain_merge_pcs.run(kml_path, out_path) register_time...
Alignak-monitoring-contrib/alignak-app
alignak_app/locales/__init__.py
Python
agpl-3.0
885
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2015-2018: # Matthieu Estrada, ttamalfor@gmail.com # # This file is part of (AlignakApp). # # (AlignakApp) is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Sof...
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 (AlignakApp). If...
mefly2012/platform
src/clean_validate/qyxg_zzjgdm.py
Python
apache-2.0
5,593
0.002275
# -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') from common import public import re class qyxg_zzjgdm(): """组织机构代码""" need_check_ziduan = [ '_id', 'bbd_table', 'bbd_type', 'bbd_uptime', 'bbd_dotime', 'bbd_version', 'jgdm'...
lic.date_format(ustr=ustr): ret = u'不合法日期' return ret def check_certificate_orgname(self, indexstr, ustr): """办证机构名称""" """可为空;若非空必须含有汉字""" ret = None if ustr and len(ustr.strip()): if not public.has_count_hz(ustr,
1): ret = u'没有汉字' return ret def check_esdate(self, indexstr, ustr): """注册日期""" """可为空;不为空则以下日期格式之一:yyyy年mm月dd日、yyyy-mm-dd、yyyy/mm/dd、yyyymmdd、yyyy.mm.dd""" ret = None if ustr and len(ustr.strip()): if not public.date_format(ustr): ...
libscie/liberator
liberator/lib/python3.6/site-packages/requests/utils.py
Python
cc0-1.0
27,607
0.000616
# -*- coding: utf-8 -*- """ requests.utils ~~~~~~~~~~~~~~ This module provides utility functions that are used within Requests that are also useful for external consumption. """ import cgi import codecs import collections import contextlib import io import os import platform import re import socket import struct imp...
o useable fileno try: # seek to end of file o.seek(0, 2) total_length = o.tell() # seek back to current position to support # partially read file-like objects o.seek(current_position ...
OSError, IOError): total_length = 0 if total_length is None: total_length = 0 return max(0, total_length - current_position) def get_netrc_auth(url, raise_errors=False): """Returns the Requests tuple auth for a given url from netrc.""" try: from netrc import netr...
vollov/build-tracker
src/api/__init__.py
Python
mit
34
0.029412
#
-*- coding: utf-8
-*- import api
Huluzai/DoonSketch
inkscape-0.48.5/share/extensions/voronoi2svg.py
Python
gpl-2.0
10,842
0.027301
#!/usr/bin/env python """ voronoi2svg.py Create Voronoi diagram from seeds (midpoints of selected objects) - Voronoi Diagram algorithm and C code by Steven Fortune, 1987, http://ect.bell-labs.com/who/sjf/ - Python translation to file voronoi.py by Bill Simons, 2005, http://www.oxfish.com/ Copyright (C) 2011 Vincent ...
_ = gettext.gettext class Point: def __init__(self,x,y
): self.x = x self.y = y class Voronoi2svg(inkex.Effect): def __init__(self): inkex.Effect.__init__(self) #{{{ Additional options self.OptionParser.add_option( "--tab", action="store", type="string", dest="tab") self.OptionParser.add_option( '--diagram-type', ...
magicalbob/ctime
ctime_blank.py
Python
gpl-2.0
698
0.001433
""" blank screen to stop game being played out-of-hours """ import random import os import pygame import pygame.locals from ctime_common import go_fullscreen class BlankScreen(): """ a blank screen with no controls """ def __init__(self, ctime, screen_width, screen_height, log): log.info('Time for bed ...
ee') self.screen_size = {'width': screen_width, 'height': scree
n_height} self.screen = pygame.display.get_surface() self.screen.fill(pygame.Color(0, 0, 0, 0), (0, 0, screen_width, screen_height), 0) log.info('Lights out') ctime.button_power.rpi_power() go_fullscreen()
PaulWGraham/ExampleSite
brogue/brogue/wsgi.py
Python
mit
390
0
""" WSGI config for brogue
project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "brogue.setti...
lication()
vitojph/flws
flws/flwsnl.py
Python
apache-2.0
7,573
0.005547
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Simple flask-based API to access pattern.nl functionalities. """ __author__ = "Víctor Peinado" __email__ = "vitojph@gmail.com" __date__ = "19/07/2013" from pattern.nl import parsetree, Word from flask import Flask, Response, request from flask.ext.restful import Api...
rue): output.append("%s(" % chunk.type) # handle PNP chunks if isinstance(chunk, Word): output.append("%s/%s/%s" % (chunk.string, chunk.lemma, chunk.tag)) else: if chunk.type == "PNP":
for ch in chunk.chunks: output.append("%s(" % ch.type) for word in ch.words: output.append("%s/%s/%s" % (word.string, word.lemma, word.tag)) output.append(")") output.append(")") e...
ajaniv/django-core-models
configs/common/django.py
Python
mit
3,872
0
""" .. module:: configs.common.django :synopsis: Django settings file. Django settings for django_core_models project. Generated by 'django-admin startproject' using Django 1.9. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and the...
PROJECT_ROOT, DEBUG # BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) BASE_DIR = PROJECT_ROOT # Build paths inside the project like this: os.path.join(BASE_DIR, ...) # BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for p...
ecret key used in production secret! # SECRET_KEY = 'ubd(v=i$@^plvy!-yyo*&@xi!y0514r4wkjp49k+e@r&*)7u-_' ENV_SECRET_KEY = 'DJANGO_SECRET_KEY' SECRET_KEY = os.environ[ENV_SECRET_KEY] # SECURITY WARNING: don't run with debug turned on in production! # DEBUG = True ALLOWED_HOSTS = [] # Application definition BASIC_DJ...
JeffAMcGee/friendloc
friendloc/explore/fixgis.py
Python
bsd-2-clause
1,516
0.009894
#!/usr/bin/env python from collections import defaultdict import itertools import numpy from friendloc.base import utils,gob from friendloc.base.gisgraphy import GisgraphyResource @gob.mapper(all_items=True) def gnp_gps(users): "find home location and geocoded location for geocoded users" gis = GisgraphyRes...
ists(gnp_gps): "find median location error and save to a dict using geocoded users" item_cutoff=2 kind_cutoff=5 mdist = {} dists = defaultdict(list) gnps = {} for gnp,m
loc in gnp_gps: d = utils.coord_in_miles(gnp,mloc) id = gnp.get('fid','COORD') dists[id].append(d) gnps[id] = gnp codes = defaultdict(list) for k,gnp in gnps.iteritems(): if len(dists[k])>item_cutoff: #add an entry for each feature that has a meaningful media...
dladd/pyFormex
pyformex/plugins/f2flu.py
Python
gpl-3.0
7,649
0.016473
# $Id$ *** pyformex *** ## ## This file is part of pyFormex 0.8.9 (Fri Nov 9 10:49:51 CET 2012) ## pyFormex is a tool for generating, manipulating and transforming 3D ## geometrical models by sequences of mathematical operations. ## Home page: http://pyformex.org ## Project page: http://savannah.nongnu.org...
"'%fil)
def output_fluent(fil,nodes,elems): """Write a tetraeder mesh in Fluent format to fil. The tetraeder mesh consists of an array of nodal coordinates and an array of element connectivity. """ print("Nodal coordinates") print(nodes) print("Element connectivity") print(elems) faces = a...
pe2mbs/ajenti-mdadm
make_messages.py
Python
agpl-3.0
4,684
0.00491
#!/usr/bin/env python # coding=utf-8 # --------------------------------------------------------------------------- # Messages compiler for Ajenti plugins. # # Copyright (C) 2015 Marc Bertens <m.bertens@pe2mbs.nl> # Adapted from make_messages.py by Eugene Pankov # # This program is free software: you can redistribut...
h('.py') if f.endswith('.xml'): print('Extracting from %s' % path) content = open(path).read() xml = etree.fromstring('<xml xmlns:bind="bind" xmlns:binder="binder">' + content + '</xml>') try:
msgs = [] def traverse(n): for k, v in n.items(): if v.startswith('{') and v.endswith('}'): msgs.append(v[1:-1]) try: if "_('" in v: ...
nullr0ute/oz
oz/Linux.py
Python
lgpl-2.1
16,373
0.002016
# Copyright (C) 2013-2017 Chris Lalancette <clalancette@gmail.com> # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; # version 2.1 of the License. # This library is distributed in the ho...
ents us from falling back to # keyboard-interactive password prompting # # -F /dev/null makes sure t
hat we don't use the global or per-user # configuration files return oz.ozutil.subprocess_check_output(["scp", "-i", self.sshprivkey, "-F", "/dev/null", "-o", "ServerAliveInterval=30", ...
gaqzi/py-gocd-cli
gocd_cli/settings.py
Python
mit
3,825
0.000261
import ConfigParser from os import getenv class BaseSettings(object): def __init__(self, **kwargs): pass def get(self, option): """Tries to find a configuration variable in the current store. Returns: string, number, boolean or other representation of what was found or ...
g found. """ return None class IniSettings(BaseSettings): """Reads configuration from ini files scoped to a specific section. Args: section: The ini file
section this configuration is scoped to filename: The path to the ini file to use Example: settings = IniSettings(section='main', filename='gocd-cli.cfg') settings.get('api_key') """ def __init__(self, **kwargs): self.section = kwargs.get('section', ''...
mailhexu/pyDFTutils
pyDFTutils/vasp/myvasp.py
Python
lgpl-3.0
29,832
0.001542
#! /usr/bin/env python from pyDFTutils.vasp.vasp_utils import read_poscar_and_unsort import ase.calculators.vasp.create_input if 'maskcell' not in ase.calculators.vasp.create_input.int_keys: ase.calculators.vasp.create_input.int_keys.append('maskcell') from ase.calculators.vasp import Vasp, Vasp2 from ase.dft.kpoi...
tempfile import ase.io from pyDFTutils.ase_utils.symbol import symbol_number import socket from shutil import copyfile, move default_pps_1 = { 'Pr': 'Pr_3
', 'Ni': 'Ni', 'Yb': 'Yb_3', 'Pd': 'Pd', 'Pt': 'Pt', 'Ru': 'Ru_pv', 'S': 'S', 'Na': 'Na_pv', 'Nb': 'Nb_sv', 'Nd': 'Nd_3', 'C': 'C', 'Li': 'Li_sv', 'Pb': 'Pb_d', 'Y': 'Y_sv', 'Tl': 'Tl_d', 'Lu': 'Lu_3', 'Rb': 'Rb_sv', 'Ti': 'Ti_sv', 'Te': 'Te', ...
rhiever/bokeh
bokeh/models/widgets/icons.py
Python
bsd-3-clause
948
0.00211
""" Various kinds of icon widgets. """ from __future__ import absolute_import from ...properties import Bool, Float, Enum from ...enums import NamedIcon from ..widget import Widget class AbstractIcon(Widget): """ An abstract base class for icon widgets. ``AbstractIcon`` is not generally us
eful to instantiate on its own. """ class Icon(AbstractIcon): """ A "stock" icon based on FontAwesome. """ name = Enum(NamedIcon, help=""" What icon to use. See http://fortawesome.github.io/Font-Awesome/icons/ for the list of available icons. """) size = Float(None, help=""" The...
ne, help=""" Optionally flip the icon horizontally or vertically. """) spin = Bool(False, help=""" Indicates a spinning (animated) icon. This value is ignored for icons that do not support spinning. """)
andrebellafronte/stoq
stoqlib/gui/test/test_client_details.py
Python
gpl-2.0
6,128
0.002285
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Copyright (C) 2012 Async Open Source <http://www.async.com.br> ## All rights reserved ## ## 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 Foundati...
_call(client.person) dialog = ClientDetailsDialog(self.store, client) self.check_editor(dialog, 'dialog-client-details') @mock.patch('stoqlib.gui.dialogs.clientdetails.run_person_role_dialog') def test_further_details(self, run_dialog): client = self.create_client() dialog = C...
new_store = 'stoqlib.gui.dialogs.clientdetails.api.new_store' with mock.patch(new_store) as new_store: with mock.patch.object(self.store, 'close'): new_store.return_value = self.store self.click(dialog.further_details_button) args, kwargs = run_dialog.call_...
frankrousseau/weboob
modules/lutim/browser.py
Python
agpl-3.0
1,496
0.000668
# -*- co
ding: utf-8 -*- # Copyright(C) 2014 Vincent A # # This file is part of weboob. # # weboob 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...
TNESS 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, see <http://www.gnu.org/licenses/>. from weboob.deprecated.browser import Browser from StringIO import StringIO import...
LeResKP/sqla-taskq
docs/conf.py
Python
mit
9,266
0.006046
# -*- coding: utf-8 -*- # # sqla-taskq documentation build configuration file, created by # sphinx-quickstart on Fri Jun 12 07:55:53 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # ...
ages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'defau
lt'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'sqla-taskqdoc' # -- Options for LaTeX output ------------...
abau171/highfive
examples/sum_worker.py
Python
mit
1,495
0.001338
import time import random import highfive # This is the remote worker for the sum example. Here, we define what the # workers do when they get a call from the master. All we need is a single # function which takes the call, does some processing, and returns a response. # An interesting way to play with the workers ...
name__ == "__main__": try: highfive.run_worker_pool(delayed_sum) except Keyboard
Interrupt: print("keyboard interrupt")
JavierGarciaD/AlgoTrader
algotrader/log/log_settings.py
Python
mit
2,265
0.000883
# coding=utf-8 """ https://docs.python.org/3/howto/logging.html https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/ """ import logging import logging.config from logging import Formatter import pathlib import yaml import time from common.settings import AlgoSettings def setup_logging(default_lev...
Format for log titles :param msg: :return: """ total_len = 120 len_msg = len(msg) sides_space = (total_len-len_msg) - 2 l_space = sides
_space / 2 r_space = l_space if sides_space % 2 != 0: r_space += 1 l_str = int(l_space) * " " r_str = int(r_space) * " " complete_line = ('#' * total_len) msg_line = ('#' + l_str + msg + r_str + '#') space_line = "#" + (" " * (total_len - 2)) + "#" logging.info(complete_line)...
kavdev/dj-stripe
tests/apps/testapp_content/urls.py
Python
mit
220
0.004545
""" Represents protected content """ from dja
ngo.conf.urls import url from django.http import HttpResponse def testview(request): return HttpResponse() urlpatterns = [url(r"^$", testv
iew, name="test_url_content")]
linkedin/WhereHows
metadata-ingestion/src/datahub/ingestion/source/lookml.py
Python
apache-2.0
45,412
0.002004
import glob import importlib import itertools import logging import pathlib import re import sys from dataclasses import dataclass from dataclasses import field as dataclass_field from dataclasses import replace from typing import Any, Dict, Iterable, List, Optional, Set, Tuple, Type import pydantic from looker_sdk.er...
(platform, d
b, schema) def _get_generic_definition( looker_connection: DBConnection, platform: Optional[str] = None ) -> Tuple[str, Optional[str], Optional[str]]: if platform is None: # We extract the platform from the dialect name dialect_name = looker_connection.dialect_name assert dialect_name ...
scottp-dpaw/gsconfig
examples/postgislayers.py
Python
mit
662
0.007553
#!/usr/bin/env python ''' gsconfig is a python library for manipulating a GeoServer instance via the GeoServer RESTConfig API. The project is distributed under a MIT License . ''' __author__ = "David Winslow" __copyright__ = "Copyright 2012-2015 Boundless, Copyright 2010-2012 OpenPlans" __license__ = "MIT" from geo...
dbtype") == "post
gis"] res = [] for s in pg_stores: res.extend(r.name for r in cat.get_resources(store=s)) print res
supracd/pygal
pygal/maps/__init__.py
Python
lgpl-3.0
813
0
# -*- coding: utf-8 -*- # This file is part of pygal # # A python svg graph plotting library # Copyright © 2012-2015 Kozea # # This library is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version...
, or (at your option) any # later version. # # This library 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. S
ee the GNU Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with pygal. If not, see <http://www.gnu.org/licenses/>. """Maps extensions namespace module"""
Dioptas/Dioptas
dioptas/controller/integration/phase/PhaseInCakeController.py
Python
gpl-3.0
5,615
0.00285
# -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher (clemens.prescher@gmail.com) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany ...
# along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import
DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def...
googleapis/python-secret-manager
samples/snippets/iam_grant_access.py
Python
apache-2.0
2,075
0.001446
#!/usr/bin/env python # 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 ...
Secret Manager client library. from google.cloud import secretmanager # Create the Secret Manager client. client = secretmanager.SecretManagerServiceClient() # Build the resource name of the secret. name = client.secret_path(project_id, secret_id) # Get the current IAM policy. policy = cl...
t={"resource": name}) # Add the given member with access permissions. policy.bindings.add(role="roles/secretmanager.secretAccessor", members=[member]) # Update the IAM Policy. new_policy = client.set_iam_policy(request={"resource": name, "policy": policy}) # Print data about the secret. print...
mabhub/Geotrek
geotrek/core/admin.py
Python
bsd-2-clause
1,125
0
from django.contrib import admin from geotrek.core.models import (PathSource, Stake, Usage, Network, Comfort) class PathSourceAdmin(admin.ModelAdmin): list_display = ('source', 'structure') search_fields = ('source', 'structure') list_filter = ('structure',) class StakeAdmin(admin.ModelAdmin): list...
in): list_display = ('usage', 'structure') search_fields = ('usage', 'structure') list_filter = ('structure',) class NetworkAdmin(admin.ModelAdmin): list_display = ('network', 'structure') search_fields = ('network', 'structure') list_filter = ('structure',) class ComfortAdmin(admin.ModelAdm...
nickzuber/ClusterRunner
app/util/ordered_set_queue.py
Python
apache-2.0
2,158
0.000463
import collections from queue import Queue class OrderedSetQueue(Queue): """ A queue based on ordered set. This behaves just like a normal queue but does not allow the same item to be in the queue more than once. """ def _init(self, maxsize): self.queue = OrderedSet() def _put(self,
item): self.queue.add(item) def _get(self): return self.queue.pop() class
OrderedSet(collections.MutableSet): """ Set that remembers original insertion order. Code from http://code.activestate.com/recipes/576694/ """ def __init__(self, iterable=None): self.end = end = [] end += [None, end, end] # sentinel node for doubly linked list self....
pandas-dev/pandas
pandas/core/indexers/objects.py
Python
bsd-3-clause
12,816
0.001951
"""Indexer objects for computing start/end window bounds for rolling operations""" from __future__ import annotations from datetime import timedelta import numpy as np from pandas._libs.window.indexers import calculate_variable_window_bounds from pandas.util._decorators import Appender from pandas.core.dtypes.commo...
f = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]}) >>> df B 0 0.0 1 1.0 2 2.0 3 NaN 4 4.0 >>> indexer = pd.api.indexers.FixedForwardWindowIndexer(window_size=2) >>> df.rolling(window=indexer, min_periods=1).sum() B 0 1.0 1 3.0 2 2.0 3 4.0 4 4.0...
def get_window_bounds( self, num_values: int = 0, min_periods: int | None = None, center: bool | None = None, closed: str | None = None, step: int | None = None, ) -> tuple[np.ndarray, np.ndarray]: if center: raise ValueError("Forward-looking wind...
amentis/Rexi
RxAPI/RxGUI/Border.py
Python
apache-2.0
1,108
0.002708
__author__ = 'amentis' from RxAPI.RxGUI import Color, RxGUIObject class Border(RxGUIObject): """ Drawable border for any d
rawable RxGUIObject. """ def __init__(self, name, color=None, style
="solid", width="1px"): """ @param name: str name of the REXI object @param color: Color color of the border @param style: str style of the border, acceptable values: none, hidden, dotted, dashed, solid, double, groove, ridge, inset, outset, inherit @param width: str widt...
ipapusha/amnet
amnet/opt.py
Python
bsd-3-clause
13,435
0.001638
from __future__ import division import itertools from enum import Enum import numpy as np import amnet from amnet.util import Relation import z3 ################################################################################ # Classes and routines related to Multiplexing Programming with AMNs ######################...
lf.objective = amnet.atoms.zero_from(self.variable, dim=1) else: self.variable = self.objective.variable # ensure the leaf variable is the same across con
straints assert all([constraint.variable is self.variable for constraint in self.constraints]) # initialize default solver if necessary if solver is None: self.solver = z3.Solver() else: self.solver = solver self.enc_list = [] ...
tuffery/Frog2
frowns/build/lib/frowns/IdGenerator.py
Python
gpl-3.0
715
0.006993
"""IdGenerator A simple class to provide a sequence of integers that can be used for identification
purposes generator = IdGenerator() generator() -> returns 0 generator() -> returns 1 ... generator = IdGenerator(1000) generator() -> returns 1000 generator() -> returns 1001 """ class IdGenerator: def __init__(self, start=1): self.start = start-1 def __call__(self): self.start += 1 ...
ef test(): generator = IdGenerator() assert generator() == 1 assert generator() == 2 generator = IdGenerator(start=1000) assert generator() == 1000 assert generator() == 1001 if __name__ == "__main__": test()
andrewedstrom/cs638project
arkive table analysis/parse.py
Python
mit
5,243
0.008392
import os.path import requests import time from bs4 import BeautifulSoup from geotext import GeoText as gt from string import punctuation from collections import Counter import re import sys reload(sys) sys.setdefaultencoding("utf-8") threats = ['loss', 'fragmentation', 'hunting', 'poaching', 'fishing', 'overfishi...
badge = len(items) if badge > 6: f.write(items[badge - 1] + ',') else: f.write(',') badges = soup.findAll("p"
, class_="Threats") ofInterest = str(badges) foundThreats = findThreats(ofInterest) ofInterest = parseThrough(ofInterest) threatString = threatString + ofInterest if ofInterest: f.write(ofInterest) ...
intelxed/xed
pysrc/read_xed_db.py
Python
apache-2.0
33,709
0.008366
#!/usr/bin/env python # -*- python -*- #BEGIN_LEGAL # #Copyright (c) 2019 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-...
ame, dtype, widths): """ a name and a dict of widths indexed by osz 8, 16,32, and 64b""" self.name = name.upper() self.dtype = dtype self.widths = widths # dict indexed by 8,16,32,64 def __str__(self)
: s = [] s.append("name {}".format(self.name)) s.append("datatype: {}".format(self.dtype)) s.append("widths: {}".format(",".join(self.widths.values()))) return " ".join(s) completely_numeric = re.compile(r'^[0-9]+$') # only numbers def _is_bits(val): """Return a number ...
ethanhlc/streamlink
src/streamlink/packages/flashmedia/types.py
Python
bsd-2-clause
45,802
0.000939
from .compat import OrderedDict, is_py2, str, bytes, integer_types, string_types from .util import pack_bytes_into from collections import namedtuple from struct import Struct, error as struct_error from inspect import getargspec (SCRIPT_DATA_TYPE_NUMBER, SCRIPT_DATA_TYPE_BOOLEAN, SCRIPT_DATA_TYPE_STRING, SCRIPT_DAT...
"{0} format requires {1} <= number <= {2}".format(self.format, self.lower, self.upper) raise struct_error(msg) if self.reverse:
high = val >> self.highbits low = val & self.lowmask else: high = val & self.lowmask low = val >> self.highbits return PrimitiveType.pack(self, high, low) def pack_into(self, buf, offset, val): if val < self.lower or val > self.upper: ms...
pczhaoyun/obtainfo
zinnia/views/mixins/entry_protection.py
Python
apache-2.0
2,489
0.002411
"""Protection mixins for Zinnia views""" from django.contrib.auth.views import login from django.conf import settings class LoginMixin(object): """ Mixin implemeting a login view configurated for Zinnia. """ def login(self): """ Return the login view. """ return log...
f.request, template='zinnia/password.html', context={'error': self.error}) class EntryProtectionMixin(LoginMixin, PasswordMixin): """ Mixin returning a login view if the current entry need authentication and password view if the ent...
self.object.access += 1 except TypeError: self.object.access = 1 self.object.save() def get(self, request, *args, **kwargs): """ Do the login and password protection. """ response = super(EntryProtectionMixin, self).get( ...
h-s-c/ci-tools
run_ctest.py
Python
unlicense
858
0.003497
#!/usr/bin/python # -*- coding: utf-8 -*- import platform import os import subprocess if __name__ == "__main__": #
Figure out
path of our own cmake install CITOOLS_PATH = os.path.join(os.getcwd(), "ci-tools") CMAKE_PATH = os.path.join(CITOOLS_PATH, "cmake") if platform.system() == "Linux": os.environ["PATH"] = os.path.join(CMAKE_PATH, "bin")+":"+os.environ.get("PATH", os.path.join(CMAKE_PATH, "bin")) elif platform.sys...
wangscript/libjingle-1
trunk/third_party/webrtc/tools/barcode_tools/barcode_decoder.py
Python
bsd-3-clause
10,771
0.008263
#!/usr/bin/env python # Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All c...
ound in the AUTHORS file in the root of the s
ource tree. import optparse import os import sys import helper_functions def convert_yuv_to_png_files(yuv_file_name, yuv_frame_width, yuv_frame_height, output_directory, ffmpeg_dir=None): """Converts a YUV video file into PNG frames. The function uses ffmpeg to convert the YUV file...
dya2/python-for-android
python3-alpha/python3-src/Tools/scripts/ndiff.py
Python
apache-2.0
3,825
0.002614
#! /usr/bin/env python3 # Module ndiff version 1.7.0 # Released to the public domain 08-Dec-2000, # by Tim Peters (tim.one@home.com). # Provided as-is; use at your own risk; no warranty; no promises; enjoy! # ndiff.py is now simply a front-end to the difflib.ndiff() function. # Originally, it contained the difflib.S...
') to stdout def restore(which): restored = difflib.restore(
sys.stdin.readlines(), which) sys.stdout.writelines(restored) if __name__ == '__main__': args = sys.argv[1:] if "-profile" in args: import profile, pstats args.remove("-profile") statf = "ndiff.pro" profile.run("main(args)", statf) stats = pstats.Stats(statf) ...
koery/win-sublime
Data/Packages/Default/switch_file.py
Python
mit
1,112
0.002698
import sublime, sublime_plugin import os.path import platform def compare_file_names(x, y): if platform.system() == 'Windows' or platform.system() == 'Darwin': return x.lower() == y.lower() else: return x == y class SwitchFileCommand(sublime_plugin.WindowCommand): def run(self, extensions=...
w.active_view(): return fname = self.window.active_view().file_name() if not fname:
return path = os.path.dirname(fname) base, ext = os.path.splitext(fname) start = 0 count = len(extensions) if ext != "": ext = ext[1:] for i in range(0, len(extensions)): if compare_file_names(extensions[i], ext): ...
tLDP/lampadas
pylib/data/search.py
Python
gpl-2.0
4,556
0.019096
#!/usr/bin/python # # This file is part of the Lampadas Documentation System. # # Copyright (c) 2000, 2001, 2002 David Merrill <david@lupercalia.net>. # # 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 Fou...
nse # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # from Globals import * from
globals import * from Config import config from HTML import page_factory from Tables import tables from Sessions import sessions from URLParse import URI from Log import log from mod_python import apache import os from CoreDM import dms def document(req, title='', short_title='', ...