Upload folder using huggingface_hub (part 46)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- pool/shard003/Python/0027227_pycaw.test.py +31 -0
- pool/shard003/Python/0027232_generate.py +61 -0
- pool/shard003/Python/0027236_sgf.py +61 -0
- pool/shard003/Python/0027242_test4.py +55 -0
- pool/shard003/Python/0027243_d38e04c12aa2_add_serialized_dag_table.py +93 -0
- pool/shard003/Python/0027246_chartDrawing.py +24 -0
- pool/shard003/Python/0027250_utils.py +44 -0
- pool/shard003/Python/0027253_local.py +88 -0
- pool/shard003/Python/0027254_problem035.py +22 -0
- pool/shard003/Python/0027266_test_ip_lib.py +94 -0
- pool/shard003/Python/0027273_0001_initial.py +27 -0
- pool/shard003/Python/0027275_test_exp.py +91 -0
- pool/shard003/Python/0027277_models.py +14 -0
- pool/shard003/Python/0027278_beerpoint.py +46 -0
- pool/shard003/Python/0027284_hiplicious.py +255 -0
- pool/shard003/Python/0027286_quadrat_builder.py +49 -0
- pool/shard003/Python/0027288_camshift.py +175 -0
- pool/shard003/Python/0027301_0017_auto_20160419_2041.py +24 -0
- pool/shard003/Python/0027305_wps.py +130 -0
- pool/shard003/Python/0027312_test_query_class.py +59 -0
- pool/shard003/Python/0027314_tests.py +172 -0
- pool/shard003/Python/0027315_TrayIcon.py +74 -0
- pool/shard003/Python/0027317_main.py +123 -0
- pool/shard003/Python/0027319_static_and_shared_library.py +38 -0
- pool/shard003/Python/0027331_test_output.py +29 -0
- pool/shard003/Python/0027350_desktop_ui_stories.py +110 -0
- pool/shard003/Python/0027352_settings.py +267 -0
- pool/shard003/Python/0027356_AddPost.py +51 -0
- pool/shard003/Python/0027357_locks.py +113 -0
- pool/shard003/Python/0027361_test_upgrade_pool_with_demoted_nodes.py +30 -0
- pool/shard003/Python/0027362_test_model_parallel.py +81 -0
- pool/shard003/Python/0027363_JSIterator.py +31 -0
- pool/shard003/Python/0027365_demo_print_region.py +35 -0
- pool/shard003/Python/0027380_zbx_trigger.py +234 -0
- pool/shard003/Python/0027382_dumpcsv.py +97 -0
- pool/shard003/Python/0027388_openclose_h2.test.py +156 -0
- pool/shard003/Python/0027393_fixtures.py +81 -0
- pool/shard003/Python/0027394_write_nwchem.py +37 -0
- pool/shard003/Python/0027398_eyes.py +46 -0
- pool/shard003/Python/0027400_test_real_browser.py +316 -0
- pool/shard003/Python/0027401_winscp.py +163 -0
- pool/shard003/Python/0027414_all.py +110 -0
- pool/shard003/Python/0027417_views.py +198 -0
- pool/shard003/Python/0027418_rejoin_user_event_test.py +38 -0
- pool/shard003/Python/0027423_engine.py +132 -0
- pool/shard003/Python/0027430_export.py +237 -0
- pool/shard003/Python/0027432_util.py +94 -0
- pool/shard003/Python/0027433_UserHandlers.py +216 -0
- pool/shard003/Python/0027441_test_simulations.py +15 -0
- pool/shard003/Python/0027444_documents.py +129 -0
pool/shard003/Python/0027227_pycaw.test.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
from pycaw.pycaw import AudioUtilities, ISimpleAudioVolume
|
| 4 |
+
from pydub import AudioSegment
|
| 5 |
+
from pydub.playback import play
|
| 6 |
+
|
| 7 |
+
# https://stackoverflow.com/a/43727046
|
| 8 |
+
def main():
|
| 9 |
+
song = AudioSegment.from_mp3("beep.mp3")
|
| 10 |
+
|
| 11 |
+
global sess, vol
|
| 12 |
+
|
| 13 |
+
play(song)
|
| 14 |
+
sessions = AudioUtilities.GetAllSessions()
|
| 15 |
+
for session in sessions:
|
| 16 |
+
# if session.Process:
|
| 17 |
+
# print(session.Process.name())
|
| 18 |
+
if session.Process and session.Process.name() == "python.exe":
|
| 19 |
+
sess = session
|
| 20 |
+
vol = sess._ctl.QueryInterface(ISimpleAudioVolume)
|
| 21 |
+
print("volume.GetMasterVolume(): %s" % vol.GetMasterVolume())
|
| 22 |
+
vol.SetMasterVolume(0, None)
|
| 23 |
+
|
| 24 |
+
play(song)
|
| 25 |
+
vol.SetMasterVolume(1, None)
|
| 26 |
+
play(song)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if __name__ == "__main__":
|
| 31 |
+
main()
|
pool/shard003/Python/0027232_generate.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
#
|
| 4 |
+
# Copyright (C) 2017-2020 The Project X-Ray Authors.
|
| 5 |
+
#
|
| 6 |
+
# Use of this source code is governed by a ISC-style
|
| 7 |
+
# license that can be found in the LICENSE file or at
|
| 8 |
+
# https://opensource.org/licenses/ISC
|
| 9 |
+
#
|
| 10 |
+
# SPDX-License-Identifier: ISC
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
|
| 14 |
+
from prjxray.segmaker import Segmaker
|
| 15 |
+
from prjxray import verilog
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def add_enum_bits(segmk, params, key, options):
|
| 19 |
+
for opt in options:
|
| 20 |
+
segmk.add_site_tag(
|
| 21 |
+
params['tile'], '{}_{}'.format(key, opt), params[key] == opt)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def output_integer_tags(segmk, params, key, invert=False):
|
| 25 |
+
tile = params['tile']
|
| 26 |
+
bits = verilog.parse_bitstr(params[key])
|
| 27 |
+
for bit, tag_val in enumerate(bits):
|
| 28 |
+
if not invert:
|
| 29 |
+
segmk.add_tile_tag(
|
| 30 |
+
tile, "{}[{}]".format(key,
|
| 31 |
+
len(bits) - bit - 1), tag_val)
|
| 32 |
+
else:
|
| 33 |
+
segmk.add_tile_tag(
|
| 34 |
+
tile, "Z{}[{}]".format(key,
|
| 35 |
+
len(bits) - bit - 1),
|
| 36 |
+
0 if tag_val else 1)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def main():
|
| 40 |
+
segmk = Segmaker("design.bits")
|
| 41 |
+
|
| 42 |
+
print("Loading tags")
|
| 43 |
+
with open('params.json') as f:
|
| 44 |
+
params = json.load(f)
|
| 45 |
+
|
| 46 |
+
for tile_param in params:
|
| 47 |
+
if tile_param['EN_SYN'] and tile_param['DATA_WIDTH'] == 4:
|
| 48 |
+
output_integer_tags(
|
| 49 |
+
segmk, tile_param, 'ALMOST_EMPTY_OFFSET', invert=True)
|
| 50 |
+
output_integer_tags(
|
| 51 |
+
segmk, tile_param, 'ALMOST_FULL_OFFSET', invert=True)
|
| 52 |
+
|
| 53 |
+
for param in ('EN_SYN', 'FIRST_WORD_FALL_THROUGH'):
|
| 54 |
+
segmk.add_tile_tag(tile_param['tile'], param, tile_param[param])
|
| 55 |
+
|
| 56 |
+
segmk.compile()
|
| 57 |
+
segmk.write()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
if __name__ == '__main__':
|
| 61 |
+
main()
|
pool/shard003/Python/0027236_sgf.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
pygments.lexers.sgf
|
| 4 |
+
~~~~~~~~~~~~~~~~~~~
|
| 5 |
+
|
| 6 |
+
Lexer for Smart Game Format (sgf) file format.
|
| 7 |
+
|
| 8 |
+
:copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
|
| 9 |
+
:license: BSD, see LICENSE for details.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from pygments.lexer import RegexLexer, bygroups
|
| 13 |
+
from pygments.token import Name, Literal, String, Text, Punctuation
|
| 14 |
+
|
| 15 |
+
__all__ = ["SmartGameFormatLexer"]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class SmartGameFormatLexer(RegexLexer):
|
| 19 |
+
"""
|
| 20 |
+
Lexer for Smart Game Format (sgf) file format.
|
| 21 |
+
|
| 22 |
+
The format is used to store game records of board games for two players
|
| 23 |
+
(mainly Go game).
|
| 24 |
+
For more information about the definition of the format, see:
|
| 25 |
+
https://www.red-bean.com/sgf/
|
| 26 |
+
|
| 27 |
+
.. versionadded:: 2.4
|
| 28 |
+
"""
|
| 29 |
+
name = 'SmartGameFormat'
|
| 30 |
+
aliases = ['sgf']
|
| 31 |
+
filenames = ['*.sgf']
|
| 32 |
+
|
| 33 |
+
tokens = {
|
| 34 |
+
'root': [
|
| 35 |
+
(r'[\s():;]', Punctuation),
|
| 36 |
+
# tokens:
|
| 37 |
+
(r'(A[BW]|AE|AN|AP|AR|AS|[BW]L|BM|[BW]R|[BW]S|[BW]T|CA|CH|CP|CR|'
|
| 38 |
+
r'DD|DM|DO|DT|EL|EV|EX|FF|FG|G[BW]|GC|GM|GN|HA|HO|ID|IP|IT|IY|KM|'
|
| 39 |
+
r'KO|LB|LN|LT|L|MA|MN|M|N|OB|OM|ON|OP|OT|OV|P[BW]|PC|PL|PM|RE|RG|'
|
| 40 |
+
r'RO|RU|SO|SC|SE|SI|SL|SO|SQ|ST|SU|SZ|T[BW]|TC|TE|TM|TR|UC|US|VW|'
|
| 41 |
+
r'V|[BW]|C)',
|
| 42 |
+
Name.Builtin),
|
| 43 |
+
# number:
|
| 44 |
+
(r'(\[)([0-9.]+)(\])',
|
| 45 |
+
bygroups(Punctuation, Literal.Number, Punctuation)),
|
| 46 |
+
# date:
|
| 47 |
+
(r'(\[)([0-9]{4}-[0-9]{2}-[0-9]{2})(\])',
|
| 48 |
+
bygroups(Punctuation, Literal.Date, Punctuation)),
|
| 49 |
+
# point:
|
| 50 |
+
(r'(\[)([a-z]{2})(\])',
|
| 51 |
+
bygroups(Punctuation, String, Punctuation)),
|
| 52 |
+
# double points:
|
| 53 |
+
(r'(\[)([a-z]{2})(:)([a-z]{2})(\])',
|
| 54 |
+
bygroups(Punctuation, String, Punctuation, String, Punctuation)),
|
| 55 |
+
|
| 56 |
+
(r'(\[)([\w\s#()+,\-.:?]+)(\])',
|
| 57 |
+
bygroups(Punctuation, String, Punctuation)),
|
| 58 |
+
(r'(\[)(\s.*)(\])',
|
| 59 |
+
bygroups(Punctuation, Text, Punctuation)),
|
| 60 |
+
],
|
| 61 |
+
}
|
pool/shard003/Python/0027242_test4.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#trying to build a prime number finder
|
| 2 |
+
#only designed to work on positive numbers
|
| 3 |
+
#I want users to eventually be able to input top and bottom numbers to search
|
| 4 |
+
#1 is being defined as non-prime for this
|
| 5 |
+
|
| 6 |
+
#variables
|
| 7 |
+
prime = True #assigning this variable a value to start with
|
| 8 |
+
|
| 9 |
+
aNumber = input("What's the smallest number that you'd like me to test?") #The number being tested, starts at the bottom and increments throughout the program
|
| 10 |
+
maxSize = input("what's the largest number that you'd like me to test?") #largest number to be tested
|
| 11 |
+
|
| 12 |
+
#test that entries are numbers
|
| 13 |
+
try:
|
| 14 |
+
divisor = int(aNumber)-1 #dividing by a number less than the tested number, this decriments through the program
|
| 15 |
+
except:
|
| 16 |
+
print("Python thinks you didn't enter a smaller number. Let's just call it 2.")
|
| 17 |
+
aNumber = 2
|
| 18 |
+
divisor = int(aNumber)-1
|
| 19 |
+
else:
|
| 20 |
+
aNumber = int(aNumber)
|
| 21 |
+
divisor = int(aNumber)-1
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
maxSize = int(maxSize)
|
| 25 |
+
except:
|
| 26 |
+
print("Python thinks that you didn't enter a larger number. Let's call it ",aNumber)
|
| 27 |
+
maxSize = int(aNumber)
|
| 28 |
+
else:
|
| 29 |
+
maxSize = int(maxSize)
|
| 30 |
+
|
| 31 |
+
#test the aNumber is a postive number
|
| 32 |
+
if aNumber < 1:
|
| 33 |
+
print("You entered 0 or a negative number, I'm bumping you up to 1 to start")
|
| 34 |
+
aNumber = 1
|
| 35 |
+
if maxSize < 1:
|
| 36 |
+
print("You entered 0 or a negative number, I'm bumping you up to 2 to start")
|
| 37 |
+
maxSize = 2
|
| 38 |
+
|
| 39 |
+
#quick test for starting numbers larger than ending number
|
| 40 |
+
if aNumber > maxSize:
|
| 41 |
+
print("your smallest number (",aNumber,") is larger than your largest number)",maxSize,") so I'm going to swap them")
|
| 42 |
+
foo = aNumber
|
| 43 |
+
aNumber = maxSize
|
| 44 |
+
maxSize = foo
|
| 45 |
+
|
| 46 |
+
while (aNumber <= maxSize):
|
| 47 |
+
if divisor < 1: prime = False #tests that we're not using
|
| 48 |
+
while (divisor > 1 and prime == True):
|
| 49 |
+
if aNumber % divisor == 0:prime = False
|
| 50 |
+
divisor -= 1
|
| 51 |
+
if prime == True: print ("Prime number found: ", aNumber)
|
| 52 |
+
prime = True
|
| 53 |
+
divisor = aNumber
|
| 54 |
+
aNumber +=1
|
| 55 |
+
|
pool/shard003/Python/0027243_d38e04c12aa2_add_serialized_dag_table.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 3 |
+
# or more contributor license agreements. See the NOTICE file
|
| 4 |
+
# distributed with this work for additional information
|
| 5 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 6 |
+
# to you under the Apache License, Version 2.0 (the
|
| 7 |
+
# "License"); you may not use this file except in compliance
|
| 8 |
+
# with the License. You may obtain a copy of the License at
|
| 9 |
+
#
|
| 10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 11 |
+
#
|
| 12 |
+
# Unless required by applicable law or agreed to in writing,
|
| 13 |
+
# software distributed under the License is distributed on an
|
| 14 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 15 |
+
# KIND, either express or implied. See the License for the
|
| 16 |
+
# specific language governing permissions and limitations
|
| 17 |
+
# under the License.
|
| 18 |
+
|
| 19 |
+
"""add serialized_dag table
|
| 20 |
+
|
| 21 |
+
Revision ID: d38e04c12aa2
|
| 22 |
+
Revises: 6e96a59344a4
|
| 23 |
+
Create Date: 2019-08-01 14:39:35.616417
|
| 24 |
+
|
| 25 |
+
"""
|
| 26 |
+
import sqlalchemy as sa
|
| 27 |
+
from alembic import op
|
| 28 |
+
from sqlalchemy.dialects import mysql
|
| 29 |
+
|
| 30 |
+
# revision identifiers, used by Alembic.
|
| 31 |
+
revision = 'd38e04c12aa2'
|
| 32 |
+
down_revision = '6e96a59344a4'
|
| 33 |
+
branch_labels = None
|
| 34 |
+
depends_on = None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def upgrade():
|
| 38 |
+
"""Upgrade version."""
|
| 39 |
+
json_type = sa.JSON
|
| 40 |
+
conn = op.get_bind()
|
| 41 |
+
|
| 42 |
+
if conn.dialect.name != "postgresql":
|
| 43 |
+
# Mysql 5.7+/MariaDB 10.2.3 has JSON support. Rather than checking for
|
| 44 |
+
# versions, check for the function existing.
|
| 45 |
+
try:
|
| 46 |
+
conn.execute("SELECT JSON_VALID(1)").fetchone()
|
| 47 |
+
except (sa.exc.OperationalError, sa.exc.ProgrammingError):
|
| 48 |
+
json_type = sa.Text
|
| 49 |
+
|
| 50 |
+
op.create_table(
|
| 51 |
+
'serialized_dag',
|
| 52 |
+
sa.Column('dag_id', sa.String(length=250), nullable=False),
|
| 53 |
+
sa.Column('fileloc', sa.String(length=2000), nullable=False),
|
| 54 |
+
sa.Column('fileloc_hash', sa.Integer(), nullable=False),
|
| 55 |
+
sa.Column('data', json_type(), nullable=False),
|
| 56 |
+
sa.Column('last_updated', sa.DateTime(), nullable=False),
|
| 57 |
+
sa.PrimaryKeyConstraint('dag_id'),
|
| 58 |
+
)
|
| 59 |
+
op.create_index('idx_fileloc_hash', 'serialized_dag', ['fileloc_hash'])
|
| 60 |
+
|
| 61 |
+
if conn.dialect.name == "mysql":
|
| 62 |
+
conn.execute("SET time_zone = '+00:00'")
|
| 63 |
+
cur = conn.execute("SELECT @@explicit_defaults_for_timestamp")
|
| 64 |
+
res = cur.fetchall()
|
| 65 |
+
if res[0][0] == 0:
|
| 66 |
+
raise Exception("Global variable explicit_defaults_for_timestamp needs to be on (1) for mysql")
|
| 67 |
+
|
| 68 |
+
op.alter_column(
|
| 69 |
+
table_name="serialized_dag",
|
| 70 |
+
column_name="last_updated",
|
| 71 |
+
type_=mysql.TIMESTAMP(fsp=6),
|
| 72 |
+
nullable=False,
|
| 73 |
+
)
|
| 74 |
+
else:
|
| 75 |
+
# sqlite and mssql datetime are fine as is. Therefore, not converting
|
| 76 |
+
if conn.dialect.name in ("sqlite", "mssql"):
|
| 77 |
+
return
|
| 78 |
+
|
| 79 |
+
# we try to be database agnostic, but not every db (e.g. sqlserver)
|
| 80 |
+
# supports per session time zones
|
| 81 |
+
if conn.dialect.name == "postgresql":
|
| 82 |
+
conn.execute("set timezone=UTC")
|
| 83 |
+
|
| 84 |
+
op.alter_column(
|
| 85 |
+
table_name="serialized_dag",
|
| 86 |
+
column_name="last_updated",
|
| 87 |
+
type_=sa.TIMESTAMP(timezone=True),
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def downgrade():
|
| 92 |
+
"""Downgrade version."""
|
| 93 |
+
op.drop_table('serialized_dag')
|
pool/shard003/Python/0027246_chartDrawing.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from matplotlib import pyplot as plt
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def drawWaiteForAnyCustomer(xList, yList,name):
|
| 6 |
+
fig = plt.figure()
|
| 7 |
+
width = .5
|
| 8 |
+
ind = np.arange(len(yList))
|
| 9 |
+
plt.bar(ind, yList)
|
| 10 |
+
plt.xticks(ind + width / 2, xList)
|
| 11 |
+
# fig.autofmt_xdate()
|
| 12 |
+
|
| 13 |
+
plt.savefig("results/"+name+"_waitingPerCustomer.pdf")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def drawFrequencyForAnyWaiteData(xList, yList, name):
|
| 17 |
+
fig = plt.figure()
|
| 18 |
+
width = .5
|
| 19 |
+
ind = np.arange(len(yList))
|
| 20 |
+
plt.bar(ind, yList)
|
| 21 |
+
plt.xticks(ind + width / 2, xList)
|
| 22 |
+
# fig.autofmt_xdate()
|
| 23 |
+
|
| 24 |
+
plt.savefig("results/"+name+"_FrequencyPerWaitAmount.pdf")
|
pool/shard003/Python/0027250_utils.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import namedtuple
|
| 2 |
+
import xml.etree.ElementTree as ET
|
| 3 |
+
|
| 4 |
+
OPERA_TIMESTAMP_FORMAT = "%Y%m%dT%H:%M:%S"
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def parse_receipts_xml(receipt_xml_data):
|
| 8 |
+
tree = ET.fromstring(receipt_xml_data)
|
| 9 |
+
return map(receipt_to_namedtuple, tree.findall('receipt'))
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def receipt_element_to_dict(element):
|
| 13 |
+
"""
|
| 14 |
+
Turn an ElementTree element '<data><el>1</el></data>' into {el: 1}.
|
| 15 |
+
Not recursive!
|
| 16 |
+
|
| 17 |
+
>>> data = ET.fromstring("<data><el>1</el></data>")
|
| 18 |
+
>>> receipt_element_to_dict(data)
|
| 19 |
+
{'el': '1'}
|
| 20 |
+
>>>
|
| 21 |
+
|
| 22 |
+
"""
|
| 23 |
+
return dict([(child.tag, child.text) for child in element.getchildren()])
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def receipt_to_namedtuple(element):
|
| 27 |
+
"""
|
| 28 |
+
Turn an ElementTree element into an object with named params.
|
| 29 |
+
Not recursive!
|
| 30 |
+
|
| 31 |
+
>>> data = ET.fromstring("<data><el>1</el></data>")
|
| 32 |
+
>>> receipt_to_namedtuple(data)
|
| 33 |
+
data(el='1')
|
| 34 |
+
|
| 35 |
+
"""
|
| 36 |
+
d = receipt_element_to_dict(element)
|
| 37 |
+
klass = namedtuple(element.tag, d.keys())
|
| 38 |
+
return klass._make(d.values())
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def parse_post_event_xml(post_event_xml_data):
|
| 42 |
+
tree = ET.fromstring(post_event_xml_data)
|
| 43 |
+
fields = tree.findall('field')
|
| 44 |
+
return dict([(field.attrib['name'], field.text) for field in fields])
|
pool/shard003/Python/0027253_local.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
#
|
| 4 |
+
# Copyright 2012-2015 clowwindy
|
| 5 |
+
#
|
| 6 |
+
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
| 7 |
+
# not use this file except in compliance with the License. You may obtain
|
| 8 |
+
# a copy of the License at
|
| 9 |
+
#
|
| 10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 11 |
+
#
|
| 12 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 13 |
+
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
| 14 |
+
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
| 15 |
+
# License for the specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
import sys
|
| 19 |
+
import os
|
| 20 |
+
import logging
|
| 21 |
+
import signal
|
| 22 |
+
|
| 23 |
+
from module import shell
|
| 24 |
+
from module import daemon
|
| 25 |
+
from module import eventloop
|
| 26 |
+
from module import tcprelay
|
| 27 |
+
from module import udprelay
|
| 28 |
+
from module import asyncdns
|
| 29 |
+
|
| 30 |
+
def main():
|
| 31 |
+
|
| 32 |
+
'''
|
| 33 |
+
main function
|
| 34 |
+
'''
|
| 35 |
+
|
| 36 |
+
shell.check_python()
|
| 37 |
+
|
| 38 |
+
config = shell.get_config(True)
|
| 39 |
+
|
| 40 |
+
if not config.get('dns_ipv6', False):
|
| 41 |
+
asyncdns.IPV6_CONNECTION_SUPPORT = False
|
| 42 |
+
|
| 43 |
+
daemon.daemon_exec(config)
|
| 44 |
+
|
| 45 |
+
show_str = "local start with protocol[%s] password [%s] method [%s] obfs [%s] obfs_param [%s]" % (
|
| 46 |
+
config['protocol'],
|
| 47 |
+
config['password'],
|
| 48 |
+
config['method'],
|
| 49 |
+
config['obfs'],
|
| 50 |
+
config['obfs_param']
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
logging.info(show_str)
|
| 54 |
+
|
| 55 |
+
try:
|
| 56 |
+
show_str_1 = "starting local at %s:%d" % (
|
| 57 |
+
config['local_address'],
|
| 58 |
+
config['local_port']
|
| 59 |
+
)
|
| 60 |
+
logging.info(show_str_1)
|
| 61 |
+
print(config['server'])
|
| 62 |
+
|
| 63 |
+
dns_resolver = asyncdns.DNSResolver()
|
| 64 |
+
tcp_server = tcprelay.TCPRelay(config, dns_resolver, True)
|
| 65 |
+
udp_server = udprelay.UDPRelay(config, dns_resolver, True)
|
| 66 |
+
loop = eventloop.EventLoop()
|
| 67 |
+
dns_resolver.add_to_loop(loop)
|
| 68 |
+
tcp_server.add_to_loop(loop)
|
| 69 |
+
udp_server.add_to_loop(loop)
|
| 70 |
+
|
| 71 |
+
def handler(signum, _):
|
| 72 |
+
logging.warn('received SIGQUIT, doing graceful shutting down..')
|
| 73 |
+
tcp_server.close(next_tick=True)
|
| 74 |
+
udp_server.close(next_tick=True)
|
| 75 |
+
signal.signal(getattr(signal, 'SIGQUIT', signal.SIGTERM), handler)
|
| 76 |
+
|
| 77 |
+
def int_handler(signum, _):
|
| 78 |
+
sys.exit(1)
|
| 79 |
+
signal.signal(signal.SIGINT, int_handler)
|
| 80 |
+
|
| 81 |
+
daemon.set_user(config.get('user', None))
|
| 82 |
+
loop.run()
|
| 83 |
+
except Exception as e:
|
| 84 |
+
shell.print_exception(e)
|
| 85 |
+
sys.exit(1)
|
| 86 |
+
|
| 87 |
+
if __name__ == '__main__':
|
| 88 |
+
main()
|
pool/shard003/Python/0027254_problem035.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from common import primes
|
| 2 |
+
|
| 3 |
+
def main():
|
| 4 |
+
print(len(circularPrimesBelow(1000000)))
|
| 5 |
+
|
| 6 |
+
def circularPrimesBelow(limit):
|
| 7 |
+
primeList = []
|
| 8 |
+
for i in range(limit):
|
| 9 |
+
if isCircularPrime(i):
|
| 10 |
+
primeList.append(i)
|
| 11 |
+
return primeList
|
| 12 |
+
|
| 13 |
+
def isCircularPrime(n):
|
| 14 |
+
n = str(n)
|
| 15 |
+
for _ in range(len(n)):
|
| 16 |
+
if not primes.isPrime(int(n)):
|
| 17 |
+
return False
|
| 18 |
+
n = n[1:] + n[0]
|
| 19 |
+
return True
|
| 20 |
+
|
| 21 |
+
if __name__ == "__main__":
|
| 22 |
+
main()
|
pool/shard003/Python/0027266_test_ip_lib.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2016 Cloudbase Solutions.
|
| 2 |
+
# All Rights Reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
| 5 |
+
# not use this file except in compliance with the License. You may obtain
|
| 6 |
+
# a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
| 12 |
+
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
| 13 |
+
# License for the specific language governing permissions and limitations
|
| 14 |
+
# under the License.
|
| 15 |
+
|
| 16 |
+
import mock
|
| 17 |
+
import netifaces
|
| 18 |
+
|
| 19 |
+
from neutron.agent.windows import ip_lib
|
| 20 |
+
from neutron.tests import base
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TestIpWrapper(base.BaseTestCase):
|
| 24 |
+
|
| 25 |
+
def test_get_device_by_ip_no_ip(self):
|
| 26 |
+
ret = ip_lib.IPWrapper().get_device_by_ip(None)
|
| 27 |
+
self.assertIsNone(ret)
|
| 28 |
+
|
| 29 |
+
@mock.patch.object(ip_lib.IPWrapper, 'get_devices')
|
| 30 |
+
def test_get_device_by_ip(self, mock_get_devices):
|
| 31 |
+
mock_dev1 = mock.MagicMock()
|
| 32 |
+
mock_dev2 = mock.MagicMock()
|
| 33 |
+
mock_dev1.device_has_ip.return_value = False
|
| 34 |
+
mock_dev2.device_has_ip.return_value = True
|
| 35 |
+
mock_get_devices.return_value = [mock_dev1, mock_dev2]
|
| 36 |
+
ret = ip_lib.IPWrapper().get_device_by_ip('fake_ip')
|
| 37 |
+
|
| 38 |
+
self.assertEqual(mock_dev2, ret)
|
| 39 |
+
|
| 40 |
+
@mock.patch('netifaces.interfaces')
|
| 41 |
+
def test_get_devices(self, mock_interfaces):
|
| 42 |
+
mock_interfaces.return_value = [mock.sentinel.dev1,
|
| 43 |
+
mock.sentinel.dev2]
|
| 44 |
+
|
| 45 |
+
ret = ip_lib.IPWrapper().get_devices()
|
| 46 |
+
self.assertEqual(mock.sentinel.dev1, ret[0].device_name)
|
| 47 |
+
self.assertEqual(mock.sentinel.dev2, ret[1].device_name)
|
| 48 |
+
|
| 49 |
+
@mock.patch('netifaces.interfaces')
|
| 50 |
+
def test_get_devices_error(self, mock_interfaces):
|
| 51 |
+
mock_interfaces.side_effect = OSError
|
| 52 |
+
ret = ip_lib.IPWrapper().get_devices()
|
| 53 |
+
|
| 54 |
+
self.assertEqual([], ret)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class TestIpDevice(base.BaseTestCase):
|
| 58 |
+
|
| 59 |
+
@mock.patch('netifaces.ifaddresses')
|
| 60 |
+
def test_device_has_ip(self, mock_netifaces):
|
| 61 |
+
mock_address = {'addr': mock.sentinel.fake_addr}
|
| 62 |
+
mock_netifaces.return_value = {netifaces.AF_INET: [mock_address]}
|
| 63 |
+
|
| 64 |
+
ret = ip_lib.IPDevice("fake_dev").device_has_ip(
|
| 65 |
+
mock.sentinel.fake_addr)
|
| 66 |
+
|
| 67 |
+
self.assertTrue(ret)
|
| 68 |
+
|
| 69 |
+
@mock.patch('netifaces.ifaddresses')
|
| 70 |
+
def test_device_has_ip_false(self, mock_netifaces):
|
| 71 |
+
mock_netifaces.return_value = {}
|
| 72 |
+
|
| 73 |
+
ret = ip_lib.IPDevice("fake_dev").device_has_ip(
|
| 74 |
+
mock.sentinel.fake_addr)
|
| 75 |
+
|
| 76 |
+
self.assertFalse(ret)
|
| 77 |
+
|
| 78 |
+
@mock.patch('netifaces.ifaddresses')
|
| 79 |
+
def test_device_has_ip_error(self, mock_netifaces):
|
| 80 |
+
mock_netifaces.side_effect = OSError
|
| 81 |
+
|
| 82 |
+
ret = ip_lib.IPDevice("fake_dev").device_has_ip(
|
| 83 |
+
mock.sentinel.fake_addr)
|
| 84 |
+
|
| 85 |
+
self.assertFalse(ret)
|
| 86 |
+
|
| 87 |
+
@mock.patch('netifaces.ifaddresses')
|
| 88 |
+
def test_device_not_found(self, mock_netifaces):
|
| 89 |
+
mock_netifaces.side_effect = ValueError
|
| 90 |
+
|
| 91 |
+
ret = ip_lib.IPDevice("fake_dev").device_has_ip(
|
| 92 |
+
mock.sentinel.fake_addr)
|
| 93 |
+
|
| 94 |
+
self.assertFalse(ret)
|
pool/shard003/Python/0027273_0001_initial.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Generated by Django 1.10 on 2016-08-31 18:03
|
| 3 |
+
from __future__ import unicode_literals
|
| 4 |
+
|
| 5 |
+
from django.db import migrations, models
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Migration(migrations.Migration):
|
| 9 |
+
|
| 10 |
+
initial = True
|
| 11 |
+
|
| 12 |
+
dependencies = [
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
operations = [
|
| 16 |
+
migrations.CreateModel(
|
| 17 |
+
name='Bactracking_Solutiion',
|
| 18 |
+
fields=[
|
| 19 |
+
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
| 20 |
+
('matrix_size', models.IntegerField(default=0)),
|
| 21 |
+
('solution_cost', models.FloatField(default=0.0)),
|
| 22 |
+
('coordinates', models.CharField(max_length=100000)),
|
| 23 |
+
('expanded_nodes', models.IntegerField(default=0)),
|
| 24 |
+
('excecution_time', models.FloatField(default=0.0)),
|
| 25 |
+
],
|
| 26 |
+
),
|
| 27 |
+
]
|
pool/shard003/Python/0027275_test_exp.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from rump import Request, types, and_, or_, not_
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def test_str():
|
| 5 |
+
cases = [
|
| 6 |
+
(Request.client_ip4.in_(types.IPNetwork('1/8')),
|
| 7 |
+
'client_ip4 in 1.0.0.0/8'),
|
| 8 |
+
(Request.client_ip4.in_(types.IPNetwork('1/8')) &
|
| 9 |
+
(Request.method == 'GET'),
|
| 10 |
+
'client_ip4 in 1.0.0.0/8 and method = "GET"'),
|
| 11 |
+
(Request.client_ip4.in_(types.IPNetwork('1/8')) |
|
| 12 |
+
(Request.method == 'GET'),
|
| 13 |
+
'client_ip4 in 1.0.0.0/8 or method = "GET"'),
|
| 14 |
+
(Request.client_ip4 != types.IPAddress('1.2.3.4'),
|
| 15 |
+
'client_ip4 != 1.2.3.4'),
|
| 16 |
+
(Request.path.match('/v[1234]/resources'),
|
| 17 |
+
'path ~ "/v[1234]/resources"'),
|
| 18 |
+
(~Request.path.match('/v[1234]/resources'),
|
| 19 |
+
'path !~ "/v[1234]/resources"'),
|
| 20 |
+
]
|
| 21 |
+
for case, expected in cases:
|
| 22 |
+
assert str(case) == expected
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_compile():
|
| 26 |
+
cases = [
|
| 27 |
+
Request.client_ip4.in_(types.IPNetwork('1/8')),
|
| 28 |
+
Request.client_ip4.in_(types.IPNetwork('1/8')) & (Request.method == 'GET'),
|
| 29 |
+
Request.client_ip4.in_(types.IPNetwork('1/8')) | (Request.method == 'GET'),
|
| 30 |
+
Request.client_ip4 != types.IPAddress('1.2.3.4'),
|
| 31 |
+
Request.path.match('/v[1234]/resources'),
|
| 32 |
+
Request.path.startswith('/veep/'),
|
| 33 |
+
Request.path.endswith('/'),
|
| 34 |
+
Request.path.contains('veep'),
|
| 35 |
+
Request.content_length < 100,
|
| 36 |
+
Request.content_length >= 100,
|
| 37 |
+
Request.has_content,
|
| 38 |
+
]
|
| 39 |
+
for case in cases:
|
| 40 |
+
assert case.compile(case.symbols())
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_traverse():
|
| 44 |
+
e = and_(
|
| 45 |
+
Request.client_ip4.in_(types.IPNetwork('1.2.3.4/32')),
|
| 46 |
+
Request.method == 'GET',
|
| 47 |
+
or_(
|
| 48 |
+
not_(Request.path.match('/something/.+')),
|
| 49 |
+
Request.query.contains('a'),
|
| 50 |
+
)
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
def _visit(v):
|
| 54 |
+
vs.append(v)
|
| 55 |
+
return v
|
| 56 |
+
|
| 57 |
+
vs = []
|
| 58 |
+
e.traverse(bool_op=_visit, field_op=_visit, order=e.PREFIX)
|
| 59 |
+
assert map(str, vs) == [
|
| 60 |
+
'client_ip4 in 1.2.3.4/32 and method = "GET" and path !~ "/something/.+" or a in query',
|
| 61 |
+
'client_ip4 in 1.2.3.4/32 and method = "GET"',
|
| 62 |
+
'client_ip4 in 1.2.3.4/32',
|
| 63 |
+
'method = "GET"',
|
| 64 |
+
'path !~ "/something/.+" or a in query',
|
| 65 |
+
'path !~ "/something/.+"',
|
| 66 |
+
'a in query',
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
vs = []
|
| 70 |
+
e.traverse(bool_op=_visit, field_op=_visit, order=e.INFIX)
|
| 71 |
+
assert map(str, vs) == [
|
| 72 |
+
'client_ip4 in 1.2.3.4/32',
|
| 73 |
+
'client_ip4 in 1.2.3.4/32 and method = "GET"',
|
| 74 |
+
'method = "GET"',
|
| 75 |
+
'client_ip4 in 1.2.3.4/32 and method = "GET" and path !~ "/something/.+" or a in query',
|
| 76 |
+
'path !~ "/something/.+"',
|
| 77 |
+
'path !~ "/something/.+" or a in query',
|
| 78 |
+
'a in query',
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
+
vs = []
|
| 82 |
+
e.traverse(bool_op=_visit, field_op=_visit, order=e.POSTFIX)
|
| 83 |
+
assert map(str, vs) == [
|
| 84 |
+
'client_ip4 in 1.2.3.4/32',
|
| 85 |
+
'method = "GET"',
|
| 86 |
+
'client_ip4 in 1.2.3.4/32 and method = "GET"',
|
| 87 |
+
'path !~ "/something/.+"',
|
| 88 |
+
'a in query',
|
| 89 |
+
'path !~ "/something/.+" or a in query',
|
| 90 |
+
'client_ip4 in 1.2.3.4/32 and method = "GET" and path !~ "/something/.+" or a in query'
|
| 91 |
+
]
|
pool/shard003/Python/0027277_models.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from django.db import models
|
| 2 |
+
|
| 3 |
+
class Url(models.Model):
|
| 4 |
+
'''Hostname and urls'''
|
| 5 |
+
title = models.CharField( max_length=100, )
|
| 6 |
+
ip = models.CharField( max_length=100, )
|
| 7 |
+
urls = models.CharField( max_length=500, )
|
| 8 |
+
slug = models.SlugField()
|
| 9 |
+
|
| 10 |
+
def __unicode__(self):
|
| 11 |
+
return u'%s' % self.title
|
| 12 |
+
|
| 13 |
+
# class Meta:
|
| 14 |
+
# ordering = ['slug']
|
pool/shard003/Python/0027278_beerpoint.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
import re
|
| 3 |
+
from BeautifulSoup import BeautifulSoup
|
| 4 |
+
|
| 5 |
+
@given('Beer point')
|
| 6 |
+
@when('Looking at home page')
|
| 7 |
+
def step(context):
|
| 8 |
+
context.browser.go(context.baseurl)
|
| 9 |
+
context.page = context.browser.get_html().decode('utf-8')
|
| 10 |
+
assert context.page
|
| 11 |
+
|
| 12 |
+
@then('We see beer point name')
|
| 13 |
+
def step(context):
|
| 14 |
+
assert re.search('beer point name: \w+', context.page)
|
| 15 |
+
|
| 16 |
+
@then('We see "{text}" in title')
|
| 17 |
+
def step(context, text):
|
| 18 |
+
assert text in context.browser.get_title()
|
| 19 |
+
|
| 20 |
+
@then('We see beer styles')
|
| 21 |
+
def step(context):
|
| 22 |
+
for row in context.table:
|
| 23 |
+
assert row['type'] in context.page
|
| 24 |
+
|
| 25 |
+
@when('Number of pints for a beer is {text} 0')
|
| 26 |
+
def step(context, text):
|
| 27 |
+
# base on text pattern
|
| 28 |
+
if text == 'equal': pattern = 'pints=0'
|
| 29 |
+
if text == 'greater than': pattern = 'pints=[1-9]'
|
| 30 |
+
# find all beers descriptions
|
| 31 |
+
beerslist = BeautifulSoup(context.page).findAll('li')
|
| 32 |
+
context.beerslist = []
|
| 33 |
+
for beer_d in beerslist:
|
| 34 |
+
# beers descriptions maching pattern add to context.beerslist
|
| 35 |
+
if re.search(pattern ,beer_d.text):
|
| 36 |
+
context.beerslist.append(str(beer_d))
|
| 37 |
+
# check that pattern exist in page and we have good example to test
|
| 38 |
+
assert re.search(pattern,context.page)
|
| 39 |
+
|
| 40 |
+
@then('The Beer description is {text}')
|
| 41 |
+
def step(context, text):
|
| 42 |
+
for beer_d in context.beerslist:
|
| 43 |
+
if text == 'red':
|
| 44 |
+
assert re.search('color=["\']red["\']', beer_d)
|
| 45 |
+
if text == 'not red':
|
| 46 |
+
assert not re.search('color=["\']red["\']', beer_d)
|
pool/shard003/Python/0027284_hiplicious.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import base64
|
| 6 |
+
import datetime
|
| 7 |
+
import json
|
| 8 |
+
import re
|
| 9 |
+
import urllib
|
| 10 |
+
import urllib2
|
| 11 |
+
|
| 12 |
+
config = {
|
| 13 |
+
'DELICIOUS_USERNAME': '-------',
|
| 14 |
+
'DELICIOUS_PASSWORD': '-------',
|
| 15 |
+
'DELICIOUS_BASE_URI': 'https://api.delicious.com/v1',
|
| 16 |
+
'DELICIOUS_SHARED': 'no',
|
| 17 |
+
'HIPCHAT_TOKEN': '-------',
|
| 18 |
+
'HIPCHAT_ROOM': '-------',
|
| 19 |
+
'HIPCHAT_BASE_URI': 'https://api.hipchat.com/v1',
|
| 20 |
+
'HIPCHAT_INCLUDE_FILES': False,
|
| 21 |
+
'LOG_FILE': 'hiplicious.log'
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
# Set up and parse command line argments
|
| 25 |
+
parser = argparse.ArgumentParser(description='Import links from a HipChat room\
|
| 26 |
+
to Delicious.com')
|
| 27 |
+
parser.add_argument('-a', '--all',
|
| 28 |
+
action='store_true',
|
| 29 |
+
help='Import the entire history')
|
| 30 |
+
parser.add_argument('-c', '--continuous',
|
| 31 |
+
action='store_true',
|
| 32 |
+
help='Continue from the specified date until today')
|
| 33 |
+
parser.add_argument('-d', '--date',
|
| 34 |
+
help='Specify a date (YYYY-MM-DD format) to import')
|
| 35 |
+
args = parser.parse_args()
|
| 36 |
+
|
| 37 |
+
def build_url(provider, endpoint, **kwargs):
|
| 38 |
+
"""Builds a request URL
|
| 39 |
+
|
| 40 |
+
:param provider: either 'hipchat' or 'delicious'
|
| 41 |
+
:param endpoint: the API endpoint
|
| 42 |
+
:param **kwargs: optional URL parameters
|
| 43 |
+
"""
|
| 44 |
+
if provider == 'hipchat':
|
| 45 |
+
base = config.get('HIPCHAT_BASE_URI')
|
| 46 |
+
elif provider == 'delicious':
|
| 47 |
+
base = config.get('DELICIOUS_BASE_URI')
|
| 48 |
+
|
| 49 |
+
# Keep urlencode from choking on unicode data
|
| 50 |
+
# http://stackoverflow.com/a/3121311
|
| 51 |
+
string_kwargs = {}
|
| 52 |
+
for k, v in kwargs.iteritems():
|
| 53 |
+
string_kwargs[k] = unicode(v).encode('utf-8')
|
| 54 |
+
|
| 55 |
+
return ''.join([base, endpoint, '?', urllib.urlencode(string_kwargs)])
|
| 56 |
+
|
| 57 |
+
def make_request(url, auth=None, json_format=True):
|
| 58 |
+
"""
|
| 59 |
+
Makes a request using urllib2 and returns the response in the requested
|
| 60 |
+
format.
|
| 61 |
+
|
| 62 |
+
:param url: the url to send a request to
|
| 63 |
+
:param auth: (optional) List containing a username and password
|
| 64 |
+
:param json_format: (optional) whether to load the response as json and
|
| 65 |
+
return a Dict. Defaults to True.
|
| 66 |
+
"""
|
| 67 |
+
request = urllib2.Request(url)
|
| 68 |
+
|
| 69 |
+
if auth and len(auth) == 2:
|
| 70 |
+
base64string = base64.encodestring(':'.join(auth)).replace('\n', '')
|
| 71 |
+
request.add_header("Authorization", "Basic %s" % base64string)
|
| 72 |
+
|
| 73 |
+
try:
|
| 74 |
+
response = urllib2.urlopen(request)
|
| 75 |
+
except urllib2.URLError as e:
|
| 76 |
+
print e.reason
|
| 77 |
+
|
| 78 |
+
data = response.read()
|
| 79 |
+
|
| 80 |
+
if json_format:
|
| 81 |
+
return json.loads(data)
|
| 82 |
+
else:
|
| 83 |
+
return data
|
| 84 |
+
|
| 85 |
+
def hipchat_get_creation_date():
|
| 86 |
+
"""
|
| 87 |
+
Returns the creation date of config['HIPCHAT_ROOM'] in YYYY-MM-DD format
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
endpoint = '/rooms/show'
|
| 91 |
+
options = {
|
| 92 |
+
'room_id': config.get('HIPCHAT_ROOM'),
|
| 93 |
+
'format': json,
|
| 94 |
+
'auth_token': config.get('HIPCHAT_TOKEN')
|
| 95 |
+
}
|
| 96 |
+
request_url = build_url('hipchat', endpoint, **options)
|
| 97 |
+
response = make_request(request_url)
|
| 98 |
+
|
| 99 |
+
date = datetime.datetime.fromtimestamp(int(response['room']['created']))
|
| 100 |
+
return date.strftime("%Y-%m-%d")
|
| 101 |
+
|
| 102 |
+
def hipchat_get_log(date):
|
| 103 |
+
"""
|
| 104 |
+
Given a date, returns Hipchat log for that date
|
| 105 |
+
|
| 106 |
+
:param date: date in YYYY-MM-DD format
|
| 107 |
+
"""
|
| 108 |
+
print 'Retrieving log for ', date
|
| 109 |
+
|
| 110 |
+
endpoint = '/rooms/history'
|
| 111 |
+
options = {
|
| 112 |
+
'room_id': config.get('HIPCHAT_ROOM'),
|
| 113 |
+
'date': date,
|
| 114 |
+
'format': json,
|
| 115 |
+
'auth_token': config.get('HIPCHAT_TOKEN')
|
| 116 |
+
}
|
| 117 |
+
request_url = build_url('hipchat', endpoint, **options)
|
| 118 |
+
response = make_request(request_url)
|
| 119 |
+
|
| 120 |
+
print 'Log retrieved'
|
| 121 |
+
return response
|
| 122 |
+
|
| 123 |
+
def get_urls_from_log(log, include_files=config.get('HIPCHAT_INCLUDE_FILES',
|
| 124 |
+
False)):
|
| 125 |
+
"""
|
| 126 |
+
Given a dict containing a list of Hipchat messages, extracts URLs and builds
|
| 127 |
+
bookmark dicts
|
| 128 |
+
|
| 129 |
+
:param log: Dict containing a Hipchat history
|
| 130 |
+
:param include_files: (optional) whether to include file attachment URLs or
|
| 131 |
+
just in-message URLs. Defaults to False.
|
| 132 |
+
"""
|
| 133 |
+
print 'Extracting URLs'
|
| 134 |
+
regexp = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F]'\
|
| 135 |
+
'[0-9a-fA-F]))+'
|
| 136 |
+
bookmarks = []
|
| 137 |
+
|
| 138 |
+
for item in log['messages']:
|
| 139 |
+
urls = re.findall(regexp, item['message'])
|
| 140 |
+
if urls:
|
| 141 |
+
for url in urls:
|
| 142 |
+
# Remove the URL from the comment itself
|
| 143 |
+
pattern = re.escape(url)
|
| 144 |
+
placeholder = '[link]'
|
| 145 |
+
comment = re.sub(pattern, placeholder, item['message'])
|
| 146 |
+
|
| 147 |
+
# Remove characters that choke Delicious's API. Couldn't figure
|
| 148 |
+
# out how to combine these...
|
| 149 |
+
comment = re.sub(u'\u2026', ' ', comment)
|
| 150 |
+
comment = re.sub('[<>]', ' ', comment)
|
| 151 |
+
|
| 152 |
+
if comment.strip() == placeholder:
|
| 153 |
+
comment = ''
|
| 154 |
+
bookmark = {
|
| 155 |
+
'url': url,
|
| 156 |
+
'comment': comment,
|
| 157 |
+
'dt': item['date'],
|
| 158 |
+
'tags': ','.join([item['from']['name'],
|
| 159 |
+
get_tags_from_message(item['message'])])
|
| 160 |
+
}
|
| 161 |
+
bookmarks.append(bookmark)
|
| 162 |
+
if include_files:
|
| 163 |
+
if item.get('file'):
|
| 164 |
+
bookmark = {
|
| 165 |
+
'url': item['file']['url'],
|
| 166 |
+
'comment': comment,
|
| 167 |
+
'dt': item['date'],
|
| 168 |
+
'tags': ','.join([item['from']['name'], 'file',
|
| 169 |
+
get_tags_from_message(item['message'])])
|
| 170 |
+
}
|
| 171 |
+
bookmarks.append(bookmark)
|
| 172 |
+
print len(bookmarks), ' bookmarks found'
|
| 173 |
+
return bookmarks
|
| 174 |
+
|
| 175 |
+
def get_tags_from_message(message):
|
| 176 |
+
"""
|
| 177 |
+
Given a message string, extracts hashtags and returns a comma-separated list
|
| 178 |
+
|
| 179 |
+
:param message: a Hipchat message body
|
| 180 |
+
"""
|
| 181 |
+
tags = {word.strip('#') for word in message.split() if word.startswith('#')}
|
| 182 |
+
return ','.join(tags)
|
| 183 |
+
|
| 184 |
+
def format_date_string(datestring):
|
| 185 |
+
"""
|
| 186 |
+
Given a Hipchat-style date string, reformat to Delicious-style date string,
|
| 187 |
+
e.g. 2013-08-06T19:46:49+0000 to 2013-08-06T19:46:49Z
|
| 188 |
+
|
| 189 |
+
:param datestring: the Hipchat date string
|
| 190 |
+
"""
|
| 191 |
+
return re.sub('\+(.)*$', 'Z', datestring)
|
| 192 |
+
|
| 193 |
+
def delicious_add_bookmarks(bookmarks):
|
| 194 |
+
print 'Adding bookmarks to delicious.com'
|
| 195 |
+
|
| 196 |
+
endpoint = '/posts/add'
|
| 197 |
+
|
| 198 |
+
for bookmark in bookmarks:
|
| 199 |
+
#print bookmark.get('comment')
|
| 200 |
+
options = {
|
| 201 |
+
'url': bookmark.get('url'),
|
| 202 |
+
'description': bookmark.get('url'),
|
| 203 |
+
'extended': bookmark.get('comment'),
|
| 204 |
+
'tags': bookmark.get('tags'),
|
| 205 |
+
'dt': format_date_string(bookmark.get('dt')),
|
| 206 |
+
'shared': config.get('DELICIOUS_SHARED')
|
| 207 |
+
}
|
| 208 |
+
request_url = build_url('delicious', endpoint, **options)
|
| 209 |
+
creds = [config.get('DELICIOUS_USERNAME'),
|
| 210 |
+
config.get('DELICIOUS_PASSWORD')]
|
| 211 |
+
response = make_request(request_url, auth=creds, json_format=False)
|
| 212 |
+
|
| 213 |
+
if 'done' in response:
|
| 214 |
+
print ' '.join(['Added', bookmark.get('url')])
|
| 215 |
+
else:
|
| 216 |
+
print ' '.join(['Could not add', bookmark.get('url')])
|
| 217 |
+
with open(config.get('LOG_FILE'), 'a') as logfile:
|
| 218 |
+
logfile.write('\n' + bookmark.get('url'))
|
| 219 |
+
|
| 220 |
+
def make_my_hipchat_delicious(start, continuous=False):
|
| 221 |
+
"""Iterates over dates and runs the import/export
|
| 222 |
+
|
| 223 |
+
:param start: String of a start date in YYYY-MM-DD format.
|
| 224 |
+
:param continuous: (optional) whether to proceed from the start date until
|
| 225 |
+
today. Defaults to False.
|
| 226 |
+
"""
|
| 227 |
+
|
| 228 |
+
if continuous:
|
| 229 |
+
date = datetime.datetime.strptime(start, '%Y-%m-%d').date()
|
| 230 |
+
while date <= datetime.date.today():
|
| 231 |
+
run_import(date.strftime('%Y-%m-%d'))
|
| 232 |
+
date += datetime.timedelta(days=1)
|
| 233 |
+
else:
|
| 234 |
+
run_import(start)
|
| 235 |
+
|
| 236 |
+
def run_import(date):
|
| 237 |
+
"""Runs the import steps
|
| 238 |
+
|
| 239 |
+
:param date: Date in YYYY-MM-DD format
|
| 240 |
+
"""
|
| 241 |
+
log = hipchat_get_log(date)
|
| 242 |
+
bookmarks = get_urls_from_log(log)
|
| 243 |
+
delicious_add_bookmarks(bookmarks)
|
| 244 |
+
|
| 245 |
+
if __name__ == '__main__':
|
| 246 |
+
if args.date:
|
| 247 |
+
desired_date = args.date
|
| 248 |
+
elif args.all:
|
| 249 |
+
desired_date = hipchat_get_creation_date()
|
| 250 |
+
else:
|
| 251 |
+
desired_date = datetime.date.today().strftime('%Y-%m-%d')
|
| 252 |
+
|
| 253 |
+
continuous = args.continuous
|
| 254 |
+
|
| 255 |
+
make_my_hipchat_delicious(desired_date, continuous)
|
pool/shard003/Python/0027286_quadrat_builder.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .vertex import Vertex
|
| 2 |
+
from .quadrat import Quadrat
|
| 3 |
+
from .helpers import get_midpoint_of_edge
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class QuadratBuilder(object):
|
| 7 |
+
"""A class that builds quadrats on a mesh, starting from the centre position."""
|
| 8 |
+
|
| 9 |
+
def build(self, box, size):
|
| 10 |
+
"""
|
| 11 |
+
Method to contruct a list of quadrats using a given bounding box.
|
| 12 |
+
@param box the bounding box of the meshes to measure
|
| 13 |
+
@param size the size of the square quadrilateral (in the units of the provided mesh)
|
| 14 |
+
@return list of the quadrats that fit the bounding box
|
| 15 |
+
"""
|
| 16 |
+
centroid = box.centroid
|
| 17 |
+
edge1_midpoint = get_midpoint_of_edge(
|
| 18 |
+
box.vertices[0], box.vertices[1])
|
| 19 |
+
distance_to_edge1 = centroid.distance_to_xyz(edge1_midpoint)
|
| 20 |
+
quadrat_indexes1 = range(int(distance_to_edge1 / size) + 1)
|
| 21 |
+
|
| 22 |
+
edge2_midpoint = get_midpoint_of_edge(
|
| 23 |
+
box.vertices[0], box.vertices[3])
|
| 24 |
+
distance_to_edge2 = centroid.distance_to_xyz(edge2_midpoint)
|
| 25 |
+
quadrat_indexes2 = range(int(distance_to_edge2 / size) + 1)
|
| 26 |
+
|
| 27 |
+
quadrats = list()
|
| 28 |
+
for i in quadrat_indexes2:
|
| 29 |
+
for j in quadrat_indexes1:
|
| 30 |
+
if i == 0 and j == 0:
|
| 31 |
+
quadrats.append(Quadrat((0, 0), size, centroid))
|
| 32 |
+
else:
|
| 33 |
+
top_right = Vertex(centroid.x + i * size,
|
| 34 |
+
centroid.y + (j * size), centroid.z)
|
| 35 |
+
top_left = Vertex(centroid.x + i * size,
|
| 36 |
+
centroid.y - (j * size), centroid.z)
|
| 37 |
+
bottom_right = Vertex(
|
| 38 |
+
centroid.x - i * size, centroid.y + (j * size), centroid.z)
|
| 39 |
+
bottom_left = Vertex(
|
| 40 |
+
centroid.x - i * size, centroid.y - (j * size), centroid.z)
|
| 41 |
+
four_quadrats = [Quadrat((i, j), size, top_right),
|
| 42 |
+
Quadrat((i, -1 * j), size, top_left),
|
| 43 |
+
Quadrat((-1 * i, j), size, bottom_right),
|
| 44 |
+
Quadrat((-1 * i, -1 * j), size, bottom_left)]
|
| 45 |
+
quadrats_inside = list(
|
| 46 |
+
filter(lambda x: box.contains(x.midpoint), four_quadrats))
|
| 47 |
+
quadrats += quadrats_inside
|
| 48 |
+
# print("There are this many quadrats: " + str(len(quadrats)))
|
| 49 |
+
return tuple(set(quadrats))
|
pool/shard003/Python/0027288_camshift.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
|
| 3 |
+
'''
|
| 4 |
+
Camshift tracker
|
| 5 |
+
================
|
| 6 |
+
This is a demo that shows mean-shift based tracking
|
| 7 |
+
You select a color objects such as your face and it tracks it.
|
| 8 |
+
This reads from video camera (0 by default, or the camera number the user enters)
|
| 9 |
+
http://www.robinhewitt.com/research/track/camshift.html
|
| 10 |
+
Usage:
|
| 11 |
+
------
|
| 12 |
+
camshift.py [<video source>]
|
| 13 |
+
To initialize tracking, select the object with mouse
|
| 14 |
+
Keys:
|
| 15 |
+
-----
|
| 16 |
+
ESC,q - exit
|
| 17 |
+
b - toggle back-projected probability visualization
|
| 18 |
+
h - toggle histogram visualization
|
| 19 |
+
'''
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import cv2
|
| 23 |
+
|
| 24 |
+
# local module
|
| 25 |
+
import rospy
|
| 26 |
+
from sensor_msgs.msg import RegionOfInterest, Image
|
| 27 |
+
from cv_bridge import CvBridge
|
| 28 |
+
|
| 29 |
+
def is_rect_nonzero(r):
|
| 30 |
+
(_,_,w,h) = r
|
| 31 |
+
return (w > 0) and (h > 0)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class App(object):
|
| 35 |
+
def __init__(self, video_src):
|
| 36 |
+
self.frame = np.zeros((320,240,3), np.uint8)
|
| 37 |
+
self.hist = np.zeros((320,240,3), np.uint8)
|
| 38 |
+
self.backproject = np.zeros((320,240,3), np.uint8)
|
| 39 |
+
self.br = CvBridge()
|
| 40 |
+
self.pause = False
|
| 41 |
+
cv2.namedWindow('camshift')
|
| 42 |
+
# cv2.namedWindow('hist')
|
| 43 |
+
cv2.setMouseCallback('camshift', self.onmouse)
|
| 44 |
+
|
| 45 |
+
self.selection = None
|
| 46 |
+
self.drag_start = None
|
| 47 |
+
self.tracking_state = 0
|
| 48 |
+
self.show_backproj = False
|
| 49 |
+
|
| 50 |
+
def onmouse(self, event, x, y, flags, param):
|
| 51 |
+
down = [cv2.EVENT_LBUTTONDOWN,cv2.EVENT_MBUTTONDOWN,cv2.EVENT_RBUTTONDOWN]
|
| 52 |
+
up = [cv2.EVENT_LBUTTONUP,cv2.EVENT_MBUTTONUP,cv2.EVENT_RBUTTONUP]
|
| 53 |
+
flagb = cv2.EVENT_FLAG_LBUTTON | cv2.EVENT_FLAG_MBUTTON | cv2.EVENT_FLAG_RBUTTON;
|
| 54 |
+
x, y = np.int16([x, y]) # BUG
|
| 55 |
+
if event in down:
|
| 56 |
+
self.drag_start = (x, y)
|
| 57 |
+
self.tracking_state = 0
|
| 58 |
+
rospy.loginfo("L/R button down")
|
| 59 |
+
if event in up:
|
| 60 |
+
rospy.loginfo("L/R button up")
|
| 61 |
+
self.drag_start = None
|
| 62 |
+
if self.selection is not None:
|
| 63 |
+
rospy.loginfo("Completed " + str(self.selection))
|
| 64 |
+
self.tracking_state = 1
|
| 65 |
+
if self.drag_start is not None:
|
| 66 |
+
# rospy.loginfo("Dragging %04X / %04X",flags,flagb)
|
| 67 |
+
h, w = self.frame.shape[:2]
|
| 68 |
+
xo, yo = self.drag_start
|
| 69 |
+
x0, y0 = np.maximum(0, np.minimum([xo, yo], [x, y]))
|
| 70 |
+
x1, y1 = np.minimum([w, h], np.maximum([xo, yo], [x, y]))
|
| 71 |
+
self.selection = None
|
| 72 |
+
if x1-x0 > 0 and y1-y0 > 0:
|
| 73 |
+
self.selection = (x0, y0, x1, y1)
|
| 74 |
+
# rospy.loginfo("Dragging " + str(self.selection))
|
| 75 |
+
|
| 76 |
+
def hue_histogram_as_image(self,hist):
|
| 77 |
+
bin_count = hist.shape[0]
|
| 78 |
+
bin_w = 24
|
| 79 |
+
img = np.zeros((256, bin_count*bin_w, 3), np.uint8)
|
| 80 |
+
for i in xrange(bin_count):
|
| 81 |
+
h = int(hist[i])
|
| 82 |
+
cv2.rectangle(img, (i*bin_w+2, 255), ((i+1)*bin_w-2, 255-h), (int(180.0*i/bin_count), 255, 255), -1)
|
| 83 |
+
img = cv2.cvtColor(img, cv2.COLOR_HSV2BGR)
|
| 84 |
+
return img
|
| 85 |
+
|
| 86 |
+
def detect_and_draw(self,imgmsg):
|
| 87 |
+
if self.pause:
|
| 88 |
+
return
|
| 89 |
+
frame = self.br.imgmsg_to_cv2(imgmsg, "bgr8")
|
| 90 |
+
self.frame = frame.copy()
|
| 91 |
+
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
|
| 92 |
+
mask = cv2.inRange(hsv, np.array((0., 60., 32.)), np.array((180., 255., 255.)))
|
| 93 |
+
|
| 94 |
+
# rospy.loginfo("Selection %s / TS : %d" % (str(self.selection),self.tracking_state))
|
| 95 |
+
|
| 96 |
+
if self.selection:
|
| 97 |
+
x0, y0, x1, y1 = self.selection
|
| 98 |
+
#print(self.selection)
|
| 99 |
+
self.track_window = (x0, y0, x1-x0, y1-y0)
|
| 100 |
+
hsv_roi = hsv[y0:y1, x0:x1]
|
| 101 |
+
mask_roi = mask[y0:y1, x0:x1]
|
| 102 |
+
hist = cv2.calcHist( [hsv_roi], [0], mask_roi, [16], [0, 180] )
|
| 103 |
+
cv2.normalize(hist, hist, 0, 255, cv2.NORM_MINMAX);
|
| 104 |
+
self.hist = hist.reshape(-1)
|
| 105 |
+
|
| 106 |
+
vis_roi = self.frame[y0:y1, x0:x1]
|
| 107 |
+
cv2.bitwise_not(vis_roi, vis_roi)
|
| 108 |
+
self.frame[mask == 0] = 0
|
| 109 |
+
|
| 110 |
+
if self.tracking_state == 1 and is_rect_nonzero(self.track_window):
|
| 111 |
+
self.selection = None
|
| 112 |
+
prob = cv2.calcBackProject([hsv], [0], self.hist, [0, 180], 1)
|
| 113 |
+
prob &= mask
|
| 114 |
+
term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )
|
| 115 |
+
track_box, self.track_window = cv2.CamShift(prob, self.track_window, term_crit)
|
| 116 |
+
print prob.shape
|
| 117 |
+
self.backproject = prob[...,np.newaxis].copy()
|
| 118 |
+
|
| 119 |
+
if self.show_backproj:
|
| 120 |
+
self.frame = self.backproject.copy()
|
| 121 |
+
try:
|
| 122 |
+
cv2.ellipse(self.frame, track_box, (0, 0, 255), 2)
|
| 123 |
+
except:
|
| 124 |
+
print track_box
|
| 125 |
+
x,y,w,h = self.track_window
|
| 126 |
+
self.bbpub.publish(RegionOfInterest(x,y, w,h,False))
|
| 127 |
+
proba_msg = self.br.cv2_to_imgmsg(self.backproject,"mono8")
|
| 128 |
+
proba_msg.header = imgmsg.header
|
| 129 |
+
self.bppub.publish(proba_msg)
|
| 130 |
+
|
| 131 |
+
if not self.pause:
|
| 132 |
+
if not self.backproject_mode:
|
| 133 |
+
cv2.imshow( "camshift", self.frame )
|
| 134 |
+
else:
|
| 135 |
+
cv2.imshow( "camshift", self.backproject)
|
| 136 |
+
if self.disp_hist:
|
| 137 |
+
cv2.imshow( "Histogram", self.hue_histogram_as_image(self.hist))
|
| 138 |
+
|
| 139 |
+
def run(self):
|
| 140 |
+
self.backproject_mode = False
|
| 141 |
+
rospy.init_node('blob_tracker')
|
| 142 |
+
image_topic = rospy.resolve_name("image")
|
| 143 |
+
self.bbpub = rospy.Publisher("~blob",RegionOfInterest,queue_size=1)
|
| 144 |
+
self.bppub = rospy.Publisher("~backproject",Image,queue_size=1)
|
| 145 |
+
self.disp_hist = rospy.get_param("~display_histogram",False)
|
| 146 |
+
rospy.Subscriber(image_topic, Image, self.detect_and_draw)
|
| 147 |
+
rate = rospy.Rate(5)
|
| 148 |
+
while not rospy.is_shutdown():
|
| 149 |
+
# rospy.spin_once()
|
| 150 |
+
c = cv2.waitKey(7) & 0x0FF
|
| 151 |
+
if c == 27 or c == ord("q"):
|
| 152 |
+
rospy.signal_shutdown("OpenCV said so")
|
| 153 |
+
elif c == ord("p"):
|
| 154 |
+
self.pause = not self.pause
|
| 155 |
+
elif c == ord("h"):
|
| 156 |
+
self.disp_hist = not self.disp_hist
|
| 157 |
+
if not self.disp_hist:
|
| 158 |
+
cv2.destroyWindow("Histogram")
|
| 159 |
+
elif c == ord("b"):
|
| 160 |
+
self.backproject_mode = not self.backproject_mode
|
| 161 |
+
cv2.destroyAllWindows()
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
if __name__ == '__main__':
|
| 165 |
+
import sys
|
| 166 |
+
try:
|
| 167 |
+
video_src = sys.argv[1]
|
| 168 |
+
except:
|
| 169 |
+
video_src = 0
|
| 170 |
+
print __doc__
|
| 171 |
+
App(video_src).run()
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
|
pool/shard003/Python/0027301_0017_auto_20160419_2041.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
from __future__ import unicode_literals
|
| 3 |
+
|
| 4 |
+
from django.db import migrations, models
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Migration(migrations.Migration):
|
| 8 |
+
|
| 9 |
+
dependencies = [
|
| 10 |
+
('content', '0016_auto_20151023_1159'),
|
| 11 |
+
]
|
| 12 |
+
|
| 13 |
+
operations = [
|
| 14 |
+
migrations.AlterField(
|
| 15 |
+
model_name='event',
|
| 16 |
+
name='event_description',
|
| 17 |
+
field=models.TextField(null=True, blank=True, verbose_name='Details'),
|
| 18 |
+
),
|
| 19 |
+
migrations.AlterField(
|
| 20 |
+
model_name='message',
|
| 21 |
+
name='msg_author',
|
| 22 |
+
field=models.EmailField(editable=False, max_length=254, verbose_name='From'),
|
| 23 |
+
),
|
| 24 |
+
]
|
pool/shard003/Python/0027305_wps.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
#-*- coding: utf-8 -*-
|
| 3 |
+
"""
|
| 4 |
+
This program is simple implementation of OGC's [http://opengeospatial.org]
|
| 5 |
+
Web Processing Service (OpenGIS(r) Web Processing Service - OGC 05-007r7)
|
| 6 |
+
version 1.0.0 from 2007-06-08
|
| 7 |
+
|
| 8 |
+
Target of this application is to bring functionality of GIS GRASS
|
| 9 |
+
[http://grass.osgeo.it] to the World Wide Web - it should work like
|
| 10 |
+
wrapper for modules of this GIS. Though GRASS was at the first place in the
|
| 11 |
+
focus, it is not necessary to use it's modules - you can use any program
|
| 12 |
+
you can script in Python or other language.
|
| 13 |
+
|
| 14 |
+
This first version was written with support of Deutsche Bundesstiftung
|
| 15 |
+
Umwelt, Osnabrueck, Germany on the spring 2006. SVN server was hosted by
|
| 16 |
+
GDF-Hannover, Hannover, Germany; today at Intevation GmbH, Germany.
|
| 17 |
+
|
| 18 |
+
Current development is supported mainly by:
|
| 19 |
+
Help Service - Remote Sensing s.r.o
|
| 20 |
+
Cernoleska 1600
|
| 21 |
+
256 01 - Benesov u Prahy
|
| 22 |
+
Czech Republic
|
| 23 |
+
Europe
|
| 24 |
+
|
| 25 |
+
For setting see comments in 'etc' directory and documentation.
|
| 26 |
+
|
| 27 |
+
This program is free software, distributed under the terms of GNU General
|
| 28 |
+
Public License as published by the Free Software Foundation version 2 of the
|
| 29 |
+
License.
|
| 30 |
+
|
| 31 |
+
Enjoy and happy GISing!
|
| 32 |
+
"""
|
| 33 |
+
__version__ = "3.2.2"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# Author: Jachym Cepicky
|
| 37 |
+
# http://les-ejk.cz
|
| 38 |
+
# License:
|
| 39 |
+
#
|
| 40 |
+
# Web Processing Service implementation
|
| 41 |
+
# Copyright (C) 2006 Jachym Cepicky
|
| 42 |
+
#
|
| 43 |
+
# This program is free software; you can redistribute it and/or modify
|
| 44 |
+
# it under the terms of the GNU General Public License as published by
|
| 45 |
+
# the Free Software Foundation; either version 2 of the License.
|
| 46 |
+
#
|
| 47 |
+
# This program is distributed in the hope that it will be useful,
|
| 48 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 49 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 50 |
+
# GNU General Public License for more details.
|
| 51 |
+
#
|
| 52 |
+
# You should have received a copy of the GNU General Public License
|
| 53 |
+
# along with this program; if not, write to the Free Software
|
| 54 |
+
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
| 55 |
+
# 02110-1301 USA
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# first qgis
|
| 59 |
+
from qgis.core import *
|
| 60 |
+
# next Qt
|
| 61 |
+
from PyQt4.QtCore import *
|
| 62 |
+
from PyQt4.QtGui import *
|
| 63 |
+
|
| 64 |
+
import pywps
|
| 65 |
+
from pywps import config
|
| 66 |
+
from pywps.Exceptions import *
|
| 67 |
+
|
| 68 |
+
import sys
|
| 69 |
+
import os
|
| 70 |
+
import traceback
|
| 71 |
+
import inspect
|
| 72 |
+
|
| 73 |
+
# get the request method and inputs
|
| 74 |
+
method = os.getenv("REQUEST_METHOD")
|
| 75 |
+
if not method: # set standard method
|
| 76 |
+
method = pywps.METHOD_GET
|
| 77 |
+
|
| 78 |
+
inputQuery = None
|
| 79 |
+
if method == pywps.METHOD_GET:
|
| 80 |
+
try:
|
| 81 |
+
inputQuery = os.environ["QUERY_STRING"]
|
| 82 |
+
except KeyError:
|
| 83 |
+
# if QUERY_STRING isn't found in env-dictionary, try to read
|
| 84 |
+
# query from command line:
|
| 85 |
+
if len(sys.argv) > 1: # any arguments available?
|
| 86 |
+
inputQuery = sys.argv[1]
|
| 87 |
+
if not inputQuery:
|
| 88 |
+
err = NoApplicableCode("No query string found.")
|
| 89 |
+
pywps.response.response(err, sys.stdout)
|
| 90 |
+
sys.exit(1)
|
| 91 |
+
else:
|
| 92 |
+
inputQuery = sys.stdin
|
| 93 |
+
|
| 94 |
+
# create the WPS object
|
| 95 |
+
wps = None
|
| 96 |
+
try:
|
| 97 |
+
# Get or define user_folder
|
| 98 |
+
config.loadConfiguration()
|
| 99 |
+
user_folder = os.path.dirname(os.path.abspath(
|
| 100 |
+
inspect.getfile(inspect.currentframe())))
|
| 101 |
+
if config.config.has_option('qgis', 'user_folder'):
|
| 102 |
+
user_folder = config.getConfigValue('qgis', 'user_folder')
|
| 103 |
+
|
| 104 |
+
# init QgsApplication
|
| 105 |
+
QgsApplication(sys.argv, False, user_folder)
|
| 106 |
+
# supply path to where is your qgis installed
|
| 107 |
+
QgsApplication.setPrefixPath(config.getConfigValue("qgis", "prefix"), True)
|
| 108 |
+
|
| 109 |
+
# load providers
|
| 110 |
+
QgsApplication.initQgis()
|
| 111 |
+
|
| 112 |
+
# initialize application
|
| 113 |
+
qa = QApplication(sys.argv)
|
| 114 |
+
wps = pywps.Pywps(method)
|
| 115 |
+
if wps.parseRequest(inputQuery):
|
| 116 |
+
pywps.debug(wps.inputs)
|
| 117 |
+
response = wps.performRequest()
|
| 118 |
+
# request performed, write the response back
|
| 119 |
+
if response:
|
| 120 |
+
# print only to standard out
|
| 121 |
+
pywps.response.response(wps.response,
|
| 122 |
+
sys.stdout, wps.parser.soapVersion, wps.parser.isSoap, wps.parser.isSoapExecute, wps.request.contentType)
|
| 123 |
+
QgsApplication.exitQgis()
|
| 124 |
+
qa.exit()
|
| 125 |
+
|
| 126 |
+
except WPSException, e:
|
| 127 |
+
traceback.print_exc(file=pywps.logFile)
|
| 128 |
+
pywps.response.response(e, sys.stdout, wps.parser.soapVersion,
|
| 129 |
+
wps.parser.isSoap,
|
| 130 |
+
wps.parser.isSoapExecute)
|
pool/shard003/Python/0027312_test_query_class.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import flask_sqlalchemy as fsa
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def test_default_query_class(db):
|
| 5 |
+
class Parent(db.Model):
|
| 6 |
+
id = db.Column(db.Integer, primary_key=True)
|
| 7 |
+
children = db.relationship("Child", backref="parent", lazy='dynamic')
|
| 8 |
+
|
| 9 |
+
class Child(db.Model):
|
| 10 |
+
id = db.Column(db.Integer, primary_key=True)
|
| 11 |
+
parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'))
|
| 12 |
+
|
| 13 |
+
p = Parent()
|
| 14 |
+
c = Child()
|
| 15 |
+
c.parent = p
|
| 16 |
+
|
| 17 |
+
assert type(Parent.query) == fsa.BaseQuery
|
| 18 |
+
assert type(Child.query) == fsa.BaseQuery
|
| 19 |
+
assert isinstance(p.children, fsa.BaseQuery)
|
| 20 |
+
assert isinstance(db.session.query(Parent), fsa.BaseQuery)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_custom_query_class(app):
|
| 24 |
+
class CustomQueryClass(fsa.BaseQuery):
|
| 25 |
+
pass
|
| 26 |
+
|
| 27 |
+
db = fsa.SQLAlchemy(app, query_class=CustomQueryClass)
|
| 28 |
+
|
| 29 |
+
class Parent(db.Model):
|
| 30 |
+
id = db.Column(db.Integer, primary_key=True)
|
| 31 |
+
children = db.relationship("Child", backref="parent", lazy='dynamic')
|
| 32 |
+
|
| 33 |
+
class Child(db.Model):
|
| 34 |
+
id = db.Column(db.Integer, primary_key=True)
|
| 35 |
+
parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'))
|
| 36 |
+
|
| 37 |
+
p = Parent()
|
| 38 |
+
c = Child()
|
| 39 |
+
c.parent = p
|
| 40 |
+
|
| 41 |
+
assert type(Parent.query) == CustomQueryClass
|
| 42 |
+
assert type(Child.query) == CustomQueryClass
|
| 43 |
+
assert isinstance(p.children, CustomQueryClass)
|
| 44 |
+
assert db.Query == CustomQueryClass
|
| 45 |
+
assert db.Model.query_class == CustomQueryClass
|
| 46 |
+
assert isinstance(db.session.query(Parent), CustomQueryClass)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_dont_override_model_default(app):
|
| 50 |
+
class CustomQueryClass(fsa.BaseQuery):
|
| 51 |
+
pass
|
| 52 |
+
|
| 53 |
+
db = fsa.SQLAlchemy(app, query_class=CustomQueryClass)
|
| 54 |
+
|
| 55 |
+
class SomeModel(db.Model):
|
| 56 |
+
id = db.Column(db.Integer, primary_key=True)
|
| 57 |
+
query_class = fsa.BaseQuery
|
| 58 |
+
|
| 59 |
+
assert type(SomeModel.query) == fsa.BaseQuery
|
pool/shard003/Python/0027314_tests.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from django.test import TestCase
|
| 2 |
+
from django.test.client import Client
|
| 3 |
+
from django.conf import settings
|
| 4 |
+
|
| 5 |
+
from models import *
|
| 6 |
+
from views import *
|
| 7 |
+
|
| 8 |
+
import datetime
|
| 9 |
+
|
| 10 |
+
"""
|
| 11 |
+
class InstallationTest(TestCase):
|
| 12 |
+
|
| 13 |
+
def test_urls(self):
|
| 14 |
+
from django.conf.urls import patterns, include, url
|
| 15 |
+
|
| 16 |
+
good_urlpatterns = patterns('',
|
| 17 |
+
url(r'',include("tinycms.urls"))
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
error_urlpatterns = patterns('',)
|
| 21 |
+
|
| 22 |
+
self.assertTrue(check_url(good_urlpatterns))
|
| 23 |
+
self.assertFalse(check_url(error_urlpatterns))
|
| 24 |
+
|
| 25 |
+
def test_languages(self):
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
def test_templates(self):
|
| 29 |
+
pass
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class ConfigurationTest(TestCase):
|
| 33 |
+
pass
|
| 34 |
+
|
| 35 |
+
class CreateAndShowPageTest(TestCase):
|
| 36 |
+
pass
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
class ModellTest(TestCase):
|
| 40 |
+
def setUp(self):
|
| 41 |
+
Dispatcher.clear()
|
| 42 |
+
self.c512 =""
|
| 43 |
+
for i in range(0,511):
|
| 44 |
+
self.c512 += "a"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def test_model_normal(self):
|
| 48 |
+
testDispatch={}
|
| 49 |
+
|
| 50 |
+
page = Page(slug="test",template="tinycms/shelltest.html",is_active=True)
|
| 51 |
+
page.save()
|
| 52 |
+
page2 = Page(slug="test2",template="tinycms/shelltest.html",parent=page,is_active=True)
|
| 53 |
+
page2.save()
|
| 54 |
+
|
| 55 |
+
testDispatch[u'test/']=page
|
| 56 |
+
testDispatch[u'test/test2/']=page2
|
| 57 |
+
|
| 58 |
+
with self.assertRaises(Exception):
|
| 59 |
+
page = Page(slug="test",template="tinycms/shelltest.html",is_active=True)
|
| 60 |
+
page.save()
|
| 61 |
+
|
| 62 |
+
page = Page(slug=self.c512,template="tinycms/shelltest.html",is_active=True)
|
| 63 |
+
page.save()
|
| 64 |
+
testDispatch[unicode(self.c512+"/")]=page
|
| 65 |
+
|
| 66 |
+
cont = Content(page=page,value_name="main",language="ja",content="test")
|
| 67 |
+
cont.save()
|
| 68 |
+
|
| 69 |
+
Dispatcher.register()
|
| 70 |
+
self.assertEqual(Dispatcher.dispatchURLs,testDispatch)#,"Invalid dispatch url\n"+str(Dispatcher.dispatchURLs))
|
| 71 |
+
|
| 72 |
+
def test_slash(self):
|
| 73 |
+
|
| 74 |
+
page = Page(slug="/test/",template="tinycms/shelltest.html",is_active=True)
|
| 75 |
+
page.save()
|
| 76 |
+
page2 = Page(slug="/test2/",template="tinycms/shelltest.html",parent=page,is_active=True)
|
| 77 |
+
page2.save()
|
| 78 |
+
|
| 79 |
+
page3 = Page(slug="/test3",template="tinycms/shelltest.html",parent=page,is_active=True,url_overwrite="/test3")
|
| 80 |
+
page3.save()
|
| 81 |
+
|
| 82 |
+
page4 = Page(slug="/",template="tinycms/shelltest.html",is_active=True)
|
| 83 |
+
page4.save()
|
| 84 |
+
|
| 85 |
+
testDispatch={}
|
| 86 |
+
testDispatch[u'test/']=page
|
| 87 |
+
testDispatch[u'test/test2/']=page2
|
| 88 |
+
testDispatch[u'test3']=page3
|
| 89 |
+
testDispatch[u'']=page4
|
| 90 |
+
|
| 91 |
+
Dispatcher.register()
|
| 92 |
+
self.assertEqual(Dispatcher.dispatchURLs,testDispatch)#,"Invalid dispatch url\n"+str(Dispatcher.dispatchURLs))
|
| 93 |
+
|
| 94 |
+
def test_slash2(self):
|
| 95 |
+
page4 = Page(slug="home",template="tinycms/shelltest.html",is_active=True,url_overwrite="/")
|
| 96 |
+
page4.save()
|
| 97 |
+
|
| 98 |
+
testDispatch={}
|
| 99 |
+
testDispatch[u'']=page4
|
| 100 |
+
|
| 101 |
+
Dispatcher.register()
|
| 102 |
+
self.assertEqual(Dispatcher.dispatchURLs,testDispatch)#,"Invalid dispatch url\n"+str(Dispatcher.dispatchURLs))
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class DummyRequest:
|
| 106 |
+
def __init__(self,user=None,GET={}):
|
| 107 |
+
self.user=user
|
| 108 |
+
self.GET=GET
|
| 109 |
+
self.POST={}
|
| 110 |
+
self.method="GET"
|
| 111 |
+
|
| 112 |
+
class ViewTest(TestCase):
|
| 113 |
+
def setUp(self):
|
| 114 |
+
Dispatcher.clear()
|
| 115 |
+
|
| 116 |
+
def test_content(self):
|
| 117 |
+
page = Page(slug="test",template="tinycms/shelltest.html",is_active=True)
|
| 118 |
+
page.save()
|
| 119 |
+
page2 = Page(slug="test2",template="tinycms/shelltest.html",parent=page,is_active=True)
|
| 120 |
+
page2.save()
|
| 121 |
+
cont = Content(page=page,value_name="main",language="ja",content="test")
|
| 122 |
+
cont.save()
|
| 123 |
+
cont = Content(page=page,value_name="main",language="en",content="test")
|
| 124 |
+
cont.save()
|
| 125 |
+
|
| 126 |
+
req = DummyRequest()
|
| 127 |
+
result = show_page(req,"test/")
|
| 128 |
+
candResult = '<html><body><p>test</p></body></html>'
|
| 129 |
+
self.assertEqual(result.content,candResult)
|
| 130 |
+
|
| 131 |
+
with self.assertRaises(Exception):
|
| 132 |
+
result = show_page(req,"test2/")
|
| 133 |
+
|
| 134 |
+
def test_menu(self):
|
| 135 |
+
page = Page(slug="test",template="tinycms/menutest.html",is_active=True)
|
| 136 |
+
page.save()
|
| 137 |
+
page2 = Page(slug="test2",template="tinycms/menutest.html",parent=page,is_active=True)
|
| 138 |
+
page2.save()
|
| 139 |
+
cont = Content(page=page,value_name="main",language="ja",content="test")
|
| 140 |
+
cont.save()
|
| 141 |
+
cont = Content(page=page,value_name="main",language="en",content="test")
|
| 142 |
+
cont.save()
|
| 143 |
+
cont = Content(page=page,value_name="menu_title",language="en",content="test")
|
| 144 |
+
cont.save()
|
| 145 |
+
cont = Content(page=page2,value_name="menu_title",language="en",content="test2")
|
| 146 |
+
cont.save()
|
| 147 |
+
|
| 148 |
+
req = DummyRequest()
|
| 149 |
+
result = show_page(req,"test/")
|
| 150 |
+
candResult = "<html><body><ul><li><a href='/en/test/'>test</a><ul><li><a href='/en/test/test2/'>test2</a></li></ul></li></ul><p>test</p></body></html>"
|
| 151 |
+
self.assertEqual(result.content,candResult)
|
| 152 |
+
|
| 153 |
+
def test_slash(self):
|
| 154 |
+
page4 = Page(slug="/",template="tinycms/shelltest.html",is_active=True)
|
| 155 |
+
page4.save()
|
| 156 |
+
cont = Content(page=page4,value_name="main",language="en",content="test")
|
| 157 |
+
cont.save()
|
| 158 |
+
cont = Content(page=page4,value_name="main",language="ja",content="test")
|
| 159 |
+
cont.save()
|
| 160 |
+
|
| 161 |
+
Dispatcher.register()
|
| 162 |
+
|
| 163 |
+
from django.test import Client
|
| 164 |
+
c = Client()
|
| 165 |
+
response = c.get('/en/')
|
| 166 |
+
self.assertEqual(response.status_code,200)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
|
pool/shard003/Python/0027315_TrayIcon.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# TrayIcon.py
|
| 2 |
+
# This file is part of Labyrinth
|
| 3 |
+
#
|
| 4 |
+
# Copyright (C) 2006 - Andreas Sliwka <andreas.sliwka@gmail.com>
|
| 5 |
+
#
|
| 6 |
+
# Labyrinth is free software; you can redistribute it and/or modify
|
| 7 |
+
# it under the terms of the GNU General Public License as published by
|
| 8 |
+
# the Free Software Foundation; either version 2 of the License, or
|
| 9 |
+
# (at your option) any later version.
|
| 10 |
+
#
|
| 11 |
+
# Labyrinth is distributed in the hope that it will be useful,
|
| 12 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 13 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 14 |
+
# GNU General Public License for more details.
|
| 15 |
+
#
|
| 16 |
+
# You should have received a copy of the GNU General Public License
|
| 17 |
+
# along with Labyrinth; if not, write to the Free Software
|
| 18 |
+
# Foundation, Inc., 51 Franklin St, Fifth Floor,
|
| 19 |
+
# Boston, MA 02110-1301 USA
|
| 20 |
+
#
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
this module implements a tray icon for Labyrinth.
|
| 25 |
+
|
| 26 |
+
As of now it only brings the application to front if it is clicked.
|
| 27 |
+
|
| 28 |
+
"""
|
| 29 |
+
import sys
|
| 30 |
+
import os
|
| 31 |
+
import gtk
|
| 32 |
+
from utils import *
|
| 33 |
+
|
| 34 |
+
class TrayIcon(object):
|
| 35 |
+
"""This is possibly the thinnest wrapper class I've written. Ever.
|
| 36 |
+
|
| 37 |
+
Its a tray icon that you can parameterize during initialisation with the name or file of an icon, with a menu and a simple callback
|
| 38 |
+
|
| 39 |
+
It will create such an Icon, will display the image, call back the callback when left clicked and pop up the menu
|
| 40 |
+
when right clicked.
|
| 41 |
+
"""
|
| 42 |
+
def __init__(self, icon_name="TestTrayIcon", icon_file=None, menu=None, activate=None):
|
| 43 |
+
# thats so incredibly simple!
|
| 44 |
+
if icon_file:
|
| 45 |
+
self.status_icon=gtk.status_icon_new_from_file(icon_file)
|
| 46 |
+
else:
|
| 47 |
+
self.status_icon=gtk.status_icon_new_from_icon_name(icon_name)
|
| 48 |
+
|
| 49 |
+
# connect the menu and the callback if given
|
| 50 |
+
if menu:
|
| 51 |
+
self.connect_popup_menu(menu)
|
| 52 |
+
|
| 53 |
+
if activate:
|
| 54 |
+
self.connect_activate(activate)
|
| 55 |
+
|
| 56 |
+
def connect_activate(self, method):
|
| 57 |
+
def activate_callback(status_icon, *data):
|
| 58 |
+
method()
|
| 59 |
+
self.status_icon.connect("activate", activate_callback)
|
| 60 |
+
|
| 61 |
+
def connect_popup_menu(self, menu):
|
| 62 |
+
def popup_menu_callback(status_icon, button, activate_time, *data):
|
| 63 |
+
menu.popup(None, None, gtk.status_icon_position_menu, button, activate_time, status_icon)
|
| 64 |
+
self.status_icon.connect("popup-menu", popup_menu_callback)
|
| 65 |
+
|
| 66 |
+
if __name__ == "__main__":
|
| 67 |
+
menu = gtk.Menu()
|
| 68 |
+
quit_item = gtk.MenuItem("Quit")
|
| 69 |
+
quit_item.connect("activate", gtk.main_quit)
|
| 70 |
+
menu.add(quit_item)
|
| 71 |
+
menu.show_all()
|
| 72 |
+
yell_at_them = lambda : sys.stdout.write("you hit %s...\n" % trayicon)
|
| 73 |
+
trayicon = TrayIcon(icon_name="labyrinth", menu=menu, activate=yell_at_them)
|
| 74 |
+
gtk.main()
|
pool/shard003/Python/0027317_main.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python
|
| 2 |
+
|
| 3 |
+
import atexit
|
| 4 |
+
import ConfigParser
|
| 5 |
+
import signal
|
| 6 |
+
import sys
|
| 7 |
+
import time
|
| 8 |
+
|
| 9 |
+
import pyupm_grove as grove
|
| 10 |
+
import pyupm_grovespeaker as upmGrovespeaker
|
| 11 |
+
import pyupm_i2clcd as lcd
|
| 12 |
+
|
| 13 |
+
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
|
| 14 |
+
from wit import Wit
|
| 15 |
+
|
| 16 |
+
# from core.xcamera import takePhoto
|
| 17 |
+
# from core.xfacerecognition import recognizeFaces
|
| 18 |
+
from core.xspeechrecognition import recognizeSpeech
|
| 19 |
+
from core.xsay import isay
|
| 20 |
+
from core.xvoice import recordAudio
|
| 21 |
+
from core.xvoice import playAudio
|
| 22 |
+
from core.xwolfram import askWolfram
|
| 23 |
+
|
| 24 |
+
credentials = ConfigParser.ConfigParser()
|
| 25 |
+
credentialsfile = "core/configuration/credentials.config"
|
| 26 |
+
credentials.read(credentialsfile)
|
| 27 |
+
button = grove.GroveButton(8)
|
| 28 |
+
display = lcd.Jhd1313m1(0, 0x3E, 0x62)
|
| 29 |
+
light = grove.GroveLight(0)
|
| 30 |
+
speaker = upmGrovespeaker.GroveSpeaker(6)
|
| 31 |
+
|
| 32 |
+
def functionLight(bot, update):
|
| 33 |
+
luxes = light.value()
|
| 34 |
+
bot.sendMessage(update.message.chat_id, text='Light ' + str(luxes))
|
| 35 |
+
|
| 36 |
+
def functionSpeaker(bot, update):
|
| 37 |
+
speaker.playSound('c', True, "med")
|
| 38 |
+
bot.sendMessage(update.message.chat_id, text='Sound Reproduced!')
|
| 39 |
+
|
| 40 |
+
def functionEcho(bot, update):
|
| 41 |
+
bot.sendMessage(update.message.chat_id, text=update.message.text)
|
| 42 |
+
|
| 43 |
+
def SIGINTHandler(signum, frame):
|
| 44 |
+
raise SystemExit
|
| 45 |
+
|
| 46 |
+
def exitHandler():
|
| 47 |
+
print "Exiting"
|
| 48 |
+
sys.exit(0)
|
| 49 |
+
|
| 50 |
+
atexit.register(exitHandler)
|
| 51 |
+
signal.signal(signal.SIGINT, SIGINTHandler)
|
| 52 |
+
|
| 53 |
+
def say(session_id, context, msg):
|
| 54 |
+
print(msg)
|
| 55 |
+
|
| 56 |
+
def merge(session_id, context, entities, msg):
|
| 57 |
+
return context
|
| 58 |
+
|
| 59 |
+
def error(session_id, context, e):
|
| 60 |
+
print(str(e))
|
| 61 |
+
|
| 62 |
+
def witaiLight(session_id, context):
|
| 63 |
+
luxes = light.value()
|
| 64 |
+
message = "Light value is " + str(luxes)
|
| 65 |
+
isay("english", message)
|
| 66 |
+
context['forecast'] = 'sunny'
|
| 67 |
+
return context
|
| 68 |
+
|
| 69 |
+
def witaiSpeaker(session_id, context):
|
| 70 |
+
print "Play Sound"
|
| 71 |
+
speaker.playSound('c', True, "med")
|
| 72 |
+
context['forecast'] = 'sunny'
|
| 73 |
+
return context
|
| 74 |
+
|
| 75 |
+
actions = {
|
| 76 |
+
'say': say,
|
| 77 |
+
'merge': merge,
|
| 78 |
+
'error': error,
|
| 79 |
+
'witaiLight': witaiLight,
|
| 80 |
+
'witaiSpeaker': witaiSpeaker
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
if __name__ == '__main__':
|
| 84 |
+
|
| 85 |
+
credential = credentials.get("telegram", "token")
|
| 86 |
+
updater = Updater(credential)
|
| 87 |
+
dp = updater.dispatcher
|
| 88 |
+
|
| 89 |
+
dp.add_handler(CommandHandler("light", functionLight))
|
| 90 |
+
dp.add_handler(CommandHandler("speaker", functionSpeaker))
|
| 91 |
+
dp.add_handler(MessageHandler([Filters.text], functionEcho))
|
| 92 |
+
|
| 93 |
+
updater.start_polling()
|
| 94 |
+
|
| 95 |
+
credential = credentials.get("witai", "ServerAccessToken")
|
| 96 |
+
client = Wit(credential, actions)
|
| 97 |
+
|
| 98 |
+
session_id = 'my-user-id-42'
|
| 99 |
+
|
| 100 |
+
while True:
|
| 101 |
+
|
| 102 |
+
luxes = light.value()
|
| 103 |
+
luxes = int(luxes)
|
| 104 |
+
display.setColor(luxes, luxes, luxes)
|
| 105 |
+
|
| 106 |
+
if button.value() is 1:
|
| 107 |
+
isay("english", "Hi! This is GiekIe! How can I help?")
|
| 108 |
+
message = recognizeSpeech()
|
| 109 |
+
display.clear()
|
| 110 |
+
display.setCursor(0,0)
|
| 111 |
+
display.write(str(message))
|
| 112 |
+
client.run_actions(session_id, message, {})
|
| 113 |
+
|
| 114 |
+
#updater.idle()
|
| 115 |
+
|
| 116 |
+
'''
|
| 117 |
+
luxes = light.value()
|
| 118 |
+
display.setColor(255, 0, 0)
|
| 119 |
+
display.setCursor(0,0)
|
| 120 |
+
display.write('Light ' + str(luxes))
|
| 121 |
+
print 'Light ' + str(luxes)
|
| 122 |
+
time.sleep(1)
|
| 123 |
+
'''
|
pool/shard003/Python/0027319_static_and_shared_library.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python
|
| 2 |
+
|
| 3 |
+
# Copyright 2002, 2003 Dave Abrahams
|
| 4 |
+
# Copyright 2002, 2003, 2005 Vladimir Prus
|
| 5 |
+
# Distributed under the Boost Software License, Version 1.0.
|
| 6 |
+
# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
|
| 7 |
+
|
| 8 |
+
import BoostBuild
|
| 9 |
+
|
| 10 |
+
t = BoostBuild.Tester(use_test_config=False)
|
| 11 |
+
t.write("jamroot.jam", "")
|
| 12 |
+
t.write("lib/c.cpp", "int bar() { return 0; }\n")
|
| 13 |
+
t.write("lib/jamfile.jam", """\
|
| 14 |
+
static-lib auxilliary1 : c.cpp ;
|
| 15 |
+
lib auxilliary2 : c.cpp ;
|
| 16 |
+
""")
|
| 17 |
+
|
| 18 |
+
def reset():
|
| 19 |
+
t.rm("lib/bin")
|
| 20 |
+
|
| 21 |
+
t.run_build_system(subdir='lib')
|
| 22 |
+
t.expect_addition("lib/bin/$toolset/debug*/" * BoostBuild.List("c.obj "
|
| 23 |
+
"auxilliary1.lib auxilliary2.dll"))
|
| 24 |
+
t.expect_nothing_more()
|
| 25 |
+
|
| 26 |
+
reset()
|
| 27 |
+
t.run_build_system(["link=shared"], subdir="lib")
|
| 28 |
+
t.expect_addition("lib/bin/$toolset/debug*/" * BoostBuild.List("c.obj "
|
| 29 |
+
"auxilliary1.lib auxilliary2.dll"))
|
| 30 |
+
t.expect_nothing_more()
|
| 31 |
+
|
| 32 |
+
reset()
|
| 33 |
+
t.run_build_system(["link=static"], subdir="lib")
|
| 34 |
+
t.expect_addition("lib/bin/$toolset/debug/link-static*/" * BoostBuild.List(
|
| 35 |
+
"c.obj auxilliary1.lib auxilliary2.lib"))
|
| 36 |
+
t.expect_nothing_more()
|
| 37 |
+
|
| 38 |
+
t.cleanup()
|
pool/shard003/Python/0027331_test_output.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import print_function
|
| 2 |
+
from __future__ import division
|
| 3 |
+
from __future__ import absolute_import
|
| 4 |
+
from mock import MagicMock
|
| 5 |
+
import unittest
|
| 6 |
+
|
| 7 |
+
from stacker.stack import Stack
|
| 8 |
+
from ...factories import generate_definition
|
| 9 |
+
from stacker.lookups.handlers.output import OutputLookup
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TestOutputHandler(unittest.TestCase):
|
| 13 |
+
|
| 14 |
+
def setUp(self):
|
| 15 |
+
self.context = MagicMock()
|
| 16 |
+
|
| 17 |
+
def test_output_handler(self):
|
| 18 |
+
stack = Stack(
|
| 19 |
+
definition=generate_definition("vpc", 1),
|
| 20 |
+
context=self.context)
|
| 21 |
+
stack.set_outputs({
|
| 22 |
+
"SomeOutput": "Test Output"})
|
| 23 |
+
self.context.get_stack.return_value = stack
|
| 24 |
+
value = OutputLookup.handle("stack-name::SomeOutput",
|
| 25 |
+
context=self.context)
|
| 26 |
+
self.assertEqual(value, "Test Output")
|
| 27 |
+
self.assertEqual(self.context.get_stack.call_count, 1)
|
| 28 |
+
args = self.context.get_stack.call_args
|
| 29 |
+
self.assertEqual(args[0][0], "stack-name")
|
pool/shard003/Python/0027350_desktop_ui_stories.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The Chromium Authors. All rights reserved.
|
| 2 |
+
# Use of this source code is governed by a BSD-style license that can be
|
| 3 |
+
# found in the LICENSE file.
|
| 4 |
+
|
| 5 |
+
from telemetry import story
|
| 6 |
+
from page_sets.desktop_ui import \
|
| 7 |
+
download_shelf_story, new_tab_page_story, omnibox_story, \
|
| 8 |
+
side_search_story, tab_search_story, webui_tab_strip_story
|
| 9 |
+
from page_sets.desktop_ui.ui_devtools_utils import IsMac
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class DesktopUIStorySet(story.StorySet):
|
| 13 |
+
TAB_SEARCH_STORIES = [
|
| 14 |
+
tab_search_story.TabSearchStoryTop10,
|
| 15 |
+
tab_search_story.TabSearchStoryTop50,
|
| 16 |
+
tab_search_story.TabSearchStoryTop10Loading,
|
| 17 |
+
tab_search_story.TabSearchStoryRecentlyClosed10,
|
| 18 |
+
tab_search_story.TabSearchStoryRecentlyClosed50,
|
| 19 |
+
tab_search_story.TabSearchStoryRecentlyClosed100,
|
| 20 |
+
tab_search_story.TabSearchStoryTop50Loading,
|
| 21 |
+
tab_search_story.TabSearchStoryCloseAndOpen,
|
| 22 |
+
tab_search_story.TabSearchStoryCloseAndOpenLoading,
|
| 23 |
+
tab_search_story.TabSearchStoryScrollUpAndDown,
|
| 24 |
+
tab_search_story.TabSearchStoryCleanSlate,
|
| 25 |
+
tab_search_story.TabSearchStoryMeasureMemoryBefore,
|
| 26 |
+
tab_search_story.TabSearchStoryMeasureMemoryAfter,
|
| 27 |
+
tab_search_story.TabSearchStoryMeasureMemoryMultiwindow,
|
| 28 |
+
tab_search_story.TabSearchStoryMeasureMemory2TabSearch,
|
| 29 |
+
tab_search_story.TabSearchStoryMeasureMemory3TabSearch,
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
DOWNLOAD_SHELF_STORIES = [
|
| 33 |
+
download_shelf_story.DownloadShelfStory1File,
|
| 34 |
+
download_shelf_story.DownloadShelfStory5File,
|
| 35 |
+
download_shelf_story.DownloadShelfStoryMeasureMemory,
|
| 36 |
+
download_shelf_story.DownloadShelfStoryTop10Loading,
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
DOWNLOAD_SHELF_WEBUI_STORIES = [
|
| 40 |
+
download_shelf_story.DownloadShelfWebUIStory1File,
|
| 41 |
+
download_shelf_story.DownloadShelfWebUIStory5File,
|
| 42 |
+
download_shelf_story.DownloadShelfWebUIStoryMeasureMemory,
|
| 43 |
+
download_shelf_story.DownloadShelfWebUIStoryTop10Loading,
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
WEBUI_TAB_STRIP_STORIES = [
|
| 47 |
+
webui_tab_strip_story.WebUITabStripStoryCleanSlate,
|
| 48 |
+
webui_tab_strip_story.WebUITabStripStoryMeasureMemory,
|
| 49 |
+
webui_tab_strip_story.WebUITabStripStoryMeasureMemory2Window,
|
| 50 |
+
webui_tab_strip_story.WebUITabStripStoryTop10,
|
| 51 |
+
webui_tab_strip_story.WebUITabStripStoryTop10Loading,
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
OMNIBOX_STORIES = [
|
| 55 |
+
omnibox_story.OmniboxStoryPedal,
|
| 56 |
+
omnibox_story.OmniboxStoryScopedSearch,
|
| 57 |
+
omnibox_story.OmniboxStorySearch,
|
| 58 |
+
]
|
| 59 |
+
|
| 60 |
+
NEW_TAB_PAGE_STORIES = [
|
| 61 |
+
new_tab_page_story.NewTabPageStoryLoading,
|
| 62 |
+
]
|
| 63 |
+
|
| 64 |
+
SIDE_SEARCH_STORIES = [
|
| 65 |
+
side_search_story.SideSearchStoryMeasureMemory,
|
| 66 |
+
side_search_story.SideSearchStoryNavigation,
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
def __init__(self):
|
| 70 |
+
super(DesktopUIStorySet,
|
| 71 |
+
self).__init__(archive_data_file=('../data/desktop_ui.json'),
|
| 72 |
+
cloud_storage_bucket=story.PARTNER_BUCKET)
|
| 73 |
+
for cls in self.TAB_SEARCH_STORIES:
|
| 74 |
+
self.AddStory(
|
| 75 |
+
cls(self, [
|
| 76 |
+
'--top-chrome-touch-ui=disabled',
|
| 77 |
+
]))
|
| 78 |
+
|
| 79 |
+
for cls in self.DOWNLOAD_SHELF_STORIES:
|
| 80 |
+
self.AddStory(cls(self))
|
| 81 |
+
|
| 82 |
+
for cls in self.DOWNLOAD_SHELF_WEBUI_STORIES:
|
| 83 |
+
self.AddStory(
|
| 84 |
+
cls(self, [
|
| 85 |
+
'--enable-features=WebUIDownloadShelf',
|
| 86 |
+
]))
|
| 87 |
+
|
| 88 |
+
# WebUI Tab Strip is not available on Mac.
|
| 89 |
+
if not IsMac():
|
| 90 |
+
for cls in self.WEBUI_TAB_STRIP_STORIES:
|
| 91 |
+
self.AddStory(
|
| 92 |
+
cls(self, [
|
| 93 |
+
'--enable-features=WebUITabStrip',
|
| 94 |
+
'--top-chrome-touch-ui=enabled',
|
| 95 |
+
]))
|
| 96 |
+
|
| 97 |
+
for cls in self.OMNIBOX_STORIES:
|
| 98 |
+
self.AddStory(cls(self))
|
| 99 |
+
|
| 100 |
+
for cls in self.NEW_TAB_PAGE_STORIES:
|
| 101 |
+
self.AddStory(
|
| 102 |
+
cls(self, [
|
| 103 |
+
'--enable-features=NtpModules,\
|
| 104 |
+
NtpRecipeTasksModule:NtpRecipeTasksModuleDataParam/fake'
|
| 105 |
+
]))
|
| 106 |
+
|
| 107 |
+
for cls in self.SIDE_SEARCH_STORIES:
|
| 108 |
+
self.AddStory(cls(self, [
|
| 109 |
+
'--enable-features=SideSearch',
|
| 110 |
+
]))
|
pool/shard003/Python/0027352_settings.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from __future__ import unicode_literals
|
| 4 |
+
|
| 5 |
+
import importlib
|
| 6 |
+
import os
|
| 7 |
+
import pytz
|
| 8 |
+
|
| 9 |
+
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
|
| 10 |
+
from trello.organization import Organization
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 14 |
+
|
| 15 |
+
MEDIA_URL = "/media/"
|
| 16 |
+
MEDIA_ROOT = BASE_DIR+"/djanban/media"
|
| 17 |
+
|
| 18 |
+
#
|
| 19 |
+
settings_local_module = 'djanban.settings_local'
|
| 20 |
+
if os.environ.get("DJANGO_APP_MODE") == "desktop_app":
|
| 21 |
+
settings_local_module = 'djanban.settings_desktop_app'
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
settings_local = importlib.import_module(settings_local_module)
|
| 25 |
+
except ImportError:
|
| 26 |
+
print("Please, create a {0} in project directory "
|
| 27 |
+
"with SECRET_KEY, DEBUG, DOMAIN, ALLOWED_HOSTS and DATABASES settings".format(settings_local_module))
|
| 28 |
+
exit(-1)
|
| 29 |
+
|
| 30 |
+
DATABASES = settings_local.DATABASES
|
| 31 |
+
|
| 32 |
+
TEST_DATABASE_PATH = os.path.join(BASE_DIR, "../resources/database/test.db")
|
| 33 |
+
|
| 34 |
+
if 'test' in sys.argv:
|
| 35 |
+
DATABASES['default'] = {
|
| 36 |
+
'ENGINE': 'django.db.backends.sqlite3',
|
| 37 |
+
'NAME': TEST_DATABASE_PATH
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
# SECURITY WARNING: keep the secret key used in production secret!
|
| 41 |
+
SECRET_KEY = settings_local.SECRET_KEY
|
| 42 |
+
|
| 43 |
+
# This is the checksum of the destruction password. It is needed to verify the identity of administrator
|
| 44 |
+
# that is executing the manage destruct_all option
|
| 45 |
+
DESTRUCTION_PASSWORD_CHECKSUM = None
|
| 46 |
+
if hasattr(settings_local, "DESTRUCTION_PASSWORD_CHECKSUM"):
|
| 47 |
+
DESTRUCTION_PASSWORD_CHECKSUM = settings_local.DESTRUCTION_PASSWORD_CHECKSUM
|
| 48 |
+
|
| 49 |
+
# Signup restriction by email regex
|
| 50 |
+
SIGNUP_ALLOWED_EMAIL_REGEXES = None
|
| 51 |
+
if hasattr(settings_local, "SIGNUP_ALLOWED_EMAIL_REGEXES"):
|
| 52 |
+
SIGNUP_ALLOWED_EMAIL_REGEXES = settings_local.SIGNUP_ALLOWED_EMAIL_REGEXES
|
| 53 |
+
|
| 54 |
+
# SECURITY WARNING: don't run with debug turned on in production!
|
| 55 |
+
DEBUG = settings_local.DEBUG
|
| 56 |
+
|
| 57 |
+
DOMAIN = settings_local.DOMAIN
|
| 58 |
+
PORT = settings_local.PORT
|
| 59 |
+
ALLOWED_HOSTS = settings_local.ALLOWED_HOSTS
|
| 60 |
+
|
| 61 |
+
ADMINS = []
|
| 62 |
+
if hasattr(settings_local, "ADMINS"):
|
| 63 |
+
ADMINS = settings_local.ADMINS
|
| 64 |
+
|
| 65 |
+
SITE_ID = 1
|
| 66 |
+
|
| 67 |
+
# Administrator group
|
| 68 |
+
ADMINISTRATOR_GROUP = "Administrators"
|
| 69 |
+
|
| 70 |
+
DATE_INPUT_FORMATS = ('%Y-%m-%d', '%Y/%m/%d', '%d-%m-%Y', '%d/%m/%Y')
|
| 71 |
+
|
| 72 |
+
# Application definition
|
| 73 |
+
|
| 74 |
+
INSTALLED_APPS = [
|
| 75 |
+
'async_include',
|
| 76 |
+
'captcha',
|
| 77 |
+
'ckeditor',
|
| 78 |
+
'ckeditor_uploader',
|
| 79 |
+
'crequest',
|
| 80 |
+
'cuser',
|
| 81 |
+
'dal',
|
| 82 |
+
'dal_select2',
|
| 83 |
+
'django.contrib.auth',
|
| 84 |
+
'django.contrib.contenttypes',
|
| 85 |
+
'django.contrib.humanize',
|
| 86 |
+
'django.contrib.sessions',
|
| 87 |
+
'django.contrib.sites',
|
| 88 |
+
'django.contrib.messages',
|
| 89 |
+
'django.contrib.staticfiles',
|
| 90 |
+
'django.contrib.admin',
|
| 91 |
+
'djanban.apps.agility_rating',
|
| 92 |
+
'djanban.apps.api',
|
| 93 |
+
'djanban.apps.anonymizer',
|
| 94 |
+
'djanban.apps.base',
|
| 95 |
+
'djanban.apps.boards',
|
| 96 |
+
'djanban.apps.charts',
|
| 97 |
+
'djanban.apps.hourly_rates',
|
| 98 |
+
'djanban.apps.index',
|
| 99 |
+
'djanban.apps.journal',
|
| 100 |
+
'djanban.apps.destructor',
|
| 101 |
+
'djanban.apps.dev_times',
|
| 102 |
+
'djanban.apps.dev_environment',
|
| 103 |
+
'djanban.apps.fetch',
|
| 104 |
+
'djanban.apps.forecasters',
|
| 105 |
+
'djanban.apps.members',
|
| 106 |
+
'djanban.apps.multiboards',
|
| 107 |
+
'djanban.apps.niko_niko_calendar',
|
| 108 |
+
'djanban.apps.notifications',
|
| 109 |
+
'djanban.apps.password_reseter',
|
| 110 |
+
'djanban.apps.recurrent_cards',
|
| 111 |
+
'djanban.apps.reporter',
|
| 112 |
+
'djanban.apps.reports',
|
| 113 |
+
'djanban.apps.repositories',
|
| 114 |
+
'djanban.apps.requirements',
|
| 115 |
+
'djanban.apps.slideshow',
|
| 116 |
+
'djanban.apps.visitors',
|
| 117 |
+
'djanban.apps.work_hours_packages',
|
| 118 |
+
'djanban.apps.workflows',
|
| 119 |
+
]
|
| 120 |
+
|
| 121 |
+
MIDDLEWARE_CLASSES = (
|
| 122 |
+
'django.contrib.sessions.middleware.SessionMiddleware',
|
| 123 |
+
'django.middleware.locale.LocaleMiddleware',
|
| 124 |
+
'django.middleware.common.CommonMiddleware',
|
| 125 |
+
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
| 126 |
+
'django.contrib.messages.middleware.MessageMiddleware',
|
| 127 |
+
'crequest.middleware.CrequestMiddleware',
|
| 128 |
+
'cuser.middleware.CuserMiddleware'
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# Based on the tutorial that integrates Django with Angular
|
| 132 |
+
# (https://4sw.in/blog/2016/django-angular2-tutorial-part-2/)
|
| 133 |
+
ANGULAR_URL = '/ng/'
|
| 134 |
+
ANGULAR_URL_REGEX = r'^ng/(?P<path>.*)$'
|
| 135 |
+
ANGULAR_ROOT = os.path.join(BASE_DIR, 'angularapp/')
|
| 136 |
+
|
| 137 |
+
ROOT_URLCONF = 'djanban.urls'
|
| 138 |
+
|
| 139 |
+
TEMPLATES = [
|
| 140 |
+
{
|
| 141 |
+
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
| 142 |
+
'DIRS': [BASE_DIR+"/djanban/templates"],
|
| 143 |
+
'APP_DIRS': True,
|
| 144 |
+
'OPTIONS': {
|
| 145 |
+
'context_processors': [
|
| 146 |
+
'django.contrib.auth.context_processors.auth',
|
| 147 |
+
'django.template.context_processors.debug',
|
| 148 |
+
'django.template.context_processors.media',
|
| 149 |
+
'django.template.context_processors.static',
|
| 150 |
+
'django.template.context_processors.tz',
|
| 151 |
+
'django.contrib.messages.context_processors.messages',
|
| 152 |
+
'django.template.context_processors.request',
|
| 153 |
+
],
|
| 154 |
+
},
|
| 155 |
+
},
|
| 156 |
+
]
|
| 157 |
+
|
| 158 |
+
WSGI_APPLICATION = 'wsgi.wsgi.application'
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
# Database
|
| 162 |
+
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# Password validation
|
| 167 |
+
# https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators
|
| 168 |
+
|
| 169 |
+
# AUTH_PASSWORD_VALIDATORS = [
|
| 170 |
+
# {
|
| 171 |
+
# 'NAME': 'django.contrib.member.password_validation.UserAttributeSimilarityValidator',
|
| 172 |
+
# },
|
| 173 |
+
# {
|
| 174 |
+
# 'NAME': 'django.contrib.member.password_validation.MinimumLengthValidator',
|
| 175 |
+
# },
|
| 176 |
+
# {
|
| 177 |
+
# 'NAME': 'django.contrib.member.password_validation.CommonPasswordValidator',
|
| 178 |
+
# },
|
| 179 |
+
# {
|
| 180 |
+
# 'NAME': 'django.contrib.member.password_validation.NumericPasswordValidator',
|
| 181 |
+
# },
|
| 182 |
+
# ]
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
# Internationalization
|
| 186 |
+
# https://docs.djangoproject.com/en/dev/topics/i18n/
|
| 187 |
+
|
| 188 |
+
LANGUAGE_CODE = settings_local.LANGUAGE_CODE
|
| 189 |
+
|
| 190 |
+
TIME_ZONE = settings_local.TIME_ZONE
|
| 191 |
+
Organization.TIMEZONE = TIME_ZONE
|
| 192 |
+
PYTZ_SERVER_TIME_ZONE = pytz.timezone(TIME_ZONE)
|
| 193 |
+
PYTZ_UTC_TIME_ZONE = pytz.timezone('UTC')
|
| 194 |
+
|
| 195 |
+
if hasattr(settings_local, "DATE_FORMAT"):
|
| 196 |
+
DATE_FORMAT = settings_local.DATE_FORMAT
|
| 197 |
+
else:
|
| 198 |
+
DATE_FORMAT = "Y-m-d"
|
| 199 |
+
|
| 200 |
+
if hasattr(settings_local, "DATETIME_FORMAT"):
|
| 201 |
+
DATETIME_FORMAT = settings_local.DATETIME_FORMAT
|
| 202 |
+
else:
|
| 203 |
+
DATETIME_FORMAT = "Y-m-d H:i"
|
| 204 |
+
|
| 205 |
+
USE_I18N = False
|
| 206 |
+
|
| 207 |
+
USE_L10N = False
|
| 208 |
+
|
| 209 |
+
USE_TZ = True
|
| 210 |
+
|
| 211 |
+
LOGIN_URL = '/base/login/'
|
| 212 |
+
|
| 213 |
+
EMAIL_USE_TLS = settings_local.EMAIL_USE_TLS
|
| 214 |
+
EMAIL_HOST = settings_local.EMAIL_HOST
|
| 215 |
+
EMAIL_PORT = settings_local.EMAIL_PORT
|
| 216 |
+
EMAIL_HOST_USER = settings_local.EMAIL_HOST_USER
|
| 217 |
+
EMAIL_HOST_PASSWORD = settings_local.EMAIL_HOST_PASSWORD
|
| 218 |
+
DEFAULT_FROM_EMAIL = settings_local.DEFAULT_FROM_EMAIL
|
| 219 |
+
SERVER_EMAIL = settings_local.SERVER_EMAIL
|
| 220 |
+
|
| 221 |
+
# HTTPS configuration
|
| 222 |
+
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
|
| 223 |
+
USE_X_FORWARDED_HOST = False # Django >= 1.4
|
| 224 |
+
USE_X_FORWARDED_PORT = False
|
| 225 |
+
SECURE_SSL_REDIRECT = False
|
| 226 |
+
SECURE_SSL_HOST = None
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
# Static files (CSS, JavaScript, Images)
|
| 230 |
+
# https://docs.djangoproject.com/en/dev/howto/static-files/
|
| 231 |
+
STATICFILES_DIRS = [
|
| 232 |
+
BASE_DIR + "/djanban/static/"
|
| 233 |
+
]
|
| 234 |
+
|
| 235 |
+
TMP_DIR = BASE_DIR + "/djanban/tmp/"
|
| 236 |
+
|
| 237 |
+
STATIC_URL = '/static/'
|
| 238 |
+
|
| 239 |
+
STATIC_ROOT = BASE_DIR + "/public_html/collectedstatic"
|
| 240 |
+
|
| 241 |
+
# Captcha image and font size
|
| 242 |
+
CAPTCHA_IMAGE_SIZE = (200, 70)
|
| 243 |
+
CAPTCHA_FONT_SIZE = 52
|
| 244 |
+
|
| 245 |
+
# CKEDITOR preferences
|
| 246 |
+
CKEDITOR_UPLOAD_PATH = "uploads/"
|
| 247 |
+
CKEDITOR_RESTRICT_BY_USER = False
|
| 248 |
+
CKEDITOR_BROWSE_SHOW_DIRS = True
|
| 249 |
+
|
| 250 |
+
CKEDITOR_IMAGE_BACKEND = "pillow"
|
| 251 |
+
CKEDITOR_CONFIGS = {
|
| 252 |
+
'default': {
|
| 253 |
+
'toolbar': 'Custom',
|
| 254 |
+
'toolbar_Custom': [
|
| 255 |
+
['Bold', 'Italic', 'Underline'],
|
| 256 |
+
['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
|
| 257 |
+
['Image', 'Update', 'Link', 'Unlink'],
|
| 258 |
+
['RemoveFormat'],
|
| 259 |
+
],
|
| 260 |
+
},
|
| 261 |
+
'basic': {
|
| 262 |
+
'toolbar': 'basic'
|
| 263 |
+
},
|
| 264 |
+
'full': {
|
| 265 |
+
'toolbar': 'full'
|
| 266 |
+
}
|
| 267 |
+
}
|
pool/shard003/Python/0027356_AddPost.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .Component import Component
|
| 2 |
+
from django.template.response import TemplateResponse
|
| 3 |
+
from django.http import JsonResponse
|
| 4 |
+
from toPickApp.models import Topic
|
| 5 |
+
|
| 6 |
+
class AddPost(Component):
|
| 7 |
+
|
| 8 |
+
def __init__(self):
|
| 9 |
+
super(AddPost, self).__init__()
|
| 10 |
+
|
| 11 |
+
self.attributeTypes['topicName'] = 'str'
|
| 12 |
+
self.attributeTypes['userName'] = 'str'
|
| 13 |
+
self.attributeTypes['postText'] = 'str'
|
| 14 |
+
self.attributeTypes['DB'] = 'Database'
|
| 15 |
+
|
| 16 |
+
def __str__(self):
|
| 17 |
+
return "AddPost"
|
| 18 |
+
|
| 19 |
+
def description(self):
|
| 20 |
+
return "Users are able to add posts."
|
| 21 |
+
|
| 22 |
+
def createHTML(self, request, instanceID):
|
| 23 |
+
context = {}
|
| 24 |
+
context['topics'] = Topic.objects.all()
|
| 25 |
+
context['instanceID'] = instanceID
|
| 26 |
+
return TemplateResponse(request, 'addPost.html', context).render()
|
| 27 |
+
|
| 28 |
+
def handleAJAXRequest(self, request, instanceID):
|
| 29 |
+
if request.method == 'POST':
|
| 30 |
+
user = request.user
|
| 31 |
+
if not user.is_active:
|
| 32 |
+
raise Exception
|
| 33 |
+
topicID = request.POST.get('topic')
|
| 34 |
+
topic = Topic.objects.get(id=topicID)
|
| 35 |
+
text = request.POST.get('text')
|
| 36 |
+
|
| 37 |
+
success = self['DB'].addPost(user, topic, text)
|
| 38 |
+
|
| 39 |
+
if success:
|
| 40 |
+
result = {'result': 'success'}
|
| 41 |
+
return JsonResponse(result)
|
| 42 |
+
else:
|
| 43 |
+
raise Exception
|
| 44 |
+
|
| 45 |
+
def execute(self):
|
| 46 |
+
|
| 47 |
+
result = self['DB'].addPost(self['userName'], self['topicName'], self['postText'])
|
| 48 |
+
if result != None:
|
| 49 |
+
return '<div>Add post is successful</div>'
|
| 50 |
+
else:
|
| 51 |
+
return '<div>Add post is unsuccessful</div>'
|
pool/shard003/Python/0027357_locks.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Portable file locking utilities.
|
| 2 |
+
|
| 3 |
+
Based partially on an example by Jonathan Feignberg in the Python
|
| 4 |
+
Cookbook [1] (licensed under the Python Software License) and a ctypes port by
|
| 5 |
+
Anatoly Techtonik for Roundup [2] (license [3]).
|
| 6 |
+
|
| 7 |
+
[1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203
|
| 8 |
+
[2] http://sourceforge.net/p/roundup/code/ci/default/tree/roundup/backends/
|
| 9 |
+
portalocker.py
|
| 10 |
+
[3] http://sourceforge.net/p/roundup/code/ci/default/tree/COPYING.txt
|
| 11 |
+
|
| 12 |
+
Example Usage::
|
| 13 |
+
|
| 14 |
+
>>> from dache.utils.files import locks
|
| 15 |
+
>>> with open('./file', 'wb') as f:
|
| 16 |
+
... locks.lock(f, locks.LOCK_EX)
|
| 17 |
+
... f.write('test')
|
| 18 |
+
"""
|
| 19 |
+
import os
|
| 20 |
+
|
| 21 |
+
__all__ = ('LOCK_EX', 'LOCK_SH', 'LOCK_NB', 'lock', 'unlock')
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _fd(f):
|
| 25 |
+
"""Get a filedescriptor from something which could be a file or an fd."""
|
| 26 |
+
return f.fileno() if hasattr(f, 'fileno') else f
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if os.name == 'nt':
|
| 30 |
+
import msvcrt
|
| 31 |
+
from ctypes import (sizeof, c_ulong, c_void_p, c_int64,
|
| 32 |
+
Structure, Union, POINTER, windll, byref)
|
| 33 |
+
from ctypes.wintypes import BOOL, DWORD, HANDLE
|
| 34 |
+
|
| 35 |
+
LOCK_SH = 0 # the default
|
| 36 |
+
LOCK_NB = 0x1 # LOCKFILE_FAIL_IMMEDIATELY
|
| 37 |
+
LOCK_EX = 0x2 # LOCKFILE_EXCLUSIVE_LOCK
|
| 38 |
+
|
| 39 |
+
# --- Adapted from the pyserial project ---
|
| 40 |
+
# detect size of ULONG_PTR
|
| 41 |
+
if sizeof(c_ulong) != sizeof(c_void_p):
|
| 42 |
+
ULONG_PTR = c_int64
|
| 43 |
+
else:
|
| 44 |
+
ULONG_PTR = c_ulong
|
| 45 |
+
PVOID = c_void_p
|
| 46 |
+
|
| 47 |
+
# --- Union inside Structure by stackoverflow:3480240 ---
|
| 48 |
+
class _OFFSET(Structure):
|
| 49 |
+
_fields_ = [
|
| 50 |
+
('Offset', DWORD),
|
| 51 |
+
('OffsetHigh', DWORD)]
|
| 52 |
+
|
| 53 |
+
class _OFFSET_UNION(Union):
|
| 54 |
+
_anonymous_ = ['_offset']
|
| 55 |
+
_fields_ = [
|
| 56 |
+
('_offset', _OFFSET),
|
| 57 |
+
('Pointer', PVOID)]
|
| 58 |
+
|
| 59 |
+
class OVERLAPPED(Structure):
|
| 60 |
+
_anonymous_ = ['_offset_union']
|
| 61 |
+
_fields_ = [
|
| 62 |
+
('Internal', ULONG_PTR),
|
| 63 |
+
('InternalHigh', ULONG_PTR),
|
| 64 |
+
('_offset_union', _OFFSET_UNION),
|
| 65 |
+
('hEvent', HANDLE)]
|
| 66 |
+
|
| 67 |
+
LPOVERLAPPED = POINTER(OVERLAPPED)
|
| 68 |
+
|
| 69 |
+
# --- Define function prototypes for extra safety ---
|
| 70 |
+
LockFileEx = windll.kernel32.LockFileEx
|
| 71 |
+
LockFileEx.restype = BOOL
|
| 72 |
+
LockFileEx.argtypes = [HANDLE, DWORD, DWORD, DWORD, DWORD, LPOVERLAPPED]
|
| 73 |
+
UnlockFileEx = windll.kernel32.UnlockFileEx
|
| 74 |
+
UnlockFileEx.restype = BOOL
|
| 75 |
+
UnlockFileEx.argtypes = [HANDLE, DWORD, DWORD, DWORD, LPOVERLAPPED]
|
| 76 |
+
|
| 77 |
+
def lock(f, flags):
|
| 78 |
+
hfile = msvcrt.get_osfhandle(_fd(f))
|
| 79 |
+
overlapped = OVERLAPPED()
|
| 80 |
+
ret = LockFileEx(hfile, flags, 0, 0, 0xFFFF0000, byref(overlapped))
|
| 81 |
+
return bool(ret)
|
| 82 |
+
|
| 83 |
+
def unlock(f):
|
| 84 |
+
hfile = msvcrt.get_osfhandle(_fd(f))
|
| 85 |
+
overlapped = OVERLAPPED()
|
| 86 |
+
ret = UnlockFileEx(hfile, 0, 0, 0xFFFF0000, byref(overlapped))
|
| 87 |
+
return bool(ret)
|
| 88 |
+
else:
|
| 89 |
+
try:
|
| 90 |
+
import fcntl
|
| 91 |
+
LOCK_SH = fcntl.LOCK_SH # shared lock
|
| 92 |
+
LOCK_NB = fcntl.LOCK_NB # non-blocking
|
| 93 |
+
LOCK_EX = fcntl.LOCK_EX
|
| 94 |
+
except (ImportError, AttributeError):
|
| 95 |
+
# File locking is not supported.
|
| 96 |
+
LOCK_EX = LOCK_SH = LOCK_NB = 0
|
| 97 |
+
|
| 98 |
+
# Dummy functions that don't do anything.
|
| 99 |
+
def lock(f, flags):
|
| 100 |
+
# File is not locked
|
| 101 |
+
return False
|
| 102 |
+
|
| 103 |
+
def unlock(f):
|
| 104 |
+
# File is unlocked
|
| 105 |
+
return True
|
| 106 |
+
else:
|
| 107 |
+
def lock(f, flags):
|
| 108 |
+
ret = fcntl.flock(_fd(f), flags)
|
| 109 |
+
return (ret == 0)
|
| 110 |
+
|
| 111 |
+
def unlock(f):
|
| 112 |
+
ret = fcntl.flock(_fd(f), fcntl.LOCK_UN)
|
| 113 |
+
return (ret == 0)
|
pool/shard003/Python/0027361_test_upgrade_pool_with_demoted_nodes.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from indy_node.test import waits
|
| 2 |
+
from stp_core.loop.eventually import eventually
|
| 3 |
+
from plenum.common.constants import ALIAS, SERVICES, VERSION
|
| 4 |
+
from indy_common.constants import SCHEDULE
|
| 5 |
+
from indy_node.test.upgrade.helper import ensureUpgradeSent, checkUpgradeScheduled
|
| 6 |
+
|
| 7 |
+
from plenum.test.pool_transactions.helper import updateNodeData
|
| 8 |
+
from plenum.test.conftest import pool_txn_stewards_data, stewards_and_wallets
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_update_with_demoted_node(looper, nodeSet, validUpgrade,
|
| 12 |
+
stewards_and_wallets, trustee, trusteeWallet):
|
| 13 |
+
# demote one node
|
| 14 |
+
node_steward_cl, steward_wallet = stewards_and_wallets[3]
|
| 15 |
+
node_data = {
|
| 16 |
+
ALIAS: nodeSet[3].name,
|
| 17 |
+
SERVICES: []
|
| 18 |
+
}
|
| 19 |
+
updateNodeData(looper, node_steward_cl, steward_wallet, nodeSet[3], node_data)
|
| 20 |
+
|
| 21 |
+
# remove demoted node from upgrade schedule
|
| 22 |
+
upgr = validUpgrade
|
| 23 |
+
del upgr[SCHEDULE][nodeSet[3].id]
|
| 24 |
+
|
| 25 |
+
# send upgrade
|
| 26 |
+
ensureUpgradeSent(looper, trustee, trusteeWallet, upgr)
|
| 27 |
+
|
| 28 |
+
# check upg scheduled
|
| 29 |
+
looper.run(eventually(checkUpgradeScheduled, nodeSet[:3], upgr[VERSION], retryWait=1,
|
| 30 |
+
timeout=waits.expectedUpgradeScheduled()))
|
pool/shard003/Python/0027362_test_model_parallel.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import mxnet as mx
|
| 20 |
+
|
| 21 |
+
def reldiff(a, b):
|
| 22 |
+
diff = np.sum(np.abs(a - b))
|
| 23 |
+
norm = np.sum(np.abs(a))
|
| 24 |
+
if diff == 0:
|
| 25 |
+
return 0
|
| 26 |
+
reldiff = diff / norm
|
| 27 |
+
return reldiff
|
| 28 |
+
|
| 29 |
+
def test_chain():
|
| 30 |
+
ctx1 = mx.cpu(0)
|
| 31 |
+
ctx2 = mx.cpu(1)
|
| 32 |
+
n = 2
|
| 33 |
+
data1 = mx.sym.Variable('data1')
|
| 34 |
+
data2 = mx.sym.Variable('data2')
|
| 35 |
+
data3 = mx.sym.Variable('data3')
|
| 36 |
+
with mx.AttrScope(ctx_group='dev1'):
|
| 37 |
+
net = data1 + data2
|
| 38 |
+
net = net * 3
|
| 39 |
+
|
| 40 |
+
with mx.AttrScope(ctx_group='dev2'):
|
| 41 |
+
net = net + data3
|
| 42 |
+
|
| 43 |
+
arr = []
|
| 44 |
+
arr_grad = []
|
| 45 |
+
shape = (4, 5)
|
| 46 |
+
with mx.Context(ctx1):
|
| 47 |
+
for i in range(n):
|
| 48 |
+
arr.append(mx.nd.empty(shape))
|
| 49 |
+
arr_grad.append(mx.nd.empty(shape))
|
| 50 |
+
with mx.Context(ctx2):
|
| 51 |
+
arr.append(mx.nd.empty(shape))
|
| 52 |
+
arr_grad.append(mx.nd.empty(shape))
|
| 53 |
+
|
| 54 |
+
exec1 = net.bind(ctx1,
|
| 55 |
+
args=arr,
|
| 56 |
+
args_grad=arr_grad,
|
| 57 |
+
group2ctx={'dev1': ctx1, 'dev2': ctx2})
|
| 58 |
+
arr[0][:] = 1.0
|
| 59 |
+
arr[1][:] = 2.0
|
| 60 |
+
arr[2][:] = 3.0
|
| 61 |
+
arr2 = [a.copyto(ctx1) for a in arr]
|
| 62 |
+
arr_grad2 = [a.copyto(ctx1) for a in arr_grad]
|
| 63 |
+
exec2 = net.bind(ctx1,
|
| 64 |
+
args=arr2,
|
| 65 |
+
args_grad=arr_grad2)
|
| 66 |
+
|
| 67 |
+
# Show the execution plan that involves copynode
|
| 68 |
+
print(exec1.debug_str())
|
| 69 |
+
exec1.forward(is_train=True)
|
| 70 |
+
exec2.forward(is_train=True)
|
| 71 |
+
assert reldiff(exec1.outputs[0].asnumpy(), exec2.outputs[0].asnumpy()) < 1e-6
|
| 72 |
+
out_grad = mx.nd.empty(shape, ctx1)
|
| 73 |
+
out_grad[:] = 1.0
|
| 74 |
+
exec1.backward([out_grad])
|
| 75 |
+
exec2.backward([out_grad.copyto(ctx1)])
|
| 76 |
+
for a, b in zip(arr_grad, arr_grad2):
|
| 77 |
+
assert reldiff(a.asnumpy(), b.asnumpy()) < 1e-6
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
if __name__ == '__main__':
|
| 81 |
+
test_chain()
|
pool/shard003/Python/0027363_JSIterator.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class JSListIterator(object):
|
| 2 |
+
def __init__(self, l):
|
| 3 |
+
assert isinstance(l, list)
|
| 4 |
+
self.list = l
|
| 5 |
+
self.index = -1
|
| 6 |
+
self.length = len(self.list)
|
| 7 |
+
if self.length > 0:
|
| 8 |
+
self.index = 0
|
| 9 |
+
|
| 10 |
+
def rewind(self):
|
| 11 |
+
self.index = 0
|
| 12 |
+
|
| 13 |
+
def next(self):
|
| 14 |
+
if self.index >= len(self.list):
|
| 15 |
+
return None
|
| 16 |
+
val = self.get(self.index)
|
| 17 |
+
self.index += 1
|
| 18 |
+
return val
|
| 19 |
+
|
| 20 |
+
def prev(self):
|
| 21 |
+
if self.index == -1:
|
| 22 |
+
raise IndexError()
|
| 23 |
+
self.index -= 1
|
| 24 |
+
|
| 25 |
+
def get(self, index = None):
|
| 26 |
+
if index == None:
|
| 27 |
+
index = self.index
|
| 28 |
+
return self.list[index]
|
| 29 |
+
|
| 30 |
+
def refresh(self):
|
| 31 |
+
self.length = len(self.list)
|
pool/shard003/Python/0027365_demo_print_region.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Example how to read and print regions.
|
| 2 |
+
"""
|
| 3 |
+
from astropy.io.fits import Header
|
| 4 |
+
import pyregion
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def print_shape_list(shape_list):
|
| 8 |
+
for idx, shape in enumerate(shape_list, start=1):
|
| 9 |
+
print("[region %d]" % idx)
|
| 10 |
+
print()
|
| 11 |
+
print("%s; %s(%s)" % (shape.coord_format,
|
| 12 |
+
shape.name,
|
| 13 |
+
", ".join([str(s) for s in shape.coord_list])))
|
| 14 |
+
|
| 15 |
+
print(shape.attr[0])
|
| 16 |
+
print(", ".join(["%s=%s" % (k, v.strip()) for k, v in list(shape.attr[1].items())]))
|
| 17 |
+
print()
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if __name__ == "__main__":
|
| 21 |
+
print("** coordinate in FK5 **")
|
| 22 |
+
print()
|
| 23 |
+
filename = "test01_print.reg"
|
| 24 |
+
# filename = "test_text.reg"
|
| 25 |
+
# filename = "test01.reg"
|
| 26 |
+
shape_list = pyregion.open(filename)
|
| 27 |
+
print_shape_list(shape_list)
|
| 28 |
+
|
| 29 |
+
print()
|
| 30 |
+
print()
|
| 31 |
+
print("** coordinate in image **")
|
| 32 |
+
print()
|
| 33 |
+
header = Header.fromtextfile("test.header")
|
| 34 |
+
shape_list2 = shape_list.as_imagecoord(header=header)
|
| 35 |
+
print_shape_list(shape_list2)
|
pool/shard003/Python/0027380_zbx_trigger.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
'''
|
| 3 |
+
ansible module for zabbix triggers
|
| 4 |
+
'''
|
| 5 |
+
# vim: expandtab:tabstop=4:shiftwidth=4
|
| 6 |
+
#
|
| 7 |
+
# Zabbix trigger ansible module
|
| 8 |
+
#
|
| 9 |
+
#
|
| 10 |
+
# Copyright 2015 Red Hat Inc.
|
| 11 |
+
#
|
| 12 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 13 |
+
# you may not use this file except in compliance with the License.
|
| 14 |
+
# You may obtain a copy of the License at
|
| 15 |
+
#
|
| 16 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 17 |
+
#
|
| 18 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 19 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 20 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 21 |
+
# See the License for the specific language governing permissions and
|
| 22 |
+
# limitations under the License.
|
| 23 |
+
#
|
| 24 |
+
|
| 25 |
+
# This is in place because each module looks similar to each other.
|
| 26 |
+
# These need duplicate code as their behavior is very similar
|
| 27 |
+
# but different for each zabbix class.
|
| 28 |
+
# pylint: disable=duplicate-code
|
| 29 |
+
|
| 30 |
+
# pylint: disable=import-error
|
| 31 |
+
from openshift_tools.zbxapi import ZabbixAPI, ZabbixConnection
|
| 32 |
+
|
| 33 |
+
def exists(content, key='result'):
|
| 34 |
+
''' Check if key exists in content or the size of content[key] > 0
|
| 35 |
+
'''
|
| 36 |
+
if not content.has_key(key):
|
| 37 |
+
return False
|
| 38 |
+
|
| 39 |
+
if not content[key]:
|
| 40 |
+
return False
|
| 41 |
+
|
| 42 |
+
return True
|
| 43 |
+
|
| 44 |
+
def get_priority(priority):
|
| 45 |
+
''' determine priority
|
| 46 |
+
'''
|
| 47 |
+
prior = 0
|
| 48 |
+
if 'info' in priority:
|
| 49 |
+
prior = 1
|
| 50 |
+
elif 'warn' in priority:
|
| 51 |
+
prior = 2
|
| 52 |
+
elif 'avg' == priority or 'ave' in priority:
|
| 53 |
+
prior = 3
|
| 54 |
+
elif 'high' in priority:
|
| 55 |
+
prior = 4
|
| 56 |
+
elif 'dis' in priority:
|
| 57 |
+
prior = 5
|
| 58 |
+
|
| 59 |
+
return prior
|
| 60 |
+
|
| 61 |
+
def get_deps(zapi, deps):
|
| 62 |
+
''' get trigger dependencies
|
| 63 |
+
'''
|
| 64 |
+
results = []
|
| 65 |
+
for desc in deps:
|
| 66 |
+
content = zapi.get_content('trigger',
|
| 67 |
+
'get',
|
| 68 |
+
{'filter': {'description': desc},
|
| 69 |
+
'expandExpression': True,
|
| 70 |
+
'selectDependencies': 'triggerid',
|
| 71 |
+
})
|
| 72 |
+
if content.has_key('result'):
|
| 73 |
+
results.append({'triggerid': content['result'][0]['triggerid']})
|
| 74 |
+
|
| 75 |
+
return results
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def get_trigger_status(inc_status):
|
| 79 |
+
''' Determine the trigger's status
|
| 80 |
+
0 is enabled
|
| 81 |
+
1 is disabled
|
| 82 |
+
'''
|
| 83 |
+
r_status = 0
|
| 84 |
+
if inc_status == 'disabled':
|
| 85 |
+
r_status = 1
|
| 86 |
+
|
| 87 |
+
return r_status
|
| 88 |
+
|
| 89 |
+
def get_template_id(zapi, template_name):
|
| 90 |
+
'''
|
| 91 |
+
get related templates
|
| 92 |
+
'''
|
| 93 |
+
template_ids = []
|
| 94 |
+
app_ids = {}
|
| 95 |
+
# Fetch templates by name
|
| 96 |
+
content = zapi.get_content('template',
|
| 97 |
+
'get',
|
| 98 |
+
{'search': {'host': template_name},
|
| 99 |
+
'selectApplications': ['applicationid', 'name']})
|
| 100 |
+
if content.has_key('result'):
|
| 101 |
+
template_ids.append(content['result'][0]['templateid'])
|
| 102 |
+
for app in content['result'][0]['applications']:
|
| 103 |
+
app_ids[app['name']] = app['applicationid']
|
| 104 |
+
|
| 105 |
+
return template_ids, app_ids
|
| 106 |
+
|
| 107 |
+
def main():
|
| 108 |
+
'''
|
| 109 |
+
Create a trigger in zabbix
|
| 110 |
+
|
| 111 |
+
Example:
|
| 112 |
+
"params": {
|
| 113 |
+
"description": "Processor load is too high on {HOST.NAME}",
|
| 114 |
+
"expression": "{Linux server:system.cpu.load[percpu,avg1].last()}>5",
|
| 115 |
+
"dependencies": [
|
| 116 |
+
{
|
| 117 |
+
"triggerid": "14062"
|
| 118 |
+
}
|
| 119 |
+
]
|
| 120 |
+
},
|
| 121 |
+
|
| 122 |
+
'''
|
| 123 |
+
|
| 124 |
+
module = AnsibleModule(
|
| 125 |
+
argument_spec=dict(
|
| 126 |
+
zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
|
| 127 |
+
zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'),
|
| 128 |
+
zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'),
|
| 129 |
+
zbx_debug=dict(default=False, type='bool'),
|
| 130 |
+
expression=dict(default=None, type='str'),
|
| 131 |
+
name=dict(default=None, type='str'),
|
| 132 |
+
description=dict(default=None, type='str'),
|
| 133 |
+
dependencies=dict(default=[], type='list'),
|
| 134 |
+
priority=dict(default='avg', type='str'),
|
| 135 |
+
url=dict(default=None, type='str'),
|
| 136 |
+
status=dict(default=None, type='str'),
|
| 137 |
+
state=dict(default='present', type='str'),
|
| 138 |
+
template_name=dict(default=None, type='str'),
|
| 139 |
+
hostgroup_name=dict(default=None, type='str'),
|
| 140 |
+
query_type=dict(default='filter', choices=['filter', 'search'], type='str'),
|
| 141 |
+
),
|
| 142 |
+
#supports_check_mode=True
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'],
|
| 146 |
+
module.params['zbx_user'],
|
| 147 |
+
module.params['zbx_password'],
|
| 148 |
+
module.params['zbx_debug']))
|
| 149 |
+
|
| 150 |
+
#Set the instance and the template for the rest of the calls
|
| 151 |
+
zbx_class_name = 'trigger'
|
| 152 |
+
idname = "triggerid"
|
| 153 |
+
state = module.params['state']
|
| 154 |
+
tname = module.params['name']
|
| 155 |
+
|
| 156 |
+
templateid = None
|
| 157 |
+
if module.params['template_name']:
|
| 158 |
+
templateid, _ = get_template_id(zapi, module.params['template_name'])
|
| 159 |
+
|
| 160 |
+
content = zapi.get_content(zbx_class_name,
|
| 161 |
+
'get',
|
| 162 |
+
{module.params['query_type']: {'description': tname},
|
| 163 |
+
'expandExpression': True,
|
| 164 |
+
'selectDependencies': 'triggerid',
|
| 165 |
+
'templateids': templateid,
|
| 166 |
+
'group': module.params['hostgroup_name'],
|
| 167 |
+
})
|
| 168 |
+
|
| 169 |
+
# Get
|
| 170 |
+
if state == 'list':
|
| 171 |
+
module.exit_json(changed=False, results=content['result'], state="list")
|
| 172 |
+
|
| 173 |
+
# Delete
|
| 174 |
+
if state == 'absent':
|
| 175 |
+
if not exists(content):
|
| 176 |
+
module.exit_json(changed=False, state="absent")
|
| 177 |
+
content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]])
|
| 178 |
+
module.exit_json(changed=True, results=content['result'], state="absent")
|
| 179 |
+
|
| 180 |
+
# Create and Update
|
| 181 |
+
if state == 'present':
|
| 182 |
+
params = {'description': tname,
|
| 183 |
+
'comments': module.params['description'],
|
| 184 |
+
'expression': module.params['expression'],
|
| 185 |
+
'dependencies': get_deps(zapi, module.params['dependencies']),
|
| 186 |
+
'priority': get_priority(module.params['priority']),
|
| 187 |
+
'url': module.params['url'],
|
| 188 |
+
'status': get_trigger_status(module.params['status']),
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
# Remove any None valued params
|
| 192 |
+
_ = [params.pop(key, None) for key in params.keys() if params[key] is None]
|
| 193 |
+
|
| 194 |
+
#******#
|
| 195 |
+
# CREATE
|
| 196 |
+
#******#
|
| 197 |
+
if not exists(content):
|
| 198 |
+
# if we didn't find it, create it
|
| 199 |
+
content = zapi.get_content(zbx_class_name, 'create', params)
|
| 200 |
+
|
| 201 |
+
if content.has_key('error'):
|
| 202 |
+
module.exit_json(failed=True, changed=True, results=content['error'], state="present")
|
| 203 |
+
|
| 204 |
+
module.exit_json(changed=True, results=content['result'], state='present')
|
| 205 |
+
|
| 206 |
+
########
|
| 207 |
+
# UPDATE
|
| 208 |
+
########
|
| 209 |
+
differences = {}
|
| 210 |
+
zab_results = content['result'][0]
|
| 211 |
+
for key, value in params.items():
|
| 212 |
+
|
| 213 |
+
if zab_results[key] != value and zab_results[key] != str(value):
|
| 214 |
+
differences[key] = value
|
| 215 |
+
|
| 216 |
+
if not differences:
|
| 217 |
+
module.exit_json(changed=False, results=zab_results, state="present")
|
| 218 |
+
|
| 219 |
+
# We have differences and need to update
|
| 220 |
+
differences[idname] = zab_results[idname]
|
| 221 |
+
content = zapi.get_content(zbx_class_name, 'update', differences)
|
| 222 |
+
module.exit_json(changed=True, results=content['result'], state="present")
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
module.exit_json(failed=True,
|
| 226 |
+
changed=False,
|
| 227 |
+
results='Unknown state passed. %s' % state,
|
| 228 |
+
state="unknown")
|
| 229 |
+
|
| 230 |
+
# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
|
| 231 |
+
# import module snippets. This are required
|
| 232 |
+
from ansible.module_utils.basic import *
|
| 233 |
+
|
| 234 |
+
main()
|
pool/shard003/Python/0027382_dumpcsv.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) 2013, Roberto Riggio
|
| 4 |
+
# All rights reserved.
|
| 5 |
+
#
|
| 6 |
+
# Redistribution and use in source and binary forms, with or without
|
| 7 |
+
# modification, are permitted provided that the following conditions are met:
|
| 8 |
+
# * Redistributions of source code must retain the above copyright
|
| 9 |
+
# notice, this list of conditions and the following disclaimer.
|
| 10 |
+
# * Redistributions in binary form must reproduce the above copyright
|
| 11 |
+
# notice, this list of conditions and the following disclaimer in the
|
| 12 |
+
# documentation and/or other materials provided with the distribution.
|
| 13 |
+
# * Neither the name of the CREATE-NET nor the
|
| 14 |
+
# names of its contributors may be used to endorse or promote products
|
| 15 |
+
# derived from this software without specific prior written permission.
|
| 16 |
+
#
|
| 17 |
+
# THIS SOFTWARE IS PROVIDED BY CREATE-NET ''AS IS'' AND ANY
|
| 18 |
+
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
| 19 |
+
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 20 |
+
# DISCLAIMED. IN NO EVENT SHALL CREATE-NET BE LIABLE FOR ANY
|
| 21 |
+
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
| 22 |
+
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
| 23 |
+
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
| 24 |
+
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
| 25 |
+
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
| 26 |
+
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 27 |
+
|
| 28 |
+
"""
|
| 29 |
+
Joule Dump CSV. The dumpcsv commands outputs the content of a Joule descriptor
|
| 30 |
+
to CSV format. Noticice that the Joule descriptor must be the one saved by the
|
| 31 |
+
Joule profiler, i.e. it must contain the power consumption statistics. The csv
|
| 32 |
+
is printed to the standard output.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
import os
|
| 36 |
+
import json
|
| 37 |
+
import optparse
|
| 38 |
+
|
| 39 |
+
DEFAULT_JOULE = './joule.json'
|
| 40 |
+
|
| 41 |
+
def main():
|
| 42 |
+
""" Dump Joule file descriptor as csv. """
|
| 43 |
+
|
| 44 |
+
parser = optparse.OptionParser()
|
| 45 |
+
|
| 46 |
+
parser.add_option('--joule', '-j', dest="joule", default=DEFAULT_JOULE)
|
| 47 |
+
parser.add_option('--byrate', '-r',
|
| 48 |
+
action="store_true",
|
| 49 |
+
dest="byrate",
|
| 50 |
+
default=False)
|
| 51 |
+
|
| 52 |
+
options, _ = parser.parse_args()
|
| 53 |
+
|
| 54 |
+
with open(os.path.expanduser(options.joule)) as data_file:
|
| 55 |
+
data = json.load(data_file)
|
| 56 |
+
|
| 57 |
+
pairs = {}
|
| 58 |
+
|
| 59 |
+
for stint in data['stints']:
|
| 60 |
+
|
| 61 |
+
probe_ids = (stint['src'], stint['dst'])
|
| 62 |
+
|
| 63 |
+
if not probe_ids in pairs:
|
| 64 |
+
pairs[probe_ids] = []
|
| 65 |
+
|
| 66 |
+
run = [stint['bitrate_mbps'],
|
| 67 |
+
stint['packetsize_bytes'],
|
| 68 |
+
stint['stats']['losses'],
|
| 69 |
+
stint['stats']['median'],
|
| 70 |
+
stint['stats']['mean']]
|
| 71 |
+
|
| 72 |
+
pairs[probe_ids].append(run)
|
| 73 |
+
|
| 74 |
+
for entry in pairs:
|
| 75 |
+
|
| 76 |
+
print("# %s -> %s" % (data['probes'][entry[0]]['ip'],
|
| 77 |
+
data['probes'][entry[1]]['ip']))
|
| 78 |
+
|
| 79 |
+
print("# bitrate, length, loss, median power, mean power")
|
| 80 |
+
|
| 81 |
+
if options.byrate:
|
| 82 |
+
|
| 83 |
+
sorted_pairs = sorted(pairs[entry],
|
| 84 |
+
key=lambda d: (d[1], d[0]),
|
| 85 |
+
reverse=False)
|
| 86 |
+
|
| 87 |
+
else:
|
| 88 |
+
|
| 89 |
+
sorted_pairs = sorted(pairs[entry],
|
| 90 |
+
key=lambda d: (d[0], d[1]),
|
| 91 |
+
reverse=False)
|
| 92 |
+
|
| 93 |
+
pairs_str = ["%f;%f;%f;%f;%f" % tuple(line) for line in sorted_pairs]
|
| 94 |
+
print("\n".join(pairs_str))
|
| 95 |
+
|
| 96 |
+
if __name__ == "__main__":
|
| 97 |
+
main()
|
pool/shard003/Python/0027388_openclose_h2.test.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
'''
|
| 3 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 4 |
+
# or more contributor license agreements. See the NOTICE file
|
| 5 |
+
# distributed with this work for additional information
|
| 6 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 7 |
+
# to you under the Apache License, Version 2.0 (the
|
| 8 |
+
# "License"); you may not use this file except in compliance
|
| 9 |
+
# with the License. You may obtain a copy of the License at
|
| 10 |
+
#
|
| 11 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 12 |
+
#
|
| 13 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 14 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 15 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 16 |
+
# See the License for the specific language governing permissions and
|
| 17 |
+
# limitations under the License.
|
| 18 |
+
|
| 19 |
+
import os
|
| 20 |
+
import subprocess
|
| 21 |
+
Test.Summary = '''
|
| 22 |
+
Test transactions and sessions over http2, making sure they open and close in the proper order.
|
| 23 |
+
'''
|
| 24 |
+
|
| 25 |
+
Test.SkipUnless(
|
| 26 |
+
Condition.HasCurlFeature('http2')
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# Define default ATS. Disable the cache to simplify the test.
|
| 30 |
+
ts = Test.MakeATSProcess("ts", select_ports=True, enable_tls=True, command="traffic_manager", enable_cache=False)
|
| 31 |
+
|
| 32 |
+
server = Test.MakeOriginServer("server")
|
| 33 |
+
server2 = Test.MakeOriginServer("server2")
|
| 34 |
+
|
| 35 |
+
Test.testName = ""
|
| 36 |
+
request_header = {"headers": "GET / HTTP/1.1\r\nHost: oc.test\r\n\r\n",
|
| 37 |
+
"timestamp": "1469733493.993", "body": ""}
|
| 38 |
+
# expected response from the origin server
|
| 39 |
+
response_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length:0\r\n\r\n",
|
| 40 |
+
"timestamp": "1469733493.993", "body": ""}
|
| 41 |
+
|
| 42 |
+
# add ssl materials like key, certificates for the server
|
| 43 |
+
ts.addDefaultSSLFiles()
|
| 44 |
+
|
| 45 |
+
Test.PrepareTestPlugin(os.path.join(Test.Variables.AtsTestPluginsDir,
|
| 46 |
+
'ssntxnorder_verify.so'), ts)
|
| 47 |
+
|
| 48 |
+
# add response to the server dictionary
|
| 49 |
+
server.addResponse("sessionfile.log", request_header, response_header)
|
| 50 |
+
ts.Disk.records_config.update({
|
| 51 |
+
'proxy.config.http2.zombie_debug_timeout_in': 10,
|
| 52 |
+
'proxy.config.diags.debug.enabled': 0,
|
| 53 |
+
'proxy.config.diags.debug.tags': 'ssntxnorder_verify',
|
| 54 |
+
'proxy.config.cache.enable_read_while_writer': 0,
|
| 55 |
+
'proxy.config.ssl.server.cert.path': '{0}'.format(ts.Variables.SSLDir),
|
| 56 |
+
'proxy.config.ssl.server.private_key.path': '{0}'.format(ts.Variables.SSLDir),
|
| 57 |
+
})
|
| 58 |
+
|
| 59 |
+
ts.Disk.remap_config.AddLine(
|
| 60 |
+
'map https://oc.test:{0} http://127.0.0.1:{1}'.format(
|
| 61 |
+
ts.Variables.ssl_port, server.Variables.Port)
|
| 62 |
+
)
|
| 63 |
+
ts.Disk.ssl_multicert_config.AddLine(
|
| 64 |
+
'dest_ip=* ssl_cert_name=server.pem ssl_key_name=server.key'
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
cmd = 'curl -k --resolve oc.test:{0}:127.0.0.1 --http2 https://oc.test:{0}'.format(ts.Variables.ssl_port)
|
| 68 |
+
numberOfRequests = 100
|
| 69 |
+
|
| 70 |
+
tr = Test.AddTestRun()
|
| 71 |
+
# Create a bunch of curl commands to be executed in parallel. Default.Process is set in SpawnCommands.
|
| 72 |
+
# On Fedora 28/29, it seems that curl will occaisionally timeout after a couple seconds and return exitcode 2
|
| 73 |
+
# Examinig the packet capture shows that Traffic Server dutifully sends the response
|
| 74 |
+
ps = tr.SpawnCommands(cmdstr=cmd, count=numberOfRequests, retcode=Any(0, 2))
|
| 75 |
+
tr.Processes.Default.Env = ts.Env
|
| 76 |
+
tr.Processes.Default.ReturnCode = Any(0, 2)
|
| 77 |
+
|
| 78 |
+
# Execution order is: ts/server, ps(curl cmds), Default Process.
|
| 79 |
+
tr.Processes.Default.StartBefore(
|
| 80 |
+
server, ready=When.PortOpen(server.Variables.Port))
|
| 81 |
+
tr.Processes.Default.StartBefore(Test.Processes.ts)
|
| 82 |
+
# Don't know why we need both the start before and the start after
|
| 83 |
+
ts.StartAfter(*ps)
|
| 84 |
+
server.StartAfter(*ps)
|
| 85 |
+
tr.StillRunningAfter = ts
|
| 86 |
+
|
| 87 |
+
# Signal that all the curl processes have completed
|
| 88 |
+
tr = Test.AddTestRun("Curl Done")
|
| 89 |
+
tr.DelayStart = 2 # Delaying a couple seconds to make sure the global continuation's lock contention resolves.
|
| 90 |
+
tr.Processes.Default.Command = "traffic_ctl plugin msg done done"
|
| 91 |
+
tr.Processes.Default.ReturnCode = 0
|
| 92 |
+
tr.Processes.Default.Env = ts.Env
|
| 93 |
+
tr.StillRunningAfter = ts
|
| 94 |
+
|
| 95 |
+
# Parking this as a ready tester on a meaningless process
|
| 96 |
+
# To stall the test runs that check for the stats until the
|
| 97 |
+
# stats have propagated and are ready to read.
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def make_done_stat_ready(tsenv):
|
| 101 |
+
def done_stat_ready(process, hasRunFor, **kw):
|
| 102 |
+
retval = subprocess.run("traffic_ctl metric get ssntxnorder_verify.test.done > done 2> /dev/null", shell=True, env=tsenv)
|
| 103 |
+
if retval.returncode == 0:
|
| 104 |
+
retval = subprocess.run("grep 1 done > /dev/null", shell=True, env=tsenv)
|
| 105 |
+
return retval.returncode == 0
|
| 106 |
+
|
| 107 |
+
return done_stat_ready
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# number of sessions/transactions opened and closed are equal
|
| 111 |
+
tr = Test.AddTestRun("Check Ssn order errors")
|
| 112 |
+
server2.StartupTimeout = 60
|
| 113 |
+
# Again, here the imporant thing is the ready function not the server2 process
|
| 114 |
+
tr.Processes.Default.StartBefore(server2, ready=make_done_stat_ready(ts.Env))
|
| 115 |
+
tr.Processes.Default.Command = 'traffic_ctl metric get ssntxnorder_verify.err'
|
| 116 |
+
tr.Processes.Default.ReturnCode = 0
|
| 117 |
+
tr.Processes.Default.Env = ts.Env
|
| 118 |
+
tr.Processes.Default.Streams.All = Testers.ContainsExpression(
|
| 119 |
+
'ssntxnorder_verify.err 0', 'incorrect statistic return, or possible error.')
|
| 120 |
+
tr.StillRunningAfter = ts
|
| 121 |
+
tr.StillRunningAfter = server
|
| 122 |
+
|
| 123 |
+
comparator_command = '''
|
| 124 |
+
if test "`traffic_ctl metric get ssntxnorder_verify.{0}.start | cut -d ' ' -f 2`" -eq "`traffic_ctl metric get ssntxnorder_verify.{0}.close | cut -d ' ' -f 2`" ; then\
|
| 125 |
+
echo yes;\
|
| 126 |
+
else \
|
| 127 |
+
echo no; \
|
| 128 |
+
fi; \
|
| 129 |
+
traffic_ctl metric match ssntxnorder_verify
|
| 130 |
+
'''
|
| 131 |
+
|
| 132 |
+
# number of sessions/transactions opened and closed are equal
|
| 133 |
+
tr = Test.AddTestRun("Check for ssn open/close")
|
| 134 |
+
tr.Processes.Default.Command = comparator_command.format('ssn')
|
| 135 |
+
tr.Processes.Default.ReturnCode = 0
|
| 136 |
+
tr.Processes.Default.Env = ts.Env
|
| 137 |
+
tr.Processes.Default.Streams.stdout = Testers.ContainsExpression(
|
| 138 |
+
"yes", 'should verify contents')
|
| 139 |
+
tr.Processes.Default.Streams.stdout += Testers.ExcludesExpression(
|
| 140 |
+
"ssntxnorder_verify.ssn.start 0", 'should be nonzero')
|
| 141 |
+
tr.StillRunningAfter = ts
|
| 142 |
+
tr.StillRunningAfter = server
|
| 143 |
+
|
| 144 |
+
tr = Test.AddTestRun("Check for txn/open/close")
|
| 145 |
+
tr.Processes.Default.Command = comparator_command.format('txn')
|
| 146 |
+
tr.Processes.Default.ReturnCode = 0
|
| 147 |
+
tr.Processes.Default.Env = ts.Env
|
| 148 |
+
tr.Processes.Default.Streams.stdout = Testers.ContainsExpression(
|
| 149 |
+
"yes", 'should verify contents')
|
| 150 |
+
tr.Processes.Default.Streams.stdout += Testers.ExcludesExpression(
|
| 151 |
+
"ssntxnorder_verify.txn.start 0", 'should be nonzero')
|
| 152 |
+
# and we receive the same number of transactions as we asked it to make
|
| 153 |
+
tr.Processes.Default.Streams.stdout += Testers.ContainsExpression(
|
| 154 |
+
"ssntxnorder_verify.txn.start {}".format(numberOfRequests), 'should be the number of transactions we made')
|
| 155 |
+
tr.StillRunningAfter = ts
|
| 156 |
+
tr.StillRunningAfter = server
|
pool/shard003/Python/0027393_fixtures.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pytest
|
| 3 |
+
import hydra_base
|
| 4 |
+
from hydra_base import JSONObject
|
| 5 |
+
from hydra_pywr.importer import PywrHydraImporter
|
| 6 |
+
from hydra_pywr.template import pywr_template_name, register_template
|
| 7 |
+
from hydra_client.connection import JSONConnection
|
| 8 |
+
from hydra_base_fixtures import testdb_uri
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@pytest.fixture()
|
| 12 |
+
def client(testdb_uri):
|
| 13 |
+
return JSONConnection(app_name="Test Pywr application.", db_url=testdb_uri)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@pytest.fixture()
|
| 17 |
+
def logged_in_client(client):
|
| 18 |
+
root_user_id = client.login('root', '')
|
| 19 |
+
return client
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@pytest.fixture()
|
| 23 |
+
def model_directory():
|
| 24 |
+
return os.path.join(os.path.dirname(__file__), 'models')
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@pytest.fixture()
|
| 28 |
+
def simple1(model_directory):
|
| 29 |
+
return os.path.join(model_directory, 'simple1.json')
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@pytest.fixture(params=[
|
| 33 |
+
'simple1.json',
|
| 34 |
+
'reservoir2.json',
|
| 35 |
+
'parameter_reference.json',
|
| 36 |
+
'hydra_generated.json'
|
| 37 |
+
])
|
| 38 |
+
def pywr_json_filename(request, model_directory):
|
| 39 |
+
return os.path.join(model_directory, request.param)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@pytest.fixture()
|
| 43 |
+
def session_with_pywr_network(pywr_json_filename, session_with_pywr_template, projectmaker, root_user_id):
|
| 44 |
+
project = projectmaker.create()
|
| 45 |
+
|
| 46 |
+
template = JSONObject(hydra_base.get_template_by_name(pywr_template_name('Full')))
|
| 47 |
+
|
| 48 |
+
importer = PywrHydraImporter(pywr_json_filename, template)
|
| 49 |
+
|
| 50 |
+
# First the attributes must be added.
|
| 51 |
+
attributes = [JSONObject(a) for a in importer.add_attributes_request_data()]
|
| 52 |
+
|
| 53 |
+
# The response attributes have ids now.
|
| 54 |
+
response_attributes = hydra_base.add_attributes(attributes)
|
| 55 |
+
|
| 56 |
+
# Convert to a simple dict for local processing.
|
| 57 |
+
attribute_ids = {a.name: a.id for a in response_attributes}
|
| 58 |
+
|
| 59 |
+
# Now we try to create the network
|
| 60 |
+
network = importer.add_network_request_data(attribute_ids, project.id)
|
| 61 |
+
hydra_network = hydra_base.add_network(JSONObject(network), user_id=root_user_id)
|
| 62 |
+
|
| 63 |
+
return hydra_network.id, pywr_json_filename
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@pytest.fixture()
|
| 67 |
+
def db_with_template(db_with_users, logged_in_client):
|
| 68 |
+
register_template(logged_in_client)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@pytest.fixture()
|
| 72 |
+
def db_with_pywr_network(pywr_json_filename, db_with_template, projectmaker, logged_in_client):
|
| 73 |
+
client = logged_in_client
|
| 74 |
+
|
| 75 |
+
project = projectmaker.create()
|
| 76 |
+
|
| 77 |
+
importer = PywrHydraImporter.from_client(client, pywr_json_filename, 'Full')
|
| 78 |
+
network_id, scenario_id = importer.import_data(client, project.id)
|
| 79 |
+
|
| 80 |
+
return network_id, scenario_id, pywr_json_filename
|
| 81 |
+
|
pool/shard003/Python/0027394_write_nwchem.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
|
| 3 |
+
def dft(dihedrals):
|
| 4 |
+
"""Writes dft calculations for nwchem. This is wrong. Uses dihedrals. Runs
|
| 5 |
+
|
| 6 |
+
Keyword Arguments:
|
| 7 |
+
dihedrals - The list of dihedrals to generate a nwchem output from. If the dihedral is marked as dft it will run
|
| 8 |
+
"""
|
| 9 |
+
dftfile = open('outputs/dft.nw','w')
|
| 10 |
+
sys.stdout = dftfile
|
| 11 |
+
|
| 12 |
+
print 'title "SMDPPEH with displacement: 04.00 Angstroms"\n'
|
| 13 |
+
counter = "A"
|
| 14 |
+
for i in range(len(dihedrals)):
|
| 15 |
+
if dihedrals[i].dft:
|
| 16 |
+
print 'geometry mol%s units angstroms noautoz noautosym' % counter
|
| 17 |
+
print "%s %s %s %s" % (dihedrals[i].dihedral_master1.atom_type,dihedrals[i].dihedral_master1.x_pos,dihedrals[i].dihedral_master1.y_pos,dihedrals[i].dihedral_master1.z_pos)
|
| 18 |
+
print "%s %s %s %s" % (dihedrals[i].dihedral_master2.atom_type,dihedrals[i].dihedral_master2.x_pos,dihedrals[i].dihedral_master2.y_pos,dihedrals[i].dihedral_master2.z_pos)
|
| 19 |
+
print "%s %s %s %s" % (dihedrals[i].dihedral_slave1.atom_type,dihedrals[i].dihedral_slave1.x_pos,dihedrals[i].dihedral_slave1.y_pos,dihedrals[i].dihedral_slave1.z_pos)
|
| 20 |
+
print "%s %s %s %s" % (dihedrals[i].dihedral_slave2.atom_type,dihedrals[i].dihedral_slave2.x_pos,dihedrals[i].dihedral_slave2.y_pos,dihedrals[i].dihedral_slave2.z_pos)
|
| 21 |
+
print "end\n"
|
| 22 |
+
counter = chr(ord(counter)+1)
|
| 23 |
+
|
| 24 |
+
print "basis"
|
| 25 |
+
print " * library 6-31++G*"
|
| 26 |
+
print "end\n"
|
| 27 |
+
|
| 28 |
+
counter = "A"
|
| 29 |
+
for i in range(len(dihedrals)):
|
| 30 |
+
if dihedrals[i].dft:
|
| 31 |
+
print "set geometry mol%s" % counter
|
| 32 |
+
print "dft"
|
| 33 |
+
print " cdft 1 60 charge -1"
|
| 34 |
+
print "end\n"
|
| 35 |
+
print "task dft ignore\n"
|
| 36 |
+
counter = chr(ord(counter)+1)
|
| 37 |
+
dftfile.close()
|
pool/shard003/Python/0027398_eyes.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unreal_engine as ue
|
| 2 |
+
|
| 3 |
+
from unreal_engine.classes import SceneCaptureComponent2D, PyHUD
|
| 4 |
+
from unreal_engine.enums import ESceneCaptureSource
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
import cv2
|
| 9 |
+
import numpy
|
| 10 |
+
|
| 11 |
+
class Sight:
|
| 12 |
+
|
| 13 |
+
def __init__(self):
|
| 14 |
+
self.what_i_am_seeing = ue.create_transient_texture_render_target2d(512, 512)
|
| 15 |
+
|
| 16 |
+
def pre_initialize_components(self):
|
| 17 |
+
# add a new root component (a SceneCaptureComponent2D one)
|
| 18 |
+
self.scene_capturer = self.uobject.add_actor_root_component(SceneCaptureComponent2D, 'Scene Capture')
|
| 19 |
+
# use the previously created texture as the render target
|
| 20 |
+
self.scene_capturer.TextureTarget = self.what_i_am_seeing
|
| 21 |
+
# store pixels as linear colors (non HDR)
|
| 22 |
+
self.scene_capturer.CaptureSource = ESceneCaptureSource.SCS_FinalColorLDR
|
| 23 |
+
|
| 24 |
+
def begin_play(self):
|
| 25 |
+
# get a reference to the pawn currently controlled by the player
|
| 26 |
+
mannequin = self.uobject.get_player_pawn()
|
| 27 |
+
# attach myself to the 'head' bone of the mannequin Mesh component
|
| 28 |
+
self.uobject.attach_to_component(mannequin.Mesh, 'head')
|
| 29 |
+
|
| 30 |
+
# spawn a new HUD (well, a PyHUD)
|
| 31 |
+
hud = self.uobject.actor_spawn(PyHUD, PythonModule='hud', PythonClass='FacesDetector')
|
| 32 |
+
# get a reference to its proxy class
|
| 33 |
+
self.py_hud = hud.get_py_proxy()
|
| 34 |
+
|
| 35 |
+
# set the texture to draw
|
| 36 |
+
self.py_hud.texture_to_draw = self.what_i_am_seeing
|
| 37 |
+
|
| 38 |
+
# use this new HUD as the player default one (so the engine will start drawing it)
|
| 39 |
+
self.uobject.set_player_hud(hud)
|
| 40 |
+
|
| 41 |
+
def tick(self, delta_time):
|
| 42 |
+
# read raw data from the render target
|
| 43 |
+
data = self.what_i_am_seeing.render_target_get_data()
|
| 44 |
+
# convert them to a numpy array with the format expected by OpenCV
|
| 45 |
+
npy_data = numpy.frombuffer(data, dtype=numpy.uint8).reshape(512, 512, 4)
|
| 46 |
+
self.py_hud.gray_data = cv2.cvtColor(npy_data, cv2.COLOR_BGRA2GRAY)
|
pool/shard003/Python/0027400_test_real_browser.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2015 Vladimir Rutsky <vladimir@rutsky.org>
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""System test using real browser.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
import json
|
| 20 |
+
import asyncio
|
| 21 |
+
import socket
|
| 22 |
+
import pathlib
|
| 23 |
+
import logging
|
| 24 |
+
import webbrowser
|
| 25 |
+
|
| 26 |
+
from aiohttp import web, hdrs
|
| 27 |
+
import pytest
|
| 28 |
+
|
| 29 |
+
import selenium.common.exceptions
|
| 30 |
+
from selenium import webdriver
|
| 31 |
+
from selenium.webdriver.support.ui import WebDriverWait
|
| 32 |
+
from selenium.webdriver.common.keys import Keys
|
| 33 |
+
from selenium.webdriver.common.by import By
|
| 34 |
+
from selenium.webdriver.support import expected_conditions as EC
|
| 35 |
+
|
| 36 |
+
from aiohttp_cors import setup as _setup, ResourceOptions, CorsViewMixin
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class _ServerDescr:
|
| 40 |
+
"""Auxiliary class for storing server info"""
|
| 41 |
+
|
| 42 |
+
def __init__(self):
|
| 43 |
+
self.app = None
|
| 44 |
+
self.cors = None
|
| 45 |
+
self.handler = None
|
| 46 |
+
self.server = None
|
| 47 |
+
self.url = None
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class IntegrationServers:
|
| 51 |
+
"""Integration servers starting/stopping manager"""
|
| 52 |
+
|
| 53 |
+
def __init__(self, use_resources, use_webview, *, loop=None):
|
| 54 |
+
self.servers = {}
|
| 55 |
+
|
| 56 |
+
self.loop = loop
|
| 57 |
+
if self.loop is None:
|
| 58 |
+
self.loop = asyncio.get_event_loop()
|
| 59 |
+
|
| 60 |
+
self.use_resources = use_resources
|
| 61 |
+
self.use_webview = use_webview
|
| 62 |
+
|
| 63 |
+
self._logger = logging.getLogger("IntegrationServers")
|
| 64 |
+
|
| 65 |
+
@property
|
| 66 |
+
def origin_server_url(self):
|
| 67 |
+
return self.servers["origin"].url
|
| 68 |
+
|
| 69 |
+
async def start_servers(self):
|
| 70 |
+
test_page_path = pathlib.Path(__file__).with_name("test_page.html")
|
| 71 |
+
|
| 72 |
+
async def handle_test_page(request: web.Request) -> web.StreamResponse:
|
| 73 |
+
with test_page_path.open("r", encoding="utf-8") as f:
|
| 74 |
+
return web.Response(
|
| 75 |
+
text=f.read(),
|
| 76 |
+
headers={hdrs.CONTENT_TYPE: "text/html"})
|
| 77 |
+
|
| 78 |
+
async def handle_no_cors(request: web.Request) -> web.StreamResponse:
|
| 79 |
+
return web.Response(
|
| 80 |
+
text="""{"type": "no_cors.json"}""",
|
| 81 |
+
headers={hdrs.CONTENT_TYPE: "application/json"})
|
| 82 |
+
|
| 83 |
+
async def handle_resource(request: web.Request) -> web.StreamResponse:
|
| 84 |
+
return web.Response(
|
| 85 |
+
text="""{"type": "resource"}""",
|
| 86 |
+
headers={hdrs.CONTENT_TYPE: "application/json"})
|
| 87 |
+
|
| 88 |
+
async def handle_servers_addresses(
|
| 89 |
+
request: web.Request) -> web.StreamResponse:
|
| 90 |
+
servers_addresses = \
|
| 91 |
+
{name: descr.url for name, descr in self.servers.items()}
|
| 92 |
+
return web.Response(
|
| 93 |
+
text=json.dumps(servers_addresses))
|
| 94 |
+
|
| 95 |
+
class ResourceView(web.View, CorsViewMixin):
|
| 96 |
+
|
| 97 |
+
async def get(self) -> web.StreamResponse:
|
| 98 |
+
return await handle_resource(self.request)
|
| 99 |
+
|
| 100 |
+
# For most resources:
|
| 101 |
+
# "origin" server has no CORS configuration.
|
| 102 |
+
# "allowing" server explicitly allows CORS requests to "origin" server.
|
| 103 |
+
# "denying" server explicitly disallows CORS requests to "origin"
|
| 104 |
+
# server.
|
| 105 |
+
# "free_for_all" server allows CORS requests for all origins server.
|
| 106 |
+
# "no_cors" server has no CORS configuration.
|
| 107 |
+
cors_server_names = ["allowing", "denying", "free_for_all"]
|
| 108 |
+
server_names = cors_server_names + ["origin", "no_cors"]
|
| 109 |
+
|
| 110 |
+
for server_name in server_names:
|
| 111 |
+
assert server_name not in self.servers
|
| 112 |
+
self.servers[server_name] = _ServerDescr()
|
| 113 |
+
|
| 114 |
+
server_sockets = {}
|
| 115 |
+
|
| 116 |
+
# Create applications and sockets.
|
| 117 |
+
for server_name, server_descr in self.servers.items():
|
| 118 |
+
server_descr.app = web.Application()
|
| 119 |
+
|
| 120 |
+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
| 121 |
+
sock.bind(("127.0.0.1", 0))
|
| 122 |
+
sock.listen(10)
|
| 123 |
+
server_sockets[server_name] = sock
|
| 124 |
+
|
| 125 |
+
hostaddr, port = sock.getsockname()
|
| 126 |
+
server_descr.url = "http://{host}:{port}".format(
|
| 127 |
+
host=hostaddr, port=port)
|
| 128 |
+
|
| 129 |
+
# Server test page from origin server.
|
| 130 |
+
self.servers["origin"].app.router.add_route(
|
| 131 |
+
"GET", "/", handle_test_page)
|
| 132 |
+
self.servers["origin"].app.router.add_route(
|
| 133 |
+
"GET", "/servers_addresses", handle_servers_addresses)
|
| 134 |
+
|
| 135 |
+
# Add routes to all servers.
|
| 136 |
+
for server_name in server_names:
|
| 137 |
+
app = self.servers[server_name].app
|
| 138 |
+
app.router.add_route("GET", "/no_cors.json", handle_no_cors)
|
| 139 |
+
if self.use_webview:
|
| 140 |
+
app.router.add_route("*", "/cors_resource", ResourceView,
|
| 141 |
+
name="cors_resource")
|
| 142 |
+
else:
|
| 143 |
+
app.router.add_route("GET", "/cors_resource", handle_resource,
|
| 144 |
+
name="cors_resource")
|
| 145 |
+
|
| 146 |
+
cors_default_configs = {
|
| 147 |
+
"allowing": {
|
| 148 |
+
self.servers["origin"].url:
|
| 149 |
+
ResourceOptions(
|
| 150 |
+
allow_credentials=True, expose_headers="*",
|
| 151 |
+
allow_headers="*")
|
| 152 |
+
},
|
| 153 |
+
"denying": {
|
| 154 |
+
# Allow requests to other than "origin" server.
|
| 155 |
+
self.servers["allowing"].url:
|
| 156 |
+
ResourceOptions(
|
| 157 |
+
allow_credentials=True, expose_headers="*",
|
| 158 |
+
allow_headers="*")
|
| 159 |
+
},
|
| 160 |
+
"free_for_all": {
|
| 161 |
+
"*":
|
| 162 |
+
ResourceOptions(
|
| 163 |
+
allow_credentials=True, expose_headers="*",
|
| 164 |
+
allow_headers="*")
|
| 165 |
+
},
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
# Configure CORS.
|
| 169 |
+
for server_name, server_descr in self.servers.items():
|
| 170 |
+
default_config = cors_default_configs.get(server_name)
|
| 171 |
+
if default_config is None:
|
| 172 |
+
continue
|
| 173 |
+
server_descr.cors = _setup(
|
| 174 |
+
server_descr.app, defaults=default_config)
|
| 175 |
+
|
| 176 |
+
# Add CORS routes.
|
| 177 |
+
for server_name in cors_server_names:
|
| 178 |
+
server_descr = self.servers[server_name]
|
| 179 |
+
# TODO: Starting from aiohttp 0.21.0 name-based access returns
|
| 180 |
+
# Resource, not Route. Manually get route while aiohttp_cors
|
| 181 |
+
# doesn't support configuring for Resources.
|
| 182 |
+
resource = server_descr.app.router["cors_resource"]
|
| 183 |
+
route = next(iter(resource))
|
| 184 |
+
if self.use_resources:
|
| 185 |
+
server_descr.cors.add(resource)
|
| 186 |
+
server_descr.cors.add(route)
|
| 187 |
+
|
| 188 |
+
elif self.use_webview:
|
| 189 |
+
server_descr.cors.add(route)
|
| 190 |
+
|
| 191 |
+
else:
|
| 192 |
+
server_descr.cors.add(route)
|
| 193 |
+
|
| 194 |
+
# Start servers.
|
| 195 |
+
for server_name, server_descr in self.servers.items():
|
| 196 |
+
runner = web.AppRunner(server_descr.app)
|
| 197 |
+
await runner.setup()
|
| 198 |
+
site = web.SockSite(runner, server_sockets[server_name])
|
| 199 |
+
await site.start()
|
| 200 |
+
server_descr.runner = runner
|
| 201 |
+
|
| 202 |
+
self._logger.info("Started server '%s' at '%s'",
|
| 203 |
+
server_name, server_descr.url)
|
| 204 |
+
|
| 205 |
+
async def stop_servers(self):
|
| 206 |
+
for server_descr in self.servers.values():
|
| 207 |
+
runner = server_descr.runner
|
| 208 |
+
await runner.shutdown()
|
| 209 |
+
await runner.cleanup()
|
| 210 |
+
|
| 211 |
+
self.servers = {}
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def _get_chrome_driver():
|
| 215 |
+
driver_path_env = "WEBDRIVER_CHROMEDRIVER_PATH"
|
| 216 |
+
|
| 217 |
+
if driver_path_env in os.environ:
|
| 218 |
+
driver = webdriver.Chrome(executable_path=os.environ[driver_path_env])
|
| 219 |
+
else:
|
| 220 |
+
driver = webdriver.Chrome()
|
| 221 |
+
|
| 222 |
+
return driver
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
@pytest.fixture(params=[(False, False),
|
| 226 |
+
(True, False),
|
| 227 |
+
(False, True)])
|
| 228 |
+
def server(request, loop):
|
| 229 |
+
async def inner():
|
| 230 |
+
# to grab implicit loop
|
| 231 |
+
return IntegrationServers(*request.param)
|
| 232 |
+
return loop.run_until_complete(inner())
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
@pytest.fixture(params=[webdriver.Firefox,
|
| 236 |
+
_get_chrome_driver])
|
| 237 |
+
def driver(request):
|
| 238 |
+
try:
|
| 239 |
+
driver = request.param()
|
| 240 |
+
except selenium.common.exceptions.WebDriverException:
|
| 241 |
+
pytest.skip("Driver is not supported")
|
| 242 |
+
|
| 243 |
+
yield driver
|
| 244 |
+
driver.close()
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
async def test_in_webdriver(driver, server):
|
| 248 |
+
loop = asyncio.get_event_loop()
|
| 249 |
+
await server.start_servers()
|
| 250 |
+
|
| 251 |
+
def selenium_thread():
|
| 252 |
+
driver.get(server.origin_server_url)
|
| 253 |
+
assert "aiohttp_cors" in driver.title
|
| 254 |
+
|
| 255 |
+
wait = WebDriverWait(driver, 10)
|
| 256 |
+
|
| 257 |
+
run_button = wait.until(EC.element_to_be_clickable(
|
| 258 |
+
(By.ID, "runTestsButton")))
|
| 259 |
+
|
| 260 |
+
# Start tests.
|
| 261 |
+
run_button.send_keys(Keys.RETURN)
|
| 262 |
+
|
| 263 |
+
# Wait while test will finish (until clear button is not
|
| 264 |
+
# activated).
|
| 265 |
+
wait.until(EC.element_to_be_clickable(
|
| 266 |
+
(By.ID, "clearResultsButton")))
|
| 267 |
+
|
| 268 |
+
# Get results json
|
| 269 |
+
results_area = driver.find_element_by_id("results")
|
| 270 |
+
|
| 271 |
+
return json.loads(results_area.get_attribute("value"))
|
| 272 |
+
|
| 273 |
+
try:
|
| 274 |
+
results = await loop.run_in_executor(
|
| 275 |
+
None, selenium_thread)
|
| 276 |
+
|
| 277 |
+
assert results["status"] == "success"
|
| 278 |
+
for test_name, test_data in results["data"].items():
|
| 279 |
+
assert test_data["status"] == "success"
|
| 280 |
+
|
| 281 |
+
finally:
|
| 282 |
+
await server.stop_servers()
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def _run_integration_server():
|
| 286 |
+
"""Runs integration server for interactive debugging."""
|
| 287 |
+
|
| 288 |
+
logging.basicConfig(level=logging.INFO)
|
| 289 |
+
|
| 290 |
+
logger = logging.getLogger("run_integration_server")
|
| 291 |
+
|
| 292 |
+
loop = asyncio.get_event_loop()
|
| 293 |
+
|
| 294 |
+
servers = IntegrationServers(False, True)
|
| 295 |
+
logger.info("Starting integration servers...")
|
| 296 |
+
loop.run_until_complete(servers.start_servers())
|
| 297 |
+
|
| 298 |
+
try:
|
| 299 |
+
webbrowser.open(servers.origin_server_url)
|
| 300 |
+
except webbrowser.Error:
|
| 301 |
+
pass
|
| 302 |
+
|
| 303 |
+
try:
|
| 304 |
+
loop.run_forever()
|
| 305 |
+
except KeyboardInterrupt:
|
| 306 |
+
pass
|
| 307 |
+
finally:
|
| 308 |
+
logger.info("Stopping integration servers...")
|
| 309 |
+
loop.run_until_complete(servers.stop_servers())
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
if __name__ == "__main__":
|
| 313 |
+
# This module can be run in the following way:
|
| 314 |
+
# $ python -m tests.integration.test_real_browser
|
| 315 |
+
# from aiohttp_cors root directory.
|
| 316 |
+
_run_integration_server()
|
pool/shard003/Python/0027401_winscp.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Based on the work of https://github.com/AlessandroZ/LaZagne/blob/master/Windows/lazagne/
|
| 2 |
+
import win32con, win32api
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class WinSCP():
|
| 6 |
+
def __init__(self):
|
| 7 |
+
self.hash = ''
|
| 8 |
+
self.username = ''
|
| 9 |
+
self.hostname = ''
|
| 10 |
+
|
| 11 |
+
# ------------------------------ Getters and Setters ------------------------------
|
| 12 |
+
def get_hash(self):
|
| 13 |
+
return self.hash
|
| 14 |
+
|
| 15 |
+
def set_hash(self, _hash):
|
| 16 |
+
self.hash = _hash
|
| 17 |
+
|
| 18 |
+
def get_username(self):
|
| 19 |
+
return self.username
|
| 20 |
+
|
| 21 |
+
def set_username(self, _username):
|
| 22 |
+
self.username = _username
|
| 23 |
+
|
| 24 |
+
def get_hostname(self):
|
| 25 |
+
return self.hostname
|
| 26 |
+
|
| 27 |
+
def set_hostname(self, _hostname):
|
| 28 |
+
self.hostname = _hostname
|
| 29 |
+
|
| 30 |
+
def decrypt_char(self):
|
| 31 |
+
hash = self.get_hash()
|
| 32 |
+
|
| 33 |
+
hex_flag = 0xA3
|
| 34 |
+
charset = '0123456789ABCDEF'
|
| 35 |
+
|
| 36 |
+
if len(hash) > 0:
|
| 37 |
+
unpack1 = charset.find(hash[0])
|
| 38 |
+
unpack1 = unpack1 << 4
|
| 39 |
+
|
| 40 |
+
unpack2 = charset.find(hash[1])
|
| 41 |
+
result = ~((unpack1 + unpack2) ^ hex_flag) & 0xff
|
| 42 |
+
|
| 43 |
+
# store the new hash
|
| 44 |
+
self.set_hash(hash[2:])
|
| 45 |
+
|
| 46 |
+
return result
|
| 47 |
+
|
| 48 |
+
def check_winscp_installed(self):
|
| 49 |
+
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
|
| 50 |
+
try:
|
| 51 |
+
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER,
|
| 52 |
+
'Software\Martin Prikryl\WinSCP 2\Configuration\Security', 0, accessRead)
|
| 53 |
+
return True
|
| 54 |
+
except Exception, e:
|
| 55 |
+
return False
|
| 56 |
+
|
| 57 |
+
def check_masterPassword(self):
|
| 58 |
+
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
|
| 59 |
+
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, 'Software\Martin Prikryl\WinSCP 2\Configuration\Security',
|
| 60 |
+
0, accessRead)
|
| 61 |
+
thisName = str(win32api.RegQueryValueEx(key, 'UseMasterPassword')[0])
|
| 62 |
+
|
| 63 |
+
if thisName == '0':
|
| 64 |
+
return False
|
| 65 |
+
else:
|
| 66 |
+
return True
|
| 67 |
+
|
| 68 |
+
def get_logins_info(self):
|
| 69 |
+
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
|
| 70 |
+
try:
|
| 71 |
+
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, 'Software\Martin Prikryl\WinSCP 2\Sessions', 0,
|
| 72 |
+
accessRead)
|
| 73 |
+
except Exception, e:
|
| 74 |
+
return False
|
| 75 |
+
|
| 76 |
+
num_profiles = win32api.RegQueryInfoKey(key)[0]
|
| 77 |
+
|
| 78 |
+
pwdFound = []
|
| 79 |
+
for n in range(num_profiles):
|
| 80 |
+
name_skey = win32api.RegEnumKey(key, n)
|
| 81 |
+
|
| 82 |
+
skey = win32api.RegOpenKey(key, name_skey, 0, accessRead)
|
| 83 |
+
num = win32api.RegQueryInfoKey(skey)[1]
|
| 84 |
+
|
| 85 |
+
port = ''
|
| 86 |
+
values = {}
|
| 87 |
+
|
| 88 |
+
for nn in range(num):
|
| 89 |
+
k = win32api.RegEnumValue(skey, nn)
|
| 90 |
+
|
| 91 |
+
if k[0] == 'HostName':
|
| 92 |
+
self.set_hostname(k[1])
|
| 93 |
+
|
| 94 |
+
if k[0] == 'UserName':
|
| 95 |
+
self.set_username(k[1])
|
| 96 |
+
|
| 97 |
+
if k[0] == 'Password':
|
| 98 |
+
self.set_hash(k[1])
|
| 99 |
+
|
| 100 |
+
if k[0] == 'PortNumber':
|
| 101 |
+
port = str(k[1])
|
| 102 |
+
|
| 103 |
+
if num != 0:
|
| 104 |
+
if port == '':
|
| 105 |
+
port = '22'
|
| 106 |
+
try:
|
| 107 |
+
password = self.decrypt_password()
|
| 108 |
+
values['Password'] = password
|
| 109 |
+
except Exception, e:
|
| 110 |
+
pass
|
| 111 |
+
|
| 112 |
+
values['Hostname'] = self.get_hostname()
|
| 113 |
+
values['Port'] = port
|
| 114 |
+
values['Username'] = self.get_username()
|
| 115 |
+
|
| 116 |
+
pwdFound.append(values)
|
| 117 |
+
|
| 118 |
+
# print the results
|
| 119 |
+
return pwdFound
|
| 120 |
+
|
| 121 |
+
def decrypt_password(self):
|
| 122 |
+
hex_flag = 0xFF
|
| 123 |
+
|
| 124 |
+
flag = self.decrypt_char()
|
| 125 |
+
if flag == hex_flag:
|
| 126 |
+
self.decrypt_char()
|
| 127 |
+
length = self.decrypt_char()
|
| 128 |
+
else:
|
| 129 |
+
length = flag
|
| 130 |
+
|
| 131 |
+
ldel = (self.decrypt_char()) * 2
|
| 132 |
+
|
| 133 |
+
hash = self.get_hash()
|
| 134 |
+
self.set_hash(hash[ldel: len(hash)])
|
| 135 |
+
|
| 136 |
+
result = ''
|
| 137 |
+
for ss in range(length):
|
| 138 |
+
|
| 139 |
+
try:
|
| 140 |
+
result += chr(int(self.decrypt_char()))
|
| 141 |
+
except Exception, e:
|
| 142 |
+
pass
|
| 143 |
+
|
| 144 |
+
if flag == hex_flag:
|
| 145 |
+
key = self.get_username() + self.get_hostname()
|
| 146 |
+
result = result[len(key): len(result)]
|
| 147 |
+
|
| 148 |
+
return result
|
| 149 |
+
|
| 150 |
+
# --------- Main function ---------
|
| 151 |
+
def run(self):
|
| 152 |
+
|
| 153 |
+
if self.check_winscp_installed():
|
| 154 |
+
if not self.check_masterPassword():
|
| 155 |
+
r = self.get_logins_info()
|
| 156 |
+
if r == False:
|
| 157 |
+
pass
|
| 158 |
+
else:
|
| 159 |
+
return r
|
| 160 |
+
|
| 161 |
+
# tem = WinSCP()
|
| 162 |
+
# a = tem.run()
|
| 163 |
+
# print a
|
pool/shard003/Python/0027414_all.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2011, 2012 Abhijit Mahabal
|
| 2 |
+
#
|
| 3 |
+
# This program is free software: you can redistribute it and/or modify it under
|
| 4 |
+
# the terms of the GNU General Public License as published by the Free Software
|
| 5 |
+
# Foundation, either version 3 of the License, or (at your option) any later version.
|
| 6 |
+
#
|
| 7 |
+
# This program is distributed in the hope that it will be useful, but WITHOUT ANY
|
| 8 |
+
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
|
| 9 |
+
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
| 10 |
+
#
|
| 11 |
+
# You should have received a copy of the GNU General Public License along with this
|
| 12 |
+
# program. If not, see <http://www.gnu.org/licenses/>
|
| 13 |
+
|
| 14 |
+
import logging
|
| 15 |
+
|
| 16 |
+
from farg.apps.seqsee.anchored import SAnchored
|
| 17 |
+
from farg.apps.seqsee.exceptions import ConflictingGroupException
|
| 18 |
+
from farg.apps.seqsee.subspaces.are_we_done import SubspaceAreWeDone
|
| 19 |
+
from farg.apps.seqsee.subspaces.deal_with_conflicting_groups import SubspaceDealWithConflictingGroups
|
| 20 |
+
from farg.apps.seqsee.subspaces.is_this_interlaced import SubspaceIsThisInterlaced
|
| 21 |
+
from farg.core.codelet import CodeletFamily
|
| 22 |
+
from farg.core.exceptions import AnswerFoundException
|
| 23 |
+
from farg.core.history import History
|
| 24 |
+
class CF_FocusOn(CodeletFamily):
|
| 25 |
+
"""Causes the required focusable to be added to the stream."""
|
| 26 |
+
@classmethod
|
| 27 |
+
def Run(cls, controller, focusable, *, me):
|
| 28 |
+
controller.stream.FocusOn(focusable, parents=[me])
|
| 29 |
+
|
| 30 |
+
class CF_GroupFromRelation(CodeletFamily):
|
| 31 |
+
"""Causes the required relations' ends to create a group."""
|
| 32 |
+
@classmethod
|
| 33 |
+
def Run(cls, controller, relation, *, me):
|
| 34 |
+
# If there is a group spanning the proposed group, perish the thought.
|
| 35 |
+
left, right = relation.first.start_pos, relation.second.end_pos
|
| 36 |
+
from farg.apps.seqsee.util import GreaterThanEq, LessThanEq
|
| 37 |
+
if tuple(controller.workspace.GetGroupsWithSpan(LessThanEq(left), GreaterThanEq(right))):
|
| 38 |
+
History.Note("CF_GroupFromRelation: a spanning group exists")
|
| 39 |
+
return
|
| 40 |
+
anchored = SAnchored.Create((relation.first, relation.second),
|
| 41 |
+
underlying_mapping_set=relation.mapping_set)
|
| 42 |
+
try:
|
| 43 |
+
controller.workspace.InsertGroup(anchored, parent=[me])
|
| 44 |
+
except ConflictingGroupException as e:
|
| 45 |
+
SubspaceDealWithConflictingGroups(
|
| 46 |
+
controller,
|
| 47 |
+
workspace_arguments=dict(new_group=anchored,
|
| 48 |
+
incumbents=e.conflicting_groups),
|
| 49 |
+
parents=[me, relation],
|
| 50 |
+
msg="Conflict while inserting %s" % anchored.BriefLabel()).Run()
|
| 51 |
+
|
| 52 |
+
class CF_DescribeAs(CodeletFamily):
|
| 53 |
+
"""Attempt to describe item as belonging to category."""
|
| 54 |
+
@classmethod
|
| 55 |
+
def Run(cls, controller, item, category, *, me):
|
| 56 |
+
if not item.IsKnownAsInstanceOf(category):
|
| 57 |
+
item.DescribeAs(category)
|
| 58 |
+
|
| 59 |
+
class CF_AreWeDone(CodeletFamily):
|
| 60 |
+
"""Check using a subspace if we are done. If yes, quit."""
|
| 61 |
+
@classmethod
|
| 62 |
+
def Run(cls, controller, *, me):
|
| 63 |
+
answer = SubspaceAreWeDone(controller, parents=[me]).Run()
|
| 64 |
+
if answer:
|
| 65 |
+
controller.ui.DisplayMessage("In its current nascent stage, Seqsee decides that it "
|
| 66 |
+
"has found the solution as soon as it has added 10 new "
|
| 67 |
+
"terms. This is something that needs fixing. Quitting.")
|
| 68 |
+
raise AnswerFoundException("AnswerFound", codelet_count=controller.steps_taken)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class CF_IsThisInterlaced(CodeletFamily):
|
| 72 |
+
"""Check using a subspace if we may be looking at an interlaced sequence."""
|
| 73 |
+
@classmethod
|
| 74 |
+
def Run(cls, controller, distance, *, me):
|
| 75 |
+
logging.debug("RUNNING CF_AreweDone with distance=%s", str(distance))
|
| 76 |
+
SubspaceIsThisInterlaced(controller,
|
| 77 |
+
nsteps=20,
|
| 78 |
+
workspace_arguments=dict(distance=distance),
|
| 79 |
+
parents=[me]).Run()
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class CF_RemoveSpuriousRelations(CodeletFamily):
|
| 83 |
+
"""Removes relations between all pairs (A, B) where both belong to supuergroups but their
|
| 84 |
+
supergroups don't overlap.
|
| 85 |
+
"""
|
| 86 |
+
@classmethod
|
| 87 |
+
def Run(cls, controller, *, me):
|
| 88 |
+
workspace = controller.workspace
|
| 89 |
+
supergroups_map = workspace.CalculateSupergroupMap()
|
| 90 |
+
History.Note("CF_RemoveSpuriousRelations: called")
|
| 91 |
+
for element in workspace.elements:
|
| 92 |
+
supergps = supergroups_map[element]
|
| 93 |
+
if not supergps:
|
| 94 |
+
continue
|
| 95 |
+
relations_to_remove = []
|
| 96 |
+
for relation in element.relations:
|
| 97 |
+
if relation.first == element:
|
| 98 |
+
other_end = relation.second
|
| 99 |
+
else:
|
| 100 |
+
other_end = relation.first
|
| 101 |
+
other_supergps = supergroups_map[other_end]
|
| 102 |
+
if not other_supergps:
|
| 103 |
+
continue
|
| 104 |
+
if supergps.intersection(other_supergps):
|
| 105 |
+
continue
|
| 106 |
+
other_end.relations.discard(relation)
|
| 107 |
+
relations_to_remove.append(relation)
|
| 108 |
+
History.Note("CF_RemoveSpuriousRelations: removed", times=len(relations_to_remove))
|
| 109 |
+
for relation in relations_to_remove:
|
| 110 |
+
element.relations.discard(relation)
|
pool/shard003/Python/0027417_views.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
|
| 3 |
+
from django.views.generic import FormView, View
|
| 4 |
+
from django.views.generic.detail import SingleObjectMixin
|
| 5 |
+
from django.contrib import messages
|
| 6 |
+
from django.http import Http404, HttpResponse
|
| 7 |
+
from django.shortcuts import redirect
|
| 8 |
+
from django.core.exceptions import ValidationError
|
| 9 |
+
from django.core.validators import validate_email
|
| 10 |
+
from django.contrib.auth.decorators import login_required
|
| 11 |
+
from django.utils.decorators import method_decorator
|
| 12 |
+
|
| 13 |
+
from .forms import InviteForm, CleanEmailMixin
|
| 14 |
+
from .exceptions import AlreadyInvited, AlreadyAccepted, UserRegisteredEmail
|
| 15 |
+
from .app_settings import app_settings
|
| 16 |
+
from .adapters import get_invitations_adapter
|
| 17 |
+
from .signals import invite_accepted
|
| 18 |
+
from .utils import get_invitation_model
|
| 19 |
+
|
| 20 |
+
Invitation = get_invitation_model()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class SendInvite(FormView):
|
| 24 |
+
template_name = 'invitations/forms/_invite.html'
|
| 25 |
+
form_class = InviteForm
|
| 26 |
+
|
| 27 |
+
@method_decorator(login_required)
|
| 28 |
+
def dispatch(self, request, *args, **kwargs):
|
| 29 |
+
return super(SendInvite, self).dispatch(request, *args, **kwargs)
|
| 30 |
+
|
| 31 |
+
def form_valid(self, form):
|
| 32 |
+
email = form.cleaned_data["email"]
|
| 33 |
+
|
| 34 |
+
try:
|
| 35 |
+
invite = form.save(email)
|
| 36 |
+
invite.inviter = self.request.user
|
| 37 |
+
invite.save()
|
| 38 |
+
invite.send_invitation(self.request)
|
| 39 |
+
except Exception:
|
| 40 |
+
return self.form_invalid(form)
|
| 41 |
+
|
| 42 |
+
return self.render_to_response(
|
| 43 |
+
self.get_context_data(
|
| 44 |
+
success_message='%s has been invited' % email))
|
| 45 |
+
|
| 46 |
+
def form_invalid(self, form):
|
| 47 |
+
return self.render_to_response(self.get_context_data(form=form))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class SendJSONInvite(View):
|
| 51 |
+
http_method_names = [u'post']
|
| 52 |
+
|
| 53 |
+
@method_decorator(login_required)
|
| 54 |
+
def dispatch(self, request, *args, **kwargs):
|
| 55 |
+
if app_settings.ALLOW_JSON_INVITES:
|
| 56 |
+
return super(SendJSONInvite, self).dispatch(
|
| 57 |
+
request, *args, **kwargs)
|
| 58 |
+
else:
|
| 59 |
+
raise Http404
|
| 60 |
+
|
| 61 |
+
def post(self, request, *args, **kwargs):
|
| 62 |
+
status_code = 400
|
| 63 |
+
invitees = json.loads(request.body.decode())
|
| 64 |
+
response = {'valid': [], 'invalid': []}
|
| 65 |
+
if isinstance(invitees, list):
|
| 66 |
+
for invitee in invitees:
|
| 67 |
+
try:
|
| 68 |
+
validate_email(invitee)
|
| 69 |
+
CleanEmailMixin().validate_invitation(invitee)
|
| 70 |
+
invite = Invitation.create(invitee)
|
| 71 |
+
except(ValueError, KeyError):
|
| 72 |
+
pass
|
| 73 |
+
except(ValidationError):
|
| 74 |
+
response['invalid'].append({
|
| 75 |
+
invitee: 'invalid email'})
|
| 76 |
+
except(AlreadyAccepted):
|
| 77 |
+
response['invalid'].append({
|
| 78 |
+
invitee: 'already accepted'})
|
| 79 |
+
except(AlreadyInvited):
|
| 80 |
+
response['invalid'].append(
|
| 81 |
+
{invitee: 'pending invite'})
|
| 82 |
+
except(UserRegisteredEmail):
|
| 83 |
+
response['invalid'].append(
|
| 84 |
+
{invitee: 'user registered email'})
|
| 85 |
+
else:
|
| 86 |
+
invite.send_invitation(request)
|
| 87 |
+
response['valid'].append({invitee: 'invited'})
|
| 88 |
+
|
| 89 |
+
if response['valid']:
|
| 90 |
+
status_code = 201
|
| 91 |
+
|
| 92 |
+
return HttpResponse(
|
| 93 |
+
json.dumps(response),
|
| 94 |
+
status=status_code, content_type='application/json')
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class AcceptInvite(SingleObjectMixin, View):
|
| 98 |
+
form_class = InviteForm
|
| 99 |
+
|
| 100 |
+
def get_signup_redirect(self):
|
| 101 |
+
return app_settings.SIGNUP_REDIRECT
|
| 102 |
+
|
| 103 |
+
def get(self, *args, **kwargs):
|
| 104 |
+
if app_settings.CONFIRM_INVITE_ON_GET:
|
| 105 |
+
return self.post(*args, **kwargs)
|
| 106 |
+
else:
|
| 107 |
+
raise Http404()
|
| 108 |
+
|
| 109 |
+
def post(self, *args, **kwargs):
|
| 110 |
+
self.object = invitation = self.get_object()
|
| 111 |
+
|
| 112 |
+
# Compatibility with older versions: return an HTTP 410 GONE if there
|
| 113 |
+
# is an error. # Error conditions are: no key, expired key or
|
| 114 |
+
# previously accepted key.
|
| 115 |
+
if app_settings.GONE_ON_ACCEPT_ERROR and \
|
| 116 |
+
(not invitation or
|
| 117 |
+
(invitation and (invitation.accepted or
|
| 118 |
+
invitation.key_expired()))):
|
| 119 |
+
return HttpResponse(status=410)
|
| 120 |
+
|
| 121 |
+
# No invitation was found.
|
| 122 |
+
if not invitation:
|
| 123 |
+
# Newer behavior: show an error message and redirect.
|
| 124 |
+
get_invitations_adapter().add_message(
|
| 125 |
+
self.request,
|
| 126 |
+
messages.ERROR,
|
| 127 |
+
'invitations/messages/invite_invalid.txt')
|
| 128 |
+
return redirect(app_settings.LOGIN_REDIRECT)
|
| 129 |
+
|
| 130 |
+
# The invitation was previously accepted, redirect to the login
|
| 131 |
+
# view.
|
| 132 |
+
if invitation.accepted:
|
| 133 |
+
get_invitations_adapter().add_message(
|
| 134 |
+
self.request,
|
| 135 |
+
messages.ERROR,
|
| 136 |
+
'invitations/messages/invite_already_accepted.txt',
|
| 137 |
+
{'email': invitation.email})
|
| 138 |
+
# Redirect to login since there's hopefully an account already.
|
| 139 |
+
return redirect(app_settings.LOGIN_REDIRECT)
|
| 140 |
+
|
| 141 |
+
# The key was expired.
|
| 142 |
+
if invitation.key_expired():
|
| 143 |
+
get_invitations_adapter().add_message(
|
| 144 |
+
self.request,
|
| 145 |
+
messages.ERROR,
|
| 146 |
+
'invitations/messages/invite_expired.txt',
|
| 147 |
+
{'email': invitation.email})
|
| 148 |
+
# Redirect to sign-up since they might be able to register anyway.
|
| 149 |
+
return redirect(self.get_signup_redirect())
|
| 150 |
+
|
| 151 |
+
# The invitation is valid.
|
| 152 |
+
# Mark it as accepted now if ACCEPT_INVITE_AFTER_SIGNUP is False.
|
| 153 |
+
if not app_settings.ACCEPT_INVITE_AFTER_SIGNUP:
|
| 154 |
+
accept_invitation(invitation=invitation,
|
| 155 |
+
request=self.request,
|
| 156 |
+
signal_sender=self.__class__)
|
| 157 |
+
|
| 158 |
+
get_invitations_adapter().stash_verified_email(
|
| 159 |
+
self.request, invitation.email)
|
| 160 |
+
|
| 161 |
+
return redirect(self.get_signup_redirect())
|
| 162 |
+
|
| 163 |
+
def get_object(self, queryset=None):
|
| 164 |
+
if queryset is None:
|
| 165 |
+
queryset = self.get_queryset()
|
| 166 |
+
try:
|
| 167 |
+
return queryset.get(key=self.kwargs["key"].lower())
|
| 168 |
+
except Invitation.DoesNotExist:
|
| 169 |
+
return None
|
| 170 |
+
|
| 171 |
+
def get_queryset(self):
|
| 172 |
+
return Invitation.objects.all()
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def accept_invitation(invitation, request, signal_sender):
|
| 176 |
+
invitation.accepted = True
|
| 177 |
+
invitation.save()
|
| 178 |
+
|
| 179 |
+
invite_accepted.send(sender=signal_sender, email=invitation.email)
|
| 180 |
+
|
| 181 |
+
get_invitations_adapter().add_message(
|
| 182 |
+
request,
|
| 183 |
+
messages.SUCCESS,
|
| 184 |
+
'invitations/messages/invite_accepted.txt',
|
| 185 |
+
{'email': invitation.email})
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def accept_invite_after_signup(sender, request, user, **kwargs):
|
| 189 |
+
invitation = Invitation.objects.filter(email=user.email).first()
|
| 190 |
+
if invitation:
|
| 191 |
+
accept_invitation(invitation=invitation,
|
| 192 |
+
request=request,
|
| 193 |
+
signal_sender=Invitation)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
if app_settings.ACCEPT_INVITE_AFTER_SIGNUP:
|
| 197 |
+
signed_up_signal = get_invitations_adapter().get_user_signed_up_signal()
|
| 198 |
+
signed_up_signal.connect(accept_invite_after_signup)
|
pool/shard003/Python/0027418_rejoin_user_event_test.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 Google Inc. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import re
|
| 16 |
+
import subprocess
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_create_product():
|
| 20 |
+
output = str(subprocess.check_output("python rejoin_user_event.py", shell=True))
|
| 21 |
+
|
| 22 |
+
assert re.match(".*the user event is written.*", output)
|
| 23 |
+
assert re.match(
|
| 24 |
+
'.*rejoin user events request.*?parent: "projects/.*?/locations/global/catalogs/default_catalog.*',
|
| 25 |
+
output,
|
| 26 |
+
)
|
| 27 |
+
assert re.match(
|
| 28 |
+
".*rejoin user events request.*?user_event_rejoin_scope: UNJOINED_EVENTS.*",
|
| 29 |
+
output,
|
| 30 |
+
)
|
| 31 |
+
assert re.match(
|
| 32 |
+
".*the rejoin operation was started.*?projects/.*?/locations/global/catalogs/default_catalog/operations/rejoin-user-events.*",
|
| 33 |
+
output,
|
| 34 |
+
)
|
| 35 |
+
assert re.match(
|
| 36 |
+
".*the purge operation was started.*?projects/.*?/locations/global/catalogs/default_catalog/operations/purge-user-events.*",
|
| 37 |
+
output,
|
| 38 |
+
)
|
pool/shard003/Python/0027423_engine.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
__author__ = 'Yuvv'
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import functools
|
| 7 |
+
|
| 8 |
+
rule_file = open('res/rules-v1.json')
|
| 9 |
+
rules = json.load(rule_file)
|
| 10 |
+
explanations = rules['explanations']
|
| 11 |
+
rules = rules['rules']
|
| 12 |
+
rule_file.close()
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def param_splitter(params):
|
| 16 |
+
param_dict = {}
|
| 17 |
+
for i in range(len(params)):
|
| 18 |
+
if i % 2:
|
| 19 |
+
continue
|
| 20 |
+
param_dict[params[i]] = float(params[i + 1])
|
| 21 |
+
i += 1
|
| 22 |
+
|
| 23 |
+
return param_dict
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def calc_reduce_for_get(a, b):
|
| 27 |
+
"""reduce function for get_factor
|
| 28 |
+
"""
|
| 29 |
+
if a >= 0 and b >= 0:
|
| 30 |
+
return a + b - a * b
|
| 31 |
+
elif a <= 0 and b <= 0:
|
| 32 |
+
return a + b + a * b
|
| 33 |
+
else:
|
| 34 |
+
return (a + b) / (1 - min(abs(a), abs(b)))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# TODO: 对条件中的或情况还未考虑。是否做一个parser?
|
| 38 |
+
def get_factor(target, factors):
|
| 39 |
+
"""Calculate certainty factor.计算CF(H).
|
| 40 |
+
:param target: 目标因子
|
| 41 |
+
:param factors: 前置因子字典
|
| 42 |
+
:type target: str
|
| 43 |
+
:type factors: dict
|
| 44 |
+
:return: 返回计算值或None(条件不足无法计算)
|
| 45 |
+
"""
|
| 46 |
+
associated_rules = [] # 包含target的规则
|
| 47 |
+
requested_factors = [] # 前置条件
|
| 48 |
+
for rule in rules:
|
| 49 |
+
if rule[-3] == target:
|
| 50 |
+
associated_rules.append(rule)
|
| 51 |
+
requested_factors.extend(rule[:-3])
|
| 52 |
+
|
| 53 |
+
# 去重复
|
| 54 |
+
# associated_rules = list(set(associated_rules))
|
| 55 |
+
requested_factors = list(set(requested_factors))
|
| 56 |
+
|
| 57 |
+
# 计算用户未给出需要经推理得出的因子
|
| 58 |
+
for factor in requested_factors:
|
| 59 |
+
if factor not in factors:
|
| 60 |
+
factor_value = get_factor(factor, factors)
|
| 61 |
+
if factor_value:
|
| 62 |
+
factors[factor] = factor_value
|
| 63 |
+
else:
|
| 64 |
+
return None
|
| 65 |
+
|
| 66 |
+
factor_list = list(map(
|
| 67 |
+
lambda x: x[-2] * max(
|
| 68 |
+
0, min(list(map(lambda y: factors[y], x[:-3])))) if min(list(map(
|
| 69 |
+
lambda y: factors[y], x[:-3]))) > 0 else factors[min(list(map(
|
| 70 |
+
lambda y: factors[y], x[:-3])))],
|
| 71 |
+
associated_rules))
|
| 72 |
+
result = functools.reduce(calc_reduce_for_get, factor_list)
|
| 73 |
+
|
| 74 |
+
return result
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# TODO: 所有因子一开始是不是都会给全啊?(笑cry)
|
| 78 |
+
def update_factor(target, factors):
|
| 79 |
+
"""Calculate certainty factor.更新CF(H),即计算CF(H|E).
|
| 80 |
+
:param target: 目标因子
|
| 81 |
+
:param factors: 前置因子字典,需包含目标因子
|
| 82 |
+
:type target: str
|
| 83 |
+
:type factors: dict
|
| 84 |
+
:return: 返回计算值或None(条件不足无法计算)
|
| 85 |
+
"""
|
| 86 |
+
associated_rules = [] # 包含target的规则
|
| 87 |
+
entire_targets = [] # 全部目标因子
|
| 88 |
+
requested_factors = [] # 前置条件
|
| 89 |
+
for rule in rules:
|
| 90 |
+
if rule[-3] == target:
|
| 91 |
+
associated_rules.append(rule)
|
| 92 |
+
requested_factors.extend(rule[:-3])
|
| 93 |
+
entire_targets.append(rule[-3])
|
| 94 |
+
|
| 95 |
+
# 去重复
|
| 96 |
+
# associated_rules = list(set(associated_rules))
|
| 97 |
+
requested_factors = list(set(requested_factors))
|
| 98 |
+
|
| 99 |
+
# 计算用户未给出需要经推理得出的因子
|
| 100 |
+
for factor in requested_factors:
|
| 101 |
+
if factor in entire_targets:
|
| 102 |
+
factor_value = update_factor(factor, factors)
|
| 103 |
+
if factor_value:
|
| 104 |
+
factors[factor] = factor_value
|
| 105 |
+
else:
|
| 106 |
+
return None
|
| 107 |
+
|
| 108 |
+
condition_factors = list(map(
|
| 109 |
+
lambda x: [min(list(map(lambda y: factors[y], x[:-3]))), x[-2], x[-1]],
|
| 110 |
+
associated_rules
|
| 111 |
+
))
|
| 112 |
+
for c in condition_factors:
|
| 113 |
+
e = c[0] * c[1] # CF(E)*CF(H,E)
|
| 114 |
+
h = factors[target] # CF(H)
|
| 115 |
+
if h >= 0 and e >= 0:
|
| 116 |
+
factors[target] = h + e * (1 - h)
|
| 117 |
+
elif h <= 0 and e <= 0:
|
| 118 |
+
factors[target] = h + e * (1 + h)
|
| 119 |
+
else:
|
| 120 |
+
factors[target] = (h + e) / (1 - min(abs(h), abs(e)))
|
| 121 |
+
|
| 122 |
+
return factors[target]
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# 计算带阈值CF(H)
|
| 126 |
+
def get_factor_v2(target, factors):
|
| 127 |
+
pass
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
# 更新带阈值CF(H),即计算CF(H|E)
|
| 131 |
+
def update_factor_v2(target, factors):
|
| 132 |
+
pass
|
pool/shard003/Python/0027430_export.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ./sedater/export.py
|
| 2 |
+
# Author: Ulli Goschler <ulligoschler@gmail.com>
|
| 3 |
+
# Created: Sun, 08.11.2015 - 22:21:45
|
| 4 |
+
# Modified: Fri, 11.12.2015 - 01:14:26
|
| 5 |
+
|
| 6 |
+
import csv
|
| 7 |
+
import os
|
| 8 |
+
from xml.etree import ElementTree as et
|
| 9 |
+
|
| 10 |
+
from sedater.lib import shared
|
| 11 |
+
|
| 12 |
+
class Exporter(object):
|
| 13 |
+
"""
|
| 14 |
+
Exports the compiled data.
|
| 15 |
+
|
| 16 |
+
The data collected by either binary or text files (and ready for
|
| 17 |
+
exportation), will be written to the filesystem.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
def __init__(self):
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
def prepareOutputDir(self, dirPrefix, session, exercise=False):
|
| 24 |
+
"""
|
| 25 |
+
Creates all necessary directories for the exporting process.
|
| 26 |
+
|
| 27 |
+
Each individual ``session`` gets an own directory under the ``ouputDir``
|
| 28 |
+
provided by command line.
|
| 29 |
+
|
| 30 |
+
:param str dirPrefix: Path under which all directories will be created
|
| 31 |
+
:param str session: Session identifier
|
| 32 |
+
:param str exercise: (optional) Exercise identifier
|
| 33 |
+
:return: Path to existing directory
|
| 34 |
+
:rtype: str
|
| 35 |
+
"""
|
| 36 |
+
ePrefix = "_E"+exercise if exercise else ''
|
| 37 |
+
sPrefix = "session"+session
|
| 38 |
+
|
| 39 |
+
output = dirPrefix + '/' + sPrefix + ePrefix + '/'
|
| 40 |
+
|
| 41 |
+
if not os.path.exists(output):
|
| 42 |
+
os.makedirs(output)
|
| 43 |
+
|
| 44 |
+
return output
|
| 45 |
+
|
| 46 |
+
class XMLExporter(Exporter):
|
| 47 |
+
"""
|
| 48 |
+
Exports TextValidation files to a single file in XML notation
|
| 49 |
+
|
| 50 |
+
:param str exportLocation: Path to the export directory
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
def __init__(self, exportLocation):
|
| 54 |
+
self.exportLocation = exportLocation
|
| 55 |
+
self.annotationFile = 'annotation.xml'
|
| 56 |
+
|
| 57 |
+
def export(self, validation):
|
| 58 |
+
"""
|
| 59 |
+
:param validation: The parsed
|
| 60 |
+
:class:`Textfile <txtvalidation.TxtConverter.parseTxtFile>`
|
| 61 |
+
:type validation:
|
| 62 |
+
:class:`Validationfile <lib.shared.Validationfile>`
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
filename = 'annotation.xml'
|
| 66 |
+
|
| 67 |
+
self._exportMetaInformationToXML(validation.sourcefile.session,
|
| 68 |
+
validation.sourcefile.exercise, filename)
|
| 69 |
+
output = self._getExportLocation(validation.sourcefile.session,
|
| 70 |
+
validation.sourcefile.exercise)
|
| 71 |
+
|
| 72 |
+
# check if file already exists (from a previous run or the other sensors)
|
| 73 |
+
if os.path.isfile(output + filename):
|
| 74 |
+
document = et.ElementTree()
|
| 75 |
+
document.parse(output + filename)
|
| 76 |
+
|
| 77 |
+
overwrite = document.find('.//Sensor[@Orientation="'+
|
| 78 |
+
validation.sourcefile.orientation.name.lower() +'"]/..[@Type="'+validation.type+'"]')
|
| 79 |
+
if overwrite:
|
| 80 |
+
document.getroot().remove(overwrite)
|
| 81 |
+
else:
|
| 82 |
+
head = et.Element('Data')
|
| 83 |
+
document = et.ElementTree(head)
|
| 84 |
+
|
| 85 |
+
document = document.getroot()
|
| 86 |
+
if validation.type:
|
| 87 |
+
validationXML = et.SubElement(document, 'Validation')
|
| 88 |
+
validationXML.set('Type', validation.type)
|
| 89 |
+
else:
|
| 90 |
+
validationXML = document
|
| 91 |
+
|
| 92 |
+
orientationXML = et.SubElement(validationXML, 'Sensor')
|
| 93 |
+
orientationXML.set('Orientation', validation.sourcefile.orientation.name)
|
| 94 |
+
|
| 95 |
+
meta = et.SubElement(orientationXML, 'Meta')
|
| 96 |
+
#print(validation.properties, file=sys.stderr)
|
| 97 |
+
for prop in validation.properties:
|
| 98 |
+
tmp = et.SubElement(meta, prop[0])
|
| 99 |
+
tmp.text = prop[1]
|
| 100 |
+
|
| 101 |
+
content = et.SubElement(orientationXML, 'Content')
|
| 102 |
+
steps = 1
|
| 103 |
+
for prop in validation.content:
|
| 104 |
+
counter = et.SubElement(content, 'No' + str(steps))
|
| 105 |
+
for key, value in prop.items():
|
| 106 |
+
tmp = et.SubElement(counter, key)
|
| 107 |
+
tmp.text = value
|
| 108 |
+
steps = steps + 1
|
| 109 |
+
|
| 110 |
+
export = et.ElementTree(document)
|
| 111 |
+
shared.indentXML(document)
|
| 112 |
+
export.write(output + filename, encoding='utf-8',
|
| 113 |
+
xml_declaration=True)
|
| 114 |
+
return True
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _getExportLocation(self, session, exercise):
|
| 118 |
+
"""
|
| 119 |
+
Returns a dynamic export location.
|
| 120 |
+
|
| 121 |
+
:param str session: Session
|
| 122 |
+
:param str exercise: Exercise
|
| 123 |
+
:return: Current export location
|
| 124 |
+
:rtype: str
|
| 125 |
+
"""
|
| 126 |
+
ePrefix = "_E"+exercise if exercise else ''
|
| 127 |
+
sPrefix = "session"+session
|
| 128 |
+
|
| 129 |
+
output = self.exportLocation + '/' + sPrefix + ePrefix + '/'
|
| 130 |
+
|
| 131 |
+
return output
|
| 132 |
+
|
| 133 |
+
def _exportMetaInformationToXML(self, session, exercise, annotationFile):
|
| 134 |
+
"""
|
| 135 |
+
Creates a XML file containing the session details. Specifying the
|
| 136 |
+
``Session``, ``Exercise`` and the fll path to the ``Annotationfile``
|
| 137 |
+
containing all Validationdata.
|
| 138 |
+
|
| 139 |
+
:param str session: Name of the current session
|
| 140 |
+
:param str exercise: Name of the current exercise
|
| 141 |
+
:param str annotationFile: Full path to the annotation file
|
| 142 |
+
"""
|
| 143 |
+
filename = 'metainformation.xml'
|
| 144 |
+
output = self._getExportLocation(session, exercise)
|
| 145 |
+
|
| 146 |
+
# Build XML structure
|
| 147 |
+
documentXML = et.Element('Meta')
|
| 148 |
+
|
| 149 |
+
sessionXML = et.SubElement(documentXML, 'Session')
|
| 150 |
+
sessionXML.text = session
|
| 151 |
+
|
| 152 |
+
exerciseXML = et.SubElement(documentXML, 'Exercise')
|
| 153 |
+
exerciseXML.text = exercise
|
| 154 |
+
|
| 155 |
+
annotationXML = et.SubElement(documentXML, 'Annotationfile')
|
| 156 |
+
annotationXML.text = output + annotationFile
|
| 157 |
+
|
| 158 |
+
exportXML = et.ElementTree(documentXML)
|
| 159 |
+
shared.indentXML(documentXML)
|
| 160 |
+
exportXML.write(output + filename, encoding='utf-8',
|
| 161 |
+
xml_declaration=True)
|
| 162 |
+
return True
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class CSVExporter(Exporter):
|
| 166 |
+
"""
|
| 167 |
+
This Exporter handles the export of the RawValidation files to CSV files.
|
| 168 |
+
|
| 169 |
+
After the :class:`Sensorsegments <lib.shared.Sensorsegment>` are
|
| 170 |
+
normalized they can be exported back to the filesystem as CSV files.
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
def export(self, segments, exportLocation
|
| 174 |
+
, withHeader=False
|
| 175 |
+
, withIndices=True):
|
| 176 |
+
"""
|
| 177 |
+
Exports the given segments to a specific file in CSV notation
|
| 178 |
+
|
| 179 |
+
:param segments: A list (array) of segments which should be exported to
|
| 180 |
+
the same file
|
| 181 |
+
:type segments: list of
|
| 182 |
+
:class:`Sensorsegment <lib.shared.Sensorsegment>`
|
| 183 |
+
:param str exportLocation: export path location (incl. filename)
|
| 184 |
+
:param Boolean withHeader: Print a header line in the csv file,
|
| 185 |
+
indicating the row attributes
|
| 186 |
+
:param Boolean withIndices: Print an Indexnumber in the first column
|
| 187 |
+
:return: Indication whether the export succeeded
|
| 188 |
+
:rtype: Boolean
|
| 189 |
+
"""
|
| 190 |
+
|
| 191 |
+
try:
|
| 192 |
+
with open(exportLocation, 'w') as exportFile:
|
| 193 |
+
# TODO: indices are currently always placed in the first
|
| 194 |
+
# column,
|
| 195 |
+
# as they are needed for the plotting. But this might not
|
| 196 |
+
# be wanted by the user. So maybe deactivate them by
|
| 197 |
+
# commandline switch
|
| 198 |
+
exp = csv.writer(exportFile)
|
| 199 |
+
if withHeader:
|
| 200 |
+
if withIndices:
|
| 201 |
+
# Header with indices
|
| 202 |
+
header = ['Index']
|
| 203 |
+
header.extend(shared.Sensorsegment._fields)
|
| 204 |
+
exp.writerow(header)
|
| 205 |
+
else:
|
| 206 |
+
# header without indices
|
| 207 |
+
header = shared.Sensorsegment._fields
|
| 208 |
+
exp.writerow(header)
|
| 209 |
+
if withIndices:
|
| 210 |
+
# column with indices
|
| 211 |
+
exp.writerows([(
|
| 212 |
+
index+1
|
| 213 |
+
, value.accelX
|
| 214 |
+
, value.accelY
|
| 215 |
+
, value.accelZ
|
| 216 |
+
, value.gyroX
|
| 217 |
+
, value.gyroY
|
| 218 |
+
, value.gyroZ
|
| 219 |
+
) for index,value in enumerate(segments)])
|
| 220 |
+
else:
|
| 221 |
+
# column without indices
|
| 222 |
+
exp.writerows([(
|
| 223 |
+
value.accelX
|
| 224 |
+
, value.accelY
|
| 225 |
+
, value.accelZ
|
| 226 |
+
, value.gyroX
|
| 227 |
+
, value.gyroY
|
| 228 |
+
, value.gyroZ
|
| 229 |
+
) for value in segments])
|
| 230 |
+
|
| 231 |
+
except Exception as e:
|
| 232 |
+
# TODO: handle common exceptions;
|
| 233 |
+
# but not sure what could happen here besides filesystem
|
| 234 |
+
# failures
|
| 235 |
+
raise e
|
| 236 |
+
|
| 237 |
+
return True
|
pool/shard003/Python/0027432_util.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Utilities
|
| 2 |
+
|
| 3 |
+
:Author: Jonathan Karr <karr@mssm.edu>
|
| 4 |
+
:Date: 2016-11-10
|
| 5 |
+
:Copyright: 2016, Karr Lab
|
| 6 |
+
:License: MIT
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from obj_model import get_models as base_get_models
|
| 10 |
+
from wc_lang import core
|
| 11 |
+
from wc_lang import io
|
| 12 |
+
from wc_utils.util import git
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def get_model_size(model):
|
| 16 |
+
""" Get numbers of model components
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
model (:obj:`core.Model`): model
|
| 20 |
+
|
| 21 |
+
Returns:
|
| 22 |
+
:obj:`dict`: dictionary with numbers of each type of model component
|
| 23 |
+
"""
|
| 24 |
+
return {
|
| 25 |
+
"submodels": len(model.get_submodels()),
|
| 26 |
+
"compartments": len(model.get_compartments()),
|
| 27 |
+
"species_types": len(model.get_species_types()),
|
| 28 |
+
"species": len(model.get_species()),
|
| 29 |
+
"parameters": len(model.get_parameters()),
|
| 30 |
+
"references": len(model.get_references()),
|
| 31 |
+
"reactions": len(model.get_reactions()),
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def get_model_summary(model):
|
| 36 |
+
""" Get textual summary of a model
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
model (:obj:`core.Model`): model
|
| 40 |
+
|
| 41 |
+
Returns:
|
| 42 |
+
:obj:`str`: textual summary of the model
|
| 43 |
+
"""
|
| 44 |
+
return "Model with:" \
|
| 45 |
+
+ "\n{:d} submodels".format(len(model.get_submodels())) \
|
| 46 |
+
+ "\n{:d} compartments".format(len(model.get_compartments())) \
|
| 47 |
+
+ "\n{:d} species types".format(len(model.get_species_types())) \
|
| 48 |
+
+ "\n{:d} species".format(len(model.get_species())) \
|
| 49 |
+
+ "\n{:d} parameters".format(len(model.get_parameters())) \
|
| 50 |
+
+ "\n{:d} references".format(len(model.get_references())) \
|
| 51 |
+
+ "\n{:d} dFBA objective reactions".format(len(model.get_dfba_obj_reactions())) \
|
| 52 |
+
+ "\n{:d} reactions".format(len(model.get_reactions())) \
|
| 53 |
+
+ "\n{:d} rate laws".format(len(model.get_rate_laws()))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def get_models(inline=True):
|
| 57 |
+
""" Get list of models
|
| 58 |
+
Args:
|
| 59 |
+
inline (:obj:`bool`, optional): if true, return inline models
|
| 60 |
+
|
| 61 |
+
Returns:
|
| 62 |
+
:obj:`list` of :obj:`class`: list of models
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
return base_get_models(module=core, inline=inline)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def gen_ids(model):
|
| 69 |
+
""" Generate ids for model objects
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
model (:obj:`core.Model`): model
|
| 73 |
+
"""
|
| 74 |
+
for obj in model.get_related():
|
| 75 |
+
if hasattr(obj, 'gen_id'):
|
| 76 |
+
obj.id = obj.gen_id()
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def migrate(in_path, wc_lang_version, out_path=None, set_repo_metadata_from_path=True):
|
| 80 |
+
""" Migrate a model to another version of wc_lang
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
in_path (:obj:`str`): path to model
|
| 84 |
+
wc_lang_version (:obj:`str`): version to migrate to
|
| 85 |
+
out_path (:obj:`str`, optional): path to save migrated model; default: overwrite original model
|
| 86 |
+
set_repo_metadata_from_path (:obj:`bool`, optional): if :obj:`True`, set the Git repository metadata (URL,
|
| 87 |
+
branch, revision) for the model from the parent directory of :obj:`core_path`
|
| 88 |
+
"""
|
| 89 |
+
if not out_path:
|
| 90 |
+
out_path = in_path
|
| 91 |
+
|
| 92 |
+
model = io.Reader().run(in_path)[core.Model][0]
|
| 93 |
+
model.wc_lang_version = wc_lang_version
|
| 94 |
+
io.Writer().run(out_path, model, set_repo_metadata_from_path=set_repo_metadata_from_path)
|
pool/shard003/Python/0027433_UserHandlers.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
'''
|
| 3 |
+
Created on Mar 13, 2012
|
| 4 |
+
|
| 5 |
+
@author: moloch
|
| 6 |
+
|
| 7 |
+
Copyright 2012 Root the Box
|
| 8 |
+
|
| 9 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
you may not use this file except in compliance with the License.
|
| 11 |
+
You may obtain a copy of the License at
|
| 12 |
+
|
| 13 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
|
| 15 |
+
Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
See the License for the specific language governing permissions and
|
| 19 |
+
limitations under the License.
|
| 20 |
+
----------------------------------------------------------------------------
|
| 21 |
+
|
| 22 |
+
This file contains code for managing user accounts
|
| 23 |
+
|
| 24 |
+
'''
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
import urllib
|
| 28 |
+
import logging
|
| 29 |
+
import tornado
|
| 30 |
+
|
| 31 |
+
from models.User import User, ADMIN_PERMISSION
|
| 32 |
+
from models.Theme import Theme
|
| 33 |
+
from libs.EventManager import EventManager
|
| 34 |
+
from libs.ValidationError import ValidationError
|
| 35 |
+
from libs.SecurityDecorators import authenticated
|
| 36 |
+
from BaseHandlers import BaseHandler
|
| 37 |
+
from tornado.options import options
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
RECAPTCHA_URL = 'http://www.google.com/recaptcha/api/verify'
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class HomeHandler(BaseHandler):
|
| 44 |
+
|
| 45 |
+
@authenticated
|
| 46 |
+
def get(self, *args, **kwargs):
|
| 47 |
+
''' Display the default user page '''
|
| 48 |
+
user = self.get_current_user()
|
| 49 |
+
if user.has_permission(ADMIN_PERMISSION):
|
| 50 |
+
self.render('admin/home.html', user=user)
|
| 51 |
+
else:
|
| 52 |
+
self.render('user/home.html', user=user)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class SettingsHandler(BaseHandler):
|
| 56 |
+
''' Modify user controlled attributes '''
|
| 57 |
+
|
| 58 |
+
@authenticated
|
| 59 |
+
@tornado.web.asynchronous
|
| 60 |
+
def get(self, *args, **kwargs):
|
| 61 |
+
''' Display the user settings '''
|
| 62 |
+
self.render_page()
|
| 63 |
+
|
| 64 |
+
@authenticated
|
| 65 |
+
@tornado.web.asynchronous
|
| 66 |
+
def post(self, *args, **kwargs):
|
| 67 |
+
''' Calls function based on parameter '''
|
| 68 |
+
post_functions = {
|
| 69 |
+
'avatar': self.post_avatar,
|
| 70 |
+
'password': self.post_password,
|
| 71 |
+
'bank_password': self.post_bankpassword,
|
| 72 |
+
'theme': self.post_theme,
|
| 73 |
+
}
|
| 74 |
+
if len(args) == 1 and args[0] in post_functions:
|
| 75 |
+
post_functions[args[0]]()
|
| 76 |
+
else:
|
| 77 |
+
self.render_page()
|
| 78 |
+
|
| 79 |
+
def render_page(self, errors=[], success=[]):
|
| 80 |
+
''' Small wrap for self.render to cut down on lenghty params '''
|
| 81 |
+
self.add_content_policy('script', "'unsafe-eval'")
|
| 82 |
+
current_theme = Theme.by_id(self.session["theme_id"])
|
| 83 |
+
self.add_content_policy('script', 'www.google.com')
|
| 84 |
+
self.add_content_policy('img', 'www.google.com')
|
| 85 |
+
self.render("user/settings.html",
|
| 86 |
+
errors=errors,
|
| 87 |
+
success=success,
|
| 88 |
+
current_theme=current_theme)
|
| 89 |
+
|
| 90 |
+
def post_avatar(self, *args, **kwargs):
|
| 91 |
+
'''
|
| 92 |
+
Saves avatar - Reads file header an only allows approved formats
|
| 93 |
+
'''
|
| 94 |
+
user = self.get_current_user()
|
| 95 |
+
if hasattr(self.request, 'files') and 'avatar' in self.request.files:
|
| 96 |
+
try:
|
| 97 |
+
user.avatar = self.request.files['avatar'][0]['body']
|
| 98 |
+
self.dbsession.add(user)
|
| 99 |
+
self.dbsession.commit()
|
| 100 |
+
self.render_page(success=["Updated avatar"])
|
| 101 |
+
except ValidationError as error:
|
| 102 |
+
self.render_page(errors=[str(error), ])
|
| 103 |
+
else:
|
| 104 |
+
self.render_page(errors=["Please provide an image"])
|
| 105 |
+
|
| 106 |
+
def post_theme(self, *args, **kwargs):
|
| 107 |
+
''' Change per-user theme '''
|
| 108 |
+
theme = Theme.by_uuid(self.get_argument('theme_uuid', ''))
|
| 109 |
+
if theme is not None:
|
| 110 |
+
self.session['theme_id'] = theme.id
|
| 111 |
+
self.session['theme'] = [str(f) for f in theme.files]
|
| 112 |
+
self.session.save()
|
| 113 |
+
user = self.get_current_user()
|
| 114 |
+
user.theme_id = theme.id
|
| 115 |
+
self.dbsession.add(user)
|
| 116 |
+
self.dbsession.commit()
|
| 117 |
+
self.render_page()
|
| 118 |
+
else:
|
| 119 |
+
self.render_page(errors=["Theme does not exist."])
|
| 120 |
+
|
| 121 |
+
def post_password(self, *args, **kwargs):
|
| 122 |
+
''' Called on POST request for password change '''
|
| 123 |
+
self.set_password(
|
| 124 |
+
self.get_current_user(),
|
| 125 |
+
self.get_argument('old_password'),
|
| 126 |
+
self.get_argument('new_password'),
|
| 127 |
+
self.get_argument('new_password2')
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
def set_password(self, user, old_password, new_password, new_password2):
|
| 131 |
+
''' Sets a users password '''
|
| 132 |
+
if user.validate_password(old_password):
|
| 133 |
+
if len(new_password) >= options.min_user_password_length or self.config.debug:
|
| 134 |
+
if 16 <= len(new_password) or self.config.debug:
|
| 135 |
+
user.password = new_password
|
| 136 |
+
self.dbsession.add(user)
|
| 137 |
+
self.dbsession.commit()
|
| 138 |
+
self.render_page(success=["Successfully updated password"])
|
| 139 |
+
else:
|
| 140 |
+
self.render_page(errors=["Password must be at least %d characters " % (
|
| 141 |
+
options.min_user_password_length,
|
| 142 |
+
)])
|
| 143 |
+
else:
|
| 144 |
+
self.render_page(errors=["New password's didn't match"])
|
| 145 |
+
else:
|
| 146 |
+
self.render_page(errors=["Invalid old password"])
|
| 147 |
+
|
| 148 |
+
def post_bankpassword(self):
|
| 149 |
+
''' Update user's bank password '''
|
| 150 |
+
old_bankpw = self.get_argument('old_bpassword')
|
| 151 |
+
user = self.get_current_user()
|
| 152 |
+
if user.validate_bank_password(old_bankpw):
|
| 153 |
+
if self.config.recaptcha_enabled:
|
| 154 |
+
self.verify_recaptcha()
|
| 155 |
+
else:
|
| 156 |
+
self.set_bankpassword()
|
| 157 |
+
else:
|
| 158 |
+
self.render_page(errors=["Invalid old password."])
|
| 159 |
+
|
| 160 |
+
def set_bankpassword(self):
|
| 161 |
+
user = self.get_current_user()
|
| 162 |
+
user.bank_password = self.get_argument('new_bpassword')
|
| 163 |
+
self.dbsession.add(user)
|
| 164 |
+
self.dbsession.commit()
|
| 165 |
+
self.render_page(success=['Successfully updated bank password'])
|
| 166 |
+
|
| 167 |
+
def verify_recaptcha(self):
|
| 168 |
+
''' Checks recaptcha '''
|
| 169 |
+
recaptcha_challenge = self.get_argument('recaptcha_challenge_field', '')
|
| 170 |
+
recaptcha_response = self.get_argument('recaptcha_response_field', '')
|
| 171 |
+
recaptcha_req_data = {
|
| 172 |
+
'privatekey': self.config.recaptcha_private_key,
|
| 173 |
+
'remoteip': self.request.remote_ip,
|
| 174 |
+
'challenge': recaptcha_challenge,
|
| 175 |
+
'response': recaptcha_response
|
| 176 |
+
}
|
| 177 |
+
try:
|
| 178 |
+
recaptcha_http = tornado.httpclient.AsyncHTTPClient()
|
| 179 |
+
recaptcha_req_body = urllib.urlencode(recaptcha_req_data)
|
| 180 |
+
recaptcha_http.fetch(RECAPTCHA_URL, self.recaptcha_callback,
|
| 181 |
+
method='POST',
|
| 182 |
+
body=recaptcha_req_body)
|
| 183 |
+
except tornado.httpclient.HTTPError:
|
| 184 |
+
logging.exception('Recaptcha AsyncHTTP request threw an exception')
|
| 185 |
+
self.recaptcha_callback(None)
|
| 186 |
+
self.render_page(errors=['Error making backend recaptcha request'])
|
| 187 |
+
|
| 188 |
+
def recaptcha_callback(self, response):
|
| 189 |
+
'''
|
| 190 |
+
Validates recaptcha response
|
| 191 |
+
Recaptcha docs: https://developers.google.com/recaptcha/docs/verify
|
| 192 |
+
'''
|
| 193 |
+
if response and response.body.startswith('true'):
|
| 194 |
+
self.set_bankpassword()
|
| 195 |
+
else:
|
| 196 |
+
self.render_page(errors=["Invalid captcha, try again"])
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class LogoutHandler(BaseHandler):
|
| 200 |
+
''' Log user out of current session '''
|
| 201 |
+
|
| 202 |
+
def get(self, *args, **kwargs):
|
| 203 |
+
''' Redirect '''
|
| 204 |
+
if self.session is not None:
|
| 205 |
+
self.redirect('/user')
|
| 206 |
+
else:
|
| 207 |
+
self.redirect('/login')
|
| 208 |
+
|
| 209 |
+
def post(self, *args, **kwargs):
|
| 210 |
+
''' Clears cookies and session data '''
|
| 211 |
+
if self.session is not None:
|
| 212 |
+
user = self.get_current_user()
|
| 213 |
+
EventManager.instance().deauth(user)
|
| 214 |
+
self.session.delete()
|
| 215 |
+
self.clear_all_cookies()
|
| 216 |
+
self.redirect("/")
|
pool/shard003/Python/0027441_test_simulations.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
import os
|
| 3 |
+
from plutokore import simulations
|
| 4 |
+
|
| 5 |
+
PLUTO_FIXTURE_DIR = os.path.join(
|
| 6 |
+
os.path.dirname(os.path.realpath(__file__)),
|
| 7 |
+
'data', )
|
| 8 |
+
|
| 9 |
+
@pytest.mark.datafiles(
|
| 10 |
+
os.path.join(PLUTO_FIXTURE_DIR, 'pluto'), keep_top_dir=True)
|
| 11 |
+
def test_get_last_timestep(datafiles):
|
| 12 |
+
assert len(datafiles.listdir()) == 1
|
| 13 |
+
path = str(datafiles.listdir()[0])
|
| 14 |
+
lt = simulations.get_last_timestep(path)
|
| 15 |
+
assert lt == 1003
|
pool/shard003/Python/0027444_documents.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Helper functions for working with Documents.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from django.core.files import File
|
| 6 |
+
|
| 7 |
+
from dateutil.parser import parse as dt_parse
|
| 8 |
+
from os import path
|
| 9 |
+
import subprocess
|
| 10 |
+
from urllib import parse
|
| 11 |
+
|
| 12 |
+
import requests
|
| 13 |
+
|
| 14 |
+
from scripts import pdf
|
| 15 |
+
from shared import files
|
| 16 |
+
from utils import extension
|
| 17 |
+
|
| 18 |
+
from .models import Image
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def save_from_url(doc, url, filename_base=None):
|
| 22 |
+
"""
|
| 23 |
+
Downloads the document at `url` and saves it locally, storing the path in
|
| 24 |
+
the given Document.
|
| 25 |
+
|
| 26 |
+
:param doc: a Document model
|
| 27 |
+
:param url: URL string
|
| 28 |
+
:param filename_base: optional subpath specifying where to save the
|
| 29 |
+
document
|
| 30 |
+
|
| 31 |
+
Returns a tuple: (success, status_code, updated)
|
| 32 |
+
"""
|
| 33 |
+
filename = path.basename(parse.urlsplit(url).path)
|
| 34 |
+
|
| 35 |
+
if filename_base:
|
| 36 |
+
filename = "{}.{}".format(filename_base, extension(filename))
|
| 37 |
+
|
| 38 |
+
exists = doc.document and path.exists(doc.document.path)
|
| 39 |
+
if exists:
|
| 40 |
+
published = doc.published
|
| 41 |
+
headers = {"If-Modified-Since": published.strftime("%a, %d %b %Y %H:%M:%S GMT")}
|
| 42 |
+
else:
|
| 43 |
+
headers = {}
|
| 44 |
+
|
| 45 |
+
with requests.get(url, headers=headers, stream=True) as response:
|
| 46 |
+
if response:
|
| 47 |
+
if response.status_code == 304:
|
| 48 |
+
return (True, response.status_code, False)
|
| 49 |
+
|
| 50 |
+
doc.document.save(filename, File(response.raw), save=False)
|
| 51 |
+
|
| 52 |
+
file_published = files.published_date(doc.document.path)
|
| 53 |
+
|
| 54 |
+
if file_published:
|
| 55 |
+
doc.published = file_published
|
| 56 |
+
elif "Last-Modified" in response.headers:
|
| 57 |
+
doc.published = dt_parse(response.headers["Last-Modified"])
|
| 58 |
+
|
| 59 |
+
doc.save()
|
| 60 |
+
return (True, response.status_code, exists)
|
| 61 |
+
else:
|
| 62 |
+
return (False, response.status_code, response.reason)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def save_images(doc):
|
| 66 |
+
if not doc.document:
|
| 67 |
+
raise Exception("Document has not been copied to the local filesystem.")
|
| 68 |
+
return []
|
| 69 |
+
|
| 70 |
+
path = doc.document.path
|
| 71 |
+
image_gen = pdf.extract_images(path)
|
| 72 |
+
|
| 73 |
+
images = []
|
| 74 |
+
# Do stuff with the images in the directory
|
| 75 |
+
for i, (image_data, ext, w, h) in enumerate(image_gen):
|
| 76 |
+
image = Image(proposal=doc.proposal, document=doc)
|
| 77 |
+
image.width = w
|
| 78 |
+
image.height = h
|
| 79 |
+
image.image.save("image-{:0>3}.{}".format(i, ext), image_data)
|
| 80 |
+
image.save()
|
| 81 |
+
images.append(image)
|
| 82 |
+
|
| 83 |
+
return images
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def generate_thumbnail(doc):
|
| 87 |
+
"Generate a Document thumbnail."
|
| 88 |
+
if not doc.document:
|
| 89 |
+
raise FileNotFoundError(
|
| 90 |
+
"Document has not been copied to the local filesystem")
|
| 91 |
+
|
| 92 |
+
doc_path = doc.document.path
|
| 93 |
+
|
| 94 |
+
# TODO: Dispatch on extension. Handle other common file types
|
| 95 |
+
if extension(doc_path) != "pdf":
|
| 96 |
+
return
|
| 97 |
+
|
| 98 |
+
out_prefix = path.join(path.dirname(doc_path), "thumbnail")
|
| 99 |
+
|
| 100 |
+
proc = subprocess.Popen(
|
| 101 |
+
[
|
| 102 |
+
"pdftoppm", "-jpeg", "-singlefile", "-scale-to", "200", doc_path,
|
| 103 |
+
out_prefix
|
| 104 |
+
],
|
| 105 |
+
stderr=subprocess.PIPE)
|
| 106 |
+
_, err = proc.communicate()
|
| 107 |
+
|
| 108 |
+
if proc.returncode:
|
| 109 |
+
raise Exception("Failed for document %s" % doc.pk, err)
|
| 110 |
+
|
| 111 |
+
thumb_path = out_prefix + path.extsep + "jpg"
|
| 112 |
+
with open(thumb_path, "rb") as thumb_file:
|
| 113 |
+
doc.thumbnail.save("thumbnail.jpg", File(thumb_file))
|
| 114 |
+
|
| 115 |
+
return thumb_path
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def extract_text(doc):
|
| 119 |
+
# Could consider storing the full extracted text of the document in
|
| 120 |
+
# the database and indexing it, rather than extracting it to a file.
|
| 121 |
+
text_path = path.join(path.dirname(doc.local_path), "text.txt")
|
| 122 |
+
|
| 123 |
+
if files.extract_text(doc.local_path, text_path):
|
| 124 |
+
doc.fulltext = text_path
|
| 125 |
+
doc.encoding = files.encoding(doc.local_path)
|
| 126 |
+
doc.save()
|
| 127 |
+
return True
|
| 128 |
+
|
| 129 |
+
return False
|