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
alobbs/autome
plugins/telegram.py
Python
mit
5,837
0.000171
import glob import os import tempfile import urllib.parse import plugin import pluginconf import requests import telepot util = plugin.get("util") ERROR_USER_UNKNOWN = ("I don't know you, but I'll tell you someth
ing. " "Sometimes, I use words that I don't " "know to make me seem more… photosynthesis.") ERROR_NO_USERID = ("You gotta set yourself a name alias " "if you wanna talk to me.") class Keyboard: def __init__(self, items_per_line=1):
self._markup = None self._keyboard = [] self.items_per_line = items_per_line # Guts def _get_markup(self): if self._markup: return self._markup if self._keyboard: # Split in rows n = max(1, self.items_per_line) kb = [self._keyb...
frappe/frappe
frappe/www/profile.py
Python
mit
165
0.024242
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Co
ntributors # License: MIT. See LICENSE
no_cache = 1 def get_context(context): context.show_sidebar=True
mark47/OESandbox
liquibase/OE2.8/testCatalogCI_LNSP/scripts/testPanel.py
Python
mpl-2.0
1,391
0.007908
#!/usr/bin/env python # -*- coding: utf-8 -*- panel_file = open('panels.txt','r') name_file = open('testName.txt','r') sample_type_file = open("sampleType.txt") test_panel_results = open("output/testPanelResults.txt", 'w') panel
= [] type = [] test_names = [] def get_split_names( name ): split_name_list = name.split("/") for i in range(0, len(split_name
_list)): split_name_list[i] = split_name_list[i].strip() return split_name_list def esc_char(name): if "'" in name: return "$$" + name + "$$" else: return "'" + name + "'" for line in panel_file: panel.append(line.strip()) panel_file.close() for line in sample_type_file: ...
morta-code/IntelliStock
intellistock/ui/navigatorplotwidget.py
Python
gpl-2.0
3,270
0.003671
# -*- coding: utf-8 -*- """ Created on Thu Dec 4 00:18:49 2014 @author: Polcz Péter <[email protected]> """ import sys import numpy as np from PyQt4.QtGui import QVBoxLayout, QMessageBox, QApplication from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar from intellistock.ui.plo...
vas) layout.addWidget(self.mpl_toolbar) self.setLayout(layout) def on_pick(self, event): # The event received here is of the type # matplotlib.backend_bases.PickEvent # # It carries lots of information, of which we're using # only a small amount here. ...
a bar with coordinates:\n %s" % box_points QMessageBox.information(self, "Click!", msg) def on_draw(self): self.canvas.draw() # -------------------------------------------------------------------------------------------------------------------- # # -- TEST --------------------------------...
kmatzen/ansible
lib/ansible/__init__.py
Python
gpl-3.0
888
0.001126
# (c) 2012-201
4, Michael DeHaan <[email protected]> # # 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 L
icense as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible 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...
yoyo2k/l10n-romania
partner_create_by_vat/res_partner.py
Python
agpl-3.0
9,585
0.00407
# -*- encoding: utf-8 -*- #############################
################################################# # # Romanian accounting localization for OpenERP V7 # @author - Fekete Mihai, Tatár Attila <[email protected]> # Copyright (C) 2011-2013 TOTAL PC SYSTEMS (http://www.www.erpsystems.ro). # Copyright (C) 2013 Tatár Attila # # This program is free software...
eneral 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 distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS...
VirusTotal/content
Packs/PrismaCloud/Integrations/RedLock/RedLock_test.py
Python
mit
5,638
0.004966
import pytest from freezegun import freeze_time import demistomock as demisto integration_params = { 'url': 'http://test.com', 'credentials': {'identifier': 'test', 'password': 'pass'}, 'fetch_time': '3 days', 'proxy': 'false', 'unsecure': 'false', } @pytest.fixture(autouse=True) def set_mocks(m...
'scanTime': '2021-10-18T14:38:53.654174' } }] } expected_readable_output = '### Scans List:\n|ID|Name|Scan Time|Type|User|\n|---|---|---|---|---|\n| 111111111 |' \ ' test name | 2021-10-18T14:38:53.654174 | test type | test user |\n' expected_context_en...
'111111111', 'name': ['test name'], 'type': ['test type'], 'user': ['test user'], ...
Connexions/cnx-publishing
cnxpublishing/main.py
Python
agpl-3.0
838
0
# -*- coding: utf-8 -*- # ### # Copyright (c) 2013, Rice University # This software is subject to the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. # ### import os from ._version import get_versions __version__ = get_ve
rsions()['version'] del get_versions __name__ = 'c
nxpublishing' def find_migrations_directory(): # pragma: no cover """Finds and returns the location of the database migrations directory. This function is used from a setuptools entry-point for db-migrator. """ here = os.path.abspath(os.path.dirname(__file__)) return os.path.join(here, 'sql/migra...
marktoakley/LamarckiAnt
SCRIPTS/AMBER/symmetrise_prmtop/perm-prmtop.ff03ua.py
Python
gpl-3.0
31,681
0.023137
#!/usr/bin/env python import os import os.path import sys import string ############################################################### ## # ## Edyta Malolepsza # ## David Wales' group, University of Cambridge ...
ROPER responsible for trouble with NH2 group permutation: find_atom1 = a[aa.index(residue)].index('NE') atomNumber1 = find_atom1+currentAtomNumber atomNumberIndex1 = atomNumber1*3 find_atom2 = a[aa.index(residue)].index('NH1') atomNumber2 = find_atom2+currentAtomNumber atomNumberInd...
tomNumber atomNumberIndex3 = atomNumber3*3 find_atom4 = a[aa.index(residue)].index('NH2') atomNumber4 = find_atom4+currentAtomNumber atomNumberIndex4 = atomNumber4*3 for j in range(len(dihedrals)): if ((dihedrals[j][0]==str(atomNumberIndex1)) and (dihedrals[j][1]==str(atomNumberInd...
klarnemann/jagust_rsfmri
rsfmri/utils.py
Python
mit
19,059
0.007346
import os, sys import datetime from glob import glob import json import numpy as np import pandas from skimage.morphology import binary_erosion from nitime.timeseries import TimeSeries from nitime.analysis import SpectralAnalyzer, FilterAnalyzer import nibabel import nipype.interfaces.spm as spm from nipype.interfac...
p %s %s'%(infile, newdir)) out
= cl.run() if not out.runtime.returncode == 0: print 'failed to copy %s' % infile print out.runtime.stderr return None else: basenme = os.path.split(infile)[1] newfile = os.path.join(newdir, basenme) return newfile def copy_files(infiles, newdir): """wraps c...
nnsnodnb/django-ios-notifications
notification/views.py
Python
mit
3,036
0.000988
from django.shortcuts import render, redirect from django.http.response import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from .forms import CertFileUploadForm from .models import DeviceToken, CertFile from .utils import send_notification, upload_certificate import json @csrf_exe...
pResponse('Successful sending.', status=200) except DeviceToken.DoesNotExist:
return HttpResponse('Not found. Your device token.', status=404) def cert_upload(request): if not request.user.is_superuser: return redirect('notification:login') if request.method == 'POST': form = CertFileUploadForm(request.POST, request.FILES) if form.is_valid(): result...
bc-jackiehuynh/bigcommerce-api-python
bigcommerce/connection.py
Python
mit
4,916
0.008544
""" Simple wrapper around requests library, mostly for configuring connection and usage by resources. The get, post, put, and delete methods of the class could be used directly. _run_method doc: Runs given method (requests.post, .get, .put, .delete) with given req_path (the part after /api/v2), and the gi...
classmethod def get(cls, req_path, **options): return cls._run_method(requests.get, req_path, None, **options) @classmethod def delete(cls, re
q_path, **options): """ No return value. Exception if not successful. """ return cls._run_method(requests.delete, req_path, None, **options) @classmethod def post(cls, req_path, data, **options): return cls._run_method(requests.post, req_path, data, **options) ...
AusTac/parma
b3/parsers/moh.py
Python
gpl-2.0
24,337
0.012204
# # Medal of Honor Parser for BigBrotherBot(B3) (www.bigbrotherbot.net) # Copyright (C) 2010 James 'Bakes' Baker ([email protected]) # # This program is free software; you can redistribute it and/or modify # it under the te
rms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version. # # This program is 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 more details. # # You should have received a copy o...
Jellofishi/solartron
qtsolartron.py
Python
lgpl-3.0
12,301
0.028453
#!/bin/env python r"""Solartron Orbit network reader GUI.""" # python modules import sys from time import sleep # external modules from serial.serialutil import SerialException from PyQt4 import QtCore, QtGui # app modules from solartron import Driver from sderrors import * from pedal import DummyPedal as Pedal from...
QtGui.QLineEdit() self.output.setReadOnly(1) self.layout = QtGui.QHBoxLayout() self.layout.addWidget(self.label) self.layout.addWidget(self.output) self.layout.setContentsMargins(0,0,0,0) self.
setLayout(self.layout) def setValue(self, value): """Update probe readout value.""" self.output.setText(str(value)) def text(self): """Get probe readout value as text.""" return self.output.text() class PedalPoller(QtCore.QThread): """Poll pedal driver.""" def __init__(self, *args): QtCore.QThread....
octarin/PySrt
PySrt.py
Python
gpl-3.0
3,556
0.005624
import re import sys class SrtSection: """ This class is used to stock a section from a srt file (subtitle frames). - self.beginning is the time (in seconds) where the subframe begins - self.duration is the duration (in seconds) of the subframe - self.content is the content of the s...
string is the content of the srt file. """ self.rawsections = [s.strip() for s in string.split("\n\n") if s != ''] self.sections = self.__extract_sections() def __extract_sections(self): """ Extracts all the informations from a list containing all the sec...
n seconds content the sub to show at this time """ sections = [] for section in self.rawsections: lines = section.split('\n') beginning, duration = self.__extract_tdata(lines[1]) content = "\n".join(lines[2:]) sections...
jghenry/standard_deviation
setup.py
Python
mit
187
0.005348
from distutils.core import setup setup( name='standard_deviation', version='0.1dev', packages=['sd_py',],
license='MIT', long_description=open('README.md').read(),
)
tweemeterjop/thug
thug/DOM/W3C/HTML/HTMLFontElement.py
Python
gpl-2.0
352
0.008523
#!/usr/bin/env pyt
hon from .HTMLElement import HTMLElement from .attr_property import attr_property class HTMLFontElement(HTMLElement): def __init__(self, doc, tag): HTMLElement.__init__(self, doc, tag) color = attr_property("color") face = attr_p
roperty("face") size = attr_property("size")
Comunitea/CMNT_00098_2017_JIM_addons
custom_sale_order_variant_mgmt/models/sale_order.py
Python
agpl-3.0
13,669
0.001171
# -*- coding: utf-8 -*- # © 2017 Comunitea # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models, fields, api, _ from odoo.tools import float_compare from lxml import etree class SaleOrderLineTemplate(models.Model): _name = 'sale.order.line.template' _inherit = 'sale.order....
product_id = self.env['product.product'].browse(line_vals['product_id']) if template_product.display_name == line_vals['name']: line_vals['name'] = product_id.display_name line_vals.update({
'product_id': product_id.id, 'product_uom': product_id.uom_id, 'order_id': order_id, }) order_line = self.env['sale.order.line'].with_context(ctx).new(line_vals) order_line.product_id_change() orde...
nvbn/coviolations_web
violations/coverage.py
Python
mit
1,087
0
from django.template.loader import render_to_string from tasks.const import STATUS_SUCCESS from .base import library @library.register('coverage') def coverage_violation(data): """Coverage violation parser :param data: task data :type data: dict :returns: dict """ data['status'] = STATUS_SUCC...
lit('\n')[-2] statements, miss, cover = [ part for part in line.split(' ') if len(part) > 0 and 'TOTAL' not in part ] each_file = [ filter(len, line.split(' ')) for line in data['raw'].split('\n')[2:-3] ] data['preview'] = render_to_string('violations/coverage/preview...
/prepared.html', { 'statements': statements, 'miss': miss, 'cover': cover, 'each_file': each_file, }) data['plot'] = { 'cover': int(cover[:-1]), } data['success_percent'] = int(cover[:-1]) return data
criswell/noink
src/noink/role_db.py
Python
agpl-3.0
7,210
0.000832
""" ##BOILERPLATE_COPYRIGHT ##BOILERPLATE_COPYRIGHT """ import datetime from types import IntType from noink import mainDB from noink.data_models import Role, RoleMapping from noink.user_db import UserDB from noink.activity_table import get_activity_dict from noink.exceptions import DuplicateRole, RoleNotFound from...
t to use the user ID of the person adding this role? self.eventLog.add('add_role', -1, True, blob, role.name)
return role def update_role(self, role): """ Given a role object, update the database with whatever changes it contains. """ if isinstance(role, Role): exists = Role.query.get(role.id) if exists == []: mainDB.session.add(role) ...
christianmemije/kolibri
kolibri/plugins/learn/viewsets.py
Python
mit
2,084
0.00048
from .serializers import LearnerClassroomSerializer from django.db.models.query import F from kolibri.auth.api import KolibriAuthPermissionsFilter from kolibri.auth.filters import HierarchyRelationsFilter from kolibri.auth.models import Classroom from kolibri.auth.serializers import ClassroomSerializer from kolibri.cor...
t_queryset(self): assignments = HierarchyRelationsFilter(LessonAssignment.objects.all()) \ .filter_by_hierarchy( target_user=self.request.user, ancestor_collection=F('collection') ) return Lesson.objects.filter( lesson_assignments__in=assig...
is_active=True )
taylorhardy/ConferenceApp
conference.py
Python
apache-2.0
34,962
0.003976
""" conference.py -- Udacity conference server-side Python App Engine API; uses Google Cloud Endpoints $Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $ created by wesc on 2014 apr 21 """ __author__ = '[email protected] (Wesley Chun)' from datetime import datetime, timedelta, time as timed import j...
ch.fetch(url) if resp.status_code == 200: user = json.loads(resp.content) break elif resp.status_code == 400 and 'invalid_token' in resp.content: url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?%s=%s' % ('access_token', token)) else: ...
time.sleep(wait) wait = wait + i return user.get('user_id', '') @endpoints.api(name='conference', version='v1', audiences=[ANDROID_AUDIENCE], allowed_client_ids=[WEB_CLIENT_ID, API_EXPLORER_CLIENT_ID, ANDROID_CLIENT_ID, IOS_CLIENT_ID], scopes=[EMAIL_SCOPE]) class ConferenceApi(remote.Service):...
Glottotopia/aagd
moin/local/moin/build/lib.linux-x86_64-2.6/MoinMoin/support/passlib/exc.py
Python
mit
7,667
0.004826
"""passlib.exc -- exceptions & warnings raised by passlib""" #============================================================================= # exceptions #============================================================================= class MissingBackendError(RuntimeError): """Error raised if multi-backend handl...
uested backend is not available. :exc:`!MissingBackendError` derives from :exc:`RuntimeError`, since it usually indicates lack of an external library or OS feature. This is primarily raised by handlers which depend on external libraries (which is currently just
:class:`~passlib.hash.bcrypt`). """ class PasswordSizeError(ValueError): """Error raised if a password exceeds the maximum size allowed by Passlib (4096 characters). Many password hash algorithms take proportionately larger amounts of time and/or memory depending on the size of the p...
googleads/google-ads-python
google/ads/googleads/v8/services/services/gender_view_service/transports/grpc.py
Python
apache-2.0
10,280
0.000875
# -*- 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...
that channel and credentials are not both # provided. credentials = False # If a channel
was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None elif api_mtls_endpoint: warnings.warn( "api_mtls_endpoint and client_cert_source are deprecated", DeprecationWarning, ) ...
disabler/isida3
lib/chardet/sbcsgroupprober.py
Python
gpl-3.0
2,948
0.010855
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Universal charset detector code. # # The Initial Developer of the Origi
nal Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 2001 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # Shy Shalom - original C code # # This library is free software; you can redistribute it and/or # m...
he License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should hav...
StartupsPoleEmploi/labonneboite
labonneboite/web/admin/views/index.py
Python
agpl-3.0
619
0
""" The admin interface is built on top of Flask-Admin: - https://flask-admin.readthed
ocs.io/en/latest/ - http://flask-admin.readthedocs.io/en/latest/api/mod_model/ - http://mrjoes.github.io/2015/06/17/flask-admin-120.html """ from flask_admin import AdminIndexView, expose
from labonneboite.web.admin.utils import abort_if_not_admin, user_is_admin class LbbAdminIndexView(AdminIndexView): """ A custom index view class for the LBB admin. """ @expose('/') def index(self): if user_is_admin(): return super(LbbAdminIndexView, self).index() ret...
sfstpala/robot-ci
robot/tests/test_tasks.py
Python
gpl-3.0
7,594
0
import urllib.parse import unittest.mock import tornado.httpclient import robot.tests class TasksHandlerTest(robot.tests.TestCase): @unittest.mock.patch("robot.tasks.TasksHandler.fetch") def test_get(self, fetch): fetch.return_value = robot.tests.future(unittest.mock.Mock(json={ "rows": [...
asks", method="POST", body={ "lang": "bash", "text": "echo hello", "name": "test"}) @unittest.mock.patch("robot.tasks.TasksHandler.fetch") def test_post_bad_request(self, fetch): fetch.return_value = robot.tests.future( exception=tornado.httpclient.HTTPError(400)) body =...
lib.parse.urlencode({ "name": "test", "lang": "", "text": "", }) res = self.fetch( "/tasks", method="POST", body=body, authenticated=True, follow_redirects=False) self.assertEqual(res.code, 400) class TaskHandlerTest(robot.tests.TestC...
mbohlool/client-python
kubernetes/test/test_v1beta1_http_ingress_path.py
Python
apache-2.0
1,011
0.004946
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.8.2 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys im...
client from kubernetes.client.rest import ApiException from kubernetes.client.models.v1beta1_http_ingress_path import V1beta1HTTPIngressPath class TestV1beta1HTTPIngressPath(unittest.TestCase): """ V1beta1HTTPIngressPath unit test stubs """ def setUp(self): pass def tearDown(self): pass ...
xample values #model = kubernetes.client.models.v1beta1_http_ingress_path.V1beta1HTTPIngressPath() pass if __name__ == '__main__': unittest.main()
astroufsc/python-si-tcpclient
si/commands/__init__.py
Python
gpl-2.0
22
0
from came
ra import *
lukehsiao/RobotSoccer
MotionControl/scripts/kalman_filter/LocationFilter.py
Python
mit
821
0.013398
#!/usr/bin/env python from gamepieces.HomeRobot import * from gamepieces.Ball import * import cPickle as pickle class LocationFilter: def __init__(self): self.lastSample = None def callback(self,data): # parse message measuredLocations = Locati
ons() measuredLocations.setDataFromSample(data) measuredRobotLocation = RobotLocation(measuredSample.time, measuredSample.home1_x
, newSample.home1_y, newSample.home1_theta) newBallLocation = BallLocation(newSample.time, newSample.ball_x, newSample.ball_y) updatedRobotLocation = self.filterRobotLocation(newRobotLocation) self.ball.time = newSample.time self.ball.point.x = newSample.ball_x s...
keishi/chromium
chrome/test/functional/autofill.py
Python
bsd-3-clause
41,065
0.004359
#!/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. import logging import os import pickle import re import simplejson import autofill_dataset_converter import autofill_dataset_gener...
to check. windex: The index of the window containing the webpage form to check. """ field_check_code = ''.join( ['if (!document.getElementById("%s")) ready = "false";' % key for key in form_profile.keys()]) js = """ var ready = 'true'; if (!document.getElementById("testfo...
eJavascript(js, tab_index, windex), expect_retval='true'), msg='Timeout waiting for webpage form to be ready to be filled in.') def _FillFormAndSubmit(self, datalist, filename, tab_index=0, windex=0): """Navigate to the form, input values into the fields, and submit the form. ...
openstack/python-openstacksdk
openstack/baremetal/v1/node.py
Python
apache-2.0
38,102
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...
e, ``AVAILABLE``, ``DEPLOYING``, ``DEPLOYWAIT``, ``DEPLOYING``, #: ``ACTIVE`` etc. target_provision_state = resource.Body("target_provision_state") #: The requested state during a state transition. target_power_state = resource.Body("target_power_state") #: The requested RAID configuration of the no...
#: Traits of the node. Introduced in API microversion 1.37. traits = resource.Body("traits", type=list) #: Timestamp at which the node was last updated. updated_at = resource.Body("updated_at") # Hardware interfaces grouped together for convenience. #: BIOS interface to use when setting BIOS pr...
royharoush/rtools
dnc.py
Python
gpl-2.0
13,314
0.026288
#! /usr/bin/env python # Copyright (C) 2009 Sebastian Garcia # # 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. # #...
a, --alias Your name alias so we can give credit to you for your help. Optional" print " -d, --debug Debuging." print " -m, --max-rate Force nmaps commands to use at most this rate. Useful to slow
nmap down. Adds the --max-rate parameter." print sys.exit(1) def check_clean(line): global debug try: outbound_chars = [';', '#', '`'] ret = True for char in outbound_chars: if char in line: ret = False return ret except Exception as inst: print 'Problem in dataReceived function' print typ...
katemsu/kate_website
kate3/mobile_apps/migrations/0002_auto__add_field_app_created_at.py
Python
mit
2,545
0.007859
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'App.created_at' db.add_column('mobile_apps_app', 'created_at', self.gf('django.db.models.f...
.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'levels'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['core.Level']"}), 'link': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'name': ('django.db.models.fields.CharField', [], {'max_leng...
oreignKey', [], {'to': "orm['mobile_apps.Type']"}) }, 'mobile_apps.type': { 'Meta': {'object_name': 'Type'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True...
FilipeMaia/afnumpy
afnumpy/core/shape_base.py
Python
bsd-2-clause
1,076
0.009294
from . import numeric as _nx from .numeric import asanyarray, newaxis def atleast_1d(*arys): res = [] for ary in arys: ary = asanyarray(ary) if len(ary.shape) == 0 : result = ary.reshape(1) else : result = ary res.append(result) if len(res) == 1: ...
[atleast_1d(_m
) for _m in tup] # As a special case, dimension 0 of 1-dimensional arrays is "horizontal" if arrs[0].ndim == 1: return _nx.concatenate(arrs, 0) else: return _nx.concatenate(arrs, 1)
Crimson-Star-Software/data-combine
datacombine/datacombine/migrations/0001_initial.py
Python
mit
7,003
0.003427
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-08-25 16:19 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Crea...
ls.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='datacombine.ConstantContactList')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='datacombine.Contact')), ],
), migrations.AddField( model_name='contact', name='cc_lists', field=models.ManyToManyField(through='datacombine.UserStatusOnCCList', to='datacombine.ConstantContactList'), ), migrations.AddField( model_name='contact', name='cell...
allegro/django-powerdns-dnssec
powerdns/migrations/0015_auto_20151214_0632.py
Python
bsd-2-clause
1,537
0.002602
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.core.validators import powerdns.models.powerdns class Migration(migrations.Migration): dependencies = [ ('powerdns', '0014_auto_20151124_0505'), ] operations = [ migrat...
me='Unrestricted', help_text="Can users that are not owners of this domain add recordsto it without owner's permission?"), ), migrations.AddField( model_name='domainrequest', name='unrestricted', field=models.BooleanField(default=False, verbose_name='Unrestricted', he...
domain add recordsto it without owner's permission?"), ), migrations.AddField( model_name='domaintemplate', name='unrestricted', field=models.BooleanField(default=False, verbose_name='Unrestricted', help_text="Can users that are not owners of this domain add recordst...
jlopezpena/bearcart
docs/conf.py
Python
mit
7,820
0.007417
# -*- coding: utf-8 -*- # # bearcart documentation build configuration file, created by # sphinx-quickstart on Mon May 6 20:08:35 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # Al...
, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when
looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to...
avishek-r-kumar/dfitools
MD_DFI_analysis/makecpptraj.py
Python
bsd-3-clause
1,742
0.030425
#!/usr/bin/env python """ Makecpptraj =========== Usage ----- ./makecpptraj.py title trajlen interval parm traj """ import sys def getwindow(trajlen,interval=2000): i = trajlen timewindows=[] while i > 0: timewindows.append(i) i = i - interval timewindows.append(0) return tim...
f i+1 >= len(trajcuts): break fname="{title}_{start}_{end}.cpptraj".format(title=title,start=trajcuts[i],end=trajcuts[i+1]) with open(fname,'w') as outfile: print "Writing out to:",fname outfile.write( makecpptrajscript(title,trajcuts[i], trajcuts[i+1],parm,traj) ) i...
ys.exit() title=sys.argv[1] trajlen=int(sys.argv[2]) interval=int(sys.argv[3]) if(len(sys.argv)) > 4: parm = sys.argv[4] traj = sys.argv[5] outputcpptrajscript(title,trajlen,interval,parm,traj) else: outputcpptrajscript(title,trajlen,interval)
juice-ryang/online-judge
OnlineJudgeServer/process_capsule.py
Python
gpl-3.0
5,696
0
"""Process Capsule: The PExpect Wrapper.""" from errno import ESRCH as NoSuchProcess from os import kill, environ from os.path import join from signal import SIGTERM as CTRL_C from chardet import detect as Chardet from pexpect import ( spawn, TIMEOUT, EOF, ) __author__ = "Minho Ryang ([email protected]...
try: kill(sel
f._initialized_pid, CTRL_C) except OSError as exc: if exc.errno != NoSuchProcess: raise exc def __enter__(self): return self def __exit__(self, *exc): self.__del__() def __cmd__(self): return 'bash -c "./%s 2>&1 #%s"' % (self.program...
marscher/PyEMMA
pyemma/coordinates/tests/test_stride.py
Python
lgpl-3.0
4,463
0.002241
# This file is part of PyEMMA. # # Copyright (c) 2015, 2014 Computational Molecular Biology Group, Freie Universitaet Berlin (GER) # # PyEMMA is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either vers...
f): for stride in range(1, 100, 23): r = coor.source(self.trajnames, top=self.temppdb) tau = 5 try: t = coor.tica(r, lag=tau, stride=stride, dim=2) # force_eigenvalues_le_one=True enables an internal consistency check in TICA se...
) except RuntimeError: assert tau % stride != 0 @classmethod def tearDownClass(cls): for fname in cls.trajnames: os.unlink(fname) os.unlink(cls.temppdb) super(TestStride, cls).tearDownClass() if __name__ == "__main__": unittest.main()
bright-pan/my_data_sync
old2new.py
Python
gpl-2.0
11,662
0.017869
# -*- coding: utf-8 -*- __author__ = 'Bright Pan' # 注意:我们必须要把old数据库中的yehnet_customer表中的postdate改成add_time import types import urllib.request try: import simplejson as json except Exception: import json import pymysql import datetime import sys print(sys.getdefaultencoding()) def f(x): if isinst
ance(x, str): return x.encode("gbk", "ignore").decode("gbk") return x class DB(object): def __init__(self, host="localhost", user="root", passwd="", old_db="", new_db="",charset="utf8"): self.new_conn=pymysql.connect(host=host,user=user,passwd=passwd,db=new_db,charset=charset, cursorclass=pymy...
ctCursor) self.new_cur = self.new_conn.cursor() self.old_cur = self.old_conn.cursor() def db_clear_data(self): self.new_cur.execute("show tables") qs_new = self.new_cur.fetchall() print(qs_new) for each in qs_new: self.new_cur.execute("truncate %s" % each...
J535D165/recordlinkage
tests/test_measures.py
Python
bsd-3-clause
4,180
0.000478
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division import recordlinkage as rl import numpy import pandas FULL_INDEX = pandas.MultiIndex.from_product( [[1, 2, 3], [1, 2, 3]], # 3x3 matrix names=['first', 'second']) LINKS_TRUE = pandas.MultiIndex.from_tuples( [(1, 1), (2, 2), (...
rec)) assert rl.fscore(LINKS_TRUE, LINKS_PRED) == expected assert rl.fscore(cm) == expected def test_full_inde
x_size(self): df_a = pandas.DataFrame(numpy.arange(10)) df_b = pandas.DataFrame(numpy.arange(10)) assert rl.full_index_size(df_a) == 45 assert rl.full_index_size(len(df_a)) == 45 assert rl.full_index_size((len(df_a))) == 45 assert rl.full_index_size([len(df_a)]) == 45 ...
mdhaman/superdesk-core
superdesk/io/commands/add_provider.py
Python
agpl-3.0
2,040
0.003431
# -*- 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 import super...
= superdesk.app.validator(superdesk.app.config['DOMAIN']['ingest_providers']['schema'], 'ingest_providers') validation = validator.validate(data) if validation: get_resource_service('ingest_providers').post([data]) ...
else: ex = Exception('Failed to add Provider as the data provided is invalid. Errors: {}' .format(str(validator.errors))) raise ProviderError.providerAddError(exception=ex, provider=data) except Exception as ex: raise ProviderError.pr...
naturalness/unnaturalcode
unnaturalcode/pythonSource.py
Python
agpl-3.0
4,032
0.010665
#!/usr/bin/python # Copyright 2013, 2014 Joshua Charles Campbell, Alex Wilson, Eddie Santos # # This file is part of UnnaturalCode. # # UnnaturalCode 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 Softwa...
ize.generate_tokens(StringIO(code).readline, mid_line) return [pythonLexeme.fromTuple(t) for t in tokGen] def unCommented(self): assert len(self) return filter(lambda a: not a.comment(), copy(self)) def scrubbed(self): """Clean up python source code remo...
i = 0 r = [] for i in range(0, len(ls)): if ls[i].comment(): continue elif ls[i].ltype == 'NL': continue elif ls[i].ltype == 'NEWLINE' and i < len(ls)-1 and ls[i+1].ltype == 'NEWLINE': continue elif l...
tweekmonster/django-userjs
userjs/utils.py
Python
bsd-3-clause
1,325
0
import six import json from userjs.userjs_settings import JSON_HANDLERS def _json_handlers(obj): """Extra handlers that JSON aren't able to parse. The only built-in conversion is for datetime. User configured handlers are tried for other types. If they all fail, raise TypeError. """ if hasattr...
this in Django that's available to use. """ value = obj for field in fiel
d_name.split('__'): if not hasattr(value, field): return None value = getattr(value, field) if six.callable(value): return value() return value
Aladom/django-mailing
django_mailing/wsgi.py
Python
mit
405
0
""" WSGI config for django_mai
ling 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.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_mailing.settings") application = get_wsgi_application()
googleads/google-ads-python
google/ads/googleads/v8/enums/types/campaign_experiment_traffic_split_type.py
Python
apache-2.0
1,292
0.000774
# -*- 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 distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either ex...
ge governing permissions and # limitations under the License. # import proto # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v8.enums", marshal="google.ads.googleads.v8", manifest={"CampaignExperimentTrafficSplitTypeEnum",}, ) class CampaignExperimentTrafficSplitTypeEnum(proto...
wuzheng-sjtu/FastFPN
libs/preprocessings/city_v1.py
Python
apache-2.0
3,441
0.011334
#!/usr/bin/env python # coding=utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import tensorflow as tf import libs.configs.config_v1 as cfg from . import utils as preprocess_utils FLAGS = tf.app.flags.FLAGS def preprocess_image(image, g...
s(image, 0) image = tf.image.resize_bilinear(image, [new_ih, new_iw], align_corners=False) image = tf.squeeze(image, axis=[0]) #gt_masks = tf.expand_dims(gt_masks, -1) #gt_masks = tf.cast(gt_masks, tf.float32) #gt
_masks = tf.image.resize_nearest_neighbor(gt_masks, [new_ih, new_iw], align_corners=False) #gt_masks = tf.cast(gt_masks, tf.int32) #gt_masks = tf.squeeze(gt_masks, axis=[-1]) scale_ratio = tf.to_float(new_ih) / tf.to_float(ih) gt_boxes = preprocess_utils.resize_gt_boxes(gt_boxes, scale_ratio) ## r...
mvesper/invenio-circulation
tests/test_api.py
Python
gpl-2.0
3,899
0
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016 CERN. # # Invenio is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later...
obj = _api.create(*val) _id = obj.id assert obj.get(_id) #
Test update _api.update(obj, **dict([(changes[key], 'bar')])) assert getattr(obj.get(_id), changes[key]) == 'bar' # Test delete _api.delete(obj) try: obj.get(_id) raise AssertionError('The object should not be there anymore.')...
ddevlin/GitSavvy
common/interwebs.py
Python
mit
2,509
0.001594
"
"" A simple HTTP interface for making GET, PUT and POST requests. """ import http.client import json from urllib.parse import urlparse, urlencode # NOQA from base64 import b64encode from functools import partial from collections import namedtuple Respon
se = namedtuple("Response", ("payload", "headers", "status", "is_json")) def request(verb, host, port, path, payload=None, https=False, headers=None, auth=None, redirect=True): """ Make an HTTP(S) request with the provided HTTP verb, host FQDN, port number, path, payload, protocol, headers, and auth infor...
Shrews/PyGerrit
webapp/django/contrib/gis/utils/layermapping.py
Python
apache-2.0
29,814
0.005601
# LayerMapping -- A Django Model/OGR Layer Mapping
Utility """ The LayerMapping class provides a way to map the contents of OGR vector files (e.g. SHP files) to Geographic-enabled Django models. This grew out of my personal needs, s
pecifically the code repetition that went into pulling geometries and fields out of an OGR layer, converting to another coordinate system (e.g. WGS84), and then inserting into a GeoDjango model. Please report any bugs encountered using this utility. Requirements: OGR C Library (from GDAL) required. Usage: ...
tersmitten/ansible
lib/ansible/modules/database/mysql/mysql_db.py
Python
gpl-3.0
15,596
0.002501
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2012, Mark Theunissen <[email protected]> # Sponsored by Four Kitchens http://fourkitchens.com. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_functi...
le_transaction=None, quick=None, ignore_tables=None): cmd = module.get_bin_path('mysqldump', True) # If defined, mysqldump demands --defaults-extra-file be the first option if config_file: cmd += " --defaults-extra-file=%s" % pipes.quote(config_file) if user is not None:
cmd += " --user=%s" % pipes.quote(user) if password is not None: cmd += " --password=%s" % pipes.quote(password) if ssl_cert is not None: cmd += " --ssl-cert=%s" % pipes.quote(ssl_cert) if ssl_key is not None: cmd += " --ssl-key=%s" % pipes.quote(ssl_key) if ssl_ca is not No...
scop/bash-completion
test/t/test_kpdf.py
Python
gpl-2.0
502
0
import p
ytest from conftest import assert_complete, create_dummy_filedirs @pytest.mark.bashcomp(temp_cwd=True) class TestKpdf: def test_1(self, bash): files, dirs = create_dummy_filedirs(
".eps .EPS .pdf .PDF .ps .PS .txt".split(), "foo".split(), ) completion = assert_complete(bash, "kpdf ") assert completion == [ x for x in sorted(files + ["%s/" % d for d in dirs]) if x.lower() != ".txt" ]
0x1306e6d/Baekjoon
baekjoon/2439.py
Python
gpl-2.0
326
0.003125
""" 2439 : 별 찍기 -
2 URL : https://www.acmicpc.net/problem/2439 Input : 5 Output : * ** *** **** ***** """ from itertools import repeat N = int(input()) for i in range(1, N + 1): print(''.join(list(repeat(' ', N - i)) + list(r
epeat('*', i))))
sivakuna-aap/superdesk
server/apps/ldap/commands.py
Python
agpl-3.0
2,913
0.004806
# -*- 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 import loggi...
ose profile need to be imported need not to be the same. Uses ad_username and ad_password to bind to AD and then searches for
a user identified by username_to_import and if found imports into Mongo. """ option_list = ( superdesk.Option('--ad_username', '-adu', dest='ad_username', required=True), superdesk.Option('--ad_password', '-adp', dest='ad_password', required=True), superdesk.Option('--username_to_impor...
appsembler/awstrial
awstrial/trial/context_processors.py
Python
agpl-3.0
532
0.003759
''' Context processors for AWSTrial pages ''' from django.conf import settings def google_analytics_id(request): """Adds the google analytics id to the context if it's present.""" return { 'google
_analytics_id': getattr(settings, 'GOOGLE_ANALYTICS_ID', None), } def theme_assets_root(request): """Adds the ASSET_ROOT variable from the settings file""
" root = getattr(settings, 'ASSET_ROOT', '') if root.endswith('/'): root = root[:-1] return { 'ASSET_ROOT': root, }
nathanbullock/pymtp-nkb
pymtp/main.py
Python
gpl-3.0
23,914
0.031237
#!/usr/bin/env python #
-*- coding: iso-8859-1 -*- # # PyMTP # Developed by: Nick Devito ([email protected]) # (c) 2008 Nick Devito # Released under the GPLv3 or later. # import os import ctypes import ctypes.util from models import * from constants import * from errors import * _module_path = ctypes.util.find_library("mtp") _libmtp = ctype...
alized once) _libmtp.LIBMTP_Init() # ---------- # Type Definitions # ---------- _libmtp.LIBMTP_Detect_Raw_Devices = ctypes.c_int _libmtp.LIBMTP_Get_Friendlyname.restype = ctypes.c_char_p _libmtp.LIBMTP_Get_Serialnumber.restype = ctypes.c_char_p _libmtp.LIBMTP_Get_Modelname.restype = ctypes.c_char_p _libmtp.LIBMTP_Get_...
pocketone/django-shoppy
shoppy/shop/management/commands/shoppy_updatePermissions.py
Python
bsd-3-clause
893
0.003359
#!/usr/bin/python # -*- coding: iso-8859-15 -*- from django.core.management.base import NoArgsCommand class Command(NoArgsCommand): help = "Update permissions without using syncdb." de
f handle_noargs(self, **options): from django.core.management import setup_environ try: import settings except ImportError: import sys sys.stderr.write("Couldn't find the settings
.py module.") sys.exit(1) setup_environ(settings) # Add any missing content types from django.contrib.contenttypes.management import update_all_contenttypes update_all_contenttypes() # Add any missing permissions from django.contrib.auth.management import c...
claimsmall/waterbug
app_config.py
Python
mit
5,956
0.002015
#!/usr/bin/env python """ Project-wide application configuration. DO NOT STORE SECRETS, PASSWORDS, ETC. IN THIS FILE. They will be exposed to users. Use environment variables instead. See get_secrets() below for a fast way to access them. """ import os from authomatic.providers import oauth2 from authomatic import ...
LE_OAUTH_CLIENT_ID'), 'consumer_secret': os.environ.get('GOOGLE_OAUTH_CONSUMER_SECRET'), 'scope': ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/userinfo.email'], 'offline': True, }, } authomatic = Authomatic(authomatic_config, os.environ.get('AUTHOMATIC_SALT')) ...
thod for accessing our secrets. """ secrets_dict = {} for k,v in os.environ.items(): if k.startswith(PROJECT_SLUG): k = k[len(PROJECT_SLUG) + 1:] secrets_dict[k] = v return secrets_dict def configure_targets(deployment_target): """ Configure deployment targets....
47lining/ansible-modules-core
network/basics/get_url.py
Python
gpl-3.0
11,195
0.004288
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Jan-Piet Mens <jpmens () gmail.com> # # 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 L...
version_added: '1.6' others: description: - all arguments accepted by the M(file) module also work here required: false notes: - This module doesn't yet support co
nfiguration for proxies. # informational: requirements for nodes requirements: [ urllib2, urlparse ] author: Jan-Piet Mens ''' EXAMPLES=''' - name: download foo.conf get_url: url=http://example.com/path/file.conf dest=/etc/foo.conf mode=0440 - name: download file with sha256 check get_url: url=http://example.com/...
dotKom/onlineweb4
apps/sso/endpoints.py
Python
mit
1,048
0.001908
# -*- coding: utf8 -*- # # Created by 'myth' on 6/27/15 from django.http import JsonResponse from oauth2_provider.decorators import protected_resource from apps.sso.userinfo import Onlineweb4Userinfo USERINFO_SCOPES = [ 'authentication.onlineuser.username.read', 'authentication.onlineuser.first_name.read', ...
pplication :
param request: The Django Request object :return: An HTTP response """ return JsonResponse(status=200, data=Onlineweb4Userinfo(request.user).oauth2())
uclouvain/osis
ddd/logic/preparation_programme_annuel_etudiant/domain/service/get_programme_inscription_cours.py
Python
agpl-3.0
8,497
0.002707
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core ...
) ) return contenu @classmethod def __build_unite_enseignement_ajoute_dtos( cls, groupement: 'ContenuGroupementCatalogueDTO', groupements_ajustes: List['GroupementAjusteInscriptionCours'], unite_enseignement_ajoutes_dto: List...
) -> List['UniteEnseignementAjouteeDTO']: groupement_ajuste_correspondant = next( ( groupement_ajuste for groupement_ajuste in groupements_ajustes if groupement_ajuste.groupement_id.code == groupement.groupement_contenant.code ), ...
cwmartin/rez
src/rez/release_vcs.py
Python
lgpl-3.0
8,750
0.000457
from rez.exceptions import ReleaseVCSError from rez.packages_ import get_developer_package from rez.util import which from rez.utils.system import popen from rez.utils.logging_ import print_debug from rez.utils.filesystem import walk_up_dirs from pipes import quote import subprocess def get_release_vcs_types(): "...
) classes_by_level = {} for vcs_name in vcs_types: cls = plugin_manager.get_
plugin_class('release_vcs', vcs_name) result = cls.find_vcs_root(path) if not result: continue vcs_path, levels_up = result classes_by_level.setdefault(levels_up, []).append((cls, vcs_path)) if not classes_by_level: raise ReleaseVCSError("No version control syste...
anubhavshrimal/Data_Structures_Algorithms_In_Python
Tree/BinarySearchTree/Lowest_Common_Ancestor.py
Python
mit
1,935
0
# Find the Lowest Common Ancestor (LCA) in a Binary Search Tree # A Binary Search Tree node class Node: # Constructor to initialise node def __init__(self, data): self.data = data self.left = None self.right = None class BST: def __init__(self): self.root = None def ...
ght elif value2 < root.data > value1: root = root.left else: return root.data if __name__ == '__main__': tree = BST() tree.insert_node(6) tree.insert_node(8) tree.insert_node(9) tree.insert_node(6) tree.insert_node(5) tree.insert_node(7) tree.ins...
7 9 3 2 4 """
gangadhar-kadam/sapphite_lib
webnotes/model/doc.py
Python
mit
20,173
0.044218
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. # MIT License. See license.txt from __future__ import unicode_literals """ Contains the Document class representing an object / record """ _toc = ["webnotes.model.doc.Document"] import webnotes import webnotes.model.meta import MySQLdb from webnotes.utils impo...
ired' self.name = n.strip() elif autoname and autoname.startswith("naming_series:"): self.set_naming_s
eries() if not self.naming_series: webnotes.msgprint(webnotes._("Naming Series mandatory"), raise_exception=True) self.name = make_autoname(self.naming_series+'.#####') # based on expression elif autoname and autoname.startswith('eval:'): doc = self # for setting self.name = eval(autoname[5:]) ...
lukas-hetzenecker/home-assistant
homeassistant/components/plex/server.py
Python
apache-2.0
25,421
0.001377
"""Shared class to maintain Plex server instances.""" import logging import ssl import time from urllib.parse import urlparse from plexapi.client import PlexClient from plexapi.exceptions import BadRequest, NotFound, Unauthorized import plexapi.myplex import plexapi.playqueue import plexapi.server from requests import...
assistant.helpers.dispatcher import async_dispatcher_send f
rom .const import ( CONF_IGNORE_NEW_SHARED_USERS, CONF_IGNORE_PLEX_WEB_CLIENTS, CONF_MONITORED_USERS, CONF_SERVER, CONF_USE_EPISODE_ART, DEBOUNCE_TIMEOUT, DEFAULT_VERIFY_SSL, DOMAIN, GDM_DEBOUNCER, GDM_SCANNER, PLAYER_SOURCE, PLEX_NEW_MP_SIGNAL, PLEX_UPDATE_MEDIA_PLAY...
mellis13/moose
scripts/memory_logger.py
Python
lgpl-2.1
43,940
0.013359
#!/usr/bin/env python from tempfile import TemporaryFile, SpooledTemporaryFile import os, sys, re, socket, time, pickle, csv, uuid, subprocess, argparse, decimal, select, platform class LLDB: def __init__(self): self.debugger = lldb.SBDebugger.Create() self.command_interpreter = self.debugger.GetCommandInter...
self.startServer() else: print 'I could not find your PBS_NODEFILE. Is PBS loaded?' sys.exit(1) # If we are not a server, start the single client else:
self.startClient() def startServer(self): # Setup the TCP socket self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.bind((socket.gethostname(), 0)) self.server_socket.listen(5) (self.host, self.port) = self.server_socket.getsockname() # We will stor...
labordoc/labordoc-next
modules/bibformat/lib/elements/bfe_ILO_conventions_link.py
Python
gpl-2.0
1,688
0.013626
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either ve...
t will be usefu
l, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## #<BFE_ILO_CONVENTIONS prefix='<br/><small class="quicknote">' suffix="</small>" # ## You should have received a copy of the GNU General...
gangadhar-kadam/hrshop
shopping_cart/config/desktop.py
Python
agpl-3.0
176
0.039773
data = { "Shopping Cart": { "color": "#B7E0
90", "icon": "icon-shopping-cart",
"label": "Shopping Cart", "link": "Form/Shopping Cart Settings", "type": "module" } }
ssorgatem/pulsar
pulsar/client/transport/poster.py
Python
apache-2.0
1,308
0.002294
from __future__ import absolute_import import logging try: from urllib2 import urlopen except ImportError: from urllib.request import urlopen try: from urllib2 import Request except ImportError:
from urllib.request import Request try: from galaxy import eggs eggs.require("poster")
except ImportError: pass try: import poster except ImportError: poster = None POSTER_UNAVAILABLE_MESSAGE = "Pulsar configured to use poster module - but it is unavailable. Please install poster." log = logging.getLogger(__name__) if poster is not None: poster.streaminghttp.register_openers() def ...
google/llvm-propeller
mlir/integration_test/lit.cfg.py
Python
apache-2.0
1,725
0
# -*- Python -*- import os import platform import re import subprocess import tempfile import lit.formats import lit.util from lit.llvm import llvm_config from lit.llvm.subst import ToolSubst # Configuration file for the 'lit' integration test runner. # name: The name of this integration test suite. config.name = ...
t path where integration tests are located. config.test_source_root = os.path.dirname(__file__) # test_exec_root: The root path where integration tests should be run. config.test_exec_root = os.path.join(config.mlir_obj_root, 'integration_test') config.substitutions.append(('%PATH%', config.environment['PATH'])) conf...
substitutions.append(('%shlibext', config.llvm_shlib_ext)) config.substitutions.append(('%mlir_src_root', config.mlir_src_root)) llvm_config.with_system_environment(['HOME', 'INCLUDE', 'LIB', 'TMP', 'TEMP']) llvm_config.use_default_substitutions() # excludes: A list of directories to exclude from the integration tes...
BansheeMediaPlayer/bockbuild
packages/mono-addins.py
Python
mit
144
0.0625
Git
HubPackage ('mono', 'mono-addins', '0.6.2', 'adcd75bb47ffc1665c8c410f44dad3511dec0da0', configure = './autogen.s
h --prefix="%{prefix}"' )
druss316/G-Harvestor
html/udPassword.py
Python
gpl-3.0
2,697
0.001854
#!/usr/bin/python """ Copyright 2016 Paul Willworth <[email protected]> This file is part of Galaxy Harvester. Galaxy Harvester 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 th...
) import dbInfo # Get current url try: url = os.environ['SCRIPT_NAME'] except KeyError: url = '' form = cgi.FieldStorage() # Get Cookies errorstr = '' cookies = Cookie.SimpleCookie() try: cookies.load(os.environ['HTTP_COOKIE']) except KeyError: errorstr = 'no cookies\n' if errorstr == '': try: ...
except KeyError: loginResult = 'success' try: sid = cookies['gh_sid'].value except KeyError: sid = form.getfirst('gh_sid', '') else: currentUser = '' loginResult = 'success' sid = form.getfirst('gh_sid', '') userpass = form.getfirst("userpass") # escape input to prevent s...
rahulsharma1991/frontera
frontera/contrib/canonicalsolvers/__init__.py
Python
bsd-3-clause
78
0.012821
# -*- coding: utf-8 -*- from . impo
rt basic Basic
= basic.BasicCanonicalSolver
chuckus/chromewhip
chromewhip/base.py
Python
mit
1,195
0.001674
# https://stackoverflow.com/questions/30155138/how-can-i-write-asyncio-coroutines-that-optionally-act-as-regular-functions import asyncio class SyncAdder
(type): """ A metaclass which adds synchronous version of coroutines. This metaclass finds all coroutine functions defined on a class and adds a synchronous version with a '_s' suffix appended to the original function name. """ def __new__(cls, clsname, bases, dct, **kwargs): new_dct =...
nc version of all coroutine functions if asyncio.iscoroutinefunction(val): meth = cls.sync_maker(name) syncname = '{}_s'.format(name) meth.__name__ = syncname meth.__qualname__ = '{}.{}'.format(clsname, syncname) new_dct[syncnam...
goldhand/art-portfolio
art-portfolio/imagestore/urls.py
Python
bsd-3-clause
1,663
0.00902
from django.conf.
urls import patterns, url from views import (AlbumListView, ImageListView, UpdateImage, UpdateAlbum, CreateImage, CreateAlbum, DeleteImage, \ DeleteAlbum, ImageView, AlbumList) urlpatterns = patterns('imagestore.views', url(r'^$', AlbumListView.as_view(), name='index'), ...
'album'), url(r'^album/(?P<pk>\d+)/edit/$', UpdateAlbum.as_view(), name='update-album'), url(r'^album/(?P<pk>\d+)/delete/$', DeleteAlbum.as_view(), name='delete-album'), url(r'^tag/(?P<tag>[^/]+)/$', ImageListView.as_view(), name='tag'), ...
ledbutter/ProjectEulerPython
Problem46.py
Python
mit
1,921
0.032795
# It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. # 9 = 7 + 2x1^2 # 15 = 7 + 2x2^2 # 21 = 3 + 2x3^2 # 25 = 7 + 2x3^2 # 27 = 19 + 2x2^2 # 33 = 31 + 2x1^2 # It turns out that the conjecture was false. # What is the smallest odd c...
ight, com
posite_odds))) #5777 #mine: works fairly fast # from itertools import count, takewhile # from Utils import is_prime, primes_sieve # #first come up with iterator to generate all odd composite numbers # composite_odds = filter(lambda x: not is_prime(x), count(35, 2)) # # i = 0 # # for c in composite_odds: ...
googleads/googleads-adxbuyer-examples
python/samples/v2_x/list_invitations.py
Python
apache-2.0
2,388
0.0067
#!/usr/bin/python # # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
_argument( '-a', '--account_id', default=DEFAULT_ACCOUNT_ID, type=int, help='The integer id of the Author
ized Buyers account.') parser.add_argument( '-c', '--client_buyer_id', default=DEFAULT_CLIENT_BUYER_ID, type=int, help='The integer id of the client buyer.') args = parser.parse_args() try: service = samples_util.GetService('v2beta1') except IOError as ex: print(f'Unable to create adexchang...
vishesh/pycket
pycket/test/test_struct.py
Python
mit
17,186
0.0032
from pycket.test.testhelper import * from pycket.values import * import pytest skip = pytest.mark.skipif("True") # Creating Structure Types def test_make_struct_type(doctest): """ > (define-values (struct:a make-a a? a-ref a-set!) (make-struct-type 'a #f 2 1 'uninitialized)) > (define an-a (make...
b-ref a-b 1) 'b-uninitialized > (b-ref a-b 2) 'b-uninitialized ;;;;;;;;;;;;;;;; > (define p1 #s(p a b c)) > (define-values (struct:p make-p p? p-ref p-set!) (make-struct-type 'p #f
3 0 #f null 'prefab #f '(0 1 2))) > (p? p1) #t > (p-ref p1 0) 'a > (make-p 'x 'y 'z) '#s(p x y z) """ assert doctest def test_make_struct_type2(doctest): """ ! (require racket/private/generic-interfaces) > (struct color (r g b) #:constructor-name -color) > (struct recta...
heathseals/CouchPotatoServer
libs/pyutil/scripts/time_comparisons.py
Python
gpl-3.0
8,758
0.003882
# If you run this file, it will make up a random secret and then crack it # using timing information from a string comparison function. Maybe--if it # gets lucky. It takes a long, long time to work. # So, the thing I need help with is statistics. The way this thing works is # extremely stupid. Suppose you want to know...
D, then after that every next step it takes will be the # "drawing from the same distribution" kind -- any difference between ABCXQ # and ABCXR will be just due to noise, since both are equally far from the # correct answer, which startsw with ABCD. If it could realize that there is # no real difference between the dis...
Giving the ability to measure, noisily, the time taken by comparison(), # how can you most efficiently figure out which guess takes the longest? If # you can do that more efficiently, you can crack secrets more efficiently. # The script takes two arguments. The first is how many symbols in the # secret, and the second...
dracos/QGIS
python/plugins/processing/gui/EditScriptAction.py
Python
gpl-2.0
2,221
0
# -*- coding: utf-8 -*- """ *************************************************************************** EditScriptAction.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com **********************...
ScriptEditorDialog from processing.algs.r.RAlgorithm import RAlgorithm from processing.script.ScriptAlgorithm import ScriptAlgorithm class EditScriptAction(ContextAction): SCRIPT_PYTHON = 0 SCRIPT_R = 1 def __init__(self, scriptType): self.name = self.tr('Edit script', 'EditScriptAction') ...
alog.SCRIPT_PYTHON: return isinstance(self.alg, ScriptAlgorithm) and self.alg.allowEdit elif self.scriptType == ScriptEditorDialog.SCRIPT_R: return isinstance(self.alg, RAlgorithm) def execute(self): dlg = ScriptEditorDialog(self.scriptType, self.alg) dlg.show() ...
vishalsahu5/carpool
journeys/__init__.py
Python
mit
51
0
default_app_config = 'journeys
.app
s.JourneyConfig'
conikuvat/edegal
backend/larppikuvat/migrations/0001_initial.py
Python
mit
1,162
0.001721
# Generated by Django 3.0.7 on 2020-09-27 13:39 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('edegal', '0025_photographer_flickr_handle'), ] operations = [ migrations.CreateModel( ...
blank=True)), ('copy_protection', models.TextField(blank=True)),
('expected_compensation', models.TextField(blank=True)), ('photographer', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='larppikuvat_profile', to='edegal.Photographer')), ], ), ]
felipegerard/arte_mexicano_antiguo
montactuaria/Analisis_access_log/luigi/ functions/functions.py
Python
agpl-3.0
362
0.005525
import shutil from pprint import pprint import
pandas as pd import csv import pickle import inspect, os import requests from os import listdir import numpy as np import subprocess from luigi import six from sklearn.decomposition import NMF from
sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.naive_bayes import MultinomialNB
jhprinz/openpathsampling
openpathsampling/high_level/transition.py
Python
lgpl-2.1
19,446
0.002263
import logging import numpy as np import openpathsampling as paths from openpathsampling.numerics import ( Histogram, histograms_to_pandas_dataframe, LookupFunction, Histogrammer ) from openpathsampling.numerics import WHAM from openpathsampling.netcdfplus import StorableNamedObject from openpathsampling.analysi...
f_args={}, hist_args={} ) } self.minus_ensemble = paths.MinusInterfaceEnsemble( state_vol=stateA, innermost_vols=interfaces[0] ).named("Out " + stateA.name + " minus") def copy(self, with_results=True): copy
= self.from_dict(self.to_dict()) copy.copy_analysis_from(self) return copy def copy_analysis_from(self, other): self.default_orderparameter = other.default_orderparameter self.total_crossing_probability_method = other.total_crossing_probability_method self.hist_args = other....
avalentino/PyTables
examples/carray1.py
Python
bsd-3-clause
468
0
import numpy as np import tables as tb fileName = 'carray1.h5' shape = (200, 300) atom = tb.UInt8Atom() filters = tb.Filters(complevel=5, complib='zlib') h5f = tb.open_file(fileName, 'w') ca = h5f.create_carray(h5f.root, 'carray', atom, shape, filters=filters) # Fill a hyperslab in ``ca``. ca[10:60, 20:70] = np.ones(...
h5f.close()
deployed/django-emailtemplates
emailtemplates/migrations/0006_auto_20201110_1151.py
Python
mit
689
0.002903
# Generated by Django 3.1.2 on 2020-11-10 11:51 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('emailtemplates', '0005_auto_20201110_1115'), ] operations = [ migrations.AlterField( model_name='em...
ate', name='created', field=models.DateTimeField(default=django.utils.timezone.now, verbose_name='created'),
), migrations.AlterField( model_name='emailtemplate', name='modified', field=models.DateTimeField(default=django.utils.timezone.now, verbose_name='modified'), ), ]
lcpt/xc
python_modules/import_export/sciaXML/scia_loads/LoadCaseContainer.py
Python
gpl-3.0
2,570
0.040109
# -*- coding: utf-8 -*- #Based on sXML-master projet on gitHub __author__= "Luis C. Pérez Tato (LCPT)" __copyright__= "Copyright 2015 LCPT" __license__= "GPL" __version__= "3.0" __email__= "[email protected]" __author__= "Luis C. Pérez Tato (LCPT)" __copyright__= "Copyright 2015 LCPT" __license__= "GPL" __versio...
wn action type (not permanent, not variable)." return 0 def getLoadCaseObject(loadCase): retval= obj.Object() id= str(loadCase.id) retval.setId(id) name= loadCas
e.name if(name==''): name= loadCasePrefix+id retval.setNm(name) retval.setP0(oI.ObjectItem(name)) #Name retval.setP1(oI.ObjectItem('{'+str(uuid.uuid4())+'}')) # Unique id tmp= oI.ObjectItem(str(getActionTypeCode(loadCase.actionType))) tmp.t= loadCase.actionType retval.setP2(tmp) #?? retval.setP3(oI....
FRosner/drunken-data-quality
python/setup.py
Python
apache-2.0
1,956
0.001022
#!/usr/bin/env python """ Setup file for pyddq. This file was generated with PyScaffold 2.5.6, a tool that easily puts up a scaffold for yo
ur new Python project. Learn more under: http://pyscaffold.readthedocs.org/ """ import sys import os import glob import subprocess from setuptools import setup, Command class IntegrationTestCommand(Command): description = "A command to run integration tests" user_options = [("jar=", None, "Path to Drunke...
finalize_options(self): if self.addopts is None: exit("error: option addopts should be specified in setup.cfg") elif self.jar is None: exit("error: path to Drunken Data Quality jar should be specified") def run(self): log4j_path = os.path.abspath("../src/test/resour...
OpenUpgrade-dev/OpenUpgrade
openerp/addons/test_inherit/models.py
Python
agpl-3.0
2,104
0.000951
# -*- coding: utf-8 -*- from openerp import models, fields, api, osv # We just create a new model class mother(models.Model): _name = 'test.inherit.mother' _columns = { # check interoperability of field inheritance with old-style fields 'name': osv.fields.char('Name', required=True), } ...
me = self.field_in_mother else: super(mother, self)._compute_surname() class mother(models.Model): _inherit = 'test.inherit.mother' # extend again the selection
of the state field state = fields.Selection(selection_add=[('d', 'D')]) class daughter(models.Model): _inherit = 'test.inherit.daughter' # simply redeclare the field without adding any option template_id = fields.Many2one() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Xilinx/meta-petalinux
lib/devtool/plnx-sdk-update.py
Python
mit
6,269
0.005104
#******************************************************************************* # # Copyright (C) 2019 Xilinx, Inc. All rights reserved. # # 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 w...
d_uninative_checksums(os.path.join(basepath, 'conf/local.conf')) newsums = read_uninative_checksums(os.path.join(updateserver, 'conf/local.conf')) if oldsums != newsums: uninative = True if uninative: shutil.rmtree(os.path.join(basepath, 'downloads', 'uninative')) shutil...
ating configuration files") new_conf_dir = os.path.join(updateserver, 'conf') shutil.rmtree(conf_dir) shutil.copytree(new_conf_dir, conf_dir) logger.info("Updating layers") new_layers_dir = os.path.join(updateserver, 'layers') shutil.rmtree(layers_dir) ret = subprocess.call("cp -a %s %s" % ...
nferch/acd_cli
acdcli/api/metadata.py
Python
gpl-2.0
10,176
0.002752
"""Node metadata operations""" import json import logging import http.client from collections import namedtuple from .common import * logger = logging.getLogger(__name__) ChangeSet = namedtuple('Changes', ['nodes', 'purged_nodes', 'checkpoint', 'reset']) class MetadataMixin(object): def get_node_list(self, **...
ms=params) if r.status_code not in OK_CODES: raise RequestError(r.status_code, r.text)
data = r.json() if 'id' in data['data'][0]: return data['data'][0]['id'] def list_children(self, node_id: str) -> list: l = self.BOReq.paginated_get(self.metadata_url + 'nodes/' + node_id + '/children') return l def add_child(self, parent_id: str, child_id: str) -...
asajeffrey/servo
etc/start_servo.py
Python
mpl-2.0
992
0.001008
# Copyright 2018 The Servo Project Developers. See the COPYRIGHT # file at the top-level directory of this distribution. # # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your #...
The script is intended to start servo on localhost:7002 """ import subprocess def start_servo(port, resolution): # Use the below command if you are running this script on windows # cmds =
'mach.bat run --webdriver ' + port + ' --resolution ' + resolution cmds = './mach run --webdriver=' + port + ' --resolution ' + resolution process = subprocess.Popen(cmds, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return process
janezd/kontrabant
kontrabant.py
Python
gpl-3.0
40,758
0.000589
## Unquill: Copyright (C) 2003 Janez Demsar ## ## During development I peeked a lot at Unquill from John Elliott, 1996-2000. ## ## 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...
ARRIED): self.objects[param1].location = self.location_no else: self.printout("Tega sploh nimam.") return -1 def do_remove(self, param1): loc = self.objects[param1].location if loc != self.Object.WORN: self.printout("Tega sploh ne nosim!") ...
lse: self.objects[param1].location = self.Object.CARRIED def do_dropall(self): for obj in self.objects: if obj.location == self.Object.WORN or \ obj.location == self.Object.CARRIED: obj.location = self.location_no self.flags[1] = 0 ...
JonasWallin/logisticnormal
logisticnormal/PurePython/priors.py
Python
gpl-3.0
5,934
0.004887
''' Created on Jul 5, 2014 updated: May 28, 2015: added AMCMC @author: jonaswallin ''' import numpy as np import numpy.random as npr from ..utils.gammad import ln_gamma_d def f_prior_nu(x, nu=0.01): """ deafult prior for nu which is gamma returns : log of prior """ return -nu*x class n...
self.amcmc_count = 0. self.amcmc_accept = 0. def set_val(self, nu): self.nu = nu self.calc_lik = False def set_d(self, d): """ Set dimension """ self
.calc_lik = False self.d = d if self.nu is None: self.nu = 2*self.d self.ln_gamma_d = ln_gamma_d(self.d) def set_parameter(self, param): """ param - dict with ['Q'] or better ['detQ'] (which containes log det of Q) """ #print param['Q'] ...
googleapis/python-service-directory
samples/generated_samples/servicedirectory_v1_generated_registration_service_list_services_sync.py
Python
apache-2.0
1,551
0.000645
# -*- coding: utf-8 -*- # Copyright 2022 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...
odifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-service-directory # [START servicedirectory_v1_generated_RegistrationService_ListServices_sync] from google.cloud import servicedirectory_v1 def sample_list...
# Initialize request argument(s) request = servicedirectory_v1.ListServicesRequest( parent="parent_value", ) # Make the request page_result = client.list_services(request=request) # Handle the response for response in page_result: print(response) # [END servicedirectory_v1_...
biswajitsahu/kuma
vendor/packages/translate/filters/spelling.py
Python
mpl-2.0
2,109
0.000474
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2007 Zuza Software Foundation # 2013 F Wolff # # This file is part of translate. # # translate 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...
= logging.getLogger(__name__) available = False try: # Enchant from enchant import checker, Error as EnchantError available = True checkers = {} def _get_c
hecker(lang): if not lang in checkers: try: checkers[lang] = checker.SpellChecker(lang) # some versions only report an error when checking something checkers[lang].check(u'bla') except EnchantError as e: # sometimes this is ...
drxaero/calibre
src/calibre/gui2/dbus_export/menu.py
Python
gpl-3.0
14,935
0.00221
#!/usr/bin/env python2 # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' # Support for excporting Qt's MenuBars/Menus over DBUS. The API is defined i...
elf, visible): ac = self.id_to_action(0) if ac is not None and self.qmenu is not None: changed = False blocked = not visible for ac in menu_actions(ac.menu()): ac_id = self.action_to_id(ac) if ac_id is not None:
old = ac.property('blocked') if old is not blocked: ac.setProperty('blocked', blocked) self.action_changes.add(ac_id) changed = True if changed: self.action_changed_timer.start() d...
ebrehault/diazo
docs/conf.py
Python
bsd-3-clause
6,987
0.006441
# -*- coding: utf-8 -*- # # Diazo documentation build configuration file, created by # sphinx-quickstart on Tue Nov 2 18:58:07 2010. # # 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 c...
nting, acts as replacement for # |version| and |release|, also used in various other places throughout
the # built documents. # # The short X.Y version. version = '1.0b1' # The full version, including alpha/beta/rc tags. release = '1.0b1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: eithe...