Upload folder using huggingface_hub (part 88)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- pool/shard007/Python/0069676_tagging.py +228 -0
- pool/shard007/Python/0069680_3003-playback_trajectory.py +53 -0
- pool/shard007/Python/0069687_coroutine.py +41 -0
- pool/shard007/Python/0069691_capture_device_capabilities.py +136 -0
- pool/shard007/Python/0069693_cmd_filter.py +105 -0
- pool/shard007/Python/0069694_gmin_rotamer.py +158 -0
- pool/shard007/Python/0069696_server.py +72 -0
- pool/shard007/Python/0069697_main.py +101 -0
- pool/shard007/Python/0069701_NotInClanModule.py +21 -0
- pool/shard007/Python/0069703_views.py +87 -0
- pool/shard007/Python/0069704_bazel_api_test.py +157 -0
- pool/shard007/Python/0069706_backup_database.py +71 -0
- pool/shard007/Python/0069709_run-on-all.py +32 -0
- pool/shard007/Python/0069710_file_data_source.py +189 -0
- pool/shard007/Python/0069713_iOS_private.py +225 -0
- pool/shard007/Python/0069718_ChangePasswordDlg.py +112 -0
- pool/shard007/Python/0069719_window.py +172 -0
- pool/shard007/Python/0069720_watchdog.py +232 -0
- pool/shard007/Python/0069723_q1.py +32 -0
- pool/shard007/Python/0069725_init__.py +89 -0
- pool/shard007/Python/0069728_helper.py +28 -0
- pool/shard007/Python/0069733_throttled.py +52 -0
- pool/shard007/Python/0069734_titansoftv.py +153 -0
- pool/shard007/Python/0069740_matchessourcefilter.py +55 -0
- pool/shard007/Python/0069741_makeparsed.py +65 -0
- pool/shard007/Python/0069751_contexts.py +78 -0
- pool/shard007/Python/0069758_1217_conveniences.py +59 -0
- pool/shard007/Python/0069761_ahlinux_to_ghost.py +235 -0
- pool/shard007/Python/0069765_init__.py +35 -0
- pool/shard007/Python/0069768_electrostatics_example.py +226 -0
- pool/shard007/Python/0069771_ledongli.py +117 -0
- pool/shard007/Python/0069776_demo.py +46 -0
- pool/shard007/Python/0069777_navigation.py +52 -0
- pool/shard007/Python/0069785_sensor_energymeter.py +137 -0
- pool/shard007/Python/0069789_gather_domain_token_stats.py +129 -0
- pool/shard007/Python/0069790_p240_search_a_2d_matrix_ii.py +87 -0
- pool/shard007/Python/0069793_test_http_spider.py +29 -0
- pool/shard007/Python/0069798_test_ftp.py +179 -0
- pool/shard007/Python/0069799_bin2obj.py +187 -0
- pool/shard007/Python/0069800_stap_gen_code.py +77 -0
- pool/shard007/Python/0069804_ro.py +71 -0
- pool/shard007/Python/0069812_web_views_test.py +94 -0
- pool/shard007/Python/0069816_urls.py +167 -0
- pool/shard007/Python/0069818_test_abstract_protein.py +56 -0
- pool/shard007/Python/0069820_storage.py +78 -0
- pool/shard007/Python/0069824_Hello.py +247 -0
- pool/shard007/Python/0069826_wiz_import_procurement_from_plan.py +53 -0
- pool/shard007/Python/0069831_test_footer.py +72 -0
- pool/shard007/Python/0069835_app_lib.py +75 -0
- pool/shard007/Python/0069849_oss_fs_impl.py +107 -0
pool/shard007/Python/0069676_tagging.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import shutil
|
| 4 |
+
import string
|
| 5 |
+
import os.path
|
| 6 |
+
import textwrap
|
| 7 |
+
import beets.autotag
|
| 8 |
+
from beets.mediafile import MediaFile
|
| 9 |
+
from beets.util import sanitize_path
|
| 10 |
+
from .utils import locate, ext_matcher
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
ALBUM_TEMPLATE = string.Template('$artist - $album ($year) [$format_info]')
|
| 14 |
+
AUDIO_FILE_TEMPLATE = string.Template('$number $title$extension')
|
| 15 |
+
RELEASE_DESCRIPTION_TEMPLATE = string.Template('''
|
| 16 |
+
Track list:
|
| 17 |
+
$track_list
|
| 18 |
+
'''.strip())
|
| 19 |
+
AUDIO_EXTENSIONS = ('.flac', '.mp3')
|
| 20 |
+
ALLOWED_EXTENSIONS = AUDIO_EXTENSIONS + ('.cue', '.log', '.gif', '.jpeg', '.jpg', '.md5', '.nfo', '.pdf', '.png',
|
| 21 |
+
'.sfv', '.txt')
|
| 22 |
+
BLOCKED_CHARS_REGEX = re.compile(r'[:?<>\*|"/]')
|
| 23 |
+
MAX_FILENAME_LENGTH = 180
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class InvalidFormatException(Exception):
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def directory_name(release):
|
| 31 |
+
'''
|
| 32 |
+
Returns the proper directory name for a Release.
|
| 33 |
+
'''
|
| 34 |
+
artist = textwrap.shorten(release.album_artist, width=50, placeholder='_')
|
| 35 |
+
album = textwrap.shorten(release.title, width=40, placeholder='_')
|
| 36 |
+
year = release.year
|
| 37 |
+
if release.bitrate == 'V0 (VBR)':
|
| 38 |
+
format_info = 'V0'
|
| 39 |
+
elif release.bitrate == '320':
|
| 40 |
+
format_info = '320'
|
| 41 |
+
else:
|
| 42 |
+
format_info = release.format
|
| 43 |
+
if release.medium != 'CD':
|
| 44 |
+
format_info = release.medium + ' ' + format_info
|
| 45 |
+
path = ALBUM_TEMPLATE.substitute(**locals())
|
| 46 |
+
if release.catalog_number:
|
| 47 |
+
path += ' {' + release.catalog_number + '}'
|
| 48 |
+
path = path.replace('/', '_').replace('\\', '_')
|
| 49 |
+
path = sanitize_path(path)
|
| 50 |
+
return path
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def audio_filename(path, is_compilation=False):
|
| 54 |
+
''''
|
| 55 |
+
Returns the proper filename for the audio file located at `path`.
|
| 56 |
+
|
| 57 |
+
Assumes that the audio file has already been properly tagged.
|
| 58 |
+
|
| 59 |
+
If `is_compilation` is True, it means the audio file is part of
|
| 60 |
+
a compilation, and thus the track artist will be included in the
|
| 61 |
+
filename.
|
| 62 |
+
'''
|
| 63 |
+
mediafile = MediaFile(path)
|
| 64 |
+
|
| 65 |
+
if mediafile.disctotal and mediafile.disc and mediafile.disctotal > 1:
|
| 66 |
+
number = '{}.{:02}'.format(mediafile.disc, mediafile.track)
|
| 67 |
+
else:
|
| 68 |
+
number = '{:02}'.format(mediafile.track)
|
| 69 |
+
|
| 70 |
+
if is_compilation:
|
| 71 |
+
title = '{} - {}'.format(mediafile.artist, mediafile.title)
|
| 72 |
+
else:
|
| 73 |
+
title = mediafile.title
|
| 74 |
+
|
| 75 |
+
_, extension = os.path.splitext(path)
|
| 76 |
+
filename = AUDIO_FILE_TEMPLATE.substitute(**locals())
|
| 77 |
+
filename = BLOCKED_CHARS_REGEX.sub('_', filename)
|
| 78 |
+
return filename
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def apply_metadata(release):
|
| 82 |
+
'''
|
| 83 |
+
Assuming that `release` has a valid AlbumMatch, this function will
|
| 84 |
+
apply the new metadata to the release's audio files.
|
| 85 |
+
'''
|
| 86 |
+
beets.autotag.apply_metadata(release.info, release.match.mapping)
|
| 87 |
+
for item, _ in release.match.mapping.items():
|
| 88 |
+
item.try_write()
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def fix_release_filenames(release, directory=None, copy=False):
|
| 92 |
+
'''
|
| 93 |
+
Renames a release and all of its files so that it has the proper
|
| 94 |
+
directory name and includes only allowed files with filenames less
|
| 95 |
+
than {} characters total.
|
| 96 |
+
|
| 97 |
+
If `directory` is specified, the release will be moved
|
| 98 |
+
there. Otherwise, it will be renamed in its current directory.
|
| 99 |
+
'''.format(MAX_FILENAME_LENGTH)
|
| 100 |
+
if directory is None:
|
| 101 |
+
directory = os.path.dirname(release.path)
|
| 102 |
+
|
| 103 |
+
output_dir = os.path.join(directory, directory_name(release))
|
| 104 |
+
os.makedirs(output_dir, exist_ok=not copy)
|
| 105 |
+
|
| 106 |
+
rename_audio_files(release, directory=output_dir, copy=copy)
|
| 107 |
+
rename_other_files(release, directory=output_dir, copy=copy)
|
| 108 |
+
|
| 109 |
+
release.path = output_dir
|
| 110 |
+
return release
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def rename_audio_files(release, directory, copy=False):
|
| 114 |
+
'''
|
| 115 |
+
Moves (or copies) `release.audio_files` to their proper location within `directory`.
|
| 116 |
+
|
| 117 |
+
Assumes that the audio files have already been properly tagged.
|
| 118 |
+
'''
|
| 119 |
+
for audio_file in release.audio_files:
|
| 120 |
+
filename = audio_filename(audio_file, is_compilation=release.type == 7)
|
| 121 |
+
path = os.path.join(directory, filename)
|
| 122 |
+
path = truncate_path(path)
|
| 123 |
+
if copy:
|
| 124 |
+
shutil.copy2(audio_file, path)
|
| 125 |
+
else:
|
| 126 |
+
shutil.move(audio_file, path)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def rename_other_files(release, directory, copy=False):
|
| 130 |
+
'''
|
| 131 |
+
Moves (or copies) `release.other_files` to their proper location within `directory`.
|
| 132 |
+
'''
|
| 133 |
+
for other_file in release.other_files:
|
| 134 |
+
relpath = os.path.relpath(other_file, start=release.path)
|
| 135 |
+
path = os.path.join(directory, relpath)
|
| 136 |
+
path = truncate_path(path)
|
| 137 |
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
| 138 |
+
if copy:
|
| 139 |
+
shutil.copy2(other_file, path)
|
| 140 |
+
else:
|
| 141 |
+
shutil.move(other_file, path)
|
| 142 |
+
|
| 143 |
+
def truncate_path(path):
|
| 144 |
+
'''
|
| 145 |
+
Truncates `path` to contain no more than {max_length} characters.
|
| 146 |
+
|
| 147 |
+
If `path` has fewer than {max_length} characters, it will be returned unchanged.
|
| 148 |
+
'''.format(max_length=MAX_FILENAME_LENGTH)
|
| 149 |
+
if len(path) <= MAX_FILENAME_LENGTH:
|
| 150 |
+
return path
|
| 151 |
+
|
| 152 |
+
base, ext = os.path.splitext(os.path.basename(path))
|
| 153 |
+
offset = MAX_FILENAME_LENGTH - len(path)
|
| 154 |
+
assert len(base) + offset > 0
|
| 155 |
+
return os.path.join(os.path.dirname(path), base[:offset] + ext)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def audio_files(path):
|
| 159 |
+
'''
|
| 160 |
+
Returns a list of all audio files within `path`.
|
| 161 |
+
'''
|
| 162 |
+
return sorted(locate(path, ext_matcher(*AUDIO_EXTENSIONS)))
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def allowed_files(path):
|
| 166 |
+
'''
|
| 167 |
+
Returns a list of all allowed files within `path`.
|
| 168 |
+
'''
|
| 169 |
+
return sorted(locate(path, ext_matcher(*ALLOWED_EXTENSIONS)))
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def log_files(path):
|
| 173 |
+
'''
|
| 174 |
+
Returns a list of all log files within `path`.
|
| 175 |
+
'''
|
| 176 |
+
return sorted(locate(path, ext_matcher('.log')))
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def audio_format(path):
|
| 180 |
+
'''
|
| 181 |
+
Returns the format (FLAC / MP3) of the release located at `path`.
|
| 182 |
+
'''
|
| 183 |
+
mediafile = MediaFile(audio_files(path)[0])
|
| 184 |
+
if mediafile.format == 'FLAC':
|
| 185 |
+
return 'FLAC'
|
| 186 |
+
elif mediafile.format == 'MP3':
|
| 187 |
+
return 'MP3'
|
| 188 |
+
raise InvalidFormatException('{} is not a valid audio release.'.format(path))
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def audio_bitrate(path):
|
| 192 |
+
'''
|
| 193 |
+
Returns the bitrate (Lossless / 24bit Lossless / 320 / V0 (VBR))
|
| 194 |
+
of the release located at `path`.
|
| 195 |
+
'''
|
| 196 |
+
mediafile = MediaFile(audio_files(path)[0])
|
| 197 |
+
if mediafile.format == 'FLAC' and mediafile.bitdepth == 24:
|
| 198 |
+
return '24bit Lossless'
|
| 199 |
+
elif mediafile.format == 'FLAC' and mediafile.bitdepth == 16:
|
| 200 |
+
return 'Lossless'
|
| 201 |
+
elif mediafile.format == 'MP3' and mediafile.bitrate == 320000:
|
| 202 |
+
return '320'
|
| 203 |
+
elif mediafile.format == 'MP3':
|
| 204 |
+
bitrates = [MediaFile(audio_file).bitrate for audio_file in audio_files(path)]
|
| 205 |
+
average_bitrate = sum(bitrates) / len(bitrates)
|
| 206 |
+
if average_bitrate >= 200000:
|
| 207 |
+
return 'V0 (VBR)'
|
| 208 |
+
raise InvalidFormatException('{} is not a valid audio release.'.format(path))
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def release_year(path):
|
| 212 |
+
'''
|
| 213 |
+
Returns the year in which the release located at `path` was released.
|
| 214 |
+
'''
|
| 215 |
+
match = re.search(r'\d{4}', path)
|
| 216 |
+
if match:
|
| 217 |
+
return int(match.group(0))
|
| 218 |
+
mediafile = MediaFile(audio_files(path)[0])
|
| 219 |
+
return mediafile.year
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def release_description(release):
|
| 223 |
+
'''
|
| 224 |
+
Returns a bbcode formatted description for `release`.
|
| 225 |
+
'''
|
| 226 |
+
track_list = ['[#]{}'.format(track.title) for track in release.info.tracks]
|
| 227 |
+
track_list = '\n'.join(track_list)
|
| 228 |
+
return RELEASE_DESCRIPTION_TEMPLATE.substitute(**locals())
|
pool/shard007/Python/0069680_3003-playback_trajectory.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# Software License Agreement (BSD License)
|
| 3 |
+
#
|
| 4 |
+
# Copyright (c) 2019, UFACTORY, Inc.
|
| 5 |
+
# All rights reserved.
|
| 6 |
+
#
|
| 7 |
+
# Author: Vinman <vinman.wen@ufactory.cc> <vinman.cub@gmail.com>
|
| 8 |
+
|
| 9 |
+
"""
|
| 10 |
+
Description: playback trajectory
|
| 11 |
+
1. requires firmware 1.2.0 and above support
|
| 12 |
+
2. need to record the trajectory in advance
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import sys
|
| 17 |
+
import time
|
| 18 |
+
|
| 19 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), '../../..'))
|
| 20 |
+
|
| 21 |
+
from xarm.wrapper import XArmAPI
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
#######################################################
|
| 25 |
+
"""
|
| 26 |
+
Just for test example
|
| 27 |
+
"""
|
| 28 |
+
if len(sys.argv) >= 2:
|
| 29 |
+
ip = sys.argv[1]
|
| 30 |
+
else:
|
| 31 |
+
try:
|
| 32 |
+
from configparser import ConfigParser
|
| 33 |
+
parser = ConfigParser()
|
| 34 |
+
parser.read('../robot.conf')
|
| 35 |
+
ip = parser.get('xArm', 'ip')
|
| 36 |
+
except:
|
| 37 |
+
ip = input('Please input the xArm ip address:')
|
| 38 |
+
if not ip:
|
| 39 |
+
print('input error, exit')
|
| 40 |
+
sys.exit(1)
|
| 41 |
+
########################################################
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
arm = XArmAPI(ip, is_radian=True)
|
| 45 |
+
arm.motion_enable(enable=True)
|
| 46 |
+
arm.set_mode(0)
|
| 47 |
+
arm.set_state(state=0)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
arm.load_trajectory('test.traj')
|
| 51 |
+
arm.playback_trajectory()
|
| 52 |
+
|
| 53 |
+
|
pool/shard007/Python/0069687_coroutine.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
#coding:utf-8
|
| 3 |
+
# Author : tuxpy
|
| 4 |
+
# Email : q8886888@qq.com.com
|
| 5 |
+
# Last modified : 2015-08-25 19:59:30
|
| 6 |
+
# Filename : coroutine.py
|
| 7 |
+
# Description :
|
| 8 |
+
import gevent
|
| 9 |
+
from gevent import Greenlet, monkey
|
| 10 |
+
from functools import wraps
|
| 11 |
+
|
| 12 |
+
class Coroutine(Greenlet):
|
| 13 |
+
def __init__(self, func, args = None, kwargs = None, callback = None):
|
| 14 |
+
Greenlet.__init__(self)
|
| 15 |
+
self._args = args or ()
|
| 16 |
+
self._kwargs = kwargs or {}
|
| 17 |
+
self._callback = callback
|
| 18 |
+
self._func = func
|
| 19 |
+
|
| 20 |
+
def _run(self):
|
| 21 |
+
error = None
|
| 22 |
+
result = None
|
| 23 |
+
try:
|
| 24 |
+
result = self._func(*self._args, **self._kwargs)
|
| 25 |
+
except Exception as e:
|
| 26 |
+
error = e
|
| 27 |
+
|
| 28 |
+
if self._callback:
|
| 29 |
+
self._callback(result, error)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def coroutine(func):
|
| 33 |
+
@wraps(func)
|
| 34 |
+
def wrap(*args, **kwargs):
|
| 35 |
+
monkey.patch_all()
|
| 36 |
+
callback = kwargs.pop('callback', None)
|
| 37 |
+
_coroutine = Coroutine(func, args, kwargs,
|
| 38 |
+
callback = callback)
|
| 39 |
+
_coroutine.start()
|
| 40 |
+
|
| 41 |
+
return wrap
|
pool/shard007/Python/0069691_capture_device_capabilities.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python
|
| 2 |
+
# Copyright 2014 The Chromium Authors. All rights reserved.
|
| 3 |
+
# Use of this source code is governed by a BSD-style license that can be
|
| 4 |
+
# found in the LICENSE file.
|
| 5 |
+
|
| 6 |
+
"""Code generator DeviceCapabilities literal."""
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import ctypes
|
| 10 |
+
import evdev
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
TEST_DATA_GROUP_SIZE = 64 # Aligns with sysfs on 64-bit devices.
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def bits_to_groups(bits):
|
| 19 |
+
return (bits + TEST_DATA_GROUP_SIZE - 1) / TEST_DATA_GROUP_SIZE
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# As in /sys/class/input/input*/capabilities/*
|
| 23 |
+
def serialize_bitfield(bitfield, max_bit):
|
| 24 |
+
result = ""
|
| 25 |
+
group_count = bits_to_groups(max_bit)
|
| 26 |
+
for group in xrange(group_count - 1, -1, -1):
|
| 27 |
+
group_val = 0
|
| 28 |
+
for group_bit in xrange(TEST_DATA_GROUP_SIZE):
|
| 29 |
+
code = group * TEST_DATA_GROUP_SIZE + group_bit
|
| 30 |
+
if code in bitfield:
|
| 31 |
+
group_val |= (1 << group_bit)
|
| 32 |
+
if group_val or result:
|
| 33 |
+
result += '%x' % group_val
|
| 34 |
+
if group:
|
| 35 |
+
result += ' '
|
| 36 |
+
if not result:
|
| 37 |
+
return '0'
|
| 38 |
+
return result
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def dump_absinfo(out, capabilities, identifier):
|
| 42 |
+
out.write('const DeviceAbsoluteAxis %s[] = {\n' % identifier)
|
| 43 |
+
|
| 44 |
+
for code, absinfo in capabilities[evdev.ecodes.EV_ABS]:
|
| 45 |
+
# Set value := 0 to make it deterministic.
|
| 46 |
+
code_name = evdev.ecodes.bytype[evdev.ecodes.EV_ABS][code]
|
| 47 |
+
absinfo_struct = (0, absinfo.min, absinfo.max, absinfo.fuzz, absinfo.flat,
|
| 48 |
+
absinfo.resolution)
|
| 49 |
+
data = (code_name,) + absinfo_struct
|
| 50 |
+
out.write(' {%s, {%d, %d, %d, %d, %d, %d}},\n' % data)
|
| 51 |
+
|
| 52 |
+
out.write('};\n')
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def dump_capabilities(out, dev, identifier):
|
| 56 |
+
capabilities = dev.capabilities()
|
| 57 |
+
has_abs = evdev.ecodes.EV_ABS in capabilities
|
| 58 |
+
|
| 59 |
+
sysfs_path = '/sys/class/input/' + os.path.basename(dev.fn)
|
| 60 |
+
|
| 61 |
+
# python-evdev is missing some features
|
| 62 |
+
uniq = open(sysfs_path + '/device/uniq', 'r').read().strip()
|
| 63 |
+
prop = open(sysfs_path + '/device/properties', 'r').read().strip()
|
| 64 |
+
ff = open(sysfs_path + '/device/capabilities/ff', 'r').read().strip()
|
| 65 |
+
|
| 66 |
+
# python-evdev parses the id wrong.
|
| 67 |
+
bustype = open(sysfs_path + '/device/id/bustype', 'r').read().strip()
|
| 68 |
+
vendor = open(sysfs_path + '/device/id/vendor', 'r').read().strip()
|
| 69 |
+
product = open(sysfs_path + '/device/id/product', 'r').read().strip()
|
| 70 |
+
version = open(sysfs_path + '/device/id/version', 'r').read().strip()
|
| 71 |
+
|
| 72 |
+
# python-evdev drops EV_REP from the event set.
|
| 73 |
+
ev = open(sysfs_path + '/device/capabilities/ev', 'r').read().strip()
|
| 74 |
+
|
| 75 |
+
if ctypes.sizeof(ctypes.c_long()) != 8:
|
| 76 |
+
# /sys/class/input/*/properties format is word size dependent.
|
| 77 |
+
# Could be fixed by regrouping but for now, just raise an error.
|
| 78 |
+
raise ValueError("Must be run on 64-bit machine")
|
| 79 |
+
|
| 80 |
+
key_bits = capabilities.get(evdev.ecodes.EV_KEY, [])
|
| 81 |
+
rel_bits = capabilities.get(evdev.ecodes.EV_REL, [])
|
| 82 |
+
abs_bits = [abs[0] for abs in capabilities.get(evdev.ecodes.EV_ABS, [])]
|
| 83 |
+
msc_bits = capabilities.get(evdev.ecodes.EV_MSC, [])
|
| 84 |
+
sw_bits = capabilities.get(evdev.ecodes.EV_SW, [])
|
| 85 |
+
led_bits = capabilities.get(evdev.ecodes.EV_LED, [])
|
| 86 |
+
|
| 87 |
+
fields = [
|
| 88 |
+
('path', os.path.realpath(sysfs_path)),
|
| 89 |
+
('name', dev.name),
|
| 90 |
+
('phys', dev.phys),
|
| 91 |
+
('uniq', uniq),
|
| 92 |
+
('bustype', bustype),
|
| 93 |
+
('vendor', vendor),
|
| 94 |
+
('product', product),
|
| 95 |
+
('version', version),
|
| 96 |
+
('prop', prop),
|
| 97 |
+
('ev', ev),
|
| 98 |
+
('key', serialize_bitfield(key_bits, evdev.ecodes.KEY_CNT)),
|
| 99 |
+
('rel', serialize_bitfield(rel_bits, evdev.ecodes.REL_CNT)),
|
| 100 |
+
('abs', serialize_bitfield(abs_bits, evdev.ecodes.ABS_CNT)),
|
| 101 |
+
('msc', serialize_bitfield(msc_bits, evdev.ecodes.MSC_CNT)),
|
| 102 |
+
('sw', serialize_bitfield(sw_bits, evdev.ecodes.SW_CNT)),
|
| 103 |
+
('led', serialize_bitfield(led_bits, evdev.ecodes.LED_CNT)),
|
| 104 |
+
('ff', ff),
|
| 105 |
+
]
|
| 106 |
+
|
| 107 |
+
if has_abs:
|
| 108 |
+
absinfo_identifier = identifier + 'AbsAxes'
|
| 109 |
+
dump_absinfo(out, capabilities, absinfo_identifier)
|
| 110 |
+
|
| 111 |
+
out.write('const DeviceCapabilities %s = {\n' % identifier)
|
| 112 |
+
for name, val in fields:
|
| 113 |
+
out.write(' /* %s */ "%s",\n' % (name, val))
|
| 114 |
+
|
| 115 |
+
if has_abs:
|
| 116 |
+
out.write(' %s,\n' % absinfo_identifier)
|
| 117 |
+
out.write(' arraysize(%s),\n' % absinfo_identifier)
|
| 118 |
+
|
| 119 |
+
out.write('};\n')
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def main(argv):
|
| 123 |
+
parser = argparse.ArgumentParser()
|
| 124 |
+
parser.add_argument('device')
|
| 125 |
+
parser.add_argument('identifier')
|
| 126 |
+
args = parser.parse_args(argv)
|
| 127 |
+
|
| 128 |
+
dev = evdev.InputDevice(args.device)
|
| 129 |
+
out = sys.stdout
|
| 130 |
+
|
| 131 |
+
dump_capabilities(out, dev, args.identifier)
|
| 132 |
+
return 0
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
if __name__ == '__main__':
|
| 136 |
+
sys.exit(main(sys.argv[1:]))
|
pool/shard007/Python/0069693_cmd_filter.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
#
|
| 3 |
+
import re
|
| 4 |
+
from rest_framework import serializers
|
| 5 |
+
|
| 6 |
+
from django.utils.translation import ugettext_lazy as _
|
| 7 |
+
from ..models import CommandFilter, CommandFilterRule
|
| 8 |
+
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
| 9 |
+
from orgs.utils import tmp_to_root_org
|
| 10 |
+
from common.utils import get_object_or_none, lazyproperty
|
| 11 |
+
from terminal.models import Session
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class CommandFilterSerializer(BulkOrgResourceModelSerializer):
|
| 15 |
+
|
| 16 |
+
class Meta:
|
| 17 |
+
model = CommandFilter
|
| 18 |
+
fields_mini = ['id', 'name']
|
| 19 |
+
fields_small = fields_mini + [
|
| 20 |
+
'org_id', 'org_name',
|
| 21 |
+
'is_active',
|
| 22 |
+
'date_created', 'date_updated',
|
| 23 |
+
'comment', 'created_by',
|
| 24 |
+
]
|
| 25 |
+
fields_fk = ['rules']
|
| 26 |
+
fields_m2m = ['users', 'user_groups', 'system_users', 'assets', 'applications']
|
| 27 |
+
fields = fields_small + fields_fk + fields_m2m
|
| 28 |
+
extra_kwargs = {
|
| 29 |
+
'rules': {'read_only': True}
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class CommandFilterRuleSerializer(BulkOrgResourceModelSerializer):
|
| 34 |
+
type_display = serializers.ReadOnlyField(source='get_type_display')
|
| 35 |
+
action_display = serializers.ReadOnlyField(source='get_action_display')
|
| 36 |
+
|
| 37 |
+
class Meta:
|
| 38 |
+
model = CommandFilterRule
|
| 39 |
+
fields_mini = ['id']
|
| 40 |
+
fields_small = fields_mini + [
|
| 41 |
+
'type', 'type_display', 'content', 'ignore_case', 'pattern', 'priority',
|
| 42 |
+
'action', 'action_display', 'reviewers',
|
| 43 |
+
'date_created', 'date_updated',
|
| 44 |
+
'comment', 'created_by',
|
| 45 |
+
]
|
| 46 |
+
fields_fk = ['filter']
|
| 47 |
+
fields = fields_small + fields_fk
|
| 48 |
+
|
| 49 |
+
def __init__(self, *args, **kwargs):
|
| 50 |
+
super().__init__(*args, **kwargs)
|
| 51 |
+
self.set_action_choices()
|
| 52 |
+
|
| 53 |
+
def set_action_choices(self):
|
| 54 |
+
from django.conf import settings
|
| 55 |
+
action = self.fields.get('action')
|
| 56 |
+
if not action:
|
| 57 |
+
return
|
| 58 |
+
choices = action._choices
|
| 59 |
+
if not settings.XPACK_ENABLED:
|
| 60 |
+
choices.pop(CommandFilterRule.ActionChoices.confirm, None)
|
| 61 |
+
action._choices = choices
|
| 62 |
+
|
| 63 |
+
def validate_content(self, content):
|
| 64 |
+
tp = self.initial_data.get("type")
|
| 65 |
+
if tp == CommandFilterRule.TYPE_COMMAND:
|
| 66 |
+
regex = CommandFilterRule.construct_command_regex(content)
|
| 67 |
+
else:
|
| 68 |
+
regex = content
|
| 69 |
+
ignore_case = self.initial_data.get('ignore_case')
|
| 70 |
+
succeed, error, pattern = CommandFilterRule.compile_regex(regex, ignore_case)
|
| 71 |
+
if not succeed:
|
| 72 |
+
raise serializers.ValidationError(error)
|
| 73 |
+
return content
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class CommandConfirmSerializer(serializers.Serializer):
|
| 77 |
+
session_id = serializers.UUIDField(required=True, allow_null=False)
|
| 78 |
+
cmd_filter_rule_id = serializers.UUIDField(required=True, allow_null=False)
|
| 79 |
+
run_command = serializers.CharField(required=True, allow_null=False)
|
| 80 |
+
|
| 81 |
+
def __init__(self, *args, **kwargs):
|
| 82 |
+
super().__init__(*args, **kwargs)
|
| 83 |
+
self.session = None
|
| 84 |
+
self.cmd_filter_rule = None
|
| 85 |
+
|
| 86 |
+
def validate_session_id(self, session_id):
|
| 87 |
+
self.session = self.validate_object_exist(Session, session_id)
|
| 88 |
+
return session_id
|
| 89 |
+
|
| 90 |
+
def validate_cmd_filter_rule_id(self, cmd_filter_rule_id):
|
| 91 |
+
self.cmd_filter_rule = self.validate_object_exist(CommandFilterRule, cmd_filter_rule_id)
|
| 92 |
+
return cmd_filter_rule_id
|
| 93 |
+
|
| 94 |
+
@staticmethod
|
| 95 |
+
def validate_object_exist(model, field_id):
|
| 96 |
+
with tmp_to_root_org():
|
| 97 |
+
obj = get_object_or_none(model, id=field_id)
|
| 98 |
+
if not obj:
|
| 99 |
+
error = '{} Model object does not exist'.format(model.__name__)
|
| 100 |
+
raise serializers.ValidationError(error)
|
| 101 |
+
return obj
|
| 102 |
+
|
| 103 |
+
@lazyproperty
|
| 104 |
+
def org(self):
|
| 105 |
+
return self.session.org
|
pool/shard007/Python/0069694_gmin_rotamer.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import joblib
|
| 2 |
+
import re
|
| 3 |
+
import os.path
|
| 4 |
+
import rotamer.topology.read_amber_prmtop as prmtop
|
| 5 |
+
|
| 6 |
+
kcal_mol_in_joules = 4184
|
| 7 |
+
gas_constant = 8.3145
|
| 8 |
+
|
| 9 |
+
class RotamerMove():
|
| 10 |
+
def __init__(self, pickle_filename=None, prmtop_filename=None, settings_filename=None):
|
| 11 |
+
"""
|
| 12 |
+
Initialise from either a file or a pickled RotamerMove instance.
|
| 13 |
+
"""
|
| 14 |
+
if pickle_filename:
|
| 15 |
+
self = joblib.load(pickle_filename)
|
| 16 |
+
elif prmtop_filename:
|
| 17 |
+
self.parse_prmtop(prmtop_filename)
|
| 18 |
+
self.moving_residues = []
|
| 19 |
+
self.deps = set()
|
| 20 |
+
self.save_file = None
|
| 21 |
+
if settings_filename:
|
| 22 |
+
self.read_settings(settings_filename)
|
| 23 |
+
else:
|
| 24 |
+
raise ValueError("Either pickle_filename or prmtop_filename must be specified.")
|
| 25 |
+
|
| 26 |
+
def parse_prmtop(self, prmtop_filename):
|
| 27 |
+
self.molecule = prmtop.parse_topology_file(prmtop_filename)
|
| 28 |
+
|
| 29 |
+
def read_settings(self, settings_filename):
|
| 30 |
+
"""
|
| 31 |
+
Read settings for the rotamer move, which determines the residues that move and which distribution the move is
|
| 32 |
+
selected from.
|
| 33 |
+
|
| 34 |
+
:param settings_filename: filename of file containing settings
|
| 35 |
+
"""
|
| 36 |
+
with open(settings_filename, "r") as settings_file:
|
| 37 |
+
for line in settings_file:
|
| 38 |
+
# List comp splits the string and gets rid of empty strings
|
| 39 |
+
tokenized = [tok for tok in re.split("[ ,]", line) if tok]
|
| 40 |
+
# Go through the possible options
|
| 41 |
+
# Residue list
|
| 42 |
+
if re.match("res", tokenized[0]):
|
| 43 |
+
self.moving_residues = self.parse_res_list(" ".join(tokenized[1:]))
|
| 44 |
+
# Dependencies
|
| 45 |
+
elif any([re.match("depend", tok) for tok in tokenized]):
|
| 46 |
+
if any(["bb" in tok or "backbone" in tok for tok in tokenized]):
|
| 47 |
+
self.deps.add("backbone")
|
| 48 |
+
if any(["neighbour" in tok or "neighbor" in tok for tok in tokenized]):
|
| 49 |
+
self.deps.add("neighbour_idents")
|
| 50 |
+
if any(["sidechain" in tok or "sc" in tok for tok in tokenized]):
|
| 51 |
+
self.deps.add("neighbour_identities")
|
| 52 |
+
self.deps.add("neighbour_sidechains")
|
| 53 |
+
# Rotamer distribution temperature
|
| 54 |
+
elif re.match("temp", tokenized[0]):
|
| 55 |
+
kelvin = any(["K" in tok for tok in tokenized[1:]])
|
| 56 |
+
if kelvin:
|
| 57 |
+
tokenized[1:] = [tok.strip("K ") for tok in tokenized[1:] if tok.strip("K ")]
|
| 58 |
+
self.temp = float(tokenized[1]) * gas_constant / kcal_mol_in_joules
|
| 59 |
+
else:
|
| 60 |
+
self.temp = float(tokenized[1])
|
| 61 |
+
|
| 62 |
+
def print_settings(self):
|
| 63 |
+
"""
|
| 64 |
+
Prints the current settings for the rotamer moves.
|
| 65 |
+
"""
|
| 66 |
+
for k, v in self.__dict__.items():
|
| 67 |
+
print k, v
|
| 68 |
+
|
| 69 |
+
def save_move(self):
|
| 70 |
+
"""
|
| 71 |
+
Pickles the object, to save the move parameters between subsequent GMIN steps.
|
| 72 |
+
|
| 73 |
+
:return:
|
| 74 |
+
"""
|
| 75 |
+
if not self.save_file:
|
| 76 |
+
import tempfile
|
| 77 |
+
savedir = tempfile.mkdtemp()
|
| 78 |
+
self.save_file = os.path.join(savedir, "rotamer.pkl")
|
| 79 |
+
joblib.dump(self, self.save_file)
|
| 80 |
+
return self.save_file
|
| 81 |
+
|
| 82 |
+
def parse_res_list(self, res_list):
|
| 83 |
+
"""
|
| 84 |
+
Parses the given residue list and returns a list of matching residue indices.
|
| 85 |
+
|
| 86 |
+
:param res_list: list of residues according to the defined format
|
| 87 |
+
:return: list of indices of matching residues
|
| 88 |
+
"""
|
| 89 |
+
res_idxs = set()
|
| 90 |
+
# Get rid of whitespace around hyphens, just in case
|
| 91 |
+
res_list = re.sub(" - ", "-", res_list)
|
| 92 |
+
# Split into tokens
|
| 93 |
+
res_list = res_list.split()
|
| 94 |
+
subtract = False
|
| 95 |
+
for i, res in enumerate(res_list):
|
| 96 |
+
if res == "not":
|
| 97 |
+
subtract = True
|
| 98 |
+
continue
|
| 99 |
+
elif "-" in res:
|
| 100 |
+
res_sublist = range(int(res.split("-")[0]), int(res.split("-")[1]) + 1)
|
| 101 |
+
else:
|
| 102 |
+
res_sublist = [int(res)]
|
| 103 |
+
if subtract:
|
| 104 |
+
for r in res_sublist:
|
| 105 |
+
res_idxs.remove(r)
|
| 106 |
+
subtract = False
|
| 107 |
+
else:
|
| 108 |
+
for r in res_sublist:
|
| 109 |
+
res_idxs.add(r)
|
| 110 |
+
return list(res_idxs)
|
| 111 |
+
|
| 112 |
+
def __call__(self, coords):
|
| 113 |
+
"""
|
| 114 |
+
Performs the rotamer move on a given set of coordinates.
|
| 115 |
+
|
| 116 |
+
There are a few possible dependency levels:
|
| 117 |
+
|
| 118 |
+
1) Identity of the amino acid being moved.
|
| 119 |
+
|
| 120 |
+
In this case, we build a partition function by averaging over all of the neighbours and all neighbouring
|
| 121 |
+
configurations.
|
| 122 |
+
|
| 123 |
+
2) Identity of the amino acid and configuration of its backbone (phi/psi angles).
|
| 124 |
+
|
| 125 |
+
In this case, we use variable kernel density estimates to construct conditional distributions of phi/psi
|
| 126 |
+
angles as a function of rotamer states, and invert these using Bayes' rule to obtain P(r|phi, psi) (from
|
| 127 |
+
Shapovalov MV and Dunbrack RL, Structure, 19, pp844-858, 2011)
|
| 128 |
+
|
| 129 |
+
3) Identity of the amino acid and identity of the neighbouring amino acids.
|
| 130 |
+
|
| 131 |
+
This is the same as case 1, but constructing separate partition functions for each pair of amino acid
|
| 132 |
+
neighbours (i.e. 22 * 22 = 484 in total).
|
| 133 |
+
|
| 134 |
+
4) Identity of the amino acid, its neighbours and rotameric states of the neighbours.
|
| 135 |
+
|
| 136 |
+
This is the same as case 3, but constructing a conditional probability for the central rotamers in terms of
|
| 137 |
+
the neighbouring rotameric states. *** TODO: Should this be an inversion of P(r_i-1, r_i+1 | r_i)? ***
|
| 138 |
+
|
| 139 |
+
5) Combinations of 3 and 4 with backbone configurations.
|
| 140 |
+
|
| 141 |
+
Each of these requires a slightly different method for calculating the probability distributions and different
|
| 142 |
+
amounts of structural information prior to making a move.
|
| 143 |
+
|
| 144 |
+
:param coords: Initial coordinates
|
| 145 |
+
:return: New coordinates (after the move)
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
if __name__ == "__main__":
|
| 151 |
+
move = RotamerMove(prmtop_filename="../tests/data/ARG_LYS_ASN.prmtop")
|
| 152 |
+
move.read_settings("../tests/data/example_settings")
|
| 153 |
+
# move.print_settings()
|
| 154 |
+
location = move.save_move()
|
| 155 |
+
joblib.dump(move, location)
|
| 156 |
+
move_copy = RotamerMove(pickle_filename=location)
|
| 157 |
+
move_copy = joblib.load(location)
|
| 158 |
+
move_copy.print_settings()
|
pool/shard007/Python/0069696_server.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
import os
|
| 4 |
+
from flask import Flask, request, redirect, url_for
|
| 5 |
+
from werkzeug import secure_filename
|
| 6 |
+
|
| 7 |
+
# change this as you see fit
|
| 8 |
+
#filename = sys.argv[1]
|
| 9 |
+
#print("filename : " + filename)
|
| 10 |
+
#image_path = sys.argv[1]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# Loads label file, strips off carriage return
|
| 15 |
+
label_lines = [line.rstrip() for line
|
| 16 |
+
in tf.gfile.GFile("labels.txt")]
|
| 17 |
+
|
| 18 |
+
# Unpersists graph from file
|
| 19 |
+
with tf.gfile.FastGFile("model.pb", 'rb') as f:
|
| 20 |
+
graph_def = tf.GraphDef()
|
| 21 |
+
graph_def.ParseFromString(f.read())
|
| 22 |
+
_ = tf.import_graph_def(graph_def, name='')
|
| 23 |
+
|
| 24 |
+
sess = tf.Session()
|
| 25 |
+
# Feed the image_data as input to the graph and get first prediction
|
| 26 |
+
softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
|
| 27 |
+
print("loaded tensor")
|
| 28 |
+
|
| 29 |
+
UPLOAD_FOLDER = '/tmp/'
|
| 30 |
+
ALLOWED_EXTENSIONS = set(['jpg', 'jpeg'])
|
| 31 |
+
|
| 32 |
+
app = Flask(__name__)
|
| 33 |
+
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
| 34 |
+
|
| 35 |
+
def allowed_file(filename):
|
| 36 |
+
return '.' in filename and \
|
| 37 |
+
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
|
| 38 |
+
|
| 39 |
+
@app.route("/", methods=['GET', 'POST'])
|
| 40 |
+
def index():
|
| 41 |
+
if request.method == 'POST':
|
| 42 |
+
file = request.files['file']
|
| 43 |
+
if file and allowed_file(file.filename):
|
| 44 |
+
filename = secure_filename(file.filename)
|
| 45 |
+
image_path =os.path.join(app.config['UPLOAD_FOLDER'], filename)
|
| 46 |
+
file.save(image_path)
|
| 47 |
+
# Read in the image_data
|
| 48 |
+
image_data = tf.gfile.FastGFile(image_path, 'rb').read()
|
| 49 |
+
predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data})
|
| 50 |
+
|
| 51 |
+
# Sort to show labels of first prediction in order of confidence
|
| 52 |
+
top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]
|
| 53 |
+
|
| 54 |
+
for node_id in top_k:
|
| 55 |
+
human_string = label_lines[node_id]
|
| 56 |
+
score = predictions[0][node_id]
|
| 57 |
+
print('%s (score = %.5f)' % (human_string, score))
|
| 58 |
+
|
| 59 |
+
return redirect(url_for('index'))
|
| 60 |
+
return """
|
| 61 |
+
<!doctype html>
|
| 62 |
+
<title>Upload new File</title>
|
| 63 |
+
<h1>Upload new File</h1>
|
| 64 |
+
<form action="" method=post enctype=multipart/form-data>
|
| 65 |
+
<p><input type=file name=file>
|
| 66 |
+
<input type=submit value=Upload>
|
| 67 |
+
</form>
|
| 68 |
+
<p>%s</p>
|
| 69 |
+
""" % "<br>".join(os.listdir(app.config['UPLOAD_FOLDER'],))
|
| 70 |
+
|
| 71 |
+
if __name__ == "__main__":
|
| 72 |
+
app.run(host='0.0.0.0', port=5001, debug=True)
|
pool/shard007/Python/0069697_main.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
#
|
| 4 |
+
# === This file is part of Calamares - <http://github.com/calamares> ===
|
| 5 |
+
#
|
| 6 |
+
# Copyright 2014, Philip Müller <philm@manjaro.org>
|
| 7 |
+
# Copyright 2014, Teo Mrnjavac <teo@kde.org>
|
| 8 |
+
# Copyright 2017, Alf Gaida <agaida@siduction.org>
|
| 9 |
+
#
|
| 10 |
+
# Calamares is free software: you can redistribute it and/or modify
|
| 11 |
+
# it under the terms of the GNU General Public License as published by
|
| 12 |
+
# the Free Software Foundation, either version 3 of the License, or
|
| 13 |
+
# (at your option) any later version.
|
| 14 |
+
#
|
| 15 |
+
# Calamares is distributed in the hope that it will be useful,
|
| 16 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 17 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 18 |
+
# GNU General Public License for more details.
|
| 19 |
+
#
|
| 20 |
+
# You should have received a copy of the GNU General Public License
|
| 21 |
+
# along with Calamares. If not, see <http://www.gnu.org/licenses/>.
|
| 22 |
+
|
| 23 |
+
import libcalamares
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def run():
|
| 27 |
+
"""
|
| 28 |
+
Setup systemd services
|
| 29 |
+
"""
|
| 30 |
+
services = libcalamares.job.configuration['services']
|
| 31 |
+
targets = libcalamares.job.configuration['targets']
|
| 32 |
+
disable = libcalamares.job.configuration['disable']
|
| 33 |
+
|
| 34 |
+
# note that the "systemctl enable" and "systemctl disable" commands used
|
| 35 |
+
# here will work in a chroot; in fact, they are the only systemctl commands
|
| 36 |
+
# that support that, see:
|
| 37 |
+
# http://0pointer.de/blog/projects/changing-roots.html
|
| 38 |
+
|
| 39 |
+
# enable services
|
| 40 |
+
for svc in services:
|
| 41 |
+
ec = libcalamares.utils.target_env_call(
|
| 42 |
+
['systemctl', 'enable', '{}.service'.format(svc['name'])]
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
if ec != 0:
|
| 46 |
+
if svc['mandatory']:
|
| 47 |
+
return ("Cannot enable systemd service {}".format(svc['name']),
|
| 48 |
+
"systemctl enable call in chroot returned error code "
|
| 49 |
+
"{}".format(ec)
|
| 50 |
+
)
|
| 51 |
+
else:
|
| 52 |
+
libcalamares.utils.debug(
|
| 53 |
+
"Cannot enable systemd service {}".format(svc['name'])
|
| 54 |
+
)
|
| 55 |
+
libcalamares.utils.debug(
|
| 56 |
+
"systemctl enable call in chroot returned error code "
|
| 57 |
+
"{}".format(ec)
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
# enable targets
|
| 61 |
+
for tgt in targets:
|
| 62 |
+
ec = libcalamares.utils.target_env_call(
|
| 63 |
+
['systemctl', 'enable', '{}.target'.format(tgt['name'])]
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
if ec != 0:
|
| 67 |
+
if tgt['mandatory']:
|
| 68 |
+
return ("Cannot enable systemd target {}".format(tgt['name']),
|
| 69 |
+
"systemctl enable call in chroot returned error code"
|
| 70 |
+
"{}".format(ec)
|
| 71 |
+
)
|
| 72 |
+
else:
|
| 73 |
+
libcalamares.utils.debug(
|
| 74 |
+
"Cannot enable systemd target {}".format(tgt['name'])
|
| 75 |
+
)
|
| 76 |
+
libcalamares.utils.debug(
|
| 77 |
+
"systemctl enable call in chroot returned error code "
|
| 78 |
+
"{}".format(ec)
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
for dbl in disable:
|
| 82 |
+
ec = libcalamares.utils.target_env_call(
|
| 83 |
+
['systemctl', 'disable', '{}.service'.format(dbl['name'])]
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
if ec != 0:
|
| 87 |
+
if dbl['mandatory']:
|
| 88 |
+
return ("Cannot disable systemd service"
|
| 89 |
+
"{}".format(dbl['name']),
|
| 90 |
+
"systemctl disable call in chroot returned error code"
|
| 91 |
+
"{}".format(ec))
|
| 92 |
+
else:
|
| 93 |
+
libcalamares.utils.debug(
|
| 94 |
+
"Cannot disable systemd service {}".format(dbl['name'])
|
| 95 |
+
)
|
| 96 |
+
libcalamares.utils.debug(
|
| 97 |
+
"systemctl disable call in chroot returned error code "
|
| 98 |
+
"{}".format(ec)
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
return None
|
pool/shard007/Python/0069701_NotInClanModule.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from cwbot.modules.BaseKmailModule import BaseKmailModule
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class NotInClanModule(BaseKmailModule):
|
| 5 |
+
"""
|
| 6 |
+
A module that returns a kmail from somebody not in the clan.
|
| 7 |
+
|
| 8 |
+
No configuration options.
|
| 9 |
+
"""
|
| 10 |
+
requiredCapabilities = ['kmail']
|
| 11 |
+
_name = "nonclan"
|
| 12 |
+
|
| 13 |
+
def __init__(self, manager, identity, config):
|
| 14 |
+
super(NotInClanModule, self).__init__(manager, identity, config)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _processKmail(self, message):
|
| 18 |
+
if not self.parent.checkClan(message.uid):
|
| 19 |
+
return (self.newMessage(message.uid, "You're not in my clan.")
|
| 20 |
+
.addItems(message.items))
|
| 21 |
+
return None
|
pool/shard007/Python/0069703_views.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
##########################################################################################
|
| 3 |
+
# Developer: Luan,Jingchao Project: HuMaIN (http://humain.acis.ufl.edu)
|
| 4 |
+
# Description:
|
| 5 |
+
# Receive OCRopus segmentation service requests from user, call segmentation function
|
| 6 |
+
# and get the output, and then return the output or error info to user.
|
| 7 |
+
##########################################################################################
|
| 8 |
+
# Copyright 2017 Advanced Computing and Information Systems (ACIS) Lab - UF
|
| 9 |
+
# (https://www.acis.ufl.edu/)
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
##########################################################################################
|
| 22 |
+
|
| 23 |
+
from __future__ import unicode_literals
|
| 24 |
+
from rest_framework.decorators import api_view
|
| 25 |
+
from rest_framework.response import Response
|
| 26 |
+
from rest_framework import status
|
| 27 |
+
from django.views.decorators.csrf import csrf_exempt
|
| 28 |
+
from django.http import HttpResponse, JsonResponse
|
| 29 |
+
from django.conf import settings
|
| 30 |
+
from django.shortcuts import render
|
| 31 |
+
from .segmentation import segmentation_exec
|
| 32 |
+
import sys, os, os.path, zipfile, StringIO
|
| 33 |
+
import logging
|
| 34 |
+
|
| 35 |
+
reload(sys)
|
| 36 |
+
sys.setdefaultencoding('utf8')
|
| 37 |
+
|
| 38 |
+
def index(request):
|
| 39 |
+
return render(request, 'index.html')
|
| 40 |
+
|
| 41 |
+
@csrf_exempt
|
| 42 |
+
@api_view(['GET', 'POST'])
|
| 43 |
+
def segmentationView(request, format=None):
|
| 44 |
+
logger = logging.getLogger('segmentation')
|
| 45 |
+
if request.data.get('image') is None:
|
| 46 |
+
logger.error("Please upload only one image")
|
| 47 |
+
return Response("ERROR: Please upload an image", status=status.HTTP_400_BAD_REQUEST)
|
| 48 |
+
|
| 49 |
+
### Receive parameters set by user
|
| 50 |
+
parameters = request.data.dict()
|
| 51 |
+
del parameters['image'] # parameter 'image' will be processed later
|
| 52 |
+
keys = parameters.keys()
|
| 53 |
+
if 'usegauss' in keys:
|
| 54 |
+
keys.remove('usegauss')
|
| 55 |
+
for key in keys:
|
| 56 |
+
parameters[key] = float(parameters[key])
|
| 57 |
+
|
| 58 |
+
image_object = request.FILES['image']
|
| 59 |
+
### Call segmentation function
|
| 60 |
+
seg_result = segmentation_exec(image_object, parameters)
|
| 61 |
+
if not seg_result: # if output_list is empty
|
| 62 |
+
logger.error("sth wrong with segmentation")
|
| 63 |
+
return Response("ERROR: sth wrong with segmentation", status=status.HTTP_500_INTERNAL_SERVER_ERROR)
|
| 64 |
+
|
| 65 |
+
### Else return the segmented images in zip type
|
| 66 |
+
# Folder name in ZIP archive which contains the above files
|
| 67 |
+
imagename_base, ext = os.path.splitext(str(image_object))
|
| 68 |
+
zip_dir = imagename_base+"_seg"
|
| 69 |
+
zip_name = "%s.zip" % zip_dir
|
| 70 |
+
strio = StringIO.StringIO() # Open StringIO to grab in-memory ZIP contents
|
| 71 |
+
zf = zipfile.ZipFile(strio, "w") # The zip compressor
|
| 72 |
+
|
| 73 |
+
# Zip multiple image objects from memory
|
| 74 |
+
for key in seg_result:
|
| 75 |
+
# Save single-line image object in memory as png format
|
| 76 |
+
line_image_io = StringIO.StringIO()
|
| 77 |
+
seg_result[key].save(line_image_io, 'png')
|
| 78 |
+
zip_path = os.path.join(zip_dir, key)
|
| 79 |
+
zf.writestr(zip_path, line_image_io.getvalue())
|
| 80 |
+
zf.close()
|
| 81 |
+
|
| 82 |
+
# Grab ZIP file from in-memory, make response with correct MIME-type
|
| 83 |
+
response = HttpResponse(strio.getvalue(), content_type="application/x-zip")
|
| 84 |
+
# And correct content-disposition
|
| 85 |
+
response["Content-Disposition"] = 'attachment; filename=%s' % zip_name
|
| 86 |
+
|
| 87 |
+
return response
|
pool/shard007/Python/0069704_bazel_api_test.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Lint as: python3
|
| 2 |
+
# Copyright 2020 The Bazel Authors. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain 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,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tests for bazel_api.py."""
|
| 16 |
+
import os
|
| 17 |
+
import unittest
|
| 18 |
+
from src.test.py.bazel import test_base
|
| 19 |
+
from tools.ctexplain.bazel_api import BazelApi
|
| 20 |
+
from tools.ctexplain.types import HostConfiguration
|
| 21 |
+
from tools.ctexplain.types import NullConfiguration
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class BazelApiTest(test_base.TestBase):
|
| 25 |
+
|
| 26 |
+
_bazel_api: BazelApi = None
|
| 27 |
+
|
| 28 |
+
def setUp(self):
|
| 29 |
+
test_base.TestBase.setUp(self)
|
| 30 |
+
self._bazel_api = BazelApi(self.RunBazel)
|
| 31 |
+
self.ScratchFile('WORKSPACE')
|
| 32 |
+
self.CreateWorkspaceWithDefaultRepos('repo/WORKSPACE')
|
| 33 |
+
|
| 34 |
+
def tearDown(self):
|
| 35 |
+
test_base.TestBase.tearDown(self)
|
| 36 |
+
|
| 37 |
+
def testBasicCquery(self):
|
| 38 |
+
self.ScratchFile('testapp/BUILD', [
|
| 39 |
+
'filegroup(name = "fg", srcs = ["a.file"])',
|
| 40 |
+
])
|
| 41 |
+
res = self._bazel_api.cquery(['//testapp:all'])
|
| 42 |
+
success = res[0]
|
| 43 |
+
cts = res[2]
|
| 44 |
+
self.assertTrue(success)
|
| 45 |
+
self.assertEqual(len(cts), 1)
|
| 46 |
+
self.assertEqual(cts[0].label, '//testapp:fg')
|
| 47 |
+
self.assertIsNone(cts[0].config)
|
| 48 |
+
self.assertGreater(len(cts[0].config_hash), 10)
|
| 49 |
+
self.assertIn('PlatformConfiguration', cts[0].transitive_fragments)
|
| 50 |
+
|
| 51 |
+
def testFailedCquery(self):
|
| 52 |
+
self.ScratchFile('testapp/BUILD', [
|
| 53 |
+
'filegroup(name = "fg", srcs = ["a.file"])',
|
| 54 |
+
])
|
| 55 |
+
(success, stderr, cts) = self._bazel_api.cquery(['//testapp:typo'])
|
| 56 |
+
self.assertFalse(success)
|
| 57 |
+
self.assertEqual(len(cts), 0)
|
| 58 |
+
self.assertIn("target 'typo' not declared in package 'testapp'",
|
| 59 |
+
os.linesep.join(stderr))
|
| 60 |
+
|
| 61 |
+
def testTransitiveFragmentsAccuracy(self):
|
| 62 |
+
self.ScratchFile('testapp/BUILD', [
|
| 63 |
+
'filegroup(name = "fg", srcs = ["a.file"])',
|
| 64 |
+
'filegroup(name = "ccfg", srcs = [":ccbin"])',
|
| 65 |
+
'cc_binary(name = "ccbin", srcs = ["ccbin.cc"])'
|
| 66 |
+
])
|
| 67 |
+
cts1 = self._bazel_api.cquery(['//testapp:fg'])[2]
|
| 68 |
+
self.assertNotIn('CppConfiguration', cts1[0].transitive_fragments)
|
| 69 |
+
cts2 = self._bazel_api.cquery(['//testapp:ccfg'])[2]
|
| 70 |
+
self.assertIn('CppConfiguration', cts2[0].transitive_fragments)
|
| 71 |
+
|
| 72 |
+
def testGetTargetConfig(self):
|
| 73 |
+
self.ScratchFile('testapp/BUILD', [
|
| 74 |
+
'filegroup(name = "fg", srcs = ["a.file"])',
|
| 75 |
+
])
|
| 76 |
+
cts = self._bazel_api.cquery(['//testapp:fg'])[2]
|
| 77 |
+
config = self._bazel_api.get_config(cts[0].config_hash)
|
| 78 |
+
expected_fragments = ['PlatformConfiguration', 'JavaConfiguration']
|
| 79 |
+
for exp in expected_fragments:
|
| 80 |
+
self.assertIn(exp, config.fragments.keys())
|
| 81 |
+
core_options = config.options['CoreOptions']
|
| 82 |
+
self.assertIsNotNone(core_options)
|
| 83 |
+
self.assertIn(('stamp', 'false'), core_options.items())
|
| 84 |
+
|
| 85 |
+
def testGetHostConfig(self):
|
| 86 |
+
self.ScratchFile('testapp/BUILD', [
|
| 87 |
+
'genrule(',
|
| 88 |
+
' name = "g",',
|
| 89 |
+
' srcs = [],',
|
| 90 |
+
' cmd = "",',
|
| 91 |
+
' outs = ["g.out"],',
|
| 92 |
+
' tools = [":fg"])',
|
| 93 |
+
'filegroup(name = "fg", srcs = ["a.file"])',
|
| 94 |
+
])
|
| 95 |
+
query = ['//testapp:fg', '--universe_scope=//testapp:g']
|
| 96 |
+
cts = self._bazel_api.cquery(query)[2]
|
| 97 |
+
config = self._bazel_api.get_config(cts[0].config_hash)
|
| 98 |
+
self.assertIsInstance(config, HostConfiguration)
|
| 99 |
+
# We don't currently populate or read a host configuration's details.
|
| 100 |
+
self.assertEqual(len(config.fragments), 0)
|
| 101 |
+
self.assertEqual(len(config.options), 0)
|
| 102 |
+
|
| 103 |
+
def testGetNullConfig(self):
|
| 104 |
+
self.ScratchFile('testapp/BUILD', [
|
| 105 |
+
'filegroup(name = "fg", srcs = ["a.file"])',
|
| 106 |
+
])
|
| 107 |
+
cts = self._bazel_api.cquery(['//testapp:a.file'])[2]
|
| 108 |
+
config = self._bazel_api.get_config(cts[0].config_hash)
|
| 109 |
+
self.assertIsInstance(config, NullConfiguration)
|
| 110 |
+
# Null configurations have no information by definition.
|
| 111 |
+
self.assertEqual(len(config.fragments), 0)
|
| 112 |
+
self.assertEqual(len(config.options), 0)
|
| 113 |
+
|
| 114 |
+
def testConfigFragmentsMap(self):
|
| 115 |
+
self.ScratchFile('testapp/BUILD', [
|
| 116 |
+
'filegroup(name = "fg", srcs = ["a.file"])',
|
| 117 |
+
])
|
| 118 |
+
cts = self._bazel_api.cquery(['//testapp:fg'])[2]
|
| 119 |
+
fragments_map = self._bazel_api.get_config(cts[0].config_hash).fragments
|
| 120 |
+
self.assertIn('PlatformOptions', fragments_map['PlatformConfiguration'])
|
| 121 |
+
self.assertIn('ShellConfiguration$Options',
|
| 122 |
+
fragments_map['ShellConfiguration'])
|
| 123 |
+
|
| 124 |
+
def testConfigWithDefines(self):
|
| 125 |
+
self.ScratchFile('testapp/BUILD', [
|
| 126 |
+
'filegroup(name = "fg", srcs = ["a.file"])',
|
| 127 |
+
])
|
| 128 |
+
cquery_args = ['//testapp:fg', '--define', 'a=b']
|
| 129 |
+
cts = self._bazel_api.cquery(cquery_args)[2]
|
| 130 |
+
config = self._bazel_api.get_config(cts[0].config_hash)
|
| 131 |
+
user_defined_options = config.options['user-defined']
|
| 132 |
+
self.assertIsNotNone(user_defined_options)
|
| 133 |
+
self.assertDictEqual(user_defined_options._dict, {'--define:a': 'b'})
|
| 134 |
+
|
| 135 |
+
def testConfigWithStarlarkFlags(self):
|
| 136 |
+
self.ScratchFile('testapp/defs.bzl', [
|
| 137 |
+
'def _flag_impl(settings, attr):', ' pass', 'string_flag = rule(',
|
| 138 |
+
' implementation = _flag_impl,',
|
| 139 |
+
' build_setting = config.string(flag = True)'
|
| 140 |
+
')'
|
| 141 |
+
])
|
| 142 |
+
self.ScratchFile('testapp/BUILD', [
|
| 143 |
+
'load(":defs.bzl", "string_flag")',
|
| 144 |
+
'string_flag(name = "my_flag", build_setting_default = "nada")',
|
| 145 |
+
'filegroup(name = "fg", srcs = ["a.file"])',
|
| 146 |
+
])
|
| 147 |
+
cquery_args = ['//testapp:fg', '--//testapp:my_flag', 'algo']
|
| 148 |
+
cts = self._bazel_api.cquery(cquery_args)[2]
|
| 149 |
+
config = self._bazel_api.get_config(cts[0].config_hash)
|
| 150 |
+
user_defined_options = config.options['user-defined']
|
| 151 |
+
self.assertIsNotNone(user_defined_options)
|
| 152 |
+
self.assertDictEqual(user_defined_options._dict,
|
| 153 |
+
{'//testapp:my_flag': 'algo'})
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
if __name__ == '__main__':
|
| 157 |
+
unittest.main()
|
pool/shard007/Python/0069706_backup_database.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from optparse import make_option
|
| 2 |
+
from subprocess import Popen, PIPE
|
| 3 |
+
from django.core.management.base import BaseCommand
|
| 4 |
+
from django.conf import settings
|
| 5 |
+
from django.core.mail import EmailMessage
|
| 6 |
+
import sys
|
| 7 |
+
|
| 8 |
+
from socket import gethostname
|
| 9 |
+
|
| 10 |
+
class Command(BaseCommand):
|
| 11 |
+
option_list = BaseCommand.option_list + (
|
| 12 |
+
make_option('-d', '--database', choices=settings.DATABASES.keys(), default='default', help='Database to backup'),
|
| 13 |
+
|
| 14 |
+
make_option('-o', '--output', choices=['file', 'stdout', 'email'], default='email', help='Output to file or stout or email'),
|
| 15 |
+
make_option('-f', '--filename', default='database.backup', help='File location to write to if output is file'),
|
| 16 |
+
|
| 17 |
+
make_option('-s', '--subject', default='%s Database Backup' % settings.EMAIL_SUBJECT_PREFIX),
|
| 18 |
+
)
|
| 19 |
+
help = 'Send email backups of a database'
|
| 20 |
+
|
| 21 |
+
def handle(self, *emails, **options):
|
| 22 |
+
self.filename = options['filename'] if options['output'] == 'file' else None
|
| 23 |
+
self.file_content = None
|
| 24 |
+
self.file_written = False
|
| 25 |
+
|
| 26 |
+
self.backup(options['database'], filename=self.filename)
|
| 27 |
+
|
| 28 |
+
if options['output'] == 'stdout':
|
| 29 |
+
sys.stdout.write(self.file_content)
|
| 30 |
+
elif options['output'] == 'email':
|
| 31 |
+
if emails:
|
| 32 |
+
self.email(*emails, subject=options['subject'], filename=options['filename'])
|
| 33 |
+
elif options['output'] == 'file' and not self.file_written and self.file_content:
|
| 34 |
+
print 'write file'
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def backup(self, database, *args, **kwargs):
|
| 38 |
+
if settings.DATABASES[database]['ENGINE'] in ['django.db.backends.postgresql_psycopg2']:
|
| 39 |
+
self.file_content = self.postgresql(database, *args, **kwargs)
|
| 40 |
+
|
| 41 |
+
def postgresql(self, database, filename=None, cmd='pg_dump'):
|
| 42 |
+
cmd_args = [
|
| 43 |
+
'--format', 'custom',
|
| 44 |
+
'--blobs',
|
| 45 |
+
'-U', settings.DATABASES[database]['USER'],
|
| 46 |
+
]
|
| 47 |
+
if filename:
|
| 48 |
+
cmd_args.append('--file')
|
| 49 |
+
cmd_args.append(filename)
|
| 50 |
+
self.filename = filename
|
| 51 |
+
self.file_written = True
|
| 52 |
+
|
| 53 |
+
pf = Popen([cmd] + cmd_args + [settings.DATABASES[database]['NAME']],
|
| 54 |
+
env = {
|
| 55 |
+
'PGPASSWORD': settings.DATABASES[database]['PASSWORD']
|
| 56 |
+
},
|
| 57 |
+
stdout=PIPE
|
| 58 |
+
)
|
| 59 |
+
return pf.communicate()[0]
|
| 60 |
+
|
| 61 |
+
def email(self, *emails, **kwargs):
|
| 62 |
+
msg = EmailMessage(
|
| 63 |
+
subject=kwargs.get('subject', None),
|
| 64 |
+
to = list(emails),
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
if self.filename:
|
| 68 |
+
msg.attach_file(self.filename)
|
| 69 |
+
elif self.file_content:
|
| 70 |
+
msg.attach(kwargs.get('filename'), self.file_content)
|
| 71 |
+
msg.send()
|
pool/shard007/Python/0069709_run-on-all.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# We attempted to make this program work with both python2 and python3
|
| 3 |
+
# -*-python-*-
|
| 4 |
+
|
| 5 |
+
"""This script runs a command on all worker hosts of a Hillview cluster."""
|
| 6 |
+
# pylint: disable=invalid-name
|
| 7 |
+
|
| 8 |
+
from argparse import ArgumentParser, REMAINDER
|
| 9 |
+
from hillviewCommon import ClusterConfiguration, get_config, get_logger
|
| 10 |
+
|
| 11 |
+
logger = get_logger("run-on-all")
|
| 12 |
+
|
| 13 |
+
def execute_command_on_all(config, command):
|
| 14 |
+
"""Executes command on all workers"""
|
| 15 |
+
assert isinstance(config, ClusterConfiguration)
|
| 16 |
+
message = "Executing `" + str(command) + "' on " + str(len(config.get_workers())) + " hosts"
|
| 17 |
+
logger.info(message)
|
| 18 |
+
lam = lambda rh: rh.run_remote_shell_command(command)
|
| 19 |
+
config.run_on_all_workers(lam)
|
| 20 |
+
|
| 21 |
+
def main():
|
| 22 |
+
"""Main function"""
|
| 23 |
+
parser = ArgumentParser()
|
| 24 |
+
parser.add_argument("config", help="json cluster configuration file")
|
| 25 |
+
parser.add_argument("command", help="command to run", nargs=REMAINDER)
|
| 26 |
+
args = parser.parse_args()
|
| 27 |
+
config = get_config(parser, args)
|
| 28 |
+
command = " ".join(args.command)
|
| 29 |
+
execute_command_on_all(config, command)
|
| 30 |
+
|
| 31 |
+
if __name__ == "__main__":
|
| 32 |
+
main()
|
pool/shard007/Python/0069710_file_data_source.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The base file related data source object from which all MayaVi data
|
| 2 |
+
sources derive.
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
# Author: Prabhu Ramachandran <prabhu_r@users.sf.net>
|
| 6 |
+
# Copyright (c) 2005, Enthought, Inc.
|
| 7 |
+
# License: BSD Style.
|
| 8 |
+
|
| 9 |
+
# Standard library imports.
|
| 10 |
+
import re
|
| 11 |
+
from os.path import split, join, isfile
|
| 12 |
+
from glob import glob
|
| 13 |
+
|
| 14 |
+
# Enthought library imports.
|
| 15 |
+
from traits.api import List, Str, Instance, Int, Range
|
| 16 |
+
from traitsui.api import Group, Item, FileEditor
|
| 17 |
+
from apptools.persistence.state_pickler import set_state
|
| 18 |
+
from apptools.persistence.file_path import FilePath
|
| 19 |
+
|
| 20 |
+
# Local imports
|
| 21 |
+
from mayavi.core.source import Source
|
| 22 |
+
from mayavi.core.common import handle_children_state
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
######################################################################
|
| 26 |
+
# Utility functions.
|
| 27 |
+
######################################################################
|
| 28 |
+
def get_file_list(file_name):
|
| 29 |
+
""" Given a file name, this function treats the file as a part of
|
| 30 |
+
a series of files based on the index of the file and tries to
|
| 31 |
+
determine the list of files in the series. The file name of a
|
| 32 |
+
file in a time series must be of the form 'some_name[0-9]*.ext'.
|
| 33 |
+
That is the integers at the end of the file determine what part of
|
| 34 |
+
the time series the file belongs to. The files are then sorted as
|
| 35 |
+
per this index."""
|
| 36 |
+
|
| 37 |
+
# The matching is done only for the basename of the file.
|
| 38 |
+
f_dir, f_base = split(file_name)
|
| 39 |
+
# Find the head and tail of the file pattern.
|
| 40 |
+
head = re.sub("[0-9]+[^0-9]*$", "", f_base)
|
| 41 |
+
tail = re.sub("^.*[0-9]+", "", f_base)
|
| 42 |
+
pattern = head+"[0-9]*"+tail
|
| 43 |
+
# Glob the files for the pattern.
|
| 44 |
+
_files = glob(join(f_dir, pattern))
|
| 45 |
+
|
| 46 |
+
# A simple function to get the index from the file.
|
| 47 |
+
def _get_index(f, head=head, tail=tail):
|
| 48 |
+
base = split(f)[1]
|
| 49 |
+
result = base.replace(head, '')
|
| 50 |
+
return float(result.replace(tail, ''))
|
| 51 |
+
|
| 52 |
+
# Before sorting make sure the files in the globbed series are
|
| 53 |
+
# really part of a timeseries. This can happen in cases like so:
|
| 54 |
+
# 5_2_1.vtk and 5_2_1s.vtk will be globbed but 5_2_1s.vtk is
|
| 55 |
+
# obviously not a valid time series file.
|
| 56 |
+
files = []
|
| 57 |
+
for x in _files:
|
| 58 |
+
try:
|
| 59 |
+
_get_index(x)
|
| 60 |
+
except ValueError:
|
| 61 |
+
pass
|
| 62 |
+
else:
|
| 63 |
+
files.append(x)
|
| 64 |
+
|
| 65 |
+
# Sort the globbed files based on the index value.
|
| 66 |
+
def file_sort(x, y):
|
| 67 |
+
x1 = _get_index(x)
|
| 68 |
+
y1 = _get_index(y)
|
| 69 |
+
if x1 > y1:
|
| 70 |
+
return 1
|
| 71 |
+
elif y1 > x1:
|
| 72 |
+
return -1
|
| 73 |
+
else:
|
| 74 |
+
return 0
|
| 75 |
+
|
| 76 |
+
files.sort(file_sort)
|
| 77 |
+
return files
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
######################################################################
|
| 81 |
+
# `FileDataSource` class.
|
| 82 |
+
######################################################################
|
| 83 |
+
class FileDataSource(Source):
|
| 84 |
+
|
| 85 |
+
# The version of this class. Used for persistence.
|
| 86 |
+
__version__ = 0
|
| 87 |
+
|
| 88 |
+
# The list of file names for the timeseries.
|
| 89 |
+
file_list = List(Str, desc='a list of files belonging to a time series')
|
| 90 |
+
|
| 91 |
+
# The current time step (starts with 0). This trait is a dummy
|
| 92 |
+
# and is dynamically changed when the `file_list` trait changes.
|
| 93 |
+
# This is done so the timestep bounds are linked to the number of
|
| 94 |
+
# the files in the file list.
|
| 95 |
+
timestep = Range(value=0,
|
| 96 |
+
low='_min_timestep',
|
| 97 |
+
high='_max_timestep',
|
| 98 |
+
enter_set=True, auto_set=False,
|
| 99 |
+
desc='the current time step')
|
| 100 |
+
|
| 101 |
+
base_file_name=Str('', desc="the base name of the file",
|
| 102 |
+
enter_set=True, auto_set=False,
|
| 103 |
+
editor=FileEditor())
|
| 104 |
+
|
| 105 |
+
# A timestep view group that may be included by subclasses.
|
| 106 |
+
time_step_group = Group(Item(name='file_path', style='readonly'),
|
| 107 |
+
Item(name='timestep',
|
| 108 |
+
defined_when='len(object.file_list) > 1')
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
##################################################
|
| 112 |
+
# Private traits.
|
| 113 |
+
##################################################
|
| 114 |
+
|
| 115 |
+
# The current file name. This is not meant to be touched by the
|
| 116 |
+
# user.
|
| 117 |
+
file_path = Instance(FilePath, (), desc='the current file name')
|
| 118 |
+
|
| 119 |
+
_min_timestep = Int(0)
|
| 120 |
+
_max_timestep = Int(0)
|
| 121 |
+
|
| 122 |
+
######################################################################
|
| 123 |
+
# `object` interface
|
| 124 |
+
######################################################################
|
| 125 |
+
def __get_pure_state__(self):
|
| 126 |
+
d = super(FileDataSource, self).__get_pure_state__()
|
| 127 |
+
# These are obtained dynamically, so don't pickle them.
|
| 128 |
+
for x in ['file_list', 'timestep']:
|
| 129 |
+
d.pop(x, None)
|
| 130 |
+
return d
|
| 131 |
+
|
| 132 |
+
def __set_pure_state__(self, state):
|
| 133 |
+
# Use the saved path to initialize the file_list and timestep.
|
| 134 |
+
fname = state.file_path.abs_pth
|
| 135 |
+
if not isfile(fname):
|
| 136 |
+
msg = 'Could not find file at %s\n'%fname
|
| 137 |
+
msg += 'Please move the file there and try again.'
|
| 138 |
+
raise IOError, msg
|
| 139 |
+
|
| 140 |
+
self.initialize(fname)
|
| 141 |
+
# Now set the remaining state without touching the children.
|
| 142 |
+
set_state(self, state, ignore=['children', 'file_path'])
|
| 143 |
+
# Setup the children.
|
| 144 |
+
handle_children_state(self.children, state.children)
|
| 145 |
+
# Setup the children's state.
|
| 146 |
+
set_state(self, state, first=['children'], ignore=['*'])
|
| 147 |
+
|
| 148 |
+
######################################################################
|
| 149 |
+
# `FileDataSource` interface
|
| 150 |
+
######################################################################
|
| 151 |
+
def initialize(self, base_file_name):
|
| 152 |
+
"""Given a single filename which may or may not be part of a
|
| 153 |
+
time series, this initializes the list of files. This method
|
| 154 |
+
need not be called to initialize the data.
|
| 155 |
+
"""
|
| 156 |
+
self.base_file_name = base_file_name
|
| 157 |
+
|
| 158 |
+
######################################################################
|
| 159 |
+
# Non-public interface
|
| 160 |
+
######################################################################
|
| 161 |
+
def _file_list_changed(self, value):
|
| 162 |
+
# Change the range of the timestep suitably to reflect new list.
|
| 163 |
+
n_files = len(self.file_list)
|
| 164 |
+
timestep = min(self.timestep, n_files)
|
| 165 |
+
self._max_timestep = max(n_files -1, 0)
|
| 166 |
+
if self.timestep == timestep:
|
| 167 |
+
self._timestep_changed(timestep)
|
| 168 |
+
else:
|
| 169 |
+
self.timestep = timestep
|
| 170 |
+
|
| 171 |
+
def _file_list_items_changed(self, list_event):
|
| 172 |
+
self._file_list_changed(self.file_list)
|
| 173 |
+
|
| 174 |
+
def _timestep_changed(self, value):
|
| 175 |
+
file_list = self.file_list
|
| 176 |
+
if len(file_list) > 0:
|
| 177 |
+
self.file_path = FilePath(file_list[value])
|
| 178 |
+
else:
|
| 179 |
+
self.file_path = FilePath('')
|
| 180 |
+
|
| 181 |
+
def _base_file_name_changed(self,value):
|
| 182 |
+
self.file_list = get_file_list(value)
|
| 183 |
+
if len(self.file_list) == 0:
|
| 184 |
+
self.file_list = [value]
|
| 185 |
+
try:
|
| 186 |
+
self.timestep = self.file_list.index(value)
|
| 187 |
+
except ValueError:
|
| 188 |
+
self.timestep = 0
|
| 189 |
+
|
pool/shard007/Python/0069713_iOS_private.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#coding=utf-8
|
| 2 |
+
'''
|
| 3 |
+
Created on 2015年10月27日
|
| 4 |
+
iOS private api检查入口
|
| 5 |
+
@author: atool
|
| 6 |
+
'''
|
| 7 |
+
import os, shutil
|
| 8 |
+
from utils import report_utils, utils
|
| 9 |
+
from dump import otool_utils, codesign_utils
|
| 10 |
+
from api import app_utils, api_utils
|
| 11 |
+
from db import api_dbs
|
| 12 |
+
# from app.utils import IpaParse
|
| 13 |
+
from app.utils import checkipa
|
| 14 |
+
|
| 15 |
+
def get_executable_path(ipa_path, pid):
|
| 16 |
+
'''
|
| 17 |
+
info: unzip ipa, get execute app path
|
| 18 |
+
'''
|
| 19 |
+
if not os.path.exists(ipa_path):
|
| 20 |
+
#不存在,返回检查结果为空值
|
| 21 |
+
return False
|
| 22 |
+
cur_dir = os.getcwd()
|
| 23 |
+
dest = os.path.join(cur_dir, 'tmp/' + pid)
|
| 24 |
+
if not os.path.exists(dest):
|
| 25 |
+
os.mkdir(dest)
|
| 26 |
+
app_path = app_utils.unzip_ipa(ipa_path, dest) #解压ipa,获得xxx.app目录路径
|
| 27 |
+
app = app_utils.get_executable_file(app_path)
|
| 28 |
+
|
| 29 |
+
return app
|
| 30 |
+
|
| 31 |
+
#检查私有api,返回三个参数
|
| 32 |
+
def check_private_api(app, pid):
|
| 33 |
+
strings = app_utils.get_app_strings(app, pid) #一般是app中的一些可打印文本
|
| 34 |
+
#app中的私有库和公有库 .framework
|
| 35 |
+
private, public = otool_utils.otool_app(app)
|
| 36 |
+
print '=' * 15
|
| 37 |
+
print 'private:', len(private)
|
| 38 |
+
print 'public', len(public)
|
| 39 |
+
print '=' * 15
|
| 40 |
+
|
| 41 |
+
dump_result = app_utils.get_dump_result(app)
|
| 42 |
+
app_varibles = app_utils.get_app_variables(dump_result, pid) #app自定义的一些方法,不需要检查
|
| 43 |
+
left = strings - app_varibles #去除一些app中开发人员自定义的方法,剩余app中的一些字符串
|
| 44 |
+
|
| 45 |
+
app_methods = app_utils.get_app_methods(dump_result, pid) #dump-class分析出app中的类和方法名
|
| 46 |
+
|
| 47 |
+
app_apis = []
|
| 48 |
+
for m in app_methods:
|
| 49 |
+
class_name = m["class"] if m["class"] != "ctype" else 'cur_app'
|
| 50 |
+
#if m["class"] != "ctype" else 'cur_app'
|
| 51 |
+
method_list = m["methods"]
|
| 52 |
+
m_type = m["type"]
|
| 53 |
+
for m in method_list:
|
| 54 |
+
tmp_api = {}
|
| 55 |
+
tmp_api['api_name'] = m
|
| 56 |
+
tmp_api['class_name'] = class_name
|
| 57 |
+
tmp_api['type'] = m_type
|
| 58 |
+
#tmp_api['header_file'] = ''
|
| 59 |
+
#tmp_api['sdk'] = ''
|
| 60 |
+
#tmp_api['framework'] = ''
|
| 61 |
+
app_apis.append(tmp_api)
|
| 62 |
+
|
| 63 |
+
api_set = api_dbs.get_private_api_list(public) #数据库中的私有api,去除了whitelist白名单
|
| 64 |
+
print '=' * 15
|
| 65 |
+
print 'left app_varibles:', len(left)
|
| 66 |
+
print 'app_methods:', len(app_apis)
|
| 67 |
+
print 'private length:', len(api_set)
|
| 68 |
+
print '=' * 15
|
| 69 |
+
inter_api = api_utils.intersection_list_and_api(left, api_set) # app中的api和数据库中的私有api取交集,获得app中的私有api关键字数据
|
| 70 |
+
|
| 71 |
+
methods_in_app, method_not_in = api_utils.intersection_api(app_apis, inter_api) #app中的私有方法
|
| 72 |
+
|
| 73 |
+
print '=' * 15
|
| 74 |
+
print 'methods_in_app', len(methods_in_app)
|
| 75 |
+
print 'methods_not_in_app', len(method_not_in)
|
| 76 |
+
# for i in xrange(20):
|
| 77 |
+
# print methods_not_in_app[i]
|
| 78 |
+
print '=' * 15
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
return methods_in_app, method_not_in, private
|
| 82 |
+
|
| 83 |
+
#检查架构,返回架构数组
|
| 84 |
+
def check_architectures(app):
|
| 85 |
+
arcs = app_utils.check_architectures(app)
|
| 86 |
+
return arcs
|
| 87 |
+
|
| 88 |
+
#检查xcode ghost,返回bool
|
| 89 |
+
def check_xcode_ghost(app):
|
| 90 |
+
return app_utils.check_xcode_ghost(app)
|
| 91 |
+
|
| 92 |
+
#检查info和provision文件,并获取建议和错误配置
|
| 93 |
+
def check_app_info_and_provision(ipa):
|
| 94 |
+
return checkipa.process_ipa(ipa)
|
| 95 |
+
|
| 96 |
+
#检查codesign信息
|
| 97 |
+
def check_codesign(app):
|
| 98 |
+
return codesign_utils.codesignapp(app)
|
| 99 |
+
|
| 100 |
+
#ipa的md5
|
| 101 |
+
def get_file_md5(ipa):
|
| 102 |
+
return app_utils.file_md5(ipa)
|
| 103 |
+
|
| 104 |
+
#检查单个的app,获得结果字典
|
| 105 |
+
def check_ipa(ipa_path):
|
| 106 |
+
result = {} #每个app的检查结果
|
| 107 |
+
pid = utils.get_unique_str()
|
| 108 |
+
print '1.', '+' * 10, 'get_file_md5'
|
| 109 |
+
result['md5'] = get_file_md5(ipa_path)
|
| 110 |
+
|
| 111 |
+
print '2.', '+' * 10, 'check_app_info_and_provision'
|
| 112 |
+
rsts = check_app_info_and_provision(ipa_path)
|
| 113 |
+
for key in rsts.keys():
|
| 114 |
+
result[key] = rsts[key]
|
| 115 |
+
#检查ios私有api
|
| 116 |
+
print '3.', '+' * 10, 'check_private_api'
|
| 117 |
+
app = get_executable_path(ipa_path, pid)
|
| 118 |
+
if not app:
|
| 119 |
+
#找不到math-o文件,说明不是正常的ipa,忽略
|
| 120 |
+
return False
|
| 121 |
+
|
| 122 |
+
methods_in_app, _, private = check_private_api(app, pid)
|
| 123 |
+
result['private_apis'] = methods_in_app
|
| 124 |
+
# result['private_apis_not'] = _
|
| 125 |
+
result['private_frameworks'] = list(private)
|
| 126 |
+
#检查ipa 64支持情况
|
| 127 |
+
print '4.', '+' * 10, 'check_architectures'
|
| 128 |
+
arcs = check_architectures(app)
|
| 129 |
+
result['arcs'] = arcs
|
| 130 |
+
if len(arcs) < 2:
|
| 131 |
+
result['error'].append({'label': 'Architecture:',
|
| 132 |
+
'description': 'app may be not support 64-bit'})
|
| 133 |
+
#检查ghost情况
|
| 134 |
+
print '5.', '+' * 10, 'check_xcode_ghost'
|
| 135 |
+
ghost = check_xcode_ghost(app)
|
| 136 |
+
result['ghost'] = ghost
|
| 137 |
+
#检查codesign
|
| 138 |
+
print '6.', '+' * 10, 'check_private_api'
|
| 139 |
+
codesign = check_codesign(app)
|
| 140 |
+
result['codesign'] = codesign
|
| 141 |
+
|
| 142 |
+
print '7.', '+' * 10, 'remove tmp files'
|
| 143 |
+
cur_dir = os.getcwd() #删除检查临时目录
|
| 144 |
+
dest_tmp = os.path.join(cur_dir, 'tmp/' + pid)
|
| 145 |
+
# print 'tmp:', dest_tmp
|
| 146 |
+
if os.path.exists(dest_tmp):
|
| 147 |
+
shutil.rmtree(dest_tmp)
|
| 148 |
+
|
| 149 |
+
return result
|
| 150 |
+
|
| 151 |
+
def batch_check(app_folder, excel_path):
|
| 152 |
+
'''
|
| 153 |
+
批量检测多个ipa,并产生excel报告
|
| 154 |
+
'''
|
| 155 |
+
#遍历folder,找出.ipa文件
|
| 156 |
+
if not app_folder or not excel_path:
|
| 157 |
+
return False
|
| 158 |
+
|
| 159 |
+
check_results = []
|
| 160 |
+
ipa_list = os.listdir(app_folder)
|
| 161 |
+
for ipa in ipa_list:
|
| 162 |
+
print 'start check :', ipa
|
| 163 |
+
if ipa.endswith('.ipa'):
|
| 164 |
+
ipa_path = os.path.join(app_folder, ipa)
|
| 165 |
+
#单个app的检查结果
|
| 166 |
+
try:
|
| 167 |
+
r = check_ipa(ipa_path)
|
| 168 |
+
if r:
|
| 169 |
+
check_results.append(r)
|
| 170 |
+
except Exception, e:
|
| 171 |
+
print e
|
| 172 |
+
continue
|
| 173 |
+
|
| 174 |
+
#将结果转化成excel报告
|
| 175 |
+
report_utils.excel_report(check_results, excel_path)
|
| 176 |
+
return excel_path
|
| 177 |
+
|
| 178 |
+
if __name__ == '__main__':
|
| 179 |
+
#######
|
| 180 |
+
#check one app
|
| 181 |
+
# ipa_path = "/Users/summer-wj/code/svn/ljsg_for_netease_20150928_resign.ipa"
|
| 182 |
+
|
| 183 |
+
# private_1 = open("tmp/private_1.txt", "w")
|
| 184 |
+
# private_2 = open("tmp/private_2.txt", "w")
|
| 185 |
+
# #将strings内容输出到文件中
|
| 186 |
+
# pid = app_utils.get_unique_str()
|
| 187 |
+
# app = get_executable_path(ipa_path, pid)
|
| 188 |
+
# print app
|
| 189 |
+
# arcs = check_architectures(app)
|
| 190 |
+
# print arcs
|
| 191 |
+
# a, b, c = check_private_api(app, pid)
|
| 192 |
+
# print "=" * 50
|
| 193 |
+
# print len(a), "Private Methods in App:"
|
| 194 |
+
# print "*" * 50
|
| 195 |
+
# for aa in a:
|
| 196 |
+
# print aa
|
| 197 |
+
# print >>private_1, aa
|
| 198 |
+
|
| 199 |
+
# print "=" * 50
|
| 200 |
+
# print len(b), "Private Methods not in App, May in Framework Used:"
|
| 201 |
+
# print "*" * 50
|
| 202 |
+
# for bb in b:
|
| 203 |
+
# print >>private_2, bb
|
| 204 |
+
|
| 205 |
+
# print "=" * 50
|
| 206 |
+
# print len(c), "Private Framework in App:"
|
| 207 |
+
# print "*" * 50
|
| 208 |
+
|
| 209 |
+
##########
|
| 210 |
+
#test batch check ipa
|
| 211 |
+
cwd = os.getcwd()
|
| 212 |
+
excel_path = os.path.join(cwd, 'tmp/' + utils.get_unique_str() + '.xlsx')
|
| 213 |
+
# excel_path = os.path.join(cwd, 'tmp/test.xlsx') # for test
|
| 214 |
+
print excel_path
|
| 215 |
+
ipa_folder = '/Users/netease/Downloads/ipas/mg/'
|
| 216 |
+
# ipa_folder = '/Users/netease/Music/iTunes/iTunes Media/Mobile Applications/'
|
| 217 |
+
# ipa_folder = '/Users/netease/Music/iTunes/iTunes Media/'
|
| 218 |
+
print batch_check(ipa_folder, excel_path)
|
| 219 |
+
|
| 220 |
+
#########
|
| 221 |
+
#test check arcs
|
| 222 |
+
# app_path = '/Users/netease/Downloads/ipas/mg/Payload'
|
| 223 |
+
# app = app_utils.get_executable_file(app_path)
|
| 224 |
+
# print check_architectures(app)
|
| 225 |
+
|
pool/shard007/Python/0069718_ChangePasswordDlg.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Copyright 2001 - 2018 Ludek Smid [http://www.ospace.net/]
|
| 3 |
+
#
|
| 4 |
+
# This file is part of Outer Space.
|
| 5 |
+
#
|
| 6 |
+
# Outer Space 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 |
+
# Outer Space 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 Outer Space; if not, write to the Free Software
|
| 18 |
+
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
| 19 |
+
#
|
| 20 |
+
|
| 21 |
+
import pygameui as ui
|
| 22 |
+
from osci import client, gdata, res
|
| 23 |
+
from ige import SecurityException
|
| 24 |
+
|
| 25 |
+
class ChangePasswordDlg:
|
| 26 |
+
|
| 27 |
+
def __init__(self, app):
|
| 28 |
+
self.app = app
|
| 29 |
+
self.createUI()
|
| 30 |
+
|
| 31 |
+
def display(self, caller = None, message = None):
|
| 32 |
+
self.caller = caller
|
| 33 |
+
self.win.vOld.text = ""
|
| 34 |
+
self.win.vNew.text = ""
|
| 35 |
+
self.win.vConfirm.text = ""
|
| 36 |
+
self.win.show()
|
| 37 |
+
|
| 38 |
+
def hide(self):
|
| 39 |
+
self.win.hide()
|
| 40 |
+
|
| 41 |
+
def onChange(self, widget, action, data):
|
| 42 |
+
oldPassword = self.win.vOld.text
|
| 43 |
+
newPassword = self.win.vNew.text
|
| 44 |
+
confirmPassword = self.win.vConfirm.text
|
| 45 |
+
if newPassword != confirmPassword:
|
| 46 |
+
self.win.vMessage.text = _("Passwords do not match.")
|
| 47 |
+
self.win.vNew.text = ""
|
| 48 |
+
self.win.vConfirm.text = ""
|
| 49 |
+
return
|
| 50 |
+
self.win.hide()
|
| 51 |
+
try:
|
| 52 |
+
client.cmdProxy.changePassword(oldPassword, newPassword)
|
| 53 |
+
except SecurityException, e:
|
| 54 |
+
# failed
|
| 55 |
+
self.win.vMessage.text = _(e.args[0])
|
| 56 |
+
self.win.show()
|
| 57 |
+
return
|
| 58 |
+
if self.caller:
|
| 59 |
+
self.caller.display(message = _("The password has been changed."))
|
| 60 |
+
|
| 61 |
+
def onCancel(self, widget, action, data):
|
| 62 |
+
self.win.hide()
|
| 63 |
+
if self.caller:
|
| 64 |
+
self.caller.display()
|
| 65 |
+
|
| 66 |
+
def createUI(self):
|
| 67 |
+
w, h = gdata.scrnSize
|
| 68 |
+
self.win = ui.Window(self.app,
|
| 69 |
+
modal = 1,
|
| 70 |
+
movable = 0,
|
| 71 |
+
title = _('Change password'),
|
| 72 |
+
rect = ui.Rect((w - 324) / 2, (h - 104) / 2, 324, 104),
|
| 73 |
+
layoutManager = ui.SimpleGridLM(),
|
| 74 |
+
tabChange = True
|
| 75 |
+
)
|
| 76 |
+
self.win.subscribeAction('*', self)
|
| 77 |
+
ui.Label(self.win,
|
| 78 |
+
text = _('Old password'),
|
| 79 |
+
align = ui.ALIGN_E,
|
| 80 |
+
layout = (0, 0, 6, 1)
|
| 81 |
+
)
|
| 82 |
+
ui.Entry(self.win, id = 'vOld',
|
| 83 |
+
align = ui.ALIGN_W,
|
| 84 |
+
showChar = '*',
|
| 85 |
+
layout = (6, 0, 10, 1),
|
| 86 |
+
orderNo = 1
|
| 87 |
+
)
|
| 88 |
+
ui.Label(self.win,
|
| 89 |
+
text = _('New password'),
|
| 90 |
+
align = ui.ALIGN_E,
|
| 91 |
+
layout = (0, 1, 6, 1),
|
| 92 |
+
)
|
| 93 |
+
ui.Entry(self.win, id = 'vNew',
|
| 94 |
+
align = ui.ALIGN_W,
|
| 95 |
+
showChar = '*',
|
| 96 |
+
layout = (6, 1, 10, 1),
|
| 97 |
+
orderNo = 2
|
| 98 |
+
)
|
| 99 |
+
ui.Label(self.win,
|
| 100 |
+
align = ui.ALIGN_E,
|
| 101 |
+
text = _('Confirm'),
|
| 102 |
+
layout = (0, 2, 6, 1),
|
| 103 |
+
)
|
| 104 |
+
ui.Entry(self.win, id = 'vConfirm',
|
| 105 |
+
align = ui.ALIGN_W,
|
| 106 |
+
layout = (6, 2, 10, 1),
|
| 107 |
+
showChar = "*",
|
| 108 |
+
orderNo = 3
|
| 109 |
+
)
|
| 110 |
+
ui.Title(self.win, layout = (0, 3, 8, 1), id = 'vMessage', align = ui.ALIGN_W)
|
| 111 |
+
ui.TitleButton(self.win, layout = (8, 3, 4, 1), text = _('Cancel'), action = 'onCancel')
|
| 112 |
+
ui.TitleButton(self.win, layout = (12, 3, 4, 1), text = _('Apply'), action = 'onChange')
|
pool/shard007/Python/0069719_window.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2010 Arthur Mesh
|
| 2 |
+
# 2010 Christopher Nelson
|
| 3 |
+
#
|
| 4 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 5 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 6 |
+
# in the Software without restriction, including without limitation the rights
|
| 7 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 8 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 9 |
+
# furnished to do so, subject to the following conditions:
|
| 10 |
+
#
|
| 11 |
+
# The above copyright notice and this permission notice shall be included in
|
| 12 |
+
# all copies or substantial portions of the Software.
|
| 13 |
+
#
|
| 14 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 15 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 16 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 17 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 18 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 19 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
| 20 |
+
# THE SOFTWARE.
|
| 21 |
+
|
| 22 |
+
import pygtk
|
| 23 |
+
pygtk.require('2.0')
|
| 24 |
+
import gtk
|
| 25 |
+
|
| 26 |
+
from snmp.nms_accessor import NMSAccessor
|
| 27 |
+
|
| 28 |
+
from widgets.treeview import TreeView
|
| 29 |
+
from widgets.textview import TextView
|
| 30 |
+
|
| 31 |
+
class Window(gtk.Window):
|
| 32 |
+
"""
|
| 33 |
+
Top-level window of the application.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def delete_event(self, widget, event, data=None):
|
| 37 |
+
"""
|
| 38 |
+
Close the window and exit.
|
| 39 |
+
"""
|
| 40 |
+
gtk.main_quit()
|
| 41 |
+
return False
|
| 42 |
+
|
| 43 |
+
def __init__(self):
|
| 44 |
+
"""
|
| 45 |
+
Create the top-level window and add children to it.
|
| 46 |
+
"""
|
| 47 |
+
gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
|
| 48 |
+
|
| 49 |
+
self.scrolled = None
|
| 50 |
+
self.scrolled_text = None
|
| 51 |
+
self.treeview = None
|
| 52 |
+
self.textview = None
|
| 53 |
+
self.set_box = None
|
| 54 |
+
|
| 55 |
+
self.set_title("Noname MIB 'Browser'")
|
| 56 |
+
self.set_size_request(640, 480)
|
| 57 |
+
self.connect('delete_event', self.delete_event)
|
| 58 |
+
|
| 59 |
+
label = gtk.Label('Address: ')
|
| 60 |
+
self.inputbox = gtk.Entry()
|
| 61 |
+
self.hbox = gtk.HBox()
|
| 62 |
+
self.hbox.pack_start(label, expand = False)
|
| 63 |
+
self.hbox.pack_start(self.inputbox)
|
| 64 |
+
|
| 65 |
+
self.login_box = gtk.HBox()
|
| 66 |
+
label = gtk.Label('Username: ')
|
| 67 |
+
self.login_box.pack_start(label, expand = False)
|
| 68 |
+
self.uname_box = gtk.Entry()
|
| 69 |
+
self.login_box.pack_start(self.uname_box)
|
| 70 |
+
label = gtk.Label('Password: ')
|
| 71 |
+
self.login_box.pack_start(label, expand = False)
|
| 72 |
+
self.passwd_box = gtk.Entry()
|
| 73 |
+
self.passwd_box.set_visibility(False)
|
| 74 |
+
self.login_box.pack_start(self.passwd_box)
|
| 75 |
+
button = gtk.Button('Login')
|
| 76 |
+
button.connect('clicked', self.login)
|
| 77 |
+
self.login_box.pack_start(button)
|
| 78 |
+
|
| 79 |
+
self.vbox = gtk.VBox()
|
| 80 |
+
self.vbox.pack_start(self.hbox, expand=False)
|
| 81 |
+
self.vbox.pack_start(self.login_box, expand = False)
|
| 82 |
+
|
| 83 |
+
self.add(self.vbox)
|
| 84 |
+
|
| 85 |
+
self.show_all()
|
| 86 |
+
|
| 87 |
+
def login(self, widget, data = None):
|
| 88 |
+
"""
|
| 89 |
+
Login to the application.
|
| 90 |
+
"""
|
| 91 |
+
# first, create the nms_accessor
|
| 92 |
+
self.nms_accessor = NMSAccessor(self.inputbox.get_text())
|
| 93 |
+
# then, login
|
| 94 |
+
self.nms_accessor.login(self.uname_box.get_text(),
|
| 95 |
+
self.passwd_box.get_text())
|
| 96 |
+
# then, set up the choice of devices to activate
|
| 97 |
+
self.combobox = gtk.combo_box_new_text()
|
| 98 |
+
combo_data = self.nms_accessor.get_devices()
|
| 99 |
+
for data in combo_data:
|
| 100 |
+
self.combobox.append_text(data)
|
| 101 |
+
self.combobox.set_active(1)
|
| 102 |
+
self.combobox.connect('changed', self.change_device)
|
| 103 |
+
|
| 104 |
+
self.vbox.remove(self.login_box)
|
| 105 |
+
self.vbox.pack_start(self.combobox, expand = False)
|
| 106 |
+
|
| 107 |
+
self.change_device(None)
|
| 108 |
+
|
| 109 |
+
self.show_all()
|
| 110 |
+
|
| 111 |
+
def change_device(self, widget, data = None):
|
| 112 |
+
"""
|
| 113 |
+
Change which device we're looking at.
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
if self.set_box is None:
|
| 117 |
+
self.set_box = gtk.HBox()
|
| 118 |
+
label = gtk.Label('OID: ')
|
| 119 |
+
self.set_box.pack_start(label, expand = False)
|
| 120 |
+
self.set_entry_oid = gtk.Entry()
|
| 121 |
+
self.set_box.pack_start(self.set_entry_oid)
|
| 122 |
+
label = gtk.Label('Value: ')
|
| 123 |
+
self.set_box.pack_start(label, expand = False)
|
| 124 |
+
self.set_entry_value = gtk.Entry()
|
| 125 |
+
self.set_box.pack_start(self.set_entry_value)
|
| 126 |
+
button = gtk.Button('Set')
|
| 127 |
+
button.connect('clicked', self.set_value)
|
| 128 |
+
self.set_box.pack_start(button, expand = False)
|
| 129 |
+
|
| 130 |
+
self.vbox.pack_start(self.set_box, expand = False)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
if self.scrolled is not None:
|
| 134 |
+
self.vbox.remove(self.scrolled)
|
| 135 |
+
if self.scrolled_text is not None:
|
| 136 |
+
self.vbox.remove(self.scrolled_text)
|
| 137 |
+
|
| 138 |
+
self.scrolled = gtk.ScrolledWindow()
|
| 139 |
+
self.scrolled_text = gtk.ScrolledWindow()
|
| 140 |
+
|
| 141 |
+
self.textview = TextView()
|
| 142 |
+
|
| 143 |
+
self.treeview = TreeView(self.textview,
|
| 144 |
+
self.nms_accessor,
|
| 145 |
+
self.combobox.get_active_text())
|
| 146 |
+
|
| 147 |
+
if self.treeview is not None:
|
| 148 |
+
self.scrolled.remove(self.treeview)
|
| 149 |
+
self.scrolled.add_with_viewport(self.treeview)
|
| 150 |
+
if self.textview is not None:
|
| 151 |
+
self.scrolled_text.remove(self.textview)
|
| 152 |
+
self.scrolled_text.add_with_viewport(self.textview)
|
| 153 |
+
|
| 154 |
+
self.vbox.pack_start(self.scrolled)
|
| 155 |
+
self.vbox.pack_start(self.scrolled_text)
|
| 156 |
+
|
| 157 |
+
self.show_all()
|
| 158 |
+
|
| 159 |
+
def set_value(self, widget, data = None):
|
| 160 |
+
"""
|
| 161 |
+
Set the value at the OID in self.set_entry_oid
|
| 162 |
+
"""
|
| 163 |
+
self.nms_accessor.set_value(self.combobox.get_active_text(),
|
| 164 |
+
self.set_entry_oid.get_text(),
|
| 165 |
+
self.set_entry_value.get_text())
|
| 166 |
+
|
| 167 |
+
def run(self):
|
| 168 |
+
"""
|
| 169 |
+
Run the application.
|
| 170 |
+
"""
|
| 171 |
+
gtk.main()
|
| 172 |
+
return
|
pool/shard007/Python/0069720_watchdog.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
|
| 3 |
+
"""Alerta WatchDog script to monitor Alerta service"""
|
| 4 |
+
__author__ = "Mark Bradley (mbrad@github)"
|
| 5 |
+
__version__ = "0.8.1"
|
| 6 |
+
|
| 7 |
+
import urllib, urllib2, sys, os, smtplib, time, socket
|
| 8 |
+
from email.mime.image import MIMEImage
|
| 9 |
+
from email.mime.multipart import MIMEMultipart
|
| 10 |
+
from email.mime.text import MIMEText
|
| 11 |
+
|
| 12 |
+
# Monitor options
|
| 13 |
+
alertaURL = 'http://alerta.example.com:8080/alerta/management/healthcheck'
|
| 14 |
+
httptimeout = 5
|
| 15 |
+
tko = 3
|
| 16 |
+
retrytime = 10
|
| 17 |
+
checkperiod = 600
|
| 18 |
+
# Email Options
|
| 19 |
+
fromaddr = 'Alerta Watchdog <alerta@example.com>'
|
| 20 |
+
toaddr = ['admins@example.com']
|
| 21 |
+
smtphost = 'localhost'
|
| 22 |
+
# PushOver.net Options
|
| 23 |
+
pushenable = False
|
| 24 |
+
pushurl = 'https://api.pushover.net/1/messages.json'
|
| 25 |
+
pushtoken = 'obtain-app-token-from-pushover'
|
| 26 |
+
pushuser = 'this-is-your-pushover-token'
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Event:
|
| 30 |
+
"Event class to construct an event object"
|
| 31 |
+
def __init__(self):
|
| 32 |
+
self.epoch = int(time.time())
|
| 33 |
+
tt = time.gmtime(self.epoch)
|
| 34 |
+
self.human = '%02d/%02d/%02d %02d:%02d:%02d' % \
|
| 35 |
+
(tt[2], tt[1], tt[0], tt[3], tt[4], tt[5])
|
| 36 |
+
try:
|
| 37 |
+
request = urllib2.Request(alertaURL, None, { 'User-Agent' : 'python' })
|
| 38 |
+
socket.setdefaulttimeout(httptimeout)
|
| 39 |
+
httpresponse = urllib2.urlopen(request, None, timeout = httptimeout)
|
| 40 |
+
self.code = httpresponse.getcode()
|
| 41 |
+
self.body = httpresponse.read()
|
| 42 |
+
httpresponse.close()
|
| 43 |
+
except urllib2.HTTPError, e:
|
| 44 |
+
self.code = e.code
|
| 45 |
+
self.body = e.read()
|
| 46 |
+
except urllib2.URLError, e:
|
| 47 |
+
self.code = 0
|
| 48 |
+
self.body = str(e.reason)
|
| 49 |
+
except socket.timeout, e:
|
| 50 |
+
self.code = 0
|
| 51 |
+
self.body = str(e.reason)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _argvchk():
|
| 55 |
+
if len(sys.argv) == 1:
|
| 56 |
+
return True
|
| 57 |
+
elif ('-h' or '--help') in sys.argv[1]:
|
| 58 |
+
print "\nThis daemon polls Alerta's Management URI remotely and determines if there is a problem.\n\t\
|
| 59 |
+
Usage: %s (-f = foreground)\n" % ((sys.argv[0]).split('/')[-1])
|
| 60 |
+
sys.exit(0)
|
| 61 |
+
elif '-f' in sys.argv[1]:
|
| 62 |
+
print "Debug Mode: Staying in foreground...\n"
|
| 63 |
+
return False
|
| 64 |
+
else:
|
| 65 |
+
print >>sys.stderr, "Error: Unknown Option"
|
| 66 |
+
sys.exit(1)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def dprint(msg):
|
| 70 |
+
if isdaemon == False: print msg
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def mailalert(last, cache, typestr):
|
| 74 |
+
if pushcount > 3:
|
| 75 |
+
dprint('Info: Not sending Email notification - too many messages for event')
|
| 76 |
+
return
|
| 77 |
+
elif pushcount == 3:
|
| 78 |
+
suppnote = 'Further notifications will be suppressed.'
|
| 79 |
+
else:
|
| 80 |
+
suppnote = ' '
|
| 81 |
+
msg = MIMEMultipart('alternative')
|
| 82 |
+
msg['Subject'] = "Alerta Service Notification"
|
| 83 |
+
msg['From'] = fromaddr
|
| 84 |
+
msg['To'] = ', '.join(toaddr)
|
| 85 |
+
if typestr == 'WARNING':
|
| 86 |
+
colour = 'ff8c00'
|
| 87 |
+
elif typestr == 'CRITICAL':
|
| 88 |
+
colour = 'ff0000'
|
| 89 |
+
elif typestr == 'OK':
|
| 90 |
+
colour = '00ff00'
|
| 91 |
+
text = """\
|
| 92 |
+
Alerta state change: %s - Response: %s (Code: %d)
|
| 93 |
+
|
| 94 |
+
TKO: %d
|
| 95 |
+
Soft Event logged at %s
|
| 96 |
+
Hard Event logged at %s
|
| 97 |
+
|
| 98 |
+
Service Probed: %s
|
| 99 |
+
|
| 100 |
+
%s
|
| 101 |
+
|
| 102 |
+
Auto-generated by Alerta-WatchDog
|
| 103 |
+
|
| 104 |
+
--
|
| 105 |
+
|
| 106 |
+
""" % (typestr, last.body, last.code, tko, cache.human, \
|
| 107 |
+
last.human, alertaURL, suppnote)
|
| 108 |
+
html = """\
|
| 109 |
+
<html>
|
| 110 |
+
<head></head>
|
| 111 |
+
<body>
|
| 112 |
+
<p>
|
| 113 |
+
Alerta state change: <span style="background-color:#%s;">%s</span> - Response: <b>%s</b> (Code: %d)<br />
|
| 114 |
+
<br />
|
| 115 |
+
<I>TKO</I>: %d<br />
|
| 116 |
+
<I>Soft Event triggered at</I> %s<br />
|
| 117 |
+
<I>Hard Event triggered at</I> %s<br />
|
| 118 |
+
<br />
|
| 119 |
+
<I>Service Probed:</I> %s</p>
|
| 120 |
+
<p><I><B>%s</I></B></p>
|
| 121 |
+
<p><I>Auto-generated by Alerta-WatchDog</I><p>
|
| 122 |
+
--
|
| 123 |
+
</body>
|
| 124 |
+
</html>
|
| 125 |
+
""" % (colour, typestr, last.body, last.code, tko, cache.human, \
|
| 126 |
+
last.human, alertaURL, suppnote)
|
| 127 |
+
|
| 128 |
+
textpart = MIMEText(text, 'plain')
|
| 129 |
+
htmlpart = MIMEText(html, 'html')
|
| 130 |
+
msg.attach(textpart)
|
| 131 |
+
msg.attach(htmlpart)
|
| 132 |
+
|
| 133 |
+
s=smtplib.SMTP(smtphost)
|
| 134 |
+
s.sendmail(fromaddr, toaddr, msg.as_string())
|
| 135 |
+
|
| 136 |
+
dprint('\033[92mMAIL SENT\033[0m\n' + text)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def pushover(last, typestr):
|
| 140 |
+
if pushcount > 3:
|
| 141 |
+
dprint('Info: Not sending PushOver notification - too many messages for event')
|
| 142 |
+
return
|
| 143 |
+
elif pushenable == False:
|
| 144 |
+
dprint('Info: PushOver notifications disabled.')
|
| 145 |
+
return
|
| 146 |
+
pushmessage = 'State: %s Response: %s (%s)' % (typestr, last.body, last.code)
|
| 147 |
+
pushdata = urllib.urlencode({"token": pushtoken, "user": pushuser, "message": pushmessage})
|
| 148 |
+
try:
|
| 149 |
+
pushrequest = urllib2.Request(pushurl, pushdata, { "Content-type": "application/x-www-form-urlencoded" })
|
| 150 |
+
socket.setdefaulttimeout(httptimeout)
|
| 151 |
+
pushresponse = urllib2.urlopen(pushrequest, timeout = httptimeout)
|
| 152 |
+
except:
|
| 153 |
+
dprint('Error: Could not send data to Pushover')
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def main():
|
| 157 |
+
"""Looping main function"""
|
| 158 |
+
global pushcount
|
| 159 |
+
pushcount = 1
|
| 160 |
+
count = 1
|
| 161 |
+
state = 'OK'
|
| 162 |
+
sleeptime = checkperiod
|
| 163 |
+
while 1:
|
| 164 |
+
dprint('Probing Alerta URI: %s' % (alertaURL))
|
| 165 |
+
response = Event()
|
| 166 |
+
dprint('Probe Response: [ Code: %s | Body: %s | Epoch: %d ]' % \
|
| 167 |
+
(response.code, response.body, response.epoch))
|
| 168 |
+
dprint('\nCOUNT: %d' % (count))
|
| 169 |
+
if response.code != 200:
|
| 170 |
+
dprint('Event Triggered')
|
| 171 |
+
if count == 1:
|
| 172 |
+
cache = response
|
| 173 |
+
dprint('Caching first event: [ Code: %d | Body: %s | Epoch: %d ]' % \
|
| 174 |
+
(cache.code, cache.body, cache.epoch))
|
| 175 |
+
if count == tko:
|
| 176 |
+
#Warnings
|
| 177 |
+
if response.body ==\
|
| 178 |
+
'HEARTBEAT_STALE':
|
| 179 |
+
state = 'WARNING'
|
| 180 |
+
dprint('State: \033[93mWARNING\033[0m')
|
| 181 |
+
mailalert(response, cache, state)
|
| 182 |
+
pushover(response, state)
|
| 183 |
+
pushcount += 1
|
| 184 |
+
count = 0 # Reset for tko more tries.
|
| 185 |
+
sleeptime = checkperiod
|
| 186 |
+
dprint('\nRe-Probing in %d seconds...' % (sleeptime))
|
| 187 |
+
time.sleep(sleeptime)
|
| 188 |
+
continue
|
| 189 |
+
else:
|
| 190 |
+
#Criticals
|
| 191 |
+
state = 'CRITICAL'
|
| 192 |
+
dprint('State: \033[91mCRITICAL\033[0m')
|
| 193 |
+
mailalert(response, cache, state)
|
| 194 |
+
pushover(response, state)
|
| 195 |
+
pushcount += 1
|
| 196 |
+
count = 0 # Reset for tko more tries.
|
| 197 |
+
sleeptime = checkperiod
|
| 198 |
+
dprint('\nRe-Probing in %d seconds...' % (sleeptime))
|
| 199 |
+
time.sleep(sleeptime)
|
| 200 |
+
continue
|
| 201 |
+
count += 1
|
| 202 |
+
sleeptime = retrytime
|
| 203 |
+
elif response.code == 200:
|
| 204 |
+
dprint('State: \033[92mOK\033[0m')
|
| 205 |
+
if state != 'OK':
|
| 206 |
+
state = 'OK'
|
| 207 |
+
pushcount = 0
|
| 208 |
+
mailalert(response, cache, state)
|
| 209 |
+
pushover(response, state)
|
| 210 |
+
sleeptime = checkperiod
|
| 211 |
+
count = 1
|
| 212 |
+
dprint('\nRe-Probing in %d seconds...' % (sleeptime))
|
| 213 |
+
time.sleep(sleeptime)
|
| 214 |
+
|
| 215 |
+
if __name__ == '__main__':
|
| 216 |
+
isdaemon = _argvchk()
|
| 217 |
+
if isdaemon == True:
|
| 218 |
+
pid = os.fork()
|
| 219 |
+
if pid:
|
| 220 |
+
sys.exit(0)
|
| 221 |
+
else:
|
| 222 |
+
print 'Alerta WatchDog process started... (PID: %d)' % (os.getpid())
|
| 223 |
+
os.close(2)
|
| 224 |
+
os.close(0)
|
| 225 |
+
os.close(1)
|
| 226 |
+
main()
|
| 227 |
+
sys.exit(0)
|
| 228 |
+
else:
|
| 229 |
+
print 'PID: %d' % (os.getpid())
|
| 230 |
+
main()
|
| 231 |
+
|
| 232 |
+
# vim: set ts=4 sw=4 et :
|
pool/shard007/Python/0069723_q1.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash/python
|
| 2 |
+
#grab urls and get all the links
|
| 3 |
+
|
| 4 |
+
from bs4 import BeautifulSoup
|
| 5 |
+
import urllib2
|
| 6 |
+
|
| 7 |
+
fn = open("100url.list","r")
|
| 8 |
+
|
| 9 |
+
for i, line in enumerate(fn):
|
| 10 |
+
try:
|
| 11 |
+
print i
|
| 12 |
+
f = open("100urls/%i.data" %i,'w')
|
| 13 |
+
hdr = { 'User-Agent' : 'Firefox 25.0' }
|
| 14 |
+
req = urllib2.Request(line, headers=hdr)
|
| 15 |
+
redditFile = urllib2.urlopen(req)
|
| 16 |
+
redditHtml = redditFile.read()
|
| 17 |
+
redditFile.close()
|
| 18 |
+
#downloads all the reference link
|
| 19 |
+
soup = BeautifulSoup(redditHtml)
|
| 20 |
+
redditAll = soup.find_all("a")
|
| 21 |
+
f.write('site:' + '\n')
|
| 22 |
+
f.write(line + '\n')
|
| 23 |
+
f.write('links:'+ '\n')
|
| 24 |
+
for links in soup.find_all('a'):
|
| 25 |
+
content = links.get('href')
|
| 26 |
+
print(content)
|
| 27 |
+
try:
|
| 28 |
+
f.write(content +'\n')
|
| 29 |
+
except:
|
| 30 |
+
f.close()
|
| 31 |
+
except:
|
| 32 |
+
pass
|
pool/shard007/Python/0069725_init__.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2016 Mycroft AI, Inc.
|
| 2 |
+
#
|
| 3 |
+
# This file is part of Mycroft Core.
|
| 4 |
+
#
|
| 5 |
+
# Mycroft Core is free software: you can redistribute it and/or modify
|
| 6 |
+
# it under the terms of the GNU General Public License as published by
|
| 7 |
+
# the Free Software Foundation, either version 3 of the License, or
|
| 8 |
+
# (at your option) any later version.
|
| 9 |
+
#
|
| 10 |
+
# Mycroft Core is distributed in the hope that it will be useful,
|
| 11 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 12 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 13 |
+
# GNU General Public License for more details.
|
| 14 |
+
#
|
| 15 |
+
# You should have received a copy of the GNU General Public License
|
| 16 |
+
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
|
| 17 |
+
|
| 18 |
+
from os.path import dirname
|
| 19 |
+
|
| 20 |
+
from adapt.intent import IntentBuilder
|
| 21 |
+
from mycroft.skills.core import MycroftSkill
|
| 22 |
+
from mycroft.util.log import getLogger
|
| 23 |
+
|
| 24 |
+
__author__ = 'chrisl8'
|
| 25 |
+
# Based on helloworld by eward
|
| 26 |
+
|
| 27 |
+
LOG = getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
class SmallTalkSkill(MycroftSkill):
|
| 30 |
+
|
| 31 |
+
def __init__(self):
|
| 32 |
+
super(SmallTalkSkill, self).__init__(name="SmallTalkSkill")
|
| 33 |
+
|
| 34 |
+
def initialize(self):
|
| 35 |
+
self.load_data_files(dirname(__file__))
|
| 36 |
+
|
| 37 |
+
# thank_you_intent = IntentBuilder("ThankYouIntent").\
|
| 38 |
+
# require("ThankYouKeyword").build()
|
| 39 |
+
# self.register_intent(thank_you_intent, self.handle_thank_you_intent)
|
| 40 |
+
#
|
| 41 |
+
# how_are_you_intent = IntentBuilder("HowAreYouIntent").\
|
| 42 |
+
# require("HowAreYouKeyword").build()
|
| 43 |
+
# self.register_intent(how_are_you_intent,
|
| 44 |
+
# self.handle_how_are_you_intent)
|
| 45 |
+
|
| 46 |
+
hi_intent = IntentBuilder("HiIntent").\
|
| 47 |
+
require("HiKeyword").build()
|
| 48 |
+
self.register_intent(hi_intent,
|
| 49 |
+
self.handle_hi_intent)
|
| 50 |
+
|
| 51 |
+
good_morning_intent = IntentBuilder("GoodMorningIntent"). \
|
| 52 |
+
require("GoodMorningKeyword").build()
|
| 53 |
+
self.register_intent(good_morning_intent,
|
| 54 |
+
self.handle_good_morning_intent)
|
| 55 |
+
|
| 56 |
+
do_you_have_my_glasses = IntentBuilder("GlassesIntent"). \
|
| 57 |
+
require("GlassesKeyword").build()
|
| 58 |
+
self.register_intent(do_you_have_my_glasses,
|
| 59 |
+
self.handle_do_you_have_my_glasses)
|
| 60 |
+
|
| 61 |
+
self.emitter.on('fallback_failure', self.handle_fallback)
|
| 62 |
+
|
| 63 |
+
# def handle_thank_you_intent(self, message):
|
| 64 |
+
# self.speak_dialog("welcome")
|
| 65 |
+
#
|
| 66 |
+
# def handle_how_are_you_intent(self, message):
|
| 67 |
+
# self.speak_dialog("how.are.you")
|
| 68 |
+
|
| 69 |
+
def handle_hi_intent(self, message):
|
| 70 |
+
self.speak_dialog("hi")
|
| 71 |
+
|
| 72 |
+
def handle_good_morning_intent(self, message):
|
| 73 |
+
self.speak_dialog("good.morning")
|
| 74 |
+
|
| 75 |
+
def handle_do_you_have_my_glasses(self, message):
|
| 76 |
+
self.speak_dialog("glasses")
|
| 77 |
+
|
| 78 |
+
def handle_fallback(self, message):
|
| 79 |
+
utt = message.data.get('utterance')
|
| 80 |
+
LOG.debug("SmallTalk fallback attempt: " + utt)
|
| 81 |
+
self.speak_dialog("fallback", data={'phrase': utt})
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def stop(self):
|
| 85 |
+
pass
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def create_skill():
|
| 89 |
+
return SmallTalkSkill()
|
pool/shard007/Python/0069728_helper.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import errno
|
| 2 |
+
import shutil
|
| 3 |
+
import tempfile
|
| 4 |
+
|
| 5 |
+
class TempDirTest(object):
|
| 6 |
+
def setup(self):
|
| 7 |
+
self.tmp_dir = tempfile.mkdtemp()
|
| 8 |
+
|
| 9 |
+
def teardown(self):
|
| 10 |
+
try:
|
| 11 |
+
shutil.rmtree(self.tmp_dir)
|
| 12 |
+
except OSError as ex:
|
| 13 |
+
if ex.errno != errno.ENOENT:
|
| 14 |
+
raise
|
| 15 |
+
|
| 16 |
+
class _ANY(object):
|
| 17 |
+
"A helper object that compares equal to everything."
|
| 18 |
+
|
| 19 |
+
def __eq__(self, other):
|
| 20 |
+
return True
|
| 21 |
+
|
| 22 |
+
def __ne__(self, other):
|
| 23 |
+
return False
|
| 24 |
+
|
| 25 |
+
def __repr__(self):
|
| 26 |
+
return '<ANY>'
|
| 27 |
+
|
| 28 |
+
ANY = _ANY()
|
pool/shard007/Python/0069733_throttled.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Throttled(object):
|
| 7 |
+
def __init__(self, min_time_since_last_run_s=5):
|
| 8 |
+
"""Used for simple throttled execution.
|
| 9 |
+
|
| 10 |
+
Here's a simple example:
|
| 11 |
+
|
| 12 |
+
@Throttled(1)
|
| 13 |
+
def lol(i):
|
| 14 |
+
print('epoch %d' % (i,), flush=True)
|
| 15 |
+
|
| 16 |
+
for i in range(100000000):
|
| 17 |
+
lol(i)
|
| 18 |
+
|
| 19 |
+
Above code will report the epoch every second.
|
| 20 |
+
|
| 21 |
+
Here's another way:
|
| 22 |
+
|
| 23 |
+
throttled = Throttled(1)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
for i in range(100000000000):
|
| 27 |
+
if throttled.should_i_run():
|
| 28 |
+
print('epoch %d' % (i,), flush=True)
|
| 29 |
+
"""
|
| 30 |
+
self.last_time = None
|
| 31 |
+
self.min_time_since_last_run_s = min_time_since_last_run_s
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def should_i_run(self, min_time_since_last_run_s=None):
|
| 35 |
+
min_time_since_last_run_s = min_time_since_last_run_s or self.min_time_since_last_run_s
|
| 36 |
+
now = time.time()
|
| 37 |
+
if self.last_time is None or (now - self.last_time) > min_time_since_last_run_s:
|
| 38 |
+
self.last_time = now
|
| 39 |
+
return True
|
| 40 |
+
else:
|
| 41 |
+
return False
|
| 42 |
+
|
| 43 |
+
def maybe_run(self, f, min_time_since_last_run_s=None):
|
| 44 |
+
if self.should_i_run(min_time_since_last_run_s):
|
| 45 |
+
return f()
|
| 46 |
+
else:
|
| 47 |
+
return None
|
| 48 |
+
|
| 49 |
+
def __call__(self, f):
|
| 50 |
+
def wrapper(*args, **kwargs):
|
| 51 |
+
return self.maybe_run(lambda: f(*args, **kwargs))
|
| 52 |
+
return wrapper
|
pool/shard007/Python/0069734_titansoftv.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# URL: http://code.google.com/p/sickbeard
|
| 3 |
+
# Originally written for SickGear
|
| 4 |
+
#
|
| 5 |
+
# This file is part of SickRage.
|
| 6 |
+
#
|
| 7 |
+
# SickRage is free software: you can redistribute it and/or modify
|
| 8 |
+
# it under the terms of the GNU General Public License as published by
|
| 9 |
+
# the Free Software Foundation, either version 3 of the License, or
|
| 10 |
+
# (at your option) any later version.
|
| 11 |
+
#
|
| 12 |
+
# SickRage is distributed in the hope that it will be useful,
|
| 13 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 14 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 15 |
+
# GNU General Public License for more details.
|
| 16 |
+
#
|
| 17 |
+
# You should have received a copy of the GNU General Public License
|
| 18 |
+
# along with SickRage. If not, see <http://www.gnu.org/licenses/>.
|
| 19 |
+
|
| 20 |
+
import urllib
|
| 21 |
+
|
| 22 |
+
import generic
|
| 23 |
+
from sickbeard import logger
|
| 24 |
+
from sickbeard import tvcache
|
| 25 |
+
from sickbeard.helpers import mapIndexersToShow
|
| 26 |
+
from sickrage.helper.exceptions import AuthException
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class TitansOfTVProvider(generic.TorrentProvider):
|
| 30 |
+
def __init__(self):
|
| 31 |
+
generic.TorrentProvider.__init__(self, 'TitansOfTV')
|
| 32 |
+
self.supportsBacklog = True
|
| 33 |
+
self.public = False
|
| 34 |
+
self.supportsAbsoluteNumbering = True
|
| 35 |
+
self.api_key = None
|
| 36 |
+
self.ratio = None
|
| 37 |
+
self.cache = TitansOfTVCache(self)
|
| 38 |
+
self.url = 'http://titansof.tv/api/torrents'
|
| 39 |
+
self.download_url = 'http://titansof.tv/api/torrents/%s/download?apikey=%s'
|
| 40 |
+
|
| 41 |
+
def isEnabled(self):
|
| 42 |
+
return self.enabled
|
| 43 |
+
|
| 44 |
+
def imageName(self):
|
| 45 |
+
return 'titansoftv.png'
|
| 46 |
+
|
| 47 |
+
def seedRatio(self):
|
| 48 |
+
return self.ratio
|
| 49 |
+
|
| 50 |
+
def _checkAuth(self):
|
| 51 |
+
if not self.api_key:
|
| 52 |
+
raise AuthException('Your authentication credentials for ' + self.name + ' are missing, check your config.')
|
| 53 |
+
|
| 54 |
+
return True
|
| 55 |
+
|
| 56 |
+
def _checkAuthFromData(self, data):
|
| 57 |
+
|
| 58 |
+
if 'error' in data:
|
| 59 |
+
logger.log(u'Incorrect authentication credentials for ' + self.name + ' : ' + data['error'],
|
| 60 |
+
logger.DEBUG)
|
| 61 |
+
raise AuthException(
|
| 62 |
+
'Your authentication credentials for ' + self.name + ' are incorrect, check your config.')
|
| 63 |
+
|
| 64 |
+
return True
|
| 65 |
+
|
| 66 |
+
def _doSearch(self, search_params, search_mode='eponly', epcount=0, age=0, epObj=None):
|
| 67 |
+
self._checkAuth()
|
| 68 |
+
results = []
|
| 69 |
+
params = {}
|
| 70 |
+
self.headers.update({'X-Authorization': self.api_key})
|
| 71 |
+
|
| 72 |
+
if search_params:
|
| 73 |
+
params.update(search_params)
|
| 74 |
+
|
| 75 |
+
search_url = self.url + '?' + urllib.urlencode(params)
|
| 76 |
+
logger.log(u'Search url: %s' % search_url)
|
| 77 |
+
|
| 78 |
+
parsedJSON = self.getURL(search_url, json=True) # do search
|
| 79 |
+
|
| 80 |
+
if not parsedJSON:
|
| 81 |
+
logger.log(u'No data returned from ' + self.name, logger.ERROR)
|
| 82 |
+
return results
|
| 83 |
+
|
| 84 |
+
if self._checkAuthFromData(parsedJSON):
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
found_torrents = parsedJSON['results']
|
| 88 |
+
except:
|
| 89 |
+
found_torrents = {}
|
| 90 |
+
|
| 91 |
+
for result in found_torrents:
|
| 92 |
+
(title, url) = self._get_title_and_url(result)
|
| 93 |
+
|
| 94 |
+
if title and url:
|
| 95 |
+
results.append(result)
|
| 96 |
+
|
| 97 |
+
return results
|
| 98 |
+
|
| 99 |
+
def _get_title_and_url(self, parsedJSON):
|
| 100 |
+
|
| 101 |
+
title = parsedJSON['release_name']
|
| 102 |
+
id = parsedJSON['id']
|
| 103 |
+
url = self.download_url % (id, self.api_key)
|
| 104 |
+
|
| 105 |
+
return title, url
|
| 106 |
+
|
| 107 |
+
def _get_season_search_strings(self, ep_obj):
|
| 108 |
+
search_params = {'limit': 100}
|
| 109 |
+
|
| 110 |
+
search_params['season'] = 'Season %02d' % ep_obj.scene_season
|
| 111 |
+
|
| 112 |
+
if ep_obj.show.indexer == 1:
|
| 113 |
+
search_params['series_id'] = ep_obj.show.indexerid
|
| 114 |
+
elif ep_obj.show.indexer == 2:
|
| 115 |
+
tvdbid = mapIndexersToShow(ep_obj.show)[1]
|
| 116 |
+
if tvdbid:
|
| 117 |
+
search_params['series_id'] = tvdbid
|
| 118 |
+
|
| 119 |
+
return [search_params]
|
| 120 |
+
|
| 121 |
+
def _get_episode_search_strings(self, ep_obj, add_string=''):
|
| 122 |
+
|
| 123 |
+
if not ep_obj:
|
| 124 |
+
return [{}]
|
| 125 |
+
|
| 126 |
+
search_params = {'limit': 100}
|
| 127 |
+
|
| 128 |
+
# Do a general name search for the episode, formatted like SXXEYY
|
| 129 |
+
search_params['episode'] = 'S%02dE%02d' % (ep_obj.scene_season, ep_obj.scene_episode)
|
| 130 |
+
|
| 131 |
+
if ep_obj.show.indexer == 1:
|
| 132 |
+
search_params['series_id'] = ep_obj.show.indexerid
|
| 133 |
+
elif ep_obj.show.indexer == 2:
|
| 134 |
+
tvdbid = mapIndexersToShow(ep_obj.show)[1]
|
| 135 |
+
if tvdbid:
|
| 136 |
+
search_params['series_id'] = tvdbid
|
| 137 |
+
|
| 138 |
+
return [search_params]
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class TitansOfTVCache(tvcache.TVCache):
|
| 142 |
+
def __init__(self, provider):
|
| 143 |
+
tvcache.TVCache.__init__(self, provider)
|
| 144 |
+
|
| 145 |
+
# At least 10 minutes between queries
|
| 146 |
+
self.minTime = 10
|
| 147 |
+
|
| 148 |
+
def _getRSSData(self):
|
| 149 |
+
search_params = {'limit': 100}
|
| 150 |
+
return self.provider._doSearch(search_params)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
provider = TitansOfTVProvider()
|
pool/shard007/Python/0069740_matchessourcefilter.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Gramps - a GTK+/GNOME based genealogy program
|
| 3 |
+
#
|
| 4 |
+
# Copyright (C) 2002-2006 Donald N. Allingham
|
| 5 |
+
# Copyright (C) 2010 Benny Malengier
|
| 6 |
+
# Copyright (C) 2011 Tim G L Lyons
|
| 7 |
+
#
|
| 8 |
+
# This program is free software; you can redistribute it and/or modify
|
| 9 |
+
# it under the terms of the GNU General Public License as published by
|
| 10 |
+
# the Free Software Foundation; either version 2 of the License, or
|
| 11 |
+
# (at your option) any later version.
|
| 12 |
+
#
|
| 13 |
+
# This program is distributed in the hope that it will be useful,
|
| 14 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 15 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 16 |
+
# GNU General Public License for more details.
|
| 17 |
+
#
|
| 18 |
+
# You should have received a copy of the GNU General Public License
|
| 19 |
+
# along with this program; if not, write to the Free Software
|
| 20 |
+
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
| 21 |
+
#
|
| 22 |
+
|
| 23 |
+
#-------------------------------------------------------------------------
|
| 24 |
+
#
|
| 25 |
+
# Standard Python modules
|
| 26 |
+
#
|
| 27 |
+
#-------------------------------------------------------------------------
|
| 28 |
+
from ....const import GRAMPS_LOCALE as glocale
|
| 29 |
+
_ = glocale.translation.gettext
|
| 30 |
+
|
| 31 |
+
#-------------------------------------------------------------------------
|
| 32 |
+
#
|
| 33 |
+
# GRAMPS modules
|
| 34 |
+
#
|
| 35 |
+
#-------------------------------------------------------------------------
|
| 36 |
+
from .. import MatchesSourceFilterBase
|
| 37 |
+
|
| 38 |
+
#-------------------------------------------------------------------------
|
| 39 |
+
#
|
| 40 |
+
# MatchesFilter
|
| 41 |
+
#
|
| 42 |
+
#-------------------------------------------------------------------------
|
| 43 |
+
class MatchesSourceFilter(MatchesSourceFilterBase):
|
| 44 |
+
"""
|
| 45 |
+
Rule that checks against another filter.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
labels = [_('Source filter name:')]
|
| 49 |
+
name = _('Events with source matching the <source filter>')
|
| 50 |
+
description = _("Matches events with sources that match the "
|
| 51 |
+
"specified source filter name")
|
| 52 |
+
category = _('Citation/source filters')
|
| 53 |
+
|
| 54 |
+
# we want to have this filter show source filters
|
| 55 |
+
namespace = 'Source'
|
pool/shard007/Python/0069741_makeparsed.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Global modules
|
| 2 |
+
import os
|
| 3 |
+
# Third party modules
|
| 4 |
+
import pystache
|
| 5 |
+
# Local modules
|
| 6 |
+
from seleniumcrawler.filesystem import locate_sites
|
| 7 |
+
|
| 8 |
+
template = '''from selenium import webdriver
|
| 9 |
+
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
|
| 10 |
+
|
| 11 |
+
def get_profile():
|
| 12 |
+
# get the Firefox profile object
|
| 13 |
+
firefoxProfile = FirefoxProfile()
|
| 14 |
+
# Disable CSS
|
| 15 |
+
firefoxProfile.set_preference('permissions.default.stylesheet', 2)
|
| 16 |
+
# Disable images
|
| 17 |
+
firefoxProfile.set_preference('permissions.default.image', 2)
|
| 18 |
+
# Disable Flash
|
| 19 |
+
firefoxProfile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so',
|
| 20 |
+
'false')
|
| 21 |
+
|
| 22 |
+
return firefoxProfile
|
| 23 |
+
|
| 24 |
+
def handle_link(link):
|
| 25 |
+
profile = get_profile()
|
| 26 |
+
|
| 27 |
+
# Set the modified profile while creating the browser object
|
| 28 |
+
driver = webdriver.Firefox(profile)
|
| 29 |
+
driver.implicitly_wait(30)
|
| 30 |
+
driver.get(link)
|
| 31 |
+
|
| 32 |
+
{{{code}}}
|
| 33 |
+
results = {
|
| 34 |
+
'url': driver.current_url,
|
| 35 |
+
'source': driver.page_source
|
| 36 |
+
}
|
| 37 |
+
driver.quit()
|
| 38 |
+
|
| 39 |
+
return results
|
| 40 |
+
'''
|
| 41 |
+
|
| 42 |
+
def parse_raw_script(name, directory, path):
|
| 43 |
+
f = open(path)
|
| 44 |
+
|
| 45 |
+
codelines = []
|
| 46 |
+
at_main_code = False
|
| 47 |
+
for line in f:
|
| 48 |
+
if at_main_code:
|
| 49 |
+
codelines.append(line[4:])
|
| 50 |
+
if line.startswith(' def test_'):
|
| 51 |
+
at_main_code = True
|
| 52 |
+
elif line.startswith(' def') and at_main_code:
|
| 53 |
+
codelines = codelines[1:-2]
|
| 54 |
+
at_main_code = False
|
| 55 |
+
break
|
| 56 |
+
|
| 57 |
+
fout = open(os.path.join(directory, name + '.py'), 'w')
|
| 58 |
+
code = ''.join(codelines)
|
| 59 |
+
data = {'code': code}
|
| 60 |
+
rendered = pystache.render(template, data)
|
| 61 |
+
fout.write(rendered)
|
| 62 |
+
|
| 63 |
+
for site in locate_sites():
|
| 64 |
+
parse_raw_script(site['name'], site['site_dir'], site['script_path'])
|
| 65 |
+
print "Parsed %s." % site['script_path']
|
pool/shard007/Python/0069751_contexts.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
# Open Chord Charts -- Database of free chord charts
|
| 5 |
+
# By: Christophe Benz <contact@openchordcharts.org>
|
| 6 |
+
#
|
| 7 |
+
# Copyright (C) 2012, 2013, 2014, 2015 Christophe Benz
|
| 8 |
+
# https://github.com/openchordcharts/
|
| 9 |
+
#
|
| 10 |
+
# This file is part of Open Chord Charts.
|
| 11 |
+
#
|
| 12 |
+
# Open Chord Charts is free software; you can redistribute it and/or modify
|
| 13 |
+
# it under the terms of the GNU Affero General Public License as
|
| 14 |
+
# published by the Free Software Foundation, either version 3 of the
|
| 15 |
+
# License, or (at your option) any later version.
|
| 16 |
+
#
|
| 17 |
+
# Open Chord Charts is distributed in the hope that it will be useful,
|
| 18 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 19 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 20 |
+
# GNU Affero General Public License for more details.
|
| 21 |
+
#
|
| 22 |
+
# You should have received a copy of the GNU Affero General Public License
|
| 23 |
+
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
"""Context loaded and saved in WSGI requests"""
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
from biryani.states import State
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class Ctx(State):
|
| 33 |
+
env_keys = ('_node', '_user')
|
| 34 |
+
_ = lambda self, message: message
|
| 35 |
+
_node = None # Used by route functions to store model object matching id or slug in URL.
|
| 36 |
+
_user = UnboundLocalError
|
| 37 |
+
req = None
|
| 38 |
+
|
| 39 |
+
def __init__(self, req=None):
|
| 40 |
+
if req is not None:
|
| 41 |
+
self.req = req
|
| 42 |
+
ctx_env = req.environ.get('open-chord-charts', {})
|
| 43 |
+
for key in self.env_keys:
|
| 44 |
+
value = ctx_env.get(key)
|
| 45 |
+
if value is not None:
|
| 46 |
+
setattr(self, key, value)
|
| 47 |
+
|
| 48 |
+
def node_del(self):
|
| 49 |
+
del self._node
|
| 50 |
+
if self.req is not None and self.req.environ.get('open-chord-charts') is not None \
|
| 51 |
+
and '_node' in self.req.environ['open-chord-charts']:
|
| 52 |
+
del self.req.environ['open-chord-charts']['_node']
|
| 53 |
+
|
| 54 |
+
def node_get(self):
|
| 55 |
+
return self._node
|
| 56 |
+
|
| 57 |
+
def node_set(self, node):
|
| 58 |
+
self._node = node
|
| 59 |
+
if self.req is not None:
|
| 60 |
+
self.req.environ.setdefault('open-chord-charts', {})['_node'] = node
|
| 61 |
+
|
| 62 |
+
node = property(node_get, node_set, node_del)
|
| 63 |
+
|
| 64 |
+
def user_del(self):
|
| 65 |
+
del self._user
|
| 66 |
+
if self.req is not None and self.req.environ.get('open-chord-charts') is not None \
|
| 67 |
+
and '_user' in self.req.environ['open-chord-charts']:
|
| 68 |
+
del self.req.environ['open-chord-charts']['_user']
|
| 69 |
+
|
| 70 |
+
def user_get(self):
|
| 71 |
+
return self._user
|
| 72 |
+
|
| 73 |
+
def user_set(self, user):
|
| 74 |
+
self._user = user
|
| 75 |
+
if self.req is not None:
|
| 76 |
+
self.req.environ.setdefault('open-chord-charts', {})['_user'] = user
|
| 77 |
+
|
| 78 |
+
user = property(user_get, user_set, user_del)
|
pool/shard007/Python/0069758_1217_conveniences.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python
|
| 2 |
+
'''
|
| 3 |
+
NPR 2017-12-17
|
| 4 |
+
https://www.npr.org/2017/12/17/571421849/sunday-puzzle-capital-letters
|
| 5 |
+
|
| 6 |
+
Think of a convenience introduced in the 19th century that is still around today.
|
| 7 |
+
Its name has two words. Take the first three letters of the first word and the
|
| 8 |
+
first letter of its second word, in order, to get a convenience introduced in the
|
| 9 |
+
21st century that serves a similar purpose. Their names are otherwise unrelated.
|
| 10 |
+
What two conveniences are these?
|
| 11 |
+
'''
|
| 12 |
+
|
| 13 |
+
from nltk.corpus import wordnet as wn
|
| 14 |
+
|
| 15 |
+
from nltk.tokenize import word_tokenize
|
| 16 |
+
from nltk import FreqDist
|
| 17 |
+
|
| 18 |
+
import sys
|
| 19 |
+
sys.path.append('..')
|
| 20 |
+
from nprcommontools import get_hypernyms
|
| 21 |
+
|
| 22 |
+
#%%
|
| 23 |
+
# "common" words from Wordnet
|
| 24 |
+
# We use words in example sentences
|
| 25 |
+
def_corpus = []
|
| 26 |
+
for s in wn.all_synsets():
|
| 27 |
+
for ex in s.examples():
|
| 28 |
+
for w in word_tokenize(ex):
|
| 29 |
+
if w.isalpha():
|
| 30 |
+
def_corpus.append(w.lower())
|
| 31 |
+
|
| 32 |
+
fdist = FreqDist(def_corpus)
|
| 33 |
+
common_words = set()
|
| 34 |
+
NUM_WORDS = 50000
|
| 35 |
+
for word, frequency in fdist.most_common(NUM_WORDS):
|
| 36 |
+
# Keep only the best short words
|
| 37 |
+
if len(word) > 2 or word in ('a','i') or fdist[word] > 100:
|
| 38 |
+
common_words.add(word)
|
| 39 |
+
|
| 40 |
+
#%%
|
| 41 |
+
four = set()
|
| 42 |
+
two_words = set()
|
| 43 |
+
for s in wn.all_synsets():
|
| 44 |
+
if s.pos() == 'n':
|
| 45 |
+
for l in s.lemma_names():
|
| 46 |
+
if l[0] != l[0].upper():
|
| 47 |
+
if len(l) == 4 and '_' not in l and l in common_words:
|
| 48 |
+
four.add(l)
|
| 49 |
+
elif l.count('_') == 1 and l.split('_')[0] in common_words and l.split('_')[1] in common_words:
|
| 50 |
+
if 'product' in get_hypernyms(l):
|
| 51 |
+
two_words.add(l)
|
| 52 |
+
|
| 53 |
+
#%%
|
| 54 |
+
for t in sorted(two_words):
|
| 55 |
+
w1,w2 = t.split('_')
|
| 56 |
+
if w1[:3] + w2[0] in four:
|
| 57 |
+
print t,w1[:3] + w2[0]
|
| 58 |
+
|
| 59 |
+
|
pool/shard007/Python/0069761_ahlinux_to_ghost.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -*- coding:utf-8 -*-
|
| 3 |
+
|
| 4 |
+
import _env
|
| 5 |
+
import io
|
| 6 |
+
import json
|
| 7 |
+
import re
|
| 8 |
+
import time
|
| 9 |
+
from lib._db import get_collection
|
| 10 |
+
from config.config import CONFIG
|
| 11 |
+
from judge_upload import exist_or_insert
|
| 12 |
+
DB = CONFIG.MONGO.DATABASE
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
PAT = re.compile('[-#\w]+')
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def find_first_tag(s):
|
| 19 |
+
m = PAT.search(s)
|
| 20 |
+
return m.group() if m else s
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def remove_china_char(s):
|
| 24 |
+
if not s:
|
| 25 |
+
return s
|
| 26 |
+
return re.sub(ur"[\u4e00-\u9fa5]+", '', s)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def cur_timestamp():
|
| 30 |
+
return int(time.time() * 1000)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
USERS = [
|
| 34 |
+
{
|
| 35 |
+
"id": 1,
|
| 36 |
+
"name": "jishushare",
|
| 37 |
+
"slug": "jishushare",
|
| 38 |
+
"email": "user@example.com",
|
| 39 |
+
"image": None,
|
| 40 |
+
"cover": None,
|
| 41 |
+
"bio": None,
|
| 42 |
+
"website": None,
|
| 43 |
+
"location": None,
|
| 44 |
+
"accessibility": None,
|
| 45 |
+
"status": "active",
|
| 46 |
+
"language": "zh_CN",
|
| 47 |
+
"meta_title": None,
|
| 48 |
+
"meta_description": None,
|
| 49 |
+
"last_login": None,
|
| 50 |
+
"created_at": 1283780649000,
|
| 51 |
+
"created_by": 1,
|
| 52 |
+
"updated_at": 1286958624000,
|
| 53 |
+
"updated_by": 1
|
| 54 |
+
}
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
TAGS = [
|
| 59 |
+
{
|
| 60 |
+
"id": 1,
|
| 61 |
+
"name": u'文章',
|
| 62 |
+
"slug": u'article',
|
| 63 |
+
"description": ""
|
| 64 |
+
}
|
| 65 |
+
]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def replace_post(post_data):
|
| 69 |
+
d = {
|
| 70 |
+
"id": 5,
|
| 71 |
+
"title": "my blog post title",
|
| 72 |
+
#"slug": "my-blog-post-title",
|
| 73 |
+
"markdown": "the *markdown* formatted post body",
|
| 74 |
+
#"html": "the <i>html</i> formatted post body",
|
| 75 |
+
"image": None,
|
| 76 |
+
"featured": 0,
|
| 77 |
+
"page": 0,
|
| 78 |
+
"status": "published",
|
| 79 |
+
"language": "zh_CN",
|
| 80 |
+
"meta_title": None,
|
| 81 |
+
"meta_description": None,
|
| 82 |
+
"author_id": 1,
|
| 83 |
+
"created_at": cur_timestamp(),
|
| 84 |
+
"created_by": 1,
|
| 85 |
+
"updated_at": cur_timestamp(),
|
| 86 |
+
"updated_by": 1,
|
| 87 |
+
"published_at": cur_timestamp(),
|
| 88 |
+
"published_by": 1
|
| 89 |
+
}
|
| 90 |
+
d['id'] = int(post_data['source_url'].rsplit('/', 1)[1].split('.')[0])
|
| 91 |
+
d['title'] = post_data['title'].strip()
|
| 92 |
+
if post_data['slug'] > 30:
|
| 93 |
+
d['slug'] = post_data['slug'][0:30]
|
| 94 |
+
d['markdown'] = post_data['content'].strip()
|
| 95 |
+
return d
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def migrate(coll_name='article_pyhome', skip=0, limit=10):
|
| 99 |
+
res = {
|
| 100 |
+
"meta": {
|
| 101 |
+
"exported_on": cur_timestamp(),
|
| 102 |
+
"version": "003"
|
| 103 |
+
}
|
| 104 |
+
}
|
| 105 |
+
coll = get_collection(DB, coll_name)
|
| 106 |
+
|
| 107 |
+
posts = []
|
| 108 |
+
posts_tags = []
|
| 109 |
+
slug_set = set()
|
| 110 |
+
|
| 111 |
+
for doc in coll.find().skip(skip).limit(limit):
|
| 112 |
+
title = doc.get('title')
|
| 113 |
+
slug = title.lower().strip()
|
| 114 |
+
|
| 115 |
+
if slug and (slug not in slug_set):
|
| 116 |
+
slug_set.add(slug)
|
| 117 |
+
doc['slug'] = slug
|
| 118 |
+
|
| 119 |
+
if not exist_or_insert(slug):
|
| 120 |
+
doc_id = doc.get('_id')
|
| 121 |
+
post_id = int(doc['source_url'].rsplit('/', 1)[1].split('.')[0])
|
| 122 |
+
|
| 123 |
+
posts.append(replace_post(doc))
|
| 124 |
+
posts_tags.append(
|
| 125 |
+
{"tag_id": 1, "post_id": post_id}
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
data = {
|
| 129 |
+
"posts": posts,
|
| 130 |
+
"tags": TAGS,
|
| 131 |
+
"posts_tags": posts_tags,
|
| 132 |
+
"users": USERS
|
| 133 |
+
}
|
| 134 |
+
res["data"] = data
|
| 135 |
+
return res
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def tag_migrate(limit=10):
|
| 139 |
+
res = {
|
| 140 |
+
"meta": {
|
| 141 |
+
"exported_on": cur_timestamp(),
|
| 142 |
+
"version": "003"
|
| 143 |
+
}
|
| 144 |
+
}
|
| 145 |
+
coll = get_collection(DB, 'article')
|
| 146 |
+
|
| 147 |
+
posts = []
|
| 148 |
+
tags_id_map = {}
|
| 149 |
+
posts_tags = []
|
| 150 |
+
tag_id = 1000
|
| 151 |
+
index = 0
|
| 152 |
+
|
| 153 |
+
for doc in coll.find().batch_size(1000):
|
| 154 |
+
#print(doc.get('title'))
|
| 155 |
+
index += 1
|
| 156 |
+
if index > limit:
|
| 157 |
+
break
|
| 158 |
+
|
| 159 |
+
posts.append(replace_post(doc))
|
| 160 |
+
post_id = int(doc['source_url'].rsplit('/', 1)[1].split('.')[0])
|
| 161 |
+
tag_list = doc.get('tag_list')
|
| 162 |
+
tag = tag_list[0] if tag_list else ''
|
| 163 |
+
tag = remove_china_char(tag)
|
| 164 |
+
if tag:
|
| 165 |
+
save_tag = tag.replace(' ', '-').lower()
|
| 166 |
+
save_tag = find_first_tag(save_tag)
|
| 167 |
+
if len(save_tag) > 10:
|
| 168 |
+
posts_tags.append(
|
| 169 |
+
{"tag_id": 1, "post_id": post_id}
|
| 170 |
+
)
|
| 171 |
+
continue
|
| 172 |
+
|
| 173 |
+
if save_tag not in tags_id_map:
|
| 174 |
+
tag_id += 1
|
| 175 |
+
TAGS.append({
|
| 176 |
+
"id": tag_id,
|
| 177 |
+
"name": save_tag,
|
| 178 |
+
"slug": save_tag,
|
| 179 |
+
"description": ""
|
| 180 |
+
})
|
| 181 |
+
tags_id_map[save_tag] = tag_id
|
| 182 |
+
posts_tags.append(
|
| 183 |
+
{"tag_id": tags_id_map[save_tag], "post_id": post_id}
|
| 184 |
+
)
|
| 185 |
+
else:
|
| 186 |
+
posts_tags.append(
|
| 187 |
+
{"tag_id": tags_id_map[save_tag], "post_id": post_id}
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
data = {
|
| 191 |
+
"posts": posts,
|
| 192 |
+
"tags": TAGS,
|
| 193 |
+
"posts_tags": posts_tags,
|
| 194 |
+
"users": USERS
|
| 195 |
+
}
|
| 196 |
+
res["data"] = data
|
| 197 |
+
return res
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def test():
|
| 201 |
+
print(find_first_tag('正则表达式指南'))
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def incr_migrate(coll_name, limit):
|
| 205 |
+
coll = get_collection(DB, coll_name)
|
| 206 |
+
all_cnt = coll.find().count()
|
| 207 |
+
start = 0
|
| 208 |
+
index = 0
|
| 209 |
+
|
| 210 |
+
while start < all_cnt:
|
| 211 |
+
res = migrate(coll_name, start, limit)
|
| 212 |
+
filename = str(index) + '_article.json'
|
| 213 |
+
# print(json.dumps(res, indent=4))
|
| 214 |
+
with io.open(filename, 'w+', encoding='utf8') as outfile:
|
| 215 |
+
data = json.dumps(res, ensure_ascii=False,
|
| 216 |
+
encoding='utf8', indent=4)
|
| 217 |
+
outfile.write(unicode(data))
|
| 218 |
+
|
| 219 |
+
index += 1
|
| 220 |
+
start += limit
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def main():
|
| 224 |
+
import sys
|
| 225 |
+
try:
|
| 226 |
+
cnt = int(sys.argv[1])
|
| 227 |
+
except:
|
| 228 |
+
cnt = 300
|
| 229 |
+
res = migrate('ahlinux_pyhome', 0, 500)
|
| 230 |
+
print(json.dumps(res, indent=4))
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
if __name__ == '__main__':
|
| 234 |
+
#main()
|
| 235 |
+
incr_migrate('ahlinux_pyhome', limit=500)
|
pool/shard007/Python/0069765_init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Quokka CMS!"""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from quokka.core.app import QuokkaApp
|
| 5 |
+
from quokka.core import configure_extensions, configure_extension
|
| 6 |
+
from quokka.core.flask_dynaconf import configure_dynaconf
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def create_app_base(test=False, ext_list=None, **settings):
|
| 10 |
+
"""Creates basic app only with extensions provided in ext_list
|
| 11 |
+
useful for testing."""
|
| 12 |
+
|
| 13 |
+
app = QuokkaApp('quokka')
|
| 14 |
+
if settings:
|
| 15 |
+
app.config.update(settings)
|
| 16 |
+
configure_dynaconf(app)
|
| 17 |
+
|
| 18 |
+
if test or app.config.get('TESTING'):
|
| 19 |
+
app.testing = True
|
| 20 |
+
|
| 21 |
+
app.static_folder = Path.cwd() / Path('static')
|
| 22 |
+
# Path(app.config['PROJECT_ROOT'])
|
| 23 |
+
|
| 24 |
+
if ext_list:
|
| 25 |
+
for ext in ext_list:
|
| 26 |
+
configure_extension(ext, app=app)
|
| 27 |
+
|
| 28 |
+
return app
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def create_app(test=False, **settings):
|
| 32 |
+
"""Creates full app with all extensions loaded"""
|
| 33 |
+
app = create_app_base(test=test, **settings)
|
| 34 |
+
configure_extensions(app)
|
| 35 |
+
return app
|
pool/shard007/Python/0069768_electrostatics_example.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
# This script is an example of calculation of long range interactions
|
| 3 |
+
# (Coulomb interaction) using the Ewald summation and the P3M methods.
|
| 4 |
+
#
|
| 5 |
+
# Initially, the simple cubic structure is generated in order to represent the
|
| 6 |
+
# NaCl crystal. Then the energy and forces are calculated and compared using both
|
| 7 |
+
# the Ewald summation and the P3M. At the end the Madelung constant of NaCl crystal
|
| 8 |
+
# is calculated.
|
| 9 |
+
#
|
| 10 |
+
# At the moment there is only metallic surrounding media is possible.
|
| 11 |
+
|
| 12 |
+
# Parameters:
|
| 13 |
+
|
| 14 |
+
# Ewald summation:
|
| 15 |
+
alpha = 1.112583061 (Ewald parameter)
|
| 16 |
+
rspacecutoff = 4.9 (the cutoff in real space)
|
| 17 |
+
kspacecutoff = 30 (the cutoff in reciprocal space)
|
| 18 |
+
|
| 19 |
+
# P3M:
|
| 20 |
+
M = (16, 16, 16) (mesh)
|
| 21 |
+
P = 7 (charge assignment order)
|
| 22 |
+
'''
|
| 23 |
+
|
| 24 |
+
# The script itself
|
| 25 |
+
import mpi4py.MPI as MPI
|
| 26 |
+
import espressopp
|
| 27 |
+
from espressopp import Real3D
|
| 28 |
+
|
| 29 |
+
# initial parameters
|
| 30 |
+
N = 16 # number of particles on lattice site
|
| 31 |
+
num_particles = N**3 # total number of particles
|
| 32 |
+
rho = 0.03 # number density of particles, number of particles devided by volume
|
| 33 |
+
|
| 34 |
+
# creating a cubic NaCl crystal
|
| 35 |
+
#print 'Creating a simple cubic structure...'
|
| 36 |
+
x, y, z, Lx, Ly, Lz = espressopp.tools.lattice.createCubic(num_particles, rho, False)
|
| 37 |
+
|
| 38 |
+
# creating the system box
|
| 39 |
+
box = (Lx, Ly, Lz)
|
| 40 |
+
print 'System box size: ', box
|
| 41 |
+
print 'Number of particles = ', num_particles
|
| 42 |
+
|
| 43 |
+
# Ewald summation parameters
|
| 44 |
+
#alphaEwald = 1.112583061 # alpha - Ewald parameter
|
| 45 |
+
alphaEwald = 0.660557
|
| 46 |
+
rspacecutoff = 4.9 # rspacecutoff - the cutoff in real space
|
| 47 |
+
kspacecutoff = 30 # kspacecutoff - the cutoff in reciprocal space
|
| 48 |
+
|
| 49 |
+
print 'Ewald parameters:'
|
| 50 |
+
print 'alfa=%f, rcutoff=%f, kcutoff=%d' % (alphaEwald, rspacecutoff, kspacecutoff)
|
| 51 |
+
|
| 52 |
+
# P3M parameters
|
| 53 |
+
M = espressopp.Int3D(64, 64, 64)
|
| 54 |
+
P = 7
|
| 55 |
+
#alphaP3M = 1.112583061 # alpha - Ewald parameter
|
| 56 |
+
alphaP3M = 0.660557
|
| 57 |
+
|
| 58 |
+
print 'P3M parameters:'
|
| 59 |
+
print 'Mesh=', M,', charge assignment order=%d, alphaP3M=%lf' % ( P, alphaP3M)
|
| 60 |
+
|
| 61 |
+
# a skin for Verlet list
|
| 62 |
+
skin = 0.2
|
| 63 |
+
|
| 64 |
+
# Coulomb prefactor parameters
|
| 65 |
+
bjerrumlength = 1.0
|
| 66 |
+
temperature = 1.0
|
| 67 |
+
coulomb_prefactor = bjerrumlength * temperature
|
| 68 |
+
|
| 69 |
+
nodeGrid = espressopp.tools.decomp.nodeGrid(MPI.COMM_WORLD.size)
|
| 70 |
+
cellGrid = espressopp.tools.decomp.cellGrid(box, nodeGrid, rspacecutoff, skin)
|
| 71 |
+
|
| 72 |
+
print ''
|
| 73 |
+
print 'density = %.4f' % (rho)
|
| 74 |
+
print 'NodeGrid = %s' % (nodeGrid,)
|
| 75 |
+
print 'CellGrid = %s' % (cellGrid,)
|
| 76 |
+
print ''
|
| 77 |
+
|
| 78 |
+
'''
|
| 79 |
+
Below two systems for Ewald summation and PPPM methods will be created.
|
| 80 |
+
'''
|
| 81 |
+
|
| 82 |
+
#######################################################################################
|
| 83 |
+
# system for Ewald
|
| 84 |
+
#######################################################################################
|
| 85 |
+
|
| 86 |
+
systemEwald = espressopp.System()
|
| 87 |
+
systemEwald.rng = espressopp.esutil.RNG()
|
| 88 |
+
systemEwald.bc = espressopp.bc.OrthorhombicBC(systemEwald.rng, box)
|
| 89 |
+
systemEwald.skin = skin
|
| 90 |
+
systemEwald.storage = espressopp.storage.DomainDecomposition(systemEwald, nodeGrid, cellGrid)
|
| 91 |
+
|
| 92 |
+
#######################################################################################
|
| 93 |
+
# system for PPPM
|
| 94 |
+
#######################################################################################
|
| 95 |
+
|
| 96 |
+
systemPPPM = espressopp.System()
|
| 97 |
+
systemPPPM.rng = espressopp.esutil.RNG()
|
| 98 |
+
systemPPPM.bc = espressopp.bc.OrthorhombicBC(systemPPPM.rng, box)
|
| 99 |
+
systemPPPM.skin = skin
|
| 100 |
+
systemPPPM.storage = espressopp.storage.DomainDecomposition(systemPPPM, nodeGrid, cellGrid)
|
| 101 |
+
|
| 102 |
+
#######################################################################################
|
| 103 |
+
|
| 104 |
+
# adding particles
|
| 105 |
+
props = ['id', 'pos', 'type', 'q']
|
| 106 |
+
new_particles = []
|
| 107 |
+
countX = countY = countZ = 0
|
| 108 |
+
for i in range(0, num_particles):
|
| 109 |
+
|
| 110 |
+
# charge should be accordingly to NaCl crystall
|
| 111 |
+
charge = pow(-1, countX + countY + countZ)
|
| 112 |
+
part = [ i, Real3D(x[i], y[i], z[i]), 0, charge ]
|
| 113 |
+
new_particles.append(part)
|
| 114 |
+
|
| 115 |
+
countX += 1
|
| 116 |
+
if countX >= N:
|
| 117 |
+
countX = 0
|
| 118 |
+
countY += 1
|
| 119 |
+
if countY >= N:
|
| 120 |
+
countY = 0
|
| 121 |
+
countZ += 1
|
| 122 |
+
|
| 123 |
+
# adding particles to Ewald system
|
| 124 |
+
systemEwald.storage.addParticles(new_particles, *props)
|
| 125 |
+
systemEwald.storage.decompose()
|
| 126 |
+
|
| 127 |
+
# adding particles to PPPM system
|
| 128 |
+
systemPPPM.storage.addParticles(new_particles, *props)
|
| 129 |
+
systemPPPM.storage.decompose()
|
| 130 |
+
|
| 131 |
+
## potentials and interactions ##
|
| 132 |
+
|
| 133 |
+
# setting a Verlet list
|
| 134 |
+
vlEwald = espressopp.VerletList(systemEwald, rspacecutoff)
|
| 135 |
+
vlPPPM = espressopp.VerletList(systemPPPM, rspacecutoff)
|
| 136 |
+
|
| 137 |
+
# real space interaction for Ewald system
|
| 138 |
+
# R space part of electrostatic interaction
|
| 139 |
+
coulombR_potEwald = espressopp.interaction.CoulombRSpace(coulomb_prefactor, alphaEwald, rspacecutoff)
|
| 140 |
+
# creating an interaction based on the Verlet list
|
| 141 |
+
coulombR_intEwald = espressopp.interaction.VerletListCoulombRSpace(vlEwald)
|
| 142 |
+
# setting the potential for the interaction between particles of type 0 and 0
|
| 143 |
+
coulombR_intEwald.setPotential(type1=0, type2=0, potential = coulombR_potEwald)
|
| 144 |
+
# adding the interaction to the system
|
| 145 |
+
systemEwald.addInteraction(coulombR_intEwald)
|
| 146 |
+
|
| 147 |
+
# real space interaction for PPPM system
|
| 148 |
+
# R space part of electrostatic interaction
|
| 149 |
+
coulombR_potP3M = espressopp.interaction.CoulombRSpace(coulomb_prefactor, alphaP3M, rspacecutoff)
|
| 150 |
+
# creating an interaction based on the Verlet list
|
| 151 |
+
coulombR_intPPPM = espressopp.interaction.VerletListCoulombRSpace(vlPPPM)
|
| 152 |
+
# setting the potential for the interaction between particles of type 0 and 0
|
| 153 |
+
coulombR_intPPPM.setPotential(type1=0, type2=0, potential = coulombR_potP3M)
|
| 154 |
+
# adding the interaction to the system
|
| 155 |
+
systemPPPM.addInteraction(coulombR_intPPPM)
|
| 156 |
+
|
| 157 |
+
# K space part of electrostatic interaction
|
| 158 |
+
ewaldK_pot = espressopp.interaction.CoulombKSpaceEwald(systemEwald, coulomb_prefactor, alphaEwald, kspacecutoff)
|
| 159 |
+
# creating an interaction based on the Cell list for all particle interaction and potential in K space
|
| 160 |
+
ewaldK_int = espressopp.interaction.CellListCoulombKSpaceEwald(systemEwald.storage, ewaldK_pot)
|
| 161 |
+
# adding the interaction to the system
|
| 162 |
+
systemEwald.addInteraction(ewaldK_int)
|
| 163 |
+
|
| 164 |
+
# PPPM system
|
| 165 |
+
p3m_pot = espressopp.interaction.CoulombKSpaceP3M( systemPPPM, coulomb_prefactor, alphaP3M, M, P, rspacecutoff)
|
| 166 |
+
# creating the interaction based on the Cell list for all particle interaction and potential in K space
|
| 167 |
+
p3m_int = espressopp.interaction.CellListCoulombKSpaceP3M(systemPPPM.storage, p3m_pot)
|
| 168 |
+
# adding the interaction to the system
|
| 169 |
+
systemPPPM.addInteraction(p3m_int)
|
| 170 |
+
|
| 171 |
+
### Integrators for Ewald and PPPM
|
| 172 |
+
# creating the integrator which based on the Verlet algorithm
|
| 173 |
+
integratorEwald = espressopp.integrator.VelocityVerlet(systemEwald)
|
| 174 |
+
# seting the time step (it is not important here)
|
| 175 |
+
integratorEwald.dt = 0.0001
|
| 176 |
+
# nothing will be changed in system, just forces will be calculated ones
|
| 177 |
+
integratorEwald.run(0)
|
| 178 |
+
|
| 179 |
+
# creating the integrator which based on the Verlet algorithm
|
| 180 |
+
integratorPPPM = espressopp.integrator.VelocityVerlet(systemPPPM)
|
| 181 |
+
# seting the time step (it is not important here)
|
| 182 |
+
integratorPPPM.dt = 0.0001
|
| 183 |
+
# nothing will be changed in system, just forces will be calculated ones
|
| 184 |
+
integratorPPPM.run(0)
|
| 185 |
+
|
| 186 |
+
# printing the particle id and force difference (x,y,z) for first 6 particles
|
| 187 |
+
print ('\n Difference between forces calculated by Ewald summation and PPPM (first 6 particles)')
|
| 188 |
+
print ('%3s %20s %20s %20s\n' % ('id', 'dfx', 'dfy', 'dfz'))
|
| 189 |
+
|
| 190 |
+
#sock = espressopp.tools.vmd.connect(systemPPPM)
|
| 191 |
+
#espressopp.tools.vmd.imd_positions(systemPPPM, sock)
|
| 192 |
+
|
| 193 |
+
print_N = min(num_particles, 20)
|
| 194 |
+
|
| 195 |
+
for j in range(0, print_N):
|
| 196 |
+
print ( '%3d %3.17f %3.17f %3.17f' % (j, \
|
| 197 |
+
abs(systemEwald.storage.getParticle(j).f.x - systemPPPM.storage.getParticle(j).f.x), \
|
| 198 |
+
abs(systemEwald.storage.getParticle(j).f.y - systemPPPM.storage.getParticle(j).f.y), \
|
| 199 |
+
abs(systemEwald.storage.getParticle(j).f.z - systemPPPM.storage.getParticle(j).f.z)) )
|
| 200 |
+
|
| 201 |
+
print 'force:', systemPPPM.storage.getParticle(j).f, ' ', systemEwald.storage.getParticle(j).f
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
# calculating the R space part of electrostatic energy
|
| 205 |
+
energyEwaldR = coulombR_intEwald.computeEnergy()
|
| 206 |
+
# calculating the K space part of electrostatic energy
|
| 207 |
+
energyEwaldK = ewaldK_int.computeEnergy()
|
| 208 |
+
# total energy (Ewald summation)
|
| 209 |
+
enTotEwald = energyEwaldR + energyEwaldK
|
| 210 |
+
|
| 211 |
+
# calculating the R space part of electrostatic energy
|
| 212 |
+
energyPPPMR = coulombR_intPPPM.computeEnergy()
|
| 213 |
+
# calculating the K space part of electrostatic energy
|
| 214 |
+
energyPPPMK = p3m_int.computeEnergy()
|
| 215 |
+
# total energy (PPPM)
|
| 216 |
+
enTotPPPM = energyPPPMR + energyPPPMK
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
# printing the total energy and the difference
|
| 220 |
+
print 'Energy (Ewald summation): %5.16f Energy (PPPM): %5.16f\n' % (enTotEwald, enTotPPPM)
|
| 221 |
+
print 'The difference in energy (Ewald - PPPM): %5.16f\n' % (enTotEwald-enTotPPPM)
|
| 222 |
+
|
| 223 |
+
a = 2 * pow( Lx*Ly*Lz / num_particles , 1./3. )
|
| 224 |
+
madelung_NaCl = -1.747564594633182190636212035544397403481
|
| 225 |
+
print ("Madelung constant is: %14.10f\n" % (enTotEwald/num_particles * a))
|
| 226 |
+
print (" error: %e\n\n" % ( abs( abs( enTotPPPM/num_particles * a) - abs(madelung_NaCl))))
|
pool/shard007/Python/0069771_ledongli.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#coding: utf-8
|
| 2 |
+
|
| 3 |
+
#date: 刷微信步数
|
| 4 |
+
|
| 5 |
+
#usage: edit steps and ledongli's uid(u need to download this app) .That would be ok .Good luck. ^_^
|
| 6 |
+
|
| 7 |
+
import requests
|
| 8 |
+
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
|
| 13 |
+
import datetime
|
| 14 |
+
|
| 15 |
+
import time
|
| 16 |
+
|
| 17 |
+
def isnum(value):
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
|
| 21 |
+
temp = int(value)
|
| 22 |
+
|
| 23 |
+
except Exception, e:
|
| 24 |
+
|
| 25 |
+
return False
|
| 26 |
+
|
| 27 |
+
else:
|
| 28 |
+
|
| 29 |
+
return True
|
| 30 |
+
|
| 31 |
+
# like 2015-09-25 00:00:00 converts to unix time stamp
|
| 32 |
+
|
| 33 |
+
def formatDate():
|
| 34 |
+
|
| 35 |
+
nowtime = datetime.datetime.now()
|
| 36 |
+
|
| 37 |
+
date = time.strftime('%Y-%m-%d')
|
| 38 |
+
|
| 39 |
+
strtemp_date = date + ' 00:00:00'
|
| 40 |
+
|
| 41 |
+
ledongli_date = time.strptime(strtemp_date, '%Y-%m-%d %H:%M:%S')
|
| 42 |
+
|
| 43 |
+
finaldate = time.mktime(ledongli_date) # rusult is 1443456000.0(float type), but still need to format to 1443456000
|
| 44 |
+
|
| 45 |
+
finaldate = int(finaldate)
|
| 46 |
+
|
| 47 |
+
return finaldate
|
| 48 |
+
|
| 49 |
+
def main(steps, uid):
|
| 50 |
+
|
| 51 |
+
if not isnum(steps):
|
| 52 |
+
|
| 53 |
+
print 'param error. steps must be an integer.'
|
| 54 |
+
|
| 55 |
+
url = 'http://pl.api.ledongli.cn/xq/io.ashx'
|
| 56 |
+
|
| 57 |
+
fake_headers = {
|
| 58 |
+
|
| 59 |
+
'User-Agent' : 'le dong li/5.4 (iPhone; iOS 9.1; Scale/2.00)',
|
| 60 |
+
|
| 61 |
+
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8',
|
| 62 |
+
|
| 63 |
+
'Accept-Encoding': 'gzip'
|
| 64 |
+
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
keycontentjson = [
|
| 68 |
+
|
| 69 |
+
{
|
| 70 |
+
|
| 71 |
+
"date": formatDate(),
|
| 72 |
+
"calories": 0,
|
| 73 |
+
"activeValue": 108,
|
| 74 |
+
"steps": steps,
|
| 75 |
+
"pm2d5": 0,
|
| 76 |
+
"duration": 0,
|
| 77 |
+
"distance": 0,
|
| 78 |
+
"report": "[]"
|
| 79 |
+
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
]
|
| 83 |
+
|
| 84 |
+
# key is a str type
|
| 85 |
+
|
| 86 |
+
# key must be a json data convert to string
|
| 87 |
+
|
| 88 |
+
key = json.dumps(keycontentjson)
|
| 89 |
+
|
| 90 |
+
param = {
|
| 91 |
+
|
| 92 |
+
'action': 'profile',
|
| 93 |
+
|
| 94 |
+
'pc': '29e39ed274ea8e7a50f8a83abf1239faca843022',
|
| 95 |
+
|
| 96 |
+
'cmd': 'updatedaily',
|
| 97 |
+
|
| 98 |
+
'uid': uid,
|
| 99 |
+
|
| 100 |
+
'list': key,
|
| 101 |
+
'v' : '5.4%20ios',
|
| 102 |
+
'vc' : '540%20ios'
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
r = requests.post(url, data = param, headers = fake_headers)
|
| 106 |
+
|
| 107 |
+
print r.text
|
| 108 |
+
|
| 109 |
+
print '_kazakhsoft曰:装逼成功'
|
| 110 |
+
|
| 111 |
+
if __name__ == '__main__':
|
| 112 |
+
|
| 113 |
+
steps = 98801
|
| 114 |
+
|
| 115 |
+
uid = '39082958'
|
| 116 |
+
|
| 117 |
+
main(steps, uid)
|
pool/shard007/Python/0069776_demo.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from kivy.app import App
|
| 2 |
+
from kivy.clock import Clock
|
| 3 |
+
from kivy.graphics import Color, Ellipse, Line
|
| 4 |
+
from kivy.uix.widget import Widget
|
| 5 |
+
|
| 6 |
+
from control import Control
|
| 7 |
+
from simulation import Simulation
|
| 8 |
+
|
| 9 |
+
from control import PIXELS_PER_INCH
|
| 10 |
+
|
| 11 |
+
class PlateWidget(Widget):
|
| 12 |
+
def setup_simulation(self):
|
| 13 |
+
self.sim = Simulation(Control(), (0,0))
|
| 14 |
+
|
| 15 |
+
def render(self, dt):
|
| 16 |
+
with self.canvas:
|
| 17 |
+
self.sim.step()
|
| 18 |
+
self.canvas.clear()
|
| 19 |
+
Color(.5, .5, .5)
|
| 20 |
+
x = (self.sim.center_axis[0] * PIXELS_PER_INCH)+400-4
|
| 21 |
+
y = (self.sim.center_axis[1] * PIXELS_PER_INCH)+300-4
|
| 22 |
+
Ellipse(pos=(x,y), size=(9, 9))
|
| 23 |
+
|
| 24 |
+
Color(1, 1, 0)
|
| 25 |
+
for p in self.sim.tool_history:
|
| 26 |
+
x = ((p[0]*1) * PIXELS_PER_INCH)+400-1
|
| 27 |
+
y = ((p[1]*1) * PIXELS_PER_INCH)+300-1
|
| 28 |
+
Ellipse(pos=(x,y), size=(3, 3))
|
| 29 |
+
|
| 30 |
+
Color(1,0,0)
|
| 31 |
+
x = (self.sim.tool_position[0] * PIXELS_PER_INCH)+400-2
|
| 32 |
+
y = (self.sim.tool_position[1] * PIXELS_PER_INCH)+300-2
|
| 33 |
+
Ellipse(pos=(x,y), size=(5, 5))
|
| 34 |
+
|
| 35 |
+
class DemoApp(App):
|
| 36 |
+
def build(self):
|
| 37 |
+
w = PlateWidget()
|
| 38 |
+
w.setup_simulation()
|
| 39 |
+
|
| 40 |
+
# Schedule simulation step
|
| 41 |
+
event = Clock.schedule_interval(w.render, 1 / 60.)
|
| 42 |
+
|
| 43 |
+
return w
|
| 44 |
+
|
| 45 |
+
if __name__ == '__main__':
|
| 46 |
+
DemoApp().run()
|
pool/shard007/Python/0069777_navigation.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class Navigation(object):
|
| 2 |
+
def __init__(self):
|
| 3 |
+
self.children = []
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Element(object):
|
| 7 |
+
pass
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class Link(Element):
|
| 11 |
+
def __init__(self, route, text, icon=None, **args):
|
| 12 |
+
self.route = route
|
| 13 |
+
self.text = text
|
| 14 |
+
self.icon = icon
|
| 15 |
+
self.args = args
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class Menu(Element):
|
| 19 |
+
def __init__(self, text, children, icon=None, **args):
|
| 20 |
+
self.text = text
|
| 21 |
+
self.args = args
|
| 22 |
+
self.icon = icon
|
| 23 |
+
self.children = children
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Divider(Element):
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# Dictionary to hold navigation instances. Gets added to each request.
|
| 31 |
+
navigation = {
|
| 32 |
+
"navbar-left": Navigation(),
|
| 33 |
+
"acp": Navigation(),
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def configure(config):
|
| 38 |
+
config.add_request_method(lambda x: navigation, "navigation", reify=True)
|
| 39 |
+
|
| 40 |
+
def add_link(config, nav="navbar-left", **args):
|
| 41 |
+
if nav not in navigation:
|
| 42 |
+
navigation[nav] = Navigation()
|
| 43 |
+
navigation[nav].children.append(Link(**args))
|
| 44 |
+
config.add_directive("add_navigation_link", add_link, action_wrap=False)
|
| 45 |
+
|
| 46 |
+
def add_menu(config, nav="navbar-left", **args):
|
| 47 |
+
if nav not in navigation:
|
| 48 |
+
navigation[nav] = Navigation()
|
| 49 |
+
navigation[nav].children.append(Menu(**args))
|
| 50 |
+
config.add_directive("add_navigation_menu", add_menu, action_wrap=False)
|
| 51 |
+
|
| 52 |
+
config.add_navigation_link(nav="acp", icon="dashboard", route="admin.dashboard", text="Dashboard")
|
pool/shard007/Python/0069785_sensor_energymeter.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python2
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
sensor_power.py: Current and Voltage sensor driver
|
| 5 |
+
|
| 6 |
+
This sensor driver collects current and voltage measurements from external arduino board.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
__author__ = "Daniel Mazzer"
|
| 10 |
+
__copyright__ = "Copyright 2016, NORS project"
|
| 11 |
+
__credits__ = ""
|
| 12 |
+
__license__ = "MIT"
|
| 13 |
+
__maintainer__ = "Daniel Mazzer"
|
| 14 |
+
__email__ = "dmazzer@gmail.com"
|
| 15 |
+
|
| 16 |
+
import signal
|
| 17 |
+
import serial
|
| 18 |
+
|
| 19 |
+
from genericsensor.genericsensor import Nors_GenericSensor
|
| 20 |
+
|
| 21 |
+
from grovepi import *
|
| 22 |
+
|
| 23 |
+
from norsutils.logmsgs.logger import Logger
|
| 24 |
+
|
| 25 |
+
from serial_ports import serial_ports
|
| 26 |
+
|
| 27 |
+
logger = Logger('debug')
|
| 28 |
+
logger.log("SENSOR - Dual phase power meter", 'info')
|
| 29 |
+
|
| 30 |
+
class RealSensor(Nors_GenericSensor):
|
| 31 |
+
def __init__(self):
|
| 32 |
+
|
| 33 |
+
self.sensor_name = 'PWRMTR'
|
| 34 |
+
self.message = {}
|
| 35 |
+
|
| 36 |
+
if self.connect_to_energy_meter() == True:
|
| 37 |
+
super(RealSensor, self).__init__(
|
| 38 |
+
gs_name = self.sensor_name,
|
| 39 |
+
gs_id = 'bdeb5806-a9a2-11e6-a119-080027bc22fd',
|
| 40 |
+
gs_description = 'Dual phase power meter',
|
| 41 |
+
gs_interface = None,
|
| 42 |
+
gs_read_interval = 60)
|
| 43 |
+
else:
|
| 44 |
+
logger.log('Energy meter device was not found on serial ports', 'error')
|
| 45 |
+
raise SystemExit('Exiting')
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def SensorRead(self):
|
| 49 |
+
if self.ser.inWaiting() > 0 :
|
| 50 |
+
msg = self.ser.readline()
|
| 51 |
+
measures = self.msg_parse(msg)
|
| 52 |
+
# if measures is None:
|
| 53 |
+
# self.ser.flushInput()
|
| 54 |
+
# self.ser.flushOutput()
|
| 55 |
+
|
| 56 |
+
logger.log(str(measures), 'debug')
|
| 57 |
+
return measures
|
| 58 |
+
else:
|
| 59 |
+
return None
|
| 60 |
+
|
| 61 |
+
def SensorDataProcessing(self,sensor_data):
|
| 62 |
+
return sensor_data
|
| 63 |
+
|
| 64 |
+
def connect_to_energy_meter(self):
|
| 65 |
+
logger.log('Searching serial ports','info')
|
| 66 |
+
ports = serial_ports()
|
| 67 |
+
for port in ports:
|
| 68 |
+
try:
|
| 69 |
+
logger.log('Trying ' + str(port),'info')
|
| 70 |
+
self.ser = serial.Serial(port, 115200, timeout=10)
|
| 71 |
+
retry = 100
|
| 72 |
+
while retry > 0:
|
| 73 |
+
logger.log('Countdown ' + str(retry),'info')
|
| 74 |
+
self.ser.flushInput()
|
| 75 |
+
self.ser.flushOutput()
|
| 76 |
+
self.ser.write('#')
|
| 77 |
+
# time.sleep(2)
|
| 78 |
+
check_em = self.ser.read()
|
| 79 |
+
if check_em == '!':
|
| 80 |
+
logger.log('Success on port ' + str(port),'info')
|
| 81 |
+
return True
|
| 82 |
+
retry = retry-1
|
| 83 |
+
# time.sleep(2)
|
| 84 |
+
|
| 85 |
+
except (serial.SerialException) as e:
|
| 86 |
+
return False
|
| 87 |
+
|
| 88 |
+
return False
|
| 89 |
+
|
| 90 |
+
def msg_parse(self, msg):
|
| 91 |
+
msg_p = msg.split()
|
| 92 |
+
|
| 93 |
+
# checking message parsing result using list size
|
| 94 |
+
if len(msg_p) != 6:
|
| 95 |
+
return None
|
| 96 |
+
|
| 97 |
+
measure = {}
|
| 98 |
+
# for python 3 use:
|
| 99 |
+
# measure['channel'] = int(str(msg_p[0]).replace("b'@", "").replace("'", ""))
|
| 100 |
+
channel = int(str(msg_p[0]).replace("@", ""))
|
| 101 |
+
if (channel != 1) and (channel != 2):
|
| 102 |
+
return None
|
| 103 |
+
|
| 104 |
+
measure['channel'] = channel
|
| 105 |
+
measure['real_power'] = float(msg_p[1])
|
| 106 |
+
measure['apparent_power'] = float(msg_p[2])
|
| 107 |
+
measure['Vrms'] = float(msg_p[3])
|
| 108 |
+
measure['Irms'] = float(msg_p[4])
|
| 109 |
+
measure['power_factor'] = float(msg_p[5])
|
| 110 |
+
# return {str(channel): measure}
|
| 111 |
+
|
| 112 |
+
return self.msg_agregate(measure)
|
| 113 |
+
|
| 114 |
+
def msg_agregate(self, msg):
|
| 115 |
+
# print(msg)
|
| 116 |
+
if msg['channel'] == 1:
|
| 117 |
+
self.message = {'ch1': msg}
|
| 118 |
+
# print('canal1')
|
| 119 |
+
return None
|
| 120 |
+
if msg['channel'] == 2:
|
| 121 |
+
self.message['ch2'] = msg
|
| 122 |
+
# print('canal2')
|
| 123 |
+
return self.message
|
| 124 |
+
|
| 125 |
+
if __name__ == '__main__':
|
| 126 |
+
sensor = RealSensor()
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def do_exit(sig, stack):
|
| 130 |
+
raise SystemExit('Exiting')
|
| 131 |
+
|
| 132 |
+
signal.signal(signal.SIGINT, do_exit)
|
| 133 |
+
signal.signal(signal.SIGUSR1, do_exit)
|
| 134 |
+
|
| 135 |
+
signal.pause()
|
| 136 |
+
|
| 137 |
+
|
pool/shard007/Python/0069789_gather_domain_token_stats.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2014 Google Inc. All Rights Reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# 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, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
"""Gather token information for a whole domain and show some stats.
|
| 18 |
+
|
| 19 |
+
This may be a large task given many domains > 20k users. Therefore,
|
| 20 |
+
this script requires some form of perisistence. Likely, this script
|
| 21 |
+
will get interrupted by quota constraints and need to be resumed
|
| 22 |
+
so progress should be tracked.
|
| 23 |
+
|
| 24 |
+
Overall, enough data should be collected to show 3 primary stats:
|
| 25 |
+
1. List the domains the are most frequently issued tokens.
|
| 26 |
+
2. List the users most frequently authorizing token access.
|
| 27 |
+
3. Show a map of users to client_ids (to allow for revocation).
|
| 28 |
+
|
| 29 |
+
Tool to show usage of Admin SDK Directory APIs.
|
| 30 |
+
|
| 31 |
+
APIs Used:
|
| 32 |
+
Admin SDK Directory API: user management
|
| 33 |
+
Experimental Google Apps 3-legged OAuth Token Management API.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
import sys
|
| 37 |
+
|
| 38 |
+
# setup_path required to allow imports from component dirs (e.g. utils)
|
| 39 |
+
# and lib (where the OAuth and Google API Python Client modules reside).
|
| 40 |
+
import setup_path # pylint: disable=unused-import,g-bad-import-order
|
| 41 |
+
|
| 42 |
+
from admin_sdk_directory_api import tokens_api
|
| 43 |
+
from utils import admin_api_tool_errors
|
| 44 |
+
from utils import auth_helper
|
| 45 |
+
from utils import common_flags
|
| 46 |
+
from utils import log_utils
|
| 47 |
+
from utils import token_report_utils
|
| 48 |
+
from utils import user_iterator
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def AddFlags(arg_parser):
|
| 52 |
+
"""Handle command line flags unique to this script.
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
arg_parser: object from argparse.ArgumentParser() to accumulate flags.
|
| 56 |
+
"""
|
| 57 |
+
common_flags.DefineAppsDomainFlagWithDefault(arg_parser)
|
| 58 |
+
common_flags.DefineForceFlagWithDefaultFalse(arg_parser)
|
| 59 |
+
common_flags.DefineVerboseFlagWithDefaultFalse(arg_parser)
|
| 60 |
+
|
| 61 |
+
arg_parser.add_argument('--first_n', type=int, default=0,
|
| 62 |
+
help=('Gather tokens for the first n users in the '
|
| 63 |
+
'domain.'))
|
| 64 |
+
arg_parser.add_argument('--resume', '-r', action='store_true', default=False,
|
| 65 |
+
help='Resume an interrupted gather command.')
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def main(argv):
|
| 69 |
+
"""A script to test Apps Security APIs: summarizing oauth2 tokens."""
|
| 70 |
+
flags = common_flags.ParseFlags(argv,
|
| 71 |
+
'Gather token status for entire domain.',
|
| 72 |
+
AddFlags)
|
| 73 |
+
# Tracks stats for each domain-scope:
|
| 74 |
+
# {
|
| 75 |
+
# (scope1, domain1): [user1, user2, ...],
|
| 76 |
+
# (scope2, domain1): [user1, user3, ...],
|
| 77 |
+
# (scope1, domain2): [user4, user5, ...],
|
| 78 |
+
# (scope3, domain3): [user6, user7, ...],
|
| 79 |
+
# }
|
| 80 |
+
# Issue domains (e.g.twitter.com) are the domains to whom the token was
|
| 81 |
+
# issued and scopes reflect the data accessed.
|
| 82 |
+
#
|
| 83 |
+
# This is simple to minimize memory footprint. Later processing of this data
|
| 84 |
+
# structure will report most frequent: issue domains, scopes and users.
|
| 85 |
+
token_stats = {}
|
| 86 |
+
|
| 87 |
+
if not flags.resume:
|
| 88 |
+
# Early check if file exists and not --force.
|
| 89 |
+
filename_path = token_report_utils.WriteTokensIssuedJson(token_stats,
|
| 90 |
+
flags.force)
|
| 91 |
+
else:
|
| 92 |
+
token_stats = token_report_utils.GetTokenStats()
|
| 93 |
+
|
| 94 |
+
http = auth_helper.GetAuthorizedHttp(flags)
|
| 95 |
+
apps_security_api = tokens_api.TokensApiWrapper(http)
|
| 96 |
+
|
| 97 |
+
iterator_purpose = 'collection' # Used to tag iterator progress data.
|
| 98 |
+
|
| 99 |
+
# The user list holds a tuple for each user of: email, id, full_name
|
| 100 |
+
# (e.g. 'larry', '112351558298938768732', 'Larry Summon').
|
| 101 |
+
print 'Scanning domain users for %s' % iterator_purpose
|
| 102 |
+
for user in user_iterator.StartUserIterator(http, iterator_purpose, flags):
|
| 103 |
+
user_email, user_id, checkpoint = user
|
| 104 |
+
try:
|
| 105 |
+
token_list = apps_security_api.GetTokensForUser(user_id)
|
| 106 |
+
except admin_api_tool_errors.AdminAPIToolTokenRequestError as e:
|
| 107 |
+
# This suggests an unexpected response from the apps security api.
|
| 108 |
+
# As much detail as possible is provided by the raiser.
|
| 109 |
+
sys.stdout.write('%80s\r' % '') # Clear the previous entry.
|
| 110 |
+
sys.stdout.flush()
|
| 111 |
+
log_utils.LogError('Unable to get user tokens.', e)
|
| 112 |
+
sys.exit(1)
|
| 113 |
+
|
| 114 |
+
for token in token_list:
|
| 115 |
+
# Save lists of users with tokens.
|
| 116 |
+
for scope in token['scopes']:
|
| 117 |
+
stat_key = token_report_utils.PackStatKey(token['clientId'], scope)
|
| 118 |
+
token_stats.setdefault(stat_key, [])
|
| 119 |
+
token_stats[stat_key].append(user_email)
|
| 120 |
+
|
| 121 |
+
if checkpoint:
|
| 122 |
+
# Save progress every n users.
|
| 123 |
+
filename_path = token_report_utils.WriteTokensIssuedJson(
|
| 124 |
+
token_stats, overwrite_ok=True)
|
| 125 |
+
print 'Token report written: %s' % filename_path
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
if __name__ == '__main__':
|
| 129 |
+
main(sys.argv[1:])
|
pool/shard007/Python/0069790_p240_search_a_2d_matrix_ii.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding: utf-8
|
| 2 |
+
|
| 3 |
+
# author: Fei Gao
|
| 4 |
+
#
|
| 5 |
+
# Search A 2d Matrix Ii
|
| 6 |
+
|
| 7 |
+
# Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
|
| 8 |
+
# Integers in each row are sorted in ascending from left to right.
|
| 9 |
+
# Integers in each column are sorted in ascending from top to bottom.
|
| 10 |
+
# For example,
|
| 11 |
+
# Consider the following matrix:
|
| 12 |
+
# [
|
| 13 |
+
# [1, 4, 7, 11, 15],
|
| 14 |
+
# [2, 5, 8, 12, 19],
|
| 15 |
+
# [3, 6, 9, 16, 22],
|
| 16 |
+
# [10, 13, 14, 17, 24],
|
| 17 |
+
# [18, 21, 23, 26, 30]
|
| 18 |
+
# ]
|
| 19 |
+
# Given target = 5, return true.
|
| 20 |
+
# Given target = 20, return false.
|
| 21 |
+
# Subscribe to see which companies asked this question
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Solution(object):
|
| 25 |
+
def searchMatrix(self, matrix, target):
|
| 26 |
+
"""
|
| 27 |
+
:type matrix: List[List[int]]
|
| 28 |
+
:type target: int
|
| 29 |
+
:rtype: bool
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def search(row1, row2, col1, col2):
|
| 33 |
+
"""Search target in sub matrix[row1:row2][col1:col2]"""
|
| 34 |
+
# zero elements
|
| 35 |
+
if row1 >= row2 or col1 >= col2:
|
| 36 |
+
return False
|
| 37 |
+
if matrix[row1][col1] == target:
|
| 38 |
+
return True
|
| 39 |
+
# target less than up-left corner
|
| 40 |
+
if target < matrix[row1][col1]:
|
| 41 |
+
return False
|
| 42 |
+
# target greater than low-right corner
|
| 43 |
+
if target > matrix[row2 - 1][col2 - 1]:
|
| 44 |
+
return False
|
| 45 |
+
row3 = (row1 + row2 + 1) // 2
|
| 46 |
+
col3 = (col1 + col2 + 1) // 2
|
| 47 |
+
# print(row1, row3, row2, col1, col3, col2)
|
| 48 |
+
result = (search(row1, row3, col1, col3)
|
| 49 |
+
or search(row1, row3, col3, col2)
|
| 50 |
+
or search(row3, row2, col1, col3)
|
| 51 |
+
or search(row3, row2, col3, col2))
|
| 52 |
+
# print(row1, row2, col1, col2, result)
|
| 53 |
+
return result
|
| 54 |
+
|
| 55 |
+
return search(0, len(matrix), 0, len(matrix[0]))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def main():
|
| 59 |
+
solver = Solution()
|
| 60 |
+
tests = [
|
| 61 |
+
([
|
| 62 |
+
[1, 4, 7, 11, 15],
|
| 63 |
+
[2, 5, 8, 12, 19],
|
| 64 |
+
[3, 6, 9, 16, 22],
|
| 65 |
+
[10, 13, 14, 17, 24],
|
| 66 |
+
[18, 21, 23, 26, 30]
|
| 67 |
+
], 5),
|
| 68 |
+
([
|
| 69 |
+
[1, 4, 7, 11, 15],
|
| 70 |
+
[2, 5, 8, 12, 19],
|
| 71 |
+
[3, 6, 9, 16, 22],
|
| 72 |
+
[10, 13, 14, 17, 24],
|
| 73 |
+
[18, 21, 23, 26, 30]
|
| 74 |
+
], 20)
|
| 75 |
+
]
|
| 76 |
+
for test in tests:
|
| 77 |
+
print(test)
|
| 78 |
+
print(' ->')
|
| 79 |
+
result = solver.searchMatrix(*test)
|
| 80 |
+
print(result)
|
| 81 |
+
print('~' * 10)
|
| 82 |
+
pass
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
if __name__ == '__main__':
|
| 86 |
+
main()
|
| 87 |
+
pass
|
pool/shard007/Python/0069793_test_http_spider.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# coding=utf-8
|
| 3 |
+
|
| 4 |
+
import unittest
|
| 5 |
+
|
| 6 |
+
import httpretty
|
| 7 |
+
|
| 8 |
+
from pycon2015.http_spider import get_url_data
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class HttpSpiderTestCase(unittest.TestCase):
|
| 12 |
+
|
| 13 |
+
@unittest.skip('Fuck GFW')
|
| 14 |
+
def test_get_url_data_impossible_in_china(self):
|
| 15 |
+
url_data = get_url_data('http://www.google.com/')
|
| 16 |
+
|
| 17 |
+
self.assertEqual(url_data['status_code'], 200)
|
| 18 |
+
self.assertEqual(url_data['encoding'], 'utf-8')
|
| 19 |
+
|
| 20 |
+
@httpretty.activate
|
| 21 |
+
def test_get_url_data(self):
|
| 22 |
+
url = 'http://www.google.com/'
|
| 23 |
+
httpretty.register_uri(
|
| 24 |
+
httpretty.GET, url, body='Fake Google', status=200
|
| 25 |
+
)
|
| 26 |
+
url_data = get_url_data(url)
|
| 27 |
+
|
| 28 |
+
self.assertEqual(url_data['status_code'], 200)
|
| 29 |
+
self.assertEqual(url_data['encoding'], 'utf-8')
|
pool/shard007/Python/0069798_test_ftp.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import io
|
| 19 |
+
import unittest
|
| 20 |
+
from unittest import mock
|
| 21 |
+
|
| 22 |
+
from airflow.providers.ftp.hooks import ftp as fh
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class TestFTPHook(unittest.TestCase):
|
| 26 |
+
def setUp(self):
|
| 27 |
+
super().setUp()
|
| 28 |
+
self.path = '/some/path'
|
| 29 |
+
self.conn_mock = mock.MagicMock(name='conn')
|
| 30 |
+
self.get_conn_orig = fh.FTPHook.get_conn
|
| 31 |
+
|
| 32 |
+
def _get_conn_mock(hook):
|
| 33 |
+
hook.conn = self.conn_mock
|
| 34 |
+
return self.conn_mock
|
| 35 |
+
|
| 36 |
+
fh.FTPHook.get_conn = _get_conn_mock
|
| 37 |
+
|
| 38 |
+
def tearDown(self):
|
| 39 |
+
fh.FTPHook.get_conn = self.get_conn_orig
|
| 40 |
+
super().tearDown()
|
| 41 |
+
|
| 42 |
+
def test_close_conn(self):
|
| 43 |
+
ftp_hook = fh.FTPHook()
|
| 44 |
+
ftp_hook.get_conn()
|
| 45 |
+
ftp_hook.close_conn()
|
| 46 |
+
|
| 47 |
+
self.conn_mock.quit.assert_called_once_with()
|
| 48 |
+
|
| 49 |
+
def test_list_directory(self):
|
| 50 |
+
with fh.FTPHook() as ftp_hook:
|
| 51 |
+
ftp_hook.list_directory(self.path)
|
| 52 |
+
|
| 53 |
+
self.conn_mock.cwd.assert_called_once_with(self.path)
|
| 54 |
+
self.conn_mock.nlst.assert_called_once_with()
|
| 55 |
+
|
| 56 |
+
def test_create_directory(self):
|
| 57 |
+
with fh.FTPHook() as ftp_hook:
|
| 58 |
+
ftp_hook.create_directory(self.path)
|
| 59 |
+
|
| 60 |
+
self.conn_mock.mkd.assert_called_once_with(self.path)
|
| 61 |
+
|
| 62 |
+
def test_delete_directory(self):
|
| 63 |
+
with fh.FTPHook() as ftp_hook:
|
| 64 |
+
ftp_hook.delete_directory(self.path)
|
| 65 |
+
|
| 66 |
+
self.conn_mock.rmd.assert_called_once_with(self.path)
|
| 67 |
+
|
| 68 |
+
def test_delete_file(self):
|
| 69 |
+
with fh.FTPHook() as ftp_hook:
|
| 70 |
+
ftp_hook.delete_file(self.path)
|
| 71 |
+
|
| 72 |
+
self.conn_mock.delete.assert_called_once_with(self.path)
|
| 73 |
+
|
| 74 |
+
def test_rename(self):
|
| 75 |
+
from_path = '/path/from'
|
| 76 |
+
to_path = '/path/to'
|
| 77 |
+
with fh.FTPHook() as ftp_hook:
|
| 78 |
+
ftp_hook.rename(from_path, to_path)
|
| 79 |
+
|
| 80 |
+
self.conn_mock.rename.assert_called_once_with(from_path, to_path)
|
| 81 |
+
self.conn_mock.quit.assert_called_once_with()
|
| 82 |
+
|
| 83 |
+
def test_mod_time(self):
|
| 84 |
+
self.conn_mock.sendcmd.return_value = '213 20170428010138'
|
| 85 |
+
|
| 86 |
+
path = '/path/file'
|
| 87 |
+
with fh.FTPHook() as ftp_hook:
|
| 88 |
+
ftp_hook.get_mod_time(path)
|
| 89 |
+
|
| 90 |
+
self.conn_mock.sendcmd.assert_called_once_with('MDTM ' + path)
|
| 91 |
+
|
| 92 |
+
def test_mod_time_micro(self):
|
| 93 |
+
self.conn_mock.sendcmd.return_value = '213 20170428010138.003'
|
| 94 |
+
|
| 95 |
+
path = '/path/file'
|
| 96 |
+
with fh.FTPHook() as ftp_hook:
|
| 97 |
+
ftp_hook.get_mod_time(path)
|
| 98 |
+
|
| 99 |
+
self.conn_mock.sendcmd.assert_called_once_with('MDTM ' + path)
|
| 100 |
+
|
| 101 |
+
def test_get_size(self):
|
| 102 |
+
self.conn_mock.size.return_value = 1942
|
| 103 |
+
|
| 104 |
+
path = '/path/file'
|
| 105 |
+
with fh.FTPHook() as ftp_hook:
|
| 106 |
+
ftp_hook.get_size(path)
|
| 107 |
+
|
| 108 |
+
self.conn_mock.size.assert_called_once_with(path)
|
| 109 |
+
|
| 110 |
+
def test_retrieve_file(self):
|
| 111 |
+
_buffer = io.StringIO('buffer')
|
| 112 |
+
with fh.FTPHook() as ftp_hook:
|
| 113 |
+
ftp_hook.retrieve_file(self.path, _buffer)
|
| 114 |
+
self.conn_mock.retrbinary.assert_called_once_with('RETR path', _buffer.write)
|
| 115 |
+
|
| 116 |
+
def test_retrieve_file_with_callback(self):
|
| 117 |
+
func = mock.Mock()
|
| 118 |
+
_buffer = io.StringIO('buffer')
|
| 119 |
+
with fh.FTPHook() as ftp_hook:
|
| 120 |
+
ftp_hook.retrieve_file(self.path, _buffer, callback=func)
|
| 121 |
+
self.conn_mock.retrbinary.assert_called_once_with('RETR path', func)
|
| 122 |
+
|
| 123 |
+
def test_connection_success(self):
|
| 124 |
+
with fh.FTPHook() as ftp_hook:
|
| 125 |
+
status, msg = ftp_hook.test_connection()
|
| 126 |
+
assert status is True
|
| 127 |
+
assert msg == 'Connection successfully tested'
|
| 128 |
+
|
| 129 |
+
def test_connection_failure(self):
|
| 130 |
+
self.conn_mock = mock.MagicMock(name='conn_mock', side_effect=Exception('Test'))
|
| 131 |
+
fh.FTPHook.get_conn = self.conn_mock
|
| 132 |
+
with fh.FTPHook() as ftp_hook:
|
| 133 |
+
status, msg = ftp_hook.test_connection()
|
| 134 |
+
assert status is False
|
| 135 |
+
assert msg == 'Test'
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class TestIntegrationFTPHook(unittest.TestCase):
|
| 139 |
+
def setUp(self):
|
| 140 |
+
super().setUp()
|
| 141 |
+
from airflow.models import Connection
|
| 142 |
+
from airflow.utils import db
|
| 143 |
+
|
| 144 |
+
db.merge_conn(
|
| 145 |
+
Connection(conn_id='ftp_passive', conn_type='ftp', host='localhost', extra='{"passive": true}')
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
db.merge_conn(
|
| 149 |
+
Connection(conn_id='ftp_active', conn_type='ftp', host='localhost', extra='{"passive": false}')
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
def _test_mode(self, hook_type, connection_id, expected_mode):
|
| 153 |
+
hook = hook_type(connection_id)
|
| 154 |
+
conn = hook.get_conn()
|
| 155 |
+
conn.set_pasv.assert_called_once_with(expected_mode)
|
| 156 |
+
|
| 157 |
+
@mock.patch("ftplib.FTP")
|
| 158 |
+
def test_ftp_passive_mode(self, mock_ftp):
|
| 159 |
+
from airflow.providers.ftp.hooks.ftp import FTPHook
|
| 160 |
+
|
| 161 |
+
self._test_mode(FTPHook, "ftp_passive", True)
|
| 162 |
+
|
| 163 |
+
@mock.patch("ftplib.FTP")
|
| 164 |
+
def test_ftp_active_mode(self, mock_ftp):
|
| 165 |
+
from airflow.providers.ftp.hooks.ftp import FTPHook
|
| 166 |
+
|
| 167 |
+
self._test_mode(FTPHook, "ftp_active", False)
|
| 168 |
+
|
| 169 |
+
@mock.patch("ftplib.FTP_TLS")
|
| 170 |
+
def test_ftps_passive_mode(self, mock_ftp):
|
| 171 |
+
from airflow.providers.ftp.hooks.ftp import FTPSHook
|
| 172 |
+
|
| 173 |
+
self._test_mode(FTPSHook, "ftp_passive", True)
|
| 174 |
+
|
| 175 |
+
@mock.patch("ftplib.FTP_TLS")
|
| 176 |
+
def test_ftps_active_mode(self, mock_ftp):
|
| 177 |
+
from airflow.providers.ftp.hooks.ftp import FTPSHook
|
| 178 |
+
|
| 179 |
+
self._test_mode(FTPSHook, "ftp_active", False)
|
pool/shard007/Python/0069799_bin2obj.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from lar import *
|
| 2 |
+
from scipy import *
|
| 3 |
+
import json
|
| 4 |
+
import scipy
|
| 5 |
+
import numpy as np
|
| 6 |
+
import time as tm
|
| 7 |
+
import gc
|
| 8 |
+
import struct
|
| 9 |
+
|
| 10 |
+
# ------------------------------------------------------------
|
| 11 |
+
# Logging & Timer
|
| 12 |
+
# ------------------------------------------------------------
|
| 13 |
+
|
| 14 |
+
logging_level = 2;
|
| 15 |
+
|
| 16 |
+
# 0 = no_logging
|
| 17 |
+
# 1 = few details
|
| 18 |
+
# 2 = many details
|
| 19 |
+
# 3 = many many details
|
| 20 |
+
|
| 21 |
+
def log(n, l):
|
| 22 |
+
|
| 23 |
+
if __name__=="__main__" and n <= logging_level:
|
| 24 |
+
for s in l:
|
| 25 |
+
print "Log:", s;
|
| 26 |
+
|
| 27 |
+
timer = 1;
|
| 28 |
+
|
| 29 |
+
timer_last = tm.time()
|
| 30 |
+
|
| 31 |
+
def timer_start(s):
|
| 32 |
+
|
| 33 |
+
global timer_last;
|
| 34 |
+
if __name__=="__main__" and timer == 1:
|
| 35 |
+
print "Timer start:", s;
|
| 36 |
+
timer_last = tm.time();
|
| 37 |
+
|
| 38 |
+
def timer_stop():
|
| 39 |
+
|
| 40 |
+
global timer_last;
|
| 41 |
+
if __name__=="__main__" and timer == 1:
|
| 42 |
+
print "Timer stop :", tm.time() - timer_last;
|
| 43 |
+
|
| 44 |
+
# ------------------------------------------------------------
|
| 45 |
+
# Configuration parameters
|
| 46 |
+
# ------------------------------------------------------------
|
| 47 |
+
|
| 48 |
+
nx = ny = nz = 64
|
| 49 |
+
log(1, ["nx, ny, nz = " + str(nx) + "," + str(ny) + "," + str(nz)]);
|
| 50 |
+
|
| 51 |
+
chunksize = nx * ny + nx * nz + ny * nz + 3 * nx * ny * nz
|
| 52 |
+
log(1, ["chunksize = " + str(chunksize)]);
|
| 53 |
+
# chunksize = 798720 (nx=ny=nz=64)
|
| 54 |
+
|
| 55 |
+
MAX_CHUNKS = 64 #1024
|
| 56 |
+
log(1, ["MAX_CHUNKS = " + str(MAX_CHUNKS)]);
|
| 57 |
+
|
| 58 |
+
# ------------------------------------------------------------
|
| 59 |
+
|
| 60 |
+
def ind(x,y,z): return x + (nx+1) * (y + (ny+1) * (z))
|
| 61 |
+
|
| 62 |
+
def invertIndex(nx,ny,nz):
|
| 63 |
+
nx,ny,nz = nx+1,ny+1,nz+1
|
| 64 |
+
def invertIndex0(offset):
|
| 65 |
+
a0, b0 = offset / nx, offset % nx
|
| 66 |
+
a1, b1 = a0 / ny, a0 % ny
|
| 67 |
+
a2, b2 = a1 / nz, a1 % nz
|
| 68 |
+
return b0,b1,b2
|
| 69 |
+
return invertIndex0
|
| 70 |
+
|
| 71 |
+
# Construction of vertex coordinates (nx * ny * nz)
|
| 72 |
+
# ------------------------------------------------------------
|
| 73 |
+
|
| 74 |
+
timer_start("V");
|
| 75 |
+
|
| 76 |
+
V = [[x,y,z] for z in range(nz+1) for y in range(ny+1) for x in range(nx+1) ]
|
| 77 |
+
|
| 78 |
+
timer_stop();
|
| 79 |
+
log(3, ["V = " + str(V)]);
|
| 80 |
+
|
| 81 |
+
# Construction of FV relation (nx * ny * nz)
|
| 82 |
+
# ------------------------------------------------------------
|
| 83 |
+
|
| 84 |
+
FV = []
|
| 85 |
+
|
| 86 |
+
timer_start("v2coords");
|
| 87 |
+
|
| 88 |
+
v2coords = invertIndex(nx,ny,nz)
|
| 89 |
+
|
| 90 |
+
timer_stop();
|
| 91 |
+
|
| 92 |
+
timer_start("h");
|
| 93 |
+
|
| 94 |
+
for h in range(len(V)):
|
| 95 |
+
x,y,z = v2coords(h)
|
| 96 |
+
if (x < nx) and (y < ny): FV.append([h,ind(x+1,y,z),ind(x,y+1,z),ind(x+1,y+1,z)])
|
| 97 |
+
if (x < nx) and (z < nz): FV.append([h,ind(x+1,y,z),ind(x,y,z+1),ind(x+1,y,z+1)])
|
| 98 |
+
if (y < ny) and (z < nz): FV.append([h,ind(x,y+1,z),ind(x,y,z+1),ind(x,y+1,z+1)])
|
| 99 |
+
|
| 100 |
+
timer_stop();
|
| 101 |
+
log(3, ["FV = " + str(FV)]);
|
| 102 |
+
|
| 103 |
+
# ------------------------------------------------------------
|
| 104 |
+
|
| 105 |
+
out = []
|
| 106 |
+
file = open("output.bin", "rb")
|
| 107 |
+
|
| 108 |
+
fileVertex = open("outputVtx.obj", "w")
|
| 109 |
+
fileFaces = open("outputFaces.obj", "w")
|
| 110 |
+
|
| 111 |
+
vertex_count = 1
|
| 112 |
+
old_vertex_count = vertex_count
|
| 113 |
+
count = 0
|
| 114 |
+
|
| 115 |
+
for i in range(MAX_CHUNKS):
|
| 116 |
+
|
| 117 |
+
count += 1
|
| 118 |
+
|
| 119 |
+
zStart = struct.unpack('>I', file.read(4))[0]
|
| 120 |
+
xStart = struct.unpack('>I', file.read(4))[0]
|
| 121 |
+
yStart = struct.unpack('>I', file.read(4))[0]
|
| 122 |
+
|
| 123 |
+
log(1, ["zStart, xStart, yStart = " + str(zStart) + "," + str(xStart) + "," + str(yStart)]);
|
| 124 |
+
# zStart, xStart, yStart = LISTA_OFFSET[i].astype(float64)
|
| 125 |
+
|
| 126 |
+
LISTA_VETTORI2 = np.zeros(chunksize,dtype=int32);
|
| 127 |
+
|
| 128 |
+
temp = file.read(chunksize);
|
| 129 |
+
|
| 130 |
+
timer_start("LISTA_VETTORI2 " + str(i));
|
| 131 |
+
i = 0
|
| 132 |
+
while (i < chunksize):
|
| 133 |
+
if (temp[i] == '\x01'):
|
| 134 |
+
LISTA_VETTORI2[i] = 1;
|
| 135 |
+
i = i + 1;
|
| 136 |
+
timer_stop();
|
| 137 |
+
|
| 138 |
+
timer_start("objectBoundaryChain ");
|
| 139 |
+
l = len(LISTA_VETTORI2)
|
| 140 |
+
objectBoundaryChain = scipy.sparse.csr_matrix(LISTA_VETTORI2.reshape((l,1)))
|
| 141 |
+
timer_stop();
|
| 142 |
+
|
| 143 |
+
timer_start("csrChainToCellList " + str(i));
|
| 144 |
+
b2cells = csrChainToCellList(objectBoundaryChain)
|
| 145 |
+
timer_stop();
|
| 146 |
+
|
| 147 |
+
timer_start("MKPOLS " + str(i));
|
| 148 |
+
|
| 149 |
+
for f in b2cells:
|
| 150 |
+
old_vertex_count = vertex_count
|
| 151 |
+
|
| 152 |
+
for vtx in FV[f]:
|
| 153 |
+
fileVertex.write("v ")
|
| 154 |
+
fileVertex.write(str(V[vtx][0] + xStart))
|
| 155 |
+
fileVertex.write(" ")
|
| 156 |
+
fileVertex.write(str(V[vtx][1] + yStart))
|
| 157 |
+
fileVertex.write(" ")
|
| 158 |
+
fileVertex.write(str(V[vtx][2] + zStart))
|
| 159 |
+
fileVertex.write("\n")
|
| 160 |
+
vertex_count = vertex_count + 1
|
| 161 |
+
|
| 162 |
+
fileFaces.write("f ")
|
| 163 |
+
fileFaces.write(str(old_vertex_count + 0))
|
| 164 |
+
fileFaces.write(" ")
|
| 165 |
+
fileFaces.write(str(old_vertex_count + 1))
|
| 166 |
+
fileFaces.write(" ")
|
| 167 |
+
fileFaces.write(str(old_vertex_count + 3))
|
| 168 |
+
fileFaces.write("\n")
|
| 169 |
+
|
| 170 |
+
fileFaces.write("f ")
|
| 171 |
+
fileFaces.write(str(old_vertex_count + 0))
|
| 172 |
+
fileFaces.write(" ")
|
| 173 |
+
fileFaces.write(str(old_vertex_count + 3))
|
| 174 |
+
fileFaces.write(" ")
|
| 175 |
+
fileFaces.write(str(old_vertex_count + 2))
|
| 176 |
+
fileFaces.write("\n")
|
| 177 |
+
|
| 178 |
+
timer_stop();
|
| 179 |
+
|
| 180 |
+
if count == MAX_CHUNKS:
|
| 181 |
+
timer_start("VIEW(STRUCT(out))");
|
| 182 |
+
timer_stop();
|
| 183 |
+
|
| 184 |
+
file.close()
|
| 185 |
+
fileVertex.close()
|
| 186 |
+
fileFaces.close()
|
| 187 |
+
|
pool/shard007/Python/0069800_stap_gen_code.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python
|
| 2 |
+
|
| 3 |
+
# Copyright (C) 2014 Red Hat Inc.
|
| 4 |
+
#
|
| 5 |
+
# This file is part of systemtap, and is free software. You can
|
| 6 |
+
# redistribute it and/or modify it under the terms of the GNU General
|
| 7 |
+
# Public License (GPL); either version 2, or (at your option) any
|
| 8 |
+
# later version.
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
from config_opts import config_opts
|
| 13 |
+
|
| 14 |
+
def gen_files(dir, subset):
|
| 15 |
+
f = open('%s/probes.stp' % dir, 'w')
|
| 16 |
+
|
| 17 |
+
# Output the script
|
| 18 |
+
i = 0
|
| 19 |
+
while i < len(subset):
|
| 20 |
+
print >>f, ("global called%d" % (i))
|
| 21 |
+
i += 1
|
| 22 |
+
print >>f, "probe begin(-1)"
|
| 23 |
+
print >>f, "{"
|
| 24 |
+
i = 0
|
| 25 |
+
while i < len(subset):
|
| 26 |
+
print >>f, ("\tcalled%d <<< 0" % (i))
|
| 27 |
+
i += 1
|
| 28 |
+
print >>f, "}"
|
| 29 |
+
i = 0
|
| 30 |
+
while i < len(subset):
|
| 31 |
+
print >>f, ("probe kernel.function(\"%s\").call { called%d <<< 1 }" % (subset[i], i))
|
| 32 |
+
i += 1
|
| 33 |
+
print >>f, "probe end"
|
| 34 |
+
print >>f, "{"
|
| 35 |
+
i = 0
|
| 36 |
+
while i < len(subset):
|
| 37 |
+
print >>f, ("\tprintf(\"%%d %s\\n\", @sum(called%d))" % (subset[i], i))
|
| 38 |
+
i += 1
|
| 39 |
+
print >>f, "\tprintf(\"probe_module unloaded\\n\")"
|
| 40 |
+
print >>f, "}"
|
| 41 |
+
f.close()
|
| 42 |
+
|
| 43 |
+
def gen_module():
|
| 44 |
+
f = open(config_opts['probes_current'])
|
| 45 |
+
probes = f.readlines()
|
| 46 |
+
f.close()
|
| 47 |
+
if len(probes) == 0:
|
| 48 |
+
print >>sys.stderr, ("Error: no probe points in %s"
|
| 49 |
+
% config_opts['probes_current'])
|
| 50 |
+
return -1
|
| 51 |
+
|
| 52 |
+
# Cleanup each probe by stripping whitespace
|
| 53 |
+
i = 0
|
| 54 |
+
while i < len(probes):
|
| 55 |
+
probes[i] = probes[i].rstrip()
|
| 56 |
+
i += 1
|
| 57 |
+
|
| 58 |
+
# Generate necessary files
|
| 59 |
+
gen_files(os.getcwd(), probes)
|
| 60 |
+
|
| 61 |
+
# Try to build the module
|
| 62 |
+
os.system('rm -f ./probe_module.ko')
|
| 63 |
+
|
| 64 |
+
cmd = "stap -g --suppress-handler-errors --suppress-time-limits -vp4 -m probe_module probes.stp >build.log 2>&1"
|
| 65 |
+
print "Running", cmd
|
| 66 |
+
rc = os.system(cmd)
|
| 67 |
+
if os.WEXITSTATUS(rc) != 0:
|
| 68 |
+
print >>sys.stderr, "Error: stap failed, see build.log for details"
|
| 69 |
+
return -1
|
| 70 |
+
return 0
|
| 71 |
+
|
| 72 |
+
def main():
|
| 73 |
+
rc = gen_module()
|
| 74 |
+
sys.exit(rc)
|
| 75 |
+
|
| 76 |
+
if __name__ == "__main__":
|
| 77 |
+
main()
|
pool/shard007/Python/0069804_ro.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
##############################################################################
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) 2003 Zope Foundation and Contributors.
|
| 4 |
+
# All Rights Reserved.
|
| 5 |
+
#
|
| 6 |
+
# This software is subject to the provisions of the Zope Public License,
|
| 7 |
+
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
|
| 8 |
+
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
|
| 9 |
+
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
| 10 |
+
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
|
| 11 |
+
# FOR A PARTICULAR PURPOSE.
|
| 12 |
+
#
|
| 13 |
+
##############################################################################
|
| 14 |
+
"""Compute a resolution order for an object and its bases
|
| 15 |
+
|
| 16 |
+
$Id: ro.py 110536 2010-04-06 02:59:44Z tseaver $
|
| 17 |
+
"""
|
| 18 |
+
__docformat__ = 'restructuredtext'
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def ro(object):
|
| 22 |
+
"""Compute a "resolution order" for an object
|
| 23 |
+
"""
|
| 24 |
+
return mergeOrderings([_flatten(object)])
|
| 25 |
+
|
| 26 |
+
def mergeOrderings(orderings, seen=None):
|
| 27 |
+
"""Merge multiple orderings so that within-ordering order is preserved
|
| 28 |
+
|
| 29 |
+
Orderings are constrained in such a way that if an object appears
|
| 30 |
+
in two or more orderings, then the suffix that begins with the
|
| 31 |
+
object must be in both orderings.
|
| 32 |
+
|
| 33 |
+
For example:
|
| 34 |
+
|
| 35 |
+
>>> _mergeOrderings([
|
| 36 |
+
... ['x', 'y', 'z'],
|
| 37 |
+
... ['q', 'z'],
|
| 38 |
+
... [1, 3, 5],
|
| 39 |
+
... ['z']
|
| 40 |
+
... ])
|
| 41 |
+
['x', 'y', 'q', 1, 3, 5, 'z']
|
| 42 |
+
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
if seen is None:
|
| 46 |
+
seen = {}
|
| 47 |
+
result = []
|
| 48 |
+
orderings.reverse()
|
| 49 |
+
for ordering in orderings:
|
| 50 |
+
ordering = list(ordering)
|
| 51 |
+
ordering.reverse()
|
| 52 |
+
for o in ordering:
|
| 53 |
+
if o not in seen:
|
| 54 |
+
seen[o] = 1
|
| 55 |
+
result.append(o)
|
| 56 |
+
|
| 57 |
+
result.reverse()
|
| 58 |
+
return result
|
| 59 |
+
|
| 60 |
+
def _flatten(ob):
|
| 61 |
+
result = [ob]
|
| 62 |
+
i = 0
|
| 63 |
+
for ob in iter(result):
|
| 64 |
+
i += 1
|
| 65 |
+
# The recursive calls can be avoided by inserting the base classes
|
| 66 |
+
# into the dynamically growing list directly after the currently
|
| 67 |
+
# considered object; the iterator makes sure this will keep working
|
| 68 |
+
# in the future, since it cannot rely on the length of the list
|
| 69 |
+
# by definition.
|
| 70 |
+
result[i:i] = ob.__bases__
|
| 71 |
+
return result
|
pool/shard007/Python/0069812_web_views_test.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from cStringIO import StringIO
|
| 2 |
+
import unittest
|
| 3 |
+
|
| 4 |
+
import mock
|
| 5 |
+
from PyPDF2 import PdfFileReader
|
| 6 |
+
|
| 7 |
+
from logic import reminder_service
|
| 8 |
+
from testing import test_base
|
| 9 |
+
from testing import test_data
|
| 10 |
+
from util import ids
|
| 11 |
+
from views import web_views
|
| 12 |
+
assert web_views # Silence pyflakes
|
| 13 |
+
|
| 14 |
+
pelosi = test_data.RepData.nancy_pelosi
|
| 15 |
+
|
| 16 |
+
class WebViewsTest(test_base.DatabaseWithTestdataTest):
|
| 17 |
+
def test_heartbeat(self):
|
| 18 |
+
resp = self.client.get('/')
|
| 19 |
+
self.assertEqual(200, resp.status_code)
|
| 20 |
+
resp = self.client.get('/district/%s' % test_data.DistrictData.wy00.district_code)
|
| 21 |
+
self.assertEqual(200, resp.status_code)
|
| 22 |
+
resp = self.client.get('/compose/%s' % pelosi.rep_id)
|
| 23 |
+
self.assertEqual(200, resp.status_code)
|
| 24 |
+
|
| 25 |
+
resp = self.client.get('/robots.txt')
|
| 26 |
+
self.assertEqual(200, resp.status_code)
|
| 27 |
+
resp = self.client.get('/sitemap.txt')
|
| 28 |
+
self.assertEqual(200, resp.status_code)
|
| 29 |
+
|
| 30 |
+
def test_generate_letter_pdf(self):
|
| 31 |
+
resp = self.client.post('/letter', data=dict(
|
| 32 |
+
rep_id=str(pelosi.rep_id),
|
| 33 |
+
body='hello world',
|
| 34 |
+
name_and_address='Bob Smith\nSan Francisco, CA',
|
| 35 |
+
include_address_page='1'))
|
| 36 |
+
self.assertEqual(200, resp.status_code)
|
| 37 |
+
self.assertEqual('application/pdf', resp.headers.get('Content-Type'))
|
| 38 |
+
self.assertIsNotNone(resp.data)
|
| 39 |
+
|
| 40 |
+
pdf_reader = PdfFileReader(StringIO(resp.data))
|
| 41 |
+
self.assertEqual(2, pdf_reader.getNumPages())
|
| 42 |
+
|
| 43 |
+
def test_generate_letter_pdf_without_address_page(self):
|
| 44 |
+
resp = self.client.post('/letter', data=dict(
|
| 45 |
+
rep_id=str(pelosi.rep_id),
|
| 46 |
+
body='hello world',
|
| 47 |
+
name_and_address='Bob Smith\nSan Francisco, CA',
|
| 48 |
+
include_address_page='0'))
|
| 49 |
+
self.assertEqual(200, resp.status_code)
|
| 50 |
+
self.assertEqual('application/pdf', resp.headers.get('Content-Type'))
|
| 51 |
+
self.assertIsNotNone(resp.data)
|
| 52 |
+
|
| 53 |
+
pdf_reader = PdfFileReader(StringIO(resp.data))
|
| 54 |
+
self.assertEqual(1, pdf_reader.getNumPages())
|
| 55 |
+
|
| 56 |
+
@mock.patch('app.app.logger.error')
|
| 57 |
+
def test_generate_letter_with_invalid_params(self, mock_log_error):
|
| 58 |
+
resp = self.client.post('/letter', data=dict(
|
| 59 |
+
rep_id='-1',
|
| 60 |
+
body='hello world',
|
| 61 |
+
name_and_address='Bob Smith\nSan Francisco, CA',
|
| 62 |
+
include_address_page='1'))
|
| 63 |
+
self.assertEqual(400, resp.status_code)
|
| 64 |
+
mock_log_error.assert_called_once()
|
| 65 |
+
|
| 66 |
+
@mock.patch.object(reminder_service.ReminderServiceImpl, 'update')
|
| 67 |
+
def test_reminder_unsubscribe(self, mock_update):
|
| 68 |
+
resp = self.client.get('/reminder/unsubscribe?email=foo@foo.com&token=blah')
|
| 69 |
+
self.assertEqual(200, resp.status_code)
|
| 70 |
+
mock_update.assert_called_once()
|
| 71 |
+
update_req = mock_update.call_args[0][0]
|
| 72 |
+
self.assertEqual('foo@foo.com', update_req.email)
|
| 73 |
+
self.assertEqual('blah', update_req.token)
|
| 74 |
+
self.assertEqual('UNSUBSCRIBED', update_req.status)
|
| 75 |
+
|
| 76 |
+
def test_get_issue_page(self):
|
| 77 |
+
issue_data = test_data.IssueData.issue1
|
| 78 |
+
resp = self.client.get('/issue/%s' % ids.public_id(issue_data.issue_id))
|
| 79 |
+
self.assertEqual(200, resp.status_code)
|
| 80 |
+
|
| 81 |
+
def test_create_issue_page(self):
|
| 82 |
+
resp = self.client.get('/issue/create')
|
| 83 |
+
self.assertEqual(200, resp.status_code)
|
| 84 |
+
|
| 85 |
+
def test_edit_issue_page(self):
|
| 86 |
+
issue_data = test_data.IssueData.issue1
|
| 87 |
+
resp = self.client.get('/issue/%s/edit?token=issuetoken' %
|
| 88 |
+
ids.public_id(issue_data.issue_id))
|
| 89 |
+
self.assertEqual(200, resp.status_code)
|
| 90 |
+
self.assertTrue('issuetoken' in resp.data)
|
| 91 |
+
self.assertTrue(issue_data.description in resp.data)
|
| 92 |
+
|
| 93 |
+
if __name__ == '__main__':
|
| 94 |
+
unittest.main()
|
pool/shard007/Python/0069816_urls.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from django.contrib.auth.decorators import login_required
|
| 2 |
+
from django.shortcuts import redirect
|
| 3 |
+
from django.urls import re_path
|
| 4 |
+
from django.views.generic import TemplateView
|
| 5 |
+
|
| 6 |
+
from dados.dbdata import STATE_NAME
|
| 7 |
+
|
| 8 |
+
# local
|
| 9 |
+
from .views import (
|
| 10 |
+
AboutPageView,
|
| 11 |
+
AlertaGeoJSONView,
|
| 12 |
+
AlertaMainView,
|
| 13 |
+
AlertaMRJPageView,
|
| 14 |
+
AlertaMunicipioPageView,
|
| 15 |
+
AlertaStateView,
|
| 16 |
+
ChartsMainView,
|
| 17 |
+
DataPublicServicesPageView,
|
| 18 |
+
DetailsPageView,
|
| 19 |
+
GeoJsonView,
|
| 20 |
+
GeoTiffView,
|
| 21 |
+
JoininPageView,
|
| 22 |
+
ReportCityView,
|
| 23 |
+
ReportStateView,
|
| 24 |
+
ReportView,
|
| 25 |
+
SinanCasesView,
|
| 26 |
+
TeamPageView,
|
| 27 |
+
get_municipio,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def redirect_alerta_dengue(request, state):
|
| 32 |
+
return redirect('dados:alerta_uf', state=state, disease='dengue')
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def redirect_alert_rio_dengue(request):
|
| 36 |
+
return redirect('dados:mrj', disease='dengue')
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def redirect_alert_city_dengue(request, geocodigo):
|
| 40 |
+
return redirect(
|
| 41 |
+
'dados:alerta_cidade', geocodigo=geocodigo, disease='dengue'
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
app_name = "dados"
|
| 46 |
+
|
| 47 |
+
state_abbv = '|'.join(state for state in STATE_NAME.keys())
|
| 48 |
+
|
| 49 |
+
__disease = '(?P<disease>dengue|chikungunya|zika)'
|
| 50 |
+
__state_abbv = f'(?P<state>{state_abbv})'
|
| 51 |
+
__geocode = r'(?P<geocodigo>\d{7})'
|
| 52 |
+
__geocode_ = r'(?P<geocode>\d{7})'
|
| 53 |
+
__year = r'(?P<year>\d{4})'
|
| 54 |
+
__month = r'(?P<month>\d{2})'
|
| 55 |
+
__day = r'(?P<day>\d{2})'
|
| 56 |
+
__e_week = r'(?P<e_week>\d{2})'
|
| 57 |
+
__year_week = r'(?P<year_week>\d{6})'
|
| 58 |
+
|
| 59 |
+
__report_type = '(?P<report_type>city|state)'
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
urlpatterns = [
|
| 63 |
+
re_path(r'^$', AlertaMainView.as_view(), name='main'),
|
| 64 |
+
re_path(
|
| 65 |
+
r'^chartshome/{}$'.format(__state_abbv),
|
| 66 |
+
ChartsMainView.as_view(),
|
| 67 |
+
name='chartshome',
|
| 68 |
+
),
|
| 69 |
+
re_path(r'^informacoes/$', AboutPageView.as_view(), name='about'),
|
| 70 |
+
re_path(r'^equipe/$', TeamPageView.as_view(), name='team'),
|
| 71 |
+
re_path(r'^participe/$', JoininPageView.as_view(), name='joinin'),
|
| 72 |
+
re_path(
|
| 73 |
+
r'^services/(?P<service>maps|api)?$',
|
| 74 |
+
DataPublicServicesPageView.as_view(),
|
| 75 |
+
name="data_public_services",
|
| 76 |
+
),
|
| 77 |
+
re_path(
|
| 78 |
+
r'^services/(?P<service>maps|tutorial)?$',
|
| 79 |
+
DataPublicServicesPageView.as_view(),
|
| 80 |
+
name="data_public_services",
|
| 81 |
+
),
|
| 82 |
+
re_path(
|
| 83 |
+
r'^services/(?P<service>maps|tutorial)/(?P<service_type>R)$',
|
| 84 |
+
DataPublicServicesPageView.as_view(
|
| 85 |
+
template_name="services_tutorial_R.html"
|
| 86 |
+
),
|
| 87 |
+
name='services_tutorial_R',
|
| 88 |
+
),
|
| 89 |
+
re_path(
|
| 90 |
+
r'^tutorial_api_r/',
|
| 91 |
+
TemplateView.as_view(
|
| 92 |
+
template_name="components/tutorial/notebook-API-R-en.html"
|
| 93 |
+
),
|
| 94 |
+
name='tutorial_api_R',
|
| 95 |
+
),
|
| 96 |
+
re_path(
|
| 97 |
+
r'^services/(?P<service>maps|tutorial)/(?P<service_type>Python)$',
|
| 98 |
+
DataPublicServicesPageView.as_view(
|
| 99 |
+
template_name="services_tutorial_Python.html"
|
| 100 |
+
),
|
| 101 |
+
name='services_tutorial_Python',
|
| 102 |
+
),
|
| 103 |
+
re_path(
|
| 104 |
+
r'^tutorial_api_python/',
|
| 105 |
+
TemplateView.as_view(
|
| 106 |
+
template_name="components/tutorial/notebook-API-Python-en.html"
|
| 107 |
+
),
|
| 108 |
+
name='tutorial_api_python',
|
| 109 |
+
),
|
| 110 |
+
re_path(
|
| 111 |
+
r'^services/(?P<service>maps|api)/(?P<service_type>doc)$',
|
| 112 |
+
DataPublicServicesPageView.as_view(),
|
| 113 |
+
name="data_public_services_type",
|
| 114 |
+
),
|
| 115 |
+
re_path(r'^alerta/%s[/]?$' % __state_abbv, redirect_alerta_dengue),
|
| 116 |
+
re_path(
|
| 117 |
+
r'^alerta/%s/%s$' % (__state_abbv, __disease),
|
| 118 |
+
AlertaStateView.as_view(),
|
| 119 |
+
name='alerta_uf',
|
| 120 |
+
),
|
| 121 |
+
re_path(r'^alerta/rio/$', redirect_alert_rio_dengue),
|
| 122 |
+
re_path(
|
| 123 |
+
r'^alerta/rio/%s$' % __disease, AlertaMRJPageView.as_view(), name='mrj'
|
| 124 |
+
),
|
| 125 |
+
re_path(r'^alerta/%s[/]?$' % __geocode, redirect_alert_city_dengue),
|
| 126 |
+
re_path(
|
| 127 |
+
r'^alerta/%s/%s$' % (__geocode, __disease),
|
| 128 |
+
AlertaMunicipioPageView.as_view(),
|
| 129 |
+
name='alerta_cidade',
|
| 130 |
+
),
|
| 131 |
+
re_path(r'^alerta-detalhado/$', DetailsPageView.as_view(), name='home'),
|
| 132 |
+
re_path(
|
| 133 |
+
r'^alertageoJSON/$',
|
| 134 |
+
login_required(AlertaGeoJSONView.as_view()),
|
| 135 |
+
name='alerta-layer',
|
| 136 |
+
),
|
| 137 |
+
re_path(r'^getcity/$', get_municipio, name='get_city'),
|
| 138 |
+
re_path(
|
| 139 |
+
r'^sinan/(\d{4})/(\d{1,2})', SinanCasesView.as_view(), name='sinan'
|
| 140 |
+
),
|
| 141 |
+
re_path(
|
| 142 |
+
r'^geotiff/%s/%s/$' % (__geocode, __disease),
|
| 143 |
+
GeoTiffView.as_view(),
|
| 144 |
+
name='geotiff',
|
| 145 |
+
),
|
| 146 |
+
re_path(
|
| 147 |
+
r'^geojson/%s/%s/$' % (__geocode, __disease),
|
| 148 |
+
GeoJsonView.as_view(),
|
| 149 |
+
name='geojson',
|
| 150 |
+
),
|
| 151 |
+
re_path(r'^report/$', ReportView.as_view(), name='report'),
|
| 152 |
+
re_path(
|
| 153 |
+
r'^report/{}/{}$'.format(__state_abbv, __report_type),
|
| 154 |
+
ReportView.as_view(),
|
| 155 |
+
name='report_filter',
|
| 156 |
+
),
|
| 157 |
+
re_path(
|
| 158 |
+
r'^report/{}/{}/{}$'.format(__state_abbv, __geocode_, __year_week),
|
| 159 |
+
ReportCityView.as_view(),
|
| 160 |
+
name='report_city',
|
| 161 |
+
),
|
| 162 |
+
re_path(
|
| 163 |
+
r'^report/{}/{}$'.format(__state_abbv, __year_week),
|
| 164 |
+
ReportStateView.as_view(),
|
| 165 |
+
name='report_state',
|
| 166 |
+
),
|
| 167 |
+
]
|
pool/shard007/Python/0069818_test_abstract_protein.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from helpers.filters import Filter
|
| 2 |
+
from view_testing import ViewTest
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class TestAbstractProteinView(ViewTest):
|
| 6 |
+
|
| 7 |
+
def view_module(self):
|
| 8 |
+
from website.views import abstract_protein
|
| 9 |
+
return abstract_protein
|
| 10 |
+
|
| 11 |
+
def test_are_filter_managers_graceful(self):
|
| 12 |
+
from views import ProteinView, SequenceView, NetworkView
|
| 13 |
+
from views.abstract_protein import GracefulFilterManager
|
| 14 |
+
|
| 15 |
+
graceful_views = [SequenceView, ProteinView, NetworkView]
|
| 16 |
+
for view in graceful_views:
|
| 17 |
+
assert issubclass(view.filter_class, GracefulFilterManager)
|
| 18 |
+
|
| 19 |
+
def test_graceful_manager(self):
|
| 20 |
+
from website.views.abstract_protein import GracefulFilterManager
|
| 21 |
+
|
| 22 |
+
class Target:
|
| 23 |
+
__name__ = 'TestModel'
|
| 24 |
+
|
| 25 |
+
class Request:
|
| 26 |
+
method = 'GET'
|
| 27 |
+
|
| 28 |
+
def __init__(self, args):
|
| 29 |
+
self.args = args
|
| 30 |
+
|
| 31 |
+
class TestViewFilters(GracefulFilterManager):
|
| 32 |
+
|
| 33 |
+
def __init__(self, request):
|
| 34 |
+
|
| 35 |
+
filters = [
|
| 36 |
+
Filter(
|
| 37 |
+
Target(), 'property', comparators=['in'],
|
| 38 |
+
choices=['Value1', "Value2, corrected"],
|
| 39 |
+
multiple=True
|
| 40 |
+
)
|
| 41 |
+
]
|
| 42 |
+
super().__init__(filters)
|
| 43 |
+
self.update_from_request(request)
|
| 44 |
+
|
| 45 |
+
test_request = Request({
|
| 46 |
+
'filters': "TestModel.property:in:Value1,Value2,'Value2, corrected'"
|
| 47 |
+
})
|
| 48 |
+
TestViewFilters(test_request)
|
| 49 |
+
with self.assert_flashes(
|
| 50 |
+
content='<i>Value2</i> does not occur in <i>property</i> for this protein and therefore it was left out.',
|
| 51 |
+
category='warning'
|
| 52 |
+
):
|
| 53 |
+
test_request = Request({
|
| 54 |
+
'filters': "TestModel.property:in:Value1,Value2,'Value2, corrected'"
|
| 55 |
+
})
|
| 56 |
+
TestViewFilters(test_request)
|
pool/shard007/Python/0069820_storage.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from django.conf import settings
|
| 4 |
+
from django.core.exceptions import ImproperlyConfigured
|
| 5 |
+
from django.utils.functional import cached_property
|
| 6 |
+
|
| 7 |
+
from django_tenants import utils
|
| 8 |
+
from django_tenants.files.storage import TenantFileSystemStorage
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TenantStaticFilesStorage(TenantFileSystemStorage):
|
| 12 |
+
"""
|
| 13 |
+
Implementation that extends core Django's StaticFilesStorage for multi-tenant setups.
|
| 14 |
+
|
| 15 |
+
The defaults for ``location`` and ``base_url`` are ``STATIC_ROOT`` and ``STATIC_URL``.
|
| 16 |
+
|
| 17 |
+
"""
|
| 18 |
+
def _clear_cached_properties(self, setting, **kwargs):
|
| 19 |
+
"""Reset setting based property values."""
|
| 20 |
+
super()._clear_cached_properties(settings, **kwargs)
|
| 21 |
+
|
| 22 |
+
if setting == 'MULTITENANT_RELATIVE_STATIC_ROOT':
|
| 23 |
+
self.__dict__.pop('relative_static_root', None)
|
| 24 |
+
|
| 25 |
+
@cached_property
|
| 26 |
+
def relative_static_root(self):
|
| 27 |
+
try:
|
| 28 |
+
return os.path.join(settings.STATIC_ROOT, settings.MULTITENANT_RELATIVE_STATIC_ROOT)
|
| 29 |
+
except AttributeError:
|
| 30 |
+
# MULTITENANT_RELATIVE_STATIC_ROOT is an optional setting. Use the default of just appending
|
| 31 |
+
# the tenant schema_name to STATIC_ROOT if no configuration value is provided
|
| 32 |
+
try:
|
| 33 |
+
return settings.STATIC_ROOT
|
| 34 |
+
except AttributeError:
|
| 35 |
+
raise ImproperlyConfigured("You're using the staticfiles app "
|
| 36 |
+
"without having set the STATIC_ROOT "
|
| 37 |
+
"setting to a filesystem path.")
|
| 38 |
+
|
| 39 |
+
@cached_property
|
| 40 |
+
def relative_static_url(self):
|
| 41 |
+
url = settings.STATIC_URL
|
| 42 |
+
rewrite_on = False
|
| 43 |
+
|
| 44 |
+
try:
|
| 45 |
+
if settings.REWRITE_STATIC_URLS is True:
|
| 46 |
+
rewrite_on = True
|
| 47 |
+
try:
|
| 48 |
+
multitenant_relative_url = settings.MULTITENANT_RELATIVE_STATIC_ROOT
|
| 49 |
+
except AttributeError:
|
| 50 |
+
# MULTITENANT_RELATIVE_STATIC_ROOT is an optional setting. Use the default of just appending
|
| 51 |
+
# the tenant schema_name to STATIC_ROOT if no configuration value is provided
|
| 52 |
+
multitenant_relative_url = "%s"
|
| 53 |
+
|
| 54 |
+
url = "/" + "/".join(s.strip("/") for s in [url, multitenant_relative_url]) + "/"
|
| 55 |
+
|
| 56 |
+
except AttributeError:
|
| 57 |
+
# REWRITE_STATIC_URLS not set - ignore
|
| 58 |
+
pass
|
| 59 |
+
|
| 60 |
+
return rewrite_on, url
|
| 61 |
+
|
| 62 |
+
@property # Not cached like in parent class
|
| 63 |
+
def base_location(self):
|
| 64 |
+
return self._value_or_setting(self._location, utils.parse_tenant_config_path(self.relative_static_root))
|
| 65 |
+
|
| 66 |
+
@property # Not cached like in parent class
|
| 67 |
+
def base_url(self):
|
| 68 |
+
rewrite_on, relative_tenant_url = self.relative_static_url
|
| 69 |
+
if rewrite_on:
|
| 70 |
+
relative_tenant_url = utils.parse_tenant_config_path(relative_tenant_url)
|
| 71 |
+
|
| 72 |
+
if not relative_tenant_url.endswith('/'):
|
| 73 |
+
relative_tenant_url += '/'
|
| 74 |
+
|
| 75 |
+
if self._base_url is not None and not self._base_url.endswith('/'):
|
| 76 |
+
self._base_url += '/'
|
| 77 |
+
|
| 78 |
+
return self._value_or_setting(self._base_url, relative_tenant_url)
|
pool/shard007/Python/0069824_Hello.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Autogenerated by Thrift Compiler (0.13.0)
|
| 3 |
+
#
|
| 4 |
+
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
|
| 5 |
+
#
|
| 6 |
+
# options string: py
|
| 7 |
+
#
|
| 8 |
+
|
| 9 |
+
from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
|
| 10 |
+
from thrift.protocol.TProtocol import TProtocolException
|
| 11 |
+
from thrift.TRecursive import fix_spec
|
| 12 |
+
|
| 13 |
+
import sys
|
| 14 |
+
import logging
|
| 15 |
+
from .ttypes import *
|
| 16 |
+
from thrift.Thrift import TProcessor
|
| 17 |
+
from thrift.transport import TTransport
|
| 18 |
+
all_structs = []
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class Iface(object):
|
| 22 |
+
def hi(self, test_data):
|
| 23 |
+
"""
|
| 24 |
+
Parameters:
|
| 25 |
+
- test_data
|
| 26 |
+
|
| 27 |
+
"""
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class Client(Iface):
|
| 32 |
+
def __init__(self, iprot, oprot=None):
|
| 33 |
+
self._iprot = self._oprot = iprot
|
| 34 |
+
if oprot is not None:
|
| 35 |
+
self._oprot = oprot
|
| 36 |
+
self._seqid = 0
|
| 37 |
+
|
| 38 |
+
def hi(self, test_data):
|
| 39 |
+
"""
|
| 40 |
+
Parameters:
|
| 41 |
+
- test_data
|
| 42 |
+
|
| 43 |
+
"""
|
| 44 |
+
self.send_hi(test_data)
|
| 45 |
+
return self.recv_hi()
|
| 46 |
+
|
| 47 |
+
def send_hi(self, test_data):
|
| 48 |
+
self._oprot.writeMessageBegin('hi', TMessageType.CALL, self._seqid)
|
| 49 |
+
args = hi_args()
|
| 50 |
+
args.test_data = test_data
|
| 51 |
+
args.write(self._oprot)
|
| 52 |
+
self._oprot.writeMessageEnd()
|
| 53 |
+
self._oprot.trans.flush()
|
| 54 |
+
|
| 55 |
+
def recv_hi(self):
|
| 56 |
+
iprot = self._iprot
|
| 57 |
+
(fname, mtype, rseqid) = iprot.readMessageBegin()
|
| 58 |
+
if mtype == TMessageType.EXCEPTION:
|
| 59 |
+
x = TApplicationException()
|
| 60 |
+
x.read(iprot)
|
| 61 |
+
iprot.readMessageEnd()
|
| 62 |
+
raise x
|
| 63 |
+
result = hi_result()
|
| 64 |
+
result.read(iprot)
|
| 65 |
+
iprot.readMessageEnd()
|
| 66 |
+
if result.success is not None:
|
| 67 |
+
return result.success
|
| 68 |
+
raise TApplicationException(TApplicationException.MISSING_RESULT, "hi failed: unknown result")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class Processor(Iface, TProcessor):
|
| 72 |
+
def __init__(self, handler):
|
| 73 |
+
self._handler = handler
|
| 74 |
+
self._processMap = {}
|
| 75 |
+
self._processMap["hi"] = Processor.process_hi
|
| 76 |
+
self._on_message_begin = None
|
| 77 |
+
|
| 78 |
+
def on_message_begin(self, func):
|
| 79 |
+
self._on_message_begin = func
|
| 80 |
+
|
| 81 |
+
def process(self, iprot, oprot):
|
| 82 |
+
(name, type, seqid) = iprot.readMessageBegin()
|
| 83 |
+
if self._on_message_begin:
|
| 84 |
+
self._on_message_begin(name, type, seqid)
|
| 85 |
+
if name not in self._processMap:
|
| 86 |
+
iprot.skip(TType.STRUCT)
|
| 87 |
+
iprot.readMessageEnd()
|
| 88 |
+
x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' % (name))
|
| 89 |
+
oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid)
|
| 90 |
+
x.write(oprot)
|
| 91 |
+
oprot.writeMessageEnd()
|
| 92 |
+
oprot.trans.flush()
|
| 93 |
+
return
|
| 94 |
+
else:
|
| 95 |
+
self._processMap[name](self, seqid, iprot, oprot)
|
| 96 |
+
return True
|
| 97 |
+
|
| 98 |
+
def process_hi(self, seqid, iprot, oprot):
|
| 99 |
+
args = hi_args()
|
| 100 |
+
args.read(iprot)
|
| 101 |
+
iprot.readMessageEnd()
|
| 102 |
+
result = hi_result()
|
| 103 |
+
try:
|
| 104 |
+
result.success = self._handler.hi(args.test_data)
|
| 105 |
+
msg_type = TMessageType.REPLY
|
| 106 |
+
except TTransport.TTransportException:
|
| 107 |
+
raise
|
| 108 |
+
except TApplicationException as ex:
|
| 109 |
+
logging.exception('TApplication exception in handler')
|
| 110 |
+
msg_type = TMessageType.EXCEPTION
|
| 111 |
+
result = ex
|
| 112 |
+
except Exception:
|
| 113 |
+
logging.exception('Unexpected exception in handler')
|
| 114 |
+
msg_type = TMessageType.EXCEPTION
|
| 115 |
+
result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error')
|
| 116 |
+
oprot.writeMessageBegin("hi", msg_type, seqid)
|
| 117 |
+
result.write(oprot)
|
| 118 |
+
oprot.writeMessageEnd()
|
| 119 |
+
oprot.trans.flush()
|
| 120 |
+
|
| 121 |
+
# HELPER FUNCTIONS AND STRUCTURES
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class hi_args(object):
|
| 125 |
+
"""
|
| 126 |
+
Attributes:
|
| 127 |
+
- test_data
|
| 128 |
+
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def __init__(self, test_data=None,):
|
| 133 |
+
self.test_data = test_data
|
| 134 |
+
|
| 135 |
+
def read(self, iprot):
|
| 136 |
+
if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None:
|
| 137 |
+
iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec])
|
| 138 |
+
return
|
| 139 |
+
iprot.readStructBegin()
|
| 140 |
+
while True:
|
| 141 |
+
(fname, ftype, fid) = iprot.readFieldBegin()
|
| 142 |
+
if ftype == TType.STOP:
|
| 143 |
+
break
|
| 144 |
+
if fid == 1:
|
| 145 |
+
if ftype == TType.STRING:
|
| 146 |
+
self.test_data = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
|
| 147 |
+
else:
|
| 148 |
+
iprot.skip(ftype)
|
| 149 |
+
else:
|
| 150 |
+
iprot.skip(ftype)
|
| 151 |
+
iprot.readFieldEnd()
|
| 152 |
+
iprot.readStructEnd()
|
| 153 |
+
|
| 154 |
+
def write(self, oprot):
|
| 155 |
+
if oprot._fast_encode is not None and self.thrift_spec is not None:
|
| 156 |
+
oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec]))
|
| 157 |
+
return
|
| 158 |
+
oprot.writeStructBegin('hi_args')
|
| 159 |
+
if self.test_data is not None:
|
| 160 |
+
oprot.writeFieldBegin('test_data', TType.STRING, 1)
|
| 161 |
+
oprot.writeString(self.test_data.encode('utf-8') if sys.version_info[0] == 2 else self.test_data)
|
| 162 |
+
oprot.writeFieldEnd()
|
| 163 |
+
oprot.writeFieldStop()
|
| 164 |
+
oprot.writeStructEnd()
|
| 165 |
+
|
| 166 |
+
def validate(self):
|
| 167 |
+
return
|
| 168 |
+
|
| 169 |
+
def __repr__(self):
|
| 170 |
+
L = ['%s=%r' % (key, value)
|
| 171 |
+
for key, value in self.__dict__.items()]
|
| 172 |
+
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
|
| 173 |
+
|
| 174 |
+
def __eq__(self, other):
|
| 175 |
+
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
|
| 176 |
+
|
| 177 |
+
def __ne__(self, other):
|
| 178 |
+
return not (self == other)
|
| 179 |
+
all_structs.append(hi_args)
|
| 180 |
+
hi_args.thrift_spec = (
|
| 181 |
+
None, # 0
|
| 182 |
+
(1, TType.STRING, 'test_data', 'UTF8', None, ), # 1
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class hi_result(object):
|
| 187 |
+
"""
|
| 188 |
+
Attributes:
|
| 189 |
+
- success
|
| 190 |
+
|
| 191 |
+
"""
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def __init__(self, success=None,):
|
| 195 |
+
self.success = success
|
| 196 |
+
|
| 197 |
+
def read(self, iprot):
|
| 198 |
+
if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None:
|
| 199 |
+
iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec])
|
| 200 |
+
return
|
| 201 |
+
iprot.readStructBegin()
|
| 202 |
+
while True:
|
| 203 |
+
(fname, ftype, fid) = iprot.readFieldBegin()
|
| 204 |
+
if ftype == TType.STOP:
|
| 205 |
+
break
|
| 206 |
+
if fid == 0:
|
| 207 |
+
if ftype == TType.STRING:
|
| 208 |
+
self.success = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
|
| 209 |
+
else:
|
| 210 |
+
iprot.skip(ftype)
|
| 211 |
+
else:
|
| 212 |
+
iprot.skip(ftype)
|
| 213 |
+
iprot.readFieldEnd()
|
| 214 |
+
iprot.readStructEnd()
|
| 215 |
+
|
| 216 |
+
def write(self, oprot):
|
| 217 |
+
if oprot._fast_encode is not None and self.thrift_spec is not None:
|
| 218 |
+
oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec]))
|
| 219 |
+
return
|
| 220 |
+
oprot.writeStructBegin('hi_result')
|
| 221 |
+
if self.success is not None:
|
| 222 |
+
oprot.writeFieldBegin('success', TType.STRING, 0)
|
| 223 |
+
oprot.writeString(self.success.encode('utf-8') if sys.version_info[0] == 2 else self.success)
|
| 224 |
+
oprot.writeFieldEnd()
|
| 225 |
+
oprot.writeFieldStop()
|
| 226 |
+
oprot.writeStructEnd()
|
| 227 |
+
|
| 228 |
+
def validate(self):
|
| 229 |
+
return
|
| 230 |
+
|
| 231 |
+
def __repr__(self):
|
| 232 |
+
L = ['%s=%r' % (key, value)
|
| 233 |
+
for key, value in self.__dict__.items()]
|
| 234 |
+
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
|
| 235 |
+
|
| 236 |
+
def __eq__(self, other):
|
| 237 |
+
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
|
| 238 |
+
|
| 239 |
+
def __ne__(self, other):
|
| 240 |
+
return not (self == other)
|
| 241 |
+
all_structs.append(hi_result)
|
| 242 |
+
hi_result.thrift_spec = (
|
| 243 |
+
(0, TType.STRING, 'success', 'UTF8', None, ), # 0
|
| 244 |
+
)
|
| 245 |
+
fix_spec(all_structs)
|
| 246 |
+
del all_structs
|
| 247 |
+
|
pool/shard007/Python/0069826_wiz_import_procurement_from_plan.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# (c) 2015 Alfredo de la Fuente - AvanzOSC
|
| 3 |
+
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
|
| 4 |
+
from openerp import models, fields, api
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class WizImportProcurementFromPlan(models.TransientModel):
|
| 8 |
+
|
| 9 |
+
_name = 'wiz.import.procurement.from.plan'
|
| 10 |
+
|
| 11 |
+
from_date = fields.Date(string='From Date')
|
| 12 |
+
to_date = fields.Date(string='to Date')
|
| 13 |
+
warehouse_id = fields.Many2one('stock.warehouse', string='Warehouse')
|
| 14 |
+
procurement_ids = fields.Many2many(
|
| 15 |
+
comodel_name="procurement.order",
|
| 16 |
+
relation="import_from_plan_procurement_rel",
|
| 17 |
+
column1="wiz_import_plan_id", column2="procurement_id",
|
| 18 |
+
string="Procurements")
|
| 19 |
+
|
| 20 |
+
@api.model
|
| 21 |
+
def default_get(self, var_fields):
|
| 22 |
+
plan = self.env['procurement.plan'].browse(
|
| 23 |
+
self.env.context['active_id'])
|
| 24 |
+
return {'from_date': plan.from_date,
|
| 25 |
+
'to_date': plan.to_date,
|
| 26 |
+
'warehouse_id': plan.warehouse_id.id}
|
| 27 |
+
|
| 28 |
+
@api.multi
|
| 29 |
+
@api.onchange('warehouse_id')
|
| 30 |
+
def onchange_warehouse_id(self):
|
| 31 |
+
self.ensure_one()
|
| 32 |
+
cond = [('warehouse_id', '=', self.warehouse_id.id),
|
| 33 |
+
('state', 'not in', ('cancel', 'done')),
|
| 34 |
+
('location_type', '=', 'internal'),
|
| 35 |
+
('plan', '=', False)]
|
| 36 |
+
if self.from_date:
|
| 37 |
+
cond.append(('date_planned', '>=', self.from_date))
|
| 38 |
+
if self.to_date:
|
| 39 |
+
cond.append(('date_planned', '<=', self.to_date))
|
| 40 |
+
return {'domain': {'procurement_ids': cond}}
|
| 41 |
+
|
| 42 |
+
@api.multi
|
| 43 |
+
def import_procurements(self):
|
| 44 |
+
self.ensure_one()
|
| 45 |
+
self.procurement_ids.write({'plan': self.env.context['active_id']})
|
| 46 |
+
plan = self.env['procurement.plan'].browse(
|
| 47 |
+
self.env.context['active_id'])
|
| 48 |
+
if plan.procurement_ids:
|
| 49 |
+
sorted_procs = sorted(plan.procurement_ids,
|
| 50 |
+
key=lambda l: l.date_planned, reverse=True)
|
| 51 |
+
plan.to_date = sorted_procs[0].date_planned
|
| 52 |
+
plan.from_date = sorted_procs[len(sorted_procs)-1].date_planned
|
| 53 |
+
return True
|
pool/shard007/Python/0069831_test_footer.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests related to the basic footer-switching based off SITE_NAME to ensure
|
| 3 |
+
edx.org uses an edx footer but other instances use an Open edX footer.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import unittest
|
| 7 |
+
|
| 8 |
+
from django.conf import settings
|
| 9 |
+
from django.test import TestCase
|
| 10 |
+
from django.test.utils import override_settings
|
| 11 |
+
|
| 12 |
+
from openedx.core.djangoapps.theming.tests.test_util import with_comprehensive_theme
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
|
| 16 |
+
class TestFooter(TestCase):
|
| 17 |
+
"""
|
| 18 |
+
Tests for edx and OpenEdX footer
|
| 19 |
+
"""
|
| 20 |
+
shard = 1
|
| 21 |
+
|
| 22 |
+
SOCIAL_MEDIA_NAMES = [
|
| 23 |
+
"facebook",
|
| 24 |
+
"google_plus",
|
| 25 |
+
"twitter",
|
| 26 |
+
"linkedin",
|
| 27 |
+
"tumblr",
|
| 28 |
+
"meetup",
|
| 29 |
+
"reddit",
|
| 30 |
+
"youtube",
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
SOCIAL_MEDIA_URLS = {
|
| 34 |
+
"facebook": "http://www.facebook.com/",
|
| 35 |
+
"google_plus": "https://plus.google.com/",
|
| 36 |
+
"twitter": "https://twitter.com/",
|
| 37 |
+
"linkedin": "http://www.linkedin.com/",
|
| 38 |
+
"tumblr": "http://www.tumblr.com/",
|
| 39 |
+
"meetup": "http://www.meetup.com/",
|
| 40 |
+
"reddit": "http://www.reddit.com/",
|
| 41 |
+
"youtube": "https://www.youtube.com/"
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
@with_comprehensive_theme("edx.org")
|
| 45 |
+
def test_edx_footer(self):
|
| 46 |
+
"""
|
| 47 |
+
Verify that the homepage, when accessed at edx.org, has the edX footer
|
| 48 |
+
"""
|
| 49 |
+
resp = self.client.get('/')
|
| 50 |
+
self.assertEqual(resp.status_code, 200)
|
| 51 |
+
self.assertContains(resp, 'footer-edx-v3')
|
| 52 |
+
|
| 53 |
+
def test_openedx_footer(self):
|
| 54 |
+
"""
|
| 55 |
+
Verify that the homepage, when accessed at something other than
|
| 56 |
+
edx.org, has the Open edX footer
|
| 57 |
+
"""
|
| 58 |
+
resp = self.client.get('/')
|
| 59 |
+
self.assertEqual(resp.status_code, 200)
|
| 60 |
+
self.assertContains(resp, 'footer-openedx')
|
| 61 |
+
|
| 62 |
+
@with_comprehensive_theme("edx.org")
|
| 63 |
+
@override_settings(
|
| 64 |
+
SOCIAL_MEDIA_FOOTER_NAMES=SOCIAL_MEDIA_NAMES,
|
| 65 |
+
SOCIAL_MEDIA_FOOTER_URLS=SOCIAL_MEDIA_URLS
|
| 66 |
+
)
|
| 67 |
+
def test_edx_footer_social_links(self):
|
| 68 |
+
resp = self.client.get('/')
|
| 69 |
+
for name, url in self.SOCIAL_MEDIA_URLS.iteritems():
|
| 70 |
+
self.assertContains(resp, url)
|
| 71 |
+
self.assertContains(resp, settings.SOCIAL_MEDIA_FOOTER_DISPLAY[name]['title'])
|
| 72 |
+
self.assertContains(resp, settings.SOCIAL_MEDIA_FOOTER_DISPLAY[name]['icon'])
|
pool/shard007/Python/0069835_app_lib.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Class to set App lib directory for current version of Python"""
|
| 2 |
+
# standard library
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class AppLib:
|
| 8 |
+
"""Set App Lib Directory"""
|
| 9 |
+
|
| 10 |
+
def __init__(self):
|
| 11 |
+
"""Initialize App properties."""
|
| 12 |
+
self._lib_directories = None
|
| 13 |
+
|
| 14 |
+
# All Python Version that will be searched
|
| 15 |
+
self.lib_major_version = f'lib_{sys.version_info.major}'
|
| 16 |
+
self.lib_minor_version = f'{self.lib_major_version}.{sys.version_info.minor}'
|
| 17 |
+
self.lib_micro_version = f'{self.lib_minor_version}.{sys.version_info.micro}'
|
| 18 |
+
|
| 19 |
+
def find_lib_directory(self) -> str:
|
| 20 |
+
"""Find the optimal lib directory."""
|
| 21 |
+
lib_directory = None
|
| 22 |
+
if self.lib_micro_version in self.lib_directories:
|
| 23 |
+
lib_directory = self.lib_micro_version
|
| 24 |
+
elif self.lib_minor_version in self.lib_directories:
|
| 25 |
+
lib_directory = self.lib_minor_version
|
| 26 |
+
elif self.lib_major_version in self.lib_directories:
|
| 27 |
+
lib_directory = self.lib_major_version
|
| 28 |
+
else:
|
| 29 |
+
for lv in [self.lib_micro_version, self.lib_minor_version, self.lib_major_version]:
|
| 30 |
+
for d in self.lib_directories:
|
| 31 |
+
if lv in d:
|
| 32 |
+
lib_directory = d
|
| 33 |
+
break
|
| 34 |
+
else:
|
| 35 |
+
continue
|
| 36 |
+
break
|
| 37 |
+
return lib_directory
|
| 38 |
+
|
| 39 |
+
@property
|
| 40 |
+
def lib_directories(self) -> list:
|
| 41 |
+
"""Return all "lib_" directories."""
|
| 42 |
+
if self._lib_directories is None:
|
| 43 |
+
self._lib_directories = []
|
| 44 |
+
app_path = os.getcwd()
|
| 45 |
+
contents = os.listdir(app_path)
|
| 46 |
+
for c in contents:
|
| 47 |
+
# ensure content starts with lib, is directory, and is readable
|
| 48 |
+
if c.startswith('lib') and os.path.isdir(c) and (os.access(c, os.R_OK)):
|
| 49 |
+
self._lib_directories.append(c)
|
| 50 |
+
return sorted(self._lib_directories, reverse=True)
|
| 51 |
+
|
| 52 |
+
def update_path(self) -> None:
|
| 53 |
+
"""Update sys path to ensure all required modules can be found.
|
| 54 |
+
|
| 55 |
+
All Apps must be able to access included modules, this method will ensure that the system
|
| 56 |
+
path has been updated to include the "cwd" and the proper "lib_" directories.
|
| 57 |
+
"""
|
| 58 |
+
lib_directory = self.find_lib_directory()
|
| 59 |
+
lib_latest = os.path.join(os.getcwd(), 'lib_latest')
|
| 60 |
+
|
| 61 |
+
# insert the appropriate lib_directory into system path if found, otherwise insert
|
| 62 |
+
# lib_latest directory into the system Path. This entry will be bumped to index 1
|
| 63 |
+
# after adding the current working directory.
|
| 64 |
+
if lib_directory is None:
|
| 65 |
+
lib_directory = lib_latest
|
| 66 |
+
sys.path.insert(0, os.path.join(os.getcwd(), lib_directory))
|
| 67 |
+
|
| 68 |
+
# insert the current working directory into the system Path for the App, ensuring that it is
|
| 69 |
+
# always the first entry in the list.
|
| 70 |
+
cwd = os.getcwd()
|
| 71 |
+
try:
|
| 72 |
+
sys.path.remove(cwd)
|
| 73 |
+
except ValueError:
|
| 74 |
+
pass
|
| 75 |
+
sys.path.insert(0, cwd)
|
pool/shard007/Python/0069849_oss_fs_impl.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
from pyftpdlib.filesystems import FilesystemError
|
| 3 |
+
import oss2
|
| 4 |
+
|
| 5 |
+
import oss_file_operation
|
| 6 |
+
import defaults
|
| 7 |
+
|
| 8 |
+
class OssFsImpl:
|
| 9 |
+
|
| 10 |
+
def __init__(self, bucket_name, endpoint, access_id, access_key):
|
| 11 |
+
self.bucket_name = bucket_name
|
| 12 |
+
self.endpoint = endpoint
|
| 13 |
+
self.access_id = access_id
|
| 14 |
+
self.access_key = access_key
|
| 15 |
+
|
| 16 |
+
self.bucket = oss2.Bucket(oss2.Auth(self.access_id, self.access_key), self.endpoint, self.bucket_name, app_name=defaults.app_name)
|
| 17 |
+
self.size_cache = {}
|
| 18 |
+
self.dir_cache = {}
|
| 19 |
+
|
| 20 |
+
def is_bucket(self, path):
|
| 21 |
+
phyPath = path.rstrip('/')
|
| 22 |
+
index = phyPath.rfind('/')
|
| 23 |
+
if index == 0 and not self.is_root(path):
|
| 24 |
+
return True
|
| 25 |
+
return False
|
| 26 |
+
|
| 27 |
+
def is_root(self, path):
|
| 28 |
+
return path == '/'
|
| 29 |
+
|
| 30 |
+
def get_oss_bucket_name(self, path):
|
| 31 |
+
if self.is_root(path):
|
| 32 |
+
return u'/'
|
| 33 |
+
phyPath = path.rstrip('/')
|
| 34 |
+
index = phyPath.find('/', 1)
|
| 35 |
+
if index <= 0:
|
| 36 |
+
return phyPath[1:]
|
| 37 |
+
else:
|
| 38 |
+
return phyPath[1:index]
|
| 39 |
+
|
| 40 |
+
def get_file_name(self, path):
|
| 41 |
+
if self.is_bucket(path):
|
| 42 |
+
return ""
|
| 43 |
+
if path == '/':
|
| 44 |
+
return u'/'
|
| 45 |
+
bucket = self.get_oss_bucket_name(path)
|
| 46 |
+
return path[len(bucket)+2:]
|
| 47 |
+
|
| 48 |
+
def normalize_separate_char(self, path):
|
| 49 |
+
normalized_path_name = path.replace('\\', '/')
|
| 50 |
+
return normalized_path_name
|
| 51 |
+
|
| 52 |
+
def get_bucket(self, path):
|
| 53 |
+
path = self.normalize_separate_char(path)
|
| 54 |
+
bucket_name = self.get_oss_bucket_name(path)
|
| 55 |
+
bucket = oss2.Bucket(oss2.Auth(self.access_id, self.access_key), self.endpoint, bucket_name, app_name=defaults.app_name)
|
| 56 |
+
return bucket
|
| 57 |
+
|
| 58 |
+
def get_object(self, path):
|
| 59 |
+
path = self.normalize_separate_char(path)
|
| 60 |
+
object = self.get_file_name(path)
|
| 61 |
+
return object
|
| 62 |
+
|
| 63 |
+
def get_file_operation_instance(self, path):
|
| 64 |
+
return oss_file_operation.OssFileOperation(self.get_bucket(path), self.get_object(path), self.size_cache, self.dir_cache)
|
| 65 |
+
|
| 66 |
+
def open_read(self, path):
|
| 67 |
+
return self.get_file_operation_instance(path).open_read()
|
| 68 |
+
|
| 69 |
+
def open_write(self, path):
|
| 70 |
+
return self.get_file_operation_instance(path)
|
| 71 |
+
|
| 72 |
+
def mkdir(self, path):
|
| 73 |
+
return self.get_file_operation_instance(path).mkdir()
|
| 74 |
+
|
| 75 |
+
def infopath(self, path):
|
| 76 |
+
return get_file_operation_instance(path).infopath()
|
| 77 |
+
|
| 78 |
+
def listdir(self, path):
|
| 79 |
+
return self.get_file_operation_instance(path).listdir()
|
| 80 |
+
|
| 81 |
+
def rmdir(self, path):
|
| 82 |
+
return self.get_file_operation_instance(path).rmdir()
|
| 83 |
+
|
| 84 |
+
def remove(self, path):
|
| 85 |
+
return self.get_file_operation_instance(path).remove()
|
| 86 |
+
|
| 87 |
+
def rename(self, path1, path2):
|
| 88 |
+
raise FilesystemError("method rename not implied")
|
| 89 |
+
|
| 90 |
+
def getsize(self, path):
|
| 91 |
+
return self.get_file_operation_instance(path).getsize()
|
| 92 |
+
|
| 93 |
+
def getmtime(self, path):
|
| 94 |
+
return self.get_file_operation_instance(path).getmtime()
|
| 95 |
+
|
| 96 |
+
def isfile(self, path):
|
| 97 |
+
return self.get_file_operation_instance(path).isfile()
|
| 98 |
+
|
| 99 |
+
def isdir(self, path):
|
| 100 |
+
path = self.normalize_separate_char(path)
|
| 101 |
+
if self.is_bucket(path):
|
| 102 |
+
return True
|
| 103 |
+
if self.is_root(path):
|
| 104 |
+
return True
|
| 105 |
+
return self.get_file_operation_instance(path).isdir()
|
| 106 |
+
def lexists(self, path):
|
| 107 |
+
return self.isfile(path) or self.isdir(path)
|