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
varogami/c4rdz
c4rdz-gui.py
Python
gpl-3.0
9,876
0.006683
#!/usr/bin/env python import random, os.path #import basic pygame modules import pygame from pygame.locals import * #see if we can load more than standard BMP if not pygame.image.get_extended(): raise SystemExit("Sorry, extended image module required") #game constants MAX_SHOTS = 2 #mos...
Explosion(pygame.sprite.Sprite): defaultlife = 12 animcycle = 3 images = [] def __init__(self, actor): pygame.sprite.Sprite.__init__(self, self.containers) self.image = self.images[0] self.rect = self.image.get_rect(center=actor.rect.center) self.life = self.defa...
self.image = self.images[self.life//self.animcycle%2] if self.life <= 0: self.kill() class Shot(pygame.sprite.Sprite): speed = -11 images = [] def __init__(self, pos): pygame.sprite.Sprite.__init__(self, self.containers) self.image = self.images[0] self.r...
SergeyCherepanov/ansible
ansible/ansible/modules/database/postgresql/postgresql_idx.py
Python
mit
17,072
0.002284
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2018, Andrey Klychkov (@Andersson007) <aaklychkov@mail.ru> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {...
t index test_gist_idx concurrently on column geo_data of table map postgresql_idx: db: somedb table: map idxtype: gist columns: geo_data idxname: test_gist_idx # Note: for the example below pg_trgm extension must be installed for gin_trgm_ops - name: Create gin index gin0_idx not concurrently on ...
sql_idx: idxname: gin0_idx table: test columns: comment gin_trgm_ops concurrent: no idxtype: gin - name: Drop btree test_idx concurrently postgresql_idx: db: mydb idxname: test_idx state: absent - name: Drop test_idx cascade postgresql_idx: db: mydb idxname: test_idx st...
chintak/scikit-image
skimage/morphology/setup.py
Python
bsd-3-clause
2,125
0.000471
#!/usr/bin/env python im
port os from skimage._build import cython base_path = os.path.abspath(os.path.dirname(__file__)) def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs config =
Configuration('morphology', parent_package, top_path) config.add_data_dir('tests') cython(['ccomp.pyx'], working_path=base_path) cython(['cmorph.pyx'], working_path=base_path) cython(['_watershed.pyx'], working_path=base_path) cython(['_skeletonize_cy.pyx'], working_path=base_path) cython(['_p...
MindPass/Code
Interface_graphique/mindmap/svgwrite-1.1.6/tests/test_svg.py
Python
gpl-3.0
802
0.009975
#!/usr/bin/env python #coding:utf-8 # Auth
or: mozman --<mozman@gmx.at> # Purpose: test svg element # Created: 25.09.2010 # Copyright (C) 2010, Manfred Moitzi # License: MIT License import sys import unittest from svgwrite.container import SVG, Symbol class TestSVG(unittest.TestCase): def test_constructor(self): svg = SVG(insert=(10,20), size=(1...
self.assertTrue(isinstance(svg, Symbol)) self.assertEqual(svg.tostring(), '<svg height="200" width="100" x="10" y="20"><defs /></svg>') def test_add_svg_as_subelement(self): svg = SVG(id='svg') subsvg = SVG(id='subsvg') svg.add(subsvg) self.assertEqual(svg.tostring(), '<...
DanielGabris/radius_restserver
src/settings/__init__.py
Python
mit
149
0.020134
fro
m __future__ import absolute_import from .dev import Dev # noqa try: from .production import Production # noqa except Imp
ortError: pass
Alexoner/web-crawlers
scripts/rails.ctrip.com/ctripRails/middlewares/__init__.py
Python
gpl-2.0
98
0
#!/usr/b
in/env python # -*- coding: utf-8 -*
- from .randomproxy import ProxyDownloaderMiddleware
openvenues/address_deduper
address_deduper/__init__.py
Python
mit
765
0.006536
from flask import Flask import config from db import db_from_config from address_deduper.views import init_views from a
ddress_normalizer.deduping.near_duplicates import * def create_app(env, **kw): app = Flask(__name__) specified_config = kw.get('config') if specified_config: __import__('address_normalizer.' + specified_config) config.current_env = env conf = config.valid_configs.get(env) if not conf: ...
% ','.join(valid_configs.keys())) app.config.from_object(conf) app.url_map.strict_slashes = False db = db_from_config(app.config) AddressNearDupe.configure(db, geohash_precision=app.config['GEOHASH_PRECISION']) init_views(app) return app
Pulgama/supriya
supriya/ext/book.py
Python
mit
2,339
0.000855
import base64 import pathlib import pickle import textwrap from docutils.nodes import FixedTextElement, General, SkipNode from uqbar.book.extensions import Extension from uqbar.strings import normalize from supriya.ext import websafe_audio from supriya.io import Player class RenderExtension(Extension): template...
ickle.dumps((self.renderable, self.render_kwargs)) ).decode() ) ) n
ode = self.render_block(code, code) return [node] @classmethod def render(cls, node, output_path): output_path.mkdir(exist_ok=True) renderable, render_kwargs = pickle.loads( base64.b64decode("".join(node[0].split())) ) return websafe_audio( render...
fxia22/ASM_xf
PythonD/site_python/numarray/random_array/__init__.py
Python
gpl-2.0
218
0.004587
__doc__ = """Random number arra
y generators for numarray. This package was ported to numarray from Numeric's RandomArray and provides functions to generate numarray
of random numbers. """ from RandomArray2 import *
linea-it/qlf
backend/framework/qlf/dashboard/migrations/0014_product.py
Python
gpl-3.0
995
0.00402
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 20
19-01-29 16:08 from __future__ import unicode_literals import django.contrib.postgres.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [
('dashboard', '0013_auto_20181002_1939'), ] operations = [ migrations.CreateModel( name='Product', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('value', django.contrib.postgres....
yingyun/RendererEvaluator
utils/Shader2Char.py
Python
gpl-2.0
360
0.013889
#20140125 Cui.Yingyun #Convert C style code to Char style import sys file = sys.stdin if len(sys.argv) > 1:
file = open(sys.argv[1]) else: prin
t "Input argument which specify shader program" sys.exit(0); lines = file.readlines() print '\"\\' for line in lines[:-1]: print line.rstrip() + '\\n\\' print lines[-1].rstrip() + '\\n\"' file.close()
franck-talbart/codelet_tuning_infrastructure
ctr-common/plugins/34f27d92-f558-4121-b862-85216c54e18f/main.py
Python
gpl-3.0
2,154
0.010678
#************************************************************************ # Codelet Tuning Infrastructure # Copyright (C) 2010-2015 Intel Corporation, CEA, GENCI, and UVSQ # # 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 # th...
fields=["entry_info.entry_uid", "category.name"] ) for r in result: print r[0] + ":" + r[1] #--------------------------------------------------------------------------- # By pass the authentification system # Needed by the d...
check_passwd(self): return True #--------------------------------------------------------------------------- if __name__ == "__main__": p = CategoryPlugin() exit(p.main(sys.argv))
sloe/analyseapp
models/menu.py
Python
apache-2.0
523
0.026769
response.title = settings.title response.subtitle = settings.subtitle response.meta.author = '%(author)s <%(author_email)s>' % settings response.meta.keywords = settings.keywords response.meta.description = settings.description res
ponse.menu = [ (T('Index'),URL('d
efault','index')==URL(),URL('default','index'),[]), (T('Video'),URL('default','video')==URL(),URL('default','video'),[]), (T('Info'), False, "http://www.oarstack.com/2015/04/oarstack-analysis/", []), ] response.google_analytics_id="UA-52135133-2"
thatguystone/vault
vault/cmd.py
Python
mit
136
0.029412
def
vault(args): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() if __name__ == "__main__": vault(s
ys.argv)
anpolsky/phaxio-python
docs/source/conf.py
Python
apache-2.0
5,715
0.001225
# -*- coding: utf-8 -*- # # phaxio-
python documentation build configuration file, created by # sphinx-quickstart on Sun Jan 8 20:17:15 2017. # # 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. #
# All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absol...
kpavel/docker-py
docker/auth/auth.py
Python
apache-2.0
6,366
0
# Copyright 2013 dotCloud 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 t...
index_name = INDEX_NAME return index_name def split_repo_name(repo
_name): parts = repo_name.split('/', 1) if len(parts) == 1 or ( '.' not in parts[0] and ':' not in parts[0] and parts[0] != 'localhost' ): # This is a docker index repo (ex: username/foobar or ubuntu) return INDEX_NAME, repo_name return tuple(parts) def resolve_authconfig(authc...
siosio/intellij-community
python/testData/refactoring/changeSignature/newParameterWithSignatureDefaultMakesSubsequentExistingParametersUseKeywordArguments.before.py
Python
apache-2.0
82
0.02439
def foo(a, b
=None): pass foo("a", "b") foo("a") foo("a", b
="b") foo("a", None)
plentific/django-encrypted-fields
encrypted_fields/tests.py
Python
mit
9,124
0.001316
# -*- coding: utf-8 -*- import re import unittest import django from django.conf import settings from django.db import models, connection from django.test import TestCase from django.utils import timezone from .fields import ( EncryptedCharField, EncryptedTextField, EncryptedDateTimeField, EncryptedI...
of an encrypted char field """ plaintext = 'Oh hi, test reader!' model = TestModel() model.short_char = plaintext self.assertRaises(ValueError, model.save) def test_text_field_encrypted(self): plaintext = 'Oh hi, t
est reader!' * 10 model = TestModel() model.text = plaintext model.save() ciphertext = self.get_db_value('text', model.id) self.assertNotEqual(plaintext, ciphertext) self.assertTrue('test' not in ciphertext) fresh_model = TestModel.objects.get(id=model.id) ...
RuiNascimento/krepo
script.module.lambdascrapers/lib/lambdascrapers/sources_ lambdascrapers/en/series9.py
Python
gpl-2.0
7,221
0.008725
# -*- coding: UTF-8 -*- ''' series9 scraper for Exodus forks. Nov 9 2018 - Checked Updated and refactored by someone. Originally created by others. ''' import re,traceback,urllib,urlparse from resources.lib.modules import cleantitle from resources.lib.modules import client from resources.lib.modules i...
None: url = self.searchShow(data['tvshowtitle'], data['season'], aliases, headers) else: url = self.searchMovie(data['title'], data['year'], aliases, headers) if url == None: raise Exception() r = client.request(url, headers=headers, timeout='10...
ode'] links = client.parseDOM(r, 'a', attrs={'episode-data': ep}, ret='player-data') else: links = client.parseDOM(r, 'a', ret='player-data') for link in links: if '123movieshd' in link or 'seriesonline' in link: r = client.req...
stonier/ecto
test/benchmark/metrics.py
Python
bsd-3-clause
4,501
0.004888
#!/usr/bin/env python # # Copyright (c) 2011, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # n...
ency_seconds assert 0.95 < metrics.outputs.hz < 1.05 assert 0.95 < metrics.outputs.latency_seconds < 1.05 # # It is hard to test the middle cases, i.e. if you have one thread # per node, things should run at n_nodes hz and 1 second latency but # if there are less than that, things are somewhere in the middle....
est_tp(niter, n_nodes): (plasm, metrics) = makeplasm(n_nodes) sched = ecto.Scheduler(plasm) sched.execute(niter=niter) print "Hz:", metrics.outputs.hz, " Latency in seconds:", metrics.outputs.latency_seconds assert n_nodes * 0.95 < metrics.outputs.hz < n_nodes * 1.05 assert 0.9 < metrics.outpu...
kgao/MediaDrop
mediadrop/lib/auth/tests/static_query_test.py
Python
gpl-3.0
1,790
0.006145
# -*- coding: utf-8 -*- # This file is a part of MediaDrop (http://www.mediadrop.net), # Copyright 2009-2014 MediaDrop contributors # For the exact contribution history, see the git revision log. # The source code in this file is dual licensed under the MIT license or # the GPLv3 or (at your option) any later version. ...
list(self.query) # consume all other items as
sert_none(self.query.first()) import unittest def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(StaticQueryTest)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite')
JShadowMan/package
python/module/calc/calc.py
Python
mit
239
0.016736
#!/usr/bin/python35 def add(x, y): return x + y def dec(x, y): return x -
y def div(x, y): if y == 0: return 0 return x / y def mult(x, y): return x * y if __name__ == '__main__': p
rint('Module: Calc')
RobSpectre/garfield
garfield/phone_numbers/migrations/0002_phonenumber_related_sim.py
Python
mit
626
0.001597
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-11-01 20:02 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(
mig
rations.Migration): initial = True dependencies = [ ('phone_numbers', '0001_initial'), ('sims', '0001_initial'), ] operations = [ migrations.AddField( model_name='phonenumber', name='related_sim', field=models.ForeignKey(null=True, on_delete...
SanketDG/networkx
networkx/exception.py
Python
bsd-3-clause
1,828
0.005476
# -*- coding: utf-8 -*- """ ********** Exceptions ********** Base exceptions and errors for NetworkX. """ __author__ = """Aric Hagberg (hagberg@lanl.gov)\nPieter Swart (swart@lanl.gov)\nDan Schult(dschult@colgate.edu)\nLoïc
Séguin-C. <loicseguin@gmail.com>""" # Copyright (C) 2004-2016 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. # # Exception handling # the root of all Exceptions class NetworkXException(Exception): """...
essConcept(NetworkXException): """Harary, F. and Read, R. "Is the Null Graph a Pointless Concept?" In Graphs and Combinatorics Conference, George Washington University. New York: Springer-Verlag, 1973. """ class NetworkXAlgorithmError(NetworkXException): """Exception for unexpected termination of algorithms.""...
nerdvegas/rez
example_packages/hello_world/package.py
Python
apache-2.0
381
0.002625
name = "hello_world" version = "1.0.0" authors = [ "ajohns" ] descriptio
n = \ """ Pyth
on-based hello world example package. """ tools = [ "hello" ] requires = [ "python" ] uuid = "examples.hello_world_py" build_command = 'python {root}/build.py {install}' def commands(): env.PYTHONPATH.append("{root}/python") env.PATH.append("{root}/bin")
sephiroth6/nodeshot
nodeshot/networking/net/models/ip.py
Python
gpl-3.0
2,430
0.002881
from netfields import InetAddressField, CidrAddressField from django.db import models from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from django.conf import settings from nodeshot.core.base.models import BaseAccessLevel from ..managers import NetAccessLevelM...
ef save(self, *args, **kwargs): """ Determines ip protocol version automatically. Stores address in interface shortcuts for convenience. """ self.protocol = 'ipv%d' % self.address.versi
on # save super(Ip, self).save(*args, **kwargs) # TODO: do we really need this? # save shortcut on interfaces #ip_cached_list = self.interface.ip_addresses ## if not present in interface shorctus add it to the list #if str(self.address) not in ip_cached_list: ...
ferdhika31/smarttraffic
hmmtagger/java2python_runtime.py
Python
gpl-3.0
108
0
def ternary(cond
1, result1, result2
): if cond1: return result1 else: return result2
anaviltripathi/pgmpy
pgmpy/inference/dbn_inference.py
Python
mit
18,559
0.00167
from itertools import tee, chain, combinations from collections import defaultdict from pgmpy.factors import Factor from pgmpy.factors.Factor import factor_product from pgmpy.inference import Inference, BeliefPropagation class DBNInference(Inference): def __init__(self, model): """ Class for perf...
if message.scope() and clique_potential.scope(): new_factor = old_factor * message new_factor = new_factor / clique_pot
ential else: new_factor = old_factor else: new_factor = old_factor * clique_potential belief_prop.junction_tree.add_factors(new_factor) belief_prop.calibrate() def _get_factor(self, belief_prop, evidence): """ Extracts the required fac...
punalpatel/st2
st2common/st2common/validators/api/reactor.py
Python
apache-2.0
3,644
0.003293
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
t. if trigger_type_ref == CRON_TIMER_TRIGGER_REF: # Validate that the user provided parameters are valid. This is required since JSON schema # allows arbitrary strings, but not any arbitrary string is a valid CronTrigger argument # Note: Constructor throws ValueError on invalid parameters ...
return cleaned
sn3p/Orrery
data/data_to_json.py
Python
mit
4,117
0.005101
#!/usr/bin/env python """ Extract minor planet orbital elements and discovery dates to json. Orbital elements are extracted from the file MPCORB.DAT: https://minorplanetcenter.net/iau/MPCORB/MPCORB.DAT Discovery dates are extracted from the file NumberedMPs.txt: https://minorplanetcenter.net/iau/lists/NumberedMPs.txt ...
mpcs = [] count = 0 for line in open(MPCORB_FILE): nr = line[167:173].strip().replace('(', '') if not nr: continue nr = int(nr) # Skip if discovery date is missing if nr not in m
pcs_disc: print 'Skipping MPC #%d (no discovery date found)' % (nr) continue # Extract the orbital elements _, _, _, epoch, M, w, W, i, e, n, a, _ = line.split(None, 11) mpc = (mpcs_disc[nr], pd2jd(epoch), float(a), float(e), float(i), float(W), float(w), float(M), float...
stormi/tsunami
src/secondaires/navigation/equipage/volontes/relacher_gouvernail.py
Python
bsd-3-clause
3,566
0.000563
# -*-coding:Utf-8 -* # Copyright (c) 2013 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # lis...
IAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (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) # ARISI...
l""" import re from secondaires.navigation.equipage.ordres.relacher_gouvernail import \ RelacherGouvernail as OrdreRelacherGouvernail from secondaires.navigation.equipage.ordres.long_deplacer import LongDeplacer from secondaires.navigation.equipage.volonte import Volonte class RelacherGouvernail(Volonte): ...
gloaec/trifle
src/trifle/server/views/__init__.py
Python
gpl-3.0
200
0.02
from trifle.server.views.fronte
nd import frontend from trifle.server.views.api import api from trifle.server.views.monit
or import monitor from trifle.server.views.configure import configure
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/social/backends/mailru.py
Python
agpl-3.0
1,693
0
""" Mail.ru OAuth2 backend, docs at: http://psa.matiasaguirre.net/docs/backends/mailru.html """ from hashlib import md5 from social.p3 import unquote from social.backends.oauth import BaseOAuth2 class MailruOAuth2(BaseOAuth2): """Mail.ru authentication backend""" name = 'mailru-oauth2' ID_KEY = 'uid'...
(response['email']), 'fullname': fullname, 'first_name': first_name, 'last_name': last_name} def user_data(self, access_token, *args, **kwargs): """Return user data from Mail.ru REST API""" key, secret = self.get_key_and_se
cret() data = {'method': 'users.getInfo', 'session_key': access_token, 'app_id': key, 'secure': '1'} param_list = sorted(list(item + '=' + data[item] for item in data)) data['sig'] = md5( (''.join(param_list) + secret).encode('utf-8') ...
RicostruzioneTrasparente/rt-scrapers
providers/Halley.py
Python
gpl-3.0
6,427
0.012916
# Halley provider definition # Mandatory imports from .Provider import Provider from rfeed import * # Optional imports import requests, mimetypes, logging logging.basicConfig(level=logging.INFO) from bs4 import BeautifulSoup as bs # Halley provider class inherit from the Provider one defined in providers/Provider.py...
dt # # Specific methods to customize: # - opts: using options from csv file properly # - urls: extract single item urls from index page # - item: extract and structure data from single item page # # WARNING: class name is also the value of provider column in elen
co_albi.csv # class Halley(Provider): # Mandatory attributes input_format = "DD/MM/YYYY" # Optional attributes # ... # Transform and prepare options from CSV row (options column) def opts(self, opt): self.options["base_url"] = "http://halleyweb.com/%s/mc/" % opt return self # ...
eshijia/magnum
magnum/common/pythonk8sclient/swagger_client/models/v1_persistent_volume_claim_list.py
Python
apache-2.0
5,511
0.001633
# coding: utf-8 """ Copyright 2015 SmartBear Software 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...
standard list metadata; see http://releases.k8s.io/v1.0.4/docs/api-conventions.md#types-kinds :return: The metadata of this V1PersistentVolumeClaimList. :rtype: V1ListMeta """ return self._metadata @metadata.setter def metadata(self, metadata): """ Sets the m...
ons.md#types-kinds :param metadata: The metadata of this V1PersistentVolumeClaimList. :type: V1ListMeta """ self._metadata = metadata @property def items(self): """ Gets the items of this V1PersistentVolumeClaimList. a list of persistent volume claims; s...
ta2-1/pootle
pootle/apps/pootle_app/management/commands/set_filetype.py
Python
gpl-3.0
2,012
0.001988
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os os.environ['DJANGO_SETTINGS_MODUL...
Store formats." def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( 'filetype', action='store', help="File type to set") parser.add_argument( '--from-filetype', action='store', ...
ser.add_argument( '--matching', action='store', help="Glob match Store path excluding extension") def get_projects(self): if not self.projects: return Project.objects.all() return Project.objects.filter(code__in=self.projects) def get_filetype(s...
szaghi/MaTiSSe
release/MaTiSSe-1.2.0/matisse/matisse.py
Python
gpl-3.0
4,821
0.010786
#!/usr/bin/env python """ MaTiSSe.py, Markdown To Impressive Scientific Slides """ from __future__ import print_function import argparse import os import sys from matisse_config import MatisseConfig from presentation import Presentation __appname__ = "MaTiSSe.py" __description__ = "MaTiSSe.py, Markdown To Impressive S...
s.input, 'r') as mdf:
source = mdf.read() presentation = Presentation() if config.verbose: print('Parsing source ' + cliargs.input) presentation.parse(config=config, source=source) if cliargs.output: output = cliargs.output else: output = os.path.splitext(os.path.basename(cliargs.inpu...
wevote/WeVoteServer
quick_info/models.py
Python
mit
40,696
0.002408
# quick_info/models.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- # Diagrams here: https://docs.google.com/drawings/d/1fEs_f2-4Du9knJ8FXn6PQ2BcmXL4zSkMYh-cp75EeLE/edit from ballot.models import OFFICE, CANDIDATE, POLITICIAN, MEASURE, KIND_OF_BALLOT_ITEM_CHOICES from django.db import models from exce...
rue) # TODO Convert to date_last_changed # The unique id of the last person who edited this entry. last_editor_we_vote_id = models.CharField( verbose_name="last editor we vote id", max_length=255, null=True, blank=True, unique=False) # This is the office that the quick_info refers to. # Eith...
s.CharField( verbose_name="we vote permanent id for the contest_office", max_length=255, null=True, blank=True, unique=False) # This is the candidate/politician that the quick_info refers to. # Either candidate is filled, contest_office OR contest_measure, but not all three candidate_campaign_we_v...
pybuilder/pybuilder
src/unittest/python/graph_utils_tests.py
Python
apache-2.0
2,592
0.003472
# -*- coding: utf-8 -*- # # This file is part of PyBuilder # # Copyright 2011
-2020 PyBuilder Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
S 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 unittest import TestCase from pybuilder.graph_utils import Graph class GraphUtilsTests(TestCase): def test_sho...
skipzone/Illumicone
simulator/coneLayouts/cone.py
Python
gpl-3.0
1,276
0.007053
#!/usr/bin/env python from __future__ import division import math import optparse import sys #------------------------------------------------------------------------------- # Illumicone simulator, based on code from: https://github.com/zestyping/openpixelcontrol NUM_STRINGS = 48 PIXELS_PER_STRING = 100 SCALE = 7 ...
] theta = 0 for s in range(NUM_STRINGS
): theta = 2 * math.pi * s / NUM_STRINGS for p in range(PIXELS_PER_STRING): z = HEIGHT - PIXEL_DISTANCE * p radius = PIXEL_DISTANCE * p + MIN_RADIUS x = math.cos(theta) * radius y = math.sin(theta) * radius result.append(' {"point": [%.4f, %.4f, %.4f]},' % (x, y, z)) ...
deanishe/alfred-fakeum
src/libs/faker/providers/color/__init__.py
Python
mit
5,864
0
# coding=utf-8 from __future__ import unicode_literals from collections import OrderedDict from .. import BaseProvider localized = True class Provider(BaseProvider): all_colors = OrderedDict(( ("AliceBlue", "#F0F8FF"), ("AntiqueWhite", "#FAEBD7"), ("Aqua", "#00FFFF"), ("Aquamarin...
("PowderBlue", "#B0E0E6"), ("Purple", "#800080"), ("Red", "#FF0000"), ("RosyBrown", "#BC8F8F"), ("RoyalBlue", "#4169E1"), ("SaddleBrown", "#8B4513"), ("Salmon", "#FA8072"), ("SandyBr
own", "#F4A460"), ("SeaGreen", "#2E8B57"), ("SeaShell", "#FFF5EE"), ("Sienna", "#A0522D"), ("Silver", "#C0C0C0"), ("SkyBlue", "#87CEEB"), ("SlateBlue", "#6A5ACD"), ("SlateGray", "#708090"), ("Snow", "#FFFAFA"), ("SpringGreen", "#00FF7F"), (...
liangtianyou/ST
stserver/libcommon/san/stssan.py
Python
gpl-3.0
644
0.019169
#-*- coding: utf-8 -*- import traceback from libc
ommon import utils from libcommon import commonlib from libcommon.logger import stsdebug #---------------------------------- # 获取san服务是否运行 #---------------------------------- def get_san_status(): san_status = False try: retcode,proc = utils.cust_popen([commonlib.ISCSI_SCST,'status']) result = p...
san_status = True except: stsdebug.write(stsdebug.get_line(),"stssan",traceback.print_exc()) return san_status
Nasdin/ReinforcementLearning-AtariGame
A3CModel.py
Python
bsd-3-clause
2,624
0.001143
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def norm_col_init(weights, std=1.0): x = torch.randn(weights.size()) x *= std / torch.sqrt((x**2).sum(1, keepdim=True)) return x def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') !=...
= np.sqrt(6. / (fan_in + fan_out)) m.weight.data.uniform_(-w_bound, w_bound) m.bias.data.fill_(0) class A3Clstm(torch.nn.Module): def __init__(self, num_inputs, action_space): super(A3Clstm, self).__init__() # convolutional neural networks self.conv1 = nn.Conv2d(num_inputs,...
nn.MaxPool2d(2, 2) self.conv3 = nn.Conv2d(32, 64, 4, stride=1, padding=1) self.maxp3 = nn.MaxPool2d(2, 2) self.conv4 = nn.Conv2d(64, 64, 3, stride=1, padding=1) self.maxp4 = nn.MaxPool2d(2, 2) # LSTM Cells self.lstm = nn.LSTMCell(1024, 512) num_outputs = action_s...
levilucio/SyVOLT
mbeddr2C_MM/Contracts/HAssignmentInstance_CompleteLHS.py
Python
mit
94,636
0.01379
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HAssignmentInstance_CompleteLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HAssignmentInstance_CompleteLHS. """ ...
====================================== # This code is executed when evaluating if a node shall be matched by this rule. # You can access the value of the current node's attribute value by: attr_value. # You can access any attribute x of this node by:
this['x']. # If the constraint relies on attribute values from other nodes, # use the LHS/NAC constraint instead. # The given constraint must evaluate to a boolean expression. #=============================================================================== return True """ self.vs[2]["MT_label__"] = ""...
fedora-conary/conary
config/components/invariant/test.py
Python
apache-2.0
625
0
# # Copyright (c) SAS Institute Inc. # # L
icensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the L...
erning permissions and # limitations under the License. # filters = ('test', ('%(testdir)s/',))
uucastine/soundbooth
soundbooth/urls.py
Python
bsd-3-clause
658
0.00304
from django.conf import settings from django.conf.urls impo
rt include, url from django.views.generic import TemplateView from django.contrib import admin admin.autodiscover() from booth.views import HomepageView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('allauth.urls')), url(r'^', include('booth.urls', namespace='booth...
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url("^$", HomepageView.as_view(), name="homepage") ] if settings.DEBUG: import debug_toolbar urlpatterns.append( url(r'^__debug__/', include(debug_toolbar.urls)), )
malramsay64/MD-Molecules-Hoomd
test/figures_test.py
Python
mit
1,269
0.003155
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2017 Malcolm Ramsay <malramsay64@gmail.com> # # Distributed under terms of the MIT license. """Test function from the generation of figures.""" import math import gsd.hoomd from hypothesis import given from hypothesis.strategies import f...
f test_plot(): with gsd.hoomd.open('test/data/trajectory-13.50-3.00.gsd') as trj: plot(trj[0], repeat=True, offset=True) def test_snapshot2data(): with gsd.hoomd.open('test/
data/trajectory-13.50-3.00.gsd') as trj: snapshot2data(trj[0]) def test_order(): with gsd.hoomd.open('test/data/trajectory-13.50-3.00.gsd') as trj: order_list = compute_voronoi_neighs(trj[0].configuration.box, trj[0].particles.position) plot(trj[...
mpetyx/palmdrop
venv/lib/python2.7/site-packages/cms/migrations/0036_auto__add_field_cmsplugin_changed_date.py
Python
apache-2.0
19,523
0.003739
# -*- 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): # Dummy migration pass def backwards(self, orm): # Dummy migration pass models = { ...
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ( 'django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': (
'django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.model...
kg-bot/SupyBot
plugins/GUI/frontend/frontend.py
Python
gpl-3.0
9,802
0.00153
#!/usr/bin/env python # -*- coding: utf8 -*- ### # Copyright (c) 2011, Valentin Lorentz # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the abov...
nection closed *')) self.commandEdit.readOnly = True self._eventsManager.stop() def _refreshConfigurationTree(self): """Slot called when the user clicks 'Refresh' under the configuration tree.""" ConfigurationTreeRefresh(self._eventsManager, self) def configurati
onItemActivated(self, item): print(repr(item)) class EventsManager(QtCore.QObject): """This class handles all incoming messages, and call the associated callback (using hook() method)""" def __init__(self, sock): self._sock = sock self.defaultCallback = lambda x:x self._c...
maxalbert/Pytess
pytess/__init__.py
Python
mit
1,265
0.003162
""" # Pytess Pure Python tessellation of points into polygons, including Delauney/Thiessin, and Voronoi polygons. Built as a convenient user interface for Bill Simons/Ca
rson Farmer python port of Steven Fortune C++ version of a Delauney triangulator. ## Platforms Tested on Python version 2.x. ## Dependencies Pure Python, no dependencies. ## Installing it Pytess is installed with pip from the commandline: pip install pytess ## Usage To triangulate a set of points, si...
triangulate(points) And for voronoi diagrams: import pytess points = [(1,1), (5,5), (3,5), (8,1)] voronoipolys = pytess.voronoi(points) ## More Information: - [Home Page](http://github.com/karimbahgat/Pytess) - [API Documentation](http://pythonhosted.org/Pytess) ## License: This code is free to ...
kyuridenamida/atcoder-tools
atcodertools/fileutils/load_text_file.py
Python
mit
103
0
def load_text_file(text_file: str) -> str: with open(text
_file, 'r') as f: return f.
read()
hotpoor-for-Liwei/hj_hackathon_201607
vendor/qiniu/services/processing/pfop.py
Python
mit
1,697
0.001394
# -*- coding: utf-8 -*- from qiniu import config from qiniu import http class PersistentFop(object): """持久化处理类 该类用于主动触发异步持久化操作,具体规格参考: http://developer.qiniu.com/docs/v6/api/reference/fop/pfop/pfop.html Attributes: auth: 账号管理密钥对,Auth对象 bucket: 操作资源所在空间 pipeline: ...
self.buc
ket = bucket self.pipeline = pipeline self.notify_url = notify_url def execute(self, key, fops, force=None): """执行持久化处理: Args: key: 待处理的源文件 fops: 处理详细操作,规格详见 http://developer.qiniu.com/docs/v6/api/reference/fop/ force: 强制执行持久化处理开关 ...
hequn8128/flink
flink-python/pyflink/ml/tests/test_params.py
Python
apache-2.0
6,487
0.001233
################################################################################ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distr
ibuted with
this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LIC...
google/earthengine-community
samples/python/apidocs/ee_dictionary_aside.py
Python
apache-2.0
1,056
0.002841
# Copyright 2021 The Google Earth Engine Community Authors # # Licensed under the Apache License, Ve
rsion 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, 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. # [START earthengine__apidocs__ee_dictionary_aside] # A dictionary (e.g. r...
hjanime/VisTrails
vistrails/core/vistrail/port_spec.py
Python
bsd-3-clause
20,455
0.002982
############################################################################### ## ## Copyright (C) 2014-2015, New York University. ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## ...
IABILITY, OR TORT (INCLUDING NEGLIGENCE OR ## OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ## ############################################################################### from __future__ import division from itertools import izip import operat...
dules.utils import create_port_spec_string, parse_port_spec_string from vistrails.core.system import get_vistrails_basic_pkg_id, \ get_module_registry from vistrails.core.utils import enum, VistrailsInternalError from vistrails.core.vistrail.port_spec_item import PortSpecItem from vistrails.db.domain import DBPortS...
DarkFenX/Pyfa
gui/builtinStatsViews/resistancesViewFull.py
Python
gpl-3.0
9,855
0.003146
# ============================================================================= # Copyright (C) 2010 Diego Duclos # # This file is part of pyfa. # # pyfa 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 ...
, # but WITHOUT ANY WARRANTY; with
out 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 pyfa. If not, see <http://www.gnu.org/licenses/>. # ========================================...
WarrenWeckesser/scipy
benchmarks/benchmarks/fftpack_pseudo_diffs.py
Python
bsd-3-clause
2,237
0
""" Benchmark functions for fftpack.pseudo_diffs module """ from numpy import arange, sin, cos, pi, exp, tanh, sign from .common import Benchmark, safe_import with safe_import(): from scipy.fftpack import diff, fft, ifft, tilbert, hilbert, shift, fftfreq def direct_diff(x, k=1, period=None): fx = fft(x) ...
if soltype == 'fft': tilbert(self.f, 1) else: direct_tilbert(self.f, 1) def time_hilbert(self, size, soltype): if soltyp
e == 'fft': hilbert(self.f) else: direct_hilbert(self.f) def time_shift(self, size, soltype): if soltype == 'fft': shift(self.f, self.a) else: direct_shift(self.f, self.a)
alcemirsantos/algorithms-py
tests/data_stuctures/test_mockdata.py
Python
mit
400
0.0025
import unittest from src.data_structures.mockdata import MockData class TestMockData (unittest.TestCase): def setUp(self): self.data = Moc
kData() def test_random_data(self): data = MockData() a_set = data.get_random_elements(10) self.assertTrue(len(a_
set) == 10, "the data should have 10 elements!") if __name__ == '__main__': unittest.main()
fx2003/tensorflow-study
TensorFlow实战/《TensorFlow实战》代码/3_2_HelloWorld.py
Python
mit
1,784
0.001682
#%% # Copyright 2015 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 app...
older(tf.float32, [None, 10]) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) tf.global_variables_initializer().run() for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) train_...
(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))
open-forcefield-group/smarty
smarty/__init__.py
Python
mit
392
0.002551
try: import openeye # These can only be imported if openeye tools are available from smarty.atomtyper import * from smarty.sampler import * from smarty.utils import * from smarty.sampler_smirky import * except Exception as e: print(e) print('Warning: Cannot import openeye toolkit; not a...
ill be available.') from smarty.score_utils impor
t *
eflynch/pygamelan
pygamelan/core.py
Python
gpl-2.0
2,581
0.019372
##################################################################### # # core.py # # Copyright (c) 2015, Eran Egozy # # Released under the MIT L
icense (http://opensource.org/licenses/MIT) # ########
############################################################# import kivy from kivy.app import App from kivy.core.window import Window from kivy.uix.widget import Widget from kivy.clock import Clock import traceback class BaseWidget(Widget): """Has some common core functionality we want in all our apps - handl...
pabigot/pyxb
tests/drivers/test-ctd-simple.py
Python
apache-2.0
1,997
0.007511
# -*- coding: utf-8 -*- import logging if __name__ == '__main__': logging.basicConfig() _log = logging.getLogger(__name__) import pyxb.binding.generate import pyxb.binding.datatypes as xsd import pyxb.utils.domutils from xml.dom import Node import os.path schema_path = os.path.abspath(os.path.join(os.path.dirname(...
maxLength.value()) def testClause1_2 (self): self.assertTrue(clause1_2._IsSimpleTypeContent()) self.assertTrue(
issubclass(clause1_2, clause4)) self.assertTrue(issubclass(clause1_2._TypeDefinition, xsd.string)) self.assertEqual(6, clause1_2._TypeDefinition._CF_length.value()) if __name__ == '__main__': unittest.main()
opencord/maas
library/maas_item.py
Python
apache-2.0
6,217
0.006434
#!/usr/bin/python # Copyright 2017-present Open Networking Foundation # # 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 ap...
'error']: module.fail_json(msg=res['status']) else: module.exit_json(changed=True, item=res['status']) else: # No differences, to nothing to change module.exit_json(changed=False, item=item) else: # If we don't want this item, then ...
'status']) else: module.exit_json(changed=True, item=item) # this is magic, see lib/ansible/module_common.py #<<INCLUDE_ANSIBLE_MODULE_COMMON>> if __name__ == '__main__': main()
esben/setuptools_scm
setuptools_scm/git.py
Python
mit
1,196
0
from .utils import do, do_ex, trace from .version import meta from os.path import abspath, realpath FILES_COMMAND = 'git ls-files' DEFAULT_DESCRIBE = 'git describe --dirty --tags --long --match *.*' def parse(root, describe_command=DEFAULT_DESCRIBE): real_root, _, ret = do_ex('git rev-parse --show-toplevel', ro...
AD', root) if ret: return meta('0.0') rev_node = rev_node[:7] out, err,
ret = do_ex(describe_command, root) if '-' not in out and '.' not in out: revs = do('git rev-list HEAD', root) count = revs.count('\n') if ret: out = rev_node return meta('0.0', distance=count + 1, node=out) if ret: return dirty = out.endswith('-dirty') ...
1and1/artifactory-debian
dput-webdav/webdav.py
Python
apache-2.0
17,864
0.004646
# -*- coding: utf-8 -*- # pylint: disable=locally-disabled, star-args """ WebDAV upload method for dput. Install to "/usr/share/dput/webdav.py". """ from __future__ import with_statement import re import os import sys import cgi import netrc import socket import fnmatch import getpass import httplib import urllib...
else: url = url.format(**pkgdata) # Python 2.6+ except KeyError, exc: raise dputhelper.DputUploadFatalException("Unknown key (%s) in incoming templates '%s'" % (exc, incoming)) trace("Resolved incoming to `%(url)s' params=%(params)r", url=ur
l, params=url_params) return url, url_params def _url_connection(url, method, skip_host=False, skip_accept_encoding=False): """Create HTTP[S] connection for `url`.""" scheme, netloc, path, params, query, _ = urlparse.urlparse(url) result = conn = (httplib.HTTPSConnection if scheme == "https" else http...
achanda/refstack
refstack/decorators.py
Python
apache-2.0
409
0.002445
#-*- coding:
utf-8 -*- # This file based on MIT licensed code at: https://github.com/imwilsonxu/fbone from functools import wraps from flask import abort from flask.ext.login import current_user def admin_required(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.is_admin():
abort(403) return f(*args, **kwargs) return decorated_function
lscsoft/gwdetchar
gwdetchar/omega/__init__.py
Python
gpl-3.0
1,099
0
# coding=utf-8 # Copyright (C) Duncan Macleod (2015) # # This file is part of the GW DetChar python package. # # GW DetChar 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 th
e License, or # (at your option) any later version. # # GW DetChar is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY o
r 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 GW DetChar. If not, see <http://www.gnu.org/licenses/>. """Methods and utilties for performing Omega pipline scans See Chatterji 2005 [thesis]...
chocopoche/mangopay2-python-sdk
setup.py
Python
mit
1,575
0.001905
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'DESCRIPTION.md'), encoding='utf-8') as f: long_description = f.read() setup( name='jestocke-mangopaysdk', version='3.0.6', description='A clie...
ed :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', ], keywords='mangopay api development emoney sdk', packages=find_packages(exclude=['contrib', 'd...
=['requests', 'simplejson', 'blinker', 'six' ], extras_require={ 'dev': ['responses', 'nose', 'coverage', 'httplib2', 'pyopenssl', 'ndg-httpsclient', 'pyasn1', 'exam'], 'test': ['responses', 'nose', 'coverage', 'httplib2', 'pyopenssl', 'ndg-httpsclient', 'pyasn1', 'e...
kaikai581/NOvA
xsec-2019/check_light_syst/check_entries/file_lists/pull_common_files.py
Python
gpl-2.0
1,096
0.014599
#!/usr/bin/env python from __future__ import print_function import os import subprocess syst_names = ['nominal','lightdown','lightup','ckv','calibneg','calibpos','calibshape'] flists = [syst_name+'.txt' for syst_name in syst_names] def process_dataset(ds_idx): flist = flists[ds_idx] fns = [] with open(...
s.path.exists(out_path): os.makedirs(out_path) for fn in fns: bashout = subprocess.check_output('samweb locate-file {}'.format(fn), shell=True) bashout = bashout.split('\n') for line in bashout: if 'dcache' in line: location = line.split(':')[1] c...
es)): process_dataset(i)
hdoria/HnTool
HnTool/modules/php.py
Python
gpl-2.0
4,760
0.005252
# -*- coding: utf-8 -*- # # HnTool rules - php # Copyright (C) 2009-2010 Candido Vieira <cvieira.br@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the Lic...
" self.long_name="Checks security problems on php config file" self.type="config" self.required_files = ['/etc/php5/apache2/php.ini', '/etc/php5/cli/php.ini', '/etc/php.ini'] def requires(self): return self.required_files def analyze(self, options): check_results = self...
k_results conf_files = self.required_files for php_conf in conf_files: if os.path.isfile(php_conf): config = ConfigParser.ConfigParser() try: config.read(php_conf) except ConfigParser.ParsingError, (errno, strerror): ...
dmsimard/ansible
lib/ansible/modules/git.py
Python
gpl-3.0
53,677
0.002459
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: git autho...
a branch name, a tag name. It can also be a I(SHA-1) hash, in which case I(refspec) needs to be specified if the given revision is not already available. type: str default: "HEAD" accept_hostkey: description: - If C(yes), ensure that "-o StrictHostKeyC...
description: - As of OpenSSH 7.5, "-o StrictHostKeyChecking=accept-new" can be used which is safer and will only accepts host keys which are not present or are the same. if C(yes), ensure that "-o StrictHostKeyChecking=accept-new" is present as an ssh option. ...
grs/amqp_subscriptions
d.py
Python
apache-2.0
2,628
0.003044
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "...
on-durable event.container.container_id = self.id event.container.create_receiver(self.url, name=self.subscription, options=[Capabilities('shared')]) def on_message(self, event): if self.expected == 0 or self.received < self.expected: print(event.message.body) self.r...
if self.received == self.expected: event.receiver.close() event.connection.close() parser = optparse.OptionParser(usage="usage: %prog [options]") parser.add_option("-a", "--address", default="localhost:5672/examples", help="address from which messages are received ...
dturner-tw/pants
src/python/pants/backend/graph_info/tasks/sorttargets.py
Python
apache-2.0
1,081
0.007401
# 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, p
rint_function, unicode_literals, with_statement) from pants.build_graph.bu
ild_graph import sort_targets from pants.task.console_task import ConsoleTask class SortTargets(ConsoleTask): """Topologically sort the targets.""" @classmethod def register_options(cls, register): super(SortTargets, cls).register_options(register) register('--reverse', action='store_true', default=Fal...
mrawls/kepler-makelc
lc_functions.py
Python
mit
5,357
0.022961
import numpy as np from pyraf import iraf from pyraf.iraf import kepler ''' Useful functions for Kepler light curve processing Use this with the program 'makelc.py' Originally by Jean McKeever Edited and improved by Meredith Rawls ''' # calculate orbital phase # times must be a list of observation times in the same un...
ux = flux/fit*1e6 - 1e6 # put it in ppm >:( flux = flux/fit*np.median(flux) # don't put it in ppm, because ppm is annoying return t, flux # Delete any observation that has one or more NaN values. # Assumes there are six parallel arrays... use dummy arrays if you don't have 6 # columns of interest to operate on...
= np.transpose(a) newatrans = [] newa = [] for row in atrans: # only save rows that DON'T contain a NaN value if np.isnan(row).any() != True: newatrans.append(row) newa = np.transpose(newatrans) newtime = newa[0] newflux = newa[1] newferr = newa[2] newother1 = newa[3] newother2 = newa[4] newother3 = n...
grlee77/numpy
numpy/core/overrides.py
Python
bsd-3-clause
8,273
0.000363
"""Implementation of __array_function__ overrides from NEP-18.""" import collections import functools import os import textwrap from numpy.core._multiarray_umath import ( add_docstring, implement_array_function, _get_implementing_args) from numpy.compat._inspect import getargspec ARRAY_FUNCTION_ENABLED = bool( ...
``. Returns ------- Result from calling ``implementation()`` or an ``__array_function__`` method, as appropriate. Raises ------ TypeError : if no implementation is found. """) # exposed for testing purposes; used
internally by implement_array_function add_docstring( _get_implementing_args, """ Collect arguments on which to call __array_function__. Parameters ---------- relevant_args : iterable of array-like Iterable of possibly array-like arguments to check for __array_function__ methods...
srcLurker/home-assistant
homeassistant/components/media_player/mpd.py
Python
mit
7,141
0
""" Support to interact with a Music Player Daemon. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.mpd/ """ import logging import socket import voluptuous as vol from homeassistant.components.media_player import ( MEDIA_TYPE_MUSIC, SUP...
n as cv REQUIREMENTS = ['python-mpd2==0.5.5'] _LOGGER = logging.getLogger(__name__) CONF_LOCATION = 'location' DEFAULT_LOCATION = 'MPD' DEFAULT_PORT = 6600 SUPPORT_MPD = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_TURN_OFF | \ SUPPORT_TURN_ON | SUPPORT_PREVIOUS_TRACK | SU
PPORT_NEXT_TRACK | \ SUPPORT_PLAY_MEDIA PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_LOCATION, default=DEFAULT_LOCATION): cv.string, vol.Optional(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, }) # pylint: dis...
Lukasa/urllib3
test/contrib/test_socks.py
Python
mit
21,538
0
import threading import socket from urllib3.contrib import socks from urllib3.exceptions import ConnectTimeoutError, NewConnectionError from dummyserver.server import DEFAULT_CERTS from dummyserver.testcase import IPV4SocketDummyServerTestCase from nose.plugins.skip import SkipTest try: import ssl from urll...
ecv(1) chunks.append(chunk) if chunk == char: break return b''.join(chunks) def _address_from_socket(sock): """ Returns the address from the SOCKS socket """ addr_type = sock.recv(1) if addr_type == b'\x01': ipv4_addr = _read_exactly(sock, 4) retur...
return socket.inet_ntop(socket.AF_INET6, ipv6_addr) elif addr_type == b'\x03': addr_len = ord(sock.recv(1)) return _read_exactly(sock, addr_len) else: raise RuntimeError("Unexpected addr type: %r" % addr_type) def handle_socks5_negotiation(sock, negotiate, username=None, ...
tundebabzy/frappe
frappe/model/db_query.py
Python
mit
21,717
0.027766
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals from six import iteritems, string_types """build query for doclistview and return results""" import frappe, json, copy, re import frappe.defaults import frappe.share import fra...
ctype) # filters and fields swappable # its hard to remember what comes first if (isinstance(fields, dict) or (isinstance(fields, list) and fields and isinstance(fields[0], list))): # if fields is given as dict/list of list, its probably filters filters, fields = fields, filters elif fields and isins...
\ and len(filters) > 1 and isinstance(filters[0], string_types): # if `filters` is a list of strings, its probably fields filters, fields = fields, filters if fields: self.fields = fields else: self.fields = ["`tab{0}`.`name`".format(self.doctype)] if start: limit_start = start if page_length:...
anksp21/Community-Zenpacks
ZenPacks.community.powerware/setup.py
Python
gpl-2.0
3,281
0.009448
########################################################################### # # This program is part of Zenoss Core, an open source monitoring platform. # Copyright (C) 2008, Zenoss Inc. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License versi...
# of this form. e
ntry_points = { 'zenoss.zenpacks': '%s = %s' % (NAME, NAME), }, # All ZenPack eggs must be installed in unzipped form. zip_safe = False, )
Maethorin/pivocram
tests/unit/test_pivocram.py
Python
mit
8,498
0.00353
# -*- coding: utf-8 -*- from tests import base from app import pivocram class PivocramConnetcTest(base.TestCase): def setUp(self): self.connect = pivocram.Connect('PIVOTAL_TEST_TOKEN') def test_should_have_the_pivotal_api_url(self): self.connect.PIVOTAL_URL.should.be.equal('https://www.pivota...
self.client.connect = self.mock.MagicMock() self.client.connect.get_projects.return_value = [1, 2, 3] self.client.get_projects().should.be.equal([1, 2, 3]) def test_should_get_empty_if_no_projects(self): self.client.conne
ct = self.mock.MagicMock() self.client.connect.get_projects.return_value = [] self.client.get_projects().should.be.equal([]) def test_should_set_current_iteration(self): self.client.connect = self.mock.MagicMock() self.client.connect.get_project.return_value = self.project_mock ...
robobrobro/coffer
coffer/command/commands/__init__.py
Python
mit
53
0
""" Functions and cla
sses dealing with commands. """
mitdbg/modeldb
client/verta/verta/_swagger/_public/modeldb/model/ModeldbFindHydratedProjectsByTeam.py
Python
mit
1,079
0.012048
# THIS FILE IS AUTO-GENERATED. DO NOT EDIT from verta._swagger.base_type import BaseType class ModeldbFindHydratedProjectsByTeam(BaseType): def __init__(self, find_projects=None, org_id=None, name=None, id=None): required =
{ "find_projects": False, "org_id": False, "name": False, "id": False, } self.find_projects = find_projects self.org_id = org_id self.name = name self.id = id for k, v in required.items(): if self[k] is None and v: raise ValueError('attribute {} is required...
: d['find_projects'] = ModeldbFindProjects.from_json(tmp) tmp = d.get('org_id', None) if tmp is not None: d['org_id'] = tmp tmp = d.get('name', None) if tmp is not None: d['name'] = tmp tmp = d.get('id', None) if tmp is not None: d['id'] = tmp return ModeldbFindHydra...
laborautonomo/bitmask_client
src/leap/bitmask/services/eip/darwinvpnlauncher.py
Python
gpl-3.0
6,729
0
# -*- coding: utf-8 -*- # darwinvpnlauncher.py # Copyright (C) 2013 LEAP # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later versio...
_PATH = "/Applications/Bitmask.app/" INSTALL_PATH_ESCAPED = os.path.realpath(os.getcwd() + "/../../") OPENVPN_BIN = 'openvpn.leap' OPENVPN_PATH = "%s/Contents/Resources/openvpn" % (INSTALL_PATH,) OPENVPN_PATH_ESCAPED = "%s/Contents/Resources/openvpn" % ( INSTALL_PATH_ESCAPED,) OPENVPN_BIN_PA...
s/client.down.sh" % (OPENVPN_PATH,) OPENVPN_DOWN_PLUGIN = '%s/openvpn-down-root.so' % (OPENVPN_PATH,) UPDOWN_FILES = (UP_SCRIPT, DOWN_SCRIPT, OPENVPN_DOWN_PLUGIN) OTHER_FILES = [] @classmethod def cmd_for_missing_scripts(kls, frompath): """ Returns a command that can copy the missi...
mindbody/API-Examples
SDKs/Python/test/test_client_api.py
Python
bsd-2-clause
5,280
0
# coding: utf-8 """ MINDBODY Public API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: v6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import impo...
"""Test case for client_get_client_formula_notes Get a client's formula notes. # noqa: E501 """ pass def test_client_get_client_indexes(self): """Test case for client_get_client_indexes Get a site's configured client indexes and client index values.
# noqa: E501 """ pass def test_client_get_client_purchases(self): """Test case for client_get_client_purchases Get a client's purchase history. # noqa: E501 """ pass def test_client_get_client_referral_types(self): """Test case for client_get_client_...
agry/NGECore2
scripts/houses/player_house_corellia_large_style_02.py
Python
lgpl-3.0
706
0.022663
import sys from services.housing import HouseTemplate from engine.resources.scene import Point3D def setup(housingTemplates): houseTemplate = HouseTemplate("object/tangible/deed/player_house_deed/shared_corellia_house_large_style_02_deed.
iff", "object/building/player/shared_player_house_generic_large_style_02.iff", 5) houseTemplate.addBuildingSign("object/tangible/sign/player/shared_house_address.iff", Point3D(float(-13.4), float(3), float(9.1))) houseTemplate.addPlaceablePlanet("corellia") houseTemplate.addPlaceab
lePlanet("talus") houseTemplate.setDefaultItemLimit(500) houseTemplate.setBaseMaintenanceRate(26) housingTemplates.put(houseTemplate.getDeedTemplate(), houseTemplate) return
MiniLight/DeepCL
python/benchmarking/deepcl_benchmark2.py
Python
mpl-2.0
11,420
0.009632
#!/usr/bin/python # This was originally created to target inclusion in soumith's benchmarks as # https://github.com/soumith/convnet-benchmarks # extending this to handle also a couple of clarke and storkey type layers # and some plausible mnist layers from __future__ import print_function import os import sys import ...
results_dict['type'] = benchmark_type results_dict['format'] = 'v0.4' results_dict['direction'] = direction results_dict['net_string'] = net_string if layer is
not None: results_dict['layer_string'] = layer.asString() results_dict['time_ms'] = str(time_ms) results_dict['cmd_line'] = cmd_line f = open('results.txt', 'a') json.dump(results_dict, f) f.write( '\n' ) f.close() def time_layer(num_epochs, label, batch_size, net_string): print('...
stxnext-csr/volontulo
apps/volontulo/views/organizations.py
Python
mit
6,645
0
# -*- coding: utf-8 -*- u""" .. module:: organizations """ from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.shortcuts import get_object_or_404 from django.shortcuts import redirect from django.shortcuts import render...
{ 'organization': org, 'contact_form': form,
'offers': offers, 'allow_contact': allow_contact, 'allow_edit': allow_edit, 'allow_offer_create': allow_offer_create, }, ) return render( request, "organizations/organization_view.html", { ...
emitrom/integra-openstack-ui
workflows/post/post.py
Python
apache-2.0
151
0
class Post(obje
ct): def __init__(self, **kwargs): self.__dict__.update(kwargs) def __iter__(s
elf): return iter(self.__dict__)
SaptakS/open-event-orga-server
app/api/attendees.py
Python
gpl-3.0
2,552
0.002351
from flask.ext.restplus import Namespace from app.api.tickets import ORDER, TICKET from app.helpers.ticketing import TicketingManager from app.api.helpers.helpers import ( requires_auth, can_access, replace_event_id) from app.api.helpers.utils import POST_RESPONSES from app.api.helpers.utils import Resource f...
k_in_toggle', responses=POST_RESPONSES) @api.marshal_with(ATTENDEE) def post(self, event_id, holder_identifier): """Toggle and Attendee's Checked in State""" holder = TicketingManager.attendee_check_in_out(event_id, holder_identifier) return holder, 200 @api.route('/events/<string:even...
lass AttendeeCheckIn(Resource): @requires_auth @replace_event_id @can_access @api.doc('check_in_toggle', responses=POST_RESPONSES) @api.marshal_with(ATTENDEE) def post(self, event_id, holder_identifier): """Check in attendee""" holder = TicketingManager.attendee_check_in_out(even...
DePierre/owtf
framework/db/command_register.py
Python
bsd-3-clause
2,347
0.001704
#!/usr/bin/env python ''' Component to handle data storage and search of all commands run ''' from framework.dependency_management.dependency_resolver import BaseComponent from framework.dependency_management.interfaces import CommandRegisterInterface from framework.lib.general import cprint from framework.db import m...
self.db = self.get_component("db") self.plugin_output = None self.target = None def init(sel
f): self.target = self.get_component("target") self.plugin_output = self.get_component("plugin_output") def AddCommand(self, Command): self.db.session.merge(models.Command( start_time=Command['Start'], end_time=Command['End'], success=Command['Success'], ...
Christoph/tag-connect
keyvis_add/ml.py
Python
mit
2,394
0.002924
import numpy as np import keras from keras.datasets import mnist from keras.models import Model, Sequential from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D from keras.layers import Flatten, Reshape from keras import regularizers from plotly import offline as py import plotly.graph_objs as go ...
make_subplots(rows=1, cols=3, print_grid=False) t1 = go.Heatmap(z=x_test[random_test_images[0]].reshape(28, 28), showscale=False) fig.append_trace(t1, 1, 1) # fig.append_trace(trace2, 1, 2) # fig.append_trace(trace3, 1, 3) for i in map(str,range(1, 4)): y = 'yaxis'+ i x = 'xaxis' + i fig['lay...
r = 'x') fig['layout'][x].update(showticklabels=False, ticks='') fig['layout'].update(height=600) py.iplot(fig)
tomjelinek/pcs
pcs/common/resource_agent/const.py
Python
gpl-2.0
285
0
# OCF 1.0 doesn't define unique groups, they are defined since OCF 1.1. Pcs # transforms OCF 1.0 agents to OCF 1.1 structur
e and t
herefore needs to create # a group name for OCF 1.0 unique attrs. The name is: {this_prefix}{attr_name} DEFAULT_UNIQUE_GROUP_PREFIX = "_pcs_unique_group_"
kayhayen/Nuitka
tests/programs/absolute_import/foobar/foobar.py
Python
apache-2.0
1,043
0
# Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com # # Python te
sts originally created or extracted from other peoples work. The # parts were too small to be protected. # # 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....
nder 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. # """ Using absolute import, do from module imports. """ from __future__ im...
gkarakou/systemd-denotify
denotify/mailer.py
Python
gpl-3.0
8,509
0.007051
#!/usr/bin/python2 import threading from systemd import journal from threading import Thread import smtplib import email.utils from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class Mailer(threading.Thread): """ Mailer :desc: Class that sends an email Extends Thread ...
ary = dictio msg = MIMEMultipart("alternative") #get it from th
e queue? stripped = stri.strip() part1 = MIMEText(stripped, "plain") msg['Subject'] = dictionary['email_subject'] #http://pymotw.com/2/smtplib/ msg['To'] = email.utils.formataddr(('Recipient', dictionary['email_to'])) msg['From'] = email.utils.formataddr((dictionary['emai...
pgdr/ert
python/tests/gui/ide/test_proper_name_format_argument.py
Python
gpl-3.0
595
0.001681
from ert_gui.ide.keywords.definitions import ProperNameFormatArgument from ecl.test import ExtendedTestCase class ProperNameFormatArgumentTest(ExtendedTestCase): def test_pr
oper_name_format_argument(self): argument = ProperNameFormatArgument() self.assertTrue(argument.validate("NAME%d")) self.assertTrue(argument.validate("__NA%dME__")) self.assertTrue(argument.validate("<NAME>%d")) self.assertTrue(argument.validate("%d-NAME-"))
self.assertFalse(argument.validate("-%dNA ME-")) self.assertFalse(argument.validate("NAME*%d"))
moonso/vcf_parser
tests/test_split_variants.py
Python
mit
9,713
0.014414
import pytest from vcf_parser.utils import split_variants, format_variant from vcf_parser import HeaderParser def get_header(header_lines = None): """Initiate a HeaderParser and return it""" header_parser = HeaderParser() if not header_lines: header_lines = [ '##fileformat=VCFv4.2'...
'mother'] == "0/1:60:7,10:17" assert first_variant['proband'] == "0/1:60:0,7:16" assert second_variant['proband'] == "0/1:60:0,8:16" def test_split_minimal(): """ Test to split a vcf line without genotypes """ header_lines = [ '##fileformat=VCFv4.2', '##FILTER=<ID=LowQual,D...
ID\tREF\tALT\tQUAL\tFILTER\tINFO' ] header_parser = get_header(header_lines) variant_line = "3\t947379\t.\tA\tT,C\t100\tPASS\tMQ=1" variant = format_variant( line = variant_line, header_parser=header_parser, check_info=True ) splitted_variants = [] ...
zlorb/mitmproxy
mitmproxy/tools/console/flowdetailview.py
Python
mit
5,591
0.000358
import urwid from mitmproxy import http from mitmproxy.tools.console import common, searchable from mitmproxy.utils import human from mitmproxy.utils import strutils def maybe_timestamp(base, attr): if base is not None and getattr(base, attr): return human.format_timestamp_with_milli(getattr(base, attr))...
ow.client_conn req = flow.request resp = flow.response metadata = flow.metadata if metadata is not None and len(metadata) > 0: parts = [(str(k), repr(v)) for k, v in metadata.items()] text.append(urwid.Text([("head", "Metadata:")])) text.extend(common.format_keyvals(parts, inden...
r Connection:")])) parts = [ ("Address", human.format_address(sc.address)), ] if sc.ip_address: parts.append(("Resolved Address", human.format_address(sc.ip_address))) if resp: parts.append(("HTTP Version", resp.http_version)) if sc.alpn_proto_...
imatge-upc/trecvid-2015
scripts/python/evaluate.py
Python
mit
4,066
0.021397
import numpy as np from get_params import get_params import os import pickle """ Returns mAP for each query. """ def relnotrel( fileGT, id_q, rankingShots ): '''Takes ground truth file (fileGT), query name (id_q) and ranking (rankingShots) in order to create a vector of 1's and 0's to compute Average Pre...
['root'],'9_other','score_txt',params['query_name'] + '.txt') np.savetxt(save_txt_file,save_fi
le,delimiter='\t', fmt="%s") ap = AveragePrecision(np.squeeze(labels),num_relevant) print ap else: errors.append(query) print "Done" print errors
Azure/azure-sdk-for-python
sdk/formrecognizer/azure-ai-formrecognizer/azure/ai/formrecognizer/_generated/aio/_form_recognizer_client.py
Python
mit
5,812
0.002753
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
ndpoint: str :param api_version: API version to use if no profile is provided, or if missing in profile. :type api_version: str :param profile: A profile definition, from KnownProfiles to dict. :type profile: azure.profiles.KnownProfiles :keyword int polling_interval: Default waiting time between tw...
RecognizerClient" LATEST_PROFILE = ProfileDefinition({ _PROFILE_TAG: { None: DEFAULT_API_VERSION, 'authorize_copy_document_model': '2022-01-30-preview', 'begin_analyze_document': '2022-01-30-preview', 'begin_build_document_model': '2022-01-30-preview', ...
elzaggo/pydoop
examples/pydoop_submit/mr/map_only_python_writer.py
Python
apache-2.0
1,895
0.001583
#!/usr/bin/env python # BEGIN_COPYRIGHT # # Copyright 2009-2018 CRS4. # # 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 ap...
apper(api.Mapper): def __init__(self, context): self.name = hdfs.path.basename(context.input_split.filename) def map(self, context): context.emit((self.name, context.key), context.value.upper()) class Writer(api.RecordWriter): def __init__(self, context): super(Writer, self).__i...
self.logger = LOGGER.getChild("Writer") jc = context.job_conf outfn = context.get_default_work_file() self.logger.info("writing to %s", outfn) hdfs_user = jc.get("pydoop.hdfs.user", None) self.sep = jc.get("mapreduce.output.textoutputformat.separator", "\t") self.f...