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 |
|---|---|---|---|---|---|---|---|---|
SpiNNakerManchester/SpiNNer | tests/test_transforms.py | Python | gpl-2.0 | 4,699 | 0.070653 | import pytest
from spinner import transforms
from spinner import coordinates
from spinner import cabinet
from example_cabinet_params import exact
def test_hex_to_cartesian():
h = coordinates.Hexagonal
c = coordinates.Cartesian2D
# Test single element cases
o0 = "o0"
o1 = "o1"
o2 = "o2"
assert transforms.he... | gaps(
[(o0, c(0,0,0)), (o1, c(0,0,2))])) ==\
set([(o0, c(0,0,0)), (o1, c(0,0,1))])
assert set(transforms.remove_gaps(
[(o0, c(0,0,5)), (o1, c(0,0,2))]) | ) ==\
set([(o0, c(0,0,1)), (o1, c(0,0,0))])
# Independent frames with restructuring needs
assert set(transforms.remove_gaps(
[(o0, c(1,0,5)), (o1, c(0,1,2))])) ==\
set([(o0, c(1,0,0)), (o1, c(0,1,0))])
assert set(transforms.remove_gaps(
[(o0, c(0,0,0)), (o1, c(0,0,3)), (o2, c(1,0,3))])) ==\
set([(o0, c(0... |
achille-fouilleul/meta-ii | from_asm.py | Python | mit | 582 | 0.010309 | def get_mnemo_arg(l):
assert l.startswith(' ')
l = l.strip()
| i = l.find(' ')
if i >= 0:
return (l[:i], l[i+1:].strip())
else:
return (l, None)
def get_func_names(lines):
names = set()
entry = None
for l in lines:
if l.startswith(' '):
mnemo, arg = get_mnemo_arg(l)
if mnemo in { 'ADR', 'CLL' }:
n... |
assert entry is None
assert arg is not None
entry = arg
return entry, names
|
buguen/pylayers | pylayers/util/mayautil.py | Python | lgpl-3.0 | 8,758 | 0.007993 | # -*- coding:Utf-8 -*-
import numpy as np
from traits.api import HasTraits, Instance, Array, on_trait_change
from traitsui.api import View, Item, HGroup, Group
from tvtk.api import tvtk
from tvtk.pyface.scene import Scene
from mayavi import mlab
from mayavi.core.api import PipelineBase, Source
from mayavi.core.ui.ap... |
Item('scene_z',
editor=SceneEditor(scene_cl | ass=Scene),
height=250, width=300),
show_labels=False,
),
Group(
Item('scene_x',
editor=SceneEditor(scene_class=Scene),
height=250, width=300),
... |
iAddz/allianceauth | services/modules/mumble/tasks.py | Python | gpl-2.0 | 1,977 | 0.002023 | from __future__ import unicode_literals
from alliance_auth.celeryapp import app
from django.con | f import settings
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from .models import MumbleUser
from .manager import MumbleManager
import logging
logger = logging.getLogger(__name__)
class MumbleTasks:
def __init__(self):
pass
@staticmethod
de... | ccount(user):
try:
return user.mumble.username != ''
except ObjectDoesNotExist:
return False
@staticmethod
def disable_mumble():
logger.info("Deleting all MumbleUser models")
MumbleUser.objects.all().delete()
@staticmethod
@app.task(bind=True, na... |
Techbikers/techbikers | server/rides/urls.py | Python | mit | 732 | 0.005464 | from django.conf.urls import url, include
from server.rides.views import RidesList, RideDetails, RideRidersList, RideRiderDetails, RideRiderCharge, RideRiderFundraiser
urlpatterns = [
url(r'^(?P<id>\d+)/riders/(?P<rider_ | id>\d+)/fundraiser', RideRiderFu | ndraiser.as_view(), name='ride-rider-fundraiser'),
url(r'^(?P<id>\d+)/riders/(?P<rider_id>\d+)/charge', RideRiderCharge.as_view(), name='ride-rider-charge'),
url(r'^(?P<id>\d+)/riders/(?P<rider_id>\d+)', RideRiderDetails.as_view(), name='ride-rider-details'),
url(r'^(?P<id>\d+)/riders', RideRidersList.as_vi... |
Valeureux/wezer-exchange | __unreviewed__/community_marketplace/community_marketplace.py | Python | agpl-3.0 | 2,488 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Yannick Buron and Valeureux Copyright Valeureux.org
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License a | s
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPO... | General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm
class Groups... |
agilman/django-maps | maps/migrations/0005_userprofilepicture.py | Python | mit | 885 | 0.00226 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-12-20 04:17
from __future__ import unicode_literals
from django.conf import s | ettings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migratio | ns.swappable_dependency(settings.AUTH_USER_MODEL),
('maps', '0004_auto_20161217_2034'),
]
operations = [
migrations.CreateModel(
name='UserProfilePicture',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name... |
ExCiteS/geokey-sapelli | geokey_sapelli/migrations/0006_sapelliproject_sapelli_fingerprint.py | Python | mit | 468 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('geokey_sapelli', '0005_sapellifield_truefalse'),
]
operations = [
migrations.AddField(
model_name='sapelliprojec... | tegerField(default=-1),
| preserve_default=False,
),
]
|
vero4karu/burger_shop | app/urls.py | Python | mit | 549 | 0 | #! /usr/bin/env python
# -*- coding: utf-8 - | *-
# Author: Vera Mazhuga http://vero4ka.info
from django.conf.urls import include, url
from django.views.generic import TemplateView
from django. | contrib import admin
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'),
url(r'^accounts/', include('userprofile.urls', namespace='userprofile')),
url(r'^shop/', include('shop.urls', namespace='shop')),
url(r'^grappelli/', include('grappelli.urls')),
url(r'... |
armorunicorn/price_forecast | price_forecast.py | Python | gpl-3.0 | 739 | 0.002706 | # -*- coding: utf-8 -*-
from flask import Flask
from flask.ext.pymongo import PyMongo
import config
app = Flask(__name__)
app.config.from_object(confi | g)
mongo = PyMongo(app)
app.config["mongo"] = mongo
def register_blueprint(_app):
# Prevents circular imports
# from price_interface.uploads import upload
# from price_interface.updates import update
# from price_interface.downloads import download
from web.search.index impor | t index_blueprint
# from views import admin
# _app.register_blueprint(upload)
# _app.register_blueprint(update)
# _app.register_blueprint(download)
_app.register_blueprint(index_blueprint)
register_blueprint(app)
if __name__ == '__main__':
app.run(debug=True)
|
poojavade/Genomics_Docker | Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/pybedtools-0.7.6-py2.7-linux-x86_64.egg/EGG-INFO/scripts/intron_exon_reads.py | Python | apache-2.0 | 3,362 | 0.001785 | #!/usr/bin/python
"""
Example from pybedtools documentation (:ref:`third example`) to count \
reads in introns and exons using multiple CPUs.
"""
from __future__ import print_function
import pybedtools
import argparse
import os
import sys
import multiprocessing
def featuretype_filter(feature, featuretype):
"""
... | ).saveas()
intron_only = introns.subtract(exons).merge().remove_invalid().saveas()
intron_and_exon = exons\
.intersect(introns).merge().remove_invalid().saveas()
# Do intersections with BAM file in parallel
features = (exon_only, intron_only, intron_and_exon)
results = pool.map(count_re... | label, reads in zip(labels, results):
print('%s %s' % (label, reads))
pybedtools.cleanup(verbose=False)
if __name__ == "__main__":
main()
|
TonyHinjos/Machine-Learning-Algorithms-Toolkit | k-means-clustering/k_means_cluster.py | Python | mit | 4,794 | 0.051731 | #!/usr/bin/python3
# Filename: k_means_cluster.py
"""
A Machine learning algorithm for K mean clustering.
Date: 24th March, 2015 pm
"""
__author__ = "Anthony Wanjohi"
__version__ = "1.0.0"
import random, fractions
def euclidean_distance(point, centroid):
'''Returns the euclidean distance between two points'''
asser... | e(y, centroid_two)
euclid_distance.append((distance_one, distance_two))
#group matrix condtions
if distance_one > distance_two:
grp_matrix.append((0, 1))
elif distance_one < distance_two:
grp_matrix.append((1, 0))
return grp_matrix
def get_avg_centroid(x_y_index, coords):
'''Returns new centroid coo... | '''
x_coords, y_coords = [], []
for index in x_y_index:
#new_points.append(coords[index])
x, y = coords[index]
x_coords.append(x)
y_coords.append(y)
#get average of both x and y coords
x_coords = round(sum(x_coords) / (len(x_coords) * 1.0), 4)
y_coords = round(sum(y_coords) / (len(y_coords) * 1.0), 4)
c... |
lvercelli/pytsbp | tsbp/consts/operations.py | Python | mit | 59 | 0.016949 | SETUP = 1
SIGN_UP = 2
TOKE | N_GENERATION = 3
SOCI | AL_LOGIN = 4 |
ClockworkOrigins/m2etis | configurator/missile/classes/PersistenceStrategy.py | Python | apache-2.0 | 516 | 0.005814 | import copy
import logging
from strategy import Strategy
logging.basicConfig(level=logging.INFO)
LOG = logging.getLogger(__name__)
class PersistenceStrategy(Strategy):
def __init__(self, strategy):
self.__dict__ = copy.deepcopy(strategy.__dict__)
def compatible(self, event):
if e | vent is None:
return True
if event.dimensions["persistency"]["enabled"] == self.classification["description"]["enabled"]:
return | True
else:
return False |
cslansing/vehicle-journal | manage.py | Python | mit | 310 | 0 | #!/usr/bin/env python
import os
import sys
sys.path.append('/var/www/vehicle-journal/vjournal')
if __name__ == "__main__":
os.environ.s | etdefault("DJANGO_ | SETTINGS_MODULE", "vjournal.settings.prod")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
xray/xray | xarray/tests/test_concat.py | Python | apache-2.0 | 21,946 | 0.001094 | from copy import deepcopy
import numpy as np
import pandas as pd
import pytest
from xarray import DataArray, Dataset, Variable, concat
from xarray.core import dtypes, merge
from . import (
InaccessibleArray,
assert_array_equal,
assert_equal,
assert_identical,
raises_regex,
requires_dask,
)
fr... | actual = concat([data0, data1], "dim1")
expected = data.copy().assign(foo=data1.foo)
assert_identical(expected, actual)
def test_concat_2(self, data):
dim = "dim2"
datasets = [g for _, g in data.groupby(dim, squeeze=True)]
concat_over = [k for k, v in data.coords.ite... | rk.parametrize("coords", ["different", "minimal", "all"])
@pytest.mark.parametrize("dim", ["dim1", "dim2"])
def test_concat_coords_kwarg(self, data, dim, coords):
data = data.copy(deep=True)
# make sure the coords argument behaves as expected
data.coords["extra"] = ("dim4", np.arange(3))... |
andreadelprete/sot-torque-control | python/hrp2_motors_parameters_symmetric_id.py | Python | lgpl-3.0 | 599 | 0.006678 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 9 13:55:16 2015
@author: adelpret
"""
from numpy import zeros as zeros
NJ = 30;
k_tau = zeros(NJ);
k_v = zeros(NJ);
# PARAMETERS OF R_hip_y JOINT 0
k_v[0] = 0.017585
k_tau[0] = 0.000355
# PARAMETERS OF R_hip_r JOINT 1
k_v[1] = 0.006573
k_tau[1] = 0.000036
# PARAMETER... | ee JOINT 3
k_v[3] = 0.006774
k_tau[3] = 0.000060
# PARAMETERS OF R_ankle pitch JOINT 4
k_v[4] = 0.008107
k_tau[4] = 0.000226
# PARAMETERS OF R_ankle roll JOINT 5
k_v[5] = 0.007444
k_ta | u[5] = 0.000273
|
RPGOne/Skynet | pytorch-master/torch/legacy/nn/TemporalConvolution.py | Python | bsd-3-clause | 1,969 | 0 | import math
import torch
from .Module import Mo | dule
class TemporalConvolution(Module):
def __init__(self, inputFrameSize, outputFrameSize, kW, dW=1):
super(TemporalConvolution, self).__init__()
self.inputFrameSize = inputFrameSize
self.outputFrameSize = outputFrameSize
self.kW = kW
self.dW = dW
self.weight = ... | torch.Tensor(outputFrameSize, inputFrameSize * kW)
self.gradBias = torch.Tensor(outputFrameSize)
self.reset()
def reset(self, stdv=None):
if stdv is not None:
stdv = stdv * math.sqrt(3)
else:
stdv = 1. / math.sqrt(self.kW * self.inputFrameSize)
self... |
indautgrp/frappe | frappe/config/tools.py | Python | mit | 60 | 0.016667 | from __future__ import unicode_ | literals
f | rom frappe import _ |
LiveBeef/TDTMBot | bot.py | Python | gpl-3.0 | 5,093 | 0.016493 | import praw
from collections import deque
import re
import yaml
import os
#Set globals
r=praw.Reddit("PlusBot by /u/captainmeta4")
sub = r.get_subreddit('captainmeta4bots')
class Bot():
def __init__(self):
#login
r.login('PlusBot',os.environ.get('password'))
#store up to 100 link/autho... | self.author_points[comment.subreddit.display_name][parent_comment.author.name].append(comment.link_id)
#get new score and flair text
score = len(self.author_points[comment.subreddit.display_name][parent_comment.author.name])
#variables for new flair
flair_ | class = self.score_class(score)
flair_text = "+"+str(score)
#if user has no flair, or score flair, set new score flair
if parent_comment.author_flair_css_class is None:
#save flair to reddit
r.set_flair(comment.subreddit,parent_comment.author,flair_t... |
gary-pickens/HouseMonitor | housemonitor/qt/hm.py | Python | mit | 5,321 | 0.030445 | #!/usr/bin/python2.7
from PySide.QtCore import *
from PySide.QtGui import *
from PySide import *
import sys
import monitor
from monitorthread import MonitorThread
from monitordata import MonitorData
class HMStandardItemModel( QStandardItemModel ):
monito | r_data = None
values = None
previous_values = None
get_data = Signal()
def __init__( self, rows, columns, monitor_data ):
super( HMStandardItemModel, self ).__init__( rows, columns )
self.monitor_data = monitor_data
@QtCore.Slot()
def read_data( self ):
self.previous_v | alues = self.values
self.values = self.monitor_data.retreive_data()
for rows in range( 0, len( self.values ) ):
for columns in range( 0, 4 ):
if ( self.previous_values == None ):
item = QStandardItem( self.values[rows][columns] )
self.s... |
wslihgt/pyfasst | pyfasst/SeparateLeadStereo/SeparateLeadStereoTF.py | Python | gpl-2.0 | 84,353 | 0.008547 | """SeparateLeadStereo, with Time-Frequency choice
Provides a class (``SeparateLeadProcess``) within which several
processings can be run on an audio file, in order to extract the
lead instrument/main voice from a (stereophonic) audio mixture.
copyright (C) 2011 - 2013 Jean-Louis Durrieu
"""
# Importing necessary pac... | ixed*
'dictionary' of smooth spectral shapes for the filte | r part
'WM' : (F, R) ndarray, *estimated*
array of spectral shapes that are directly *estimated* on the
signal
verbose : boolean
if True, the program writes some information about what is happening
wavCanvas : instance from MplCanvas o... |
VitalPet/c2c-rd-addons | chricar_room/room.py | Python | agpl-3.0 | 3,108 | 0.018018 | # -*- coding: utf-8 -*-
#!/usr/bin/python
# -*- coding: utf-8 -*-
##############################################
#
# ChriCar Beteiligungs- und Beratungs- GmbH
# Copyright (C) ChriCar Beteiligungs- und Beratungs- GmbH
# all rights reserved
# created 2009-07-11 12:22:10+02
#
# WARNING: This program as such is intended t... |
chricar_room()
class chricar_top(osv.osv):
_inherit = "chricar.top"
_columns = {
'room_ids': fields.one2many('chricar.room','top_i | d','Rooms'),
}
chricar_top()
|
samsath/skeleton | src/website/clubsessions/admin.py | Python | gpl-3.0 | 1,156 | 0.016436 | from .models import *
from django.contrib import admin
from django.db import models
from website.base.form import TinyMCEAdminMixin
from django.utils.translation import ugettext_lazy as _
from mediastore.admin import ModelAdmin
class SessionAdmin(TinyMCEAdminMixin, ModelAdmin):
list_display = ('title','day_of_wee... |
'fields':(
'description',
)
}),
(_('Cost'),{
'fields':(
'cost',
)
}),
(_('Location'),{
'fields':(
'location',
)
}),
(_('Settings'), {
'fiel... | d',
)
})
)
admin.site.register(Session,SessionAdmin) |
KristianOellegaard/django-filer | filer/server/backends/default.py | Python | mit | 1,458 | 0.004115 | #-*- coding: utf-8 -*-
import os
import stat
from django.http import Http404, HttpResponse, HttpResponseNotModified
from django.utils.http import http_date
from django.views.static import was_modified_since
from filer.server.backends.base import ServerBase
class DefaultServer(ServerBase):
'''
Serve static file... | tpResponseNotModified(mimetype=mimetype)
response = HttpResponse(open(fullpath, 'rb').read(), mimetype=mimetype)
respon | se["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
self.default_headers(request=request, response=response, file=file, **kwargs)
return response
|
sjdv1982/seamless | seamless/metalevel/python_bridges/__init__.py | Python | mit | 1,180 | 0.001695 | # To install another language:
# - update default_bridges below
# - update languages.cson in seamless/compiler
from ...highlevel.Environment import ContextEnvironment, Environment
from . import r
_default_bridges = {
"r": {
"code": r.bridge_r,
"params": r.default_bridge_parameters,
"envir... | if "environment" in b:
e = b["environment"]
bridge_env = Environment()
if "conda" in e:
bridge_env.set_conda(e["conda"], format="yaml")
if "which" in e:
bridge_env.set_which(e["which"], format="plain")
| env.set_py_bridge_environment(lang, bridge_env)
|
rapidpro/ureport | ureport/assets/context_processors.py | Python | agpl-3.0 | 689 | 0.002903 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
def set_assets_processor(request):
"""
Simple c | ontext processor that overwrite the assets of 'org' on the context if org
is present in the request.
"""
if getattr(request, "org", None):
org = request.org
pattern_bg = org.images.filter(is_active=True, image_type="P")
pattern_bg = pattern_bg.order_by("-pk").first()
banner_b... | ue, image_type="B")
banner_bg = banner_bg.order_by("-pk").first()
return dict(pattern_bg=pattern_bg, banner_bg=banner_bg)
else:
return dict()
|
blake-sheridan/py | test/test_functools.py | Python | apache-2.0 | 309 | 0.006472 | import unittest
from b | .functools import identity, noop
class IdentityTests(unittest.TestCase):
def test_identity(self):
a = object()
self.assertIs(identity(a), a)
class NoopTests(unittest.TestCase):
def test | _noop(self):
noop()
noop(1, 2, 3)
noop(abc='xyz')
|
google-research/google-research | adaptive_learning_rate_tuner/resnet_model_fast.py | Python | apache-2.0 | 19,574 | 0.005007 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | ad_beg
if data_format == 'channels_first':
padded_inputs = tf.pad(
tensor=inputs,
paddings=[[0, 0], [0, 0], [pad_beg, pad_end], [pad_beg, pad_end]])
else:
padded_inputs = tf.pad(
tensor=inputs,
paddings=[[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]])
return padde... | strides, data_format,
name):
"""Strided 2-D convolution with explicit padding."""
# The padding is consistent and is based only on `kernel_size`, not on the
# dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone).
if strides > 1:
inputs = fixed_padding(inputs, kernel... |
Clinical-Genomics/scout | scout/utils/scout_requests.py | Python | bsd-3-clause | 13,130 | 0.001752 | """Code for performing requests"""
import json
import logging
import urllib.request
import zlib
from urllib.error import HTTPError
import requests
from defusedxml import ElementTree
from scout.constants import CHROMOSOMES, HPO_URL, HPOTERMS_URL
from scout.utils.ensembl_rest_clients import EnsemblBiomartClient
LOG = ... | e):
"""
Fetch the necessary HPO files from http://compbio.charite.de
Args:
genes_to_phenotype(bool): if file genes_to_phenotype.txt is required
phenotype_to_genes(bool): if file phenotype_to_genes.txt is required
hpo_terms(bool):if file hp.obo is required
Returns:
hpo_f... | hpo_files["genes_to_phenotype"] = fetch_genes_to_hpo_to_disease()
if phenotype_to_genes is True:
hpo_files["phenotype_to_genes"] = fetch_hpo_to_genes_to_disease()
if hpo_terms is True:
hpo_files["hpo_terms"] = fetch_hpo_terms()
return hpo_files
def fetch_mim_files(api_key, mim2genes=Fa... |
v-iam/azure-sdk-for-python | azure-mgmt-sql/azure/mgmt/sql/models/elastic_pool_database_activity_paged.py | Python | mit | 950 | 0.002105 | # 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 ... | nerated.
# ------------------------------------------------------ | --------------------
from msrest.paging import Paged
class ElasticPoolDatabaseActivityPaged(Paged):
"""
A paging container for iterating over a list of ElasticPoolDatabaseActivity object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': '... |
ECP-CANDLE/Supervisor | workflows/cp-leaveout/scripts/list-nodes.py | Python | mit | 450 | 0.004444 | #!/usr/bin/env python
# LIST NODE | S PY
# Extract just the nodes from | the JSON file for human inspection
import argparse, json
parser = argparse.ArgumentParser()
parser.add_argument('plan', type=str, help='Plan data file')
args = parser.parse_args()
try:
with open(args.plan) as fp:
J = json.load(fp)
except Exception as e:
print("could not read JSON in file: %s\n" % arg... |
shyampurk/tto-bluemix | ttoServer/ttoServer.py | Python | mit | 37,445 | 0.040486 | import pymongo
from pymongo import MongoClient
import datetime
import pytz
import math
import time
import datetime
from pubnub import Pubnub
import threading
import logging
pub_key ='pub-c-f2fc0469-ad0f-4756-be0c-e003d1392d43'
sub_key ='sub-c-4d48a9d8-1c1b-11e6-9327-02ee2ddab7fe'
LOG_FILENAME = 'TTO_serverlogs.... | age =result,error=error)
if (pbreturn[0] == 1):
return None
elif(pbreturn[0] == 0):
logging.error("The publish return error %s for the client %s\n"%(pbreturn[1],channel))
pbtry+=1
else:
pass
except Exception as error_pdhandler:
logging.error("The error_pdhandler Exceptio... | er,type(error_pdhandler)))
pbtry+=1
else:
pass
except Exception as pubhandlerError:
logging.error("The publish function Exception is %s,%s,%s\n"%(pubhandlerError,type(pubhandlerError),str(result)))
'''****************************************************************************************
Function... |
cdegroc/scikit-learn | sklearn/manifold/tests/test_isomap.py | Python | bsd-3-clause | 4,072 | 0 | from itertools import product
import numpy as np
from numpy.testing import assert_almost_equal, assert_array_almost_equal
from nose.tools import assert_true
from sklearn import datasets
from sklearn import manifold
from sklearn import neighbors
from sklearn import pipeline
from sklearn import preprocessing
eigen_sol... | 1
# grid of equidistant points in 2D, out_dim = n_dim
X = np.array(list(product(range(N_per_side), repeat=2)))
# add noise in a third dimension
rng = np.random.RandomState(0)
noise = 0.1 * rng.randn(Npts, 1)
X = np.concatenate((X, noise), 1)
# compute input kernel
G = neighbors.kneigh... | h(X, n_neighbors,
mode='distance').toarray()
centerer = preprocessing.KernelCenterer()
K = centerer.fit_transform(-0.5 * G ** 2)
for eigen_solver in eigen_solvers:
for path_method in path_methods:
clf = manifold.Isomap(n_neighbors=n_neighbors, out_dim... |
ibelikov/jimmy | jimmy/modules/jenkins_configuration/tests/test_jenkins_configuration.py | Python | apache-2.0 | 11,065 | 0.001356 | # -*- coding: utf-8 -*-
# Copyright 2016 Mirantis, 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... | s-cli.jar >>',
'-s', 'http://localhost:8080', 'groovy',
modules_dir + '/' + 'jenkins_configuration/resources/jenkins.groovy',
'setLocationUrl',
"'http://example.com/jenkins/'"],
shell=False),
... | ns-cli.jar >>',
'-s', 'http://localhost:8080', 'groovy',
modules_dir + '/' + 'jenkins_configuration/resources/jenkins.groovy',
'setMarkupFormatter',
'raw-html'],
shell=False),
call(['java',... |
infinitewarp/trekipsum | trekipsum/dialog/__init__.py | Python | mit | 71 | 0 | from .sq | lite import DialogChooser | as SqliteRandomChooser # noqa: F401
|
googleads/googleads-dfa-reporting-samples | python/v3_5/get_user_role_permissions.py | Python | apache-2.0 | 2,245 | 0.005345 | #!/usr/bin/python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | ns']:
print ('Found user role permission with ID %s and name "%s".'
% (permission['id'], permission['name']))
except client.AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name_ | _ == '__main__':
main(sys.argv)
|
HusqvarnaResearch/hrp | am_bno055_gyro/setup.py | Python | mit | 196 | 0 | from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_se | tup(
packages=['am_bn | o055_gyro'],
package_dir={'': 'src'}
)
setup(**d)
|
CERT-BDF/Cortex-Analyzers | analyzers/MaxMind/geo.py | Python | agpl-3.0 | 3,380 | 0.002071 | #!/usr/bin/env python
# encoding: utf-8
import os
import geoip2.database
from geoip2.errors import AddressNotFoundError
from cortexutils.analyzer import Analyzer
class MaxMindAnalyzer(Analyzer):
def dump_city(self, city):
return {
'confidence': city.confidence,
'geoname_id': city.... | oname_id,
'name': city.name,
'names': city.names
}
def dump_continent(self, continent):
return {
'code': continent.code,
'geoname_id': continent.geoname_id,
'name': continent.name,
'names': con | tinent.names,
}
def dump_country(self, country):
return {
'confidence': country.confidence,
'geoname_id': country.geoname_id,
'iso_code': country.iso_code,
'name': country.name,
'names': country.names
}
def dump_location(self,... |
jtopjian/st2contrib | packs/rackspace/actions/find_dns_record_id.py | Python | apache-2.0 | 335 | 0.00597 | from lib.action import PyraxBaseAction
__all__ = [
'FindDNSRecordIdAction'
]
class FindDNSRecordIdAction(PyraxBaseAction):
def run(self, name, zone_id):
cdns = self.pyrax.cloud_dns
dns_id = [record for record in cdns.list_records(zone_id)
if record.name == nam | e][0] | .id
return dns_id
|
QingChenmsft/azure-cli | src/command_modules/azure-cli-interactive/azure/cli/command_modules/interactive/tests/test_feedback.py | Python | mit | 2,996 | 0.00267 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | empfile.mkstemp()
if os.path.exists(fh.FREQUENCY_PATH):
os.remove(fh.FREQUENCY_PATH)
# without a file already written
| json_freq = fh.update_frequency()
now = fh.day_format(datetime.datetime.now())
self.assertEqual(json_freq, {now: 1})
if os.path.exists(fh.FREQUENCY_PATH):
os.remove(fh.FREQUENCY_PATH)
if __name__ == '__main__':
unittest.main()
|
hinnefe2/brewlog | brewlog/models/params.py | Python | gpl-3.0 | 413 | 0 | from sqlalchemy import ForeignKey
from brewlog import db
class ParamRecord(db.Model):
__tablename__ = 'params'
id = db.Column(db.Integer, primary_key=True)
brew_id = db.Col | umn(db.Integer, ForeignKey('brews.brew_id')) |
param_type = db.Column(db.String(20), nullable=False)
value = db.Column(db.String(100), nullable=False)
def as_dict(self):
return {self.param_type: self.value}
|
raphapr/openstack-neat | vm-placement.py | Python | apache-2.0 | 3,249 | 0.000308 | #!/usr/bin/python2
# Copyright 2012 Anton Beloglazov
#
# 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 ... | RE | QUIRED_FIELDS)
db = manager.init_db(config['sql_connection'])
nova = client.Client(config['os_admin_user'],
config['os_admin_password'],
config['os_admin_tenant_name'],
config['os_auth_url'],
service_type="compute")
hosts = common.parse... |
livni/old-OK | src/knesset/laws/migrations/0005_add_votes_count_to_vote_data.py | Python | bsd-3-clause | 6,357 | 0.009281 |
from south.db import db
from django.db import models
from knesset.laws.models import *
class Migration:
no_dry_run = True
def forwards(self, orm):
for v in orm.Vote.objects.all():
v.votes_count = orm.VoteAction.objects.filter(vote=v).count()
v.save()
def bac... | {'default': 'False', 'blank': 'True'}),
'against_party': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'member': ('django.db.models.fields.related.ForeignKey', [], {'to': ... | eignKey', [], {'to': "orm['laws.Vote']"})
},
'mks.member': {
'current_party': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'members'", 'null': 'True', 'to': "orm['mks.Party']"}),
'date_of_birth': ('django.db.models.fields.DateField', [], {... |
bazelbuild/rules_pkg | tests/rpm/tree_artifacts/rpm_contents_vs_manifest_test.py | Python | apache-2.0 | 2,348 | 0.000426 | #!/usr/bin/env python3
# Copyright 2021 The Bazel Authors. All rights reserved.
#
# Licensed u | nder the Apache License, Version 2.0 (the "License");
# you may not use this file excep | t 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... |
ronhuang/adieu | backend/midautumn/handlers.py | Python | mit | 2,015 | 0.002978 | #!/usr/bin/env python
# Midautumn
# Copyright 2011 Ron Huang
# See LICENSE for details.
from google.appengine.dist import use_library
use_library('django', '1.2')
import logging
import midautumn.facebook as facebook
from midautumn.models import FacebookUser
from google.appengine.ext import webapp
from midautumn.conf... | rofile_url=profile["link"],
access_token=cookie["access_token"])
user.put()
elif user.access_token != cookie["access_tok | en"]:
user.access_token = cookie["access_token"]
user.put()
self._current_user = user
return self._current_user
|
molecular/electrum | plugins/digitalbitbox/qt.py | Python | mit | 542 | 0 | from PyQt5.QtWidgets import (QInputDialog, QLineEdit)
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
from digitalbitbox import DigitalBitboxPlugin
c | lass Plugin(DigitalBitboxPlugin, QtPluginBase):
icon_unpaired = ":icons/digitalbitbox_unpaired.png"
icon_paired = ":icons/digitalbitbox.png"
def create_handler(self, window):
return DigitalBitbox_Handler(window)
class DigitalBitbox_Handler(QtHan | dlerBase):
def __init__(self, win):
super(DigitalBitbox_Handler, self).__init__(win, 'Digital Bitbox')
|
KIWIKIGMBH/logstash2csv | setup.py | Python | mpl-2.0 | 122 | 0 | from | setuptools import setup
setup(
name="logstash2csv",
version="0.1",
install_req | uires=["elasticsearch"])
|
WALR/taiga-back | taiga/events/backends/base.py | Python | agpl-3.0 | 1,894 | 0.007392 | # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This progra... | rror importing {0}: "{1}"'.format(mod_name, e))
try:
klass = getattr(mod, klass_name)
except AttributeError:
raise ImproperlyConfigured('Module "{0}" does not define a "{1}" class'.format(mod_name, klass_name))
return klass
def get_events_backend(path:str=None, options:dict=None):
if... | raise ImproperlyConfigured("Events push system not configured")
if options is None:
options = getattr(settings, "EVENTS_PUSH_BACKEND_OPTIONS", {})
cls = load_class(path)
return cls(**options)
|
ejspina/Gene_expression_tools | Python/blast_parse.py | Python | gpl-2.0 | 2,755 | 0.021053 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Eli
#
# Created: 22/01/2015
# Copyright: (c) Eli 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
def m... | pass
#else:
| #idlist2.append(name)
#idlist1.remove(name)
#print line
count+=1
#Code for checking remaining values in ID list
#for item in idlist1:
# print "bakow!"
# sys.stdout.write(item + '\t' + idlist2[item] + '\t' + idlist1[item] + '\n')
#else:
# print line.split(... |
dstl/ideaworks | backend/ideaworks/ideasapp/documents.py | Python | agpl-3.0 | 6,632 | 0.015682 |
# (c) Crown Copyright 2014 Defence Science and Technology Laboratory UK
# Author: Rich Brantingham
import datetime
from mongoengine import Document, BooleanField, IntField, EmbeddedDocument, DateTimeField, ListField, StringField, EmbeddedDocumentField, FloatField
class InheritableDocument(Document):
m... | ingField(max_length=200, required=False, help_text='Full classification name protecting this object')
classification_short = StringField(max_length=200, required=False, help_text='Abbreviated classification protecting this object')
classification_rank | = IntField(default=0, required=False, help_text='A numeric representation of the classification to allow sorting. </br>0 - unclassified</br>5 - TS')
# Descriptor
descriptor = StringField(max_length=200, required=False, help_text='escriptors protecting this object.')
# Codeword info
... |
openprocurement/openprocurement.tender.belowthreshold | openprocurement/tender/belowthreshold/includeme.py | Python | apache-2.0 | 716 | 0.00419 | # -*- coding: utf-8 -*-
from pyramid.interfaces import IRequest
from openprocurement.api.interfaces import IContentConfigurator
from openprocurement.tender.belowthreshold. | models import Tender, IBelowThresholdTender
from openprocurement.tender.belowthreshold.adapters import TenderBelowThersholdConfigurator
def includeme(config):
config.add_tender_procurementMethodType(Tender)
config.scan("openprocurement.tender.belowthreshold.views")
config.scan("openprocurement.tender.bel... | lowThersholdConfigurator,
(IBelowThresholdTender, IRequest),
IContentConfigurator)
|
markemus/economy | gui/convo_screen.py | Python | mit | 4,826 | 0.002487 | import tkinter as tk
TITLE_FONT = ("Black chancery", "18", "bold")
TEXT_FONT = ("Black chancery", "15")
BUTTON_FONT = ("Black chancery", "13")
class convo_controller(tk.Frame):
def __init__(self, parent, root, *args, **kwargs):
tk.Frame.__init__(self, master=parent, *args, **kwargs)
self.root = r... | font=BUTTON_FONT)
topic = tk.Button(self, text="Change Topic", font=BUTTON_FONT)
end = tk.Button(self, text="End Conversation", font=BUTTON_FONT)
header.p | ack()
family.pack()
job.pack()
skills.pack()
different.pack()
topic.pack()
end.pack()
def raise_frame(self):
self.tkraise()
gui = tk.Tk()
convo = friend(gui, None, None)
convo.pack()
gui.mainloop() |
enthought/etsproxy | enthought/chaco/tools/legend_highlighter.py | Python | bsd-3-clause | 99 | 0 | # proxy module
| from | __future__ import absolute_import
from chaco.tools.legend_highlighter import *
|
scls19fr/numpy-buffer | samples/sample_pyqtgraph_no_datetime.py | Python | bsd-3-clause | 1,706 | 0.000586 | import sys
import numpy as np
from PyQt4.QtCore import QTimer
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
from timestamp import now_timestamp
from numpy_buffer import RingBuffer
class MyApplication(QtGui.QApplication):
def __init__(self, *args, **kwargs):
super(MyApplication, self).__i... | _(*args, **kwargs)
# self.t = QTime()
# self.t.start()
maxlen = 50
self.data_x = RingBuffer(maxlen)
self.data_y = RingBuffer(maxlen)
self.win = pg.GraphicsWindow(title="Basic plotting examples")
self.win.resize(1000, 600)
self.win.setWindowTitle('Plot wi... | plot()
pen = pg.mkPen('r', style=QtCore.Qt.SolidLine)
self.curve = self.plot.plot(pen=pen, symbol='+')
self.timer = QTimer()
self.timer.timeout.connect(self.update)
self.timer.start(100)
self.y = 100
def update(self):
# self.data.append({'x': self.t.elapse... |
lex/yuuh-pizza-kebab | app.py | Python | bsd-2-clause | 87 | 0 | from yuuhpizzakebab import ap | p
if __name__ == '__main__':
app.ru | n(host='0.0.0.0')
|
z-plot/z-plot | examples/basics-svg/verticalbars.py | Python | bsd-3-clause | 2,343 | 0.005548 | #! /usr/bin/env python
from zplot import *
# populate zplot table f | rom data file
t = table('verticalbars.data')
# create the postscript file we'll use as our canvas
canvas = svg('verticalbars.svg')
# on the x-axis, we want categories, not numbers. Thus, we
# determine the number of categories by checking the max
# "rownumber" (a field automatically added by zplot). We want a
# hal... | ar locations
# so we don't overflow the drawable.
d = drawable(canvas, xrange=[-0.5,t.getmax('rownumber')+0.5], yrange=[0,80])
# xmanual is a list of the form [(label1,x1), (label2,x2), ...].
# We want to use the "op" field from the data file as our labels
# and use "rownumber" as our x coordinate.
axis(d, xtitle='Ope... |
claudep/translate | translate/storage/test_directory.py | Python | gpl-2.0 | 2,805 | 0 | #!/usr/bin/env python
"""Tests for the directory module"""
import os
from translate.storage import directory
class TestDirectory(object):
"""a test class to run tests on a test Pootle Server"""
def setup_method(self, method):
"""sets up a test directory"""
print("setup_method called on", s... | s.sort()
assert filenames == files
def test_structure(self):
"""Tests a small directory structure."""
files = ["a.po", "b.po", "c.po"]
self.touchfiles(self.testdir, files)
self.mkdir("bla")
self.touchfiles(os.path.join | (self.testdir, "bla"), files)
d = directory.Directory(self.testdir)
filenames = [name for dirname, name in d.getfiles()]
filenames.sort()
files = files * 2
files.sort()
assert filenames == files
def test_getunits(self):
"""Tests basic functionality."""
... |
mytliulei/DCNRobotInstallPackages | windows/win32/pygal-1.7.0/pygal/graph/horizontal.py | Python | apache-2.0 | 1,780 | 0 | # -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2014 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version... | self.view._force_vertical = True
super(HorizontalGraph, self)._axes()
self.view._force_vertical = False
def _set_view(self):
"""Assign a view to current graph"""
if self.logarithmic:
view_class = Horizon | talLogView
else:
view_class = HorizontalView
self.view = view_class(
self.width - self.margin.x,
self.height - self.margin.y,
self._box)
|
aaloy/puput | puput/management/commands/puput_initial_data.py | Python | mit | 1,136 | 0 | # -*- coding: utf-8 -*-
from django import VERSION as DJANGO_VERSION
from django.contrib.contenttypes.models import ContentType
from django.core.management import BaseCommand
from wagtail.wagtailcore.models import Page, Site
class Command(BaseCommand):
help = "Load Puput initial dummy data"
def handle(self... |
# Get blogpage content type
blogpage_content_type, created = ContentType.objects.get_or_create(
model='blogpage',
app_label='puput',
defaults={'name': 'page'} if DJANGO_VERSION < (1, 8) else {}
)
# Get root page
rootpage = Page.objects.first(... | example blog page
blogpage = Page(
title="Blog",
content_type=blogpage_content_type,
slug='blog',
)
# Add blog page as a child for homepage
rootpage.add_child(instance=blogpage)
revision = blogpage.save_revision()
revision.publish()
|
vpetersson/docker-py | tests/integration/regression_test.py | Python | apache-2.0 | 2,323 | 0 | import io
import random
import docker
import six
from .base import BaseAPIIntegrationTest, BUSYBOX
class TestRegressions(BaseAPIIntegrationTest):
def test_443_handle_nonchunked_response_in_stream(self):
dfile = io.BytesIO()
with self.assertRaises(docker.errors.APIError) as exc:
for l... | def test_715_handle_user_param_as_int_value(self):
ctnr = self.client.create_container(BUSYBOX, ['id', '-u'], user=1000)
self.client.start(ctnr)
self.client.wait(ctnr)
logs = self.client.logs(ctnr)
if six.PY3:
logs = logs.decode('utf-8')
assert logs == '100 | 0\n'
def test_792_explicit_port_protocol(self):
tcp_port, udp_port = random.sample(range(9999, 32000), 2)
ctnr = self.client.create_container(
BUSYBOX, ['sleep', '9999'], ports=[2000, (2000, 'udp')],
host_config=self.client.create_host_config(
port_bindings=... |
anotherjesse/nova | nova/virt/hyperv.py | Python | apache-2.0 | 19,653 | 0.002748 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2010 Cloud.com, 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.... | is associated with a
Msvm_VirtualSystemGlobalSettingData (vs_gs_data) instance and one or more
Msvm_VirtualSystemSet | tingData (vmsetting) instances. For each vmsetting
there is a series of Msvm_ResourceAllocationSettingData (rasd) objects.
The rasd objects describe the settings for each device in a VM.
Together, the vs_gs_data, vmsettings and rasds describe the configuration
of the virtual machine.
Creating new r... |
barentsen/exoplanet-charts | publication-stats/kepler-author-seniority.py | Python | mit | 3,210 | 0.000935 | """
Start of Kepler observations: 2009 May 2
First Kepler release: 2010 Jun 15
Start of K2 observation (C0): 2014 Mar 8
First release of K2 data: 2014 Sep 08
=> Limit to 2 years after start of data taking,
i.e. 2016 Mar for K2 and 2011 May for Kepler.
"""
import matplotlib as mpl
import matplotlib.pyplot as pl
from m... | seniority, BINS),
color=palette[0], e | dgecolor='black',
alpha=0.8, width=0.6, zorder=20,
label='K2 (first two years)')
ax_k.bar(left=np.array(range(len(BINS)-1)) + 0.6,
height=binning(k_seniority, BINS),
color="#2980b9", edgecolor='black',
alpha=0.8, width=0.8, zorder=10,
label='Kepler (first two years)... |
sgarrity/bedrock | bedrock/mozorg/templatetags/__init__.py | Python | mpl-2.0 | 76 | 0 | # flake8: noqa
from b | edrock.mozorg.templatetags import misc, soc | ial_widgets
|
superboot/radioIsland | boneYard/orderTest.py | Python | gpl-2.0 | 88 | 0 | from classes | import *
hammer = Item()
nail = Item()
print(hammer.name) |
print(nail.name)
|
eduNEXT/edx-platform | lms/envs/devstack.py | Python | agpl-3.0 | 17,710 | 0.004687 | """
Specific overrides to the base prod settings to make development easier.
"""
# Silence noisy logs
import logging
from os.path import abspath, dirname, join
from corsheaders.defaults import default_headers as corsheaders_default_headers
# pylint: enable=unicode-format-string # lint-amnesty, pylint: disable=bad-... | age'
# Revert to the default set of finders as we don't want the production pipeline
STATICFILES_FINDERS = [
'openedx.core.dj | angoapps.theming.finders.ThemeFilesFinder',
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
# Disable JavaScript compression in development
PIPELINE['JS_COMPRESSOR'] = None
# Whether to run django-require in debug mode.
REQUIRE_DEBUG = DEBUG
... |
ufukdogan92/is-teklif-sistemi | is_teklif_sistemi/urls.py | Python | gpl-3.0 | 774 | 0 | """is_teklif_sistemi URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home'... | s'))
" | ""
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
|
t3dev/odoo | addons/payment_paypal/models/payment.py | Python | gpl-3.0 | 11,083 | 0.004331 | # coding: utf-8
import json
import logging
import dateutil.parser
import pytz
from werkzeug import urls
from odoo import api, fields, models, _
from odoo.addons.payment.models.payment_acquirer import ValidationError
from odoo.addons.payment_paypal.controllers.main import PaypalController
from odoo.tools.float_utils ... | er_account = fields.Char(
'Paypal Merchant ID', groups='base.group_user',
help='The Merchant ID is used to ensure communications coming from Paypal are valid and secured.')
paypal_use_ipn = fields.Boolean('Use IPN', default=True, help='Paypal Instant Payment Notification', groups='base.group_user')
... | de.', groups='base.group_user')
# Server 2 server
paypal_api_enabled = fields.Boolean('Use Rest API', default=False)
paypal_api_username = fields.Char('Rest API Username', groups='base.group_user')
paypal_api_password = fields.Char('Rest API Password', groups='base.group_user')
paypal_api_access_tok... |
googlecodelabs/analyze_gsimg | alt/analyze_gsimg-newauth.py | Python | apache-2.0 | 7,125 | 0.003649 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... | d results row to Google Sheet.
'''
from __future__ import print_function
import argparse
import base64
import io
import os
import webbrowser
from googleapiclient import discovery, http
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2 import c... | ' # YOUR IMG FILE PREFIX
SHEET = 'YOUR_SHEET_ID'
TOP = 5 # TOP # of VISION LABELS TO SAVE
DEBUG = False
# process credentials for OAuth2 tokens
creds = None
TOKENS = 'tokens.json' # OAuth2 token storage
SCOPES = (
'https://www.googleapis.com/auth/drive.readonly',
'https://www.googleapis.com/auth/devs... |
versae/ipython-cypher | src/cypher/run.py | Python | gpl-2.0 | 19,870 | 0.000101 | import codecs
from collections import defaultdict
import copy
import csv
from functools import reduce
import json
import prettytable
import operator
import os.path
try:
import matplotlib.pylab as plt
import matplotlib.patches as mpatches
import matplotlib.lines as Line2D
except:
plt = None
mpatches ... | writerow(row)
class CsvResultDescriptor(object):
"""Provides IPython Notebook-friendly output for the feedback after
a ``.csv`` called."""
def __init__(self, file_path):
self.file_path = file_path
def __repr__(self):
return 'CSV r | esults at %s' % os.path.join(os.path.abspath('.'),
self.file_path)
def _repr_html_(self):
return '<a href="%s">CSV results</a>' % os.path.join('.', 'files',
self.file_path)
class ResultSet(list,... |
onlinepcwizard/dms | dms/database/zone_sectag.py | Python | gpl-3.0 | 4,785 | 0.003135 | #!/usr/bin/env python3.2
#
# Copyright (c) Net24 Limited, Christchurch, New Zealand 2011-2012
# and Voyager Internet Ltd, New Zealand, 2012-2013
#
# This file is part of py-magcode-core.
#
# Py-magcode-core is free software: you can redistribute it and/or modify
# it under the terms of the GNU Gener... | l Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with py-magcode-core. If not, see <http://www.gnu.org/licenses/>.
#
"""
Zone security tag class, corresponding to zone_sectags table
"""
from sqlalchemy.orm.exc import NoResultFound
from magcode.co... |
@saregister
class ZoneSecTag(object):
"""
DNS Resource Record comment.
Comparison methods are also used for sorting displayed output.
"""
_table="zone_sectags"
def __init__(self, sectag_label=None):
"""
Initialise a security tag comment
"""
self.sectag = sectag... |
ini-bdds/ermrest | ermrest/model/table.py | Python | apache-2.0 | 10,745 | 0.00456 | #
# Copyright 2013-2015 University of Southern California
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | = self
if name not in self.schema.tables:
self.schema.tables[name] = self
@staticmethod
def introspect_annotation(model=None, schema_name=None, ta | ble_name=None, annotation_uri=None, annotation_value=None):
model.schemas[schema_name].tables[table_name].annotations[annotation_uri] = annotation_value
def __str__(self):
return ':%s:%s' % (
urllib.quote(unicode(self.schema.name).encode('utf8')),
urllib.quote(unicode(self.n... |
snowball-one/cid | cid/middleware.py | Python | bsd-3-clause | 1,889 | 0 | from django.conf import settings
from cid.locals import generate_new_cid
from cid.locals import get_cid
from cid.locals import set_cid
class CidMiddleware:
"""
Middleware class to extract the correlation id from incoming headers
and add them to outgoing headers
"""
def __init__(self, get_respons... | ting."""
def __init__(self):
print('middleware init')
| # `get_response` is only used in `CidMiddleware.__call__`,
# which is not called when using `MIDDLEWARE_CLASSES`.
super().__init__(get_response='dummy')
def process_request(self, request):
self._process_request(request)
# We must return None otherwise Django thinks it's the
... |
mantaraya36/xmms2-mantaraya36 | wafadmin/Tools/vala.py | Python | lgpl-2.1 | 10,297 | 0.027095 | #!/usr/bin/env python
# encoding: utf-8
# Ali Sabil, 2007
import os.path, shutil
import Task, Runner, Utils, Logs, Build, Node, Options
from TaskGen import extension, after, before
EXT_VALA = ['.vala', '.gs']
class valac_task(Task.Task):
vars = ("VALAC", "VALAC_VERSION", "VALAFLAGS")
before = ("cc", "cxx")
def ... | self.threading:
cmd.append('--thread')
if self.profile:
cmd.append('--profile=%s' % self.profile)
if self.target_glib:
cmd.append('--target-glib=%s' % self.target_glib)
features = self.generator.features
if 'cshlib' in features or 'cstaticlib' in features:
output_dir = self.outputs[0].bld_dir(e... | :
for x in self.outputs:
if x.name.endswith('.h'):
cmd.append('--header ' + x.bldpath(self.env))
cmd.append('--basedir ' + top_src)
cmd.append('-d ' + top_bld)
if env['VALAC_VERSION'] > (0, 7, 2) and hasattr(self, 'gir'):
cmd.append('--gir=%s.gir' % self.gir)
else:
output_dir = self.ou... |
caioherrera/django-pizza | pizzaria/pizza/models.py | Python | cc0-1.0 | 412 | 0.002427 | from django.db import models
# Create yo | ur models here.
class Pizza(models.Model):
name = models.CharField(max_length=128)
price = models.DecimalField(decimal_places=2, max_digits=5)
ingredients = models.TextField()
picture = models.ImageField(blank=True, null=True)
def __unicode__(self):
return u'Pizza: {}'.format(self.name)
... | unicode(self)
|
microelly2/cadquery-freecad-module | CadQuery/Examples/Ex021_Splitting_an_Object.py | Python | lgpl-3.0 | 435 | 0 | # This example is me | ant to be used from within the CadQuery module of FreeCAD.
import cadquery
from Helpers import show
# Create a simple block with a hole through it that we can split
c = cadquery.Workplane("XY").box(1, 1, 1).faces(">Z").workplane() \
.circle(0.25 | ).cutThruAll()
# Cut the block in half sideways
result = c.faces(">Y").workplane(-0.5).split(keepTop=True)
# Render the solid
show(result)
|
shobhitmishra/CodingProblems | epi_judge_python/drawing_skyline.py | Python | mit | 812 | 0 | import collections
import functools
from typing import List
from test_framework import generic_test
from test_framework.test_utils import enable_executor_hook
Rect = collections.namedtuple('Rect', ('le | ft', 'right', 'height'))
def compute_skyline(buildings: List[Rect]) -> List[Rect]:
# TODO - you fill in here.
return []
@enable_executor_hook
def compute_skyline_wrapper(executor, buildings):
buildings = [Rect(*x) for x in buildings]
result = executor.run(functools.partial(compute_skyline, building... | _name__ == '__main__':
exit(
generic_test.generic_test_main('drawing_skyline.py',
'drawing_skyline.tsv',
compute_skyline_wrapper))
|
ghisvail/vispy | vispy/visuals/line/__init__.py | Python | bsd-3-clause | 221 | 0 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.t | xt for more info.
from .line import LineVisual # noqa
from . | arrow import ArrowVisual # noqa
|
martinrusev/amonone | amon/apps/files/models.py | Python | mit | 1,183 | 0.007608 | import gridfs
import tempfile
from amon.apps.core.basemodel import BaseModel
class FilesModel(BaseModel):
def __init__(self):
super(FilesModel, self).__init__()
self.fs = gridfs.GridFS(self.mongo.get_database(), collection | ='files')
def get_by_id(self, file_id=None):
file_id = self.object_id(file_id)
result = self.fs.get(file_id)
return result
def delete(self, file_id=None):
self.fs.delete(file_id)
def add(self, file=None, filename=None):
# Filename is used for temporary ... | filename = filename if filename else file.name
file_id = self.fs.put(file, filename=filename)
return file_id
# The file is string, write it to temp
def add_with_temporary(self, file=None, filename=None):
file_id = None
file = "\n".join(file.splitlines()) # Transorm \... |
martbhell/wasthereannhlgamelastnight | src/lib/pyasn1_modules/rfc7894.py | Python | mit | 2,769 | 0.000361 | #
# This file is part of pyasn1-modules software.
#
# Created by Russ Housley.
#
# Copyright (c) 2019, Vigil Security, LLC
# License: http://snmplabs.com/pyasn1/license.html
#
# Alternative Challenge Password Attributes for EST
#
# ASN.1 source from:
# https://www.rfc-editor.org/rfc/rfc7894.txt
#
from pyasn1.type impo... | ttrValues'][0] = DirectoryString()
# Revocation Challeng | e Attribute
id_aa_revocationChallenge = univ.ObjectIdentifier('1.2.840.113549.1.9.16.2.57')
ub_aa_revocationChallenge = univ.Integer(255)
revocationChallenge = Attribute()
revocationChallenge['attrType'] = id_aa_revocationChallenge
revocationChallenge['attrValues'][0] = DirectoryString()
# EST Identity Linking At... |
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/elasticsearch/client/utils.py | Python | agpl-3.0 | 2,382 | 0.002519 | from datetime import date, datetime
from functools import wraps
try:
# PY2
from urllib import quote_plus
except ImportError:
# PY3
from urllib.parse import quote_plus
# parts of URL to be omitted
SKIP_IN_PATH = (None, '', [], ())
def _escape(value):
"""
Escape a single value of a URL string or... | nco | de
pass
return str(value)
def _make_path(*parts):
"""
Create a URL string from parts, omit all `None` values and empty strings.
Convert lists nad tuples to comma separated values.
"""
#TODO: maybe only allow some parts to be lists/tuples ?
return '/' + '/'.join(
# p... |
yetone/timeout-decorator | timeout_decorator/timeout_decorator.py | Python | mit | 5,411 | 0.000924 | """
Timeout decorator.
:copyright: (c) 2012-2013 by PN.
:license: MIT, see LICENSE for more details.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import sys
import time
import multiprocessing
import signal
from functools import wraps
#####... | def __call__(self, *args, **kwargs):
"""Execute the embedded function object asynchronously.
The function given to the constructor is transparently called and
requires that "ready" be intermittently polled. If and when it is
True, the "value" property may then be checked for returned da... | ) + args
self.__process = multiprocessing.Process(target=_target,
args=args,
kwargs=kwargs)
self.__process.daemon = True
self.__process.start()
self.__timeout = self.__limit + time.time()
... |
justanotherdot/advent-linguist | 2017/aoc_04.py | Python | mit | 23,369 | 0.000086 | pps = """bdwdjjo avricm cjbmj ran lmfsom ivsof
mxonybc fndyzzi gmdp gdfyoi inrvhr kpuueel wdpga vkq
bneh ylltsc vhryov lsd hmruxy ebnh pdln vdprrky
fumay zbccai qymavw zwoove hqpd rcxyvy
bcuo khhkkro mpt dxrebym qwum zqp lhmbma esmr qiyomu
qjs giedut mzsubkn rcbugk voxk yrlp rqxfvz kspz vxg zskp
srceh xdwao reshc shecr... | wxlcww pdd dcn ddp
macllv ldl kyluine lbt hbxbr wxcaspp ezwvc qxkeu
ivg gxv zsf ucr uff yrz
tdlwbny bqlrlz tbynwdl lwtbdny
tnekq pdaievs ttwpfh xfm fcaa
zqqhl zbf fbz uqrv bfz ffwavhk foccg
vcw ebqdd cwv eddbq nrmq
hpiusz sizphu xzq sgyehk wgagkv hsygek
vagkxa iou frqdnnr ipcg uxvh vvh eskf katgpiq aqktigp gzvseyi
xkw... | rp
fruuqjk gtote gooklg bzwhim zfnccmm ezipnf cxwdxa wfu fdca
zcyxb byzxc cxbyz pgcqco ivlxz
wrjh zfdinsf ihw xwosiah hdg xpiabno bilyy azdeczg javuwa
rinlv dcpt qhencba mmb njxw gadc
qwcpua qzyzt cxjsgh kumh byiimas qhsgf qytzz rqqruwp ismyiba xydcxz rwkscqa
xbzefi hltca ibzxfe fkx xizbfe wvaynts
oyuce vzk ouxvj gfh e... |
maebert/knyfe | knyfe/perm_test.py | Python | mit | 8,835 | 0.010867 | import numpy as np
import itertools
from scipy.misc import comb as bincoef
import random
#########################################################################
# GENERATORS
#########################################################################
def sign_permutations(length):
""" Memory efficient generator: ... | generate_limit = kwds.get('generate_limit', None)
while True if generate_limit == None else limiter < generate_limit:
limiter = limiter + 1
yield tuple(random.choice(pool) for pool in pools)
def random_sign_permutations(length, limit):
""" Random sign permutation generator. """
return rando... | erate all length choose sublength combinations. """
# get the combination indices, support both infinite and finite length generators
combination_indices = comb_function(range(length), sublength, limit) if limit else comb_function(range(length), sublength)
def indices_to_sign_vectors():
""" Generat... |
adamrp/qiime | tests/test_relatedness.py | Python | gpl-2.0 | 7,588 | 0 | #!/usr/bin/env python
# File created on 02 May 2012
from __future__ import division
__author__ = "William Van Treuren"
__copyright__ = "Copyright 2011, The QIIME project"
__credits__ = ["William Van Treuren"]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__maintainer__ = "William Van Treuren"
__email__ = "wdwvt1@gmail... | equal(exp_1, reduce_mtx(distmat, inds_1))
assert_almos | t_equal(exp_2, reduce_mtx(distmat, inds_2))
def test_random_mpd(self):
"""Test random mpd draws are calculated correctly when seeded."""
seed(0)
distmat = array([[0., 0.85, 0.5, 0.14, 0.36],
[0.85, 0., 0.79, 0.25, 0.47],
[0.5, 0.79, 0., 0.2... |
wiiiky/ydict | pydict/about.py | Python | gpl-3.0 | 743 | 0 | # encoding=utf-8
from gi.repository import Gtk
from .i18n import _
class AboutDialog(Gtk.AboutDialog):
def __init__(self, parent):
super(AboutDialog, self).__init__(title=_('About'), parent=parent)
self.s | et_modal(True)
self.set_program_name('Ydict')
self.set_authors(['Wiky L<wiiiky@outlook.com>'])
self.set_artists(['Wiky L<wiiiky@outlook.com>'])
self.set_ | comments('')
self.set_copyright('Copyright (c) Wiky L 2015')
self.set_license_type(Gtk.License.GPL_3_0)
self.set_logo_icon_name('ydict')
self.set_version('1.0')
self.set_website('https://github.com/wiiiky/ydict')
self.set_website_label('GitHub')
self.set_wrap_lice... |
lvidarte/lai-client | lai/db/mongo.py | Python | gpl-3.0 | 6,391 | 0.001408 | # -*- coding: utf-8 -*-
# Author: Leo Vidarte <http://nerdlabs.com.ar>
#
# This file is part of lai-client.
#
# lai-client is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3
# as published by the Free Software Foundation.
#
# lai-client is distribut... | n row['update']:
docs['updated'].append(self.get(id, deleted=True))
if row and 'commit' in row:
for id in row['commit']:
docs['committed'].append(self.get(id, deleted=True))
| to_commit = self.get_docs_to_commit()
for row in to_commit:
doc = Document(**row)
docs['to_commit'].append(doc)
return docs
def __str__(self):
return "%s://%s:%s/%s" % ('mongo', self.host, self.port, self.name)
|
alphydan/bhs-ical | new-bhs-cal/import_fun_and_stats.py | Python | gpl-2.0 | 13,512 | 0.003034 | #!/usr/bin/env python
# Class Based implementation of the BHS calendar
from datetime import datetime as dt
from datetime import timedelta as td
import csv, re
from icalendar import Calendar, Event
# What period is at what time? eg. period 1 from 8:40 - 9:45
from new_schedule_times import reg, l1, l2, l3, l4, l5, lunc... | string(day_data):
all_classes = get_list_of_unique_lessons(timetable_path_n_file)
dd = day_data
full_string = 'The following numbers show the lessons you will \
teach minus half-days, study leave, sports/art/steam days and final exams: \n\n'
for class_name in all_classes:
sub_string = class_na... | \n' % \
(day_data.stats[class_name+'-done'], day_data.stats[class_name+'-left'])
full_string = full_string + sub_string
teaching_days ='\n %d days of teaching left, %d days of teaching done \n ' % \
(dd.stats['days_left_teaching'], dd.stats['days_taught'])
just_days = "%d d... |
ella/ella-polls | ella_polls/views.py | Python | bsd-3-clause | 18,977 | 0.003583 | from datetime import datetime, timedelta
from itertools import chain, cycle
from django.shortcuts import render_to_response
from django.utils.translation import ugettext, ugettext_lazy as _
from django.http import HttpResponseRedirect, Http404
from django import forms
from django.views.decorators.http import require_P... | if poll.check_vote_by_ip_address(ip_address):
return polls_settings.USER_ALLREADY_VOTED
return polls_settings.USER_NOT_YET_VOTED
def survey_check_vote(request, survey):
sess_jv = request.session.get(polls_settings.SURVEY_JUST_VOTED_COOKIE_NAME, [] | )
# removing just voted info from session
if survey.id in sess_jv:
del request.session[polls_settings.SURVEY_JUST_VOTED_COOKIE_NAME]
# TODO - del just my poll, not the entire list !
return polls_settings.USER_JUST_VOTED
# removing no vote info from session
sess_nv = request.sessi... |
eoyilmaz/anima | anima/dcc/mayaEnv/pivot_switcher.py | Python | mit | 8,729 | 0.000916 | # -*- coding: utf-8 -*-
"""
oyPivotSwitcher.py by Erkan Ozgur Yilmaz (c) 2009
v10.5.17
Description :
-------------
A tool for easy animating of switching of pivots
Version History :
-----------------
v10.5.17
- modifications for Maya 2011 and PyMel 1.0.2
v9.12.25
- removed oyAxialCorrectionGroup script import
- mov... | ame(self._object, at="scalePivotX", t=frame, ott="step")
pm.setKeyframe(self._object, at="scalePivotY", t=frame, ott="step")
pm.setKeyframe(self._object, at="scalePivotZ", t=frame, ott="step")
# set piv | ot translations
self._object.setAttr("rotatePivotTranslate", -1 * displacement)
self._object.setAttr("scalePivotTranslate", -1 * displacement)
# set keyframes
pm.setKeyframe(self._object, at="rotatePivotTranslateX", t=frame, ott="step")
pm.setKeyframe(self._object, at="rotatePiv... |
tonussi/inseguro | laboratorio/rsa/pseudo.py | Python | mit | 4,350 | 0.001149 | # -*- coding: utf-8 -*-
import random as rand
class PrimeTester(object):
def solovay_strassen(self, primo, acuracidade=5):
nro_tentativas = 0
if primo == 2 or primo == 3:
return (nro_tentativas, True)
if primo < 2:
raise ValueError('Entrada < 2')
if primo %... | ndidato, 2, primo)
if primo_candidato == primo - 1:
return False
return True
def miller_rabin(self, primo, acuracidade=5):
nro_tentativas = 0
if primo == 2 or primo == 3:
return (nro_tentativas, True)
if primo < 2:
return (nro_t... | ange(acuracidade):
nro_tentativas += 1
possivelmente_primo = rand.randint(2, primo - 2)
if self.testacandidato(possivelmente_primo, primo, expoente, resto):
return (nro_tentativas, False)
return (nro_tentativas, True)
def potencia(self, base, exp, modul... |
EdisonAlgorithms/ProjectEuler | vol3/119.py | Python | mit | 416 | 0.002404 | def digit_sum(x):
return sum([ord(s) - ord('0') for s in str(x)])
if __name__ == "__main__":
cnt = 0
ans = []
for i in range(2, 50):
for j in range(2, 400):
v = j ** i
if digit_sum( | v) == j:
cnt += 1
| ans.append(v)
if cnt >= 50:
break
if cnt >= 50:
break
print sorted(ans)[29]
|
m-wichmann/pyArch | asm/src/output.py | Python | lgpl-3.0 | 572 | 0.003497 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
INSTR_PER_LINE = 8 |
class Output(object):
def __init__(self):
pass
def output_text(self, tokens, outfile):
fd = open(outfile, 'w')
instr_counter = 0
for t in tokens:
instr = "%02X%02X%02X%02X" % tuple(reversed(t))
instr_counter = instr_counter + 1
if (instr_co... | else:
instr += " "
fd.write(instr)
fd.close()
|
cloudify-cosmo/cloudify-azure-plugin | cloudify_azure/resources/storage/file.py | Python | apache-2.0 | 4,418 | 0 | # #######
# Copyright (c) 2016-2020 Cloudify Platform Ltd. 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... | _account = utils.get_storage_account(ctx)
resource_group_name = utils.get_resource_group(ctx)
azure_config = utils.get_client_config(ctx.node.properties)
keys = StorageAccount(azure_config, ctx.logger).list_keys(
resource_group_name, storage_account)
if not keys or not keys.get("key1"):
... | he Storage Account
storage_account_key = keys.get("key1")
# Get an interface to the File Share
api_version = \
ctx.node.properties.get('api_version',
constants.API_VER_STORAGE_FILE_SHARE)
file_share = FileShare(azure_config, ctx.logger, api_version)
try:
... |
estaban/pyload | module/plugins/hoster/XFileSharingPro.py | Python | gpl-3.0 | 13,352 | 0.001947 | # - | *- coding: utf-8 -*-
################ | ###############################################################
# 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 version.
#
# ... |
ashkankzme/IAISCustomsLoadTest | web/log/config.py | Python | apache-2.0 | 3,429 | 0.001458 | #!/usr/bin/env python
import sys
import logging
import logging.handlers
#The terminal has 8 colors with codes from 0 to 7
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
#These are the sequences need to get colored ouput
RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"
BOLD_SEQ = "\033[1m"
#The backg... | "[%(asctime)s" + \
"][%(threadName)-22s][%(levelname)s] %(message)s " + \
"(" + BOLD_SEQ + "%(filename)s" + RESET_SEQ + ":%(lineno)d)"
NO_COLOR_FORMAT = "[%(asctime)s] | [%(threadName)-22s][%(levelname)s] " + \
"%(message)s " + \
"(%(filename)s:%(lineno)d)"
FILE_FORMAT = "[%(asctime)s][%(threadName)-22s][%(levelname)s] " + \
"%(message)s "
@classmethod
def set(cls, log_level, log_filename, append=None, **kwargs)... |
johnsaigle/flush-tool | lib/loaders/product_loader.py | Python | bsd-3-clause | 4,102 | 0.008532 | import os
import xlrd
import configparser
import logging
from ..entities import product
def process_cell(cell):
"""Converts the given cell to the appropriate value."""
if cell.value == 'NA':
return ''
ttype = cell.ctype # get the cell's 'type'
if ttype == xlrd.XL_CELL_EMPTY or ttype == xlrd.XL... | = curr_row[NAME_COL].valu | e
visc_40_low = curr_row[VISC_40_LOW_COL].value
visc_40_high = curr_row[VISC_40_HIGH_COL].value
visc_100_low = curr_row[VISC_100_LOW_COL].value
visc_100_high = curr_row[VISC_100_HIGH_COL].value
# all elemental values should be formatted as floats
e... |
etherkit/OpenBeacon2 | macos/venv/lib/python3.8/site-packages/_pyinstaller_hooks_contrib/hooks/stdhooks/hook-pylint.py | Python | gpl-3.0 | 2,709 | 0.001107 | # ------------ | ------------------------------------------------------
# Copyright (c) 2020 PyInstaller Development Team.
#
# This file is distributed under the terms of the GNU General Public
# License (version 2.0 or later).
#
# The full license is available in LICENSE.GPL.txt, distributed with
# this | software.
#
# SPDX-License-Identifier: GPL-2.0-or-later
# ------------------------------------------------------------------
#
# *************************************************
# hook-pylint.py - PyInstaller hook file for pylint
# *************************************************
# The pylint package, in __pkginfo__.... |
mark-me/Pi-Jukebox | venv/Scripts/pip-script.py | Python | agpl-3.0 | 419 | 0 | #!C:\Users\Mark.Zwart\PycharmProjects\Pi-Jukebox\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip'
__requires__ = 'pip==19.0.3'
import re
import sys
from pkg_resources import load_entry_point
if __ | name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==19.0.3', 'console_scripts', ' | pip')()
)
|
dufferzafar/picard | setup.py | Python | gpl-2.0 | 27,977 | 0.002645 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import print_function
import datetime
import glob
import os
import re
import sys
import subprocess
from picard import __version__, compat
if sys.version_info < (2, 6):
print("*** You need Python 2.6 or higher to use Picard.")
args = {}
try:
fro... | defined_options('build', ('build_locales', 'build_dir'))
self.locales = self.distribution.locales
def run(self):
for domain, locale, po in self.locales:
if self.inplace:
path = os.path.join('locale | ', locale, 'LC_MESSAGES')
else:
path = os.path.join(self.build_dir, locale, 'LC_MESSAGES')
mo = os.path.join(path, '%s.mo' % domain)
self.mkpath(path)
self.spawn(['msgfmt', '-o', mo, po])
Distribution.locales = None
class picard_install_locales(Command)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.