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 |
|---|---|---|---|---|---|---|---|---|
NMTHydro/Recharge | utils/TAW_optimization_subroutine/disagg_tester.py | Python | apache-2.0 | 15,034 | 0.002993 | # ===============================================================================
# Copyright 2019 Jan Hendrickx and Gabriel Parrish
#
# 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:/... | transform in order to georefference the image
output_dataset.SetGeoTransform(geotransform)
# set the projection
output_dataset.SetProjection(projection)
def numpy_to_geotiff(array, geo_info, output_path, output_name):
""""""
trans = geo_info['geotransform']
dim = geo_info['dimensions']
pr... | projections', proj
write_raster(array, geotransform=trans, output_path=output_path, output_filename=output_name,
dimensions=dim, projection=proj)
def geotiff_output(taw_vals, rss_arrs, geo_info, namekey, outpath):
""""""
for arr, taw_val in zip(rss_arrs, taw_vals):
outname = '{}_i... |
githubutilities/LeetCode | Python/intersection-of-two-arrays.py | Python | mit | 2,721 | 0.002205 | # Time: O(m + n)
# Space: O(min(m, n))
# Given two arrays, write a function to compute their intersection.
#
# Example:
# Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
#
# Note:
# Each element in the result must be unique.
# The result can be in any order.
# Hash solution.
class Solution(object):
def... | List[int]
:rtype: List[int]
"""
if len(nums1) > len(nums2):
return self.intersection(nums2, nums1)
lookup = set()
for i in nums1:
lookup.add(i)
res = []
for i in nums2:
if i in lookup:
res += i,
... | st[int]
:rtype: List[int]
"""
return list(set(nums1) & set(nums2))
# Time: O(max(m, n) * log(max(m, n)))
# Space: O(1)
# Binary search solution.
class Solution2(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
... |
koeninger/spark | python/examples/wordcount.py | Python | bsd-3-clause | 555 | 0 | import sys
from operator import add
from pyspark import SparkContext |
if __name__ == "__main__":
if len(sys.argv) < 3:
print >> sys.stderr, \
"Usage: PythonWordCount <master> <file>"
exit(-1)
sc = SparkContext(sys.argv[1], "PythonWordCount")
lines = sc.textFile(sys.argv[2], 1)
counts = lines.flatMap(lambda x: x.split(' ')) \
... | |
motobyus/moto | module_django/jstest/jstest/settings.py | Python | mit | 3,255 | 0.001536 | """
Django settings for jstest project.
Generated by 'django-admin startproject' using Django 1.10.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
... | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Seoul'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# ht | tps://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'samplepage/statics'),
)
|
shincling/MemNN_and_Varieties | DataCoupus/list_document/namelist_answer.py | Python | bsd-3-clause | 2,870 | 0.004476 | # -*- coding: utf8 -*-
__author__ = 'shin'
import jieba
namelist_answer=[]
'''
namelist_answer.append('[slot_name]。')
namelist_answer.append('叫[slot_name]。')
namelist_answer.append('姓名是[slot_name]。')
namelist_answer.append('我是[slot_name]。')
namelist_answer.append('您好,我叫[slot_name]。')
namelist_answer.append('[slot_name... | )
namelist_answer.append('名叫周杰伦。')
namelist_answer.append('叫周杰伦。')
namelist_answer.append('没问题,我叫周杰伦。')
namelist_answer.append('好的,名字是周杰伦。')
namelist_answer.append('我的全名就是周杰伦。')
namelist_answer.append('姓名是周杰伦。')
namelist_answer.append('周杰伦是我的名字。')
namelist_answer.append('我名叫周杰伦。')
namelist_answer.append('我是周杰伦啊。')
nam... | end('名字叫周杰伦。')
namelist_answer.append('您好,我叫周杰伦。')
namelist_answer.append('好的。您记一下。周杰伦。')
namelist_answer.append('名是周杰伦。')
namelist_answer.append('名叫周杰伦。')
namelist_answer.append('我叫周杰伦。')
namelist_answer.append('我是周杰伦。')
namelist_answer.append('名字是周杰伦。')
namelist_answer.append('我的名字是周杰伦。')
namelist_answer_cut=[]
f... |
jenix21/DarunGrim | Src/Scripts/Test/ListDirectories.py | Python | bsd-3-clause | 1,288 | 0.045031 | import dircache
import os.path
from sqlalchemy import create_engine,Table,Column,Integer,String,ForeignKey,MetaData
from sqlalchemy.orm import mapper
from sqlalchemy.orm import sessionmaker
from Files import *
def SearchDirectory(session,directory,whitelist):
for file in dircache.listdir(directory):
if fil... | rsion,full_path
session.add(Files(filename,version,full_path))
fd.close()
except:
pass
engine=create_engine('sqlite:///Files.db',echo=True)
"""
metadata=MetaData()
FilesTable=Table('Files',metadata,
Column('id',Integer,primary_key=True),
Column('Filename',S | tring),
Column('Version',String),
Column('FullPath',String))
mapper(Files,FilesTable)
"""
metadata=Base.metadata
metadata.create_all(engine)
Session=sessionmaker(bind=engine)
session=Session()
SearchDirectory(session,r'T:\mat\Projects\Binaries',['.svn'])
session.commit()
|
plotly/python-api | packages/python/plotly/plotly/validators/heatmapgl/_visible.py | Python | mit | 517 | 0.001934 | import _plotly_utils.basevalidators
class VisibleValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="visible", parent_name="heatmapgl", **kwargs):
super(VisibleValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_ | name,
edit_type=kwargs.pop("edit_type", "calc"),
role=kwargs.pop("role", "info" | ),
values=kwargs.pop("values", [True, False, "legendonly"]),
**kwargs
)
|
willthames/ansible-lint | test/TestAnsibleSyntax.py | Python | mit | 409 | 0 | """Test Ansible Syntax.
This module | contains tests that validate that linter does not produce errors
when encountering what counts as valid Ansible syntax.
"""
PB_WITH_NULL_TASKS = '''
- hosts: all
tasks:
'''
def test_null_tasks(default_text_runner):
"""Assure we do not fail when encountering null tasks."""
results = default_text_run | ner.run_playbook(PB_WITH_NULL_TASKS)
assert not results
|
mindm/2017Challenges | challenge_3/python/sarcodian/src/challenge_3.py | Python | mit | 218 | 0.009174 | def majority(array0):
store = { | }
for i in array0:
store[i] = store.get(i,0) + 1
for i in store.keys():
if store[i] > len(array0)//2:
| return i
print('No majority found')
|
alexlo03/ansible | lib/ansible/utils/plugin_docs.py | Python | gpl-3.0 | 4,053 | 0.002714 | # Copyright: (c) 2012, Jan-Piet Mens <jpmens () gmail.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_function)
__metaclass__ = type
from ansible.errors import AnsibleError, AnsibleAssertionError
from ansible.mo... | ents loaded by the PluginLoader from the module_docs_fragments directory.
"""
data = read_docstring(filename, verbose=verbose, ignore_errors=ignore_errors)
# add fragments to documentation
if data.get('doc | ', False):
add_fragments(data['doc'], filename, fragment_loader=fragment_loader)
return data['doc'], data['plainexamples'], data['returndocs'], data['metadata']
|
log2timeline/plaso | tests/cli/helpers/parsers.py | Python | apache-2.0 | 2,477 | 0.002826 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the parsers CLI arguments helper."""
import argparse
import unittest
from plaso.cli import tools
from plaso.cli.helpers import parsers
from plaso.lib import errors
from tests.cli import test_lib as cli_test_lib
class ParsersArgumentsHelperTest | (cli_test_lib.CLIToolTestCase):
"""Tests for the parsers CLI arguments helper."""
# pylint: disable=no-member,protected-access
_EXPECTED_OUTPUT = """\
usage: cli_helper.py [--parsers PARSER_FILTER_EXPRESSION]
Test argument parser.
{0:s}:
--parsers PARSER_FILTER_EXPRESSION
Define whic... | s to use,
or show possible values. The expression is a comma
separated string where each element is a preset,
parser or plugin name. Each element can be prepended
with an exclamation mark to exclude the item. Matching
... |
smurfix/pybble | TEST.py | Python | gpl-3.0 | 466 | 0.038627 | # -*- coding: utf-8 -*-
## This is a minima | l config file for testing.
TESTING=True # this file only works in test mode
sql_driver="sqlite"
sql_database=":memory:" ## overridden when running tests
##
SECRET_KEY="fbfzkar2ihf3ulqhelg8srlzg7resibg748wifgbz478"
#TRACE=True
#M | EDIA_PATH="/var/tmp/pybble"
## set by the test run script
ADMIN_EMAIL="smurf@smurf.noris.de"
URLFOR_ERROR_FATAL=False
REDIS_HOST='localhost'
REDIS_DB=3 ## a db number not used in production
|
jpbonson/SBBReinforcementLearner | SBB/environments/default_environment.py | Python | bsd-2-clause | 2,122 | 0.010839 | import abc
from default_metrics import DefaultMetrics
class DefaultEnvironment(object):
"""
Abstract class for environments. All environments must implement these
methods to be able to work with SBB.
"""
__metaclass__ = abc.ABCMeta
def __init__(self):
self.metrics_ = Defau... | ate the fitness of the point population, to define which points will be removed
or added in the next generation, when setup_point_population() is executed.
"""
|
@abc.abstractmethod
def evaluate_teams_population_for_training(self, teams_population):
"""
Evaluate all the teams using the evaluate_team() method, and sets metrics. Used only
for training.
"""
@abc.abstractmethod
def evaluate_team(self, team, mode):
... |
nlproc/splunkml | bin/mcpredict.py | Python | apache-2.0 | 2,357 | 0.026729 | #!env python
import os
import sys
sys.path.append(
os.path.join(
os.environ.get( "SPLUNK_HOME", "/opt/splunk/6.1.3" ),
"etc/apps/framework/contrib/splunk-sdk-python/1.3.0",
)
)
from collections import Counter, OrderedDict
from math import log
from nltk import tokenize
import execnet
import json
from splunkl... | eption as e:
print >> sys.stderr, "ERROR", e
channel.send({ 'error': "Couldn't find model %s" % args['model']})
else:
X, y_labels, textmodel = process_records(records, fields, target, textmodel=textmodel)
print >> sys.stderr, X.shape
y = est.predict(X)
y_labels = encoder.inverse_transform(y)
| for i, record in enumerate(records):
record['%s_predicted' % target] = y_labels.item(i)
channel.send(record)
"""
def __dir__(self):
return ['model']
dispatch(MCPredict, sys.argv, sys.stdin, sys.stdout, __name__)
|
psychopy/versions | psychopy/hardware/labjacks.py | Python | gpl-3.0 | 1,270 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2020 Open Science Too | ls Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
"""This provides a basic ButtonBox class, and imports the
`ioLab python library <http://github.com/ioLab/python-ioLabs>`_.
"""
from __future__ import absolute_import, division, print_function
try:
from labjack import u3
except Impo... | te, endian='big', address=6701):
"""Write 1 byte of data to the U3 port
parameters:
- byte: the value to write (must be an integer 0:255)
- endian: ['big' or 'small'] ignored from 1.84 onwards; automatic?
- address: the memory address to send the byte to
... |
agry/NGECore2 | scripts/mobiles/rori/dreaded_vir_vir.py | Python | lgpl-3.0 | 1,491 | 0.028169 | import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Ve | ctor
def addTemplate(core):
mobileTemplate = MobileTemplate()
mobileTemplate.setCreatureName('dreaded_vir_vir')
mobileTemplate.setLevel(40)
mobileTemplate.setDifficulty(Difficulty.NORMAL)
mobileTemplate.setMinSpawnDistance(4)
mobileTemplate.setMaxSpawnDistance(8)
mobileTemplate.setDeathblow(True)
| mobileTemplate.setScale(1)
mobileTemplate.setMeatType("Avian Meat")
mobileTemplate.setMeatAmount(25)
mobileTemplate.setBoneType("Avian Bones")
mobileTemplate.setBoneAmount(16)
mobileTemplate.setSocialGroup("vir vur")
mobileTemplate.setAssistRange(2)
mobileTemplate.setStalker(True)
mobileTemplate.setOptionsBitma... |
Jacy-Wang/MyLeetCode | MaxDepthBinTree104Recursion.py | Python | gpl-2.0 | 678 | 0.001475 | tion for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root:
s... | )
return max(self.cand)
else:
return 0
def find(self, length, node):
if node.left:
self.cand.append(self.find(length + 1, node.left))
if node.right:
self.cand.append(self.find(length + 1, node.right))
self. | cand.append(length + 1)
|
Venefyxatu/phennyfyxata | phennyfyxata/scores/models.py | Python | bsd-2-clause | 1,030 | 0.000971 | from django.db import models
class Writer(models.Model):
alias = models.ForeignKey('Writer', blank=True, null=True)
nick = models.CharField(unique=True, max_length=16)
class War(models.Model):
id = models.AutoField(primary_key=True)
starttim | e = models.DateTimeField()
endtime = models.DateTimeField()
finished = models.BooleanField(default=False)
def __unicode__(self):
return "War %s: %s tot %s (%s minuten)" % (self.id, self.starttime.strftime("%H:%M"), self.endtime.strftime("%H:%M"), (self.endtime - self.starttime).seconds / 60)
clas... | Key(War)
score = models.IntegerField(default=0, blank=True)
class WriterStats(models.Model):
warcount = models.IntegerField()
wordcount = models.IntegerField()
wpm = models.DecimalField(max_digits=5, decimal_places=2)
class WarParticipants(models.Model):
war = models.ForeignKey(War)
particip... |
alexallah/django | tests/postgres_tests/models.py | Python | bsd-3-clause | 5,090 | 0.000393 | from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from .fields import (
ArrayField, BigIntegerRangeField, CICharField, CIEmailField, CITextField,
DateRangeField, DateTimeRangeField, FloatRangeField, HStoreField,
IntegerRangeField, JSONField, SearchVectorField,
)
clas... |
class NestedIntegerArrayModel(PostgreSQLModel):
field = ArrayField(ArrayField(models.IntegerField()))
class O | therTypesArrayModel(PostgreSQLModel):
ips = ArrayField(models.GenericIPAddressField())
uuids = ArrayField(models.UUIDField())
decimals = ArrayField(models.DecimalField(max_digits=5, decimal_places=2))
tags = ArrayField(TagField(), blank=True, null=True)
class HStoreModel(PostgreSQLModel):
field = ... |
mtils/ems | ems/qt4/services/modelupdate.py | Python | mit | 590 | 0.013559 | '''
Created on 04.10.2012
@author: michi
'''
from PyQt4.QtCore import pyqtSignal
from ems.qt4.applicationservice import ApplicationService #@UnresolvedImport
class ModelUpdateService(ApplicationService):
objectIdsUpdated = pyqtSignal(str, list)
objectsUpdated = pyqtSignal(str)
modelUpdate... | s is not None:
self.objectIdsUpdated.emit(modelObjectName, keys)
else:
self.objectsUpdated.emit(modelObjectName)
self.model | Updated.emit() |
nicolashainaux/mathmaker | tests/integration/mental_calculation/04_yellow1/test_04_yellow1_multi_divi_10_100_1000.py | Python | gpl-3.0 | 1,673 | 0 | # -*- coding: utf-8 -*-
# Mathmaker creates automatically maths exercises sheets
# with their answers
# Copyright 2006-2018 Nicolas Hainaux <nh.techn@gmail.com>
# This file is part of Mathmaker.
# Mathmaker is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License... | ):
"""Check this sheet is generated without any error."""
shared.machine.write_out(str(Sheet('mental_calculation',
'04_yellow1',
'multi_divi_10_100_1000')),
pdf_output=True)
def test_multi_divi_10_100_10... |
shared.machine.write_out(str(Sheet('mental_calculation',
'04_yellow1',
'multi_divi_10_100_1000',
enable_js_form=True)),
pdf_output=True)
|
sandvine/horizon | horizon/forms/fields.py | Python | apache-2.0 | 15,925 | 0.000063 | # Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | html.escape(option_value), other_html, option_label)
def get_data_attrs(self, option_label):
other_html = []
if | not isinstance(option_label, (six.string_types, Promise)):
for data_attr in self.data_attrs:
data_value = html.conditional_escape(
force_text(getattr(option_label,
data_attr, "")))
other_html.append('data-%s="%s"' % (... |
deanishe/alfred-fakeum | src/libs/faker/providers/phone_number/tr_TR/__init__.py | Python | mit | 389 | 0 | from __future__ import unicode_literals
from .. import Provider as PhoneNumberProvider
class Provider(PhoneNumberProvider):
form | ats = (
'+90(###)#######',
'+90 (###) #######',
'0### ### ## ##',
'0##########',
'0###-### ####',
'(###)### ####',
'### # ###',
'+90(###)###-####x###',
'+90(###)### | -####x####',
)
|
KiChjang/servo | tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_handlers.py | Python | mpl-2.0 | 16,970 | 0.00165 | import json
import os
import sys
import unittest
import uuid
import pytest
from urllib.error import HTTPError
wptserve = pytest.importorskip("wptserve")
from .base import TestUsingServer, TestUsingH2Server, doc_root
from .base import TestWrapperHandlerUsingServer
from serve import serve
class TestFileHandler(TestU... | st data", resp.read())
def test_tuple_3_rv_1(self):
@wptserve.handlers.handler
def handler(request, response):
return (202, "Some Status"), [("test-header", "test-value")], "test data"
route = ("GET", "/test/test_tuple_3_rv_1", handler)
self.server.router.register(*rout... | self.assertEqual(202, resp.getcode())
self.assertEqual("Some Status", resp.msg)
self.assertEqual("test-value", resp.info()["test-header"])
self.assertEqual(b"test data", resp.read())
def test_tuple_4_rv(self):
@wptserve.handlers.handler
def handler(request, response):... |
SNoiraud/gramps | gramps/plugins/docgen/cairodoc.py | Python | gpl-2.0 | 12,315 | 0.002436 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2007 Zsolt Foldvari
# Copyright (C) 2008 Brian G. Matherly
# Copyright (C) 2013 Vassilii Khachaturov
#
# 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 F... | ference/surfaces.html#class-ps | surface-surface
# for the arg semantics.
raise "Missing surface factory override!!!"
def run(self):
"""Create the output file.
The derived class overrides EXT and create_cairo_surface
"""
# get paper dimensions
paper_width = self.paper.get_size().get_width() ... |
heynemann/level | tests/unit/test_app.py | Python | mit | 6,332 | 0.000632 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of level.
# https://github.com/heynemann/level
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT-license
# Copyright (c) 2016, Bernardo Heynemann <heynemann@gmail.com>
from importer import Importer
from preggy import expect
fr... | await self.wait_for(lambda: self.service.message is not None)
expect(self.service.socket_id).not_to_be_null()
expect(self.service.message).to_be_like({
'type': 'core.connection.close',
| 'socket_id': self.service.socket_id,
'payload': {},
})
@gen_test
async def test_can_receive_message(self):
await self.websocket_connect('/ws')
expect(self.ws).not_to_be_null()
await self.ws.write_message(dumps({
'type': 'custom.message',
'q... |
rtfd/readthedocs.org | readthedocs/core/fields.py | Python | mit | 218 | 0 | # -*- coding: utf-8 -*-
"""Shar | ed model fields and defaults."""
import | binascii
import os
def default_token():
"""Generate default value for token field."""
return binascii.hexlify(os.urandom(20)).decode()
|
BhallaLab/moose-thalamocortical | pymoose/gui/moosetree.py | Python | lgpl-2.1 | 3,777 | 0.018268 | # moosetree.py --- |
#
# Filename: moosetree.py
# Description:
# Author: subhasis ray
# Maintainer:
# Created: Tue Jun 23 18:54:14 2009 (+0530)
# Version:
# Last-Updated: Sun Jul 5 01:35:11 2009 (+0530)
# By: subhasis ray
# Update #: 137
# URL:
# Keywords:
# Compatibility:
#
#
# Commentary:
#
#
#
#
# Change... | modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3, 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 ... |
VitalPet/bank-statement-import | account_bank_statement_import/__openerp__.py | Python | agpl-3.0 | 573 | 0 | # -*- encoding: utf-8 -*-
{
'name': 'Account Bank Statement Import',
'category': 'Banking addons',
'version': '8.0.1.0.1',
'author': 'OpenERP SA,'
'Odoo Community Association (OCA)',
'website': 'https://github.com | /OCA/bank-statement-import',
'depends': ['account'],
| 'data': [
"views/account_config_settings.xml",
'views/account_bank_statement_import_view.xml',
],
'demo': [
'demo/fiscalyear_period.xml',
'demo/partner_bank.xml',
],
'auto_install': False,
'installable': False,
}
|
cjhdev/lora_device_lib | vendor/cmocka/.ycm_extra_conf.py | Python | mit | 3,399 | 0.028832 | import os
import ycm_core
flags = [
'-Wall',
'-Wextra',
'-Werror',
'-x', 'c',
'-Iinclude',
]
# Set this to the absolute path to the folder (NOT the file!) containing the
# compile_commands.json file to use that instead of 'flags'. See here for
# more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html
#
... | k
if flag.startswith( path_flag ):
path = flag[ len( | path_flag ): ]
new_flag = path_flag + os.path.join( working_directory, path )
break
if new_flag:
new_flags.append( new_flag )
return new_flags
def IsHeaderFile( filename ):
extension = os.path.splitext( filename )[ 1 ]
return extension in [ '.h', '.hxx', '.hpp', '.hh' ]
def GetCompi... |
Tecnativa/website | website_event_register_free/model/__init__.py | Python | agpl-3.0 | 1,041 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open S | ource Management Solution
# This module copyright (C) 2015 Therp BV <http://therp.nl>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, ... | am 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public Li... |
mohamedhagag/community-addons | project_scrum/tests/test_project_scrum.py | Python | agpl-3.0 | 196 | 0.020408 | # -*- coding: utf-8 -*-
from openerp.tests import common
clas | s TestProjectScrum(common.Tr | ansactionCase):
def test_project_scrum(self)
env = self.env
record = env['project_scrum.0'].create({})
|
homoludens/EventMap | hello/forms.py | Python | agpl-3.0 | 1,156 | 0.006055 | from flask_wtf import Form
| from wtforms import TextField, DecimalField, TextAreaField, DateField, validators, PasswordField, BooleanField
class | CommentForm(Form):
text = TextField('Title', [validators.Required()])
text2 = TextAreaField('Body')
longitude = DecimalField('Longitude')
latitude = DecimalField('Longitude')
date = DateField('Date')
class SignupForm(Form):
username = TextField('Username', [validators.Required()])
password... |
mhoffma/micropython | tests/basics/struct_micropython.py | Python | mit | 332 | 0.009036 | # test MicroPython-specific features of st | ruct
try:
import ustruct as struct
except:
try:
import struct
except ImportError:
import sys
print("SKIP")
sys.exit()
class A():
pass
# pack and unpack objects
o = A()
s = struct.pack("<O", o)
o2 = struct.unpack("<O", s) |
print(o is o2[0])
|
simontakite/sysadmin | pythonscripts/thinkpython/thread.py | Python | gpl-2.0 | 439 | 0.006834 | """Example code using Python threads.
Copy | right 2010 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from threading import Thread
from time import sleep
def counter(xs, delay=1):
for x in xs:
print x
sleep(delay)
# one thread counts backwards, fast
t = Thread(target=counter, args=[range(100, 1, -1), 0.25])
t.... | rt()
# the other thread count forwards, slow
counter(range(1, 100), 1)
|
mrok/ircAntiFloodBot | src/antiFloodBot.py | Python | apache-2.0 | 2,562 | 0.010929 | import os
import time
import json
import pprint
from util import hook
def readConfig():
### Read config json and parse it
confJson = None
with open(os.getcwd() + '/antiFloodBotConfig.json', 'r') as confFile:
confJson = confFile.read()
return json.loads(confJson)
inputs = {} #store time (uni... | n' % (nick))
out = "KICK %s %s : %s" % (chan, nick, explanationMessage)
conn.send(out)
kicked.append(nick)
file.close()
#todo
#if the same user joins again within 24 hour and keeps spamming temp ban in XX time.
#step 3) if the same user joins after the removal of the ban and spams, pe... | .
@hook.event('PRIVMSG')
def paramDump(inp, nick=None, msg=None, conn=None, chan=None):
def saveToFile(file, label, obj):
file.write("===== " + label + " ======== \n")
file.write("type " + str(type (obj)) + " ========\n")
file.write("methods " + str(dir(obj)) + " ========\n")
file.... |
oldmanmike/minecraftd | minecraftd/tests/test.py | Python | gpl-3.0 | 812 | 0.002463 | import random
import unittest
from minecraftd.common import tmux_id
"""
def tmux_id(id_list):
random.seed()
new_id = random.randint(1,100)
while new_id in id_list:
new_id = random.randint(1,100)
return new_id
"""
class CommonTest(unittest.TestCase):
def setUp(self):
self.id_list =... | t.append(new_id)
print(self.id_list)
print(new_id_list)
pri | nt(old_id_list)
self.assertEqual(len(set(new_id_list)), (len(set(old_id_list)) + 1))
if __name__ == '__main__':
unittest.main()
|
jzcxer/0Math | python/test.py | Python | gpl-3.0 | 286 | 0.045455 | l=int(input())
d=list(input().split())
s={0:0}
for i in range(l):
for j in range(i+1,l):
diff=abs(int(d[i])-int(d[j]))
if diff not in s:
| s[abs(diff)]=1
else:
s[diff]=s[diff]+1
f =lambda | x:print(str(x)+" "+str(s[x]))
f(max(s.keys())) |
koturn/FiveProgrammingProblems | Python/problem05.py | Python | mit | 602 | 0.001661 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def problem05(nrlst, oplst, answer):
if len(nrlst) == 0:
return []
else:
| exprlst = []
def _problem05(expr, i):
if i < len(nrlst):
for op in oplst:
_problem05(expr + op + str(nrlst[i]), i + 1)
elif eval(expr) == answer:
exprlst.append(expr)
_problem05(str(nrlst[0]), 1)
return exprlst
if __n... | :
print expr, '=', ANSWER
|
mosen/salt-osx | _modules/app.py | Python | mit | 2,741 | 0.001094 | # -*- coding: utf-8 -*-
'''
Manage running applications.
Similar to `ps`, you can treat running applications as unix processes.
On OS X, there is a higher level Cocoa functionality (see NSApplication) which responds to events sent through the
notification center. This module operates at that level.
:maintainer: M... | eturn status
def processes():
'''
Get a list of running processes in the user session
TODO: optional get by bundle ID
TODO: optional get hidden
'''
workSpace = NSWorkspace.sh | aredWorkspace()
appList = workSpace.runningApplications()
names = [app.localizedName() for app in appList]
names.sort()
return names
def frontmost():
'''
Get the name of the frontmost application
'''
workSpace = NSWorkspace.sharedWorkspace()
app = workSpace.frontmostApplication()... |
godiard/sugar-toolkit-gtk3 | src/sugar3/graphics/animator.py | Python | lgpl-2.1 | 7,131 | 0 | # Copyright (C) 2007, Red Hat, Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distrib... | l Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
"""
The animator module provide | s a simple framwork to create animations.
Example:
Animate the size of a window::
from gi.repository import Gtk
from sugar3.graphics.animator import Animator, Animation
# Construct a 5 second animator
animator = Animator(5)
# Construct a window to animate
w = Gtk.... |
huzq/scikit-learn | sklearn/datasets/_svmlight_format_io.py | Python | bsd-3-clause | 19,022 | 0.000473 | """This module implements a loader and dumper for the svmlight format
This format is a text-based format, with one sample per line. It does
not store zero valued features hence is suitable for sparse dataset.
The first element of each line can be used to store a target variable to
predict.
This format is used as the... | _load_svml | ight_file(
f, dtype, multilabel, zero_based, query_id, offset, length
)
# convert from array.array, give data the right dtype
if not multilabel:
labels = np.frombuffer(labels, np.float64)
data = np.frombuffer(data, actual_dtype)
indices = np.frombuffer(ind, np.longlo... |
beeftornado/sentry | src/sentry/constants.py | Python | bsd-3-clause | 16,659 | 0.00102 | """
These settings act as the default (base) settings for the Sentry-provided
web-server
"""
from __future__ import absolute_import, print_function
import logging
import os.path
import six
from datetime import timedelta
from collections import OrderedDict, namedtuple
from django.conf import settings
from django.utils... | ",
"plugins",
"themonitor",
"settings",
"legal",
"avatar",
"organization-avatar",
"project-avatar", |
"team-avatar",
"careers",
"_experiment",
"sentry-apps",
"resources",
"integration-platform",
"trust",
"legal",
"community",
)
)
RESERVED_PROJECT_SLUGS = frozenset(
(
"api-keys",
"audit-log",
"auth",
"member... |
supersu097/Mydailytools | converter.py | Python | gpl-3.0 | 905 | 0.01105 | #!/usr/bin/env python
# coding=utf-8
import sys
import argparse
parser = argparse.ArgumentParser(
description='convert a non-standord hostname like xx-xx-[1-3] to a '
'expansion state',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Sample:
$ ./converter.py xxx-xxx-\[1-3\]
xxx-xxx-1
x... | split('-')
prefix='-'.join(basestr[:-2])
range_li=basestr[-2:]
start_num=int(range_li[0][1:])
end_num=int(range_li[1][:-1])
for i in range(start | _num,end_num+1):
print prefix + '-' + str(i)
|
jiadaizhao/LeetCode | 0201-0300/0287-Find the Duplicate Number/0287-Find the Duplicate Number.py | Python | mit | 357 | 0.002801 | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
slow = nums[0]
fast | = nums[nums[0]]
while slow != fast:
slow = nums[slow]
fast = nums[nums[fast]]
slow2 = 0
while slow != slow2:
slow = nums[slow]
| slow2 = nums[slow2]
return slow
|
dougwig/acos-client | acos_client/v21/partition.py | Python | apache-2.0 | 1,617 | 0 | # Copyright 2014, Doug Wiegley, A10 Networks.
#
# 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 appli... | guage governing permissions and limitations
# under the Licen | se.
import acos_client.errors as acos_errors
import base
class Partition(base.BaseV21):
def exists(self, name):
if name == 'shared':
return True
try:
self._post("system.partition.search", {'name': name})
return True
except acos_errors.NotFound:
... |
dadisigursveinn/VEF-Lokaverkefni | photos/views.py | Python | bsd-3-clause | 991 | 0.002018 | from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from .models import Document
from .forms import DocumentForm
def list(request):
# Handle file upload
if request.method == 'POST'... | uments = Docum | ent.objects.all()
# Render list page with the documents and the form
return render_to_response(
'list.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
) |
wilkerwma/codeschool | src/cs_core/migrations/0007_auto_20160619_2154.py | Python | gpl-3.0 | 729 | 0.001372 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-06-20 00:54
from __future__ import unicode_literals
from dja | ngo.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cs_c | ore', '0006_auto_20160619_2151'),
]
operations = [
migrations.RemoveField(
model_name='responsecontext',
name='parent',
),
migrations.AlterField(
model_name='responsecontext',
name='delayed_feedback',
field=models.BooleanField(... |
tofu-rocketry/apel | test/test_blah.py | Python | apache-2.0 | 6,667 | 0.00855 | import datetime
import unittest
from iso8601 import ParseError
from apel.parsers import BlahParser
from apel.db.records.record import InvalidRecordException
class ParserBlahTest(unittest.TestCase):
'''
Test case for LSF parser
'''
def setUp(self):
self.parser = BlahParser('testSite', 'testH... | = record._record_content
# Check that 'Site' has been set
self.assertEqual(cont['Site'], 'testSite')
for key in cases[line].keys():
# Check all fields are present
self.assertTrue(key in cont, "Key '%s' not in record." % key)
# Check v... | line][key],
"'%s' != '%s' for key '%s'" %
(cont[key], cases[line][key], key))
if __name__ == '__main__':
unittest.main()
|
mbroome/ogslb | bin/backend-test.py | Python | gpl-2.0 | 2,025 | 0.017284 | #!/usr/bin/python
# Open Global Server Load Balancer (ogslb)
# Copyright (C) 2010 Mitchell Broome
#
# 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... | sys.exit()
try:
scriptName = scriptPath + '/backend.py'
p = Popen(scriptName, shell=True, bufsize=256, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
# p = Popen(scriptName, shell=True, bufsize=256, stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdin, child_stdout) = (p.stdin, p.s... | n' % host);
child_stdin.flush()
l = child_stdout.readline()
print l
p.close()
except:
''' '''
|
zepheir/pySrv_sipai | srv/src/sipaiSampleServer.py | Python | apache-2.0 | 4,049 | 0.013844 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2012-2-5
@author: zepheir
'''
import sys
sys.path.append('/app/srv/src')
from binascii import b2a_hex
try:
from twisted.internet import epollreactor
epollreactor.install()
except:
pass
from twisted.internet import reactor
from twisted.pytho... | # servs1.update()
# servs2.update()
# # servs3.update()
# else:
# for sds in SipaiModsDict:
# servs[sds]=SampleServer(sds[0],sds[1])
# servs[sds].update()
# time.sleep(0.2)
if __name__ == '__main__':
import sys
main()
reactor.run()
pr... | PAI")
|
endlessm/chromium-browser | third_party/llvm/lldb/test/API/lang/objc/conflicting-definition/TestConflictingDefinition.py | Python | bsd-3-clause | 1,681 | 0.000595 | """Test that types defined in shared libraries work correctly."""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestRealDefinition(TestBase):
mydir = TestBase.compute_mydir(__file__)
@skipUnlessDarwin
def test_frame... | [
"42"])
def common_setup(self):
exe = self.getBuildArtifact("a.out")
target = self.dbg.CreateTarget(exe)
self.registerSharedLibrariesWithTarget(target, self.shlib_names)
self. | runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
|
hmustafamail/digitalimageprocessing | HW 3 - Spatial Filtering/spatialFiltering.py | Python | gpl-2.0 | 8,567 | 0.023345 | # Mustafa Hussain
# Digital Image Processing with Dr. Anas Salah Eddin
# FL Poly, Spring 2015
#
# Homework 3: Spatial Filtering
#
# USAGE NOTES:
#
# Written in Python 2.7
#
# Please ensure that the script is running as the same directory as the images
# directory!
import cv2
import copy
#import matplotlib.pyplot as p... | s.
for i in range(width - 2):
for j in range(height - 2):
neighborhood = list()
for i1 in range(i - 2, i + 3):
for j1 in range(j - 2, j + 3):
neighborhood. | append(image[i1][j1])
filteredImage[i][j] = numpy.median(neighborhood)
return filteredImage
def laplacianFilter(image):
"""Approximates the second derivative, bringing out edges.
Referencing below zero wraps around, so top and left sides will be sharpened.
We are not bothering with the... |
Devyani-Divs/pagure | pagure/lib/__init__.py | Python | gpl-2.0 | 44,784 | 0.000357 | # -*- coding: utf-8 -*-
"""
(c) 2014-2015 - Copyright Red Hat Inc
Authors:
Pierre-Yves Chibon <pingou@pingoured.fr>
"""
import datetime
import os
import shutil
import tempfile
import uuid
import sqlalchemy
import sqlalchemy.schema
from datetime import timedelta
from sqlalchemy import func
from sqlalchemy.orm... | issue, repo=issue.project, repofolder=ticketfolder)
if notify:
pagure.lib.notify.notify_new_comment(issue_comment, user=user_obj)
if not issue.private:
pagure.lib.notify.fedmsg_publish(
'issue.comment.added',
dict(
issue=issue.to_json(),
... | ssue, tags, user, ticketfolder):
''' Add a tag to an issue. '''
user_obj = __get_user(session, user)
if isinstance(tags, basestring):
tags = [tags]
msgs = []
added_tags = []
for issue_tag in tags:
known = False
for tag_issue in issue.tags:
if tag_issue.tag =... |
Thingee/cinder | cinder/api/contrib/backups.py | Python | apache-2.0 | 13,643 | 0.000073 | # Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
# 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/LICEN... | xmlutil.SubTemplateElement(root, 'backup', selector='backups')
make_backup(elem)
alias = Backups.alias
namespace = Backups.namespace
return xmlutil.MasterTemplate(root, 1, nsmap={alias: namespace})
class BackupRestoreTemplate(xmlutil.TemplateBuilder):
| def construct(self):
root = xmlutil.TemplateElement('restore', selector='restore')
make_backup_restore(root)
alias = Backups.alias
namespace = Backups.namespace
return xmlutil.MasterTemplate(root, 1, nsmap={alias: namespace})
class BackupExportImportTemplate(xmlutil.TemplateBu... |
timbrom/lightshow | scripts/flash_and_debug.py | Python | apache-2.0 | 2,657 | 0.004893 | #!/usr/bin/env python
import telnetlib
import subprocess
import signal
import time
###############################################################
# This script will automatically flash and start a GDB debug
# session to the STM32 discovery board using OpenOCD. It is
# meant to be called from the rake task "debug" (... | pass # do nothing
############ | ###################################################
# Start up the openocd thread
###############################################################
# We need gdb to respond to a SIGINT (ctrl-c), but by default,
# that will cause every other child process to die, including
# openocd. Disable sigint, then re-enable it af... |
RCMRD/geonode | geonode/upload/views.py | Python | gpl-3.0 | 26,130 | 0.000651 | #########################################################################
#
# Copyright (C) 2012 OpenPlans
#
# 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
#... | # if the current step is the view POST for this step, advance one
if req.method == 'POST':
if upload_session.completed_step:
advance_step(req, upload_session)
else:
upload_session.completed_step = 'save'
next = get_next_step(upload_session)
if next == 'time':
... | for coverages currently
import_session = upload_session.import_session
store_type = import_session.tasks[0].target.store_type
if store_type == 'coverageStore':
upload_session.completed_step = 'time'
return _next_step_response(req, upload_session, force_ajax)
if next ... |
jmarcelogimenez/petroFoam | initialConditions.py | Python | gpl-2.0 | 6,385 | 0.010807 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 25 13:08:19 2015
@author: jgimenez
"""
from PyQt4 import QtGui, QtCore
from initialConditions_ui import Ui_initialConditionsUI
import os
from utils import *
from PyFoam.RunDictionary.BoundaryDict import BoundaryDict
from PyFoam.RunDictionary.ParsedParameterFile import P... | else:
parsedData['internalField'] = '%s (%s %s %s)'%(layout2.itemAt(0).widget().currentText(),layout2.itemAt(1).widget().text(),layout2.itemAt(2).widget | ().text(),layout2.itemAt(3).widget().text())
parsedData.writeFile()
self.pushButton.setEnabled(False)
if runPotentialFlow:
QtGui.QMessageBox.about(self, "ERROR", 'Debe simularse con potentialFoam, hacer!!')
return
def checkData(self... |
scholer/pptx-downsizer | pptx_downsizer/utils.py | Python | gpl-3.0 | 3,492 | 0.003436 | import os
import sys
import zipfile
def zip_directory(directory, targetfn=None, relative=True, compress_type=zipfile.ZIP_DEFLATED, verbose=1):
"""Zip all files and folders in a directory.
Args:
directory: The directory whose contents should be zipped.
targetfn: Output filename of the zipped a... | ompress_type)
filecount += 1
if verbose and verbose > 0:
print("\n%s files written to archive %r" % (filecount, targetfn))
return targetfn
def convert_str_to_int(s, do_float=True, do_eval=True):
try:
return int(s)
except ValueError as e:
if do_float:
... | _eval=False)
except ValueError as e:
try:
import humanfriendly
except ImportError:
print((
"Warning, the `humanfriendly` package is not available."
"If you want to use e.g. \"500kb\" as fi... |
mozilla/lumbergh | careers/base/templatetags/helpers.py | Python | mpl-2.0 | 1,025 | 0 | import datetime
try:
import urllib.parse as urlparse
except ImportError:
from urllib.urlparse import urlparse
from django_jinja import library
from django.utils.http import urlencode
@library.global_function
def thisyear():
"""The current year."""
return datetime.date.today().year
@library.filter
d... | )
fragment = hash if hash is not None else url.fragment
# Use dict(parse_qsl) so we don't get lists of values.
query_dict = dict(urlparse.parse_qsl(url.query))
query_dict.update(query)
query_string = urlencode(
[(k, v) for k, v in query_dict.items() if v is not None])
new = urlparse.Pa... | rl.params,
query_string, fragment)
return new.geturl()
|
google/grr | grr/server/grr_response_server/prometheus_stats_collector_test.py | Python | apache-2.0 | 514 | 0.005837 | #!/u | sr/bin/env python
# Lint as: python3
"""Tests for PrometheusStatsCollector."""
from absl import app
from grr_response_core.stats import stats_test_utils
from grr_response_server import prometheus_stats_collector
from grr.test_lib import test_lib
class PrometheusStatsCollectorTest(stats_test_utils.StatsCollectorTes... | |
prculley/gramps | gramps/gen/filters/rules/person/_changedsince.py | Python | gpl-2.0 | 1,921 | 0.006247 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2007 Donald N. Allingham
#
# 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 you... | n.filters.rules/Person/_ChangedSince.py
#-------------------------------------------------------------------------
#
# Standard Python modules
#
#-------------------------------------------------------------------------
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#------------------... | --------------------------------------------------------
from .._changedsincebase import ChangedSinceBase
#-------------------------------------------------------------------------
#
# ChangedSince
#
#-------------------------------------------------------------------------
class ChangedSince(ChangedSinceBase):
""... |
zenodo/zenodo-migrator | zenodo_migrator/serializers/schemas/__init__.py | Python | gpl-2.0 | 1,061 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo 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.
#
# Zenodo 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 th | e GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges ... |
tuxlifan/moneyguru | qt/controller/panel.py | Python | gpl-3.0 | 5,750 | 0.003826 | # Copyright 2016 Virgil Dupras
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
QDialog, QLin... | (self.comboBoxCurrentIndexChanged)
index = comboBox.currentIndex()
combo | Box.clear()
comboBox.addItems(newItems)
comboBox.setCurrentIndex(index)
if comboBox in self._widget2ModelAttr:
comboBox.currentIndexChanged.connect(self.comboBoxCurrentIndexChanged)
def _connectSignals(self):
for widgetName, modelAttr in self.FIELDS:
widget =... |
macks22/nsf-award-data | util/num_cpus.py | Python | mit | 2,737 | 0 | import os
import re
import subprocess
def available_cpu_count():
""" Number of available virtual or physical CPUs on this system, i.e.
user/real as output by time(1) when called with an optimally scaling
userspace-only program"""
# cpuset
# cpuset may restrict the number of *available* processors... | puid@[0-9]+$', pd):
res += 1
if res > 0:
return res
except OSError:
pass
# Other UNIXes (heuristic)
try:
try:
dmesg = open('/var/run/dmesg.boot').read()
except IOError:
dmesgProcess = subprocess.Popen(['dmesg'], stdout=sub... | esg:
res += 1
if res > 0:
return res
except OSError:
pass
raise Exception('Can not determine number of CPUs on this system')
|
geoscixyz/em_examples | em_examples/Loop.py | Python | mit | 6,800 | 0.032206 | from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from SimPEG import Mesh, Utils
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from scipy.sparse import spdiags,csr_matrix, eye,kron,hstack,vstack,eye,diags
impor... | (I,r)
rsq = np.linalg.norm(r,axis=1)**3.
B = B + c*cr/rsq[:,None]
else:
print('error: index of J out of bounds (number of edges in the mesh)')
return B
def analytic_infinite_wire(obsloc,wireloc,orientation,I=1.):
"""
Compute the response of an infinite wire with... | z]
"""
n,d = obsloc.shape
t,d = wireloc.shape
d = np.sqrt(np.dot(obsloc**2.,np.ones([d,t]))+np.dot(np.ones([n,d]),(wireloc.T)**2.)
- 2.*np.dot(obsloc,wireloc.T))
distr = np.amin(d, axis=1, keepdims = True)
idxmind = d.argmin(axis=1)
r = obsloc - wireloc[idxmind]
orient = np.c_[[ori... |
davelab6/pyfontaine | fontaine/charsets/internals/google_greek_ancient_musical_symbols.py | Python | gpl-3.0 | 371 | 0.008086 | # -*- coding: utf-8 -*-
from fontaine.namelist import codepoin | tsInNamelist
class Charset:
common_name = u'Google Fonts: Greek Ancient Musical Symbols'
native_name = u''
abbreviation = 'GREK'
def glyphs(self):
gl | yphs = codepointsInNamelist("charsets/internals/google_glyphsets/Greek/GF-greek-ancient-musical-symbols.nam")
return glyphs
|
hirokazumiyaji/pundler | pundler/commands/install.py | Python | mit | 258 | 0 | # coding: utf-8
from __future__ i | mport absolute_import
from .base import Base
class Install(Base):
def __init__(self, config):
self.config = config
def run(self):
for package in self.config.packages:
package.inst | all()
|
EmreAtes/spack | var/spack/repos/builtin/packages/py-traceback2/package.py | Python | lgpl-2.1 | 1,692 | 0.001182 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | rogram 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 th | e terms and
# conditions of 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 program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#######################... |
kfeiWang/pythonUtils | wordProbability.py | Python | mit | 1,782 | 0.003064 | # -*- coding:utf8 -*-
from __future__ import division
import codecs
import re
def calWordProbability(infile, outfile):
'''
计算词概率,源语言词翻译成目标语言词的概率
一个源语言可能对应多个目标语言,这里计算平均值
infile: 输入文件 格式:source word \t target word
outfile: source word \t target word \t probability
'''
with codecs.open(infil... | eadline()
linNum = 1
while line:
linNum += 1
if linNum % 10001 == 1:
print(linNum, line.encode('utf8'))
line = line.strip() # 删除两端空白符
wArr = re.split('[ |\t]', line)
if len(wArr) >= 2:
key = wArr[0] # 源语言词
... | y][val] = 1
else:
valMap = dict()
valMap[val] = 1
wordDic[key] = valMap
line = fin.readline()
with codecs.open(outfile, 'w', 'utf8') as fout:
print('start write')
wCount = 0
for key in wordDic.keys():
... |
OCA/bank-statement-reconcile | base_transaction_id/models/invoice.py | Python | agpl-3.0 | 1,321 | 0 | # Copyright 2011-2012 Nicolas Bessi (Camptocamp)
# Copyright 2012-2015 Yannick Vaucher (Camptocamp)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models, fields, api
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
transaction_id = fields.Char(string='Transa... |
@api.multi |
def finalize_invoice_move_lines(self, move_lines):
"""Propagate the transaction_id from the invoice to the move lines.
The transaction ID is written on the move lines only if the account is
the same than the invoice's one.
"""
move_lines = super(AccountInvoice, self).finali... |
pstrinkle/drf-coupons | coupons/views.py | Python | apache-2.0 | 8,022 | 0.001247 | from django.conf import settings
from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters, status, viewsets
from rest_... | value_is_int = True
except ValueError:
pass
| if value_is_int:
coupon = get_object_or_404(Coupon.objects.all(), pk=pk)
else:
coupon = get_object_or_404(Coupon.objects.all(), code_l=pk.lower())
serializer = CouponSerializer(coupon, context={'request': request})
return Response(serializer.data)
@method_deco... |
botify-labs/moto | moto/cloudwatch/urls.py | Python | apache-2.0 | 164 | 0 | from .responses import | CloudWatchResponse
url_bases = [
"https?://monitoring.(.+).amazonaws.com",
]
url_paths = {
'{0}/$': CloudWa | tchResponse.dispatch,
}
|
meatballhat/ansible-inventory-hacks | ansible_inventory_hacks/filters/instance_filter.py | Python | mit | 1,066 | 0 | #!/usr/bin/env python
# vim:fileencoding=utf-8
import argparse
import json
import sys
import os
def main(sysargs=sys.argv[:]):
parser = argparse.A | rgumentParser()
parser.add_argument(
'instream', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
parser.add_argument(
'-f', '--output-format', choices=['text', 'json'],
default=os.environ.get('FORMAT', 'json'))
args = parser.parse_args(sysargs[1:])
instance_mapped_inv... | for key, value in sorted(instance_mapped_inv.items()):
sys.stdout.write('{} {}\n'.format(key, value))
else:
json.dump(instance_mapped_inv, sys.stdout, indent=2)
sys.stdout.write('\n')
return 0
def filter_json(inv):
instance_mapped_inv = {}
for key, values in inv.items(... |
tdyas/pants | contrib/node/src/python/pants/contrib/node/register.py | Python | apache-2.0 | 2,805 | 0.001426 | # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
"""Support for JavaScript and Node.js."""
from pants.build_graph.build_file_aliases import BuildFileAliases
from pants.goal.task_registrar import TaskRegistrar as task
from pants.contrib... | ts.contrib.node.targets.node_remote_module import NodeRemoteModule as NodeRemoteModuleV1
from pants.contrib.node.targets.node_test import NodeTest as NodeTestTargetV1
from | pants.contrib.node.tasks.javascript_style import JavascriptStyleFmt, JavascriptStyleLint
from pants.contrib.node.tasks.node_build import NodeBuild
from pants.contrib.node.tasks.node_bundle import NodeBundle as NodeBundleTask
from pants.contrib.node.tasks.node_install import NodeInstall
from pants.contrib.node.tasks.no... |
tcstewar/ev3_demo | udp_base.py | Python | gpl-2.0 | 3,050 | 0.00623 | import nengo
from nengo.dists import Uniform
import nstbot
import numpy as np
import joystick_node
import udp
import time
use_bot = False
if use_bot:
bot = nstbot.EV3Bot()
#bot.connect(nstbot.connection.Socket('192.168.1.160'))
bot.connect(nstbot.connection.Socket('10.162.177.187'))
time.sleep(1)
... | mbles:
ens.intercepts = Uniform(0.05, 0.9)
omni_transform = np.array([[-1, 0, -1], [0.5, 1, -0.5], [1, -1, -1]]).T
nengo.Connection(control.output[[1, 0, 2]], motor.input[:3],
| transform=omni_transform * 2, synapse=synapse)
nengo.Connection(control.output[3], motor.input[3], transform=-1,
synapse=synapse)
def bot_motor(t, x):
if use_bot:
bot.motor(1, x[0], msg_period=msg_period)
bot.motor(0, x[1], msg_period=msg... |
mitschabaude/nanopores | nanopores/geo2xml.py | Python | mit | 6,483 | 0.004782 | import subprocess
from importlib import import_module
import os
import dolfin
import nanopores
from nanopores.tools.utilities import Log
#FIXME: deprecated because of license conflict -> import from dolfin
#from nanopores.meshconvert import convert2xml
MESHDIR = "/tmp/nanopores"
def geofile2geo(code, meta, name=None, ... | ly take latest mesh
# if params is not None, check if they agree with meta["params"]
# throw error if no matching mesh is available
meshdir = (MESHDIR + "/" + name) if name is not None else MESHD | IR
if not os.path.exists(meshdir):
raise EnvironmentError("Geometry folder does not exist yet.")
if pid is None:
# get pid of latest mesh
files = os.listdir(meshdir)
mfiles = [f for f in files if f.startswith("input")]
if not mfiles:
raise EnvironmentError("No... |
cooncesean/remotestatus | remotestatus/urls.py | Python | mit | 328 | 0.009146 | from django.conf.urls import patterns, include, url
urlpatterns = patterns('remotestatus.views',
url(r'^re | mote-box/(?P<remote_box_id>[0-9]+)/$', 'remote_box_detail', name='rs-remote-box-detail'),
url(r'^(?P<call_round_id>[0- | 9]+)/$', 'dashboard', name='rs-dashboard'),
url(r'^$', 'dashboard', name='rs-dashboard'),
) |
sih4sing5hong5/django-allauth | allauth/account/views.py | Python | mit | 27,368 | 0.000512 | from django.core.urlresolvers import reverse, reverse_lazy
from django.http import (HttpResponseRedirect, Http404,
HttpResponsePermanentRedirect)
from django.views.generic.base import TemplateResponseMixin, View, TemplateView
from django.views.generic.edit import FormView
from django.contrib im... | ordForm, SignupForm, UserTokenForm)
from .utils import sync_user_email_addresses
from .models import EmailAddress, EmailConfirmation
from . import signals
from . import app_settings
from .adapter import get_adapter
try:
from django.contrib.auth import update_session_auth_hash
except ImportError:
update_sessi... | se(request, response, form=None):
if request.is_ajax():
if (isinstance(response, HttpResponseRedirect)
or isinstance(response, HttpResponsePermanentRedirect)):
redirect_to = response['Location']
else:
redirect_to = None
response = get_adapter().ajax_re... |
seraphln/onedrop | onedrop/odtasks/tests.py | Python | gpl-3.0 | 72 | 0.017241 | # c | oding=utf8
#
"""
odtasks模块的测试用例
"""
import un | ittest |
zellahenderson/PennApps2013 | src/prettydate.py | Python | mit | 1,307 | 0.004591 | def pretty_date(time=False):
"""
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
"""
from datetime import datetime
now = datetime.now()
if type(time) is int:
diff = now - datetime.fromtim... | return "Yesterday"
if day_diff < 7:
return str(day_diff) + " days ago"
if day_diff < 31:
return str(day_diff/7) + " weeks ago"
if day_diff < 365:
return str(day_diff/30) + " mont | hs ago"
return str(day_diff/365) + " years ago"
|
alabarga/SocialLearning | SocialLearning/pbl.py | Python | gpl-3.0 | 1,607 | 0.009956 | enlaces_iniciales = ['http://www.edutopia.org/project-based-learning-history',
'http://bie.org/about/why_pbl',
'http://es.wikipedia.org/wiki/Aprendizaje_basado_en_proyectos',
'http://en.wikipedia.org/wiki/Project-based_learning',
'https://www.youtube.com/watch?v=LMCZvGesRz8',
'http://www.learnnc.org/lp/pages/4753',
'ht... | /seven_essentials_for_project-based_learning.aspx',
'http://eric.ed.gov/?q=%22%22&ff1=subActive+Learning',
'http://eric.ed.gov/?q=%22%22&ff1=subStudent+Projects']
from learningobjects.utils.alchemyapi import AlchemyAPI
from learningobjects.utils.parsers import *
from learningobjects.utils.search import *
from ftfy imp... |
for url in enlaces_iniciales:
gp_desc = GooseParser(url).describe()
texto += gp_desc.text
for tag in gp_desc.tags:
tags.add(tag.strip())
texto = fix_text(texto)
more_links = set()
alchemyapi = AlchemyAPI()
response = alchemyapi.keywords("text", texto)
concept = response['keywords'][0]['text']
... |
dudochkin-victor/contextkit | sandbox/multithreading-tests/stress-test/provider.py | Python | lgpl-2.1 | 946 | 0.013742 | #!/u | sr/bin/env python2.5
"""A test provider for the stress testing."""
# change registry this often [msec]
registryChangeTimeout = 2017
from ContextKit.flexiprovider import *
import gobject
import time
import os
def update():
t = time.time()
dt = int(1000*(t - round(t)))
gobject.timeout_add(1000 - dt, upda... | return False
pcnt = 0
def chgRegistry():
global pcnt
pcnt += 1
if pcnt % 2:
print "1 provider"
os.system('cp 1provider.cdb tmp.cdb; mv tmp.cdb cache.cdb')
else:
print "2 providers"
os.system('cp 2providers.cdb tmp.cdb; mv tmp.cdb cache.cdb')
return True
gobject.timeout_add... |
albertosalmeronunefa/tuconsejocomunal | addons/tcc_communal_council/models/family.py | Python | gpl-3.0 | 24,178 | 0.009822 | # -*- coding: utf-8 -*-
from datetime import date, datetime
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, tools, SUPERUSER_ID, _
from odoo.exceptions import AccessDenied, AccessError, UserError, ValidationError
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT as DF
from odoo... | cion', 'Habitación'),
('Other','Otro'),
]
name = fields.Char(
string='Nombre de la familia',
readonly=True,
)
code_family = fields.Char(
string='Código de la familia',
readonly=True,
... | mmunal_council_id = fields.Many2one(
'tcc.communal.council',
string='Consejo comunal',
default=default_communal_council,
readonly=True,
)
apartment = fields.Char(
string='Apartamento',
)
floor = fiel... |
vmalloc/flux | flux/timeline.py | Python | bsd-3-clause | 5,399 | 0.001297 | import contextlib
import datetime
import functools
import heapq
import time
from numbers import Number
class Timeline(object):
def __init__(self, start_time=None):
super(Timeline, self).__init__()
current_time = self._real_time()
self._forced_time = None
self._scheduled = []
... | # shift stems from the previous correction...
self._time_correction.shift = 0
def sleep(self, seconds):
"""
Sleeps a given number of seconds in the virtual timeline
| """
if not isinstance(seconds, Number):
raise ValueError(
"Invalid number of seconds specified: {0!r}".format(seconds))
if seconds < 0:
raise ValueError("Cannot sleep negative number of seconds")
if self._time_factor == 0:
self.set_time(sel... |
BurtBiel/azure-cli | src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/mgmt_avail_set/lib/models/__init__.py | Python | mit | 1,439 | 0.00417 | #---------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#---------------------------------------------------------------------... | ------------------------
from .deployment_avail_set import DeploymentAvailSet
from .template_link import TemplateLink
from .parameters_link import ParametersLink
from .provider_resource_type import ProviderResourceType
from .provider import Provider
from .basic_dependency import BasicDependency
from .depen | dency import Dependency
from .deployment_properties_extended import DeploymentPropertiesExtended
from .deployment_extended import DeploymentExtended
from .avail_set_creation_client_enums import (
DeploymentMode,
)
__all__ = [
'DeploymentAvailSet',
'TemplateLink',
'ParametersLink',
'ProviderResource... |
dsweet04/rekall | rekall-agent/rekall_agent/client_actions/tsk_test.py | Python | gpl-2.0 | 1,298 | 0 | from rekall import resources
from rekall_agent import testlib
from rekall_agent.client_actions import files
from rekall_agent.client_actions import tsk
class TestTSK(testlib.ClientAcionTest):
def setUp(self):
super(TestTSK, self).setUp()
# Add a fake mount point to the image.
mount_tree_h... | mount_tree, "/mnt/",
resources.get_resource("winexec_img.dd",
package="rekall_agent",
prefix="test_data"),
"ext2")
se | lf.session.SetParameter("mount_points", mount_tree)
def testTSK(self):
action = tsk.TSKListDirectoryAction(session=self.session)
action.path = "/mnt/a"
action.vfs_location = self.get_test_location("test")
self.assert_baseline("testTSK", list(action.collect()))
def testTSKRecurs... |
danking/hail | hail/python/setup-hailtop.py | Python | mit | 848 | 0 | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='hailtop',
version="0.0.1",
author="Hail Team",
author_email="hail@broadinstitute.org",
description="Top level Hail module.",
url="https://hail.is",
| project_urls={
'Documentation': 'https://hail.is/docs/0.2/',
'Repository': 'https://github.com/hail-is/hail',
},
packages=find_packages('.'),
package_dir={
'hailtop': 'hailtop'},
package_data={
'hailtop.hailctl': ['hail_version', 'deploy.yaml']}, |
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
],
python_requires=">=3.6",
entry_points={
'console_scripts': ['hailctl = hailtop.hailctl.__main__:main']
},
setup_requires=["pytest-runner", "wheel"]
)
|
andreaso/ansible | lib/ansible/modules/system/ohai.py | Python | gpl-3.0 | 1,863 | 0.002684 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you c | an 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.
#
# A | nsible 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 of the GNU General Public License
# along with Ans... |
vimilimiv/weibo-popularity_judge-and-content_optimization | 数据处理/get_keyword_feature.py | Python | mit | 3,446 | 0.016007 | #-------------------------------------------------------------------------------
# | coding=utf8
# Name: 模块1
# Purpose:
#
# Author: zhx
#
# Created: 10/05/2016
# Copyright: (c) zhx 2016
# Licence: <yo | ur licence>
#-------------------------------------------------------------------------------
import openpyxl
import jieba
threshold = 2140
popular = 0
def main():
cctv_data = openpyxl.load_workbook("cctv.xlsx")
cctv_keywords = openpyxl.load_workbook("cctv_keywords.xlsx")
cctv_new = openpyxl.Workbook()
n... |
pythonistas-tw/academy | web-api/tonypythoneer/db-exercise/v2/app/views/users/auth.py | Python | gpl-2.0 | 2,194 | 0.000456 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @first_date 20160129
# @date 20160129
# @version 0.0
"""auth for Users API
"""
from flask import abort
from flask.views import MethodView
from flask.ext.login import login_required, current_user
from sqlalchemy.exc import IntegrityError
from webargs... | =('json',))
def put(self, args):
user = current_user
if not user.check_password(args['old_password']):
abort(401)
user.set_password(args['new_password'])
user.update()
return self.get_response(status=200)
# Url patterns: To register views in blueprint
users_bp.a... | ogout', view_func=LogoutView.as_view('logout'))
users_bp.add_url_rule('/reset_password', view_func=ResetPasswordView.as_view('reset-password'))
|
LuyaoHuang/patchwatcher | patchwatcher2/patchwork/patchwork.py | Python | lgpl-3.0 | 3,188 | 0.00345 | import os
import re
import lxml.etree as etree
import subprocess
import urllib2
""" TODO: move patchwatcher in this dir """
def improvemailaddr(strings):
if '<' in strings and '>' in strings:
tmplist = strings[strings.find('<')+1:strings.find('>')].split()
retstrings = "%s@" % tmplist[0]
fi... | [1:]
if "PATCH" not in subject:
return [info, cleansubj, labels]
for i in re.findall('\[[^\[\]]+\]', subject):
tmplist = i[1:-1].replace('PATCH', ' ').split()
for n in tmplist:
if '/' in n:
info = n
labels.append(n)... |
if not tmpsubject:
continue
index, _, _ = _parseSubject(tmpsubject)
if index == '':
""" not sure what happened """
ret_patch += tmppatch
continue
patch_dict[str(index)] = tmppatch
queue = patch_dict.keys()
queue.sort()
for i ... |
snakeleon/YouCompleteMe-x86 | third_party/ycmd/third_party/JediHTTP/vendor/jedi/test/completion/definition.py | Python | gpl-3.0 | 1,072 | 0.028918 | """
Fallback to callee definition when definition not found.
- https://github.com/davidhalter/jedi/issues/131
- https://github.com/davidhalter/jedi/pull/149
"""
"""Parenthesis closed at next line."""
# Ignore these definitions for a little while, not sure if we really want them.
# python <= 2.5
#? isinstance
isinsta... | ce( )
"""Unclosed parenthesis."""
#? isinstance
isinstance(
def | x(): pass # acts like EOF
##? isinstance
isinstance(
def x(): pass # acts like EOF
#? isinstance
isinstance(None,
def x(): pass # acts like EOF
##? isinstance
isinstance(None,
|
wei0831/fileorganizer | fileorganizer/fanhaorename.py | Python | mit | 2,156 | 0.000928 | #!/usr/bin/python
""" fanhaorename.py
"""
import os
import os.path
import logging
import fileorganizer
from fileorganizer import _helper
from fileorganizer.replacename import _replacename
__author__ = "Jack Chang <wei0831@gmail.com>"
def _tagHelper(tag):
""" TODO
"""
result = ""
for c in tag:
... | f mode in (1, 2): # mode 1 and 2
for item in _replacename(_find_dir, _replace_dir, work_dir, 1,
exclude):
item.commit() if wetrun else loger.info("%s", item)
loger.info("[END] === %s [%s RUN] ===", this_name, this_run)
if __name__ == "__main | __":
fileorganizer.cli.cli_fanhaorename()
|
kohr-h/odl | odl/contrib/tensorflow/examples/tensorflow_layer_ray_transform.py | Python | mpl-2.0 | 1,582 | 0 | """Example of how to convert a RayTransform operator to a tensorflow layer.
This example is similar to ``tensorflow_layer_matrix``, | but demonstrates how
more advanced operators, such as a ray transform, can be handled.
"""
from __future__ im | port print_function
import tensorflow as tf
import numpy as np
import odl
import odl.contrib.tensorflow
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
space = odl.uniform_discr([-64, -64], [64, 64], [128, 128],
dtype='float32')
geometry = odl.tomo.parallel_beam_geome... |
crypotex/taas | taas/user/migrations/0003_change_user_manager.py | Python | gpl-2.0 | 447 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import taas.user.models
class Migration(migrations.Migration):
dependencies = [
('user', '0002_r | emove_username'),
]
operations = [
migrations.AlterModelManagers(
name='user',
managers=[
('objects', taas.user.mode | ls.CustomUserManager()),
],
),
]
|
unioslo/cerebrum | Cerebrum/modules/tsd/ResourceService.py | Python | gpl-2.0 | 5,210 | 0.001536 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2013 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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 t... | Subnet(self.db)
self.aaaa = AAAARecord.AAAARecord(self.db)
self.ip = IPv6Number.IPv6Number(self.db)
# TODO: could we save work by only using a single, shared object of
# the auth class? It is supposed to be thread safe.
#self.ba = BofhdAuth(self.db)
self.operator_id = op... | hen Twisted is reusing the threads.
"""
if hasattr(self, 'db'):
try:
self.db.close()
except Exception, e:
log.warning("Problems with db.close: %s" % e)
else:
# TODO: this could be removed later, when it is considered stable
... |
ajinabraham/Mobile-Security-Framework-MobSF | MalwareAnalyzer/views/domain_check.py | Python | gpl-3.0 | 4,055 | 0.002466 | # -*- coding: utf_8 -*-
# Module for Malware Analysis
from urllib.parse import urlparse
import logging
import shutil
import io
import os
import re
import tempfile
import requests
from django.conf import settings
from MobSF.utils import (
PrintException,
isInternetAvailable,
upstream_proxy,
sha256
)
lo... | )
with io.open(mal_db, mode='r', encoding="utf8", errors="ignore") as flip:
entry_list = flip.readlines()
| for entry in entry_list:
enlist = entry.split('","')
if len(enlist) > 5:
details_dict = dict()
details_dict["domain_or_url"] = enlist[1]
details_dict["ip"] = enlist[2]
details_dict["desc"] = enlist[4]
... |
jstacoder/pycrm | level2_pycrm/__init__.py | Python | bsd-3-clause | 9,286 | 0.010015 | # -*- coding: utf-8 -*-
import wtforms
from werkzeug import OrderedMultiDict
from sample_data import ContactsDashboard
from flask import Flask, redirect, url_for, render_template, session, request, flash
from functools import wraps
from flask_dashed.views import get_next_or
from flask_dashed.admin import Admin
from f... | lse, cascade="all, delete-orphan"))
company = db.relationship(Company, backref=db.backref("staff"))
def __unicode__(self):
return self.user.username
user_group = db.Table(
'user_group', db.Model.metadata,
db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
db.Column('group_i... | ullable=False)
users = db.relationship("User", secondary=user_group,
backref=db.backref("groups", lazy='dynamic'))
def __unicode__(self):
return unicode(self.name)
def __repr__(self):
return '<Group %r>' % self.name
db.drop_all()
db.create_all()
group = Group(name="admins")
db_... |
flopezag/fiware-backlog | kernel/DataFactory.py | Python | apache-2.0 | 5,015 | 0.002991 | __author__ = "Manuel Escriche <mev@tid.es>"
import os, pickle, base64, requests
from datetime import datetime
from kconfig import trackersBook, trackersBookByKey
from kconfig import tComponentsBook
from kernel.Jira import JIRA
class DataEngine:
class DataObject:
def __init__(self, name, storage):
... | except Exception:
data, timestamp = self.engine.getComponentData(cmp_id)
source = 'store'
return data, timestamp, source
def getQueryData(self, name, jql):
try:
data = JIRA().getQuery(jql)
self.engine.saveQueryData(name, data)
timestamp... | return data, timestamp, source
def getTrackerNoComponentData(self, tracker_id):
jql = 'project = {} AND component = EMPTY'.format(tracker_id)
name = '{}-NoComp'.format(tracker_id)
try:
data = JIRA().getQuery(jql)
self.engine.saveQueryData(name, data)
t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.