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 |
|---|---|---|---|---|---|---|---|---|
kodibx/kodibx | plugin.program.teverzwizard/resources/libs/wizard.py | Python | gpl-2.0 | 117,008 | 0.030186 | ################################################################################
# Copyright (C) 2015 Surfacingx #
# #
# This Program is free software; you can redistribute it and/or modify ... | a copy of the GNU General Public License #
# along with XBMC; see the file COPYING. If not, write to #
# the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139 | , USA. #
# http://www.gnu.org/copyleft/gpl.html #
################################################################################
import xbmc, xbmcaddon, xbmcgui, xbmcplugin, os, sys, xbmcvfs, HTMLParser, glob, zipfile, json
import shutil
import errno
import string
import... |
KousikaGanesh/purchaseandInventory | openerp/addons/mrp_operations/mrp_operations.py | Python | agpl-3.0 | 28,224 | 0.014243 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | rod_obj = oper_obj.production_id
if action == ' | start':
if prod_obj.state =='confirmed':
prod_obj_pool.force_production(cr, uid, [prod_obj.id])
wf_service.trg_validate(uid, 'mrp.production', prod_obj.id, 'button_produce', cr)
elif prod_obj.state =='ready':
wf_service.trg_validate(... |
mtzstngl/RSA_Encryption | .ycm_extra_conf.py | Python | mit | 4,012 | 0.025174 | import os
import ycm_core
from clang_helpers import PrepareClangFlags
# These are the compilation flags that will be used in case there's no
# compilation database set (by default, one is not set).
# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR.
flags = [
'-Wall',
'-Wextra',
'-Werror',
'... | final_flags = PrepareClangFlags(
MakeRelativePathsInFlagsAbsolute(
compilation_info.compiler_flags_,
compilation_info.compiler_working_dir_ ),
filename )
# NOTE: This is just for YouCompleteMe; it' | s highly likely that your project
# does NOT need to remove the stdlib flag. DO NOT USE THIS IN YOUR
# ycm_extra_conf IF YOU'RE NOT 100% YOU NEED IT.
try:
final_flags.remove( '-stdlib=libc++' )
except ValueError:
pass
else:
relative_to = DirectoryOfThisScript()
final_flags = MakeRe... |
databuild/databuild | databuild/compat.py | Python | bsd-3-clause | 155 | 0.006452 | import six
if six.PY2:
def _open(*args, **kwargs):
kwargs.pop('encoding', False)
return open(*args, **kwargs)
else:
_ope | n = open
| |
fedora-infra/the-new-hotness | hotness/use_cases/retrieve_data_use_case.py | Python | lgpl-2.1 | 1,991 | 0.001005 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2021 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This ... | es import Database
from hotness.requests import RetrieveDataRequest
from hotness import responses
logger = logging.getLogger(__name__)
class RetrieveDataUseCase:
"""
This class represents use case for retrieving value for key using databases.
Attributes:
database: Database to use.
"""
... | e
def retrieve(self, request: RetrieveDataRequest) -> responses.Response:
"""
Call the retrieve method on the database.
This method will handle any error that happens when retrieving data.
Params:
request: Request to handle.
Return:
Output of the dat... |
jokuf/hack-blog | users/managers.py | Python | mit | 1,053 | 0 | from django.contrib.auth. | base_user import BaseUserManager
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
if not email:
| raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
extr... |
bbengfort/jobs-report | elmr/views.py | Python | mit | 20,091 | 0.00209 | # views
# Routes for the ELMR web application
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Thu Apr 09 09:13:29 2015 -0400
#
# Copyright (C) 2015 University of Maryland
# For license information, see LICENSE.txt
#
# ID: views.py [] benjamin@bengfort.com $
"""
Routes for the ELMR web application
"... | self._parser.add_argument('delta', type=str)
return self._parser
@property
def detail_parser(self):
"""
Returns the detail parser for the SeriesView (for PUT)
"""
if not hasattr(self, '_detail_parser'):
self._detail_parser = reqparse.RequestParser... | itle', type=str, required=True)
return self._detail_parser
def get(self, blsid):
"""
Returns the Series detail for a given blsid.
"""
args = self.parser.parse_args()
series = Series.query.filter_by(blsid=blsid).first_or_404()
context = {
"bls... |
lthurlow/Network-Grapher | proj/external/matplotlib-1.2.1/lib/mpl_examples/pylab_examples/demo_tight_layout.py | Python | mit | 2,028 | 0.002959 |
import matplotlib.pyplot as plt
import random
fontsizes = [8, 16, 24, 32]
def example_plot(ax):
ax.plot([1, 2])
ax.set_xlabel('x-label', fontsize=random.choice(fontsizes))
ax.set_ylabel('y-label', fontsize=random.choice(fontsizes))
ax.set_title('Title', fontsize=random.choice(fontsizes))
fig, ax = p... | x2)
example_plot(ax3)
| example_plot(ax4)
plt.tight_layout()
plt.show()
fig = plt.figure()
import matplotlib.gridspec as gridspec
gs1 = gridspec.GridSpec(3, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])
ax3 = fig.add_subplot(gs1[2])
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
gs1.tight_layout(fig, rect=[None... |
mozman/ezdxf | tests/test_01_dxf_entities/test_118_appid_table_entry.py | Python | mit | 365 | 0 | # Created: 16.03.2011, 2018 rewritten for py | test
# Copyright (C) 2011-2019, Manfred Moitzi
# License: MIT License
import pytest
from ezdxf.entities.appid import AppID
@pytest.fixture
def appid():
return AppID.new(
"FFFF",
dxfattribs={
"name": "EZDXF",
},
)
def test_name(appid):
ass | ert appid.dxf.name == "EZDXF"
|
Chuban/moose | python/chigger/tests/viewports/viewports.py | Python | lgpl-2.1 | 1,321 | 0.002271 | #!/usr/bin/env python
#pylint: disable=missing-docstring
#################################################################
# DO NOT MODIFY THIS HEADER #
# MOOSE - Multiphysics Object Oriented Simulation Environment #
# #... | ################## | ##########
import chigger
reader = chigger.exodus.ExodusReader('../input/mug_blocks_out.e')
mug0 = chigger.exodus.ExodusResult(reader, variable='convected', viewport=[0, 0, 0.5, 1], cmap='shock')
mug1 = chigger.exodus.ExodusResult(reader, variable='diffused', viewport=[0.5, 0, 1, 1], cmap='coolwarm')
window = chigger.R... |
d15123601/geotinkering | dummy_gis.py | Python | mit | 17,528 | 0.022136 | """
This is a dummy to try and get a gis gui up and running
"""
from GUI_1 import MyShape
import json
from collections import defaultdict
from tkinter import *
from tkinter import ttk
from descartes.patch import PolygonPatch
import shapely
import shapely.geometry as geometry
from shapely.ops import cascaded_union
impor... | counties'])
stack.append([places_pts, 'asciiname', 'towns'])
gis_data = defaultdict()
if stack:
for obj in stack:
gis_data[obj[2]] = MyShape(obj[0], obj[1])
root = Tk()
MicksGis(root, gis_data)
root.mainloop()
class MicksGis:
"""
This class will construct th... | gis gui.
We pass in the collection of MyShape objects.
"""
def __init__(self, master, datasets):
with open("provinces.txt",'r') as f2:
prov_str = f2.read()
prov_polygons = json.loads(prov_str)
provs = []
for f in prov_polygons['fea... |
smorante/continuous-goal-directed-actions | abandoned/connected-images/src/superseeded/python/motion_temp.py | Python | mit | 15,421 | 0.019454 | # -*- coding: utf-8 -*-
"""
Author: Santiago Morante
Robotics Lab. Universidad Carlos III de Madrid
About: This file (when finished) captures two videos, and trains weights
to relate both images. After training (in fact, it is online, so I should say
'when enough time has elapsed') it can predict movements between came... | FILENAME = sys.argv[1]
print "[INFO] Reproducing experiment with params: " + str(sys.argv[1])
REPRODUCE_EXPERIMENT = True
#### SAVE EXPERIMENT PARAMS ####
TIME = time.strftime("%H:%M:%S")
DA | TE = time.strftime("%d.%b.%Y")
if SAVE_EXPERIMENT == True:
FILENAME_WEIGHTS = "../../cross-validation/experiments/weights/motion_weights_" \
+ DATE + "_" + TIME + ".npy"
FILENAME_RESULTS = "../../cross-validation/experiments/results/motion_results_" \
+ DATE + "_" + TIME + ".csv"
FILENAM... |
silly-wacky-3-town-toon/SOURCE-COD | toontown/parties/DistributedPartyJukeboxActivityBase.py | Python | apache-2.0 | 9,133 | 0.00208 | from direct.actor.Actor import Actor
from direct.task.Task import Task
from panda3d.core import *
from panda3d.direct import *
from otp.otpbase.OTPBase import OTPBase
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
from toontown.parties.DistributedPartyActivity import Distributed... | Bitmask | ToontownGlobals.WallBitmask)
collTube = CollisionTube(0, 0, 0, 0.0, 0.0, 4.25, 2.25)
collTube.setTangible(1)
self.collNode.addSolid(collTube)
self.collNodePath = self.juk | ebox.attachNewNode(self.collNode)
self.sign.setPos(-5.0, 0, 0)
self.activate()
def unload(self):
DistributedPartyActivity.unload(self)
self.gui.unload()
if self.music is not None:
self.music.stop()
self.jukebox.stop()
self.jukebox.delete()
... |
Rjerk/snippets | python/ICPUP/二分查找.py | Python | gpl-3.0 | 540 | 0.001852 | def search(L, e):
def bSearch(L, e, low, high):
if high == low:
return L[low] == e
mid = (low + high) // 2
|
if L[mid] == e:
return True
elif L[mid] > e:
if low == mid:
| return False
else:
return bSearch(L, e, low, mid - 1)
else:
return bSearch(L, e, mid + 1, high)
if len(L) == 0:
return False
else:
return bSearch(L, e, 0, len(L) - 1)
L = [1, 2, 5, 3, 6, 7, 9, 10]
search(L, 8)
|
anhstudios/swganh | data/scripts/templates/object/mobile/shared_dressed_marooned_pirate_tran_m.py | Python | mit | 460 | 0.045652 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE T | HE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_marooned_pirate_tran_m.iff"
result.attribute_template_id = 9
result.stfName("npc_name","trandoshan_bas | e_male")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
dongguangming/python-phonenumbers | python/phonenumbers/data/region_TT.py | Python | apache-2.0 | 1,892 | 0.0074 | """Auto-generated file, do not edit by hand. TT metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_TT = PhoneMetadata(id='TT', country_code=1, international_prefix='011',
general_desc=PhoneNumberDesc(national_number_pattern='[589]\\d{9}', possible_number_pattern='\\... | d)|4[6-9]\\d|6(?:20|78|8\\d)|7(?:0[1-9]|1[02-9]|[2-9]\\d))\\d{4}', possible_number_pattern='\\d{10}', example_number='8682911234'),
toll_free=PhoneNumberDesc(national_number_pattern='8(?:00|44|55|66|77|88)[2-9]\\d{6}', possible_number_pattern='\\d{10}', example_number='8002345678'),
premium_rate=PhoneNumberDesc | (national_number_pattern='900[2-9]\\d{6}', possible_number_pattern='\\d{10}', example_number='9002345678'),
shared_cost=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
personal_number=PhoneNumberDesc(national_number_pattern='5(?:00|33|44|66|77)[2-9]\\d{6}', possible_number_pattern='... |
naderman/spoac | src/examples/python/PlanTester.py | Python | gpl-3.0 | 2,580 | 0.00155 | import sys
from spoac import SymbolicExecutionSlice
from spoac import PlanningSlice
from spoac.util.IceApplication import IceApplication
class PlanTesterApp(IceApplication):
def run(self, args):
planner = self.stormGetTopic("PlanController",
PlanningSlice.PlanControllerTopicPrx)
symb... | on = PlanningSlice.SymbolDefinition()
pred1 = PlanningSlice.PredicateDefinition()
pred1.name = "pred1"
pred1.arguments = 1
symbolDefinition.predicates = [pred1]
function1 = PlanningSlice.FunctionDefinition()
function1.name = "function1"
function1.arguments = | 0
symbolDefinition.functions = [function1]
symbolDefinition.constants = ["obj1", "obj2"]
print "setSymbolDefinitions"
planner.setSymbolDefinitions(symbolDefinition)
action1 = PlanningSlice.ActionDefinition()
action1.name = "action1"
action1parameter1 = Plann... |
davidbgk/udata | udata/tests/features/territories/test_territories_process.py | Python | agpl-3.0 | 21,564 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from flask import url_for
from udata.core.dataset.factories import VisibleDatasetFactory
from udata.core.organization.factories import OrganizationFactory
from udata.core.spatial.factories import GeoZoneFactory, SpatialCoverageFactory
from udata.core.spa... | ation=2700266)
occitanie = GeoZoneFactory(
id='fr:region:76@2016-01-01', level='fr:region',
name='Languedoc-Rousillon et Midi-Pyrénées',
ancesto | rs=['fr:region:91@1970-01-09'], code='76',
validity__start='2016-01-01', validity__end=END_OF_TIME,
population=5573000)
return lr, occitanie
class TerritoriesSettings(Testing):
ACTIVATE_TERRITORIES = True
HANDLED_LEVELS = ('fr:commune', 'fr:departement', 'fr:region', 'country')
class Ter... |
bcbnz/django-admin-loginpatches | admin-loginpatches/middleware.py | Python | gpl-3.0 | 6,110 | 0.000818 | # This file is part of django-admin-loginpatches, a project to patch
# the Django admin login interface to better support custom
# authentication backends.
# Copyright (C) 2010 Blair Bonnett
#
# django-admin-loginpatches is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Pub... | ive account'),
'message': _('Your account is not active.'),
}
return render_to_response(template, context,
context_instance=RequestContext(request))
# Not a staff member
if not request.user.is_staff:
| template = getattr(settings, 'ADMIN_LOGIN_NOTSTAFF_TEMPLATE',
'admin/not_staff.html')
context = {
'title': _('Not staff'),
'message': _('You need to be a staff member to view this page.'),
}
return render_to_response(t... |
immenz/pyload | module/plugins/hooks/RealdebridCom.py | Python | gpl-3.0 | 1,471 | 0.028552 | # -*- coding: utf-8 -*-
from module.plugins.internal.MultiHook import MultiHook
class RealdebridCom(MultiHook):
__name__ = "RealdebridCom"
__type__ = "hook"
__version__ = "0.46"
__config__ = [("pluginmode" , "all;listed;unlisted", "Use for plugins" , "all"),
... | , "Number of retries before revert" , 10 ),
("retryinterval" , "int" , "Retry interval in minutes" , 1 ),
("reload" , "bool" , "Reload plugin list" , True ),
("reloadinterval", "int" ... | ption__ = """Real-Debrid.com hook plugin"""
__license__ = "GPLv3"
__authors__ = [("Devirex Hazzard", "naibaf_11@yahoo.de")]
def getHosters(self):
https = "https" if self.getConfig("ssl") else "http"
html = self.getURL(https + "://real-debrid.com/api/hosters.php").replace("\"", "").... |
jasontlam/snorkel | snorkel/learning/disc_learning.py | Python | apache-2.0 | 15,799 | 0.003861 | import math
import tensorflow as tf
import numpy as np
from time import time
import os
from six.moves.cPickle import dump, load
from numpy import inf
from .classifier import Classifier
from .utils import reshape_marginals, LabelBalancer
from sklearn.utils.class_weight import compute_sample_weight
class TFNoiseAwareMo... | e Issue #679.
"""
# Note: The below arguments need to be constructed by self._build!
return {self.X: X_b, self.Y: Y_b, self.lr: lr}
def _build_new_graph_session(self, **model_kwargs):
"""Creates new graph, builds network, and sets new session."""
self.model_kwargs = model_kw... | self.graph = tf.Graph()
with self.graph.as_default():
# Set graph-level random seed
tf.set_random_seed(self.seed)
# Build network here in the graph
self._build_model(**model_kwargs)
# Create new session
self.session = tf.Session(
... |
AlexandraMercier/StrategyIA | ai/STA/Strategy/SimpleOffense.py | Python | mit | 545 | 0.001838 | # Under MIT license, see LICENSE.txt
from ai.STA.Tactic.GoGetBall import G | oGetBall
from ai.STA.Tactic.GoalKeeper import GoalKeeper
from . Strategy import Strategy
from ai.Algorithm.Node import Node
# | stratégie: tout le monde fonce vers la balle car c'est tout ce qu'on sait faire
class SimpleOffense(Strategy):
def __init__(self, p_game_state):
super().__init__(p_game_state)
self.add_tactic(0, GoalKeeper(self.game_state, 0))
for i in range(1, 6):
self.add_tactic(i, GoGetBal... |
shermdog/py-junos-eznc | tests/unit/facts/test_routing_engines.py | Python | apache-2.0 | 4,180 | 0.001196 | __author__ = "Nitin Kumar, Rick Sherman"
__credits__ = "Jeremy Schulman"
import unittest
from nose.plugins.attrib import attr
from mock import patch, MagicMock
import os
from jnpr.junos import Device
from jnpr.junos.facts.routing_engines import facts_routing_engines as routing_engines
from ncclient.manager import Ma... | te'], 'backup')
@patch('jnpr.junos.Device.execute')
def test_mixed_mode_vcf(self, mock_execute):
mock_execute.side_effect = self._mock_manager
self.mode = 'multi'
self.vc = True
self.vcf = True
routing_engines(self.dev, self.facts)
self.assertTrue(self.facts['vc_... | '], 'Mixed')
@patch('jnpr.junos.Device.execute')
def test_multi_instance(self, mock_execute):
mock_execute.side_effect = self._mock_manager
self.mode = 'multi'
routing_engines(self.dev, self.facts)
self.assertTrue(self.facts['2RE'])
@patch('jnpr.junos.Device.execute')
d... |
cjaymes/pyscap | src/scap/model/ai_1_1/LocationsType.py | Python | gpl-3.0 | 1,280 | 0.003125 | # Copyright 2016 Casey Jaymes
# 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 that it will be useful... | should have received a copy of the GNU General Public License
# along with PySCAP. If not, see <http://www.gnu.org/licenses/>.
from scap.Model import Model
import logging
logger = logging.getLogger(__name__)
class LocationsType(Model):
MODEL_MAP = {
'tag_name': 'locations',
'elements': [
... |
eduNEXT/edx-platform | lms/djangoapps/grades/migrations/0014_persistentsubsectiongradeoverridehistory.py | Python | agpl-3.0 | 1,332 | 0.004505 | # Generated by Django 1.11.16 on 2018-11-27 20:53
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('grades', '0013_persis... | e, null | =True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
|
mhvk/astropy | astropy/io/fits/fitsrec.py | Python | bsd-3-clause | 53,877 | 0.000111 | # Licensed under a 3-clause BSD style license - see PYFITS.rst
import copy
import operator
import warnings
import weakref
from contextlib import suppress
from functools import reduce
import numpy as np
from numpy import char as chararray
from .column import (ASCIITNULL, FITS2NUMPY, ASCII2NUMPY, ASCII2STR, ColDefs,... | ecord array from a recarray.
"""
# input should be a record array
if input.dtype.subdtype is None:
self = np.recarray.__new__(subtype, input.shape, input.dtype,
buf=input.data)
else:
self = np.recarray.__new__(subtype, input... |
self._init()
if self.dtype.fields:
self._nfields = len(self.dtype.fields)
return self
def __setstate__(self, state):
meta = state[-1]
column_state = state[-2]
state = state[:-2]
super().__setstate__(state)
self._col_weakrefs = weakref.... |
PolyLAN/polybookexchange | polybookexchange/migrations/0002_auto__add_field_exemplar_out_reason__add_field_exemplar_money_given_da.py | Python | bsd-2-clause | 7,600 | 0.006974 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Exemplar.out_reason'
db.add_column(u'polybookexchange_exe... | 'True'}),
'section': ('django.db.models.fields.related.Fore | ignKey', [], {'to': u"orm['polybookexchange.Section']"}),
'semester': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['polybookexchange.Semester']"})
}
}
complete_apps = ['polybookexchange'] |
fs714/drcontroller | drcontroller/test/recovery_url_test.py | Python | apache-2.0 | 345 | 0.002899 | import requests
import json
ip = '127.0.0.1'
port = 80
payload = {'key1': 'value1', 'key2': {'key2_1': 'v | alue2_1', 'key2_2': 'value2_2'}}
req_url = 'http://' + str(ip) + | ':' + str(port) + '/v1/recovery/start'
headers = {'Content-type': 'application/json'}
req = requests.post(req_url, data=json.dumps(payload), headers=headers)
print req.text
|
fga-gpp-mds/2017.2-Receituario-Medico | medical_prescription/medicine/test/test_view_list_all_medications.py | Python | mit | 676 | 0 | from django.test import TestCase
from medicine.models import Medicine
from medicine.views import ListAllMedicines
from user.models import HealthProfessional
class T | estListAllMedicines(TestCase):
def setUp(self):
# Making a HealthProfessional
self.view = ListAllMedicines
# Making medicati
self.medi | cine = Medicine()
self.medicine.name = "Medicamento Teste"
self.medicine.active_ingredient = "Teste Lab"
self.medicine.save()
self.listing = Medicine.objects.all()
def test_medicine_is_show(self):
instance = self.view()
self.assertEqual(instance.get_queryset()[0], s... |
dennyb87/pycity | week7/GeometricObject.py | Python | gpl-3.0 | 543 | 0 | #! | /usr/bin/env python3
"""Geometric Object Class"""
class GeometricObject:
def __init__(self, color="green", filled=True):
self.__color = color
self.__filled = filled
def get_color(self):
return self.__color
def set_color(self, color):
self.__color = color
def is_fi | lled(self):
return self.__filled
def set_filled(self, filled):
self.__filled = filled
def __str__(self):
return "color: " + self.__color + \
" and filled: " + str(self.__filled)
|
memphis-iis/gluten | gluten/auth.py | Python | apache-2.0 | 4,308 | 0.000464 | """Flask Blueprint adding login functionality to our app. Note that we expect
gluten model and db config to be handled elsewhere
"""
import sys
import traceback
from functools import partial, wraps
from flask import redirect, request, flash, session, abort, g, url_for
from flask.globals import LocalProxy, _lookup_ap... | turn wrapper
# Make the google blueprint (taken from their contrib code)
auth = OAuth2ConsumerBlueprint(
"auth",
__name__,
client_id=None, # Handled via app config
client_secret=None, # Handled via app config
scope=["profile", "email"],
base_url="https://www.googleapis.com/",
authorizati... | login_url=None,
authorized_url=None,
authorization_url_params={},
session_class=None,
backend=None,
)
auth.from_config["client_id"] = "GOOGLE_OAUTH_CLIENT_ID"
auth.from_config["client_secret"] = "GOOGLE_OAUTH_CLIENT_SECRET"
@auth.before_app_request
def set_applocal_session():
ctx = stack.top
... |
ricardog/raster-project | projections/scripts/gen_sps.py | Python | apache-2.0 | 6,241 | 0.02051 | #!/usr/bin/env python
import click
from copy import copy
from netCDF4 import Dataset
import numpy as np
import numpy.ma as ma
import os
import rasterio
import rasterio.warp as rwarp
import time
import osr
from .. import geotools
from .. import utils
def earth_radius():
srs = osr.SpatialReference()
srs.ImportFrom... |
ds.height,
*ds.bounds,
resolution=resolutio | n)
out.mask.fill(False)
rwarp.reproject(arr, out,
src_transform = ds.affine,
dst_transform = newaff,
width = width,
height = height,
src_nodata = nodata,
dst_nodata = nodata,
src_crs = crs,
... |
fridex/gofed | parseOptions.py | Python | gpl-2.0 | 955 | 0.040838 | from modules.Utils import runCommand
import re
import sys
def parseOptions(command):
so, se, rc = runCommand("gofed %s --help" % command)
if rc != 0:
return []
options = []
option_f = False
for line in so.split("\n"):
if line == "Options:":
option_f = True
continue
if option_f == True:
if line ==... | -":
continue
line = line.strip()
parts = line.split(' ')[0].spli | t(',')
if parts == []:
continue
# do we have both short and long options?
opts = map(lambda i: i.strip().split(' ')[0].split('=')[0], parts)
for opt in opts:
options.append(opt)
return sorted(options)
if __name__ == "__main__":
if len(sys.argv) != 2:
print ""
command = sys.argv[1]
opt... |
tmelin/plugin.video.tv4.se | playapi.py | Python | gpl-2.0 | 6,539 | 0.003364 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Tomas Melin 2016
# Basic tv4play API implementation.
#
# 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, or (at your option)
# ... | -us) ' \
'AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10'
PROGRAMS = 'http://webapi.tv4play.se/play/programs?is_active=true&per_page=550&fl=name,nid,program_image,description,category&start=0'
EPISODES_BASEURL = 'http://webapi.tv4play.se/play/video_assets?... | //prima.tv4play.se/api/web/asset/{0}/play'
MOST_VIEWEDURL = 'http://webapi.tv4play.se/play/video_assets/most_viewed?type=episode&platform=web&is_live=false&per_page=32&start=0'
LIVE_SHOWSURL = 'http://webapi.tv4play.se/play/video_assets?platform=web&is_live=true&per_page=100&sort_order=asc&sort=broadcast_date_t... |
njwilson23/rasterio | tests/test_crs.py | Python | bsd-3-clause | 5,355 | 0.003361 | import logging
import pytest
import subprocess
import sys
import json
import rasterio
from rasterio import crs
from rasterio.crs import (
is_geographic_crs, is_projected_crs, is_same_crs, is_valid_crs)
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
# When possible, Rasterio gives you the CRS in th... | s=GRS80 +y_0=0 +no_defs=True +proj=lcc +x_0=0 +units=m +lat_2=77 +lat_1=49 +lat_0=0')
assert is_geographic_crs(lcc_crs) is False
def test_is_projected():
assert is_projected_crs({'init': 'EPSG:3857'}) is True
assert is_projected_crs({'init': 'EPSG:4326'}) is False
l | cc_crs = crs.from_string('+lon_0=-95 +ellps=GRS80 +y_0=0 +no_defs=True +proj=lcc +x_0=0 +units=m +lat_2=77 +lat_1=49 +lat_0=0')
assert is_projected_crs(lcc_crs) is True
wgs84_crs = crs.from_string('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
assert is_projected_crs(wgs84_crs) is False
def test_is_... |
ktsitsikas/odemis | src/odemis/gui/comp/overlay/view.py | Python | gpl-2.0 | 50,884 | 0.001199 | # -*- coding: utf-8 -*-
"""
:created: 2014-01-25
:author: Rinze de Laat
:copyright: © 2014 Rinze de Laat, Delmic
This file is part of Odemis.
.. license::
Odemis is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License version 2 as published by the Free
... | ight, right, _, margin = self._get_dimensions()
bar_width = max(width / 3, 1)
gap_width = max(width - (2 * bar_width), 1) - 0.5
x = right - margin - bar_width + 0.5
y = margin + 0.5
ctx.set_line_width(1)
ctx.set_source_rgba(*self.colour)
ctx.rectangle(x, y, ba... | et_source_rgb(0, 0, 0)
ctx.stroke()
class FocusOverlay(base.ViewOverlay):
""" Display the focus modification indicator """
def __init__(self, cnvs):
base.ViewOverlay.__init__(self, cnvs)
self.margin = 10
self.line_width = 16
self.shifts = [None, None] # None or float... |
marcokuchla/name-systems | runbr.py | Python | mit | 390 | 0.005128 | #!/usr/ | bin/env python3
# coding=utf-8
"""Executa o servidor de nomes ".br"."""
import logging
import dns
def main():
logging.basicConfig(
format='[ | %(levelname)s]%(threadName)s %(message)s',
level=logging.INFO)
brNS = dns.NameServer('.br', 2, '127.0.0.1', 10001)
brNS.add_record('uem.br', '127.0.0.1:10002')
brNS.run()
if __name__ == '__main__':
main()
|
moonbury/notebooks | github/MatplotlibCookbook/Chapter 7/09.py | Python | gpl-3.0 | 546 | 0.007326 | import numpy
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plot
# Data | generation
alpha = numpy.linspace(1, 8, 5)
t = numpy.linspace(0, 5, 16)
T, A = numpy.meshgrid(t, alpha)
data = numpy.exp(-T * (1. / A))
# Plotting
fig = plot.figure()
ax = fig.gca(projection = '3d')
Xi = T.flatten()
Yi = A.flatten()
Zi = numpy.zeros(data.size)
dx = .25 * numpy.ones(data.size)
dy = .25 * numpy.ones(d... | how()
|
akstealthay/anoy | app/utils/FileIO.py | Python | mit | 406 | 0.007389 | #
# FileIO.py
#
# Description: All FILE utilities goes here
#
import os
def readFile(fi | lePath):
"""
Reads the file file_path and returns the data or appropriate error
"""
error, response = None, {}
try:
with open(filePath, 'rb') as dataFile:
response['raw'] = dataFile.read()
except IOError as e: |
error = e.strerror
return error, response |
quaddra/engage | python_pkg/engage/drivers/standard/postgres_database__9_x/driver.py | Python | apache-2.0 | 5,516 | 0.006708 |
"""Resource manager for postgres-database 9.x
"""
# Common stdlib imports
import sys
import os
import os.path
## import commands
# fix path if necessary (if running from source or running as test)
try:
import engage.utils
except:
sys.exc_clear()
dir_to_add_to_python_path = os.path.abspath((os.path.join(... | _name,
'-U', database_user, '-c', r'\d'], None,
self.ctx.logger, os.path.dirname(psql_exe))
return rc==0
def make_context(reso | urce_json, sudo_password_fn, dry_run=False):
"""Create a Context object (defined in engage.utils.action). This contains
the resource's metadata in ctx.props, references to the logger and sudo
password function, and various helper functions. The context object is used
by individual actions.
If your ... |
akx/stackspy | stackspy/detectors/js/__init__.py | Python | mit | 668 | 0.017964 | # -- encoding: utf-8 --
from __future__ | import with_statement
from stackspy.detection.utils import find_in_html_by_substring
SIMPLE_SUBSTRINGS = {
".google-analytics.com/ga.js": "Google Analytics",
"js/chartbeat.js": "Chartbeat",
".snoobi.com/snoop": "Snoobi",
".quantserve.com/quant.js": "QuantServe",
".addthis.com/js": "AddThis",
"Typekit.load": "... | acta.com/tb/": "Attracta Toolbar",
"var NREUMQ=NREUMQ||[]": "New Relic End User Monitoring",
}
def detect_js(context):
find_in_html_by_substring(context, SIMPLE_SUBSTRINGS)
|
alephu5/Soundbyte | environment/lib/python3.3/site-packages/sympy/physics/wigner.py | Python | gpl-3.0 | 21,674 | 0.001153 | r"""
Wigner, Clebsch-Gordan, Racah, and Gaunt coefficients
Collection of functions for calculating Wigner 3j, 6j, 9j,
Clebsch-Gordan, Racah as well as Gaunt coefficients exactly, all
evaluating to a rational number times the square root of a rational
number [Rasch03]_.
Please see the description of the individual fun... | int_function, division
from sympy import Integer, pi, sqrt, sympify
#from sage.rings.complex_number import ComplexNumber
#from sage.rings.finite_rings | .integer_mod import Mod
# This list of precomputed factorials is needed to massively
# accelerate future calculations of the various coefficients
_Factlist = [1]
def _calc_factlist(nn):
r"""
Function calculates a list of precomputed factorials in order to
massively accelerate future calculations of the v... |
prodicus/spammy | spammy/__init__.py | Python | gpl-3.0 | 7,251 | 0.003448 | # -*- coding: utf-8 -*-
# @Author: tasdik
# @Date: 2016-04-11 18:52:17
# @Last Modified by: Tasdik Rahman
# @Last Modified time: 2016-04-12 17:07:33
# @GPLv3 License
# @http://tasdikrahman.me
# @https://github.com/tasdikrahman
from __future__ import absolute_import, division
import os
import bs4
from spammy.train... |
if limit > safe_limit:
limit = safe_limit
self.directory = directory
self.ha | m = os.path.join(self.directory, ham)
self.spam = os.path.join(self.directory, spam)
self.limit = limit
def train(self):
"""
Trains the classifier object
:param self: the classifier object
:Example:
>>> from spammy import Spammy
>>> direct... |
diogocs1/comps | web/addons/edi/controllers/__init__.py | Python | apache-2.0 | 79 | 0 | import main
# vim: | expandtab:smartindent:tabstop=4:softtabstop=4: | shiftwidth=4:
|
talareq/selenium | test/link_opener.py | Python | apache-2.0 | 753 | 0.007968 |
def test_example(app):
ap | p.litecard_helper.login_admin()
app.get("http://localhost/litecart/admin/?app=countries&doc=countries")
app.get("http://localhost/litec | art/admin/?app=countries&doc=edit_country")
links=app.driver.find_elements_by_css_selector("i.fa.fa-external-link")
for n in range(0,len(links)):
current = app.driver.window_handles[0]
Button = app.driver.find_elements_by_css_selector("i.fa.fa-external-link")
Button[n].click()
ap... |
krother/maze_run | 16_static_typing/highscores.py | Python | mit | 1,039 | 0.002887 |
from typing import NamedTuple, List
import csv
Highscore = NamedTuple('Highscore', [('score', int), ('name', str)])
class HighscoreList:
"""A sorted list of top scores"""
def __init__(self, places: int=10) -> None:
self.scores = [] # type: List[Highscore]
self.places = places
def ad... | = self.scores[:self.places]
def __repr__(self) -> str:
return "\n".join | (["{:10s} {}".format(s.name, s.score) for s in self.scores])
def load_highscores(filename: str) -> HighscoreList:
hs = HighscoreList()
for row in csv.reader(open(filename)):
name = row[0]
score = int(row[1])
hs.add(Highscore(score, name))
return hs
if __name__ == '__main__':
... |
nirvaris/nirvaris-profile | n_profile/views.py | Python | mit | 23,203 | 0.002672 | import pdb
from datetime import date, timedelta
from io import BytesIO
from PIL import Image
from django.contrib.auth import login, logout, authenticate
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models impor... | uestContext |
from django.utils.translation import ugettext as _
from django.views.generic.base import View, TemplateView, RedirectView
from django.views.generic.edit import FormView
from menu.mixins import MenuPermissionsMixin
from menu.permissions import is_admin
from .crypto import decrypt
from .email import send_activation_em... |
petrlosa/ella | ella/core/models/publishable.py | Python | bsd-3-clause | 11,751 | 0.002383 | from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _, ugettext
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.contrib.redirects.models import Redirect
from django.core.validators import ... | '), default=False)
priority = models.PositiveSmallIntegerField(default=1, null=True, blank=True)
# Last updated
last_updated = models.DateTimeField(_('Last updated'), blank=True)
# generic JSON field to store app cpecific data
app_data = AppDataField(default='{}', editable=False)
# has the c... | ish signal sent', default=False, editable=False)
objects = PublishableManager()
class Meta:
app_label = 'core'
verbose_name = _('Publishable object')
verbose_name_plural = _('Publishable objects')
def __unicode__(self):
return self.title
def __eq__(self, other):
... |
alessandrocamilli/l10n-italy | account_fiscal_year_closing/wizard/wizard_run.py | Python | agpl-3.0 | 25,619 | 0.004918 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP - Import operations model 347 engine
# Copyright (C) 2009 Asr Oss. All Rights Reserved
# Copyright (C) 2012 Agile Business Group sagl (<http://www.agilebg.com>)
# Copyright (C) 2012 Domsense sr... | s/>.
#
##############################################################################
"""
Create FYC entries wizards
"""
from tools.translate import _
import netsvc
import decimal_precision as dp
from osv import fields, osv
class wizard_run(osv.osv_memory):
"""
Wizard to create the FYC entries.
"""
... | def run(self, cr, uid, ids, context=None):
"""
Creates / removes FYC entries
"""
pool = self.pool
active_id = context and context.get('active_id', False) or False
if not active_id:
raise osv.except_osv(_('Error'), _('No active ID found'))
# Read the... |
VirtuosoChris/appengine | experimental/shardcounter_sync.py | Python | gpl-3.0 | 2,052 | 0.007797 | import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
... | index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent | ', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is... |
enthought/pyside | tests/QtGui/bug_693.py | Python | lgpl-2.1 | 670 | 0.00597 |
from PySide.QtCore import *
from PySide.QtGui import *
import unittest
class MyModel (QAbstractListModel):
stupidLine = QLine(0, 0, 10, 10)
def rowCount(self, parent):
return 1
def data(self, index, role):
return self.stupidLine
class TestBug693(unittest.TestCase):
| def testIt(self):
app = QApplication([])
model = MyModel()
view = QListView()
view.setModel(model)
view.show()
# This must NOT throw the exception:
# RuntimeError: Internal C++ object (PySide.QtCore.QLine) already deleted.
MyModel.stupidLine.isNull()
... |
unittest.main()
|
cloudbase/nova | nova/tests/unit/virt/libvirt/test_driver.py | Python | apache-2.0 | 828,674 | 0.00039 | # Copyright 2010 OpenStack Foundation
# Copyright 2012 University Of Minho
#
# 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.... | < | slot>0</slot>
<function>1</function>
<product id='0x1013'>MT27700 Family [ConnectX-4]</product>
<vendor id='0x15b3'>Mellanox Technologies</vendor>
<iommuGroup number='15'>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x0'/>
<address domain='0x0000' bus='0... |
mbudiu-vmw/hiero | docs/number-sections.py | Python | apache-2.0 | 4,761 | 0.003571 | #!/usr/bin/env python3
# This script numbers the section in a markdown document
# It makes some simplifying assumptions about the structure
# of the document: i.e., no references occur in quoted blocks
# pylint: disable=invalid-name,missing-docstring
import re
import os
import datetime
class Headings:
def __init_... | erence(heading)
ref = self.makeReference(sectionNumber + heading)
# self.toc.append("|" + sectionNumber + "|[" + heading.strip() + "]" + ref + "|\n")
self.toc.append(spaces + "* " + sectionNumber + " [" + heading.strip() + "]" + ref + "\n")
result = row[0:depth+2] + secti | onNumber + row[depth+1:len(row)]
self.referenceRewrite[origRef] = ref
self.lastDepth = depth
return result
def fixReference(self, match):
reference = match.group(0)
if reference in self.referenceRewrite:
return self.referenceRewrite[reference]
raise ... |
pdellaert/ansible | lib/ansible/modules/system/mount.py | Python | gpl-3.0 | 22,818 | 0.000833 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2012, Red Hat, inc
# Written by Seth Vidal
# based on the mount modules from salt and puppet
# 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
__metacl... | return v
else:
return(
v.
replace('\\', '\\134').
replace(' ', '\\040').
replace('&', '\\046'))
def set_mount(module, args):
"""Set/change a mount point location in fstab."""
to_write = []
exists = False
changed = False
escaped_ar... | ine = '%(src)s %(name)s %(fstype)s %(opts)s %(dump)s %(passno)s\n'
if get_platform() == 'SunOS':
new_line = (
'%(src)s - %(name)s %(fstype)s %(passno)s %(boot)s %(opts)s\n')
for line in open(args['fstab'], 'r').readlines():
if not line.strip():
to_write.append(line)
... |
Skylion007/popupcad | popupcad/filetypes/layer.py | Python | mit | 2,863 | 0.002445 | # -*- coding: utf-8 -*-
"""
Written by Daniel M. Aukes.
Email: danaukes<at>seas.harvard.edu.
Please see LICENSE.txt for full license.
"""
import shapely.geometry as sg
import popupcad
class Layer(object):
def __init__(self, geoms):
self.geoms = geoms
def union(self, layer):
return self.binar... | opupcad.algorithms.csg_shapely.unary_union_safe([newgeom])
result2 = popupcad.algorithms.csg_shapely.condition_shapely_entities(result1)
return type(self)(result2)
def valueoperation(self, functionname, *args, **kwargs):
sourcegeoms = self.geoms
if sourcegeoms == []:
so... | oms)
function = getattr(sourcegeom, functionname)
newgeom = function(*args, **kwargs)
result1 = popupcad.algorithms.csg_shapely.unary_union_safe([newgeom])
result2 = popupcad.algorithms.csg_shapely.condition_shapely_entities(result1)
return type(self)(result2)
def isEmpty(s... |
hryamzik/ansible | lib/ansible/modules/storage/purestorage/purefa_volume.py | Python | gpl-3.0 | 6,827 | 0.001465 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2018, Simon Dodsley (simon@purestorage.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
ANSIBLE_METADATA = {'metadata_version': '1.1',... | ume(module.params['name'])
if human_to_bytes(module.params['size']) > vol['size']:
if not module.check_mode:
array.extend_volume(module.params['name'], module.params['size'])
else:
changed = False
module.exit_json(changed=changed)
def delete_volume(module, array):
""" Delet... | try:
array.destroy_volume(module.params['name'])
if module.params['eradicate']:
try:
array.eradicate_volume(module.params['name'])
except:
changed = False
except:
changed = False
module.exit_json(c... |
6si/alembic | tests/test_autogenerate.py | Python | mit | 52,371 | 0.004965 | import re
import sys
from unittest import TestCase
from . import Mock
from sqlalchemy import MetaData, Column, Table, Integer, String, Text, \
Numeric, CHAR, ForeignKey, DATETIME, INTEGER, \
TypeDecorator, CheckConstraint, Unicode, Enum,\
UniqueConstraint, Boolean, ForeignKeyConstraint,\
PrimaryKeyCons... | lalchemy.engine.reflection import Inspector
from sqlalchemy.sql import and_, column, literal_column
from alembic import autogenerate, util, compat
from alembic.migration import MigrationContext
from . import staging_env, sqlite_db, clear_staging_env, eq_, \
eq_ignore_whitespace, db_for_dialect
py3k = sys.vers... | , reflected, compare_to):
if type_ == "table":
return name in names_in_this_test
else:
return True
_default_object_filters = [
_default_include_object
]
from sqlalchemy import event
@event.listens_for(Table, "after_parent_attach")
def new_table(table, parent):
names_in_this_test.add(tab... |
ikben/troposphere | troposphere/elasticache.py | Python | bsd-2-clause | 5,785 | 0 | # Copyright (c) 2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
import re
from . import AWSObject, AWSProperty, Tags
from .validators import boolean, integer, network_port
def validate_node_group_id(node_group_id):
if re.match(r'\d{1,4}', node_group_id):
ret... | p': (integer, False),
'ReplicationGroupDescription': (basestring, True),
'ReplicationGroupId': (basestring, False),
'SecurityGroupIds': ([basestring], False),
'SnapshotArns': ([basestring], False),
'SnapshotName': (basestring, False),
'SnapshotRetentionLimit': (integer, F... | ': (Tags, False),
'TransitEncryptionEnabled': (boolean, False),
}
def validate(self):
if 'NumCacheClusters' not in self.properties and \
'NumNodeGroups' not in self.properties and \
'ReplicasPerNodeGroup' not in self.properties and \
'PrimaryClusterId' not in se... |
y-lan/python-hiveserver2 | src/TCLIService/constants.py | Python | apache-2.0 | 883 | 0.021518 | #
# Autogenerated by Thrift Compiler (0.9.0)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TException, TApplicationException
from ttypes import *
PRIMITIVE_TYPES = set([
0,
1,
2,
3,
4,
5,
6,
... | NAMES = {
0 : "BOOLEAN",
1 : "TINYINT",
2 : "SMALLINT",
3 : "INT",
4 : "BIGINT",
5 : "FLOAT",
6 : "DOUBLE",
7 : "STRING",
8 : "TIMESTAMP",
9 : "BINARY",
10 : "ARRAY",
11 : "MAP",
12 : "STRUCT",
| 13 : "UNIONTYPE",
15 : "DECIMAL",
16 : "NULL",
17 : "DATE",
18 : "VARCHAR",
}
CHARACTER_MAXIMUM_LENGTH = "characterMaximumLength"
|
gboenn/chunking | python/expwindow.py | Python | gpl-3.0 | 304 | 0.006579 | # expwindow.py
# Copyright (C) 2018 Georg Boenn
# GNU General Public License version 3.0
# Free Software Foundation
import math as m
def expw | in(n):
win = []
step = 2./n
for k in range(n+1):
val = -1. + k*step
win.append(m.exp(-(val*val)))
return win
#pr | int expwin(128)
|
SitiBanc/1061_NCTU_IOMDS | 1025/Homework 5/HW5_2.py | Python | apache-2.0 | 6,016 | 0.002021 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 25 21:46:31 2017
@author: sitibanc
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# =============================================================================
# Read CSV
# =============================================... | ]
# 設定停損點
idx2 = np.nonzero(TAIEX[idx, 4] <= p1 - 30)[0] # 最低價跌破停損點
# | 設定停利點
idx3 = np.nonzero(TAIEX[idx, 3] >= p1 + 30)[0] # 最高價衝破停利點
if len(idx2) == 0 and len(idx3) == 0: # 當日沒有觸及平損停利點
p2 = TAIEX[idx[-1], 1] # 當日收盤價賣出
elif len(idx3) == 0: # 當日沒有停利但停損
p2 ... |
saisankargochhayat/algo_quest | leetcode/763. Partition Labels/soln.py | Python | apache-2.0 | 555 | 0.003604 | from typing import List
class Solution:
def partitionLabels(self, S: str) -> List[int]:
lastPos, seen, currMax = {}, set(), -1
res = []
for i in range(0, 26):
c = chr(97+i)
lastPo | s[c] = S.rfind(c)
for i, c in enumerate(S):
# Encounter new index higher than currMax
if | i > currMax:
res.append(currMax+1)
currMax = max(currMax, lastPos[c])
res.append(len(S))
ans = [res[i]-res[i-1] for i in range(1, len(res))]
return ans |
kingvuplus/PKT-gui2 | skin.py | Python | gpl-2.0 | 33,730 | 0.033353 | from Tools.Profile import profile
profile("LOAD:ElementTree")
import xml.etree.cElementTree
import os
profile("LOAD:enigma_skin")
from enigma import eSize, ePoint, eRect, gFont, eWindow, eLabel, ePixmap, eWindowStyleManager, addFont, gRGB, eWindowStyleSkinned, getDesktop
from Components.config import ConfigSubsection,... | val = 0
if s:
if s[-1] is '%':
val += e * int(s[:-1]) / 100
elif s[-1] is 'w':
val += fonts[fo | nt][3] * int(s[:-1])
elif s[-1] is 'h':
val += fonts[font][2] * int(s[:-1])
else:
val += int(s)
if val < 0:
val = 0
return val
def getParentSize(object, desktop):
size = eSize()
if object:
parent = object.getParent()
# For some widgets (e.g. ScrollLabel) the skin attributes are applied to
# ... |
Microvellum/Fluid-Designer | win64-vc/2.78/Python/lib/site-packages/PIL/PaletteFile.py | Python | gpl-3.0 | 1,113 | 0 | #
# Python Imaging Library
# $Id$
#
# stuff to read simple, teragon-style palette files
#
# History:
# 97-08-23 fl Created
#
# Copyright (c) Secret Labs AB 1997.
# Copyright (c) Fredrik Lundh 1997.
#
# See the README file for information on usage and redistribution | .
#
from PIL._binary import o8
##
# File | handler for Teragon-style palette files.
class PaletteFile(object):
rawmode = "RGB"
def __init__(self, fp):
self.palette = [(i, i, i) for i in range(256)]
while True:
s = fp.readline()
if not s:
break
if s[0:1] == b"#":
... |
accwebs/DockerMake | dockermake/imagedefs.py | Python | apache-2.0 | 7,810 | 0.002049 | #!/usr/bin/env python2.7
# Copyright 2016 Autodesk 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 la... | dependencies[image] = None
return dependencies.keys()
def get_external_base_image(self, image):
""" Makes sure that this image has exactly one external base image
"""
exter | nalbase = self.ymldefs[image].get('FROM', None)
for base in self.ymldefs[image].get('requires', []):
try:
otherexternal = self.get_external_base_image(base)
except ValueError:
continue
if externalbase is None:
externalbase = o... |
Lambdanaut/crits | crits/core/management/commands/create_default_collections.py | Python | mit | 4,409 | 0.001361 | import os
from django.conf import settings
from django.core.management.base import BaseCommand
from optparse import make_option
from create_indexes import create_indexes
from create_locations import add_location_objects
from setconfig import create_config_if_not_exist
from create_default_dashboard import create_dashb... | ,
dest='drop',
action="store_true",
| default=False,
help='Drop existing content before adding.'),
)
help = 'Creates default CRITs collections in MongoDB.'
def handle(self, *args, **options):
"""
Script Execution.
"""
drop = options.get('drop')
if drop:
print "D... |
faush01/MBCon | resources/lib/clientinfo.py | Python | gpl-2.0 | 1,316 | 0.00152 | # Gnu General Public License - see LICENSE.TXT
from uuid import uuid4 as uuid4
import xbmcaddon
import xbmc
import xbmcvfs
from .kodi_utils import HomeWindow
from .simple_logging import SimpleLogging
log = SimpleLogging(__name__)
class ClientInformation():
def getDeviceId(self):
WINDOW = HomeWindow()
... |
emby_guid_path = xbmc.translatePath("special://temp/embycon_guid").decode('utf-8')
log.debug("emby_guid_path: {0}", emby_guid_path)
guid = xbmcvfs.File(emby_guid_path)
client_id = guid.read()
guid.close()
if not client_id:
client_id = str("%012X" % uuid4())... |
guid.write(client_id)
guid.close()
log.debug("emby_client_id (NEW): {0}", client_id)
else:
log.debug("emby_client_id: {0}", client_id)
WINDOW.setProperty("client_id", client_id)
return client_id
def getVersion(self):
addon = xbmcaddo... |
joshbruning/selenium | py/selenium/webdriver/remote/webelement.py | Python | apache-2.0 | 24,103 | 0.000913 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for addi | tional information
# regarding copyright ownership. The SFC 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 by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import ba... |
Marcelpv96/SITWprac2017 | sportsBetting/forms.py | Python | gpl-3.0 | 1,955 | 0.002046 | from django import forms
from .models import *
class TeamForm(forms.ModelForm):
crest = forms.ImageField(required=False)
class Meta:
model = Team
fields = ('name', 'short_name', 'crest', )
widgets = {
'name': forms.TextInput(attrs={
'class': 'input-sm form-c... | red=False)
class Meta:
model = Competition
exclude = ('user', )
widgets = {
'name': forms.TextInput(attr | s={
'class': 'input-sm form-control',
'placeholder': 'Enter the complete name...'
}),
'short_name': forms.TextInput(attrs={
'class': 'input-sm form-control',
'placeholder': 'This name will be used in creating the name event...'
... |
OpenReliability/OpenReliability | veusz/document/emf_export.py | Python | gpl-2.0 | 14,999 | 0.003734 | # Copyright (C) 2009 Jeremy S. Sanders
# Email: Jeremy Sanders <jeremy@jeremysanders.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 Foundation; either version 2 of the License, or
# ... | i < count:
e = path.elementAt(i)
if e.type == qt4.QPainterPath.MoveToElement:
self.emf.MoveTo( int(e.x*scale), int(e.y*scale) )
#print "M", e.x*scale, e.y*scale
elif e.type == qt4.QPainterPath.LineToElement:
self.emf.LineTo( int(e.x*sca... | scale
elif e.type == qt4.QPainterPath.CurveToElement:
e1 = path.elementAt(i+1)
e2 = path.elementAt(i+2)
params = ( ( int(e.x*scale), int(e.y*scale) ),
( int(e1.x*scale), int(e1.y*scale) ),
( int(e2.x*scale)... |
huiyiqun/check_mk | agents/windows/it/test_section_df.py | Python | gpl-2.0 | 1,334 | 0 | #!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset: 4 -*-
import os
import pytest
import re
from remote import (actual_output, config, remotetest, remotedir, wait_agent,
write_c | onfig)
class Globals(object):
section = 'df'
alone = True
@pytest.fixture
def testfile():
return os.path.basename(__file__)
@pytest.fixture(params=['alone', 'with_systemtime'])
def testconfig(request, config):
Globa | ls.alone = request.param == 'alone'
if Globals.alone:
config.set('global', 'sections', Globals.section)
else:
config.set('global', 'sections', '%s systemtime' % Globals.section)
config.set('global', 'crash_debug', 'yes')
return config
@pytest.fixture
def expected_output():
drive = ... |
laurentb/weboob | modules/binck/__init__.py | Python | lgpl-3.0 | 843 | 0 | # -*- coding: utf-8 -*-
# Copyright(C) 2016 Edouard Lambert
#
# This file is part of a weboob module.
#
# This weboob module is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the... | PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a co | py of the GNU Lesser General Public License
# along with this weboob module. If not, see <http://www.gnu.org/licenses/>.
from .module import BinckModule
__all__ = ['BinckModule']
|
xbash/LabUNAB | 01_Introduccion/temp3.py | Python | gpl-3.0 | 142 | 0.042254 | while True:
temp = float(input("Un valor valido? "))
if t | emp > 50 and temp <52:
print("Numero correcto")
print("Intenta nuevamente!") | |
CooperLuan/devops.notes | taobao/top/api/rest/ItemUpdateDelistingRequest.py | Python | mit | 318 | 0.028302 | '''
Created by auto_sdk on 2014-12-17 17:22:51
'''
from top.api.base import RestApi
class ItemUpdateDelistingRequest(RestApi):
def __init__(self,domain='gw.api.taob | ao.com',port=80):
RestApi.__init__(self,domain, port)
self.num_iid = None
def getapiname(self):
return 'taobao.ite | m.update.delisting'
|
peeringdb/peeringdb-py | src/peeringdb/_fetch.py | Python | apache-2.0 | 3,326 | 0.000601 | """
RPC / REST client implementation module
"""
import re
import requests
from twentyc.rpc import RestClient
from twentyc.rpc.client import (
InvalidRequestException,
NotFoundException,
PermissionDeniedException,
)
import peeringdb
class CompatibilityError(Exception):
pass
class Fetcher(RestClient... | rams=kwargs))
def _request(self, typ, id=0, method="GET", params=None, data=None, url=None):
"""
send the request, return response obj
"""
backend, backend_version = peeringdb.get_backend_info()
user_agent = "PeeringDB/{} {}/{}".format(
peeringdb.__version__, bac... |
"Accept": "application/json",
"User-Agent": user_agent,
}
auth = None
if self.user:
auth = (self.user, self.password)
if not url:
if id:
url = "{}/{}/{}".format(self.url, typ, id)
else:
url = "{... |
misnyo/searx | searx/engines/google.py | Python | agpl-3.0 | 13,491 | 0.001482 | # Google (Web)
#
# @website https://www.google.com
# @provide-api yes (https://developers.google.com/custom-search/)
#
# @using-api no
# @results HTML
# @stable no (HTML can change)
# @parse url, title, content, suggestion
import re
from flask_babel import gettext
from lxml import html, etree
fro... | "spe | ll"]'
# map : detail location
map_address_xpath = './/div[@class="s"]//table//td[2]/span/text()'
map_phone_xpath = './/div[@class="s"]//table//td[2]/span/span'
map_website_url_xpath = 'h3[2]/a/@href'
map_website_title_xpath = 'h3[2]'
# map : near the location
map_near = 'table[@class="ts"]//tr'
map_near_title = './/h... |
qitianchan/LightLights | lightlights/utils/__init__.py | Python | apache-2.0 | 279 | 0.007168 | # -*- coding: utf-8 -*
from flask import jsonify
def | jsonifyReturn(success=True, status_code=201, code=1000, message='Success', data=None):
res = jsonify({'success': success, 'code': code, 'message': message, 'data': data})
res.status_code = status_code
return re | s
|
dcbishop/py-shell-alias | test_aliasdb.py | Python | cc0-1.0 | 5,584 | 0 | import unittest
import io
import aliasdb
from aliasdb import Alias, AliasDB, JSONBackend
class FakeAliasDatabase():
def __init__(self):
self.aliases = []
def add_alias(self, alias):
self.aliases.append(alias)
def get_aliases(self):
return self.aliases
def make_fake_aliases():
... | expected = """alias test="echo \\\'This contains quotes\\\'"\n"""
self.assertEqual(expected, result)
def test_contains_doublequotes(self):
adb = make_test_json_aliasdb()
adb.add_alias(Alias('test', 'echo "This contains quotes"'))
result = adb.get_sh_script()
expected = "a... | adb = make_test_json_aliasdb()
adb.add_alias(Alias('hasbrackets', 'echo (This is in brackets)'))
result = adb.get_sh_script()
expected = 'alias hasbrackets="echo (This is in brackets)"\n'
self.assertEqual(expected, result)
|
isomer/dhcparpd | pyomapi/test.py | Python | gpl-2.0 | 301 | 0.0299 | #!/usr/bin/python2.4
import omapi
a=omapi.Omapi("10.1.23.3",7911,"OMAPI","dGVzdGtleQ==")
mac=a.lookup_mac("10.4.254.255")
print "mac= | ",mac
ip=a.lookup_ip(mac)
print "ip=",ip
print "adding host"
a.add_ho | st("10.4.255.252","00:01:02:03:04:05")
print "deleting host"
a.del_host("00:01:02:03:04:05")
|
thoolihan/KaggleMNIST | Python/nn.py | Python | apache-2.0 | 4,805 | 0.008533 | import tensorflow as tf
import numpy as np
import pandas as pd
import time
def get_step_indexes(step, batch_size, n):
start = (step * batch_size) % n
stop = start + batch_size
if stop > n:
stop = n
return (start, stop)
ratio = 0.7
batch_size = 1000
n_features = 784
label_index = 0
feature_ind... | skiprows = 1,
dtype = np.float32,
usecols = range(0, n_features + 1))
np.random.shuffle(x_all)
n_total = x_all.shape[0]
split = int(ratio * n_total)
n_hidden_1 = np.int32(np.floor(n_features / 2))
n_hidden_2 = np.int32(np.floor(n_features / 2))
n_hidden_3 = np.int32(np.floor(n_features /... | int(b)] = 1.0
x_train = x_all[:split, feature_index]
x_test = x_all[split:, feature_index]
y_train = y_all[:split, :]
y_test = y_all[split:, :]
n = x_train.shape[0]
x = tf.placeholder("float", [None, n_features])
y = tf.placeholder("float", [None, n_classes])
dropout = tf.placeholder("float")
def nn(_X, _weights, _b... |
Duke-LeTran/practice-and-notes | decorators.py | Python | mit | 1,230 | 0.011382 | """
This is a decorator practice script
"""
class Test:
def __init__(self):
self._value = 5
@property
def value(self) -> int:
return self._value
@value.setter
def value(self, value: int) -> None:
self._value = value
@value.deleter
def value(self) -> None:
... | ing.pub/decorators-in-python-72a1d578eac4
* https://realpython.com/primer-on-python-decorators/#timing-functions
* https://realpython.com/primer-on-python-decorators/#decorators-with-arguments
"""
@fun | ctools.wraps(func)
def wrapper_timer():
start_time = time.perf_counter() # starts counting
func() # main
end_time = time.perf_counter() # ends counting
time_elapsed = end_time - start_time
print(f"Main completed in {time_elapsed:.4f}s.")
return wrapper_timer
if __name__ ... |
hanlind/nova | nova/virt/libvirt/designer.py | Python | apache-2.0 | 5,322 | 0.000376 | # Copyright (C) 2013 Red Hat, 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 ... | hrough'
conf.source_dev = pci_utils.get_ifname_by_pci_address(devname)
conf.driver_name = 'vhost'
else:
conf.source_dev = devname
conf.model = None
conf.vporttype = "802.1Qbh"
conf.add_vport_param("profileid", profileid)
if tapname:
conf.target_dev = tapname
def... | opulate a LibvirtConfigGuestInterface instance
with host backend details for an device that supports hardware
virtual ethernet bridge.
"""
conf.net_type = net_type
if net_type == 'direct':
conf.source_mode = 'passthrough'
conf.source_dev = pci_utils.get_ifname_by_pci_address(devname... |
schollz/playlistfromsong | docs/conf.py | Python | mit | 8,685 | 0.005066 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# playlistfromsong documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in t... | show_copyright = True
# If true, an OpenSearch description file will be output, and all pages
# will contain a <link> tag referring to it. The value of this option
# must be the base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#... | fromsongdoc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#... |
zenodo/invenio | invenio/base/signals.py | Python | gpl-2.0 | 3,895 | 0 | # -*- coding: utf-8 -*-
# This file is part of Invenio.
# Copyright (C) 2013, 2014 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any ... | gnals.signal(
'websearch-before-search')
"""
This signal is sent right before search handler is called.
"""
websearch_before_browse = _signals.signal(
'websearch-before-browse | ')
"""
This signal is sent right before browse handler is called.
"""
webcoll_after_webpage_cache_update = _signals.signal(
'webcoll-after-webpage-cache-update')
"""
This signal is sent right after webcoll runs webpage cache update.
It is passed the collection to be sent named `response`.
Example subscriber::
... |
mribeirodantas/newpump | travas.py | Python | gpl-3.0 | 848 | 0.001179 | __author__ = 'pabloholanda'
import settings
def trava(vp):
if -4 <= vp <= 4:
return vp
elif vp > 4.00:
return 4
elif vp < -4:
return -4.00
def trava_alto_nivel(vp):
if settings.tanque['pvtq_1'] > 28 and vp > 3.15:
return 3.15
else:
return vp
def trava_mu... | gs.tanque['pvtq_1'] < 4.00) and (vp < 0):
return 0
else:
re | turn vp
def nivel_cascata(pv):
if pv > 30:
return 30
elif pv < -30:
return -30
else:
return pv
def sequencia_travas(vp):
vp = trava(vp)
vp = trava_alto_nivel(vp)
vp = trava_muito_nivel(vp)
vp = trava_nivel_baixo(vp)
return vp
|
mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/eggs/Cheetah-2.2.2-py2.7-linux-x86_64-ucs4.egg/Cheetah/Utils/VerifyType.py | Python | gpl-3.0 | 2,938 | 0.002723 | # $Id: VerifyType.py,v 1.4 2005/11/02 22:26:08 tavis_rudd Exp $
"""Functions to verify an argument's type
Meta-Data
================================================================================
Author: Mike Orr <iron@mso.oz.net>
License: This software is released for unlimited distribution under the
terms ... | '\n' + errmsgExtra
return "arg '%s' must be %s%s" % (argname, ltd, errmsgExtra)
##################################################
## TYPE VERIFICATION FUNCTIONS
def VerifyType(arg, argname, legalTypes, ltd, errmsgExtra=''):
"""Verify the type of an argument.
arg, any, the argument.
argname, str... | , the allowed types.
ltd, string, description of legal types (for error message).
errmsgExtra, string, text to append to error message.
Returns: None.
Exceptions: TypeError if 'arg' is the wrong type.
"""
if type(arg) not in legalTypes:
m = _errmsg(argname, ltd, errmsgExtra)
rais... |
PanDAWMS/panda-server | pandaserver/srvcore/MailUtils.py | Python | apache-2.0 | 4,037 | 0.008174 | '''
email utilities
'''
import sys
import smtplib
from pandaserver.config import panda_config
from pandacommon.pandalogger.PandaLogger import PandaLogger
# logger
_logger = PandaLogger().getLogger('MailUtils')
# wrapper to patch smtplib.stderr to send debug info to logger
class StderrLogger(object):
def __init... | userStr = ''
for userName in userNames:
userStr += ' %s,' % userName
userStr = userStr[:-1]
mailBody += " %s\n\n" % userStr
# send
retVal = self.send(toAddr,mailSubject,mailBody)
# return
return retVal
# add tailer
... | sis-help@cern.ch
the Panda JIRA for software bug
https://its.cern.ch/jira/browse/ATLASPANDA
"""
return msg
|
dragly/doconce | lib/doconce/gwiki.py | Python | bsd-3-clause | 9,341 | 0.003212 | """
Google Code Wiki translator.
Syntax defined by http://code.google.com/p/support/wiki/WikiSyntax
Here called gwiki to make the dialect clear (g for google).
"""
import re, os, commands, sys
from common import default_movie, plain_exercise, insert_code_and_tex, \
fix_ref_section_chapter
from plaintext import p... | \n', r'}}}\n', filestr)
return filestr
def gwiki_figure(m):
filename = m.group('filename')
link = filename if filename.startswith('http') else None
if not link and not os.path.isfile(filename):
raise IOError('no figure file %s' % filename)
| basename = os.path.basename(filename)
stem, ext = os.path.splitext(basename)
root, ext = os.path.splitext(filename)
if link is None:
if not ext in '.png .gif .jpg .jpeg'.split():
# try to convert image file to PNG, using
# convert from ImageMagick:
cmd = 'con... |
mitlib-tdm/foist | foist/__init__.py | Python | apache-2.0 | 257 | 0 | # -*- coding: utf-8 -*-
"""
FOIST
"""
from .app import (create_container, initialize_custom_prefixes,
parse_text_encoding_errors, Thesis, transaction, |
upload_file, update_metadata, upload_thesis)
__version__ = '0.1.0'
| |
yeukhon/algorithm | leetcode/tests/test_2_add_two_numbers.py | Python | mpl-2.0 | 1,220 | 0.001639 | import unittest
from leetcode.s2_add_two_numbers import Solution, ListNode
class TestAddTwoNumbers(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.solution = Solution().addTwoNumbers
def test_default_case(self):
l1 = ListNode(2)
l1.next = ListNode(4)
l1.next.next... | l2.next = ListNode(2)
answer = self.solution(l1, l2)
self.assertEqual(answer.val, '0')
self.assertEqual(answer.next.val, '3')
def test_99_plus_1(self):
l1 = ListNode(9)
l1.next = ListNode(9)
l2 = ListNode(1)
answer = self.solution(l1, l2)
se... | next.val, '1')
if __name__ == '__main__':
unittest.main()
|
ppizarror/Ned-For-Spod | bin/external/pil/TiffImagePlugin.py | Python | gpl-2.0 | 27,979 | 0.006684 | #
# The Python Imaging Library.
# $Id$
#
# TIFF file handling
#
# TIFF is a flexible, if somewhat aged, image file format originally
# defined by Aldus. Although TIFF supports a wide variety of pixel
# layouts and compression methods, the name doesn't really stand for
# "thousands of incompatible file formats," it jus... | --------------
# Read TIFF files
def il16(c,o=0):
return ord(c[o]) + (ord(c[o+1])<<8)
def il32(c,o=0):
return ord(c[o]) + (ord(c[o+1])<<8) + (ord(c[o+2] | )<<16) + (ord(c[o+3])<<24)
def ol16(i):
return chr(i&255) + chr(i>>8&255)
def ol32(i):
return chr(i&255) + chr(i>>8&255) + chr(i>>16&255) + chr(i>>24&255)
def ib16(c,o=0):
return ord(c[o+1]) + (ord(c[o])<<8)
def ib32(c,o=0):
return ord(c[o+3]) + (ord(c[o+2])<<8) + (ord(c[o+1])<<16) + (ord(c[o])<<24)
de... |
zestrada/nova-cs498cc | nova/network/security_group/security_group_base.py | Python | apache-2.0 | 8,407 | 0.001189 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Piston Cloud Computing, Inc.
# Copyright 2012 Red Hat, Inc.
# Copyright 2013 Nicira, Inc.
# All Rights Reserved
#
# Licen... | om_port = int(from_port)
to_port = int(to_port)
except ValueError:
if ip_protocol.upper() == 'ICMP':
raise exception.InvalidInput(reason="Type and"
" Code must be integers for ICMP protocol type")
| else:
raise exception.InvalidInput(reason="To and From ports "
"must be integers")
if ip_protocol.upper() not in ['TCP', 'UDP', 'ICMP']:
raise exception.InvalidIpProtocol(protocol=ip_protocol)
# Verify that from_port ... |
psathyrella/partis | bin/test-per-base.py | Python | gpl-3.0 | 8,597 | 0.007095 | #!/usr/bin/env python
import csv
import os
import sys
import argparse
import colored_traceback.always
# if you move this script, you'll need to change this method of getting the imports
partis_dir = os.path.dirname(os.path.realpath(__file__)).replace('/bin', '')
sys.path.insert(1, partis_dir + '/python')
import utils... | 10 --constant-number-of-leaves --seed 1' # --check-tree-depths
simcmd = './bin/partis simulate --n-sim-events 100 --n-procs 8 --only-genes IGHV1-2*02:IGHJ4*02 -- | n-leaves 10 --constant-number-of-leaves --seed 1 --mutation-multiplier 5' # --check-tree-depths
for label, xtra_args in cfglist:
utils.simplerun('%s %s --outfname %s/%s/simu.yaml' % (simcmd, ' '.join(xtra_args), outdir, label)) #, dryrun=True)
utils.simplerun('./bin/example-parse-output.py --fname %s/%s/simu.... |
noppanit/wp-downloader | dump_to_es.py | Python | mit | 1,435 | 0.003484 | from pymongo import MongoClient
from elasticsearch import Elasticsearch
client = MongoClient()
db = client.wp
posts = db.posts.find({})
es = Elasticsearch()
es.indices.delete(index='wp-posts | ', ignore=[400, 404])
es.indices.create(
index='wp-posts',
body={
'settings': {
# just one shard, no replicas for tes | ting
'number_of_shards': 1,
'number_of_replicas': 0,
'mappings': {
'post': {
'properties': {
'content': {
'type' :'string',
"index" : "analyzed"
... |
mfherbst/spack | var/spack/repos/builtin/packages/perl-extutils-pkgconfig/package.py | Python | lgpl-2.1 | 1,647 | 0.001821 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it und | er the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. S... |
eliasfernandez/django-simplecms | cms/urls.py | Python | bsd-2-clause | 537 | 0.020484 | from django.conf.urls import include, url
from d | jango.views.generic.base import RedirectView
from cms.models import *
from cms.views import show
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = [
url(r'^$', show,{'slug':"/%s"%settings.HOME_SLUG}, name='cms.home'), # contenido ... | 'cms.show'),
] |
normanmaurer/autobahntestsuite-maven-plugin | src/main/resources/autobahntestsuite/wamptestserver.py | Python | apache-2.0 | 7,727 | 0.027307 | ###############################################################################
##
## Copyright 2011,2012 Tavendo GmbH
##
## 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:... | turn None
else:
print "event is not dict or misses count attribute"
return None
except:
print "illegal topic - skipped publication of event"
return None
class WampTestServerProtocol(WampServerProtocol):
def onSessionOpen(self):
self.initSimpleRpc()
... | itCalculator()
self.initSimplePubSub()
self.initPubSubAuth()
def initSimpleRpc(self):
## Simple RPC
self.simple = Simple()
self.registerForRpc(self.simple, "http://example.com/simple/calc#")
def initKeyValue(self):
## Key-Value Store
self.registerForRpc(self.factory.key... |
50thomatoes50/blender.io_mqo | io_scene_mqo/export_mqo.py | Python | gpl-2.0 | 12,347 | 0.00575 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | tate -90 degrees about X axis
vv = m @ v.co
fw.append("\t\t%.5f %.5f %.5f\n" % (vv[0]*scale, vv[1]*scale, vv[2]*scale))
else:
fw.append("\t\t%.5f %.5f %.5f\n" % (v.co[0]* | scale, v.co[1]*scale, v.co[2]*scale))
fw.append("\t}\n")
me.update(calc_edges=True, calc_edges_loose=True)
faces = me.polygons
lostEdges = 0
for e in me.edges:
if e.is_loose:
lostEdges+=1
if edge:
fw.append("\tface %i {\n" % (len(faces)+lostEdges))
for e in m... |
praekelt/molo-freebasics | freebasics/wsgi.py | Python | bsd-2-clause | 409 | 0 | """
WSGI config for base freebasics.
It exposes the WSGI callable as a module-level variable named ``application``.
For more infor | mation on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault(
"DJANGO_SETTINGS_MODULE", "freebasics.settings.production")
application = g | et_wsgi_application()
|
adalke/rdkit | rdkit/Chem/PandasTools.py | Python | bsd-3-clause | 22,208 | 0.017201 | '''
Importing pandasTools enables several features that allow for using RDKit molecules as columns of a Pandas dataframe.
If the dataframe is containing a molecule format in a column (e.g. smiles), like in this example:
>>> from rdkit.Chem import PandasTools
>>> import pandas as pd
>>> import os
>>> from rdkit import R... | _ import print_function
from base64 import b64encode
import types,copy
from rdkit.six import BytesIO, string_types
from rdkit import Chem
from rdkit.Chem import Draw
try:
import pandas as pd
try:
v = pd.__version__.split('.')
except AttributeError:
# support for older versions of pandas
v = pd.vers... | idth' in pd.core.config._registered_options:
pd.set_option('display.width',1000000000)
if 'display.max_rows' in pd.core.config._registered_options:
pd.set_option('display.max_rows',1000000000)
elif 'display.height' in pd.core.config._registered_options:
pd.set_option('display.height',100000... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.