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 |
|---|---|---|---|---|---|---|---|---|
jralls/gramps | gramps/gui/plug/quick/_quicktable.py | Python | gpl-2.0 | 18,614 | 0.003385 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2008 Donald N. Allingham
# Copyright (C) 2009 Douglas S. Blank
# Copyright (C) 2011 Tim G L Lyons
#
# 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
# ... | y = | int(event.y)
path_info = treeview.get_path_at_pos(x, y)
func = None
if path_info is not None:
path, col, cellx, celly = path_info
selection = treeview.get_selection()
store, paths = selection.get_selected_rows()
tpath =... |
weblabdeusto/weblabdeusto | server/src/test/unit/weblab/core/test_alive_users.py | Python | bsd-2-clause | 6,851 | 0.003066 | #!/usr/bin/env python
#-*-*- encoding: utf-8 -*-*-
#
# Copyright (C) 2005 onwards University of Deusto
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# This software consists of contributions made by many individual... | auc.check_expired_users()
self.assertEquals(0, len(expired_users))
def test_three_sessions_one_expired(self):
session_id1 = self.create_session(self.tm.time())
session_id2 = self.create_session(self.tm.time() - 3600) # expired
session_id3 = self.create_session(self.tm.time())
... | .assertEquals(1, len(expired_users))
self.assertEquals(session_id2, expired_users[0])
expired_users = self.auc.check_expired_users()
self.assertEquals(0, len(expired_users))
# Some time passes with same results
self.tm.set(self.tm.time() + self.auc._min_time_between_checks + 1)... |
tragiclifestories/django | tests/runtests.py | Python | bsd-3-clause | 16,531 | 0.001149 | #!/usr/bin/env python
import logging
import os
import shutil
import subprocess
import sys
import tempfile
import warnings
from argparse import ArgumentParser
import django
from django.apps import apps
from django.conf import settings
from django.db import connection
from django.test import TestCase, TransactionTestCas... | path.abspath(os.path.dirname(upath(__file__)))
TEMPLATE_DIR = os.path.join(RUNTESTS_DIR, 'templates')
# Create a specific subdirectory for the duration of the test suite.
TMPDIR = tempfile.mkdtem | p(prefix='django_')
# Set the TMPDIR environment variable in addition to tempfile.tempdir
# so that children processes inherit it.
tempfile.tempdir = os.environ['TMPDIR'] = TMPDIR
SUBDIRS_TO_SKIP = [
'data',
'import_error_package',
'test_discovery_sample',
'test_discovery_sample2',
'test_runner_dep... |
dcf21/4most-4gp-scripts | src/scripts/degrade_spectra/degrade_library_with_rv.py | Python | mit | 9,491 | 0.005163 | #!../../../../virtualenv/bin/python3
# -*- coding: utf-8 -*-
# NB: The shebang line above assumes you've installed a python virtual environment alongside your working copy of the
# <4most-4gp-scripts> git repository. It also only works if you invoke this python script from the directory where it
# is located. If these... | t (which will share the same uid / name)
search_criteria = input_spectra_constraints.copy()
search_criteria[spectrum_matching_field] = object_name
search_criteria['continuum_normalised'] = 1
continuum_normalised_spectrum_id = input_library.search | (**search_criteria)
# Check that continuum-normalised spectrum exists and is unique
assert len(continuum_normalised_spectrum_id) == 1, "Could not find continuum-normalised spectrum."
# Load the continuum-normalised version
input_spectrum_continuum_normalised_arr = input_library.open(id... |
fredmorcos/attic | snippets/python/lex-parse/loader.py | Python | isc | 963 | 0.031153 | class Loader:
def __init__(self, options):
self.options = options
self.error = False
self.error_message = ''
self.input_file = None
self.output_file = None
if options.input_filename == '' or options.input_filename == Non | e:
self.error = True
self.error_message = 'Please provide an input file'
return
if options.output_filename == '' or options.output_filename == None:
self.error = True
self.error_message = 'Please provide an output file'
return
if options.input_filename == options.output_filename:
s | elf.error = True
self.error_message = 'Do not provide same input and output files'
return
def open_input(self):
self.input_file = file(self.options.input_filename, 'r')
return self.input_file
def open_output(self):
self.output_file = file(self.options.output_filename, 'w')
return self.output_file
de... |
TheTimmy/spack | lib/spack/spack/schema/mirrors.py | Python | lgpl-2.1 | 1,811 | 0 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | ails.
#
# You should have received a copy of the GNU Lesser Gen | eral 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
##############################################################################
"""Schema for mirrors.yaml configuration file.
.. literalinclude:: ../spack/schema/m... |
Runscope/pysaml2 | src/saml2/entity_category/refeds.py | Python | bsd-2-clause | 345 | 0.005797 | __author__ = 'rolandh'
RESEARCH_AND_SCHOLARSHIP = "http://refeds.org/category/research-and-scholarship"
RELEASE = {
"": ["eduPersonTargetedID"],
RESEARCH_AND_SCHOLARSHIP: [ | "eduPersonPrin | cipalName",
"eduPersonScopedAffiliation", "mail",
"givenName", "sn", "displayName"]
}
|
HybridF5/jacket | jacket/tests/compute/functional/api_sample_tests/test_consoles.py | Python | apache-2.0 | 2,234 | 0 | # Copyright 2012 Nebula, Inc.
# Copyright 2013 IBM Corp.
#
# 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... | plesJsonTest, self).setUp()
self.flags(console_public_hostname='fake')
self.flags(console_host='fake')
self.flags(console_driver='compute.console.fake.FakeConsoleProxy')
self.console = self.start_service('console', host='fake')
def _create_consoles(self, server_uuid):
respon... | server_uuid,
'consoles-create-req', {})
self.assertEqual(response.status_code, 200)
def test_create_consoles(self):
uuid = self._post_server()
self._create_consoles(uuid)
def test_list_consoles(self):
uuid = self._post_server()
self._cr... |
philgyford/django-spectator | spectator/reading/migrations/0001_initial.py | Python | mit | 10,589 | 0.001417 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-17 17:14
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import spectator.core.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
("spectator_co... | "isbn_uk",
models.CharField(
blank=True,
help_text="e.g. '0356500489'.",
max_length=20,
verbose_name="UK ISBN",
),
),
(
| "isbn_us",
models.CharField(
blank=True,
help_text="e.g. '0316098094'.",
max_length=20,
verbose_name="US ISBN",
),
),
(
"n... |
kdart/pycopia3 | core/pycopia/table.py | Python | apache-2.0 | 9,285 | 0.003016 | #!/usr/bin/python3.4
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by app... | .headings.index(x)
if isinstance(y, str):
y = self.rownames.index(y)
return x, y
# this row object is returned when iterating over the table. It allows indexing
# by header name.
class TableRow(list):
def __init | __(self, init, headings, label=""):
super(TableRow, self).__init__(init)
self.label = label
self.headings = headings
def __getitem__(self, key):
kt = type(key)
if kt is str:
i = self.headings.index(key)
return list.__getitem__(self, i)
elif kt... |
fogelomer/cloudify-filebeat-plugin | filebeat_plugin/tasks.py | Python | apache-2.0 | 7,991 | 0.000501 | ########
# Copyright (c) 2014 GigaSpaces Technologies 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... | ))
ctx.logger.info('Downloading filebeat...')
if not download_url:
if distro in ('ubuntu', 'debian'):
download_url = 'https://download.elastic.co/beats/filebeat/' + \
'filebeat_1.2.3_am | d64.deb'
elif distro in ('centos', 'redhat'):
download_url = 'https://download.elastic.co/beats/filebeat/' + \
'filebeat-1.2.3-x86_64.rpm'
else:
raise exceptions.NonRecoverableError(
'''Error! distribution is not supported.
Ubuntu, ... |
sysuwuhaibin/vatus | vatus/testcases/test_education/test_user_management/test_E83_modify_the_students_information.py | Python | apache-2.0 | 7,684 | 0.003271 | # -*- coding: utf-8 -*-
import time
import unittest
from selenium import webdriver
import settings
class ModifyStudentInfo(unittest.TestCase):
def setUp(self):
self.driver = None
self.base_url = settings.test_parameters.get("education_base_url")
def test_E83_modify_the_student... | ).clear()
driver.find_element_by_id("fullname").\
send_keys("1234567890123456789012345678901234567890123456789012345678901234567890")
driver.find_element_by_id("email").clear()
driver.find_element_by_id("email").\
send_keys("1234567890123456789012... | nd_element_by_id("confirm_action").click()
time.sleep(2)
self.assertEqual("长度不超过64个字", driver.find_element_by_id("fullname-error").text)
self.assertEqual("长度1-64个字", driver.find_element_by_id("email-error").text)
###########################################
... |
FeiZhan/Algo-Collection | answers/leetcode/Valid Sudoku/Valid Sudoku.py | Python | mit | 1,115 | 0 | class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
for i in range(len(board)):
sudoku = {}
for j in range(len(board[i])):
| if board[i][j] in sudoku:
return False
elif '.' != board[i][j]:
sudoku[board[i][j]] = 1
for i in range(len(board[0])):
sudoku = {}
for j in range(len(board)):
if board[j][i] in sudoku:
retur... | sudoku = {}
for m in range(len(board) / 3):
for n in range(len(board) / 3):
if board[i * 3 + m][j * 3 + n] in sudoku:
return False
elif '.' != board[i * 3 + m][j * 3 + n]:
... |
geminy/aidear | snippets/cppfunc/cppcheck/cppcheck-1.80/htmlreport/setup.py | Python | gpl-3.0 | 536 | 0.001866 | #!/usr/bin/env python
from setuptools import setup
with open('README.txt') as f:
readme = f.read()
setup(
name="cppchec | k",
description='Python script to parse the XML (version 2) output of ' +
'cppcheck and generate an HTML report using Pygments for syntax ' +
'highlighting.',
long_description=readme,
author='Henrik Nilsson | ',
url='https://github.com/danmar/cppcheck',
license='GPL',
scripts=[
"cppcheck-htmlreport",
],
install_requires=['Pygments']
)
|
ismailsunni/NewsAnalytic | libs/__init__.py | Python | gpl-2.0 | 153 | 0.006536 | __author__ = 'user'
__project_name = 'NewsA | nalytic'
__filename = '__init__.py'
__date__ = '03/02/14'
__copyright__ = 'imajimatika@gmail.com'
__doc__ = '' | |
cvsuser-chromium/native_client | PRESUBMIT.py | Python | bsd-3-clause | 6,342 | 0.008042 | # Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Documentation on PRESUBMIT.py can be found at:
# http://www.chromium.org/developers/how-tos/depottools/presubmit-scripts
import os.path
import sy... | ted source,
# which may not follow our conventions.
'src/trusted/validator_x86/gen',
'src/trusted/validator/x86/decoder/gen',
'src/trusted/validator/x86/decoder/generator/gen',
'src/trusted/vali | dator/x86/ncval_seg_sfi/gen',
'src/trusted/validator_arm/gen',
'src/trusted/validator_ragel/gen',
]
def NaClTopDir():
# git-cl and gcl run PRESUBMIT.py with the current directory set to
# the native_client directory (which may have a different basename
# in a standalone checkout).
return os.getcwd(... |
wl-net/dataview | api/views.py | Python | gpl-2.0 | 6,096 | 0.009514 | from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
import django_filters
from rest_framework import viewsets
from rest_framework.response import Response
from api.serializers import UserSerializer, AddressSerializer, DestinationSerializer, GuestSerializer, MessageSerializer, Op... | {'request': request})
return Response(serializer.data)
class OpenHourViewSet(viewsets.ModelViewSet):
queryset = OpenHour.objects.all() |
serializer_class = OpenHourSerializer
# other applications
from sensors.models import Sensor, SensorValue
from api.serializers import SensorSerializer, SensorValueSerializer
class SensorViewSet(viewsets.ModelViewSet):
queryset = Sensor.objects.all()
serializer_class = SensorSerializer
class SensorV... |
andredalton/imecare | imecare/wsgi.py | Python | mit | 391 | 0 | """
WSGI config for imecare project. |
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "imecare.settings")
ap... | t_wsgi_application()
|
shinnova/lcurse | modules/waitdlg.py | Python | unlicense | 13,439 | 0.002009 | from PyQt5 import Qt
from bs4 import BeautifulSoup
import urllib.parse
from urllib.request import build_opener, HTTPCookieProcessor, HTTPError
from http import cookiejar
import zipfile
import defines
import os
import re
import time
from _thread import start_new_thread
from threading import Lock
from subprocess import c... | ib/2.6') will *not* work
opener.addheaders = [('User-Agent', 'Mozilla/5.0'), ]
def OpenWithRetry(url):
count = 0
maxcount = 5
# Retry 5 times
while count < maxcount:
try:
response = opener.open(urllib.parse.urlparse(urllib.parse.quote(url, ':/')).geturl())
return resp... | ption as e:
print("Could not open '{}', retrying... ({})".format(url, count))
count = count + 1
time.sleep(1)
if count >= maxcount:
raise
class CheckDlg(Qt.QDialog):
checkFinished = Qt.pyqtSignal(Qt.QVariant, bool, Qt.QVariant)
closeSignal = Qt... |
arpho/mmasgis5 | mmasgis/ProvinciaPg.py | Python | mit | 558 | 0.050179 | from Utb import Utb
"""
astrae le utb di tipo provincia p | er postgres
"""
class ProvinciaPg(Utb):
def __init__(self,header="header",istat=-1):
Utb.__init__(self, header, 'pro', istat)
def getSelect(self):
query=" SELECT tc_istat_id FROM tc_istat JOIN province ON tc_istat.tc_provincia_id = province.tc_provincia_id WHERE province.codice = {0}".format(self.istat)
re... | e |
CSIRT-MU/Stream4Flow | applications/statistics/hosts_profiling/spark/host_daily_profile.py | Python | mit | 13,684 | 0.00475 | # -*- coding: utf-8 -*-
#
# MIT License
#
# Copyright (c) 2017 Michal Stefanik <stefanik dot m@mail.muni.cz>, Tomas Jirsik <jirsik@ics.muni.cz>
# Institute of Computer Science, Masaryk University
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated document... | # collection interval of all aggregations as items in temporal array
INCREMENT = 0
# temporal methods resolving the temporal | array consistency and construction:
def increment():
"""
increments the global counter that should keep consistent with the duration of the app run in hours
"""
global INCREMENT
INCREMENT += 1
def modulate_position(timestamp):
"""
counts the position in time-sorted log of IP activity as ... |
DavidMulder/simple_browse | simple_browse.py | Python | gpl-2.0 | 8,391 | 0.004886 | #!/usr/bin/python
import sys, os, urllib, argparse, base64, time, threading, re
from gi.repository import Gtk, WebKit, Notify
webView = None
def refresh(widget, event):
global webView
webView.reload()
window_title = ''
def HandleTitleChanged(webview, title):
global window_title
window_title = title
... | #webView.connect('notify::title', HandleTitleChanged)
webVi | ew.connect('mime-type-policy-decision-requested', HandleMimeType)
webView.connect('load-finished', prefill_password)
win.set_title('')
# Add the Refresh button
fixed = Gtk.Fixed()
fixed.set_halign(Gtk.Align.START)
fixed.set_valign(Gtk.Align.START)
overlay.add_overlay(fixed)
fixed.show()... |
Alexhuszagh/Lan-Huang-Scripts | python/make_decoys.py | Python | gpl-3.0 | 4,946 | 0.000202 | #!/usr/bin/env python
'''
Copyright (C) 2015 The Regents of the University of California.
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 late... | andom.shuffle(seq)
return ''.join(seq)
class Writer(ParseFasta):
'''Writes the new FASTA sequence information to file'''
def __init__(self, fasta, outfile):
super(Writer, self).__init__(fasta)
self.outfile = outfile
for spacers, metadata, sequence in self:
while... | tfile)
print(sequence, file=self.outfile)
def main():
'''On script execution'''
with open(ARGS.fasta) as fasta:
with open(ARGS.out, 'w') as out:
Writer(fasta, out)
if __name__ == '__main__':
main()
|
bjones1/enki | enki/plugins/session.py | Python | gpl-2.0 | 4,134 | 0.000726 | """
session --- Reopen files when starting
======================================
"""
from PyQt5.QtCore import QTimer
import os.path
from enki.core.core import core
from enki.core.defines import CONFIG_DIR
import enki.core.json_wrapper
_AUTO_SAVE_INTERVAL_MS = 60 * 1000
def getSessionFilePath():
if core.comma... | gs()['session_name']
elif core.commandLineArgs()['auto-session-name']:
session_name = os.getcwd().split(os.path.sep)[-1]
elif 'ENKI_SESSION' in os.environ:
session_name = os.environ['ENKI_SESSION']
else:
session_name = ''
if session_name:
session_filename = 'session_{}.j... | for char in r'<>:"/\|?*' + ' ': # reserved characters for file name on Windows. By MSDN. And space
session_filename = session_filename.replace(char, '_')
else:
session_filename = 'session.json'
return os.path.join(CONFIG_DIR, session_filename)
_SESSION_FILE_PATH = getSessionFilePath()... |
onepesu/django_transmission | core/urls.py | Python | mit | 315 | 0 | from django.conf.urls import include
from dja | ngo.contrib import admin
from django.urls import path
app_name = "transmission"
urlpatterns = [
path("admin/", admin.site.urls),
path("torrents/", include("torrents.urls", nam | espace="torrents")),
path("shows/", include("shows.urls", namespace="shows")),
]
|
ennoborg/gramps | gramps/plugins/db/dbapi/dbapi.gpr.py | Python | gpl-2.0 | 1,381 | 0.016655 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2015 Douglas Blank <doug.blank@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, o... | asec | lass = 'DBAPI',
authors=['Doug Blank'],
authors_email=["doug.blank@gmail.com"],
)
|
google-research/google-research | xirl/xirl/evaluators/base.py | Python | apache-2.0 | 3,670 | 0.008174 | # 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... | nt the `_evaluate` method.
"""
def __init__(self, | inter_class):
self.inter_class = inter_class
@abc.abstractmethod
def evaluate(self, outs):
"""Evaluate the downstream task in embedding space.
Args:
outs: A list of outputs generated by the model on the downstream dataset.
:meta public:
"""
pass
|
jeremiedecock/snippets | python/pyqt/pyqt5/widget_QDateEdit.py | Python | mit | 2,406 | 0.002494 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# S | ee http://doc.qt.io/qt-5/qdateedit.html#details
import sys
import datetime
from PyQt5.QtWidgets import QApplication, QWidget, QDateEdit, QPushButton, QVBoxLayout
class Window(QWidget):
def __init__(self):
super().__init__()
# Make widgets #################
self.edit1 = QDateEdit()
... | ateEdit()
self.edit1.setMinimumDate(datetime.date(year=2017, month=9, day=1))
self.edit2.setMinimumDate(datetime.date(year=2017, month=9, day=1))
self.edit3.setMinimumDate(datetime.date(year=2017, month=9, day=1))
self.edit1.setMaximumDate(datetime.date(year=2020, month=9, day=1))
... |
pombredanne/pants | tests/python/pants_test/engine/test_scheduler.py | Python | apache-2.0 | 12,738 | 0.005652 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import uni... | ])
| @unittest.skip('Skipped to expedite landing #3821; see: #4020.')
def test_gen(self):
build_request = self.request(['gen'], self.thrift)
root, = self.build(build_request)
# Root: expect the synthetic GenGoal product.
self.assert_root(root, self.thrift, GenGoal("non-empty input to satisfy the Goal cons... |
gaga3966/django-timepiece | timepiece/crm/views.py | Python | mit | 21,298 | 0.001174 | import datetime
from dateutil.relativedelta import relativedelta
import urllib
from django.contrib import messages
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse, reverse_lazy
from django.db import ... | _object().pk,))
return_url += '?%s' % urllib.urlencode(request_get)
return redirect(return_url)
return super(ProjectTimesheet, self).get(*args, **kwargs)
def get_context_data(self, **kwargs):
context = super(ProjectTimesheet, self).get_context_data(**kwargs)
project ... | ar_month_form.save()
else:
date = utils.add_timezone(datetime.datetime.today())
from_date = utils.get_month_start(date).date()
to_date = from_date + relativedelta(months=1)
entries_qs = Entry.objects
entries_qs = entries_qs.timespan(from_date, span='month').fi... |
matejc/searx | searx/engines/frinkiac.py | Python | agpl-3.0 | 1,303 | 0.002302 | """
Frinkiac (Images)
@website https://www.frinkiac.com
@provide-api no
@using-api no
@results JSON
@stable no
@parse url, title, img_src
"""
from json import loads
from urllib import urlencode
categories = ['images']
BASE = 'https://frinkiac.com/'
SEARCH_URL = '{base}api/search?{query}'
RESULT... | query=urlencode({'p': 'caption', 'e': episode, 't': timestamp})),
'title': episode,
'content': '',
| 'thumbnail_src': THUMB_URL.format(base=BASE, episode=episode, timestamp=timestamp),
'img_src': IMAGE_URL.format(base=BASE, episode=episode, timestamp=timestamp)})
return results
|
PadaliaRushabh/EasyMail | src/easymail_lib/Email.py | Python | gpl-2.0 | 6,371 | 0.024329 | """
TODO: better security for password and username
get contacts from different account
store password in secure way
get feedback from software if email is successfully devlivered
get multiple attachment paths
if a directory contains directory then error appears that directory cannot be op... | end_email(self):
auth = Security(self.username , self.password)
| if self.attachment_path is not None:
attachment = Attachment(self.attachment_path)
email = Email(self.from_address , self.to_address , self.subject , self.body ,self.email_server ,attachment)
else:
email = Email(self.from_address , self.to_address , self.subject , self.body ,email_serve... |
sinnwerkstatt/landmatrix | apps/graphql/resolvers/formfields.py | Python | agpl-3.0 | 799 | 0.001252 | from t | yping import Any
from django.utils import translation
from graphql import GraphQLResolveInfo
from apps.landmatrix.forms.deal import DealForm
from apps.landmatrix.forms.deal_submodels import (
contract_fields,
location_fields,
datasource_fields,
)
from apps.landmatrix.forms.investor import InvestorForm, In... | rm().get_fields(),
"location": location_fields,
"contract": contract_fields,
"datasource": datasource_fields,
"investor": InvestorForm().get_fields(),
"involvement": InvestorVentureInvolvementForm().get_fields(),
}
|
snakeleon/YouCompleteMe-x86 | python/ycm/tests/omni_completer_test.py | Python | gpl-3.0 | 22,455 | 0.048163 | # encoding: utf-8
#
# Copyright (C) 2016 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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... | hat the results are not filtered, as we expect the
# omniufunc or vim itself to do this filtering
eq_( results | , omnifunc_result )
@ExpectedFailure( 'We ignore the result of the call to findstart and use our '
'own interpretation of where the identifier should be',
contains_string( "test_omnifunc(0,'t')" ) )
@YouCompleteMeInstance( { 'cache_omnifunc': 1 } )
def OmniCompleter_GetCompletsions... |
google-research/google-research | dual_dice/algos/base.py | Python | apache-2.0 | 3,612 | 0.006091 | # 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... | nt_function
import abc
import numpy as np
import six
from typing import Any, Callable
import dual_dice.policy as policy_lib
import dual_dice.transition_data as transition_data_lib
@six.add_metaclass(abc.ABCMeta)
class BaseAlgo(object):
"""Abstract class representing algorithm for off-policy corrections."""
@a... | y evaluation given experience and policy."""
@abc.abstractmethod
def estimate_average_reward(self, data, target_policy):
"""Estimates value (average per-step reward) of policy."""
def close(self):
pass
def estimate_value_from_state_ratios(
data,
target_policy,
gamma,
state_ratio_fn):
... |
gewethor/Chartreuse-Back-End | api/migrations/0004_auto_20160706_2133.py | Python | gpl-3.0 | 580 | 0.001724 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-06 21:33
from __fut | ure__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0003_l | ike_user'),
]
operations = [
migrations.AlterField(
model_name='like',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user', to=settings.AUTH_USER_MODEL),
),
]
|
maia-dev/statFMB | statFMB/upload.py | Python | gpl-3.0 | 20,623 | 0.012581 | import xlrd
from datetime import date, datetime
from openpyxl import load_workbook, worksheet
from openpyxl.workbook import Workbook
from openpyxl.reader.excel import load_workbook, InvalidFileException
from statFMB.views import db, current_user, app
from statFMB.models import *
from statFMB.utils import clear_str, r... | ile.filename))
|
##load uploaded file and sheets
try:
file_ext = new_file.filename[-4:]
if file_ext == ".xls":
wb = open_xls_as_xlsx(new_file)
else:
wb = load_workbook(new_file, read_only = False, data_only = True)
except Exception as err:
print (err)
return "... |
GillesArcas/numsed | numsed/__init__.py | Python | mit | 118 | 0.025424 | __all__ = ['checker', | 'transformer', 'codegen', 'common', 'numsed','numsed_lib','op | coder', 'sedcode', 'snippet_test']
|
phocean/netios | test/jc.py | Python | gpl-2.0 | 789 | 0.057034 | #!/usr/bin/env python
# coding=UTF-8
import os
from multiprocessing import Process, Queue, current_process, Lock
from time import sleep
def ntptest(host):
sleep (10)
return 0
def worker(queue,lock):
lock.acquire()
print 'starting child process with id: ', os.getpid()
print 'parent process:', os.getppid()
lock.... | f main():
PROCESSUS = 3
hosts = ["10.10.10.100","10.10.10.99","127.0.0.1","192.168.22.2", "172.15.1.1"]
queue = Queue()
lock = Lock()
for host in hosts:
print ">>> Host %s"%host
queue.put(host)
for i in hosts:
proc = Process(target=worker, args=(queue,lock))
proc.start()
#pro | c.join()
if __name__ == '__main__':
main()
|
openstack/keystone | keystone/api/discovery.py | Python | apache-2.0 | 4,259 | 0 | # 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
# d... |
import http.client
from oslo_serialization import jsonutils
from keystone.common import json_home
import keystone.conf
from keystone.server import flask as ks_flask
CONF = keystone.conf.CONF
MEDIA_TYPE_JSON = 'appl | ication/vnd.openstack.identity-%s+json'
_DISCOVERY_BLUEPRINT = flask.Blueprint('Discovery', __name__)
def _get_versions_list(identity_url):
versions = {}
versions['v3'] = {
'id': 'v3.14',
'status': 'stable',
'updated': '2020-04-07T00:00:00Z',
'links': [{
'rel': 'sel... |
digibyte/digibyte | test/functional/feature_fee_estimation.py | Python | mit | 11,548 | 0.003117 | #!/usr/bin/env python3
# Copyright (c) 2009-2019 The Bitcoin Core developers
# Copyright (c) 2014-2019 The DigiByte Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test fee estimation code."""
from decimal import... | 005"), min_fee, min_fee)
tx_kbytes = (len(txhex) // 2) / 1000.0
self.fees_per_kb.append(float(fee) / tx_kbytes)
sync_mempools(self.nodes[0:3], wait=.1)
mined = mining_node.getblock(mining_node.gene | rate(1)[0], True)["tx"]
sync_blocks(self.nodes[0:3], wait=.1)
# update which txouts are confirmed
newmem = []
for utx in self.memutxo:
|
clouserw/zamboni | mkt/site/log.py | Python | bsd-3-clause | 18,674 | 0.000428 | from inspect import isclass
from django.conf import settings
from django.core.files.storage import get_storage_class
from celery.datastructures import AttributeDict
from tower import ugettext_lazy as _
__all__ = ('LOG', 'LOG_BY_ID', 'LOG_KEEP',)
class _LOG(object):
action_class = None
class CREATE_ADDON(_LOG... | )
class USER_DISABLE(_LOG):
id = 8
format = _(u'{addon} disabled.')
keep = True
class USER_ENABLE(_LOG):
id = 9
format = _(u'{addon} enabled.')
keep = True
# TODO(davedash): Log these types when pages are present
class SET_PUBLIC_STATS(_LOG):
id = 10
format = _(u'Stats set public f... | Log these types when pages are present
class UNSET_PUBLIC_STATS(_LOG):
id = 11
format = _(u'{addon} stats set to private.')
keep = True
class CHANGE_STATUS(_LOG):
id = 12
# L10n: {0} is the status
format = _(u'{addon} status changed to {0}.')
keep = True
class ADD_PREVIEW(_LOG):
id =... |
Remeic/Squozy | redirector/views.py | Python | mit | 2,951 | 0.019993 | from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from .models import UrlShrinked
from .forms import UrlShrinkedForm
from django.shortcuts import render, get_object_or_404,redirect
from django.contrib.sites.shortcuts import get_current_site
from django.http import JsonResponse,HttpR... | ST)
if form.is_valid():
url=form.save(commit=False)
url.save()
| url.publish()
tmp="/"+url.shrinked_code+"/"
full_url = ''.join(['http://', get_current_site(request).domain,tmp])
return render(request, 'redirector/shrink_detail.html', {'url_skrink': full_url})
else:
form=UrlShrinkedForm()
return render(request, 'redirector/crea... |
killuazhu/vimrc | sources_non_forked/deoplete.nvim/rplugin/python3/deoplete/source/member.py | Python | mit | 2,077 | 0.002407 | # ============================================================================
# FILE: member.py
# AUTHOR: Shougo Matsushita <Shougo.Matsu | at gmail.com>
# License: MIT license
# ============================================================================
from .base import Base
import re
from deoplete.util import (
convert2list, parse_buffer_pattern, set_pattern, getlines)
class Source(Base):
def __init__(self, vim):
super | ().__init__(vim)
self.name = 'member'
self.mark = '[M]'
self.min_pattern_length = 0
self._object_pattern = r'[a-zA-Z_]\w*(?:\(\)?)?'
self._prefix = ''
prefix_patterns = {}
set_pattern(prefix_patterns,
'_', '\.')
set_pattern(prefix_pa... |
ooici/marine-integrations | mi/dataset/parser/test/test_mopak_o_dcl.py | Python | bsd-2-clause | 28,907 | 0.0055 | #!/usr/bin/env python
"""
@package mi.dataset.parser.test.test_mopak_o_dcl
@file marine-integrations/mi/dataset/parser/test/test_mopak_o_dcl.py
@author Emily Hahn
@brief Test code for a mopak_o_dcl data parser
"""
import ntplib
import struct
import os
from datetime import datetime
import time
from nose.pl... |
self.state_callback_value = state
self.file_ingested_value = file_ingested
def pub_callback(self, pub):
""" Call back method to watch what comes in via the publish callback """
self.publish_callback_value = pub
def except_callback(self, exception):
"""
... | f setUp(self):
ParserUnitTestCase.setUp(self)
self.config = {
DataSetDriverConfigKeys.PARTICLE_MODULE: 'mi.dataset.parser.mopak_o_dcl',
DataSetDriverConfigKeys.PARTICLE_CLASS: ['MopakODclAccelParserDataParticle',
'Mopa... |
woddx/privacyidea | privacyidea/api/policy.py | Python | agpl-3.0 | 16,381 | 0.000427 | # -*- coding: utf-8 -*-
#
# http://www.privacyidea.org
# (c) cornelius kölbel, privacyidea.org
#
# 2014-12-08 Cornelius Kölbel, <cornelius@privacyidea.org>
# Complete rewrite during flask migration
# Try to provide REST API
#
# privacyIDEA is a fork of LinOTP. Some code is adapted from
# the syste... | /policy/pol1 HTTP/1.1
Host: example.com
Accept: application/json
scope=admin
realm=realm1
action=enroll, disable
**Example response**:
.. sourcecode:: http
HTTP/1.0 200 OK
Content-Length: 354
Content-Type: application/json
{
"id": 1,... | "version": "privacyIDEA unknown"
}
"""
res = {}
param = request.all_data
if not re.match('^[a-zA-Z0-9_.]*$', name):
raise Exception(_("The name of the policy may only contain "
"the characters a-zA-Z0-9_."))
if name.lower() == "check":
raise Except... |
wxgeo/geophar | wxgeometrie/sympy/codegen/tests/test_cfunctions.py | Python | gpl-2.0 | 4,553 | 0.001098 | from sympy import symbols, Symbol, exp, log, pi, Rational, S
from sympy.codegen.cfunctions import (
expm1, log1p, exp2, log2, fma, log10, Sqrt, Cbrt, hypot
)
from sympy.core.function import expand_log
def test_expm1():
# Eval
assert expm1(0) == 0
x = Symbol('x', real=True, finite=True)
# Expand ... | Expand
assert Cbrt(x).expand(func=True) - x**Rational(1, 3) == 0
# Diff
assert Cbrt(42*x).diff(x) - 42*(42*x)**(Rational(1, 3) - 1)/3 == 0
assert Cbrt(42*x).diff(x) - Cbrt(42*x).exp | and(func=True).diff(x) == 0
def test_Sqrt():
x = Symbol('x')
# Expand
assert Sqrt(x).expand(func=True) - x**Rational(1, 2) == 0
# Diff
assert Sqrt(42*x).diff(x) - 42*(42*x)**(Rational(1, 2) - 1)/2 == 0
assert Sqrt(42*x).diff(x) - Sqrt(42*x).expand(func=True).diff(x) == 0
def test_hypot():
... |
crunchmail/munch-core | src/munch/core/migrations/0001_initial.py | Python | agpl-3.0 | 1,697 | 0.003536 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-06 10:09
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import munch.core.utils.models
class Migration(migrations.Migration):
initial = True
dep... | b.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='author')),
],
options={
'verbose_name': 'category',
'verbose_name_plural': 'categories',
'abstract': False,
'default_permissions': ('view', 'add', 'c | hange', 'delete', 'view_mine', 'change_mine', 'delete_mine', 'view_organizations', 'change_organizations', 'delete_organizations'),
},
bases=(models.Model, munch.core.utils.models.OwnedModelMixin),
),
migrations.CreateModel(
name='RawMail',
fields=[
... |
rodrigomalk/Novos-Bandeirantes | backend/appengine/routes/criar.py | Python | mit | 1,831 | 0.003823 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from config.template_middleware import TemplateResponse
from gaecookie.decorator import no_csrf
from gaepermission.decorator import login_not_required
from tekton impor | t router
from tekton.gae.middleware.redirect import RedirectRes | ponse
from models import Game, Quest
from forms import GameForm, QuestForm
@login_not_required
@no_csrf
def index():
contexto = {'criar_modelo': router.to_path(salvar)}
return TemplateResponse(contexto)
titulo = ''
def salvar(**propriedades):
global titulo
game_form = GameForm(**propriedades)
t... |
legalsylvain/oca-custom | __unported__/oca_freestore/models/github_repository_branch.py | Python | agpl-3.0 | 11,894 | 0.000336 | # -*- coding: utf-8 -*-
# Copyright (C) 2016-Today: Odoo Community Association (OCA)
# @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
import os
from git import Repo
from subprocess import check_output
from datetime import ... | 'repository_id': repository_id})
return repository_branch
def _download_code(self):
for repository_branch in self:
path = self._get_local_path(repository_branch.complete_name)
if not os.path.exists(path):
_logger.info(
"Cloning new r... | os.makedirs(path)
os.system(
"cd %s &&"
" git clone https://github.com/%s.git -b %s ." % (
path,
repository_branch.repository_id.complete_name,
repository_branch.name))
... |
pescobar/easybuild-easyblocks | easybuild/easyblocks/m/mpich.py | Python | gpl-2.0 | 7,319 | 0.003006 | ##
# Copyright 2009-2020 Ghent University, Forschungszentrum Juelich
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# the... | POSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EasyBuild. If not, see <http://www.gnu.org/licenses/>.
##
"""
EasyBuild support for building and installing the MPICH MPI library and derivatives, implemented as an easyblock... | (Ghent University)
@author: Jens Timmerman (Ghent University)
@author: Damian Alvarez (Forschungszentrum Juelich)
@author: Xavier Besseron (University of Luxembourg)
"""
import os
from distutils.version import LooseVersion
import easybuild.tools.environment as env
from easybuild.easyblocks.generic.configuremake impor... |
nakayamaqs/PythonModule | Learning/narcissistic.py | Python | mit | 1,383 | 0.040492 | #!/usr/bin/env python
# encoding: utf-8
# Here's a simple script (feels like a program, though) that prints out
# the first n narcissistic numbers, where n is provided on the command line. import sys
import sys
def | numDigits(num):
"""Returns the number of digits making
up a number, not counting leading zeroes,
except for the number 0 itself."""
if(num ==0): return 1
digitCount = 0
while(num > 0):
digitCount += 1
num /= 10
return digitCount
def isNarcissistic(num):
"""Returns True if and only if the number is a narci... | otal += digits ** exp
num /= 10
return total == originalNum
def listNarcissisticNumbers(numNeeded):
"""Searches for an prints out the first 'numNeeded' narcissistic numbers."""
numFound = 0
numToConsider = 0
print ("here are the first ", numNeeded, " narcissistic numbers.")
while(numFound < numNeeded):
if... |
IftachSadeh/ANNZ | examples/scripts/annz_binCls_quick.py | Python | gpl-3.0 | 8,873 | 0.012172 | from scripts.helperFuncs import *
# command line arguments and basic settings
# --------------------------------------------------------------------------------------------------
init()
# just in case... (may comment this out)
if not glob.annz["doBinnedCls"]:
log.info(red(" - "+time.strftime("%d/%m/%y %H:%M:%S")+" ... | -
# optimization
# ------------------------------------------------------------------------------ | --------------------
if glob.annz["doVerif"]:
# run ANNZ with the current settings
runANNZ()
# --------------------------------------------------------------------------------------------------
# evaluation
# ----------------------------------------------------------------------------------... |
gangliao/Paddle | python/paddle/v2/config_base.py | Python | apache-2.0 | 5,435 | 0.000368 | # Copyright (c) 2016 PaddlePaddle 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 applic... | elf.context_name()]
else:
return context[self.name]
def to_proto_impl(self, **kwargs):
raise NotImplementedError()
def context_name(self):
"""
Context name means the context | which stores `to_proto_impl` result.
If multiple layer share same context_name, the `to_proto_impl` of them
will be invoked only once.
"""
return self.name
def use_context_name(self):
return False
def calculate_size(self):
"""
lazy calculate size of the ... |
RalfBarkow/Zettelkasten | venv/lib/python3.9/site-packages/pip/_vendor/html5lib/treewalkers/etree_lxml.py | Python | gpl-3.0 | 6,357 | 0.000944 | from __future__ import absolute_import, division, unicode_literals
from pip._vendor.six import text_type
from collections import OrderedDict
from lxml import etree
from ..treebuilders.etree import tag_regexp
from . import base
from .. import _ihatexml
def ensure_str(s):
if s is None:
return None
e... | nsure_str(node.tag))
if match:
namespace, tag = match.groups()
else:
namespace = None
tag = ensure_str(node.tag)
attrs = OrderedDict()
for name, value in list(node.att | rib.items()):
name = ensure_str(name)
value = ensure_str(value)
match = tag_regexp.match(name)
if match:
attrs[(match.group(1), match.group(2))] = value
else:
attrs[(None, name)] = value
r... |
plxaye/chromium | src/chrome/test/functional/chromoting/me2me_enable.py | Python | apache-2.0 | 1,431 | 0.00559 | #!/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.
"""Chromoting me2me enable/disable related test cases."""
import chromoting_base
import pyauto
class Me2MeEnable(chromoting_base... | ""Drives the me2me enable test cases."""
def setUp(self):
"""Set up for me2me enable test."""
# Disable test on vista and xp until the failure is figured
if self.IsWinVista() or self.IsWinXP():
return
pyauto.PyUITest.setUp(self)
self.InstallHostDaemon()
webapp = self.InstallExtension(... | ()
def tearDown(self):
"""Mainly uninstalls the host daemon."""
# Disable test on vista and xp until the failure is figured
if self.IsWinVista() or self.IsWinXP():
return
self.UninstallHostDaemon()
pyauto.PyUITest.tearDown(self)
def testMe2MeEnableDisable(self):
"""Enables/disables... |
fberanizo/neural_network | tests/ibovespa/mlp.py | Python | bsd-2-clause | 5,708 | 0.007187 | # -*- coding: utf-8 -*-
import sys, os
sys.path.insert(0, os.path.abspath('../..'))
import unittest, pandas, numpy, datetime, itertools, mlp
from sklearn import cross_validation, preprocessing
class MLP(unittest.TestCase):
"""Test cases for Ibovespa tendency problem."""
grid_search = True
def test_1(sel... | )
columns = ['Date', 'Trend'] + range(len(stocks))
data = [ibovespa_data["Date"], trend] + stocks
row = pandas.DataFrame([data], columns=columns).set_index("Date")
| # Data from last 3 months is test, the rest is train
three_months_ago = pandas.to_datetime('today') + pandas.Timedelta('-90 days')
if ibovespa_data["Date"] < three_months_ago:
train = train.append(row)
else:
test = test.append(row)
# Re... |
EmreAtes/spack | var/spack/repos/builtin/packages/font-micro-misc/package.py | Python | lgpl-2.1 | 2,102 | 0.000951 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | # You should have received a copy of the GNU Lesser 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
##############################################################################
from spack import *
class Fo... | micro-misc"
url = "https://www.x.org/archive/individual/font/font-micro-misc-1.0.3.tar.gz"
version('1.0.3', '4de3f0ce500aef85f198c52ace5e66ac')
depends_on('font-util')
depends_on('fontconfig', type='build')
depends_on('mkfontdir', type='build')
depends_on('bdftopcf', type='build')
de... |
PJUllrich/Complete-Bunq-API-Python-Wrapper | tests/endpoints/test_attachment_public.py | Python | mit | 1,221 | 0.000819 | from apiwrapper.endpoints.attachment_public import AttachmentPublic
from tests.endpoints.test_endpoint import EndpointTest
class AttachmentPublicTest(EndpointTest):
__base_endpoint_url = "/attachment-public/%s"
@property
def _base_endpoint(self):
return self.__base_endpoint_url % self.random_uuid... | ould_be = self._base_endpoint
endpoint_to_check = self.test_class._get_base_endpoint(self.random_uuid)
self.assert_parameters(endpoint_should_be, endpoint_to_check)
def test_get_public_attachment_by_id(self):
endpoint_should_be = self._base_endpoint
endpoint_to_check = self.test_... | self.random_uuid)
self.assert_parameters(endpoint_should_be, endpoint_to_check)
def test_get_content_of_public_attachment(self):
endpoint_should_be = self._base_endpoint
endpoint_should_be += "/content"
endpoint_to_check = self.test_class.get_content_of_public_attachment(
... |
sbxg/sbxg | sbxg/error.py | Python | mit | 3,454 | 0.003474 | # Copyright (c) 2017 Jean Guyomarc'h
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# i | n 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 perso | ns to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING B... |
adviti/melange | thirdparty/google_appengine/lib/django_1_2/tests/regressiontests/templates/nodelist.py | Python | apache-2.0 | 1,121 | 0 | from unittest import TestCase
from django.template.loader import get_template_from_string
from django.template import VariableNode
class NodelistTest(TestCase):
def test_for(self):
source = '{% for i in 1 %}{{ a }}{% endfor %}'
template = get_template_from_string(source)
vars = template.n... | rce)
vars = template.nodelist.get_nodes_by_type(VariableNode)
self.assertEqual(len(vars), 1)
def test_ifequal(self):
source = '{% ifequal x y %}{{ a }}{% endifequal %}'
template = get_template | _from_string(source)
vars = template.nodelist.get_nodes_by_type(VariableNode)
self.assertEqual(len(vars), 1)
def test_ifchanged(self):
source = '{% ifchanged x %}{{ a }}{% endifchanged %}'
template = get_template_from_string(source)
vars = template.nodelist.get_nodes_by_type... |
Disassem/urllib3 | test/socketpair_helper.py | Python | mit | 2,414 | 0.000414 | import socket
# Figuring out what errors could come out of a socket. There are three
# different situations. Python 3 post-PEP3151 will define and use
# BlockingIOError and InterruptedError from sockets. For Python pre-PEP3151
# both OSError and socket.error can be raised except on Windows where
# WindowsError can als... | connect((addr, port))
except _CONNECT_ERROR:
pass
csock.setblocking(True)
| ssock, _ = lsock.accept()
except:
csock.close()
raise
finally:
lsock.close()
return (ssock, csock)
|
trevorlinton/skia | gm/gm_json.py | Python | bsd-3-clause | 5,464 | 0.003477 | #!/usr/bin/env python
# Copyright (c) 2013 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.
"""Schema of the JSON summary file written out by the GM tool.
This must be kept in sync with the kJsonKey_ constants in gm_expect... | image expectations are stored.
SKIMAGE_EXPECTATIONS_ROOT = os.path.join('expectations', 'skimage')
# Pattern used to assemble each image's filename
IMAGE_FILENAME_PATTERN = '(.+)_(.+)\.png' # matches (testname, config)
def CreateGmActualUrl(test_name, hash_type, hash_digest,
gm_actuals_root_url... | URL we can use to download a particular version of
the actually-generated image for this particular GM test.
test_name: name of the test, e.g. 'perlinnoise'
hash_type: string indicating the hash type used to generate hash_digest,
e.g. JSONKEY_HASHTYPE_BITMAP_64BITMD5
hash_digest: the hash digest ... |
DonBeo/statsmodels | examples/incomplete/ols_table.py | Python | bsd-3-clause | 1,999 | 0.002501 | """Example: statsmodels.OLS
"""
from statsmodels.datasets.longley import load
import statsmodels.api as sm
from statsmodels.iolib.table import SimpleTable, default_txt_fmt
import numpy as np
data = load()
data_orig = (data.endog.copy(), data.exog.copy())
#.. Note: In this example using zscored/standardized variable... | s[:, 0] = res.params
indall = range(7)
for i in range(6):
ind = indall[:]
del ind[i]
res = | sm.OLS(data.endog, data.exog[:, ind]).fit()
resparams[ind, i + 1] = res.params
if rescale == 1:
pass
if rescale == 3:
resparams[:-1, :] *= rescale_ratio[:, None]
txt_fmt1 = default_txt_fmt
numformat = '%10.4f'
txt_fmt1 = dict(data_fmts=[numformat])
rowstubs = data.names[1:] + ['const']
headers = ['all'] +... |
AutorestCI/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_09_01/models/connectivity_information.py | Python | mit | 2,726 | 0 | # 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 ... | 'probes_sent': {'key': 'probesSent', 'type': 'int'},
'probes_failed': {'key': 'probesFailed', 'type': 'int'},
}
def __init__(self):
super(ConnectivityInformation, self).__init__()
self.hops = None
self.connection_status = None
self.avg_latency_in_ms = None
... | one
|
mlesche/dsp | dsp/src/database_scripts/archive_analysis.py | Python | mit | 4,536 | 0.017416 | #!/usr/bin/env python
'''
The MIT License (MIT)
Copyright (c) <2018> <Mathias Lesche>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
... | nd/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall | be included in
all copies or substantial 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... |
mirontoli/tolle-rasp | pico/009_serlcd_rgb.py | Python | mit | 628 | 0.012739 | # finally found how to change the backlight color
# https://diyodemag.com/projects/playing_with_raspberry_pi_pico_review_project
import machine
import utime
sda = machine.Pin(0)
scl = machine.Pin(1)
i2c = machine.I2C(0, sda=sda, scl=scl, freq=400000)
utime.sleep(1)
i2c.writeto(114, '\x7C | ') # | enter settings mode
i2c.writeto(114, '\x2B') # + change color
i2c.writeto(114, '\xFF') # red
i2c.writeto(114, '\xFF') # green
i2c.writeto(114, '\xFF') # blue
i2c.writeto(114, '\x7C') | # enter settings mode
i2c.writeto(114, '\x2D') # clear display
# i2c.writeto(114, '\x2C') # firmware version 1.4
i2c.writeto(114, 'Salam tence!')
|
alexgorban/models | official/vision/detection/evaluation/factory.py | Python | apache-2.0 | 1,390 | 0.003597 | # Copyright 2019 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... | r the License.
# ==============================================================================
"""Evaluator factory."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from official.vision.detection.evaluation import coco_evaluator
def evaluator_generato... | annotation_file=params.val_json_file, include_mask=False)
elif params.type == 'box_and_mask':
evaluator = coco_evaluator.COCOEvaluator(
annotation_file=params.val_json_file, include_mask=True)
else:
raise ValueError('Evaluator %s is not supported.' % params.type)
return coco_evaluator.Metri... |
ChesnakovKonstantin/Test-Example | Python projects/fenics/PythonApplicationFenics.py | Python | mit | 2,939 | 0.002382 | from fenics import *
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import tri
from math import pi,sinh,cosh
from mshr import *
# Create mesh and define function space
box = Rectangle(Point(0, 0), Point(5,3))
mesh = genera | te_mesh(box, 400)
# element of degree 1
V = FunctionSpace(mesh, 'P', 1)
nearEr = 1e-14
# Define boundary condition x
u_left = Expression('sin(pi*x[0]/5)', degree=1)
u_right = Expression('sin(3*pi*x[0]/5)', degree=1)
# Define boundary c | ondition y
g_left = Expression('sin(3*pi*x[1]/3)', degree=1)
g_right = Expression('sin(2*pi*x[1]/3)', degree=1)
# Define boundary (x = 0 or x = 5)
def boundary_leftX(x, on_boundary):
return on_boundary and near(x[0], 0, nearEr)
def boundary_rightX(x, on_boundary):
return on_boundary and near(x[0], 5, nearE... |
jamesthechamp/zamboni | mkt/constants/tests/test_regions.py | Python | bsd-3-clause | 3,275 | 0 | from contextlib import contextmanager
from mpconstants.countries import COUNTRY_DETAILS
from nose.tools import eq_, ok_
from tower import activate
import mkt.constants.regions as regions
from mkt.site.tests import TestCase
class TestRegions(TestCase):
def test_no_missing_region(self):
"""Test that we hav... | ns.USA)
for region in regions.REGIONS_DICT.values():
# Make sure the regions dict contains region objects.
ok_(issubclass(region, regions.REGION))
# Make sure we can find each region in the regi | ons module locals.
eq_(getattr(regions, region.__name__), region)
# Make sure the name is a lazy unicode object - encoding it to
# utf-8 it should work.
ok_(region.name.encode('utf-8'))
class TestRegionContentRatings(TestCase):
@contextmanager
def tower_activa... |
pinkevich/django-project-template | project_name/urls.py | Python | mit | 743 | 0.002692 | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^grappelli/', include('grappelli.urls | ')),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', '{{ project_name }}.views.main', name='main'),
)
if settings.DEVELOPMENT and settings.DEBUG and 'debug_toolbar' in settings.INSTALLED_APPS:
import debug_toolbar
urlpatterns += patterns(
'',
url(r'^__debug__/', include(debug_tool... | s.DEBUG:
urlpatterns += patterns(
'django.views.static',
url(r'^media/(?P<path>.*)$', 'serve', {'document_root': settings.MEDIA_ROOT}))
|
Azure/azure-sdk-for-python | sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/v3_0/models/__init__.py | Python | mit | 4,297 | 0.000465 | # 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 may ... | s import MultiLanguageInput # type: ignore
from ._models import RequestStatistics # type: ignore
from ._models import SentenceSentiment # type: ignore
from ._models import SentimentConfidenceScorePerLabel # type: ignore
from ._models import SentimentResponse # type: ignore
from ._models import ... | rt TextAnalyticsWarning # type: ignore
from ._text_analytics_client_enums import (
DocumentSentimentValue,
ErrorCodeValue,
InnerErrorCodeValue,
SentenceSentimentValue,
WarningCodeValue,
)
__all__ = [
'DetectedLanguage',
'DocumentEntities',
'DocumentError',
'DocumentKeyPhrases',
... |
Gagnon06/StrategyIA | tests/Algorithm/test_graph.py | Python | mit | 6,665 | 0.002101 | # Under MIT licence, see LICENCE.txt
import unittest
from RULEngine.Game.Ball import Ball
from RULEngine.Game.Game import Game
from RULEngine.Game.Referee import Referee
from RULEngine.Util.Pose import Pose
from RULEngine.Util.Position import Position
from RULEngine.Util.game_world import GameWorld
from RULEngine.Uti... | graph1.nodes[i]) + "\n"
self.assertEqual(str(self.graph1), expected_string)
if __name__ == "__ | main__":
unittest.main()
|
akshmakov/Dolfin-Fijee-Fork | site-packages/dolfin/functions/specialfunctions.py | Python | lgpl-3.0 | 6,001 | 0.003166 | # -*- coding: utf-8 -*-
"""This module defines some special functions
(originally defined in SpecialFunctions.h)."""
# Copyright (C) 2008-2014 Anders Logg
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as... | .ufl_domain(), 1)
| ufl.Coefficient.__init__(self, self._ufl_element, count=self.id())
MeshCoordinates.__doc__ = cpp.MeshCoordinates.__doc__
class FacetArea(Expression, ufl.Coefficient, cpp.FacetArea):
def __init__(self, mesh):
"""
Create function that evaluates to the facet area/length on each facet.
*Argu... |
mganeva/mantid | Testing/SystemTests/tests/analysis/FindSatellitePeaksTest.py | Python | gpl-3.0 | 2,531 | 0.003161 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
from mantid.simpleapi import FindSatellitePea... | peaks_test"
}
k = 2
self._satellites_refined = FindSatellitePeaks(NuclearPeaks=main_peaks, SatellitePeaks=satellite_peaks, MDWorkspace=md_workspace,
NumOfQs=k, **fixed | _params)
def validate(self):
return self._satellites_refined.name(), 'refine_satellites_fixed_q_test.nxs'
class FindSatellitePeaksTestAutoFindQ(systemtesting.MantidSystemTest):
def requiredFiles(self):
return ["WISH_md_small.nxs", "WISH_peak_hkl_small.nxs", "WISH_peak_hkl_frac_small.nxs"]
... |
yashaka/selene | selene/core/conditions.py | Python | mit | 1,391 | 0.000719 | # MIT License
#
# Copyright (c) 2015-2 | 021 Iakiv Kramarenko
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without lim | itation 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
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or... |
rethore/FUSED-Wake | fusedwake/gau/__init__.py | Python | agpl-3.0 | 6,002 | 0.005665 | # import python.gau as gau
import fortran as fgau
import numpy as np
class GAU(object):
# The different versions and their respective inputs
inputs = {
# 'py0': ['WF', 'WS', 'WD', 'K'],
'fort_gau_av': ['x_g', 'y_g', 'z_g', 'dt', 'p_c', 'ct_c', 'ws', 'wd', 'ks','ng',
'av', 'rh... | ran version {} failed with the followind inputs: {}, and the error message: {}'.format(
self.version, self._get_kwargs(self.version), e))
A = 0.25 * self.WF.WT.rotor_diameter**2.0
self.c_t = self.t_wt / (0.5 * A * self.rho * self.u_wt**2.0)
self.p_wt *= 1.0E3 # Scaling the p... | self.p_wt, self.u_wt, self.c_t = gau.gauarsen(**self._get_kwargs(self.version))
def __call__(self, **kwargs):
self.set(kwargs)
if hasattr(self, 'version'):
getattr(self, self.version)()
if not self.version in self.versions:
raise Exception("Version %s is not... |
zguangyu/wechat-python-sdk | wechat_sdk/basic.py | Python | bsd-2-clause | 37,055 | 0.001801 | # -*- coding: utf-8 -*-
import hashlib
import requests
import time
import json
import cgi
from io import StringIO
from xml.dom import minidom
from .messages import MESSAGE_TYPES, UnknownMessage
from .exceptions import ParseError, NeedParseError, NeedParamError, OfficialAPIError
from .reply import TextReply, ImageRep... | self.__is_parse = True
@property
| def message(self):
return self.get_message()
def get_message(self):
"""
获取解析好的 WechatMessage 对象
:return: 解析好的 WechatMessage 对象
"""
self._check_parse()
return self.__message
def get_access_token(self):
"""
获取 Access Token 及 Access Toke... |
zoho/books-python-wrappers | test/ExpensesTest.py | Python | mit | 2,882 | 0.009368 | #$Id$#
from books.model.Expense import Expense
from books.service.ZohoBooks import ZohoBooks
zoho_books = ZohoBooks("{auth_token}", "{organization_id}")
expenses_api = zoho_books.get_expenses_api()
expense_id = expenses_api.get_expenses().get_expenses()[0].get_expense_id()
accounts_api = zoho_books.get_bank_accoun... | .get_vendor_payments()[0].get_vendor_id()
# List Expenses
parameters={'filter_by':'Status.Unbilled'}
print expenses_api.get_expenses()
print expenses_api.get | _expenses(parameters)
# Get an expense
print expenses_api.get(expense_id)
# Create an expense
expenses=Expense()
expenses.set_account_id(expense_account_id)
expenses.set_paid_through_account_id(account_id)
expenses.set_date("2012-12-30")
expenses.set_amount(100.0)
expenses.set_tax_id("71127000000077019")
expenses.s... |
khosrow/metpx | sundew/doc/pds_conversion/routing_step3.py | Python | gpl-2.0 | 3,482 | 0.03676 | import os,re,string,sys
# ---------------------------------------------------
# read in the ACCEPT/REJECT MASK
# ---------------------------------------------------
KMASKS = []
KFLAGS = []
CMASKS = []
f=open("fromPds.conf",'rb')
data=f.readlines()
f.close()
for l in data :
l = l.strip()
if len(l) == 0 : con... | ----------------
# read in the ROUTING
# ---------------------------------------------------
f=open("pdsRouting.conf",'rb')
data2=f.readlines()
f.close()
ROUT={}
for l in data2:
l2 = l.strip()
if len(l2) == 0 : continue
if l2[0] == '#' : continue
parts = l2.split(' ')
if len(parts) != 4 :
p... | AD LINE %s" % l )
continue
if parts[1] in ROUT :
print("duplicated %s" % parts[1])
lst = parts[2].split(',')
lst.sort()
str = ','.join(lst)
ROUT[parts[1]] = str
# ---------------------------------------------------
# get key
# ---------------------------------------------------
def ... |
google/UIforETW | bin/ETWPackSymbols.py | Python | apache-2.0 | 7,629 | 0.01298 | # 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 by applicable... | foundPath = s | ymCachePathv3
if foundPath:
matchExists += 1
print("Copying %s" % foundPath)
dest = foundPath[len(symCachePathBase):]
dest_dir, dest_file = os.path.split(dest)
if dest_dir:
try:
os.makedirs(os.path.join(DestDirName, dest_dir))
exce... |
Merck/DeepNeuralNet-QSAR | dnn.py | Python | gpl-3.0 | 17,485 | 0.009151 | """
Copyright (c) 2011,2012,2016,2017 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co., Inc., Kenilworth, NJ, USA.
This file is part of the Deep Neural Network QSAR program.
Deep Neural Network QSAR is free software: you can redistribute it and/or modify
it under the terms of the GNU General Publ... | s=None, initialBiases=None, targMean=None, targStd=None):
"""
Construct a Neural Network object with Basic Structure:
| - layerSizes: [input size, hidden layer size list, output size]
- outputActFunct: activation function for output layer, such as Linear() and LinearMasked()
- useReLU: True/False, use ReLU() or Sigmoid() as activation function
"""
self.layerSizes = layerSizes
self.outputActFu... |
priseborough/ardupilot | Tools/scripts/generate_manifest.py | Python | gpl-3.0 | 13,723 | 0.000219 | #!/usr/bin/python
from __future__ import print_function
import sys
import json
import os
import re
class Firmware():
def __init__(self,
date=None,
platform=None,
vehicletype=None,
filepath=None,
git_sha=None,
f... | firmware["git_sha"] = git_sha
firmware["frame"] = frame
firmware["timestamp"] = os.path.getctime(firmware["filepath"])
firmware["format"] = firmware_format
firmware["firmware-version"] = firmware_version
def xfirmwares_to_firmwares(self, xfirmwares)... | o = self.xfirmwares_to_fir |
watchdogpolska/feder | feder/letters/sitemaps.py | Python | mit | 218 | 0 | from django.contrib.sitemaps impo | rt Sitemap
from .models import Letter
class LetterSitemap(S | itemap):
def items(self):
return Letter.objects.all()
def lastmod(self, obj):
return obj.modified
|
ajrichards/GenesDI | genesdi/qtlib/InitialDock1.py | Python | gpl-3.0 | 3,606 | 0.009706 | import sys
from PyQt4 import QtGui, QtCore
class InitialDock1(QtGui.QWidget):
def __init__(self, parent=None, message=None, speciesDefault=None, contBtnFn=None, addBtnFn=None, speciesFn=None):
QtGui.QWidget.__init__(self,parent)
self.setWindowTitle('Data Processing')
vbox = QtGui.QVBoxLayo... | if addBtnFn != None:
self.connect(self.addBtn, QtCore.SIGNAL('clicked()'),addBtnFn)
## cont button
if contBtnFn != False:
self.contBtn = QtGui.QPushButton("Continue")
self.contBtn.setMaximumWidth(100)
self.contBtn.setMinimumWidth(100)
... |
if contBtnFn != None:
self.connect(self.contBtn, QtCore.SIGNAL('clicked()'),contBtnFn)
## species selector
if speciesFn != False:
hbox1.addWidget(QtGui.QLabel('Species Selector'))
hbox1.setAlignment(QtCore.Qt.AlignTop)
... |
dims/keystone | keystone/federation/controllers.py | Python | apache-2.0 | 20,514 | 0 | # 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 t... | ection(context, protocols)
@controller.protected()
def delete_protocol(self, context, idp_id, protocol_id):
self.federation_api.delete_protocol(idp_id, protocol_id)
@dependency.requires('federation_api')
class MappingController(_ControllerBase):
collection_name = 'mappings'
member_name = 'map... | f._no |
kmuehlbauer/wradlib | wradlib/io/radolan.py | Python | mit | 23,177 | 0 | #!/usr/bin/env python
# Copyright (c) 2011-2018, wradlib developers.
# Distributed under the MIT License. See LICENSE.txt for more info.
"""
Read RADOLAN and DX
^^^^^^^^^^^^^^^^^^^
Reading DX and RADOLAN data from German Weather Service
.. autosummary::
:nosignatures:
:toctree: generated/
read_dx
rea... | # data is encoded in the first 12 bits
data = 4095
# the zero compression flag is bit 13
flag = 4096
beam = []
# # naive version
# # 49193 function calls in 0.772 CPU seconds
# # 20234 function calls in 0.581 CPU seconds
# for item in raw:
# if item & flag:
# beam.e... | y
# 6204 function calls in 0.149 CPU seconds
# get all compression cases
flagged = np.where(raw & flag)[0]
# if there is no zero in the whole data, we can return raw as it is
if flagged.size == 0:
assert raw.size == 128
return raw
# everything until the first flag is normal da... |
mensler/ansible | lib/ansible/modules/cloud/ovirt/ovirt_templates_facts.py | Python | gpl-3.0 | 3,553 | 0.001689 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Red Hat, Inc.
#
# 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
#... | tem_service().templates_service()
templates = templates_service.list(search=module.params['pattern'])
module.exit_json(
changed=False,
ansible_facts=dict(
ovirt_templates=[
get_dict_of_struct(
struct=c,
... | tributes=module.params.get('nested_attributes'),
) for c in templates
],
),
)
except Exception as e:
module.fail_json(msg=str(e), exception=traceback.format_exc())
finally:
connection.close(logout=auth.get('token') is None)
if __name__ ==... |
Kozea/Dyko | kalamar/access_point/xml/rest.py | Python | gpl-3.0 | 5,053 | 0.000792 | # -*- coding: utf-8 -*-
# This file is part of Dyko
# Copyright © 2008-2010 Kozea
#
# This library 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 lat... | = item.xml_tree.getroot()
elem = etree.Element(
"role-def", cla | sses="raw-kalamar", format="kalamar")
parent.append(elem)
super(Rest, self).update_xml_tree(item)
def preprocess_save(self, item):
if len(item.unsaved_properties):
self.update_xml_tree(item)
string = to_bytes(MAIN_XSLT(item.xml_tree))[:-1]
item[se... |
food52/thumbor | thumbor/detectors/glasses_detector/__init__.py | Python | mit | 691 | 0.001447 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbo | r imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
from tornado.options import options, define
from thumbor.detectors.local_detector import CascadeLoaderDetector
define... | CASCADE_FILE', default='haarcascade_eye_tree_eyeglasses.xml')
class Detector(CascadeLoaderDetector):
def __init__(self, context, index, detectors):
super(Detector, self).__init__(context, index, detectors)
self.load_cascade_file(__file__, options.GLASSES_DETECTOR_CASCADE_FILE)
|
spring-week-topos/cinder-week | cinder/tests/test_wsgi.py | Python | apache-2.0 | 10,194 | 0 | # Copyright 2011 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 ... | "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Unit tests for `cinder.wsgi`."""
import mock
import os.path
import tempfile
import urllib2
from oslo.config imp... | port testtools
import webob
import webob.dec
from cinder import exception
from cinder.openstack.common import gettextutils
from cinder import test
import cinder.wsgi
CONF = cfg.CONF
TEST_VAR_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),
'var'))
class TestLoaderNothing... |
emilroz/openmicroscopy | components/tools/OmeroPy/test/unit/clitest/test_cli.py | Python | gpl-2.0 | 1,860 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Test of the omero cli base class including line parsing.
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import os
import pytest
from path import path
from omero.cli import CLI
from ome... | with pytest.raises(NonZeroReturnCode):
self.cli.invoke("load %s" % tmp, strict=True)
self.cli.invoke("load | -k %s" % tmp, strict=True)
self.cli.invoke("load --keep-going %s" % tmp, strict=True)
|
Cibiv/Teaser | lib/teaser.py | Python | mit | 17,308 | 0.032355 | #!/usr/bin/env python
import os
import shutil
import time
import yaml
import util
import simulator
from lib import gsample
from tools import fastq2sam
from lib import sam
class Teaser:
def __init__(self, mate, config):
self.mate = mate
self.config = config
self.supported_platforms = ["illumina","454","ion_to... | io
def calcualteRegionLen(self,test):
if test["paired"]:
return test["sampling"]["region_len_multiplier"] * ( | test["insert_size"]+test["insert_size_error"])
else:
return test["sampling"]["region_len_multiplier"] * test["read_length"]
def calculateRegionPadding(self,test):
if test["paired"]:
return 2 * (test["insert_size"]+test["insert_size_error"])
else:
return 2 * test["read_length"]
def makeDatasetDS(sel... |
jacksono/Bucketlist_API_Jxn | tests/base_test.py | Python | mit | 1,193 | 0 | """Contain the setup for other test cases."""
from flask_testing import TestCase
from app import db
from start import app
from bucketlist.models import User, Bucketlist, Item
from configuration.config import app_config
app.config.from_object(app_config["testing"])
class BaseTest(TestCase):
"""Base configuration... | ."""
return app
def setUp(self):
"""Fixture to create test database and set up test client."""
self.app = app.test_client()
db.create_all()
user = User(username="user", e | mail="user@bucketlist.com",
password="password")
bucketlist = Bucketlist(title="Travel",
description="Places I have to visit",
created_by=1)
item = Item(name="Enjoy the beautiful beaches of Hawaii",
... |
HybridF5/jacket | jacket/api/compute/metadata/vendordata_json.py | Python | apache-2.0 | 2,141 | 0 | # Copyright 2013 Canonical 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 required by... | {'logprefix': logprefix})
raise
self._data = data
def get(self):
| return self._data
|
vdt/ml-service-api | ml_grading/models.py | Python | agpl-3.0 | 2,344 | 0.016212 | from django.db import models
from django.utils import timezone
import json
CHARFIELD_LEN_SMALL=128
CHARFIELD_LEN_LONG = 1024
class CreatedModel(models.Model):
#When it was created/modified
modified=models.DateTimeField(auto_now=True)
created=models.DateTimeField(auto_now_add=True)
#Properties of the ... | submission_id_list=json.loads(self.submission_ids_used)
except:
return False, "No essays used or not in json format."
return True, submission_i | d_list |
badele/serialkiller-plugins | skplugins/checker/__init__.py | Python | gpl-3.0 | 4,974 | 0.001207 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__authors__ = 'Bruno Adelé <bruno@adele.im>'
__copyright__ = 'Copyright (C) 2013 Bruno Adelé'
__description__ = """A plugins for serialkiller project"""
__license__ = 'GPL'
__version__ = '0.0.2'
__apiversion__ = '1.0'
import os
import sys
import json
import time
import lo... | /%(server)s | /api/%(apiversion)s/%(request)s" % locals()
requests.get(url)
#print url
except:
pass
|
altMITgcm/MITgcm66h | utils/python/MITgcmutils/MITgcmutils/mnc.py | Python | mit | 14,112 | 0.00333 | import sys
import glob
import numpy as np
from .netcdf import netcdf_file
_exclude_global = ['close',
'createDimension',
'createVariable',
'dimensions',
'filename',
'flush',
'fp',
'mode'... | self.variables = dict((k, MNCVariable(self, k)) for k in var0)
def __getattr__(self, k):
tr | y:
return self._attributes[k]
except KeyError:
raise AttributeError("'MNC' object has no attribute '" + k + "'")
def __dir__(self):
return self.__dict__.keys() + self._attributes.keys()
def close(self):
"""Close tile files"""
for nc in self.nc:
... |
devashishp/Content-Based-Image-Retrieval | optimized.py | Python | mit | 3,209 | 0.014023 | from feature import *
from pymongo import MongoClient
from bson.binary import Binary as BsonBinary
import pickle
import os
from operator import itemgetter
import time
import sys
imagelocation = "" #Input Image path
indir = "" #Directory Path
client = MongoClient('mongodb://localhost:27017')
db = client.coil #Inser... | ute((llfeature-img.llfeature).sum())
glosim = np.logical_xor(glfeature,img.glfeature).sum()
distance = locsim+glosim
if(glosim>maxglosim):
gridmax = glfeature
maxglosim=glosim
if(locsim>maxlocsim):
maxlocsim=locsim
vectormax = llfeature
if(distance>maximum):
v... | re).sum())
maxiglosim = np.logical_xor(gridmax,img.glfeature).sum()
processed_time = time.time()
print("\nTotal Processing Time : {0:.2f} seconds".format(processed_time-start_time))
def gloDist(gridA,gridB):
glosim = np.logical_xor(gridA,gridB).sum()
return glosim/maxiglosim
def locDist(vectorA,vectorB):
... |
phisiart/tvm | python/tvm/contrib/mxnet.py | Python | apache-2.0 | 1,841 | 0.000543 | """MXNet bridge wrap Function MXNet's async function."""
from __future__ import absolute_import as _abs
from .. import api, _api_internal, ndarray
from ..module import Module
# pylint: disable=invalid-name
_wrap_async = None
def to_mxnet_func(func, const_loc=None):
"""Wrap a TVM function as MXNet function
... | func, Module):
func = func.entry_func
def _get_bridge_func():
"""Get MXNet bridge function"""
if not mxnet.base._LIB.MXTVMBridge:
| raise RuntimeError(
"MXTVMBridge not exist in mxnet package,"
" please update to latest version")
fdict = api.extract_ext_funcs(mxnet.base._LIB.MXTVMBridge)
ret = fdict["WrapAsyncCall"]
ret.is_global = True
return ret
global _wrap_async
if _wrap... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.