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
theirc/refugeeinfo.eu
content/management/commands/syncdocs.py
Python
apache-2.0
4,605
0.003474
from __future__ import absolute_import, unicode_literals, division, print_function __author__ = 'reyrodrigues' import os import httplib2 from apiclient import discovery import oauth2client from oauth2client import client from django.core.management.base import BaseCommand from content import models import requests ...
title=location.name, html_url=document_link) content = requests.get(document_link).text cache.set(document_link, content) except Exception as e:
print(e.message) print("Error loading one of the files: {}.".format(key)) except Exception as e: pass self.stdout.write('Successfully created/updated content!') def _list_folders(self, credentials): http = credentials.authorize(httplib2.Http()) ...
netkicorp/python-partner-api-client
netki/NetkiClient.py
Python
bsd-3-clause
10,490
0.003718
__author__ = 'frank' from Certificate import Certificate from Domain import Domain from Partner import Partner from Requestor import process_request from WalletName import WalletName class Netki: """ General methods for interacting with Netki's Partner API. :param partner_id: Your Partner ID available i...
e = process_request(self, '/api/domain/%s' % domain_name if domain_name else '/api/domain', 'GET') if not response.get('domains'): return [] domain_list = list() for d in response.domain
s: domain = Domain(d.domain_name) domain.set_netki_client(self) domain_list.append(domain) return domain_list def create_partner_domain(self, domain_name, sub_partner_id=None): """ Domain Operation Create a partner domain used to offer Wallet N...
bayesimpact/bob-emploi
frontend/server/apps/__init__.py
Python
gpl-3.0
1,728
0.001736
"""Plugins defining Flas apps. Each python module in this folder should have an `app` variable at top level, with a flask.Blueprint in it. # TODO(cyrille): DRY up with modules/__init__.py """ import importlib import pkgutil import logging import os import typing import flask # Import behind guard to enable flask a...
{package.name}', __package__))
if module.app.name == 'main': # TODO(cyrille): Export main app as blueprint. # TODO(cyrille): Consider not making an exception for this one. app.register_blueprint(module.app) else: app.register_blueprint(module.app, url_prefix=f'/api/{module.app.name}')
ioniATX/DHT_oblivion
Blocs/InputDataClient.py
Python
gpl-2.0
5,237
0.027688
from shutil import copy from os import remove import sys from I_Data_Degradation_Block.Code.Degradation import main as blockI from II_Cryptography_Block.Code.encrypt import main as blockII from III_Shamirs_Block.Code.SecretSharing import main as blockIII from IV_DHT_Block.Code.Parted_Keys_to_OWI_Input import main...
Encryption Keys') ################################
################################ # BLOCK 3 ################################################################ dataduration = [] for a in range(0,degradationLevels): i = a+1 print "How long do you want the data of privacy level "+str(i)+" to be available ? (1 is the most private level, the syntax is...
plotly/plotly.py
packages/python/plotly/plotly/validators/histogram/marker/colorbar/_minexponent.py
Python
mit
507
0
import _plotly_utils.basevalidators class MinexponentValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="minexponent", parent_name="histogram.marker.colorbar", **kwargs ): sup
er(MinexponentValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "color
bars"), min=kwargs.pop("min", 0), **kwargs )
openstack/monasca-notification
monasca_notification/plugins/pagerduty_notifier.py
Python
apache-2.0
3,277
0.00061
# (C) Copyright 2015,2016 Hewlett Packard Enterprise Development LP # Copyright 2017 Fujitsu LIMITED # # 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/LICE...
otifier_group = cfg.OptGroup(name='%s_notifier' % PagerdutyNotifier.type) pagerduty_notifier_opts = [ cfg.IntOpt(name='timeout', default=5, min=1), cfg.StrOpt(name='url', default='h
ttps://events.pagerduty.com/' 'generic/2010-04-15/create_event.json') ] def register_opts(conf): conf.register_group(pagerduty_notifier_group) conf.register_opts(pagerduty_notifier_opts, group=pagerduty_notifier_group) def list_opts(): return { pagerduty_notifier_group: pa...
samuelgarcia/python-neo
neo/io/__init__.py
Python
bsd-3-clause
8,472
0.000118
""" :mod:`neo.io` provides classes for reading and/or writing electrophysiological data files. Note that if the package dependency is not satisfied for one io, it does not raise an error but a warning. :attr:`neo.io.iolist` provides a list of successfully imported io classes. Functions: .. autofunction:: neo.io.get...
neo.io.asciisignalio import AsciiSignalIO from neo.io.asciispiketrainio import AsciiSpikeTrainIO from neo.io.axographio import AxographIO from neo.io.axonaio import AxonaIO from neo.io.axonio import AxonIO from neo.io.biocamio import BiocamIO from neo.io.blackrockio import BlackrockIO from neo.io.blkio import BlkIO fro...
2000io import BCI2000IO from neo.io.brainvisionio import BrainVisionIO from neo.io.brainwaredamio import BrainwareDamIO from neo.io.brainwaref32io import BrainwareF32IO from neo.io.brainwaresrcio import BrainwareSrcIO from neo.io.cedio import CedIO from neo.io.elanio import ElanIO from neo.io.elphyio import ElphyIO fro...
theguardian/JIRA-APPy
lib/passlib/tests/test_hosts.py
Python
gpl-2.0
3,934
0.003559
"""test passlib.hosts""" #============================================================================= # imports #============================================================================= from __future__ import with_statement # core import logging; log = logging.getLogger(__name__) import warnings # site # pkg fro...
('$5$rounds=31817$iZGmlyBQ99JSB5n6$p4E.pdPBWx19OajgjLRiOW0itGny' 'xDGgMlDcOsfaI17'), '$1$TXl/FX/U$BZge.lr.ux6ekjEjxmzwz0', 'kAJJz.Rwp0A/I', ]: self.assertTrue(ctx.verify("test", hash)) self.check_unix_disabled(ctx) def test_bsd_contex...
sts.freebsd_context, hosts.openbsd_context, hosts.netbsd_context, ]: for hash in [ '$1$TXl/FX/U$BZge.lr.ux6ekjEjxmzwz0', 'kAJJz.Rwp0A/I', ]: self.assertTrue(ctx.verify("test", hash)) h1 = "$2a$04$yjDgE74R...
rjschwei/azure-sdk-for-python
azure-mgmt-compute/azure/mgmt/compute/models/virtual_machine_scale_set_data_disk.py
Python
mit
2,382
0.001259
# 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 ...
------------------- from msrest.serialization import Model class VirtualMachineScaleSetDataDisk(Model): """Describes a virtual machine scale set data disk. :param name: The disk name. :type name: str :param lun: The logical unit number. :type lun: int :param caching: The caching type. Possib...
'ReadOnly', 'ReadWrite' :type caching: str or :class:`CachingTypes <azure.mgmt.compute.models.CachingTypes>` :param create_option: The create option. Possible values include: 'fromImage', 'empty', 'attach' :type create_option: str or :class:`DiskCreateOptionTypes <azure.mgmt.compute.mode...
divadrei/django-responsive-dfp
dfp/templatetags/dfp.py
Python
mit
636
0.012579
from django.conf import settings from django.utils.safestr
ing import SafeString from django import
template register = template.Library() def dfp(slot): html = SafeString() data = settings.DFP_SLOTS data = data[slot] html+='<div class="dfp-ads" data-slot="%s" data-account="%s" >' % (data['slot'],data['account']) for version in data['responsive']: html+='<div data-sizes="%s" data-media...
napalm-automation/napalm-yang
napalm_yang/models/openconfig/network_instances/network_instance/segment_routing/srlbs/srlb/config/__init__.py
Python
apache-2.0
36,989
0.001622
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListTy...
ne) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements:
if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) ...
dermoth/gramps
gramps/plugins/drawreport/statisticschart.py
Python
gpl-2.0
47,903
0.001211
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2003-2006 Donald N. Allingham # Copyright (C) 2004-2005 Eero Tamminen # Copyright (C) 2007-2012 Brian G. Matherly # Copyright (C) 2008 Peter Landgren # Copyright (C) 2010 Jakim Friant # Copyright (C) 2012-2016 Paul Franklin # # This program i...
ta _x_ = cent
erx + cos(eangle) * radius _y_ = centery + sin(eangle) * radius path.append((_x_, _y_)) if short_radius: _x_ = centerx + cos(eangle) * short_radius _y_ = centery + sin(eangle) * short_radius path.append((_x_, _y_)) angle = eangle while angle >= sangle: _...
xp3i4/seqan
apps/bs_tools/tests/run_tests.py
Python
bsd-3-clause
10,973
0.004648
#!/usr/bin/env python """Execute the tests for bs_tools. The golden test outputs are generated by the script generate_outputs.sh. You have to give the root paths to the source and the binaries as arguments to the program. These are the paths to the directory that contains the 'projects' directory. Usage: run_tests...
se, 'apps/bs_tools/tests') # tests dir # ============================================================ # Auto-detect the binary path. # ============================================================ path_to_bisar = app_tests.autolocateBinary( binary_base, 'apps/bs_tools', 'bisar') path
_to_casbar = app_tests.autolocateBinary( binary_base, 'apps/bs_tools', 'casbar') # ============================================================ # Built TestConf list. # ============================================================ # Build list with TestConf objects, analoguely to how the output ...
Ahmed--Mohsen/leetcode
peeking_iterator.py
Python
mit
2,482
0.019742
""" Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation -- it essentially peek() at the element that will be returned by the next call to next(). Here is an example. Assume that the iterator is initialized to the beginning of t...
terator, which is already defined for you. # # class Iterator(object): # def __init__(self, nums): # """ # Initializes an iterator object to the beginning of a list. # :type nums: List[int] # """ # # def hasNext(self): # """ # Returns true if the iteration has mor...
ents. # :rtype: bool # """ # # def next(self): # """ # Returns the next element in the iteration. # :rtype: int # """ class PeekingIterator(object): def __init__(self, iterator): """ Initialize your data structure here. :type iterator: Iterator """ self.it...
levilucio/SyVOLT
UMLRT2Kiltera_MM/Properties/from_MPS/HSS1_then_IsolatedLHS.py
Python
mit
851
0.028202
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HSS1_then_IsolatedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the him
esis graph representing the AToM3 model HSS1_then_IsolatedLHS """ # Flag this instance as compiled now self.is_compiled = True super(HSS1_then_IsolatedLHS, self).__init__(name='HSS1_then_IsolatedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # S
et the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """return True""" self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HSS1_then_IsolatedLHS') self["equations"] = [] # Set the node attributes # define evaluation methods for eac...
mscuthbert/abjad
abjad/tools/mathtools/least_multiple_greater_equal.py
Python
gpl-3.0
845
0.002367
# -*- encoding: utf-8 -*- import math def least_mul
tiple_greater_equal(m, n): r'''Returns the least integer multiple of `m` greater than or equal to `n`. ::
>>> mathtools.least_multiple_greater_equal(10, 47) 50 :: >>> for m in range(1, 10): ... print(m, mathtools.least_multiple_greater_equal(m, 47)) ... 1 47 2 48 3 48 4 48 5 50 6 48 7 49 8 48 9 54 :...
pombredanne/grr
endtoend_tests/artifacts.py
Python
apache-2.0
4,156
0.007459
#!/usr/bin/env python """End to end
tests that run ArtifactCollectorFlow.""" from grr.endtoend_tests import base from grr.lib import aff4 from grr.lib.rdfvalues import client as rdf_client class TestDarwinPersistenceMechanisms(base.AutomatedTest): """Test DarwinPersistenceMechani
sms.""" platforms = ["Darwin"] flow = "ArtifactCollectorFlow" test_output_path = "analysis/persistence/testing" args = {"artifact_list": ["DarwinPersistenceMechanisms"], "output": test_output_path} def CheckFlow(self): output_urn = self.client_id.Add(self.test_output_path) collection = aff4...
Iolaum/Phi1337
scripts/pipeline/a03d_matrix_concat.py
Python
apache-2.0
1,585
0.026498
import pandas as pd import numpy as np import os def concatDataFrames(): score_df = pd.read_pickle('../../dataset/score_df.pickle') tf_idf_df = pd.read_pickle('../../dataset/score_df_tfidf.pickle') lsa_df = pd.read_pickle('../../dataset/score_df_lsa_cvect.pickle') # Read additional features from the result of fea...
e if should_add_features: # score_matrix target_column = score_df['relevance'] score_df = score_df.drop(score_df.columns[[-1]], axis=1) print score_df.shape # TF_IDF tf_idf_df = tf_idf_df.drop(tf_idf_df.columns[[-1]], axis=1) print tf_idf_df.shape # LSA lsa_df = lsa_df.drop(l
sa_df.columns[[-1]], axis=1) print lsa_df.shape features_df = pd.DataFrame(features_np_arr, index=score_df.index, columns=feature_cols) print features_df.shape print(features_df) result = pd.concat([score_df, tf_idf_df, lsa_df, features_df, target_column], axis=1) print result.columns.tolist() #resul...
chenjiancan/LeetCodeSolutions
src/two_sum/two_sum.py
Python
mit
414
0.002415
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """
inspected_dict = {} for i, num in enumerate(nums): try: j = inspected_dict[num] return j+1, i+1 exc
ept KeyError: inspected_dict[target-num] = i
spi-x-i/shee
shee/frames/network.py
Python
gpl-3.0
2,568
0.001558
#!/usr/bin/env python # -*- coding: utf-8 -*- from frame import DStatFrame from shee.util import get_result_dir_name import matplotlib.pyplot as plt import matplotlib.dates as mdates class DStatNetwork(DStatFrame): def __init__(self, filename, frame=None, eth=None, grain=False): if frame is not None: ...
ax.tick_params
(axis='x', pad=20) plt.setp(ax.xaxis.get_minorticklabels(), rotation=40) def _set_subplots_title_and_plot(self, ax, xlab, ylab): ax.set_title(ylab) ax.plot(self.df[xlab], self.df[ylab]) @staticmethod def _set_subplots_time(ax, hours, mins): ax.xaxis.set_major_locator(ho...
huggingface/transformers
src/transformers/models/squeezebert/__init__.py
Python
apache-2.0
2,532
0.001975
# flake8: noqa # There's no way to ignore "F401 '...' imported but unused" warnings in this # module, but to preserve other warnings. So, don't check this module at all. # Copyright 2020 The HuggingFace Team. All rights reserved. # # Lic
ensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the
License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # S...
noroutine/ansible
lib/ansible/modules/network/nxos/nxos_linkagg.py
Python
gpl-3.0
12,553
0.002151
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Ansible by Red Hat, inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
commands.append('interface port-channel {0}'.format(group)) commands.append('exit') commands.append('interface {0}'.format
(m)) if force: commands.append('channel-group {0} force mode {1}'.format(group, mode)) else: commands.append('channel-group {0} mode {1}'.format(group, mode)) superfluous_memb...
andresriancho/PyGithub
github/GistComment.py
Python
gpl-3.0
4,007
0.002995
# -*- coding: utf-8 -*- # Copyright 2012 Vincent Jacques # vincent@vincent-jacques.net # This file is part of PyGithub. http://vincent-jacques.net/PyGit
hub # PyGithub is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 of th
e License, or (at your option) any later version. # PyGithub 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 have received ...
plotly/plotly.py
packages/python/plotly/plotly/validators/bar/hoverlabel/font/_sizesrc.py
Python
mit
419
0.002387
import _plotly_utils.basevalidators class SizesrcValidator(_p
lotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="sizesrc", parent_name="bar.hoverlabel.font", **kwargs ): super(SizesrcValidator, self).__init__( plotly_name=plotly_n
ame, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), **kwargs )
TylerKirby/cltk
cltk/stop/marathi/stops.py
Python
mit
2,693
0.001502
"""This list is composed from 100 most frequently occuring words in Marathi corpus in CLTK. """ STOP_LIST =["न", "तरी", "तो", "हें", "तें", "कां", "आणि", "जें", "जे", "मग", "ते", "मी", ...
"जाण",
"जैसी", "होये", "जेवीं", "एऱ्हवीं", "मीचि", "किरीटी", "दिसे", "देवा", "हो", "तरि", "कीजे", "तैसे", "आपण", "तिये", "कर्म", "नोहे", ...
ar4s/django
django/db/backends/oracle/introspection.py
Python
bsd-3-clause
14,220
0.001899
from collections import namedtuple import cx_Oracle from django.db import models from django.db.backends.base.introspection import ( BaseDatabaseIntrospection, FieldInfo as BaseFieldInfo, TableInfo, ) from django.utils.functional import cached_property FieldInfo = namedtuple('FieldInfo', BaseFieldInfo._fields + ...
is case insensitive under Oracle.""" return name.lower() def get_sequences(self, cursor, table_name, table_fields=()): cursor.execute(""" SELECT user_tab_ident
ity_cols.sequence_name, user_tab_identity_cols.column_name FROM user_tab_identity_cols, user_constraints, user_cons_columns cols WHERE user_constraints.constraint_name = cols.constraint_name AND user_...
Arno-Nymous/pyload
module/plugins/hoster/OboomCom.py
Python
gpl-3.0
4,818
0.000415
# -*- coding: utf-8 -*- # # Test links: # https://www.oboom.com/B7CYZIEB/10Mio.dat import re from ..captcha.ReCaptcha import ReCaptcha from ..internal.Hoster import Hoster from ..internal.misc import json class OboomCom(Hoster): __name__ = "OboomCom" __type__ = "hoster" __version__ = "0.46" __status...
estsessio
n" result = self.load_url(apiUrl) if result[0] == 200: self.session_token = result[1] else: self.fail( _("Could not retrieve token for guest session. Error code: %s") % result[0]) def solve_captcha(self): ...
codepython/CollectorCity-Market-Place
stores/apps/inventory/migrations/0001_initial.py
Python
apache-2.0
13,952
0.008171
# 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 model 'ProductType' db.create_table('inventory_producttype', ( ('id', self.gf('django...
fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [...
: ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta':...
jawilson/home-assistant
homeassistant/components/homematicip_cloud/__init__.py
Python
apache-2.0
4,501
0.001111
"""Support for HomematicIP Cloud devices.""" import voluptuous as vol from homeassistant import config_entries from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_NAME, EVENT_HOMEASSISTANT_STOP from homeassistant.core import HomeAssistant, callback from homeassistant.helpers impor...
c def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" hap = hass.data[DOMAIN].pop(entry.unique_id) hap.reset_connection_listener() await async_unload_services(hass) return await hap.async_reset() @callback def _async_remove_obsolete_entities( ...
n < "2.2.12": return entity_registry = er.async_get(hass) er_entries = async_entries_for_config_entry(entity_registry, entry.entry_id) for er_entry in er_entries: if er_entry.unique_id.startswith("HomematicipAccesspointStatus"): entity_registry.async_remove(er_entry.entity_id) ...
songjs1993/DeepLearning
5Project/facenet/src/freeze_graph.py
Python
apache-2.0
4,619
0.007144
"""Imports a model metagraph and checkpoint file, converts the variables to constants and exports the model as a graphdef protobuf """ # MIT License # # Copyright (c) 2016 David Sandberg # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation fi...
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, E...
ORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from __future__ import absolute_import from __future__ import division from __fu...
CoronalRain/Saga
saga.py
Python
gpl-3.0
20,417
0.002694
import requests from lxml import html import datetime import inflect from docx import Document from docx.shared import Inches from PyQt4 import QtGui, uic from PyQt4.QtGui import QTableWidgetItem, QApplication, QColor, QIcon, QPushButton, QHBoxLayout, QAction from PyQt4.QtCore import QDate, QTimer, QSize, Qt import sys...
topics): # Initialize the lesson with certain attributed. self.lesson_url = lesson_url self.date = date.strftime("%D") self.notes = notes self.topics = topics class Student(object): def __init__(self, name, subject, tutor): # Initialize the student with certain attr...
lf.subject = subject self.tutor = tutor self.lessons = [] self.notes = [] self.topics = [] def __str__(self): # Format student's info as a string. st = "---------------\n" st += self.name + "\n" st += self.subject + "\n" st += "---------------...
rembo10/headphones
lib/cherrypy/process/wspbus.py
Python
gpl-3.0
21,460
0.000047
r"""An implementation of the Web Site Process Bus. This module is completely standalone, depending only on the stdlib. Web Site Process Bus -------------------- A Bus object is used to contain and manage site-wide behavior: daemonization, HTTP server start/stop, process reload, signal handling, drop privileges, PID ...
raw_items = ( (self._priorities[(channel, listener)], listener) for listener in self.listeners[channel] )
items = sorted(raw_items, key=operator.itemgetter(0)) for priority, listener in items: try: output.append(listener(*args, **kwargs)) except KeyboardInterrupt: raise except SystemExit: e = sys.exc_info()[1] ...
RichardLeeK/MachineLearning
MachineLearning/CNN_PLATEAU/preprocess.py
Python
mit
3,335
0.029685
import pytz import numpy as np from datetime import datetime, timedelta def fromOADate(v): return datetime(1899, 12, 30, 0, 0, 0, tzinfo=pytz.utc) + timedelta(days=v) def get_group(data): timelapse=data[0] timelist=[] for i in range(len(timelapse)): curdt=fromOADate(timelapse[i]) ...
tart_idx,end_idx) total_group.append(cur_g
roup) return total_group def cut_by_hour(data,hour_limit=3): timelapse=data[0] progress_hour=0 cur_hour=0 total_data=[] start_idx=0 for idx in range(len(timelapse)): curdt=fromOADate(timelapse[idx]) dthour=curdt.hour if cur_hour!=dthour: ...
makfire/gstudio
gnowsys-ndf/gnowsys_ndf/ndf/views/topics.py
Python
agpl-3.0
38,687
0.015974
''' -- imports from python libraries -- ''' # import os -- Keep such imports here import json ''' -- imports from installed packages -- ''' from django
.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.http import HttpResponseRedirect from django.http import HttpResponse from django.core.urlresolvers import reverse from django.shortcuts import render_to_response, render from django.templ
ate import RequestContext from mongokit import paginator try: from bson import ObjectId except ImportError: # old pymongo from pymongo.objectid import ObjectId ''' -- imports from application folders/files -- ''' from gnowsys_ndf.settings import LANGUAGES from gnowsys_ndf.ndf.models import Node, Triple fro...
piotrek-golda/CivilHubIndependantCopy
rest/serializers.py
Python
gpl-3.0
27,254
0.002715
# -*- coding: utf-8 -*- from rest_framework import serializers from rest_framework.pagination import PaginationSerializer from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.utils.translation import get_language from django.utils.translation import gettext ...
'poll': return truncatehtml(target.question, 140) elif ct.model == 'discussion': return truncatehtml(target.intro, 140) elif ct.model =
= 'entry': return truncatehtml(target.content, 140) elif ct.model == 'locationgalleryitem': return '<a href="' + target.get_absolute_url() + '">' + \ '<img src="' + target.get_thumbnail((256,256)) + '" /></a>' elif ct.model == 'socialproject': ...
socketubs/requirements
tests/test_base.py
Python
mit
8,877
0.001352
import os import sys import shutil import tempfile from unittest import TestCase sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) from requirements import Requirement from requirements import Requirements ORIGINAL_DIRECTORY = os.getcwd() class RequirementsTestCase(TestCase): def setUp(self): ...
tests_requirements_path = os.path.join( self.root_directory, 'requirements', 'tests.txt') with open(tests_requirements_path, 'w') as f:
f.write('flake8==2.5.4\n') dependencies = self.r.dependencies self.assertEqual(dependencies['tests_require'], ['flake8 == 2.5.4']) self.assertEqual(dependencies['install_requires'], ['requests == 2.9.1']) self.assertEqual(dependencies['dependency_links'], []) def test_multi_...
kiriakosv/movie-recommendator
moviesite/movielists/urls.py
Python
mit
736
0.002717
from django.conf.urls import url, patterns from django.conf import settings from . import views urlpatterns = [ url(r'^$', view
s.index, name = 'index'),
url(r'^(?P<genre>\D+)/$', views.movies_by_genre, name='movies_by_genre'), url(r'^(?P<movie_id>[0-9]+)/details/$', views.movie_details, name='movie_details'), url(r'^(?P<movie_id>[0-9]+)/comments/$', views.movie_comments, name='movie_comments'), url(r'...
echevemaster/saef
saef_app/core/database.py
Python
bsd-3-clause
96
0.010417
from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlc
hemy()
from saef_app.core import models
mikedh/trimesh
tests/test_minimal.py
Python
mit
1,347
0
""" test_minimal.py -------------- Test things that should work with a *minimal* trimesh install. """ import os import unittest import trimesh # the path of the current directory _pwd = os.path.dirname( os.path.abspath(os.path.expanduser(__file__))) # the absolute path for our reference models _mwd = os.path.a...
os.path.join(_pwd, '..', 'models')) def get_mesh(file_name, **kwargs): return
trimesh.load(os.path.join(_mwd, file_name), **kwargs) class MinimalTest(unittest.TestCase): def test_load(self): # kinds of files we should be able to # load even with a minimal install kinds = 'stl ply obj off gltf glb'.split() for file_name in os.listdir...
comtihon/coon
enot/utils/erl_file_utils.py
Python
apache-2.0
3,028
0.000991
import os from os.path import join from enot.utils.file_utils import read_file # read application config file. Return application name, version, applications and if it contains jinja2 templates def parse_app_config(path: str, suffix='.app.src') -> (str, str or None, list or None, bool): file = find_app_file(path...
.path.exists(path): raise FileNotFoundError('No ' + suffix + ' file in ' + path) res = [f for f in os.listdir(path) if join(path, f).endswith(suffix)] if not res: raise FileNotFoundError('No ' + suffix
+ ' file in ' + path) if len(res) > 1: raise RuntimeError('More than one app.src file found: ' + str(res)) return res[0] def find_app_name(content: str) -> str: return get_value('application', 0, content, 1).replace("'", '') def find_app_vsn(content: str) -> str or None: [_, rest] = str.spli...
nypdmax/NUMA
tools/qemu-xen/scripts/analyse-9p-simpletrace.py
Python
gpl-2.0
9,058
0.01656
#!/usr/bin/env python # Pretty print 9p simpletrace log # Usage: ./analyse-9p-simpletrace <trace-events> <trace-pid> # # Author: Harsh Prateek Bora import os import simpletrace symbol_9p = { 6 : 'TLERROR', 7 : 'RLERROR', 8 : 'TSTATFS', 9 : 'RSTATFS', 12 : 'TLOPEN', 13 : 'RLOPEN', ...
d, type, start, length): print "TLOCK (tag =", tag, ", fid =", fid, "type =", type, ", start =", start, ", length =", length, ")" def v9fs_lock_return(self, tag, id, status): print "RLOCK (tag =", tag, ", status =", status, ")" def v9fs_getlock(self, tag, id, fid, type,...
tart, ", length =", length, ")" def v9fs_getlock_return(self, tag, id, type, start, length, proc_id): print "RGETLOCK (tag =", tag, "type =", type, ", start =", start, ", length =", length, ", proc_id =", proc_id, ")" def v9fs_mkdir(self, tag, id, fid, name, mode, gid): ...
aziele/alfpy
tests/test_distance.py
Python
mit
3,659
0.000273
import unittest from alfpy import word_pattern from alfpy import word_vector from alfpy.utils import distance from alfpy.utils import distmatrix from . import utils class DistanceTest(unittest.TestCase, utils.ModulesCommonTest): def __init__(self, *args, **kwargs): super(DistanceTest, self).__init__(*a...
self.patter
n) self.freqs = word_vector.Freqs(self.dna_records.length_list, self.pattern) def test_euclid_squared_counts(self): # The result of this method is identical to that from decaf+py. dist = distance.Distance(self.counts, 'euclid_squared') matrix =...
clickwork/clickwork
main/abbreviations.py
Python
mit
9,976
0
# coding=utf-8 """Abbreviations and codes of interest.""" LANGUAGE_CODES = { "aa": "Afar", "ab": "Abkhazian", "ae": "Avestan", "af": "Afrikaans", "ak": "Akan", "am": "Amharic", "an": "Aragonese", "ar": "Arabic", "as": "Assamese", "av": "Avaric", "ay": "Aymara", "az": "Az...
gu", "tg": "Tajik", "th": "Thai", "ti": "Tigrinya", "tk": "Turkmen", "tl": "Tagalog", "tn": "Tswana", "to": "Tonga (Tonga Islands)", "tr": "Turkish", "ts": "Tsonga", "tt": "Tatar", "tw": "Twi", "ty": "Tahitian", "ug": "Uighur", "uk": "Ukrainian", "ur": "Urdu",...
Vietnamese", "vo": "Volapük", "wa": "Walloon", "wo": "Wolof", "xh": "Xhosa", "yi": "Yiddish", "yo": "Yoruba", "za": "Zhuang", "zh": "Chinese", "zu": "Zulu" } COUNTRY_CODES = { "AF": "Afghanistan", "AL": "Albania", "DZ": "Algeria", "AS": "American Samoa", "AD"...
sc0w/pluma
plugins/snippets/snippets/SubstitutionParser.py
Python
gpl-2.0
7,459
0.015686
# Pluma snippets plugin # Copyright (C) 2006-2007 Jesse van den Kieboom <jesse@icecrew.nl> # # 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 #...
irst, rest = Modifiers._first_char(s) return '%s%s' % (first.lower(), rest) def lower(s): return s.lower() def title(s): return s.title() upper_first = staticmethod(upper_f
irst) upper = staticmethod(upper) lower_first = staticmethod(lower_first) lower = staticmethod(lower) title = staticmethod(title) _first_char = staticmethod(_first_char) class SubstitutionParser: REG_ID = '[0-9]+' REG_NAME = '[a-zA-Z_]+' REG_MOD = '[a-zA-...
mhubig/intelhex
scripts/hex2dump.py
Python
bsd-3-clause
3,960
0.001768
#!/usr/bin/python # Copyright (c) 2008,2010,2011,2012,2013 Alexander Belchenko # All rights reserved. # # Redistribution and use in source and binary forms, # with or without modification, are permitted provided # that the following conditions are met: # # * Redistributions of source code must retain # the above cop...
hvp:r:", ["help", "version", "range="]) for o, a in opts: if o in ("-h", "--help"): print(USAGE) return
0 elif o in ("-v", "--version"): print(VERSION) return 0 elif o in ("-r", "--range"): try: l = a.split(":") if l[0] != '': start = int(l[0], 16) if l[1] != '': ...
staranjeet/fjord
fjord/base/helpers.py
Python
bsd-3-clause
3,652
0
import datetime import json import time import urllib import urlparse from django.contrib.humanize.templatetags import humanize from django.contrib.staticfiles.storage import staticfiles_storage from django.template import defaultfilters from django.utils.encoding import smart_str from django.utils.html import strip_t...
@register.function def static(path): return staticfiles_storage.url(path) @register.filter def naturaltime(*args): return humanize.naturaltime(*args) def json_handle_datetime(obj): """Convert a datetime obj to a number of milliseconds since epoch. This uses milliseconds since this is probably go...
(obj.timetuple()) * 1000 except AttributeError: return obj @register.filter def to_json(data): return json.dumps(data, default=json_handle_datetime) @register.filter def locale_name(locale, native=False, default=_lazy(u'Unknown')): """Convert a locale code into a human readable locale name""" ...
laurentb/weboob
modules/spirica/test.py
Python
lgpl-3.0
947
0
# -*- coding: utf-8 -*- # Copyright(C) 2016 Edouard Lambert # # This file is part of a weboob module. # # This weboob module is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the...
en the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this weboob module. If not, see <http://www.gnu.org/licenses/>. from weboob.tools.te...
aise NotImplementedError()
zackster/HipHopGoblin
examples/artist_video.py
Python
bsd-3-clause
584
0.003425
# Uncomment to set the API key explicitly. Otherwise Pyechonest will # look in the ECHO_NEST_API_
KEY environment variable for the key. #from pyechonest import config #config.ECHO_NEST_API_KEY='YOUR A
PI KEY' from pyechonest import artist okg_results = artist.search(name='OK Go') if okg_results: okg = okg_results[0] print 'Vidoes for %s:' % (okg.name,) for video_document in okg.video: print '%s' % (video_document['title']) for key, val in video_document.iteritems(): print '...
lazunin/stclient
guimporter.py
Python
mit
92
0.021739
#guimporter.py import sys from Py
Side import QtGui, QtCore
, QtWebKit Signal = QtCore.Signal
buzzfeed/caliendo
test/api/callback.py
Python
mit
831
0.00722
import sys import os import tempfile ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__))) CALLBACK_FILE = os.path.join(ROOT, 'callback_notes') CACHED_METHOD_FILE = os.path.join(ROOT, 'cached_method_notes') if
not os.path.exists(CACHED_METHOD_FILE): open(CACHED_METHOD_FILE,'w+') def callback_for_method(a, b, c): assert a == 1 assert b == 2 assert c
== 3 if os.path.exists(CALLBACK_FILE): with open(CALLBACK_FILE, 'a') as f: f.write('.') else: with open(CALLBACK_FILE, 'w+') as f: f.write('.') return CALLBACK_FILE def method_with_callback(callback, something=None): with open(CACHED_METHOD_FILE, 'a') as f: ...
cabanm/project-euler
primes.py
Python
gpl-2.0
212
0.018868
class int(int): def isPrime(self): for q in range(2, int(self**(
1/2))): if self%q: print(self,
q,self%q) else: return 0 return 1
geome-mitbbs/QTS_Research
Trade_Algo.py
Python
mit
7,950
0.009937
try: from . import Portfolio from . import Data_API from .Quant_Indicators import * except: import Portfolio import Data_API from Quant_Indicators import * class Trade_Algo: def __init__(self,command=None): self.command = command if not self.safety_check(): ...
utput += """portfolio3:\n""" + str(self.portfolio3.get_measures()) + """\n""" return output def back_test_plot(self): import matplotlib.pyplot as plt import matplotlib.dates as mdates fig = plt.figure() all_lines = [] ax = fig.add_subplot(111) ax.s...
as_right_ax = False if 'quant_index' in self.used_vars or \ 'quant_index1' in self.used_vars or \ 'quant_index2' in self.used_vars or \ 'quant_index3' in self.used_vars: has_right_ax = True dates = [ x[0] for x in self.pnls['portfolio'] ] fo...
topazproject/topaz
topaz/utils/regexp.py
Python
bsd-3-clause
41,441
0.000796
import sys from rpython.rlib.listsort import make_timsort_class from rpython.rlib.objectmodel import specialize from rpython.rlib.rstring import StringBuilder from rpython.rlib.rsre.rsre_core import ( OPCODE_LITERAL, OPCODE_LITERAL_IGNORE, OPCODE_SUCCESS, OPCODE_ASSERT, OPCODE_MARK, OPCODE_REPEAT, OPCODE_ANY, ...
pos = len(s) else: break if s[pos] != c: return False pos += 1 self.pos = pos return True else: if pos + len(substr) <= l
en(s): matches = True for i in xrange(len(substr)): if s[pos + i] != substr[i]: matches = False else: matches = False if not matches: return False self.pos = pos + len(substr) ...
chrisgtech/peergrader
setup.py
Python
gpl-3.0
312
0.003205
from setuptools import setup setup(name='peergrader', version='0.1', description='Peer grading project'
, url='https://github.com/chrisgtech/peergrader', author='Chris Graham', author_email='chrisgraham@example.com', license='GPLv3', packages=[''],
zip_safe=False)
AsymmetricVentures/asymmetricbase
asymmetricbase/jinja/response.py
Python
gpl-2.0
1,647
0.015179
# -*- coding: utf-8 -*- # Asymmetric Base Framework - A collection of utilities for django frameworks # Copyright (C) 2013 Asymmetric Ventures Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free S...
# # You should have received a copy of the GNU General Public License along # with
this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import absolute_import, division, print_function, unicode_literals from django.template.response import TemplateResponse from django.template.context import RequestContex...
liguangyulgy/mytest1
mergeTxt.py
Python
bsd-2-clause
444
0.024272
import os,glob o
utFileName = 'C:/Users/Guangyu/Downloads/铁汉娇娃/铁汉娇娃.txt' dirPath = 'C:/Users/Guangyu/Downloads/铁汉娇娃/铁汉娇娃/*' def write(fn,of): with open(fn,'rb') as inf: of.write(inf.read()) pass def main(): with open(outFileName,'ab+') as of: print(glob.glob(dirPath)) for fileName in glob.glob(dirP...
_': main()
kouk/pingdom-uptime-report
tests/util.py
Python
mit
615
0
import sys from contextlib import contextmanager
from six import BytesIO class TeeIO(BytesIO): """Like UNIX tee but for python streams. Inspired by CarbonCopy from Fabric. """ def __init__(self, pipe=None, *args, **kwargs): """Construct a TeeIO object. :param pipe: a writable stream (default: sys.stdout). """ self....
gs, **kwargs) def write(self, s): BytesIO.write(self, s) self.pipe.write(s) @contextmanager def as_manager(self): yield self
raphaelvalentin/qtlayout
syntax/bin/fasthenry.py
Python
gpl-2.0
1,919
0.020844
from simulator import fasthenry as simulator from syntax import * from math import pi, sqrt from simulator import fasthen
ry as simulator __all__ = ['FastHenry', 'Title', 'Units', 'Default', 'Node', 'Segment', 'Port', 'Freq', 'Equiv'] class FastHenry(list): def __init__(self): list.__init__(self, []) def __str__(self): self.append('.end')
return "\n".join([str(line) for line in self]) def run(self, verbose=False, **options): simu = simulator(self) simu.run(verbose=verbose, **options) self.raw = simu.raw @property def stdout(self): s = [] n = len(self.raw) nfreq = len(self.raw['fr...
IGITUGraz/scoop
test/tests.py
Python
lgpl-3.0
21,163
0.002504
#!/usr/bin/env python # # This file is part of Scalable COncurrent Operations in Python (SCOOP). # # SCOOP is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3 of # the Licens...
def funcSub(n): f = futures.submit(func4, n) return f.result() def funcMapScan(l): resultat = futures.mapScan(func4, operator.add, l) _control.execQueue.socket.pumpInfoSocket() return resultat def funcMapReduce(l): resultat = fu...
operator.add, l) _control.execQueue.socket.pumpInfoSocket() return resultat def funcDoubleMapReduce(l): resultat = futures.mapReduce(func4, operator.add, l) resultat2 = futures.mapReduce(func4, ...
tranhuucuong91/simple-notebooks
app/routes/load_data.py
Python
mit
4,200
0.001905
#!/usr/bin/env python # import csv # import titlecase from elasticsearch import Elasticsearch from app import app # PATH_FILE = 'data/dict_financial_accounting.csv' # PATH_FILE = 'data/dict_economics.csv' # PATH_FILE = 'data/dict_accounting.csv' # PATH_FILE = 'data/dict_digital-marketing-terms.csv' # PATH_FILE = 'da...
no_accent'] = remove_diacritic(da
ta['vi_term']) # # data['vi_desc_no_accent'] = remove_diacritic(data['vi_desc']) # bulk_data.append(op_dict) # bulk_data.append(data) # # return bulk_data from app import Entry def create_bulk_data(): entries = Entry pass def create_index(): """create ES client, cr...
virbose/demosite
demosite/contact/urls.py
Python
mit
175
0.005714
# from d
jango.conf.urls import url # # from .views import ContactUsForm
PageView # # urlpatterns = [ # url(r'^$', ContactUsFormPageView.as_view(), name='contact_us'), # # ]
jwecode/JWE
ChineseCharCrawler/ChineseCharCrawler/settings.py
Python
mit
3,255
0.009217
# -*- coding: utf-8 -*- # Scrapy settings for ChineseCharCrawler project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.or...
loader middlewares # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 'ChineseCharCrawler.middlewares.MyCustomDownloaderMiddleware': 543, #} # Enable or disable extensions # See http://scrapy.readthedocs.org/en/latest/topics/extensions.html #EXTENSIONS = { ...
e http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html #ITEM_PIPELINES = { # 'ChineseCharCrawler.pipelines.SomePipeline': 300, #} # Enable and configure the AutoThrottle extension (disabled by default) # See http://doc.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The ini...
devilry/devilry-django
devilry/devilry_account/cradminextensions/devilry_crmenu_account.py
Python
bsd-3-clause
531
0
from django.utils.translation import gettext_lazy from cradmin_legacy.crinstance import reverse_cradmin_url from devilry.devilry_cradmin import devilry_crmenu class
Menu(devilry_crmenu.Menu): def add_role_menuitem_object(self, active=False): self.add_headeritem_object(devilry_crmenu.BreadcrumbMenuItem( label=gettext_lazy('Account'), url=reverse_cradmin_url( instanceid='devilry_account', appname='account' ...
), active=active ))
JonnyWong16/plexpy
lib/cherrypy/test/benchmark.py
Python
gpl-3.0
12,563
0
"""CherryPy Benchmark Tool Usage: benchmark.py [options] --null: use a null Request object (to bench the HTTP server only) --notests: start the server but do not run the tests; this allows you to check the tested pages with a browser --help: show this help ...
TML transferred: 14000 bytes Requests per second: 103.69 [#/sec] (mean) Time per request: 96.439 [ms] (mean) Time per request: 9.644 [ms] (mean, across all concurrent requests) Transfer rate: 19.08 [Kbytes/sec] received Connection Times (m
s) min mean[+/-sd] median max Connect: 0 0 2.9 0 10 Processing: 20 94 7.3 90 130 Waiting: 0 43 28.1 40 100 Total: 20 95 7.3 100 130 Percentage of the requests served within a certain time (ms) 50% 100 66% 100 75% ...
hankcs/HanLP
hanlp/datasets/tokenization/sighan2005/pku.py
Python
apache-2.0
813
0
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-12-21 15:42 from hanlp.datasets.tokenization.sighan2005 import SIGHAN2005, make SIGHAN2005_PKU_DICT = SIGHAN2005 + "#" + "gold/pku_training_words.utf8" '''Dic
tionary built
on trainings set.''' SIGHAN2005_PKU_TRAIN_ALL = SIGHAN2005 + "#" + "training/pku_training.utf8" '''Full training set.''' SIGHAN2005_PKU_TRAIN = SIGHAN2005 + "#" + "training/pku_training_90.txt" '''Training set (first 90% of the full official training set).''' SIGHAN2005_PKU_DEV = SIGHAN2005 + "#" + "training/pku_train...
DrOctogon/unwash_ecom
oscar/apps/dashboard/promotions/forms.py
Python
bsd-3-clause
2,643
0
from dj
ango import forms from django.conf import settings from django.forms.models impo
rt inlineformset_factory from django.utils.translation import ugettext_lazy as _ from oscar.apps.promotions.conf import PROMOTION_CLASSES from oscar.forms.fields import ExtendedURLField from oscar.core.loading import get_classes, get_class HandPickedProductList, RawHTML, SingleProduct, PagePromotion, OrderedProduct \...
cangencer/hazelcast-python-client
hazelcast/protocol/codec/map_remove_entry_listener_codec.py
Python
apache-2.0
1,199
0.001668
from hazelcast.serialization.bits import * from hazelcast.protocol.client_message import ClientMessage from hazelcast.protocol.custom_codec import * from hazelcast.util import ImmutableLazyDataList from hazelcast.protocol.codec.map_message_type import * REQUEST_TYPE = MAP_REMOVEENTRYLISTENER RESPONSE_TYPE = 101 RETRYA...
size""" data_size = 0 data_size += calculate_size_str(name) data_size += calculate_size_str(registration_id) return data_size def encode_request(name, registration_id): """ Encode request into client_message""" client_message = ClientMessage(payload_size=calculate_size(name, registration_id))...
_message.set_message_type(REQUEST_TYPE) client_message.set_retryable(RETRYABLE) client_message.append_str(name) client_message.append_str(registration_id) client_message.update_frame_length() return client_message def decode_response(client_message, to_object=None): """ Decode response from cl...
djsilenceboy/LearnTest
Python_Test/PyDataMiningSample/com/djs/learn/test/ura/TestDownloadTransactionData2.py
Python
apache-2.0
354
0
''' Download URA data. Update log: (date / version / author : comments) 2020-06-10 / 1.0.0 / Du Jiang : Creation ''' fro
m com.djs.learn.ura import DownloadData __data_type = 0 __base_file_name = "URA_CondoEcTrans_M" argv = ["-d", __data_type] Download
Data.main(argv) ''' Or run: python DownloadData.py -d 0 ''' if __name__ == '__main__': pass
eduNEXT/edunext-platform
common/djangoapps/third_party_auth/migrations/0019_consolidate_slug.py
Python
agpl-3.0
2,165
0.003233
""" Custom migration script to add slug field to all Prov
iderConfig models. """ from django.db import migrations, models from django.utils.text import slugify def fill_slug_field(apps, schema_editor): """ Fill in the slug field for each ProviderConfig class for backwards compatability. """ OAuth2ProviderConfig = apps.get_model('third_party_auth', 'OAuth2P...
ProviderConfig = apps.get_model('third_party_auth', 'SAMLProviderConfig') LTIProviderConfig = apps.get_model('third_party_auth', 'LTIProviderConfig') for config in OAuth2ProviderConfig.objects.all(): config.slug = config.provider_slug config.save() for config in SAMLProviderConfig.objects....
h-mayorquin/mnist_deep_neural_network_BPNNs
create_and_store_connectivity.py
Python
bsd-3-clause
696
0.001437
import numpy as np from load_binary_files import training_ims, training_labels from init_functions import connectivity # Select quantity of data to use N_data_total = len(training_labels) percentage = 0.001 N_to_use = int(percentage * N_data_total) # Decide how much data to use X = training_ims[0:N_to_use] Y = t...
= X.shape[1] units_per_hypercolumn = 2 w, p = connectivity(N_hypercolumns, units_per_hypercolumn, X, low_noise=0.00001) folder = './data/' name = 'saved_connectivity' name_to_save_matrix = folder + name + '_matrix' name_to_save_p = folder + name + '_p' np.save(name_to_save_matrix, w) np.save(name...
joaobarroca93/AI
Space-Station-Assembly/search.py
Python
gpl-3.0
2,739
0.0084
""" Copyright (C) 2017 João Barroca <joao.barroca@tecnico.ulisboa.pt> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This pro...
not frontier: iteration = next(iterCounter) return None, iteration, len(frontier), generatedNodes # chooses the node with the lowest cost # first we sort by max and then we take the last element of the list # this allow us to choose the vertice with th
e last lowest cost that was # appended to list (in case of ties) sortedFrontier = sorted(frontier, key = itemgetter('f'), reverse = True) node = sortedFrontier[-1] # and remove it from the frontier frontier.remove(node) # checks if the chosen node its a goal state before ...
jluttine/bayespy
doc/source/conf.py
Python
mit
11,116
0.007019
# -*- coding: utf-8 -*- # # BayesPy documentation build configuration file, created by # sphinx-quickstart on Mon Aug 27 12:22:11 2012. # # 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...
the LaTeX preamble. 'preamble': r''' \usepackage{tikz} \usepackage{amssymb} \usepackage{amsmath} \usepackage{svg} \usetikzlibrary{shapes} \usetikzlibrary{fit} \usetikzlibrary{chains} \usetikzlibrary{arrows} ''', # Do not use [T1]{fontenc} because it does not work on libre systems 'fontenc': '' } #latex_additional_fil...
y',] # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'BayesPy.tex', u'BayesPy Documentation', u'J
mottosso/maya-multicapture
multicapture.py
Python
mit
4,677
0.000214
import os import sys import shutil import tempfile import contextlib from PySide import QtGui from maya import ( cmds, OpenMaya as api, OpenMayaUI as apiUI ) class Window(QtGui.QDialog): def __init__(self, filename, parent=None): super(Window, self).__init__(parent) panel1 = QtGui.Q...
%s" % fname)
self.is_running = False def closeEvent(self, event): try: shutil.rmtree(self.tempdir) except OSError: print("Had some problems cleaning up @ %s" % self.tempdir) super(Window, self).closeEvent(event) @contextlib.contextmanager def no_undo(): undo_is_on...
BrainTech/pre-pisak
modules/others/symbols.py
Python
gpl-3.0
23,745
0.041972
#!/bin/env python2.7 # -*- coding: utf-8 -*- # This file is part of AT-Platform. # # AT-Platform 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...
e.rfind('=')+2:-1 ] elif line[ :line.find('=')-1 ] == 'scanningColour': self.scanningColour = line[ line.rfind('=')+2:-1 ] elif line[ :line.find('=')-1 ] == 'selectionColour': self.selectionColour = line[ line.rfind('=')+2:-1 ] ...
ind('=')+2:-1 ] ) elif line[ :line.find('=')-1 ] == 'musicVolume': self.musicVolumeLevel = int( line[ line.rfind('=')+2:-1 ] ) elif not line.isspace( ): print 'Niewłaściwie opisane parametry' ...
MicroPyramid/docker-box
dockit/templatetags/sizes.py
Python
mit
1,519
0.003292
import datetime from django import template import requests from dockit.utils import DHost from django.conf import settings from dateutil import parser register = template.Library() @register.filter def bytes_to_mb(bytes): return format(bytes / 1024 / 1024, '.2f') @register.filter def remove_slash(string): ...
ost.cpu('count') @register.assignment_tag def host_ram_in_mb(): return DHost.memory('total') @register.filter def convert_to_date_obj(date_string): date_obj = parser.parse(date_string) return date_obj @register.filter def s
plit(string, split_char): return string.split(split_char)
drissfr2017/BlocklyDriss
ardublocklyserver/sketchcreator.py
Python
apache-2.0
2,877
0
# -*- coding: utf-8 -*- """Sketch Creator module creates an Arduino Sketch source code file. Copyright (c) 2017 carlosperate https://github.com/carlosperate/ Licensed under the Apache License, Version 2.0 (the "License"): http://www.apache.org/licenses/LICENSE-2.0 """ from __future__ import unicode_literals, absol...
etch_dir: Location for the sketch. :param sketch_name: Optional name for the sketch. :param sketch_code: Optional unicode string with the code for the sketch. :return: Unicode string with full path to the sketch file Return None indicates an error has occurred. """ # Check the code firs...
not isinstance(sketch_code, six.string_types) or \ not isinstance(sketch_name, six.string_types): print('The sketch name or code given is not a valid string !!!') return None # Create the sketch path sketch_path = build_sketch_path(sketch_dir, sketch_name) try: with code...
jobovy/tact
aa/example.py
Python
gpl-3.0
999
0.035035
import numpy as np import sys sys.path.append('lib/') import aa_py X = np.array([8.,0.1,0.3,40.,220.,30.]) Pot = aa_py.GalPot('../Torus/pot/PJM11_best.Tpot') ## Fudge AA = aa_py.Actions_AxisymmetricStackel_Fudge(Pot
,-30.) print AA.actions(X) ## Iterative Torus Tor = aa_py.IterativeTorusMachine(AA,Pot,1e-8,5,1e-5) print Tor.actions(X)[:3] ## Generati
ng Function AG = aa_py.Actions_Genfunc(Pot,"axisymmetric") print AG.actions(X) ## Average generating Function AGav = aa_py.Actions_Genfunc_Average(Pot,"axisymmetric") print AGav.actions(X) ## uvorb UV = aa_py.Actions_AxisymmetricStackel_Fudge_DeltaGuess(Pot,1.,20.,10,10,"example.delta_uv") print UV.actions(X) ## Pol...
EduPepperPDTesting/pepper2013-testing
lms/djangoapps/certificates/views.py
Python
agpl-3.0
23,890
0.010172
from django.contrib.auth.decorators import login_required import logging from certificates.models import GeneratedCertificate from certificates.models import CertificateStatuses as status from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse import json #@begin:View certificate page...
ne) : # certificate_agent.py:175 cert.error_reason = xqueue_body['error_reason'] else: if cert.status
in [status.generating, status.regenerating]: cert.download_uuid = xqueue_body['download_uuid'] cert.verify_uuid = xqueue_body['verify_uuid'] cert.download_url = xqueue_body['url'] cert.status = status.downloadable elif cert.status in [status.d...
rsutormin/narrative
src/biokbase/narrative/ws_util.py
Python
mit
11,249
0.010668
""" Some helper functions for workspace stuff """ import logging import re import biokbase import biokbase.workspace from biokbase.workspace import client as WorkspaceClient g_log = logging.getLogger(__name__) # regex for parsing out workspace_id and object_id from # a "ws.{workspace}.{object}" string ws_regex = re.c...
se BadWorkspaceID("%s does not match workspace ID format ws.{workspace id}.obj.{object id}" % ws_id) ws_id = match.group(1) elif ws_id is None and ref is None: ra
ise BadWorkspaceID("No workspace id or object reference given!") wsclient.alter_workspace_metadata({'wsi':{'id':ws_id}, 'new':new_metadata}) def get_wsobj(wsclient, ws_id, objtype=None): """ This is just a wrapper for the workspace get_objects call. Takes an initialized workspace client and a worksp...
razielb/sdarot.tv_downloader
sdarot-dl.py
Python
gpl-2.0
4,089
0.029592
#!/usr/bin/env python2 import urllib2 import json import time ''' coded by R4z [raziel.b7@gmail.com] enhanced by elicn ''' class Sdarot: _HEADERS = {'Cookie' : r'jwplayer.volume=100;', 'Referer' : r'http://www.sdarot.tv/watch/53-%D7%90%D7%99%D7%9A-%D7%A4%D7%92%D7%A9%D7%AA%D7%99-%D7%90%D7%AA-%D7%90%D7%9E%...
dictionaries holding the content of the loaded webpage ''' headers = Sdarot._HEADERS if episode is not None: data_list = ('watch=false', 'serie=%d' % serie, 'season=%d' % season, 'episode=%d' % episode) else: data_list = ('episodeList=true', 'serie=%d' % serie, 'season=%d' % season)
data = '&'.join(data_list) headers['Content-Length'] = '%d' % len(data) req = urllib2.Request(r'http://www.sdarot.tv/ajax/watch', data, headers) res = urllib2.urlopen(req) return json.loads(res.read()) @staticmethod def _download(url, filename): '''A private method for downloading content and saving it ...
tammoippen/nest-simulator
pynest/examples/brunel_delta_nest.py
Python
gpl-2.0
12,049
0.000249
# -*- coding: utf-8 -*- # # brunel_delta_nest.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 Licen...
e property # `record_to` to *"ascii"* ensures that the spikes will be recorded to a file, # whose name starts with the string assigned to the pr
operty `label`. espikes.set(label="brunel-py-ex", record_to="ascii") ispikes.set(label="brunel-py-in", record_to="ascii") print("Connecting devices") ############################################################################### # Definition of a synapse using ``CopyModel``, which expects the model name of # a pre-...
ooz/Confopy
confopy/pdfextract/xml_util.py
Python
mit
445
0.006742
# coding: utf-8 from xml.dom import Node import xml.sax.saxutils as SU def getChildEleme
ntsByTagName(node, tagName): children = node.childNodes elems = list() for i in range(children.length): child = children.item(i) if child.nodeType == Node.ELEMENT_NODE and child.nodeName == tagName: elems.append(child) return elems de
f escape(string): return (SU.escape(string)).replace(u"\"", u"&quot;")
partofthething/home-assistant
homeassistant/components/upnp/__init__.py
Python
apache-2.0
5,372
0.000745
"""Open ports in your router for Home Assistant and provide statistics.""" import asyncio from ipaddress import ip_address import voluptuous as vol from homeassistant import config_entries from homeassistant.config_entries import ConfigEntry from homeassistant.exceptions import ConfigEntryNotReady from homeassistant....
discovery = discoveries[0] _LOGGER.debug("Constructing from discovery: %s", discovery) location = discovery[DISCOVERY_LOCATION] return await Device.async_create_device(hass, location) async def async_setup(hass: HomeAssistantType, config: ConfigType):
"""Set up UPnP component.""" _LOGGER.debug("async_setup, config: %s", config) conf_default = CONFIG_SCHEMA({DOMAIN: {}})[DOMAIN] conf = config.get(DOMAIN, conf_default) local_ip = await hass.async_add_executor_job(get_local_ip) hass.data[DOMAIN] = { DOMAIN_CONFIG: conf, DOMAIN_CO...
levkar/odoo-addons
sale_dummy_confirmation/sale.py
Python
agpl-3.0
1,353
0.006652
# -*- coding: utf-8 -*- from openerp import api, fields, models, _ class sale_order(models.Model): _inherit = 'sale.order' dummy_confirmation = fields.Boolean('Dummy Confirmation', help="If true, this sale order has been dummy confirmed and can go back to draft.") def action_button_confirm(self, ...
' so = self.browse(cr, uid, ids[0], context=context) if so.company_id.sale_order_dummy_confirm: so.write({'state':'done','dummy_confirmation':True})
# redisplay the record as a sales order view_ref = self.pool.get('ir.model.data').get_object_reference( cr, uid, 'sale', 'view_order_form') view_id = view_ref and view_ref[1] or False return { 'type': 'ir.actions.act_window', 'name': ...
tinchoa/broflow
pox/misc/ip_s.py
Python
gpl-3.0
5,114
0.043215
from pox.core import core import pox.openflow.libopenflow_01 as of from pox.lib.revent import * from pox.lib.util import dpidToStr from pox.lib.addresses import EthAddr, IPAddr from collections import namedtuple import pox.lib.packet as pkt import os import string,sys,socket,json, subprocess import thread log = core....
received thread.start_new_thread(thread_socket,tuple([])) #################################################################json global received encoded_data = json.loads(received) Interface=encoded_data[0]["Interface"] IP_dst=encoded_data[0]["IP_dst"] Port=encoded_data[0]["Port"] MAC=encoded_data[0]["MA...
] ifaceid=Interface.split("eth") ifaceid=ifaceid[1] port_dst=Port.split("/") port_dst=port_dst[0] # print Interface # print IP_dst # print Port # print MAC # print IP_attack ##########getting the domain name directory= "cd /root/VMs/cfgvms " #virtual machine configurati...
openstack/senlin
senlin/tests/unit/engine/actions/test_check.py
Python
apache-2.0
8,927
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 unde...
text, 'NODE_ACTION_1', {'status': 'READY'}), mock.call(action.context, 'NODE_ACTION_2', {'status': 'READY'}), ]) mock_start.assert_called_once_with() mock_wait.assert_called_once_with() cluster.eval_status.assert_called_once_with( action.context, consts.CLUSTER_CH...
j.Dependency, 'create') @mock.patch.object(dispatcher, 'start_action') @mock.patch.object(ca.ClusterAction, '_wait_for_dependents') def test_do_check_need_delete(self, mock_wait, mock_start, mock_dep, mock_delete, mock_action, mock_update, ...
scottfrazer/cAST
cast/ParserCommon.py
Python
mit
7,246
0.022771
class Terminal: def __init__(self, id, str, resource, line, col): self.__dict__.update(locals()) def getId(self): return self.id def toAst(self): return self def toString(self, format): return self.str def __str__(self): return self.str class NonTerminal(): def __init__(self, id, str): ...
, list): if len(ast) == 0: return '%s[]' % (indentStr) string = '%s[\n' % (indentStr) string += ',\n'.join([self._prettyPrint(element, indent + 2) for element in ast]) string += '\n%s]' % (indentStr) return string elif isinstance(ast, Terminal): return '%s%s' % (indentStr...
red(str(ast), 9)) class ParseTreePrettyPrintable: def __init__(self, ast, color=False): self.__dict__.update(locals()) def __str__(self): return self._prettyPrint(self.ast, 0) def _prettyPrint(self, parsetree, indent = 0): colored = noColor if self.color: colored = termColor indentStr =...
clarkperkins/stackdio
stackdio/core/queryset_transform.py
Python
apache-2.0
2,471
0.002428
# -*- coding: utf-8 -*- # Copyright (c) 2010, Simon Willison. # All rights reserved. # # https://github.com/simonw/django-queryset-transform # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of...
vided with the distribution. # # 3. Neither the name of Django nor the names of its contributors may be used # to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # AN...
D WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMIT...
Bajoo/client-pc
tests/gui/bug_report_window.py
Python
gpl-3.0
659
0
class BugReportWindowTestController(object): def __ini
t__(self, factory
, exit): self.view = factory(self) self.view.show() self._exit = exit def send_report_action(self, email, description): print('Send report action') print('Email is: "%s"' % email) print('Description is:\n%s' % description) if email: print('Display...
caioserra/apiAdwords
examples/adspygoogle/dfp/v201311/user_team_association_service/get_user_team_associations_by_statement.py
Python
apache-2.0
2,518
0.001986
#!/usr/bin/python # # Copyright 2013 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...
ed. import os import sys sys.path.insert(0, os.path.join('..', '..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle import DfpClient # Initialize client object. client = DfpClient(path=os.path.join('..', '..', '..', '..', '..')) # Initialize appropriate service. user_team_...
rsion='v201311') # Get the current user ID. current_user_id = user_service.GetCurrentUser()[0]['id'] # Create filter text to select user team associations by the user ID. values = [{ 'key': 'userId', 'value': { 'xsi_type': 'NumberValue', 'value': current_user_id } }] filter_statement = {'q...
X0Leon/XQuant
xquant/engine/data.py
Python
mit
4,710
0.000955
# -*- coding: utf-8 -*- """ DataHandler抽象基类 @author: Leon Zhang @version: 0.5.2 """ import datetime import os import sys import pandas as pd import functools from collections import namedtuple from abc import ABCMeta, abstractmethod from .event import BarEvent class DataHandler(object): """ DataHandler抽象基...
for b in self.symbol_data[symbol]: yield DataHandler.Bar(symbol, b[0], b[1][0], b[1][1], b[1][2], b[1][3], b[1][4]) def get_latest_bars(self, symbol, N=1): """ 从latest_symbol列表中返回最新的N个bar,或者所能返回的最大数量的bar """ try: bars_list = self.latest_symbol_data[symbo...
t_bar(self, symbol): """ 从latest_symbol列表中直接返回最后的bar 而get_latest_bars(symbol, N=1)返回元素只有最后一个bar的list """ try: bars_list = self.latest_symbol_data[symbol] except KeyError: print("Not available symbol in the historical data set!") else: ...
erh3cq/hyperspy
hyperspy/tests/axes/test_conversion_units.py
Python
gpl-3.0
19,120
0.000628
# -*- coding: utf-8 -*- # Copyright 2007-2021 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy 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...
) out = self.uc._convert_units('nm') assert out is None assert self.uc.units == 'nm' np.testing.assert_almost_equal(self.uc.scale, 500) self._set_units_scale_size('µm', 5) out = self.uc._convert_units('cm') assert out is None assert self.uc.units == 'cm' ...
ert_almost_equal(self.uc.scale, 0.0005) self._set_units_scale_size('1/µm', 5) out = self.uc._convert_units('1/nm') assert out is None assert self.uc.units == '1 / nm' np.testing.assert_almost_equal(self.uc.scale, 0.005) self._set_units_scale_size('eV', 5) out = ...
PythonCharmers/python-future
tests/test_future/test_str.py
Python
mit
19,879
0.000403
# -*- coding: utf-8 -*- """ Tests for the backported class:`str` class. """ from __future__ import absolute_import, unicode_literals, print_function from future.builtins import * from future import utils from future.tests.base import unittest, expectedFailurePY2 import os TEST_UNICODE_STR = u'ℝεα∂@ßʟ℮ ☂ℯṧт υηḯ¢☺ḓ℮' ...
def test_str_str(self): self.assertEqual(str('ABC'), u'ABC') self.assertEqual(str('ABC'), 'ABC') def test_str_is_str(self): s = str(u'ABC') self.assertTrue(str(s) is s) self.assertEqual(repr(str(s)), "'ABC'") def test_str_fromhex(self): self.assertFa
lse(hasattr(str, 'fromhex')) def test_str_hasattr_decode(self): """ This test tests whether hasattr(s, 'decode') is False, like it is on Py3. Sometimes code (such as http.client in Py3.3) checks hasattr(mystring, 'decode') to determine if a string-like thing needs encoding. It woul...
yasir1brahim/OLiMS
controllers/fields.py
Python
agpl-3.0
126
0.02381
''' Created
on Aug 12, 2015 @author: yasir1brahim ''' from openerp import fields, models clas
s fields(): pass fields()
tochev/obshtestvo.bg
projects/migrations/0012_auto__add_field_project_is_forced_active.py
Python
unlicense
19,324
0.007814
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Project.is_forced_active' db.add_column(u'projects_projec...
'middlemen': ('django.db.models.fields.rel
ated.ManyToManyField', [], {'blank': 'True', 'related_name': "'middleman_organisations'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['projects.Member']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'partnered_project': ('django.db.models.fields.related.Fo...
snim2mirror/openihm
src/openihm/model/householdincome_employment.py
Python
lgpl-3.0
4,411
0.024258
#!/usr/bin/env python """ This file is part of open-ihm. open-ihm is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. open-ihm is di...
= Database() database.open() query = '''INSERT INTO employmentincome(pid, hhid, incomesource, foodtypepaid, unitofmeasure, unitspaid, incomekcal, cashincome) VALUES(%s,%s,'%s','%s','%s',%s,%s,%s) ''' % ( pid, hhid, incomesource, foodtypepaid, unitofmeasure, unitspaid, inc...
# execute query database.execUpdateQuery( query ) query = "SELECT LAST_INSERT_ID()" rows = database.execSelectQuery( query ) for row in rows: incomeid = row[0] database.close() # update income attributes ...
mnahm5/django-estore
Lib/site-packages/awscli/customizations/emr/argumentschema.py
Python
mit
22,109
0.002216
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
}, "SimpleScalingPolicyConfiguration": {
"type": "object", "description": "The Simple scaling configuration that will be associated" "to Auto Scaling action.", "properties": { ...
osbzr/gooderp_org
portal/wizard/portal_wizard.py
Python
agpl-3.0
11,851
0.003375
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2011 OpenERP S.A (<http://www.openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms ...
user = self._retrieve_user(cr, SUPERUSER_ID, wizard_user, context) if wizard_user.partner_id.email != wizard_user.email: wizard_user.partner_id.write({'email': wizard_user.email}) if wizard_user.in_portal: # create a user if necessary, and make sure it...
user.active) or (portal not in user.groups_id): user.write({'active': True, 'groups_id': [(4, portal.id)]}) # prepare for the signup process user.partner_id.signup_prepare() self._send_email(cr, uid, wizard_user, context) w...
stevenmizuno/QGIS
python/plugins/processing/algs/grass7/ext/v_net_salesman.py
Python
gpl-2.0
1,496
0
# -*- coding: utf-8 -*- """ *************************************************************************** v_net_salesman.py --------------------- Date : December 2015 Copyright : (C) 2015 by Médéric Ribreux Email : medspx at medspx dot fr **
************************************************************************* * * * 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 Softw...
* *************************************************************************** """ __author__ = 'Médéric Ribreux' __date__ = 'December 2015' __copyright__ = '(C) 2015, Médéric Ribreux' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$...
yasoob/PythonRSSReader
venv/lib/python2.7/dist-packages/ubuntu-sso-client/ubuntu_sso/utils/webclient/__init__.py
Python
mit
2,532
0.001185
# -*- coding: utf-8 -*- # # Copyright 2011-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, bu...
s # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may ex
tend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """A common webclient that can use a Qt...