id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
245,600
rameshg87/pyremotevbox
pyremotevbox/ZSI/digest_auth.py
fetch_challenge
def fetch_challenge(http_header): """ apparently keywords Basic and Digest are not being checked anywhere and decisions are being made based on authorization configuration of client, so I guess you better know what you are doing. Here I am requiring one or the other be specified. challenge Basic auth_param challenge Digest auth_param """ m = fetch_challenge.wwwauth_header_re.match(http_header) if m is None: raise RuntimeError, 'expecting "WWW-Authenticate header [Basic,Digest]"' d = dict(challenge=m.groups()[0]) m = fetch_challenge.auth_param_re.search(http_header) while m is not None: k,v = http_header[m.start():m.end()].split('=') d[k.lower()] = v[1:-1] m = fetch_challenge.auth_param_re.search(http_header, m.end()) return d
python
def fetch_challenge(http_header): """ apparently keywords Basic and Digest are not being checked anywhere and decisions are being made based on authorization configuration of client, so I guess you better know what you are doing. Here I am requiring one or the other be specified. challenge Basic auth_param challenge Digest auth_param """ m = fetch_challenge.wwwauth_header_re.match(http_header) if m is None: raise RuntimeError, 'expecting "WWW-Authenticate header [Basic,Digest]"' d = dict(challenge=m.groups()[0]) m = fetch_challenge.auth_param_re.search(http_header) while m is not None: k,v = http_header[m.start():m.end()].split('=') d[k.lower()] = v[1:-1] m = fetch_challenge.auth_param_re.search(http_header, m.end()) return d
[ "def", "fetch_challenge", "(", "http_header", ")", ":", "m", "=", "fetch_challenge", ".", "wwwauth_header_re", ".", "match", "(", "http_header", ")", "if", "m", "is", "None", ":", "raise", "RuntimeError", ",", "'expecting \"WWW-Authenticate header [Basic,Digest]\"'", "d", "=", "dict", "(", "challenge", "=", "m", ".", "groups", "(", ")", "[", "0", "]", ")", "m", "=", "fetch_challenge", ".", "auth_param_re", ".", "search", "(", "http_header", ")", "while", "m", "is", "not", "None", ":", "k", ",", "v", "=", "http_header", "[", "m", ".", "start", "(", ")", ":", "m", ".", "end", "(", ")", "]", ".", "split", "(", "'='", ")", "d", "[", "k", ".", "lower", "(", ")", "]", "=", "v", "[", "1", ":", "-", "1", "]", "m", "=", "fetch_challenge", ".", "auth_param_re", ".", "search", "(", "http_header", ",", "m", ".", "end", "(", ")", ")", "return", "d" ]
apparently keywords Basic and Digest are not being checked anywhere and decisions are being made based on authorization configuration of client, so I guess you better know what you are doing. Here I am requiring one or the other be specified. challenge Basic auth_param challenge Digest auth_param
[ "apparently", "keywords", "Basic", "and", "Digest", "are", "not", "being", "checked", "anywhere", "and", "decisions", "are", "being", "made", "based", "on", "authorization", "configuration", "of", "client", "so", "I", "guess", "you", "better", "know", "what", "you", "are", "doing", ".", "Here", "I", "am", "requiring", "one", "or", "the", "other", "be", "specified", "." ]
123dffff27da57c8faa3ac1dd4c68b1cf4558b1a
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/digest_auth.py#L77-L97
245,601
bwesterb/tkbd
src/mytimetable.py
MyTimetable.open_url
def open_url(self, url): """ Open's URL with apiToken in the headers """ try: c = pycurl.Curl() c.setopt(pycurl.FAILONERROR, True) c.setopt(pycurl.URL, "%s/api/v0/%s" % (self.url, url)) c.setopt(pycurl.HTTPHEADER, ["User-Agent: %s" % self.userAgent, "apiToken: %s" % self.apiToken]) b = StringIO.StringIO() c.setopt(pycurl.WRITEFUNCTION, b.write) c.setopt(pycurl.FOLLOWLOCATION, 1) c.setopt(pycurl.MAXREDIRS, 5) # Persoonlijkrooster only supports SSLv3, not the default SSLv23. c.setopt(pycurl.SSLVERSION, pycurl.SSLVERSION_SSLv3) # Verify authenticity of peer's certificate. (0 will not check it) c.setopt(pycurl.SSL_VERIFYPEER, 1) # Verify that domain in URL matches to the Common Name Field or # a Subject Alternate Name field in the certificate. # (0 will not check it; 1 is an invalid value) c.setopt(pycurl.SSL_VERIFYHOST, 2) c.perform() return b.getvalue() except pycurl.error, e: raise MyTimetableError(e)
python
def open_url(self, url): """ Open's URL with apiToken in the headers """ try: c = pycurl.Curl() c.setopt(pycurl.FAILONERROR, True) c.setopt(pycurl.URL, "%s/api/v0/%s" % (self.url, url)) c.setopt(pycurl.HTTPHEADER, ["User-Agent: %s" % self.userAgent, "apiToken: %s" % self.apiToken]) b = StringIO.StringIO() c.setopt(pycurl.WRITEFUNCTION, b.write) c.setopt(pycurl.FOLLOWLOCATION, 1) c.setopt(pycurl.MAXREDIRS, 5) # Persoonlijkrooster only supports SSLv3, not the default SSLv23. c.setopt(pycurl.SSLVERSION, pycurl.SSLVERSION_SSLv3) # Verify authenticity of peer's certificate. (0 will not check it) c.setopt(pycurl.SSL_VERIFYPEER, 1) # Verify that domain in URL matches to the Common Name Field or # a Subject Alternate Name field in the certificate. # (0 will not check it; 1 is an invalid value) c.setopt(pycurl.SSL_VERIFYHOST, 2) c.perform() return b.getvalue() except pycurl.error, e: raise MyTimetableError(e)
[ "def", "open_url", "(", "self", ",", "url", ")", ":", "try", ":", "c", "=", "pycurl", ".", "Curl", "(", ")", "c", ".", "setopt", "(", "pycurl", ".", "FAILONERROR", ",", "True", ")", "c", ".", "setopt", "(", "pycurl", ".", "URL", ",", "\"%s/api/v0/%s\"", "%", "(", "self", ".", "url", ",", "url", ")", ")", "c", ".", "setopt", "(", "pycurl", ".", "HTTPHEADER", ",", "[", "\"User-Agent: %s\"", "%", "self", ".", "userAgent", ",", "\"apiToken: %s\"", "%", "self", ".", "apiToken", "]", ")", "b", "=", "StringIO", ".", "StringIO", "(", ")", "c", ".", "setopt", "(", "pycurl", ".", "WRITEFUNCTION", ",", "b", ".", "write", ")", "c", ".", "setopt", "(", "pycurl", ".", "FOLLOWLOCATION", ",", "1", ")", "c", ".", "setopt", "(", "pycurl", ".", "MAXREDIRS", ",", "5", ")", "# Persoonlijkrooster only supports SSLv3, not the default SSLv23.", "c", ".", "setopt", "(", "pycurl", ".", "SSLVERSION", ",", "pycurl", ".", "SSLVERSION_SSLv3", ")", "# Verify authenticity of peer's certificate. (0 will not check it)", "c", ".", "setopt", "(", "pycurl", ".", "SSL_VERIFYPEER", ",", "1", ")", "# Verify that domain in URL matches to the Common Name Field or", "# a Subject Alternate Name field in the certificate.", "# (0 will not check it; 1 is an invalid value)", "c", ".", "setopt", "(", "pycurl", ".", "SSL_VERIFYHOST", ",", "2", ")", "c", ".", "perform", "(", ")", "return", "b", ".", "getvalue", "(", ")", "except", "pycurl", ".", "error", ",", "e", ":", "raise", "MyTimetableError", "(", "e", ")" ]
Open's URL with apiToken in the headers
[ "Open", "s", "URL", "with", "apiToken", "in", "the", "headers" ]
fcf16977d38a93fe9b7fa198513007ab9921b650
https://github.com/bwesterb/tkbd/blob/fcf16977d38a93fe9b7fa198513007ab9921b650/src/mytimetable.py#L27-L50
245,602
Nixiware/viper
nx/viper/module.py
Module._loadConfiguration
def _loadConfiguration(self): """ Load module configuration files. :return: <void> """ configPath = os.path.join(self.path, "config") if not os.path.isdir(configPath): return config = Config(configPath) Config.mergeDictionaries(config.getData(), self.application.config)
python
def _loadConfiguration(self): """ Load module configuration files. :return: <void> """ configPath = os.path.join(self.path, "config") if not os.path.isdir(configPath): return config = Config(configPath) Config.mergeDictionaries(config.getData(), self.application.config)
[ "def", "_loadConfiguration", "(", "self", ")", ":", "configPath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "\"config\"", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "configPath", ")", ":", "return", "config", "=", "Config", "(", "configPath", ")", "Config", ".", "mergeDictionaries", "(", "config", ".", "getData", "(", ")", ",", "self", ".", "application", ".", "config", ")" ]
Load module configuration files. :return: <void>
[ "Load", "module", "configuration", "files", "." ]
fbe6057facd8d46103e9955880dfd99e63b7acb3
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/module.py#L24-L36
245,603
Nixiware/viper
nx/viper/module.py
Module._loadModels
def _loadModels(self): """ Load module models. :return: <void> """ modelsPath = os.path.join(self.path, "model") if not os.path.isdir(modelsPath): return for modelFile in os.listdir(modelsPath): modelName = modelFile.replace(".py", "") modelPath = os.path.join( self.path, "model", modelFile ) if not os.path.isfile(modelPath): continue # importing model modelSpec = importlib.util.spec_from_file_location( modelName, modelPath ) model = importlib.util.module_from_spec(modelSpec) modelSpec.loader.exec_module(model) # initializing model modelInstance = model.Model(self.application) self.application.addModel(self.name, modelName, modelInstance)
python
def _loadModels(self): """ Load module models. :return: <void> """ modelsPath = os.path.join(self.path, "model") if not os.path.isdir(modelsPath): return for modelFile in os.listdir(modelsPath): modelName = modelFile.replace(".py", "") modelPath = os.path.join( self.path, "model", modelFile ) if not os.path.isfile(modelPath): continue # importing model modelSpec = importlib.util.spec_from_file_location( modelName, modelPath ) model = importlib.util.module_from_spec(modelSpec) modelSpec.loader.exec_module(model) # initializing model modelInstance = model.Model(self.application) self.application.addModel(self.name, modelName, modelInstance)
[ "def", "_loadModels", "(", "self", ")", ":", "modelsPath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "\"model\"", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "modelsPath", ")", ":", "return", "for", "modelFile", "in", "os", ".", "listdir", "(", "modelsPath", ")", ":", "modelName", "=", "modelFile", ".", "replace", "(", "\".py\"", ",", "\"\"", ")", "modelPath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "\"model\"", ",", "modelFile", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "modelPath", ")", ":", "continue", "# importing model", "modelSpec", "=", "importlib", ".", "util", ".", "spec_from_file_location", "(", "modelName", ",", "modelPath", ")", "model", "=", "importlib", ".", "util", ".", "module_from_spec", "(", "modelSpec", ")", "modelSpec", ".", "loader", ".", "exec_module", "(", "model", ")", "# initializing model", "modelInstance", "=", "model", ".", "Model", "(", "self", ".", "application", ")", "self", ".", "application", ".", "addModel", "(", "self", ".", "name", ",", "modelName", ",", "modelInstance", ")" ]
Load module models. :return: <void>
[ "Load", "module", "models", "." ]
fbe6057facd8d46103e9955880dfd99e63b7acb3
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/module.py#L38-L67
245,604
Nixiware/viper
nx/viper/module.py
Module._loadServices
def _loadServices(self): """ Load module services. :return: <void> """ servicesPath = os.path.join(self.path, "service") if not os.path.isdir(servicesPath): return self._scanDirectoryForServices(servicesPath)
python
def _loadServices(self): """ Load module services. :return: <void> """ servicesPath = os.path.join(self.path, "service") if not os.path.isdir(servicesPath): return self._scanDirectoryForServices(servicesPath)
[ "def", "_loadServices", "(", "self", ")", ":", "servicesPath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "\"service\"", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "servicesPath", ")", ":", "return", "self", ".", "_scanDirectoryForServices", "(", "servicesPath", ")" ]
Load module services. :return: <void>
[ "Load", "module", "services", "." ]
fbe6057facd8d46103e9955880dfd99e63b7acb3
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/module.py#L69-L79
245,605
Nixiware/viper
nx/viper/module.py
Module._loadService
def _loadService(self, servicePath): """ Check if an application service can be found at the specified path. If found, instantiate it and add it to the application service pool. :param: <str> service file path :return: <void> """ serviceName = ntpath.basename(servicePath).replace(".py", "") # importing service serviceSpec = importlib.util.spec_from_file_location( serviceName, servicePath ) service = importlib.util.module_from_spec(serviceSpec) serviceSpec.loader.exec_module(service) # checking if there is a service in the file if hasattr(service, "Service"): # instantiate the service serviceInstance = service.Service(self.application) self.application.addService( self.name, serviceName, serviceInstance )
python
def _loadService(self, servicePath): """ Check if an application service can be found at the specified path. If found, instantiate it and add it to the application service pool. :param: <str> service file path :return: <void> """ serviceName = ntpath.basename(servicePath).replace(".py", "") # importing service serviceSpec = importlib.util.spec_from_file_location( serviceName, servicePath ) service = importlib.util.module_from_spec(serviceSpec) serviceSpec.loader.exec_module(service) # checking if there is a service in the file if hasattr(service, "Service"): # instantiate the service serviceInstance = service.Service(self.application) self.application.addService( self.name, serviceName, serviceInstance )
[ "def", "_loadService", "(", "self", ",", "servicePath", ")", ":", "serviceName", "=", "ntpath", ".", "basename", "(", "servicePath", ")", ".", "replace", "(", "\".py\"", ",", "\"\"", ")", "# importing service", "serviceSpec", "=", "importlib", ".", "util", ".", "spec_from_file_location", "(", "serviceName", ",", "servicePath", ")", "service", "=", "importlib", ".", "util", ".", "module_from_spec", "(", "serviceSpec", ")", "serviceSpec", ".", "loader", ".", "exec_module", "(", "service", ")", "# checking if there is a service in the file", "if", "hasattr", "(", "service", ",", "\"Service\"", ")", ":", "# instantiate the service", "serviceInstance", "=", "service", ".", "Service", "(", "self", ".", "application", ")", "self", ".", "application", ".", "addService", "(", "self", ".", "name", ",", "serviceName", ",", "serviceInstance", ")" ]
Check if an application service can be found at the specified path. If found, instantiate it and add it to the application service pool. :param: <str> service file path :return: <void>
[ "Check", "if", "an", "application", "service", "can", "be", "found", "at", "the", "specified", "path", ".", "If", "found", "instantiate", "it", "and", "add", "it", "to", "the", "application", "service", "pool", "." ]
fbe6057facd8d46103e9955880dfd99e63b7acb3
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/module.py#L108-L134
245,606
colab/colab-superarchives-plugin
src/colab_superarchives/views.py
EmailView.post
def post(self, request, key): """Create new email address that will wait for validation""" email = request.POST.get('email') user_id = request.POST.get('user') if not email: return http.HttpResponseBadRequest() try: EmailAddressValidation.objects.create(address=email, user_id=user_id) except IntegrityError: # 409 Conflict # duplicated entries # email exist and it's waiting for validation return http.HttpResponse(status=409) return http.HttpResponse(status=201)
python
def post(self, request, key): """Create new email address that will wait for validation""" email = request.POST.get('email') user_id = request.POST.get('user') if not email: return http.HttpResponseBadRequest() try: EmailAddressValidation.objects.create(address=email, user_id=user_id) except IntegrityError: # 409 Conflict # duplicated entries # email exist and it's waiting for validation return http.HttpResponse(status=409) return http.HttpResponse(status=201)
[ "def", "post", "(", "self", ",", "request", ",", "key", ")", ":", "email", "=", "request", ".", "POST", ".", "get", "(", "'email'", ")", "user_id", "=", "request", ".", "POST", ".", "get", "(", "'user'", ")", "if", "not", "email", ":", "return", "http", ".", "HttpResponseBadRequest", "(", ")", "try", ":", "EmailAddressValidation", ".", "objects", ".", "create", "(", "address", "=", "email", ",", "user_id", "=", "user_id", ")", "except", "IntegrityError", ":", "# 409 Conflict", "# duplicated entries", "# email exist and it's waiting for validation", "return", "http", ".", "HttpResponse", "(", "status", "=", "409", ")", "return", "http", ".", "HttpResponse", "(", "status", "=", "201", ")" ]
Create new email address that will wait for validation
[ "Create", "new", "email", "address", "that", "will", "wait", "for", "validation" ]
fe588a1d4fac874ccad2063ee19a857028a22721
https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/views.py#L202-L219
245,607
maxfischer2781/chainlet
chainlet/concurrency/base.py
multi_iter
def multi_iter(iterable, count=2): """Return `count` independent, thread-safe iterators for `iterable`""" # no need to special-case re-usable, container-like iterables if not isinstance( iterable, ( list, tuple, set, FutureChainResults, collections.Sequence, collections.Set, collections.Mapping, collections.MappingView )): iterable = SafeTee(iterable, n=count) return (iter(iterable) for _ in range(count))
python
def multi_iter(iterable, count=2): """Return `count` independent, thread-safe iterators for `iterable`""" # no need to special-case re-usable, container-like iterables if not isinstance( iterable, ( list, tuple, set, FutureChainResults, collections.Sequence, collections.Set, collections.Mapping, collections.MappingView )): iterable = SafeTee(iterable, n=count) return (iter(iterable) for _ in range(count))
[ "def", "multi_iter", "(", "iterable", ",", "count", "=", "2", ")", ":", "# no need to special-case re-usable, container-like iterables", "if", "not", "isinstance", "(", "iterable", ",", "(", "list", ",", "tuple", ",", "set", ",", "FutureChainResults", ",", "collections", ".", "Sequence", ",", "collections", ".", "Set", ",", "collections", ".", "Mapping", ",", "collections", ".", "MappingView", ")", ")", ":", "iterable", "=", "SafeTee", "(", "iterable", ",", "n", "=", "count", ")", "return", "(", "iter", "(", "iterable", ")", "for", "_", "in", "range", "(", "count", ")", ")" ]
Return `count` independent, thread-safe iterators for `iterable`
[ "Return", "count", "independent", "thread", "-", "safe", "iterators", "for", "iterable" ]
4e17f9992b4780bd0d9309202e2847df640bffe8
https://github.com/maxfischer2781/chainlet/blob/4e17f9992b4780bd0d9309202e2847df640bffe8/chainlet/concurrency/base.py#L192-L203
245,608
maxfischer2781/chainlet
chainlet/concurrency/base.py
StoredFuture.realise
def realise(self): """ Realise the future if possible If the future has not been realised yet, do so in the current thread. This will block execution until the future is realised. Otherwise, do not block but return whether the result is already available. This will not return the result nor propagate any exceptions of the future itself. :return: whether the future has been realised :rtype: bool """ if self._mutex.acquire(False): # realise the future in this thread try: if self._result is not None: return True call, args, kwargs = self._instruction try: result = call(*args, **kwargs) except BaseException as err: self._result = None, err else: self._result = result, None return True finally: self._mutex.release() else: # indicate whether the executing thread is done return self._result is not None
python
def realise(self): """ Realise the future if possible If the future has not been realised yet, do so in the current thread. This will block execution until the future is realised. Otherwise, do not block but return whether the result is already available. This will not return the result nor propagate any exceptions of the future itself. :return: whether the future has been realised :rtype: bool """ if self._mutex.acquire(False): # realise the future in this thread try: if self._result is not None: return True call, args, kwargs = self._instruction try: result = call(*args, **kwargs) except BaseException as err: self._result = None, err else: self._result = result, None return True finally: self._mutex.release() else: # indicate whether the executing thread is done return self._result is not None
[ "def", "realise", "(", "self", ")", ":", "if", "self", ".", "_mutex", ".", "acquire", "(", "False", ")", ":", "# realise the future in this thread", "try", ":", "if", "self", ".", "_result", "is", "not", "None", ":", "return", "True", "call", ",", "args", ",", "kwargs", "=", "self", ".", "_instruction", "try", ":", "result", "=", "call", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "BaseException", "as", "err", ":", "self", ".", "_result", "=", "None", ",", "err", "else", ":", "self", ".", "_result", "=", "result", ",", "None", "return", "True", "finally", ":", "self", ".", "_mutex", ".", "release", "(", ")", "else", ":", "# indicate whether the executing thread is done", "return", "self", ".", "_result", "is", "not", "None" ]
Realise the future if possible If the future has not been realised yet, do so in the current thread. This will block execution until the future is realised. Otherwise, do not block but return whether the result is already available. This will not return the result nor propagate any exceptions of the future itself. :return: whether the future has been realised :rtype: bool
[ "Realise", "the", "future", "if", "possible" ]
4e17f9992b4780bd0d9309202e2847df640bffe8
https://github.com/maxfischer2781/chainlet/blob/4e17f9992b4780bd0d9309202e2847df640bffe8/chainlet/concurrency/base.py#L30-L60
245,609
maxfischer2781/chainlet
chainlet/concurrency/base.py
StoredFuture.result
def result(self): """ The result from realising the future If the result is not available, block until done. :return: result of the future :raises: any exception encountered during realising the future """ if self._result is None: self.await_result() chunks, exception = self._result if exception is None: return chunks raise exception
python
def result(self): """ The result from realising the future If the result is not available, block until done. :return: result of the future :raises: any exception encountered during realising the future """ if self._result is None: self.await_result() chunks, exception = self._result if exception is None: return chunks raise exception
[ "def", "result", "(", "self", ")", ":", "if", "self", ".", "_result", "is", "None", ":", "self", ".", "await_result", "(", ")", "chunks", ",", "exception", "=", "self", ".", "_result", "if", "exception", "is", "None", ":", "return", "chunks", "raise", "exception" ]
The result from realising the future If the result is not available, block until done. :return: result of the future :raises: any exception encountered during realising the future
[ "The", "result", "from", "realising", "the", "future" ]
4e17f9992b4780bd0d9309202e2847df640bffe8
https://github.com/maxfischer2781/chainlet/blob/4e17f9992b4780bd0d9309202e2847df640bffe8/chainlet/concurrency/base.py#L71-L85
245,610
msvana/warcreader
warcreader/warcreader.py
WarcFile.get_warcinfo
def get_warcinfo(self): ''' Returns WARCINFO record from the archieve as a single string including WARC header. Expects the record to be in the beginning of the archieve, otherwise it will be not found. ''' if self.searched_for_warcinfo: return self.warcinfo prev_line = None in_warcinfo_record = False self.searched_for_warcinfo = True for line in self.file_object: if not in_warcinfo_record: if line[:11] == b'WARC-Type: ': if line[:19] == b'WARC-Type: warcinfo': in_warcinfo_record = True warcinfo_lines = [prev_line, line] else: self.warcinfo = None break else: if line[0:1] == self.w_letter and self.warc_header_re.match(line): self.warcinfo = b''.join(warcinfo_lines) break warcinfo_lines.append(line) prev_line = line self.file_object.seek(0) return self.warcinfo
python
def get_warcinfo(self): ''' Returns WARCINFO record from the archieve as a single string including WARC header. Expects the record to be in the beginning of the archieve, otherwise it will be not found. ''' if self.searched_for_warcinfo: return self.warcinfo prev_line = None in_warcinfo_record = False self.searched_for_warcinfo = True for line in self.file_object: if not in_warcinfo_record: if line[:11] == b'WARC-Type: ': if line[:19] == b'WARC-Type: warcinfo': in_warcinfo_record = True warcinfo_lines = [prev_line, line] else: self.warcinfo = None break else: if line[0:1] == self.w_letter and self.warc_header_re.match(line): self.warcinfo = b''.join(warcinfo_lines) break warcinfo_lines.append(line) prev_line = line self.file_object.seek(0) return self.warcinfo
[ "def", "get_warcinfo", "(", "self", ")", ":", "if", "self", ".", "searched_for_warcinfo", ":", "return", "self", ".", "warcinfo", "prev_line", "=", "None", "in_warcinfo_record", "=", "False", "self", ".", "searched_for_warcinfo", "=", "True", "for", "line", "in", "self", ".", "file_object", ":", "if", "not", "in_warcinfo_record", ":", "if", "line", "[", ":", "11", "]", "==", "b'WARC-Type: '", ":", "if", "line", "[", ":", "19", "]", "==", "b'WARC-Type: warcinfo'", ":", "in_warcinfo_record", "=", "True", "warcinfo_lines", "=", "[", "prev_line", ",", "line", "]", "else", ":", "self", ".", "warcinfo", "=", "None", "break", "else", ":", "if", "line", "[", "0", ":", "1", "]", "==", "self", ".", "w_letter", "and", "self", ".", "warc_header_re", ".", "match", "(", "line", ")", ":", "self", ".", "warcinfo", "=", "b''", ".", "join", "(", "warcinfo_lines", ")", "break", "warcinfo_lines", ".", "append", "(", "line", ")", "prev_line", "=", "line", "self", ".", "file_object", ".", "seek", "(", "0", ")", "return", "self", ".", "warcinfo" ]
Returns WARCINFO record from the archieve as a single string including WARC header. Expects the record to be in the beginning of the archieve, otherwise it will be not found.
[ "Returns", "WARCINFO", "record", "from", "the", "archieve", "as", "a", "single", "string", "including", "WARC", "header", ".", "Expects", "the", "record", "to", "be", "in", "the", "beginning", "of", "the", "archieve", "otherwise", "it", "will", "be", "not", "found", "." ]
c61454ce95a7b6e3e8560852dfd319dd64351bf0
https://github.com/msvana/warcreader/blob/c61454ce95a7b6e3e8560852dfd319dd64351bf0/warcreader/warcreader.py#L105-L132
245,611
msvana/warcreader
warcreader/warcreader.py
WarcFile.init_state
def init_state(self): ''' Sets the initial state of the state machine. ''' self.in_warc_response = False self.in_http_response = False self.in_payload = False
python
def init_state(self): ''' Sets the initial state of the state machine. ''' self.in_warc_response = False self.in_http_response = False self.in_payload = False
[ "def", "init_state", "(", "self", ")", ":", "self", ".", "in_warc_response", "=", "False", "self", ".", "in_http_response", "=", "False", "self", ".", "in_payload", "=", "False" ]
Sets the initial state of the state machine.
[ "Sets", "the", "initial", "state", "of", "the", "state", "machine", "." ]
c61454ce95a7b6e3e8560852dfd319dd64351bf0
https://github.com/msvana/warcreader/blob/c61454ce95a7b6e3e8560852dfd319dd64351bf0/warcreader/warcreader.py#L134-L138
245,612
dossier/dossier.label
dossier/label/relation_label.py
RelationLabelStore._keys_from_label
def _keys_from_label(self, label): '''Convert a label into a kvl key. ''' k1 = (label.content_id1, label.content_id2, label.annotator_id, time_complement(label.epoch_ticks)) k2 = (label.content_id2, label.content_id1, label.annotator_id, time_complement(label.epoch_ticks)) return k1, k2
python
def _keys_from_label(self, label): '''Convert a label into a kvl key. ''' k1 = (label.content_id1, label.content_id2, label.annotator_id, time_complement(label.epoch_ticks)) k2 = (label.content_id2, label.content_id1, label.annotator_id, time_complement(label.epoch_ticks)) return k1, k2
[ "def", "_keys_from_label", "(", "self", ",", "label", ")", ":", "k1", "=", "(", "label", ".", "content_id1", ",", "label", ".", "content_id2", ",", "label", ".", "annotator_id", ",", "time_complement", "(", "label", ".", "epoch_ticks", ")", ")", "k2", "=", "(", "label", ".", "content_id2", ",", "label", ".", "content_id1", ",", "label", ".", "annotator_id", ",", "time_complement", "(", "label", ".", "epoch_ticks", ")", ")", "return", "k1", ",", "k2" ]
Convert a label into a kvl key.
[ "Convert", "a", "label", "into", "a", "kvl", "key", "." ]
d445e56b02ffd91ad46b0872cfbff62b9afef7ec
https://github.com/dossier/dossier.label/blob/d445e56b02ffd91ad46b0872cfbff62b9afef7ec/dossier/label/relation_label.py#L218-L225
245,613
dossier/dossier.label
dossier/label/relation_label.py
RelationLabelStore._value_from_label
def _value_from_label(self, label): '''Convert a label into a kvl value. ''' unser_val = (label.rel_strength.value, label.meta) return cbor.dumps(unser_val)
python
def _value_from_label(self, label): '''Convert a label into a kvl value. ''' unser_val = (label.rel_strength.value, label.meta) return cbor.dumps(unser_val)
[ "def", "_value_from_label", "(", "self", ",", "label", ")", ":", "unser_val", "=", "(", "label", ".", "rel_strength", ".", "value", ",", "label", ".", "meta", ")", "return", "cbor", ".", "dumps", "(", "unser_val", ")" ]
Convert a label into a kvl value.
[ "Convert", "a", "label", "into", "a", "kvl", "value", "." ]
d445e56b02ffd91ad46b0872cfbff62b9afef7ec
https://github.com/dossier/dossier.label/blob/d445e56b02ffd91ad46b0872cfbff62b9afef7ec/dossier/label/relation_label.py#L227-L231
245,614
dossier/dossier.label
dossier/label/relation_label.py
RelationLabelStore.get
def get(self, cid1, cid2, annotator_id): '''Retrieve a relation label from the store. ''' t = (cid1, cid2, annotator_id) for k, v in self.kvl.scan(self.TABLE, (t, t)): return self._label_from_kvlayer(k, v)
python
def get(self, cid1, cid2, annotator_id): '''Retrieve a relation label from the store. ''' t = (cid1, cid2, annotator_id) for k, v in self.kvl.scan(self.TABLE, (t, t)): return self._label_from_kvlayer(k, v)
[ "def", "get", "(", "self", ",", "cid1", ",", "cid2", ",", "annotator_id", ")", ":", "t", "=", "(", "cid1", ",", "cid2", ",", "annotator_id", ")", "for", "k", ",", "v", "in", "self", ".", "kvl", ".", "scan", "(", "self", ".", "TABLE", ",", "(", "t", ",", "t", ")", ")", ":", "return", "self", ".", "_label_from_kvlayer", "(", "k", ",", "v", ")" ]
Retrieve a relation label from the store.
[ "Retrieve", "a", "relation", "label", "from", "the", "store", "." ]
d445e56b02ffd91ad46b0872cfbff62b9afef7ec
https://github.com/dossier/dossier.label/blob/d445e56b02ffd91ad46b0872cfbff62b9afef7ec/dossier/label/relation_label.py#L256-L261
245,615
dossier/dossier.label
dossier/label/relation_label.py
RelationLabelStore.get_related
def get_related(self, content_id, min_strength=None): '''Get positive relation labels for ``cid``. If ``min_strength`` is set, will restrict results to labels with a ``rel_strength`` greater or equal to the provided ``RelationStrength`` value. Note: ``min_strength`` should be of type ``RelationStrength``. ''' def is_related(label): if min_strength is not None: return label.rel_strength >= min_strength else: return label.rel_strength.is_positive labels = self.everything(content_id=content_id) return ifilter(is_related, labels)
python
def get_related(self, content_id, min_strength=None): '''Get positive relation labels for ``cid``. If ``min_strength`` is set, will restrict results to labels with a ``rel_strength`` greater or equal to the provided ``RelationStrength`` value. Note: ``min_strength`` should be of type ``RelationStrength``. ''' def is_related(label): if min_strength is not None: return label.rel_strength >= min_strength else: return label.rel_strength.is_positive labels = self.everything(content_id=content_id) return ifilter(is_related, labels)
[ "def", "get_related", "(", "self", ",", "content_id", ",", "min_strength", "=", "None", ")", ":", "def", "is_related", "(", "label", ")", ":", "if", "min_strength", "is", "not", "None", ":", "return", "label", ".", "rel_strength", ">=", "min_strength", "else", ":", "return", "label", ".", "rel_strength", ".", "is_positive", "labels", "=", "self", ".", "everything", "(", "content_id", "=", "content_id", ")", "return", "ifilter", "(", "is_related", ",", "labels", ")" ]
Get positive relation labels for ``cid``. If ``min_strength`` is set, will restrict results to labels with a ``rel_strength`` greater or equal to the provided ``RelationStrength`` value. Note: ``min_strength`` should be of type ``RelationStrength``.
[ "Get", "positive", "relation", "labels", "for", "cid", "." ]
d445e56b02ffd91ad46b0872cfbff62b9afef7ec
https://github.com/dossier/dossier.label/blob/d445e56b02ffd91ad46b0872cfbff62b9afef7ec/dossier/label/relation_label.py#L263-L278
245,616
dossier/dossier.label
dossier/label/relation_label.py
RelationLabelStore.get_related_ids
def get_related_ids(self, content_id, min_strength=None): '''Get identifiers for related identifiers. ''' related_labels = self.get_related(content_id, min_strength=min_strength) related_idents = set() for label in related_labels: related_idents.add(label.other(content_id)) return list(related_idents)
python
def get_related_ids(self, content_id, min_strength=None): '''Get identifiers for related identifiers. ''' related_labels = self.get_related(content_id, min_strength=min_strength) related_idents = set() for label in related_labels: related_idents.add(label.other(content_id)) return list(related_idents)
[ "def", "get_related_ids", "(", "self", ",", "content_id", ",", "min_strength", "=", "None", ")", ":", "related_labels", "=", "self", ".", "get_related", "(", "content_id", ",", "min_strength", "=", "min_strength", ")", "related_idents", "=", "set", "(", ")", "for", "label", "in", "related_labels", ":", "related_idents", ".", "add", "(", "label", ".", "other", "(", "content_id", ")", ")", "return", "list", "(", "related_idents", ")" ]
Get identifiers for related identifiers.
[ "Get", "identifiers", "for", "related", "identifiers", "." ]
d445e56b02ffd91ad46b0872cfbff62b9afef7ec
https://github.com/dossier/dossier.label/blob/d445e56b02ffd91ad46b0872cfbff62b9afef7ec/dossier/label/relation_label.py#L280-L289
245,617
dossier/dossier.label
dossier/label/relation_label.py
RelationLabelStore.get_relationships_for_idents
def get_relationships_for_idents(self, cid, idents): '''Get relationships between ``idents`` and a ``cid``. Returns a dictionary mapping the identifiers in ``idents`` to either None, if no relationship label is found between the identifier and ``cid``, or a RelationshipType classifying the strength of the relationship between the identifier and ``cid``. ''' keys = [(cid, ident,) for ident in idents] key_ranges = zip(keys, keys) mapping = {} for k, v in self.kvl.scan(self.TABLE, *key_ranges): label = self._label_from_kvlayer(k, v) ident = label.other(cid) rel_strength = label.rel_strength mapping[ident] = label.rel_strength return mapping
python
def get_relationships_for_idents(self, cid, idents): '''Get relationships between ``idents`` and a ``cid``. Returns a dictionary mapping the identifiers in ``idents`` to either None, if no relationship label is found between the identifier and ``cid``, or a RelationshipType classifying the strength of the relationship between the identifier and ``cid``. ''' keys = [(cid, ident,) for ident in idents] key_ranges = zip(keys, keys) mapping = {} for k, v in self.kvl.scan(self.TABLE, *key_ranges): label = self._label_from_kvlayer(k, v) ident = label.other(cid) rel_strength = label.rel_strength mapping[ident] = label.rel_strength return mapping
[ "def", "get_relationships_for_idents", "(", "self", ",", "cid", ",", "idents", ")", ":", "keys", "=", "[", "(", "cid", ",", "ident", ",", ")", "for", "ident", "in", "idents", "]", "key_ranges", "=", "zip", "(", "keys", ",", "keys", ")", "mapping", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "kvl", ".", "scan", "(", "self", ".", "TABLE", ",", "*", "key_ranges", ")", ":", "label", "=", "self", ".", "_label_from_kvlayer", "(", "k", ",", "v", ")", "ident", "=", "label", ".", "other", "(", "cid", ")", "rel_strength", "=", "label", ".", "rel_strength", "mapping", "[", "ident", "]", "=", "label", ".", "rel_strength", "return", "mapping" ]
Get relationships between ``idents`` and a ``cid``. Returns a dictionary mapping the identifiers in ``idents`` to either None, if no relationship label is found between the identifier and ``cid``, or a RelationshipType classifying the strength of the relationship between the identifier and ``cid``.
[ "Get", "relationships", "between", "idents", "and", "a", "cid", "." ]
d445e56b02ffd91ad46b0872cfbff62b9afef7ec
https://github.com/dossier/dossier.label/blob/d445e56b02ffd91ad46b0872cfbff62b9afef7ec/dossier/label/relation_label.py#L291-L309
245,618
sassoo/goldman
goldman/queryparams/sort.py
_validate_field
def _validate_field(param, fields): """ Ensure the sortable field exists on the model """ if param.field not in fields: raise InvalidQueryParams(**{ 'detail': 'The sort query param value of "%s" is ' 'invalid. That field does not exist on the ' 'resource being requested.' % param.raw_field, 'links': LINK, 'parameter': PARAM, })
python
def _validate_field(param, fields): """ Ensure the sortable field exists on the model """ if param.field not in fields: raise InvalidQueryParams(**{ 'detail': 'The sort query param value of "%s" is ' 'invalid. That field does not exist on the ' 'resource being requested.' % param.raw_field, 'links': LINK, 'parameter': PARAM, })
[ "def", "_validate_field", "(", "param", ",", "fields", ")", ":", "if", "param", ".", "field", "not", "in", "fields", ":", "raise", "InvalidQueryParams", "(", "*", "*", "{", "'detail'", ":", "'The sort query param value of \"%s\" is '", "'invalid. That field does not exist on the '", "'resource being requested.'", "%", "param", ".", "raw_field", ",", "'links'", ":", "LINK", ",", "'parameter'", ":", "PARAM", ",", "}", ")" ]
Ensure the sortable field exists on the model
[ "Ensure", "the", "sortable", "field", "exists", "on", "the", "model" ]
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/queryparams/sort.py#L74-L84
245,619
sassoo/goldman
goldman/queryparams/sort.py
_validate_no_rels
def _validate_no_rels(param, rels): """ Ensure the sortable field is not on a relationship """ if param.field in rels: raise InvalidQueryParams(**{ 'detail': 'The sort query param value of "%s" is not ' 'supported. Sorting on relationships is not ' 'currently supported' % param.raw_field, 'links': LINK, 'parameter': PARAM, })
python
def _validate_no_rels(param, rels): """ Ensure the sortable field is not on a relationship """ if param.field in rels: raise InvalidQueryParams(**{ 'detail': 'The sort query param value of "%s" is not ' 'supported. Sorting on relationships is not ' 'currently supported' % param.raw_field, 'links': LINK, 'parameter': PARAM, })
[ "def", "_validate_no_rels", "(", "param", ",", "rels", ")", ":", "if", "param", ".", "field", "in", "rels", ":", "raise", "InvalidQueryParams", "(", "*", "*", "{", "'detail'", ":", "'The sort query param value of \"%s\" is not '", "'supported. Sorting on relationships is not '", "'currently supported'", "%", "param", ".", "raw_field", ",", "'links'", ":", "LINK", ",", "'parameter'", ":", "PARAM", ",", "}", ")" ]
Ensure the sortable field is not on a relationship
[ "Ensure", "the", "sortable", "field", "is", "not", "on", "a", "relationship" ]
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/queryparams/sort.py#L87-L97
245,620
sassoo/goldman
goldman/queryparams/sort.py
init
def init(req, model): """ Determine the sorting preference by query parameter Return an array of Sortable objects. """ rels = model.relationships fields = model.all_fields params = req.get_param_as_list('sort') or [goldman.config.SORT] params = [Sortable(param.lower()) for param in params] for param in params: _validate_no_rels(param, rels) _validate_field(param, fields) return params
python
def init(req, model): """ Determine the sorting preference by query parameter Return an array of Sortable objects. """ rels = model.relationships fields = model.all_fields params = req.get_param_as_list('sort') or [goldman.config.SORT] params = [Sortable(param.lower()) for param in params] for param in params: _validate_no_rels(param, rels) _validate_field(param, fields) return params
[ "def", "init", "(", "req", ",", "model", ")", ":", "rels", "=", "model", ".", "relationships", "fields", "=", "model", ".", "all_fields", "params", "=", "req", ".", "get_param_as_list", "(", "'sort'", ")", "or", "[", "goldman", ".", "config", ".", "SORT", "]", "params", "=", "[", "Sortable", "(", "param", ".", "lower", "(", ")", ")", "for", "param", "in", "params", "]", "for", "param", "in", "params", ":", "_validate_no_rels", "(", "param", ",", "rels", ")", "_validate_field", "(", "param", ",", "fields", ")", "return", "params" ]
Determine the sorting preference by query parameter Return an array of Sortable objects.
[ "Determine", "the", "sorting", "preference", "by", "query", "parameter" ]
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/queryparams/sort.py#L100-L116
245,621
xtream1101/web-wrapper
web_wrapper/driver_requests.py
DriverRequests._get_site
def _get_site(self, url, headers, cookies, timeout, driver_args, driver_kwargs): """ Try and return page content in the requested format using requests """ try: # Headers and cookies are combined to the ones stored in the requests session # Ones passed in here will override the ones in the session if they are the same key response = self.driver.get(url, *driver_args, headers=headers, cookies=cookies, timeout=timeout, **driver_kwargs) # Set data to access from script self.status_code = response.status_code self.url = response.url self.response = response if response.status_code == requests.codes.ok: # Return the correct format return response.text response.raise_for_status() except Exception as e: raise e.with_traceback(sys.exc_info()[2])
python
def _get_site(self, url, headers, cookies, timeout, driver_args, driver_kwargs): """ Try and return page content in the requested format using requests """ try: # Headers and cookies are combined to the ones stored in the requests session # Ones passed in here will override the ones in the session if they are the same key response = self.driver.get(url, *driver_args, headers=headers, cookies=cookies, timeout=timeout, **driver_kwargs) # Set data to access from script self.status_code = response.status_code self.url = response.url self.response = response if response.status_code == requests.codes.ok: # Return the correct format return response.text response.raise_for_status() except Exception as e: raise e.with_traceback(sys.exc_info()[2])
[ "def", "_get_site", "(", "self", ",", "url", ",", "headers", ",", "cookies", ",", "timeout", ",", "driver_args", ",", "driver_kwargs", ")", ":", "try", ":", "# Headers and cookies are combined to the ones stored in the requests session", "# Ones passed in here will override the ones in the session if they are the same key", "response", "=", "self", ".", "driver", ".", "get", "(", "url", ",", "*", "driver_args", ",", "headers", "=", "headers", ",", "cookies", "=", "cookies", ",", "timeout", "=", "timeout", ",", "*", "*", "driver_kwargs", ")", "# Set data to access from script", "self", ".", "status_code", "=", "response", ".", "status_code", "self", ".", "url", "=", "response", ".", "url", "self", ".", "response", "=", "response", "if", "response", ".", "status_code", "==", "requests", ".", "codes", ".", "ok", ":", "# Return the correct format", "return", "response", ".", "text", "response", ".", "raise_for_status", "(", ")", "except", "Exception", "as", "e", ":", "raise", "e", ".", "with_traceback", "(", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")" ]
Try and return page content in the requested format using requests
[ "Try", "and", "return", "page", "content", "in", "the", "requested", "format", "using", "requests" ]
2bfc63caa7d316564088951f01a490db493ea240
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_requests.py#L99-L125
245,622
PyMLGame/pymlgame
pymlgame/controller.py
Controller._new_controller
def _new_controller(self, addr, port): """ Get an uid for your controller. :param addr: Address of the controller :param port: Port of the controller :type addr: str :type port: int :return: Unique id of the controller :rtype: str """ for uid, controller in self.controllers.items(): if controller[0] == addr: # duplicate address. sending the uid again #print('/uid/{} => {}:{}'.format(uid, addr, port)) self.sock.sendto('/uid/{}'.format(uid).encode('utf-8'), (addr, port)) return False # get an uid and add the controller to the game uid = str(uuid4()) self.controllers[uid] = [addr, port, '00000000000000', time.time()] # tell the controller about it #print('/uid/{} => {}:{}'.format(uid, addr, port)) self.sock.sendto('/uid/{}'.format(uid).encode('utf-8'), (addr, port)) # create event for pymlgame e = Event(uid, E_NEWCTLR) self.queue.put_nowait(e) return uid
python
def _new_controller(self, addr, port): """ Get an uid for your controller. :param addr: Address of the controller :param port: Port of the controller :type addr: str :type port: int :return: Unique id of the controller :rtype: str """ for uid, controller in self.controllers.items(): if controller[0] == addr: # duplicate address. sending the uid again #print('/uid/{} => {}:{}'.format(uid, addr, port)) self.sock.sendto('/uid/{}'.format(uid).encode('utf-8'), (addr, port)) return False # get an uid and add the controller to the game uid = str(uuid4()) self.controllers[uid] = [addr, port, '00000000000000', time.time()] # tell the controller about it #print('/uid/{} => {}:{}'.format(uid, addr, port)) self.sock.sendto('/uid/{}'.format(uid).encode('utf-8'), (addr, port)) # create event for pymlgame e = Event(uid, E_NEWCTLR) self.queue.put_nowait(e) return uid
[ "def", "_new_controller", "(", "self", ",", "addr", ",", "port", ")", ":", "for", "uid", ",", "controller", "in", "self", ".", "controllers", ".", "items", "(", ")", ":", "if", "controller", "[", "0", "]", "==", "addr", ":", "# duplicate address. sending the uid again", "#print('/uid/{} => {}:{}'.format(uid, addr, port))", "self", ".", "sock", ".", "sendto", "(", "'/uid/{}'", ".", "format", "(", "uid", ")", ".", "encode", "(", "'utf-8'", ")", ",", "(", "addr", ",", "port", ")", ")", "return", "False", "# get an uid and add the controller to the game", "uid", "=", "str", "(", "uuid4", "(", ")", ")", "self", ".", "controllers", "[", "uid", "]", "=", "[", "addr", ",", "port", ",", "'00000000000000'", ",", "time", ".", "time", "(", ")", "]", "# tell the controller about it", "#print('/uid/{} => {}:{}'.format(uid, addr, port))", "self", ".", "sock", ".", "sendto", "(", "'/uid/{}'", ".", "format", "(", "uid", ")", ".", "encode", "(", "'utf-8'", ")", ",", "(", "addr", ",", "port", ")", ")", "# create event for pymlgame", "e", "=", "Event", "(", "uid", ",", "E_NEWCTLR", ")", "self", ".", "queue", ".", "put_nowait", "(", "e", ")", "return", "uid" ]
Get an uid for your controller. :param addr: Address of the controller :param port: Port of the controller :type addr: str :type port: int :return: Unique id of the controller :rtype: str
[ "Get", "an", "uid", "for", "your", "controller", "." ]
450fe77d35f9a26c107586d6954f69c3895bf504
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/pymlgame/controller.py#L40-L70
245,623
PyMLGame/pymlgame
pymlgame/controller.py
Controller._del_controller
def _del_controller(self, uid): """ Remove controller from internal list and tell the game. :param uid: Unique id of the controller :type uid: str """ try: self.controllers.pop(uid) e = Event(uid, E_DISCONNECT) self.queue.put_nowait(e) except KeyError: # There is no such controller, ignore the command pass
python
def _del_controller(self, uid): """ Remove controller from internal list and tell the game. :param uid: Unique id of the controller :type uid: str """ try: self.controllers.pop(uid) e = Event(uid, E_DISCONNECT) self.queue.put_nowait(e) except KeyError: # There is no such controller, ignore the command pass
[ "def", "_del_controller", "(", "self", ",", "uid", ")", ":", "try", ":", "self", ".", "controllers", ".", "pop", "(", "uid", ")", "e", "=", "Event", "(", "uid", ",", "E_DISCONNECT", ")", "self", ".", "queue", ".", "put_nowait", "(", "e", ")", "except", "KeyError", ":", "# There is no such controller, ignore the command", "pass" ]
Remove controller from internal list and tell the game. :param uid: Unique id of the controller :type uid: str
[ "Remove", "controller", "from", "internal", "list", "and", "tell", "the", "game", "." ]
450fe77d35f9a26c107586d6954f69c3895bf504
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/pymlgame/controller.py#L72-L85
245,624
PyMLGame/pymlgame
pymlgame/controller.py
Controller._ping
def _ping(self, uid, addr, port): """ Just say hello so that pymlgame knows that your controller is still alive. Unused controllers will be deleted after a while. This function is also used to update the address and port of the controller if it has changed. :param uid: Unique id of the controller :param addr: Address of the controller :param port: Port that the controller listens on :type uid: str :type addr: str :type port: int """ try: self.controllers[uid][0] = addr self.controllers[uid][1] = port self.controllers[uid][3] = time.time() e = Event(uid, E_PING) self.queue.put_nowait(e) except KeyError: # There is no such controller, ignore the command pass
python
def _ping(self, uid, addr, port): """ Just say hello so that pymlgame knows that your controller is still alive. Unused controllers will be deleted after a while. This function is also used to update the address and port of the controller if it has changed. :param uid: Unique id of the controller :param addr: Address of the controller :param port: Port that the controller listens on :type uid: str :type addr: str :type port: int """ try: self.controllers[uid][0] = addr self.controllers[uid][1] = port self.controllers[uid][3] = time.time() e = Event(uid, E_PING) self.queue.put_nowait(e) except KeyError: # There is no such controller, ignore the command pass
[ "def", "_ping", "(", "self", ",", "uid", ",", "addr", ",", "port", ")", ":", "try", ":", "self", ".", "controllers", "[", "uid", "]", "[", "0", "]", "=", "addr", "self", ".", "controllers", "[", "uid", "]", "[", "1", "]", "=", "port", "self", ".", "controllers", "[", "uid", "]", "[", "3", "]", "=", "time", ".", "time", "(", ")", "e", "=", "Event", "(", "uid", ",", "E_PING", ")", "self", ".", "queue", ".", "put_nowait", "(", "e", ")", "except", "KeyError", ":", "# There is no such controller, ignore the command", "pass" ]
Just say hello so that pymlgame knows that your controller is still alive. Unused controllers will be deleted after a while. This function is also used to update the address and port of the controller if it has changed. :param uid: Unique id of the controller :param addr: Address of the controller :param port: Port that the controller listens on :type uid: str :type addr: str :type port: int
[ "Just", "say", "hello", "so", "that", "pymlgame", "knows", "that", "your", "controller", "is", "still", "alive", ".", "Unused", "controllers", "will", "be", "deleted", "after", "a", "while", ".", "This", "function", "is", "also", "used", "to", "update", "the", "address", "and", "port", "of", "the", "controller", "if", "it", "has", "changed", "." ]
450fe77d35f9a26c107586d6954f69c3895bf504
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/pymlgame/controller.py#L87-L108
245,625
PyMLGame/pymlgame
pymlgame/controller.py
Controller._update_states
def _update_states(self, uid, states): """ Got states of all buttons from a controller. Now check if something changed and create events if neccesary. :param uid: Unique id of the controller :param states: Buttons states :type uid: str :type states: str """ #TODO: use try and catch all exceptions # test if uid exists if self.controllers[uid]: # test if states have correct lenght if len(states) == 14: old_states = self.controllers[uid][2] if old_states != states: for key in range(14): if int(old_states[key]) > int(states[key]): e = Event(uid, E_KEYUP, key) self.queue.put_nowait(e) elif int(old_states[key]) < int(states[key]): e = Event(uid, E_KEYDOWN, key) self.queue.put_nowait(e) self.controllers[uid][2] = states self.controllers[uid][3] = time.time()
python
def _update_states(self, uid, states): """ Got states of all buttons from a controller. Now check if something changed and create events if neccesary. :param uid: Unique id of the controller :param states: Buttons states :type uid: str :type states: str """ #TODO: use try and catch all exceptions # test if uid exists if self.controllers[uid]: # test if states have correct lenght if len(states) == 14: old_states = self.controllers[uid][2] if old_states != states: for key in range(14): if int(old_states[key]) > int(states[key]): e = Event(uid, E_KEYUP, key) self.queue.put_nowait(e) elif int(old_states[key]) < int(states[key]): e = Event(uid, E_KEYDOWN, key) self.queue.put_nowait(e) self.controllers[uid][2] = states self.controllers[uid][3] = time.time()
[ "def", "_update_states", "(", "self", ",", "uid", ",", "states", ")", ":", "#TODO: use try and catch all exceptions", "# test if uid exists", "if", "self", ".", "controllers", "[", "uid", "]", ":", "# test if states have correct lenght", "if", "len", "(", "states", ")", "==", "14", ":", "old_states", "=", "self", ".", "controllers", "[", "uid", "]", "[", "2", "]", "if", "old_states", "!=", "states", ":", "for", "key", "in", "range", "(", "14", ")", ":", "if", "int", "(", "old_states", "[", "key", "]", ")", ">", "int", "(", "states", "[", "key", "]", ")", ":", "e", "=", "Event", "(", "uid", ",", "E_KEYUP", ",", "key", ")", "self", ".", "queue", ".", "put_nowait", "(", "e", ")", "elif", "int", "(", "old_states", "[", "key", "]", ")", "<", "int", "(", "states", "[", "key", "]", ")", ":", "e", "=", "Event", "(", "uid", ",", "E_KEYDOWN", ",", "key", ")", "self", ".", "queue", ".", "put_nowait", "(", "e", ")", "self", ".", "controllers", "[", "uid", "]", "[", "2", "]", "=", "states", "self", ".", "controllers", "[", "uid", "]", "[", "3", "]", "=", "time", ".", "time", "(", ")" ]
Got states of all buttons from a controller. Now check if something changed and create events if neccesary. :param uid: Unique id of the controller :param states: Buttons states :type uid: str :type states: str
[ "Got", "states", "of", "all", "buttons", "from", "a", "controller", ".", "Now", "check", "if", "something", "changed", "and", "create", "events", "if", "neccesary", "." ]
450fe77d35f9a26c107586d6954f69c3895bf504
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/pymlgame/controller.py#L110-L134
245,626
PyMLGame/pymlgame
pymlgame/controller.py
Controller._got_message
def _got_message(self, uid, text): """ The controller has send us a message. :param uid: Unique id of the controller :param text: Text to display :type uid: str :type text: str """ #TODO: use try e = Event(uid, E_MESSAGE, text) self.queue.put_nowait(e) self.controllers[uid][2] = time.time()
python
def _got_message(self, uid, text): """ The controller has send us a message. :param uid: Unique id of the controller :param text: Text to display :type uid: str :type text: str """ #TODO: use try e = Event(uid, E_MESSAGE, text) self.queue.put_nowait(e) self.controllers[uid][2] = time.time()
[ "def", "_got_message", "(", "self", ",", "uid", ",", "text", ")", ":", "#TODO: use try", "e", "=", "Event", "(", "uid", ",", "E_MESSAGE", ",", "text", ")", "self", ".", "queue", ".", "put_nowait", "(", "e", ")", "self", ".", "controllers", "[", "uid", "]", "[", "2", "]", "=", "time", ".", "time", "(", ")" ]
The controller has send us a message. :param uid: Unique id of the controller :param text: Text to display :type uid: str :type text: str
[ "The", "controller", "has", "send", "us", "a", "message", "." ]
450fe77d35f9a26c107586d6954f69c3895bf504
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/pymlgame/controller.py#L136-L149
245,627
PyMLGame/pymlgame
pymlgame/controller.py
Controller.send
def send(self, uid, event, payload=None): """ Send an event to a connected controller. Use pymlgame event type and correct payload. To send a message to the controller use pymlgame.E_MESSAGE event and a string as payload. :param uid: Unique id of the controller :param event: Event type :param payload: Payload of the event :type uid: str :type event: Event :type payload: str :return: Number of bytes send or False :rtype: int """ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if uid in self.controllers.keys(): addr = self.controllers[uid][0] port = self.controllers[uid][1] if event == E_MESSAGE: #print('/message/{} => {}:{}'.format(payload, addr, port)) return sock.sendto('/message/{}'.format(payload).encode('utf-8'), (addr, port)) elif event == E_RUMBLE: #print('/rumble/{} => {}:{}'.format(payload, addr, port)) return sock.sendto('/rumble/{}'.format(payload).encode('utf-8'), (addr, port)) else: pass else: pass return False
python
def send(self, uid, event, payload=None): """ Send an event to a connected controller. Use pymlgame event type and correct payload. To send a message to the controller use pymlgame.E_MESSAGE event and a string as payload. :param uid: Unique id of the controller :param event: Event type :param payload: Payload of the event :type uid: str :type event: Event :type payload: str :return: Number of bytes send or False :rtype: int """ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if uid in self.controllers.keys(): addr = self.controllers[uid][0] port = self.controllers[uid][1] if event == E_MESSAGE: #print('/message/{} => {}:{}'.format(payload, addr, port)) return sock.sendto('/message/{}'.format(payload).encode('utf-8'), (addr, port)) elif event == E_RUMBLE: #print('/rumble/{} => {}:{}'.format(payload, addr, port)) return sock.sendto('/rumble/{}'.format(payload).encode('utf-8'), (addr, port)) else: pass else: pass return False
[ "def", "send", "(", "self", ",", "uid", ",", "event", ",", "payload", "=", "None", ")", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "if", "uid", "in", "self", ".", "controllers", ".", "keys", "(", ")", ":", "addr", "=", "self", ".", "controllers", "[", "uid", "]", "[", "0", "]", "port", "=", "self", ".", "controllers", "[", "uid", "]", "[", "1", "]", "if", "event", "==", "E_MESSAGE", ":", "#print('/message/{} => {}:{}'.format(payload, addr, port))", "return", "sock", ".", "sendto", "(", "'/message/{}'", ".", "format", "(", "payload", ")", ".", "encode", "(", "'utf-8'", ")", ",", "(", "addr", ",", "port", ")", ")", "elif", "event", "==", "E_RUMBLE", ":", "#print('/rumble/{} => {}:{}'.format(payload, addr, port))", "return", "sock", ".", "sendto", "(", "'/rumble/{}'", ".", "format", "(", "payload", ")", ".", "encode", "(", "'utf-8'", ")", ",", "(", "addr", ",", "port", ")", ")", "else", ":", "pass", "else", ":", "pass", "return", "False" ]
Send an event to a connected controller. Use pymlgame event type and correct payload. To send a message to the controller use pymlgame.E_MESSAGE event and a string as payload. :param uid: Unique id of the controller :param event: Event type :param payload: Payload of the event :type uid: str :type event: Event :type payload: str :return: Number of bytes send or False :rtype: int
[ "Send", "an", "event", "to", "a", "connected", "controller", ".", "Use", "pymlgame", "event", "type", "and", "correct", "payload", ".", "To", "send", "a", "message", "to", "the", "controller", "use", "pymlgame", ".", "E_MESSAGE", "event", "and", "a", "string", "as", "payload", "." ]
450fe77d35f9a26c107586d6954f69c3895bf504
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/pymlgame/controller.py#L151-L179
245,628
PyMLGame/pymlgame
pymlgame/controller.py
Controller.run
def run(self): """ Listen for controllers. """ while True: data, sender = self.sock.recvfrom(1024) addr = sender[0] msg = data.decode('utf-8') if msg.startswith('/controller/'): try: uid = msg.split('/')[2] if uid == 'new': port = int(msg.split('/')[3]) self._new_controller(addr, port) else: cmd = msg.split('/')[3] if cmd == 'ping': port = msg.split('/')[3] self._ping(uid, addr, port) elif cmd == 'kthxbye': self._del_controller(uid) elif cmd == 'states': states = msg.split('/')[4] self._update_states(uid, states) elif cmd == 'text': # /controller/<uid>/text/<text> text = msg[12 + len(uid) + 6:] self._got_message(uid, text) except IndexError or KeyError: pass else: pass # find unused controllers and delete them ctlrs = self.controllers.items() for uid, state in ctlrs: if state[3] < time.time() - 60: self.controllers.pop(uid)
python
def run(self): """ Listen for controllers. """ while True: data, sender = self.sock.recvfrom(1024) addr = sender[0] msg = data.decode('utf-8') if msg.startswith('/controller/'): try: uid = msg.split('/')[2] if uid == 'new': port = int(msg.split('/')[3]) self._new_controller(addr, port) else: cmd = msg.split('/')[3] if cmd == 'ping': port = msg.split('/')[3] self._ping(uid, addr, port) elif cmd == 'kthxbye': self._del_controller(uid) elif cmd == 'states': states = msg.split('/')[4] self._update_states(uid, states) elif cmd == 'text': # /controller/<uid>/text/<text> text = msg[12 + len(uid) + 6:] self._got_message(uid, text) except IndexError or KeyError: pass else: pass # find unused controllers and delete them ctlrs = self.controllers.items() for uid, state in ctlrs: if state[3] < time.time() - 60: self.controllers.pop(uid)
[ "def", "run", "(", "self", ")", ":", "while", "True", ":", "data", ",", "sender", "=", "self", ".", "sock", ".", "recvfrom", "(", "1024", ")", "addr", "=", "sender", "[", "0", "]", "msg", "=", "data", ".", "decode", "(", "'utf-8'", ")", "if", "msg", ".", "startswith", "(", "'/controller/'", ")", ":", "try", ":", "uid", "=", "msg", ".", "split", "(", "'/'", ")", "[", "2", "]", "if", "uid", "==", "'new'", ":", "port", "=", "int", "(", "msg", ".", "split", "(", "'/'", ")", "[", "3", "]", ")", "self", ".", "_new_controller", "(", "addr", ",", "port", ")", "else", ":", "cmd", "=", "msg", ".", "split", "(", "'/'", ")", "[", "3", "]", "if", "cmd", "==", "'ping'", ":", "port", "=", "msg", ".", "split", "(", "'/'", ")", "[", "3", "]", "self", ".", "_ping", "(", "uid", ",", "addr", ",", "port", ")", "elif", "cmd", "==", "'kthxbye'", ":", "self", ".", "_del_controller", "(", "uid", ")", "elif", "cmd", "==", "'states'", ":", "states", "=", "msg", ".", "split", "(", "'/'", ")", "[", "4", "]", "self", ".", "_update_states", "(", "uid", ",", "states", ")", "elif", "cmd", "==", "'text'", ":", "# /controller/<uid>/text/<text>", "text", "=", "msg", "[", "12", "+", "len", "(", "uid", ")", "+", "6", ":", "]", "self", ".", "_got_message", "(", "uid", ",", "text", ")", "except", "IndexError", "or", "KeyError", ":", "pass", "else", ":", "pass", "# find unused controllers and delete them", "ctlrs", "=", "self", ".", "controllers", ".", "items", "(", ")", "for", "uid", ",", "state", "in", "ctlrs", ":", "if", "state", "[", "3", "]", "<", "time", ".", "time", "(", ")", "-", "60", ":", "self", ".", "controllers", ".", "pop", "(", "uid", ")" ]
Listen for controllers.
[ "Listen", "for", "controllers", "." ]
450fe77d35f9a26c107586d6954f69c3895bf504
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/pymlgame/controller.py#L181-L218
245,629
KnowledgeLinks/rdfframework
rdfframework/utilities/baseutilities.py
get_obj_frm_str
def get_obj_frm_str(obj_str, **kwargs): """ Returns a python object from a python object string args: obj_str: python object path expamle "rdfframework.connections.ConnManager[{param1}]" kwargs: * kwargs used to format the 'obj_str' """ obj_str = obj_str.format(**kwargs) args = [] kwargs = {} params = [] # parse the call portion of the string if "(" in obj_str: call_args = obj_str[obj_str.find("("):] obj_str = obj_str[:obj_str.find("(")] call_args = call_args[1:-1] if call_args: call_args = call_args.split(",") else: call_args = [] call_args = [arg.strip() for arg in call_args] for arg in call_args: if "=" in arg: parts = arg.split("=") kwargs[parts[0]] = parts[1] else: args.append(arg) # parse a the __getitem__ portion of the string if "[" in obj_str: params = obj_str[obj_str.find("["):] obj_str = obj_str[:obj_str.find("[")] params = [part.replace("[", "").replace("]", "") for part in params.split("][")] obj = pydoc.locate(obj_str) if params: for part in params: obj = get_attr(obj, part) if args or kwargs: if kwargs: obj = obj.__call__(*args, **kwargs) else: obj = obj.__call__(*args) return obj
python
def get_obj_frm_str(obj_str, **kwargs): """ Returns a python object from a python object string args: obj_str: python object path expamle "rdfframework.connections.ConnManager[{param1}]" kwargs: * kwargs used to format the 'obj_str' """ obj_str = obj_str.format(**kwargs) args = [] kwargs = {} params = [] # parse the call portion of the string if "(" in obj_str: call_args = obj_str[obj_str.find("("):] obj_str = obj_str[:obj_str.find("(")] call_args = call_args[1:-1] if call_args: call_args = call_args.split(",") else: call_args = [] call_args = [arg.strip() for arg in call_args] for arg in call_args: if "=" in arg: parts = arg.split("=") kwargs[parts[0]] = parts[1] else: args.append(arg) # parse a the __getitem__ portion of the string if "[" in obj_str: params = obj_str[obj_str.find("["):] obj_str = obj_str[:obj_str.find("[")] params = [part.replace("[", "").replace("]", "") for part in params.split("][")] obj = pydoc.locate(obj_str) if params: for part in params: obj = get_attr(obj, part) if args or kwargs: if kwargs: obj = obj.__call__(*args, **kwargs) else: obj = obj.__call__(*args) return obj
[ "def", "get_obj_frm_str", "(", "obj_str", ",", "*", "*", "kwargs", ")", ":", "obj_str", "=", "obj_str", ".", "format", "(", "*", "*", "kwargs", ")", "args", "=", "[", "]", "kwargs", "=", "{", "}", "params", "=", "[", "]", "# parse the call portion of the string", "if", "\"(\"", "in", "obj_str", ":", "call_args", "=", "obj_str", "[", "obj_str", ".", "find", "(", "\"(\"", ")", ":", "]", "obj_str", "=", "obj_str", "[", ":", "obj_str", ".", "find", "(", "\"(\"", ")", "]", "call_args", "=", "call_args", "[", "1", ":", "-", "1", "]", "if", "call_args", ":", "call_args", "=", "call_args", ".", "split", "(", "\",\"", ")", "else", ":", "call_args", "=", "[", "]", "call_args", "=", "[", "arg", ".", "strip", "(", ")", "for", "arg", "in", "call_args", "]", "for", "arg", "in", "call_args", ":", "if", "\"=\"", "in", "arg", ":", "parts", "=", "arg", ".", "split", "(", "\"=\"", ")", "kwargs", "[", "parts", "[", "0", "]", "]", "=", "parts", "[", "1", "]", "else", ":", "args", ".", "append", "(", "arg", ")", "# parse a the __getitem__ portion of the string", "if", "\"[\"", "in", "obj_str", ":", "params", "=", "obj_str", "[", "obj_str", ".", "find", "(", "\"[\"", ")", ":", "]", "obj_str", "=", "obj_str", "[", ":", "obj_str", ".", "find", "(", "\"[\"", ")", "]", "params", "=", "[", "part", ".", "replace", "(", "\"[\"", ",", "\"\"", ")", ".", "replace", "(", "\"]\"", ",", "\"\"", ")", "for", "part", "in", "params", ".", "split", "(", "\"][\"", ")", "]", "obj", "=", "pydoc", ".", "locate", "(", "obj_str", ")", "if", "params", ":", "for", "part", "in", "params", ":", "obj", "=", "get_attr", "(", "obj", ",", "part", ")", "if", "args", "or", "kwargs", ":", "if", "kwargs", ":", "obj", "=", "obj", ".", "__call__", "(", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "obj", "=", "obj", ".", "__call__", "(", "*", "args", ")", "return", "obj" ]
Returns a python object from a python object string args: obj_str: python object path expamle "rdfframework.connections.ConnManager[{param1}]" kwargs: * kwargs used to format the 'obj_str'
[ "Returns", "a", "python", "object", "from", "a", "python", "object", "string" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/baseutilities.py#L36-L83
245,630
KnowledgeLinks/rdfframework
rdfframework/utilities/baseutilities.py
pyfile_path
def pyfile_path(path): """ converst a file path argment to the is path within the framework args: path: filepath to the python file """ if "/" in path: parts = path.split("/") join_term = "/" elif "\\" in path: parts =path.split("\\") join_term = "\\" parts.reverse() base = parts[:parts.index('rdfframework')] base.reverse() return join_term.join(base)
python
def pyfile_path(path): """ converst a file path argment to the is path within the framework args: path: filepath to the python file """ if "/" in path: parts = path.split("/") join_term = "/" elif "\\" in path: parts =path.split("\\") join_term = "\\" parts.reverse() base = parts[:parts.index('rdfframework')] base.reverse() return join_term.join(base)
[ "def", "pyfile_path", "(", "path", ")", ":", "if", "\"/\"", "in", "path", ":", "parts", "=", "path", ".", "split", "(", "\"/\"", ")", "join_term", "=", "\"/\"", "elif", "\"\\\\\"", "in", "path", ":", "parts", "=", "path", ".", "split", "(", "\"\\\\\"", ")", "join_term", "=", "\"\\\\\"", "parts", ".", "reverse", "(", ")", "base", "=", "parts", "[", ":", "parts", ".", "index", "(", "'rdfframework'", ")", "]", "base", ".", "reverse", "(", ")", "return", "join_term", ".", "join", "(", "base", ")" ]
converst a file path argment to the is path within the framework args: path: filepath to the python file
[ "converst", "a", "file", "path", "argment", "to", "the", "is", "path", "within", "the", "framework" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/baseutilities.py#L146-L161
245,631
KnowledgeLinks/rdfframework
rdfframework/utilities/baseutilities.py
nz
def nz(value, none_value, strict=True): ''' This function is named after an old VBA function. It returns a default value if the passed in value is None. If strict is False it will treat an empty string as None as well. example: x = None nz(x,"hello") --> "hello" nz(x,"") --> "" y = "" nz(y,"hello") --> "" nz(y,"hello", False) --> "hello" ''' if not DEBUG: debug = False else: debug = False if debug: print("START nz frameworkutilities.py ----------------------\n") if value is None and strict: return_val = none_value elif strict and value is not None: return_val = value elif not strict and not is_not_null(value): return_val = none_value else: return_val = value if debug: print("value: %s | none_value: %s | return_val: %s" % (value, none_value, return_val)) if debug: print("END nz frameworkutilities.py ----------------------\n") return return_val
python
def nz(value, none_value, strict=True): ''' This function is named after an old VBA function. It returns a default value if the passed in value is None. If strict is False it will treat an empty string as None as well. example: x = None nz(x,"hello") --> "hello" nz(x,"") --> "" y = "" nz(y,"hello") --> "" nz(y,"hello", False) --> "hello" ''' if not DEBUG: debug = False else: debug = False if debug: print("START nz frameworkutilities.py ----------------------\n") if value is None and strict: return_val = none_value elif strict and value is not None: return_val = value elif not strict and not is_not_null(value): return_val = none_value else: return_val = value if debug: print("value: %s | none_value: %s | return_val: %s" % (value, none_value, return_val)) if debug: print("END nz frameworkutilities.py ----------------------\n") return return_val
[ "def", "nz", "(", "value", ",", "none_value", ",", "strict", "=", "True", ")", ":", "if", "not", "DEBUG", ":", "debug", "=", "False", "else", ":", "debug", "=", "False", "if", "debug", ":", "print", "(", "\"START nz frameworkutilities.py ----------------------\\n\"", ")", "if", "value", "is", "None", "and", "strict", ":", "return_val", "=", "none_value", "elif", "strict", "and", "value", "is", "not", "None", ":", "return_val", "=", "value", "elif", "not", "strict", "and", "not", "is_not_null", "(", "value", ")", ":", "return_val", "=", "none_value", "else", ":", "return_val", "=", "value", "if", "debug", ":", "print", "(", "\"value: %s | none_value: %s | return_val: %s\"", "%", "(", "value", ",", "none_value", ",", "return_val", ")", ")", "if", "debug", ":", "print", "(", "\"END nz frameworkutilities.py ----------------------\\n\"", ")", "return", "return_val" ]
This function is named after an old VBA function. It returns a default value if the passed in value is None. If strict is False it will treat an empty string as None as well. example: x = None nz(x,"hello") --> "hello" nz(x,"") --> "" y = "" nz(y,"hello") --> "" nz(y,"hello", False) --> "hello"
[ "This", "function", "is", "named", "after", "an", "old", "VBA", "function", ".", "It", "returns", "a", "default", "value", "if", "the", "passed", "in", "value", "is", "None", ".", "If", "strict", "is", "False", "it", "will", "treat", "an", "empty", "string", "as", "None", "as", "well", "." ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/baseutilities.py#L170-L202
245,632
KnowledgeLinks/rdfframework
rdfframework/utilities/baseutilities.py
make_set
def make_set(value): ''' Takes a value and turns it into a set !!!! This is important because set(string) will parse a string to individual characters vs. adding the string as an element of the set i.e. x = 'setvalue' set(x) = {'t', 'a', 'e', 'v', 'u', 's', 'l'} make_set(x) = {'setvalue'} or use set([x,]) by adding string as first item in list. ''' if isinstance(value, list): value = set(value) elif not isinstance(value, set): value = set([value,]) return value
python
def make_set(value): ''' Takes a value and turns it into a set !!!! This is important because set(string) will parse a string to individual characters vs. adding the string as an element of the set i.e. x = 'setvalue' set(x) = {'t', 'a', 'e', 'v', 'u', 's', 'l'} make_set(x) = {'setvalue'} or use set([x,]) by adding string as first item in list. ''' if isinstance(value, list): value = set(value) elif not isinstance(value, set): value = set([value,]) return value
[ "def", "make_set", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "set", "(", "value", ")", "elif", "not", "isinstance", "(", "value", ",", "set", ")", ":", "value", "=", "set", "(", "[", "value", ",", "]", ")", "return", "value" ]
Takes a value and turns it into a set !!!! This is important because set(string) will parse a string to individual characters vs. adding the string as an element of the set i.e. x = 'setvalue' set(x) = {'t', 'a', 'e', 'v', 'u', 's', 'l'} make_set(x) = {'setvalue'} or use set([x,]) by adding string as first item in list.
[ "Takes", "a", "value", "and", "turns", "it", "into", "a", "set" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/baseutilities.py#L259-L274
245,633
KnowledgeLinks/rdfframework
rdfframework/utilities/baseutilities.py
make_triple
def make_triple(sub, pred, obj): """Takes a subject predicate and object and joins them with a space in between Args: sub -- Subject pred -- Predicate obj -- Object Returns str """ return "{s} {p} {o} .".format(s=sub, p=pred, o=obj)
python
def make_triple(sub, pred, obj): """Takes a subject predicate and object and joins them with a space in between Args: sub -- Subject pred -- Predicate obj -- Object Returns str """ return "{s} {p} {o} .".format(s=sub, p=pred, o=obj)
[ "def", "make_triple", "(", "sub", ",", "pred", ",", "obj", ")", ":", "return", "\"{s} {p} {o} .\"", ".", "format", "(", "s", "=", "sub", ",", "p", "=", "pred", ",", "o", "=", "obj", ")" ]
Takes a subject predicate and object and joins them with a space in between Args: sub -- Subject pred -- Predicate obj -- Object Returns str
[ "Takes", "a", "subject", "predicate", "and", "object", "and", "joins", "them", "with", "a", "space", "in", "between" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/baseutilities.py#L277-L288
245,634
KnowledgeLinks/rdfframework
rdfframework/utilities/baseutilities.py
remove_null
def remove_null(obj): ''' reads through a list or set and strips any null values''' if isinstance(obj, set): try: obj.remove(None) except: pass elif isinstance(obj, list): for item in obj: if not is_not_null(item): obj.remove(item) return obj
python
def remove_null(obj): ''' reads through a list or set and strips any null values''' if isinstance(obj, set): try: obj.remove(None) except: pass elif isinstance(obj, list): for item in obj: if not is_not_null(item): obj.remove(item) return obj
[ "def", "remove_null", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "set", ")", ":", "try", ":", "obj", ".", "remove", "(", "None", ")", "except", ":", "pass", "elif", "isinstance", "(", "obj", ",", "list", ")", ":", "for", "item", "in", "obj", ":", "if", "not", "is_not_null", "(", "item", ")", ":", "obj", ".", "remove", "(", "item", ")", "return", "obj" ]
reads through a list or set and strips any null values
[ "reads", "through", "a", "list", "or", "set", "and", "strips", "any", "null", "values" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/baseutilities.py#L290-L301
245,635
KnowledgeLinks/rdfframework
rdfframework/utilities/baseutilities.py
delete_key_pattern
def delete_key_pattern(obj, regx_pattern): ''' takes a dictionary object and a regular expression pattern and removes all keys that match the pattern. args: obj: dictionay object to search trhough regx_pattern: string without beginning and ending / ''' if isinstance(obj, list): _return_list = [] for item in obj: if isinstance(item, list): _return_list.append(delete_key_pattern(item, regx_pattern)) elif isinstance(item, set): _return_list.append(list(item)) elif isinstance(item, dict): _return_list.append(delete_key_pattern(item, regx_pattern)) else: try: json.dumps(item) _return_list.append(item) except: _return_list.append(str(type(item))) return _return_list elif isinstance(obj, set): return list(obj) elif isinstance(obj, dict): _return_obj = {} for key, item in obj.items(): if not re.match(regx_pattern, key): if isinstance(item, list): _return_obj[key] = delete_key_pattern(item, regx_pattern) elif isinstance(item, set): _return_obj[key] = list(item) elif isinstance(item, dict): _return_obj[key] = delete_key_pattern(item, regx_pattern) else: try: json.dumps(item) _return_obj[key] = item except: _return_obj[key] = str(type(item)) return _return_obj else: try: json.dumps(obj) return obj except: return str(type(obj))
python
def delete_key_pattern(obj, regx_pattern): ''' takes a dictionary object and a regular expression pattern and removes all keys that match the pattern. args: obj: dictionay object to search trhough regx_pattern: string without beginning and ending / ''' if isinstance(obj, list): _return_list = [] for item in obj: if isinstance(item, list): _return_list.append(delete_key_pattern(item, regx_pattern)) elif isinstance(item, set): _return_list.append(list(item)) elif isinstance(item, dict): _return_list.append(delete_key_pattern(item, regx_pattern)) else: try: json.dumps(item) _return_list.append(item) except: _return_list.append(str(type(item))) return _return_list elif isinstance(obj, set): return list(obj) elif isinstance(obj, dict): _return_obj = {} for key, item in obj.items(): if not re.match(regx_pattern, key): if isinstance(item, list): _return_obj[key] = delete_key_pattern(item, regx_pattern) elif isinstance(item, set): _return_obj[key] = list(item) elif isinstance(item, dict): _return_obj[key] = delete_key_pattern(item, regx_pattern) else: try: json.dumps(item) _return_obj[key] = item except: _return_obj[key] = str(type(item)) return _return_obj else: try: json.dumps(obj) return obj except: return str(type(obj))
[ "def", "delete_key_pattern", "(", "obj", ",", "regx_pattern", ")", ":", "if", "isinstance", "(", "obj", ",", "list", ")", ":", "_return_list", "=", "[", "]", "for", "item", "in", "obj", ":", "if", "isinstance", "(", "item", ",", "list", ")", ":", "_return_list", ".", "append", "(", "delete_key_pattern", "(", "item", ",", "regx_pattern", ")", ")", "elif", "isinstance", "(", "item", ",", "set", ")", ":", "_return_list", ".", "append", "(", "list", "(", "item", ")", ")", "elif", "isinstance", "(", "item", ",", "dict", ")", ":", "_return_list", ".", "append", "(", "delete_key_pattern", "(", "item", ",", "regx_pattern", ")", ")", "else", ":", "try", ":", "json", ".", "dumps", "(", "item", ")", "_return_list", ".", "append", "(", "item", ")", "except", ":", "_return_list", ".", "append", "(", "str", "(", "type", "(", "item", ")", ")", ")", "return", "_return_list", "elif", "isinstance", "(", "obj", ",", "set", ")", ":", "return", "list", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "dict", ")", ":", "_return_obj", "=", "{", "}", "for", "key", ",", "item", "in", "obj", ".", "items", "(", ")", ":", "if", "not", "re", ".", "match", "(", "regx_pattern", ",", "key", ")", ":", "if", "isinstance", "(", "item", ",", "list", ")", ":", "_return_obj", "[", "key", "]", "=", "delete_key_pattern", "(", "item", ",", "regx_pattern", ")", "elif", "isinstance", "(", "item", ",", "set", ")", ":", "_return_obj", "[", "key", "]", "=", "list", "(", "item", ")", "elif", "isinstance", "(", "item", ",", "dict", ")", ":", "_return_obj", "[", "key", "]", "=", "delete_key_pattern", "(", "item", ",", "regx_pattern", ")", "else", ":", "try", ":", "json", ".", "dumps", "(", "item", ")", "_return_obj", "[", "key", "]", "=", "item", "except", ":", "_return_obj", "[", "key", "]", "=", "str", "(", "type", "(", "item", ")", ")", "return", "_return_obj", "else", ":", "try", ":", "json", ".", "dumps", "(", "obj", ")", "return", "obj", "except", ":", "return", "str", "(", "type", "(", "obj", ")", ")" ]
takes a dictionary object and a regular expression pattern and removes all keys that match the pattern. args: obj: dictionay object to search trhough regx_pattern: string without beginning and ending /
[ "takes", "a", "dictionary", "object", "and", "a", "regular", "expression", "pattern", "and", "removes", "all", "keys", "that", "match", "the", "pattern", "." ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/baseutilities.py#L423-L471
245,636
KnowledgeLinks/rdfframework
rdfframework/utilities/baseutilities.py
get_dict_key
def get_dict_key(data, key): ''' will serach a mulitdemensional dictionary for a key name and return a value list of matching results ''' if isinstance(data, Mapping): if key in data: yield data[key] for key_data in data.values(): for found in get_dict_key(key_data, key): yield found
python
def get_dict_key(data, key): ''' will serach a mulitdemensional dictionary for a key name and return a value list of matching results ''' if isinstance(data, Mapping): if key in data: yield data[key] for key_data in data.values(): for found in get_dict_key(key_data, key): yield found
[ "def", "get_dict_key", "(", "data", ",", "key", ")", ":", "if", "isinstance", "(", "data", ",", "Mapping", ")", ":", "if", "key", "in", "data", ":", "yield", "data", "[", "key", "]", "for", "key_data", "in", "data", ".", "values", "(", ")", ":", "for", "found", "in", "get_dict_key", "(", "key_data", ",", "key", ")", ":", "yield", "found" ]
will serach a mulitdemensional dictionary for a key name and return a value list of matching results
[ "will", "serach", "a", "mulitdemensional", "dictionary", "for", "a", "key", "name", "and", "return", "a", "value", "list", "of", "matching", "results" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/baseutilities.py#L473-L482
245,637
KnowledgeLinks/rdfframework
rdfframework/utilities/baseutilities.py
get_attr
def get_attr(item, name, default=None): ''' similar to getattr and get but will test for class or dict ''' try: val = item[name] except (KeyError, TypeError): try: val = getattr(item, name) except AttributeError: val = default return val
python
def get_attr(item, name, default=None): ''' similar to getattr and get but will test for class or dict ''' try: val = item[name] except (KeyError, TypeError): try: val = getattr(item, name) except AttributeError: val = default return val
[ "def", "get_attr", "(", "item", ",", "name", ",", "default", "=", "None", ")", ":", "try", ":", "val", "=", "item", "[", "name", "]", "except", "(", "KeyError", ",", "TypeError", ")", ":", "try", ":", "val", "=", "getattr", "(", "item", ",", "name", ")", "except", "AttributeError", ":", "val", "=", "default", "return", "val" ]
similar to getattr and get but will test for class or dict
[ "similar", "to", "getattr", "and", "get", "but", "will", "test", "for", "class", "or", "dict" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/baseutilities.py#L484-L493
245,638
KnowledgeLinks/rdfframework
rdfframework/utilities/baseutilities.py
get2
def get2(item, key, if_none=None, strict=True): ''' similar to dict.get functionality but None value will return then if_none value args: item: dictionary to search key: the dictionary key if_none: the value to return if None is passed in strict: if False an empty string is treated as None''' if not strict and item.get(key) == "": return if_none elif item.get(key) is None: return if_none else: return item.get(key)
python
def get2(item, key, if_none=None, strict=True): ''' similar to dict.get functionality but None value will return then if_none value args: item: dictionary to search key: the dictionary key if_none: the value to return if None is passed in strict: if False an empty string is treated as None''' if not strict and item.get(key) == "": return if_none elif item.get(key) is None: return if_none else: return item.get(key)
[ "def", "get2", "(", "item", ",", "key", ",", "if_none", "=", "None", ",", "strict", "=", "True", ")", ":", "if", "not", "strict", "and", "item", ".", "get", "(", "key", ")", "==", "\"\"", ":", "return", "if_none", "elif", "item", ".", "get", "(", "key", ")", "is", "None", ":", "return", "if_none", "else", ":", "return", "item", ".", "get", "(", "key", ")" ]
similar to dict.get functionality but None value will return then if_none value args: item: dictionary to search key: the dictionary key if_none: the value to return if None is passed in strict: if False an empty string is treated as None
[ "similar", "to", "dict", ".", "get", "functionality", "but", "None", "value", "will", "return", "then", "if_none", "value" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/baseutilities.py#L538-L553
245,639
KnowledgeLinks/rdfframework
rdfframework/utilities/baseutilities.py
initialized
def initialized(func): """ decorator for testing if a class has been initialized prior to calling any attribute """ def wrapper(self, *args, **kwargs): """ internal wrapper function """ if not self.__is_initialized__: return EmptyDot() return func(self, *args, **kwargs) return wrapper
python
def initialized(func): """ decorator for testing if a class has been initialized prior to calling any attribute """ def wrapper(self, *args, **kwargs): """ internal wrapper function """ if not self.__is_initialized__: return EmptyDot() return func(self, *args, **kwargs) return wrapper
[ "def", "initialized", "(", "func", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\" internal wrapper function \"\"\"", "if", "not", "self", ".", "__is_initialized__", ":", "return", "EmptyDot", "(", ")", "return", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
decorator for testing if a class has been initialized prior to calling any attribute
[ "decorator", "for", "testing", "if", "a", "class", "has", "been", "initialized", "prior", "to", "calling", "any", "attribute" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/baseutilities.py#L750-L759
245,640
KnowledgeLinks/rdfframework
rdfframework/utilities/baseutilities.py
RegistryDictionary.find
def find(self, value): """ returns a dictionary of items based on the a lowercase search args: value: the value to search by """ value = str(value).lower() rtn_dict = RegistryDictionary() for key, item in self.items(): if value in key.lower(): rtn_dict[key] = item return rtn_dict
python
def find(self, value): """ returns a dictionary of items based on the a lowercase search args: value: the value to search by """ value = str(value).lower() rtn_dict = RegistryDictionary() for key, item in self.items(): if value in key.lower(): rtn_dict[key] = item return rtn_dict
[ "def", "find", "(", "self", ",", "value", ")", ":", "value", "=", "str", "(", "value", ")", ".", "lower", "(", ")", "rtn_dict", "=", "RegistryDictionary", "(", ")", "for", "key", ",", "item", "in", "self", ".", "items", "(", ")", ":", "if", "value", "in", "key", ".", "lower", "(", ")", ":", "rtn_dict", "[", "key", "]", "=", "item", "return", "rtn_dict" ]
returns a dictionary of items based on the a lowercase search args: value: the value to search by
[ "returns", "a", "dictionary", "of", "items", "based", "on", "the", "a", "lowercase", "search" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/baseutilities.py#L89-L101
245,641
KnowledgeLinks/rdfframework
rdfframework/utilities/baseutilities.py
Dot.get
def get(self, prop): """ get the value off the passed in dot notation args: prop: a string of the property to retreive "a.b.c" ~ dictionary['a']['b']['c'] """ prop_parts = prop.split(".") val = None for part in prop_parts: if val is None: val = self.obj.get(part) else: val = val.get(part) return val
python
def get(self, prop): """ get the value off the passed in dot notation args: prop: a string of the property to retreive "a.b.c" ~ dictionary['a']['b']['c'] """ prop_parts = prop.split(".") val = None for part in prop_parts: if val is None: val = self.obj.get(part) else: val = val.get(part) return val
[ "def", "get", "(", "self", ",", "prop", ")", ":", "prop_parts", "=", "prop", ".", "split", "(", "\".\"", ")", "val", "=", "None", "for", "part", "in", "prop_parts", ":", "if", "val", "is", "None", ":", "val", "=", "self", ".", "obj", ".", "get", "(", "part", ")", "else", ":", "val", "=", "val", ".", "get", "(", "part", ")", "return", "val" ]
get the value off the passed in dot notation args: prop: a string of the property to retreive "a.b.c" ~ dictionary['a']['b']['c']
[ "get", "the", "value", "off", "the", "passed", "in", "dot", "notation" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/baseutilities.py#L365-L379
245,642
KnowledgeLinks/rdfframework
rdfframework/utilities/baseutilities.py
Dot.set
def set(self, prop, value): """ sets the dot notated property to the passed in value args: prop: a string of the property to retreive "a.b.c" ~ dictionary['a']['b']['c'] value: the value to set the prop object """ prop_parts = prop.split(".") if self.copy_dict: new_dict = copy.deepcopy(self.obj) else: new_dict = self.obj pointer = None parts_length = len(prop_parts) - 1 for i, part in enumerate(prop_parts): if pointer is None and i == parts_length: new_dict[part] = value elif pointer is None: pointer = new_dict.get(part) elif i == parts_length: pointer[part] = value else: pointer = pointer.get(part) return new_dict
python
def set(self, prop, value): """ sets the dot notated property to the passed in value args: prop: a string of the property to retreive "a.b.c" ~ dictionary['a']['b']['c'] value: the value to set the prop object """ prop_parts = prop.split(".") if self.copy_dict: new_dict = copy.deepcopy(self.obj) else: new_dict = self.obj pointer = None parts_length = len(prop_parts) - 1 for i, part in enumerate(prop_parts): if pointer is None and i == parts_length: new_dict[part] = value elif pointer is None: pointer = new_dict.get(part) elif i == parts_length: pointer[part] = value else: pointer = pointer.get(part) return new_dict
[ "def", "set", "(", "self", ",", "prop", ",", "value", ")", ":", "prop_parts", "=", "prop", ".", "split", "(", "\".\"", ")", "if", "self", ".", "copy_dict", ":", "new_dict", "=", "copy", ".", "deepcopy", "(", "self", ".", "obj", ")", "else", ":", "new_dict", "=", "self", ".", "obj", "pointer", "=", "None", "parts_length", "=", "len", "(", "prop_parts", ")", "-", "1", "for", "i", ",", "part", "in", "enumerate", "(", "prop_parts", ")", ":", "if", "pointer", "is", "None", "and", "i", "==", "parts_length", ":", "new_dict", "[", "part", "]", "=", "value", "elif", "pointer", "is", "None", ":", "pointer", "=", "new_dict", ".", "get", "(", "part", ")", "elif", "i", "==", "parts_length", ":", "pointer", "[", "part", "]", "=", "value", "else", ":", "pointer", "=", "pointer", ".", "get", "(", "part", ")", "return", "new_dict" ]
sets the dot notated property to the passed in value args: prop: a string of the property to retreive "a.b.c" ~ dictionary['a']['b']['c'] value: the value to set the prop object
[ "sets", "the", "dot", "notated", "property", "to", "the", "passed", "in", "value" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/baseutilities.py#L381-L406
245,643
KnowledgeLinks/rdfframework
rdfframework/utilities/baseutilities.py
DictClass.dict
def dict(self): """ converts the class to a dictionary object """ return_obj = {} for attr in dir(self): if not attr.startswith('__') and attr not in self.__reserved: if isinstance(getattr(self, attr), list): return_val = [] for item in getattr(self, attr): if isinstance(item, DictClass): return_val.append(dict(item)) else: return_val.append(item) elif isinstance(getattr(self, attr), dict): return_val = {} for key, item in getattr(self, attr).items(): if isinstance(item, DictClass): return_val[key] = item.dict() else: return_val[key] = item elif isinstance(getattr(self, attr), DictClass): return_val = getattr(self, attr).dict() else: return_val = getattr(self, attr) return_obj[attr] = return_val return return_obj
python
def dict(self): """ converts the class to a dictionary object """ return_obj = {} for attr in dir(self): if not attr.startswith('__') and attr not in self.__reserved: if isinstance(getattr(self, attr), list): return_val = [] for item in getattr(self, attr): if isinstance(item, DictClass): return_val.append(dict(item)) else: return_val.append(item) elif isinstance(getattr(self, attr), dict): return_val = {} for key, item in getattr(self, attr).items(): if isinstance(item, DictClass): return_val[key] = item.dict() else: return_val[key] = item elif isinstance(getattr(self, attr), DictClass): return_val = getattr(self, attr).dict() else: return_val = getattr(self, attr) return_obj[attr] = return_val return return_obj
[ "def", "dict", "(", "self", ")", ":", "return_obj", "=", "{", "}", "for", "attr", "in", "dir", "(", "self", ")", ":", "if", "not", "attr", ".", "startswith", "(", "'__'", ")", "and", "attr", "not", "in", "self", ".", "__reserved", ":", "if", "isinstance", "(", "getattr", "(", "self", ",", "attr", ")", ",", "list", ")", ":", "return_val", "=", "[", "]", "for", "item", "in", "getattr", "(", "self", ",", "attr", ")", ":", "if", "isinstance", "(", "item", ",", "DictClass", ")", ":", "return_val", ".", "append", "(", "dict", "(", "item", ")", ")", "else", ":", "return_val", ".", "append", "(", "item", ")", "elif", "isinstance", "(", "getattr", "(", "self", ",", "attr", ")", ",", "dict", ")", ":", "return_val", "=", "{", "}", "for", "key", ",", "item", "in", "getattr", "(", "self", ",", "attr", ")", ".", "items", "(", ")", ":", "if", "isinstance", "(", "item", ",", "DictClass", ")", ":", "return_val", "[", "key", "]", "=", "item", ".", "dict", "(", ")", "else", ":", "return_val", "[", "key", "]", "=", "item", "elif", "isinstance", "(", "getattr", "(", "self", ",", "attr", ")", ",", "DictClass", ")", ":", "return_val", "=", "getattr", "(", "self", ",", "attr", ")", ".", "dict", "(", ")", "else", ":", "return_val", "=", "getattr", "(", "self", ",", "attr", ")", "return_obj", "[", "attr", "]", "=", "return_val", "return", "return_obj" ]
converts the class to a dictionary object
[ "converts", "the", "class", "to", "a", "dictionary", "object" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/baseutilities.py#L638-L662
245,644
alexhayes/django-toolkit
django_toolkit/markup/html.py
get_anchor_href
def get_anchor_href(markup): """ Given HTML markup, return a list of hrefs for each anchor tag. """ soup = BeautifulSoup(markup, 'lxml') return ['%s' % link.get('href') for link in soup.find_all('a')]
python
def get_anchor_href(markup): """ Given HTML markup, return a list of hrefs for each anchor tag. """ soup = BeautifulSoup(markup, 'lxml') return ['%s' % link.get('href') for link in soup.find_all('a')]
[ "def", "get_anchor_href", "(", "markup", ")", ":", "soup", "=", "BeautifulSoup", "(", "markup", ",", "'lxml'", ")", "return", "[", "'%s'", "%", "link", ".", "get", "(", "'href'", ")", "for", "link", "in", "soup", ".", "find_all", "(", "'a'", ")", "]" ]
Given HTML markup, return a list of hrefs for each anchor tag.
[ "Given", "HTML", "markup", "return", "a", "list", "of", "hrefs", "for", "each", "anchor", "tag", "." ]
b64106392fad596defc915b8235fe6e1d0013b5b
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/markup/html.py#L3-L8
245,645
alexhayes/django-toolkit
django_toolkit/markup/html.py
get_anchor_contents
def get_anchor_contents(markup): """ Given HTML markup, return a list of href inner html for each anchor tag. """ soup = BeautifulSoup(markup, 'lxml') return ['%s' % link.contents[0] for link in soup.find_all('a')]
python
def get_anchor_contents(markup): """ Given HTML markup, return a list of href inner html for each anchor tag. """ soup = BeautifulSoup(markup, 'lxml') return ['%s' % link.contents[0] for link in soup.find_all('a')]
[ "def", "get_anchor_contents", "(", "markup", ")", ":", "soup", "=", "BeautifulSoup", "(", "markup", ",", "'lxml'", ")", "return", "[", "'%s'", "%", "link", ".", "contents", "[", "0", "]", "for", "link", "in", "soup", ".", "find_all", "(", "'a'", ")", "]" ]
Given HTML markup, return a list of href inner html for each anchor tag.
[ "Given", "HTML", "markup", "return", "a", "list", "of", "href", "inner", "html", "for", "each", "anchor", "tag", "." ]
b64106392fad596defc915b8235fe6e1d0013b5b
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/markup/html.py#L10-L15
245,646
abe-winter/pg13-py
pg13/weval.py
names_from_exp
def names_from_exp(exp): "Return a list of AttrX and NameX from the expression." def match(exp): return isinstance(exp, (sqparse2.NameX, sqparse2.AttrX)) paths = treepath.sub_slots(exp, match, match=True, recurse_into_matches=False) return [exp[path] for path in paths]
python
def names_from_exp(exp): "Return a list of AttrX and NameX from the expression." def match(exp): return isinstance(exp, (sqparse2.NameX, sqparse2.AttrX)) paths = treepath.sub_slots(exp, match, match=True, recurse_into_matches=False) return [exp[path] for path in paths]
[ "def", "names_from_exp", "(", "exp", ")", ":", "def", "match", "(", "exp", ")", ":", "return", "isinstance", "(", "exp", ",", "(", "sqparse2", ".", "NameX", ",", "sqparse2", ".", "AttrX", ")", ")", "paths", "=", "treepath", ".", "sub_slots", "(", "exp", ",", "match", ",", "match", "=", "True", ",", "recurse_into_matches", "=", "False", ")", "return", "[", "exp", "[", "path", "]", "for", "path", "in", "paths", "]" ]
Return a list of AttrX and NameX from the expression.
[ "Return", "a", "list", "of", "AttrX", "and", "NameX", "from", "the", "expression", "." ]
c78806f99f35541a8756987e86edca3438aa97f5
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/weval.py#L31-L36
245,647
lizardsystem/tags2sdists
tags2sdists/packagedir.py
PackageDir.add_tarball
def add_tarball(self, tarball, package): """Add a tarball, possibly creating the directory if needed.""" if tarball is None: logger.error( "No tarball found for %s: probably a renamed project?", package) return target_dir = os.path.join(self.root_directory, package) if not os.path.exists(target_dir): os.mkdir(target_dir) logger.info("Created %s", target_dir) logger.info("Copying tarball to %s", target_dir) shutil.copy(tarball, target_dir)
python
def add_tarball(self, tarball, package): """Add a tarball, possibly creating the directory if needed.""" if tarball is None: logger.error( "No tarball found for %s: probably a renamed project?", package) return target_dir = os.path.join(self.root_directory, package) if not os.path.exists(target_dir): os.mkdir(target_dir) logger.info("Created %s", target_dir) logger.info("Copying tarball to %s", target_dir) shutil.copy(tarball, target_dir)
[ "def", "add_tarball", "(", "self", ",", "tarball", ",", "package", ")", ":", "if", "tarball", "is", "None", ":", "logger", ".", "error", "(", "\"No tarball found for %s: probably a renamed project?\"", ",", "package", ")", "return", "target_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "root_directory", ",", "package", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "target_dir", ")", ":", "os", ".", "mkdir", "(", "target_dir", ")", "logger", ".", "info", "(", "\"Created %s\"", ",", "target_dir", ")", "logger", ".", "info", "(", "\"Copying tarball to %s\"", ",", "target_dir", ")", "shutil", ".", "copy", "(", "tarball", ",", "target_dir", ")" ]
Add a tarball, possibly creating the directory if needed.
[ "Add", "a", "tarball", "possibly", "creating", "the", "directory", "if", "needed", "." ]
72f3c664940133e3238fca4d87edcc36b9775e48
https://github.com/lizardsystem/tags2sdists/blob/72f3c664940133e3238fca4d87edcc36b9775e48/tags2sdists/packagedir.py#L37-L49
245,648
oubiwann/carapace
carapace/app/shell/pythonshell.py
CommandAPI.ls
def ls(self): """ List the objects in the current namespace, in alphabetical order. """ width = max([len(x) for x in self.namespace.keys()]) for key, value in sorted(self.namespace.items()): if key == "_": continue info = "" if (isinstance(value, dict) or isinstance(value, list) or key == "services"): info = "data" elif type(value).__name__ == "module": info = value.__name__ elif type(value).__name__ == "function": info = "%s.%s" % (value.__module__, value.__name__) elif type(value).__name__ == "instance": info = "%s.%s" % (value.__module__, value.__class__.__name__) else: info = "%s.%s.%s" % ( value.im_class.__module__, value.im_class.__name__, key) print "\t%s - %s" % (key.ljust(width), info)
python
def ls(self): """ List the objects in the current namespace, in alphabetical order. """ width = max([len(x) for x in self.namespace.keys()]) for key, value in sorted(self.namespace.items()): if key == "_": continue info = "" if (isinstance(value, dict) or isinstance(value, list) or key == "services"): info = "data" elif type(value).__name__ == "module": info = value.__name__ elif type(value).__name__ == "function": info = "%s.%s" % (value.__module__, value.__name__) elif type(value).__name__ == "instance": info = "%s.%s" % (value.__module__, value.__class__.__name__) else: info = "%s.%s.%s" % ( value.im_class.__module__, value.im_class.__name__, key) print "\t%s - %s" % (key.ljust(width), info)
[ "def", "ls", "(", "self", ")", ":", "width", "=", "max", "(", "[", "len", "(", "x", ")", "for", "x", "in", "self", ".", "namespace", ".", "keys", "(", ")", "]", ")", "for", "key", ",", "value", "in", "sorted", "(", "self", ".", "namespace", ".", "items", "(", ")", ")", ":", "if", "key", "==", "\"_\"", ":", "continue", "info", "=", "\"\"", "if", "(", "isinstance", "(", "value", ",", "dict", ")", "or", "isinstance", "(", "value", ",", "list", ")", "or", "key", "==", "\"services\"", ")", ":", "info", "=", "\"data\"", "elif", "type", "(", "value", ")", ".", "__name__", "==", "\"module\"", ":", "info", "=", "value", ".", "__name__", "elif", "type", "(", "value", ")", ".", "__name__", "==", "\"function\"", ":", "info", "=", "\"%s.%s\"", "%", "(", "value", ".", "__module__", ",", "value", ".", "__name__", ")", "elif", "type", "(", "value", ")", ".", "__name__", "==", "\"instance\"", ":", "info", "=", "\"%s.%s\"", "%", "(", "value", ".", "__module__", ",", "value", ".", "__class__", ".", "__name__", ")", "else", ":", "info", "=", "\"%s.%s.%s\"", "%", "(", "value", ".", "im_class", ".", "__module__", ",", "value", ".", "im_class", ".", "__name__", ",", "key", ")", "print", "\"\\t%s - %s\"", "%", "(", "key", ".", "ljust", "(", "width", ")", ",", "info", ")" ]
List the objects in the current namespace, in alphabetical order.
[ "List", "the", "objects", "in", "the", "current", "namespace", "in", "alphabetical", "order", "." ]
88470b12c198bea5067dcff1a26aa4400b73632c
https://github.com/oubiwann/carapace/blob/88470b12c198bea5067dcff1a26aa4400b73632c/carapace/app/shell/pythonshell.py#L51-L72
245,649
cogniteev/docido-python-sdk
docido_sdk/toolbox/text.py
to_unicode
def to_unicode(text, charset=None): """Convert input to an `unicode` object. For a `str` object, we'll first try to decode the bytes using the given `charset` encoding (or UTF-8 if none is specified), then we fall back to the latin1 encoding which might be correct or not, but at least preserves the original byte sequence by mapping each byte to the corresponding unicode code point in the range U+0000 to U+00FF. For anything else, a simple `unicode()` conversion is attempted, with special care taken with `Exception` objects. """ if isinstance(text, str): try: return unicode(text, charset or 'utf-8') except UnicodeDecodeError: return unicode(text, 'latin1') elif isinstance(text, Exception): if os.name == 'nt' and \ isinstance(text, (OSError, IOError)): # pragma: no cover # the exception might have a localized error string encoded with # ANSI codepage if OSError and IOError on Windows try: return unicode(str(text), 'mbcs') except UnicodeError: pass # two possibilities for storing unicode strings in exception data: try: # custom __str__ method on the exception (e.g. PermissionError) return unicode(text) except UnicodeError: # unicode arguments given to the exception (e.g. parse_date) return ' '.join([to_unicode(arg) for arg in text.args]) return unicode(text)
python
def to_unicode(text, charset=None): """Convert input to an `unicode` object. For a `str` object, we'll first try to decode the bytes using the given `charset` encoding (or UTF-8 if none is specified), then we fall back to the latin1 encoding which might be correct or not, but at least preserves the original byte sequence by mapping each byte to the corresponding unicode code point in the range U+0000 to U+00FF. For anything else, a simple `unicode()` conversion is attempted, with special care taken with `Exception` objects. """ if isinstance(text, str): try: return unicode(text, charset or 'utf-8') except UnicodeDecodeError: return unicode(text, 'latin1') elif isinstance(text, Exception): if os.name == 'nt' and \ isinstance(text, (OSError, IOError)): # pragma: no cover # the exception might have a localized error string encoded with # ANSI codepage if OSError and IOError on Windows try: return unicode(str(text), 'mbcs') except UnicodeError: pass # two possibilities for storing unicode strings in exception data: try: # custom __str__ method on the exception (e.g. PermissionError) return unicode(text) except UnicodeError: # unicode arguments given to the exception (e.g. parse_date) return ' '.join([to_unicode(arg) for arg in text.args]) return unicode(text)
[ "def", "to_unicode", "(", "text", ",", "charset", "=", "None", ")", ":", "if", "isinstance", "(", "text", ",", "str", ")", ":", "try", ":", "return", "unicode", "(", "text", ",", "charset", "or", "'utf-8'", ")", "except", "UnicodeDecodeError", ":", "return", "unicode", "(", "text", ",", "'latin1'", ")", "elif", "isinstance", "(", "text", ",", "Exception", ")", ":", "if", "os", ".", "name", "==", "'nt'", "and", "isinstance", "(", "text", ",", "(", "OSError", ",", "IOError", ")", ")", ":", "# pragma: no cover", "# the exception might have a localized error string encoded with", "# ANSI codepage if OSError and IOError on Windows", "try", ":", "return", "unicode", "(", "str", "(", "text", ")", ",", "'mbcs'", ")", "except", "UnicodeError", ":", "pass", "# two possibilities for storing unicode strings in exception data:", "try", ":", "# custom __str__ method on the exception (e.g. PermissionError)", "return", "unicode", "(", "text", ")", "except", "UnicodeError", ":", "# unicode arguments given to the exception (e.g. parse_date)", "return", "' '", ".", "join", "(", "[", "to_unicode", "(", "arg", ")", "for", "arg", "in", "text", ".", "args", "]", ")", "return", "unicode", "(", "text", ")" ]
Convert input to an `unicode` object. For a `str` object, we'll first try to decode the bytes using the given `charset` encoding (or UTF-8 if none is specified), then we fall back to the latin1 encoding which might be correct or not, but at least preserves the original byte sequence by mapping each byte to the corresponding unicode code point in the range U+0000 to U+00FF. For anything else, a simple `unicode()` conversion is attempted, with special care taken with `Exception` objects.
[ "Convert", "input", "to", "an", "unicode", "object", "." ]
58ecb6c6f5757fd40c0601657ab18368da7ddf33
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/text.py#L4-L37
245,650
cogniteev/docido-python-sdk
docido_sdk/toolbox/text.py
exception_to_unicode
def exception_to_unicode(e, traceback=False): """Convert an `Exception` to an `unicode` object. In addition to `to_unicode`, this representation of the exception also contains the class name and optionally the traceback. """ message = '%s: %s' % (e.__class__.__name__, to_unicode(e)) if traceback: from docido_sdk.toolbox import get_last_traceback traceback_only = get_last_traceback().split('\n')[:-2] message = '\n%s\n%s' % (to_unicode('\n'.join(traceback_only)), message) return message
python
def exception_to_unicode(e, traceback=False): """Convert an `Exception` to an `unicode` object. In addition to `to_unicode`, this representation of the exception also contains the class name and optionally the traceback. """ message = '%s: %s' % (e.__class__.__name__, to_unicode(e)) if traceback: from docido_sdk.toolbox import get_last_traceback traceback_only = get_last_traceback().split('\n')[:-2] message = '\n%s\n%s' % (to_unicode('\n'.join(traceback_only)), message) return message
[ "def", "exception_to_unicode", "(", "e", ",", "traceback", "=", "False", ")", ":", "message", "=", "'%s: %s'", "%", "(", "e", ".", "__class__", ".", "__name__", ",", "to_unicode", "(", "e", ")", ")", "if", "traceback", ":", "from", "docido_sdk", ".", "toolbox", "import", "get_last_traceback", "traceback_only", "=", "get_last_traceback", "(", ")", ".", "split", "(", "'\\n'", ")", "[", ":", "-", "2", "]", "message", "=", "'\\n%s\\n%s'", "%", "(", "to_unicode", "(", "'\\n'", ".", "join", "(", "traceback_only", ")", ")", ",", "message", ")", "return", "message" ]
Convert an `Exception` to an `unicode` object. In addition to `to_unicode`, this representation of the exception also contains the class name and optionally the traceback.
[ "Convert", "an", "Exception", "to", "an", "unicode", "object", "." ]
58ecb6c6f5757fd40c0601657ab18368da7ddf33
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/text.py#L40-L51
245,651
cogniteev/docido-python-sdk
docido_sdk/toolbox/text.py
levenshtein
def levenshtein(s, t): """ Compute the Levenshtein distance between 2 strings, which is the minimum number of operations required to perform on a string to get another one. code taken from https://en.wikibooks.org :param basestring s: :param basestring t: :rtype: int """ ''' From Wikipedia article; Iterative with two matrix rows. ''' if s == t: return 0 elif len(s) == 0: return len(t) elif len(t) == 0: return len(s) v0 = [None] * (len(t) + 1) v1 = [None] * (len(t) + 1) for i in range(len(v0)): v0[i] = i for i in range(len(s)): v1[0] = i + 1 for j in range(len(t)): cost = 0 if s[i] == t[j] else 1 v1[j + 1] = min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost) for j in range(len(v0)): v0[j] = v1[j] return v1[len(t)]
python
def levenshtein(s, t): """ Compute the Levenshtein distance between 2 strings, which is the minimum number of operations required to perform on a string to get another one. code taken from https://en.wikibooks.org :param basestring s: :param basestring t: :rtype: int """ ''' From Wikipedia article; Iterative with two matrix rows. ''' if s == t: return 0 elif len(s) == 0: return len(t) elif len(t) == 0: return len(s) v0 = [None] * (len(t) + 1) v1 = [None] * (len(t) + 1) for i in range(len(v0)): v0[i] = i for i in range(len(s)): v1[0] = i + 1 for j in range(len(t)): cost = 0 if s[i] == t[j] else 1 v1[j + 1] = min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost) for j in range(len(v0)): v0[j] = v1[j] return v1[len(t)]
[ "def", "levenshtein", "(", "s", ",", "t", ")", ":", "''' From Wikipedia article; Iterative with two matrix rows. '''", "if", "s", "==", "t", ":", "return", "0", "elif", "len", "(", "s", ")", "==", "0", ":", "return", "len", "(", "t", ")", "elif", "len", "(", "t", ")", "==", "0", ":", "return", "len", "(", "s", ")", "v0", "=", "[", "None", "]", "*", "(", "len", "(", "t", ")", "+", "1", ")", "v1", "=", "[", "None", "]", "*", "(", "len", "(", "t", ")", "+", "1", ")", "for", "i", "in", "range", "(", "len", "(", "v0", ")", ")", ":", "v0", "[", "i", "]", "=", "i", "for", "i", "in", "range", "(", "len", "(", "s", ")", ")", ":", "v1", "[", "0", "]", "=", "i", "+", "1", "for", "j", "in", "range", "(", "len", "(", "t", ")", ")", ":", "cost", "=", "0", "if", "s", "[", "i", "]", "==", "t", "[", "j", "]", "else", "1", "v1", "[", "j", "+", "1", "]", "=", "min", "(", "v1", "[", "j", "]", "+", "1", ",", "v0", "[", "j", "+", "1", "]", "+", "1", ",", "v0", "[", "j", "]", "+", "cost", ")", "for", "j", "in", "range", "(", "len", "(", "v0", ")", ")", ":", "v0", "[", "j", "]", "=", "v1", "[", "j", "]", "return", "v1", "[", "len", "(", "t", ")", "]" ]
Compute the Levenshtein distance between 2 strings, which is the minimum number of operations required to perform on a string to get another one. code taken from https://en.wikibooks.org :param basestring s: :param basestring t: :rtype: int
[ "Compute", "the", "Levenshtein", "distance", "between", "2", "strings", "which", "is", "the", "minimum", "number", "of", "operations", "required", "to", "perform", "on", "a", "string", "to", "get", "another", "one", "." ]
58ecb6c6f5757fd40c0601657ab18368da7ddf33
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/text.py#L54-L84
245,652
etscrivner/nose-perfdump
perfdump/console.py
Console.do_help
def do_help(self, line): """Displays help information.""" print "" print "Perfdump CLI provides a handful of simple ways to query your" print "performance data." print "" print "The simplest queries are of the form:" print "" print "\t[slowest|fastest] [tests|setups]" print "" print "For example:" print "" print "\tperfdump > slowest tests" print "" print "Prints the slowest 10 tests" print "" print "Additional grouping of results can be request." print "" print "\tperfdump > slowest tests groupby file" print "" print "Grouping options include:" print "" print "\tfile | module | class | function" print ""
python
def do_help(self, line): """Displays help information.""" print "" print "Perfdump CLI provides a handful of simple ways to query your" print "performance data." print "" print "The simplest queries are of the form:" print "" print "\t[slowest|fastest] [tests|setups]" print "" print "For example:" print "" print "\tperfdump > slowest tests" print "" print "Prints the slowest 10 tests" print "" print "Additional grouping of results can be request." print "" print "\tperfdump > slowest tests groupby file" print "" print "Grouping options include:" print "" print "\tfile | module | class | function" print ""
[ "def", "do_help", "(", "self", ",", "line", ")", ":", "print", "\"\"", "print", "\"Perfdump CLI provides a handful of simple ways to query your\"", "print", "\"performance data.\"", "print", "\"\"", "print", "\"The simplest queries are of the form:\"", "print", "\"\"", "print", "\"\\t[slowest|fastest] [tests|setups]\"", "print", "\"\"", "print", "\"For example:\"", "print", "\"\"", "print", "\"\\tperfdump > slowest tests\"", "print", "\"\"", "print", "\"Prints the slowest 10 tests\"", "print", "\"\"", "print", "\"Additional grouping of results can be request.\"", "print", "\"\"", "print", "\"\\tperfdump > slowest tests groupby file\"", "print", "\"\"", "print", "\"Grouping options include:\"", "print", "\"\"", "print", "\"\\tfile | module | class | function\"", "print", "\"\"" ]
Displays help information.
[ "Displays", "help", "information", "." ]
a203a68495d30346fab43fb903cb60cd29b17d49
https://github.com/etscrivner/nose-perfdump/blob/a203a68495d30346fab43fb903cb60cd29b17d49/perfdump/console.py#L139-L162
245,653
Phasemix/phasetumblr
phasetumblr/phasetumblr.py
TumblrBlog.get_allposts
def get_allposts(self): ''' Return all posts in blog sorted by date ''' result = self.client.posts(self.blog, offset = 0, limit = 1) try: total_posts = result['total_posts'] except: raise phasetumblr_errors.TumblrBlogException(result['meta']['msg']) delta = (total_posts / 10) + 1 all_posts = [] posts_ids = [] for j in range(delta): start = j * 10 end = (j + 1) * 10 posts = self.client.posts(self.blog, offset = start, limit = end)['posts'] if not len(posts): break for i in posts: if i['id'] in posts_ids: continue description = split_body(i['body']) body = split_body(i['body'], 1) post = {} post['title'] = i['title'] post['link'] = i['post_url'] post['date'] = datetime.strptime(i['date'], '%Y-%m-%d %H:%M:%S %Z') post['tags'] = i['tags'] post['id'] = i['id'] post['body'] = body post['description'] = description all_posts.append(post) posts_ids.append(i['id']) newlist = sorted(all_posts, key=lambda k: k['date']) return newlist
python
def get_allposts(self): ''' Return all posts in blog sorted by date ''' result = self.client.posts(self.blog, offset = 0, limit = 1) try: total_posts = result['total_posts'] except: raise phasetumblr_errors.TumblrBlogException(result['meta']['msg']) delta = (total_posts / 10) + 1 all_posts = [] posts_ids = [] for j in range(delta): start = j * 10 end = (j + 1) * 10 posts = self.client.posts(self.blog, offset = start, limit = end)['posts'] if not len(posts): break for i in posts: if i['id'] in posts_ids: continue description = split_body(i['body']) body = split_body(i['body'], 1) post = {} post['title'] = i['title'] post['link'] = i['post_url'] post['date'] = datetime.strptime(i['date'], '%Y-%m-%d %H:%M:%S %Z') post['tags'] = i['tags'] post['id'] = i['id'] post['body'] = body post['description'] = description all_posts.append(post) posts_ids.append(i['id']) newlist = sorted(all_posts, key=lambda k: k['date']) return newlist
[ "def", "get_allposts", "(", "self", ")", ":", "result", "=", "self", ".", "client", ".", "posts", "(", "self", ".", "blog", ",", "offset", "=", "0", ",", "limit", "=", "1", ")", "try", ":", "total_posts", "=", "result", "[", "'total_posts'", "]", "except", ":", "raise", "phasetumblr_errors", ".", "TumblrBlogException", "(", "result", "[", "'meta'", "]", "[", "'msg'", "]", ")", "delta", "=", "(", "total_posts", "/", "10", ")", "+", "1", "all_posts", "=", "[", "]", "posts_ids", "=", "[", "]", "for", "j", "in", "range", "(", "delta", ")", ":", "start", "=", "j", "*", "10", "end", "=", "(", "j", "+", "1", ")", "*", "10", "posts", "=", "self", ".", "client", ".", "posts", "(", "self", ".", "blog", ",", "offset", "=", "start", ",", "limit", "=", "end", ")", "[", "'posts'", "]", "if", "not", "len", "(", "posts", ")", ":", "break", "for", "i", "in", "posts", ":", "if", "i", "[", "'id'", "]", "in", "posts_ids", ":", "continue", "description", "=", "split_body", "(", "i", "[", "'body'", "]", ")", "body", "=", "split_body", "(", "i", "[", "'body'", "]", ",", "1", ")", "post", "=", "{", "}", "post", "[", "'title'", "]", "=", "i", "[", "'title'", "]", "post", "[", "'link'", "]", "=", "i", "[", "'post_url'", "]", "post", "[", "'date'", "]", "=", "datetime", ".", "strptime", "(", "i", "[", "'date'", "]", ",", "'%Y-%m-%d %H:%M:%S %Z'", ")", "post", "[", "'tags'", "]", "=", "i", "[", "'tags'", "]", "post", "[", "'id'", "]", "=", "i", "[", "'id'", "]", "post", "[", "'body'", "]", "=", "body", "post", "[", "'description'", "]", "=", "description", "all_posts", ".", "append", "(", "post", ")", "posts_ids", ".", "append", "(", "i", "[", "'id'", "]", ")", "newlist", "=", "sorted", "(", "all_posts", ",", "key", "=", "lambda", "k", ":", "k", "[", "'date'", "]", ")", "return", "newlist" ]
Return all posts in blog sorted by date
[ "Return", "all", "posts", "in", "blog", "sorted", "by", "date" ]
1b699ac3fc6a903fc0a9bfdc9d1f76cb57f679f1
https://github.com/Phasemix/phasetumblr/blob/1b699ac3fc6a903fc0a9bfdc9d1f76cb57f679f1/phasetumblr/phasetumblr.py#L24-L60
245,654
eddiejessup/metropack
metropack/pack.py
n_to_pf
def n_to_pf(L, n, R): """Returns the packing fraction for a number of non-intersecting spheres. Parameters ---------- L: float array, shape (d,) System lengths. n: integer Number of spheres. R: float Sphere radius. Returns ------- pf: float Fraction of space occupied by the spheres. """ dim = L.shape[0] return (n * sphere_volume(R=R, n=dim)) / np.product(L)
python
def n_to_pf(L, n, R): """Returns the packing fraction for a number of non-intersecting spheres. Parameters ---------- L: float array, shape (d,) System lengths. n: integer Number of spheres. R: float Sphere radius. Returns ------- pf: float Fraction of space occupied by the spheres. """ dim = L.shape[0] return (n * sphere_volume(R=R, n=dim)) / np.product(L)
[ "def", "n_to_pf", "(", "L", ",", "n", ",", "R", ")", ":", "dim", "=", "L", ".", "shape", "[", "0", "]", "return", "(", "n", "*", "sphere_volume", "(", "R", "=", "R", ",", "n", "=", "dim", ")", ")", "/", "np", ".", "product", "(", "L", ")" ]
Returns the packing fraction for a number of non-intersecting spheres. Parameters ---------- L: float array, shape (d,) System lengths. n: integer Number of spheres. R: float Sphere radius. Returns ------- pf: float Fraction of space occupied by the spheres.
[ "Returns", "the", "packing", "fraction", "for", "a", "number", "of", "non", "-", "intersecting", "spheres", "." ]
528b47d0f2f70f39e1490e41433f2da8c8b9d63c
https://github.com/eddiejessup/metropack/blob/528b47d0f2f70f39e1490e41433f2da8c8b9d63c/metropack/pack.py#L14-L32
245,655
eddiejessup/metropack
metropack/pack.py
pf_to_n
def pf_to_n(L, pf, R): """Returns the number of non-intersecting spheres required to achieve as close to a given packing fraction as possible, along with the actual achieved packing fraction. for a number of non-intersecting spheres. Parameters ---------- L: float array, shape (d,) System lengths. pf: float Fraction of space to be occupied by the spheres. R: float Sphere radius. Returns ------- n: integer Number of spheres required to achieve a packing fraction `pf_actual` pf_actual: Fraction of space occupied by `n` spheres. This is the closest possible fraction achievable to `pf`. """ dim = L.shape[0] n = int(round(pf * np.product(L) / sphere_volume(R, dim))) pf_actual = n_to_pf(L, n, R) return n, pf_actual
python
def pf_to_n(L, pf, R): """Returns the number of non-intersecting spheres required to achieve as close to a given packing fraction as possible, along with the actual achieved packing fraction. for a number of non-intersecting spheres. Parameters ---------- L: float array, shape (d,) System lengths. pf: float Fraction of space to be occupied by the spheres. R: float Sphere radius. Returns ------- n: integer Number of spheres required to achieve a packing fraction `pf_actual` pf_actual: Fraction of space occupied by `n` spheres. This is the closest possible fraction achievable to `pf`. """ dim = L.shape[0] n = int(round(pf * np.product(L) / sphere_volume(R, dim))) pf_actual = n_to_pf(L, n, R) return n, pf_actual
[ "def", "pf_to_n", "(", "L", ",", "pf", ",", "R", ")", ":", "dim", "=", "L", ".", "shape", "[", "0", "]", "n", "=", "int", "(", "round", "(", "pf", "*", "np", ".", "product", "(", "L", ")", "/", "sphere_volume", "(", "R", ",", "dim", ")", ")", ")", "pf_actual", "=", "n_to_pf", "(", "L", ",", "n", ",", "R", ")", "return", "n", ",", "pf_actual" ]
Returns the number of non-intersecting spheres required to achieve as close to a given packing fraction as possible, along with the actual achieved packing fraction. for a number of non-intersecting spheres. Parameters ---------- L: float array, shape (d,) System lengths. pf: float Fraction of space to be occupied by the spheres. R: float Sphere radius. Returns ------- n: integer Number of spheres required to achieve a packing fraction `pf_actual` pf_actual: Fraction of space occupied by `n` spheres. This is the closest possible fraction achievable to `pf`.
[ "Returns", "the", "number", "of", "non", "-", "intersecting", "spheres", "required", "to", "achieve", "as", "close", "to", "a", "given", "packing", "fraction", "as", "possible", "along", "with", "the", "actual", "achieved", "packing", "fraction", ".", "for", "a", "number", "of", "non", "-", "intersecting", "spheres", "." ]
528b47d0f2f70f39e1490e41433f2da8c8b9d63c
https://github.com/eddiejessup/metropack/blob/528b47d0f2f70f39e1490e41433f2da8c8b9d63c/metropack/pack.py#L35-L60
245,656
eddiejessup/metropack
metropack/pack.py
pack_simple
def pack_simple(R, L, pf=None, n=None, rng=None, periodic=False): """Pack a number of non-intersecting spheres into a system. Can specify packing by number of spheres or packing fraction. This implementation uses a naive uniform distribution of spheres, and the Tabula Rasa rule (start from scratch if an intersection occurs). This is likely to be very slow for high packing fractions Parameters ---------- R: float Sphere radius. L: float array, shape (d,) System lengths. pf: float or None Packing fraction n: integer or None Number of spheres. rng: RandomState or None Random number generator. If None, use inbuilt numpy state. periodic: bool Whether or not the system is periodic. Returns ------- r: float array, shape (n, d) Coordinates of the centres of the spheres for a valid configuration. R_actual: float Actual sphere radius used in the packing. In this implementation this will always be equal to `R`; it is returned only to provide a uniform interface with the Metropolis-Hastings implementation. """ if rng is None: rng = np.random if pf is not None: if pf == 0.0: return np.array([]), R # If packing fraction is specified, find required number of spheres # and the actual packing fraction this will produce n, pf_actual = pf_to_n(L, pf, R) elif n is not None: if n == 0: return np.array([]), R if periodic: return _pack_simple_periodic(R, L, n, rng) else: return _pack_simple(R, L, n, rng)
python
def pack_simple(R, L, pf=None, n=None, rng=None, periodic=False): """Pack a number of non-intersecting spheres into a system. Can specify packing by number of spheres or packing fraction. This implementation uses a naive uniform distribution of spheres, and the Tabula Rasa rule (start from scratch if an intersection occurs). This is likely to be very slow for high packing fractions Parameters ---------- R: float Sphere radius. L: float array, shape (d,) System lengths. pf: float or None Packing fraction n: integer or None Number of spheres. rng: RandomState or None Random number generator. If None, use inbuilt numpy state. periodic: bool Whether or not the system is periodic. Returns ------- r: float array, shape (n, d) Coordinates of the centres of the spheres for a valid configuration. R_actual: float Actual sphere radius used in the packing. In this implementation this will always be equal to `R`; it is returned only to provide a uniform interface with the Metropolis-Hastings implementation. """ if rng is None: rng = np.random if pf is not None: if pf == 0.0: return np.array([]), R # If packing fraction is specified, find required number of spheres # and the actual packing fraction this will produce n, pf_actual = pf_to_n(L, pf, R) elif n is not None: if n == 0: return np.array([]), R if periodic: return _pack_simple_periodic(R, L, n, rng) else: return _pack_simple(R, L, n, rng)
[ "def", "pack_simple", "(", "R", ",", "L", ",", "pf", "=", "None", ",", "n", "=", "None", ",", "rng", "=", "None", ",", "periodic", "=", "False", ")", ":", "if", "rng", "is", "None", ":", "rng", "=", "np", ".", "random", "if", "pf", "is", "not", "None", ":", "if", "pf", "==", "0.0", ":", "return", "np", ".", "array", "(", "[", "]", ")", ",", "R", "# If packing fraction is specified, find required number of spheres", "# and the actual packing fraction this will produce", "n", ",", "pf_actual", "=", "pf_to_n", "(", "L", ",", "pf", ",", "R", ")", "elif", "n", "is", "not", "None", ":", "if", "n", "==", "0", ":", "return", "np", ".", "array", "(", "[", "]", ")", ",", "R", "if", "periodic", ":", "return", "_pack_simple_periodic", "(", "R", ",", "L", ",", "n", ",", "rng", ")", "else", ":", "return", "_pack_simple", "(", "R", ",", "L", ",", "n", ",", "rng", ")" ]
Pack a number of non-intersecting spheres into a system. Can specify packing by number of spheres or packing fraction. This implementation uses a naive uniform distribution of spheres, and the Tabula Rasa rule (start from scratch if an intersection occurs). This is likely to be very slow for high packing fractions Parameters ---------- R: float Sphere radius. L: float array, shape (d,) System lengths. pf: float or None Packing fraction n: integer or None Number of spheres. rng: RandomState or None Random number generator. If None, use inbuilt numpy state. periodic: bool Whether or not the system is periodic. Returns ------- r: float array, shape (n, d) Coordinates of the centres of the spheres for a valid configuration. R_actual: float Actual sphere radius used in the packing. In this implementation this will always be equal to `R`; it is returned only to provide a uniform interface with the Metropolis-Hastings implementation.
[ "Pack", "a", "number", "of", "non", "-", "intersecting", "spheres", "into", "a", "system", "." ]
528b47d0f2f70f39e1490e41433f2da8c8b9d63c
https://github.com/eddiejessup/metropack/blob/528b47d0f2f70f39e1490e41433f2da8c8b9d63c/metropack/pack.py#L85-L134
245,657
eddiejessup/metropack
metropack/pack.py
pack
def pack(R, L, pf=None, n=None, rng=None, periodic=False, beta_max=1e4, dL_max=0.02, dr_max=0.02): """Pack a number of non-intersecting spheres into a periodic system. Can specify packing by number of spheres or packing fraction. This implementation uses the Metropolis-Hastings algorithm for an NPT system. Parameters ---------- R: float Sphere radius. L: float array, shape (d,) System lengths. pf: float or None Packing fraction n: integer or None Number of spheres. rng: RandomState or None Random number generator. If None, use inbuilt numpy state. periodic: bool Whether or not the system is periodic. Metropolis-Hastings parameters ------------------------------ Playing with these parameters may improve packing speed. beta_max: float, greater than zero. Inverse temperature which controls how little noiseis in the system. dL_max: float, 0 < dL_max < 1 Maximum fraction by which to perturb the system size. dr_max: float, 0 < dr_max < 1 Maximum system fraction by which to perturb sphere positions. Returns ------- r: float array, shape (n, d) Coordinates of the centres of the spheres for a valid configuration. R_actual: float Actual sphere radius used in the packing. """ if pf is not None: if pf == 0.0: return np.array([]), R # If packing fraction is specified, find required number of spheres # and the actual packing fraction this will produce n, pf_actual = pf_to_n(L, pf, R) elif n is not None: if n == 0: return np.array([]), R # If n is specified, find packing fraction pf_actual = n_to_pf(L, n, R) # Calculate an initial packing fraction and system size # Start at at most 0.5%; lower if the desired packing fraction is very low pf_initial = min(0.005, pf_actual / 2.0) # Find system size that will create this packing fraction dim = L.shape[0] increase_initial_ratio = (pf_actual / pf_initial) ** (1.0 / dim) L_0 = L * increase_initial_ratio # Pack naively into this system r_0, R = pack_simple(R, L_0, n=n, rng=rng, periodic=periodic) mg = metro_rcp_factory(periodic, r_0, L_0, R, dr_max, dL_max, rng=rng) print('Initial packing done, Initial packing: {:g}'.format(mg.pf)) t = 0 while mg.pf < pf_actual: t += 1 beta = beta_max * mg.pf mg.iterate(beta) if not t % every: print('Packing: {:g}%'.format(100.0 * mg.pf)) print('Final packing: {:g}%'.format(100.0 * mg.pf)) return mg.r, mg.R
python
def pack(R, L, pf=None, n=None, rng=None, periodic=False, beta_max=1e4, dL_max=0.02, dr_max=0.02): """Pack a number of non-intersecting spheres into a periodic system. Can specify packing by number of spheres or packing fraction. This implementation uses the Metropolis-Hastings algorithm for an NPT system. Parameters ---------- R: float Sphere radius. L: float array, shape (d,) System lengths. pf: float or None Packing fraction n: integer or None Number of spheres. rng: RandomState or None Random number generator. If None, use inbuilt numpy state. periodic: bool Whether or not the system is periodic. Metropolis-Hastings parameters ------------------------------ Playing with these parameters may improve packing speed. beta_max: float, greater than zero. Inverse temperature which controls how little noiseis in the system. dL_max: float, 0 < dL_max < 1 Maximum fraction by which to perturb the system size. dr_max: float, 0 < dr_max < 1 Maximum system fraction by which to perturb sphere positions. Returns ------- r: float array, shape (n, d) Coordinates of the centres of the spheres for a valid configuration. R_actual: float Actual sphere radius used in the packing. """ if pf is not None: if pf == 0.0: return np.array([]), R # If packing fraction is specified, find required number of spheres # and the actual packing fraction this will produce n, pf_actual = pf_to_n(L, pf, R) elif n is not None: if n == 0: return np.array([]), R # If n is specified, find packing fraction pf_actual = n_to_pf(L, n, R) # Calculate an initial packing fraction and system size # Start at at most 0.5%; lower if the desired packing fraction is very low pf_initial = min(0.005, pf_actual / 2.0) # Find system size that will create this packing fraction dim = L.shape[0] increase_initial_ratio = (pf_actual / pf_initial) ** (1.0 / dim) L_0 = L * increase_initial_ratio # Pack naively into this system r_0, R = pack_simple(R, L_0, n=n, rng=rng, periodic=periodic) mg = metro_rcp_factory(periodic, r_0, L_0, R, dr_max, dL_max, rng=rng) print('Initial packing done, Initial packing: {:g}'.format(mg.pf)) t = 0 while mg.pf < pf_actual: t += 1 beta = beta_max * mg.pf mg.iterate(beta) if not t % every: print('Packing: {:g}%'.format(100.0 * mg.pf)) print('Final packing: {:g}%'.format(100.0 * mg.pf)) return mg.r, mg.R
[ "def", "pack", "(", "R", ",", "L", ",", "pf", "=", "None", ",", "n", "=", "None", ",", "rng", "=", "None", ",", "periodic", "=", "False", ",", "beta_max", "=", "1e4", ",", "dL_max", "=", "0.02", ",", "dr_max", "=", "0.02", ")", ":", "if", "pf", "is", "not", "None", ":", "if", "pf", "==", "0.0", ":", "return", "np", ".", "array", "(", "[", "]", ")", ",", "R", "# If packing fraction is specified, find required number of spheres", "# and the actual packing fraction this will produce", "n", ",", "pf_actual", "=", "pf_to_n", "(", "L", ",", "pf", ",", "R", ")", "elif", "n", "is", "not", "None", ":", "if", "n", "==", "0", ":", "return", "np", ".", "array", "(", "[", "]", ")", ",", "R", "# If n is specified, find packing fraction", "pf_actual", "=", "n_to_pf", "(", "L", ",", "n", ",", "R", ")", "# Calculate an initial packing fraction and system size", "# Start at at most 0.5%; lower if the desired packing fraction is very low", "pf_initial", "=", "min", "(", "0.005", ",", "pf_actual", "/", "2.0", ")", "# Find system size that will create this packing fraction", "dim", "=", "L", ".", "shape", "[", "0", "]", "increase_initial_ratio", "=", "(", "pf_actual", "/", "pf_initial", ")", "**", "(", "1.0", "/", "dim", ")", "L_0", "=", "L", "*", "increase_initial_ratio", "# Pack naively into this system", "r_0", ",", "R", "=", "pack_simple", "(", "R", ",", "L_0", ",", "n", "=", "n", ",", "rng", "=", "rng", ",", "periodic", "=", "periodic", ")", "mg", "=", "metro_rcp_factory", "(", "periodic", ",", "r_0", ",", "L_0", ",", "R", ",", "dr_max", ",", "dL_max", ",", "rng", "=", "rng", ")", "print", "(", "'Initial packing done, Initial packing: {:g}'", ".", "format", "(", "mg", ".", "pf", ")", ")", "t", "=", "0", "while", "mg", ".", "pf", "<", "pf_actual", ":", "t", "+=", "1", "beta", "=", "beta_max", "*", "mg", ".", "pf", "mg", ".", "iterate", "(", "beta", ")", "if", "not", "t", "%", "every", ":", "print", "(", "'Packing: {:g}%'", ".", "format", "(", "100.0", "*", "mg", ".", "pf", ")", ")", "print", "(", "'Final packing: {:g}%'", ".", "format", "(", "100.0", "*", "mg", ".", "pf", ")", ")", "return", "mg", ".", "r", ",", "mg", ".", "R" ]
Pack a number of non-intersecting spheres into a periodic system. Can specify packing by number of spheres or packing fraction. This implementation uses the Metropolis-Hastings algorithm for an NPT system. Parameters ---------- R: float Sphere radius. L: float array, shape (d,) System lengths. pf: float or None Packing fraction n: integer or None Number of spheres. rng: RandomState or None Random number generator. If None, use inbuilt numpy state. periodic: bool Whether or not the system is periodic. Metropolis-Hastings parameters ------------------------------ Playing with these parameters may improve packing speed. beta_max: float, greater than zero. Inverse temperature which controls how little noiseis in the system. dL_max: float, 0 < dL_max < 1 Maximum fraction by which to perturb the system size. dr_max: float, 0 < dr_max < 1 Maximum system fraction by which to perturb sphere positions. Returns ------- r: float array, shape (n, d) Coordinates of the centres of the spheres for a valid configuration. R_actual: float Actual sphere radius used in the packing.
[ "Pack", "a", "number", "of", "non", "-", "intersecting", "spheres", "into", "a", "periodic", "system", "." ]
528b47d0f2f70f39e1490e41433f2da8c8b9d63c
https://github.com/eddiejessup/metropack/blob/528b47d0f2f70f39e1490e41433f2da8c8b9d63c/metropack/pack.py#L137-L218
245,658
delfick/gitmit
gitmit/mit.py
GitTimes.relpath_for
def relpath_for(self, path): """Find the relative path from here from the parent_dir""" if self.parent_dir in (".", ""): return path if path == self.parent_dir: return "" dirname = os.path.dirname(path) or "." basename = os.path.basename(path) cached = self.relpath_cache.get(dirname, empty) if cached is empty: cached = self.relpath_cache[dirname] = os.path.relpath(dirname, self.parent_dir) return os.path.join(cached, basename)
python
def relpath_for(self, path): """Find the relative path from here from the parent_dir""" if self.parent_dir in (".", ""): return path if path == self.parent_dir: return "" dirname = os.path.dirname(path) or "." basename = os.path.basename(path) cached = self.relpath_cache.get(dirname, empty) if cached is empty: cached = self.relpath_cache[dirname] = os.path.relpath(dirname, self.parent_dir) return os.path.join(cached, basename)
[ "def", "relpath_for", "(", "self", ",", "path", ")", ":", "if", "self", ".", "parent_dir", "in", "(", "\".\"", ",", "\"\"", ")", ":", "return", "path", "if", "path", "==", "self", ".", "parent_dir", ":", "return", "\"\"", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "or", "\".\"", "basename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "cached", "=", "self", ".", "relpath_cache", ".", "get", "(", "dirname", ",", "empty", ")", "if", "cached", "is", "empty", ":", "cached", "=", "self", ".", "relpath_cache", "[", "dirname", "]", "=", "os", ".", "path", ".", "relpath", "(", "dirname", ",", "self", ".", "parent_dir", ")", "return", "os", ".", "path", ".", "join", "(", "cached", ",", "basename", ")" ]
Find the relative path from here from the parent_dir
[ "Find", "the", "relative", "path", "from", "here", "from", "the", "parent_dir" ]
ae0aef14a06b25ad2811f8f47cc97e68a0910eae
https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/mit.py#L57-L72
245,659
delfick/gitmit
gitmit/mit.py
GitTimes.find
def find(self): """ Find all the files we want to find commit times for, and any extra files under symlinks. Then find the commit times for those files and return a dictionary of {relative_path: commit_time_as_epoch} """ mtimes = {} git = Repo(self.root_folder) all_files = git.all_files() use_files = set(self.find_files_for_use(all_files)) # the git index won't find the files under a symlink :( # And we include files under a symlink as seperate copies of the files # So we still want to generate modified times for those files extras = set(self.extra_symlinked_files(use_files)) # Combine use_files and extras use_files.update(extras) # Tell the user something if not self.silent: log.info("Finding modified times for %s/%s git controlled files in %s", len(use_files), len(all_files), self.root_folder) # Finally get the dates from git! return self.commit_times_for(git, use_files)
python
def find(self): """ Find all the files we want to find commit times for, and any extra files under symlinks. Then find the commit times for those files and return a dictionary of {relative_path: commit_time_as_epoch} """ mtimes = {} git = Repo(self.root_folder) all_files = git.all_files() use_files = set(self.find_files_for_use(all_files)) # the git index won't find the files under a symlink :( # And we include files under a symlink as seperate copies of the files # So we still want to generate modified times for those files extras = set(self.extra_symlinked_files(use_files)) # Combine use_files and extras use_files.update(extras) # Tell the user something if not self.silent: log.info("Finding modified times for %s/%s git controlled files in %s", len(use_files), len(all_files), self.root_folder) # Finally get the dates from git! return self.commit_times_for(git, use_files)
[ "def", "find", "(", "self", ")", ":", "mtimes", "=", "{", "}", "git", "=", "Repo", "(", "self", ".", "root_folder", ")", "all_files", "=", "git", ".", "all_files", "(", ")", "use_files", "=", "set", "(", "self", ".", "find_files_for_use", "(", "all_files", ")", ")", "# the git index won't find the files under a symlink :(", "# And we include files under a symlink as seperate copies of the files", "# So we still want to generate modified times for those files", "extras", "=", "set", "(", "self", ".", "extra_symlinked_files", "(", "use_files", ")", ")", "# Combine use_files and extras", "use_files", ".", "update", "(", "extras", ")", "# Tell the user something", "if", "not", "self", ".", "silent", ":", "log", ".", "info", "(", "\"Finding modified times for %s/%s git controlled files in %s\"", ",", "len", "(", "use_files", ")", ",", "len", "(", "all_files", ")", ",", "self", ".", "root_folder", ")", "# Finally get the dates from git!", "return", "self", ".", "commit_times_for", "(", "git", ",", "use_files", ")" ]
Find all the files we want to find commit times for, and any extra files under symlinks. Then find the commit times for those files and return a dictionary of {relative_path: commit_time_as_epoch}
[ "Find", "all", "the", "files", "we", "want", "to", "find", "commit", "times", "for", "and", "any", "extra", "files", "under", "symlinks", "." ]
ae0aef14a06b25ad2811f8f47cc97e68a0910eae
https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/mit.py#L74-L101
245,660
delfick/gitmit
gitmit/mit.py
GitTimes.commit_times_for
def commit_times_for(self, git, use_files): """ Return commit times for the use_files specified. We will use a cache of commit times if self.with_cache is Truthy. Finally, we yield (relpath: epoch) pairs where path is relative to self.parent_dir and epoch is the commit time in UTC for that path. """ # Use real_relpath if it exists (SymlinkdPath) and default to just the path # This is because we _want_ to compare the commits to the _real paths_ # As git only cares about the symlink itself, rather than files under it # We also want to make sure that the symlink targets are included in use_files # If they've been excluded by the filters use_files_paths = set([getattr(p, "real_relpath", p.path) for p in use_files if p.relpath]) # Find us the first commit to consider first_commit = str(git.first_commit) # Try and get our cached commit times # If we get a commit then it means we have a match for this parent/sorted_relpaths commit_times = {} cached_commit, cached_commit_times = None, {} if self.with_cache: sorted_relpaths = sorted([p.relpath for p in use_files]) cached_commit, cached_commit_times = get_cached_commit_times(self.root_folder, self.parent_dir, sorted_relpaths) if cached_commit == first_commit: commit_times = cached_commit_times # If we couldn't find cached commit times, we have to do some work if not commit_times: for commit_id, commit_time, different_paths in git.file_commit_times(use_files_paths, debug=self.debug): for path in different_paths: commit_times[path] = commit_time if self.with_cache: set_cached_commit_times(self.root_folder, self.parent_dir, first_commit, commit_times, sorted_relpaths) # Finally, yield the (relpath, commit_time) for all the files we care about. for key in use_files: if key.relpath: path = getattr(key, "real_relpath", key.path) relpath = getattr(key, "real_relpath", key.relpath) if path in commit_times: yield key.relpath, commit_times[path] else: log.warning("Couldn't find commit time for {0}".format(relpath))
python
def commit_times_for(self, git, use_files): """ Return commit times for the use_files specified. We will use a cache of commit times if self.with_cache is Truthy. Finally, we yield (relpath: epoch) pairs where path is relative to self.parent_dir and epoch is the commit time in UTC for that path. """ # Use real_relpath if it exists (SymlinkdPath) and default to just the path # This is because we _want_ to compare the commits to the _real paths_ # As git only cares about the symlink itself, rather than files under it # We also want to make sure that the symlink targets are included in use_files # If they've been excluded by the filters use_files_paths = set([getattr(p, "real_relpath", p.path) for p in use_files if p.relpath]) # Find us the first commit to consider first_commit = str(git.first_commit) # Try and get our cached commit times # If we get a commit then it means we have a match for this parent/sorted_relpaths commit_times = {} cached_commit, cached_commit_times = None, {} if self.with_cache: sorted_relpaths = sorted([p.relpath for p in use_files]) cached_commit, cached_commit_times = get_cached_commit_times(self.root_folder, self.parent_dir, sorted_relpaths) if cached_commit == first_commit: commit_times = cached_commit_times # If we couldn't find cached commit times, we have to do some work if not commit_times: for commit_id, commit_time, different_paths in git.file_commit_times(use_files_paths, debug=self.debug): for path in different_paths: commit_times[path] = commit_time if self.with_cache: set_cached_commit_times(self.root_folder, self.parent_dir, first_commit, commit_times, sorted_relpaths) # Finally, yield the (relpath, commit_time) for all the files we care about. for key in use_files: if key.relpath: path = getattr(key, "real_relpath", key.path) relpath = getattr(key, "real_relpath", key.relpath) if path in commit_times: yield key.relpath, commit_times[path] else: log.warning("Couldn't find commit time for {0}".format(relpath))
[ "def", "commit_times_for", "(", "self", ",", "git", ",", "use_files", ")", ":", "# Use real_relpath if it exists (SymlinkdPath) and default to just the path", "# This is because we _want_ to compare the commits to the _real paths_", "# As git only cares about the symlink itself, rather than files under it", "# We also want to make sure that the symlink targets are included in use_files", "# If they've been excluded by the filters", "use_files_paths", "=", "set", "(", "[", "getattr", "(", "p", ",", "\"real_relpath\"", ",", "p", ".", "path", ")", "for", "p", "in", "use_files", "if", "p", ".", "relpath", "]", ")", "# Find us the first commit to consider", "first_commit", "=", "str", "(", "git", ".", "first_commit", ")", "# Try and get our cached commit times", "# If we get a commit then it means we have a match for this parent/sorted_relpaths", "commit_times", "=", "{", "}", "cached_commit", ",", "cached_commit_times", "=", "None", ",", "{", "}", "if", "self", ".", "with_cache", ":", "sorted_relpaths", "=", "sorted", "(", "[", "p", ".", "relpath", "for", "p", "in", "use_files", "]", ")", "cached_commit", ",", "cached_commit_times", "=", "get_cached_commit_times", "(", "self", ".", "root_folder", ",", "self", ".", "parent_dir", ",", "sorted_relpaths", ")", "if", "cached_commit", "==", "first_commit", ":", "commit_times", "=", "cached_commit_times", "# If we couldn't find cached commit times, we have to do some work", "if", "not", "commit_times", ":", "for", "commit_id", ",", "commit_time", ",", "different_paths", "in", "git", ".", "file_commit_times", "(", "use_files_paths", ",", "debug", "=", "self", ".", "debug", ")", ":", "for", "path", "in", "different_paths", ":", "commit_times", "[", "path", "]", "=", "commit_time", "if", "self", ".", "with_cache", ":", "set_cached_commit_times", "(", "self", ".", "root_folder", ",", "self", ".", "parent_dir", ",", "first_commit", ",", "commit_times", ",", "sorted_relpaths", ")", "# Finally, yield the (relpath, commit_time) for all the files we care about.", "for", "key", "in", "use_files", ":", "if", "key", ".", "relpath", ":", "path", "=", "getattr", "(", "key", ",", "\"real_relpath\"", ",", "key", ".", "path", ")", "relpath", "=", "getattr", "(", "key", ",", "\"real_relpath\"", ",", "key", ".", "relpath", ")", "if", "path", "in", "commit_times", ":", "yield", "key", ".", "relpath", ",", "commit_times", "[", "path", "]", "else", ":", "log", ".", "warning", "(", "\"Couldn't find commit time for {0}\"", ".", "format", "(", "relpath", ")", ")" ]
Return commit times for the use_files specified. We will use a cache of commit times if self.with_cache is Truthy. Finally, we yield (relpath: epoch) pairs where path is relative to self.parent_dir and epoch is the commit time in UTC for that path.
[ "Return", "commit", "times", "for", "the", "use_files", "specified", "." ]
ae0aef14a06b25ad2811f8f47cc97e68a0910eae
https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/mit.py#L103-L150
245,661
delfick/gitmit
gitmit/mit.py
GitTimes.extra_symlinked_files
def extra_symlinked_files(self, potential_symlinks): """ Find any symlinkd folders and yield SymlinkdPath objects for each file that is found under the symlink. """ for key in list(potential_symlinks): location = os.path.join(self.root_folder, key.path) real_location = os.path.realpath(location) if os.path.islink(location) and os.path.isdir(real_location): for root, dirs, files in os.walk(real_location, followlinks=True): for name in files: # So this is joining the name of the symlink # With the name of the file, relative to the real location of the symlink full_path = os.path.join(root, name) rel_location = os.path.relpath(full_path, real_location) symlinkd_path = os.path.join(key.path, rel_location) # We then get that relative to the parent dir dir_part = os.path.relpath(root, real_location) symlinkd_relpath = os.path.normpath(os.path.join(key.relpath, dir_part, name)) # And we need the original file location so we can get a commit time for the symlinkd path real_path = os.path.realpath(full_path) real_root_folder = os.path.realpath(self.root_folder) real_relpath = os.path.relpath(real_path, real_root_folder) # So that's path relative to root_folder, path relative to parent_folder # and path relative to root for the target yield SymlinkdPath(symlinkd_path, symlinkd_relpath, real_relpath)
python
def extra_symlinked_files(self, potential_symlinks): """ Find any symlinkd folders and yield SymlinkdPath objects for each file that is found under the symlink. """ for key in list(potential_symlinks): location = os.path.join(self.root_folder, key.path) real_location = os.path.realpath(location) if os.path.islink(location) and os.path.isdir(real_location): for root, dirs, files in os.walk(real_location, followlinks=True): for name in files: # So this is joining the name of the symlink # With the name of the file, relative to the real location of the symlink full_path = os.path.join(root, name) rel_location = os.path.relpath(full_path, real_location) symlinkd_path = os.path.join(key.path, rel_location) # We then get that relative to the parent dir dir_part = os.path.relpath(root, real_location) symlinkd_relpath = os.path.normpath(os.path.join(key.relpath, dir_part, name)) # And we need the original file location so we can get a commit time for the symlinkd path real_path = os.path.realpath(full_path) real_root_folder = os.path.realpath(self.root_folder) real_relpath = os.path.relpath(real_path, real_root_folder) # So that's path relative to root_folder, path relative to parent_folder # and path relative to root for the target yield SymlinkdPath(symlinkd_path, symlinkd_relpath, real_relpath)
[ "def", "extra_symlinked_files", "(", "self", ",", "potential_symlinks", ")", ":", "for", "key", "in", "list", "(", "potential_symlinks", ")", ":", "location", "=", "os", ".", "path", ".", "join", "(", "self", ".", "root_folder", ",", "key", ".", "path", ")", "real_location", "=", "os", ".", "path", ".", "realpath", "(", "location", ")", "if", "os", ".", "path", ".", "islink", "(", "location", ")", "and", "os", ".", "path", ".", "isdir", "(", "real_location", ")", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "real_location", ",", "followlinks", "=", "True", ")", ":", "for", "name", "in", "files", ":", "# So this is joining the name of the symlink", "# With the name of the file, relative to the real location of the symlink", "full_path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "name", ")", "rel_location", "=", "os", ".", "path", ".", "relpath", "(", "full_path", ",", "real_location", ")", "symlinkd_path", "=", "os", ".", "path", ".", "join", "(", "key", ".", "path", ",", "rel_location", ")", "# We then get that relative to the parent dir", "dir_part", "=", "os", ".", "path", ".", "relpath", "(", "root", ",", "real_location", ")", "symlinkd_relpath", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "key", ".", "relpath", ",", "dir_part", ",", "name", ")", ")", "# And we need the original file location so we can get a commit time for the symlinkd path", "real_path", "=", "os", ".", "path", ".", "realpath", "(", "full_path", ")", "real_root_folder", "=", "os", ".", "path", ".", "realpath", "(", "self", ".", "root_folder", ")", "real_relpath", "=", "os", ".", "path", ".", "relpath", "(", "real_path", ",", "real_root_folder", ")", "# So that's path relative to root_folder, path relative to parent_folder", "# and path relative to root for the target", "yield", "SymlinkdPath", "(", "symlinkd_path", ",", "symlinkd_relpath", ",", "real_relpath", ")" ]
Find any symlinkd folders and yield SymlinkdPath objects for each file that is found under the symlink.
[ "Find", "any", "symlinkd", "folders", "and", "yield", "SymlinkdPath", "objects", "for", "each", "file", "that", "is", "found", "under", "the", "symlink", "." ]
ae0aef14a06b25ad2811f8f47cc97e68a0910eae
https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/mit.py#L152-L181
245,662
delfick/gitmit
gitmit/mit.py
GitTimes.find_files_for_use
def find_files_for_use(self, all_files): """ Given a list of all the files to consider, only yield Path objects for those we care about, given our filters """ for path in all_files: # Find the path relative to the parent dir relpath = self.relpath_for(path) # Don't care about the ./ if relpath.startswith("./"): relpath = relpath[2:] # Only care about paths that aren't filtered if not self.is_filtered(relpath): yield Path(path, relpath)
python
def find_files_for_use(self, all_files): """ Given a list of all the files to consider, only yield Path objects for those we care about, given our filters """ for path in all_files: # Find the path relative to the parent dir relpath = self.relpath_for(path) # Don't care about the ./ if relpath.startswith("./"): relpath = relpath[2:] # Only care about paths that aren't filtered if not self.is_filtered(relpath): yield Path(path, relpath)
[ "def", "find_files_for_use", "(", "self", ",", "all_files", ")", ":", "for", "path", "in", "all_files", ":", "# Find the path relative to the parent dir", "relpath", "=", "self", ".", "relpath_for", "(", "path", ")", "# Don't care about the ./", "if", "relpath", ".", "startswith", "(", "\"./\"", ")", ":", "relpath", "=", "relpath", "[", "2", ":", "]", "# Only care about paths that aren't filtered", "if", "not", "self", ".", "is_filtered", "(", "relpath", ")", ":", "yield", "Path", "(", "path", ",", "relpath", ")" ]
Given a list of all the files to consider, only yield Path objects for those we care about, given our filters
[ "Given", "a", "list", "of", "all", "the", "files", "to", "consider", "only", "yield", "Path", "objects", "for", "those", "we", "care", "about", "given", "our", "filters" ]
ae0aef14a06b25ad2811f8f47cc97e68a0910eae
https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/mit.py#L183-L198
245,663
delfick/gitmit
gitmit/mit.py
GitTimes.is_filtered
def is_filtered(self, relpath): """Say whether this relpath is filtered out""" # Only include files under the parent_dir if relpath.startswith("../"): return True # Ignore files that we don't want timestamps from if self.timestamps_for is not None and type(self.timestamps_for) is list: match = False for line in self.timestamps_for: if fnmatch.fnmatch(relpath, line): match = True break if not match: return True # Matched is true by default if # * Have exclude # * No exclude and no include matched = self.exclude or not any([self.exclude, self.include]) # Anything not matching exclude gets included if self.exclude: for line in self.exclude: if fnmatch.fnmatch(relpath, line): matched = False # Anything matching include gets included if self.include: for line in self.include: if fnmatch.fnmatch(relpath, line): matched = True break return not matched
python
def is_filtered(self, relpath): """Say whether this relpath is filtered out""" # Only include files under the parent_dir if relpath.startswith("../"): return True # Ignore files that we don't want timestamps from if self.timestamps_for is not None and type(self.timestamps_for) is list: match = False for line in self.timestamps_for: if fnmatch.fnmatch(relpath, line): match = True break if not match: return True # Matched is true by default if # * Have exclude # * No exclude and no include matched = self.exclude or not any([self.exclude, self.include]) # Anything not matching exclude gets included if self.exclude: for line in self.exclude: if fnmatch.fnmatch(relpath, line): matched = False # Anything matching include gets included if self.include: for line in self.include: if fnmatch.fnmatch(relpath, line): matched = True break return not matched
[ "def", "is_filtered", "(", "self", ",", "relpath", ")", ":", "# Only include files under the parent_dir", "if", "relpath", ".", "startswith", "(", "\"../\"", ")", ":", "return", "True", "# Ignore files that we don't want timestamps from", "if", "self", ".", "timestamps_for", "is", "not", "None", "and", "type", "(", "self", ".", "timestamps_for", ")", "is", "list", ":", "match", "=", "False", "for", "line", "in", "self", ".", "timestamps_for", ":", "if", "fnmatch", ".", "fnmatch", "(", "relpath", ",", "line", ")", ":", "match", "=", "True", "break", "if", "not", "match", ":", "return", "True", "# Matched is true by default if", "# * Have exclude", "# * No exclude and no include", "matched", "=", "self", ".", "exclude", "or", "not", "any", "(", "[", "self", ".", "exclude", ",", "self", ".", "include", "]", ")", "# Anything not matching exclude gets included", "if", "self", ".", "exclude", ":", "for", "line", "in", "self", ".", "exclude", ":", "if", "fnmatch", ".", "fnmatch", "(", "relpath", ",", "line", ")", ":", "matched", "=", "False", "# Anything matching include gets included", "if", "self", ".", "include", ":", "for", "line", "in", "self", ".", "include", ":", "if", "fnmatch", ".", "fnmatch", "(", "relpath", ",", "line", ")", ":", "matched", "=", "True", "break", "return", "not", "matched" ]
Say whether this relpath is filtered out
[ "Say", "whether", "this", "relpath", "is", "filtered", "out" ]
ae0aef14a06b25ad2811f8f47cc97e68a0910eae
https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/mit.py#L200-L234
245,664
bertrandvidal/parse_this
parse_this/core.py
_get_args_and_defaults
def _get_args_and_defaults(args, defaults): """Return a list of 2-tuples - the argument name and its default value or a special value that indicates there is no default value. Args: args: list of argument name defaults: tuple of default values """ defaults = defaults or [] args_and_defaults = [(argument, default) for (argument, default) in zip_longest(args[::-1], defaults[::-1], fillvalue=NoDefault)] return args_and_defaults[::-1]
python
def _get_args_and_defaults(args, defaults): """Return a list of 2-tuples - the argument name and its default value or a special value that indicates there is no default value. Args: args: list of argument name defaults: tuple of default values """ defaults = defaults or [] args_and_defaults = [(argument, default) for (argument, default) in zip_longest(args[::-1], defaults[::-1], fillvalue=NoDefault)] return args_and_defaults[::-1]
[ "def", "_get_args_and_defaults", "(", "args", ",", "defaults", ")", ":", "defaults", "=", "defaults", "or", "[", "]", "args_and_defaults", "=", "[", "(", "argument", ",", "default", ")", "for", "(", "argument", ",", "default", ")", "in", "zip_longest", "(", "args", "[", ":", ":", "-", "1", "]", ",", "defaults", "[", ":", ":", "-", "1", "]", ",", "fillvalue", "=", "NoDefault", ")", "]", "return", "args_and_defaults", "[", ":", ":", "-", "1", "]" ]
Return a list of 2-tuples - the argument name and its default value or a special value that indicates there is no default value. Args: args: list of argument name defaults: tuple of default values
[ "Return", "a", "list", "of", "2", "-", "tuples", "-", "the", "argument", "name", "and", "its", "default", "value", "or", "a", "special", "value", "that", "indicates", "there", "is", "no", "default", "value", "." ]
aa2e3737f19642300ef1ca65cae21c90049718a2
https://github.com/bertrandvidal/parse_this/blob/aa2e3737f19642300ef1ca65cae21c90049718a2/parse_this/core.py#L51-L63
245,665
bertrandvidal/parse_this
parse_this/core.py
_prepare_doc
def _prepare_doc(func, args, delimiter_chars): """From the function docstring get the arg parse description and arguments help message. If there is no docstring simple description and help message are created. Args: func: the function that needs argument parsing args: name of the function arguments delimiter_chars: characters used to separate the parameters from their help message in the docstring Returns: A tuple containing the description to be used in the argument parser and a dict indexed on the callable argument name and their associated help message """ _LOG.debug("Preparing doc for '%s'", func.__name__) if not func.__doc__: return _get_default_help_message(func, args) description = [] args_help = {} fill_description = True arg_name = None arg_doc_regex = re.compile("\b*(?P<arg_name>\w+)\s*%s\s*(?P<help_msg>.+)" % delimiter_chars) for line in func.__doc__.splitlines(): line = line.strip() if line and fill_description: description.append(line) elif line: arg_match = arg_doc_regex.match(line) try: arg_name = arg_match.groupdict()["arg_name"].strip() args_help[arg_name] = arg_match.groupdict()["help_msg"].strip() except AttributeError: # The line didn't match the pattern we've hit a # multiline argument docstring so we add it to the # previous argument help message if arg_name is not None: args_help[arg_name] = " ".join([args_help[arg_name], line]) else: # The first empty line we encountered means we are done with # the description. The first empty line we encounter after # filling the argument help means we are done with argument # parsing. if not fill_description and args_help: break fill_description = False return _get_default_help_message(func, args, " ".join(description), args_help)
python
def _prepare_doc(func, args, delimiter_chars): """From the function docstring get the arg parse description and arguments help message. If there is no docstring simple description and help message are created. Args: func: the function that needs argument parsing args: name of the function arguments delimiter_chars: characters used to separate the parameters from their help message in the docstring Returns: A tuple containing the description to be used in the argument parser and a dict indexed on the callable argument name and their associated help message """ _LOG.debug("Preparing doc for '%s'", func.__name__) if not func.__doc__: return _get_default_help_message(func, args) description = [] args_help = {} fill_description = True arg_name = None arg_doc_regex = re.compile("\b*(?P<arg_name>\w+)\s*%s\s*(?P<help_msg>.+)" % delimiter_chars) for line in func.__doc__.splitlines(): line = line.strip() if line and fill_description: description.append(line) elif line: arg_match = arg_doc_regex.match(line) try: arg_name = arg_match.groupdict()["arg_name"].strip() args_help[arg_name] = arg_match.groupdict()["help_msg"].strip() except AttributeError: # The line didn't match the pattern we've hit a # multiline argument docstring so we add it to the # previous argument help message if arg_name is not None: args_help[arg_name] = " ".join([args_help[arg_name], line]) else: # The first empty line we encountered means we are done with # the description. The first empty line we encounter after # filling the argument help means we are done with argument # parsing. if not fill_description and args_help: break fill_description = False return _get_default_help_message(func, args, " ".join(description), args_help)
[ "def", "_prepare_doc", "(", "func", ",", "args", ",", "delimiter_chars", ")", ":", "_LOG", ".", "debug", "(", "\"Preparing doc for '%s'\"", ",", "func", ".", "__name__", ")", "if", "not", "func", ".", "__doc__", ":", "return", "_get_default_help_message", "(", "func", ",", "args", ")", "description", "=", "[", "]", "args_help", "=", "{", "}", "fill_description", "=", "True", "arg_name", "=", "None", "arg_doc_regex", "=", "re", ".", "compile", "(", "\"\\b*(?P<arg_name>\\w+)\\s*%s\\s*(?P<help_msg>.+)\"", "%", "delimiter_chars", ")", "for", "line", "in", "func", ".", "__doc__", ".", "splitlines", "(", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", "and", "fill_description", ":", "description", ".", "append", "(", "line", ")", "elif", "line", ":", "arg_match", "=", "arg_doc_regex", ".", "match", "(", "line", ")", "try", ":", "arg_name", "=", "arg_match", ".", "groupdict", "(", ")", "[", "\"arg_name\"", "]", ".", "strip", "(", ")", "args_help", "[", "arg_name", "]", "=", "arg_match", ".", "groupdict", "(", ")", "[", "\"help_msg\"", "]", ".", "strip", "(", ")", "except", "AttributeError", ":", "# The line didn't match the pattern we've hit a", "# multiline argument docstring so we add it to the", "# previous argument help message", "if", "arg_name", "is", "not", "None", ":", "args_help", "[", "arg_name", "]", "=", "\" \"", ".", "join", "(", "[", "args_help", "[", "arg_name", "]", ",", "line", "]", ")", "else", ":", "# The first empty line we encountered means we are done with", "# the description. The first empty line we encounter after", "# filling the argument help means we are done with argument", "# parsing.", "if", "not", "fill_description", "and", "args_help", ":", "break", "fill_description", "=", "False", "return", "_get_default_help_message", "(", "func", ",", "args", ",", "\" \"", ".", "join", "(", "description", ")", ",", "args_help", ")" ]
From the function docstring get the arg parse description and arguments help message. If there is no docstring simple description and help message are created. Args: func: the function that needs argument parsing args: name of the function arguments delimiter_chars: characters used to separate the parameters from their help message in the docstring Returns: A tuple containing the description to be used in the argument parser and a dict indexed on the callable argument name and their associated help message
[ "From", "the", "function", "docstring", "get", "the", "arg", "parse", "description", "and", "arguments", "help", "message", ".", "If", "there", "is", "no", "docstring", "simple", "description", "and", "help", "message", "are", "created", "." ]
aa2e3737f19642300ef1ca65cae21c90049718a2
https://github.com/bertrandvidal/parse_this/blob/aa2e3737f19642300ef1ca65cae21c90049718a2/parse_this/core.py#L66-L115
245,666
bertrandvidal/parse_this
parse_this/core.py
_get_default_help_message
def _get_default_help_message(func, args, description=None, args_help=None): """Create a default description for the parser and help message for the agurments if they are missing. Args: func: the method we are creating a parser for args: the argument names of the method description: a potentially existing description created from the function docstring args_help: a dict {arg_name: help} with potentially missing arguments Returns: a tuple (arg_parse_description, complete_args_help) """ if description is None: description = "Argument parsing for %s" % func.__name__ args_help = args_help or {} # If an argument is missing a help message we create a simple one for argument in [arg_name for arg_name in args if arg_name not in args_help]: args_help[argument] = "Help message for %s" % argument return (description, args_help)
python
def _get_default_help_message(func, args, description=None, args_help=None): """Create a default description for the parser and help message for the agurments if they are missing. Args: func: the method we are creating a parser for args: the argument names of the method description: a potentially existing description created from the function docstring args_help: a dict {arg_name: help} with potentially missing arguments Returns: a tuple (arg_parse_description, complete_args_help) """ if description is None: description = "Argument parsing for %s" % func.__name__ args_help = args_help or {} # If an argument is missing a help message we create a simple one for argument in [arg_name for arg_name in args if arg_name not in args_help]: args_help[argument] = "Help message for %s" % argument return (description, args_help)
[ "def", "_get_default_help_message", "(", "func", ",", "args", ",", "description", "=", "None", ",", "args_help", "=", "None", ")", ":", "if", "description", "is", "None", ":", "description", "=", "\"Argument parsing for %s\"", "%", "func", ".", "__name__", "args_help", "=", "args_help", "or", "{", "}", "# If an argument is missing a help message we create a simple one", "for", "argument", "in", "[", "arg_name", "for", "arg_name", "in", "args", "if", "arg_name", "not", "in", "args_help", "]", ":", "args_help", "[", "argument", "]", "=", "\"Help message for %s\"", "%", "argument", "return", "(", "description", ",", "args_help", ")" ]
Create a default description for the parser and help message for the agurments if they are missing. Args: func: the method we are creating a parser for args: the argument names of the method description: a potentially existing description created from the function docstring args_help: a dict {arg_name: help} with potentially missing arguments Returns: a tuple (arg_parse_description, complete_args_help)
[ "Create", "a", "default", "description", "for", "the", "parser", "and", "help", "message", "for", "the", "agurments", "if", "they", "are", "missing", "." ]
aa2e3737f19642300ef1ca65cae21c90049718a2
https://github.com/bertrandvidal/parse_this/blob/aa2e3737f19642300ef1ca65cae21c90049718a2/parse_this/core.py#L151-L172
245,667
bertrandvidal/parse_this
parse_this/core.py
_get_arg_parser
def _get_arg_parser(func, types, args_and_defaults, delimiter_chars): """Return an ArgumentParser for the given function. Arguments are defined from the function arguments and their associated defaults. Args: func: function for which we want an ArgumentParser types: types to which the command line arguments should be converted to args_and_defaults: list of 2-tuples (arg_name, arg_default) delimiter_chars: characters used to separate the parameters from their help message in the docstring """ _LOG.debug("Creating ArgumentParser for '%s'", func.__name__) (description, arg_help) = _prepare_doc( func, [x for (x, _) in args_and_defaults], delimiter_chars) parser = argparse.ArgumentParser(description=description) for ((arg, default), arg_type) in zip_longest(args_and_defaults, types): help_msg = arg_help[arg] if default is NoDefault: arg_type = arg_type or identity_type if arg_type == bool: _LOG.debug("Adding optional flag %s.%s", func.__name__, arg) parser.add_argument("--%s" % arg, default=True, required=False, action="store_false", help="%s. Defaults to True if not specified" % help_msg) else: _LOG.debug("Adding positional argument %s.%s", func.__name__, arg) parser.add_argument(arg, help=help_msg, type=arg_type) else: if default is None and arg_type is None: raise ParseThisError("To use default value of 'None' you need " "to specify the type of the argument '{}' " "for the method '{}'" .format(arg, func.__name__)) arg_type = arg_type or type(default) if arg_type == bool: action = "store_false" if default else "store_true" _LOG.debug("Adding optional flag %s.%s", func.__name__, arg) parser.add_argument("--%s" % arg, help=help_msg, default=default, action=action) else: _LOG.debug( "Adding optional argument %s.%s", func.__name__, arg) parser.add_argument("--%s" % arg, help=help_msg, default=default, type=arg_type) return parser
python
def _get_arg_parser(func, types, args_and_defaults, delimiter_chars): """Return an ArgumentParser for the given function. Arguments are defined from the function arguments and their associated defaults. Args: func: function for which we want an ArgumentParser types: types to which the command line arguments should be converted to args_and_defaults: list of 2-tuples (arg_name, arg_default) delimiter_chars: characters used to separate the parameters from their help message in the docstring """ _LOG.debug("Creating ArgumentParser for '%s'", func.__name__) (description, arg_help) = _prepare_doc( func, [x for (x, _) in args_and_defaults], delimiter_chars) parser = argparse.ArgumentParser(description=description) for ((arg, default), arg_type) in zip_longest(args_and_defaults, types): help_msg = arg_help[arg] if default is NoDefault: arg_type = arg_type or identity_type if arg_type == bool: _LOG.debug("Adding optional flag %s.%s", func.__name__, arg) parser.add_argument("--%s" % arg, default=True, required=False, action="store_false", help="%s. Defaults to True if not specified" % help_msg) else: _LOG.debug("Adding positional argument %s.%s", func.__name__, arg) parser.add_argument(arg, help=help_msg, type=arg_type) else: if default is None and arg_type is None: raise ParseThisError("To use default value of 'None' you need " "to specify the type of the argument '{}' " "for the method '{}'" .format(arg, func.__name__)) arg_type = arg_type or type(default) if arg_type == bool: action = "store_false" if default else "store_true" _LOG.debug("Adding optional flag %s.%s", func.__name__, arg) parser.add_argument("--%s" % arg, help=help_msg, default=default, action=action) else: _LOG.debug( "Adding optional argument %s.%s", func.__name__, arg) parser.add_argument("--%s" % arg, help=help_msg, default=default, type=arg_type) return parser
[ "def", "_get_arg_parser", "(", "func", ",", "types", ",", "args_and_defaults", ",", "delimiter_chars", ")", ":", "_LOG", ".", "debug", "(", "\"Creating ArgumentParser for '%s'\"", ",", "func", ".", "__name__", ")", "(", "description", ",", "arg_help", ")", "=", "_prepare_doc", "(", "func", ",", "[", "x", "for", "(", "x", ",", "_", ")", "in", "args_and_defaults", "]", ",", "delimiter_chars", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "description", ")", "for", "(", "(", "arg", ",", "default", ")", ",", "arg_type", ")", "in", "zip_longest", "(", "args_and_defaults", ",", "types", ")", ":", "help_msg", "=", "arg_help", "[", "arg", "]", "if", "default", "is", "NoDefault", ":", "arg_type", "=", "arg_type", "or", "identity_type", "if", "arg_type", "==", "bool", ":", "_LOG", ".", "debug", "(", "\"Adding optional flag %s.%s\"", ",", "func", ".", "__name__", ",", "arg", ")", "parser", ".", "add_argument", "(", "\"--%s\"", "%", "arg", ",", "default", "=", "True", ",", "required", "=", "False", ",", "action", "=", "\"store_false\"", ",", "help", "=", "\"%s. Defaults to True if not specified\"", "%", "help_msg", ")", "else", ":", "_LOG", ".", "debug", "(", "\"Adding positional argument %s.%s\"", ",", "func", ".", "__name__", ",", "arg", ")", "parser", ".", "add_argument", "(", "arg", ",", "help", "=", "help_msg", ",", "type", "=", "arg_type", ")", "else", ":", "if", "default", "is", "None", "and", "arg_type", "is", "None", ":", "raise", "ParseThisError", "(", "\"To use default value of 'None' you need \"", "\"to specify the type of the argument '{}' \"", "\"for the method '{}'\"", ".", "format", "(", "arg", ",", "func", ".", "__name__", ")", ")", "arg_type", "=", "arg_type", "or", "type", "(", "default", ")", "if", "arg_type", "==", "bool", ":", "action", "=", "\"store_false\"", "if", "default", "else", "\"store_true\"", "_LOG", ".", "debug", "(", "\"Adding optional flag %s.%s\"", ",", "func", ".", "__name__", ",", "arg", ")", "parser", ".", "add_argument", "(", "\"--%s\"", "%", "arg", ",", "help", "=", "help_msg", ",", "default", "=", "default", ",", "action", "=", "action", ")", "else", ":", "_LOG", ".", "debug", "(", "\"Adding optional argument %s.%s\"", ",", "func", ".", "__name__", ",", "arg", ")", "parser", ".", "add_argument", "(", "\"--%s\"", "%", "arg", ",", "help", "=", "help_msg", ",", "default", "=", "default", ",", "type", "=", "arg_type", ")", "return", "parser" ]
Return an ArgumentParser for the given function. Arguments are defined from the function arguments and their associated defaults. Args: func: function for which we want an ArgumentParser types: types to which the command line arguments should be converted to args_and_defaults: list of 2-tuples (arg_name, arg_default) delimiter_chars: characters used to separate the parameters from their help message in the docstring
[ "Return", "an", "ArgumentParser", "for", "the", "given", "function", ".", "Arguments", "are", "defined", "from", "the", "function", "arguments", "and", "their", "associated", "defaults", "." ]
aa2e3737f19642300ef1ca65cae21c90049718a2
https://github.com/bertrandvidal/parse_this/blob/aa2e3737f19642300ef1ca65cae21c90049718a2/parse_this/core.py#L175-L221
245,668
bertrandvidal/parse_this
parse_this/core.py
_get_args_to_parse
def _get_args_to_parse(args, sys_argv): """Return the given arguments if it is not None else sys.argv if it contains something, an empty list otherwise. Args: args: argument to be parsed sys_argv: arguments of the command line i.e. sys.argv """ arguments = args if args is not None else sys_argv[1:] _LOG.debug("Parsing arguments: %s", arguments) return arguments
python
def _get_args_to_parse(args, sys_argv): """Return the given arguments if it is not None else sys.argv if it contains something, an empty list otherwise. Args: args: argument to be parsed sys_argv: arguments of the command line i.e. sys.argv """ arguments = args if args is not None else sys_argv[1:] _LOG.debug("Parsing arguments: %s", arguments) return arguments
[ "def", "_get_args_to_parse", "(", "args", ",", "sys_argv", ")", ":", "arguments", "=", "args", "if", "args", "is", "not", "None", "else", "sys_argv", "[", "1", ":", "]", "_LOG", ".", "debug", "(", "\"Parsing arguments: %s\"", ",", "arguments", ")", "return", "arguments" ]
Return the given arguments if it is not None else sys.argv if it contains something, an empty list otherwise. Args: args: argument to be parsed sys_argv: arguments of the command line i.e. sys.argv
[ "Return", "the", "given", "arguments", "if", "it", "is", "not", "None", "else", "sys", ".", "argv", "if", "it", "contains", "something", "an", "empty", "list", "otherwise", "." ]
aa2e3737f19642300ef1ca65cae21c90049718a2
https://github.com/bertrandvidal/parse_this/blob/aa2e3737f19642300ef1ca65cae21c90049718a2/parse_this/core.py#L224-L234
245,669
bertrandvidal/parse_this
parse_this/core.py
_get_parser_call_method
def _get_parser_call_method(func): """Returns the method that is linked to the 'call' method of the parser Args: func: the decorated function Raises: ParseThisError if the decorated method is __init__, __init__ can only be decorated in a class decorated by parse_class """ func_name = func.__name__ parser = func.parser def inner_call(instance=None, args=None): """This is method attached to <parser>.call. Args: instance: the instance of the parser args: arguments to be parsed """ _LOG.debug("Calling %s.parser.call", func_name) # Defer this check in the method call so that __init__ can be # decorated in class decorated with parse_class if func_name == "__init__": raise ParseThisError(("To use 'create_parser' on the" "'__init__' you need to decorate the " "class with '@parse_class'")) namespace = parser.parse_args(_get_args_to_parse(args, sys.argv)) if instance is None: # If instance is None we are probably decorating a function not a # method and don't need the instance args_name = _get_args_name_from_parser(parser) return _call(func, args_name, namespace) return _call_method_from_namespace(instance, func_name, namespace) return inner_call
python
def _get_parser_call_method(func): """Returns the method that is linked to the 'call' method of the parser Args: func: the decorated function Raises: ParseThisError if the decorated method is __init__, __init__ can only be decorated in a class decorated by parse_class """ func_name = func.__name__ parser = func.parser def inner_call(instance=None, args=None): """This is method attached to <parser>.call. Args: instance: the instance of the parser args: arguments to be parsed """ _LOG.debug("Calling %s.parser.call", func_name) # Defer this check in the method call so that __init__ can be # decorated in class decorated with parse_class if func_name == "__init__": raise ParseThisError(("To use 'create_parser' on the" "'__init__' you need to decorate the " "class with '@parse_class'")) namespace = parser.parse_args(_get_args_to_parse(args, sys.argv)) if instance is None: # If instance is None we are probably decorating a function not a # method and don't need the instance args_name = _get_args_name_from_parser(parser) return _call(func, args_name, namespace) return _call_method_from_namespace(instance, func_name, namespace) return inner_call
[ "def", "_get_parser_call_method", "(", "func", ")", ":", "func_name", "=", "func", ".", "__name__", "parser", "=", "func", ".", "parser", "def", "inner_call", "(", "instance", "=", "None", ",", "args", "=", "None", ")", ":", "\"\"\"This is method attached to <parser>.call.\n\n Args:\n instance: the instance of the parser\n args: arguments to be parsed\n \"\"\"", "_LOG", ".", "debug", "(", "\"Calling %s.parser.call\"", ",", "func_name", ")", "# Defer this check in the method call so that __init__ can be", "# decorated in class decorated with parse_class", "if", "func_name", "==", "\"__init__\"", ":", "raise", "ParseThisError", "(", "(", "\"To use 'create_parser' on the\"", "\"'__init__' you need to decorate the \"", "\"class with '@parse_class'\"", ")", ")", "namespace", "=", "parser", ".", "parse_args", "(", "_get_args_to_parse", "(", "args", ",", "sys", ".", "argv", ")", ")", "if", "instance", "is", "None", ":", "# If instance is None we are probably decorating a function not a", "# method and don't need the instance", "args_name", "=", "_get_args_name_from_parser", "(", "parser", ")", "return", "_call", "(", "func", ",", "args_name", ",", "namespace", ")", "return", "_call_method_from_namespace", "(", "instance", ",", "func_name", ",", "namespace", ")", "return", "inner_call" ]
Returns the method that is linked to the 'call' method of the parser Args: func: the decorated function Raises: ParseThisError if the decorated method is __init__, __init__ can only be decorated in a class decorated by parse_class
[ "Returns", "the", "method", "that", "is", "linked", "to", "the", "call", "method", "of", "the", "parser" ]
aa2e3737f19642300ef1ca65cae21c90049718a2
https://github.com/bertrandvidal/parse_this/blob/aa2e3737f19642300ef1ca65cae21c90049718a2/parse_this/core.py#L264-L299
245,670
bertrandvidal/parse_this
parse_this/core.py
_get_args_name_from_parser
def _get_args_name_from_parser(parser): """Retrieve the name of the function argument linked to the given parser. Args: parser: a function parser """ # Retrieve the 'action' destination of the method parser i.e. its # argument name. The HelpAction is ignored. return [action.dest for action in parser._actions if not isinstance(action, argparse._HelpAction)]
python
def _get_args_name_from_parser(parser): """Retrieve the name of the function argument linked to the given parser. Args: parser: a function parser """ # Retrieve the 'action' destination of the method parser i.e. its # argument name. The HelpAction is ignored. return [action.dest for action in parser._actions if not isinstance(action, argparse._HelpAction)]
[ "def", "_get_args_name_from_parser", "(", "parser", ")", ":", "# Retrieve the 'action' destination of the method parser i.e. its", "# argument name. The HelpAction is ignored.", "return", "[", "action", ".", "dest", "for", "action", "in", "parser", ".", "_actions", "if", "not", "isinstance", "(", "action", ",", "argparse", ".", "_HelpAction", ")", "]" ]
Retrieve the name of the function argument linked to the given parser. Args: parser: a function parser
[ "Retrieve", "the", "name", "of", "the", "function", "argument", "linked", "to", "the", "given", "parser", "." ]
aa2e3737f19642300ef1ca65cae21c90049718a2
https://github.com/bertrandvidal/parse_this/blob/aa2e3737f19642300ef1ca65cae21c90049718a2/parse_this/core.py#L302-L311
245,671
bertrandvidal/parse_this
parse_this/core.py
_call
def _call(callable_obj, arg_names, namespace): """Actually calls the callable with the namespace parsed from the command line. Args: callable_obj: a callable object arg_names: name of the function arguments namespace: the namespace object parsed from the command line """ arguments = {arg_name: getattr(namespace, arg_name) for arg_name in arg_names} return callable_obj(**arguments)
python
def _call(callable_obj, arg_names, namespace): """Actually calls the callable with the namespace parsed from the command line. Args: callable_obj: a callable object arg_names: name of the function arguments namespace: the namespace object parsed from the command line """ arguments = {arg_name: getattr(namespace, arg_name) for arg_name in arg_names} return callable_obj(**arguments)
[ "def", "_call", "(", "callable_obj", ",", "arg_names", ",", "namespace", ")", ":", "arguments", "=", "{", "arg_name", ":", "getattr", "(", "namespace", ",", "arg_name", ")", "for", "arg_name", "in", "arg_names", "}", "return", "callable_obj", "(", "*", "*", "arguments", ")" ]
Actually calls the callable with the namespace parsed from the command line. Args: callable_obj: a callable object arg_names: name of the function arguments namespace: the namespace object parsed from the command line
[ "Actually", "calls", "the", "callable", "with", "the", "namespace", "parsed", "from", "the", "command", "line", "." ]
aa2e3737f19642300ef1ca65cae21c90049718a2
https://github.com/bertrandvidal/parse_this/blob/aa2e3737f19642300ef1ca65cae21c90049718a2/parse_this/core.py#L314-L325
245,672
bertrandvidal/parse_this
parse_this/core.py
_call_method_from_namespace
def _call_method_from_namespace(obj, method_name, namespace): """Call the method, retrieved from obj, with the correct arguments via the namespace Args: obj: any kind of object method_name: method to be called namespace: an argparse.Namespace object containing parsed command line arguments """ method = getattr(obj, method_name) method_parser = method.parser arg_names = _get_args_name_from_parser(method_parser) if method_name == "__init__": return _call(obj, arg_names, namespace) return _call(method, arg_names, namespace)
python
def _call_method_from_namespace(obj, method_name, namespace): """Call the method, retrieved from obj, with the correct arguments via the namespace Args: obj: any kind of object method_name: method to be called namespace: an argparse.Namespace object containing parsed command line arguments """ method = getattr(obj, method_name) method_parser = method.parser arg_names = _get_args_name_from_parser(method_parser) if method_name == "__init__": return _call(obj, arg_names, namespace) return _call(method, arg_names, namespace)
[ "def", "_call_method_from_namespace", "(", "obj", ",", "method_name", ",", "namespace", ")", ":", "method", "=", "getattr", "(", "obj", ",", "method_name", ")", "method_parser", "=", "method", ".", "parser", "arg_names", "=", "_get_args_name_from_parser", "(", "method_parser", ")", "if", "method_name", "==", "\"__init__\"", ":", "return", "_call", "(", "obj", ",", "arg_names", ",", "namespace", ")", "return", "_call", "(", "method", ",", "arg_names", ",", "namespace", ")" ]
Call the method, retrieved from obj, with the correct arguments via the namespace Args: obj: any kind of object method_name: method to be called namespace: an argparse.Namespace object containing parsed command line arguments
[ "Call", "the", "method", "retrieved", "from", "obj", "with", "the", "correct", "arguments", "via", "the", "namespace" ]
aa2e3737f19642300ef1ca65cae21c90049718a2
https://github.com/bertrandvidal/parse_this/blob/aa2e3737f19642300ef1ca65cae21c90049718a2/parse_this/core.py#L328-L343
245,673
jtpaasch/simplygithub
simplygithub/internals/api.py
get_url
def get_url(profile, resource): """Get the URL for a resource. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. resource The part of a Github API URL that comes after ``.../:repo/git``. For instance, for ``.../:repo/git/commits``, it's ``/commits``. Returns: The full URL for the specified resource under the specified profile. """ repo = profile["repo"] url = GITHUB_API_BASE_URL + "repos/" + repo + "/git" + resource return url
python
def get_url(profile, resource): """Get the URL for a resource. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. resource The part of a Github API URL that comes after ``.../:repo/git``. For instance, for ``.../:repo/git/commits``, it's ``/commits``. Returns: The full URL for the specified resource under the specified profile. """ repo = profile["repo"] url = GITHUB_API_BASE_URL + "repos/" + repo + "/git" + resource return url
[ "def", "get_url", "(", "profile", ",", "resource", ")", ":", "repo", "=", "profile", "[", "\"repo\"", "]", "url", "=", "GITHUB_API_BASE_URL", "+", "\"repos/\"", "+", "repo", "+", "\"/git\"", "+", "resource", "return", "url" ]
Get the URL for a resource. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. resource The part of a Github API URL that comes after ``.../:repo/git``. For instance, for ``.../:repo/git/commits``, it's ``/commits``. Returns: The full URL for the specified resource under the specified profile.
[ "Get", "the", "URL", "for", "a", "resource", "." ]
b77506275ec276ce90879bf1ea9299a79448b903
https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/internals/api.py#L23-L43
245,674
jtpaasch/simplygithub
simplygithub/internals/api.py
post_merge_request
def post_merge_request(profile, payload): """Do a POST request to Github's API to merge. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. payload A dict of information to pass to Github's API as the payload for a merge request, something like this:: { "base": <base>, "head": <head>, "commit_message": <mesg>} Returns: The response returned by the ``requests`` library when it does the POST request. """ repo = profile["repo"] url = GITHUB_API_BASE_URL + "repos/" + repo + "/merges" headers = get_headers(profile) response = requests.post(url, json=payload, headers=headers) return response
python
def post_merge_request(profile, payload): """Do a POST request to Github's API to merge. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. payload A dict of information to pass to Github's API as the payload for a merge request, something like this:: { "base": <base>, "head": <head>, "commit_message": <mesg>} Returns: The response returned by the ``requests`` library when it does the POST request. """ repo = profile["repo"] url = GITHUB_API_BASE_URL + "repos/" + repo + "/merges" headers = get_headers(profile) response = requests.post(url, json=payload, headers=headers) return response
[ "def", "post_merge_request", "(", "profile", ",", "payload", ")", ":", "repo", "=", "profile", "[", "\"repo\"", "]", "url", "=", "GITHUB_API_BASE_URL", "+", "\"repos/\"", "+", "repo", "+", "\"/merges\"", "headers", "=", "get_headers", "(", "profile", ")", "response", "=", "requests", ".", "post", "(", "url", ",", "json", "=", "payload", ",", "headers", "=", "headers", ")", "return", "response" ]
Do a POST request to Github's API to merge. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. payload A dict of information to pass to Github's API as the payload for a merge request, something like this:: { "base": <base>, "head": <head>, "commit_message": <mesg>} Returns: The response returned by the ``requests`` library when it does the POST request.
[ "Do", "a", "POST", "request", "to", "Github", "s", "API", "to", "merge", "." ]
b77506275ec276ce90879bf1ea9299a79448b903
https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/internals/api.py#L46-L71
245,675
jtpaasch/simplygithub
simplygithub/internals/api.py
get_request
def get_request(profile, resource): """Do a GET request to Github's API. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. resource The part of a Github API URL that comes after ``.../:repo/git``. For instance, for ``.../:repo/git/commits``, it's ``/commits``. Returns: The body of the response, converted from JSON into a Python dict. """ url = get_url(profile, resource) headers = get_headers(profile) response = requests.get(url, headers=headers) return response.json()
python
def get_request(profile, resource): """Do a GET request to Github's API. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. resource The part of a Github API URL that comes after ``.../:repo/git``. For instance, for ``.../:repo/git/commits``, it's ``/commits``. Returns: The body of the response, converted from JSON into a Python dict. """ url = get_url(profile, resource) headers = get_headers(profile) response = requests.get(url, headers=headers) return response.json()
[ "def", "get_request", "(", "profile", ",", "resource", ")", ":", "url", "=", "get_url", "(", "profile", ",", "resource", ")", "headers", "=", "get_headers", "(", "profile", ")", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "headers", ")", "return", "response", ".", "json", "(", ")" ]
Do a GET request to Github's API. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. resource The part of a Github API URL that comes after ``.../:repo/git``. For instance, for ``.../:repo/git/commits``, it's ``/commits``. Returns: The body of the response, converted from JSON into a Python dict.
[ "Do", "a", "GET", "request", "to", "Github", "s", "API", "." ]
b77506275ec276ce90879bf1ea9299a79448b903
https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/internals/api.py#L95-L116
245,676
jtpaasch/simplygithub
simplygithub/internals/api.py
post_request
def post_request(profile, resource, payload): """Do a POST request to Github's API. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. resource The part of a Github API URL that comes after ``.../:repo/git``. For instance, for ``.../:repo/git/commits``, it's ``/commits``. payload A dict of values to send as the payload of the POST request. The data will be JSON-encoded. Returns: The body of the response, converted from JSON into a Python dict. """ url = get_url(profile, resource) headers = get_headers(profile) response = requests.post(url, json=payload, headers=headers) return response.json()
python
def post_request(profile, resource, payload): """Do a POST request to Github's API. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. resource The part of a Github API URL that comes after ``.../:repo/git``. For instance, for ``.../:repo/git/commits``, it's ``/commits``. payload A dict of values to send as the payload of the POST request. The data will be JSON-encoded. Returns: The body of the response, converted from JSON into a Python dict. """ url = get_url(profile, resource) headers = get_headers(profile) response = requests.post(url, json=payload, headers=headers) return response.json()
[ "def", "post_request", "(", "profile", ",", "resource", ",", "payload", ")", ":", "url", "=", "get_url", "(", "profile", ",", "resource", ")", "headers", "=", "get_headers", "(", "profile", ")", "response", "=", "requests", ".", "post", "(", "url", ",", "json", "=", "payload", ",", "headers", "=", "headers", ")", "return", "response", ".", "json", "(", ")" ]
Do a POST request to Github's API. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. resource The part of a Github API URL that comes after ``.../:repo/git``. For instance, for ``.../:repo/git/commits``, it's ``/commits``. payload A dict of values to send as the payload of the POST request. The data will be JSON-encoded. Returns: The body of the response, converted from JSON into a Python dict.
[ "Do", "a", "POST", "request", "to", "Github", "s", "API", "." ]
b77506275ec276ce90879bf1ea9299a79448b903
https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/internals/api.py#L119-L144
245,677
jtpaasch/simplygithub
simplygithub/internals/api.py
delete_request
def delete_request(profile, resource): """Do a DELETE request to Github's API. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. resource The part of a Github API URL that comes after ``.../:repo/git``. For instance, for ``.../:repo/git/commits``, it's ``/commits``. Returns: The response returned by the ``requests`` library when it does the POST request. """ url = get_url(profile, resource) headers = get_headers(profile) return requests.delete(url, headers=headers)
python
def delete_request(profile, resource): """Do a DELETE request to Github's API. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. resource The part of a Github API URL that comes after ``.../:repo/git``. For instance, for ``.../:repo/git/commits``, it's ``/commits``. Returns: The response returned by the ``requests`` library when it does the POST request. """ url = get_url(profile, resource) headers = get_headers(profile) return requests.delete(url, headers=headers)
[ "def", "delete_request", "(", "profile", ",", "resource", ")", ":", "url", "=", "get_url", "(", "profile", ",", "resource", ")", "headers", "=", "get_headers", "(", "profile", ")", "return", "requests", ".", "delete", "(", "url", ",", "headers", "=", "headers", ")" ]
Do a DELETE request to Github's API. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. resource The part of a Github API URL that comes after ``.../:repo/git``. For instance, for ``.../:repo/git/commits``, it's ``/commits``. Returns: The response returned by the ``requests`` library when it does the POST request.
[ "Do", "a", "DELETE", "request", "to", "Github", "s", "API", "." ]
b77506275ec276ce90879bf1ea9299a79448b903
https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/internals/api.py#L175-L196
245,678
koheimiya/extheano
extheano/nodebuffer.py
NodeBuffer._extract_updater
def _extract_updater(self): """ Get the update and reset the buffer. Return `None` if there is no update. """ if self._node is self._buffer: return None else: updater = (self._node, self._buffer) self._buffer = self._node return updater
python
def _extract_updater(self): """ Get the update and reset the buffer. Return `None` if there is no update. """ if self._node is self._buffer: return None else: updater = (self._node, self._buffer) self._buffer = self._node return updater
[ "def", "_extract_updater", "(", "self", ")", ":", "if", "self", ".", "_node", "is", "self", ".", "_buffer", ":", "return", "None", "else", ":", "updater", "=", "(", "self", ".", "_node", ",", "self", ".", "_buffer", ")", "self", ".", "_buffer", "=", "self", ".", "_node", "return", "updater" ]
Get the update and reset the buffer. Return `None` if there is no update.
[ "Get", "the", "update", "and", "reset", "the", "buffer", ".", "Return", "None", "if", "there", "is", "no", "update", "." ]
ea099a6395ca8772660b2c715fb26cde12738181
https://github.com/koheimiya/extheano/blob/ea099a6395ca8772660b2c715fb26cde12738181/extheano/nodebuffer.py#L32-L40
245,679
hmartiniano/faz
faz/graph.py
DependencyGraph._build_graph
def _build_graph(self): """ Produce a dependency graph based on a list of tasks produced by the parser. """ self._graph.add_nodes_from(self.tasks) for node1 in self._graph.nodes: for node2 in self._graph.nodes: for input_file in node1.inputs: for output_file in node2.outputs: if output_file == input_file: self._graph.add_edge(node2, node1) for order, task in enumerate(topological_sort(self._graph)): task.predecessors = self._graph.predecessors(task) task.order = order
python
def _build_graph(self): """ Produce a dependency graph based on a list of tasks produced by the parser. """ self._graph.add_nodes_from(self.tasks) for node1 in self._graph.nodes: for node2 in self._graph.nodes: for input_file in node1.inputs: for output_file in node2.outputs: if output_file == input_file: self._graph.add_edge(node2, node1) for order, task in enumerate(topological_sort(self._graph)): task.predecessors = self._graph.predecessors(task) task.order = order
[ "def", "_build_graph", "(", "self", ")", ":", "self", ".", "_graph", ".", "add_nodes_from", "(", "self", ".", "tasks", ")", "for", "node1", "in", "self", ".", "_graph", ".", "nodes", ":", "for", "node2", "in", "self", ".", "_graph", ".", "nodes", ":", "for", "input_file", "in", "node1", ".", "inputs", ":", "for", "output_file", "in", "node2", ".", "outputs", ":", "if", "output_file", "==", "input_file", ":", "self", ".", "_graph", ".", "add_edge", "(", "node2", ",", "node1", ")", "for", "order", ",", "task", "in", "enumerate", "(", "topological_sort", "(", "self", ".", "_graph", ")", ")", ":", "task", ".", "predecessors", "=", "self", ".", "_graph", ".", "predecessors", "(", "task", ")", "task", ".", "order", "=", "order" ]
Produce a dependency graph based on a list of tasks produced by the parser.
[ "Produce", "a", "dependency", "graph", "based", "on", "a", "list", "of", "tasks", "produced", "by", "the", "parser", "." ]
36a58c45e8c0718d38cb3c533542c8743e7e7a65
https://github.com/hmartiniano/faz/blob/36a58c45e8c0718d38cb3c533542c8743e7e7a65/faz/graph.py#L48-L61
245,680
blubberdiblub/eztemplate
eztemplate/engines/string_formatter_engine.py
FormatterWrapper.get_value
def get_value(self, key, args, kwargs): """Get value only from mapping and possibly convert key to string.""" if (self.tolerant and not isinstance(key, basestring) and key not in kwargs): key = str(key) return kwargs[key]
python
def get_value(self, key, args, kwargs): """Get value only from mapping and possibly convert key to string.""" if (self.tolerant and not isinstance(key, basestring) and key not in kwargs): key = str(key) return kwargs[key]
[ "def", "get_value", "(", "self", ",", "key", ",", "args", ",", "kwargs", ")", ":", "if", "(", "self", ".", "tolerant", "and", "not", "isinstance", "(", "key", ",", "basestring", ")", "and", "key", "not", "in", "kwargs", ")", ":", "key", "=", "str", "(", "key", ")", "return", "kwargs", "[", "key", "]" ]
Get value only from mapping and possibly convert key to string.
[ "Get", "value", "only", "from", "mapping", "and", "possibly", "convert", "key", "to", "string", "." ]
ab5b2b4987c045116d130fd83e216704b8edfb5d
https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/engines/string_formatter_engine.py#L49-L56
245,681
blubberdiblub/eztemplate
eztemplate/engines/string_formatter_engine.py
FormatterWrapper.get_field
def get_field(self, field_name, args, kwargs): """Create a special value when field missing and tolerant.""" try: obj, arg_used = super(FormatterWrapper, self).get_field( field_name, args, kwargs) except (KeyError, IndexError, AttributeError): if not self.tolerant: raise obj = MissingField(field_name) arg_used = field_name return obj, arg_used
python
def get_field(self, field_name, args, kwargs): """Create a special value when field missing and tolerant.""" try: obj, arg_used = super(FormatterWrapper, self).get_field( field_name, args, kwargs) except (KeyError, IndexError, AttributeError): if not self.tolerant: raise obj = MissingField(field_name) arg_used = field_name return obj, arg_used
[ "def", "get_field", "(", "self", ",", "field_name", ",", "args", ",", "kwargs", ")", ":", "try", ":", "obj", ",", "arg_used", "=", "super", "(", "FormatterWrapper", ",", "self", ")", ".", "get_field", "(", "field_name", ",", "args", ",", "kwargs", ")", "except", "(", "KeyError", ",", "IndexError", ",", "AttributeError", ")", ":", "if", "not", "self", ".", "tolerant", ":", "raise", "obj", "=", "MissingField", "(", "field_name", ")", "arg_used", "=", "field_name", "return", "obj", ",", "arg_used" ]
Create a special value when field missing and tolerant.
[ "Create", "a", "special", "value", "when", "field", "missing", "and", "tolerant", "." ]
ab5b2b4987c045116d130fd83e216704b8edfb5d
https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/engines/string_formatter_engine.py#L58-L70
245,682
blubberdiblub/eztemplate
eztemplate/engines/string_formatter_engine.py
FormatterWrapper.convert_field
def convert_field(self, value, conversion): """When field missing, store conversion specifier.""" if isinstance(value, MissingField): if conversion is not None: value.conversion = conversion return value return super(FormatterWrapper, self).convert_field(value, conversion)
python
def convert_field(self, value, conversion): """When field missing, store conversion specifier.""" if isinstance(value, MissingField): if conversion is not None: value.conversion = conversion return value return super(FormatterWrapper, self).convert_field(value, conversion)
[ "def", "convert_field", "(", "self", ",", "value", ",", "conversion", ")", ":", "if", "isinstance", "(", "value", ",", "MissingField", ")", ":", "if", "conversion", "is", "not", "None", ":", "value", ".", "conversion", "=", "conversion", "return", "value", "return", "super", "(", "FormatterWrapper", ",", "self", ")", ".", "convert_field", "(", "value", ",", "conversion", ")" ]
When field missing, store conversion specifier.
[ "When", "field", "missing", "store", "conversion", "specifier", "." ]
ab5b2b4987c045116d130fd83e216704b8edfb5d
https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/engines/string_formatter_engine.py#L72-L79
245,683
blubberdiblub/eztemplate
eztemplate/engines/string_formatter_engine.py
FormatterWrapper.format_field
def format_field(self, value, format_spec): """When field missing, return original spec.""" if isinstance(value, MissingField): if format_spec is not None: value.format_spec = format_spec return str(value) return super(FormatterWrapper, self).format_field(value, format_spec)
python
def format_field(self, value, format_spec): """When field missing, return original spec.""" if isinstance(value, MissingField): if format_spec is not None: value.format_spec = format_spec return str(value) return super(FormatterWrapper, self).format_field(value, format_spec)
[ "def", "format_field", "(", "self", ",", "value", ",", "format_spec", ")", ":", "if", "isinstance", "(", "value", ",", "MissingField", ")", ":", "if", "format_spec", "is", "not", "None", ":", "value", ".", "format_spec", "=", "format_spec", "return", "str", "(", "value", ")", "return", "super", "(", "FormatterWrapper", ",", "self", ")", ".", "format_field", "(", "value", ",", "format_spec", ")" ]
When field missing, return original spec.
[ "When", "field", "missing", "return", "original", "spec", "." ]
ab5b2b4987c045116d130fd83e216704b8edfb5d
https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/engines/string_formatter_engine.py#L81-L88
245,684
emencia/emencia-django-forum
forum/models.py
Category.get_last_thread
def get_last_thread(self): """ Return the last modified thread """ cache_key = '_get_last_thread_cache' if not hasattr(self, cache_key): item = None res = self.thread_set.filter(visible=True).order_by('-modified')[0:1] if len(res)>0: item = res[0] setattr(self, cache_key, item) return getattr(self, cache_key)
python
def get_last_thread(self): """ Return the last modified thread """ cache_key = '_get_last_thread_cache' if not hasattr(self, cache_key): item = None res = self.thread_set.filter(visible=True).order_by('-modified')[0:1] if len(res)>0: item = res[0] setattr(self, cache_key, item) return getattr(self, cache_key)
[ "def", "get_last_thread", "(", "self", ")", ":", "cache_key", "=", "'_get_last_thread_cache'", "if", "not", "hasattr", "(", "self", ",", "cache_key", ")", ":", "item", "=", "None", "res", "=", "self", ".", "thread_set", ".", "filter", "(", "visible", "=", "True", ")", ".", "order_by", "(", "'-modified'", ")", "[", "0", ":", "1", "]", "if", "len", "(", "res", ")", ">", "0", ":", "item", "=", "res", "[", "0", "]", "setattr", "(", "self", ",", "cache_key", ",", "item", ")", "return", "getattr", "(", "self", ",", "cache_key", ")" ]
Return the last modified thread
[ "Return", "the", "last", "modified", "thread" ]
cda74ed7e5822675c340ee5ec71548d981bccd3b
https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/models.py#L31-L42
245,685
emencia/emencia-django-forum
forum/models.py
Thread.save
def save(self, *args, **kwargs): """ Fill 'created' and 'modified' attributes on first create """ if self.created is None: self.created = tz_now() if self.modified is None: self.modified = self.created super(Thread, self).save(*args, **kwargs)
python
def save(self, *args, **kwargs): """ Fill 'created' and 'modified' attributes on first create """ if self.created is None: self.created = tz_now() if self.modified is None: self.modified = self.created super(Thread, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "created", "is", "None", ":", "self", ".", "created", "=", "tz_now", "(", ")", "if", "self", ".", "modified", "is", "None", ":", "self", ".", "modified", "=", "self", ".", "created", "super", "(", "Thread", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Fill 'created' and 'modified' attributes on first create
[ "Fill", "created", "and", "modified", "attributes", "on", "first", "create" ]
cda74ed7e5822675c340ee5ec71548d981bccd3b
https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/models.py#L99-L109
245,686
emencia/emencia-django-forum
forum/models.py
Post.get_paginated_urlargs
def get_paginated_urlargs(self): """ Return url arguments to retrieve the Post in a paginated list """ position = self.get_paginated_position() if not position: return '#forum-post-{0}'.format(self.id) return '?page={0}#forum-post-{1}'.format(position, self.id)
python
def get_paginated_urlargs(self): """ Return url arguments to retrieve the Post in a paginated list """ position = self.get_paginated_position() if not position: return '#forum-post-{0}'.format(self.id) return '?page={0}#forum-post-{1}'.format(position, self.id)
[ "def", "get_paginated_urlargs", "(", "self", ")", ":", "position", "=", "self", ".", "get_paginated_position", "(", ")", "if", "not", "position", ":", "return", "'#forum-post-{0}'", ".", "format", "(", "self", ".", "id", ")", "return", "'?page={0}#forum-post-{1}'", ".", "format", "(", "position", ",", "self", ".", "id", ")" ]
Return url arguments to retrieve the Post in a paginated list
[ "Return", "url", "arguments", "to", "retrieve", "the", "Post", "in", "a", "paginated", "list" ]
cda74ed7e5822675c340ee5ec71548d981bccd3b
https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/models.py#L150-L159
245,687
emencia/emencia-django-forum
forum/models.py
Post.get_paginated_position
def get_paginated_position(self): """ Return the Post position in the paginated list """ # If Post list is not paginated if not settings.FORUM_THREAD_DETAIL_PAGINATE: return 0 count = Post.objects.filter(thread=self.thread_id, created__lt=self.created).count() + 1 return int(math.ceil(count / float(settings.FORUM_THREAD_DETAIL_PAGINATE)))
python
def get_paginated_position(self): """ Return the Post position in the paginated list """ # If Post list is not paginated if not settings.FORUM_THREAD_DETAIL_PAGINATE: return 0 count = Post.objects.filter(thread=self.thread_id, created__lt=self.created).count() + 1 return int(math.ceil(count / float(settings.FORUM_THREAD_DETAIL_PAGINATE)))
[ "def", "get_paginated_position", "(", "self", ")", ":", "# If Post list is not paginated", "if", "not", "settings", ".", "FORUM_THREAD_DETAIL_PAGINATE", ":", "return", "0", "count", "=", "Post", ".", "objects", ".", "filter", "(", "thread", "=", "self", ".", "thread_id", ",", "created__lt", "=", "self", ".", "created", ")", ".", "count", "(", ")", "+", "1", "return", "int", "(", "math", ".", "ceil", "(", "count", "/", "float", "(", "settings", ".", "FORUM_THREAD_DETAIL_PAGINATE", ")", ")", ")" ]
Return the Post position in the paginated list
[ "Return", "the", "Post", "position", "in", "the", "paginated", "list" ]
cda74ed7e5822675c340ee5ec71548d981bccd3b
https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/models.py#L161-L171
245,688
emencia/emencia-django-forum
forum/models.py
Post.save
def save(self, *args, **kwargs): """ Fill 'created' and 'modified' attributes on first create and allways update the thread's 'modified' attribute """ edited = not(self.created is None) if self.created is None: self.created = tz_now() # Update de la date de modif. du message if self.modified is None: self.modified = self.created else: self.modified = tz_now() super(Post, self).save(*args, **kwargs) # Update de la date de modif. du thread lors de la création du message if not edited: self.thread.modified = self.created self.thread.save()
python
def save(self, *args, **kwargs): """ Fill 'created' and 'modified' attributes on first create and allways update the thread's 'modified' attribute """ edited = not(self.created is None) if self.created is None: self.created = tz_now() # Update de la date de modif. du message if self.modified is None: self.modified = self.created else: self.modified = tz_now() super(Post, self).save(*args, **kwargs) # Update de la date de modif. du thread lors de la création du message if not edited: self.thread.modified = self.created self.thread.save()
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "edited", "=", "not", "(", "self", ".", "created", "is", "None", ")", "if", "self", ".", "created", "is", "None", ":", "self", ".", "created", "=", "tz_now", "(", ")", "# Update de la date de modif. du message", "if", "self", ".", "modified", "is", "None", ":", "self", ".", "modified", "=", "self", ".", "created", "else", ":", "self", ".", "modified", "=", "tz_now", "(", ")", "super", "(", "Post", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# Update de la date de modif. du thread lors de la création du message", "if", "not", "edited", ":", "self", ".", "thread", ".", "modified", "=", "self", ".", "created", "self", ".", "thread", ".", "save", "(", ")" ]
Fill 'created' and 'modified' attributes on first create and allways update the thread's 'modified' attribute
[ "Fill", "created", "and", "modified", "attributes", "on", "first", "create", "and", "allways", "update", "the", "thread", "s", "modified", "attribute" ]
cda74ed7e5822675c340ee5ec71548d981bccd3b
https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/models.py#L173-L194
245,689
opinkerfi/nago
nago/extensions/plugins.py
get
def get(search="unsigned"): """ List all available plugins""" plugins = [] for i in os.walk('/usr/lib/nagios/plugins'): for f in i[2]: plugins.append(f) return plugins
python
def get(search="unsigned"): """ List all available plugins""" plugins = [] for i in os.walk('/usr/lib/nagios/plugins'): for f in i[2]: plugins.append(f) return plugins
[ "def", "get", "(", "search", "=", "\"unsigned\"", ")", ":", "plugins", "=", "[", "]", "for", "i", "in", "os", ".", "walk", "(", "'/usr/lib/nagios/plugins'", ")", ":", "for", "f", "in", "i", "[", "2", "]", ":", "plugins", ".", "append", "(", "f", ")", "return", "plugins" ]
List all available plugins
[ "List", "all", "available", "plugins" ]
85e1bdd1de0122f56868a483e7599e1b36a439b0
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/extensions/plugins.py#L13-L19
245,690
opinkerfi/nago
nago/extensions/plugins.py
run
def run(plugin_name, *args, **kwargs): """ Run a specific plugin """ plugindir = nago.settings.get_option('plugin_dir') plugin = plugindir + "/" + plugin_name if not os.path.isfile(plugin): raise ValueError("Plugin %s not found" % plugin) command = [plugin] + list(args) p = subprocess.Popen(command, stdout=subprocess.PIPE,stderr=subprocess.PIPE,) stdout, stderr = p.communicate('through stdin to stdout') result = {} result['stdout'] = stdout result['stderr'] = stderr result['return_code'] = p.returncode return result
python
def run(plugin_name, *args, **kwargs): """ Run a specific plugin """ plugindir = nago.settings.get_option('plugin_dir') plugin = plugindir + "/" + plugin_name if not os.path.isfile(plugin): raise ValueError("Plugin %s not found" % plugin) command = [plugin] + list(args) p = subprocess.Popen(command, stdout=subprocess.PIPE,stderr=subprocess.PIPE,) stdout, stderr = p.communicate('through stdin to stdout') result = {} result['stdout'] = stdout result['stderr'] = stderr result['return_code'] = p.returncode return result
[ "def", "run", "(", "plugin_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "plugindir", "=", "nago", ".", "settings", ".", "get_option", "(", "'plugin_dir'", ")", "plugin", "=", "plugindir", "+", "\"/\"", "+", "plugin_name", "if", "not", "os", ".", "path", ".", "isfile", "(", "plugin", ")", ":", "raise", "ValueError", "(", "\"Plugin %s not found\"", "%", "plugin", ")", "command", "=", "[", "plugin", "]", "+", "list", "(", "args", ")", "p", "=", "subprocess", ".", "Popen", "(", "command", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", ")", "stdout", ",", "stderr", "=", "p", ".", "communicate", "(", "'through stdin to stdout'", ")", "result", "=", "{", "}", "result", "[", "'stdout'", "]", "=", "stdout", "result", "[", "'stderr'", "]", "=", "stderr", "result", "[", "'return_code'", "]", "=", "p", ".", "returncode", "return", "result" ]
Run a specific plugin
[ "Run", "a", "specific", "plugin" ]
85e1bdd1de0122f56868a483e7599e1b36a439b0
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/extensions/plugins.py#L22-L36
245,691
b3j0f/utils
b3j0f/utils/property.py
find_ctx
def find_ctx(elt): """Get the right ctx related to input elt. In order to keep safe memory as much as possible, it is important to find the right context element. For example, instead of putting properties on a function at the level of an instance, it is important to save such property on the instance because the function.__dict__ is shared with instance class function, and so, if the instance is deleted from memory, the property is still present in the class memory. And so on, it is impossible to identify the right context in such case if all properties are saved with the same key in the same function which is the function. """ result = elt # by default, result is ctx # if elt is ctx and elt is a method, it is possible to find the best ctx if ismethod(elt): # get instance and class of the elt instance = get_method_self(elt) # if instance is not None, the right context is the instance if instance is not None: result = instance elif PY2: result = elt.im_class return result
python
def find_ctx(elt): """Get the right ctx related to input elt. In order to keep safe memory as much as possible, it is important to find the right context element. For example, instead of putting properties on a function at the level of an instance, it is important to save such property on the instance because the function.__dict__ is shared with instance class function, and so, if the instance is deleted from memory, the property is still present in the class memory. And so on, it is impossible to identify the right context in such case if all properties are saved with the same key in the same function which is the function. """ result = elt # by default, result is ctx # if elt is ctx and elt is a method, it is possible to find the best ctx if ismethod(elt): # get instance and class of the elt instance = get_method_self(elt) # if instance is not None, the right context is the instance if instance is not None: result = instance elif PY2: result = elt.im_class return result
[ "def", "find_ctx", "(", "elt", ")", ":", "result", "=", "elt", "# by default, result is ctx", "# if elt is ctx and elt is a method, it is possible to find the best ctx", "if", "ismethod", "(", "elt", ")", ":", "# get instance and class of the elt", "instance", "=", "get_method_self", "(", "elt", ")", "# if instance is not None, the right context is the instance", "if", "instance", "is", "not", "None", ":", "result", "=", "instance", "elif", "PY2", ":", "result", "=", "elt", ".", "im_class", "return", "result" ]
Get the right ctx related to input elt. In order to keep safe memory as much as possible, it is important to find the right context element. For example, instead of putting properties on a function at the level of an instance, it is important to save such property on the instance because the function.__dict__ is shared with instance class function, and so, if the instance is deleted from memory, the property is still present in the class memory. And so on, it is impossible to identify the right context in such case if all properties are saved with the same key in the same function which is the function.
[ "Get", "the", "right", "ctx", "related", "to", "input", "elt", "." ]
793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/property.py#L81-L107
245,692
b3j0f/utils
b3j0f/utils/property.py
free_cache
def free_cache(ctx, *elts): """Free properties bound to input cached elts. If empty, free the whole cache. """ for elt in elts: if isinstance(elt, Hashable): cache = __STATIC_ELEMENTS_CACHE__ else: cache = __UNHASHABLE_ELTS_CACHE__ elt = id(elt) if elt in cache: del cache[elt] if not elts: __STATIC_ELEMENTS_CACHE__.clear() __UNHASHABLE_ELTS_CACHE__.clear()
python
def free_cache(ctx, *elts): """Free properties bound to input cached elts. If empty, free the whole cache. """ for elt in elts: if isinstance(elt, Hashable): cache = __STATIC_ELEMENTS_CACHE__ else: cache = __UNHASHABLE_ELTS_CACHE__ elt = id(elt) if elt in cache: del cache[elt] if not elts: __STATIC_ELEMENTS_CACHE__.clear() __UNHASHABLE_ELTS_CACHE__.clear()
[ "def", "free_cache", "(", "ctx", ",", "*", "elts", ")", ":", "for", "elt", "in", "elts", ":", "if", "isinstance", "(", "elt", ",", "Hashable", ")", ":", "cache", "=", "__STATIC_ELEMENTS_CACHE__", "else", ":", "cache", "=", "__UNHASHABLE_ELTS_CACHE__", "elt", "=", "id", "(", "elt", ")", "if", "elt", "in", "cache", ":", "del", "cache", "[", "elt", "]", "if", "not", "elts", ":", "__STATIC_ELEMENTS_CACHE__", ".", "clear", "(", ")", "__UNHASHABLE_ELTS_CACHE__", ".", "clear", "(", ")" ]
Free properties bound to input cached elts. If empty, free the whole cache.
[ "Free", "properties", "bound", "to", "input", "cached", "elts", ".", "If", "empty", "free", "the", "whole", "cache", "." ]
793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/property.py#L110-L126
245,693
b3j0f/utils
b3j0f/utils/property.py
_ctx_elt_properties
def _ctx_elt_properties(elt, ctx=None, create=False): """Get elt properties related to a ctx. :param elt: property component elt. Not None methods or unhashable types. :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :param bool create: create ctx elt properties if not exist. :return: dictionary of property by name embedded into ctx __dict__ or in shared __STATIC_ELEMENTS_CACHE__ or else in shared __UNHASHABLE_ELTS_CACHE__. None if no properties exists. :rtype: dict """ result = None if ctx is None: ctx = find_ctx(elt=elt) ctx_properties = None # in case of dynamic object, parse the ctx __dict__ ctx__dict__ = getattr(ctx, __DICT__, None) if ctx__dict__ is not None and isinstance(ctx__dict__, dict): # if properties exist in ctx__dict__ if __B3J0F__PROPERTIES__ in ctx__dict__: ctx_properties = ctx__dict__[__B3J0F__PROPERTIES__] elif create: # if create in worst case ctx_properties = ctx__dict__[__B3J0F__PROPERTIES__] = {} else: # in case of static object if isinstance(ctx, Hashable): # search among static elements cache = __STATIC_ELEMENTS_CACHE__ else: # or unhashable elements cache = __UNHASHABLE_ELTS_CACHE__ ctx = id(ctx) if not isinstance(elt, Hashable): elt = id(elt) # if ctx is in cache if ctx in cache: # get its properties ctx_properties = cache[ctx] elif create: # elif create, get an empty dict ctx_properties = cache[ctx] = {} # if ctx_properties is not None if ctx_properties is not None: # check if elt exist in ctx_properties if elt in ctx_properties: result = ctx_properties[elt] elif create: # create the right data if create if create: result = ctx_properties[elt] = {} return result
python
def _ctx_elt_properties(elt, ctx=None, create=False): """Get elt properties related to a ctx. :param elt: property component elt. Not None methods or unhashable types. :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :param bool create: create ctx elt properties if not exist. :return: dictionary of property by name embedded into ctx __dict__ or in shared __STATIC_ELEMENTS_CACHE__ or else in shared __UNHASHABLE_ELTS_CACHE__. None if no properties exists. :rtype: dict """ result = None if ctx is None: ctx = find_ctx(elt=elt) ctx_properties = None # in case of dynamic object, parse the ctx __dict__ ctx__dict__ = getattr(ctx, __DICT__, None) if ctx__dict__ is not None and isinstance(ctx__dict__, dict): # if properties exist in ctx__dict__ if __B3J0F__PROPERTIES__ in ctx__dict__: ctx_properties = ctx__dict__[__B3J0F__PROPERTIES__] elif create: # if create in worst case ctx_properties = ctx__dict__[__B3J0F__PROPERTIES__] = {} else: # in case of static object if isinstance(ctx, Hashable): # search among static elements cache = __STATIC_ELEMENTS_CACHE__ else: # or unhashable elements cache = __UNHASHABLE_ELTS_CACHE__ ctx = id(ctx) if not isinstance(elt, Hashable): elt = id(elt) # if ctx is in cache if ctx in cache: # get its properties ctx_properties = cache[ctx] elif create: # elif create, get an empty dict ctx_properties = cache[ctx] = {} # if ctx_properties is not None if ctx_properties is not None: # check if elt exist in ctx_properties if elt in ctx_properties: result = ctx_properties[elt] elif create: # create the right data if create if create: result = ctx_properties[elt] = {} return result
[ "def", "_ctx_elt_properties", "(", "elt", ",", "ctx", "=", "None", ",", "create", "=", "False", ")", ":", "result", "=", "None", "if", "ctx", "is", "None", ":", "ctx", "=", "find_ctx", "(", "elt", "=", "elt", ")", "ctx_properties", "=", "None", "# in case of dynamic object, parse the ctx __dict__", "ctx__dict__", "=", "getattr", "(", "ctx", ",", "__DICT__", ",", "None", ")", "if", "ctx__dict__", "is", "not", "None", "and", "isinstance", "(", "ctx__dict__", ",", "dict", ")", ":", "# if properties exist in ctx__dict__", "if", "__B3J0F__PROPERTIES__", "in", "ctx__dict__", ":", "ctx_properties", "=", "ctx__dict__", "[", "__B3J0F__PROPERTIES__", "]", "elif", "create", ":", "# if create in worst case", "ctx_properties", "=", "ctx__dict__", "[", "__B3J0F__PROPERTIES__", "]", "=", "{", "}", "else", ":", "# in case of static object", "if", "isinstance", "(", "ctx", ",", "Hashable", ")", ":", "# search among static elements", "cache", "=", "__STATIC_ELEMENTS_CACHE__", "else", ":", "# or unhashable elements", "cache", "=", "__UNHASHABLE_ELTS_CACHE__", "ctx", "=", "id", "(", "ctx", ")", "if", "not", "isinstance", "(", "elt", ",", "Hashable", ")", ":", "elt", "=", "id", "(", "elt", ")", "# if ctx is in cache", "if", "ctx", "in", "cache", ":", "# get its properties", "ctx_properties", "=", "cache", "[", "ctx", "]", "elif", "create", ":", "# elif create, get an empty dict", "ctx_properties", "=", "cache", "[", "ctx", "]", "=", "{", "}", "# if ctx_properties is not None", "if", "ctx_properties", "is", "not", "None", ":", "# check if elt exist in ctx_properties", "if", "elt", "in", "ctx_properties", ":", "result", "=", "ctx_properties", "[", "elt", "]", "elif", "create", ":", "# create the right data if create", "if", "create", ":", "result", "=", "ctx_properties", "[", "elt", "]", "=", "{", "}", "return", "result" ]
Get elt properties related to a ctx. :param elt: property component elt. Not None methods or unhashable types. :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :param bool create: create ctx elt properties if not exist. :return: dictionary of property by name embedded into ctx __dict__ or in shared __STATIC_ELEMENTS_CACHE__ or else in shared __UNHASHABLE_ELTS_CACHE__. None if no properties exists. :rtype: dict
[ "Get", "elt", "properties", "related", "to", "a", "ctx", "." ]
793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/property.py#L129-L184
245,694
b3j0f/utils
b3j0f/utils/property.py
get_properties
def get_properties(elt, keys=None, ctx=None): """Get elt properties. :param elt: properties elt. Not None methods or unhashable types. :param keys: key(s) of properties to get from elt. If None, get all properties. :type keys: list or str :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :return: list of properties by elt and name. :rtype: list """ # initialize keys if str if isinstance(keys, string_types): keys = (keys,) result = _get_properties(elt, keys=keys, local=False, ctx=ctx) return result
python
def get_properties(elt, keys=None, ctx=None): """Get elt properties. :param elt: properties elt. Not None methods or unhashable types. :param keys: key(s) of properties to get from elt. If None, get all properties. :type keys: list or str :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :return: list of properties by elt and name. :rtype: list """ # initialize keys if str if isinstance(keys, string_types): keys = (keys,) result = _get_properties(elt, keys=keys, local=False, ctx=ctx) return result
[ "def", "get_properties", "(", "elt", ",", "keys", "=", "None", ",", "ctx", "=", "None", ")", ":", "# initialize keys if str", "if", "isinstance", "(", "keys", ",", "string_types", ")", ":", "keys", "=", "(", "keys", ",", ")", "result", "=", "_get_properties", "(", "elt", ",", "keys", "=", "keys", ",", "local", "=", "False", ",", "ctx", "=", "ctx", ")", "return", "result" ]
Get elt properties. :param elt: properties elt. Not None methods or unhashable types. :param keys: key(s) of properties to get from elt. If None, get all properties. :type keys: list or str :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :return: list of properties by elt and name. :rtype: list
[ "Get", "elt", "properties", "." ]
793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/property.py#L187-L208
245,695
b3j0f/utils
b3j0f/utils/property.py
get_property
def get_property(elt, key, ctx=None): """Get elt key property. :param elt: property elt. Not None methods. :param key: property key to get from elt. :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :return: list of property values by elt. :rtype: list """ result = [] properties = get_properties(elt=elt, ctx=ctx, keys=key) if key in properties: result = properties[key] return result
python
def get_property(elt, key, ctx=None): """Get elt key property. :param elt: property elt. Not None methods. :param key: property key to get from elt. :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :return: list of property values by elt. :rtype: list """ result = [] properties = get_properties(elt=elt, ctx=ctx, keys=key) if key in properties: result = properties[key] return result
[ "def", "get_property", "(", "elt", ",", "key", ",", "ctx", "=", "None", ")", ":", "result", "=", "[", "]", "properties", "=", "get_properties", "(", "elt", "=", "elt", ",", "ctx", "=", "ctx", ",", "keys", "=", "key", ")", "if", "key", "in", "properties", ":", "result", "=", "properties", "[", "key", "]", "return", "result" ]
Get elt key property. :param elt: property elt. Not None methods. :param key: property key to get from elt. :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :return: list of property values by elt. :rtype: list
[ "Get", "elt", "key", "property", "." ]
793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/property.py#L211-L231
245,696
b3j0f/utils
b3j0f/utils/property.py
get_first_properties
def get_first_properties(elt, keys=None, ctx=None): """Get first properties related to one input key. :param elt: first property elt. Not None methods. :param list keys: property keys to get. :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :return: dict of first values of elt properties. """ # ensure keys is an iterable if not None if isinstance(keys, string_types): keys = (keys,) result = _get_properties(elt, keys=keys, first=True, ctx=ctx) return result
python
def get_first_properties(elt, keys=None, ctx=None): """Get first properties related to one input key. :param elt: first property elt. Not None methods. :param list keys: property keys to get. :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :return: dict of first values of elt properties. """ # ensure keys is an iterable if not None if isinstance(keys, string_types): keys = (keys,) result = _get_properties(elt, keys=keys, first=True, ctx=ctx) return result
[ "def", "get_first_properties", "(", "elt", ",", "keys", "=", "None", ",", "ctx", "=", "None", ")", ":", "# ensure keys is an iterable if not None", "if", "isinstance", "(", "keys", ",", "string_types", ")", ":", "keys", "=", "(", "keys", ",", ")", "result", "=", "_get_properties", "(", "elt", ",", "keys", "=", "keys", ",", "first", "=", "True", ",", "ctx", "=", "ctx", ")", "return", "result" ]
Get first properties related to one input key. :param elt: first property elt. Not None methods. :param list keys: property keys to get. :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :return: dict of first values of elt properties.
[ "Get", "first", "properties", "related", "to", "one", "input", "key", "." ]
793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/property.py#L234-L252
245,697
b3j0f/utils
b3j0f/utils/property.py
get_first_property
def get_first_property(elt, key, default=None, ctx=None): """Get first property related to one input key. :param elt: first property elt. Not None methods. :param str key: property key to get. :param default: default value to return if key does not exist in elt. properties :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. """ result = default properties = _get_properties(elt, keys=(key,), ctx=ctx, first=True) # set value if key exists in properties if key in properties: result = properties[key] return result
python
def get_first_property(elt, key, default=None, ctx=None): """Get first property related to one input key. :param elt: first property elt. Not None methods. :param str key: property key to get. :param default: default value to return if key does not exist in elt. properties :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. """ result = default properties = _get_properties(elt, keys=(key,), ctx=ctx, first=True) # set value if key exists in properties if key in properties: result = properties[key] return result
[ "def", "get_first_property", "(", "elt", ",", "key", ",", "default", "=", "None", ",", "ctx", "=", "None", ")", ":", "result", "=", "default", "properties", "=", "_get_properties", "(", "elt", ",", "keys", "=", "(", "key", ",", ")", ",", "ctx", "=", "ctx", ",", "first", "=", "True", ")", "# set value if key exists in properties", "if", "key", "in", "properties", ":", "result", "=", "properties", "[", "key", "]", "return", "result" ]
Get first property related to one input key. :param elt: first property elt. Not None methods. :param str key: property key to get. :param default: default value to return if key does not exist in elt. properties :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class.
[ "Get", "first", "property", "related", "to", "one", "input", "key", "." ]
793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/property.py#L255-L275
245,698
b3j0f/utils
b3j0f/utils/property.py
get_local_property
def get_local_property(elt, key, default=None, ctx=None): """Get one local property related to one input key or default value if key is not found. :param elt: local property elt. Not None methods. :param str key: property key to get. :param default: default value to return if key does not exist in elt properties. :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :return: dict of properties by name. :rtype: dict """ result = default local_properties = get_local_properties(elt=elt, keys=(key,), ctx=ctx) if key in local_properties: result = local_properties[key] return result
python
def get_local_property(elt, key, default=None, ctx=None): """Get one local property related to one input key or default value if key is not found. :param elt: local property elt. Not None methods. :param str key: property key to get. :param default: default value to return if key does not exist in elt properties. :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :return: dict of properties by name. :rtype: dict """ result = default local_properties = get_local_properties(elt=elt, keys=(key,), ctx=ctx) if key in local_properties: result = local_properties[key] return result
[ "def", "get_local_property", "(", "elt", ",", "key", ",", "default", "=", "None", ",", "ctx", "=", "None", ")", ":", "result", "=", "default", "local_properties", "=", "get_local_properties", "(", "elt", "=", "elt", ",", "keys", "=", "(", "key", ",", ")", ",", "ctx", "=", "ctx", ")", "if", "key", "in", "local_properties", ":", "result", "=", "local_properties", "[", "key", "]", "return", "result" ]
Get one local property related to one input key or default value if key is not found. :param elt: local property elt. Not None methods. :param str key: property key to get. :param default: default value to return if key does not exist in elt properties. :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :return: dict of properties by name. :rtype: dict
[ "Get", "one", "local", "property", "related", "to", "one", "input", "key", "or", "default", "value", "if", "key", "is", "not", "found", "." ]
793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/property.py#L299-L321
245,699
b3j0f/utils
b3j0f/utils/property.py
put
def put(properties, ttl=None, ctx=None): """Decorator dedicated to put properties on an element. """ def put_on(elt): return put_properties(elt=elt, properties=properties, ttl=ttl, ctx=ctx) return put_on
python
def put(properties, ttl=None, ctx=None): """Decorator dedicated to put properties on an element. """ def put_on(elt): return put_properties(elt=elt, properties=properties, ttl=ttl, ctx=ctx) return put_on
[ "def", "put", "(", "properties", ",", "ttl", "=", "None", ",", "ctx", "=", "None", ")", ":", "def", "put_on", "(", "elt", ")", ":", "return", "put_properties", "(", "elt", "=", "elt", ",", "properties", "=", "properties", ",", "ttl", "=", "ttl", ",", "ctx", "=", "ctx", ")", "return", "put_on" ]
Decorator dedicated to put properties on an element.
[ "Decorator", "dedicated", "to", "put", "properties", "on", "an", "element", "." ]
793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/property.py#L569-L576