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 |
|---|---|---|---|---|---|---|---|---|
WSULib/combine | combine/urls.py | Python | mit | 818 | 0 | """combine 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')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls im... | ib import admin
urlpatterns = [
url(r'^combine/', include('core.urls')),
url(r'^admin/', admin.site.urls),
]
|
hacklab-fi/hhlevents | hhlevents/apps/hhlregistrations/admin.py | Python | bsd-3-clause | 2,455 | 0.003666 | # -*- coding: UTF-8 -*-
from django.contrib import admin
from django.db import models
from django_markdown.admin import MarkdownModelAdmin, AdminMarkdownWidget
from django_markdown.models import MarkdownField
from happenings.models import Event as HappeningsEvent
from happenings.admin import EventAdmin as HappeningsEve... | 'payment_due', 'hide_join_checkbox',
)
}),
('Cate | gory', {
'classes': ('collapse',),
'fields': ('categories',)
}),
('Tag', {
'classes': ('collapse',),
'fields': ('tags',)
}),
('Color', {
'classes': ('collapse',),
'fields': (
('background_color', 'bac... |
jeanmask/opps | opps/channels/admin.py | Python | mit | 3,690 | 0.000813 | # -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from mptt.admin import MPTTModelAdmin
from .models import Channel
from .forms import ChannelAdminForm
from opps.core.admin import PublishableAdmin
from opps.core.admin import apply_opps_rules
from opps.cor... | 'fields': ('published', | 'date_available')}),
)
def get_parent(self, obj):
if obj.parent_id:
long_slug, slug = obj.long_slug.rsplit("/", 1)
return long_slug
get_parent.admin_order_field = "parent"
get_parent.short_description = "Parent"
def show_channel_path(self, obj):
return uni... |
grantmcconnaughey/django-lazy-tags | lazy_tags/templatetags/lazy_tags.py | Python | mit | 2,029 | 0 | from django import template
from django.template.loader import render_to_string
from django.conf import settings
from ..utils import get_tag_id, set_lazy_tag_data
register = template.Library()
@register.simple_tag
def lazy_tag(tag, *args, **kwargs):
"""
Lazily loads a template tag after the page has loaded... | r.simple_tag
def lazy_tags_javascript():
"""Outputs the necessary JavaScript | to load tags over AJAX."""
return _render_js('javascript')
@register.simple_tag
def lazy_tags_jquery():
"""Outputs the necessary jQuery to load tags over AJAX."""
return _render_js('jquery')
@register.simple_tag
def lazy_tags_prototype():
"""Outputs the necessary Prototype to load tags over AJAX.""... |
ROB-Seismology/oq-hazardlib | openquake/hazardlib/tests/acceptance/disagg_test.py | Python | agpl-3.0 | 10,965 | 0.00073 | # The Hazard Library
# Copyright (C) 2012 GEM Foundation
#
# 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.
#
# Th... | DHIayrcPGnyJh
f/6vBDRI6pV3xYF4zP1Thl+Pk/L+tGE4fj1FfVRVrJtZEPPJuI2hU8i3BztYtLFqKAyVNW2WOcHi
q99OBJFu5LX7QTbUSwjtUgjGdW3vk+yZ+HGhBZ5I/gz4PYbZ3bazAegLRKnPVA8JJuF3F2eEy9pA
fRLirWyqtg0jIW4roPS8RxYoDosgaKFhmFYHQNc455paAXhe9pU2QytAuwgd9ZlCRL/o56B5ErGg
eCWkxkGvTlqI/bBp3yEjQP5MZENj5c8A3Q0bkT69BRAPxZ12qaONgF6J/ToOcgTEJbG1d62UIkH... | kA9498FVwHiNZCcSgMREvKLYhVPdEVI0NEQy5BP4gDdCouRbXfUwJfTM4fM2QcYF/qT
Y4ExQswn3Gv4Lc52ewnYh7lmWuYMyofZDeiJNyG3iOggK98ahtQD/n6vVo0/gfyW3ZI171EegThE
tKV+tEF739mPQgM5P9kR6H9hg86OKzb4ALDnaHTHIRLixBGbwAqHYUI8t+D8ec1cQNwuOjZPxgQQ
nwu16nqNrCHQ//mMhGE5gL9HbibdIxIX2R0nkh6sKiVQD313SwpIX6bom8Sn6wQUCnG87KLLnMiI
q0WqP3mA3ttEqTBiZADOz... |
bijaydev/Implementation-of-Explicit-congestion-notification-ECN-in-TCP-over-wireless-network-in-ns-3 | utils/tests/test-waf.py | Python | gpl-2.0 | 7,623 | 0.005903 | #! /usr/bin/env python
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
#
# Copyright (c) 2014 Siddharth Santurkar
#
# This program 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 Softw... | warranty of
# MERCHANTABILITY or FITNESS FOR | A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# NOTE: Run this script with t... |
wileeam/airflow | airflow/contrib/operators/bigquery_to_gcs.py | Python | apache-2.0 | 1,678 | 0.00298 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | .cloud.operators.bigquery_to_gcs.BigQueryToGCSOperator`.""",
DeprecationWarning, stacklevel=2
)
super().__init__(*args, **kwarg | s)
|
allenlavoie/tensorflow | tensorflow/python/training/warm_starting_util.py | Python | apache-2.0 | 15,397 | 0.004287 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | """
if _is_variable(var):
current_var_name = _infer_var_name | ([var])
elif isinstance(var, list) and all(_is_variable(v) for v in var):
current_var_name = _infer_var_name(var)
elif isinstance(var, variables_lib.PartitionedVariable):
current_var_name = _infer_var_name([var])
var = var._get_variable_list() # pylint: disable=protected-access
else:
raise TypeEr... |
iLoop2/ResInsight | ThirdParty/Ert/devel/python/python/ert_gui/shell/shell_tools.py | Python | gpl-3.0 | 2,275 | 0.004396 | import fnmatch
import os
import shlex
def autoCompleteList(text, items):
if not text:
completions = items
else:
completions = [item for item in items if item.lower().startswith(text.lower())]
return completions
def containsAny(string, chars):
return True in [char in string for char in... | t = [item[separator_pos + 1:] for item in auto_complete_list]
else:
auto_complete_list = autoCompleteList(text, items)
return auto_complete_list
def createParameterizedHelpFunction(parameters, help_message):
def helpFunction(self):
return parameters, help_message
return helpFunction
... | sdir(path):
return "%s/" % tail
return tail
def getPossibleFilenameCompletions(text, separators="-"):
head, tail = os.path.split(text.strip())
if head == "": # no head
head = "."
files = os.listdir(head)
separator_pos = 0
if containsAny(tail, separators):
separator_po... |
froyobin/ironic | ironic/conductor/utils.py | Python | apache-2.0 | 6,324 | 0.000316 | # coding=utf-8
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | no | de['power_state'] = target_state
LOG.info(_LI('Succesfully set node %(node)s power state to '
'%(state)s.'),
{'node': node.uuid, 'state': target_state})
finally:
node['target_power_state'] = states.NOSTATE
node.save()
@task_manager.require_exclusive_lo... |
elliottd/GroundedTranslation | data_generator.py | Python | bsd-3-clause | 36,237 | 0.003229 | """
Data processing for VisualWordLSTM happens here; this creates a class that
acts as a data generator/feed for model training.
"""
from __future__ import print_function
from collections import defaultdict
import cPickle
import h5py
import logging
import numpy as np
np.set_printoptions(threshold='nan')
import os
impo... | or each iteration over the description indices, also shuffle the
# identifiers.
| random_instance.shuffle(identifiers)
# And loop over them.
for ident in identifiers:
if i == self.args.batch_size:
targets = self.get_target_descriptions(arrays[0])
yield_data = self.create_yield_dict(arrays, target... |
DT42/BerryNet | berrynet/service/movidius_service.py | Python | gpl-3.0 | 5,991 | 0.000501 | # Copyright 2017 DT42
#
# This file is part of BerryNet.
#
# BerryNet 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.
#
# BerryNet is d... | n takes {} ms'.format(duration(t)))
classes = self.engine.classes
labels = self.engine.labels
logger.debug('draw = {}'.format(self.draw))
if self.draw is False:
self.result_hook(self.generalize_result(jpg_json, model_outputs))
else:
self.result_hook(
... | self.generalize_result(jpg_json, model_outputs),
generate_class_color(class_num=classes),
labels))
def result_hook(self, generalized_result):
logger.debug('result_hook, annotations: {}'.format(generalized_result['annotations']))
self.comm.send('... |
gdietz/OpenMEE | common_wizard_pages/histogram_dataselect_page.py | Python | gpl-3.0 | 1,558 | 0.009628 | import sys
#from functools import partial
from PyQt4 import QtCore, QtGui
from PyQt4.Qt import *
from ome_globals import *
import ui_histogram_dataselect_page
class HistogramDataSelectPage(QWizardPage, ui_histogram_dataselect_page.Ui_WizardPage):
def __init__(self, model, prev_hist_var=None, parent=None):
... | iven
self.comboBox.setCurrentIndex(default_index)
self.completeChanged.emit()
def isComplete(self):
return True
def get_selected_var(self):
idx = self.comboBox.currentIndex()
data = self.comboBox.itemData(idx)
col = data.toInt()[0]
... | ble_assigned_to_column(col)
|
qbeenslee/Nepenthes-Server | utils/jsonutil.py | Python | gpl-3.0 | 1,193 | 0.00172 | # coding:u | tf-8
'''
Author : qbeenslee
Created : 2015/1/20
'''
import json
import datetime
JSON_PARSE_ERROR = u"{'success':0,'data':[],'message':'Json 解析错误'}"
class NeJSONEncoder(json.JSONEncoder):
""" Wrapper | class to try calling an object's tojson() method. This allows us to JSONify objects coming from the ORM.
Also handles dates and datetimes. """
def default(self, obj):
try:
if hasattr(obj, '__json__'):
return obj.__json__()
elif isinstance(obj, datetime.dat... |
minhphung171093/GreenERP | openerp/addons/web_editor/models/ir_translation.py | Python | gpl-3.0 | 578 | 0.00346 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright | and licensing details.
from openerp import models, api
class ir_translation(models.Model):
_inherit = 'ir.translation'
@api.model
def _get_terms_mapping(self, field, records):
if self._context.get('edit_translations'):
self.insert_missing(field, records)
return lambda dat... | )
|
amiraliakbari/sharif-mabani-python | by-session/ta-921/j8/tuple1.py | Python | mit | 263 | 0.011407 | a = (1, 2)
b = (1, 3, 5, 7, 8, 11)
print a[0]
#b[3] = 3 # error!
x1 = a[0] |
y1 = a[1]
x1, y1 = a
b1, b2, b3, b4, b5, b6 = b
print b4
#b1 | , b2 = b # error!
a = 1, 2, 3
print a
def f():
return 1, 3
a = f()
x, y = f()
x = f()[0]
|
ConPaaS-team/conpaas | cps-tools/src/cps_tools/taskfarm.py | Python | bsd-3-clause | 10,346 | 0.002513 | # import argcomplete
# import | httplib
# import logging
# import simplejson
# import sys
# import urllib2
# from time import strftime, localtime
# from conpaas.core import https
# from .base import BaseClient
# from .config import config
# from .service import ServiceCmd
# MODES = ['DEMO', 'REAL']
# TASKFARM_MNG_PORT = 8475
# def http_jsonrpc... | for task farming)"""
# if params is None:
# params = {}
# url = "http://%s:%s%s" % (hostname, port, uri)
# data = simplejson.dumps({'method': method,
# 'params': params,
# 'jsonrpc': '2.0',
# 'id': 1,
# ... |
ekutlu/raspberry-test | test.py | Python | mit | 40 | 0.025 | __au | thor__ = 'emre'
| print "hello world" |
TunedMystic/taskr | webapp/urls.py | Python | gpl-2.0 | 434 | 0.013825 | from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.co | nf import settings
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'webapp.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r"", include("meeting.urls", namespace = "meeting")),
url(r'^admin/', include(admin.site.urls)),
)
handler404 = "misc.views.han | dler404"
handler500 = "misc.views.handler500"
|
ameyavilankar/social-network-recommendation | preprocessing/random_benchmark.py | Python | bsd-2-clause | 1,033 | 0.006776 | #! /usr/bin/env python
import random
import utilities
def read_nodes_from_training(file_name):
"""
Returns a list of all the nodes in the graph
"""
node_set = set()
for nodes in utilities.edges_generator(file_name):
for node in nodes | :
node_set.add(node)
return list(node_set)
def random_benchmark(train_file, test_file, submission_file, num_predictions):
"""
Runs the random benchmark.
"""
nodes = read_nodes_from_training(train_file)
test_nodes = utilities.read_nodes_list(test_file)
test_predictions = [[rando... | n test_nodes]
utilities.write_submission_file(submission_file,
test_nodes,
test_predictions)
if __name__=="__main__":
random_benchmark("../Data/train.csv",
"../Data/test.csv",
"../Submissions/ran... |
ld4apps/lda-examples | todo-flask/src/app.py | Python | apache-2.0 | 1,842 | 0.008143 | import lda
from flask import Flask, abort, request
app = Flask(__name__, static_url_path='')
@app.route('/td/items', methods=['GET'])
def items():
document, status, headers = lda.get_virtual_container(request.environ, 'ce_item_of')
if status != 200:
abort(status)
document, headers = lda.convert_to... | t_document(request.environ)
if status != 200:
abort(status)
document, headers = lda.convert_to_reque | sted_format(document, headers, request.environ)
return document, status, headers
@app.route('/td/items/<i>', methods=['DELETE'])
def delete_item(i):
document, status, headers = lda.delete_document(request.environ)
return "", status, headers
@app.route('/td/items/<i>', methods=['PATCH'])
def change_item(i)... |
vjFaLk/frappe | frappe/core/doctype/defaultvalue/defaultvalue.py | Python | mit | 607 | 0.021417 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class DefaultValue(Document):
pass
def on_doctype_update():
"""Create indexes for `tabDefaultValue` on `(parent, defk... | fields=['parent', 'defkey'],
index_name='defaultvalue_parent_defkey_index')
frappe.db.add_index(doctype='DefaultValue',
fields=['parent', 'p | arenttype'],
index_name='defaultvalue_parent_parenttype_index')
|
guardicore/monkey | monkey/tests/unit_tests/infection_monkey/telemetry/attack/test_t1197_telem.py | Python | gpl-3.0 | 917 | 0.001091 | import json
import pytest
from common.utils.attack_utils import ScanStatus
from infection_monkey.model import VictimHost
from infection_monkey.telemetry.attack.t1197_telem import T1197Telem
DOMAIN_NAME = "domai | n-name"
IP = "127.0.0.1"
MACHINE = VictimHost(IP, DOMAIN_NAME)
STATUS = ScanStatus.USED
USAGE_STR = "[Usage info]"
@pytest.fixture
def T1197_telem_test_instance():
return T1197Telem(STATUS, MACHINE, USAGE_STR)
def test_T1197_send(T1197_telem_test_instance, spy_send_telemetry):
T1197_telem_test_instance.send... |
"machine": {"domain_name": DOMAIN_NAME, "ip_addr": IP},
"usage": USAGE_STR,
}
expected_data = json.dumps(expected_data, cls=T1197_telem_test_instance.json_encoder)
assert spy_send_telemetry.data == expected_data
assert spy_send_telemetry.telem_category == "attack"
|
ghilbut/djign | djign/__init__.py | Python | mit | 128 | 0.023438 | # -*- coding:utf-8 -*-
from django.shortcuts import render
def | index(request):
return re | nder(request, 'djign/index.html') |
shiroyuki/vireo | vireo/drivers/amqp/consumer.py | Python | mit | 24,473 | 0.010256 | import json
import math
import sys
import threading
import traceback
import time
import uuid
from pika import BasicProperties
from pika.exceptions import ConnectionClosed, ChannelClosed, IncompatibleProtocolError
from ...helper import log, debug_mode_enabled
from ...model import Message, RemoteSignal
fro... | hen the message consumption begins.
:param callable on_disconnect: a callback function when the message consumption is interrupted due to unexpected disconnection.
:param callable on_error: a callback function when the message con | sumption is interrupted due to exception raised from the main callback function.
:param str controller_id: the associated controller ID
:param dict exchange_options: the additional options for exchange
:param bool auto_acknowledge: the flag to determine whether the consumer sh... |
titasakgm/brc-stock | openerp/addons/ineco_stock/product.py | Python | agpl-3.0 | 5,430 | 0.009024 | # -*- 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... | else:
name = ('%.0f' % (record['factor'])) + ' ' +name+' / '+uom_categ[1]
res.append((record['id'], name))
return res
def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
i | f isinstance(ids, (list, tuple)) and not len(ids):
return []
if isinstance(ids, (long, int)):
ids = [ids]
res = {}
for id in ids:
data = self.browse(cr, uid, id)
if data.uom_type == 'reference':
res[id] = 1
elif data.uom... |
rkhleics/wagtailmenus | wagtailmenus/migrations/0010_auto_20160201_1558.py | Python | mit | 408 | 0 | # -*- c | oding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wagtailmenus', '0009_auto_20160201_0859'),
]
operations = [
migrations.RenameField(
model_name='mainmenuitem',
... | e='allow_subnav',
),
]
|
bitmazk/webfaction-django-boilerplate | website/webapps/django/project/settings/test_settings.py | Python | mit | 371 | 0 | # flake8: noqa
" | ""Settings to be used for running tests."""
from settings import *
INSTALLED_APPS.append('integration_tests')
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
EMAIL_SUBJECT_PREFIX = '[test] '
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBa... | UTH_TESTS_MIGRATE = False
|
Crystal-SDS/dashboard | crystal_dashboard/dashboards/crystal/containers/browsers.py | Python | gpl-3.0 | 1,168 | 0 | # Copyright 2012 Nebula, 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 agree... | DITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from django.utils.translation import ugettext_lazy as _
from horizon import browsers
from crystal_dashboard.dashboards.crystal.containers import tables
class ... | content_table_class = tables.ObjectsTable
navigable_item_name = _("Container")
navigation_kwarg_name = "container_name"
content_kwarg_name = "subfolder_path"
has_breadcrumb = True
breadcrumb_url = "horizon:crystal:containers:index"
|
cmelange/ansible | lib/ansible/modules/network/nxos/nxos_vlan.py | Python | gpl-3.0 | 13,912 | 0.001509 | #!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distribut... | sample: {"admin_state": "down", "name": "app_vlan",
"vlan_id": "20", "vlan_state": "suspend", "mapped_vni": ""}
end_state:
description: k/v pairs of the VLAN after executing module or null
when using vlan_range
re | turned: when debug enabled
type: dict or null
sample: {"admin_state": "down", "name": "app_vlan", "vlan_id": "20",
"vlan_state": "suspend", "mapped_vni": "5000"}
updates:
description: command string sent to the device
returned: always
type: list
sample: ["vlan 20", "vlan 55", "vn-se... |
fire-uta/iiix-data-parser | cli.py | Python | mit | 1,078 | 0.008349 | import optparse
class CLI:
pass
CLI.parser = optparse.OptionParser()
CLI.parser.add_option("-q", "--queries", dest="queries", help="Queries csv file", metavar="FILE")
CLI.parser.add_option("-l", "--logs", dest="logs", help="Path to log files contain | ing directory", metavar="DIR")
CLI.parser.add_option("-r", "--results", dest="results",
help="Path to result files containing directory", metavar="DIR")
CLI.parser.add_option("-g", "--gains", dest="gains" | ,
help="Comma-separated list of gains for different relevance levels, eg. 0,1,10", metavar="LIST")
CLI.parser.add_option("-s", "--serp-len", dest="serp_len",
help="Number of results on a single Search Engine Result Page [default: %default]",
default=10, ... |
jindongh/kombu | kombu/tests/transport/test_redis.py | Python | bsd-3-clause | 40,008 | 0.000025 | from __future__ import absolute_import
import socket
import types
from collections import defaultdict
from itertools import count
from kombu import Connection, Exchange, Queue, Consumer, Producer
from kombu.exceptions import InconsistencyError, VersionMismatch
from kombu.five import Empty, Queue as _Queue
from kombu... | 'ack_emulation': False,
})
chan = conn.channel()
self.assertFalse(chan.ack_emulation)
self.assertEqual(chan.QoS, virtual.QoS)
def test_redis_info_raises(self):
pool = Mock(name='pool')
pool_at_init = [pool]
client = Mock(name='client')
class XChann... | wargs):
self._pool = pool_at_init[0]
super(XChannel, self).__init__(*args, **kwargs)
def _get_client(self):
return lambda *_, **__: client
class XTransport(Transport):
Channel = XChannel
conn = Connection(transport=XTransport)
... |
sherrardTr4129/FaceHarold | getCSVData.py | Python | mit | 2,092 | 0.010516 | import csv
import math
from CSHLDAP import CSHLDAP #get this from the wiki
from subprocess import call
your_gender_list = []
with open('match_scores.csv', 'rb') as f:
reader = csv.reader(f)
your_gender_list = list(reader)
print(your_gender_list)
tempList = [0] * len(your_gender_list)
peopleList = [... | skillsStr += skills[x] + ", "
elif(x == len(skills)-1):
skillsStr += ", and " + skills[x]
else:
skillsStr += ", " + skills[x]
msgString += "with skills in " + skillsStr
print(msgString)
call(["pico2wave", " | -w", "msg.wav", msgString])
|
leb2dg/osf.io | osf/models/node.py | Python | apache-2.0 | 117,415 | 0.001823 | import functools
import itertools
import logging
import re
import urlparse
import warnings
import bson
from django.db.models import Q
from dirtyfields import DirtyFieldsMixin
from django.apps import apps
from django.contrib.contenttypes.fields import GenericRelation
from django.core.paginator import Paginator
from dja... | nherit from AbstractNode will | appear in
the same table and will be differentiated by the `type` column.
"""
#: Whether this is a pointer or not
primary = True
settings_type = 'node' # Needed for addons
FIELD_ALIASES = {
# TODO: Find a bet |
shawncaojob/LC | LINTCODE/41_maximum_subarray.py | Python | gpl-3.0 | 410 | 0.004878 | class Solution:
"""
@param: nums: A list of integers
@return: A integer indicate the sum of max subarray
"""
def maxSubArray(self, nums):
| # write your code here
if not nums or len(nums) == 0: return 0
cur = res = nums[0]
for i in xrange(1, len(nums)):
cur = max(cur | + nums[i], nums[i])
res = max(res, cur)
return res
|
plamut/superdesk | server/apps/publish/content/__init__.py | Python | agpl-3.0 | 524 | 0 | # -*- coding: utf-8; -*-
#
# This file is part of | Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
from .publish import ArchivePublishResource, ArchivePublishSe... | kill import KillPublishResource, KillPublishService # NOQA
from .correct import CorrectPublishResource, CorrectPublishService # NOQA
|
DailyActie/Surrogate-Model | 01-codes/OpenMDAO-Framework-dev/openmdao.main/src/openmdao/main/test/test_aningvtree.py | Python | mit | 742 | 0 | import unittest
from openmdao.main.api import VariableTree, Component, Assembly
from openmdao.main.datatypes.api import Float, VarTree
class VT(VariableTree):
x = Float()
class C(Component):
x = Float(iotype='in')
out = Float(iotype='out')
def execute(self):
self.out = 2 * self.x
class A... | t = VarTree(VT(), iotype='in')
def configure(self):
self.add('c', C())
self.driver.workflow.add(['c'])
self.connect('vt.x', 'c.x')
self.create_passthrough('c.out')
class TestCase(unittest.TestCase):
def test_vtree(self):
a = A()
a.vt.x = 1.0
a.run()
... | __ == '__main__':
unittest.main()
|
AndyHannon/ctrprogress | ranker.py | Python | mit | 11,305 | 0.008138 | # -*- coding: utf-8 -*-
#!/usr/bin/env python
import webapp2,jinja2,os
import logging
import wowapi
from datetime import datetime
from google.appengine.ext import ndb
from google.appengine.api.memcache import Client
from google.appengine.api import taskqueue
from google.appengine.api.taskqueue import Queue
from goog... | eak
class Ranker(webapp2.RequestHandler):
def get(self):
queue = Queue()
stats = queue.fetch_statistics()
template_values={
'tasks': stats.tasks,
'in_flight': stats.in_flight,
}
template = JINJA_ENVIRONMENT.get_template('templates/ranker.html')
... | # refuse to start the tasks if there are some already running
queue = Queue()
stats = queue.fetch_statistics()
if stats.tasks == 0:
print 'nop'
taskqueue.add(url='/builder', params={'start':'A', 'end':'B'})
taskqueue.add(url='/builder', params={'start':'C', 'e... |
endlessm/eos-event-recorder-daemon | tests/test-opt-out-integration.py | Python | gpl-2.0 | 8,113 | 0.002588 | #!/usr/bin/env python3
# Copyright 2014, 2015, 2017 Endless Mobile, Inc.
# This file is part of eos-event-recorder-daemon.
#
# eos-event-recorder-daemon 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... | prefix='eos-event-recorder-daemon-test.')
persistent_cache_directory = os.path.join(self.test_dir.name, 'cache')
os.mkdir(persistent_cache_directory)
escaped_dir = shlex.quote(persistent_cache_directory)
persistent_cache_dir_arg = '--persistent-cache-directory=' + escaped_dir
... | pts to create CONFIG_DIR / cache-size.conf when
# launched; this will typically fail while running this test because
# either CONFIG_DIR does not exist, or it exists and is not owned by
# the user running the test. The daemon logs a warning in this case.
# (If the test is running as root... |
mrucci/moto | moto/ec2/models.py | Python | apache-2.0 | 121,494 | 0.001523 | from __future__ import unicode_literals
import boto
import copy
import itertools
import re
import six
from collections import defaultdict
from datetime import datetime
from boto.ec2.instance import Instance as BotoInstance, Reservation
from boto.ec2.blockdevicemapping import BlockDeviceMapping, BlockDeviceType
from b... | random_subnet_id,
random_subnet_association_id,
random_volume_id,
random_vpc_id,
random_vpc_peering_connection_id,
generic_filter,
is_valid_resource_id,
get_prefix,
simple_a | ws_filter_to_re,
is_valid_cidr,
filter_internet_gateways,
filter_reservations,
random_network_acl_id,
random_network_acl_subnet_association_id,
random_vpn_gateway_id,
random_vpn_connection_id,
random_customer_gateway_id,
is_tag_filter,
)
def utc_date_and_time():
return datetime... |
jos4uke/getSeqFlankBlatHit | lib/python2.7/site-packages/pybedtools/scripts/peak_pie.py | Python | gpl-2.0 | 5,681 | 0.000176 | #!/usr/bin/env python
"""
Make a pie chart where peaks fall in annotations; see \
:mod:`pybedtools.contrib.Classifier` for more flexibility.
The results here are similar to CEAS (http://liulab.dfci.harvard.edu/CEAS/).
However, multi-featuretype classes are reported. That is, if a peak falls in
an exon in one isoform... | out='out.png',
include=['exon',
'CDS',
'intron',
'five_prime_UTR',
| 'three_prime_UTR'])
if __name__ == "__main__":
import doctest
if doctest.testmod(optionflags=doctest.ELLIPSIS).failed == 0:
main()
|
TaylorOshan/spint | spint/tests/test_gravity.py | Python | bsd-3-clause | 67,670 | 0.004699 |
"""
Tests for gravity-style spatial interaction models
Test data is the Austria migration dataset used in Dennet's (2012) practical primer
on spatial interaction modeling. The data was made avialable through the
following dropbox link: http://dl.dropbox.com/u/8649795/AT_Austria.csv.
The data has been pre-filtered so ... | 'AT34',
'AT34',
'AT34'])
self.d = np.array(['AT12',
'AT13',
'AT21',
'AT22',
'AT31',
'AT32',
... | 'AT13',
'AT21',
'AT22',
'AT31',
'AT32',
'AT33',
'AT34',
'AT11',
'AT12',
... |
KronosKoderS/py_pushover | pypushover/__init__.py | Python | mit | 324 | 0.006173 | __version__ = "0 | .2.7"
from pypushover.Constants import PRIORITIES, SOUNDS, OS
from pypushover._base import BaseManager, send, base_url, PushoverError
from pypushover import client, groups, license, message, verification
__all__ = ['PRIORITIES', 'SOUNDS', 'OS', 'client', 'groups', 'license', 'message' | , 'verification']
|
Samweli/inasafe | safe/impact_functions/volcanic/volcano_point_population/impact_function.py | Python | gpl-3.0 | 8,892 | 0 | # coding=utf-8
"""InaSAFE Disaster risk tool by Australian Aid - Volcano Point on
Population Impact Function.
Contact : ole.moller.nielsen@gmail.com
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free So... | ata_warning
# include any generic exposure specific notes from definitions.py
fields = fields + self.exposure_notes()
# include any generic hazard specific notes from definitions.py
fields = fields + | self.hazard_notes()
return fields
def run(self):
"""Run volcano point population evacuation Impact Function.
Counts number of people exposed to volcano event.
:returns: Map of population exposed to the volcano hazard zone.
The returned dict will include a table with n... |
Shinichi-Nakagawa/xp2015_baseball_tools | service/__init__.py | Python | mit | 29 | 0 | _ | _author__ = 'shinyorke_mbp'
| |
nwokeo/supysonic | venv/lib/python2.7/site-packages/psycopg2/tests/test_cancel.py | Python | agpl-3.0 | 3,785 | 0.000264 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# test_cancel.py - unit test for query cancellation
#
# Copyright (C) 2010-2011 Jan Urbański <wulczer@wulczer.org>
#
# psycopg2 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... | self.assertEqual(cur.fetchall(), [(1, )])
def test_async_connection_cancel(self):
async_conn = psycopg2.connect(dsn, async_=True)
async_conn.close()
self.assertTrue(async_conn.closed)
def test_suite():
| return unittest.TestLoader().loadTestsFromName(__name__)
if __name__ == "__main__":
unittest.main()
|
coddingtonbear/inthe.am | docs/conf.py | Python | agpl-3.0 | 8,300 | 0.000602 | # type: ignore
#
# Inthe.AM documentation build configuration file, created by
# sphinx-quickstart on Sat Sep 13 15:53:25 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All confi... | relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
# Add any extra paths th | at contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_f... |
buchuki/pyjaco | tests/basic/lambda2.py | Python | mit | 67 | 0.014925 |
x = l | amb | da x: (lambda x: (lambda x: x + 2)(x+2))(x+2)
print x(2)
|
miyuchina/mistletoe | test/test_latex_token.py | Python | mit | 544 | 0 | import unittest
from mistletoe.span_token impo | rt tokenize_inner
from mistletoe.latex_token import Math
from mistletoe.latex_renderer import LaTe | XRenderer
class TestLaTeXToken(unittest.TestCase):
def setUp(self):
self.renderer = LaTeXRenderer()
self.renderer.__enter__()
self.addCleanup(self.renderer.__exit__, None, None, None)
def test_span(self):
token = next(iter(tokenize_inner('$ 1 + 2 = 3 $')))
self.assertI... |
ar4s/django | django/db/models/fields/__init__.py | Python | bsd-3-clause | 90,874 | 0.000694 | import collections.abc
import copy
import datetime
import decimal
import math
import operator
import uuid
import warnings
from base64 import b64decode, b64encode
from functools import partialmethod, total_ordering
from django import forms
from django.apps import apps
from django.conf import settings
from django.core i... | on counter, and save our local copy.
if auto_created:
self.creation_counter = Field.auto_creation_counter
Field.auto_creation_counter -= 1 |
else:
self.creation_counter = Field.creation_counter
Field.creation_counter += 1
self._validators = list(validators) # Store for deconstruction later
messages = {}
for c in reversed(self.__class__.__mro__):
messages.update(getattr(c, 'default_error... |
zcbenz/cefode-chromium | tools/git/move_source_file.py | Python | bsd-3-clause | 5,348 | 0.010845 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Moves a C++ file to a new location, updating any include paths that
point to it, and re-ordering headers as needed. Updates inc... | w_guard)
if new_contents == contents:
raise Exception(
'Error updating include guard; perhaps old guard is not per style guide?')
with open(new_path, 'w') as f:
f.write(new_contents)
def main():
if not os.path.isdir('.git'):
print 'Fatal: You must run from the root of a git checkout.'
ret... | _moved = False
if args[0] == '--already-moved':
args = args[1:]
already_moved = True
from_path = args[0]
to_path = args[1]
to_path = MakeDestinationPath(from_path, to_path)
if not already_moved:
MoveFile(from_path, to_path)
UpdatePostMove(from_path, to_path)
return 0
if __name__ == '__main... |
mparra-mpz/CURIOSITY | CURIOSITY/test/CommunicationTest.py | Python | gpl-2.0 | 1,149 | 0.007833 | #! /usr/bin/env python
import unittest
import time
from Communication import Communication
class CommunicationTest(unittest.TestCase):
def setUp(self):
'''
Verify environment is setup properly.
'''
self.controller = Communication()
self.b_list = self.controller.get_blu... | down properly.
'''
pass
def test_get_bluetooth_list(self):
'''
Verify that the bluetooth list was retrieve without problems.
'''
value = False
if "Empty" not in self.b_list[0]:
value = True
self.assertTrue(value)
def test_send(... | for b_name in self.b_list:
if "CURIOSITY"in b_name:
break
self.controller.connect(b_name)
value = self.controller.send("Hello")
time.sleep(5)
self.controller.disconnect()
self.assertTrue(value)
if __name__ == '__main__':
unittest.main() |
maminian/skewtools | scripts/animate_particles_2d_labframe.py | Python | gpl-3.0 | 1,101 | 0.070845 | from numpy import *
from matplotlib import pyplot
import scripts.skewtools as st
import sys
X,Y,t,Pe = st.importDatasets(sys.argv[1],'X','Y','Time','Peclet')
figscale = 5.
fig,ax = pyplot.subplots(1,1,figsize=(4*figscale,figscale))
uwall = 2./3.
xmax = X.max() + uwall*Pe*t[-1]
for i in range(len(t)):
#for i in [5... | = ~subset1
ax.scatter(X[subset1,i],Y[subset1,i],facecolor=[0,0,0.9],edgecolor=[0,0,0,0],s=1,alpha=0.2)
ax.scatter(X[subset2,i],Y[subset2,i],facecolor=[0.9,0,0],edgecolor=[0,0,0,0],s= | 1,alpha=0.2)
# ax.hist2d(X[subset,i] + uwall*Pe*t[i],Y[subset,i],cmap=pyplot.cm.inferno,)
# ax.hold(False)
ax.set_xlim([0.,xmax])
ax.set_ylim([-1.05,1.05])
print '%i active particles, %i of %i frames'%(sum(subset1),i,len(t)-1)
pyplot.savefig('cloudframe_'+str(i).zfill(4)+'.png',d... |
wilsonkichoi/zipline | zipline/sources/data_frame_source.py | Python | apache-2.0 | 5,146 | 0 | #
# Copyright 2015 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | ry with default values.
self.start = kwargs.get('start', self.data.major_axis[0])
self.end = kwargs.get('end', self.data.major_axis[-1])
self.sids = self.data.items
# Hash_value for downstream sorting.
self.arg_string = hash_args(data, **kwargs)
self._raw_data = None
... | self.started_sids = set()
@property
def mapping(self):
mapping = {
'dt': (lambda x: x, 'dt'),
'sid': (lambda x: x, 'sid'),
'price': (float, 'price'),
'volume': (int, 'volume'),
}
# Add additional fields.
for field_name in self.da... |
mgadi/naemonbox | sources/psdash/pyzmq-13.1.0/examples/mongodb/controller.py | Python | gpl-2.0 | 3,050 | 0.003934 | #-----------------------------------------------------------------------------
# Copyright (c) 2010 Justin Riley
#
# Distributed under the terms of the New BSD License. The full license is in
# the file COPYING.BSD, distributed as part of this software.
#-------------------------------------------------------------... | sg = 'invalid message received: %s' | % msg
print error_msg
reply = [msg[0], error_msg]
socket.send_multipart(reply)
continue
id = msg[0]
operation = msg[1]
contents = json.loads(msg[2])
# always send back the id with ROUTER
reply = [... |
pelson/conda-build | tests/test_render.py | Python | bsd-3-clause | 1,460 | 0.000685 | import os
from conda_build import api
from conda_build import render
def test_output_with_noarch_says_noarch(testing_metadata):
testing_met | adata.meta['build']['noarch'] = 'python'
output = api.get_output_file_path(testing_metadata)
assert os.path.sep + "noarch" + os.path.sep in output[0]
def test_output_with_noarch_python_says_noarch(testing_metadata):
testing_metadata.meta['build']['no | arch_python'] = True
output = api.get_output_file_path(testing_metadata)
assert os.path.sep + "noarch" + os.path.sep in output[0]
def test_reduce_duplicate_specs(testing_metadata):
reqs = {'build': ['exact', 'exact 1.2.3 1', 'exact >1.0,<2'],
'host': ['exact', 'exact 1.2.3 1']
}
testin... |
openstack/horizon | openstack_dashboard/test/unit/api/rest/test_keystone.py | Python | apache-2.0 | 37,897 | 0 | # Copyright 2014, Rackspace, US, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | 'user_create']})
def _test_user_create(self, supplied_body, add_user_call):
request = self.mock_rest_request(body=supplied_body)
self.mock_get_default_domain.return_value = \
mock.Mock(**{'id': 'the_domain'})
| self.mock_user_create.return_value = mock.Mock(**{
'id': 'user123',
'to_dict.return_value': {'id': 'user123', 'name': 'bob'}
})
response = keystone.Users().post(request)
self.assertStatusCode(response, 201)
self.assertEqual(response['location'],
... |
datakortet/django-cms | cms/tests/menu.py | Python | bsd-3-clause | 52,671 | 0.001956 | # -*- coding: utf-8 -*-
from __future__ import with_statement
import copy
from django.db import connection
from cms.api import create_page
from cms.menu import CMSMenu, get_visible_pages
from cms.models import Page
from cms.models.permissionmodels import GlobalPagePermission, PagePermission
from cms.test_utils.fixtures... | context_managers import (SettingsOverride,
LanguageOverride)
from cms.test_utils.util.mock import AttributeObject
from cms.utils import get_cms_setting
from cms.utils.i18n import force_language
from django | .conf import settings
from django.contrib.auth.models import AnonymousUser, User, Permission, Group
from django.contrib.sites.models import Site
from django.template import Template, TemplateSyntaxError
from django.utils.translation import activate
from menus.base import NavigationNode
from menus.menu_pool import menu_... |
meskio/bitmask_client | src/leap/bitmask/backend/leapbackend.py | Python | gpl-3.0 | 20,848 | 0 | # -*- coding: utf-8 -*-
# leapbackend.py
# Copyright (C) 2013 LEAP
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
#... | prov_unsupported_api
prov_name_resolution -> { PASSED_KEY: bool, ERROR_KEY: str }
prov_https_connection -> { PASSED_KEY: bool, ERROR_KEY: str }
prov_download_provider_info -> { PASSED_KEY: bool, ERROR_KEY: | str }
"""
self._call_queue.put(("provider", "setup_provider", None, provider))
def provider_cancel_setup(self):
"""
Cancel the ongoing setup provider (if any).
"""
self._call_queue.put(("provider", "cancel_setup_provider", None))
def provider_bootstrap(self, pr... |
ilausuch/CacheServer | src/test/testServer_speed.py | Python | mit | 1,247 | 0.035285 | import sys
| __author__ = "ilausuch"
__date__ = "$13-jun-2017 20:05:19$"
sys.path.append( "../Addons" )
from Client import Client
from Timer import Timer
count=1000
def test1():
print ("Test 1: Multiple entry set same connection (count={0})".format(count))
client = Client("localhost", 10001 | )
timer=Timer()
for i in range(0,count):
client.entry_set("test speed",i,i)
client.close()
print ("Seconds: {0}".format(timer.end()))
def test2():
print ("Test 2: Multiple entry set opening/closing connection (count={0})".format(count))
timer=Timer()
... |
googleapis/python-dialogflow | samples/generated_samples/dialogflow_generated_dialogflow_v2_versions_create_version_async.py | Python | apache-2.0 | 1,488 | 0.000672 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under | the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is dist... | # limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for CreateVersion
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
... |
feigaochn/leetcode | p576_out_of_boundary_paths.py | Python | mit | 1,552 | 0 | #!/usr/bin/env python3
# coding: utf-8
import sys
class Solution:
def findPaths(self, m, n, N, i, j):
"""
:type m: int
:type n: int
:type N: int
:type i: int
:type j: int
:rtype: int
"""
if N == 0:
return 0
from collectio... | ret = 0
maps = [defaultdi | ct(int), defaultdict(int)]
for c in range(n):
maps[1][(0, c)] += 1
maps[1][(m - 1, c)] += 1
for r in range(m):
maps[1][(r, 0)] += 1
maps[1][(r, n - 1)] += 1
ret += maps[1].get((i, j), 0)
for step in range(2, N + 1):
midx = ste... |
totalgood/twote | twote/model_utils.py | Python | mit | 2,398 | 0.003336 | from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
IMPORTANT_FIELD_GUESSES = ['id', 'pk', 'name', 'last', 'first', 'full_name', 'summary', 'description', 'user', 'person']
def representation(model, field_names=[], max_fields=None):
"""Uni... | elds = set([f.name for f in model._meta.fields])
for f in model._meta.fields:
field_names += [f.name] if f.name in IMPORTANT_FIELD_GUESSES else []
retval = model.__class__.__name__ + u'('
retval += ', '.join("{}".format(repr(getattr(model, s, '') or ''))
for s... | n(len(field_names), representation.max_fields)])
return retval + u')'
representation.max_fields = 5
def name_similarity():
"""Compute the similarity (inverse distance) matrix between committe names"""
pass
class LongCharField(models.CharField):
"An unlimited-length CharField to satisfy by Django and... |
Data2Semantics/linkitup | linkitup/bio2rdf/plugin.py | Python | mit | 1,736 | 0.021889 | """
Module: plugin.py
Author: Rinke Hoekstra
Created: 2 October 2012
Copyright (c) 2012, Rinke Hoekstra, VU University Amsterdam
http://github.com/Data2Semantics/linkitup
"""
from flask.ext.login import login_required
import re
from linkitup import app
from link | itup.util.baseplugin import plugin, SPARQLPlugin
from linkitup.util.provenance import provenance
app.logger.debug("Initializing DrugBank")
endpoints = ['http://drugbank | .bio2rdf.org/sparql','http://bioportal.bio2rdf.org/sparql','http://kegg.bio2rdf.org/sparql','http://affymetrix.bio2rdf.org/sparql']
@app.route('/bio2rdf', methods=['POST'])
@login_required
@plugin(fields=[('tags','id','name'),('categories','id','name')], link='mapping')
@provenance()
def link_to_bio2rdf(*args,**kwargs... |
timlinux/geonode | geonode/contrib/ows_api/views.py | Python | gpl-3.0 | 2,017 | 0.000496 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# 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 Softwa | re 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 PURPOSE. See the
# GNU General Public License for mo... | ould have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
from django.views.generic import View
from django.conf import settings
from geonode.base.enumerations import LI... |
jballanc/openmicroscopy | docs/hudson/launcher.py | Python | gpl-2.0 | 4,193 | 0.0031 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# $Id$
#
# Copyright 2010 Glencoe Software, Inc. All rights reserved.
# Use is subject to license terms supplied in LICENSE.txt
#
# Hudson launcher script which properly launches the script
# on the right system. This is used by most jobs via:
#
# cd src
# cd docs
# ... | so let them use
# the "linux" label.
if label == "macosx" or label == "matlab":
build_url = build_url.replace("label=%s" % label, "label=linux")
build_url = "%s/%s" % (build_url, "artifact/src/%s.config" % branch)
if os.path.exists(config_file):
print "Removing %s... | remove(config_file)
print "Downloading %s ... " % build_url
ConfigOpener().retrieve(build_url, filename=config_file)
os.environ["ICE_CONFIG"] = config_file
#
# BUILD COMMAND
#
path = os.path.join("docs", "hudson")
base = "OMERO-%s" % job
if "Windows" == platform.system(... |
alexandregz/simian | src/simian/mac/munki/handlers/uauth.py | Python | apache-2.0 | 2,569 | 0.011288 | #!/usr/bin/env python
#
# Copyright 2010 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 require... | Cookie | '] = '%s=%s; secure; httponly;' % (
auth_init.AUTH_TOKEN_COOKIE, output)
self.response.out.write(auth_init.AUTH_TOKEN_COOKIE)
else:
#logging.info('Uauth: unknown token')
raise NotAuthenticated
def post(self):
"""Handle POST.
Because the appengine_rpc module, used by simian.cl... |
charbec1/pokemapfuntimesyay | pogom/pgoapi/pgoapi.py | Python | mit | 6,103 | 0.00934 | """
pgoapi - Pokemon Go API
Copyright (c) 2016 tjado <https://github.com/tejado>
Permission is hereby granted, free of charge, to any person o | btaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furni... | portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTH... |
dimkal/mne-python | mne/beamformer/tests/test_lcmv.py | Python | bsd-3-clause | 15,822 | 0 | import os.path as op
from nose.tools import assert_true, assert_raises
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_array_equal
import warnings
import mne
from mne import compute_covariance
from mne.datasets import testing
from mne.beamformer import lcmv, lcmv_epochs, lcmv_raw, tf_lc... | .argmax(stc_pow)
max_stc = stc.data[idx]
tmax = stc.times[np.argmax(max_stc)]
assert_true(0.09 < tmax < 0.105, tmax)
assert_true(0.9 < np.max(max_stc) < 3., np.max(max_stc))
if fwd is forward:
# Test picking normal orientation (surface source space only)
... | ")
stc_normal.crop(0.02, None)
stc_pow = np.sum(np.abs(stc_normal.data), axis=1)
idx = np.argmax(stc_pow)
max_stc = stc_normal.data[idx]
tmax = stc_normal.times[np.argmax(max_stc)]
assert_true(0.04 < tmax < 0.11, tmax)
assert_true(0.4... |
mkhuthir/learnPython | Book_learning-python-r1.1/ch2/sequences.py | Python | mit | 1,614 | 0.019279 | # sequences.py
# strings
>>> # 4 ways to make a string
>>> str1 = 'This is a string. We built it with single quotes.'
>>> str2 = "This is also a string, but built with double quotes."
>>> str3 = '''This is built using triple quotes,
... so it can span multiple lines.'''
>>> str4 = """This too
... is a multiline one
.... | rst char
'T'
>>> s[5] # indexing at position 5, which is the sixth char
'r'
>>> s[:4] # slicing, we specify only the stop position
'The '
>>> s[4:] # slicing, we specify only the start position
'trouble is you think you have time.'
>>> s[2:14] # slicing, both start and stop positions
'e trouble is'
>>> s[2:14:3] #... | t, stop and step (every 3 chars)
'erb '
>>> s[:] # quick way of making a copy
'The trouble is you think you have time.'
|
bis12/yapwaf | yapwaf/controller.py | Python | mit | 2,107 | 0.001424 | """
The controller base class
"""
from .routes import Route
from .view import View
class Controller(object):
def __init__(self, entity, env):
"""Instantiate a controller with the name of the entity and the
environment dict.
"""
self.entity = entity.strip('/^$')
if not self.... | to run through all of the methods of this class
and see if they've been decorated to be endpoints.
"""
for funcname in dir(self):
func = getattr(self, funcname)
if hasattr(func, '_method') and hasattr(func, '_path'):
self.update_routes(func._method, func._... | its HTTP method
"""
for route in self.routes:
if route.key == matcher:
route.update(method, endpoint)
return
# If the route has not been added to the routes yet
self.routes.append(Route(method, matcher, endpoint))
def route(self, e... |
rizar/attention-lvcsr | lvsr/expressions.py | Python | mit | 2,325 | 0.00129 | from theano import tensor
from theano.tensor.nnet import conv2d
def weights_std(weights, mask_outputs=None):
positions = tensor.arange(weights.shape[2])
expected = (weights * positions).sum(axis=2)
expected2 = (weights * positions ** 2).sum(axis=2)
result = (expected2 - expected ** 2) ** 0.5
if mas... | m(cumsums[1:] - cumsums[:-1], 0).sum(axis=2)
if mask_x:
penalties *= mask_x[1:]
return penalties.sum()
def entropy(weights, mask_x):
entropies = (weights * tensor.log(weights + 1e-7)).sum(axis=2)
entropies *= mask_x
return entropies.sum()
def conv1d(sequences, masks, **kwargs):
"""Wr... | :`~theano.Variable`
(batch_size, length)
masks : :class:`~theano.Variable`
(num_filters, filter_length)
**kwargs
Will be passed to `conv2d`
Returns
-------
result : :class:`~theano.Variable`
(batch_size, num_filters, position)
"""
# For testability
seque... |
alephu5/Soundbyte | environment/lib/python3.3/site-packages/pandas/core/nanops.py | Python | gpl-3.0 | 18,949 | 0.000422 | from pandas import compat
import sys
import itertools
import functools
import numpy as np
from pandas.core.common import isnull, notnull, _values_from_object, is_float
import pandas.core.common as com
import pandas.lib as lib
import pandas.algos as algos
import pandas.hashtable as _hash
import pandas.tslib as tslib
... | else:
result_shape = (values.shape[:axis] +
values.shape[axis + 1:])
result = np.empty(result_shape)
result.fill(0)
return result
if _USE_BOTTLENECK and skipna and | _bn_ok_dtype(values.dtype):
result = bn_func(values, axis=axis, **kwds)
# prefer to treat inf/-inf as NA, but must compute the func
# twice :(
if _has_infs(result):
result = alt(values, axis=axis, skipna=skipna, **... |
ultrabug/uhashring | uhashring/__init__.py | Python | bsd-3-clause | 70 | 0 | from uhashri | ng.ring import HashRing
__all__ = ["Has | hRing", "monkey"]
|
dthoreau/rpi_rally | services/daemons/uniserve-flask/app.py | Python | mit | 302 | 0.003311 | #!/usr/bin/env python3
import connexion
if _ | _name__ == '__main__':
app = connexion.App(__name__, specification | _dir='./swagger/')
app.add_api('swagger.yaml', arguments={'title': 'A second cut at writing the code initial formed in web.py for the PiMoroni UnicornHAT\n'})
app.run(port=8080)
|
grimoirelab/perceval | tests/test_meetup.py | Python | gpl-3.0 | 37,799 | 0.001587 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2020 Bitergia
#
# 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 l... | , mode='r'):
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), filename), mode) as f:
| content = f.read()
return content
def setup_http_server(rate_limit=-1, reset_rate_limit=-1):
"""Setup a mock HTTP server"""
http_requests = []
events_bodies = [
read_file('data/meetup/meetup_events.json', 'rb'),
read_file('data/meetup/meetup_events_next.json', 'rb')
]
events... |
nelsonw2014/CSGOInvCacheConverter | cicc/image.py | Python | mit | 729 | 0.001372 | from PIL import ImageFile, Image
class CSGOInventoryCacheFile(ImageFile.ImageFile):
format = "IIC"
format_description = "CS:GO Inventory Image Cache"
def _open(self):
self.mode = "RGBA"
| self.size = 512, 384
self.tile = [
("raw", (0, 0) + self.size, 0, ("BGRA", 0, 1))
]
def convert_cache_to_image(original_location, new_location):
Image.register_open("IIC", CSGOInventoryCacheFile)
Image.register_extension("IIC", ".iic")
try:
| with open(original_location, "rb") as original_img:
img = Image.open(original_img)
img.save(new_location)
except Exception as e:
raise Exception("Originating file does not exist: ", e) |
itensionanders/distcc | include_server/cache_basics.py | Python | gpl-2.0 | 37,214 | 0.004407 | #! /usr/bin/env python3
# Copyright 2007 Google 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 program... | sh before inserting into the map.
This is useful because it allows us to use + to join this directory
with a relative filename, rather than the slower os.path.join().
RelpathMapToIndex assumes the input is a relative filepath, that is,
one that does not start with /. When combined with DirectoryMapToIndex
entries, + ... | input before
inserting it into the map: resolving symlinks, getting rid of ..'s,
etc. It takes an absolute path as input.
Other Caches
------------
Besides the maps from strings to integers, there are three other caches.
One is the realpath-cache, that takes a filename and returns
os.path.realpath(filename). We cac... |
alexis-roche/nipy | nipy/core/image/__init__.py | Python | bsd-3-clause | 518 | 0.001931 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
The Image class provides the interface which should be used
by users at the application level. The image provides a coordinate map,
and the data itself.
"""
from __future__ import | absolute_import
__docformat__ = 'restructuredtext'
# You'd usually use nipy.core.api for these
from . import image
from .image import Image
from nipy.t | esting import Tester
test = Tester().test
bench = Tester().bench
|
designcc/django-ccpages | ccpages/templatetags/ccpages_tags.py | Python | bsd-3-clause | 921 | 0.005429 | from django import template
from django.conf import settings
from ccpages.models import Page
register = template.Library()
@register.inclusion_tag('ccpages/_js.html')
def ccpages_js():
return {
'STATIC_URL': settings.STATIC_URL,
}
@register.inclusion_tag('ccpages/_css.html')
def ccpages_css():
re... | @register.inclusion_tag('ccpages/_nav_breadcrumb.html')
def ccpages_nav_breadcrumbs(page):
"""returns a breadcrumb"""
return {
'pages': Page.objects.nav_breadcrumbs(pa | ge),
'page': page,
}
@register.inclusion_tag('ccpages/_nav_local.html')
def ccpages_nav_local(page):
"""returns the local nav for a given page's root"""
return {
'pages': Page.objects.nav_local(page)
}
@register.assignment_tag
def ccpages_nav_global():
"""returns the global pages"... |
hexagonist/RedditDaltonizerBot | get_imgur_tokens.py | Python | mit | 540 | 0.003704 | from imgurpython import ImgurClient
import webbrowser
import credentials
client = ImgurClient(cre | dentials.imgur['client_id'], credentials.imgur['client_secret'])
# Authorization flow, pin example (see docs for other auth types)
authorization_url = client.get_auth_url('pin')
print authorization_url
webbrowser.open(authorization_url)
pin = raw_input("Enter pin : ")
credentials = client.authorize(pin, "pin")
pri... | resh token : %s" % credentials["refresh_token"] |
tylerdave/cookiecutter | tests/test_is_vcs_installed.py | Python | bsd-3-clause | 305 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_is_vcs_installed
---------------------
"""
from cookiecutter import vcs
def test_existing_repo_type():
assert vcs.is_vcs_installed("git")
|
def | test_non_existing_repo_type():
assert not vcs.is_vcs_installed("stringthatisntashellcommand")
|
roboime/pyroboime | roboime/utils/mathutils.py | Python | agpl-3.0 | 2,108 | 0.001423 | #
# Copyright (C) 2013-2015 RoboIME
#
# 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 program is distrib... | 963267948966
>>> angle_between((1, 0, 0), (1, 0, 0))
0.0
>>> angle_between((1, 0, 0), (-1, 0, 0))
3.141592653589793
"""
v1_u = unit_vector(v1)
v2_u = unit_v | ector(v2)
angle = np.arccos(np.dot(v1_u, v2_u))
if math.isnan(angle):
if (v1_u == v2_u).all():
return 0.0
else:
return 180
return math.degrees(angle)
|
hugobuddel/orange3 | Orange/tests/test_instance.py | Python | gpl-3.0 | 14,298 | 0.00028 | from math import isnan
import warnings
import unittest
from unittest.mock import MagicMock
import numpy as np
from numpy.testing import assert_array_equal
from Orange.data import \
Instance, Domain, Unknown, Value, \
DiscreteVariable, ContinuousVariable, StringVariable
class TestInstance(unittest.TestCase):... | self.metas)
vals = np.array([42, "M", "B", "X", 43, "Foo"], dtype=object)
inst = Instance(domain, vals)
self.assertIsInstance(inst, Instance)
self.assertIs(inst.domain, domain)
self.assertEqual(inst._x.shape, (2, ))
| self.assertEqual(inst._y.shape, (1, ))
self.assertEqual(inst._metas.shape, (3, ))
assert_array_equal(inst._x, np.array([42, 0]))
self.assertEqual(inst._y[0], 1)
assert_array_equal(inst._metas, np.array([0, 43, "Foo"], dtype=object))
def test_init_xym_list(self):
domain... |
asterix135/whoshouldivotefor | explorer/migrations/0005_auto_20170625_0617.py | Python | mit | 474 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-25 10:17
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('explorer', '0004_district_shapefile_link') | ,
]
operations = [
migrations.AlterField(
model_name='district',
name='shapefile_link' | ,
field=models.URLField(blank=True, null=True),
),
]
|
goerz/pelican | pelican/tests/test_contents.py | Python | agpl-3.0 | 24,186 | 0.001778 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
import six
from sys import platform
import locale
import os.path
from pelican.tests.support import unittest, get_settings
from pelican.contents import Page, Article, Static, URLWrapper, Author, Category
from pelican.settings import DEFA... | dt_date = dt.strftime(DEFAULT_CONFIG['DEFAULT_DATE_FORMAT'])
# dt_date is a byte string in python2, and a unicode string in python3
# Let's make sure it is a unicode string (relies on python 3.3 supporting the u prefix)
if type(dt_date) != type(u''):
# python2:
dt_d... | self.assertEqual(page.locale_date, dt_date )
page_kwargs['settings'] = get_settings()
# I doubt this can work on all platforms ...
if platform == "win32":
locale = 'jpn'
else:
locale = 'ja_JP.utf8'
page_kwargs['settings']['DATE_FORMATS'] = {'jp': (l... |
sirex/datapackage-py | datapackage/resource.py | Python | mit | 11,528 | 0.000087 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import six
import six.moves.urllib as urllib
import tabulator
from .resource_file import (
InlineResourceFile,
LocalResourceFile,
RemoteResourceFi... | fails, it'll fall | back to loading it
as a :class:`Resource`.
Args:
metadata (dict): The dict with the resource's metadata
default_base_path (str, optional): The base path to be used in case
the resource's data is in the local disk. Usually this would be
the base pa... |
Ladeia/QueroJogar | games/migrations/0001_initial.py | Python | mpl-2.0 | 1,032 | 0.002907 | # Generated by Django 2.0.1 on 2018-01-19 00:49
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
| migrations.CreateModel(
name='GameType',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=60)),
],
),
migrations.CreateModel(
... | ('title', models.CharField(max_length=100)),
('description', models.TextField()),
('game_days', models.CharField(max_length=100)),
('game_address', models.TextField()),
('game_type', models.ForeignKey(on_delete='cascade', to='games.GameType')),
... |
janbender/PositionBasedDynamics | data/scenes/CarScene.py | Python | mit | 4,517 | 0.019491 | from SceneGenerator import *
import math
import random
def scale(vec, s):
vec[0] *= s
vec[1] *= s
vec[2] *= s
return vec
s = 1
scene = generateScene('CarScene', camPosition=[1,5,20], camLookat=[0,0,0])
addParameters(scene, h=0.005, maxIter=50, maxIterVel=50, contactTolerance=0.01, gravity=[0,-2,0],... | nsity=wheelDensity)
wheelX4 = add_vector(carX, [-1.75, -0.7, -0.9])
wheel4 = addRigidBody(scene, '../models/sphere.obj', 1, coScale=wheelScale, scale=wheelScale,
translation=wheelX4, dynamic=1, rest=restitution, friction=frict, density=wheelDensity)
motorX1 = add_vector(carX, [1.75, -0.7, 0.7])
... | ody1, wheel1, motorX1, [0, 0, 1], 10.0)
addTargetVelocityMotorHingeJoint(scene, dBody2, wheel2, motorX2, [0, 0, 1], 10.0)
addTargetVelocityMotorHingeJoint(scene, dBody3, wheel3, motorX3, [0, 0, 1], 10.0)
addTargetVelocityMotorHingeJoint(scene, dBody4, wheel4, motorX4, [0, 0, 1], 10.0)
addDamperJoint(scene, chassis, dB... |
owlabs/incubator-airflow | tests/sensors/test_timeout_sensor.py | Python | apache-2.0 | 3,102 | 0.000322 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | =args)
@pytest.mark.quarantined
def test_timeout(self):
t = TimeoutTestSensor(
| task_id='test_timeout',
execution_timeout=timedelta(days=2),
return_value=False,
poke_interval=5,
params={'time_jump': timedelta(days=2, seconds=1)},
dag=self.dag
)
self.assertRaises(
AirflowSensorTimeout,
t.run,... |
MozillaSecurity/FuzzManager | server/crashmanager/migrations/0001_squashed_0020_add_app_permissions.py | Python | mpl-2.0 | 15,946 | 0.000564 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-12-09 00:06
from __future__ import unicode_literals
from django.conf import settings
import django.core.files.storage
from django.db import migrations, models
import django.db.migrations.operations.special
import django.db.models.deletion
import django.util... | ialize=False,
verbose_name="ID",
),
),
("signature", models.TextField()),
("shortDescription", models.CharField(blank=True, max_length=1023)),
],
),
migrations.CreateModel(
name="Bug",
... | "id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("externalId", models.CharField(blank=Tr... |
Urumasi/Flask-Bones | app/data/__init__.py | Python | mit | 4,084 | 0.001959 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from .models import Group, Firma, User, oauth, OAuthSignIn
from random import randint
from app.utils import fake_firma, fake_user
def populate_db(num_users=5, num_groups=15, num_firms=5):
"""
Fills the data ... | n self.searchable]
@prop | erty
def filterables(self):
return [x.name for x in self.filterable]
@property
def colspan(self):
"""Length of all columns."""
return len(self.columns) + len(self.sortable) + len(self.searchable)
def sort(self, field, order):
"""Sorts the data based on a field & order."... |
1065865483/0python_script | Python/01.py | Python | mit | 415 | 0.014164 | # # a=1
# # b=a
# # print(a,b)
# #
# # for i in range(1, | 10,2):
# # print(i)
#
# def fun():
# a=10
# print(a)
# return a +100
#
# sun = fun()
# # sun + 100
#
# print(fun())
# print(sun)
file = open('my file.txt','r') #以读文件的形式打开文件
# content = file.readline() 仅读取第一行
content = file.readlines() #读取所有行,并以列表形式存储
content[3]
print | (content[3])
|
tuxfux-hlp-notes/python-batches | archieves/batch-64/14-oop/sixth.py | Python | gpl-3.0 | 462 | 0.025974 | #!/usr/bin | /python
# bigcinemas
class InvalidAge(Exception):
def __init__(self,age):
self.age = age
def validate_age(age):
if age < 18:
raise InvalidAge(age)
else:
return "Welcome to the movies!!"
age = int(raw_input("please enter your age:"))
#print validate_age(age)
try:
validate_age(age)
# except Exception as ... | te_age(age)
|
vetu11/piloco | bin/paybot.py | Python | gpl-3.0 | 4,476 | 0.007872 | # coding=utf-8
from .token import PAYMENT_PROVIDER_TOKEN
from telegram import (LabeledPrice, InlineKeyboardButton, InlineKeyboardMarkup, ParseMode)
from telegram.ext import (MessageHandler, CallbackQueryHandler, Filters, PreCheckoutQueryHandler, ShippingQueryHandler)
import logging
logger = logging.getLogger(__name__... | ton("Cancelar 💔", callback_data="donation_cancel")],
[InlineKeyboardButton("➖", callback_data="donation_new-%s" % less),
Inli | neKeyboardButton("%s €" % eur_num_to_text, callback_data="donation_custom"),
InlineKeyboardButton("➕", callback_data="donation_new-%s" % more)],
[InlineKeyboardButton("Donar %s € ❤️" % eur_num_to_text, callback_data="donate-%s" % donation_amount)]]
if update.message:
... |
nawawi/wkhtmltopdf | webkit/Source/WebCore/make-file-arrays.py | Python | lgpl-3.0 | 5,529 | 0.000723 | #!/usr/bin/env python
# Copyright (C) 2012 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list ... | ABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
| # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Usage: make-file-arrays.py [--condition=condition-string] --out-h=<header-file-name> --out-cpp=<cpp-file-name> <input-file>...
import os.path
import re
import sys
from optparse import OptionParser
def make_variable_name_and_read(file_name):
... |
Nitrate/Nitrate | src/tcms/core/models/__init__.py | Python | gpl-2.0 | 2,359 | 0.001696 | # -*- coding: utf-8 -*-
# isort: skip_file
from django.contrib.auth.models import User
from django.db import models
# This line cannot move to the below according to the isort linter.
# Resolve it firstly, then apply isort again.
from .base import TCMSContentTypeBaseModel # noqa
from tcms.logs.views import TCMSLog
... | tion(self, who, new_value, field="", original_value=""):
log = TCMSLog(model=self)
log.make(who=who, field=field, original_value=original_value, new_value=new_value)
return log
def clean(self):
strip_types = (
models.CharField,
models.TextField,
m... | ericIPAddressField,
models.SlugField,
)
# FIXME: reconsider alternative solution
# It makes no sense to add field name each time when a new field is
# added and it accepts values containing either \t, \r and \n.
ignored_fields = ("notes", "issue_report_params", "iss... |
Shaps/ansible | lib/ansible/modules/files/file.py | Python | gpl-3.0 | 37,706 | 0.003739 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# Copyright: (c) 2017, Ansible Project
# 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__ ... | l
default: no
follow:
description:
- This flag indicates that filesys | tem links, if they exist, should be followed.
- Previous to Ansible 2.5, this was C(no) by default.
type: bool
default: yes
version_added: '1.8'
modification_time:
description:
- This parameter indicates the time the file's modification time should be set to.
- Should be C(preserve) when n... |
DataONEorg/d1_python | gmn/src/d1_gmn/app/revision.py | Python | apache-2.0 | 18,605 | 0.002687 | # This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you ma... | )
if chain_model:
_set_chain_sid(chain_model, sid)
else:
_add_sciobj(pid, sid, obsoletes_ | pid, obsoleted_by_pid)
_update_sid_to_last_existing_pid_map(pid)
def delete_chain(pid):
pid_to_chain_model = d1_gmn.app.models.ChainMember.objects.get(pid__did=pid)
chain_model = pid_to_chain_model.chain
pid_to_chain_model.delete()
if not d1_gmn.app.models.ChainMember.objects.filter(chain=chain_mo... |
luzfcb/django-configurations | tests/test_values.py | Python | bsd-3-clause | 12,772 | 0.000313 | import decimal
import os
from contextlib import contextmanager
from django.test import TestCase
from django.core.exceptions import ImproperlyConfigured
from mock import patch
from configurations.values import (Value, BooleanValue, IntegerValue,
FloatValue, DecimalValue, ListValue,
... | with env(DJANGO_TEST='2,2'):
self.assertEqual(value.setup('TEST'), ('2', '2' | ))
with env(DJANGO_TEST='2, 2 ,'):
self.assertEqual(value.setup('TEST'), ('2', '2'))
with env(DJANGO_TEST=''):
self.assertEqual(value.setup('TEST'), ())
def test_set_values_default(self):
value = SetValue()
with env(DJANGO_TEST='2,2'):
self.assert... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.