nwo
stringlengths
5
58
sha
stringlengths
40
40
path
stringlengths
5
172
language
stringclasses
1 value
identifier
stringlengths
1
100
parameters
stringlengths
2
3.5k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
21.5k
docstring
stringlengths
2
17k
docstring_summary
stringlengths
0
6.58k
docstring_tokens
sequence
function
stringlengths
35
55.6k
function_tokens
sequence
url
stringlengths
89
269
nodejs/quic
5baab3f3a05548d3b51bea98868412b08766e34d
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py
python
WinTool.ExecClCompile
(self, project_dir, selected_files)
return subprocess.call(cmd, shell=True, cwd=BASE_DIR)
Executed by msvs-ninja projects when the 'ClCompile' target is used to build selected C/C++ files.
Executed by msvs-ninja projects when the 'ClCompile' target is used to build selected C/C++ files.
[ "Executed", "by", "msvs", "-", "ninja", "projects", "when", "the", "ClCompile", "target", "is", "used", "to", "build", "selected", "C", "/", "C", "++", "files", "." ]
def ExecClCompile(self, project_dir, selected_files): """Executed by msvs-ninja projects when the 'ClCompile' target is used to build selected C/C++ files.""" project_dir = os.path.relpath(project_dir, BASE_DIR) selected_files = selected_files.split(';') ninja_targets = [os.path.join(project_dir, filename) + '^^' for filename in selected_files] cmd = ['ninja.exe'] cmd.extend(ninja_targets) return subprocess.call(cmd, shell=True, cwd=BASE_DIR)
[ "def", "ExecClCompile", "(", "self", ",", "project_dir", ",", "selected_files", ")", ":", "project_dir", "=", "os", ".", "path", ".", "relpath", "(", "project_dir", ",", "BASE_DIR", ")", "selected_files", "=", "selected_files", ".", "split", "(", "';'", ")", "ninja_targets", "=", "[", "os", ".", "path", ".", "join", "(", "project_dir", ",", "filename", ")", "+", "'^^'", "for", "filename", "in", "selected_files", "]", "cmd", "=", "[", "'ninja.exe'", "]", "cmd", ".", "extend", "(", "ninja_targets", ")", "return", "subprocess", ".", "call", "(", "cmd", ",", "shell", "=", "True", ",", "cwd", "=", "BASE_DIR", ")" ]
https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py#L315-L324
feross/Instant.fm
f084f7183a06a773bc22edd0e5c79451f21bf63a
server/utils.py
python
base36_10
(alpha_id)
return playlist_id
Converts a base 36 id (0-9a-z) to an integer
Converts a base 36 id (0-9a-z) to an integer
[ "Converts", "a", "base", "36", "id", "(", "0", "-", "9a", "-", "z", ")", "to", "an", "integer" ]
def base36_10(alpha_id): """Converts a base 36 id (0-9a-z) to an integer""" playlist_id = 0 index = 0 while index < len(alpha_id): char = alpha_id[index] if unicode.isdecimal(char): value = int(char) else: value = ord(char.lower()) - ord('a') + 10 playlist_id = playlist_id * 36 + value index += 1 return playlist_id
[ "def", "base36_10", "(", "alpha_id", ")", ":", "playlist_id", "=", "0", "index", "=", "0", "while", "index", "<", "len", "(", "alpha_id", ")", ":", "char", "=", "alpha_id", "[", "index", "]", "if", "unicode", ".", "isdecimal", "(", "char", ")", ":", "value", "=", "int", "(", "char", ")", "else", ":", "value", "=", "ord", "(", "char", ".", "lower", "(", ")", ")", "-", "ord", "(", "'a'", ")", "+", "10", "playlist_id", "=", "playlist_id", "*", "36", "+", "value", "index", "+=", "1", "return", "playlist_id" ]
https://github.com/feross/Instant.fm/blob/f084f7183a06a773bc22edd0e5c79451f21bf63a/server/utils.py#L16-L30
areski/django-audiofield
f7a36fd9772f1b35bc8b4f1985b3021000777b36
audiofield/fields.py
python
AudioField.formfield
(self, **kwargs)
return super(AudioField, self).formfield(**kwargs)
Specify form field and widget to be used on the forms
Specify form field and widget to be used on the forms
[ "Specify", "form", "field", "and", "widget", "to", "be", "used", "on", "the", "forms" ]
def formfield(self, **kwargs): '''Specify form field and widget to be used on the forms''' from audiofield.widgets import AdminAudioFileWidget from audiofield.forms import AudioFormField kwargs['widget'] = AdminAudioFileWidget kwargs['form_class'] = AudioFormField return super(AudioField, self).formfield(**kwargs)
[ "def", "formfield", "(", "self", ",", "*", "*", "kwargs", ")", ":", "from", "audiofield", ".", "widgets", "import", "AdminAudioFileWidget", "from", "audiofield", ".", "forms", "import", "AudioFormField", "kwargs", "[", "'widget'", "]", "=", "AdminAudioFileWidget", "kwargs", "[", "'form_class'", "]", "=", "AudioFormField", "return", "super", "(", "AudioField", ",", "self", ")", ".", "formfield", "(", "*", "*", "kwargs", ")" ]
https://github.com/areski/django-audiofield/blob/f7a36fd9772f1b35bc8b4f1985b3021000777b36/audiofield/fields.py#L256-L263
alaxli/ansible_ui
ea7a76e1de6d2aec3777c0182dd8cc3529c9ccd7
desktop/apps/ansible/elfinder/fields.py
python
ElfinderFormField.clean
(self, value)
return value
Override the default CharField validation to validate the ElfinderFile hash string before converting it to an ElfinderField object. Finally, return a cleaned ElfinderFile object.
Override the default CharField validation to validate the ElfinderFile hash string before converting it to an ElfinderField object. Finally, return a cleaned ElfinderFile object.
[ "Override", "the", "default", "CharField", "validation", "to", "validate", "the", "ElfinderFile", "hash", "string", "before", "converting", "it", "to", "an", "ElfinderField", "object", ".", "Finally", "return", "a", "cleaned", "ElfinderFile", "object", "." ]
def clean(self, value): """ Override the default CharField validation to validate the ElfinderFile hash string before converting it to an ElfinderField object. Finally, return a cleaned ElfinderFile object. """ self.validate(value) self.run_validators(value) value = self.to_python(value) return value
[ "def", "clean", "(", "self", ",", "value", ")", ":", "self", ".", "validate", "(", "value", ")", "self", ".", "run_validators", "(", "value", ")", "value", "=", "self", ".", "to_python", "(", "value", ")", "return", "value" ]
https://github.com/alaxli/ansible_ui/blob/ea7a76e1de6d2aec3777c0182dd8cc3529c9ccd7/desktop/apps/ansible/elfinder/fields.py#L100-L109
TeamvisionCorp/TeamVision
aa2a57469e430ff50cce21174d8f280efa0a83a7
distribute/0.0.5/build_shell/teamvision/teamvision/api/ci/viewmodel/vm_ci_task_queue.py
python
VM_CITaskQueue.__init__
(self,queue_id)
Constructor
Constructor
[ "Constructor" ]
def __init__(self,queue_id): ''' Constructor ''' self.queue_id=queue_id self.task_id=self.get_task_queue().TaskID self.task_name=self.get_task_name() self.run_uuid=self.get_task_queue().TaskUUID self.task_type=self.get_task_queue().TaskType
[ "def", "__init__", "(", "self", ",", "queue_id", ")", ":", "self", ".", "queue_id", "=", "queue_id", "self", ".", "task_id", "=", "self", ".", "get_task_queue", "(", ")", ".", "TaskID", "self", ".", "task_name", "=", "self", ".", "get_task_name", "(", ")", "self", ".", "run_uuid", "=", "self", ".", "get_task_queue", "(", ")", ".", "TaskUUID", "self", ".", "task_type", "=", "self", ".", "get_task_queue", "(", ")", ".", "TaskType" ]
https://github.com/TeamvisionCorp/TeamVision/blob/aa2a57469e430ff50cce21174d8f280efa0a83a7/distribute/0.0.5/build_shell/teamvision/teamvision/api/ci/viewmodel/vm_ci_task_queue.py#L18-L26
pyistanbul/dbpatterns
6936cfa3555bae9ef65296c7f31a6637c0ef5d54
web/dbpatterns/api/resources.py
python
MongoDBResource.get_collection
(self)
Encapsulates collection name.
Encapsulates collection name.
[ "Encapsulates", "collection", "name", "." ]
def get_collection(self): """ Encapsulates collection name. """ raise NotImplementedError("You should implement get_collection method.")
[ "def", "get_collection", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "\"You should implement get_collection method.\"", ")" ]
https://github.com/pyistanbul/dbpatterns/blob/6936cfa3555bae9ef65296c7f31a6637c0ef5d54/web/dbpatterns/api/resources.py#L22-L26
openwisp/openwisp-controller
0bfda7a28c86092f165b177c551c07babcb40630
openwisp_controller/geo/apps.py
python
GeoConfig._add_params_to_test_config
(self)
this methods adds the management fields of DeviceLocationInline to the parameters used in config.tests.test_admin.TestAdmin this hack is needed for the following reasons: - avoids breaking config.tests.test_admin.TestAdmin - avoids adding logic of geo app in config, this way config doesn't know anything about geo, keeping complexity down to a sane level
this methods adds the management fields of DeviceLocationInline to the parameters used in config.tests.test_admin.TestAdmin this hack is needed for the following reasons: - avoids breaking config.tests.test_admin.TestAdmin - avoids adding logic of geo app in config, this way config doesn't know anything about geo, keeping complexity down to a sane level
[ "this", "methods", "adds", "the", "management", "fields", "of", "DeviceLocationInline", "to", "the", "parameters", "used", "in", "config", ".", "tests", ".", "test_admin", ".", "TestAdmin", "this", "hack", "is", "needed", "for", "the", "following", "reasons", ":", "-", "avoids", "breaking", "config", ".", "tests", ".", "test_admin", ".", "TestAdmin", "-", "avoids", "adding", "logic", "of", "geo", "app", "in", "config", "this", "way", "config", "doesn", "t", "know", "anything", "about", "geo", "keeping", "complexity", "down", "to", "a", "sane", "level" ]
def _add_params_to_test_config(self): """ this methods adds the management fields of DeviceLocationInline to the parameters used in config.tests.test_admin.TestAdmin this hack is needed for the following reasons: - avoids breaking config.tests.test_admin.TestAdmin - avoids adding logic of geo app in config, this way config doesn't know anything about geo, keeping complexity down to a sane level """ from ..config.tests.test_admin import TestAdmin as TestConfigAdmin from .tests.test_admin_inline import TestAdminInline params = TestAdminInline._get_params() delete_keys = [] # delete unnecessary fields # leave only management fields for key in params.keys(): if '_FORMS' not in key: delete_keys.append(key) for key in delete_keys: del params[key] TestConfigAdmin._additional_params.update(params)
[ "def", "_add_params_to_test_config", "(", "self", ")", ":", "from", ".", ".", "config", ".", "tests", ".", "test_admin", "import", "TestAdmin", "as", "TestConfigAdmin", "from", ".", "tests", ".", "test_admin_inline", "import", "TestAdminInline", "params", "=", "TestAdminInline", ".", "_get_params", "(", ")", "delete_keys", "=", "[", "]", "# delete unnecessary fields", "# leave only management fields", "for", "key", "in", "params", ".", "keys", "(", ")", ":", "if", "'_FORMS'", "not", "in", "key", ":", "delete_keys", ".", "append", "(", "key", ")", "for", "key", "in", "delete_keys", ":", "del", "params", "[", "key", "]", "TestConfigAdmin", ".", "_additional_params", ".", "update", "(", "params", ")" ]
https://github.com/openwisp/openwisp-controller/blob/0bfda7a28c86092f165b177c551c07babcb40630/openwisp_controller/geo/apps.py#L27-L49
atom-community/ide-python
c046f9c2421713b34baa22648235541c5bb284fe
lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/_pydev_bundle/pydev_ipython_console_011.py
python
PyDevIPCompleter.__init__
(self, *args, **kwargs)
Create a Completer that reuses the advanced completion support of PyDev in addition to the completion support provided by IPython
Create a Completer that reuses the advanced completion support of PyDev in addition to the completion support provided by IPython
[ "Create", "a", "Completer", "that", "reuses", "the", "advanced", "completion", "support", "of", "PyDev", "in", "addition", "to", "the", "completion", "support", "provided", "by", "IPython" ]
def __init__(self, *args, **kwargs): """ Create a Completer that reuses the advanced completion support of PyDev in addition to the completion support provided by IPython """ IPCompleter.__init__(self, *args, **kwargs) # Use PyDev for python matches, see getCompletions below if self.python_matches in self.matchers: # `self.python_matches` matches attributes or global python names self.matchers.remove(self.python_matches)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "IPCompleter", ".", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "# Use PyDev for python matches, see getCompletions below", "if", "self", ".", "python_matches", "in", "self", ".", "matchers", ":", "# `self.python_matches` matches attributes or global python names", "self", ".", "matchers", ".", "remove", "(", "self", ".", "python_matches", ")" ]
https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/_pydev_bundle/pydev_ipython_console_011.py#L81-L88
catmaid/CATMAID
9f3312f2eacfc6fab48e4c6f1bd24672cc9c9ecf
django/applications/catmaid/control/user_evaluation.py
python
_evaluate_arbor
(user_id, skeleton_id, tree, reviews, relations, max_gap)
return epoch_ops
Split the arbor into review epochs and then evaluate each independently.
Split the arbor into review epochs and then evaluate each independently.
[ "Split", "the", "arbor", "into", "review", "epochs", "and", "then", "evaluate", "each", "independently", "." ]
def _evaluate_arbor(user_id, skeleton_id, tree, reviews, relations, max_gap) -> List: """ Split the arbor into review epochs and then evaluate each independently. """ epochs = _split_into_epochs(skeleton_id, tree, reviews, max_gap) epoch_ops = _evaluate_epochs(epochs, skeleton_id, tree, reviews, relations) return epoch_ops
[ "def", "_evaluate_arbor", "(", "user_id", ",", "skeleton_id", ",", "tree", ",", "reviews", ",", "relations", ",", "max_gap", ")", "->", "List", ":", "epochs", "=", "_split_into_epochs", "(", "skeleton_id", ",", "tree", ",", "reviews", ",", "max_gap", ")", "epoch_ops", "=", "_evaluate_epochs", "(", "epochs", ",", "skeleton_id", ",", "tree", ",", "reviews", ",", "relations", ")", "return", "epoch_ops" ]
https://github.com/catmaid/CATMAID/blob/9f3312f2eacfc6fab48e4c6f1bd24672cc9c9ecf/django/applications/catmaid/control/user_evaluation.py#L258-L262
ayojs/ayo
45a1c8cf6384f5bcc81d834343c3ed9d78b97df3
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.GetLdflags
(self, configname, product_dir, gyp_to_build_path, arch=None)
return ldflags
Returns flags that need to be passed to the linker. Args: configname: The name of the configuration to get ld flags for. product_dir: The directory where products such static and dynamic libraries are placed. This is added to the library search path. gyp_to_build_path: A function that converts paths relative to the current gyp file to paths relative to the build direcotry.
Returns flags that need to be passed to the linker.
[ "Returns", "flags", "that", "need", "to", "be", "passed", "to", "the", "linker", "." ]
def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None): """Returns flags that need to be passed to the linker. Args: configname: The name of the configuration to get ld flags for. product_dir: The directory where products such static and dynamic libraries are placed. This is added to the library search path. gyp_to_build_path: A function that converts paths relative to the current gyp file to paths relative to the build direcotry. """ self.configname = configname ldflags = [] # The xcode build is relative to a gyp file's directory, and OTHER_LDFLAGS # can contain entries that depend on this. Explicitly absolutify these. for ldflag in self._Settings().get('OTHER_LDFLAGS', []): ldflags.append(self._MapLinkerFlagFilename(ldflag, gyp_to_build_path)) if self._Test('DEAD_CODE_STRIPPING', 'YES', default='NO'): ldflags.append('-Wl,-dead_strip') if self._Test('PREBINDING', 'YES', default='NO'): ldflags.append('-Wl,-prebind') self._Appendf( ldflags, 'DYLIB_COMPATIBILITY_VERSION', '-compatibility_version %s') self._Appendf( ldflags, 'DYLIB_CURRENT_VERSION', '-current_version %s') self._AppendPlatformVersionMinFlags(ldflags) if 'SDKROOT' in self._Settings() and self._SdkPath(): ldflags.append('-isysroot ' + self._SdkPath()) for library_path in self._Settings().get('LIBRARY_SEARCH_PATHS', []): ldflags.append('-L' + gyp_to_build_path(library_path)) if 'ORDER_FILE' in self._Settings(): ldflags.append('-Wl,-order_file ' + '-Wl,' + gyp_to_build_path( self._Settings()['ORDER_FILE'])) if arch is not None: archs = [arch] else: assert self.configname archs = self.GetActiveArchs(self.configname) if len(archs) != 1: # TODO: Supporting fat binaries will be annoying. self._WarnUnimplemented('ARCHS') archs = ['i386'] ldflags.append('-arch ' + archs[0]) # Xcode adds the product directory by default. ldflags.append('-L' + product_dir) install_name = self.GetInstallName() if install_name and self.spec['type'] != 'loadable_module': ldflags.append('-install_name ' + install_name.replace(' ', r'\ ')) for rpath in self._Settings().get('LD_RUNPATH_SEARCH_PATHS', []): ldflags.append('-Wl,-rpath,' + rpath) sdk_root = self._SdkPath() if not sdk_root: sdk_root = '' config = self.spec['configurations'][self.configname] framework_dirs = config.get('mac_framework_dirs', []) for directory in framework_dirs: ldflags.append('-F' + directory.replace('$(SDKROOT)', sdk_root)) is_extension = self._IsIosAppExtension() or self._IsIosWatchKitExtension() if sdk_root and is_extension: # Adds the link flags for extensions. These flags are common for all # extensions and provide loader and main function. # These flags reflect the compilation options used by xcode to compile # extensions. ldflags.append('-lpkstart') if XcodeVersion() < '0900': ldflags.append(sdk_root + '/System/Library/PrivateFrameworks/PlugInKit.framework/PlugInKit') ldflags.append('-fapplication-extension') ldflags.append('-Xlinker -rpath ' '-Xlinker @executable_path/../../Frameworks') self._Appendf(ldflags, 'CLANG_CXX_LIBRARY', '-stdlib=%s') self.configname = None return ldflags
[ "def", "GetLdflags", "(", "self", ",", "configname", ",", "product_dir", ",", "gyp_to_build_path", ",", "arch", "=", "None", ")", ":", "self", ".", "configname", "=", "configname", "ldflags", "=", "[", "]", "# The xcode build is relative to a gyp file's directory, and OTHER_LDFLAGS", "# can contain entries that depend on this. Explicitly absolutify these.", "for", "ldflag", "in", "self", ".", "_Settings", "(", ")", ".", "get", "(", "'OTHER_LDFLAGS'", ",", "[", "]", ")", ":", "ldflags", ".", "append", "(", "self", ".", "_MapLinkerFlagFilename", "(", "ldflag", ",", "gyp_to_build_path", ")", ")", "if", "self", ".", "_Test", "(", "'DEAD_CODE_STRIPPING'", ",", "'YES'", ",", "default", "=", "'NO'", ")", ":", "ldflags", ".", "append", "(", "'-Wl,-dead_strip'", ")", "if", "self", ".", "_Test", "(", "'PREBINDING'", ",", "'YES'", ",", "default", "=", "'NO'", ")", ":", "ldflags", ".", "append", "(", "'-Wl,-prebind'", ")", "self", ".", "_Appendf", "(", "ldflags", ",", "'DYLIB_COMPATIBILITY_VERSION'", ",", "'-compatibility_version %s'", ")", "self", ".", "_Appendf", "(", "ldflags", ",", "'DYLIB_CURRENT_VERSION'", ",", "'-current_version %s'", ")", "self", ".", "_AppendPlatformVersionMinFlags", "(", "ldflags", ")", "if", "'SDKROOT'", "in", "self", ".", "_Settings", "(", ")", "and", "self", ".", "_SdkPath", "(", ")", ":", "ldflags", ".", "append", "(", "'-isysroot '", "+", "self", ".", "_SdkPath", "(", ")", ")", "for", "library_path", "in", "self", ".", "_Settings", "(", ")", ".", "get", "(", "'LIBRARY_SEARCH_PATHS'", ",", "[", "]", ")", ":", "ldflags", ".", "append", "(", "'-L'", "+", "gyp_to_build_path", "(", "library_path", ")", ")", "if", "'ORDER_FILE'", "in", "self", ".", "_Settings", "(", ")", ":", "ldflags", ".", "append", "(", "'-Wl,-order_file '", "+", "'-Wl,'", "+", "gyp_to_build_path", "(", "self", ".", "_Settings", "(", ")", "[", "'ORDER_FILE'", "]", ")", ")", "if", "arch", "is", "not", "None", ":", "archs", "=", "[", "arch", "]", "else", ":", "assert", "self", ".", "configname", "archs", "=", "self", ".", "GetActiveArchs", "(", "self", ".", "configname", ")", "if", "len", "(", "archs", ")", "!=", "1", ":", "# TODO: Supporting fat binaries will be annoying.", "self", ".", "_WarnUnimplemented", "(", "'ARCHS'", ")", "archs", "=", "[", "'i386'", "]", "ldflags", ".", "append", "(", "'-arch '", "+", "archs", "[", "0", "]", ")", "# Xcode adds the product directory by default.", "ldflags", ".", "append", "(", "'-L'", "+", "product_dir", ")", "install_name", "=", "self", ".", "GetInstallName", "(", ")", "if", "install_name", "and", "self", ".", "spec", "[", "'type'", "]", "!=", "'loadable_module'", ":", "ldflags", ".", "append", "(", "'-install_name '", "+", "install_name", ".", "replace", "(", "' '", ",", "r'\\ '", ")", ")", "for", "rpath", "in", "self", ".", "_Settings", "(", ")", ".", "get", "(", "'LD_RUNPATH_SEARCH_PATHS'", ",", "[", "]", ")", ":", "ldflags", ".", "append", "(", "'-Wl,-rpath,'", "+", "rpath", ")", "sdk_root", "=", "self", ".", "_SdkPath", "(", ")", "if", "not", "sdk_root", ":", "sdk_root", "=", "''", "config", "=", "self", ".", "spec", "[", "'configurations'", "]", "[", "self", ".", "configname", "]", "framework_dirs", "=", "config", ".", "get", "(", "'mac_framework_dirs'", ",", "[", "]", ")", "for", "directory", "in", "framework_dirs", ":", "ldflags", ".", "append", "(", "'-F'", "+", "directory", ".", "replace", "(", "'$(SDKROOT)'", ",", "sdk_root", ")", ")", "is_extension", "=", "self", ".", "_IsIosAppExtension", "(", ")", "or", "self", ".", "_IsIosWatchKitExtension", "(", ")", "if", "sdk_root", "and", "is_extension", ":", "# Adds the link flags for extensions. These flags are common for all", "# extensions and provide loader and main function.", "# These flags reflect the compilation options used by xcode to compile", "# extensions.", "ldflags", ".", "append", "(", "'-lpkstart'", ")", "if", "XcodeVersion", "(", ")", "<", "'0900'", ":", "ldflags", ".", "append", "(", "sdk_root", "+", "'/System/Library/PrivateFrameworks/PlugInKit.framework/PlugInKit'", ")", "ldflags", ".", "append", "(", "'-fapplication-extension'", ")", "ldflags", ".", "append", "(", "'-Xlinker -rpath '", "'-Xlinker @executable_path/../../Frameworks'", ")", "self", ".", "_Appendf", "(", "ldflags", ",", "'CLANG_CXX_LIBRARY'", ",", "'-stdlib=%s'", ")", "self", ".", "configname", "=", "None", "return", "ldflags" ]
https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L763-L851
agoravoting/agora-ciudadana
a7701035ea77d7a91baa9b5c2d0c05d91d1b4262
agora_site/agora_core/models/election.py
python
Election.get_mugshot_url
(self)
return settings.STATIC_URL + 'img/election_new_form_info.png'
Returns a default image representing the election for now
Returns a default image representing the election for now
[ "Returns", "a", "default", "image", "representing", "the", "election", "for", "now" ]
def get_mugshot_url(self): ''' Returns a default image representing the election for now ''' return settings.STATIC_URL + 'img/election_new_form_info.png'
[ "def", "get_mugshot_url", "(", "self", ")", ":", "return", "settings", ".", "STATIC_URL", "+", "'img/election_new_form_info.png'" ]
https://github.com/agoravoting/agora-ciudadana/blob/a7701035ea77d7a91baa9b5c2d0c05d91d1b4262/agora_site/agora_core/models/election.py#L292-L296
liftoff/GateOne
6ae1d01f7fe21e2703bdf982df7353e7bb81a500
gateone/applications/terminal/app_terminal.py
python
TerminalApplication.get_bell
(self)
Sends the bell sound data to the client in in the form of a data::URI.
Sends the bell sound data to the client in in the form of a data::URI.
[ "Sends", "the", "bell", "sound", "data", "to", "the", "client", "in", "in", "the", "form", "of", "a", "data", "::", "URI", "." ]
def get_bell(self): """ Sends the bell sound data to the client in in the form of a data::URI. """ bell_path = resource_filename( 'gateone.applications.terminal', '/static/bell.ogg') try: bell_data_uri = create_data_uri(bell_path) except (IOError, MimeTypeFail): # There's always the fallback self.term_log.error(_("Could not load bell: %s") % bell_path) bell_data_uri = resource_string( 'gateone.applications.terminal', '/static/fallback_bell.txt') mimetype = bell_data_uri.split(';')[0].split(':')[1] message = { 'terminal:load_bell': { 'data_uri': bell_data_uri, 'mimetype': mimetype } } self.write_message(json_encode(message))
[ "def", "get_bell", "(", "self", ")", ":", "bell_path", "=", "resource_filename", "(", "'gateone.applications.terminal'", ",", "'/static/bell.ogg'", ")", "try", ":", "bell_data_uri", "=", "create_data_uri", "(", "bell_path", ")", "except", "(", "IOError", ",", "MimeTypeFail", ")", ":", "# There's always the fallback", "self", ".", "term_log", ".", "error", "(", "_", "(", "\"Could not load bell: %s\"", ")", "%", "bell_path", ")", "bell_data_uri", "=", "resource_string", "(", "'gateone.applications.terminal'", ",", "'/static/fallback_bell.txt'", ")", "mimetype", "=", "bell_data_uri", ".", "split", "(", "';'", ")", "[", "0", "]", ".", "split", "(", "':'", ")", "[", "1", "]", "message", "=", "{", "'terminal:load_bell'", ":", "{", "'data_uri'", ":", "bell_data_uri", ",", "'mimetype'", ":", "mimetype", "}", "}", "self", ".", "write_message", "(", "json_encode", "(", "message", ")", ")" ]
https://github.com/liftoff/GateOne/blob/6ae1d01f7fe21e2703bdf982df7353e7bb81a500/gateone/applications/terminal/app_terminal.py#L1895-L1913
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
product/ERP5/Document/BusinessTemplate.py
python
BusinessTemplate.getShortRevision
(self)
return r and r[:5]
Returned a shortened revision
Returned a shortened revision
[ "Returned", "a", "shortened", "revision" ]
def getShortRevision(self): """Returned a shortened revision""" r = self.getRevision() return r and r[:5]
[ "def", "getShortRevision", "(", "self", ")", ":", "r", "=", "self", ".", "getRevision", "(", ")", "return", "r", "and", "r", "[", ":", "5", "]" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ERP5/Document/BusinessTemplate.py#L5157-L5160
IonicChina/ioniclub
208d5298939672ef44076bb8a7e8e6df5278e286
node_modules/gulp-sass/node_modules/node-sass/node_modules/pangyp/gyp/tools/graphviz.py
python
WriteGraph
(edges)
Print a graphviz graph to stdout. |edges| is a map of target to a list of other targets it depends on.
Print a graphviz graph to stdout. |edges| is a map of target to a list of other targets it depends on.
[ "Print", "a", "graphviz", "graph", "to", "stdout", ".", "|edges|", "is", "a", "map", "of", "target", "to", "a", "list", "of", "other", "targets", "it", "depends", "on", "." ]
def WriteGraph(edges): """Print a graphviz graph to stdout. |edges| is a map of target to a list of other targets it depends on.""" # Bucket targets by file. files = collections.defaultdict(list) for src, dst in edges.items(): build_file, target_name, toolset = ParseTarget(src) files[build_file].append(src) print 'digraph D {' print ' fontsize=8' # Used by subgraphs. print ' node [fontsize=8]' # Output nodes by file. We must first write out each node within # its file grouping before writing out any edges that may refer # to those nodes. for filename, targets in files.items(): if len(targets) == 1: # If there's only one node for this file, simplify # the display by making it a box without an internal node. target = targets[0] build_file, target_name, toolset = ParseTarget(target) print ' "%s" [shape=box, label="%s\\n%s"]' % (target, filename, target_name) else: # Group multiple nodes together in a subgraph. print ' subgraph "cluster_%s" {' % filename print ' label = "%s"' % filename for target in targets: build_file, target_name, toolset = ParseTarget(target) print ' "%s" [label="%s"]' % (target, target_name) print ' }' # Now that we've placed all the nodes within subgraphs, output all # the edges between nodes. for src, dsts in edges.items(): for dst in dsts: print ' "%s" -> "%s"' % (src, dst) print '}'
[ "def", "WriteGraph", "(", "edges", ")", ":", "# Bucket targets by file.", "files", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "src", ",", "dst", "in", "edges", ".", "items", "(", ")", ":", "build_file", ",", "target_name", ",", "toolset", "=", "ParseTarget", "(", "src", ")", "files", "[", "build_file", "]", ".", "append", "(", "src", ")", "print", "'digraph D {'", "print", "' fontsize=8'", "# Used by subgraphs.", "print", "' node [fontsize=8]'", "# Output nodes by file. We must first write out each node within", "# its file grouping before writing out any edges that may refer", "# to those nodes.", "for", "filename", ",", "targets", "in", "files", ".", "items", "(", ")", ":", "if", "len", "(", "targets", ")", "==", "1", ":", "# If there's only one node for this file, simplify", "# the display by making it a box without an internal node.", "target", "=", "targets", "[", "0", "]", "build_file", ",", "target_name", ",", "toolset", "=", "ParseTarget", "(", "target", ")", "print", "' \"%s\" [shape=box, label=\"%s\\\\n%s\"]'", "%", "(", "target", ",", "filename", ",", "target_name", ")", "else", ":", "# Group multiple nodes together in a subgraph.", "print", "' subgraph \"cluster_%s\" {'", "%", "filename", "print", "' label = \"%s\"'", "%", "filename", "for", "target", "in", "targets", ":", "build_file", ",", "target_name", ",", "toolset", "=", "ParseTarget", "(", "target", ")", "print", "' \"%s\" [label=\"%s\"]'", "%", "(", "target", ",", "target_name", ")", "print", "' }'", "# Now that we've placed all the nodes within subgraphs, output all", "# the edges between nodes.", "for", "src", ",", "dsts", "in", "edges", ".", "items", "(", ")", ":", "for", "dst", "in", "dsts", ":", "print", "' \"%s\" -> \"%s\"'", "%", "(", "src", ",", "dst", ")", "print", "'}'" ]
https://github.com/IonicChina/ioniclub/blob/208d5298939672ef44076bb8a7e8e6df5278e286/node_modules/gulp-sass/node_modules/node-sass/node_modules/pangyp/gyp/tools/graphviz.py#L43-L83
hotosm/tasking-manager
1a7b02c6ccd431029a96d709d4d786c83cb37f5e
backend/services/project_admin_service.py
python
ProjectAdminService.get_projects_for_admin
( admin_id: int, preferred_locale: str, search_dto: ProjectSearchDTO )
return Project.get_projects_for_admin(admin_id, preferred_locale, search_dto)
Get all projects for provided admin
Get all projects for provided admin
[ "Get", "all", "projects", "for", "provided", "admin" ]
def get_projects_for_admin( admin_id: int, preferred_locale: str, search_dto: ProjectSearchDTO ): """ Get all projects for provided admin """ return Project.get_projects_for_admin(admin_id, preferred_locale, search_dto)
[ "def", "get_projects_for_admin", "(", "admin_id", ":", "int", ",", "preferred_locale", ":", "str", ",", "search_dto", ":", "ProjectSearchDTO", ")", ":", "return", "Project", ".", "get_projects_for_admin", "(", "admin_id", ",", "preferred_locale", ",", "search_dto", ")" ]
https://github.com/hotosm/tasking-manager/blob/1a7b02c6ccd431029a96d709d4d786c83cb37f5e/backend/services/project_admin_service.py#L268-L272
carlosperate/ardublockly
04fa48273b5651386d0ef1ce6dd446795ffc2594
ardublocklyserver/compilersettings.py
python
ServerCompilerSettings.__new__
(cls, settings_dir=None, *args, **kwargs)
return cls.__singleton_instance
Create or returning the singleton instance. The argument settings_file_dir is only processed on first initialisation, and any future calls to the constructor will returned the already initialised instance with a set settings_file_dir.
Create or returning the singleton instance.
[ "Create", "or", "returning", "the", "singleton", "instance", "." ]
def __new__(cls, settings_dir=None, *args, **kwargs): """Create or returning the singleton instance. The argument settings_file_dir is only processed on first initialisation, and any future calls to the constructor will returned the already initialised instance with a set settings_file_dir. """ if not cls.__singleton_instance: # Create the singleton instance cls.__singleton_instance =\ super(ServerCompilerSettings, cls).__new__( cls, *args, **kwargs) # Initialise the instance, defaults if file not found cls.__singleton_instance.__initialise(settings_dir) return cls.__singleton_instance
[ "def", "__new__", "(", "cls", ",", "settings_dir", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "cls", ".", "__singleton_instance", ":", "# Create the singleton instance", "cls", ".", "__singleton_instance", "=", "super", "(", "ServerCompilerSettings", ",", "cls", ")", ".", "__new__", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", "# Initialise the instance, defaults if file not found", "cls", ".", "__singleton_instance", ".", "__initialise", "(", "settings_dir", ")", "return", "cls", ".", "__singleton_instance" ]
https://github.com/carlosperate/ardublockly/blob/04fa48273b5651386d0ef1ce6dd446795ffc2594/ardublocklyserver/compilersettings.py#L80-L94
quantifiedcode/quantifiedcode
cafc8b99d56a5e51820421af5d77be8b736ab03d
quantifiedcode/backend/tasks/periodic.py
python
analyze_pending_project
()
Get all projects that are marked for analysis and sort them by priority and request date. Then go through the list and check if the project has been recently analyzed, if not, analyze the first project.
Get all projects that are marked for analysis and sort them by priority and request date. Then go through the list and check if the project has been recently analyzed, if not, analyze the first project.
[ "Get", "all", "projects", "that", "are", "marked", "for", "analysis", "and", "sort", "them", "by", "priority", "and", "request", "date", ".", "Then", "go", "through", "the", "list", "and", "check", "if", "the", "project", "has", "been", "recently", "analyzed", "if", "not", "analyze", "the", "first", "project", "." ]
def analyze_pending_project(): """ Get all projects that are marked for analysis and sort them by priority and request date. Then go through the list and check if the project has been recently analyzed, if not, analyze the first project. """ logger.debug("Retrieving projects pending analysis...") pending_projects_query = { '$and': [ {'analyze': True}, {'$or': [ {'deleted': {'$exists': False}}, {'deleted': False} ]} ] } pending_projects = backend.filter(Project, pending_projects_query) pending_projects.sort([['analysis_priority', -1], ['analysis_requested_at', 1]]).limit(100) timestamp = datetime.datetime.now() max_allowed_runtime = datetime.timedelta(minutes=120) for pending_project in pending_projects: # skip projects currently being analyzed unless the analysis has been running for too long if (pending_project.analysis_status == pending_project.AnalysisStatus.in_progress and timestamp - pending_project.analyzed_at < max_allowed_runtime): continue # move the project back in the queue with backend.transaction(): backend.update(pending_project, {'analysis_requested_at': datetime.datetime.now()}) analyze_project(pending_project.pk, task_id=analyze_pending_project.request.id) break
[ "def", "analyze_pending_project", "(", ")", ":", "logger", ".", "debug", "(", "\"Retrieving projects pending analysis...\"", ")", "pending_projects_query", "=", "{", "'$and'", ":", "[", "{", "'analyze'", ":", "True", "}", ",", "{", "'$or'", ":", "[", "{", "'deleted'", ":", "{", "'$exists'", ":", "False", "}", "}", ",", "{", "'deleted'", ":", "False", "}", "]", "}", "]", "}", "pending_projects", "=", "backend", ".", "filter", "(", "Project", ",", "pending_projects_query", ")", "pending_projects", ".", "sort", "(", "[", "[", "'analysis_priority'", ",", "-", "1", "]", ",", "[", "'analysis_requested_at'", ",", "1", "]", "]", ")", ".", "limit", "(", "100", ")", "timestamp", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "max_allowed_runtime", "=", "datetime", ".", "timedelta", "(", "minutes", "=", "120", ")", "for", "pending_project", "in", "pending_projects", ":", "# skip projects currently being analyzed unless the analysis has been running for too long", "if", "(", "pending_project", ".", "analysis_status", "==", "pending_project", ".", "AnalysisStatus", ".", "in_progress", "and", "timestamp", "-", "pending_project", ".", "analyzed_at", "<", "max_allowed_runtime", ")", ":", "continue", "# move the project back in the queue", "with", "backend", ".", "transaction", "(", ")", ":", "backend", ".", "update", "(", "pending_project", ",", "{", "'analysis_requested_at'", ":", "datetime", ".", "datetime", ".", "now", "(", ")", "}", ")", "analyze_project", "(", "pending_project", ".", "pk", ",", "task_id", "=", "analyze_pending_project", ".", "request", ".", "id", ")", "break" ]
https://github.com/quantifiedcode/quantifiedcode/blob/cafc8b99d56a5e51820421af5d77be8b736ab03d/quantifiedcode/backend/tasks/periodic.py#L56-L88
atom-community/ide-python
c046f9c2421713b34baa22648235541c5bb284fe
dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/debug.py
python
Debug._notify_exit_process
(self, event)
return bCallHandler1 and bCallHandler2
Notify the termination of a process. @warning: This method is meant to be used internally by the debugger. @type event: L{ExitProcessEvent} @param event: Exit process event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise.
Notify the termination of a process.
[ "Notify", "the", "termination", "of", "a", "process", "." ]
def _notify_exit_process(self, event): """ Notify the termination of a process. @warning: This method is meant to be used internally by the debugger. @type event: L{ExitProcessEvent} @param event: Exit process event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ bCallHandler1 = _BreakpointContainer._notify_exit_process(self, event) bCallHandler2 = self.system._notify_exit_process(event) try: self.detach( event.get_pid() ) except WindowsError: e = sys.exc_info()[1] if e.winerror != win32.ERROR_INVALID_PARAMETER: warnings.warn( "Failed to detach from dead process, reason: %s" % str(e), RuntimeWarning) except Exception: e = sys.exc_info()[1] warnings.warn( "Failed to detach from dead process, reason: %s" % str(e), RuntimeWarning) return bCallHandler1 and bCallHandler2
[ "def", "_notify_exit_process", "(", "self", ",", "event", ")", ":", "bCallHandler1", "=", "_BreakpointContainer", ".", "_notify_exit_process", "(", "self", ",", "event", ")", "bCallHandler2", "=", "self", ".", "system", ".", "_notify_exit_process", "(", "event", ")", "try", ":", "self", ".", "detach", "(", "event", ".", "get_pid", "(", ")", ")", "except", "WindowsError", ":", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "e", ".", "winerror", "!=", "win32", ".", "ERROR_INVALID_PARAMETER", ":", "warnings", ".", "warn", "(", "\"Failed to detach from dead process, reason: %s\"", "%", "str", "(", "e", ")", ",", "RuntimeWarning", ")", "except", "Exception", ":", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "warnings", ".", "warn", "(", "\"Failed to detach from dead process, reason: %s\"", "%", "str", "(", "e", ")", ",", "RuntimeWarning", ")", "return", "bCallHandler1", "and", "bCallHandler2" ]
https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/debug.py#L1403-L1432
tum-pbs/PhiFlow
31d9944f4f26e56358dd73fa797dde567b6334b0
phi/geom/_sphere.py
python
Sphere.approximate_signed_distance
(self, location)
return math.min(distance - self.radius, self.shape.instance)
Computes the exact distance from location to the closest point on the sphere. Very close to the sphere center, the distance takes a constant value. Args: location: float tensor of shape (batch_size, ..., rank) Returns: float tensor of shape (*location.shape[:-1], 1).
Computes the exact distance from location to the closest point on the sphere. Very close to the sphere center, the distance takes a constant value.
[ "Computes", "the", "exact", "distance", "from", "location", "to", "the", "closest", "point", "on", "the", "sphere", ".", "Very", "close", "to", "the", "sphere", "center", "the", "distance", "takes", "a", "constant", "value", "." ]
def approximate_signed_distance(self, location): """ Computes the exact distance from location to the closest point on the sphere. Very close to the sphere center, the distance takes a constant value. Args: location: float tensor of shape (batch_size, ..., rank) Returns: float tensor of shape (*location.shape[:-1], 1). """ distance_squared = math.vec_squared(location - self.center) distance_squared = math.maximum(distance_squared, self.radius * 1e-2) # Prevent infinite spatial_gradient at sphere center distance = math.sqrt(distance_squared) return math.min(distance - self.radius, self.shape.instance)
[ "def", "approximate_signed_distance", "(", "self", ",", "location", ")", ":", "distance_squared", "=", "math", ".", "vec_squared", "(", "location", "-", "self", ".", "center", ")", "distance_squared", "=", "math", ".", "maximum", "(", "distance_squared", ",", "self", ".", "radius", "*", "1e-2", ")", "# Prevent infinite spatial_gradient at sphere center", "distance", "=", "math", ".", "sqrt", "(", "distance_squared", ")", "return", "math", ".", "min", "(", "distance", "-", "self", ".", "radius", ",", "self", ".", "shape", ".", "instance", ")" ]
https://github.com/tum-pbs/PhiFlow/blob/31d9944f4f26e56358dd73fa797dde567b6334b0/phi/geom/_sphere.py#L45-L60
mdipierro/web2py-appliances
f97658293d51519e5f06e1ed503ee85f8154fcf3
ModelLessApp/modules/plugin_ckeditor.py
python
CKEditor.edit_in_place
(self, selector, url)
return XML( """ %(javascript)s <script type="text/javascript"> jQuery(function() { jQuery('%(selector)s').ckeip({ e_url: '%(url)s', data: {'object': jQuery('%(selector)s').attr('data-object'), 'id': jQuery('%(selector)s').attr('data-id')}, ckeditor_config: ckeditor_config(), }); }); </script> """ % dict( javascript=javascript, selector=selector, url=url, ) )
Creates an instance of CKEditor that will edit selected HTML elements in place and provide AJAX saving capabilities. To start editing, the user will need to double click on one of the matched selectors. Requires a URL to return saved data to. The data will be stored in request.vars.content. NOTE: This should not be used for multi-tenant applications or where there is a possibility a malicious user could tamper with the variables.
Creates an instance of CKEditor that will edit selected HTML elements in place and provide AJAX saving capabilities. To start editing, the user will need to double click on one of the matched selectors.
[ "Creates", "an", "instance", "of", "CKEditor", "that", "will", "edit", "selected", "HTML", "elements", "in", "place", "and", "provide", "AJAX", "saving", "capabilities", ".", "To", "start", "editing", "the", "user", "will", "need", "to", "double", "click", "on", "one", "of", "the", "matched", "selectors", "." ]
def edit_in_place(self, selector, url): """ Creates an instance of CKEditor that will edit selected HTML elements in place and provide AJAX saving capabilities. To start editing, the user will need to double click on one of the matched selectors. Requires a URL to return saved data to. The data will be stored in request.vars.content. NOTE: This should not be used for multi-tenant applications or where there is a possibility a malicious user could tamper with the variables. """ javascript = self.load() return XML( """ %(javascript)s <script type="text/javascript"> jQuery(function() { jQuery('%(selector)s').ckeip({ e_url: '%(url)s', data: {'object': jQuery('%(selector)s').attr('data-object'), 'id': jQuery('%(selector)s').attr('data-id')}, ckeditor_config: ckeditor_config(), }); }); </script> """ % dict( javascript=javascript, selector=selector, url=url, ) )
[ "def", "edit_in_place", "(", "self", ",", "selector", ",", "url", ")", ":", "javascript", "=", "self", ".", "load", "(", ")", "return", "XML", "(", "\"\"\"\n %(javascript)s\n <script type=\"text/javascript\">\n jQuery(function() {\n jQuery('%(selector)s').ckeip({\n e_url: '%(url)s',\n data: {'object': jQuery('%(selector)s').attr('data-object'),\n 'id': jQuery('%(selector)s').attr('data-id')},\n ckeditor_config: ckeditor_config(),\n });\n });\n </script>\n \"\"\"", "%", "dict", "(", "javascript", "=", "javascript", ",", "selector", "=", "selector", ",", "url", "=", "url", ",", ")", ")" ]
https://github.com/mdipierro/web2py-appliances/blob/f97658293d51519e5f06e1ed503ee85f8154fcf3/ModelLessApp/modules/plugin_ckeditor.py#L89-L121
odoo/odoo
8de8c196a137f4ebbf67d7c7c83fee36f873f5c8
addons/stock/models/stock_move.py
python
StockMove._get_lang
(self)
return self.picking_id.partner_id.lang or self.partner_id.lang or self.env.user.lang
Determine language to use for translated description
Determine language to use for translated description
[ "Determine", "language", "to", "use", "for", "translated", "description" ]
def _get_lang(self): """Determine language to use for translated description""" return self.picking_id.partner_id.lang or self.partner_id.lang or self.env.user.lang
[ "def", "_get_lang", "(", "self", ")", ":", "return", "self", ".", "picking_id", ".", "partner_id", ".", "lang", "or", "self", ".", "partner_id", ".", "lang", "or", "self", ".", "env", ".", "user", ".", "lang" ]
https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/addons/stock/models/stock_move.py#L1766-L1768
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/closured/lib/python2.7/sysconfig.py
python
_parse_makefile
(filename, vars=None)
return vars
Parse a Makefile-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary.
Parse a Makefile-style file.
[ "Parse", "a", "Makefile", "-", "style", "file", "." ]
def _parse_makefile(filename, vars=None): """Parse a Makefile-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ import re # Regexes needed for parsing Makefile (and similar syntaxes, # like old-style Setup files). _variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)") _findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)") _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}") if vars is None: vars = {} done = {} notdone = {} with open(filename) as f: lines = f.readlines() for line in lines: if line.startswith('#') or line.strip() == '': continue m = _variable_rx.match(line) if m: n, v = m.group(1, 2) v = v.strip() # `$$' is a literal `$' in make tmpv = v.replace('$$', '') if "$" in tmpv: notdone[n] = v else: try: v = int(v) except ValueError: # insert literal `$' done[n] = v.replace('$$', '$') else: done[n] = v # do variable interpolation here while notdone: for name in notdone.keys(): value = notdone[name] m = _findvar1_rx.search(value) or _findvar2_rx.search(value) if m: n = m.group(1) found = True if n in done: item = str(done[n]) elif n in notdone: # get it on a subsequent round found = False elif n in os.environ: # do it like make: fall back to environment item = os.environ[n] else: done[n] = item = "" if found: after = value[m.end():] value = value[:m.start()] + item + after if "$" in after: notdone[name] = value else: try: value = int(value) except ValueError: done[name] = value.strip() else: done[name] = value del notdone[name] else: # bogus variable reference; just drop it since we can't deal del notdone[name] # strip spurious spaces for k, v in done.items(): if isinstance(v, str): done[k] = v.strip() # save the results in the global dictionary vars.update(done) return vars
[ "def", "_parse_makefile", "(", "filename", ",", "vars", "=", "None", ")", ":", "import", "re", "# Regexes needed for parsing Makefile (and similar syntaxes,", "# like old-style Setup files).", "_variable_rx", "=", "re", ".", "compile", "(", "\"([a-zA-Z][a-zA-Z0-9_]+)\\s*=\\s*(.*)\"", ")", "_findvar1_rx", "=", "re", ".", "compile", "(", "r\"\\$\\(([A-Za-z][A-Za-z0-9_]*)\\)\"", ")", "_findvar2_rx", "=", "re", ".", "compile", "(", "r\"\\${([A-Za-z][A-Za-z0-9_]*)}\"", ")", "if", "vars", "is", "None", ":", "vars", "=", "{", "}", "done", "=", "{", "}", "notdone", "=", "{", "}", "with", "open", "(", "filename", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "for", "line", "in", "lines", ":", "if", "line", ".", "startswith", "(", "'#'", ")", "or", "line", ".", "strip", "(", ")", "==", "''", ":", "continue", "m", "=", "_variable_rx", ".", "match", "(", "line", ")", "if", "m", ":", "n", ",", "v", "=", "m", ".", "group", "(", "1", ",", "2", ")", "v", "=", "v", ".", "strip", "(", ")", "# `$$' is a literal `$' in make", "tmpv", "=", "v", ".", "replace", "(", "'$$'", ",", "''", ")", "if", "\"$\"", "in", "tmpv", ":", "notdone", "[", "n", "]", "=", "v", "else", ":", "try", ":", "v", "=", "int", "(", "v", ")", "except", "ValueError", ":", "# insert literal `$'", "done", "[", "n", "]", "=", "v", ".", "replace", "(", "'$$'", ",", "'$'", ")", "else", ":", "done", "[", "n", "]", "=", "v", "# do variable interpolation here", "while", "notdone", ":", "for", "name", "in", "notdone", ".", "keys", "(", ")", ":", "value", "=", "notdone", "[", "name", "]", "m", "=", "_findvar1_rx", ".", "search", "(", "value", ")", "or", "_findvar2_rx", ".", "search", "(", "value", ")", "if", "m", ":", "n", "=", "m", ".", "group", "(", "1", ")", "found", "=", "True", "if", "n", "in", "done", ":", "item", "=", "str", "(", "done", "[", "n", "]", ")", "elif", "n", "in", "notdone", ":", "# get it on a subsequent round", "found", "=", "False", "elif", "n", "in", "os", ".", "environ", ":", "# do it like make: fall back to environment", "item", "=", "os", ".", "environ", "[", "n", "]", "else", ":", "done", "[", "n", "]", "=", "item", "=", "\"\"", "if", "found", ":", "after", "=", "value", "[", "m", ".", "end", "(", ")", ":", "]", "value", "=", "value", "[", ":", "m", ".", "start", "(", ")", "]", "+", "item", "+", "after", "if", "\"$\"", "in", "after", ":", "notdone", "[", "name", "]", "=", "value", "else", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "ValueError", ":", "done", "[", "name", "]", "=", "value", ".", "strip", "(", ")", "else", ":", "done", "[", "name", "]", "=", "value", "del", "notdone", "[", "name", "]", "else", ":", "# bogus variable reference; just drop it since we can't deal", "del", "notdone", "[", "name", "]", "# strip spurious spaces", "for", "k", ",", "v", "in", "done", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "str", ")", ":", "done", "[", "k", "]", "=", "v", ".", "strip", "(", ")", "# save the results in the global dictionary", "vars", ".", "update", "(", "done", ")", "return", "vars" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/sysconfig.py#L185-L268
wotermelon/toJump
3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f
lib/win/systrace/catapult/third_party/pyserial/serial/urlhandler/protocol_loop.py
python
LoopbackSerial._reconfigurePort
(self)
Set communication parameters on opened port. for the loop:// protocol all settings are ignored!
Set communication parameters on opened port. for the loop:// protocol all settings are ignored!
[ "Set", "communication", "parameters", "on", "opened", "port", ".", "for", "the", "loop", ":", "//", "protocol", "all", "settings", "are", "ignored!" ]
def _reconfigurePort(self): """Set communication parameters on opened port. for the loop:// protocol all settings are ignored!""" # not that's it of any real use, but it helps in the unit tests if not isinstance(self._baudrate, (int, long)) or not 0 < self._baudrate < 2**32: raise ValueError("invalid baudrate: %r" % (self._baudrate)) if self.logger: self.logger.info('_reconfigurePort()')
[ "def", "_reconfigurePort", "(", "self", ")", ":", "# not that's it of any real use, but it helps in the unit tests", "if", "not", "isinstance", "(", "self", ".", "_baudrate", ",", "(", "int", ",", "long", ")", ")", "or", "not", "0", "<", "self", ".", "_baudrate", "<", "2", "**", "32", ":", "raise", "ValueError", "(", "\"invalid baudrate: %r\"", "%", "(", "self", ".", "_baudrate", ")", ")", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "'_reconfigurePort()'", ")" ]
https://github.com/wotermelon/toJump/blob/3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f/lib/win/systrace/catapult/third_party/pyserial/serial/urlhandler/protocol_loop.py#L65-L72
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
product/ZLDAPConnection/ZLDAP.py
python
ZLDAPConnection.tpc_finish
(self, *ignored)
really really commit and DON'T FAIL
really really commit and DON'T FAIL
[ "really", "really", "commit", "and", "DON", "T", "FAIL" ]
def tpc_finish(self, *ignored): " really really commit and DON'T FAIL " oko=self._v_okobjects self._isCommitting=1 d=getattr(self,'_v_delete',[]) for deldn in d: self._deleteEntry(deldn) self._v_delete=[] for o in oko: try: if o._isDeleted: pass # we shouldn't need to do anything now that # the mass delete has happened elif o._isNew: self._addEntry(o.dn, o._data.items()) o._isNew=0 del self._v_add[o.dn] else: o._modify() o._registered=0 except: pass #XXX We should log errors here del self._v_okobjects del self._isCommitting self.GetConnection().destroy_cache()
[ "def", "tpc_finish", "(", "self", ",", "*", "ignored", ")", ":", "oko", "=", "self", ".", "_v_okobjects", "self", ".", "_isCommitting", "=", "1", "d", "=", "getattr", "(", "self", ",", "'_v_delete'", ",", "[", "]", ")", "for", "deldn", "in", "d", ":", "self", ".", "_deleteEntry", "(", "deldn", ")", "self", ".", "_v_delete", "=", "[", "]", "for", "o", "in", "oko", ":", "try", ":", "if", "o", ".", "_isDeleted", ":", "pass", "# we shouldn't need to do anything now that", "# the mass delete has happened", "elif", "o", ".", "_isNew", ":", "self", ".", "_addEntry", "(", "o", ".", "dn", ",", "o", ".", "_data", ".", "items", "(", ")", ")", "o", ".", "_isNew", "=", "0", "del", "self", ".", "_v_add", "[", "o", ".", "dn", "]", "else", ":", "o", ".", "_modify", "(", ")", "o", ".", "_registered", "=", "0", "except", ":", "pass", "#XXX We should log errors here", "del", "self", ".", "_v_okobjects", "del", "self", ".", "_isCommitting", "self", ".", "GetConnection", "(", ")", ".", "destroy_cache", "(", ")" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ZLDAPConnection/ZLDAP.py#L153-L180
TeamvisionCorp/TeamVision
aa2a57469e430ff50cce21174d8f280efa0a83a7
distribute/0.0.4/build_shell/teamvision/teamvision/productquality/views/bugreportview.py
python
index_list
(request)
return render_to_response('bugreport/bugreportindex.html',context_instance=RequestContext(request))
index page
index page
[ "index", "page" ]
def index_list(request): ''' index page''' return render_to_response('bugreport/bugreportindex.html',context_instance=RequestContext(request))
[ "def", "index_list", "(", "request", ")", ":", "return", "render_to_response", "(", "'bugreport/bugreportindex.html'", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
https://github.com/TeamvisionCorp/TeamVision/blob/aa2a57469e430ff50cce21174d8f280efa0a83a7/distribute/0.0.4/build_shell/teamvision/teamvision/productquality/views/bugreportview.py#L17-L19
scottgchin/delta5_race_timer
fe4e0f46307b05c9384f3124189edc402d812ade
src/delta5server/server.py
python
disconnect_handler
()
Emit disconnect event.
Emit disconnect event.
[ "Emit", "disconnect", "event", "." ]
def disconnect_handler(): '''Emit disconnect event.''' server_log('Client disconnected')
[ "def", "disconnect_handler", "(", ")", ":", "server_log", "(", "'Client disconnected'", ")" ]
https://github.com/scottgchin/delta5_race_timer/blob/fe4e0f46307b05c9384f3124189edc402d812ade/src/delta5server/server.py#L342-L344
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
product/ERP5/bootstrap/erp5_core/DocumentTemplateItem/portal_components/document.erp5.Inventory.py
python
Inventory.immediateReindexObject
(self, temp_constructor=None, **kw)
Rewrite reindexObject so that we can insert lines in stock table which will be equal to the difference between stock values for resource in the inventory and the one before the date of this inventory temp_constructor is used in some particular cases where we want to have our own temp object constructor, this is usefull if we want to use some classes with some particular methods
Rewrite reindexObject so that we can insert lines in stock table which will be equal to the difference between stock values for resource in the inventory and the one before the date of this inventory
[ "Rewrite", "reindexObject", "so", "that", "we", "can", "insert", "lines", "in", "stock", "table", "which", "will", "be", "equal", "to", "the", "difference", "between", "stock", "values", "for", "resource", "in", "the", "inventory", "and", "the", "one", "before", "the", "date", "of", "this", "inventory" ]
def immediateReindexObject(self, temp_constructor=None, **kw): """ Rewrite reindexObject so that we can insert lines in stock table which will be equal to the difference between stock values for resource in the inventory and the one before the date of this inventory temp_constructor is used in some particular cases where we want to have our own temp object constructor, this is usefull if we want to use some classes with some particular methods """ portal = self.getPortalObject() sql_catalog_id = kw.pop("sql_catalog_id", None) disable_archive = kw.pop("disable_archive", 0) state = self.getSimulationState() # we need reindex when cancelling inventories if (state in portal.getPortalDraftOrderStateList() and state != 'cancelled'): # this prevent from trying to calculate stock # with not all properties defined and thus making # request with no condition in mysql immediate_reindex_archive = sql_catalog_id is not None portal.portal_catalog.catalogObjectList([self], sql_catalog_id = sql_catalog_id, disable_archive=disable_archive, immediate_reindex_archive=immediate_reindex_archive) return connection_id = None if sql_catalog_id is not None: # try to get connection used in the catalog catalog = portal.portal_catalog[sql_catalog_id] connection_id = catalog.getConnectionId() default_inventory_calculation_list = ({ "inventory_params" : {"section": self.getDestinationSection(), "node" : self.getDestination(), "group_by_sub_variation" : 1, "group_by_variation" : 1, "group_by_resource" : 1, }, "list_method" : "getMovementList", "first_level" : ({'key' : 'resource_relative_url', 'getter' : 'getResource', 'setter' : ("appendToCategoryList", "resource")}, {'key' : 'variation_text', 'getter' : 'getVariationText', 'setter' : "splitAndExtendToCategoryList"}, ), "second_level" : ({'key' : 'sub_variation_text', 'getter' : 'getSubVariationText', 'setter' : "splitAndExtendToCategoryList"}, ), }, ) method = self._getTypeBasedMethod('getDefaultInventoryCalculationList') if method is not None: default_inventory_calculation_list = method() if temp_constructor is None: temp_constructor = lambda self, id, *args, **kw: self.newContent( temp_object=True, portal_type='Movement', id=id, *args, **kw) stop_date = self.getStopDate() stock_object_list = [] stock_append = stock_object_list.append to_delete_stock_uid_set = set() to_delete_stock_uid_add = to_delete_stock_uid_set.add for inventory_calculation_dict in default_inventory_calculation_list: # build a dict containing all inventory for this node # group by resource/variation and then subvariation current_inventory_list = \ portal.portal_simulation.getCurrentInventoryList( to_date=stop_date, connection_id=connection_id, **inventory_calculation_dict['inventory_params'] ) current_inventory_dict = {} current_inventory_key_id_list = [x["key"] for x in inventory_calculation_dict['first_level']] for line in current_inventory_list: current_inventory_key = [line[x] for x in current_inventory_key_id_list] for x in xrange(len(current_inventory_key)): if current_inventory_key[x] is None: current_inventory_key[x] = "" current_inventory_key = tuple(current_inventory_key) if inventory_calculation_dict.has_key("second_level"): # two level of variation try: current_inventory_by_sub_variation = \ current_inventory_dict[current_inventory_key] except KeyError: current_inventory_by_sub_variation = \ current_inventory_dict[current_inventory_key] = {} second_level_key_id_list = [x['key'] for x in inventory_calculation_dict['second_level']] second_level_key = tuple([line[x] for x in second_level_key_id_list]) current_inventory_by_sub_variation[second_level_key] = line['total_quantity'] else: # only one level of variation current_inventory_dict[current_inventory_key] = line['total_quantity'] # Browse all movements on inventory and create diff line when necessary if self.isFullInventory(): not_used_inventory_dict = current_inventory_dict else: not_used_inventory_dict = {} inventory_id = self.getId() list_method = inventory_calculation_dict['list_method'] method = getattr(self, list_method) __order_id_counter_list = [0] def getOrderIdCounter(): value = __order_id_counter_list[0] # pylint: disable=cell-var-from-loop __order_id_counter_list[0] = value + 1 # pylint: disable=cell-var-from-loop return value for movement in method(): # Make sure we remove any any value to_delete_stock_uid_add(movement.getUid()) if movement.getResourceValue() is not None and \ movement.getInventoriatedQuantity() not in (None, ''): movement_quantity = movement.getInventoriatedQuantity() # construct key to retrieve inventory into dict getter_list = [x['getter'] for x in inventory_calculation_dict['first_level']] key_list = [] for getter in getter_list: method = getattr(movement, getter, None) if method is not None: key_list.append(method()) inventory_value = current_inventory_dict.get(tuple(key_list), 0) second_key_list = [] if inventory_calculation_dict.has_key('second_level'): if inventory_value == 0: inventory_value = {} # two level second_getter_list = [x['getter'] for x in inventory_calculation_dict['second_level']] for getter in second_getter_list: method = getattr(movement, getter, None) if method is not None: second_key_list.append(method()) second_key_list = tuple(second_key_list) if inventory_value.has_key(second_key_list): total_quantity = inventory_value.pop(second_key_list) # Put remaining subvariation in a dict to know which one # to removed at end not_used_inventory_dict[tuple(key_list)] = inventory_value diff_quantity = movement_quantity - total_quantity else: # Inventory for new resource/variation/sub_variation diff_quantity = movement_quantity # Put remaining subvariation in a dict to know which one # to removed at end not_used_inventory_dict[tuple(key_list)] = inventory_value else: # we got the quantity from first level key diff_quantity = movement_quantity - inventory_value # Create tmp movement kwd = {'uid': movement.getUid(), 'start_date': stop_date, 'order_id': getOrderIdCounter(), 'mirror_order_id':getOrderIdCounter() } temp_delivery_line = temp_constructor(self, inventory_id) # set category on it only if quantity not null # thus line with same uid will be deleted but we # don't insert line with null quantity as we test # some categories like resource/destination/source # before insert but not before delete if diff_quantity != 0: kwd['quantity'] = diff_quantity category_list = self.getCategoryList() setter_list = [x['setter'] for x in inventory_calculation_dict['first_level']] if inventory_calculation_dict.has_key("second_level"): setter_list.extend([x['setter'] for x in inventory_calculation_dict['second_level']]) value_list = list(key_list) + list(second_key_list) for x in xrange(len(setter_list)): value = value_list[x] setter = setter_list[x] base_category = "" if isinstance(setter, (tuple, list)): base_category = setter[1] setter = setter[0] method = getattr(self, setter, None) if method is not None: method(category_list, value, base_category) kwd['category_list'] = category_list temp_delivery_line.edit(**kwd) stock_append(temp_delivery_line) # Now create line to remove some subvariation text not present # in new inventory if len(not_used_inventory_dict): inventory_uid = self.getUid() for first_level_key in not_used_inventory_dict.keys(): inventory_value = \ not_used_inventory_dict[tuple(first_level_key)] # XXX-Aurel : this code does not work with only one level of variation for second_level_key in inventory_value.keys(): diff_quantity = - inventory_value[tuple(second_level_key)] kwd = {'uid': inventory_uid, 'start_date': stop_date, 'order_id': getOrderIdCounter(), 'mirror_order_id':getOrderIdCounter() } # create the tmp line and set category on it temp_delivery_line = temp_constructor(self, inventory_id) kwd['quantity'] = diff_quantity category_list = self.getCategoryList() setter_list = [x['setter'] for x in inventory_calculation_dict['first_level']] if inventory_calculation_dict.has_key("second_level"): setter_list.extend([x['setter'] for x in inventory_calculation_dict['second_level']]) value_list = list(first_level_key) + list(second_level_key) for x in xrange(len(setter_list)): value = value_list[x] setter = setter_list[x] base_category = "" if isinstance(setter, (tuple, list)): base_category = setter[1] setter = setter[0] method = getattr(self, setter, None) if method is not None: method(category_list, value, base_category) kwd['category_list'] = category_list temp_delivery_line.edit(**kwd) stock_append(temp_delivery_line) # Reindex objects immediate_reindex_archive = sql_catalog_id is not None portal.portal_catalog.catalogObjectList([self], sql_catalog_id = sql_catalog_id, disable_archive=disable_archive, immediate_reindex_archive=immediate_reindex_archive) # Do deletion for everything first, even if there is no need to apply correction, # in case we need to remove previous corrections to_delete_stock_uid_add(self.getUid()) to_delete_list = [] to_delete_list_append = to_delete_list.append for uid in to_delete_stock_uid_set: temp_line = temp_constructor(self, inventory_id) temp_line.setUid(uid) to_delete_list_append(temp_line) catalog_kw = dict(sql_catalog_id=sql_catalog_id, disable_cache=1, check_uid=0, disable_archive=disable_archive, immediate_reindex_archive=immediate_reindex_archive) method_id_list = ['z0_uncatalog_stock'] if portal.portal_catalog.getSQLCatalog(sql_catalog_id) \ .hasObject('SQLCatalog_trimInventoryCacheOnCatalog'): method_id_list.append('SQLCatalog_trimInventoryCacheOnCatalog') # Delete existing stock records and old inventory_cache first. portal.portal_catalog.catalogObjectList( to_delete_list[:], method_id_list=method_id_list, **catalog_kw) if stock_object_list: # Then insert new records without delete. portal.portal_catalog.catalogObjectList( stock_object_list[:], method_id_list=('z_catalog_stock_list_without_delete_for_inventory_virtual_movement', ), **catalog_kw)
[ "def", "immediateReindexObject", "(", "self", ",", "temp_constructor", "=", "None", ",", "*", "*", "kw", ")", ":", "portal", "=", "self", ".", "getPortalObject", "(", ")", "sql_catalog_id", "=", "kw", ".", "pop", "(", "\"sql_catalog_id\"", ",", "None", ")", "disable_archive", "=", "kw", ".", "pop", "(", "\"disable_archive\"", ",", "0", ")", "state", "=", "self", ".", "getSimulationState", "(", ")", "# we need reindex when cancelling inventories", "if", "(", "state", "in", "portal", ".", "getPortalDraftOrderStateList", "(", ")", "and", "state", "!=", "'cancelled'", ")", ":", "# this prevent from trying to calculate stock", "# with not all properties defined and thus making", "# request with no condition in mysql", "immediate_reindex_archive", "=", "sql_catalog_id", "is", "not", "None", "portal", ".", "portal_catalog", ".", "catalogObjectList", "(", "[", "self", "]", ",", "sql_catalog_id", "=", "sql_catalog_id", ",", "disable_archive", "=", "disable_archive", ",", "immediate_reindex_archive", "=", "immediate_reindex_archive", ")", "return", "connection_id", "=", "None", "if", "sql_catalog_id", "is", "not", "None", ":", "# try to get connection used in the catalog", "catalog", "=", "portal", ".", "portal_catalog", "[", "sql_catalog_id", "]", "connection_id", "=", "catalog", ".", "getConnectionId", "(", ")", "default_inventory_calculation_list", "=", "(", "{", "\"inventory_params\"", ":", "{", "\"section\"", ":", "self", ".", "getDestinationSection", "(", ")", ",", "\"node\"", ":", "self", ".", "getDestination", "(", ")", ",", "\"group_by_sub_variation\"", ":", "1", ",", "\"group_by_variation\"", ":", "1", ",", "\"group_by_resource\"", ":", "1", ",", "}", ",", "\"list_method\"", ":", "\"getMovementList\"", ",", "\"first_level\"", ":", "(", "{", "'key'", ":", "'resource_relative_url'", ",", "'getter'", ":", "'getResource'", ",", "'setter'", ":", "(", "\"appendToCategoryList\"", ",", "\"resource\"", ")", "}", ",", "{", "'key'", ":", "'variation_text'", ",", "'getter'", ":", "'getVariationText'", ",", "'setter'", ":", "\"splitAndExtendToCategoryList\"", "}", ",", ")", ",", "\"second_level\"", ":", "(", "{", "'key'", ":", "'sub_variation_text'", ",", "'getter'", ":", "'getSubVariationText'", ",", "'setter'", ":", "\"splitAndExtendToCategoryList\"", "}", ",", ")", ",", "}", ",", ")", "method", "=", "self", ".", "_getTypeBasedMethod", "(", "'getDefaultInventoryCalculationList'", ")", "if", "method", "is", "not", "None", ":", "default_inventory_calculation_list", "=", "method", "(", ")", "if", "temp_constructor", "is", "None", ":", "temp_constructor", "=", "lambda", "self", ",", "id", ",", "*", "args", ",", "*", "*", "kw", ":", "self", ".", "newContent", "(", "temp_object", "=", "True", ",", "portal_type", "=", "'Movement'", ",", "id", "=", "id", ",", "*", "args", ",", "*", "*", "kw", ")", "stop_date", "=", "self", ".", "getStopDate", "(", ")", "stock_object_list", "=", "[", "]", "stock_append", "=", "stock_object_list", ".", "append", "to_delete_stock_uid_set", "=", "set", "(", ")", "to_delete_stock_uid_add", "=", "to_delete_stock_uid_set", ".", "add", "for", "inventory_calculation_dict", "in", "default_inventory_calculation_list", ":", "# build a dict containing all inventory for this node", "# group by resource/variation and then subvariation", "current_inventory_list", "=", "portal", ".", "portal_simulation", ".", "getCurrentInventoryList", "(", "to_date", "=", "stop_date", ",", "connection_id", "=", "connection_id", ",", "*", "*", "inventory_calculation_dict", "[", "'inventory_params'", "]", ")", "current_inventory_dict", "=", "{", "}", "current_inventory_key_id_list", "=", "[", "x", "[", "\"key\"", "]", "for", "x", "in", "inventory_calculation_dict", "[", "'first_level'", "]", "]", "for", "line", "in", "current_inventory_list", ":", "current_inventory_key", "=", "[", "line", "[", "x", "]", "for", "x", "in", "current_inventory_key_id_list", "]", "for", "x", "in", "xrange", "(", "len", "(", "current_inventory_key", ")", ")", ":", "if", "current_inventory_key", "[", "x", "]", "is", "None", ":", "current_inventory_key", "[", "x", "]", "=", "\"\"", "current_inventory_key", "=", "tuple", "(", "current_inventory_key", ")", "if", "inventory_calculation_dict", ".", "has_key", "(", "\"second_level\"", ")", ":", "# two level of variation", "try", ":", "current_inventory_by_sub_variation", "=", "current_inventory_dict", "[", "current_inventory_key", "]", "except", "KeyError", ":", "current_inventory_by_sub_variation", "=", "current_inventory_dict", "[", "current_inventory_key", "]", "=", "{", "}", "second_level_key_id_list", "=", "[", "x", "[", "'key'", "]", "for", "x", "in", "inventory_calculation_dict", "[", "'second_level'", "]", "]", "second_level_key", "=", "tuple", "(", "[", "line", "[", "x", "]", "for", "x", "in", "second_level_key_id_list", "]", ")", "current_inventory_by_sub_variation", "[", "second_level_key", "]", "=", "line", "[", "'total_quantity'", "]", "else", ":", "# only one level of variation", "current_inventory_dict", "[", "current_inventory_key", "]", "=", "line", "[", "'total_quantity'", "]", "# Browse all movements on inventory and create diff line when necessary", "if", "self", ".", "isFullInventory", "(", ")", ":", "not_used_inventory_dict", "=", "current_inventory_dict", "else", ":", "not_used_inventory_dict", "=", "{", "}", "inventory_id", "=", "self", ".", "getId", "(", ")", "list_method", "=", "inventory_calculation_dict", "[", "'list_method'", "]", "method", "=", "getattr", "(", "self", ",", "list_method", ")", "__order_id_counter_list", "=", "[", "0", "]", "def", "getOrderIdCounter", "(", ")", ":", "value", "=", "__order_id_counter_list", "[", "0", "]", "# pylint: disable=cell-var-from-loop", "__order_id_counter_list", "[", "0", "]", "=", "value", "+", "1", "# pylint: disable=cell-var-from-loop", "return", "value", "for", "movement", "in", "method", "(", ")", ":", "# Make sure we remove any any value", "to_delete_stock_uid_add", "(", "movement", ".", "getUid", "(", ")", ")", "if", "movement", ".", "getResourceValue", "(", ")", "is", "not", "None", "and", "movement", ".", "getInventoriatedQuantity", "(", ")", "not", "in", "(", "None", ",", "''", ")", ":", "movement_quantity", "=", "movement", ".", "getInventoriatedQuantity", "(", ")", "# construct key to retrieve inventory into dict", "getter_list", "=", "[", "x", "[", "'getter'", "]", "for", "x", "in", "inventory_calculation_dict", "[", "'first_level'", "]", "]", "key_list", "=", "[", "]", "for", "getter", "in", "getter_list", ":", "method", "=", "getattr", "(", "movement", ",", "getter", ",", "None", ")", "if", "method", "is", "not", "None", ":", "key_list", ".", "append", "(", "method", "(", ")", ")", "inventory_value", "=", "current_inventory_dict", ".", "get", "(", "tuple", "(", "key_list", ")", ",", "0", ")", "second_key_list", "=", "[", "]", "if", "inventory_calculation_dict", ".", "has_key", "(", "'second_level'", ")", ":", "if", "inventory_value", "==", "0", ":", "inventory_value", "=", "{", "}", "# two level", "second_getter_list", "=", "[", "x", "[", "'getter'", "]", "for", "x", "in", "inventory_calculation_dict", "[", "'second_level'", "]", "]", "for", "getter", "in", "second_getter_list", ":", "method", "=", "getattr", "(", "movement", ",", "getter", ",", "None", ")", "if", "method", "is", "not", "None", ":", "second_key_list", ".", "append", "(", "method", "(", ")", ")", "second_key_list", "=", "tuple", "(", "second_key_list", ")", "if", "inventory_value", ".", "has_key", "(", "second_key_list", ")", ":", "total_quantity", "=", "inventory_value", ".", "pop", "(", "second_key_list", ")", "# Put remaining subvariation in a dict to know which one", "# to removed at end", "not_used_inventory_dict", "[", "tuple", "(", "key_list", ")", "]", "=", "inventory_value", "diff_quantity", "=", "movement_quantity", "-", "total_quantity", "else", ":", "# Inventory for new resource/variation/sub_variation", "diff_quantity", "=", "movement_quantity", "# Put remaining subvariation in a dict to know which one", "# to removed at end", "not_used_inventory_dict", "[", "tuple", "(", "key_list", ")", "]", "=", "inventory_value", "else", ":", "# we got the quantity from first level key", "diff_quantity", "=", "movement_quantity", "-", "inventory_value", "# Create tmp movement", "kwd", "=", "{", "'uid'", ":", "movement", ".", "getUid", "(", ")", ",", "'start_date'", ":", "stop_date", ",", "'order_id'", ":", "getOrderIdCounter", "(", ")", ",", "'mirror_order_id'", ":", "getOrderIdCounter", "(", ")", "}", "temp_delivery_line", "=", "temp_constructor", "(", "self", ",", "inventory_id", ")", "# set category on it only if quantity not null", "# thus line with same uid will be deleted but we", "# don't insert line with null quantity as we test", "# some categories like resource/destination/source", "# before insert but not before delete", "if", "diff_quantity", "!=", "0", ":", "kwd", "[", "'quantity'", "]", "=", "diff_quantity", "category_list", "=", "self", ".", "getCategoryList", "(", ")", "setter_list", "=", "[", "x", "[", "'setter'", "]", "for", "x", "in", "inventory_calculation_dict", "[", "'first_level'", "]", "]", "if", "inventory_calculation_dict", ".", "has_key", "(", "\"second_level\"", ")", ":", "setter_list", ".", "extend", "(", "[", "x", "[", "'setter'", "]", "for", "x", "in", "inventory_calculation_dict", "[", "'second_level'", "]", "]", ")", "value_list", "=", "list", "(", "key_list", ")", "+", "list", "(", "second_key_list", ")", "for", "x", "in", "xrange", "(", "len", "(", "setter_list", ")", ")", ":", "value", "=", "value_list", "[", "x", "]", "setter", "=", "setter_list", "[", "x", "]", "base_category", "=", "\"\"", "if", "isinstance", "(", "setter", ",", "(", "tuple", ",", "list", ")", ")", ":", "base_category", "=", "setter", "[", "1", "]", "setter", "=", "setter", "[", "0", "]", "method", "=", "getattr", "(", "self", ",", "setter", ",", "None", ")", "if", "method", "is", "not", "None", ":", "method", "(", "category_list", ",", "value", ",", "base_category", ")", "kwd", "[", "'category_list'", "]", "=", "category_list", "temp_delivery_line", ".", "edit", "(", "*", "*", "kwd", ")", "stock_append", "(", "temp_delivery_line", ")", "# Now create line to remove some subvariation text not present", "# in new inventory", "if", "len", "(", "not_used_inventory_dict", ")", ":", "inventory_uid", "=", "self", ".", "getUid", "(", ")", "for", "first_level_key", "in", "not_used_inventory_dict", ".", "keys", "(", ")", ":", "inventory_value", "=", "not_used_inventory_dict", "[", "tuple", "(", "first_level_key", ")", "]", "# XXX-Aurel : this code does not work with only one level of variation", "for", "second_level_key", "in", "inventory_value", ".", "keys", "(", ")", ":", "diff_quantity", "=", "-", "inventory_value", "[", "tuple", "(", "second_level_key", ")", "]", "kwd", "=", "{", "'uid'", ":", "inventory_uid", ",", "'start_date'", ":", "stop_date", ",", "'order_id'", ":", "getOrderIdCounter", "(", ")", ",", "'mirror_order_id'", ":", "getOrderIdCounter", "(", ")", "}", "# create the tmp line and set category on it", "temp_delivery_line", "=", "temp_constructor", "(", "self", ",", "inventory_id", ")", "kwd", "[", "'quantity'", "]", "=", "diff_quantity", "category_list", "=", "self", ".", "getCategoryList", "(", ")", "setter_list", "=", "[", "x", "[", "'setter'", "]", "for", "x", "in", "inventory_calculation_dict", "[", "'first_level'", "]", "]", "if", "inventory_calculation_dict", ".", "has_key", "(", "\"second_level\"", ")", ":", "setter_list", ".", "extend", "(", "[", "x", "[", "'setter'", "]", "for", "x", "in", "inventory_calculation_dict", "[", "'second_level'", "]", "]", ")", "value_list", "=", "list", "(", "first_level_key", ")", "+", "list", "(", "second_level_key", ")", "for", "x", "in", "xrange", "(", "len", "(", "setter_list", ")", ")", ":", "value", "=", "value_list", "[", "x", "]", "setter", "=", "setter_list", "[", "x", "]", "base_category", "=", "\"\"", "if", "isinstance", "(", "setter", ",", "(", "tuple", ",", "list", ")", ")", ":", "base_category", "=", "setter", "[", "1", "]", "setter", "=", "setter", "[", "0", "]", "method", "=", "getattr", "(", "self", ",", "setter", ",", "None", ")", "if", "method", "is", "not", "None", ":", "method", "(", "category_list", ",", "value", ",", "base_category", ")", "kwd", "[", "'category_list'", "]", "=", "category_list", "temp_delivery_line", ".", "edit", "(", "*", "*", "kwd", ")", "stock_append", "(", "temp_delivery_line", ")", "# Reindex objects", "immediate_reindex_archive", "=", "sql_catalog_id", "is", "not", "None", "portal", ".", "portal_catalog", ".", "catalogObjectList", "(", "[", "self", "]", ",", "sql_catalog_id", "=", "sql_catalog_id", ",", "disable_archive", "=", "disable_archive", ",", "immediate_reindex_archive", "=", "immediate_reindex_archive", ")", "# Do deletion for everything first, even if there is no need to apply correction,", "# in case we need to remove previous corrections", "to_delete_stock_uid_add", "(", "self", ".", "getUid", "(", ")", ")", "to_delete_list", "=", "[", "]", "to_delete_list_append", "=", "to_delete_list", ".", "append", "for", "uid", "in", "to_delete_stock_uid_set", ":", "temp_line", "=", "temp_constructor", "(", "self", ",", "inventory_id", ")", "temp_line", ".", "setUid", "(", "uid", ")", "to_delete_list_append", "(", "temp_line", ")", "catalog_kw", "=", "dict", "(", "sql_catalog_id", "=", "sql_catalog_id", ",", "disable_cache", "=", "1", ",", "check_uid", "=", "0", ",", "disable_archive", "=", "disable_archive", ",", "immediate_reindex_archive", "=", "immediate_reindex_archive", ")", "method_id_list", "=", "[", "'z0_uncatalog_stock'", "]", "if", "portal", ".", "portal_catalog", ".", "getSQLCatalog", "(", "sql_catalog_id", ")", ".", "hasObject", "(", "'SQLCatalog_trimInventoryCacheOnCatalog'", ")", ":", "method_id_list", ".", "append", "(", "'SQLCatalog_trimInventoryCacheOnCatalog'", ")", "# Delete existing stock records and old inventory_cache first.", "portal", ".", "portal_catalog", ".", "catalogObjectList", "(", "to_delete_list", "[", ":", "]", ",", "method_id_list", "=", "method_id_list", ",", "*", "*", "catalog_kw", ")", "if", "stock_object_list", ":", "# Then insert new records without delete.", "portal", ".", "portal_catalog", ".", "catalogObjectList", "(", "stock_object_list", "[", ":", "]", ",", "method_id_list", "=", "(", "'z_catalog_stock_list_without_delete_for_inventory_virtual_movement'", ",", ")", ",", "*", "*", "catalog_kw", ")" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ERP5/bootstrap/erp5_core/DocumentTemplateItem/portal_components/document.erp5.Inventory.py#L86-L357
HaliteChallenge/Halite-II
5cf95b4aef38621a44a503f90399af598fb51214
airesources/Cython3/hlt/networking.py
python
Game._send_string
(s)
Send data to the game. Call :function:`done_sending` once finished. :param str s: String to send :return: nothing
Send data to the game. Call :function:`done_sending` once finished.
[ "Send", "data", "to", "the", "game", ".", "Call", ":", "function", ":", "done_sending", "once", "finished", "." ]
def _send_string(s): """ Send data to the game. Call :function:`done_sending` once finished. :param str s: String to send :return: nothing """ sys.stdout.write(s)
[ "def", "_send_string", "(", "s", ")", ":", "sys", ".", "stdout", ".", "write", "(", "s", ")" ]
https://github.com/HaliteChallenge/Halite-II/blob/5cf95b4aef38621a44a503f90399af598fb51214/airesources/Cython3/hlt/networking.py#L14-L21
eldarion/pycon
76b45a756234a71212eeca37c99a4182dafe8631
symposion/boxes/authorization.py
python
default_can_edit
(request, *args, **kwargs)
return request.user.is_staff or request.user.is_superuser
This is meant to be overridden in your project per domain specific requirements.
This is meant to be overridden in your project per domain specific requirements.
[ "This", "is", "meant", "to", "be", "overridden", "in", "your", "project", "per", "domain", "specific", "requirements", "." ]
def default_can_edit(request, *args, **kwargs): """ This is meant to be overridden in your project per domain specific requirements. """ return request.user.is_staff or request.user.is_superuser
[ "def", "default_can_edit", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "request", ".", "user", ".", "is_staff", "or", "request", ".", "user", ".", "is_superuser" ]
https://github.com/eldarion/pycon/blob/76b45a756234a71212eeca37c99a4182dafe8631/symposion/boxes/authorization.py#L6-L11
korolr/dotfiles
8e46933503ecb8d8651739ffeb1d2d4f0f5c6524
.config/sublime-text-3/Backup/20181226200442/mdpopups/st3/mdpopups/png.py
python
read_pnm_header
(infile, supported=('P5','P6'))
return header[0], header[1], header[2], depth, header[3]
Read a PNM header, returning (format,width,height,depth,maxval). `width` and `height` are in pixels. `depth` is the number of channels in the image; for PBM and PGM it is synthesized as 1, for PPM as 3; for PAM images it is read from the header. `maxval` is synthesized (as 1) for PBM images.
Read a PNM header, returning (format,width,height,depth,maxval). `width` and `height` are in pixels. `depth` is the number of channels in the image; for PBM and PGM it is synthesized as 1, for PPM as 3; for PAM images it is read from the header. `maxval` is synthesized (as 1) for PBM images.
[ "Read", "a", "PNM", "header", "returning", "(", "format", "width", "height", "depth", "maxval", ")", ".", "width", "and", "height", "are", "in", "pixels", ".", "depth", "is", "the", "number", "of", "channels", "in", "the", "image", ";", "for", "PBM", "and", "PGM", "it", "is", "synthesized", "as", "1", "for", "PPM", "as", "3", ";", "for", "PAM", "images", "it", "is", "read", "from", "the", "header", ".", "maxval", "is", "synthesized", "(", "as", "1", ")", "for", "PBM", "images", "." ]
def read_pnm_header(infile, supported=('P5','P6')): """ Read a PNM header, returning (format,width,height,depth,maxval). `width` and `height` are in pixels. `depth` is the number of channels in the image; for PBM and PGM it is synthesized as 1, for PPM as 3; for PAM images it is read from the header. `maxval` is synthesized (as 1) for PBM images. """ # Generally, see http://netpbm.sourceforge.net/doc/ppm.html # and http://netpbm.sourceforge.net/doc/pam.html supported = [strtobytes(x) for x in supported] # Technically 'P7' must be followed by a newline, so by using # rstrip() we are being liberal in what we accept. I think this # is acceptable. type = infile.read(3).rstrip() if type not in supported: raise NotImplementedError('file format %s not supported' % type) if type == strtobytes('P7'): # PAM header parsing is completely different. return read_pam_header(infile) # Expected number of tokens in header (3 for P4, 4 for P6) expected = 4 pbm = ('P1', 'P4') if type in pbm: expected = 3 header = [type] # We have to read the rest of the header byte by byte because the # final whitespace character (immediately following the MAXVAL in # the case of P6) may not be a newline. Of course all PNM files in # the wild use a newline at this point, so it's tempting to use # readline; but it would be wrong. def getc(): c = infile.read(1) if not c: raise Error('premature EOF reading PNM header') return c c = getc() while True: # Skip whitespace that precedes a token. while c.isspace(): c = getc() # Skip comments. while c == '#': while c not in '\n\r': c = getc() if not c.isdigit(): raise Error('unexpected character %s found in header' % c) # According to the specification it is legal to have comments # that appear in the middle of a token. # This is bonkers; I've never seen it; and it's a bit awkward to # code good lexers in Python (no goto). So we break on such # cases. token = strtobytes('') while c.isdigit(): token += c c = getc() # Slight hack. All "tokens" are decimal integers, so convert # them here. header.append(int(token)) if len(header) == expected: break # Skip comments (again) while c == '#': while c not in '\n\r': c = getc() if not c.isspace(): raise Error('expected header to end with whitespace, not %s' % c) if type in pbm: # synthesize a MAXVAL header.append(1) depth = (1,3)[type == strtobytes('P6')] return header[0], header[1], header[2], depth, header[3]
[ "def", "read_pnm_header", "(", "infile", ",", "supported", "=", "(", "'P5'", ",", "'P6'", ")", ")", ":", "# Generally, see http://netpbm.sourceforge.net/doc/ppm.html", "# and http://netpbm.sourceforge.net/doc/pam.html", "supported", "=", "[", "strtobytes", "(", "x", ")", "for", "x", "in", "supported", "]", "# Technically 'P7' must be followed by a newline, so by using", "# rstrip() we are being liberal in what we accept. I think this", "# is acceptable.", "type", "=", "infile", ".", "read", "(", "3", ")", ".", "rstrip", "(", ")", "if", "type", "not", "in", "supported", ":", "raise", "NotImplementedError", "(", "'file format %s not supported'", "%", "type", ")", "if", "type", "==", "strtobytes", "(", "'P7'", ")", ":", "# PAM header parsing is completely different.", "return", "read_pam_header", "(", "infile", ")", "# Expected number of tokens in header (3 for P4, 4 for P6)", "expected", "=", "4", "pbm", "=", "(", "'P1'", ",", "'P4'", ")", "if", "type", "in", "pbm", ":", "expected", "=", "3", "header", "=", "[", "type", "]", "# We have to read the rest of the header byte by byte because the", "# final whitespace character (immediately following the MAXVAL in", "# the case of P6) may not be a newline. Of course all PNM files in", "# the wild use a newline at this point, so it's tempting to use", "# readline; but it would be wrong.", "def", "getc", "(", ")", ":", "c", "=", "infile", ".", "read", "(", "1", ")", "if", "not", "c", ":", "raise", "Error", "(", "'premature EOF reading PNM header'", ")", "return", "c", "c", "=", "getc", "(", ")", "while", "True", ":", "# Skip whitespace that precedes a token.", "while", "c", ".", "isspace", "(", ")", ":", "c", "=", "getc", "(", ")", "# Skip comments.", "while", "c", "==", "'#'", ":", "while", "c", "not", "in", "'\\n\\r'", ":", "c", "=", "getc", "(", ")", "if", "not", "c", ".", "isdigit", "(", ")", ":", "raise", "Error", "(", "'unexpected character %s found in header'", "%", "c", ")", "# According to the specification it is legal to have comments", "# that appear in the middle of a token.", "# This is bonkers; I've never seen it; and it's a bit awkward to", "# code good lexers in Python (no goto). So we break on such", "# cases.", "token", "=", "strtobytes", "(", "''", ")", "while", "c", ".", "isdigit", "(", ")", ":", "token", "+=", "c", "c", "=", "getc", "(", ")", "# Slight hack. All \"tokens\" are decimal integers, so convert", "# them here.", "header", ".", "append", "(", "int", "(", "token", ")", ")", "if", "len", "(", "header", ")", "==", "expected", ":", "break", "# Skip comments (again)", "while", "c", "==", "'#'", ":", "while", "c", "not", "in", "'\\n\\r'", ":", "c", "=", "getc", "(", ")", "if", "not", "c", ".", "isspace", "(", ")", ":", "raise", "Error", "(", "'expected header to end with whitespace, not %s'", "%", "c", ")", "if", "type", "in", "pbm", ":", "# synthesize a MAXVAL", "header", ".", "append", "(", "1", ")", "depth", "=", "(", "1", ",", "3", ")", "[", "type", "==", "strtobytes", "(", "'P6'", ")", "]", "return", "header", "[", "0", "]", ",", "header", "[", "1", "]", ",", "header", "[", "2", "]", ",", "depth", ",", "header", "[", "3", "]" ]
https://github.com/korolr/dotfiles/blob/8e46933503ecb8d8651739ffeb1d2d4f0f5c6524/.config/sublime-text-3/Backup/20181226200442/mdpopups/st3/mdpopups/png.py#L3511-L3588
mdipierro/web2py-appliances
f97658293d51519e5f06e1ed503ee85f8154fcf3
PyForum2/modules/auth.py
python
CustomAuthentication.requires_role
(self, roles)
return wrapper
Decorator Helper to aid in determine whether a controller needs specific access
Decorator Helper to aid in determine whether a controller needs specific access
[ "Decorator", "Helper", "to", "aid", "in", "determine", "whether", "a", "controller", "needs", "specific", "access" ]
def requires_role(self, roles): """ Decorator Helper to aid in determine whether a controller needs specific access """ def wrapper(func): def f(*args, **kwargs): if not self.has_role(roles): return redirect(URL(r=self.request, c='default', f='login')) return func(*args, **kwargs) return f return wrapper
[ "def", "requires_role", "(", "self", ",", "roles", ")", ":", "def", "wrapper", "(", "func", ")", ":", "def", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "has_role", "(", "roles", ")", ":", "return", "redirect", "(", "URL", "(", "r", "=", "self", ".", "request", ",", "c", "=", "'default'", ",", "f", "=", "'login'", ")", ")", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "f", "return", "wrapper" ]
https://github.com/mdipierro/web2py-appliances/blob/f97658293d51519e5f06e1ed503ee85f8154fcf3/PyForum2/modules/auth.py#L223-L238
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
product/Formulator/FieldRegistry.py
python
initializeFieldForm
(field_class)
Initialize the properties (fields and values) on a particular field class. Also add the tales and override methods.
Initialize the properties (fields and values) on a particular field class. Also add the tales and override methods.
[ "Initialize", "the", "properties", "(", "fields", "and", "values", ")", "on", "a", "particular", "field", "class", ".", "Also", "add", "the", "tales", "and", "override", "methods", "." ]
def initializeFieldForm(field_class): """Initialize the properties (fields and values) on a particular field class. Also add the tales and override methods. """ from .Form import BasicForm from .DummyField import fields form = BasicForm() override_form = BasicForm() tales_form = BasicForm() for field in getPropertyFields(field_class.widget): form.add_field(field, "widget") tales_field = fields.TALESField(field.id, title=field.get_value('title'), description="", default="", display_width=40, required=0) tales_form.add_field(tales_field, "widget") method_field = fields.MethodField(field.id, title=field.get_value("title"), description="", default="", required=0) override_form.add_field(method_field, "widget") for field in getPropertyFields(field_class.validator): form.add_field(field, "validator") tales_field = fields.TALESField(field.id, title=field.get_value('title'), description="", default="", display_with=40, required=0) tales_form.add_field(tales_field, "validator") method_field = fields.MethodField(field.id, title=field.get_value("title"), description="", default="", required=0) override_form.add_field(method_field, "validator") field_class.form = form field_class.override_form = override_form field_class.tales_form = tales_form
[ "def", "initializeFieldForm", "(", "field_class", ")", ":", "from", ".", "Form", "import", "BasicForm", "from", ".", "DummyField", "import", "fields", "form", "=", "BasicForm", "(", ")", "override_form", "=", "BasicForm", "(", ")", "tales_form", "=", "BasicForm", "(", ")", "for", "field", "in", "getPropertyFields", "(", "field_class", ".", "widget", ")", ":", "form", ".", "add_field", "(", "field", ",", "\"widget\"", ")", "tales_field", "=", "fields", ".", "TALESField", "(", "field", ".", "id", ",", "title", "=", "field", ".", "get_value", "(", "'title'", ")", ",", "description", "=", "\"\"", ",", "default", "=", "\"\"", ",", "display_width", "=", "40", ",", "required", "=", "0", ")", "tales_form", ".", "add_field", "(", "tales_field", ",", "\"widget\"", ")", "method_field", "=", "fields", ".", "MethodField", "(", "field", ".", "id", ",", "title", "=", "field", ".", "get_value", "(", "\"title\"", ")", ",", "description", "=", "\"\"", ",", "default", "=", "\"\"", ",", "required", "=", "0", ")", "override_form", ".", "add_field", "(", "method_field", ",", "\"widget\"", ")", "for", "field", "in", "getPropertyFields", "(", "field_class", ".", "validator", ")", ":", "form", ".", "add_field", "(", "field", ",", "\"validator\"", ")", "tales_field", "=", "fields", ".", "TALESField", "(", "field", ".", "id", ",", "title", "=", "field", ".", "get_value", "(", "'title'", ")", ",", "description", "=", "\"\"", ",", "default", "=", "\"\"", ",", "display_with", "=", "40", ",", "required", "=", "0", ")", "tales_form", ".", "add_field", "(", "tales_field", ",", "\"validator\"", ")", "method_field", "=", "fields", ".", "MethodField", "(", "field", ".", "id", ",", "title", "=", "field", ".", "get_value", "(", "\"title\"", ")", ",", "description", "=", "\"\"", ",", "default", "=", "\"\"", ",", "required", "=", "0", ")", "override_form", ".", "add_field", "(", "method_field", ",", "\"validator\"", ")", "field_class", ".", "form", "=", "form", "field_class", ".", "override_form", "=", "override_form", "field_class", ".", "tales_form", "=", "tales_form" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/Formulator/FieldRegistry.py#L62-L108
mceSystems/node-jsc
90634f3064fab8e89a85b3942f0cc5054acc86fa
tools/gyp/pylib/gyp/generator/analyzer.py
python
_ToGypPath
(path)
return path
Converts a path to the format used by gyp.
Converts a path to the format used by gyp.
[ "Converts", "a", "path", "to", "the", "format", "used", "by", "gyp", "." ]
def _ToGypPath(path): """Converts a path to the format used by gyp.""" if os.sep == '\\' and os.altsep == '/': return path.replace('\\', '/') return path
[ "def", "_ToGypPath", "(", "path", ")", ":", "if", "os", ".", "sep", "==", "'\\\\'", "and", "os", ".", "altsep", "==", "'/'", ":", "return", "path", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "return", "path" ]
https://github.com/mceSystems/node-jsc/blob/90634f3064fab8e89a85b3942f0cc5054acc86fa/tools/gyp/pylib/gyp/generator/analyzer.py#L112-L116
jupyter/notebook
26626343384195a1f4f5461ba42eb3e133655976
notebook/services/contents/filemanager.py
python
FileContentsManager.exists
(self, path)
return exists(os_path)
Returns True if the path exists, else returns False. API-style wrapper for os.path.exists Parameters ---------- path : string The API path to the file (with '/' as separator) Returns ------- exists : bool Whether the target exists.
Returns True if the path exists, else returns False.
[ "Returns", "True", "if", "the", "path", "exists", "else", "returns", "False", "." ]
def exists(self, path): """Returns True if the path exists, else returns False. API-style wrapper for os.path.exists Parameters ---------- path : string The API path to the file (with '/' as separator) Returns ------- exists : bool Whether the target exists. """ path = path.strip('/') os_path = self._get_os_path(path=path) return exists(os_path)
[ "def", "exists", "(", "self", ",", "path", ")", ":", "path", "=", "path", ".", "strip", "(", "'/'", ")", "os_path", "=", "self", ".", "_get_os_path", "(", "path", "=", "path", ")", "return", "exists", "(", "os_path", ")" ]
https://github.com/jupyter/notebook/blob/26626343384195a1f4f5461ba42eb3e133655976/notebook/services/contents/filemanager.py#L223-L240
Southpaw-TACTIC/TACTIC
ba9b87aef0ee3b3ea51446f25b285ebbca06f62c
src/tactic/ui/widget/upload_wdg.py
python
UploadWdg.get_display_old
(self)
This is NOT used, just used as a reference for the old method
This is NOT used, just used as a reference for the old method
[ "This", "is", "NOT", "used", "just", "used", "as", "a", "reference", "for", "the", "old", "method" ]
def get_display_old(self): '''This is NOT used, just used as a reference for the old method''' icon_id = 'upload_div' div = DivWdg() if self.get_option('upload_type') == 'arbitrary': counter = HiddenWdg('upload_counter','0') div.add(counter) icon = IconButtonWdg('add upload', icon=IconWdg.ADD) icon.set_id(icon_id) icon.add_event('onclick', "Common.add_upload_input('%s','%s','upload_counter')" \ %(icon_id, self.get_input_name())) div.add(icon) table = Table() table.set_class("minimal") table.add_style("font-size: 0.8em") names = self.get_option('names') required = self.get_option('required') if not names: self.add_upload(table, self.name) else: names = names.split('|') if required: required = required.split('|') if len(required) != len(names): raise TacticException('required needs to match the number of names if defined in the config file.') # check for uniqueness in upload_names if len(set(names)) != len(names): raise TacticException('[names] in the config file must be unique') for idx, name in enumerate(names): if required: is_required = required[idx] == 'true' else: is_required = False self.add_upload(table, name, is_required) table.add_row()
[ "def", "get_display_old", "(", "self", ")", ":", "icon_id", "=", "'upload_div'", "div", "=", "DivWdg", "(", ")", "if", "self", ".", "get_option", "(", "'upload_type'", ")", "==", "'arbitrary'", ":", "counter", "=", "HiddenWdg", "(", "'upload_counter'", ",", "'0'", ")", "div", ".", "add", "(", "counter", ")", "icon", "=", "IconButtonWdg", "(", "'add upload'", ",", "icon", "=", "IconWdg", ".", "ADD", ")", "icon", ".", "set_id", "(", "icon_id", ")", "icon", ".", "add_event", "(", "'onclick'", ",", "\"Common.add_upload_input('%s','%s','upload_counter')\"", "%", "(", "icon_id", ",", "self", ".", "get_input_name", "(", ")", ")", ")", "div", ".", "add", "(", "icon", ")", "table", "=", "Table", "(", ")", "table", ".", "set_class", "(", "\"minimal\"", ")", "table", ".", "add_style", "(", "\"font-size: 0.8em\"", ")", "names", "=", "self", ".", "get_option", "(", "'names'", ")", "required", "=", "self", ".", "get_option", "(", "'required'", ")", "if", "not", "names", ":", "self", ".", "add_upload", "(", "table", ",", "self", ".", "name", ")", "else", ":", "names", "=", "names", ".", "split", "(", "'|'", ")", "if", "required", ":", "required", "=", "required", ".", "split", "(", "'|'", ")", "if", "len", "(", "required", ")", "!=", "len", "(", "names", ")", ":", "raise", "TacticException", "(", "'required needs to match the number of names if defined in the config file.'", ")", "# check for uniqueness in upload_names", "if", "len", "(", "set", "(", "names", ")", ")", "!=", "len", "(", "names", ")", ":", "raise", "TacticException", "(", "'[names] in the config file must be unique'", ")", "for", "idx", ",", "name", "in", "enumerate", "(", "names", ")", ":", "if", "required", ":", "is_required", "=", "required", "[", "idx", "]", "==", "'true'", "else", ":", "is_required", "=", "False", "self", ".", "add_upload", "(", "table", ",", "name", ",", "is_required", ")", "table", ".", "add_row", "(", ")" ]
https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/src/tactic/ui/widget/upload_wdg.py#L229-L268
Southpaw-TACTIC/TACTIC
ba9b87aef0ee3b3ea51446f25b285ebbca06f62c
3rd_party/python3/site-packages/cheroot/connections.py
python
ConnectionManager.get_conn
(self, server_socket)
return conn
Return a HTTPConnection object which is ready to be handled. A connection returned by this method should be ready for a worker to handle it. If there are no connections ready, None will be returned. Any connection returned by this method will need to be `put` back if it should be examined again for another request. Args: server_socket (socket.socket): Socket to listen to for new connections. Returns: cheroot.server.HTTPConnection instance, or None.
Return a HTTPConnection object which is ready to be handled.
[ "Return", "a", "HTTPConnection", "object", "which", "is", "ready", "to", "be", "handled", "." ]
def get_conn(self, server_socket): """Return a HTTPConnection object which is ready to be handled. A connection returned by this method should be ready for a worker to handle it. If there are no connections ready, None will be returned. Any connection returned by this method will need to be `put` back if it should be examined again for another request. Args: server_socket (socket.socket): Socket to listen to for new connections. Returns: cheroot.server.HTTPConnection instance, or None. """ # Grab file descriptors from sockets, but stop if we find a # connection which is already marked as ready. socket_dict = {} for conn in self.connections: if conn.closeable or conn.ready_with_data: break socket_dict[conn.socket.fileno()] = conn else: # No ready connection. conn = None # We have a connection ready for use. if conn: self.connections.remove(conn) return conn # Will require a select call. ss_fileno = server_socket.fileno() socket_dict[ss_fileno] = server_socket try: rlist, _, _ = select.select(list(socket_dict), [], [], 0.1) # No available socket. if not rlist: return None except OSError: # Mark any connection which no longer appears valid. for fno, conn in list(socket_dict.items()): # If the server socket is invalid, we'll just ignore it and # wait to be shutdown. if fno == ss_fileno: continue try: os.fstat(fno) except OSError: # Socket is invalid, close the connection, insert at # the front. self.connections.remove(conn) self.connections.insert(0, conn) conn.closeable = True # Wait for the next tick to occur. return None try: # See if we have a new connection coming in. rlist.remove(ss_fileno) except ValueError: # No new connection, but reuse existing socket. conn = socket_dict[rlist.pop()] else: conn = server_socket # All remaining connections in rlist should be marked as ready. for fno in rlist: socket_dict[fno].ready_with_data = True # New connection. if conn is server_socket: return self._from_server_socket(server_socket) self.connections.remove(conn) return conn
[ "def", "get_conn", "(", "self", ",", "server_socket", ")", ":", "# Grab file descriptors from sockets, but stop if we find a", "# connection which is already marked as ready.", "socket_dict", "=", "{", "}", "for", "conn", "in", "self", ".", "connections", ":", "if", "conn", ".", "closeable", "or", "conn", ".", "ready_with_data", ":", "break", "socket_dict", "[", "conn", ".", "socket", ".", "fileno", "(", ")", "]", "=", "conn", "else", ":", "# No ready connection.", "conn", "=", "None", "# We have a connection ready for use.", "if", "conn", ":", "self", ".", "connections", ".", "remove", "(", "conn", ")", "return", "conn", "# Will require a select call.", "ss_fileno", "=", "server_socket", ".", "fileno", "(", ")", "socket_dict", "[", "ss_fileno", "]", "=", "server_socket", "try", ":", "rlist", ",", "_", ",", "_", "=", "select", ".", "select", "(", "list", "(", "socket_dict", ")", ",", "[", "]", ",", "[", "]", ",", "0.1", ")", "# No available socket.", "if", "not", "rlist", ":", "return", "None", "except", "OSError", ":", "# Mark any connection which no longer appears valid.", "for", "fno", ",", "conn", "in", "list", "(", "socket_dict", ".", "items", "(", ")", ")", ":", "# If the server socket is invalid, we'll just ignore it and", "# wait to be shutdown.", "if", "fno", "==", "ss_fileno", ":", "continue", "try", ":", "os", ".", "fstat", "(", "fno", ")", "except", "OSError", ":", "# Socket is invalid, close the connection, insert at", "# the front.", "self", ".", "connections", ".", "remove", "(", "conn", ")", "self", ".", "connections", ".", "insert", "(", "0", ",", "conn", ")", "conn", ".", "closeable", "=", "True", "# Wait for the next tick to occur.", "return", "None", "try", ":", "# See if we have a new connection coming in.", "rlist", ".", "remove", "(", "ss_fileno", ")", "except", "ValueError", ":", "# No new connection, but reuse existing socket.", "conn", "=", "socket_dict", "[", "rlist", ".", "pop", "(", ")", "]", "else", ":", "conn", "=", "server_socket", "# All remaining connections in rlist should be marked as ready.", "for", "fno", "in", "rlist", ":", "socket_dict", "[", "fno", "]", ".", "ready_with_data", "=", "True", "# New connection.", "if", "conn", "is", "server_socket", ":", "return", "self", ".", "_from_server_socket", "(", "server_socket", ")", "self", ".", "connections", ".", "remove", "(", "conn", ")", "return", "conn" ]
https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/3rd_party/python3/site-packages/cheroot/connections.py#L105-L183
TeamvisionCorp/TeamVision
aa2a57469e430ff50cce21174d8f280efa0a83a7
distribute/0.0.5/build_shell/teamvision/teamvision/project/pagefactory/project_statistics_pageworker.py
python
ProjectStatisticsPageWorker.__init__
(self,request)
Constructor
Constructor
[ "Constructor" ]
def __init__(self,request): ''' Constructor ''' ProjectPageWorker.__init__(self, request) self.left_nav_bar_model=ProjectStatisticsLeftNavBar
[ "def", "__init__", "(", "self", ",", "request", ")", ":", "ProjectPageWorker", ".", "__init__", "(", "self", ",", "request", ")", "self", ".", "left_nav_bar_model", "=", "ProjectStatisticsLeftNavBar" ]
https://github.com/TeamvisionCorp/TeamVision/blob/aa2a57469e430ff50cce21174d8f280efa0a83a7/distribute/0.0.5/build_shell/teamvision/teamvision/project/pagefactory/project_statistics_pageworker.py#L20-L25
chanzuckerberg/cellxgene
ceb0cc6f27821ad056209b6908db6620f0ec3da6
server/common/config/base_config.py
python
BaseConfig.changes_from_default
(self)
return diff
Return all the attribute that are different from the default
Return all the attribute that are different from the default
[ "Return", "all", "the", "attribute", "that", "are", "different", "from", "the", "default" ]
def changes_from_default(self): """Return all the attribute that are different from the default""" mapping = self.create_mapping(self.default_config) diff = [] for attrname, (key, defval) in mapping.items(): curval = getattr(self, attrname) if curval != defval: diff.append((attrname, curval, defval)) return diff
[ "def", "changes_from_default", "(", "self", ")", ":", "mapping", "=", "self", ".", "create_mapping", "(", "self", ".", "default_config", ")", "diff", "=", "[", "]", "for", "attrname", ",", "(", "key", ",", "defval", ")", "in", "mapping", ".", "items", "(", ")", ":", "curval", "=", "getattr", "(", "self", ",", "attrname", ")", "if", "curval", "!=", "defval", ":", "diff", ".", "append", "(", "(", "attrname", ",", "curval", ",", "defval", ")", ")", "return", "diff" ]
https://github.com/chanzuckerberg/cellxgene/blob/ceb0cc6f27821ad056209b6908db6620f0ec3da6/server/common/config/base_config.py#L91-L99
jxcore/jxcore
b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410
tools/gyp/pylib/gyp/generator/ninja.py
python
ComputeOutputDir
(params)
return os.path.normpath(os.path.join(generator_dir, output_dir))
Returns the path from the toplevel_dir to the build output directory.
Returns the path from the toplevel_dir to the build output directory.
[ "Returns", "the", "path", "from", "the", "toplevel_dir", "to", "the", "build", "output", "directory", "." ]
def ComputeOutputDir(params): """Returns the path from the toplevel_dir to the build output directory.""" # generator_dir: relative path from pwd to where make puts build files. # Makes migrating from make to ninja easier, ninja doesn't put anything here. generator_dir = os.path.relpath(params['options'].generator_output or '.') # output_dir: relative path from generator_dir to the build directory. output_dir = params.get('generator_flags', {}).get('output_dir', 'out') # Relative path from source root to our output files. e.g. "out" return os.path.normpath(os.path.join(generator_dir, output_dir))
[ "def", "ComputeOutputDir", "(", "params", ")", ":", "# generator_dir: relative path from pwd to where make puts build files.", "# Makes migrating from make to ninja easier, ninja doesn't put anything here.", "generator_dir", "=", "os", ".", "path", ".", "relpath", "(", "params", "[", "'options'", "]", ".", "generator_output", "or", "'.'", ")", "# output_dir: relative path from generator_dir to the build directory.", "output_dir", "=", "params", ".", "get", "(", "'generator_flags'", ",", "{", "}", ")", ".", "get", "(", "'output_dir'", ",", "'out'", ")", "# Relative path from source root to our output files. e.g. \"out\"", "return", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "generator_dir", ",", "output_dir", ")", ")" ]
https://github.com/jxcore/jxcore/blob/b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410/tools/gyp/pylib/gyp/generator/ninja.py#L1496-L1506
korolr/dotfiles
8e46933503ecb8d8651739ffeb1d2d4f0f5c6524
.config/sublime-text-3/Packages/python-markdown/st3/markdown/extensions/footnotes.py
python
FootnoteExtension.reset
(self)
Clear footnotes on reset, and prepare for distinct document.
Clear footnotes on reset, and prepare for distinct document.
[ "Clear", "footnotes", "on", "reset", "and", "prepare", "for", "distinct", "document", "." ]
def reset(self): """ Clear footnotes on reset, and prepare for distinct document. """ self.footnotes = OrderedDict() self.unique_prefix += 1 self.found_refs = {} self.used_refs = set()
[ "def", "reset", "(", "self", ")", ":", "self", ".", "footnotes", "=", "OrderedDict", "(", ")", "self", ".", "unique_prefix", "+=", "1", "self", ".", "found_refs", "=", "{", "}", "self", ".", "used_refs", "=", "set", "(", ")" ]
https://github.com/korolr/dotfiles/blob/8e46933503ecb8d8651739ffeb1d2d4f0f5c6524/.config/sublime-text-3/Packages/python-markdown/st3/markdown/extensions/footnotes.py#L102-L107
Southpaw-TACTIC/TACTIC
ba9b87aef0ee3b3ea51446f25b285ebbca06f62c
3rd_party/python2/site-packages/cherrypy/lib/httputil.py
python
urljoin
(*atoms)
return url or '/'
r"""Return the given path \*atoms, joined into a single URL. This will correctly join a SCRIPT_NAME and PATH_INFO into the original URL, even if either atom is blank.
r"""Return the given path \*atoms, joined into a single URL.
[ "r", "Return", "the", "given", "path", "\\", "*", "atoms", "joined", "into", "a", "single", "URL", "." ]
def urljoin(*atoms): r"""Return the given path \*atoms, joined into a single URL. This will correctly join a SCRIPT_NAME and PATH_INFO into the original URL, even if either atom is blank. """ url = '/'.join([x for x in atoms if x]) while '//' in url: url = url.replace('//', '/') # Special-case the final url of "", and return "/" instead. return url or '/'
[ "def", "urljoin", "(", "*", "atoms", ")", ":", "url", "=", "'/'", ".", "join", "(", "[", "x", "for", "x", "in", "atoms", "if", "x", "]", ")", "while", "'//'", "in", "url", ":", "url", "=", "url", ".", "replace", "(", "'//'", ",", "'/'", ")", "# Special-case the final url of \"\", and return \"/\" instead.", "return", "url", "or", "'/'" ]
https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/3rd_party/python2/site-packages/cherrypy/lib/httputil.py#L40-L50
JoneXiong/DjangoX
c2a723e209ef13595f571923faac7eb29e4c8150
xadmin/sites.py
python
AdminSite.has_permission
(self, request)
return request.user.is_active and request.user.is_staff
如果返回为 ``True`` 则说明 ``request.user`` 至少能够访问当前xadmin网站。否则无法访问xadmin的任何页面。
如果返回为 ``True`` 则说明 ``request.user`` 至少能够访问当前xadmin网站。否则无法访问xadmin的任何页面。
[ "如果返回为", "True", "则说明", "request", ".", "user", "至少能够访问当前xadmin网站。否则无法访问xadmin的任何页面。" ]
def has_permission(self, request): """ 如果返回为 ``True`` 则说明 ``request.user`` 至少能够访问当前xadmin网站。否则无法访问xadmin的任何页面。 """ return request.user.is_active and request.user.is_staff
[ "def", "has_permission", "(", "self", ",", "request", ")", ":", "return", "request", ".", "user", ".", "is_active", "and", "request", ".", "user", ".", "is_staff" ]
https://github.com/JoneXiong/DjangoX/blob/c2a723e209ef13595f571923faac7eb29e4c8150/xadmin/sites.py#L254-L258
opencoweb/coweb
7b3a87ee9eda735a859447d404ee16edde1c5671
servers/python/coweb/service/manager/bayeux.py
python
ServiceConnection.on_handshake
(self, cl, req, res)
Overrides to associates a bot state with its connection.
Overrides to associates a bot state with its connection.
[ "Overrides", "to", "associates", "a", "bot", "state", "with", "its", "connection", "." ]
def on_handshake(self, cl, req, res): '''Overrides to associates a bot state with its connection.''' if res['successful']: # make the service name the username on the bayeux client cl.username = req['ext']['authentication']['user']
[ "def", "on_handshake", "(", "self", ",", "cl", ",", "req", ",", "res", ")", ":", "if", "res", "[", "'successful'", "]", ":", "# make the service name the username on the bayeux client", "cl", ".", "username", "=", "req", "[", "'ext'", "]", "[", "'authentication'", "]", "[", "'user'", "]" ]
https://github.com/opencoweb/coweb/blob/7b3a87ee9eda735a859447d404ee16edde1c5671/servers/python/coweb/service/manager/bayeux.py#L185-L189
carlosperate/ardublockly
04fa48273b5651386d0ef1ce6dd446795ffc2594
ardublocklyserver/local-packages/serial/urlhandler/protocol_loop.py
python
Serial.ri
(self)
return False
Read terminal status line: Ring Indicator
Read terminal status line: Ring Indicator
[ "Read", "terminal", "status", "line", ":", "Ring", "Indicator" ]
def ri(self): """Read terminal status line: Ring Indicator""" if not self.is_open: raise portNotOpenError if self.logger: self.logger.info('returning dummy for RI') return False
[ "def", "ri", "(", "self", ")", ":", "if", "not", "self", ".", "is_open", ":", "raise", "portNotOpenError", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "'returning dummy for RI'", ")", "return", "False" ]
https://github.com/carlosperate/ardublockly/blob/04fa48273b5651386d0ef1ce6dd446795ffc2594/ardublocklyserver/local-packages/serial/urlhandler/protocol_loop.py#L263-L269
almonk/Bind
03e9e98fb8b30a58cb4fc2829f06289fa9958897
public/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py
python
_FixPath
(path)
return path
Convert paths to a form that will make sense in a vcproj file. Arguments: path: The path to convert, may contain / etc. Returns: The path with all slashes made into backslashes.
Convert paths to a form that will make sense in a vcproj file.
[ "Convert", "paths", "to", "a", "form", "that", "will", "make", "sense", "in", "a", "vcproj", "file", "." ]
def _FixPath(path): """Convert paths to a form that will make sense in a vcproj file. Arguments: path: The path to convert, may contain / etc. Returns: The path with all slashes made into backslashes. """ if fixpath_prefix and path and not os.path.isabs(path) and not path[0] == '$': path = os.path.join(fixpath_prefix, path) path = path.replace('/', '\\') path = _NormalizedSource(path) if path and path[-1] == '\\': path = path[:-1] return path
[ "def", "_FixPath", "(", "path", ")", ":", "if", "fixpath_prefix", "and", "path", "and", "not", "os", ".", "path", ".", "isabs", "(", "path", ")", "and", "not", "path", "[", "0", "]", "==", "'$'", ":", "path", "=", "os", ".", "path", ".", "join", "(", "fixpath_prefix", ",", "path", ")", "path", "=", "path", ".", "replace", "(", "'/'", ",", "'\\\\'", ")", "path", "=", "_NormalizedSource", "(", "path", ")", "if", "path", "and", "path", "[", "-", "1", "]", "==", "'\\\\'", ":", "path", "=", "path", "[", ":", "-", "1", "]", "return", "path" ]
https://github.com/almonk/Bind/blob/03e9e98fb8b30a58cb4fc2829f06289fa9958897/public/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L189-L203
DFIRKuiper/Kuiper
c5b4cb3d535287c360b239b7596e82731954fc77
kuiper/app/parsers/vol_Parser/volatility/framework/symbols/windows/extensions/pe.py
python
IMAGE_DOS_HEADER.reconstruct
(self)
This method generates the content necessary to reconstruct a PE file from memory. It preserves slack space (similar to the old --memory) and automatically fixes the ImageBase in the output PE file. Returns: <tuple> of (<int> offset, <bytes> data)
This method generates the content necessary to reconstruct a PE file from memory. It preserves slack space (similar to the old --memory) and automatically fixes the ImageBase in the output PE file.
[ "This", "method", "generates", "the", "content", "necessary", "to", "reconstruct", "a", "PE", "file", "from", "memory", ".", "It", "preserves", "slack", "space", "(", "similar", "to", "the", "old", "--", "memory", ")", "and", "automatically", "fixes", "the", "ImageBase", "in", "the", "output", "PE", "file", "." ]
def reconstruct(self) -> Generator[Tuple[int, bytes], None, None]: """This method generates the content necessary to reconstruct a PE file from memory. It preserves slack space (similar to the old --memory) and automatically fixes the ImageBase in the output PE file. Returns: <tuple> of (<int> offset, <bytes> data) """ nt_header = self.get_nt_header() layer_name = self.vol.layer_name symbol_table_name = self.get_symbol_table_name() section_alignment = nt_header.OptionalHeader.SectionAlignment sect_header_size = self._context.symbol_space.get_type(symbol_table_name + constants.BANG + "_IMAGE_SECTION_HEADER").size size_of_image = nt_header.OptionalHeader.SizeOfImage # no legitimate PE is going to be larger than this if size_of_image > (1024 * 1024 * 100): raise ValueError("The claimed SizeOfImage is too large: {}".format(size_of_image)) read_layer = self._context.layers[layer_name] raw_data = read_layer.read(self.vol.offset, nt_header.OptionalHeader.SizeOfImage, pad = True) # fix the PE image base before yielding the initial view of the data fixed_data = self.fix_image_base(raw_data, nt_header) yield 0, fixed_data start_addr = nt_header.FileHeader.SizeOfOptionalHeader + \ (nt_header.OptionalHeader.vol.offset - self.vol.offset) counter = 0 for sect in nt_header.get_sections(): if sect.VirtualAddress > size_of_image: raise ValueError("Section VirtualAddress is too large: {}".format(sect.VirtualAddress)) if sect.Misc.VirtualSize > size_of_image: raise ValueError("Section VirtualSize is too large: {}".format(sect.Misc.VirtualSize)) if sect.SizeOfRawData > size_of_image: raise ValueError("Section SizeOfRawData is too large: {}".format(sect.SizeOfRawData)) if sect is not None: # It doesn't matter if this is too big, because it'll get overwritten by the later layers sect_size = conversion.round(sect.Misc.VirtualSize, section_alignment, up = True) sectheader = read_layer.read(sect.vol.offset, sect_header_size) sectheader = self.replace_header_field(sect, sectheader, sect.PointerToRawData, sect.VirtualAddress) sectheader = self.replace_header_field(sect, sectheader, sect.SizeOfRawData, sect_size) sectheader = self.replace_header_field(sect, sectheader, sect.Misc.VirtualSize, sect_size) offset = start_addr + (counter * sect_header_size) yield offset, sectheader counter += 1
[ "def", "reconstruct", "(", "self", ")", "->", "Generator", "[", "Tuple", "[", "int", ",", "bytes", "]", ",", "None", ",", "None", "]", ":", "nt_header", "=", "self", ".", "get_nt_header", "(", ")", "layer_name", "=", "self", ".", "vol", ".", "layer_name", "symbol_table_name", "=", "self", ".", "get_symbol_table_name", "(", ")", "section_alignment", "=", "nt_header", ".", "OptionalHeader", ".", "SectionAlignment", "sect_header_size", "=", "self", ".", "_context", ".", "symbol_space", ".", "get_type", "(", "symbol_table_name", "+", "constants", ".", "BANG", "+", "\"_IMAGE_SECTION_HEADER\"", ")", ".", "size", "size_of_image", "=", "nt_header", ".", "OptionalHeader", ".", "SizeOfImage", "# no legitimate PE is going to be larger than this", "if", "size_of_image", ">", "(", "1024", "*", "1024", "*", "100", ")", ":", "raise", "ValueError", "(", "\"The claimed SizeOfImage is too large: {}\"", ".", "format", "(", "size_of_image", ")", ")", "read_layer", "=", "self", ".", "_context", ".", "layers", "[", "layer_name", "]", "raw_data", "=", "read_layer", ".", "read", "(", "self", ".", "vol", ".", "offset", ",", "nt_header", ".", "OptionalHeader", ".", "SizeOfImage", ",", "pad", "=", "True", ")", "# fix the PE image base before yielding the initial view of the data", "fixed_data", "=", "self", ".", "fix_image_base", "(", "raw_data", ",", "nt_header", ")", "yield", "0", ",", "fixed_data", "start_addr", "=", "nt_header", ".", "FileHeader", ".", "SizeOfOptionalHeader", "+", "(", "nt_header", ".", "OptionalHeader", ".", "vol", ".", "offset", "-", "self", ".", "vol", ".", "offset", ")", "counter", "=", "0", "for", "sect", "in", "nt_header", ".", "get_sections", "(", ")", ":", "if", "sect", ".", "VirtualAddress", ">", "size_of_image", ":", "raise", "ValueError", "(", "\"Section VirtualAddress is too large: {}\"", ".", "format", "(", "sect", ".", "VirtualAddress", ")", ")", "if", "sect", ".", "Misc", ".", "VirtualSize", ">", "size_of_image", ":", "raise", "ValueError", "(", "\"Section VirtualSize is too large: {}\"", ".", "format", "(", "sect", ".", "Misc", ".", "VirtualSize", ")", ")", "if", "sect", ".", "SizeOfRawData", ">", "size_of_image", ":", "raise", "ValueError", "(", "\"Section SizeOfRawData is too large: {}\"", ".", "format", "(", "sect", ".", "SizeOfRawData", ")", ")", "if", "sect", "is", "not", "None", ":", "# It doesn't matter if this is too big, because it'll get overwritten by the later layers", "sect_size", "=", "conversion", ".", "round", "(", "sect", ".", "Misc", ".", "VirtualSize", ",", "section_alignment", ",", "up", "=", "True", ")", "sectheader", "=", "read_layer", ".", "read", "(", "sect", ".", "vol", ".", "offset", ",", "sect_header_size", ")", "sectheader", "=", "self", ".", "replace_header_field", "(", "sect", ",", "sectheader", ",", "sect", ".", "PointerToRawData", ",", "sect", ".", "VirtualAddress", ")", "sectheader", "=", "self", ".", "replace_header_field", "(", "sect", ",", "sectheader", ",", "sect", ".", "SizeOfRawData", ",", "sect_size", ")", "sectheader", "=", "self", ".", "replace_header_field", "(", "sect", ",", "sectheader", ",", "sect", ".", "Misc", ".", "VirtualSize", ",", "sect_size", ")", "offset", "=", "start_addr", "+", "(", "counter", "*", "sect_header_size", ")", "yield", "offset", ",", "sectheader", "counter", "+=", "1" ]
https://github.com/DFIRKuiper/Kuiper/blob/c5b4cb3d535287c360b239b7596e82731954fc77/kuiper/app/parsers/vol_Parser/volatility/framework/symbols/windows/extensions/pe.py#L80-L138
jam-py/jam-py
0821492cdff8665928e0f093a4435aa64285a45c
jam/third_party/sqlalchemy/sql/selectable.py
python
DeprecatedSelectGenerations.append_prefix
(self, clause)
append the given columns clause prefix expression to this select() construct. This is an **in-place** mutation method; the :meth:`~.Select.prefix_with` method is preferred, as it provides standard :term:`method chaining`.
append the given columns clause prefix expression to this select() construct.
[ "append", "the", "given", "columns", "clause", "prefix", "expression", "to", "this", "select", "()", "construct", "." ]
def append_prefix(self, clause): """append the given columns clause prefix expression to this select() construct. This is an **in-place** mutation method; the :meth:`~.Select.prefix_with` method is preferred, as it provides standard :term:`method chaining`. """ self.prefix_with.non_generative(self, clause)
[ "def", "append_prefix", "(", "self", ",", "clause", ")", ":", "self", ".", "prefix_with", ".", "non_generative", "(", "self", ",", "clause", ")" ]
https://github.com/jam-py/jam-py/blob/0821492cdff8665928e0f093a4435aa64285a45c/jam/third_party/sqlalchemy/sql/selectable.py#L3071-L3080
tain335/tain335
21c08048e6599b5f18d7fd6acfc1e88ece226d09
Lupy-0.2.1/lupy/document.py
python
Document.add
(self, field)
Adds a field to a document.
Adds a field to a document.
[ "Adds", "a", "field", "to", "a", "document", "." ]
def add(self, field): """Adds a field to a document.""" name = field.name() self._fields[name] = field if name not in self.fieldNames: self.fieldNames.append(name)
[ "def", "add", "(", "self", ",", "field", ")", ":", "name", "=", "field", ".", "name", "(", ")", "self", ".", "_fields", "[", "name", "]", "=", "field", "if", "name", "not", "in", "self", ".", "fieldNames", ":", "self", ".", "fieldNames", ".", "append", "(", "name", ")" ]
https://github.com/tain335/tain335/blob/21c08048e6599b5f18d7fd6acfc1e88ece226d09/Lupy-0.2.1/lupy/document.py#L21-L26
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
product/ERP5/Document/BusinessTemplate.py
python
BusinessTemplate.getTemplateActionPathList
(self)
return self._getOrderedList('template_action_path')
We have to set this method because we want an ordered list
We have to set this method because we want an ordered list
[ "We", "have", "to", "set", "this", "method", "because", "we", "want", "an", "ordered", "list" ]
def getTemplateActionPathList(self): """ We have to set this method because we want an ordered list """ return self._getOrderedList('template_action_path')
[ "def", "getTemplateActionPathList", "(", "self", ")", ":", "return", "self", ".", "_getOrderedList", "(", "'template_action_path'", ")" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ERP5/Document/BusinessTemplate.py#L5703-L5708
cuckoosandbox/cuckoo
50452a39ff7c3e0c4c94d114bc6317101633b958
cuckoo/apps/rooter.py
python
vpn_disable
(name)
Stop a running VPN.
Stop a running VPN.
[ "Stop", "a", "running", "VPN", "." ]
def vpn_disable(name): """Stop a running VPN.""" run(s.service, "openvpn", "stop", name)
[ "def", "vpn_disable", "(", "name", ")", ":", "run", "(", "s", ".", "service", ",", "\"openvpn\"", ",", "\"stop\"", ",", "name", ")" ]
https://github.com/cuckoosandbox/cuckoo/blob/50452a39ff7c3e0c4c94d114bc6317101633b958/cuckoo/apps/rooter.py#L107-L109
catmaid/CATMAID
9f3312f2eacfc6fab48e4c6f1bd24672cc9c9ecf
django/applications/catmaid/admin.py
python
ProjectAdmin.get_actions
(self, request)
return actions
Disable default delete action.
Disable default delete action.
[ "Disable", "default", "delete", "action", "." ]
def get_actions(self, request): """Disable default delete action. """ actions = super().get_actions(request) if 'delete_selected' in actions: del actions['delete_selected'] return actions
[ "def", "get_actions", "(", "self", ",", "request", ")", ":", "actions", "=", "super", "(", ")", ".", "get_actions", "(", "request", ")", "if", "'delete_selected'", "in", "actions", ":", "del", "actions", "[", "'delete_selected'", "]", "return", "actions" ]
https://github.com/catmaid/CATMAID/blob/9f3312f2eacfc6fab48e4c6f1bd24672cc9c9ecf/django/applications/catmaid/admin.py#L330-L336
exis-io/Exis
5383174f7b52112a97aadd09e6b9ea837c2fa07b
utils/functionizer.py
python
performFunctionalize
(args, modName, modSearch="__main__", preArgs=(), postArgs=())
Takes an argparse object, adds our required args for functioning, then calls the proper functions
Takes an argparse object, adds our required args for functioning, then calls the proper functions
[ "Takes", "an", "argparse", "object", "adds", "our", "required", "args", "for", "functioning", "then", "calls", "the", "proper", "functions" ]
def performFunctionalize(args, modName, modSearch="__main__", preArgs=(), postArgs=()): """Takes an argparse object, adds our required args for functioning, then calls the proper functions""" funcsList = args.list mod = sys.modules[modName] if(funcsList): funcs = _getModFunctions(modName, modSearch) if('*' in funcsList): funcsList = funcsList.replace('*', '') search = True else: search = False for f in funcs: if(funcsList == 'all' or (search and funcsList in f.__name__) or (not search and funcsList == f.__name__)): print('============================================================================================') _printHelp(mod, f.__name__) return # # Run the function as a command # if(args.func): if(not hasattr(mod, args.func)): print('No %s function found' % args.func) return func = args.func rfunc = getattr(mod, func) # Get any args they want used fargs = None if(args.args): fargs = [_parseValue(a) for a in args.args] # Deal with kwargs kwargs = dict() if(args.kwargs): for kw in args.kwargs: k, w = kw.split('=', 1) kwargs[k] = _parseValue(w) # Print out the docs about the function if(args.helpme): _printHelp(mod, func) return try: # Build arguments to send them theArgs = list() if(preArgs): theArgs += list(preArgs) if(fargs): theArgs += list(fargs) if(postArgs): theArgs += list(postArgs) # Call the function, if no args make special call (couldn't figure out another way) if(theArgs and kwargs): res = rfunc(*theArgs, **kwargs) elif(theArgs and not kwargs): res = rfunc(*theArgs) elif(not theArgs and kwargs): res = rfunc(**kwargs) else: res = rfunc() # Print results if(args.printResult == 'str'): print(res) elif(args.printResult == 'json'): print(_jsonPretty(res)) except Exception as e: t = ", ".join(theArgs) + ", " if theArgs else "" t += ", ".join(["{}={}".format(k, v) for k, v in kwargs.iteritems()]) print "Exception when calling {}({})".format(args.func, t) print e _printHelp(mod, func) traceback.print_exc() else: print('Call with "-h" for help') return
[ "def", "performFunctionalize", "(", "args", ",", "modName", ",", "modSearch", "=", "\"__main__\"", ",", "preArgs", "=", "(", ")", ",", "postArgs", "=", "(", ")", ")", ":", "funcsList", "=", "args", ".", "list", "mod", "=", "sys", ".", "modules", "[", "modName", "]", "if", "(", "funcsList", ")", ":", "funcs", "=", "_getModFunctions", "(", "modName", ",", "modSearch", ")", "if", "(", "'*'", "in", "funcsList", ")", ":", "funcsList", "=", "funcsList", ".", "replace", "(", "'*'", ",", "''", ")", "search", "=", "True", "else", ":", "search", "=", "False", "for", "f", "in", "funcs", ":", "if", "(", "funcsList", "==", "'all'", "or", "(", "search", "and", "funcsList", "in", "f", ".", "__name__", ")", "or", "(", "not", "search", "and", "funcsList", "==", "f", ".", "__name__", ")", ")", ":", "print", "(", "'============================================================================================'", ")", "_printHelp", "(", "mod", ",", "f", ".", "__name__", ")", "return", "#", "# Run the function as a command", "#", "if", "(", "args", ".", "func", ")", ":", "if", "(", "not", "hasattr", "(", "mod", ",", "args", ".", "func", ")", ")", ":", "print", "(", "'No %s function found'", "%", "args", ".", "func", ")", "return", "func", "=", "args", ".", "func", "rfunc", "=", "getattr", "(", "mod", ",", "func", ")", "# Get any args they want used", "fargs", "=", "None", "if", "(", "args", ".", "args", ")", ":", "fargs", "=", "[", "_parseValue", "(", "a", ")", "for", "a", "in", "args", ".", "args", "]", "# Deal with kwargs", "kwargs", "=", "dict", "(", ")", "if", "(", "args", ".", "kwargs", ")", ":", "for", "kw", "in", "args", ".", "kwargs", ":", "k", ",", "w", "=", "kw", ".", "split", "(", "'='", ",", "1", ")", "kwargs", "[", "k", "]", "=", "_parseValue", "(", "w", ")", "# Print out the docs about the function", "if", "(", "args", ".", "helpme", ")", ":", "_printHelp", "(", "mod", ",", "func", ")", "return", "try", ":", "# Build arguments to send them", "theArgs", "=", "list", "(", ")", "if", "(", "preArgs", ")", ":", "theArgs", "+=", "list", "(", "preArgs", ")", "if", "(", "fargs", ")", ":", "theArgs", "+=", "list", "(", "fargs", ")", "if", "(", "postArgs", ")", ":", "theArgs", "+=", "list", "(", "postArgs", ")", "# Call the function, if no args make special call (couldn't figure out another way)", "if", "(", "theArgs", "and", "kwargs", ")", ":", "res", "=", "rfunc", "(", "*", "theArgs", ",", "*", "*", "kwargs", ")", "elif", "(", "theArgs", "and", "not", "kwargs", ")", ":", "res", "=", "rfunc", "(", "*", "theArgs", ")", "elif", "(", "not", "theArgs", "and", "kwargs", ")", ":", "res", "=", "rfunc", "(", "*", "*", "kwargs", ")", "else", ":", "res", "=", "rfunc", "(", ")", "# Print results", "if", "(", "args", ".", "printResult", "==", "'str'", ")", ":", "print", "(", "res", ")", "elif", "(", "args", ".", "printResult", "==", "'json'", ")", ":", "print", "(", "_jsonPretty", "(", "res", ")", ")", "except", "Exception", "as", "e", ":", "t", "=", "\", \"", ".", "join", "(", "theArgs", ")", "+", "\", \"", "if", "theArgs", "else", "\"\"", "t", "+=", "\", \"", ".", "join", "(", "[", "\"{}={}\"", ".", "format", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "kwargs", ".", "iteritems", "(", ")", "]", ")", "print", "\"Exception when calling {}({})\"", ".", "format", "(", "args", ".", "func", ",", "t", ")", "print", "e", "_printHelp", "(", "mod", ",", "func", ")", "traceback", ".", "print_exc", "(", ")", "else", ":", "print", "(", "'Call with \"-h\" for help'", ")", "return" ]
https://github.com/exis-io/Exis/blob/5383174f7b52112a97aadd09e6b9ea837c2fa07b/utils/functionizer.py#L107-L189
jasonsanjose/brackets-sass
88b351f2ebc3aaa514494eac368d197f63438caf
node/2.0.3/node_modules/node-sass/node_modules/pangyp/gyp/pylib/gyp/xcodeproj_file.py
python
PBXGroup.AddOrGetVariantGroupByNameAndPath
(self, name, path)
return variant_group_ref
Returns an existing or new PBXVariantGroup for name and path. If a PBXVariantGroup identified by the name and path arguments is already present as a child of this object, it is returned. Otherwise, a new PBXVariantGroup with the correct properties is created, added as a child, and returned. This method will generally be called by AddOrGetFileByPath, which knows when to create a variant group based on the structure of the pathnames passed to it.
Returns an existing or new PBXVariantGroup for name and path.
[ "Returns", "an", "existing", "or", "new", "PBXVariantGroup", "for", "name", "and", "path", "." ]
def AddOrGetVariantGroupByNameAndPath(self, name, path): """Returns an existing or new PBXVariantGroup for name and path. If a PBXVariantGroup identified by the name and path arguments is already present as a child of this object, it is returned. Otherwise, a new PBXVariantGroup with the correct properties is created, added as a child, and returned. This method will generally be called by AddOrGetFileByPath, which knows when to create a variant group based on the structure of the pathnames passed to it. """ key = (name, path) if key in self._variant_children_by_name_and_path: variant_group_ref = self._variant_children_by_name_and_path[key] assert variant_group_ref.__class__ == PBXVariantGroup return variant_group_ref variant_group_properties = {'name': name} if path != None: variant_group_properties['path'] = path variant_group_ref = PBXVariantGroup(variant_group_properties) self.AppendChild(variant_group_ref) return variant_group_ref
[ "def", "AddOrGetVariantGroupByNameAndPath", "(", "self", ",", "name", ",", "path", ")", ":", "key", "=", "(", "name", ",", "path", ")", "if", "key", "in", "self", ".", "_variant_children_by_name_and_path", ":", "variant_group_ref", "=", "self", ".", "_variant_children_by_name_and_path", "[", "key", "]", "assert", "variant_group_ref", ".", "__class__", "==", "PBXVariantGroup", "return", "variant_group_ref", "variant_group_properties", "=", "{", "'name'", ":", "name", "}", "if", "path", "!=", "None", ":", "variant_group_properties", "[", "'path'", "]", "=", "path", "variant_group_ref", "=", "PBXVariantGroup", "(", "variant_group_properties", ")", "self", ".", "AppendChild", "(", "variant_group_ref", ")", "return", "variant_group_ref" ]
https://github.com/jasonsanjose/brackets-sass/blob/88b351f2ebc3aaa514494eac368d197f63438caf/node/2.0.3/node_modules/node-sass/node_modules/pangyp/gyp/pylib/gyp/xcodeproj_file.py#L1307-L1332
Southpaw-TACTIC/TACTIC
ba9b87aef0ee3b3ea51446f25b285ebbca06f62c
src/tactic/ui/panel/table_layout_wdg.py
python
TableLayoutWdg.handle_table_behaviors
(self, table)
table.add_relay_behavior( { #'type': 'double_click', 'type': 'mouseover', #'modkeys': 'SHIFT', 'bvr_match_class': 'spt_table_header', 'cbjs_action': ''' alert("here"); spt.table.set_table(bvr.src_el); var element_name = bvr.src_el.getAttribute("spt_element_name"); spt.table.toggle_collapse_column(element_name); ''' } )
table.add_relay_behavior( { #'type': 'double_click', 'type': 'mouseover', #'modkeys': 'SHIFT', 'bvr_match_class': 'spt_table_header', 'cbjs_action': ''' alert("here"); spt.table.set_table(bvr.src_el); var element_name = bvr.src_el.getAttribute("spt_element_name"); spt.table.toggle_collapse_column(element_name); ''' } )
[ "table", ".", "add_relay_behavior", "(", "{", "#", "type", ":", "double_click", "type", ":", "mouseover", "#", "modkeys", ":", "SHIFT", "bvr_match_class", ":", "spt_table_header", "cbjs_action", ":", "alert", "(", "here", ")", ";", "spt", ".", "table", ".", "set_table", "(", "bvr", ".", "src_el", ")", ";", "var", "element_name", "=", "bvr", ".", "src_el", ".", "getAttribute", "(", "spt_element_name", ")", ";", "spt", ".", "table", ".", "toggle_collapse_column", "(", "element_name", ")", ";", "}", ")" ]
def handle_table_behaviors(self, table): security = Environment.get_security() project_code = Project.get_project_code() self.handle_load_behaviors(table) # add the search_table_<table_id> listener used by widgets # like Add Task to Selected if self.kwargs.get('temp') != True: table.add_behavior( { 'type': 'listen', 'event_name': 'search_table_%s' % self.table_id, 'cbjs_action': ''' var top = bvr.src_el.getParent(".spt_layout"); var version = top.getAttribute("spt_version"); spt.table.set_layout(top); spt.table.run_search(); ''' } ) element_names = self.element_names column_widths = self.kwargs.get("column_widths") if not column_widths: column_widths = [] # set all of the column widths in javascript if self.kwargs.get('temp') != True: table.add_behavior( { 'type': 'load', 'element_names': self.element_names, 'column_widths': column_widths, 'cbjs_action': ''' var column_widths = bvr.column_widths; var layout = bvr.src_el.getParent(".spt_layout"); spt.table.set_layout(layout); for (var i = 0; i < bvr.element_names.length; i++) { var name = bvr.element_names[i]; var width = column_widths[i]; if (width == -1) { continue; } spt.table.set_column_width(name, width); } ''' } ) # all for collapsing of columns """ table.add_relay_behavior( { #'type': 'double_click', 'type': 'mouseover', #'modkeys': 'SHIFT', 'bvr_match_class': 'spt_table_header', 'cbjs_action': ''' alert("here"); spt.table.set_table(bvr.src_el); var element_name = bvr.src_el.getAttribute("spt_element_name"); spt.table.toggle_collapse_column(element_name); ''' } ) """ # column resizing behavior self.header_table.add_smart_styles("spt_resize_handle", { "position": "absolute", "height": "100px", "margin-top": "-3px", "right": "-1px", "width": "5px", "cursor": "e-resize", "background-color": '' } ) self.header_table.add_relay_behavior( { 'type': 'mouseover', 'drag_el': '@', 'bvr_match_class': 'spt_resize_handle', "cbjs_action": ''' bvr.src_el.setStyle("background", "#333"); ''' } ) self.header_table.add_relay_behavior( { 'type': 'mouseout', 'drag_el': '@', 'bvr_match_class': 'spt_resize_handle', "cbjs_action": ''' bvr.src_el.setStyle("background", ""); ''' } ) resize_cbjs = self.kwargs.get("resize_cbjs") or "" self.header_table.add_behavior( { 'type': 'smart_drag', 'drag_el': '@', 'bvr_match_class': 'spt_resize_handle', 'ignore_default_motion': 'true', 'resize_cbjs': resize_cbjs, "cbjs_setup": 'spt.table.drag_resize_header_setup(evt, bvr, mouse_411);', "cbjs_motion": 'spt.table.drag_resize_header_motion(evt, bvr, mouse_411)', "cbjs_action": 'spt.table.drag_resize_header_action(evt, bvr, mouse_411)', } ) table.add_relay_behavior( { 'type': 'mouseup', 'bvr_match_class': 'spt_remove_hidden_row', 'cbjs_action': ''' spt.table.remove_hidden_row_from_inside(bvr.src_el); ''' } ) border_color = table.get_color('border', modifier=20) # Drag will allow the dragging of items from a table to anywhere else table.add_behavior( { 'type': 'smart_drag', 'drag_el': 'drag_ghost_copy', 'bvr_match_class': 'spt_table_select', 'use_copy': 'true', 'border_color': border_color, 'use_delta': 'true', 'dx': 10, 'dy': 10, 'drop_code': 'DROP_ROW', 'copy_styles': 'background: #393950; color: #c2c2c2; border: solid 1px black; text-align: left; padding: 10px;', # don't use cbjs_pre_motion_setup as it assumes the drag el 'cbjs_setup': ''' if(spt.drop) { spt.drop.sobject_drop_setup( evt, bvr ); } ''', "cbjs_motion": ''' spt.mouse._smart_default_drag_motion(evt, bvr, mouse_411); var target_el = spt.get_event_target(evt); target_el = spt.mouse.check_parent(target_el, bvr.drop_code); if (target_el) { var orig_border_color = target_el.getStyle('border-color'); var orig_border_style = target_el.getStyle('border-style'); target_el.setStyle('border','dashed 2px ' + bvr.border_color); if (!target_el.getAttribute('orig_border_color')) { target_el.setAttribute('orig_border_color', orig_border_color); target_el.setAttribute('orig_border_style', orig_border_style); } } ''', "cbjs_action": ''' if (spt.drop) { spt.drop.sobject_drop_action(evt, bvr) } var dst_el = spt.get_event_target(evt); var src_el = spt.behavior.get_bvr_src(bvr); /* Keeping this around for later use */ var dst_row = dst_el.getParent(".spt_table_row"); var dst_search_key = dst_row.getAttribute("spt_search_key"); var src_row = src_el.getParent(".spt_table_row"); var src_search_key = src_row.getAttribute("spt_search_key"); ''' } ) # selection behaviors embedded_table = self.kwargs.get("__hidden__") in [True, 'true'] if not embedded_table: table.add_relay_behavior( { 'type': 'click', 'bvr_match_class': 'spt_table_select', 'cbjs_action': ''' if (evt.shift == true) return; spt.table.set_table(bvr.src_el); var row = bvr.src_el.getParent(".spt_table_row"); if (row.hasClass("spt_table_selected")) { spt.table.unselect_row(row); } else { spt.table.select_row(row); } ''' } ) table.add_relay_behavior( { 'type': 'click', 'bvr_match_class': 'spt_table_select', 'modkeys': 'SHIFT', 'cbjs_action': ''' if (evt.shift != true) return; spt.table.set_table(bvr.src_el); var row = bvr.src_el.getParent(".spt_table_row"); var rows = spt.table.get_all_rows(); var last_selected = spt.table.last_selected_row; var last_index = -1; var cur_index = -1; for (var i = 0; i < rows.length; i++) { if (rows[i] == last_selected) { last_index = i; } if (rows[i] == row) { cur_index = i; } if (cur_index != -1 && last_index != -1) { break; } } var start_index; var end_index; if (last_index < cur_index) { start_index = last_index; end_index = cur_index; } else { start_index = cur_index; end_index = last_index; } for (var i = start_index; i < end_index+1; i++) { spt.table.select_row(rows[i]); } ''' } ) # collapse groups from tactic.ui.widget.swap_display_wdg import SwapDisplayWdg SwapDisplayWdg.handle_top(table) table.add_relay_behavior( { 'type': 'click', 'bvr_match_class': 'spt_group_row_collapse', 'cbjs_action': ''' spt.table.set_table(bvr.src_el); var row = bvr.src_el.getParent(".spt_group_row"); spt.table.collapse_group(row); ''' } ) # indicator that a cell is editable table.add_behavior( { 'type': 'load', 'cbjs_action': ''' bvr.src_el.addEvent('mouseover:relay(.spt_cell_edit)', function(event, src_el) { if (src_el.hasClass("spt_cell_never_edit")) { } else if (src_el.hasClass("spt_cell_insert_no_edit")) { src_el.setStyle("background-image", "url(/context/icons/custom/no_edit.png)" ); } else { } } ) bvr.src_el.addEvent('mouseout:relay(.spt_cell_edit)', function(event, src_el) { src_el.setStyle("background-image", "" ); } ) ''' } ) # row highlighting if self.kwargs.get("show_row_highlight") not in [False, 'false']: table.add_behavior( { 'type': 'load', 'cbjs_action': ''' bvr.src_el.addEvent('mouseover:relay(.spt_table_row)', function(event, src_el) { // remember the original color src_el.addClass("spt_row_hover"); src_el.setAttribute("spt_hover_background", src_el.getStyle("background-color")); spt.mouse.table_layout_hover_over({}, {src_el: src_el, add_color_modifier: -5}); } ) bvr.src_el.addEvent('mouseout:relay(.spt_table_row)', function(event, src_el) { src_el.removeClass("spt_row_hover"); src_el.setAttribute("spt_hover_background", ""); spt.mouse.table_layout_hover_out({}, {src_el: src_el}); } ) ''' } ) # set styles at the table level to be relayed down border_color = table.get_color("table_border", default="border") select_styles = { "width": "30px", "min-width": "30px" } cell_styles = {} show_border = self.kwargs.get("show_border") if show_border in ['horizontal']: cell_styles["border-bottom"] = "solid 1px %s" % border_color cell_styles["padding"] = "3px" select_styles["border-bottom"] = "solid 1px %s" % border_color elif show_border not in [False, "false", "none"]: cell_styles["border"] = "solid 1px %s" % border_color cell_styles["padding"] = "3px" select_styles["border"] = "solid 1px %s" % border_color table.add_smart_styles("spt_table_select", select_styles) table.add_smart_styles("spt_cell_edit", cell_styles) is_editable = self.kwargs.get("is_editable") # Edit behavior if is_editable in [False, 'false']: is_editable = False else: is_editable = True # Check user access access_keys = self._get_access_keys("edit", project_code) if security.check_access("builtin", access_keys, "edit"): is_editable = True else: is_editable = False self.view_editable = False if is_editable: table.add_relay_behavior( { 'type': 'click', 'bvr_match_class': 'spt_cell_edit', 'cbjs_action': ''' spt.table.set_table(bvr.src_el); var cell = bvr.src_el; // no action for the bottom row if (!cell.getParent('spt_table_bottom_row.spt_table_bottom_row')) spt.table.show_edit(cell); return; ''' } ) #table.add_smart_styles( "spt_table_header", { # "background-repeat": "no-repeat", # "background-position": "top center" #} ) if self.kwargs.get("show_group_highlight") not in [False, 'false']: # group mouse over color table.add_relay_behavior( { 'type': "mouseover", 'bvr_match_class': 'spt_group_row', 'cbjs_action': "spt.mouse.table_layout_hover_over({}, {src_el: bvr.src_el, add_color_modifier: -5})" } ) table.add_relay_behavior( { 'type': "mouseout", 'bvr_match_class': 'spt_group_row', 'cbjs_action': "spt.mouse.table_layout_hover_out({}, {src_el: bvr.src_el})" } ) border_color = table.get_color("table_border", -10, default="border") table.add_smart_styles("spt_group_row", { 'border': 'solid 1px %s' % border_color } )
[ "def", "handle_table_behaviors", "(", "self", ",", "table", ")", ":", "security", "=", "Environment", ".", "get_security", "(", ")", "project_code", "=", "Project", ".", "get_project_code", "(", ")", "self", ".", "handle_load_behaviors", "(", "table", ")", "# add the search_table_<table_id> listener used by widgets", "# like Add Task to Selected", "if", "self", ".", "kwargs", ".", "get", "(", "'temp'", ")", "!=", "True", ":", "table", ".", "add_behavior", "(", "{", "'type'", ":", "'listen'", ",", "'event_name'", ":", "'search_table_%s'", "%", "self", ".", "table_id", ",", "'cbjs_action'", ":", "'''\n var top = bvr.src_el.getParent(\".spt_layout\");\n var version = top.getAttribute(\"spt_version\");\n spt.table.set_layout(top);\n spt.table.run_search();\n '''", "}", ")", "element_names", "=", "self", ".", "element_names", "column_widths", "=", "self", ".", "kwargs", ".", "get", "(", "\"column_widths\"", ")", "if", "not", "column_widths", ":", "column_widths", "=", "[", "]", "# set all of the column widths in javascript", "if", "self", ".", "kwargs", ".", "get", "(", "'temp'", ")", "!=", "True", ":", "table", ".", "add_behavior", "(", "{", "'type'", ":", "'load'", ",", "'element_names'", ":", "self", ".", "element_names", ",", "'column_widths'", ":", "column_widths", ",", "'cbjs_action'", ":", "'''\n\n var column_widths = bvr.column_widths;\n\n var layout = bvr.src_el.getParent(\".spt_layout\");\n spt.table.set_layout(layout);\n\n for (var i = 0; i < bvr.element_names.length; i++) {\n var name = bvr.element_names[i];\n var width = column_widths[i];\n if (width == -1) {\n continue;\n }\n spt.table.set_column_width(name, width);\n }\n\n\n '''", "}", ")", "# all for collapsing of columns", "# column resizing behavior", "self", ".", "header_table", ".", "add_smart_styles", "(", "\"spt_resize_handle\"", ",", "{", "\"position\"", ":", "\"absolute\"", ",", "\"height\"", ":", "\"100px\"", ",", "\"margin-top\"", ":", "\"-3px\"", ",", "\"right\"", ":", "\"-1px\"", ",", "\"width\"", ":", "\"5px\"", ",", "\"cursor\"", ":", "\"e-resize\"", ",", "\"background-color\"", ":", "''", "}", ")", "self", ".", "header_table", ".", "add_relay_behavior", "(", "{", "'type'", ":", "'mouseover'", ",", "'drag_el'", ":", "'@'", ",", "'bvr_match_class'", ":", "'spt_resize_handle'", ",", "\"cbjs_action\"", ":", "'''\n bvr.src_el.setStyle(\"background\", \"#333\");\n '''", "}", ")", "self", ".", "header_table", ".", "add_relay_behavior", "(", "{", "'type'", ":", "'mouseout'", ",", "'drag_el'", ":", "'@'", ",", "'bvr_match_class'", ":", "'spt_resize_handle'", ",", "\"cbjs_action\"", ":", "'''\n bvr.src_el.setStyle(\"background\", \"\");\n '''", "}", ")", "resize_cbjs", "=", "self", ".", "kwargs", ".", "get", "(", "\"resize_cbjs\"", ")", "or", "\"\"", "self", ".", "header_table", ".", "add_behavior", "(", "{", "'type'", ":", "'smart_drag'", ",", "'drag_el'", ":", "'@'", ",", "'bvr_match_class'", ":", "'spt_resize_handle'", ",", "'ignore_default_motion'", ":", "'true'", ",", "'resize_cbjs'", ":", "resize_cbjs", ",", "\"cbjs_setup\"", ":", "'spt.table.drag_resize_header_setup(evt, bvr, mouse_411);'", ",", "\"cbjs_motion\"", ":", "'spt.table.drag_resize_header_motion(evt, bvr, mouse_411)'", ",", "\"cbjs_action\"", ":", "'spt.table.drag_resize_header_action(evt, bvr, mouse_411)'", ",", "}", ")", "table", ".", "add_relay_behavior", "(", "{", "'type'", ":", "'mouseup'", ",", "'bvr_match_class'", ":", "'spt_remove_hidden_row'", ",", "'cbjs_action'", ":", "'''\n spt.table.remove_hidden_row_from_inside(bvr.src_el);\n '''", "}", ")", "border_color", "=", "table", ".", "get_color", "(", "'border'", ",", "modifier", "=", "20", ")", "# Drag will allow the dragging of items from a table to anywhere else", "table", ".", "add_behavior", "(", "{", "'type'", ":", "'smart_drag'", ",", "'drag_el'", ":", "'drag_ghost_copy'", ",", "'bvr_match_class'", ":", "'spt_table_select'", ",", "'use_copy'", ":", "'true'", ",", "'border_color'", ":", "border_color", ",", "'use_delta'", ":", "'true'", ",", "'dx'", ":", "10", ",", "'dy'", ":", "10", ",", "'drop_code'", ":", "'DROP_ROW'", ",", "'copy_styles'", ":", "'background: #393950; color: #c2c2c2; border: solid 1px black; text-align: left; padding: 10px;'", ",", "# don't use cbjs_pre_motion_setup as it assumes the drag el", "'cbjs_setup'", ":", "'''\n if(spt.drop) {\n spt.drop.sobject_drop_setup( evt, bvr );\n }\n '''", ",", "\"cbjs_motion\"", ":", "'''\n spt.mouse._smart_default_drag_motion(evt, bvr, mouse_411);\n var target_el = spt.get_event_target(evt);\n target_el = spt.mouse.check_parent(target_el, bvr.drop_code);\n if (target_el) {\n var orig_border_color = target_el.getStyle('border-color');\n var orig_border_style = target_el.getStyle('border-style');\n target_el.setStyle('border','dashed 2px ' + bvr.border_color);\n if (!target_el.getAttribute('orig_border_color')) {\n target_el.setAttribute('orig_border_color', orig_border_color);\n target_el.setAttribute('orig_border_style', orig_border_style);\n }\n }\n '''", ",", "\"cbjs_action\"", ":", "'''\n if (spt.drop) {\n spt.drop.sobject_drop_action(evt, bvr)\n }\n\n var dst_el = spt.get_event_target(evt);\n var src_el = spt.behavior.get_bvr_src(bvr);\n\n /* Keeping this around for later use */\n var dst_row = dst_el.getParent(\".spt_table_row\");\n var dst_search_key = dst_row.getAttribute(\"spt_search_key\");\n\n var src_row = src_el.getParent(\".spt_table_row\");\n var src_search_key = src_row.getAttribute(\"spt_search_key\");\n\n '''", "}", ")", "# selection behaviors", "embedded_table", "=", "self", ".", "kwargs", ".", "get", "(", "\"__hidden__\"", ")", "in", "[", "True", ",", "'true'", "]", "if", "not", "embedded_table", ":", "table", ".", "add_relay_behavior", "(", "{", "'type'", ":", "'click'", ",", "'bvr_match_class'", ":", "'spt_table_select'", ",", "'cbjs_action'", ":", "'''\n\n if (evt.shift == true) return;\n\n spt.table.set_table(bvr.src_el);\n var row = bvr.src_el.getParent(\".spt_table_row\");\n\n if (row.hasClass(\"spt_table_selected\")) {\n spt.table.unselect_row(row);\n }\n else {\n spt.table.select_row(row);\n }\n\n\n \n '''", "}", ")", "table", ".", "add_relay_behavior", "(", "{", "'type'", ":", "'click'", ",", "'bvr_match_class'", ":", "'spt_table_select'", ",", "'modkeys'", ":", "'SHIFT'", ",", "'cbjs_action'", ":", "'''\n if (evt.shift != true) return;\n\n spt.table.set_table(bvr.src_el);\n var row = bvr.src_el.getParent(\".spt_table_row\");\n\n var rows = spt.table.get_all_rows();\n var last_selected = spt.table.last_selected_row;\n var last_index = -1;\n var cur_index = -1;\n for (var i = 0; i < rows.length; i++) {\n if (rows[i] == last_selected) {\n last_index = i;\n }\n if (rows[i] == row) {\n cur_index = i;\n }\n\n if (cur_index != -1 && last_index != -1) {\n break;\n }\n\n }\n var start_index;\n var end_index;\n if (last_index < cur_index) {\n start_index = last_index;\n end_index = cur_index;\n }\n else {\n start_index = cur_index;\n end_index = last_index;\n }\n\n for (var i = start_index; i < end_index+1; i++) {\n spt.table.select_row(rows[i]);\n }\n\n\n '''", "}", ")", "# collapse groups", "from", "tactic", ".", "ui", ".", "widget", ".", "swap_display_wdg", "import", "SwapDisplayWdg", "SwapDisplayWdg", ".", "handle_top", "(", "table", ")", "table", ".", "add_relay_behavior", "(", "{", "'type'", ":", "'click'", ",", "'bvr_match_class'", ":", "'spt_group_row_collapse'", ",", "'cbjs_action'", ":", "'''\n spt.table.set_table(bvr.src_el);\n var row = bvr.src_el.getParent(\".spt_group_row\");\n spt.table.collapse_group(row);\n '''", "}", ")", "# indicator that a cell is editable", "table", ".", "add_behavior", "(", "{", "'type'", ":", "'load'", ",", "'cbjs_action'", ":", "'''\n bvr.src_el.addEvent('mouseover:relay(.spt_cell_edit)',\n function(event, src_el) {\n\n if (src_el.hasClass(\"spt_cell_never_edit\")) {\n }\n else if (src_el.hasClass(\"spt_cell_insert_no_edit\")) {\n src_el.setStyle(\"background-image\", \"url(/context/icons/custom/no_edit.png)\" );\n }\n else {\n }\n\n } )\n\n bvr.src_el.addEvent('mouseout:relay(.spt_cell_edit)',\n function(event, src_el) {\n src_el.setStyle(\"background-image\", \"\" );\n } )\n '''", "}", ")", "# row highlighting", "if", "self", ".", "kwargs", ".", "get", "(", "\"show_row_highlight\"", ")", "not", "in", "[", "False", ",", "'false'", "]", ":", "table", ".", "add_behavior", "(", "{", "'type'", ":", "'load'", ",", "'cbjs_action'", ":", "'''\n bvr.src_el.addEvent('mouseover:relay(.spt_table_row)',\n function(event, src_el) {\n // remember the original color\n src_el.addClass(\"spt_row_hover\");\n src_el.setAttribute(\"spt_hover_background\", src_el.getStyle(\"background-color\"));\n spt.mouse.table_layout_hover_over({}, {src_el: src_el, add_color_modifier: -5});\n } )\n\n bvr.src_el.addEvent('mouseout:relay(.spt_table_row)',\n function(event, src_el) {\n src_el.removeClass(\"spt_row_hover\");\n src_el.setAttribute(\"spt_hover_background\", \"\");\n spt.mouse.table_layout_hover_out({}, {src_el: src_el});\n } )\n '''", "}", ")", "# set styles at the table level to be relayed down", "border_color", "=", "table", ".", "get_color", "(", "\"table_border\"", ",", "default", "=", "\"border\"", ")", "select_styles", "=", "{", "\"width\"", ":", "\"30px\"", ",", "\"min-width\"", ":", "\"30px\"", "}", "cell_styles", "=", "{", "}", "show_border", "=", "self", ".", "kwargs", ".", "get", "(", "\"show_border\"", ")", "if", "show_border", "in", "[", "'horizontal'", "]", ":", "cell_styles", "[", "\"border-bottom\"", "]", "=", "\"solid 1px %s\"", "%", "border_color", "cell_styles", "[", "\"padding\"", "]", "=", "\"3px\"", "select_styles", "[", "\"border-bottom\"", "]", "=", "\"solid 1px %s\"", "%", "border_color", "elif", "show_border", "not", "in", "[", "False", ",", "\"false\"", ",", "\"none\"", "]", ":", "cell_styles", "[", "\"border\"", "]", "=", "\"solid 1px %s\"", "%", "border_color", "cell_styles", "[", "\"padding\"", "]", "=", "\"3px\"", "select_styles", "[", "\"border\"", "]", "=", "\"solid 1px %s\"", "%", "border_color", "table", ".", "add_smart_styles", "(", "\"spt_table_select\"", ",", "select_styles", ")", "table", ".", "add_smart_styles", "(", "\"spt_cell_edit\"", ",", "cell_styles", ")", "is_editable", "=", "self", ".", "kwargs", ".", "get", "(", "\"is_editable\"", ")", "# Edit behavior", "if", "is_editable", "in", "[", "False", ",", "'false'", "]", ":", "is_editable", "=", "False", "else", ":", "is_editable", "=", "True", "# Check user access", "access_keys", "=", "self", ".", "_get_access_keys", "(", "\"edit\"", ",", "project_code", ")", "if", "security", ".", "check_access", "(", "\"builtin\"", ",", "access_keys", ",", "\"edit\"", ")", ":", "is_editable", "=", "True", "else", ":", "is_editable", "=", "False", "self", ".", "view_editable", "=", "False", "if", "is_editable", ":", "table", ".", "add_relay_behavior", "(", "{", "'type'", ":", "'click'", ",", "'bvr_match_class'", ":", "'spt_cell_edit'", ",", "'cbjs_action'", ":", "'''\n\n spt.table.set_table(bvr.src_el);\n var cell = bvr.src_el;\n // no action for the bottom row\n if (!cell.getParent('spt_table_bottom_row.spt_table_bottom_row'))\n spt.table.show_edit(cell);\n return;\n '''", "}", ")", "#table.add_smart_styles( \"spt_table_header\", {", "# \"background-repeat\": \"no-repeat\",", "# \"background-position\": \"top center\"", "#} )", "if", "self", ".", "kwargs", ".", "get", "(", "\"show_group_highlight\"", ")", "not", "in", "[", "False", ",", "'false'", "]", ":", "# group mouse over color", "table", ".", "add_relay_behavior", "(", "{", "'type'", ":", "\"mouseover\"", ",", "'bvr_match_class'", ":", "'spt_group_row'", ",", "'cbjs_action'", ":", "\"spt.mouse.table_layout_hover_over({}, {src_el: bvr.src_el, add_color_modifier: -5})\"", "}", ")", "table", ".", "add_relay_behavior", "(", "{", "'type'", ":", "\"mouseout\"", ",", "'bvr_match_class'", ":", "'spt_group_row'", ",", "'cbjs_action'", ":", "\"spt.mouse.table_layout_hover_out({}, {src_el: bvr.src_el})\"", "}", ")", "border_color", "=", "table", ".", "get_color", "(", "\"table_border\"", ",", "-", "10", ",", "default", "=", "\"border\"", ")", "table", ".", "add_smart_styles", "(", "\"spt_group_row\"", ",", "{", "'border'", ":", "'solid 1px %s'", "%", "border_color", "}", ")" ]
https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/src/tactic/ui/panel/table_layout_wdg.py#L1772-L2197
Sefaria/Sefaria-Project
506752f49394fadebae283d525af8276eb2e241e
sefaria/model/version_state.py
python
StateNode.ja
(self, lang, key="availableTexts")
return JaggedIntArray(self.var(lang, key))
:param lang: "he", "en", or "all" :param addr: :return:
:param lang: "he", "en", or "all" :param addr: :return:
[ ":", "param", "lang", ":", "he", "en", "or", "all", ":", "param", "addr", ":", ":", "return", ":" ]
def ja(self, lang, key="availableTexts"): """ :param lang: "he", "en", or "all" :param addr: :return: """ return JaggedIntArray(self.var(lang, key))
[ "def", "ja", "(", "self", ",", "lang", ",", "key", "=", "\"availableTexts\"", ")", ":", "return", "JaggedIntArray", "(", "self", ".", "var", "(", "lang", ",", "key", ")", ")" ]
https://github.com/Sefaria/Sefaria-Project/blob/506752f49394fadebae283d525af8276eb2e241e/sefaria/model/version_state.py#L436-L442
TeamvisionCorp/TeamVision
aa2a57469e430ff50cce21174d8f280efa0a83a7
distribute/0.0.5/build_shell/teamvision/teamvision/project/views/autotask_view.py
python
index_list
(request)
return render_to_response('autotask/home_autotask_index.html',{'request':vm_myplace},context_instance=RequestContext(request))
index page
index page
[ "index", "page" ]
def index_list(request): ''' index page''' vm_myplace=VM_Home(request.user) return render_to_response('autotask/home_autotask_index.html',{'request':vm_myplace},context_instance=RequestContext(request))
[ "def", "index_list", "(", "request", ")", ":", "vm_myplace", "=", "VM_Home", "(", "request", ".", "user", ")", "return", "render_to_response", "(", "'autotask/home_autotask_index.html'", ",", "{", "'request'", ":", "vm_myplace", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
https://github.com/TeamvisionCorp/TeamVision/blob/aa2a57469e430ff50cce21174d8f280efa0a83a7/distribute/0.0.5/build_shell/teamvision/teamvision/project/views/autotask_view.py#L32-L35
ansible/awx
15c7a3f85b5e948f011c67111c4433a38c4544e9
awx/api/views/root.py
python
ApiVersionRootView.get
(self, request, format=None)
return Response(data)
List top level resources
List top level resources
[ "List", "top", "level", "resources" ]
def get(self, request, format=None): '''List top level resources''' data = OrderedDict() data['ping'] = reverse('api:api_v2_ping_view', request=request) data['instances'] = reverse('api:instance_list', request=request) data['instance_groups'] = reverse('api:instance_group_list', request=request) data['config'] = reverse('api:api_v2_config_view', request=request) data['settings'] = reverse('api:setting_category_list', request=request) data['me'] = reverse('api:user_me_list', request=request) data['dashboard'] = reverse('api:dashboard_view', request=request) data['organizations'] = reverse('api:organization_list', request=request) data['users'] = reverse('api:user_list', request=request) data['execution_environments'] = reverse('api:execution_environment_list', request=request) data['projects'] = reverse('api:project_list', request=request) data['project_updates'] = reverse('api:project_update_list', request=request) data['teams'] = reverse('api:team_list', request=request) data['credentials'] = reverse('api:credential_list', request=request) data['credential_types'] = reverse('api:credential_type_list', request=request) data['credential_input_sources'] = reverse('api:credential_input_source_list', request=request) data['applications'] = reverse('api:o_auth2_application_list', request=request) data['tokens'] = reverse('api:o_auth2_token_list', request=request) data['metrics'] = reverse('api:metrics_view', request=request) data['inventory'] = reverse('api:inventory_list', request=request) data['inventory_sources'] = reverse('api:inventory_source_list', request=request) data['inventory_updates'] = reverse('api:inventory_update_list', request=request) data['groups'] = reverse('api:group_list', request=request) data['hosts'] = reverse('api:host_list', request=request) data['job_templates'] = reverse('api:job_template_list', request=request) data['jobs'] = reverse('api:job_list', request=request) data['ad_hoc_commands'] = reverse('api:ad_hoc_command_list', request=request) data['system_job_templates'] = reverse('api:system_job_template_list', request=request) data['system_jobs'] = reverse('api:system_job_list', request=request) data['schedules'] = reverse('api:schedule_list', request=request) data['roles'] = reverse('api:role_list', request=request) data['notification_templates'] = reverse('api:notification_template_list', request=request) data['notifications'] = reverse('api:notification_list', request=request) data['labels'] = reverse('api:label_list', request=request) data['unified_job_templates'] = reverse('api:unified_job_template_list', request=request) data['unified_jobs'] = reverse('api:unified_job_list', request=request) data['activity_stream'] = reverse('api:activity_stream_list', request=request) data['workflow_job_templates'] = reverse('api:workflow_job_template_list', request=request) data['workflow_jobs'] = reverse('api:workflow_job_list', request=request) data['workflow_approvals'] = reverse('api:workflow_approval_list', request=request) data['workflow_job_template_nodes'] = reverse('api:workflow_job_template_node_list', request=request) data['workflow_job_nodes'] = reverse('api:workflow_job_node_list', request=request) data['mesh_visualizer'] = reverse('api:mesh_visualizer_view', request=request) return Response(data)
[ "def", "get", "(", "self", ",", "request", ",", "format", "=", "None", ")", ":", "data", "=", "OrderedDict", "(", ")", "data", "[", "'ping'", "]", "=", "reverse", "(", "'api:api_v2_ping_view'", ",", "request", "=", "request", ")", "data", "[", "'instances'", "]", "=", "reverse", "(", "'api:instance_list'", ",", "request", "=", "request", ")", "data", "[", "'instance_groups'", "]", "=", "reverse", "(", "'api:instance_group_list'", ",", "request", "=", "request", ")", "data", "[", "'config'", "]", "=", "reverse", "(", "'api:api_v2_config_view'", ",", "request", "=", "request", ")", "data", "[", "'settings'", "]", "=", "reverse", "(", "'api:setting_category_list'", ",", "request", "=", "request", ")", "data", "[", "'me'", "]", "=", "reverse", "(", "'api:user_me_list'", ",", "request", "=", "request", ")", "data", "[", "'dashboard'", "]", "=", "reverse", "(", "'api:dashboard_view'", ",", "request", "=", "request", ")", "data", "[", "'organizations'", "]", "=", "reverse", "(", "'api:organization_list'", ",", "request", "=", "request", ")", "data", "[", "'users'", "]", "=", "reverse", "(", "'api:user_list'", ",", "request", "=", "request", ")", "data", "[", "'execution_environments'", "]", "=", "reverse", "(", "'api:execution_environment_list'", ",", "request", "=", "request", ")", "data", "[", "'projects'", "]", "=", "reverse", "(", "'api:project_list'", ",", "request", "=", "request", ")", "data", "[", "'project_updates'", "]", "=", "reverse", "(", "'api:project_update_list'", ",", "request", "=", "request", ")", "data", "[", "'teams'", "]", "=", "reverse", "(", "'api:team_list'", ",", "request", "=", "request", ")", "data", "[", "'credentials'", "]", "=", "reverse", "(", "'api:credential_list'", ",", "request", "=", "request", ")", "data", "[", "'credential_types'", "]", "=", "reverse", "(", "'api:credential_type_list'", ",", "request", "=", "request", ")", "data", "[", "'credential_input_sources'", "]", "=", "reverse", "(", "'api:credential_input_source_list'", ",", "request", "=", "request", ")", "data", "[", "'applications'", "]", "=", "reverse", "(", "'api:o_auth2_application_list'", ",", "request", "=", "request", ")", "data", "[", "'tokens'", "]", "=", "reverse", "(", "'api:o_auth2_token_list'", ",", "request", "=", "request", ")", "data", "[", "'metrics'", "]", "=", "reverse", "(", "'api:metrics_view'", ",", "request", "=", "request", ")", "data", "[", "'inventory'", "]", "=", "reverse", "(", "'api:inventory_list'", ",", "request", "=", "request", ")", "data", "[", "'inventory_sources'", "]", "=", "reverse", "(", "'api:inventory_source_list'", ",", "request", "=", "request", ")", "data", "[", "'inventory_updates'", "]", "=", "reverse", "(", "'api:inventory_update_list'", ",", "request", "=", "request", ")", "data", "[", "'groups'", "]", "=", "reverse", "(", "'api:group_list'", ",", "request", "=", "request", ")", "data", "[", "'hosts'", "]", "=", "reverse", "(", "'api:host_list'", ",", "request", "=", "request", ")", "data", "[", "'job_templates'", "]", "=", "reverse", "(", "'api:job_template_list'", ",", "request", "=", "request", ")", "data", "[", "'jobs'", "]", "=", "reverse", "(", "'api:job_list'", ",", "request", "=", "request", ")", "data", "[", "'ad_hoc_commands'", "]", "=", "reverse", "(", "'api:ad_hoc_command_list'", ",", "request", "=", "request", ")", "data", "[", "'system_job_templates'", "]", "=", "reverse", "(", "'api:system_job_template_list'", ",", "request", "=", "request", ")", "data", "[", "'system_jobs'", "]", "=", "reverse", "(", "'api:system_job_list'", ",", "request", "=", "request", ")", "data", "[", "'schedules'", "]", "=", "reverse", "(", "'api:schedule_list'", ",", "request", "=", "request", ")", "data", "[", "'roles'", "]", "=", "reverse", "(", "'api:role_list'", ",", "request", "=", "request", ")", "data", "[", "'notification_templates'", "]", "=", "reverse", "(", "'api:notification_template_list'", ",", "request", "=", "request", ")", "data", "[", "'notifications'", "]", "=", "reverse", "(", "'api:notification_list'", ",", "request", "=", "request", ")", "data", "[", "'labels'", "]", "=", "reverse", "(", "'api:label_list'", ",", "request", "=", "request", ")", "data", "[", "'unified_job_templates'", "]", "=", "reverse", "(", "'api:unified_job_template_list'", ",", "request", "=", "request", ")", "data", "[", "'unified_jobs'", "]", "=", "reverse", "(", "'api:unified_job_list'", ",", "request", "=", "request", ")", "data", "[", "'activity_stream'", "]", "=", "reverse", "(", "'api:activity_stream_list'", ",", "request", "=", "request", ")", "data", "[", "'workflow_job_templates'", "]", "=", "reverse", "(", "'api:workflow_job_template_list'", ",", "request", "=", "request", ")", "data", "[", "'workflow_jobs'", "]", "=", "reverse", "(", "'api:workflow_job_list'", ",", "request", "=", "request", ")", "data", "[", "'workflow_approvals'", "]", "=", "reverse", "(", "'api:workflow_approval_list'", ",", "request", "=", "request", ")", "data", "[", "'workflow_job_template_nodes'", "]", "=", "reverse", "(", "'api:workflow_job_template_node_list'", ",", "request", "=", "request", ")", "data", "[", "'workflow_job_nodes'", "]", "=", "reverse", "(", "'api:workflow_job_node_list'", ",", "request", "=", "request", ")", "data", "[", "'mesh_visualizer'", "]", "=", "reverse", "(", "'api:mesh_visualizer_view'", ",", "request", "=", "request", ")", "return", "Response", "(", "data", ")" ]
https://github.com/ansible/awx/blob/15c7a3f85b5e948f011c67111c4433a38c4544e9/awx/api/views/root.py#L81-L127
ireaderlab/zkdash
a9e27e9cc63dcfbb483a1fdfa00c98fd0b079739
conf/init_settings.py
python
create_settings_module
(file_name)
return module
create settings module from config file
create settings module from config file
[ "create", "settings", "module", "from", "config", "file" ]
def create_settings_module(file_name): """ create settings module from config file """ conf_data = None with open(file_name, 'r') as conf_file: conf_data = yaml.load(conf_file) if not isinstance(conf_data, dict): raise Exception("config file not parsed correctly") module = imp.new_module('settings') module.__dict__.update(conf_data) module.__dict__.update({'OPTIONS': options}) return module
[ "def", "create_settings_module", "(", "file_name", ")", ":", "conf_data", "=", "None", "with", "open", "(", "file_name", ",", "'r'", ")", "as", "conf_file", ":", "conf_data", "=", "yaml", ".", "load", "(", "conf_file", ")", "if", "not", "isinstance", "(", "conf_data", ",", "dict", ")", ":", "raise", "Exception", "(", "\"config file not parsed correctly\"", ")", "module", "=", "imp", ".", "new_module", "(", "'settings'", ")", "module", ".", "__dict__", ".", "update", "(", "conf_data", ")", "module", ".", "__dict__", ".", "update", "(", "{", "'OPTIONS'", ":", "options", "}", ")", "return", "module" ]
https://github.com/ireaderlab/zkdash/blob/a9e27e9cc63dcfbb483a1fdfa00c98fd0b079739/conf/init_settings.py#L29-L41
inkscope/inkscope
8c4303691a17837c6d3b5c89b40b89d9f5de4252
inkscopeProbe/daemon.py
python
Daemon.status
(self)
give the current status of the process
give the current status of the process
[ "give", "the", "current", "status", "of", "the", "process" ]
def status(self): """ give the current status of the process """ try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: sys.exit(2); pid=None except SystemExit: sys.exit(); pid=None if psutil.pid_exists(pid): print "pid :",pid sys.exit(0) else: print "no such process running" sys.exit(2)
[ "def", "status", "(", "self", ")", ":", "try", ":", "pf", "=", "file", "(", "self", ".", "pidfile", ",", "'r'", ")", "pid", "=", "int", "(", "pf", ".", "read", "(", ")", ".", "strip", "(", ")", ")", "pf", ".", "close", "(", ")", "except", "IOError", ":", "sys", ".", "exit", "(", "2", ")", "pid", "=", "None", "except", "SystemExit", ":", "sys", ".", "exit", "(", ")", "pid", "=", "None", "if", "psutil", ".", "pid_exists", "(", "pid", ")", ":", "print", "\"pid :\"", ",", "pid", "sys", ".", "exit", "(", "0", ")", "else", ":", "print", "\"no such process running\"", "sys", ".", "exit", "(", "2", ")" ]
https://github.com/inkscope/inkscope/blob/8c4303691a17837c6d3b5c89b40b89d9f5de4252/inkscopeProbe/daemon.py#L132-L151
webrtc/apprtc
db975e22ea07a0c11a4179d4beb2feb31cf344f4
src/app_engine/probers.py
python
get_collider_probe_success_key
(instance_host)
return 'last_collider_probe_success_' + instance_host
Returns the memcache key for the last collider instance probing result.
Returns the memcache key for the last collider instance probing result.
[ "Returns", "the", "memcache", "key", "for", "the", "last", "collider", "instance", "probing", "result", "." ]
def get_collider_probe_success_key(instance_host): """Returns the memcache key for the last collider instance probing result.""" return 'last_collider_probe_success_' + instance_host
[ "def", "get_collider_probe_success_key", "(", "instance_host", ")", ":", "return", "'last_collider_probe_success_'", "+", "instance_host" ]
https://github.com/webrtc/apprtc/blob/db975e22ea07a0c11a4179d4beb2feb31cf344f4/src/app_engine/probers.py#L59-L61
nodejs/node-convergence-archive
e11fe0c2777561827cdb7207d46b0917ef3c42a7
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py
python
MakefileWriter._InstallableTargetInstallPath
(self)
return '$(builddir)/' + self.alias
Returns the location of the final output for an installable target.
Returns the location of the final output for an installable target.
[ "Returns", "the", "location", "of", "the", "final", "output", "for", "an", "installable", "target", "." ]
def _InstallableTargetInstallPath(self): """Returns the location of the final output for an installable target.""" # Xcode puts shared_library results into PRODUCT_DIR, and some gyp files # rely on this. Emulate this behavior for mac. # XXX(TooTallNate): disabling this code since we don't want this behavior... #if (self.type == 'shared_library' and # (self.flavor != 'mac' or self.toolset != 'target')): # # Install all shared libs into a common directory (per toolset) for # # convenient access with LD_LIBRARY_PATH. # return '$(builddir)/lib.%s/%s' % (self.toolset, self.alias) return '$(builddir)/' + self.alias
[ "def", "_InstallableTargetInstallPath", "(", "self", ")", ":", "# Xcode puts shared_library results into PRODUCT_DIR, and some gyp files", "# rely on this. Emulate this behavior for mac.", "# XXX(TooTallNate): disabling this code since we don't want this behavior...", "#if (self.type == 'shared_library' and", "# (self.flavor != 'mac' or self.toolset != 'target')):", "# # Install all shared libs into a common directory (per toolset) for", "# # convenient access with LD_LIBRARY_PATH.", "# return '$(builddir)/lib.%s/%s' % (self.toolset, self.alias)", "return", "'$(builddir)/'", "+", "self", ".", "alias" ]
https://github.com/nodejs/node-convergence-archive/blob/e11fe0c2777561827cdb7207d46b0917ef3c42a7/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py#L1887-L1898
mceSystems/node-jsc
90634f3064fab8e89a85b3942f0cc5054acc86fa
tools/gyp/pylib/gyp/common.py
python
DeepDependencyTargets
(target_dicts, roots)
return list(dependencies - set(roots))
Returns the recursive list of target dependencies.
Returns the recursive list of target dependencies.
[ "Returns", "the", "recursive", "list", "of", "target", "dependencies", "." ]
def DeepDependencyTargets(target_dicts, roots): """Returns the recursive list of target dependencies.""" dependencies = set() pending = set(roots) while pending: # Pluck out one. r = pending.pop() # Skip if visited already. if r in dependencies: continue # Add it. dependencies.add(r) # Add its children. spec = target_dicts[r] pending.update(set(spec.get('dependencies', []))) pending.update(set(spec.get('dependencies_original', []))) return list(dependencies - set(roots))
[ "def", "DeepDependencyTargets", "(", "target_dicts", ",", "roots", ")", ":", "dependencies", "=", "set", "(", ")", "pending", "=", "set", "(", "roots", ")", "while", "pending", ":", "# Pluck out one.", "r", "=", "pending", ".", "pop", "(", ")", "# Skip if visited already.", "if", "r", "in", "dependencies", ":", "continue", "# Add it.", "dependencies", ".", "add", "(", "r", ")", "# Add its children.", "spec", "=", "target_dicts", "[", "r", "]", "pending", ".", "update", "(", "set", "(", "spec", ".", "get", "(", "'dependencies'", ",", "[", "]", ")", ")", ")", "pending", ".", "update", "(", "set", "(", "spec", ".", "get", "(", "'dependencies_original'", ",", "[", "]", ")", ")", ")", "return", "list", "(", "dependencies", "-", "set", "(", "roots", ")", ")" ]
https://github.com/mceSystems/node-jsc/blob/90634f3064fab8e89a85b3942f0cc5054acc86fa/tools/gyp/pylib/gyp/common.py#L296-L312
odoo/odoo
8de8c196a137f4ebbf67d7c7c83fee36f873f5c8
addons/im_livechat/models/mail_channel.py
python
MailChannel._channel_message_notifications
(self, message, message_format=False)
return notifications
When a anonymous user create a mail.channel, the operator is not notify (to avoid massive polling when clicking on livechat button). So when the anonymous person is sending its FIRST message, the channel header should be added to the notification, since the user cannot be listining to the channel.
When a anonymous user create a mail.channel, the operator is not notify (to avoid massive polling when clicking on livechat button). So when the anonymous person is sending its FIRST message, the channel header should be added to the notification, since the user cannot be listining to the channel.
[ "When", "a", "anonymous", "user", "create", "a", "mail", ".", "channel", "the", "operator", "is", "not", "notify", "(", "to", "avoid", "massive", "polling", "when", "clicking", "on", "livechat", "button", ")", ".", "So", "when", "the", "anonymous", "person", "is", "sending", "its", "FIRST", "message", "the", "channel", "header", "should", "be", "added", "to", "the", "notification", "since", "the", "user", "cannot", "be", "listining", "to", "the", "channel", "." ]
def _channel_message_notifications(self, message, message_format=False): """ When a anonymous user create a mail.channel, the operator is not notify (to avoid massive polling when clicking on livechat button). So when the anonymous person is sending its FIRST message, the channel header should be added to the notification, since the user cannot be listining to the channel. """ notifications = super()._channel_message_notifications(message=message, message_format=message_format) for channel in self: # add uuid for private livechat channels to allow anonymous to listen if channel.channel_type == 'livechat' and channel.public == 'private': notifications.append([channel.uuid, 'mail.channel/new_message', notifications[0][2]]) if not message.author_id: unpinned_channel_partner = self.channel_last_seen_partner_ids.filtered(lambda cp: not cp.is_pinned) if unpinned_channel_partner: unpinned_channel_partner.write({'is_pinned': True}) notifications = self._channel_channel_notifications(unpinned_channel_partner.mapped('partner_id').ids) + notifications return notifications
[ "def", "_channel_message_notifications", "(", "self", ",", "message", ",", "message_format", "=", "False", ")", ":", "notifications", "=", "super", "(", ")", ".", "_channel_message_notifications", "(", "message", "=", "message", ",", "message_format", "=", "message_format", ")", "for", "channel", "in", "self", ":", "# add uuid for private livechat channels to allow anonymous to listen", "if", "channel", ".", "channel_type", "==", "'livechat'", "and", "channel", ".", "public", "==", "'private'", ":", "notifications", ".", "append", "(", "[", "channel", ".", "uuid", ",", "'mail.channel/new_message'", ",", "notifications", "[", "0", "]", "[", "2", "]", "]", ")", "if", "not", "message", ".", "author_id", ":", "unpinned_channel_partner", "=", "self", ".", "channel_last_seen_partner_ids", ".", "filtered", "(", "lambda", "cp", ":", "not", "cp", ".", "is_pinned", ")", "if", "unpinned_channel_partner", ":", "unpinned_channel_partner", ".", "write", "(", "{", "'is_pinned'", ":", "True", "}", ")", "notifications", "=", "self", ".", "_channel_channel_notifications", "(", "unpinned_channel_partner", ".", "mapped", "(", "'partner_id'", ")", ".", "ids", ")", "+", "notifications", "return", "notifications" ]
https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/addons/im_livechat/models/mail_channel.py#L33-L48
KhronosGroup/Vulkan-Docs
ee155139142a2a71b56238419bf0a6859f7b0a93
scripts/validitygenerator.py
python
ValidityOutputGenerator.null
(self)
return self.conventions.null
Preferred spelling of NULL. Delegates to the object implementing ConventionsBase.
Preferred spelling of NULL.
[ "Preferred", "spelling", "of", "NULL", "." ]
def null(self): """Preferred spelling of NULL. Delegates to the object implementing ConventionsBase. """ return self.conventions.null
[ "def", "null", "(", "self", ")", ":", "return", "self", ".", "conventions", ".", "null" ]
https://github.com/KhronosGroup/Vulkan-Docs/blob/ee155139142a2a71b56238419bf0a6859f7b0a93/scripts/validitygenerator.py#L101-L106
chagel/CNPROG
07fea9955202f0b23221081ca171192a6c7350f2
forum/management/commands/once_award_badges.py
python
Command.alpha_user
(self)
Before Jan 25, 2009(Chinese New Year Eve and enter into Beta for CNProg), every registered user will be awarded the "Alpha" badge if he has any activities.
Before Jan 25, 2009(Chinese New Year Eve and enter into Beta for CNProg), every registered user will be awarded the "Alpha" badge if he has any activities.
[ "Before", "Jan", "25", "2009", "(", "Chinese", "New", "Year", "Eve", "and", "enter", "into", "Beta", "for", "CNProg", ")", "every", "registered", "user", "will", "be", "awarded", "the", "Alpha", "badge", "if", "he", "has", "any", "activities", "." ]
def alpha_user(self): """ Before Jan 25, 2009(Chinese New Year Eve and enter into Beta for CNProg), every registered user will be awarded the "Alpha" badge if he has any activities. """ alpha_end_date = date(2009, 1, 25) if date.today() < alpha_end_date: badge = get_object_or_404(Badge, id=22) for user in User.objects.all(): award = Award.objects.filter(user=user, badge=badge) if award and not badge.multiple: continue activities = Activity.objects.filter(user=user) if len(activities) > 0: new_award = Award(user=user, badge=badge) new_award.save()
[ "def", "alpha_user", "(", "self", ")", ":", "alpha_end_date", "=", "date", "(", "2009", ",", "1", ",", "25", ")", "if", "date", ".", "today", "(", ")", "<", "alpha_end_date", ":", "badge", "=", "get_object_or_404", "(", "Badge", ",", "id", "=", "22", ")", "for", "user", "in", "User", ".", "objects", ".", "all", "(", ")", ":", "award", "=", "Award", ".", "objects", ".", "filter", "(", "user", "=", "user", ",", "badge", "=", "badge", ")", "if", "award", "and", "not", "badge", ".", "multiple", ":", "continue", "activities", "=", "Activity", ".", "objects", ".", "filter", "(", "user", "=", "user", ")", "if", "len", "(", "activities", ")", ">", "0", ":", "new_award", "=", "Award", "(", "user", "=", "user", ",", "badge", "=", "badge", ")", "new_award", ".", "save", "(", ")" ]
https://github.com/chagel/CNPROG/blob/07fea9955202f0b23221081ca171192a6c7350f2/forum/management/commands/once_award_badges.py#L111-L126
mceSystems/node-jsc
90634f3064fab8e89a85b3942f0cc5054acc86fa
tools/gyp/pylib/gyp/generator/make.py
python
_ValidateSourcesForOSX
(spec, all_sources)
Makes sure if duplicate basenames are not specified in the source list. Arguments: spec: The target dictionary containing the properties of the target.
Makes sure if duplicate basenames are not specified in the source list.
[ "Makes", "sure", "if", "duplicate", "basenames", "are", "not", "specified", "in", "the", "source", "list", "." ]
def _ValidateSourcesForOSX(spec, all_sources): """Makes sure if duplicate basenames are not specified in the source list. Arguments: spec: The target dictionary containing the properties of the target. """ if spec.get('type', None) != 'static_library': return basenames = {} for source in all_sources: name, ext = os.path.splitext(source) is_compiled_file = ext in [ '.c', '.cc', '.cpp', '.cxx', '.m', '.mm', '.s', '.S'] if not is_compiled_file: continue basename = os.path.basename(name) # Don't include extension. basenames.setdefault(basename, []).append(source) error = '' for basename, files in basenames.iteritems(): if len(files) > 1: error += ' %s: %s\n' % (basename, ' '.join(files)) if error: print('static library %s has several files with the same basename:\n' % spec['target_name'] + error + 'libtool on OS X will generate' + ' warnings for them.') raise GypError('Duplicate basenames in sources section, see list above')
[ "def", "_ValidateSourcesForOSX", "(", "spec", ",", "all_sources", ")", ":", "if", "spec", ".", "get", "(", "'type'", ",", "None", ")", "!=", "'static_library'", ":", "return", "basenames", "=", "{", "}", "for", "source", "in", "all_sources", ":", "name", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "source", ")", "is_compiled_file", "=", "ext", "in", "[", "'.c'", ",", "'.cc'", ",", "'.cpp'", ",", "'.cxx'", ",", "'.m'", ",", "'.mm'", ",", "'.s'", ",", "'.S'", "]", "if", "not", "is_compiled_file", ":", "continue", "basename", "=", "os", ".", "path", ".", "basename", "(", "name", ")", "# Don't include extension.", "basenames", ".", "setdefault", "(", "basename", ",", "[", "]", ")", ".", "append", "(", "source", ")", "error", "=", "''", "for", "basename", ",", "files", "in", "basenames", ".", "iteritems", "(", ")", ":", "if", "len", "(", "files", ")", ">", "1", ":", "error", "+=", "' %s: %s\\n'", "%", "(", "basename", ",", "' '", ".", "join", "(", "files", ")", ")", "if", "error", ":", "print", "(", "'static library %s has several files with the same basename:\\n'", "%", "spec", "[", "'target_name'", "]", "+", "error", "+", "'libtool on OS X will generate'", "+", "' warnings for them.'", ")", "raise", "GypError", "(", "'Duplicate basenames in sources section, see list above'", ")" ]
https://github.com/mceSystems/node-jsc/blob/90634f3064fab8e89a85b3942f0cc5054acc86fa/tools/gyp/pylib/gyp/generator/make.py#L633-L661
redapple0204/my-boring-python
1ab378e9d4f39ad920ff542ef3b2db68f0575a98
pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/requests/cookies.py
python
RequestsCookieJar._find_no_duplicates
(self, name, domain=None, path=None)
Both ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :raises KeyError: if cookie is not found :raises CookieConflictError: if there are multiple cookies that match name and optionally domain and path :return: cookie.value
Both ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests.
[ "Both", "__get_item__", "and", "get", "call", "this", "function", ":", "it", "s", "never", "used", "elsewhere", "in", "Requests", "." ]
def _find_no_duplicates(self, name, domain=None, path=None): """Both ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :raises KeyError: if cookie is not found :raises CookieConflictError: if there are multiple cookies that match name and optionally domain and path :return: cookie.value """ toReturn = None for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: if toReturn is not None: # if there are multiple cookies that meet passed in criteria raise CookieConflictError('There are multiple cookies with name, %r' % (name)) toReturn = cookie.value # we will eventually return this as long as no cookie conflict if toReturn: return toReturn raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
[ "def", "_find_no_duplicates", "(", "self", ",", "name", ",", "domain", "=", "None", ",", "path", "=", "None", ")", ":", "toReturn", "=", "None", "for", "cookie", "in", "iter", "(", "self", ")", ":", "if", "cookie", ".", "name", "==", "name", ":", "if", "domain", "is", "None", "or", "cookie", ".", "domain", "==", "domain", ":", "if", "path", "is", "None", "or", "cookie", ".", "path", "==", "path", ":", "if", "toReturn", "is", "not", "None", ":", "# if there are multiple cookies that meet passed in criteria", "raise", "CookieConflictError", "(", "'There are multiple cookies with name, %r'", "%", "(", "name", ")", ")", "toReturn", "=", "cookie", ".", "value", "# we will eventually return this as long as no cookie conflict", "if", "toReturn", ":", "return", "toReturn", "raise", "KeyError", "(", "'name=%r, domain=%r, path=%r'", "%", "(", "name", ",", "domain", ",", "path", ")", ")" ]
https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/requests/cookies.py#L376-L399
WuXianglong/GeekBlog
a4fe5e7de225c4891d498d8e9e8f9c0c47053b86
blog/geekblog/admin_tools/sites.py
python
custom_login
(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, current_app=None, extra_context=None)
return render_to_response(template_name, context, context_instance=RequestContext(request, current_app=current_app))
Displays the login form and handles the login action.
Displays the login form and handles the login action.
[ "Displays", "the", "login", "form", "and", "handles", "the", "login", "action", "." ]
def custom_login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, current_app=None, extra_context=None): """ Displays the login form and handles the login action. """ redirect_to = request.REQUEST.get(redirect_field_name, '') if request.method == "POST": form = authentication_form(data=request.POST, request=request) if form.is_valid(): # Ensure the user-originating redirection url is safe. if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL) # Okay, security checks complete. Log the user in. auth_login(request, form.get_user()) if request.session.test_cookie_worked(): request.session.delete_test_cookie() return HttpResponseRedirect(redirect_to) else: form = authentication_form(request) request.session.set_test_cookie() current_site = get_current_site(request) context = { 'form': form, 'site': current_site, 'site_name': current_site.name, redirect_field_name: redirect_to, } if extra_context is not None: context.update(extra_context) return render_to_response(template_name, context, context_instance=RequestContext(request, current_app=current_app))
[ "def", "custom_login", "(", "request", ",", "template_name", "=", "'registration/login.html'", ",", "redirect_field_name", "=", "REDIRECT_FIELD_NAME", ",", "authentication_form", "=", "AuthenticationForm", ",", "current_app", "=", "None", ",", "extra_context", "=", "None", ")", ":", "redirect_to", "=", "request", ".", "REQUEST", ".", "get", "(", "redirect_field_name", ",", "''", ")", "if", "request", ".", "method", "==", "\"POST\"", ":", "form", "=", "authentication_form", "(", "data", "=", "request", ".", "POST", ",", "request", "=", "request", ")", "if", "form", ".", "is_valid", "(", ")", ":", "# Ensure the user-originating redirection url is safe.", "if", "not", "is_safe_url", "(", "url", "=", "redirect_to", ",", "host", "=", "request", ".", "get_host", "(", ")", ")", ":", "redirect_to", "=", "resolve_url", "(", "settings", ".", "LOGIN_REDIRECT_URL", ")", "# Okay, security checks complete. Log the user in.", "auth_login", "(", "request", ",", "form", ".", "get_user", "(", ")", ")", "if", "request", ".", "session", ".", "test_cookie_worked", "(", ")", ":", "request", ".", "session", ".", "delete_test_cookie", "(", ")", "return", "HttpResponseRedirect", "(", "redirect_to", ")", "else", ":", "form", "=", "authentication_form", "(", "request", ")", "request", ".", "session", ".", "set_test_cookie", "(", ")", "current_site", "=", "get_current_site", "(", "request", ")", "context", "=", "{", "'form'", ":", "form", ",", "'site'", ":", "current_site", ",", "'site_name'", ":", "current_site", ".", "name", ",", "redirect_field_name", ":", "redirect_to", ",", "}", "if", "extra_context", "is", "not", "None", ":", "context", ".", "update", "(", "extra_context", ")", "return", "render_to_response", "(", "template_name", ",", "context", ",", "context_instance", "=", "RequestContext", "(", "request", ",", "current_app", "=", "current_app", ")", ")" ]
https://github.com/WuXianglong/GeekBlog/blob/a4fe5e7de225c4891d498d8e9e8f9c0c47053b86/blog/geekblog/admin_tools/sites.py#L21-L58
silklabs/silk
08c273949086350aeddd8e23e92f0f79243f446f
node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.AdjustLibraries
(self, libraries, config_name=None)
return libraries
Transforms entries like 'Cocoa.framework' in libraries into entries like '-framework Cocoa', 'libcrypto.dylib' into '-lcrypto', etc.
Transforms entries like 'Cocoa.framework' in libraries into entries like '-framework Cocoa', 'libcrypto.dylib' into '-lcrypto', etc.
[ "Transforms", "entries", "like", "Cocoa", ".", "framework", "in", "libraries", "into", "entries", "like", "-", "framework", "Cocoa", "libcrypto", ".", "dylib", "into", "-", "lcrypto", "etc", "." ]
def AdjustLibraries(self, libraries, config_name=None): """Transforms entries like 'Cocoa.framework' in libraries into entries like '-framework Cocoa', 'libcrypto.dylib' into '-lcrypto', etc. """ libraries = [self._AdjustLibrary(library, config_name) for library in libraries] return libraries
[ "def", "AdjustLibraries", "(", "self", ",", "libraries", ",", "config_name", "=", "None", ")", ":", "libraries", "=", "[", "self", ".", "_AdjustLibrary", "(", "library", ",", "config_name", ")", "for", "library", "in", "libraries", "]", "return", "libraries" ]
https://github.com/silklabs/silk/blob/08c273949086350aeddd8e23e92f0f79243f446f/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L1053-L1059
trigger-corp/browser-extensions
895c14ddb5713613c58c4af60b5dcf0d66fea552
generate/generate/utils.py
python
which
(program)
return None
http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
[ "http", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "377017", "/", "test", "-", "if", "-", "executable", "-", "exists", "-", "in", "-", "python" ]
def which(program): "http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python" def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) if sys.platform.startswith("win"): programs = [".".join((program, extension)) for extension in ("cmd", "exe", "bat")] programs.insert(0, program) else: programs = [program] for program_name in programs: fpath, fname = os.path.split(program_name) if fpath: if is_exe(program_name): LOG.debug("using {name} for {program}".format( name=program_name, program=program)) return program_name else: for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, program_name) if is_exe(exe_file): LOG.debug("using {name} for {program}".format( name=exe_file, program=program)) return exe_file return None
[ "def", "which", "(", "program", ")", ":", "def", "is_exe", "(", "fpath", ")", ":", "return", "os", ".", "path", ".", "isfile", "(", "fpath", ")", "and", "os", ".", "access", "(", "fpath", ",", "os", ".", "X_OK", ")", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ":", "programs", "=", "[", "\".\"", ".", "join", "(", "(", "program", ",", "extension", ")", ")", "for", "extension", "in", "(", "\"cmd\"", ",", "\"exe\"", ",", "\"bat\"", ")", "]", "programs", ".", "insert", "(", "0", ",", "program", ")", "else", ":", "programs", "=", "[", "program", "]", "for", "program_name", "in", "programs", ":", "fpath", ",", "fname", "=", "os", ".", "path", ".", "split", "(", "program_name", ")", "if", "fpath", ":", "if", "is_exe", "(", "program_name", ")", ":", "LOG", ".", "debug", "(", "\"using {name} for {program}\"", ".", "format", "(", "name", "=", "program_name", ",", "program", "=", "program", ")", ")", "return", "program_name", "else", ":", "for", "path", "in", "os", ".", "environ", "[", "\"PATH\"", "]", ".", "split", "(", "os", ".", "pathsep", ")", ":", "exe_file", "=", "os", ".", "path", ".", "join", "(", "path", ",", "program_name", ")", "if", "is_exe", "(", "exe_file", ")", ":", "LOG", ".", "debug", "(", "\"using {name} for {program}\"", ".", "format", "(", "name", "=", "exe_file", ",", "program", "=", "program", ")", ")", "return", "exe_file", "return", "None" ]
https://github.com/trigger-corp/browser-extensions/blob/895c14ddb5713613c58c4af60b5dcf0d66fea552/generate/generate/utils.py#L416-L442
nodejs/quic
5baab3f3a05548d3b51bea98868412b08766e34d
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py
python
_FixPath
(path)
return path
Convert paths to a form that will make sense in a vcproj file. Arguments: path: The path to convert, may contain / etc. Returns: The path with all slashes made into backslashes.
Convert paths to a form that will make sense in a vcproj file.
[ "Convert", "paths", "to", "a", "form", "that", "will", "make", "sense", "in", "a", "vcproj", "file", "." ]
def _FixPath(path): """Convert paths to a form that will make sense in a vcproj file. Arguments: path: The path to convert, may contain / etc. Returns: The path with all slashes made into backslashes. """ if fixpath_prefix and path and not os.path.isabs(path) and not path[0] == '$' and not _IsWindowsAbsPath(path): path = os.path.join(fixpath_prefix, path) path = path.replace('/', '\\') path = _NormalizedSource(path) if path and path[-1] == '\\': path = path[:-1] return path
[ "def", "_FixPath", "(", "path", ")", ":", "if", "fixpath_prefix", "and", "path", "and", "not", "os", ".", "path", ".", "isabs", "(", "path", ")", "and", "not", "path", "[", "0", "]", "==", "'$'", "and", "not", "_IsWindowsAbsPath", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "fixpath_prefix", ",", "path", ")", "path", "=", "path", ".", "replace", "(", "'/'", ",", "'\\\\'", ")", "path", "=", "_NormalizedSource", "(", "path", ")", "if", "path", "and", "path", "[", "-", "1", "]", "==", "'\\\\'", ":", "path", "=", "path", "[", ":", "-", "1", "]", "return", "path" ]
https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L156-L170
booktype/Booktype
a1fe45e873ca4381b0eee8ea1b2ee3489b8fbbc2
lib/booktype/convert/mpdf/converter.py
python
MPDFConverter.get_metadata
(self, book)
return dc_metadata
Returns metadata which will be passed to the PHP script. The idea is that we return certain metadata information which will be written to the configuration file. The idea is that booktype2mpdf.php script could also get some of the metadata information. :Args: - book: EPUB Book object :Returns: Returns dictionary with metadata information.
Returns metadata which will be passed to the PHP script.
[ "Returns", "metadata", "which", "will", "be", "passed", "to", "the", "PHP", "script", "." ]
def get_metadata(self, book): """Returns metadata which will be passed to the PHP script. The idea is that we return certain metadata information which will be written to the configuration file. The idea is that booktype2mpdf.php script could also get some of the metadata information. :Args: - book: EPUB Book object :Returns: Returns dictionary with metadata information. """ dc_metadata = { key: value[0][0] for key, value in book.metadata.get("http://purl.org/dc/elements/1.1/").iteritems() } m = book.metadata[ebooklib.epub.NAMESPACES["OPF"]] def _check(x): if x[1].get('property', '').startswith('add_meta_terms:'): return True return False for key, value in filter(_check, m[None]): dc_metadata[value.get('property')] = key dc_metadata['bkterms:dir'] = self.direction return dc_metadata
[ "def", "get_metadata", "(", "self", ",", "book", ")", ":", "dc_metadata", "=", "{", "key", ":", "value", "[", "0", "]", "[", "0", "]", "for", "key", ",", "value", "in", "book", ".", "metadata", ".", "get", "(", "\"http://purl.org/dc/elements/1.1/\"", ")", ".", "iteritems", "(", ")", "}", "m", "=", "book", ".", "metadata", "[", "ebooklib", ".", "epub", ".", "NAMESPACES", "[", "\"OPF\"", "]", "]", "def", "_check", "(", "x", ")", ":", "if", "x", "[", "1", "]", ".", "get", "(", "'property'", ",", "''", ")", ".", "startswith", "(", "'add_meta_terms:'", ")", ":", "return", "True", "return", "False", "for", "key", ",", "value", "in", "filter", "(", "_check", ",", "m", "[", "None", "]", ")", ":", "dc_metadata", "[", "value", ".", "get", "(", "'property'", ")", "]", "=", "key", "dc_metadata", "[", "'bkterms:dir'", "]", "=", "self", ".", "direction", "return", "dc_metadata" ]
https://github.com/booktype/Booktype/blob/a1fe45e873ca4381b0eee8ea1b2ee3489b8fbbc2/lib/booktype/convert/mpdf/converter.py#L253-L284
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/unclosured/lib/python2.7/stringold.py
python
expandtabs
(s, tabsize=8)
return res + line
expandtabs(s [,tabsize]) -> string Return a copy of the string s with all tab characters replaced by the appropriate number of spaces, depending on the current column, and the tabsize (default 8).
expandtabs(s [,tabsize]) -> string
[ "expandtabs", "(", "s", "[", "tabsize", "]", ")", "-", ">", "string" ]
def expandtabs(s, tabsize=8): """expandtabs(s [,tabsize]) -> string Return a copy of the string s with all tab characters replaced by the appropriate number of spaces, depending on the current column, and the tabsize (default 8). """ res = line = '' for c in s: if c == '\t': c = ' '*(tabsize - len(line) % tabsize) line = line + c if c == '\n': res = res + line line = '' return res + line
[ "def", "expandtabs", "(", "s", ",", "tabsize", "=", "8", ")", ":", "res", "=", "line", "=", "''", "for", "c", "in", "s", ":", "if", "c", "==", "'\\t'", ":", "c", "=", "' '", "*", "(", "tabsize", "-", "len", "(", "line", ")", "%", "tabsize", ")", "line", "=", "line", "+", "c", "if", "c", "==", "'\\n'", ":", "res", "=", "res", "+", "line", "line", "=", "''", "return", "res", "+", "line" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/stringold.py#L328-L344
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/unclosured/lib/python2.7/logging/__init__.py
python
Filter.__init__
(self, name='')
Initialize a filter. Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event.
Initialize a filter.
[ "Initialize", "a", "filter", "." ]
def __init__(self, name=''): """ Initialize a filter. Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event. """ self.name = name self.nlen = len(name)
[ "def", "__init__", "(", "self", ",", "name", "=", "''", ")", ":", "self", ".", "name", "=", "name", "self", ".", "nlen", "=", "len", "(", "name", ")" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/logging/__init__.py#L543-L552
weitechen/anafora
ce2ca2c20b3f432280eb5041a089f7713ec82537
src/anafora/views.py
python
getInprogressAnnotator
(request, projectName, corpusName, taskName, schemaName, modeName = None)
return HttpResponseForbidden("access not allowed")
get inprogress annotator by giving project name, corpus name, task name, and schema name. mode name is an option @type request: HTTPRequest @type projectName: str @type corpusName: str @type taskName: str @type schemaName: str @type modeName: str @rtype: HttpResponse
get inprogress annotator by giving project name, corpus name, task name, and schema name. mode name is an option
[ "get", "inprogress", "annotator", "by", "giving", "project", "name", "corpus", "name", "task", "name", "and", "schema", "name", ".", "mode", "name", "is", "an", "option" ]
def getInprogressAnnotator(request, projectName, corpusName, taskName, schemaName, modeName = None): """get inprogress annotator by giving project name, corpus name, task name, and schema name. mode name is an option @type request: HTTPRequest @type projectName: str @type corpusName: str @type taskName: str @type schemaName: str @type modeName: str @rtype: HttpResponse """ if isSchemaExist(schemaName, modeName) != True: return HttpResponseNotFound("schema file not found") if isAdjudicator(request): annotatorName = AnaforaProjectManager.getInprogressAnnotator(schemaName, projectName, corpusName, taskName) return HttpResponse(json.dumps(annotatorName)) return HttpResponseForbidden("access not allowed")
[ "def", "getInprogressAnnotator", "(", "request", ",", "projectName", ",", "corpusName", ",", "taskName", ",", "schemaName", ",", "modeName", "=", "None", ")", ":", "if", "isSchemaExist", "(", "schemaName", ",", "modeName", ")", "!=", "True", ":", "return", "HttpResponseNotFound", "(", "\"schema file not found\"", ")", "if", "isAdjudicator", "(", "request", ")", ":", "annotatorName", "=", "AnaforaProjectManager", ".", "getInprogressAnnotator", "(", "schemaName", ",", "projectName", ",", "corpusName", ",", "taskName", ")", "return", "HttpResponse", "(", "json", ".", "dumps", "(", "annotatorName", ")", ")", "return", "HttpResponseForbidden", "(", "\"access not allowed\"", ")" ]
https://github.com/weitechen/anafora/blob/ce2ca2c20b3f432280eb5041a089f7713ec82537/src/anafora/views.py#L284-L301
scottgchin/delta5_race_timer
fe4e0f46307b05c9384f3124189edc402d812ade
src/delta5server/server.py
python
hardwarelog
()
return render_template('hardwarelog.html')
Route to hardware log page.
Route to hardware log page.
[ "Route", "to", "hardware", "log", "page", "." ]
def hardwarelog(): '''Route to hardware log page.''' return render_template('hardwarelog.html')
[ "def", "hardwarelog", "(", ")", ":", "return", "render_template", "(", "'hardwarelog.html'", ")" ]
https://github.com/scottgchin/delta5_race_timer/blob/fe4e0f46307b05c9384f3124189edc402d812ade/src/delta5server/server.py#L311-L313
Southpaw-TACTIC/TACTIC
ba9b87aef0ee3b3ea51446f25b285ebbca06f62c
src/pyasm/widget/table_element_wdg.py
python
CheckboxColWdg.get_columns
(self)
return []
can override this to return a list \ of sobject's column names as identifier for value. Otherwise search_key is used
can override this to return a list \ of sobject's column names as identifier for value. Otherwise search_key is used
[ "can", "override", "this", "to", "return", "a", "list", "\\", "of", "sobject", "s", "column", "names", "as", "identifier", "for", "value", ".", "Otherwise", "search_key", "is", "used" ]
def get_columns(self): '''can override this to return a list \ of sobject's column names as identifier for value. Otherwise search_key is used ''' return []
[ "def", "get_columns", "(", "self", ")", ":", "return", "[", "]" ]
https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/src/pyasm/widget/table_element_wdg.py#L2113-L2118
jam-py/jam-py
0821492cdff8665928e0f093a4435aa64285a45c
jam/third_party/filelock.py
python
BaseFileLock._release
(self)
Releases the lock and sets self._lock_file_fd to None.
Releases the lock and sets self._lock_file_fd to None.
[ "Releases", "the", "lock", "and", "sets", "self", ".", "_lock_file_fd", "to", "None", "." ]
def _release(self): """ Releases the lock and sets self._lock_file_fd to None. """ raise NotImplementedError()
[ "def", "_release", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/jam-py/jam-py/blob/0821492cdff8665928e0f093a4435aa64285a45c/jam/third_party/filelock.py#L199-L203
almonk/Bind
03e9e98fb8b30a58cb4fc2829f06289fa9958897
public/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py
python
QuoteForRspFile
(arg)
return '"' + arg + '"'
Quote a command line argument so that it appears as one argument when processed via cmd.exe and parsed by CommandLineToArgvW (as is typical for Windows programs).
Quote a command line argument so that it appears as one argument when processed via cmd.exe and parsed by CommandLineToArgvW (as is typical for Windows programs).
[ "Quote", "a", "command", "line", "argument", "so", "that", "it", "appears", "as", "one", "argument", "when", "processed", "via", "cmd", ".", "exe", "and", "parsed", "by", "CommandLineToArgvW", "(", "as", "is", "typical", "for", "Windows", "programs", ")", "." ]
def QuoteForRspFile(arg): """Quote a command line argument so that it appears as one argument when processed via cmd.exe and parsed by CommandLineToArgvW (as is typical for Windows programs).""" # See http://goo.gl/cuFbX and http://goo.gl/dhPnp including the comment # threads. This is actually the quoting rules for CommandLineToArgvW, not # for the shell, because the shell doesn't do anything in Windows. This # works more or less because most programs (including the compiler, etc.) # use that function to handle command line arguments. # For a literal quote, CommandLineToArgvW requires 2n+1 backslashes # preceding it, and results in n backslashes + the quote. So we substitute # in 2* what we match, +1 more, plus the quote. arg = windows_quoter_regex.sub(lambda mo: 2 * mo.group(1) + '\\"', arg) # %'s also need to be doubled otherwise they're interpreted as batch # positional arguments. Also make sure to escape the % so that they're # passed literally through escaping so they can be singled to just the # original %. Otherwise, trying to pass the literal representation that # looks like an environment variable to the shell (e.g. %PATH%) would fail. arg = arg.replace('%', '%%') # These commands are used in rsp files, so no escaping for the shell (via ^) # is necessary. # Finally, wrap the whole thing in quotes so that the above quote rule # applies and whitespace isn't a word break. return '"' + arg + '"'
[ "def", "QuoteForRspFile", "(", "arg", ")", ":", "# See http://goo.gl/cuFbX and http://goo.gl/dhPnp including the comment", "# threads. This is actually the quoting rules for CommandLineToArgvW, not", "# for the shell, because the shell doesn't do anything in Windows. This", "# works more or less because most programs (including the compiler, etc.)", "# use that function to handle command line arguments.", "# For a literal quote, CommandLineToArgvW requires 2n+1 backslashes", "# preceding it, and results in n backslashes + the quote. So we substitute", "# in 2* what we match, +1 more, plus the quote.", "arg", "=", "windows_quoter_regex", ".", "sub", "(", "lambda", "mo", ":", "2", "*", "mo", ".", "group", "(", "1", ")", "+", "'\\\\\"'", ",", "arg", ")", "# %'s also need to be doubled otherwise they're interpreted as batch", "# positional arguments. Also make sure to escape the % so that they're", "# passed literally through escaping so they can be singled to just the", "# original %. Otherwise, trying to pass the literal representation that", "# looks like an environment variable to the shell (e.g. %PATH%) would fail.", "arg", "=", "arg", ".", "replace", "(", "'%'", ",", "'%%'", ")", "# These commands are used in rsp files, so no escaping for the shell (via ^)", "# is necessary.", "# Finally, wrap the whole thing in quotes so that the above quote rule", "# applies and whitespace isn't a word break.", "return", "'\"'", "+", "arg", "+", "'\"'" ]
https://github.com/almonk/Bind/blob/03e9e98fb8b30a58cb4fc2829f06289fa9958897/public/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L19-L46
nodejs/node-convergence-archive
e11fe0c2777561827cdb7207d46b0917ef3c42a7
tools/gyp/pylib/gyp/generator/cmake.py
python
SetFilesProperty
(output, source_names, property_name, values, sep)
Given a set of source files, sets the given property on them.
Given a set of source files, sets the given property on them.
[ "Given", "a", "set", "of", "source", "files", "sets", "the", "given", "property", "on", "them", "." ]
def SetFilesProperty(output, source_names, property_name, values, sep): """Given a set of source files, sets the given property on them.""" output.write('set_source_files_properties(\n') for source_name in source_names: output.write(' ') output.write(source_name) output.write('\n') output.write(' PROPERTIES\n ') output.write(property_name) output.write(' "') for value in values: output.write(CMakeStringEscape(value)) output.write(sep) output.write('"\n)\n')
[ "def", "SetFilesProperty", "(", "output", ",", "source_names", ",", "property_name", ",", "values", ",", "sep", ")", ":", "output", ".", "write", "(", "'set_source_files_properties(\\n'", ")", "for", "source_name", "in", "source_names", ":", "output", ".", "write", "(", "' '", ")", "output", ".", "write", "(", "source_name", ")", "output", ".", "write", "(", "'\\n'", ")", "output", ".", "write", "(", "' PROPERTIES\\n '", ")", "output", ".", "write", "(", "property_name", ")", "output", ".", "write", "(", "' \"'", ")", "for", "value", "in", "values", ":", "output", ".", "write", "(", "CMakeStringEscape", "(", "value", ")", ")", "output", ".", "write", "(", "sep", ")", "output", ".", "write", "(", "'\"\\n)\\n'", ")" ]
https://github.com/nodejs/node-convergence-archive/blob/e11fe0c2777561827cdb7207d46b0917ef3c42a7/tools/gyp/pylib/gyp/generator/cmake.py#L153-L166
jxcore/jxcore
b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410
deps/npm/node_modules/node-gyp/gyp/tools/graphviz.py
python
WriteGraph
(edges)
Print a graphviz graph to stdout. |edges| is a map of target to a list of other targets it depends on.
Print a graphviz graph to stdout. |edges| is a map of target to a list of other targets it depends on.
[ "Print", "a", "graphviz", "graph", "to", "stdout", ".", "|edges|", "is", "a", "map", "of", "target", "to", "a", "list", "of", "other", "targets", "it", "depends", "on", "." ]
def WriteGraph(edges): """Print a graphviz graph to stdout. |edges| is a map of target to a list of other targets it depends on.""" # Bucket targets by file. files = collections.defaultdict(list) for src, dst in edges.items(): build_file, target_name, toolset = ParseTarget(src) files[build_file].append(src) print 'digraph D {' print ' fontsize=8' # Used by subgraphs. print ' node [fontsize=8]' # Output nodes by file. We must first write out each node within # its file grouping before writing out any edges that may refer # to those nodes. for filename, targets in files.items(): if len(targets) == 1: # If there's only one node for this file, simplify # the display by making it a box without an internal node. target = targets[0] build_file, target_name, toolset = ParseTarget(target) print ' "%s" [shape=box, label="%s\\n%s"]' % (target, filename, target_name) else: # Group multiple nodes together in a subgraph. print ' subgraph "cluster_%s" {' % filename print ' label = "%s"' % filename for target in targets: build_file, target_name, toolset = ParseTarget(target) print ' "%s" [label="%s"]' % (target, target_name) print ' }' # Now that we've placed all the nodes within subgraphs, output all # the edges between nodes. for src, dsts in edges.items(): for dst in dsts: print ' "%s" -> "%s"' % (src, dst) print '}'
[ "def", "WriteGraph", "(", "edges", ")", ":", "# Bucket targets by file.", "files", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "src", ",", "dst", "in", "edges", ".", "items", "(", ")", ":", "build_file", ",", "target_name", ",", "toolset", "=", "ParseTarget", "(", "src", ")", "files", "[", "build_file", "]", ".", "append", "(", "src", ")", "print", "'digraph D {'", "print", "' fontsize=8'", "# Used by subgraphs.", "print", "' node [fontsize=8]'", "# Output nodes by file. We must first write out each node within", "# its file grouping before writing out any edges that may refer", "# to those nodes.", "for", "filename", ",", "targets", "in", "files", ".", "items", "(", ")", ":", "if", "len", "(", "targets", ")", "==", "1", ":", "# If there's only one node for this file, simplify", "# the display by making it a box without an internal node.", "target", "=", "targets", "[", "0", "]", "build_file", ",", "target_name", ",", "toolset", "=", "ParseTarget", "(", "target", ")", "print", "' \"%s\" [shape=box, label=\"%s\\\\n%s\"]'", "%", "(", "target", ",", "filename", ",", "target_name", ")", "else", ":", "# Group multiple nodes together in a subgraph.", "print", "' subgraph \"cluster_%s\" {'", "%", "filename", "print", "' label = \"%s\"'", "%", "filename", "for", "target", "in", "targets", ":", "build_file", ",", "target_name", ",", "toolset", "=", "ParseTarget", "(", "target", ")", "print", "' \"%s\" [label=\"%s\"]'", "%", "(", "target", ",", "target_name", ")", "print", "' }'", "# Now that we've placed all the nodes within subgraphs, output all", "# the edges between nodes.", "for", "src", ",", "dsts", "in", "edges", ".", "items", "(", ")", ":", "for", "dst", "in", "dsts", ":", "print", "' \"%s\" -> \"%s\"'", "%", "(", "src", ",", "dst", ")", "print", "'}'" ]
https://github.com/jxcore/jxcore/blob/b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410/deps/npm/node_modules/node-gyp/gyp/tools/graphviz.py#L43-L83
crits/crits
6b357daa5c3060cf622d3a3b0c7b41a9ca69c049
crits/core/api.py
python
CRITsSerializer.to_json
(self, data, options=None)
return json.dumps(data, sort_keys=True)
Respond with JSON formatted data. This is the default. :param data: The data to be worked on. :type data: dict for multiple objects, :class:`tastypie.bundle.Bundle` for a single object. :param options: Options to alter how this serializer works. :type options: dict :returns: str
Respond with JSON formatted data. This is the default.
[ "Respond", "with", "JSON", "formatted", "data", ".", "This", "is", "the", "default", "." ]
def to_json(self, data, options=None): """ Respond with JSON formatted data. This is the default. :param data: The data to be worked on. :type data: dict for multiple objects, :class:`tastypie.bundle.Bundle` for a single object. :param options: Options to alter how this serializer works. :type options: dict :returns: str """ options = options or {} username = options.get('username', None) # if this is a singular object, just return our internal to_json() # which handles the Embedded MongoEngine classes. if hasattr(data, 'obj'): if data.obj._has_method('sanitize'): data.obj.sanitize(username=username, rels=True) return data.obj.to_json() data = self._convert_mongoengine(data, options) return json.dumps(data, sort_keys=True)
[ "def", "to_json", "(", "self", ",", "data", ",", "options", "=", "None", ")", ":", "options", "=", "options", "or", "{", "}", "username", "=", "options", ".", "get", "(", "'username'", ",", "None", ")", "# if this is a singular object, just return our internal to_json()", "# which handles the Embedded MongoEngine classes.", "if", "hasattr", "(", "data", ",", "'obj'", ")", ":", "if", "data", ".", "obj", ".", "_has_method", "(", "'sanitize'", ")", ":", "data", ".", "obj", ".", "sanitize", "(", "username", "=", "username", ",", "rels", "=", "True", ")", "return", "data", ".", "obj", ".", "to_json", "(", ")", "data", "=", "self", ".", "_convert_mongoengine", "(", "data", ",", "options", ")", "return", "json", ".", "dumps", "(", "data", ",", "sort_keys", "=", "True", ")" ]
https://github.com/crits/crits/blob/6b357daa5c3060cf622d3a3b0c7b41a9ca69c049/crits/core/api.py#L198-L221
xl7dev/BurpSuite
d1d4bd4981a87f2f4c0c9744ad7c476336c813da
Extender/Sqlmap/thirdparty/odict/odict.py
python
_OrderedDict.__le__
(self, other)
return (self.items() <= other.items())
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> c = OrderedDict(((0, 3), (3, 2), (2, 1))) >>> e = OrderedDict(d) >>> c <= d True >>> d <= c False >>> d <= dict(c) Traceback (most recent call last): TypeError: Can only compare with other OrderedDicts >>> d <= e True
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> c = OrderedDict(((0, 3), (3, 2), (2, 1))) >>> e = OrderedDict(d) >>> c <= d True >>> d <= c False >>> d <= dict(c) Traceback (most recent call last): TypeError: Can only compare with other OrderedDicts >>> d <= e True
[ ">>>", "d", "=", "OrderedDict", "(((", "1", "3", ")", "(", "3", "2", ")", "(", "2", "1", ")))", ">>>", "c", "=", "OrderedDict", "(((", "0", "3", ")", "(", "3", "2", ")", "(", "2", "1", ")))", ">>>", "e", "=", "OrderedDict", "(", "d", ")", ">>>", "c", "<", "=", "d", "True", ">>>", "d", "<", "=", "c", "False", ">>>", "d", "<", "=", "dict", "(", "c", ")", "Traceback", "(", "most", "recent", "call", "last", ")", ":", "TypeError", ":", "Can", "only", "compare", "with", "other", "OrderedDicts", ">>>", "d", "<", "=", "e", "True" ]
def __le__(self, other): """ >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> c = OrderedDict(((0, 3), (3, 2), (2, 1))) >>> e = OrderedDict(d) >>> c <= d True >>> d <= c False >>> d <= dict(c) Traceback (most recent call last): TypeError: Can only compare with other OrderedDicts >>> d <= e True """ if not isinstance(other, OrderedDict): raise TypeError('Can only compare with other OrderedDicts') # FIXME: efficiency? # Generate both item lists for each compare return (self.items() <= other.items())
[ "def", "__le__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "OrderedDict", ")", ":", "raise", "TypeError", "(", "'Can only compare with other OrderedDicts'", ")", "# FIXME: efficiency?", "# Generate both item lists for each compare", "return", "(", "self", ".", "items", "(", ")", "<=", "other", ".", "items", "(", ")", ")" ]
https://github.com/xl7dev/BurpSuite/blob/d1d4bd4981a87f2f4c0c9744ad7c476336c813da/Extender/Sqlmap/thirdparty/odict/odict.py#L197-L216
mozilla/spidernode
aafa9e5273f954f272bb4382fc007af14674b4c2
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py
python
AndroidMkWriter.WriteRules
(self, rules, extra_sources, extra_outputs)
Write Makefile code for any 'rules' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these rules (used to make other pieces dependent on these rules)
Write Makefile code for any 'rules' from the gyp input.
[ "Write", "Makefile", "code", "for", "any", "rules", "from", "the", "gyp", "input", "." ]
def WriteRules(self, rules, extra_sources, extra_outputs): """Write Makefile code for any 'rules' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these rules (used to make other pieces dependent on these rules) """ if len(rules) == 0: return for rule in rules: if len(rule.get('rule_sources', [])) == 0: continue name = make.StringToMakefileVariable('%s_%s' % (self.relative_target, rule['rule_name'])) self.WriteLn('\n### Generated for rule "%s":' % name) self.WriteLn('# "%s":' % rule) inputs = rule.get('inputs') for rule_source in rule.get('rule_sources', []): (rule_source_dirname, rule_source_basename) = os.path.split(rule_source) (rule_source_root, rule_source_ext) = \ os.path.splitext(rule_source_basename) outputs = [self.ExpandInputRoot(out, rule_source_root, rule_source_dirname) for out in rule['outputs']] dirs = set() for out in outputs: if not out.startswith('$'): print ('WARNING: Rule for target %s writes output to local path %s' % (self.target, out)) dir = os.path.dirname(out) if dir: dirs.add(dir) extra_outputs += outputs if int(rule.get('process_outputs_as_sources', False)): extra_sources.extend(outputs) components = [] for component in rule['action']: component = self.ExpandInputRoot(component, rule_source_root, rule_source_dirname) if '$(RULE_SOURCES)' in component: component = component.replace('$(RULE_SOURCES)', rule_source) components.append(component) command = gyp.common.EncodePOSIXShellList(components) cd_action = 'cd $(gyp_local_path)/%s; ' % self.path command = cd_action + command if dirs: command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command # We set up a rule to build the first output, and then set up # a rule for each additional output to depend on the first. outputs = map(self.LocalPathify, outputs) main_output = outputs[0] self.WriteLn('%s: gyp_local_path := $(LOCAL_PATH)' % main_output) self.WriteLn('%s: gyp_var_prefix := $(GYP_VAR_PREFIX)' % main_output) self.WriteLn('%s: gyp_intermediate_dir := ' '$(abspath $(gyp_intermediate_dir))' % main_output) self.WriteLn('%s: gyp_shared_intermediate_dir := ' '$(abspath $(gyp_shared_intermediate_dir))' % main_output) # See explanation in WriteActions. self.WriteLn('%s: export PATH := ' '$(subst $(ANDROID_BUILD_PATHS),,$(PATH))' % main_output) main_output_deps = self.LocalPathify(rule_source) if inputs: main_output_deps += ' ' main_output_deps += ' '.join([self.LocalPathify(f) for f in inputs]) self.WriteLn('%s: %s $(GYP_TARGET_DEPENDENCIES)' % (main_output, main_output_deps)) self.WriteLn('\t%s\n' % command) for output in outputs[1:]: # Make each output depend on the main output, with an empty command # to force make to notice that the mtime has changed. self.WriteLn('%s: %s ;' % (output, main_output)) self.WriteLn() self.WriteLn()
[ "def", "WriteRules", "(", "self", ",", "rules", ",", "extra_sources", ",", "extra_outputs", ")", ":", "if", "len", "(", "rules", ")", "==", "0", ":", "return", "for", "rule", "in", "rules", ":", "if", "len", "(", "rule", ".", "get", "(", "'rule_sources'", ",", "[", "]", ")", ")", "==", "0", ":", "continue", "name", "=", "make", ".", "StringToMakefileVariable", "(", "'%s_%s'", "%", "(", "self", ".", "relative_target", ",", "rule", "[", "'rule_name'", "]", ")", ")", "self", ".", "WriteLn", "(", "'\\n### Generated for rule \"%s\":'", "%", "name", ")", "self", ".", "WriteLn", "(", "'# \"%s\":'", "%", "rule", ")", "inputs", "=", "rule", ".", "get", "(", "'inputs'", ")", "for", "rule_source", "in", "rule", ".", "get", "(", "'rule_sources'", ",", "[", "]", ")", ":", "(", "rule_source_dirname", ",", "rule_source_basename", ")", "=", "os", ".", "path", ".", "split", "(", "rule_source", ")", "(", "rule_source_root", ",", "rule_source_ext", ")", "=", "os", ".", "path", ".", "splitext", "(", "rule_source_basename", ")", "outputs", "=", "[", "self", ".", "ExpandInputRoot", "(", "out", ",", "rule_source_root", ",", "rule_source_dirname", ")", "for", "out", "in", "rule", "[", "'outputs'", "]", "]", "dirs", "=", "set", "(", ")", "for", "out", "in", "outputs", ":", "if", "not", "out", ".", "startswith", "(", "'$'", ")", ":", "print", "(", "'WARNING: Rule for target %s writes output to local path %s'", "%", "(", "self", ".", "target", ",", "out", ")", ")", "dir", "=", "os", ".", "path", ".", "dirname", "(", "out", ")", "if", "dir", ":", "dirs", ".", "add", "(", "dir", ")", "extra_outputs", "+=", "outputs", "if", "int", "(", "rule", ".", "get", "(", "'process_outputs_as_sources'", ",", "False", ")", ")", ":", "extra_sources", ".", "extend", "(", "outputs", ")", "components", "=", "[", "]", "for", "component", "in", "rule", "[", "'action'", "]", ":", "component", "=", "self", ".", "ExpandInputRoot", "(", "component", ",", "rule_source_root", ",", "rule_source_dirname", ")", "if", "'$(RULE_SOURCES)'", "in", "component", ":", "component", "=", "component", ".", "replace", "(", "'$(RULE_SOURCES)'", ",", "rule_source", ")", "components", ".", "append", "(", "component", ")", "command", "=", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "components", ")", "cd_action", "=", "'cd $(gyp_local_path)/%s; '", "%", "self", ".", "path", "command", "=", "cd_action", "+", "command", "if", "dirs", ":", "command", "=", "'mkdir -p %s'", "%", "' '", ".", "join", "(", "dirs", ")", "+", "'; '", "+", "command", "# We set up a rule to build the first output, and then set up", "# a rule for each additional output to depend on the first.", "outputs", "=", "map", "(", "self", ".", "LocalPathify", ",", "outputs", ")", "main_output", "=", "outputs", "[", "0", "]", "self", ".", "WriteLn", "(", "'%s: gyp_local_path := $(LOCAL_PATH)'", "%", "main_output", ")", "self", ".", "WriteLn", "(", "'%s: gyp_var_prefix := $(GYP_VAR_PREFIX)'", "%", "main_output", ")", "self", ".", "WriteLn", "(", "'%s: gyp_intermediate_dir := '", "'$(abspath $(gyp_intermediate_dir))'", "%", "main_output", ")", "self", ".", "WriteLn", "(", "'%s: gyp_shared_intermediate_dir := '", "'$(abspath $(gyp_shared_intermediate_dir))'", "%", "main_output", ")", "# See explanation in WriteActions.", "self", ".", "WriteLn", "(", "'%s: export PATH := '", "'$(subst $(ANDROID_BUILD_PATHS),,$(PATH))'", "%", "main_output", ")", "main_output_deps", "=", "self", ".", "LocalPathify", "(", "rule_source", ")", "if", "inputs", ":", "main_output_deps", "+=", "' '", "main_output_deps", "+=", "' '", ".", "join", "(", "[", "self", ".", "LocalPathify", "(", "f", ")", "for", "f", "in", "inputs", "]", ")", "self", ".", "WriteLn", "(", "'%s: %s $(GYP_TARGET_DEPENDENCIES)'", "%", "(", "main_output", ",", "main_output_deps", ")", ")", "self", ".", "WriteLn", "(", "'\\t%s\\n'", "%", "command", ")", "for", "output", "in", "outputs", "[", "1", ":", "]", ":", "# Make each output depend on the main output, with an empty command", "# to force make to notice that the mtime has changed.", "self", ".", "WriteLn", "(", "'%s: %s ;'", "%", "(", "output", ",", "main_output", ")", ")", "self", ".", "WriteLn", "(", ")", "self", ".", "WriteLn", "(", ")" ]
https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py#L326-L411
atom-community/ide-python
c046f9c2421713b34baa22648235541c5bb284fe
lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/__init__.py
python
check_modules
(project, match, root=None)
return unvendored, extensions
Verify that only vendored modules have been imported.
Verify that only vendored modules have been imported.
[ "Verify", "that", "only", "vendored", "modules", "have", "been", "imported", "." ]
def check_modules(project, match, root=None): """Verify that only vendored modules have been imported.""" if root is None: root = project_root(project) extensions = [] unvendored = {} for modname, mod in sys.modules.items(): if not match(modname, mod): continue if not hasattr(mod, '__file__'): # extension module extensions.append(modname) elif not mod.__file__.startswith(root): unvendored[modname] = mod.__file__ return unvendored, extensions
[ "def", "check_modules", "(", "project", ",", "match", ",", "root", "=", "None", ")", ":", "if", "root", "is", "None", ":", "root", "=", "project_root", "(", "project", ")", "extensions", "=", "[", "]", "unvendored", "=", "{", "}", "for", "modname", ",", "mod", "in", "sys", ".", "modules", ".", "items", "(", ")", ":", "if", "not", "match", "(", "modname", ",", "mod", ")", ":", "continue", "if", "not", "hasattr", "(", "mod", ",", "'__file__'", ")", ":", "# extension module", "extensions", ".", "append", "(", "modname", ")", "elif", "not", "mod", ".", "__file__", ".", "startswith", "(", "root", ")", ":", "unvendored", "[", "modname", "]", "=", "mod", ".", "__file__", "return", "unvendored", ",", "extensions" ]
https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/__init__.py#L90-L103
jam-py/jam-py
0821492cdff8665928e0f093a4435aa64285a45c
jam/third_party/sqlalchemy/sql/base.py
python
SchemaEventTarget._set_parent
(self, parent)
Associate with this SchemaEvent's parent object.
Associate with this SchemaEvent's parent object.
[ "Associate", "with", "this", "SchemaEvent", "s", "parent", "object", "." ]
def _set_parent(self, parent): """Associate with this SchemaEvent's parent object."""
[ "def", "_set_parent", "(", "self", ",", "parent", ")", ":" ]
https://github.com/jam-py/jam-py/blob/0821492cdff8665928e0f093a4435aa64285a45c/jam/third_party/sqlalchemy/sql/base.py#L520-L521
jupyterlab/jupyterlab
29266626af0702ff093806df7d3a7348014d0450
packages/services/examples/browser-require/main.py
python
ExampleApp.initialize_handlers
(self)
Add example handler to Lab Server's handler list.
Add example handler to Lab Server's handler list.
[ "Add", "example", "handler", "to", "Lab", "Server", "s", "handler", "list", "." ]
def initialize_handlers(self): """Add example handler to Lab Server's handler list. """ self.handlers.append( ('/example', ExampleHandler) )
[ "def", "initialize_handlers", "(", "self", ")", ":", "self", ".", "handlers", ".", "append", "(", "(", "'/example'", ",", "ExampleHandler", ")", ")" ]
https://github.com/jupyterlab/jupyterlab/blob/29266626af0702ff093806df7d3a7348014d0450/packages/services/examples/browser-require/main.py#L67-L72
liftoff/GateOne
6ae1d01f7fe21e2703bdf982df7353e7bb81a500
gateone/applications/terminal/plugins/ssh/ssh.py
python
wait_for_prompt
(term, cmd, errorback, callback, m_instance, matched)
Called by :func:`termio.Multiplex.expect` inside of :func:`execute_command`, clears the screen and executes *cmd*. Also, sets an :func:`~termio.Multiplex.expect` to call :func:`get_cmd_output` when the end of the command output is detected.
Called by :func:`termio.Multiplex.expect` inside of :func:`execute_command`, clears the screen and executes *cmd*. Also, sets an :func:`~termio.Multiplex.expect` to call :func:`get_cmd_output` when the end of the command output is detected.
[ "Called", "by", ":", "func", ":", "termio", ".", "Multiplex", ".", "expect", "inside", "of", ":", "func", ":", "execute_command", "clears", "the", "screen", "and", "executes", "*", "cmd", "*", ".", "Also", "sets", "an", ":", "func", ":", "~termio", ".", "Multiplex", ".", "expect", "to", "call", ":", "func", ":", "get_cmd_output", "when", "the", "end", "of", "the", "command", "output", "is", "detected", "." ]
def wait_for_prompt(term, cmd, errorback, callback, m_instance, matched): """ Called by :func:`termio.Multiplex.expect` inside of :func:`execute_command`, clears the screen and executes *cmd*. Also, sets an :func:`~termio.Multiplex.expect` to call :func:`get_cmd_output` when the end of the command output is detected. """ ssh_log.debug('wait_for_prompt()') m_instance.term.clear_screen() # Makes capturing just what we need easier getoutput = partial(get_cmd_output, term, errorback, callback) m_instance.expect(OUTPUT_MATCH, getoutput, errorback=errorback, preprocess=False, timeout=10) # Run our command immediately followed by our separation/ready string m_instance.writeline(( u'echo -e "{rs}"; ' # Echo the first READY_STRING u'{cmd}; ' # Execute the command in question u'echo -e "{rs}"' # READY_STRING again so we can capture the between ).format(rs=READY_STRING, cmd=cmd))
[ "def", "wait_for_prompt", "(", "term", ",", "cmd", ",", "errorback", ",", "callback", ",", "m_instance", ",", "matched", ")", ":", "ssh_log", ".", "debug", "(", "'wait_for_prompt()'", ")", "m_instance", ".", "term", ".", "clear_screen", "(", ")", "# Makes capturing just what we need easier", "getoutput", "=", "partial", "(", "get_cmd_output", ",", "term", ",", "errorback", ",", "callback", ")", "m_instance", ".", "expect", "(", "OUTPUT_MATCH", ",", "getoutput", ",", "errorback", "=", "errorback", ",", "preprocess", "=", "False", ",", "timeout", "=", "10", ")", "# Run our command immediately followed by our separation/ready string", "m_instance", ".", "writeline", "(", "(", "u'echo -e \"{rs}\"; '", "# Echo the first READY_STRING", "u'{cmd}; '", "# Execute the command in question", "u'echo -e \"{rs}\"'", "# READY_STRING again so we can capture the between", ")", ".", "format", "(", "rs", "=", "READY_STRING", ",", "cmd", "=", "cmd", ")", ")" ]
https://github.com/liftoff/GateOne/blob/6ae1d01f7fe21e2703bdf982df7353e7bb81a500/gateone/applications/terminal/plugins/ssh/ssh.py#L191-L208
infobyte/faraday
dceeac70262c7ce146020381e3dd50a7eb81f9bb
faraday/server/websocket_factories.py
python
BroadcastServerProtocol.onMessage
(self, payload, is_binary)
We only support JOIN and LEAVE workspace messages. When authentication is implemented we need to verify that the user can join the selected workspace. When authentication is implemented we need to reply the client if the join failed.
We only support JOIN and LEAVE workspace messages. When authentication is implemented we need to verify that the user can join the selected workspace. When authentication is implemented we need to reply the client if the join failed.
[ "We", "only", "support", "JOIN", "and", "LEAVE", "workspace", "messages", ".", "When", "authentication", "is", "implemented", "we", "need", "to", "verify", "that", "the", "user", "can", "join", "the", "selected", "workspace", ".", "When", "authentication", "is", "implemented", "we", "need", "to", "reply", "the", "client", "if", "the", "join", "failed", "." ]
def onMessage(self, payload, is_binary): """ We only support JOIN and LEAVE workspace messages. When authentication is implemented we need to verify that the user can join the selected workspace. When authentication is implemented we need to reply the client if the join failed. """ from faraday.server.web import get_app # pylint:disable=import-outside-toplevel if not is_binary: message = json.loads(payload) if message['action'] == 'JOIN_WORKSPACE': if 'workspace' not in message or 'token' not in message: logger.warning(f'Invalid join workspace message: {message}') self.sendClose() return signer = itsdangerous.TimestampSigner(get_app().config['SECRET_KEY'], salt="websocket") try: workspace_id = signer.unsign(message['token'], max_age=60) except itsdangerous.BadData as e: self.sendClose() logger.warning('Invalid websocket token for workspace ' '{}'.format(message['workspace'])) logger.exception(e) else: with get_app().app_context(): workspace = Workspace.query.get(int(workspace_id)) if workspace.name != message['workspace']: logger.warning( 'Trying to join workspace {} with token of ' 'workspace {}. Rejecting.'.format( message['workspace'], workspace.name )) self.sendClose() else: self.factory.join_workspace( self, message['workspace']) if message['action'] == 'LEAVE_WORKSPACE': self.factory.leave_workspace(self, message['workspace']) if message['action'] == 'JOIN_AGENT': if 'token' not in message or 'executors' not in message: logger.warning("Invalid agent join message") self.sendClose(1000, reason="Invalid JOIN_AGENT message") return False with get_app().app_context(): try: agent = decode_agent_websocket_token(message['token']) update_executors(agent, message['executors']) except ValueError: logger.warning('Invalid agent token!') self.sendClose(1000, reason="Invalid agent token!") return False # factory will now send broadcast messages to the agent return self.factory.join_agent(self, agent) if message['action'] == 'LEAVE_AGENT': with get_app().app_context(): (agent_id,) = ( k for (k, v) in connected_agents.items() if v == self ) agent = Agent.query.get(agent_id) assert agent is not None # TODO the agent could be deleted here return self.factory.leave_agent(self, agent) if message['action'] == 'RUN_STATUS': with get_app().app_context(): if 'executor_name' not in message: logger.warning(f'Missing executor_name param in message: {message}') return True (agent_id,) = ( k for (k, v) in connected_agents.items() if v == self ) agent = Agent.query.get(agent_id) assert agent is not None # TODO the agent could be deleted here execution_id = message.get('execution_id', None) assert execution_id is not None agent_execution = AgentExecution.query.filter(AgentExecution.id == execution_id).first() if agent_execution: if agent_execution.workspace.name not in \ [ workspace.name for workspace in agent.workspaces ]: logger.exception( ValueError( f"The {agent.name} agent has permission " f"to workspace {agent.workspaces} and " "ask to write to workspace " f"{agent_execution.workspace.name}" ) ) else: agent_execution.successful = message.get('successful', None) agent_execution.running = message.get('running', None) agent_execution.message = message.get('message', '') db.session.commit() else: logger.exception( NoResultFound(f"No row was found for agent executor id {execution_id}"))
[ "def", "onMessage", "(", "self", ",", "payload", ",", "is_binary", ")", ":", "from", "faraday", ".", "server", ".", "web", "import", "get_app", "# pylint:disable=import-outside-toplevel", "if", "not", "is_binary", ":", "message", "=", "json", ".", "loads", "(", "payload", ")", "if", "message", "[", "'action'", "]", "==", "'JOIN_WORKSPACE'", ":", "if", "'workspace'", "not", "in", "message", "or", "'token'", "not", "in", "message", ":", "logger", ".", "warning", "(", "f'Invalid join workspace message: {message}'", ")", "self", ".", "sendClose", "(", ")", "return", "signer", "=", "itsdangerous", ".", "TimestampSigner", "(", "get_app", "(", ")", ".", "config", "[", "'SECRET_KEY'", "]", ",", "salt", "=", "\"websocket\"", ")", "try", ":", "workspace_id", "=", "signer", ".", "unsign", "(", "message", "[", "'token'", "]", ",", "max_age", "=", "60", ")", "except", "itsdangerous", ".", "BadData", "as", "e", ":", "self", ".", "sendClose", "(", ")", "logger", ".", "warning", "(", "'Invalid websocket token for workspace '", "'{}'", ".", "format", "(", "message", "[", "'workspace'", "]", ")", ")", "logger", ".", "exception", "(", "e", ")", "else", ":", "with", "get_app", "(", ")", ".", "app_context", "(", ")", ":", "workspace", "=", "Workspace", ".", "query", ".", "get", "(", "int", "(", "workspace_id", ")", ")", "if", "workspace", ".", "name", "!=", "message", "[", "'workspace'", "]", ":", "logger", ".", "warning", "(", "'Trying to join workspace {} with token of '", "'workspace {}. Rejecting.'", ".", "format", "(", "message", "[", "'workspace'", "]", ",", "workspace", ".", "name", ")", ")", "self", ".", "sendClose", "(", ")", "else", ":", "self", ".", "factory", ".", "join_workspace", "(", "self", ",", "message", "[", "'workspace'", "]", ")", "if", "message", "[", "'action'", "]", "==", "'LEAVE_WORKSPACE'", ":", "self", ".", "factory", ".", "leave_workspace", "(", "self", ",", "message", "[", "'workspace'", "]", ")", "if", "message", "[", "'action'", "]", "==", "'JOIN_AGENT'", ":", "if", "'token'", "not", "in", "message", "or", "'executors'", "not", "in", "message", ":", "logger", ".", "warning", "(", "\"Invalid agent join message\"", ")", "self", ".", "sendClose", "(", "1000", ",", "reason", "=", "\"Invalid JOIN_AGENT message\"", ")", "return", "False", "with", "get_app", "(", ")", ".", "app_context", "(", ")", ":", "try", ":", "agent", "=", "decode_agent_websocket_token", "(", "message", "[", "'token'", "]", ")", "update_executors", "(", "agent", ",", "message", "[", "'executors'", "]", ")", "except", "ValueError", ":", "logger", ".", "warning", "(", "'Invalid agent token!'", ")", "self", ".", "sendClose", "(", "1000", ",", "reason", "=", "\"Invalid agent token!\"", ")", "return", "False", "# factory will now send broadcast messages to the agent", "return", "self", ".", "factory", ".", "join_agent", "(", "self", ",", "agent", ")", "if", "message", "[", "'action'", "]", "==", "'LEAVE_AGENT'", ":", "with", "get_app", "(", ")", ".", "app_context", "(", ")", ":", "(", "agent_id", ",", ")", "=", "(", "k", "for", "(", "k", ",", "v", ")", "in", "connected_agents", ".", "items", "(", ")", "if", "v", "==", "self", ")", "agent", "=", "Agent", ".", "query", ".", "get", "(", "agent_id", ")", "assert", "agent", "is", "not", "None", "# TODO the agent could be deleted here", "return", "self", ".", "factory", ".", "leave_agent", "(", "self", ",", "agent", ")", "if", "message", "[", "'action'", "]", "==", "'RUN_STATUS'", ":", "with", "get_app", "(", ")", ".", "app_context", "(", ")", ":", "if", "'executor_name'", "not", "in", "message", ":", "logger", ".", "warning", "(", "f'Missing executor_name param in message: {message}'", ")", "return", "True", "(", "agent_id", ",", ")", "=", "(", "k", "for", "(", "k", ",", "v", ")", "in", "connected_agents", ".", "items", "(", ")", "if", "v", "==", "self", ")", "agent", "=", "Agent", ".", "query", ".", "get", "(", "agent_id", ")", "assert", "agent", "is", "not", "None", "# TODO the agent could be deleted here", "execution_id", "=", "message", ".", "get", "(", "'execution_id'", ",", "None", ")", "assert", "execution_id", "is", "not", "None", "agent_execution", "=", "AgentExecution", ".", "query", ".", "filter", "(", "AgentExecution", ".", "id", "==", "execution_id", ")", ".", "first", "(", ")", "if", "agent_execution", ":", "if", "agent_execution", ".", "workspace", ".", "name", "not", "in", "[", "workspace", ".", "name", "for", "workspace", "in", "agent", ".", "workspaces", "]", ":", "logger", ".", "exception", "(", "ValueError", "(", "f\"The {agent.name} agent has permission \"", "f\"to workspace {agent.workspaces} and \"", "\"ask to write to workspace \"", "f\"{agent_execution.workspace.name}\"", ")", ")", "else", ":", "agent_execution", ".", "successful", "=", "message", ".", "get", "(", "'successful'", ",", "None", ")", "agent_execution", ".", "running", "=", "message", ".", "get", "(", "'running'", ",", "None", ")", "agent_execution", ".", "message", "=", "message", ".", "get", "(", "'message'", ",", "''", ")", "db", ".", "session", ".", "commit", "(", ")", "else", ":", "logger", ".", "exception", "(", "NoResultFound", "(", "f\"No row was found for agent executor id {execution_id}\"", ")", ")" ]
https://github.com/infobyte/faraday/blob/dceeac70262c7ce146020381e3dd50a7eb81f9bb/faraday/server/websocket_factories.py#L52-L156
atom-community/ide-python
c046f9c2421713b34baa22648235541c5bb284fe
lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/lib2to3/lib2to3/pytree.py
python
convert
(gr, raw_node)
Convert raw node information to a Node or Leaf instance. This is passed to the parser driver which calls it whenever a reduction of a grammar rule produces a new complete node, so that the tree is build strictly bottom-up.
Convert raw node information to a Node or Leaf instance.
[ "Convert", "raw", "node", "information", "to", "a", "Node", "or", "Leaf", "instance", "." ]
def convert(gr, raw_node): """ Convert raw node information to a Node or Leaf instance. This is passed to the parser driver which calls it whenever a reduction of a grammar rule produces a new complete node, so that the tree is build strictly bottom-up. """ type, value, context, children = raw_node if children or type in gr.number2symbol: # If there's exactly one child, return that child instead of # creating a new node. if len(children) == 1: return children[0] return Node(type, children, context=context) else: return Leaf(type, value, context=context)
[ "def", "convert", "(", "gr", ",", "raw_node", ")", ":", "type", ",", "value", ",", "context", ",", "children", "=", "raw_node", "if", "children", "or", "type", "in", "gr", ".", "number2symbol", ":", "# If there's exactly one child, return that child instead of", "# creating a new node.", "if", "len", "(", "children", ")", "==", "1", ":", "return", "children", "[", "0", "]", "return", "Node", "(", "type", ",", "children", ",", "context", "=", "context", ")", "else", ":", "return", "Leaf", "(", "type", ",", "value", ",", "context", "=", "context", ")" ]
https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/lib2to3/lib2to3/pytree.py#L429-L445
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/reloop-closured/lib/python2.7/distutils/command/config.py
python
config.check_lib
(self, library, library_dirs=None, headers=None, include_dirs=None, other_libraries=[])
return self.try_link("int main (void) { }", headers, include_dirs, [library]+other_libraries, library_dirs)
Determine if 'library' is available to be linked against, without actually checking that any particular symbols are provided by it. 'headers' will be used in constructing the source file to be compiled, but the only effect of this is to check if all the header files listed are available. Any libraries listed in 'other_libraries' will be included in the link, in case 'library' has symbols that depend on other libraries.
Determine if 'library' is available to be linked against, without actually checking that any particular symbols are provided by it. 'headers' will be used in constructing the source file to be compiled, but the only effect of this is to check if all the header files listed are available. Any libraries listed in 'other_libraries' will be included in the link, in case 'library' has symbols that depend on other libraries.
[ "Determine", "if", "library", "is", "available", "to", "be", "linked", "against", "without", "actually", "checking", "that", "any", "particular", "symbols", "are", "provided", "by", "it", ".", "headers", "will", "be", "used", "in", "constructing", "the", "source", "file", "to", "be", "compiled", "but", "the", "only", "effect", "of", "this", "is", "to", "check", "if", "all", "the", "header", "files", "listed", "are", "available", ".", "Any", "libraries", "listed", "in", "other_libraries", "will", "be", "included", "in", "the", "link", "in", "case", "library", "has", "symbols", "that", "depend", "on", "other", "libraries", "." ]
def check_lib(self, library, library_dirs=None, headers=None, include_dirs=None, other_libraries=[]): """Determine if 'library' is available to be linked against, without actually checking that any particular symbols are provided by it. 'headers' will be used in constructing the source file to be compiled, but the only effect of this is to check if all the header files listed are available. Any libraries listed in 'other_libraries' will be included in the link, in case 'library' has symbols that depend on other libraries. """ self._check_compiler() return self.try_link("int main (void) { }", headers, include_dirs, [library]+other_libraries, library_dirs)
[ "def", "check_lib", "(", "self", ",", "library", ",", "library_dirs", "=", "None", ",", "headers", "=", "None", ",", "include_dirs", "=", "None", ",", "other_libraries", "=", "[", "]", ")", ":", "self", ".", "_check_compiler", "(", ")", "return", "self", ".", "try_link", "(", "\"int main (void) { }\"", ",", "headers", ",", "include_dirs", ",", "[", "library", "]", "+", "other_libraries", ",", "library_dirs", ")" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/distutils/command/config.py#L319-L332
mceSystems/node-jsc
90634f3064fab8e89a85b3942f0cc5054acc86fa
deps/jscshim/webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/_stream_hybi.py
python
Stream._process_close_message
(self, message)
Processes close message. Args: message: close message. Raises: InvalidFrameException: when the message is invalid.
Processes close message.
[ "Processes", "close", "message", "." ]
def _process_close_message(self, message): """Processes close message. Args: message: close message. Raises: InvalidFrameException: when the message is invalid. """ self._request.client_terminated = True # Status code is optional. We can have status reason only if we # have status code. Status reason can be empty string. So, # allowed cases are # - no application data: no code no reason # - 2 octet of application data: has code but no reason # - 3 or more octet of application data: both code and reason if len(message) == 0: self._logger.debug('Received close frame (empty body)') self._request.ws_close_code = ( common.STATUS_NO_STATUS_RECEIVED) elif len(message) == 1: raise InvalidFrameException( 'If a close frame has status code, the length of ' 'status code must be 2 octet') elif len(message) >= 2: self._request.ws_close_code = struct.unpack( '!H', message[0:2])[0] self._request.ws_close_reason = message[2:].decode( 'utf-8', 'replace') self._logger.debug( 'Received close frame (code=%d, reason=%r)', self._request.ws_close_code, self._request.ws_close_reason) # As we've received a close frame, no more data is coming over the # socket. We can now safely close the socket without worrying about # RST sending. if self._request.server_terminated: self._logger.debug( 'Received ack for server-initiated closing handshake') return self._logger.debug( 'Received client-initiated closing handshake') code = common.STATUS_NORMAL_CLOSURE reason = '' if hasattr(self._request, '_dispatcher'): dispatcher = self._request._dispatcher code, reason = dispatcher.passive_closing_handshake( self._request) if code is None and reason is not None and len(reason) > 0: self._logger.warning( 'Handler specified reason despite code being None') reason = '' if reason is None: reason = '' self._send_closing_handshake(code, reason) self._logger.debug( 'Acknowledged closing handshake initiated by the peer ' '(code=%r, reason=%r)', code, reason)
[ "def", "_process_close_message", "(", "self", ",", "message", ")", ":", "self", ".", "_request", ".", "client_terminated", "=", "True", "# Status code is optional. We can have status reason only if we", "# have status code. Status reason can be empty string. So,", "# allowed cases are", "# - no application data: no code no reason", "# - 2 octet of application data: has code but no reason", "# - 3 or more octet of application data: both code and reason", "if", "len", "(", "message", ")", "==", "0", ":", "self", ".", "_logger", ".", "debug", "(", "'Received close frame (empty body)'", ")", "self", ".", "_request", ".", "ws_close_code", "=", "(", "common", ".", "STATUS_NO_STATUS_RECEIVED", ")", "elif", "len", "(", "message", ")", "==", "1", ":", "raise", "InvalidFrameException", "(", "'If a close frame has status code, the length of '", "'status code must be 2 octet'", ")", "elif", "len", "(", "message", ")", ">=", "2", ":", "self", ".", "_request", ".", "ws_close_code", "=", "struct", ".", "unpack", "(", "'!H'", ",", "message", "[", "0", ":", "2", "]", ")", "[", "0", "]", "self", ".", "_request", ".", "ws_close_reason", "=", "message", "[", "2", ":", "]", ".", "decode", "(", "'utf-8'", ",", "'replace'", ")", "self", ".", "_logger", ".", "debug", "(", "'Received close frame (code=%d, reason=%r)'", ",", "self", ".", "_request", ".", "ws_close_code", ",", "self", ".", "_request", ".", "ws_close_reason", ")", "# As we've received a close frame, no more data is coming over the", "# socket. We can now safely close the socket without worrying about", "# RST sending.", "if", "self", ".", "_request", ".", "server_terminated", ":", "self", ".", "_logger", ".", "debug", "(", "'Received ack for server-initiated closing handshake'", ")", "return", "self", ".", "_logger", ".", "debug", "(", "'Received client-initiated closing handshake'", ")", "code", "=", "common", ".", "STATUS_NORMAL_CLOSURE", "reason", "=", "''", "if", "hasattr", "(", "self", ".", "_request", ",", "'_dispatcher'", ")", ":", "dispatcher", "=", "self", ".", "_request", ".", "_dispatcher", "code", ",", "reason", "=", "dispatcher", ".", "passive_closing_handshake", "(", "self", ".", "_request", ")", "if", "code", "is", "None", "and", "reason", "is", "not", "None", "and", "len", "(", "reason", ")", ">", "0", ":", "self", ".", "_logger", ".", "warning", "(", "'Handler specified reason despite code being None'", ")", "reason", "=", "''", "if", "reason", "is", "None", ":", "reason", "=", "''", "self", ".", "_send_closing_handshake", "(", "code", ",", "reason", ")", "self", ".", "_logger", ".", "debug", "(", "'Acknowledged closing handshake initiated by the peer '", "'(code=%r, reason=%r)'", ",", "code", ",", "reason", ")" ]
https://github.com/mceSystems/node-jsc/blob/90634f3064fab8e89a85b3942f0cc5054acc86fa/deps/jscshim/webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/_stream_hybi.py#L603-L666
PrairieLearn/PrairieLearn
b21d66f54ebf412f3bc9b3d8beb7cb851b69989b
elements/pl-matching/pl-matching.py
python
categorize_matches
(element, data)
return list(options.values()), statements
Get provided statements and options from the pl-matching element
Get provided statements and options from the pl-matching element
[ "Get", "provided", "statements", "and", "options", "from", "the", "pl", "-", "matching", "element" ]
def categorize_matches(element, data): """Get provided statements and options from the pl-matching element""" options = {} statements = [] index = 0 # Sort the elements so that pl-options come first. children = element[:] children.sort(key=lambda child: child.tag) def make_option(name, html): nonlocal index option = {'index': index, 'name': name, 'html': html} index += 1 return option for child in children: if child.tag in ['pl-option', 'pl_option']: pl.check_attribs(child, required_attribs=[], optional_attribs=['name']) child_html = pl.inner_html(child) option_name = pl.get_string_attrib(child, 'name', child_html) # An option object has: index of appearance in the pl-matching element; # the name attribute; and the html content. option = make_option(option_name, child_html) options[option_name] = option elif child.tag in ['pl-statement', 'pl_statement']: pl.check_attribs(child, required_attribs=['match'], optional_attribs=[]) child_html = pl.inner_html(child) match_name = pl.get_string_attrib(child, 'match') if match_name not in options: new_option = make_option(match_name, match_name) options[match_name] = new_option # A statement object has: the name attribute of the correct matching option; and # the html content. statement = {'match': match_name, 'html': child_html} statements.append(statement) return list(options.values()), statements
[ "def", "categorize_matches", "(", "element", ",", "data", ")", ":", "options", "=", "{", "}", "statements", "=", "[", "]", "index", "=", "0", "# Sort the elements so that pl-options come first.", "children", "=", "element", "[", ":", "]", "children", ".", "sort", "(", "key", "=", "lambda", "child", ":", "child", ".", "tag", ")", "def", "make_option", "(", "name", ",", "html", ")", ":", "nonlocal", "index", "option", "=", "{", "'index'", ":", "index", ",", "'name'", ":", "name", ",", "'html'", ":", "html", "}", "index", "+=", "1", "return", "option", "for", "child", "in", "children", ":", "if", "child", ".", "tag", "in", "[", "'pl-option'", ",", "'pl_option'", "]", ":", "pl", ".", "check_attribs", "(", "child", ",", "required_attribs", "=", "[", "]", ",", "optional_attribs", "=", "[", "'name'", "]", ")", "child_html", "=", "pl", ".", "inner_html", "(", "child", ")", "option_name", "=", "pl", ".", "get_string_attrib", "(", "child", ",", "'name'", ",", "child_html", ")", "# An option object has: index of appearance in the pl-matching element;", "# the name attribute; and the html content.", "option", "=", "make_option", "(", "option_name", ",", "child_html", ")", "options", "[", "option_name", "]", "=", "option", "elif", "child", ".", "tag", "in", "[", "'pl-statement'", ",", "'pl_statement'", "]", ":", "pl", ".", "check_attribs", "(", "child", ",", "required_attribs", "=", "[", "'match'", "]", ",", "optional_attribs", "=", "[", "]", ")", "child_html", "=", "pl", ".", "inner_html", "(", "child", ")", "match_name", "=", "pl", ".", "get_string_attrib", "(", "child", ",", "'match'", ")", "if", "match_name", "not", "in", "options", ":", "new_option", "=", "make_option", "(", "match_name", ",", "match_name", ")", "options", "[", "match_name", "]", "=", "new_option", "# A statement object has: the name attribute of the correct matching option; and", "# the html content.", "statement", "=", "{", "'match'", ":", "match_name", ",", "'html'", ":", "child_html", "}", "statements", ".", "append", "(", "statement", ")", "return", "list", "(", "options", ".", "values", "(", ")", ")", ",", "statements" ]
https://github.com/PrairieLearn/PrairieLearn/blob/b21d66f54ebf412f3bc9b3d8beb7cb851b69989b/elements/pl-matching/pl-matching.py#L69-L109
ansible/awx
15c7a3f85b5e948f011c67111c4433a38c4544e9
awxkit/awxkit/api/registry.py
python
URLRegistry.url_pattern
(self, pattern_str)
return re.compile(pattern)
Converts some regex-friendly url pattern (Resources().resource string) to a compiled pattern.
Converts some regex-friendly url pattern (Resources().resource string) to a compiled pattern.
[ "Converts", "some", "regex", "-", "friendly", "url", "pattern", "(", "Resources", "()", ".", "resource", "string", ")", "to", "a", "compiled", "pattern", "." ]
def url_pattern(self, pattern_str): """Converts some regex-friendly url pattern (Resources().resource string) to a compiled pattern. """ # should account for any relative endpoint w/ query parameters pattern = r'^' + pattern_str + r'(\?.*)*$' return re.compile(pattern)
[ "def", "url_pattern", "(", "self", ",", "pattern_str", ")", ":", "# should account for any relative endpoint w/ query parameters", "pattern", "=", "r'^'", "+", "pattern_str", "+", "r'(\\?.*)*$'", "return", "re", ".", "compile", "(", "pattern", ")" ]
https://github.com/ansible/awx/blob/15c7a3f85b5e948f011c67111c4433a38c4544e9/awxkit/awxkit/api/registry.py#L15-L21
atom-community/ide-python
c046f9c2421713b34baa22648235541c5bb284fe
lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/autopep8.py
python
fix_w602
(source, aggressive=True)
return refactor(source, ['raise'], ignore='with_traceback')
Fix deprecated form of raising exception.
Fix deprecated form of raising exception.
[ "Fix", "deprecated", "form", "of", "raising", "exception", "." ]
def fix_w602(source, aggressive=True): """Fix deprecated form of raising exception.""" if not aggressive: return source return refactor(source, ['raise'], ignore='with_traceback')
[ "def", "fix_w602", "(", "source", ",", "aggressive", "=", "True", ")", ":", "if", "not", "aggressive", ":", "return", "source", "return", "refactor", "(", "source", ",", "[", "'raise'", "]", ",", "ignore", "=", "'with_traceback'", ")" ]
https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/autopep8.py#L1388-L1394
triaquae/CrazyMonitor
01c4d2660e1b12b4a07759bd61c6b4045e62aafe
monitor/backends/data_optimization.py
python
DataStore.get_max
(self,data_set)
calc the max value of the data set :param data_set: :return:
calc the max value of the data set :param data_set: :return:
[ "calc", "the", "max", "value", "of", "the", "data", "set", ":", "param", "data_set", ":", ":", "return", ":" ]
def get_max(self,data_set): ''' calc the max value of the data set :param data_set: :return: ''' if len(data_set) >0: return max(data_set) else: return 0
[ "def", "get_max", "(", "self", ",", "data_set", ")", ":", "if", "len", "(", "data_set", ")", ">", "0", ":", "return", "max", "(", "data_set", ")", "else", ":", "return", "0" ]
https://github.com/triaquae/CrazyMonitor/blob/01c4d2660e1b12b4a07759bd61c6b4045e62aafe/monitor/backends/data_optimization.py#L186-L195
HaliteChallenge/Halite-II
5cf95b4aef38621a44a503f90399af598fb51214
bot-bosses/tscommander/hlt/game_map.py
python
Map.all_players
(self)
return list(self._players.values())
:return: List of all players :rtype: list[Player]
:return: List of all players :rtype: list[Player]
[ ":", "return", ":", "List", "of", "all", "players", ":", "rtype", ":", "list", "[", "Player", "]" ]
def all_players(self): """ :return: List of all players :rtype: list[Player] """ return list(self._players.values())
[ "def", "all_players", "(", "self", ")", ":", "return", "list", "(", "self", ".", "_players", ".", "values", "(", ")", ")" ]
https://github.com/HaliteChallenge/Halite-II/blob/5cf95b4aef38621a44a503f90399af598fb51214/bot-bosses/tscommander/hlt/game_map.py#L40-L45
mapillary/OpenSfM
9766a11e11544fc71fe689f33b34d0610cca2944
opensfm/reconstruction.py
python
triangulation_reconstruction
( data: DataSetBase, tracks_manager: pymap.TracksManager )
return report, [reconstruction]
Run the triangulation reconstruction pipeline.
Run the triangulation reconstruction pipeline.
[ "Run", "the", "triangulation", "reconstruction", "pipeline", "." ]
def triangulation_reconstruction( data: DataSetBase, tracks_manager: pymap.TracksManager ) -> Tuple[Dict[str, Any], List[types.Reconstruction]]: """Run the triangulation reconstruction pipeline.""" logger.info("Starting triangulation reconstruction") report = {} chrono = Chronometer() images = tracks_manager.get_shot_ids() data.init_reference(images) camera_priors = data.load_camera_models() rig_camera_priors = data.load_rig_cameras() gcp = data.load_ground_control_points() reconstruction = helpers.reconstruction_from_metadata(data, images) config = data.config config_override = config.copy() config_override["triangulation_type"] = "ROBUST" config_override["bundle_max_iterations"] = 10 report["steps"] = [] outer_iterations = 3 inner_iterations = 5 for i in range(outer_iterations): rrep = retriangulate(tracks_manager, reconstruction, config_override) triangulated_points = rrep["num_points_after"] logger.info( f"Triangulation SfM. Outer iteration {i}, triangulated {triangulated_points} points." ) for j in range(inner_iterations): if config_override["save_partial_reconstructions"]: paint_reconstruction(data, tracks_manager, reconstruction) data.save_reconstruction( [reconstruction], f"reconstruction.{i*inner_iterations+j}.json" ) step = {} logger.info(f"Triangulation SfM. Inner iteration {j}, running bundle ...") align_reconstruction(reconstruction, gcp, config_override) b1rep = bundle( reconstruction, camera_priors, rig_camera_priors, None, config_override ) remove_outliers(reconstruction, config_override) step["bundle"] = b1rep step["retriangulation"] = rrep report["steps"].append(step) logger.info("Triangulation SfM done.") logger.info("-------------------------------------------------------") chrono.lap("compute_reconstructions") report["wall_times"] = dict(chrono.lap_times()) align_result = align_reconstruction(reconstruction, gcp, config, bias_override=True) if not align_result and config["bundle_compensate_gps_bias"]: overidden_bias_config = config.copy() overidden_bias_config["bundle_compensate_gps_bias"] = False config = overidden_bias_config bundle(reconstruction, camera_priors, rig_camera_priors, gcp, config) remove_outliers(reconstruction, config_override) paint_reconstruction(data, tracks_manager, reconstruction) return report, [reconstruction]
[ "def", "triangulation_reconstruction", "(", "data", ":", "DataSetBase", ",", "tracks_manager", ":", "pymap", ".", "TracksManager", ")", "->", "Tuple", "[", "Dict", "[", "str", ",", "Any", "]", ",", "List", "[", "types", ".", "Reconstruction", "]", "]", ":", "logger", ".", "info", "(", "\"Starting triangulation reconstruction\"", ")", "report", "=", "{", "}", "chrono", "=", "Chronometer", "(", ")", "images", "=", "tracks_manager", ".", "get_shot_ids", "(", ")", "data", ".", "init_reference", "(", "images", ")", "camera_priors", "=", "data", ".", "load_camera_models", "(", ")", "rig_camera_priors", "=", "data", ".", "load_rig_cameras", "(", ")", "gcp", "=", "data", ".", "load_ground_control_points", "(", ")", "reconstruction", "=", "helpers", ".", "reconstruction_from_metadata", "(", "data", ",", "images", ")", "config", "=", "data", ".", "config", "config_override", "=", "config", ".", "copy", "(", ")", "config_override", "[", "\"triangulation_type\"", "]", "=", "\"ROBUST\"", "config_override", "[", "\"bundle_max_iterations\"", "]", "=", "10", "report", "[", "\"steps\"", "]", "=", "[", "]", "outer_iterations", "=", "3", "inner_iterations", "=", "5", "for", "i", "in", "range", "(", "outer_iterations", ")", ":", "rrep", "=", "retriangulate", "(", "tracks_manager", ",", "reconstruction", ",", "config_override", ")", "triangulated_points", "=", "rrep", "[", "\"num_points_after\"", "]", "logger", ".", "info", "(", "f\"Triangulation SfM. Outer iteration {i}, triangulated {triangulated_points} points.\"", ")", "for", "j", "in", "range", "(", "inner_iterations", ")", ":", "if", "config_override", "[", "\"save_partial_reconstructions\"", "]", ":", "paint_reconstruction", "(", "data", ",", "tracks_manager", ",", "reconstruction", ")", "data", ".", "save_reconstruction", "(", "[", "reconstruction", "]", ",", "f\"reconstruction.{i*inner_iterations+j}.json\"", ")", "step", "=", "{", "}", "logger", ".", "info", "(", "f\"Triangulation SfM. Inner iteration {j}, running bundle ...\"", ")", "align_reconstruction", "(", "reconstruction", ",", "gcp", ",", "config_override", ")", "b1rep", "=", "bundle", "(", "reconstruction", ",", "camera_priors", ",", "rig_camera_priors", ",", "None", ",", "config_override", ")", "remove_outliers", "(", "reconstruction", ",", "config_override", ")", "step", "[", "\"bundle\"", "]", "=", "b1rep", "step", "[", "\"retriangulation\"", "]", "=", "rrep", "report", "[", "\"steps\"", "]", ".", "append", "(", "step", ")", "logger", ".", "info", "(", "\"Triangulation SfM done.\"", ")", "logger", ".", "info", "(", "\"-------------------------------------------------------\"", ")", "chrono", ".", "lap", "(", "\"compute_reconstructions\"", ")", "report", "[", "\"wall_times\"", "]", "=", "dict", "(", "chrono", ".", "lap_times", "(", ")", ")", "align_result", "=", "align_reconstruction", "(", "reconstruction", ",", "gcp", ",", "config", ",", "bias_override", "=", "True", ")", "if", "not", "align_result", "and", "config", "[", "\"bundle_compensate_gps_bias\"", "]", ":", "overidden_bias_config", "=", "config", ".", "copy", "(", ")", "overidden_bias_config", "[", "\"bundle_compensate_gps_bias\"", "]", "=", "False", "config", "=", "overidden_bias_config", "bundle", "(", "reconstruction", ",", "camera_priors", ",", "rig_camera_priors", ",", "gcp", ",", "config", ")", "remove_outliers", "(", "reconstruction", ",", "config_override", ")", "paint_reconstruction", "(", "data", ",", "tracks_manager", ",", "reconstruction", ")", "return", "report", ",", "[", "reconstruction", "]" ]
https://github.com/mapillary/OpenSfM/blob/9766a11e11544fc71fe689f33b34d0610cca2944/opensfm/reconstruction.py#L1543-L1607
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
bt5/erp5_syncml/ModuleComponentTemplateItem/portal_components/module.erp5.XMLSyncUtils.py
python
xml2wbxml
(xml)
return wbxml
convert xml string to wbxml using a temporary file
convert xml string to wbxml using a temporary file
[ "convert", "xml", "string", "to", "wbxml", "using", "a", "temporary", "file" ]
def xml2wbxml(xml): """ convert xml string to wbxml using a temporary file """ #LOG('xml2wbxml starting ...', DEBUG, '') f = open('/tmp/xml2wbxml', 'w') f.write(xml) f.close() os.system('/usr/bin/xml2wbxml -o /tmp/xml2wbxml /tmp/xml2wbxml') f = open('/tmp/xml2wbxml', 'r') wbxml = f.read() f.close() return wbxml
[ "def", "xml2wbxml", "(", "xml", ")", ":", "#LOG('xml2wbxml starting ...', DEBUG, '')", "f", "=", "open", "(", "'/tmp/xml2wbxml'", ",", "'w'", ")", "f", ".", "write", "(", "xml", ")", "f", ".", "close", "(", ")", "os", ".", "system", "(", "'/usr/bin/xml2wbxml -o /tmp/xml2wbxml /tmp/xml2wbxml'", ")", "f", "=", "open", "(", "'/tmp/xml2wbxml'", ",", "'r'", ")", "wbxml", "=", "f", ".", "read", "(", ")", "f", ".", "close", "(", ")", "return", "wbxml" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/bt5/erp5_syncml/ModuleComponentTemplateItem/portal_components/module.erp5.XMLSyncUtils.py#L89-L101
tain335/tain335
21c08048e6599b5f18d7fd6acfc1e88ece226d09
sublime packages/Package Control/package_control/downloaders/cert_provider.py
python
CertProvider.download_cert
(self, cert_id, url, domain, timeout)
return cert_downloader.download(url, 'Error downloading CA certs for %s.' % domain, timeout, 1)
Downloads CA cert(s) from a URL :param cert_id: The identifier for CA cert(s). For those provided by the channel system, this will be an md5 of the contents of the cert(s). For user-provided certs, this is something they provide. :param url: An http(s) URL to the CA cert(s) :param domain: The domain to ensure there is a CA cert for :param timeout: The int timeout for downloading the CA cert from the channel :return: The contents of the CA cert(s)
Downloads CA cert(s) from a URL
[ "Downloads", "CA", "cert", "(", "s", ")", "from", "a", "URL" ]
def download_cert(self, cert_id, url, domain, timeout): """ Downloads CA cert(s) from a URL :param cert_id: The identifier for CA cert(s). For those provided by the channel system, this will be an md5 of the contents of the cert(s). For user-provided certs, this is something they provide. :param url: An http(s) URL to the CA cert(s) :param domain: The domain to ensure there is a CA cert for :param timeout: The int timeout for downloading the CA cert from the channel :return: The contents of the CA cert(s) """ cert_downloader = self.__class__(self.settings) if self.settings.get('debug'): console_write(u"Downloading CA cert for %s from \"%s\"" % (domain, url), True) return cert_downloader.download(url, 'Error downloading CA certs for %s.' % domain, timeout, 1)
[ "def", "download_cert", "(", "self", ",", "cert_id", ",", "url", ",", "domain", ",", "timeout", ")", ":", "cert_downloader", "=", "self", ".", "__class__", "(", "self", ".", "settings", ")", "if", "self", ".", "settings", ".", "get", "(", "'debug'", ")", ":", "console_write", "(", "u\"Downloading CA cert for %s from \\\"%s\\\"\"", "%", "(", "domain", ",", "url", ")", ",", "True", ")", "return", "cert_downloader", ".", "download", "(", "url", ",", "'Error downloading CA certs for %s.'", "%", "domain", ",", "timeout", ",", "1", ")" ]
https://github.com/tain335/tain335/blob/21c08048e6599b5f18d7fd6acfc1e88ece226d09/sublime packages/Package Control/package_control/downloaders/cert_provider.py#L125-L151