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
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
247,200
knagra/farnsworth
base/views.py
manage_profile_requests_view
def manage_profile_requests_view(request): ''' The page to manage user profile requests. ''' page_name = "Admin - Manage Profile Requests" profile_requests = ProfileRequest.objects.all() return render_to_response('manage_profile_requests.html', { 'page_name': page_name, 'choices': UserProfile.STATUS_CHOICES, 'profile_requests': profile_requests }, context_instance=RequestContext(request))
python
def manage_profile_requests_view(request): ''' The page to manage user profile requests. ''' page_name = "Admin - Manage Profile Requests" profile_requests = ProfileRequest.objects.all() return render_to_response('manage_profile_requests.html', { 'page_name': page_name, 'choices': UserProfile.STATUS_CHOICES, 'profile_requests': profile_requests }, context_instance=RequestContext(request))
[ "def", "manage_profile_requests_view", "(", "request", ")", ":", "page_name", "=", "\"Admin - Manage Profile Requests\"", "profile_requests", "=", "ProfileRequest", ".", "objects", ".", "all", "(", ")", "return", "render_to_response", "(", "'manage_profile_requests.html'", ",", "{", "'page_name'", ":", "page_name", ",", "'choices'", ":", "UserProfile", ".", "STATUS_CHOICES", ",", "'profile_requests'", ":", "profile_requests", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
The page to manage user profile requests.
[ "The", "page", "to", "manage", "user", "profile", "requests", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L521-L529
247,201
knagra/farnsworth
base/views.py
custom_add_user_view
def custom_add_user_view(request): ''' The page to add a new user. ''' page_name = "Admin - Add User" add_user_form = AddUserForm(request.POST or None, initial={ 'status': UserProfile.RESIDENT, }) if add_user_form.is_valid(): add_user_form.save() message = MESSAGES['USER_ADDED'].format( username=add_user_form.cleaned_data["username"]) messages.add_message(request, messages.SUCCESS, message) return HttpResponseRedirect(reverse('custom_add_user')) return render_to_response('custom_add_user.html', { 'page_name': page_name, 'add_user_form': add_user_form, 'members': User.objects.all().exclude(username=ANONYMOUS_USERNAME), }, context_instance=RequestContext(request))
python
def custom_add_user_view(request): ''' The page to add a new user. ''' page_name = "Admin - Add User" add_user_form = AddUserForm(request.POST or None, initial={ 'status': UserProfile.RESIDENT, }) if add_user_form.is_valid(): add_user_form.save() message = MESSAGES['USER_ADDED'].format( username=add_user_form.cleaned_data["username"]) messages.add_message(request, messages.SUCCESS, message) return HttpResponseRedirect(reverse('custom_add_user')) return render_to_response('custom_add_user.html', { 'page_name': page_name, 'add_user_form': add_user_form, 'members': User.objects.all().exclude(username=ANONYMOUS_USERNAME), }, context_instance=RequestContext(request))
[ "def", "custom_add_user_view", "(", "request", ")", ":", "page_name", "=", "\"Admin - Add User\"", "add_user_form", "=", "AddUserForm", "(", "request", ".", "POST", "or", "None", ",", "initial", "=", "{", "'status'", ":", "UserProfile", ".", "RESIDENT", ",", "}", ")", "if", "add_user_form", ".", "is_valid", "(", ")", ":", "add_user_form", ".", "save", "(", ")", "message", "=", "MESSAGES", "[", "'USER_ADDED'", "]", ".", "format", "(", "username", "=", "add_user_form", ".", "cleaned_data", "[", "\"username\"", "]", ")", "messages", ".", "add_message", "(", "request", ",", "messages", ".", "SUCCESS", ",", "message", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'custom_add_user'", ")", ")", "return", "render_to_response", "(", "'custom_add_user.html'", ",", "{", "'page_name'", ":", "page_name", ",", "'add_user_form'", ":", "add_user_form", ",", "'members'", ":", "User", ".", "objects", ".", "all", "(", ")", ".", "exclude", "(", "username", "=", "ANONYMOUS_USERNAME", ")", ",", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
The page to add a new user.
[ "The", "page", "to", "add", "a", "new", "user", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L693-L709
247,202
knagra/farnsworth
base/views.py
reset_pw_confirm_view
def reset_pw_confirm_view(request, uidb64=None, token=None): """ View to confirm resetting password. """ return password_reset_confirm(request, template_name="reset_confirmation.html", uidb64=uidb64, token=token, post_reset_redirect=reverse('login'))
python
def reset_pw_confirm_view(request, uidb64=None, token=None): """ View to confirm resetting password. """ return password_reset_confirm(request, template_name="reset_confirmation.html", uidb64=uidb64, token=token, post_reset_redirect=reverse('login'))
[ "def", "reset_pw_confirm_view", "(", "request", ",", "uidb64", "=", "None", ",", "token", "=", "None", ")", ":", "return", "password_reset_confirm", "(", "request", ",", "template_name", "=", "\"reset_confirmation.html\"", ",", "uidb64", "=", "uidb64", ",", "token", "=", "token", ",", "post_reset_redirect", "=", "reverse", "(", "'login'", ")", ")" ]
View to confirm resetting password.
[ "View", "to", "confirm", "resetting", "password", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L726-L730
247,203
knagra/farnsworth
base/views.py
recount_view
def recount_view(request): """ Recount number_of_messages for all threads and number_of_responses for all requests. Also set the change_date for every thread to the post_date of the latest message associated with that thread. """ requests_changed = 0 for req in Request.objects.all(): recount = Response.objects.filter(request=req).count() if req.number_of_responses != recount: req.number_of_responses = recount req.save() requests_changed += 1 threads_changed = 0 for thread in Thread.objects.all(): recount = Message.objects.filter(thread=thread).count() if thread.number_of_messages != recount: thread.number_of_messages = recount thread.save() threads_changed += 1 dates_changed = 0 for thread in Thread.objects.all(): if thread.change_date != thread.message_set.latest('post_date').post_date: thread.change_date = thread.message_set.latest('post_date').post_date thread.save() dates_changed += 1 messages.add_message(request, messages.SUCCESS, MESSAGES['RECOUNTED'].format( requests_changed=requests_changed, request_count=Request.objects.all().count(), threads_changed=threads_changed, thread_count=Thread.objects.all().count(), dates_changed=dates_changed, )) return HttpResponseRedirect(reverse('utilities'))
python
def recount_view(request): """ Recount number_of_messages for all threads and number_of_responses for all requests. Also set the change_date for every thread to the post_date of the latest message associated with that thread. """ requests_changed = 0 for req in Request.objects.all(): recount = Response.objects.filter(request=req).count() if req.number_of_responses != recount: req.number_of_responses = recount req.save() requests_changed += 1 threads_changed = 0 for thread in Thread.objects.all(): recount = Message.objects.filter(thread=thread).count() if thread.number_of_messages != recount: thread.number_of_messages = recount thread.save() threads_changed += 1 dates_changed = 0 for thread in Thread.objects.all(): if thread.change_date != thread.message_set.latest('post_date').post_date: thread.change_date = thread.message_set.latest('post_date').post_date thread.save() dates_changed += 1 messages.add_message(request, messages.SUCCESS, MESSAGES['RECOUNTED'].format( requests_changed=requests_changed, request_count=Request.objects.all().count(), threads_changed=threads_changed, thread_count=Thread.objects.all().count(), dates_changed=dates_changed, )) return HttpResponseRedirect(reverse('utilities'))
[ "def", "recount_view", "(", "request", ")", ":", "requests_changed", "=", "0", "for", "req", "in", "Request", ".", "objects", ".", "all", "(", ")", ":", "recount", "=", "Response", ".", "objects", ".", "filter", "(", "request", "=", "req", ")", ".", "count", "(", ")", "if", "req", ".", "number_of_responses", "!=", "recount", ":", "req", ".", "number_of_responses", "=", "recount", "req", ".", "save", "(", ")", "requests_changed", "+=", "1", "threads_changed", "=", "0", "for", "thread", "in", "Thread", ".", "objects", ".", "all", "(", ")", ":", "recount", "=", "Message", ".", "objects", ".", "filter", "(", "thread", "=", "thread", ")", ".", "count", "(", ")", "if", "thread", ".", "number_of_messages", "!=", "recount", ":", "thread", ".", "number_of_messages", "=", "recount", "thread", ".", "save", "(", ")", "threads_changed", "+=", "1", "dates_changed", "=", "0", "for", "thread", "in", "Thread", ".", "objects", ".", "all", "(", ")", ":", "if", "thread", ".", "change_date", "!=", "thread", ".", "message_set", ".", "latest", "(", "'post_date'", ")", ".", "post_date", ":", "thread", ".", "change_date", "=", "thread", ".", "message_set", ".", "latest", "(", "'post_date'", ")", ".", "post_date", "thread", ".", "save", "(", ")", "dates_changed", "+=", "1", "messages", ".", "add_message", "(", "request", ",", "messages", ".", "SUCCESS", ",", "MESSAGES", "[", "'RECOUNTED'", "]", ".", "format", "(", "requests_changed", "=", "requests_changed", ",", "request_count", "=", "Request", ".", "objects", ".", "all", "(", ")", ".", "count", "(", ")", ",", "threads_changed", "=", "threads_changed", ",", "thread_count", "=", "Thread", ".", "objects", ".", "all", "(", ")", ".", "count", "(", ")", ",", "dates_changed", "=", "dates_changed", ",", ")", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'utilities'", ")", ")" ]
Recount number_of_messages for all threads and number_of_responses for all requests. Also set the change_date for every thread to the post_date of the latest message associated with that thread.
[ "Recount", "number_of_messages", "for", "all", "threads", "and", "number_of_responses", "for", "all", "requests", ".", "Also", "set", "the", "change_date", "for", "every", "thread", "to", "the", "post_date", "of", "the", "latest", "message", "associated", "with", "that", "thread", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L733-L766
247,204
knagra/farnsworth
base/views.py
archives_view
def archives_view(request): """ View of the archives page. """ page_name = "Archives" nodes, render_list = [], [] for add_context_str in settings.BASE_ARCHIVE_FUNCTIONS: module, fun = add_context_str.rsplit(".", 1) add_context_fun = getattr(import_module(module), fun) # add_context should return list of (title, url icon, number) node_lst, icon_list = add_context_fun(request) nodes += node_lst render_list += icon_list return render_to_response('archives.html', { "page_name": page_name, "render_list": render_list, "nodes": nodes, }, context_instance=RequestContext(request))
python
def archives_view(request): """ View of the archives page. """ page_name = "Archives" nodes, render_list = [], [] for add_context_str in settings.BASE_ARCHIVE_FUNCTIONS: module, fun = add_context_str.rsplit(".", 1) add_context_fun = getattr(import_module(module), fun) # add_context should return list of (title, url icon, number) node_lst, icon_list = add_context_fun(request) nodes += node_lst render_list += icon_list return render_to_response('archives.html', { "page_name": page_name, "render_list": render_list, "nodes": nodes, }, context_instance=RequestContext(request))
[ "def", "archives_view", "(", "request", ")", ":", "page_name", "=", "\"Archives\"", "nodes", ",", "render_list", "=", "[", "]", ",", "[", "]", "for", "add_context_str", "in", "settings", ".", "BASE_ARCHIVE_FUNCTIONS", ":", "module", ",", "fun", "=", "add_context_str", ".", "rsplit", "(", "\".\"", ",", "1", ")", "add_context_fun", "=", "getattr", "(", "import_module", "(", "module", ")", ",", "fun", ")", "# add_context should return list of (title, url icon, number)", "node_lst", ",", "icon_list", "=", "add_context_fun", "(", "request", ")", "nodes", "+=", "node_lst", "render_list", "+=", "icon_list", "return", "render_to_response", "(", "'archives.html'", ",", "{", "\"page_name\"", ":", "page_name", ",", "\"render_list\"", ":", "render_list", ",", "\"nodes\"", ":", "nodes", ",", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
View of the archives page.
[ "View", "of", "the", "archives", "page", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L785-L801
247,205
kderynski/blade-netconf-python-client
bnclient/conn.py
bnc_conn.connect
def connect(self): if self._sStatus != 'opened': print "Netconf Connection: Invalid Status, Could not connect to %s:%s" % (self._sHost, self._uPort) sys.exit() # establish ssh connection if self._sType == 'ssh': # setup transport connection base on socket self._hSsh = paramiko.Transport(self._iSock) try: self._hSsh.start_client() except paramiko.SSHException: print 'Netconf Connection: Connect negotiation failed' self._iSock.close() sys.exit() except: print 'Netconf Connection: Connect failed' try: self._iSock.close() except: pass sys.exit() # auth check if self._sPswd != '': try: self._hSsh.auth_password(self._sUser, self._sPswd) except: print "Netconf Connection: Auth SSH username/password fail" self._iSock.close() sys.exit() # open channel for netconf ssh subsystem try: self._hSshChn = self._hSsh.open_session() self._hSshChn.settimeout(5) self._hSshChn.set_name("netconf") self._hSshChn.invoke_subsystem("netconf") self._hSshChn.setblocking(1) except: print "Netconf Connection: Open SSH Netconf SubSystem fail" self._iSock.close() sys.exit() else: print "Netconf Connection: Unsupport Connection Type, Could not connect to %s:%s" % (self._sHost, self._uPort) sys.exit() self._sStatus = 'connected' """ end of function connect """
python
def connect(self): if self._sStatus != 'opened': print "Netconf Connection: Invalid Status, Could not connect to %s:%s" % (self._sHost, self._uPort) sys.exit() # establish ssh connection if self._sType == 'ssh': # setup transport connection base on socket self._hSsh = paramiko.Transport(self._iSock) try: self._hSsh.start_client() except paramiko.SSHException: print 'Netconf Connection: Connect negotiation failed' self._iSock.close() sys.exit() except: print 'Netconf Connection: Connect failed' try: self._iSock.close() except: pass sys.exit() # auth check if self._sPswd != '': try: self._hSsh.auth_password(self._sUser, self._sPswd) except: print "Netconf Connection: Auth SSH username/password fail" self._iSock.close() sys.exit() # open channel for netconf ssh subsystem try: self._hSshChn = self._hSsh.open_session() self._hSshChn.settimeout(5) self._hSshChn.set_name("netconf") self._hSshChn.invoke_subsystem("netconf") self._hSshChn.setblocking(1) except: print "Netconf Connection: Open SSH Netconf SubSystem fail" self._iSock.close() sys.exit() else: print "Netconf Connection: Unsupport Connection Type, Could not connect to %s:%s" % (self._sHost, self._uPort) sys.exit() self._sStatus = 'connected' """ end of function connect """
[ "def", "connect", "(", "self", ")", ":", "if", "self", ".", "_sStatus", "!=", "'opened'", ":", "print", "\"Netconf Connection: Invalid Status, Could not connect to %s:%s\"", "%", "(", "self", ".", "_sHost", ",", "self", ".", "_uPort", ")", "sys", ".", "exit", "(", ")", "# establish ssh connection", "if", "self", ".", "_sType", "==", "'ssh'", ":", "# setup transport connection base on socket", "self", ".", "_hSsh", "=", "paramiko", ".", "Transport", "(", "self", ".", "_iSock", ")", "try", ":", "self", ".", "_hSsh", ".", "start_client", "(", ")", "except", "paramiko", ".", "SSHException", ":", "print", "'Netconf Connection: Connect negotiation failed'", "self", ".", "_iSock", ".", "close", "(", ")", "sys", ".", "exit", "(", ")", "except", ":", "print", "'Netconf Connection: Connect failed'", "try", ":", "self", ".", "_iSock", ".", "close", "(", ")", "except", ":", "pass", "sys", ".", "exit", "(", ")", "# auth check", "if", "self", ".", "_sPswd", "!=", "''", ":", "try", ":", "self", ".", "_hSsh", ".", "auth_password", "(", "self", ".", "_sUser", ",", "self", ".", "_sPswd", ")", "except", ":", "print", "\"Netconf Connection: Auth SSH username/password fail\"", "self", ".", "_iSock", ".", "close", "(", ")", "sys", ".", "exit", "(", ")", "# open channel for netconf ssh subsystem", "try", ":", "self", ".", "_hSshChn", "=", "self", ".", "_hSsh", ".", "open_session", "(", ")", "self", ".", "_hSshChn", ".", "settimeout", "(", "5", ")", "self", ".", "_hSshChn", ".", "set_name", "(", "\"netconf\"", ")", "self", ".", "_hSshChn", ".", "invoke_subsystem", "(", "\"netconf\"", ")", "self", ".", "_hSshChn", ".", "setblocking", "(", "1", ")", "except", ":", "print", "\"Netconf Connection: Open SSH Netconf SubSystem fail\"", "self", ".", "_iSock", ".", "close", "(", ")", "sys", ".", "exit", "(", ")", "else", ":", "print", "\"Netconf Connection: Unsupport Connection Type, Could not connect to %s:%s\"", "%", "(", "self", ".", "_sHost", ",", "self", ".", "_uPort", ")", "sys", ".", "exit", "(", ")", "self", ".", "_sStatus", "=", "'connected'" ]
end of function connect
[ "end", "of", "function", "connect" ]
87396921a1c75f1093adf4bb7b13428ee368b2b7
https://github.com/kderynski/blade-netconf-python-client/blob/87396921a1c75f1093adf4bb7b13428ee368b2b7/bnclient/conn.py#L91-L137
247,206
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/autoparser/generator.py
_index_idiom
def _index_idiom(el_name, index, alt=None): """ Generate string where `el_name` is indexed by `index` if there are enough items or `alt` is returned. Args: el_name (str): Name of the `container` which is indexed. index (int): Index of the item you want to obtain from container. alt (whatever, default None): Alternative value. Returns: str: Python code. Live example:: >>> import generator as g >>> print g._index_idiom("xex", 0) # pick element from list xex = xex[0] if xex else None >>> print g._index_idiom("xex", 1, "something") # pick element from list xex = xex[1] if len(xex) - 1 >= 1 else 'something' """ el_index = "%s[%d]" % (el_name, index) if index == 0: cond = "%s" % el_name else: cond = "len(%s) - 1 >= %d" % (el_name, index) output = IND + "# pick element from list\n" return output + IND + "%s = %s if %s else %s\n\n" % ( el_name, el_index, cond, repr(alt) )
python
def _index_idiom(el_name, index, alt=None): """ Generate string where `el_name` is indexed by `index` if there are enough items or `alt` is returned. Args: el_name (str): Name of the `container` which is indexed. index (int): Index of the item you want to obtain from container. alt (whatever, default None): Alternative value. Returns: str: Python code. Live example:: >>> import generator as g >>> print g._index_idiom("xex", 0) # pick element from list xex = xex[0] if xex else None >>> print g._index_idiom("xex", 1, "something") # pick element from list xex = xex[1] if len(xex) - 1 >= 1 else 'something' """ el_index = "%s[%d]" % (el_name, index) if index == 0: cond = "%s" % el_name else: cond = "len(%s) - 1 >= %d" % (el_name, index) output = IND + "# pick element from list\n" return output + IND + "%s = %s if %s else %s\n\n" % ( el_name, el_index, cond, repr(alt) )
[ "def", "_index_idiom", "(", "el_name", ",", "index", ",", "alt", "=", "None", ")", ":", "el_index", "=", "\"%s[%d]\"", "%", "(", "el_name", ",", "index", ")", "if", "index", "==", "0", ":", "cond", "=", "\"%s\"", "%", "el_name", "else", ":", "cond", "=", "\"len(%s) - 1 >= %d\"", "%", "(", "el_name", ",", "index", ")", "output", "=", "IND", "+", "\"# pick element from list\\n\"", "return", "output", "+", "IND", "+", "\"%s = %s if %s else %s\\n\\n\"", "%", "(", "el_name", ",", "el_index", ",", "cond", ",", "repr", "(", "alt", ")", ")" ]
Generate string where `el_name` is indexed by `index` if there are enough items or `alt` is returned. Args: el_name (str): Name of the `container` which is indexed. index (int): Index of the item you want to obtain from container. alt (whatever, default None): Alternative value. Returns: str: Python code. Live example:: >>> import generator as g >>> print g._index_idiom("xex", 0) # pick element from list xex = xex[0] if xex else None >>> print g._index_idiom("xex", 1, "something") # pick element from list xex = xex[1] if len(xex) - 1 >= 1 else 'something'
[ "Generate", "string", "where", "el_name", "is", "indexed", "by", "index", "if", "there", "are", "enough", "items", "or", "alt", "is", "returned", "." ]
38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/generator.py#L23-L59
247,207
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/autoparser/generator.py
_required_idiom
def _required_idiom(tag_name, index, notfoundmsg): """ Generate code, which make sure that `tag_name` has enoug items. Args: tag_name (str): Name of the container. index (int): Index of the item you want to obtain from container. notfoundmsg (str): Raise :class:`.UserWarning` with debug data and following message. Returns: str: Python code. """ cond = "" if index > 0: cond = " or len(el) - 1 < %d" % index tag_name = str(tag_name) output = IND + "if not el%s:\n" % cond output += IND + IND + "raise UserWarning(\n" output += IND + IND + IND + "%s +\n" % repr(notfoundmsg.strip() + "\n") output += IND + IND + IND + repr("Tag name: " + tag_name) + " + '\\n' +\n" output += IND + IND + IND + "'El:' + str(el) + '\\n' +\n" output += IND + IND + IND + "'Dom:' + str(dom)\n" output += IND + IND + ")\n\n" return output + IND + "el = el[%d]\n\n" % index
python
def _required_idiom(tag_name, index, notfoundmsg): """ Generate code, which make sure that `tag_name` has enoug items. Args: tag_name (str): Name of the container. index (int): Index of the item you want to obtain from container. notfoundmsg (str): Raise :class:`.UserWarning` with debug data and following message. Returns: str: Python code. """ cond = "" if index > 0: cond = " or len(el) - 1 < %d" % index tag_name = str(tag_name) output = IND + "if not el%s:\n" % cond output += IND + IND + "raise UserWarning(\n" output += IND + IND + IND + "%s +\n" % repr(notfoundmsg.strip() + "\n") output += IND + IND + IND + repr("Tag name: " + tag_name) + " + '\\n' +\n" output += IND + IND + IND + "'El:' + str(el) + '\\n' +\n" output += IND + IND + IND + "'Dom:' + str(dom)\n" output += IND + IND + ")\n\n" return output + IND + "el = el[%d]\n\n" % index
[ "def", "_required_idiom", "(", "tag_name", ",", "index", ",", "notfoundmsg", ")", ":", "cond", "=", "\"\"", "if", "index", ">", "0", ":", "cond", "=", "\" or len(el) - 1 < %d\"", "%", "index", "tag_name", "=", "str", "(", "tag_name", ")", "output", "=", "IND", "+", "\"if not el%s:\\n\"", "%", "cond", "output", "+=", "IND", "+", "IND", "+", "\"raise UserWarning(\\n\"", "output", "+=", "IND", "+", "IND", "+", "IND", "+", "\"%s +\\n\"", "%", "repr", "(", "notfoundmsg", ".", "strip", "(", ")", "+", "\"\\n\"", ")", "output", "+=", "IND", "+", "IND", "+", "IND", "+", "repr", "(", "\"Tag name: \"", "+", "tag_name", ")", "+", "\" + '\\\\n' +\\n\"", "output", "+=", "IND", "+", "IND", "+", "IND", "+", "\"'El:' + str(el) + '\\\\n' +\\n\"", "output", "+=", "IND", "+", "IND", "+", "IND", "+", "\"'Dom:' + str(dom)\\n\"", "output", "+=", "IND", "+", "IND", "+", "\")\\n\\n\"", "return", "output", "+", "IND", "+", "\"el = el[%d]\\n\\n\"", "%", "index" ]
Generate code, which make sure that `tag_name` has enoug items. Args: tag_name (str): Name of the container. index (int): Index of the item you want to obtain from container. notfoundmsg (str): Raise :class:`.UserWarning` with debug data and following message. Returns: str: Python code.
[ "Generate", "code", "which", "make", "sure", "that", "tag_name", "has", "enoug", "items", "." ]
38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/generator.py#L62-L89
247,208
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/autoparser/generator.py
_neigh_template
def _neigh_template(parameters, index, left=True, required=False, notfoundmsg=None): """ Generate neighbour matching call for HTMLElement, which returns only elements with required neighbours. Args: parameters (list): List of parameters for ``.match()``. index (int): Index of the item you want to get from ``.match()`` call. left (bool, default True): Look for neigbour in the left side of el. required (bool, default False): Use :func:`_required_idiom` to returned data. notfoundmsg (str, default None): Message which will be used for :func:`_required_idiom` if the item is not found. Returns: str: Python code. """ fn_string = "has_neigh(%s, left=%s)" % ( repr(parameters.fn_params)[1:-1], repr(left) ) output = IND + "el = dom.find(\n" output += IND + IND + "%s,\n" % repr(parameters.tag_name) if parameters.params: output += IND + IND + "%s,\n" % repr(parameters.params) output += IND + IND + "fn=%s\n" % fn_string output += IND + ")\n\n" if required: return output + _required_idiom( parameters.fn_params[0], index, notfoundmsg ) return output + _index_idiom("el", index)
python
def _neigh_template(parameters, index, left=True, required=False, notfoundmsg=None): """ Generate neighbour matching call for HTMLElement, which returns only elements with required neighbours. Args: parameters (list): List of parameters for ``.match()``. index (int): Index of the item you want to get from ``.match()`` call. left (bool, default True): Look for neigbour in the left side of el. required (bool, default False): Use :func:`_required_idiom` to returned data. notfoundmsg (str, default None): Message which will be used for :func:`_required_idiom` if the item is not found. Returns: str: Python code. """ fn_string = "has_neigh(%s, left=%s)" % ( repr(parameters.fn_params)[1:-1], repr(left) ) output = IND + "el = dom.find(\n" output += IND + IND + "%s,\n" % repr(parameters.tag_name) if parameters.params: output += IND + IND + "%s,\n" % repr(parameters.params) output += IND + IND + "fn=%s\n" % fn_string output += IND + ")\n\n" if required: return output + _required_idiom( parameters.fn_params[0], index, notfoundmsg ) return output + _index_idiom("el", index)
[ "def", "_neigh_template", "(", "parameters", ",", "index", ",", "left", "=", "True", ",", "required", "=", "False", ",", "notfoundmsg", "=", "None", ")", ":", "fn_string", "=", "\"has_neigh(%s, left=%s)\"", "%", "(", "repr", "(", "parameters", ".", "fn_params", ")", "[", "1", ":", "-", "1", "]", ",", "repr", "(", "left", ")", ")", "output", "=", "IND", "+", "\"el = dom.find(\\n\"", "output", "+=", "IND", "+", "IND", "+", "\"%s,\\n\"", "%", "repr", "(", "parameters", ".", "tag_name", ")", "if", "parameters", ".", "params", ":", "output", "+=", "IND", "+", "IND", "+", "\"%s,\\n\"", "%", "repr", "(", "parameters", ".", "params", ")", "output", "+=", "IND", "+", "IND", "+", "\"fn=%s\\n\"", "%", "fn_string", "output", "+=", "IND", "+", "\")\\n\\n\"", "if", "required", ":", "return", "output", "+", "_required_idiom", "(", "parameters", ".", "fn_params", "[", "0", "]", ",", "index", ",", "notfoundmsg", ")", "return", "output", "+", "_index_idiom", "(", "\"el\"", ",", "index", ")" ]
Generate neighbour matching call for HTMLElement, which returns only elements with required neighbours. Args: parameters (list): List of parameters for ``.match()``. index (int): Index of the item you want to get from ``.match()`` call. left (bool, default True): Look for neigbour in the left side of el. required (bool, default False): Use :func:`_required_idiom` to returned data. notfoundmsg (str, default None): Message which will be used for :func:`_required_idiom` if the item is not found. Returns: str: Python code.
[ "Generate", "neighbour", "matching", "call", "for", "HTMLElement", "which", "returns", "only", "elements", "with", "required", "neighbours", "." ]
38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/generator.py#L188-L227
247,209
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/autoparser/generator.py
_generate_parser
def _generate_parser(name, path, required=False, notfoundmsg=None): """ Generate parser named `name` for given `path`. Args: name (str): Basename for the parsing function (see :func:`_get_parser_name` for details). path (obj): :class:`.PathCall` or :class:`.Chained` instance. required (bool, default False): Use :func:`_required_idiom` to returned data. notfoundmsg (str, default None): Message which will be used for :func:`_required_idiom` if the item is not found. Returns: str: Python code for parsing `path`. """ output = "def %s(dom):\n" % _get_parser_name(name) dom = True # used specifically in _wfind_template parser_table = { "find": lambda path: _find_template(path.params, path.index, required, notfoundmsg), "wfind": lambda path: _wfind_template( dom, path.params, path.index, required, notfoundmsg ), "match": lambda path: _match_template(path.params, path.index, required, notfoundmsg), "left_neighbour_tag": lambda path: _neigh_template( path.params, path.index, True, required, notfoundmsg ), "right_neighbour_tag": lambda path: _neigh_template( path.params, path.index, False, required, notfoundmsg ), } if isinstance(path, path_patterns.PathCall): output += parser_table[path.call_type](path) elif isinstance(path, path_patterns.Chained): for path in path.chain: output += parser_table[path.call_type](path) dom = False else: raise UserWarning( "Unknown type of path parameters! (%s)" % str(path) ) output += IND + "return el\n" output += "\n\n" return output
python
def _generate_parser(name, path, required=False, notfoundmsg=None): """ Generate parser named `name` for given `path`. Args: name (str): Basename for the parsing function (see :func:`_get_parser_name` for details). path (obj): :class:`.PathCall` or :class:`.Chained` instance. required (bool, default False): Use :func:`_required_idiom` to returned data. notfoundmsg (str, default None): Message which will be used for :func:`_required_idiom` if the item is not found. Returns: str: Python code for parsing `path`. """ output = "def %s(dom):\n" % _get_parser_name(name) dom = True # used specifically in _wfind_template parser_table = { "find": lambda path: _find_template(path.params, path.index, required, notfoundmsg), "wfind": lambda path: _wfind_template( dom, path.params, path.index, required, notfoundmsg ), "match": lambda path: _match_template(path.params, path.index, required, notfoundmsg), "left_neighbour_tag": lambda path: _neigh_template( path.params, path.index, True, required, notfoundmsg ), "right_neighbour_tag": lambda path: _neigh_template( path.params, path.index, False, required, notfoundmsg ), } if isinstance(path, path_patterns.PathCall): output += parser_table[path.call_type](path) elif isinstance(path, path_patterns.Chained): for path in path.chain: output += parser_table[path.call_type](path) dom = False else: raise UserWarning( "Unknown type of path parameters! (%s)" % str(path) ) output += IND + "return el\n" output += "\n\n" return output
[ "def", "_generate_parser", "(", "name", ",", "path", ",", "required", "=", "False", ",", "notfoundmsg", "=", "None", ")", ":", "output", "=", "\"def %s(dom):\\n\"", "%", "_get_parser_name", "(", "name", ")", "dom", "=", "True", "# used specifically in _wfind_template", "parser_table", "=", "{", "\"find\"", ":", "lambda", "path", ":", "_find_template", "(", "path", ".", "params", ",", "path", ".", "index", ",", "required", ",", "notfoundmsg", ")", ",", "\"wfind\"", ":", "lambda", "path", ":", "_wfind_template", "(", "dom", ",", "path", ".", "params", ",", "path", ".", "index", ",", "required", ",", "notfoundmsg", ")", ",", "\"match\"", ":", "lambda", "path", ":", "_match_template", "(", "path", ".", "params", ",", "path", ".", "index", ",", "required", ",", "notfoundmsg", ")", ",", "\"left_neighbour_tag\"", ":", "lambda", "path", ":", "_neigh_template", "(", "path", ".", "params", ",", "path", ".", "index", ",", "True", ",", "required", ",", "notfoundmsg", ")", ",", "\"right_neighbour_tag\"", ":", "lambda", "path", ":", "_neigh_template", "(", "path", ".", "params", ",", "path", ".", "index", ",", "False", ",", "required", ",", "notfoundmsg", ")", ",", "}", "if", "isinstance", "(", "path", ",", "path_patterns", ".", "PathCall", ")", ":", "output", "+=", "parser_table", "[", "path", ".", "call_type", "]", "(", "path", ")", "elif", "isinstance", "(", "path", ",", "path_patterns", ".", "Chained", ")", ":", "for", "path", "in", "path", ".", "chain", ":", "output", "+=", "parser_table", "[", "path", ".", "call_type", "]", "(", "path", ")", "dom", "=", "False", "else", ":", "raise", "UserWarning", "(", "\"Unknown type of path parameters! (%s)\"", "%", "str", "(", "path", ")", ")", "output", "+=", "IND", "+", "\"return el\\n\"", "output", "+=", "\"\\n\\n\"", "return", "output" ]
Generate parser named `name` for given `path`. Args: name (str): Basename for the parsing function (see :func:`_get_parser_name` for details). path (obj): :class:`.PathCall` or :class:`.Chained` instance. required (bool, default False): Use :func:`_required_idiom` to returned data. notfoundmsg (str, default None): Message which will be used for :func:`_required_idiom` if the item is not found. Returns: str: Python code for parsing `path`.
[ "Generate", "parser", "named", "name", "for", "given", "path", "." ]
38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/generator.py#L245-L309
247,210
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/autoparser/generator.py
generate_parsers
def generate_parsers(config, paths): """ Generate parser for all `paths`. Args: config (dict): Original configuration dictionary used to get matches for unittests. See :mod:`~harvester.autoparser.conf_reader` for details. paths (dict): Output from :func:`.select_best_paths`. Returns: str: Python code containing all parsers for `paths`. """ output = """#! /usr/bin/env python # -*- coding: utf-8 -*- # # Interpreter version: python 2.7 # # HTML parser generated by Autoparser # (https://github.com/edeposit/edeposit.amqp.harvester) # import os import os.path import httpkie import dhtmlparser # Utilities """ # add source of neighbour picking functions from utils.py output += inspect.getsource(conf_reader._get_source) + "\n\n" output += inspect.getsource(utils._get_encoding) + "\n\n" output += inspect.getsource(utils.handle_encodnig) + "\n\n" output += inspect.getsource(utils.is_equal_tag) + "\n\n" output += inspect.getsource(utils.has_neigh) + "\n\n" output += "# Generated parsers\n" for name, path in paths.items(): path = path[0] # pick path with highest priority required = config[0]["vars"][name].get("required", False) notfoundmsg = config[0]["vars"][name].get("notfoundmsg", "") output += _generate_parser(name, path, required, notfoundmsg) output += "# Unittest\n" output += _unittest_template(config) output += "# Run tests of the parser\n" output += "if __name__ == '__main__':\n" output += IND + "test_parsers()" return output
python
def generate_parsers(config, paths): """ Generate parser for all `paths`. Args: config (dict): Original configuration dictionary used to get matches for unittests. See :mod:`~harvester.autoparser.conf_reader` for details. paths (dict): Output from :func:`.select_best_paths`. Returns: str: Python code containing all parsers for `paths`. """ output = """#! /usr/bin/env python # -*- coding: utf-8 -*- # # Interpreter version: python 2.7 # # HTML parser generated by Autoparser # (https://github.com/edeposit/edeposit.amqp.harvester) # import os import os.path import httpkie import dhtmlparser # Utilities """ # add source of neighbour picking functions from utils.py output += inspect.getsource(conf_reader._get_source) + "\n\n" output += inspect.getsource(utils._get_encoding) + "\n\n" output += inspect.getsource(utils.handle_encodnig) + "\n\n" output += inspect.getsource(utils.is_equal_tag) + "\n\n" output += inspect.getsource(utils.has_neigh) + "\n\n" output += "# Generated parsers\n" for name, path in paths.items(): path = path[0] # pick path with highest priority required = config[0]["vars"][name].get("required", False) notfoundmsg = config[0]["vars"][name].get("notfoundmsg", "") output += _generate_parser(name, path, required, notfoundmsg) output += "# Unittest\n" output += _unittest_template(config) output += "# Run tests of the parser\n" output += "if __name__ == '__main__':\n" output += IND + "test_parsers()" return output
[ "def", "generate_parsers", "(", "config", ",", "paths", ")", ":", "output", "=", "\"\"\"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Interpreter version: python 2.7\n#\n# HTML parser generated by Autoparser\n# (https://github.com/edeposit/edeposit.amqp.harvester)\n#\nimport os\nimport os.path\n\nimport httpkie\nimport dhtmlparser\n\n\n# Utilities\n\"\"\"", "# add source of neighbour picking functions from utils.py", "output", "+=", "inspect", ".", "getsource", "(", "conf_reader", ".", "_get_source", ")", "+", "\"\\n\\n\"", "output", "+=", "inspect", ".", "getsource", "(", "utils", ".", "_get_encoding", ")", "+", "\"\\n\\n\"", "output", "+=", "inspect", ".", "getsource", "(", "utils", ".", "handle_encodnig", ")", "+", "\"\\n\\n\"", "output", "+=", "inspect", ".", "getsource", "(", "utils", ".", "is_equal_tag", ")", "+", "\"\\n\\n\"", "output", "+=", "inspect", ".", "getsource", "(", "utils", ".", "has_neigh", ")", "+", "\"\\n\\n\"", "output", "+=", "\"# Generated parsers\\n\"", "for", "name", ",", "path", "in", "paths", ".", "items", "(", ")", ":", "path", "=", "path", "[", "0", "]", "# pick path with highest priority", "required", "=", "config", "[", "0", "]", "[", "\"vars\"", "]", "[", "name", "]", ".", "get", "(", "\"required\"", ",", "False", ")", "notfoundmsg", "=", "config", "[", "0", "]", "[", "\"vars\"", "]", "[", "name", "]", ".", "get", "(", "\"notfoundmsg\"", ",", "\"\"", ")", "output", "+=", "_generate_parser", "(", "name", ",", "path", ",", "required", ",", "notfoundmsg", ")", "output", "+=", "\"# Unittest\\n\"", "output", "+=", "_unittest_template", "(", "config", ")", "output", "+=", "\"# Run tests of the parser\\n\"", "output", "+=", "\"if __name__ == '__main__':\\n\"", "output", "+=", "IND", "+", "\"test_parsers()\"", "return", "output" ]
Generate parser for all `paths`. Args: config (dict): Original configuration dictionary used to get matches for unittests. See :mod:`~harvester.autoparser.conf_reader` for details. paths (dict): Output from :func:`.select_best_paths`. Returns: str: Python code containing all parsers for `paths`.
[ "Generate", "parser", "for", "all", "paths", "." ]
38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/generator.py#L357-L410
247,211
nickfrostatx/walls
walls.py
load_config
def load_config(path): """Load the config value from various arguments.""" config = ConfigParser() if len(config.read(path)) == 0: stderr_and_exit("Couldn't load config {0}\n".format(path)) if not config.has_section('walls'): stderr_and_exit('Config missing [walls] section.\n') # Print out all of the missing keys keys = ['api_key', 'api_secret', 'tags', 'image_dir', 'width', 'height'] for key in set(keys): if config.has_option('walls', key): keys.remove(key) if keys: stderr_and_exit("Missing config keys: '{0}'\n" .format("', '".join(keys))) # Parse integer values int_keys = ['width', 'height'] for key in set(int_keys): try: config.getint('walls', key) int_keys.remove(key) except ValueError: pass if int_keys: stderr_and_exit("The following must be integers: '{0}'\n" .format("', '".join(int_keys))) # Check destination directory path = os.path.expanduser(config.get('walls', 'image_dir')) if not os.path.isdir(path): stderr_and_exit('The directory {0} does not exist.\n' .format(config.get('walls', 'image_dir'))) return config
python
def load_config(path): """Load the config value from various arguments.""" config = ConfigParser() if len(config.read(path)) == 0: stderr_and_exit("Couldn't load config {0}\n".format(path)) if not config.has_section('walls'): stderr_and_exit('Config missing [walls] section.\n') # Print out all of the missing keys keys = ['api_key', 'api_secret', 'tags', 'image_dir', 'width', 'height'] for key in set(keys): if config.has_option('walls', key): keys.remove(key) if keys: stderr_and_exit("Missing config keys: '{0}'\n" .format("', '".join(keys))) # Parse integer values int_keys = ['width', 'height'] for key in set(int_keys): try: config.getint('walls', key) int_keys.remove(key) except ValueError: pass if int_keys: stderr_and_exit("The following must be integers: '{0}'\n" .format("', '".join(int_keys))) # Check destination directory path = os.path.expanduser(config.get('walls', 'image_dir')) if not os.path.isdir(path): stderr_and_exit('The directory {0} does not exist.\n' .format(config.get('walls', 'image_dir'))) return config
[ "def", "load_config", "(", "path", ")", ":", "config", "=", "ConfigParser", "(", ")", "if", "len", "(", "config", ".", "read", "(", "path", ")", ")", "==", "0", ":", "stderr_and_exit", "(", "\"Couldn't load config {0}\\n\"", ".", "format", "(", "path", ")", ")", "if", "not", "config", ".", "has_section", "(", "'walls'", ")", ":", "stderr_and_exit", "(", "'Config missing [walls] section.\\n'", ")", "# Print out all of the missing keys", "keys", "=", "[", "'api_key'", ",", "'api_secret'", ",", "'tags'", ",", "'image_dir'", ",", "'width'", ",", "'height'", "]", "for", "key", "in", "set", "(", "keys", ")", ":", "if", "config", ".", "has_option", "(", "'walls'", ",", "key", ")", ":", "keys", ".", "remove", "(", "key", ")", "if", "keys", ":", "stderr_and_exit", "(", "\"Missing config keys: '{0}'\\n\"", ".", "format", "(", "\"', '\"", ".", "join", "(", "keys", ")", ")", ")", "# Parse integer values", "int_keys", "=", "[", "'width'", ",", "'height'", "]", "for", "key", "in", "set", "(", "int_keys", ")", ":", "try", ":", "config", ".", "getint", "(", "'walls'", ",", "key", ")", "int_keys", ".", "remove", "(", "key", ")", "except", "ValueError", ":", "pass", "if", "int_keys", ":", "stderr_and_exit", "(", "\"The following must be integers: '{0}'\\n\"", ".", "format", "(", "\"', '\"", ".", "join", "(", "int_keys", ")", ")", ")", "# Check destination directory", "path", "=", "os", ".", "path", ".", "expanduser", "(", "config", ".", "get", "(", "'walls'", ",", "'image_dir'", ")", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "stderr_and_exit", "(", "'The directory {0} does not exist.\\n'", ".", "format", "(", "config", ".", "get", "(", "'walls'", ",", "'image_dir'", ")", ")", ")", "return", "config" ]
Load the config value from various arguments.
[ "Load", "the", "config", "value", "from", "various", "arguments", "." ]
866f33335cf410565d6e51fdcd880770e6d089b0
https://github.com/nickfrostatx/walls/blob/866f33335cf410565d6e51fdcd880770e6d089b0/walls.py#L34-L70
247,212
nickfrostatx/walls
walls.py
clear_dir
def clear_dir(path): """Empty out the image directory.""" for f in os.listdir(path): f_path = os.path.join(path, f) if os.path.isfile(f_path) or os.path.islink(f_path): os.unlink(f_path)
python
def clear_dir(path): """Empty out the image directory.""" for f in os.listdir(path): f_path = os.path.join(path, f) if os.path.isfile(f_path) or os.path.islink(f_path): os.unlink(f_path)
[ "def", "clear_dir", "(", "path", ")", ":", "for", "f", "in", "os", ".", "listdir", "(", "path", ")", ":", "f_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", "if", "os", ".", "path", ".", "isfile", "(", "f_path", ")", "or", "os", ".", "path", ".", "islink", "(", "f_path", ")", ":", "os", ".", "unlink", "(", "f_path", ")" ]
Empty out the image directory.
[ "Empty", "out", "the", "image", "directory", "." ]
866f33335cf410565d6e51fdcd880770e6d089b0
https://github.com/nickfrostatx/walls/blob/866f33335cf410565d6e51fdcd880770e6d089b0/walls.py#L73-L78
247,213
nickfrostatx/walls
walls.py
smallest_url
def smallest_url(flickr, pid, min_width, min_height): """Return the url of the smallest photo above the dimensions. If no such photo exists, return None. """ sizes = flickr.photos_getSizes(photo_id=pid, format='parsed-json') smallest_url = None smallest_area = None for size in sizes['sizes']['size']: width = int(size['width']) height = int(size['height']) # Enforce a minimum height and width if width >= min_width and height >= min_height: if not smallest_url or height * width < smallest_area: smallest_area = height * width smallest_url = size['source'] return smallest_url
python
def smallest_url(flickr, pid, min_width, min_height): """Return the url of the smallest photo above the dimensions. If no such photo exists, return None. """ sizes = flickr.photos_getSizes(photo_id=pid, format='parsed-json') smallest_url = None smallest_area = None for size in sizes['sizes']['size']: width = int(size['width']) height = int(size['height']) # Enforce a minimum height and width if width >= min_width and height >= min_height: if not smallest_url or height * width < smallest_area: smallest_area = height * width smallest_url = size['source'] return smallest_url
[ "def", "smallest_url", "(", "flickr", ",", "pid", ",", "min_width", ",", "min_height", ")", ":", "sizes", "=", "flickr", ".", "photos_getSizes", "(", "photo_id", "=", "pid", ",", "format", "=", "'parsed-json'", ")", "smallest_url", "=", "None", "smallest_area", "=", "None", "for", "size", "in", "sizes", "[", "'sizes'", "]", "[", "'size'", "]", ":", "width", "=", "int", "(", "size", "[", "'width'", "]", ")", "height", "=", "int", "(", "size", "[", "'height'", "]", ")", "# Enforce a minimum height and width", "if", "width", ">=", "min_width", "and", "height", ">=", "min_height", ":", "if", "not", "smallest_url", "or", "height", "*", "width", "<", "smallest_area", ":", "smallest_area", "=", "height", "*", "width", "smallest_url", "=", "size", "[", "'source'", "]", "return", "smallest_url" ]
Return the url of the smallest photo above the dimensions. If no such photo exists, return None.
[ "Return", "the", "url", "of", "the", "smallest", "photo", "above", "the", "dimensions", "." ]
866f33335cf410565d6e51fdcd880770e6d089b0
https://github.com/nickfrostatx/walls/blob/866f33335cf410565d6e51fdcd880770e6d089b0/walls.py#L81-L97
247,214
nickfrostatx/walls
walls.py
download
def download(url, dest): """Download the image to disk.""" path = os.path.join(dest, url.split('/')[-1]) r = requests.get(url, stream=True) r.raise_for_status() with open(path, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: f.write(chunk) return path
python
def download(url, dest): """Download the image to disk.""" path = os.path.join(dest, url.split('/')[-1]) r = requests.get(url, stream=True) r.raise_for_status() with open(path, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: f.write(chunk) return path
[ "def", "download", "(", "url", ",", "dest", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "dest", ",", "url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ")", "r", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "r", ".", "raise_for_status", "(", ")", "with", "open", "(", "path", ",", "'wb'", ")", "as", "f", ":", "for", "chunk", "in", "r", ".", "iter_content", "(", "chunk_size", "=", "1024", ")", ":", "if", "chunk", ":", "f", ".", "write", "(", "chunk", ")", "return", "path" ]
Download the image to disk.
[ "Download", "the", "image", "to", "disk", "." ]
866f33335cf410565d6e51fdcd880770e6d089b0
https://github.com/nickfrostatx/walls/blob/866f33335cf410565d6e51fdcd880770e6d089b0/walls.py#L100-L109
247,215
nickfrostatx/walls
walls.py
run
def run(config, clear_opt=False): """Find an image and download it.""" flickr = flickrapi.FlickrAPI(config.get('walls', 'api_key'), config.get('walls', 'api_secret')) width = config.getint('walls', 'width') height = config.getint('walls', 'height') # Clear out the destination dir if clear_opt: clear_dir(os.path.expanduser(config.get('walls', 'image_dir'))) # Find an image tags = config.get('walls', 'tags') for photo in flickr.walk(tags=tags, format='etree'): try: photo_url = smallest_url(flickr, photo.get('id'), width, height) if photo_url: break except (KeyError, ValueError, TypeError): stderr_and_exit('Unexpected data from Flickr.\n') else: stderr_and_exit('No matching photos found.\n') # Download the image dest = os.path.expanduser(config.get('walls', 'image_dir')) try: download(photo_url, dest) except IOError: stderr_and_exit('Error downloading image.\n')
python
def run(config, clear_opt=False): """Find an image and download it.""" flickr = flickrapi.FlickrAPI(config.get('walls', 'api_key'), config.get('walls', 'api_secret')) width = config.getint('walls', 'width') height = config.getint('walls', 'height') # Clear out the destination dir if clear_opt: clear_dir(os.path.expanduser(config.get('walls', 'image_dir'))) # Find an image tags = config.get('walls', 'tags') for photo in flickr.walk(tags=tags, format='etree'): try: photo_url = smallest_url(flickr, photo.get('id'), width, height) if photo_url: break except (KeyError, ValueError, TypeError): stderr_and_exit('Unexpected data from Flickr.\n') else: stderr_and_exit('No matching photos found.\n') # Download the image dest = os.path.expanduser(config.get('walls', 'image_dir')) try: download(photo_url, dest) except IOError: stderr_and_exit('Error downloading image.\n')
[ "def", "run", "(", "config", ",", "clear_opt", "=", "False", ")", ":", "flickr", "=", "flickrapi", ".", "FlickrAPI", "(", "config", ".", "get", "(", "'walls'", ",", "'api_key'", ")", ",", "config", ".", "get", "(", "'walls'", ",", "'api_secret'", ")", ")", "width", "=", "config", ".", "getint", "(", "'walls'", ",", "'width'", ")", "height", "=", "config", ".", "getint", "(", "'walls'", ",", "'height'", ")", "# Clear out the destination dir", "if", "clear_opt", ":", "clear_dir", "(", "os", ".", "path", ".", "expanduser", "(", "config", ".", "get", "(", "'walls'", ",", "'image_dir'", ")", ")", ")", "# Find an image", "tags", "=", "config", ".", "get", "(", "'walls'", ",", "'tags'", ")", "for", "photo", "in", "flickr", ".", "walk", "(", "tags", "=", "tags", ",", "format", "=", "'etree'", ")", ":", "try", ":", "photo_url", "=", "smallest_url", "(", "flickr", ",", "photo", ".", "get", "(", "'id'", ")", ",", "width", ",", "height", ")", "if", "photo_url", ":", "break", "except", "(", "KeyError", ",", "ValueError", ",", "TypeError", ")", ":", "stderr_and_exit", "(", "'Unexpected data from Flickr.\\n'", ")", "else", ":", "stderr_and_exit", "(", "'No matching photos found.\\n'", ")", "# Download the image", "dest", "=", "os", ".", "path", ".", "expanduser", "(", "config", ".", "get", "(", "'walls'", ",", "'image_dir'", ")", ")", "try", ":", "download", "(", "photo_url", ",", "dest", ")", "except", "IOError", ":", "stderr_and_exit", "(", "'Error downloading image.\\n'", ")" ]
Find an image and download it.
[ "Find", "an", "image", "and", "download", "it", "." ]
866f33335cf410565d6e51fdcd880770e6d089b0
https://github.com/nickfrostatx/walls/blob/866f33335cf410565d6e51fdcd880770e6d089b0/walls.py#L112-L140
247,216
nickfrostatx/walls
walls.py
main
def main(args=sys.argv): """Parse the arguments, and pass the config object on to run.""" # Don't make changes to sys.argv args = list(args) # Remove arg[0] args.pop(0) # Pop off the options clear_opt = False if '-c' in args: args.remove('-c') clear_opt = True elif '--clear' in args: args.remove('--clear') clear_opt = True if len(args) == 0: cfg_path = os.path.expanduser('~/.wallsrc') elif len(args) == 1: cfg_path = args[0] else: stderr_and_exit('Usage: walls [-c] [config_file]\n') config = load_config(cfg_path) run(config, clear_opt)
python
def main(args=sys.argv): """Parse the arguments, and pass the config object on to run.""" # Don't make changes to sys.argv args = list(args) # Remove arg[0] args.pop(0) # Pop off the options clear_opt = False if '-c' in args: args.remove('-c') clear_opt = True elif '--clear' in args: args.remove('--clear') clear_opt = True if len(args) == 0: cfg_path = os.path.expanduser('~/.wallsrc') elif len(args) == 1: cfg_path = args[0] else: stderr_and_exit('Usage: walls [-c] [config_file]\n') config = load_config(cfg_path) run(config, clear_opt)
[ "def", "main", "(", "args", "=", "sys", ".", "argv", ")", ":", "# Don't make changes to sys.argv", "args", "=", "list", "(", "args", ")", "# Remove arg[0]", "args", ".", "pop", "(", "0", ")", "# Pop off the options", "clear_opt", "=", "False", "if", "'-c'", "in", "args", ":", "args", ".", "remove", "(", "'-c'", ")", "clear_opt", "=", "True", "elif", "'--clear'", "in", "args", ":", "args", ".", "remove", "(", "'--clear'", ")", "clear_opt", "=", "True", "if", "len", "(", "args", ")", "==", "0", ":", "cfg_path", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.wallsrc'", ")", "elif", "len", "(", "args", ")", "==", "1", ":", "cfg_path", "=", "args", "[", "0", "]", "else", ":", "stderr_and_exit", "(", "'Usage: walls [-c] [config_file]\\n'", ")", "config", "=", "load_config", "(", "cfg_path", ")", "run", "(", "config", ",", "clear_opt", ")" ]
Parse the arguments, and pass the config object on to run.
[ "Parse", "the", "arguments", "and", "pass", "the", "config", "object", "on", "to", "run", "." ]
866f33335cf410565d6e51fdcd880770e6d089b0
https://github.com/nickfrostatx/walls/blob/866f33335cf410565d6e51fdcd880770e6d089b0/walls.py#L143-L169
247,217
kodexlab/reliure
reliure/offline.py
run
def run(pipeline, input_gen, options={}): """ Run a pipeline over a input generator >>> # if we have a simple component >>> from reliure.pipeline import Composable >>> @Composable ... def print_each(letters): ... for letter in letters: ... print(letter) ... yield letter >>> # that we want to run over a given input: >>> input = "abcde" >>> # we just have to do : >>> res = run(print_each, input) a b c d e it is also possible to run any reliure pipeline this way: >>> import string >>> pipeline = Composable(lambda letters: (l.upper() for l in letters)) | print_each >>> res = run(pipeline, input) A B C D E """ logger = logging.getLogger("reliure.run") t0 = time() res = [output for output in pipeline(input_gen, **options)] logger.info("Pipeline executed in %1.3f sec" % (time() - t0)) return res
python
def run(pipeline, input_gen, options={}): """ Run a pipeline over a input generator >>> # if we have a simple component >>> from reliure.pipeline import Composable >>> @Composable ... def print_each(letters): ... for letter in letters: ... print(letter) ... yield letter >>> # that we want to run over a given input: >>> input = "abcde" >>> # we just have to do : >>> res = run(print_each, input) a b c d e it is also possible to run any reliure pipeline this way: >>> import string >>> pipeline = Composable(lambda letters: (l.upper() for l in letters)) | print_each >>> res = run(pipeline, input) A B C D E """ logger = logging.getLogger("reliure.run") t0 = time() res = [output for output in pipeline(input_gen, **options)] logger.info("Pipeline executed in %1.3f sec" % (time() - t0)) return res
[ "def", "run", "(", "pipeline", ",", "input_gen", ",", "options", "=", "{", "}", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"reliure.run\"", ")", "t0", "=", "time", "(", ")", "res", "=", "[", "output", "for", "output", "in", "pipeline", "(", "input_gen", ",", "*", "*", "options", ")", "]", "logger", ".", "info", "(", "\"Pipeline executed in %1.3f sec\"", "%", "(", "time", "(", ")", "-", "t0", ")", ")", "return", "res" ]
Run a pipeline over a input generator >>> # if we have a simple component >>> from reliure.pipeline import Composable >>> @Composable ... def print_each(letters): ... for letter in letters: ... print(letter) ... yield letter >>> # that we want to run over a given input: >>> input = "abcde" >>> # we just have to do : >>> res = run(print_each, input) a b c d e it is also possible to run any reliure pipeline this way: >>> import string >>> pipeline = Composable(lambda letters: (l.upper() for l in letters)) | print_each >>> res = run(pipeline, input) A B C D E
[ "Run", "a", "pipeline", "over", "a", "input", "generator" ]
0450c7a9254c5c003162738458bbe0c49e777ba5
https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/offline.py#L11-L45
247,218
kodexlab/reliure
reliure/offline.py
run_parallel
def run_parallel(pipeline, input_gen, options={}, ncpu=4, chunksize=200): """ Run a pipeline in parallel over a input generator cutting it into small chunks. >>> # if we have a simple component >>> from reliure.pipeline import Composable >>> # that we want to run over a given input: >>> input = "abcde" >>> import string >>> pipeline = Composable(lambda letters: (l.upper() for l in letters)) >>> res = run_parallel(pipeline, input, ncpu=2, chunksize=2) >>> #Note: res should be equals to [['C', 'D'], ['A', 'B'], ['E']] >>> #but it seems that there is a bug with py.test and mp... """ t0 = time() #FIXME: there is a know issue when pipeline results are "big" object, the merge is bloking... to be investigate #TODO: add get_pipeline args to prodvide a fct to build the pipeline (in each worker) logger = logging.getLogger("reliure.run_parallel") jobs = [] results = [] Qdata = mp.JoinableQueue(ncpu*2) # input queue Qresult = mp.Queue() # result queue # ensure input_gen is realy an itertor not a list if hasattr(input_gen, "__len__"): input_gen = iter(input_gen) for wnum in range(ncpu): logger.debug("create worker #%s" % wnum) worker = mp.Process(target=_reliure_worker, args=(wnum, Qdata, Qresult, pipeline, options)) worker.start() jobs.append(worker) while True: # consume chunksize elements from input_gen chunk = tuple(islice(input_gen, chunksize)) if not len(chunk): break logger.info("send a chunk of %s elemets to a worker" % len(chunk)) Qdata.put(chunk) logger.info("all data has beed send to workers") # wait until all task are done Qdata.join() logger.debug("wait for workers...") for worker in jobs: worker.terminate() logger.debug("merge results") try: while not Qresult.empty(): logger.debug("result queue still have %d elements" % Qresult.qsize()) res = Qresult.get_nowait() results.append(res) except mp.Queue.Empty: logger.debug("result queue is empty") pass logger.info("Pipeline executed in %1.3f sec" % (time() - t0)) return results
python
def run_parallel(pipeline, input_gen, options={}, ncpu=4, chunksize=200): """ Run a pipeline in parallel over a input generator cutting it into small chunks. >>> # if we have a simple component >>> from reliure.pipeline import Composable >>> # that we want to run over a given input: >>> input = "abcde" >>> import string >>> pipeline = Composable(lambda letters: (l.upper() for l in letters)) >>> res = run_parallel(pipeline, input, ncpu=2, chunksize=2) >>> #Note: res should be equals to [['C', 'D'], ['A', 'B'], ['E']] >>> #but it seems that there is a bug with py.test and mp... """ t0 = time() #FIXME: there is a know issue when pipeline results are "big" object, the merge is bloking... to be investigate #TODO: add get_pipeline args to prodvide a fct to build the pipeline (in each worker) logger = logging.getLogger("reliure.run_parallel") jobs = [] results = [] Qdata = mp.JoinableQueue(ncpu*2) # input queue Qresult = mp.Queue() # result queue # ensure input_gen is realy an itertor not a list if hasattr(input_gen, "__len__"): input_gen = iter(input_gen) for wnum in range(ncpu): logger.debug("create worker #%s" % wnum) worker = mp.Process(target=_reliure_worker, args=(wnum, Qdata, Qresult, pipeline, options)) worker.start() jobs.append(worker) while True: # consume chunksize elements from input_gen chunk = tuple(islice(input_gen, chunksize)) if not len(chunk): break logger.info("send a chunk of %s elemets to a worker" % len(chunk)) Qdata.put(chunk) logger.info("all data has beed send to workers") # wait until all task are done Qdata.join() logger.debug("wait for workers...") for worker in jobs: worker.terminate() logger.debug("merge results") try: while not Qresult.empty(): logger.debug("result queue still have %d elements" % Qresult.qsize()) res = Qresult.get_nowait() results.append(res) except mp.Queue.Empty: logger.debug("result queue is empty") pass logger.info("Pipeline executed in %1.3f sec" % (time() - t0)) return results
[ "def", "run_parallel", "(", "pipeline", ",", "input_gen", ",", "options", "=", "{", "}", ",", "ncpu", "=", "4", ",", "chunksize", "=", "200", ")", ":", "t0", "=", "time", "(", ")", "#FIXME: there is a know issue when pipeline results are \"big\" object, the merge is bloking... to be investigate", "#TODO: add get_pipeline args to prodvide a fct to build the pipeline (in each worker)", "logger", "=", "logging", ".", "getLogger", "(", "\"reliure.run_parallel\"", ")", "jobs", "=", "[", "]", "results", "=", "[", "]", "Qdata", "=", "mp", ".", "JoinableQueue", "(", "ncpu", "*", "2", ")", "# input queue", "Qresult", "=", "mp", ".", "Queue", "(", ")", "# result queue", "# ensure input_gen is realy an itertor not a list", "if", "hasattr", "(", "input_gen", ",", "\"__len__\"", ")", ":", "input_gen", "=", "iter", "(", "input_gen", ")", "for", "wnum", "in", "range", "(", "ncpu", ")", ":", "logger", ".", "debug", "(", "\"create worker #%s\"", "%", "wnum", ")", "worker", "=", "mp", ".", "Process", "(", "target", "=", "_reliure_worker", ",", "args", "=", "(", "wnum", ",", "Qdata", ",", "Qresult", ",", "pipeline", ",", "options", ")", ")", "worker", ".", "start", "(", ")", "jobs", ".", "append", "(", "worker", ")", "while", "True", ":", "# consume chunksize elements from input_gen", "chunk", "=", "tuple", "(", "islice", "(", "input_gen", ",", "chunksize", ")", ")", "if", "not", "len", "(", "chunk", ")", ":", "break", "logger", ".", "info", "(", "\"send a chunk of %s elemets to a worker\"", "%", "len", "(", "chunk", ")", ")", "Qdata", ".", "put", "(", "chunk", ")", "logger", ".", "info", "(", "\"all data has beed send to workers\"", ")", "# wait until all task are done", "Qdata", ".", "join", "(", ")", "logger", ".", "debug", "(", "\"wait for workers...\"", ")", "for", "worker", "in", "jobs", ":", "worker", ".", "terminate", "(", ")", "logger", ".", "debug", "(", "\"merge results\"", ")", "try", ":", "while", "not", "Qresult", ".", "empty", "(", ")", ":", "logger", ".", "debug", "(", "\"result queue still have %d elements\"", "%", "Qresult", ".", "qsize", "(", ")", ")", "res", "=", "Qresult", ".", "get_nowait", "(", ")", "results", ".", "append", "(", "res", ")", "except", "mp", ".", "Queue", ".", "Empty", ":", "logger", ".", "debug", "(", "\"result queue is empty\"", ")", "pass", "logger", ".", "info", "(", "\"Pipeline executed in %1.3f sec\"", "%", "(", "time", "(", ")", "-", "t0", ")", ")", "return", "results" ]
Run a pipeline in parallel over a input generator cutting it into small chunks. >>> # if we have a simple component >>> from reliure.pipeline import Composable >>> # that we want to run over a given input: >>> input = "abcde" >>> import string >>> pipeline = Composable(lambda letters: (l.upper() for l in letters)) >>> res = run_parallel(pipeline, input, ncpu=2, chunksize=2) >>> #Note: res should be equals to [['C', 'D'], ['A', 'B'], ['E']] >>> #but it seems that there is a bug with py.test and mp...
[ "Run", "a", "pipeline", "in", "parallel", "over", "a", "input", "generator", "cutting", "it", "into", "small", "chunks", "." ]
0450c7a9254c5c003162738458bbe0c49e777ba5
https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/offline.py#L63-L116
247,219
kodexlab/reliure
reliure/offline.py
main
def main(): """ Small run usage exemple """ #TODO: need to be mv in .rst doc from reliure.pipeline import Composable @Composable def doc_analyse(docs): for doc in docs: yield { "title": doc, "url": "http://lost.com/%s" % doc, } @Composable def print_ulrs(docs): for doc in docs: print(doc["url"]) yield doc pipeline = doc_analyse | print_ulrs documents = ("doc_%s" % d for d in xrange(20)) res = run_parallel(pipeline, documents, ncpu=2, chunksize=5) print(res)
python
def main(): """ Small run usage exemple """ #TODO: need to be mv in .rst doc from reliure.pipeline import Composable @Composable def doc_analyse(docs): for doc in docs: yield { "title": doc, "url": "http://lost.com/%s" % doc, } @Composable def print_ulrs(docs): for doc in docs: print(doc["url"]) yield doc pipeline = doc_analyse | print_ulrs documents = ("doc_%s" % d for d in xrange(20)) res = run_parallel(pipeline, documents, ncpu=2, chunksize=5) print(res)
[ "def", "main", "(", ")", ":", "#TODO: need to be mv in .rst doc", "from", "reliure", ".", "pipeline", "import", "Composable", "@", "Composable", "def", "doc_analyse", "(", "docs", ")", ":", "for", "doc", "in", "docs", ":", "yield", "{", "\"title\"", ":", "doc", ",", "\"url\"", ":", "\"http://lost.com/%s\"", "%", "doc", ",", "}", "@", "Composable", "def", "print_ulrs", "(", "docs", ")", ":", "for", "doc", "in", "docs", ":", "print", "(", "doc", "[", "\"url\"", "]", ")", "yield", "doc", "pipeline", "=", "doc_analyse", "|", "print_ulrs", "documents", "=", "(", "\"doc_%s\"", "%", "d", "for", "d", "in", "xrange", "(", "20", ")", ")", "res", "=", "run_parallel", "(", "pipeline", ",", "documents", ",", "ncpu", "=", "2", ",", "chunksize", "=", "5", ")", "print", "(", "res", ")" ]
Small run usage exemple
[ "Small", "run", "usage", "exemple" ]
0450c7a9254c5c003162738458bbe0c49e777ba5
https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/offline.py#L119-L142
247,220
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/autoparser/vectors.py
el_to_path_vector
def el_to_path_vector(el): """ Convert `el` to vector of foregoing elements. Attr: el (obj): Double-linked HTMLElement instance. Returns: list: HTMLElements which considered as path from root to `el`. """ path = [] while el.parent: path.append(el) el = el.parent return list(reversed(path + [el]))
python
def el_to_path_vector(el): """ Convert `el` to vector of foregoing elements. Attr: el (obj): Double-linked HTMLElement instance. Returns: list: HTMLElements which considered as path from root to `el`. """ path = [] while el.parent: path.append(el) el = el.parent return list(reversed(path + [el]))
[ "def", "el_to_path_vector", "(", "el", ")", ":", "path", "=", "[", "]", "while", "el", ".", "parent", ":", "path", ".", "append", "(", "el", ")", "el", "=", "el", ".", "parent", "return", "list", "(", "reversed", "(", "path", "+", "[", "el", "]", ")", ")" ]
Convert `el` to vector of foregoing elements. Attr: el (obj): Double-linked HTMLElement instance. Returns: list: HTMLElements which considered as path from root to `el`.
[ "Convert", "el", "to", "vector", "of", "foregoing", "elements", "." ]
38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/vectors.py#L14-L29
247,221
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/autoparser/vectors.py
common_vector_root
def common_vector_root(vec1, vec2): """ Return common root of the two vectors. Args: vec1 (list/tuple): First vector. vec2 (list/tuple): Second vector. Usage example:: >>> common_vector_root([1, 2, 3, 4, 5], [1, 2, 8, 9, 0]) [1, 2] Returns: list: Common part of two vectors or blank list. """ root = [] for v1, v2 in zip(vec1, vec2): if v1 == v2: root.append(v1) else: return root return root
python
def common_vector_root(vec1, vec2): """ Return common root of the two vectors. Args: vec1 (list/tuple): First vector. vec2 (list/tuple): Second vector. Usage example:: >>> common_vector_root([1, 2, 3, 4, 5], [1, 2, 8, 9, 0]) [1, 2] Returns: list: Common part of two vectors or blank list. """ root = [] for v1, v2 in zip(vec1, vec2): if v1 == v2: root.append(v1) else: return root return root
[ "def", "common_vector_root", "(", "vec1", ",", "vec2", ")", ":", "root", "=", "[", "]", "for", "v1", ",", "v2", "in", "zip", "(", "vec1", ",", "vec2", ")", ":", "if", "v1", "==", "v2", ":", "root", ".", "append", "(", "v1", ")", "else", ":", "return", "root", "return", "root" ]
Return common root of the two vectors. Args: vec1 (list/tuple): First vector. vec2 (list/tuple): Second vector. Usage example:: >>> common_vector_root([1, 2, 3, 4, 5], [1, 2, 8, 9, 0]) [1, 2] Returns: list: Common part of two vectors or blank list.
[ "Return", "common", "root", "of", "the", "two", "vectors", "." ]
38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/vectors.py#L32-L55
247,222
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/autoparser/vectors.py
find_common_root
def find_common_root(elements): """ Find root which is common for all `elements`. Args: elements (list): List of double-linked HTMLElement objects. Returns: list: Vector of HTMLElement containing path to common root. """ if not elements: raise UserWarning("Can't find common root - no elements suplied.") root_path = el_to_path_vector(elements.pop()) for el in elements: el_path = el_to_path_vector(el) root_path = common_vector_root(root_path, el_path) if not root_path: raise UserWarning( "Vectors without common root:\n%s" % str(el_path) ) return root_path
python
def find_common_root(elements): """ Find root which is common for all `elements`. Args: elements (list): List of double-linked HTMLElement objects. Returns: list: Vector of HTMLElement containing path to common root. """ if not elements: raise UserWarning("Can't find common root - no elements suplied.") root_path = el_to_path_vector(elements.pop()) for el in elements: el_path = el_to_path_vector(el) root_path = common_vector_root(root_path, el_path) if not root_path: raise UserWarning( "Vectors without common root:\n%s" % str(el_path) ) return root_path
[ "def", "find_common_root", "(", "elements", ")", ":", "if", "not", "elements", ":", "raise", "UserWarning", "(", "\"Can't find common root - no elements suplied.\"", ")", "root_path", "=", "el_to_path_vector", "(", "elements", ".", "pop", "(", ")", ")", "for", "el", "in", "elements", ":", "el_path", "=", "el_to_path_vector", "(", "el", ")", "root_path", "=", "common_vector_root", "(", "root_path", ",", "el_path", ")", "if", "not", "root_path", ":", "raise", "UserWarning", "(", "\"Vectors without common root:\\n%s\"", "%", "str", "(", "el_path", ")", ")", "return", "root_path" ]
Find root which is common for all `elements`. Args: elements (list): List of double-linked HTMLElement objects. Returns: list: Vector of HTMLElement containing path to common root.
[ "Find", "root", "which", "is", "common", "for", "all", "elements", "." ]
38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/vectors.py#L58-L83
247,223
benfb/dars
dars/__init__.py
instantiateSong
def instantiateSong(fileName): """Create an AudioSegment with the data from the given file""" ext = detectFormat(fileName) if(ext == "mp3"): return pd.AudioSegment.from_mp3(fileName) elif(ext == "wav"): return pd.AudioSegment.from_wav(fileName) elif(ext == "ogg"): return pd.AudioSegment.from_ogg(fileName) elif(ext == "flv"): return pd.AudioSegment.from_flv(fileName) elif(ext == "m4a"): return pd.AudioSegment.from_file(fileName, "mp4") else: return pd.AudioSegment.from_file(fileName, ext)
python
def instantiateSong(fileName): """Create an AudioSegment with the data from the given file""" ext = detectFormat(fileName) if(ext == "mp3"): return pd.AudioSegment.from_mp3(fileName) elif(ext == "wav"): return pd.AudioSegment.from_wav(fileName) elif(ext == "ogg"): return pd.AudioSegment.from_ogg(fileName) elif(ext == "flv"): return pd.AudioSegment.from_flv(fileName) elif(ext == "m4a"): return pd.AudioSegment.from_file(fileName, "mp4") else: return pd.AudioSegment.from_file(fileName, ext)
[ "def", "instantiateSong", "(", "fileName", ")", ":", "ext", "=", "detectFormat", "(", "fileName", ")", "if", "(", "ext", "==", "\"mp3\"", ")", ":", "return", "pd", ".", "AudioSegment", ".", "from_mp3", "(", "fileName", ")", "elif", "(", "ext", "==", "\"wav\"", ")", ":", "return", "pd", ".", "AudioSegment", ".", "from_wav", "(", "fileName", ")", "elif", "(", "ext", "==", "\"ogg\"", ")", ":", "return", "pd", ".", "AudioSegment", ".", "from_ogg", "(", "fileName", ")", "elif", "(", "ext", "==", "\"flv\"", ")", ":", "return", "pd", ".", "AudioSegment", ".", "from_flv", "(", "fileName", ")", "elif", "(", "ext", "==", "\"m4a\"", ")", ":", "return", "pd", ".", "AudioSegment", ".", "from_file", "(", "fileName", ",", "\"mp4\"", ")", "else", ":", "return", "pd", ".", "AudioSegment", ".", "from_file", "(", "fileName", ",", "ext", ")" ]
Create an AudioSegment with the data from the given file
[ "Create", "an", "AudioSegment", "with", "the", "data", "from", "the", "given", "file" ]
66778de8314f7dcec50ef706abcea84a9b3d9c7e
https://github.com/benfb/dars/blob/66778de8314f7dcec50ef706abcea84a9b3d9c7e/dars/__init__.py#L11-L25
247,224
benfb/dars
dars/__init__.py
findGap
def findGap(song): """Return the position of silence in a song""" try: silence = pd.silence.detect_silence(song) except IOError: print("There isn't a song there!") maxlength = 0 for pair in silence: length = pair[1] - pair[0] if length >= maxlength: maxlength = length gap = pair return gap
python
def findGap(song): """Return the position of silence in a song""" try: silence = pd.silence.detect_silence(song) except IOError: print("There isn't a song there!") maxlength = 0 for pair in silence: length = pair[1] - pair[0] if length >= maxlength: maxlength = length gap = pair return gap
[ "def", "findGap", "(", "song", ")", ":", "try", ":", "silence", "=", "pd", ".", "silence", ".", "detect_silence", "(", "song", ")", "except", "IOError", ":", "print", "(", "\"There isn't a song there!\"", ")", "maxlength", "=", "0", "for", "pair", "in", "silence", ":", "length", "=", "pair", "[", "1", "]", "-", "pair", "[", "0", "]", "if", "length", ">=", "maxlength", ":", "maxlength", "=", "length", "gap", "=", "pair", "return", "gap" ]
Return the position of silence in a song
[ "Return", "the", "position", "of", "silence", "in", "a", "song" ]
66778de8314f7dcec50ef706abcea84a9b3d9c7e
https://github.com/benfb/dars/blob/66778de8314f7dcec50ef706abcea84a9b3d9c7e/dars/__init__.py#L27-L42
247,225
benfb/dars
dars/__init__.py
splitSong
def splitSong(songToSplit, start1, start2): """Split a song into two parts, one starting at start1, the other at start2""" print "start1 " + str(start1) print "start2 " + str(start2) # songs = [songToSplit[:start1+2000], songToSplit[start2-2000:]] songs = [songToSplit[:start1], songToSplit[start2:]] return songs
python
def splitSong(songToSplit, start1, start2): """Split a song into two parts, one starting at start1, the other at start2""" print "start1 " + str(start1) print "start2 " + str(start2) # songs = [songToSplit[:start1+2000], songToSplit[start2-2000:]] songs = [songToSplit[:start1], songToSplit[start2:]] return songs
[ "def", "splitSong", "(", "songToSplit", ",", "start1", ",", "start2", ")", ":", "print", "\"start1 \"", "+", "str", "(", "start1", ")", "print", "\"start2 \"", "+", "str", "(", "start2", ")", "# songs = [songToSplit[:start1+2000], songToSplit[start2-2000:]]", "songs", "=", "[", "songToSplit", "[", ":", "start1", "]", ",", "songToSplit", "[", "start2", ":", "]", "]", "return", "songs" ]
Split a song into two parts, one starting at start1, the other at start2
[ "Split", "a", "song", "into", "two", "parts", "one", "starting", "at", "start1", "the", "other", "at", "start2" ]
66778de8314f7dcec50ef706abcea84a9b3d9c7e
https://github.com/benfb/dars/blob/66778de8314f7dcec50ef706abcea84a9b3d9c7e/dars/__init__.py#L44-L50
247,226
benfb/dars
dars/__init__.py
trackSeek
def trackSeek(path, artist, album, track, trackNum, fmt): """Actually runs the program""" hiddenName = "(Hidden Track).{}".format(fmt) trackName = track + ".{}".format(fmt) songIn = instantiateSong(path) times = findGap(songIn) saveFiles(trackName, hiddenName, splitSong(songIn, times[0], times[1]), artist, album, trackNum) # return [path, track.rsplit('/',1)[0] +'/{}'.format(hiddenName)] return [trackName, hiddenName]
python
def trackSeek(path, artist, album, track, trackNum, fmt): """Actually runs the program""" hiddenName = "(Hidden Track).{}".format(fmt) trackName = track + ".{}".format(fmt) songIn = instantiateSong(path) times = findGap(songIn) saveFiles(trackName, hiddenName, splitSong(songIn, times[0], times[1]), artist, album, trackNum) # return [path, track.rsplit('/',1)[0] +'/{}'.format(hiddenName)] return [trackName, hiddenName]
[ "def", "trackSeek", "(", "path", ",", "artist", ",", "album", ",", "track", ",", "trackNum", ",", "fmt", ")", ":", "hiddenName", "=", "\"(Hidden Track).{}\"", ".", "format", "(", "fmt", ")", "trackName", "=", "track", "+", "\".{}\"", ".", "format", "(", "fmt", ")", "songIn", "=", "instantiateSong", "(", "path", ")", "times", "=", "findGap", "(", "songIn", ")", "saveFiles", "(", "trackName", ",", "hiddenName", ",", "splitSong", "(", "songIn", ",", "times", "[", "0", "]", ",", "times", "[", "1", "]", ")", ",", "artist", ",", "album", ",", "trackNum", ")", "# return [path, track.rsplit('/',1)[0] +'/{}'.format(hiddenName)]", "return", "[", "trackName", ",", "hiddenName", "]" ]
Actually runs the program
[ "Actually", "runs", "the", "program" ]
66778de8314f7dcec50ef706abcea84a9b3d9c7e
https://github.com/benfb/dars/blob/66778de8314f7dcec50ef706abcea84a9b3d9c7e/dars/__init__.py#L62-L70
247,227
benfb/dars
dars/__init__.py
parseArgs
def parseArgs(): """Parses arguments passed in via the command line""" parser = argparse.ArgumentParser() parser.add_argument("name", help="the file you want to split") parser.add_argument("out1", help="the name of the first file you want to output") parser.add_argument("out2", help="the name of the second file you want to output") return parser.parse_args()
python
def parseArgs(): """Parses arguments passed in via the command line""" parser = argparse.ArgumentParser() parser.add_argument("name", help="the file you want to split") parser.add_argument("out1", help="the name of the first file you want to output") parser.add_argument("out2", help="the name of the second file you want to output") return parser.parse_args()
[ "def", "parseArgs", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"name\"", ",", "help", "=", "\"the file you want to split\"", ")", "parser", ".", "add_argument", "(", "\"out1\"", ",", "help", "=", "\"the name of the first file you want to output\"", ")", "parser", ".", "add_argument", "(", "\"out2\"", ",", "help", "=", "\"the name of the second file you want to output\"", ")", "return", "parser", ".", "parse_args", "(", ")" ]
Parses arguments passed in via the command line
[ "Parses", "arguments", "passed", "in", "via", "the", "command", "line" ]
66778de8314f7dcec50ef706abcea84a9b3d9c7e
https://github.com/benfb/dars/blob/66778de8314f7dcec50ef706abcea84a9b3d9c7e/dars/__init__.py#L72-L78
247,228
openpermissions/chub
chub/api.py
Resource._sub_resource
def _sub_resource(self, path): """ get or create sub resource """ if path not in self.resource_map: self.resource_map[path] = Resource( path, self.fetch, self.resource_map, default_headers=self.default_headers) return self.resource_map[path]
python
def _sub_resource(self, path): """ get or create sub resource """ if path not in self.resource_map: self.resource_map[path] = Resource( path, self.fetch, self.resource_map, default_headers=self.default_headers) return self.resource_map[path]
[ "def", "_sub_resource", "(", "self", ",", "path", ")", ":", "if", "path", "not", "in", "self", ".", "resource_map", ":", "self", ".", "resource_map", "[", "path", "]", "=", "Resource", "(", "path", ",", "self", ".", "fetch", ",", "self", ".", "resource_map", ",", "default_headers", "=", "self", ".", "default_headers", ")", "return", "self", ".", "resource_map", "[", "path", "]" ]
get or create sub resource
[ "get", "or", "create", "sub", "resource" ]
00762aa17015f4b3010673d1570c708eab3c34ed
https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/api.py#L61-L69
247,229
openpermissions/chub
chub/api.py
Resource.prepare_request
def prepare_request(self, *args, **kw): """ creates a full featured HTTPRequest objects """ self.http_request = self.request_class(self.path, *args, **kw)
python
def prepare_request(self, *args, **kw): """ creates a full featured HTTPRequest objects """ self.http_request = self.request_class(self.path, *args, **kw)
[ "def", "prepare_request", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "self", ".", "http_request", "=", "self", ".", "request_class", "(", "self", ".", "path", ",", "*", "args", ",", "*", "*", "kw", ")" ]
creates a full featured HTTPRequest objects
[ "creates", "a", "full", "featured", "HTTPRequest", "objects" ]
00762aa17015f4b3010673d1570c708eab3c34ed
https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/api.py#L75-L79
247,230
openpermissions/chub
chub/api.py
API.token
def token(self): """ get the token """ header = self.default_headers.get('Authorization', '') prefex = 'Bearer ' if header.startswith(prefex): token = header[len(prefex):] else: token = header return token
python
def token(self): """ get the token """ header = self.default_headers.get('Authorization', '') prefex = 'Bearer ' if header.startswith(prefex): token = header[len(prefex):] else: token = header return token
[ "def", "token", "(", "self", ")", ":", "header", "=", "self", ".", "default_headers", ".", "get", "(", "'Authorization'", ",", "''", ")", "prefex", "=", "'Bearer '", "if", "header", ".", "startswith", "(", "prefex", ")", ":", "token", "=", "header", "[", "len", "(", "prefex", ")", ":", "]", "else", ":", "token", "=", "header", "return", "token" ]
get the token
[ "get", "the", "token" ]
00762aa17015f4b3010673d1570c708eab3c34ed
https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/api.py#L99-L109
247,231
openpermissions/chub
chub/api.py
API._request
def _request(self): """ retrieve the caller frame, extract the parameters from the caller function, find the matching function, and fire the request """ caller_frame = inspect.getouterframes(inspect.currentframe())[1] args, _, _, values = inspect.getargvalues(caller_frame[0]) caller_name = caller_frame[3] kwargs = {arg: values[arg] for arg in args if arg != 'self'} func = reduce( lambda resource, name: resource.__getattr__(name), self.mappings[caller_name].split('.'), self) return func(**kwargs)
python
def _request(self): """ retrieve the caller frame, extract the parameters from the caller function, find the matching function, and fire the request """ caller_frame = inspect.getouterframes(inspect.currentframe())[1] args, _, _, values = inspect.getargvalues(caller_frame[0]) caller_name = caller_frame[3] kwargs = {arg: values[arg] for arg in args if arg != 'self'} func = reduce( lambda resource, name: resource.__getattr__(name), self.mappings[caller_name].split('.'), self) return func(**kwargs)
[ "def", "_request", "(", "self", ")", ":", "caller_frame", "=", "inspect", ".", "getouterframes", "(", "inspect", ".", "currentframe", "(", ")", ")", "[", "1", "]", "args", ",", "_", ",", "_", ",", "values", "=", "inspect", ".", "getargvalues", "(", "caller_frame", "[", "0", "]", ")", "caller_name", "=", "caller_frame", "[", "3", "]", "kwargs", "=", "{", "arg", ":", "values", "[", "arg", "]", "for", "arg", "in", "args", "if", "arg", "!=", "'self'", "}", "func", "=", "reduce", "(", "lambda", "resource", ",", "name", ":", "resource", ".", "__getattr__", "(", "name", ")", ",", "self", ".", "mappings", "[", "caller_name", "]", ".", "split", "(", "'.'", ")", ",", "self", ")", "return", "func", "(", "*", "*", "kwargs", ")" ]
retrieve the caller frame, extract the parameters from the caller function, find the matching function, and fire the request
[ "retrieve", "the", "caller", "frame", "extract", "the", "parameters", "from", "the", "caller", "function", "find", "the", "matching", "function", "and", "fire", "the", "request" ]
00762aa17015f4b3010673d1570c708eab3c34ed
https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/api.py#L118-L131
247,232
djangomini/djangomini
djangomini/tools.py
listdir
def listdir(dir_name, get_dirs=None, get_files=None, hide_ignored=False): """ Return list of all dirs and files inside given dir. Also can filter contents to return only dirs or files. Args: - dir_name: Which directory we need to scan (relative) - get_dirs: Return dirs list - get_files: Return files list - hide_ignored: Exclude files and dirs with initial underscore """ if get_dirs is None and get_files is None: get_dirs = True get_files = True source_dir = os.path.join(settings.BASE_DIR, 'app', dir_name) dirs = [] for dir_or_file_name in os.listdir(source_dir): path = os.path.join(source_dir, dir_or_file_name) if hide_ignored and dir_or_file_name.startswith('_'): continue is_dir = os.path.isdir(path) if get_dirs and is_dir or get_files and not is_dir: dirs.append(dir_or_file_name) return dirs
python
def listdir(dir_name, get_dirs=None, get_files=None, hide_ignored=False): """ Return list of all dirs and files inside given dir. Also can filter contents to return only dirs or files. Args: - dir_name: Which directory we need to scan (relative) - get_dirs: Return dirs list - get_files: Return files list - hide_ignored: Exclude files and dirs with initial underscore """ if get_dirs is None and get_files is None: get_dirs = True get_files = True source_dir = os.path.join(settings.BASE_DIR, 'app', dir_name) dirs = [] for dir_or_file_name in os.listdir(source_dir): path = os.path.join(source_dir, dir_or_file_name) if hide_ignored and dir_or_file_name.startswith('_'): continue is_dir = os.path.isdir(path) if get_dirs and is_dir or get_files and not is_dir: dirs.append(dir_or_file_name) return dirs
[ "def", "listdir", "(", "dir_name", ",", "get_dirs", "=", "None", ",", "get_files", "=", "None", ",", "hide_ignored", "=", "False", ")", ":", "if", "get_dirs", "is", "None", "and", "get_files", "is", "None", ":", "get_dirs", "=", "True", "get_files", "=", "True", "source_dir", "=", "os", ".", "path", ".", "join", "(", "settings", ".", "BASE_DIR", ",", "'app'", ",", "dir_name", ")", "dirs", "=", "[", "]", "for", "dir_or_file_name", "in", "os", ".", "listdir", "(", "source_dir", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "source_dir", ",", "dir_or_file_name", ")", "if", "hide_ignored", "and", "dir_or_file_name", ".", "startswith", "(", "'_'", ")", ":", "continue", "is_dir", "=", "os", ".", "path", ".", "isdir", "(", "path", ")", "if", "get_dirs", "and", "is_dir", "or", "get_files", "and", "not", "is_dir", ":", "dirs", ".", "append", "(", "dir_or_file_name", ")", "return", "dirs" ]
Return list of all dirs and files inside given dir. Also can filter contents to return only dirs or files. Args: - dir_name: Which directory we need to scan (relative) - get_dirs: Return dirs list - get_files: Return files list - hide_ignored: Exclude files and dirs with initial underscore
[ "Return", "list", "of", "all", "dirs", "and", "files", "inside", "given", "dir", "." ]
cfbe2d59acf0e89e5fd442df8952f9a117a63875
https://github.com/djangomini/djangomini/blob/cfbe2d59acf0e89e5fd442df8952f9a117a63875/djangomini/tools.py#L14-L42
247,233
Ffisegydd/whatis
whatis/_util.py
get_types
def get_types(obj, **kwargs): """Get the types of an iterable.""" max_iterable_length = kwargs.get('max_iterable_length', 100000) it, = itertools.tee(obj, 1) s = set() too_big = False for i, v in enumerate(it): if i <= max_iterable_length: s.add(type(v)) else: too_big = True break return {"types": s, "too_big": too_big}
python
def get_types(obj, **kwargs): """Get the types of an iterable.""" max_iterable_length = kwargs.get('max_iterable_length', 100000) it, = itertools.tee(obj, 1) s = set() too_big = False for i, v in enumerate(it): if i <= max_iterable_length: s.add(type(v)) else: too_big = True break return {"types": s, "too_big": too_big}
[ "def", "get_types", "(", "obj", ",", "*", "*", "kwargs", ")", ":", "max_iterable_length", "=", "kwargs", ".", "get", "(", "'max_iterable_length'", ",", "100000", ")", "it", ",", "=", "itertools", ".", "tee", "(", "obj", ",", "1", ")", "s", "=", "set", "(", ")", "too_big", "=", "False", "for", "i", ",", "v", "in", "enumerate", "(", "it", ")", ":", "if", "i", "<=", "max_iterable_length", ":", "s", ".", "add", "(", "type", "(", "v", ")", ")", "else", ":", "too_big", "=", "True", "break", "return", "{", "\"types\"", ":", "s", ",", "\"too_big\"", ":", "too_big", "}" ]
Get the types of an iterable.
[ "Get", "the", "types", "of", "an", "iterable", "." ]
eef780ced61aae6d001aeeef7574e5e27e613583
https://github.com/Ffisegydd/whatis/blob/eef780ced61aae6d001aeeef7574e5e27e613583/whatis/_util.py#L28-L44
247,234
MacHu-GWU/windtalker-project
windtalker/cipher.py
BaseCipher.encrypt_text
def encrypt_text(self, text, *args, **kwargs): """ Encrypt a string. input: unicode str, output: unicode str """ b = text.encode("utf-8") token = self.encrypt(b, *args, **kwargs) return base64.b64encode(token).decode("utf-8")
python
def encrypt_text(self, text, *args, **kwargs): """ Encrypt a string. input: unicode str, output: unicode str """ b = text.encode("utf-8") token = self.encrypt(b, *args, **kwargs) return base64.b64encode(token).decode("utf-8")
[ "def", "encrypt_text", "(", "self", ",", "text", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "b", "=", "text", ".", "encode", "(", "\"utf-8\"", ")", "token", "=", "self", ".", "encrypt", "(", "b", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "base64", ".", "b64encode", "(", "token", ")", ".", "decode", "(", "\"utf-8\"", ")" ]
Encrypt a string. input: unicode str, output: unicode str
[ "Encrypt", "a", "string", "." ]
1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/cipher.py#L67-L75
247,235
MacHu-GWU/windtalker-project
windtalker/cipher.py
BaseCipher.decrypt_text
def decrypt_text(self, text, *args, **kwargs): """ Decrypt a string. input: unicode str, output: unicode str """ b = text.encode("utf-8") token = base64.b64decode(b) return self.decrypt(token, *args, **kwargs).decode("utf-8")
python
def decrypt_text(self, text, *args, **kwargs): """ Decrypt a string. input: unicode str, output: unicode str """ b = text.encode("utf-8") token = base64.b64decode(b) return self.decrypt(token, *args, **kwargs).decode("utf-8")
[ "def", "decrypt_text", "(", "self", ",", "text", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "b", "=", "text", ".", "encode", "(", "\"utf-8\"", ")", "token", "=", "base64", ".", "b64decode", "(", "b", ")", "return", "self", ".", "decrypt", "(", "token", ",", "*", "args", ",", "*", "*", "kwargs", ")", ".", "decode", "(", "\"utf-8\"", ")" ]
Decrypt a string. input: unicode str, output: unicode str
[ "Decrypt", "a", "string", "." ]
1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/cipher.py#L77-L85
247,236
MacHu-GWU/windtalker-project
windtalker/cipher.py
BaseCipher._show
def _show(self, message, indent=0, enable_verbose=True): # pragma: no cover """Message printer. """ if enable_verbose: print(" " * indent + message)
python
def _show(self, message, indent=0, enable_verbose=True): # pragma: no cover """Message printer. """ if enable_verbose: print(" " * indent + message)
[ "def", "_show", "(", "self", ",", "message", ",", "indent", "=", "0", ",", "enable_verbose", "=", "True", ")", ":", "# pragma: no cover", "if", "enable_verbose", ":", "print", "(", "\" \"", "*", "indent", "+", "message", ")" ]
Message printer.
[ "Message", "printer", "." ]
1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/cipher.py#L87-L91
247,237
MacHu-GWU/windtalker-project
windtalker/cipher.py
BaseCipher.encrypt_dir
def encrypt_dir(self, path, output_path=None, overwrite=False, stream=True, enable_verbose=True): """ Encrypt everything in a directory. :param path: path of the dir you need to encrypt :param output_path: encrypted dir output path :param overwrite: if True, then silently overwrite output file if exists :param stream: if it is a very big file, stream mode can avoid using too much memory :param enable_verbose: boolean, trigger on/off the help information """ path, output_path = files.process_dst_overwrite_args( src=path, dst=output_path, overwrite=overwrite, src_to_dst_func=files.get_encrpyted_path, ) self._show("--- Encrypt directory '%s' ---" % path, enable_verbose=enable_verbose) st = time.clock() for current_dir, _, file_list in os.walk(path): new_dir = current_dir.replace(path, output_path) if not os.path.exists(new_dir): # pragma: no cover os.mkdir(new_dir) for basename in file_list: old_path = os.path.join(current_dir, basename) new_path = os.path.join(new_dir, basename) self.encrypt_file(old_path, new_path, overwrite=overwrite, stream=stream, enable_verbose=enable_verbose) self._show("Complete! Elapse %.6f seconds" % (time.clock() - st,), enable_verbose=enable_verbose) return output_path
python
def encrypt_dir(self, path, output_path=None, overwrite=False, stream=True, enable_verbose=True): """ Encrypt everything in a directory. :param path: path of the dir you need to encrypt :param output_path: encrypted dir output path :param overwrite: if True, then silently overwrite output file if exists :param stream: if it is a very big file, stream mode can avoid using too much memory :param enable_verbose: boolean, trigger on/off the help information """ path, output_path = files.process_dst_overwrite_args( src=path, dst=output_path, overwrite=overwrite, src_to_dst_func=files.get_encrpyted_path, ) self._show("--- Encrypt directory '%s' ---" % path, enable_verbose=enable_verbose) st = time.clock() for current_dir, _, file_list in os.walk(path): new_dir = current_dir.replace(path, output_path) if not os.path.exists(new_dir): # pragma: no cover os.mkdir(new_dir) for basename in file_list: old_path = os.path.join(current_dir, basename) new_path = os.path.join(new_dir, basename) self.encrypt_file(old_path, new_path, overwrite=overwrite, stream=stream, enable_verbose=enable_verbose) self._show("Complete! Elapse %.6f seconds" % (time.clock() - st,), enable_verbose=enable_verbose) return output_path
[ "def", "encrypt_dir", "(", "self", ",", "path", ",", "output_path", "=", "None", ",", "overwrite", "=", "False", ",", "stream", "=", "True", ",", "enable_verbose", "=", "True", ")", ":", "path", ",", "output_path", "=", "files", ".", "process_dst_overwrite_args", "(", "src", "=", "path", ",", "dst", "=", "output_path", ",", "overwrite", "=", "overwrite", ",", "src_to_dst_func", "=", "files", ".", "get_encrpyted_path", ",", ")", "self", ".", "_show", "(", "\"--- Encrypt directory '%s' ---\"", "%", "path", ",", "enable_verbose", "=", "enable_verbose", ")", "st", "=", "time", ".", "clock", "(", ")", "for", "current_dir", ",", "_", ",", "file_list", "in", "os", ".", "walk", "(", "path", ")", ":", "new_dir", "=", "current_dir", ".", "replace", "(", "path", ",", "output_path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "new_dir", ")", ":", "# pragma: no cover", "os", ".", "mkdir", "(", "new_dir", ")", "for", "basename", "in", "file_list", ":", "old_path", "=", "os", ".", "path", ".", "join", "(", "current_dir", ",", "basename", ")", "new_path", "=", "os", ".", "path", ".", "join", "(", "new_dir", ",", "basename", ")", "self", ".", "encrypt_file", "(", "old_path", ",", "new_path", ",", "overwrite", "=", "overwrite", ",", "stream", "=", "stream", ",", "enable_verbose", "=", "enable_verbose", ")", "self", ".", "_show", "(", "\"Complete! Elapse %.6f seconds\"", "%", "(", "time", ".", "clock", "(", ")", "-", "st", ",", ")", ",", "enable_verbose", "=", "enable_verbose", ")", "return", "output_path" ]
Encrypt everything in a directory. :param path: path of the dir you need to encrypt :param output_path: encrypted dir output path :param overwrite: if True, then silently overwrite output file if exists :param stream: if it is a very big file, stream mode can avoid using too much memory :param enable_verbose: boolean, trigger on/off the help information
[ "Encrypt", "everything", "in", "a", "directory", "." ]
1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/cipher.py#L161-L198
247,238
davisd50/sparc.cache
sparc/cache/item.py
schema_map
def schema_map(schema): """Return a valid ICachedItemMapper.map for schema""" mapper = {} for name in getFieldNames(schema): mapper[name] = name return mapper
python
def schema_map(schema): """Return a valid ICachedItemMapper.map for schema""" mapper = {} for name in getFieldNames(schema): mapper[name] = name return mapper
[ "def", "schema_map", "(", "schema", ")", ":", "mapper", "=", "{", "}", "for", "name", "in", "getFieldNames", "(", "schema", ")", ":", "mapper", "[", "name", "]", "=", "name", "return", "mapper" ]
Return a valid ICachedItemMapper.map for schema
[ "Return", "a", "valid", "ICachedItemMapper", ".", "map", "for", "schema" ]
f2378aad48c368a53820e97b093ace790d4d4121
https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/item.py#L14-L19
247,239
cirruscluster/cirruscluster
cirruscluster/ext/ansible/utils/module_docs.py
get_docstring
def get_docstring(filename, verbose=False): """ Search for assignment of the DOCUMENTATION variable in the given file. Parse that from YAML and return the YAML doc or None. """ doc = None try: # Thank you, Habbie, for this bit of code :-) M = ast.parse(''.join(open(filename))) for child in M.body: if isinstance(child, ast.Assign): if 'DOCUMENTATION' in (t.id for t in child.targets): doc = yaml.load(child.value.s) except: if verbose == True: traceback.print_exc() print "unable to parse %s" % filename return doc
python
def get_docstring(filename, verbose=False): """ Search for assignment of the DOCUMENTATION variable in the given file. Parse that from YAML and return the YAML doc or None. """ doc = None try: # Thank you, Habbie, for this bit of code :-) M = ast.parse(''.join(open(filename))) for child in M.body: if isinstance(child, ast.Assign): if 'DOCUMENTATION' in (t.id for t in child.targets): doc = yaml.load(child.value.s) except: if verbose == True: traceback.print_exc() print "unable to parse %s" % filename return doc
[ "def", "get_docstring", "(", "filename", ",", "verbose", "=", "False", ")", ":", "doc", "=", "None", "try", ":", "# Thank you, Habbie, for this bit of code :-)", "M", "=", "ast", ".", "parse", "(", "''", ".", "join", "(", "open", "(", "filename", ")", ")", ")", "for", "child", "in", "M", ".", "body", ":", "if", "isinstance", "(", "child", ",", "ast", ".", "Assign", ")", ":", "if", "'DOCUMENTATION'", "in", "(", "t", ".", "id", "for", "t", "in", "child", ".", "targets", ")", ":", "doc", "=", "yaml", ".", "load", "(", "child", ".", "value", ".", "s", ")", "except", ":", "if", "verbose", "==", "True", ":", "traceback", ".", "print_exc", "(", ")", "print", "\"unable to parse %s\"", "%", "filename", "return", "doc" ]
Search for assignment of the DOCUMENTATION variable in the given file. Parse that from YAML and return the YAML doc or None.
[ "Search", "for", "assignment", "of", "the", "DOCUMENTATION", "variable", "in", "the", "given", "file", ".", "Parse", "that", "from", "YAML", "and", "return", "the", "YAML", "doc", "or", "None", "." ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/module_docs.py#L31-L50
247,240
zakdoek/django-simple-resizer
simple_resizer/__init__.py
_normalize_params
def _normalize_params(image, width, height, crop): """ Normalize params and calculate aspect. """ if width is None and height is None: raise ValueError("Either width or height must be set. Otherwise " "resizing is useless.") if width is None or height is None: aspect = float(image.width) / float(image.height) if crop: raise ValueError("Cropping the image would be useless since only " "one dimention is give to resize along.") if width is None: width = int(round(height * aspect)) else: height = int(round(width / aspect)) return (width, height, crop)
python
def _normalize_params(image, width, height, crop): """ Normalize params and calculate aspect. """ if width is None and height is None: raise ValueError("Either width or height must be set. Otherwise " "resizing is useless.") if width is None or height is None: aspect = float(image.width) / float(image.height) if crop: raise ValueError("Cropping the image would be useless since only " "one dimention is give to resize along.") if width is None: width = int(round(height * aspect)) else: height = int(round(width / aspect)) return (width, height, crop)
[ "def", "_normalize_params", "(", "image", ",", "width", ",", "height", ",", "crop", ")", ":", "if", "width", "is", "None", "and", "height", "is", "None", ":", "raise", "ValueError", "(", "\"Either width or height must be set. Otherwise \"", "\"resizing is useless.\"", ")", "if", "width", "is", "None", "or", "height", "is", "None", ":", "aspect", "=", "float", "(", "image", ".", "width", ")", "/", "float", "(", "image", ".", "height", ")", "if", "crop", ":", "raise", "ValueError", "(", "\"Cropping the image would be useless since only \"", "\"one dimention is give to resize along.\"", ")", "if", "width", "is", "None", ":", "width", "=", "int", "(", "round", "(", "height", "*", "aspect", ")", ")", "else", ":", "height", "=", "int", "(", "round", "(", "width", "/", "aspect", ")", ")", "return", "(", "width", ",", "height", ",", "crop", ")" ]
Normalize params and calculate aspect.
[ "Normalize", "params", "and", "calculate", "aspect", "." ]
5614eb1717948c65d179c3d1567439a8c90a4d44
https://github.com/zakdoek/django-simple-resizer/blob/5614eb1717948c65d179c3d1567439a8c90a4d44/simple_resizer/__init__.py#L25-L45
247,241
zakdoek/django-simple-resizer
simple_resizer/__init__.py
_get_resized_name
def _get_resized_name(image, width, height, crop, namespace): """ Get the name of the resized file when assumed it exists. """ path, name = os.path.split(image.name) name_part = "%s/%ix%i" % (namespace, width, height) if crop: name_part += "_cropped" return os.path.join(path, name_part, name)
python
def _get_resized_name(image, width, height, crop, namespace): """ Get the name of the resized file when assumed it exists. """ path, name = os.path.split(image.name) name_part = "%s/%ix%i" % (namespace, width, height) if crop: name_part += "_cropped" return os.path.join(path, name_part, name)
[ "def", "_get_resized_name", "(", "image", ",", "width", ",", "height", ",", "crop", ",", "namespace", ")", ":", "path", ",", "name", "=", "os", ".", "path", ".", "split", "(", "image", ".", "name", ")", "name_part", "=", "\"%s/%ix%i\"", "%", "(", "namespace", ",", "width", ",", "height", ")", "if", "crop", ":", "name_part", "+=", "\"_cropped\"", "return", "os", ".", "path", ".", "join", "(", "path", ",", "name_part", ",", "name", ")" ]
Get the name of the resized file when assumed it exists.
[ "Get", "the", "name", "of", "the", "resized", "file", "when", "assumed", "it", "exists", "." ]
5614eb1717948c65d179c3d1567439a8c90a4d44
https://github.com/zakdoek/django-simple-resizer/blob/5614eb1717948c65d179c3d1567439a8c90a4d44/simple_resizer/__init__.py#L48-L57
247,242
zakdoek/django-simple-resizer
simple_resizer/__init__.py
_resize
def _resize(image, width, height, crop): """ Resize the image with respect to the aspect ratio """ ext = os.path.splitext(image.name)[1].strip(".") with Image(file=image, format=ext) as b_image: # Account for orientation if ORIENTATION_TYPES.index(b_image.orientation) > 4: # Flip target_aspect = float(width) / float(height) aspect = float(b_image.height) / float(b_image.width) else: target_aspect = float(width) / float(height) aspect = float(b_image.width) / float(b_image.height) # Fix rotation b_image.auto_orient() # Calculate target size target_aspect = float(width) / float(height) aspect = float(b_image.width) / float(b_image.height) if ((target_aspect > aspect and not crop) or (target_aspect <= aspect and crop)): # target is wider than image, set height as maximum target_height = height # calculate width # - iw / ih = tw / th (keep aspect) # => th ( iw / ih ) = tw target_width = float(target_height) * aspect if crop: # calculate crop coords # - ( tw - w ) / 2 target_left = (float(target_width) - float(width)) / 2 target_left = int(round(target_left)) target_top = 0 # correct floating point error, and convert to int, round in the # direction of the requested width if width >= target_width: target_width = int(math.ceil(target_width)) else: target_width = int(math.floor(target_width)) else: # image is wider than target, set width as maximum target_width = width # calculate height # - iw / ih = tw / th (keep aspect) # => tw / ( iw / ih ) = th target_height = float(target_width) / aspect if crop: # calculate crop coords # - ( th - h ) / 2 target_top = (float(target_height) - float(height)) / 2 target_top = int(round(target_top)) target_left = 0 # correct floating point error and convert to int if height >= target_height: target_height = int(math.ceil(target_height)) else: target_height = int(math.floor(target_height)) # strip color profiles b_image.strip() # Resize b_image.resize(target_width, target_height) if crop: # Crop to target b_image.crop(left=target_left, top=target_top, width=width, height=height) # Save to temporary file temp_file = tempfile.TemporaryFile() b_image.save(file=temp_file) # Rewind the file temp_file.seek(0) return temp_file
python
def _resize(image, width, height, crop): """ Resize the image with respect to the aspect ratio """ ext = os.path.splitext(image.name)[1].strip(".") with Image(file=image, format=ext) as b_image: # Account for orientation if ORIENTATION_TYPES.index(b_image.orientation) > 4: # Flip target_aspect = float(width) / float(height) aspect = float(b_image.height) / float(b_image.width) else: target_aspect = float(width) / float(height) aspect = float(b_image.width) / float(b_image.height) # Fix rotation b_image.auto_orient() # Calculate target size target_aspect = float(width) / float(height) aspect = float(b_image.width) / float(b_image.height) if ((target_aspect > aspect and not crop) or (target_aspect <= aspect and crop)): # target is wider than image, set height as maximum target_height = height # calculate width # - iw / ih = tw / th (keep aspect) # => th ( iw / ih ) = tw target_width = float(target_height) * aspect if crop: # calculate crop coords # - ( tw - w ) / 2 target_left = (float(target_width) - float(width)) / 2 target_left = int(round(target_left)) target_top = 0 # correct floating point error, and convert to int, round in the # direction of the requested width if width >= target_width: target_width = int(math.ceil(target_width)) else: target_width = int(math.floor(target_width)) else: # image is wider than target, set width as maximum target_width = width # calculate height # - iw / ih = tw / th (keep aspect) # => tw / ( iw / ih ) = th target_height = float(target_width) / aspect if crop: # calculate crop coords # - ( th - h ) / 2 target_top = (float(target_height) - float(height)) / 2 target_top = int(round(target_top)) target_left = 0 # correct floating point error and convert to int if height >= target_height: target_height = int(math.ceil(target_height)) else: target_height = int(math.floor(target_height)) # strip color profiles b_image.strip() # Resize b_image.resize(target_width, target_height) if crop: # Crop to target b_image.crop(left=target_left, top=target_top, width=width, height=height) # Save to temporary file temp_file = tempfile.TemporaryFile() b_image.save(file=temp_file) # Rewind the file temp_file.seek(0) return temp_file
[ "def", "_resize", "(", "image", ",", "width", ",", "height", ",", "crop", ")", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "image", ".", "name", ")", "[", "1", "]", ".", "strip", "(", "\".\"", ")", "with", "Image", "(", "file", "=", "image", ",", "format", "=", "ext", ")", "as", "b_image", ":", "# Account for orientation", "if", "ORIENTATION_TYPES", ".", "index", "(", "b_image", ".", "orientation", ")", ">", "4", ":", "# Flip", "target_aspect", "=", "float", "(", "width", ")", "/", "float", "(", "height", ")", "aspect", "=", "float", "(", "b_image", ".", "height", ")", "/", "float", "(", "b_image", ".", "width", ")", "else", ":", "target_aspect", "=", "float", "(", "width", ")", "/", "float", "(", "height", ")", "aspect", "=", "float", "(", "b_image", ".", "width", ")", "/", "float", "(", "b_image", ".", "height", ")", "# Fix rotation", "b_image", ".", "auto_orient", "(", ")", "# Calculate target size", "target_aspect", "=", "float", "(", "width", ")", "/", "float", "(", "height", ")", "aspect", "=", "float", "(", "b_image", ".", "width", ")", "/", "float", "(", "b_image", ".", "height", ")", "if", "(", "(", "target_aspect", ">", "aspect", "and", "not", "crop", ")", "or", "(", "target_aspect", "<=", "aspect", "and", "crop", ")", ")", ":", "# target is wider than image, set height as maximum", "target_height", "=", "height", "# calculate width", "# - iw / ih = tw / th (keep aspect)", "# => th ( iw / ih ) = tw", "target_width", "=", "float", "(", "target_height", ")", "*", "aspect", "if", "crop", ":", "# calculate crop coords", "# - ( tw - w ) / 2", "target_left", "=", "(", "float", "(", "target_width", ")", "-", "float", "(", "width", ")", ")", "/", "2", "target_left", "=", "int", "(", "round", "(", "target_left", ")", ")", "target_top", "=", "0", "# correct floating point error, and convert to int, round in the", "# direction of the requested width", "if", "width", ">=", "target_width", ":", "target_width", "=", "int", "(", "math", ".", "ceil", "(", "target_width", ")", ")", "else", ":", "target_width", "=", "int", "(", "math", ".", "floor", "(", "target_width", ")", ")", "else", ":", "# image is wider than target, set width as maximum", "target_width", "=", "width", "# calculate height", "# - iw / ih = tw / th (keep aspect)", "# => tw / ( iw / ih ) = th", "target_height", "=", "float", "(", "target_width", ")", "/", "aspect", "if", "crop", ":", "# calculate crop coords", "# - ( th - h ) / 2", "target_top", "=", "(", "float", "(", "target_height", ")", "-", "float", "(", "height", ")", ")", "/", "2", "target_top", "=", "int", "(", "round", "(", "target_top", ")", ")", "target_left", "=", "0", "# correct floating point error and convert to int", "if", "height", ">=", "target_height", ":", "target_height", "=", "int", "(", "math", ".", "ceil", "(", "target_height", ")", ")", "else", ":", "target_height", "=", "int", "(", "math", ".", "floor", "(", "target_height", ")", ")", "# strip color profiles", "b_image", ".", "strip", "(", ")", "# Resize", "b_image", ".", "resize", "(", "target_width", ",", "target_height", ")", "if", "crop", ":", "# Crop to target", "b_image", ".", "crop", "(", "left", "=", "target_left", ",", "top", "=", "target_top", ",", "width", "=", "width", ",", "height", "=", "height", ")", "# Save to temporary file", "temp_file", "=", "tempfile", ".", "TemporaryFile", "(", ")", "b_image", ".", "save", "(", "file", "=", "temp_file", ")", "# Rewind the file", "temp_file", ".", "seek", "(", "0", ")", "return", "temp_file" ]
Resize the image with respect to the aspect ratio
[ "Resize", "the", "image", "with", "respect", "to", "the", "aspect", "ratio" ]
5614eb1717948c65d179c3d1567439a8c90a4d44
https://github.com/zakdoek/django-simple-resizer/blob/5614eb1717948c65d179c3d1567439a8c90a4d44/simple_resizer/__init__.py#L60-L144
247,243
zakdoek/django-simple-resizer
simple_resizer/__init__.py
resize
def resize(image, width=None, height=None, crop=False): """ Resize an image and return the resized file. """ # First normalize params to determine which file to get width, height, crop = _normalize_params(image, width, height, crop) try: # Check the image file state for clean close is_closed = image.closed if is_closed: image.open() # Create the resized file # Do resize and crop resized_image = _resize(image, width, height, crop) finally: # Re-close if received a closed file if is_closed: image.close() return ImageFile(resized_image)
python
def resize(image, width=None, height=None, crop=False): """ Resize an image and return the resized file. """ # First normalize params to determine which file to get width, height, crop = _normalize_params(image, width, height, crop) try: # Check the image file state for clean close is_closed = image.closed if is_closed: image.open() # Create the resized file # Do resize and crop resized_image = _resize(image, width, height, crop) finally: # Re-close if received a closed file if is_closed: image.close() return ImageFile(resized_image)
[ "def", "resize", "(", "image", ",", "width", "=", "None", ",", "height", "=", "None", ",", "crop", "=", "False", ")", ":", "# First normalize params to determine which file to get", "width", ",", "height", ",", "crop", "=", "_normalize_params", "(", "image", ",", "width", ",", "height", ",", "crop", ")", "try", ":", "# Check the image file state for clean close", "is_closed", "=", "image", ".", "closed", "if", "is_closed", ":", "image", ".", "open", "(", ")", "# Create the resized file", "# Do resize and crop", "resized_image", "=", "_resize", "(", "image", ",", "width", ",", "height", ",", "crop", ")", "finally", ":", "# Re-close if received a closed file", "if", "is_closed", ":", "image", ".", "close", "(", ")", "return", "ImageFile", "(", "resized_image", ")" ]
Resize an image and return the resized file.
[ "Resize", "an", "image", "and", "return", "the", "resized", "file", "." ]
5614eb1717948c65d179c3d1567439a8c90a4d44
https://github.com/zakdoek/django-simple-resizer/blob/5614eb1717948c65d179c3d1567439a8c90a4d44/simple_resizer/__init__.py#L147-L169
247,244
zakdoek/django-simple-resizer
simple_resizer/__init__.py
resize_lazy
def resize_lazy(image, width=None, height=None, crop=False, force=False, namespace="resized", storage=default_storage, as_url=False): """ Returns the name of the resized file. Returns the url if as_url is True """ # First normalize params to determine which file to get width, height, crop = _normalize_params(image, width, height, crop) # Fetch the name of the resized image so i can test it if exists name = _get_resized_name(image, width, height, crop, namespace) # Fetch storage if an image has a specific storage try: storage = image.storage except AttributeError: pass # Test if exists or force if force or not storage.exists(name): resized_image = None try: resized_image = resize(image, width, height, crop) name = storage.save(name, resized_image) finally: if resized_image is not None: resized_image.close() if as_url: return storage.url(name) return name
python
def resize_lazy(image, width=None, height=None, crop=False, force=False, namespace="resized", storage=default_storage, as_url=False): """ Returns the name of the resized file. Returns the url if as_url is True """ # First normalize params to determine which file to get width, height, crop = _normalize_params(image, width, height, crop) # Fetch the name of the resized image so i can test it if exists name = _get_resized_name(image, width, height, crop, namespace) # Fetch storage if an image has a specific storage try: storage = image.storage except AttributeError: pass # Test if exists or force if force or not storage.exists(name): resized_image = None try: resized_image = resize(image, width, height, crop) name = storage.save(name, resized_image) finally: if resized_image is not None: resized_image.close() if as_url: return storage.url(name) return name
[ "def", "resize_lazy", "(", "image", ",", "width", "=", "None", ",", "height", "=", "None", ",", "crop", "=", "False", ",", "force", "=", "False", ",", "namespace", "=", "\"resized\"", ",", "storage", "=", "default_storage", ",", "as_url", "=", "False", ")", ":", "# First normalize params to determine which file to get", "width", ",", "height", ",", "crop", "=", "_normalize_params", "(", "image", ",", "width", ",", "height", ",", "crop", ")", "# Fetch the name of the resized image so i can test it if exists", "name", "=", "_get_resized_name", "(", "image", ",", "width", ",", "height", ",", "crop", ",", "namespace", ")", "# Fetch storage if an image has a specific storage", "try", ":", "storage", "=", "image", ".", "storage", "except", "AttributeError", ":", "pass", "# Test if exists or force", "if", "force", "or", "not", "storage", ".", "exists", "(", "name", ")", ":", "resized_image", "=", "None", "try", ":", "resized_image", "=", "resize", "(", "image", ",", "width", ",", "height", ",", "crop", ")", "name", "=", "storage", ".", "save", "(", "name", ",", "resized_image", ")", "finally", ":", "if", "resized_image", "is", "not", "None", ":", "resized_image", ".", "close", "(", ")", "if", "as_url", ":", "return", "storage", ".", "url", "(", "name", ")", "return", "name" ]
Returns the name of the resized file. Returns the url if as_url is True
[ "Returns", "the", "name", "of", "the", "resized", "file", ".", "Returns", "the", "url", "if", "as_url", "is", "True" ]
5614eb1717948c65d179c3d1567439a8c90a4d44
https://github.com/zakdoek/django-simple-resizer/blob/5614eb1717948c65d179c3d1567439a8c90a4d44/simple_resizer/__init__.py#L173-L203
247,245
zakdoek/django-simple-resizer
simple_resizer/__init__.py
resized
def resized(*args, **kwargs): """ Auto file closing resize function """ resized_image = None try: resized_image = resize(*args, **kwargs) yield resized_image finally: if resized_image is not None: resized_image.close()
python
def resized(*args, **kwargs): """ Auto file closing resize function """ resized_image = None try: resized_image = resize(*args, **kwargs) yield resized_image finally: if resized_image is not None: resized_image.close()
[ "def", "resized", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "resized_image", "=", "None", "try", ":", "resized_image", "=", "resize", "(", "*", "args", ",", "*", "*", "kwargs", ")", "yield", "resized_image", "finally", ":", "if", "resized_image", "is", "not", "None", ":", "resized_image", ".", "close", "(", ")" ]
Auto file closing resize function
[ "Auto", "file", "closing", "resize", "function" ]
5614eb1717948c65d179c3d1567439a8c90a4d44
https://github.com/zakdoek/django-simple-resizer/blob/5614eb1717948c65d179c3d1567439a8c90a4d44/simple_resizer/__init__.py#L208-L218
247,246
Tinche/django-bower-cache
registry/bowerlib.py
get_package
def get_package(repo_url, pkg_name, timeout=1): """Retrieve package information from a Bower registry at repo_url. Returns a dict of package data.""" url = repo_url + "/packages/" + pkg_name headers = {'accept': 'application/json'} resp = requests.get(url, headers=headers, timeout=timeout) if resp.status_code == 404: return None return resp.json()
python
def get_package(repo_url, pkg_name, timeout=1): """Retrieve package information from a Bower registry at repo_url. Returns a dict of package data.""" url = repo_url + "/packages/" + pkg_name headers = {'accept': 'application/json'} resp = requests.get(url, headers=headers, timeout=timeout) if resp.status_code == 404: return None return resp.json()
[ "def", "get_package", "(", "repo_url", ",", "pkg_name", ",", "timeout", "=", "1", ")", ":", "url", "=", "repo_url", "+", "\"/packages/\"", "+", "pkg_name", "headers", "=", "{", "'accept'", ":", "'application/json'", "}", "resp", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "headers", ",", "timeout", "=", "timeout", ")", "if", "resp", ".", "status_code", "==", "404", ":", "return", "None", "return", "resp", ".", "json", "(", ")" ]
Retrieve package information from a Bower registry at repo_url. Returns a dict of package data.
[ "Retrieve", "package", "information", "from", "a", "Bower", "registry", "at", "repo_url", "." ]
5245b2ee80c33c09d85ce0bf8f047825d9df2118
https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/bowerlib.py#L5-L14
247,247
jtpaasch/simplygithub
simplygithub/internals/commits.py
get_commit
def get_commit(profile, sha): """Fetch a commit. 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. sha The SHA of the commit to fetch. Returns: A dict with data about the commit. """ resource = "/commits/" + sha data = api.get_request(profile, resource) return prepare(data)
python
def get_commit(profile, sha): """Fetch a commit. 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. sha The SHA of the commit to fetch. Returns: A dict with data about the commit. """ resource = "/commits/" + sha data = api.get_request(profile, resource) return prepare(data)
[ "def", "get_commit", "(", "profile", ",", "sha", ")", ":", "resource", "=", "\"/commits/\"", "+", "sha", "data", "=", "api", ".", "get_request", "(", "profile", ",", "resource", ")", "return", "prepare", "(", "data", ")" ]
Fetch a commit. 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. sha The SHA of the commit to fetch. Returns: A dict with data about the commit.
[ "Fetch", "a", "commit", "." ]
b77506275ec276ce90879bf1ea9299a79448b903
https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/internals/commits.py#L17-L36
247,248
jtpaasch/simplygithub
simplygithub/internals/commits.py
create_commit
def create_commit(profile, message, tree, parents): """Create a commit. 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. message The commit message to give to the commit. tree The SHA of the tree to assign to the commit. parents A list enumerating the SHAs of the new commit's parent commits. Returns: A dict with data about the commit. """ resource = "/commits" payload = {"message": message, "tree": tree, "parents": parents} data = api.post_request(profile, resource, payload) return prepare(data)
python
def create_commit(profile, message, tree, parents): """Create a commit. 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. message The commit message to give to the commit. tree The SHA of the tree to assign to the commit. parents A list enumerating the SHAs of the new commit's parent commits. Returns: A dict with data about the commit. """ resource = "/commits" payload = {"message": message, "tree": tree, "parents": parents} data = api.post_request(profile, resource, payload) return prepare(data)
[ "def", "create_commit", "(", "profile", ",", "message", ",", "tree", ",", "parents", ")", ":", "resource", "=", "\"/commits\"", "payload", "=", "{", "\"message\"", ":", "message", ",", "\"tree\"", ":", "tree", ",", "\"parents\"", ":", "parents", "}", "data", "=", "api", ".", "post_request", "(", "profile", ",", "resource", ",", "payload", ")", "return", "prepare", "(", "data", ")" ]
Create a commit. 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. message The commit message to give to the commit. tree The SHA of the tree to assign to the commit. parents A list enumerating the SHAs of the new commit's parent commits. Returns: A dict with data about the commit.
[ "Create", "a", "commit", "." ]
b77506275ec276ce90879bf1ea9299a79448b903
https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/internals/commits.py#L39-L65
247,249
edeposit/edeposit.amqp.storage
src/edeposit/amqp/storage/structures/comm/tree.py
Tree.collect_publications
def collect_publications(self): """ Recursively collect list of all publications referenced in this tree and all sub-trees. Returns: list: List of UUID strings. """ pubs = list(self.sub_publications) for sub_tree in self.sub_trees: pubs.extend(sub_tree.collect_publications()) return pubs
python
def collect_publications(self): """ Recursively collect list of all publications referenced in this tree and all sub-trees. Returns: list: List of UUID strings. """ pubs = list(self.sub_publications) for sub_tree in self.sub_trees: pubs.extend(sub_tree.collect_publications()) return pubs
[ "def", "collect_publications", "(", "self", ")", ":", "pubs", "=", "list", "(", "self", ".", "sub_publications", ")", "for", "sub_tree", "in", "self", ".", "sub_trees", ":", "pubs", ".", "extend", "(", "sub_tree", ".", "collect_publications", "(", ")", ")", "return", "pubs" ]
Recursively collect list of all publications referenced in this tree and all sub-trees. Returns: list: List of UUID strings.
[ "Recursively", "collect", "list", "of", "all", "publications", "referenced", "in", "this", "tree", "and", "all", "sub", "-", "trees", "." ]
fb6bd326249847de04b17b64e856c878665cea92
https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/structures/comm/tree.py#L113-L126
247,250
opinkerfi/nago
nago/settings/__init__.py
get_option
def get_option(option_name, section_name="main", default=_sentinel, cfg_file=cfg_file): """ Returns a specific option specific in a config file Arguments: option_name -- Name of the option (example host_name) section_name -- Which section of the config (default: name) examples: >>> get_option("some option", default="default result") 'default result' """ defaults = get_defaults() # As a quality issue, we strictly disallow looking up an option that does not have a default # value specified in the code #if option_name not in defaults.get(section_name, {}) and default == _sentinel: # raise ValueError("There is no default value for Option %s in section %s" % (option_name, section_name)) # If default argument was provided, we set variable my_defaults to that # otherwise use the global nago defaults if default != _sentinel: my_defaults = {option_name: default} else: my_defaults = defaults.get('section_name', {}) # Lets parse our configuration file and see what we get parser = get_parser(cfg_file) return parser.get(section_name, option_name, vars=my_defaults)
python
def get_option(option_name, section_name="main", default=_sentinel, cfg_file=cfg_file): """ Returns a specific option specific in a config file Arguments: option_name -- Name of the option (example host_name) section_name -- Which section of the config (default: name) examples: >>> get_option("some option", default="default result") 'default result' """ defaults = get_defaults() # As a quality issue, we strictly disallow looking up an option that does not have a default # value specified in the code #if option_name not in defaults.get(section_name, {}) and default == _sentinel: # raise ValueError("There is no default value for Option %s in section %s" % (option_name, section_name)) # If default argument was provided, we set variable my_defaults to that # otherwise use the global nago defaults if default != _sentinel: my_defaults = {option_name: default} else: my_defaults = defaults.get('section_name', {}) # Lets parse our configuration file and see what we get parser = get_parser(cfg_file) return parser.get(section_name, option_name, vars=my_defaults)
[ "def", "get_option", "(", "option_name", ",", "section_name", "=", "\"main\"", ",", "default", "=", "_sentinel", ",", "cfg_file", "=", "cfg_file", ")", ":", "defaults", "=", "get_defaults", "(", ")", "# As a quality issue, we strictly disallow looking up an option that does not have a default", "# value specified in the code", "#if option_name not in defaults.get(section_name, {}) and default == _sentinel:", "# raise ValueError(\"There is no default value for Option %s in section %s\" % (option_name, section_name))", "# If default argument was provided, we set variable my_defaults to that", "# otherwise use the global nago defaults", "if", "default", "!=", "_sentinel", ":", "my_defaults", "=", "{", "option_name", ":", "default", "}", "else", ":", "my_defaults", "=", "defaults", ".", "get", "(", "'section_name'", ",", "{", "}", ")", "# Lets parse our configuration file and see what we get", "parser", "=", "get_parser", "(", "cfg_file", ")", "return", "parser", ".", "get", "(", "section_name", ",", "option_name", ",", "vars", "=", "my_defaults", ")" ]
Returns a specific option specific in a config file Arguments: option_name -- Name of the option (example host_name) section_name -- Which section of the config (default: name) examples: >>> get_option("some option", default="default result") 'default result'
[ "Returns", "a", "specific", "option", "specific", "in", "a", "config", "file" ]
85e1bdd1de0122f56868a483e7599e1b36a439b0
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/settings/__init__.py#L17-L44
247,251
opinkerfi/nago
nago/settings/__init__.py
set_option
def set_option(section='main', cfg_file=cfg_file, **kwargs): """ Change an option in our configuration file """ parser = get_parser(cfg_file=cfg_file) if section not in parser.sections(): parser.add_section(section) for k, v in kwargs.items(): parser.set(section=section, option=k, value=v) with open(cfg_file, 'w') as f: parser.write(f) return "Done"
python
def set_option(section='main', cfg_file=cfg_file, **kwargs): """ Change an option in our configuration file """ parser = get_parser(cfg_file=cfg_file) if section not in parser.sections(): parser.add_section(section) for k, v in kwargs.items(): parser.set(section=section, option=k, value=v) with open(cfg_file, 'w') as f: parser.write(f) return "Done"
[ "def", "set_option", "(", "section", "=", "'main'", ",", "cfg_file", "=", "cfg_file", ",", "*", "*", "kwargs", ")", ":", "parser", "=", "get_parser", "(", "cfg_file", "=", "cfg_file", ")", "if", "section", "not", "in", "parser", ".", "sections", "(", ")", ":", "parser", ".", "add_section", "(", "section", ")", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "parser", ".", "set", "(", "section", "=", "section", ",", "option", "=", "k", ",", "value", "=", "v", ")", "with", "open", "(", "cfg_file", ",", "'w'", ")", "as", "f", ":", "parser", ".", "write", "(", "f", ")", "return", "\"Done\"" ]
Change an option in our configuration file
[ "Change", "an", "option", "in", "our", "configuration", "file" ]
85e1bdd1de0122f56868a483e7599e1b36a439b0
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/settings/__init__.py#L61-L72
247,252
opinkerfi/nago
nago/settings/__init__.py
get_section
def get_section(section_name, cfg_file=cfg_file): """ Returns a dictionary of an entire section """ parser = get_parser(cfg_file=cfg_file) options = parser.options(section_name) result = {} for option in options: result[option] = parser.get(section=section_name, option=option) return result
python
def get_section(section_name, cfg_file=cfg_file): """ Returns a dictionary of an entire section """ parser = get_parser(cfg_file=cfg_file) options = parser.options(section_name) result = {} for option in options: result[option] = parser.get(section=section_name, option=option) return result
[ "def", "get_section", "(", "section_name", ",", "cfg_file", "=", "cfg_file", ")", ":", "parser", "=", "get_parser", "(", "cfg_file", "=", "cfg_file", ")", "options", "=", "parser", ".", "options", "(", "section_name", ")", "result", "=", "{", "}", "for", "option", "in", "options", ":", "result", "[", "option", "]", "=", "parser", ".", "get", "(", "section", "=", "section_name", ",", "option", "=", "option", ")", "return", "result" ]
Returns a dictionary of an entire section
[ "Returns", "a", "dictionary", "of", "an", "entire", "section" ]
85e1bdd1de0122f56868a483e7599e1b36a439b0
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/settings/__init__.py#L75-L82
247,253
opinkerfi/nago
nago/settings/__init__.py
_mkdir_for_config
def _mkdir_for_config(cfg_file=cfg_file): """ Given a path to a filename, make sure the directory exists """ dirname, filename = os.path.split(cfg_file) try: os.makedirs(dirname) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(dirname): pass else: raise
python
def _mkdir_for_config(cfg_file=cfg_file): """ Given a path to a filename, make sure the directory exists """ dirname, filename = os.path.split(cfg_file) try: os.makedirs(dirname) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(dirname): pass else: raise
[ "def", "_mkdir_for_config", "(", "cfg_file", "=", "cfg_file", ")", ":", "dirname", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "cfg_file", ")", "try", ":", "os", ".", "makedirs", "(", "dirname", ")", "except", "OSError", "as", "exc", ":", "if", "exc", ".", "errno", "==", "errno", ".", "EEXIST", "and", "os", ".", "path", ".", "isdir", "(", "dirname", ")", ":", "pass", "else", ":", "raise" ]
Given a path to a filename, make sure the directory exists
[ "Given", "a", "path", "to", "a", "filename", "make", "sure", "the", "directory", "exists" ]
85e1bdd1de0122f56868a483e7599e1b36a439b0
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/settings/__init__.py#L84-L93
247,254
opinkerfi/nago
nago/settings/__init__.py
generate_configfile
def generate_configfile(cfg_file,defaults=defaults): """ Write a new nago.ini config file from the defaults. Arguments: cfg_file -- File that is written to like /etc/nago/nago.ini defaults -- Dictionary with default values to use """ # Create a directory if needed and write an empty file _mkdir_for_config(cfg_file=cfg_file) with open(cfg_file, 'w') as f: f.write('') for section in defaults.keys(): set_option(section, cfg_file=cfg_file, **defaults[section])
python
def generate_configfile(cfg_file,defaults=defaults): """ Write a new nago.ini config file from the defaults. Arguments: cfg_file -- File that is written to like /etc/nago/nago.ini defaults -- Dictionary with default values to use """ # Create a directory if needed and write an empty file _mkdir_for_config(cfg_file=cfg_file) with open(cfg_file, 'w') as f: f.write('') for section in defaults.keys(): set_option(section, cfg_file=cfg_file, **defaults[section])
[ "def", "generate_configfile", "(", "cfg_file", ",", "defaults", "=", "defaults", ")", ":", "# Create a directory if needed and write an empty file", "_mkdir_for_config", "(", "cfg_file", "=", "cfg_file", ")", "with", "open", "(", "cfg_file", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "''", ")", "for", "section", "in", "defaults", ".", "keys", "(", ")", ":", "set_option", "(", "section", ",", "cfg_file", "=", "cfg_file", ",", "*", "*", "defaults", "[", "section", "]", ")" ]
Write a new nago.ini config file from the defaults. Arguments: cfg_file -- File that is written to like /etc/nago/nago.ini defaults -- Dictionary with default values to use
[ "Write", "a", "new", "nago", ".", "ini", "config", "file", "from", "the", "defaults", "." ]
85e1bdd1de0122f56868a483e7599e1b36a439b0
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/settings/__init__.py#L96-L108
247,255
frejanordsiek/GeminiMotorDrive
GeminiMotorDrive/utilities.py
strip_commands
def strip_commands(commands): """ Strips a sequence of commands. Strips down the sequence of commands by removing comments and surrounding whitespace around each individual command and then removing blank commands. Parameters ---------- commands : iterable of strings Iterable of commands to strip. Returns ------- stripped_commands : list of str The stripped commands with blank ones removed. """ # Go through each command one by one, stripping it and adding it to # a growing list if it is not blank. Each command needs to be # converted to an str if it is a bytes. stripped_commands = [] for v in commands: if isinstance(v, bytes): v = v.decode(errors='replace') v = v.split(';')[0].strip() if len(v) != 0: stripped_commands.append(v) return stripped_commands
python
def strip_commands(commands): """ Strips a sequence of commands. Strips down the sequence of commands by removing comments and surrounding whitespace around each individual command and then removing blank commands. Parameters ---------- commands : iterable of strings Iterable of commands to strip. Returns ------- stripped_commands : list of str The stripped commands with blank ones removed. """ # Go through each command one by one, stripping it and adding it to # a growing list if it is not blank. Each command needs to be # converted to an str if it is a bytes. stripped_commands = [] for v in commands: if isinstance(v, bytes): v = v.decode(errors='replace') v = v.split(';')[0].strip() if len(v) != 0: stripped_commands.append(v) return stripped_commands
[ "def", "strip_commands", "(", "commands", ")", ":", "# Go through each command one by one, stripping it and adding it to", "# a growing list if it is not blank. Each command needs to be", "# converted to an str if it is a bytes.", "stripped_commands", "=", "[", "]", "for", "v", "in", "commands", ":", "if", "isinstance", "(", "v", ",", "bytes", ")", ":", "v", "=", "v", ".", "decode", "(", "errors", "=", "'replace'", ")", "v", "=", "v", ".", "split", "(", "';'", ")", "[", "0", "]", ".", "strip", "(", ")", "if", "len", "(", "v", ")", "!=", "0", ":", "stripped_commands", ".", "append", "(", "v", ")", "return", "stripped_commands" ]
Strips a sequence of commands. Strips down the sequence of commands by removing comments and surrounding whitespace around each individual command and then removing blank commands. Parameters ---------- commands : iterable of strings Iterable of commands to strip. Returns ------- stripped_commands : list of str The stripped commands with blank ones removed.
[ "Strips", "a", "sequence", "of", "commands", "." ]
8de347ffb91228fbfe3832098b4996fa0141d8f1
https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/utilities.py#L22-L50
247,256
OpenVolunteeringPlatform/django-ovp-core
ovp_core/views.py
startup
def startup(request): """ This view provides initial data to the client, such as available skills and causes """ with translation.override(translation.get_language_from_request(request)): skills = serializers.SkillSerializer(models.Skill.objects.all(), many=True) causes = serializers.CauseSerializer(models.Cause.objects.all(), many=True) cities = serializers.GoogleAddressCityStateSerializer(models.GoogleAddress.objects.all(), many=True) return response.Response({ "skills": skills.data, "causes": causes.data, "cities": cities.data })
python
def startup(request): """ This view provides initial data to the client, such as available skills and causes """ with translation.override(translation.get_language_from_request(request)): skills = serializers.SkillSerializer(models.Skill.objects.all(), many=True) causes = serializers.CauseSerializer(models.Cause.objects.all(), many=True) cities = serializers.GoogleAddressCityStateSerializer(models.GoogleAddress.objects.all(), many=True) return response.Response({ "skills": skills.data, "causes": causes.data, "cities": cities.data })
[ "def", "startup", "(", "request", ")", ":", "with", "translation", ".", "override", "(", "translation", ".", "get_language_from_request", "(", "request", ")", ")", ":", "skills", "=", "serializers", ".", "SkillSerializer", "(", "models", ".", "Skill", ".", "objects", ".", "all", "(", ")", ",", "many", "=", "True", ")", "causes", "=", "serializers", ".", "CauseSerializer", "(", "models", ".", "Cause", ".", "objects", ".", "all", "(", ")", ",", "many", "=", "True", ")", "cities", "=", "serializers", ".", "GoogleAddressCityStateSerializer", "(", "models", ".", "GoogleAddress", ".", "objects", ".", "all", "(", ")", ",", "many", "=", "True", ")", "return", "response", ".", "Response", "(", "{", "\"skills\"", ":", "skills", ".", "data", ",", "\"causes\"", ":", "causes", ".", "data", ",", "\"cities\"", ":", "cities", ".", "data", "}", ")" ]
This view provides initial data to the client, such as available skills and causes
[ "This", "view", "provides", "initial", "data", "to", "the", "client", "such", "as", "available", "skills", "and", "causes" ]
c81b868a0a4b317f7b1ec0718cabc34f7794dd20
https://github.com/OpenVolunteeringPlatform/django-ovp-core/blob/c81b868a0a4b317f7b1ec0718cabc34f7794dd20/ovp_core/views.py#L12-L23
247,257
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_line_is_shebang
def _line_is_shebang(line): """Return true if line is a shebang.""" regex = re.compile(r"^(#!|@echo off).*$") if regex.match(line): return True return False
python
def _line_is_shebang(line): """Return true if line is a shebang.""" regex = re.compile(r"^(#!|@echo off).*$") if regex.match(line): return True return False
[ "def", "_line_is_shebang", "(", "line", ")", ":", "regex", "=", "re", ".", "compile", "(", "r\"^(#!|@echo off).*$\"", ")", "if", "regex", ".", "match", "(", "line", ")", ":", "return", "True", "return", "False" ]
Return true if line is a shebang.
[ "Return", "true", "if", "line", "is", "a", "shebang", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L92-L98
247,258
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_filename_in_headerblock
def _filename_in_headerblock(relative_path, contents, linter_options): """Check for a filename in a header block. like such: # /path/to/filename """ del linter_options check_index = 0 if len(contents) > 0: if _line_is_shebang(contents[0]): check_index = 1 if len(contents) < check_index + 1: description = ("""Document cannot have less than """ """{0} lines""").format(check_index + 1) return LinterFailure(description, 1, replacement=None) header_path = relative_path.replace("\\", "/") regex = re.compile(r"^{0} \/{1}$".format(_HDR_COMMENT, re.escape(header_path))) if not regex.match(contents[check_index]): description = ("""The filename /{0} must be the """ """first line of the header""") return LinterFailure(description.format(header_path), check_index + 1, _comment_type_from_line(contents[check_index]) + "/{0}\n".format(header_path))
python
def _filename_in_headerblock(relative_path, contents, linter_options): """Check for a filename in a header block. like such: # /path/to/filename """ del linter_options check_index = 0 if len(contents) > 0: if _line_is_shebang(contents[0]): check_index = 1 if len(contents) < check_index + 1: description = ("""Document cannot have less than """ """{0} lines""").format(check_index + 1) return LinterFailure(description, 1, replacement=None) header_path = relative_path.replace("\\", "/") regex = re.compile(r"^{0} \/{1}$".format(_HDR_COMMENT, re.escape(header_path))) if not regex.match(contents[check_index]): description = ("""The filename /{0} must be the """ """first line of the header""") return LinterFailure(description.format(header_path), check_index + 1, _comment_type_from_line(contents[check_index]) + "/{0}\n".format(header_path))
[ "def", "_filename_in_headerblock", "(", "relative_path", ",", "contents", ",", "linter_options", ")", ":", "del", "linter_options", "check_index", "=", "0", "if", "len", "(", "contents", ")", ">", "0", ":", "if", "_line_is_shebang", "(", "contents", "[", "0", "]", ")", ":", "check_index", "=", "1", "if", "len", "(", "contents", ")", "<", "check_index", "+", "1", ":", "description", "=", "(", "\"\"\"Document cannot have less than \"\"\"", "\"\"\"{0} lines\"\"\"", ")", ".", "format", "(", "check_index", "+", "1", ")", "return", "LinterFailure", "(", "description", ",", "1", ",", "replacement", "=", "None", ")", "header_path", "=", "relative_path", ".", "replace", "(", "\"\\\\\"", ",", "\"/\"", ")", "regex", "=", "re", ".", "compile", "(", "r\"^{0} \\/{1}$\"", ".", "format", "(", "_HDR_COMMENT", ",", "re", ".", "escape", "(", "header_path", ")", ")", ")", "if", "not", "regex", ".", "match", "(", "contents", "[", "check_index", "]", ")", ":", "description", "=", "(", "\"\"\"The filename /{0} must be the \"\"\"", "\"\"\"first line of the header\"\"\"", ")", "return", "LinterFailure", "(", "description", ".", "format", "(", "header_path", ")", ",", "check_index", "+", "1", ",", "_comment_type_from_line", "(", "contents", "[", "check_index", "]", ")", "+", "\"/{0}\\n\"", ".", "format", "(", "header_path", ")", ")" ]
Check for a filename in a header block. like such: # /path/to/filename
[ "Check", "for", "a", "filename", "in", "a", "header", "block", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L101-L128
247,259
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_match_space_at_line
def _match_space_at_line(line): """Return a re.match object if an empty comment was found on line.""" regex = re.compile(r"^{0}$".format(_MDL_COMMENT)) return regex.match(line)
python
def _match_space_at_line(line): """Return a re.match object if an empty comment was found on line.""" regex = re.compile(r"^{0}$".format(_MDL_COMMENT)) return regex.match(line)
[ "def", "_match_space_at_line", "(", "line", ")", ":", "regex", "=", "re", ".", "compile", "(", "r\"^{0}$\"", ".", "format", "(", "_MDL_COMMENT", ")", ")", "return", "regex", ".", "match", "(", "line", ")" ]
Return a re.match object if an empty comment was found on line.
[ "Return", "a", "re", ".", "match", "object", "if", "an", "empty", "comment", "was", "found", "on", "line", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L131-L134
247,260
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_find_last_line_index
def _find_last_line_index(contents): """Find the last line of the headerblock in contents.""" lineno = 0 headerblock = re.compile(r"^{0}.*$".format(_ALL_COMMENT)) if not len(contents): raise RuntimeError("""File does not not have any contents""") while headerblock.match(contents[lineno]): if lineno + 1 == len(contents): raise RuntimeError("""No end of headerblock in file""") lineno = lineno + 1 if lineno < 2: raise RuntimeError("""Headerblock must have at least two lines""") return lineno - 1
python
def _find_last_line_index(contents): """Find the last line of the headerblock in contents.""" lineno = 0 headerblock = re.compile(r"^{0}.*$".format(_ALL_COMMENT)) if not len(contents): raise RuntimeError("""File does not not have any contents""") while headerblock.match(contents[lineno]): if lineno + 1 == len(contents): raise RuntimeError("""No end of headerblock in file""") lineno = lineno + 1 if lineno < 2: raise RuntimeError("""Headerblock must have at least two lines""") return lineno - 1
[ "def", "_find_last_line_index", "(", "contents", ")", ":", "lineno", "=", "0", "headerblock", "=", "re", ".", "compile", "(", "r\"^{0}.*$\"", ".", "format", "(", "_ALL_COMMENT", ")", ")", "if", "not", "len", "(", "contents", ")", ":", "raise", "RuntimeError", "(", "\"\"\"File does not not have any contents\"\"\"", ")", "while", "headerblock", ".", "match", "(", "contents", "[", "lineno", "]", ")", ":", "if", "lineno", "+", "1", "==", "len", "(", "contents", ")", ":", "raise", "RuntimeError", "(", "\"\"\"No end of headerblock in file\"\"\"", ")", "lineno", "=", "lineno", "+", "1", "if", "lineno", "<", "2", ":", "raise", "RuntimeError", "(", "\"\"\"Headerblock must have at least two lines\"\"\"", ")", "return", "lineno", "-", "1" ]
Find the last line of the headerblock in contents.
[ "Find", "the", "last", "line", "of", "the", "headerblock", "in", "contents", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L168-L184
247,261
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_copyright_end_of_headerblock
def _copyright_end_of_headerblock(relative_path, contents, linter_options): """Check for copyright notice at end of headerblock.""" del relative_path del linter_options lineno = _find_last_line_index(contents) notice = "See /LICENCE.md for Copyright information" regex = re.compile(r"^{0} {1}( .*$|$)".format(_MDL_COMMENT, notice)) if not regex.match(contents[lineno]): description = ("""The last of the header block line must have the """ """following notice: {0}""") replacement = None comment = _comment_type_from_line(contents[lineno]) comment_footer = _end_comment_type_from_line(contents[lineno]) # If the last line has the words "Copyright" or "/LICENCE.md" the # user probably attempted to add a notice, but failed, so just # suggest replacing the whole line if re.compile(r"^.*(Copyright|LICENCE.md).*$").match(contents[lineno]): replacement = "{0}{1}\n".format(comment, notice + comment_footer) # Put the copyright notice on a new line else: # Strip off the footer and the \n at the end of the line. repl_contents = contents[lineno][:-(len(comment_footer) + 1)] replacement = "{0}\n{1}{2}\n".format(repl_contents, comment, notice + comment_footer) return LinterFailure(description.format(notice), lineno + 1, replacement)
python
def _copyright_end_of_headerblock(relative_path, contents, linter_options): """Check for copyright notice at end of headerblock.""" del relative_path del linter_options lineno = _find_last_line_index(contents) notice = "See /LICENCE.md for Copyright information" regex = re.compile(r"^{0} {1}( .*$|$)".format(_MDL_COMMENT, notice)) if not regex.match(contents[lineno]): description = ("""The last of the header block line must have the """ """following notice: {0}""") replacement = None comment = _comment_type_from_line(contents[lineno]) comment_footer = _end_comment_type_from_line(contents[lineno]) # If the last line has the words "Copyright" or "/LICENCE.md" the # user probably attempted to add a notice, but failed, so just # suggest replacing the whole line if re.compile(r"^.*(Copyright|LICENCE.md).*$").match(contents[lineno]): replacement = "{0}{1}\n".format(comment, notice + comment_footer) # Put the copyright notice on a new line else: # Strip off the footer and the \n at the end of the line. repl_contents = contents[lineno][:-(len(comment_footer) + 1)] replacement = "{0}\n{1}{2}\n".format(repl_contents, comment, notice + comment_footer) return LinterFailure(description.format(notice), lineno + 1, replacement)
[ "def", "_copyright_end_of_headerblock", "(", "relative_path", ",", "contents", ",", "linter_options", ")", ":", "del", "relative_path", "del", "linter_options", "lineno", "=", "_find_last_line_index", "(", "contents", ")", "notice", "=", "\"See /LICENCE.md for Copyright information\"", "regex", "=", "re", ".", "compile", "(", "r\"^{0} {1}( .*$|$)\"", ".", "format", "(", "_MDL_COMMENT", ",", "notice", ")", ")", "if", "not", "regex", ".", "match", "(", "contents", "[", "lineno", "]", ")", ":", "description", "=", "(", "\"\"\"The last of the header block line must have the \"\"\"", "\"\"\"following notice: {0}\"\"\"", ")", "replacement", "=", "None", "comment", "=", "_comment_type_from_line", "(", "contents", "[", "lineno", "]", ")", "comment_footer", "=", "_end_comment_type_from_line", "(", "contents", "[", "lineno", "]", ")", "# If the last line has the words \"Copyright\" or \"/LICENCE.md\" the", "# user probably attempted to add a notice, but failed, so just", "# suggest replacing the whole line", "if", "re", ".", "compile", "(", "r\"^.*(Copyright|LICENCE.md).*$\"", ")", ".", "match", "(", "contents", "[", "lineno", "]", ")", ":", "replacement", "=", "\"{0}{1}\\n\"", ".", "format", "(", "comment", ",", "notice", "+", "comment_footer", ")", "# Put the copyright notice on a new line", "else", ":", "# Strip off the footer and the \\n at the end of the line.", "repl_contents", "=", "contents", "[", "lineno", "]", "[", ":", "-", "(", "len", "(", "comment_footer", ")", "+", "1", ")", "]", "replacement", "=", "\"{0}\\n{1}{2}\\n\"", ".", "format", "(", "repl_contents", ",", "comment", ",", "notice", "+", "comment_footer", ")", "return", "LinterFailure", "(", "description", ".", "format", "(", "notice", ")", ",", "lineno", "+", "1", ",", "replacement", ")" ]
Check for copyright notice at end of headerblock.
[ "Check", "for", "copyright", "notice", "at", "end", "of", "headerblock", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L206-L235
247,262
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_populate_spelling_error
def _populate_spelling_error(word, suggestions, contents, line_offset, column_offset, message_start): """Create a LinterFailure for word. This function takes suggestions from :suggestions: and uses it to populate the message and candidate replacement. The replacement will be a line in :contents:, as determined by :line_offset: and :column_offset:. """ error_line = contents[line_offset] if len(suggestions): char_word_offset = (column_offset + len(word)) replacement = (error_line[:column_offset] + suggestions[0] + error_line[char_word_offset:]) else: replacement = None if len(suggestions): suggestions_text = (""", perhaps you meant """ + " ".join(suggestions)) else: suggestions_text = "" format_desc = message_start + suggestions_text return LinterFailure(format_desc, line_offset + 1, replacement)
python
def _populate_spelling_error(word, suggestions, contents, line_offset, column_offset, message_start): """Create a LinterFailure for word. This function takes suggestions from :suggestions: and uses it to populate the message and candidate replacement. The replacement will be a line in :contents:, as determined by :line_offset: and :column_offset:. """ error_line = contents[line_offset] if len(suggestions): char_word_offset = (column_offset + len(word)) replacement = (error_line[:column_offset] + suggestions[0] + error_line[char_word_offset:]) else: replacement = None if len(suggestions): suggestions_text = (""", perhaps you meant """ + " ".join(suggestions)) else: suggestions_text = "" format_desc = message_start + suggestions_text return LinterFailure(format_desc, line_offset + 1, replacement)
[ "def", "_populate_spelling_error", "(", "word", ",", "suggestions", ",", "contents", ",", "line_offset", ",", "column_offset", ",", "message_start", ")", ":", "error_line", "=", "contents", "[", "line_offset", "]", "if", "len", "(", "suggestions", ")", ":", "char_word_offset", "=", "(", "column_offset", "+", "len", "(", "word", ")", ")", "replacement", "=", "(", "error_line", "[", ":", "column_offset", "]", "+", "suggestions", "[", "0", "]", "+", "error_line", "[", "char_word_offset", ":", "]", ")", "else", ":", "replacement", "=", "None", "if", "len", "(", "suggestions", ")", ":", "suggestions_text", "=", "(", "\"\"\", perhaps you meant \"\"\"", "+", "\" \"", ".", "join", "(", "suggestions", ")", ")", "else", ":", "suggestions_text", "=", "\"\"", "format_desc", "=", "message_start", "+", "suggestions_text", "return", "LinterFailure", "(", "format_desc", ",", "line_offset", "+", "1", ",", "replacement", ")" ]
Create a LinterFailure for word. This function takes suggestions from :suggestions: and uses it to populate the message and candidate replacement. The replacement will be a line in :contents:, as determined by :line_offset: and :column_offset:.
[ "Create", "a", "LinterFailure", "for", "word", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L272-L303
247,263
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_find_spelling_errors_in_chunks
def _find_spelling_errors_in_chunks(chunks, contents, valid_words_dictionary=None, technical_words_dictionary=None, user_dictionary_words=None): """For each chunk and a set of valid and technical words, find errors.""" for chunk in chunks: for error in spellcheck_region(chunk.data, valid_words_dictionary, technical_words_dictionary, user_dictionary_words): col_offset = _determine_character_offset(error.line_offset, error.column_offset, chunk.column) msg = _SPELLCHECK_MESSAGES[error.error_type].format(error.word) yield _populate_spelling_error(error.word, error.suggestions, contents, error.line_offset + chunk.line, col_offset, msg)
python
def _find_spelling_errors_in_chunks(chunks, contents, valid_words_dictionary=None, technical_words_dictionary=None, user_dictionary_words=None): """For each chunk and a set of valid and technical words, find errors.""" for chunk in chunks: for error in spellcheck_region(chunk.data, valid_words_dictionary, technical_words_dictionary, user_dictionary_words): col_offset = _determine_character_offset(error.line_offset, error.column_offset, chunk.column) msg = _SPELLCHECK_MESSAGES[error.error_type].format(error.word) yield _populate_spelling_error(error.word, error.suggestions, contents, error.line_offset + chunk.line, col_offset, msg)
[ "def", "_find_spelling_errors_in_chunks", "(", "chunks", ",", "contents", ",", "valid_words_dictionary", "=", "None", ",", "technical_words_dictionary", "=", "None", ",", "user_dictionary_words", "=", "None", ")", ":", "for", "chunk", "in", "chunks", ":", "for", "error", "in", "spellcheck_region", "(", "chunk", ".", "data", ",", "valid_words_dictionary", ",", "technical_words_dictionary", ",", "user_dictionary_words", ")", ":", "col_offset", "=", "_determine_character_offset", "(", "error", ".", "line_offset", ",", "error", ".", "column_offset", ",", "chunk", ".", "column", ")", "msg", "=", "_SPELLCHECK_MESSAGES", "[", "error", ".", "error_type", "]", ".", "format", "(", "error", ".", "word", ")", "yield", "_populate_spelling_error", "(", "error", ".", "word", ",", "error", ".", "suggestions", ",", "contents", ",", "error", ".", "line_offset", "+", "chunk", ".", "line", ",", "col_offset", ",", "msg", ")" ]
For each chunk and a set of valid and technical words, find errors.
[ "For", "each", "chunk", "and", "a", "set", "of", "valid", "and", "technical", "words", "find", "errors", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L321-L342
247,264
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_create_technical_words_dictionary
def _create_technical_words_dictionary(spellchecker_cache_path, relative_path, user_words, shadow): """Create Dictionary at spellchecker_cache_path with technical words.""" technical_terms_set = (user_words | technical_words_from_shadow_contents(shadow)) technical_words = Dictionary(technical_terms_set, "technical_words_" + relative_path.replace(os.path.sep, "_"), [os.path.realpath(relative_path)], spellchecker_cache_path) return technical_words
python
def _create_technical_words_dictionary(spellchecker_cache_path, relative_path, user_words, shadow): """Create Dictionary at spellchecker_cache_path with technical words.""" technical_terms_set = (user_words | technical_words_from_shadow_contents(shadow)) technical_words = Dictionary(technical_terms_set, "technical_words_" + relative_path.replace(os.path.sep, "_"), [os.path.realpath(relative_path)], spellchecker_cache_path) return technical_words
[ "def", "_create_technical_words_dictionary", "(", "spellchecker_cache_path", ",", "relative_path", ",", "user_words", ",", "shadow", ")", ":", "technical_terms_set", "=", "(", "user_words", "|", "technical_words_from_shadow_contents", "(", "shadow", ")", ")", "technical_words", "=", "Dictionary", "(", "technical_terms_set", ",", "\"technical_words_\"", "+", "relative_path", ".", "replace", "(", "os", ".", "path", ".", "sep", ",", "\"_\"", ")", ",", "[", "os", ".", "path", ".", "realpath", "(", "relative_path", ")", "]", ",", "spellchecker_cache_path", ")", "return", "technical_words" ]
Create Dictionary at spellchecker_cache_path with technical words.
[ "Create", "Dictionary", "at", "spellchecker_cache_path", "with", "technical", "words", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L346-L358
247,265
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_construct_user_dictionary
def _construct_user_dictionary(global_options, tool_options): """Cause dictionary with valid and user words to be cached on disk.""" del global_options spellchecker_cache_path = tool_options.get("spellcheck_cache", None) valid_words_dictionary_helper.create(spellchecker_cache_path)
python
def _construct_user_dictionary(global_options, tool_options): """Cause dictionary with valid and user words to be cached on disk.""" del global_options spellchecker_cache_path = tool_options.get("spellcheck_cache", None) valid_words_dictionary_helper.create(spellchecker_cache_path)
[ "def", "_construct_user_dictionary", "(", "global_options", ",", "tool_options", ")", ":", "del", "global_options", "spellchecker_cache_path", "=", "tool_options", ".", "get", "(", "\"spellcheck_cache\"", ",", "None", ")", "valid_words_dictionary_helper", ".", "create", "(", "spellchecker_cache_path", ")" ]
Cause dictionary with valid and user words to be cached on disk.
[ "Cause", "dictionary", "with", "valid", "and", "user", "words", "to", "be", "cached", "on", "disk", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L361-L366
247,266
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_drain
def _drain(queue_to_drain, sentinel=None): """Remove all values from queue_to_drain and return as list. This uses the trick from http://stackoverflow.com/questions/ 1540822/dumping-a-multiprocessing-queue-into-a-list in order to ensure that the queue is fully drained. """ queue_to_drain.put(sentinel) queued_items = [i for i in iter(queue_to_drain.get, None)] return queued_items
python
def _drain(queue_to_drain, sentinel=None): """Remove all values from queue_to_drain and return as list. This uses the trick from http://stackoverflow.com/questions/ 1540822/dumping-a-multiprocessing-queue-into-a-list in order to ensure that the queue is fully drained. """ queue_to_drain.put(sentinel) queued_items = [i for i in iter(queue_to_drain.get, None)] return queued_items
[ "def", "_drain", "(", "queue_to_drain", ",", "sentinel", "=", "None", ")", ":", "queue_to_drain", ".", "put", "(", "sentinel", ")", "queued_items", "=", "[", "i", "for", "i", "in", "iter", "(", "queue_to_drain", ".", "get", ",", "None", ")", "]", "return", "queued_items" ]
Remove all values from queue_to_drain and return as list. This uses the trick from http://stackoverflow.com/questions/ 1540822/dumping-a-multiprocessing-queue-into-a-list in order to ensure that the queue is fully drained.
[ "Remove", "all", "values", "from", "queue_to_drain", "and", "return", "as", "list", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L369-L379
247,267
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_maybe_log_technical_terms
def _maybe_log_technical_terms(global_options, tool_options): """Log technical terms as appropriate if the user requested it. As a side effect, if --log-technical-terms-to is passed to the linter then open up the file specified (or create it) and then merge the set of technical words that we have now with the technical words already in it. """ log_technical_terms_to_path = global_options.get("log_technical_terms_to", None) log_technical_terms_to_queue = tool_options.get("log_technical_terms_to", None) if log_technical_terms_to_path: assert log_technical_terms_to_queue is not None try: os.makedirs(os.path.dirname(log_technical_terms_to_path)) except OSError as error: if error.errno != errno.EEXIST: raise error if not log_technical_terms_to_queue.empty(): with closing(os.fdopen(os.open(log_technical_terms_to_path, os.O_RDWR | os.O_CREAT), "r+")) as terms_file: # pychecker can't see through the handle returned by closing # so we need to suppress these warnings. terms = set(terms_file.read().splitlines()) new_terms = set(freduce(lambda x, y: x | y, _drain(log_technical_terms_to_queue))) if not terms.issuperset(new_terms): terms_file.seek(0) terms_file.truncate(0) terms_file.write("\n".join(list(terms | set(new_terms))))
python
def _maybe_log_technical_terms(global_options, tool_options): """Log technical terms as appropriate if the user requested it. As a side effect, if --log-technical-terms-to is passed to the linter then open up the file specified (or create it) and then merge the set of technical words that we have now with the technical words already in it. """ log_technical_terms_to_path = global_options.get("log_technical_terms_to", None) log_technical_terms_to_queue = tool_options.get("log_technical_terms_to", None) if log_technical_terms_to_path: assert log_technical_terms_to_queue is not None try: os.makedirs(os.path.dirname(log_technical_terms_to_path)) except OSError as error: if error.errno != errno.EEXIST: raise error if not log_technical_terms_to_queue.empty(): with closing(os.fdopen(os.open(log_technical_terms_to_path, os.O_RDWR | os.O_CREAT), "r+")) as terms_file: # pychecker can't see through the handle returned by closing # so we need to suppress these warnings. terms = set(terms_file.read().splitlines()) new_terms = set(freduce(lambda x, y: x | y, _drain(log_technical_terms_to_queue))) if not terms.issuperset(new_terms): terms_file.seek(0) terms_file.truncate(0) terms_file.write("\n".join(list(terms | set(new_terms))))
[ "def", "_maybe_log_technical_terms", "(", "global_options", ",", "tool_options", ")", ":", "log_technical_terms_to_path", "=", "global_options", ".", "get", "(", "\"log_technical_terms_to\"", ",", "None", ")", "log_technical_terms_to_queue", "=", "tool_options", ".", "get", "(", "\"log_technical_terms_to\"", ",", "None", ")", "if", "log_technical_terms_to_path", ":", "assert", "log_technical_terms_to_queue", "is", "not", "None", "try", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "log_technical_terms_to_path", ")", ")", "except", "OSError", "as", "error", ":", "if", "error", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "raise", "error", "if", "not", "log_technical_terms_to_queue", ".", "empty", "(", ")", ":", "with", "closing", "(", "os", ".", "fdopen", "(", "os", ".", "open", "(", "log_technical_terms_to_path", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_CREAT", ")", ",", "\"r+\"", ")", ")", "as", "terms_file", ":", "# pychecker can't see through the handle returned by closing", "# so we need to suppress these warnings.", "terms", "=", "set", "(", "terms_file", ".", "read", "(", ")", ".", "splitlines", "(", ")", ")", "new_terms", "=", "set", "(", "freduce", "(", "lambda", "x", ",", "y", ":", "x", "|", "y", ",", "_drain", "(", "log_technical_terms_to_queue", ")", ")", ")", "if", "not", "terms", ".", "issuperset", "(", "new_terms", ")", ":", "terms_file", ".", "seek", "(", "0", ")", "terms_file", ".", "truncate", "(", "0", ")", "terms_file", ".", "write", "(", "\"\\n\"", ".", "join", "(", "list", "(", "terms", "|", "set", "(", "new_terms", ")", ")", ")", ")" ]
Log technical terms as appropriate if the user requested it. As a side effect, if --log-technical-terms-to is passed to the linter then open up the file specified (or create it) and then merge the set of technical words that we have now with the technical words already in it.
[ "Log", "technical", "terms", "as", "appropriate", "if", "the", "user", "requested", "it", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L382-L417
247,268
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_no_spelling_errors
def _no_spelling_errors(relative_path, contents, linter_options): """No spelling errors in strings, comments or anything of the like.""" block_regexps = linter_options.get("block_regexps", None) chunks, shadow = spellcheckable_and_shadow_contents(contents, block_regexps) cache = linter_options.get("spellcheck_cache", None) user_words, valid_words = valid_words_dictionary_helper.create(cache) technical_words = _create_technical_words_dictionary(cache, relative_path, user_words, shadow) if linter_options.get("log_technical_terms_to"): linter_options["log_technical_terms_to"].put(technical_words.words()) return [e for e in _find_spelling_errors_in_chunks(chunks, contents, valid_words, technical_words, user_words) if e]
python
def _no_spelling_errors(relative_path, contents, linter_options): """No spelling errors in strings, comments or anything of the like.""" block_regexps = linter_options.get("block_regexps", None) chunks, shadow = spellcheckable_and_shadow_contents(contents, block_regexps) cache = linter_options.get("spellcheck_cache", None) user_words, valid_words = valid_words_dictionary_helper.create(cache) technical_words = _create_technical_words_dictionary(cache, relative_path, user_words, shadow) if linter_options.get("log_technical_terms_to"): linter_options["log_technical_terms_to"].put(technical_words.words()) return [e for e in _find_spelling_errors_in_chunks(chunks, contents, valid_words, technical_words, user_words) if e]
[ "def", "_no_spelling_errors", "(", "relative_path", ",", "contents", ",", "linter_options", ")", ":", "block_regexps", "=", "linter_options", ".", "get", "(", "\"block_regexps\"", ",", "None", ")", "chunks", ",", "shadow", "=", "spellcheckable_and_shadow_contents", "(", "contents", ",", "block_regexps", ")", "cache", "=", "linter_options", ".", "get", "(", "\"spellcheck_cache\"", ",", "None", ")", "user_words", ",", "valid_words", "=", "valid_words_dictionary_helper", ".", "create", "(", "cache", ")", "technical_words", "=", "_create_technical_words_dictionary", "(", "cache", ",", "relative_path", ",", "user_words", ",", "shadow", ")", "if", "linter_options", ".", "get", "(", "\"log_technical_terms_to\"", ")", ":", "linter_options", "[", "\"log_technical_terms_to\"", "]", ".", "put", "(", "technical_words", ".", "words", "(", ")", ")", "return", "[", "e", "for", "e", "in", "_find_spelling_errors_in_chunks", "(", "chunks", ",", "contents", ",", "valid_words", ",", "technical_words", ",", "user_words", ")", "if", "e", "]" ]
No spelling errors in strings, comments or anything of the like.
[ "No", "spelling", "errors", "in", "strings", "comments", "or", "anything", "of", "the", "like", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L420-L439
247,269
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_line_suppresses_error_code
def _line_suppresses_error_code(line, code): """Check if line contains necessary content to suppress code. A line suppresses code if it is in the format suppress(code1,code2) etc. """ match = re.compile(r"suppress\((.*)\)").match(line) if match: codes = match.group(1).split(",") return code in codes return False
python
def _line_suppresses_error_code(line, code): """Check if line contains necessary content to suppress code. A line suppresses code if it is in the format suppress(code1,code2) etc. """ match = re.compile(r"suppress\((.*)\)").match(line) if match: codes = match.group(1).split(",") return code in codes return False
[ "def", "_line_suppresses_error_code", "(", "line", ",", "code", ")", ":", "match", "=", "re", ".", "compile", "(", "r\"suppress\\((.*)\\)\"", ")", ".", "match", "(", "line", ")", "if", "match", ":", "codes", "=", "match", ".", "group", "(", "1", ")", ".", "split", "(", "\",\"", ")", "return", "code", "in", "codes", "return", "False" ]
Check if line contains necessary content to suppress code. A line suppresses code if it is in the format suppress(code1,code2) etc.
[ "Check", "if", "line", "contains", "necessary", "content", "to", "suppress", "code", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L442-L452
247,270
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_error_is_suppressed
def _error_is_suppressed(error, code, contents): """Return true if error is suppressed by an inline suppression.""" if len(contents) == 0: return False if error.line > 1: # Check above, and then to the side for suppressions above = contents[error.line - 2].split("#") if len(above) and _line_suppresses_error_code(above[-1].strip(), code): return True aside = contents[error.line - 1].split("#") if len(aside) and _line_suppresses_error_code(aside[-1].strip(), code): return True return False
python
def _error_is_suppressed(error, code, contents): """Return true if error is suppressed by an inline suppression.""" if len(contents) == 0: return False if error.line > 1: # Check above, and then to the side for suppressions above = contents[error.line - 2].split("#") if len(above) and _line_suppresses_error_code(above[-1].strip(), code): return True aside = contents[error.line - 1].split("#") if len(aside) and _line_suppresses_error_code(aside[-1].strip(), code): return True return False
[ "def", "_error_is_suppressed", "(", "error", ",", "code", ",", "contents", ")", ":", "if", "len", "(", "contents", ")", "==", "0", ":", "return", "False", "if", "error", ".", "line", ">", "1", ":", "# Check above, and then to the side for suppressions", "above", "=", "contents", "[", "error", ".", "line", "-", "2", "]", ".", "split", "(", "\"#\"", ")", "if", "len", "(", "above", ")", "and", "_line_suppresses_error_code", "(", "above", "[", "-", "1", "]", ".", "strip", "(", ")", ",", "code", ")", ":", "return", "True", "aside", "=", "contents", "[", "error", ".", "line", "-", "1", "]", ".", "split", "(", "\"#\"", ")", "if", "len", "(", "aside", ")", "and", "_line_suppresses_error_code", "(", "aside", "[", "-", "1", "]", ".", "strip", "(", ")", ",", "code", ")", ":", "return", "True", "return", "False" ]
Return true if error is suppressed by an inline suppression.
[ "Return", "true", "if", "error", "is", "suppressed", "by", "an", "inline", "suppression", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L455-L471
247,271
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
lint
def lint(relative_path_to_file, contents, linter_functions, **kwargs): r"""Actually lints some file contents. relative_path_to_file should contain the relative path to the file being linted from the root source directory. Contents should be a raw string with \n's. """ lines = contents.splitlines(True) errors = list() for (code, info) in linter_functions.items(): error = info.function(relative_path_to_file, lines, kwargs) if error: if isinstance(error, list): errors.extend([(code, e) for e in error]) else: errors.append((code, error)) errors = [e for e in errors if not _error_is_suppressed(e[1], e[0], lines)] return sorted(errors, key=lambda e: e[1].line)
python
def lint(relative_path_to_file, contents, linter_functions, **kwargs): r"""Actually lints some file contents. relative_path_to_file should contain the relative path to the file being linted from the root source directory. Contents should be a raw string with \n's. """ lines = contents.splitlines(True) errors = list() for (code, info) in linter_functions.items(): error = info.function(relative_path_to_file, lines, kwargs) if error: if isinstance(error, list): errors.extend([(code, e) for e in error]) else: errors.append((code, error)) errors = [e for e in errors if not _error_is_suppressed(e[1], e[0], lines)] return sorted(errors, key=lambda e: e[1].line)
[ "def", "lint", "(", "relative_path_to_file", ",", "contents", ",", "linter_functions", ",", "*", "*", "kwargs", ")", ":", "lines", "=", "contents", ".", "splitlines", "(", "True", ")", "errors", "=", "list", "(", ")", "for", "(", "code", ",", "info", ")", "in", "linter_functions", ".", "items", "(", ")", ":", "error", "=", "info", ".", "function", "(", "relative_path_to_file", ",", "lines", ",", "kwargs", ")", "if", "error", ":", "if", "isinstance", "(", "error", ",", "list", ")", ":", "errors", ".", "extend", "(", "[", "(", "code", ",", "e", ")", "for", "e", "in", "error", "]", ")", "else", ":", "errors", ".", "append", "(", "(", "code", ",", "error", ")", ")", "errors", "=", "[", "e", "for", "e", "in", "errors", "if", "not", "_error_is_suppressed", "(", "e", "[", "1", "]", ",", "e", "[", "0", "]", ",", "lines", ")", "]", "return", "sorted", "(", "errors", ",", "key", "=", "lambda", "e", ":", "e", "[", "1", "]", ".", "line", ")" ]
r"""Actually lints some file contents. relative_path_to_file should contain the relative path to the file being linted from the root source directory. Contents should be a raw string with \n's.
[ "r", "Actually", "lints", "some", "file", "contents", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L506-L528
247,272
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
linter_functions_from_filters
def linter_functions_from_filters(whitelist=None, blacklist=None): """Yield tuples of _LinterFunction matching whitelist but not blacklist.""" def _keyvalue_pair_if(dictionary, condition): """Return a key-value pair in dictionary if condition matched.""" return { k: v for (k, v) in dictionary.items() if condition(k) } def _check_list(check_list, cond): """Return function testing against a list if the list exists.""" def _check_against_list(key): """Return true if list exists and condition passes.""" return cond(check_list, key) if check_list is not None else True return _check_against_list linter_functions = LINTER_FUNCTIONS linter_functions = _keyvalue_pair_if(linter_functions, _check_list(whitelist, lambda l, k: k in l)) linter_functions = _keyvalue_pair_if(linter_functions, _check_list(blacklist, lambda l, k: k not in l)) for code, linter_function in linter_functions.items(): yield (code, linter_function)
python
def linter_functions_from_filters(whitelist=None, blacklist=None): """Yield tuples of _LinterFunction matching whitelist but not blacklist.""" def _keyvalue_pair_if(dictionary, condition): """Return a key-value pair in dictionary if condition matched.""" return { k: v for (k, v) in dictionary.items() if condition(k) } def _check_list(check_list, cond): """Return function testing against a list if the list exists.""" def _check_against_list(key): """Return true if list exists and condition passes.""" return cond(check_list, key) if check_list is not None else True return _check_against_list linter_functions = LINTER_FUNCTIONS linter_functions = _keyvalue_pair_if(linter_functions, _check_list(whitelist, lambda l, k: k in l)) linter_functions = _keyvalue_pair_if(linter_functions, _check_list(blacklist, lambda l, k: k not in l)) for code, linter_function in linter_functions.items(): yield (code, linter_function)
[ "def", "linter_functions_from_filters", "(", "whitelist", "=", "None", ",", "blacklist", "=", "None", ")", ":", "def", "_keyvalue_pair_if", "(", "dictionary", ",", "condition", ")", ":", "\"\"\"Return a key-value pair in dictionary if condition matched.\"\"\"", "return", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "dictionary", ".", "items", "(", ")", "if", "condition", "(", "k", ")", "}", "def", "_check_list", "(", "check_list", ",", "cond", ")", ":", "\"\"\"Return function testing against a list if the list exists.\"\"\"", "def", "_check_against_list", "(", "key", ")", ":", "\"\"\"Return true if list exists and condition passes.\"\"\"", "return", "cond", "(", "check_list", ",", "key", ")", "if", "check_list", "is", "not", "None", "else", "True", "return", "_check_against_list", "linter_functions", "=", "LINTER_FUNCTIONS", "linter_functions", "=", "_keyvalue_pair_if", "(", "linter_functions", ",", "_check_list", "(", "whitelist", ",", "lambda", "l", ",", "k", ":", "k", "in", "l", ")", ")", "linter_functions", "=", "_keyvalue_pair_if", "(", "linter_functions", ",", "_check_list", "(", "blacklist", ",", "lambda", "l", ",", "k", ":", "k", "not", "in", "l", ")", ")", "for", "code", ",", "linter_function", "in", "linter_functions", ".", "items", "(", ")", ":", "yield", "(", "code", ",", "linter_function", ")" ]
Yield tuples of _LinterFunction matching whitelist but not blacklist.
[ "Yield", "tuples", "of", "_LinterFunction", "matching", "whitelist", "but", "not", "blacklist", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L531-L557
247,273
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_report_lint_error
def _report_lint_error(error, file_path): """Report a linter error.""" line = error[1].line code = error[0] description = error[1].description sys.stdout.write("{0}:{1} [{2}] {3}\n".format(file_path, line, code, description))
python
def _report_lint_error(error, file_path): """Report a linter error.""" line = error[1].line code = error[0] description = error[1].description sys.stdout.write("{0}:{1} [{2}] {3}\n".format(file_path, line, code, description))
[ "def", "_report_lint_error", "(", "error", ",", "file_path", ")", ":", "line", "=", "error", "[", "1", "]", ".", "line", "code", "=", "error", "[", "0", "]", "description", "=", "error", "[", "1", "]", ".", "description", "sys", ".", "stdout", ".", "write", "(", "\"{0}:{1} [{2}] {3}\\n\"", ".", "format", "(", "file_path", ",", "line", ",", "code", ",", "description", ")", ")" ]
Report a linter error.
[ "Report", "a", "linter", "error", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L621-L629
247,274
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_apply_replacement
def _apply_replacement(error, found_file, file_lines): """Apply a single replacement.""" fixed_lines = file_lines fixed_lines[error[1].line - 1] = error[1].replacement concatenated_fixed_lines = "".join(fixed_lines) # Only fix one error at a time found_file.seek(0) found_file.write(concatenated_fixed_lines) found_file.truncate()
python
def _apply_replacement(error, found_file, file_lines): """Apply a single replacement.""" fixed_lines = file_lines fixed_lines[error[1].line - 1] = error[1].replacement concatenated_fixed_lines = "".join(fixed_lines) # Only fix one error at a time found_file.seek(0) found_file.write(concatenated_fixed_lines) found_file.truncate()
[ "def", "_apply_replacement", "(", "error", ",", "found_file", ",", "file_lines", ")", ":", "fixed_lines", "=", "file_lines", "fixed_lines", "[", "error", "[", "1", "]", ".", "line", "-", "1", "]", "=", "error", "[", "1", "]", ".", "replacement", "concatenated_fixed_lines", "=", "\"\"", ".", "join", "(", "fixed_lines", ")", "# Only fix one error at a time", "found_file", ".", "seek", "(", "0", ")", "found_file", ".", "write", "(", "concatenated_fixed_lines", ")", "found_file", ".", "truncate", "(", ")" ]
Apply a single replacement.
[ "Apply", "a", "single", "replacement", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L632-L641
247,275
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_obtain_queue
def _obtain_queue(num_jobs): """Return queue type most appropriate for runtime model. If we are using multiprocessing, that should be multiprocessing.Manager().Queue. If we are just using a single process, then use a normal queue type. """ if _should_use_multiprocessing(num_jobs): return ReprQueue(multiprocessing.Manager().Queue()) return ReprQueue(Queue())
python
def _obtain_queue(num_jobs): """Return queue type most appropriate for runtime model. If we are using multiprocessing, that should be multiprocessing.Manager().Queue. If we are just using a single process, then use a normal queue type. """ if _should_use_multiprocessing(num_jobs): return ReprQueue(multiprocessing.Manager().Queue()) return ReprQueue(Queue())
[ "def", "_obtain_queue", "(", "num_jobs", ")", ":", "if", "_should_use_multiprocessing", "(", "num_jobs", ")", ":", "return", "ReprQueue", "(", "multiprocessing", ".", "Manager", "(", ")", ".", "Queue", "(", ")", ")", "return", "ReprQueue", "(", "Queue", "(", ")", ")" ]
Return queue type most appropriate for runtime model. If we are using multiprocessing, that should be multiprocessing.Manager().Queue. If we are just using a single process, then use a normal queue type.
[ "Return", "queue", "type", "most", "appropriate", "for", "runtime", "model", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L676-L686
247,276
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
tool_options_from_global
def tool_options_from_global(global_options, num_jobs): """From an argparse namespace, get a dict of options for the tools.""" internal_opt = ["whitelist", "blacklist", "fix_what_you_can"] queue_object = _obtain_queue(num_jobs) translate = defaultdict(lambda: (lambda x: x), log_technical_terms_to=lambda _: queue_object) tool_options = OrderedDict() for key in sorted(global_options.keys()): if key not in internal_opt and global_options[key] is not None: tool_options[key] = translate[key](global_options[key]) return tool_options
python
def tool_options_from_global(global_options, num_jobs): """From an argparse namespace, get a dict of options for the tools.""" internal_opt = ["whitelist", "blacklist", "fix_what_you_can"] queue_object = _obtain_queue(num_jobs) translate = defaultdict(lambda: (lambda x: x), log_technical_terms_to=lambda _: queue_object) tool_options = OrderedDict() for key in sorted(global_options.keys()): if key not in internal_opt and global_options[key] is not None: tool_options[key] = translate[key](global_options[key]) return tool_options
[ "def", "tool_options_from_global", "(", "global_options", ",", "num_jobs", ")", ":", "internal_opt", "=", "[", "\"whitelist\"", ",", "\"blacklist\"", ",", "\"fix_what_you_can\"", "]", "queue_object", "=", "_obtain_queue", "(", "num_jobs", ")", "translate", "=", "defaultdict", "(", "lambda", ":", "(", "lambda", "x", ":", "x", ")", ",", "log_technical_terms_to", "=", "lambda", "_", ":", "queue_object", ")", "tool_options", "=", "OrderedDict", "(", ")", "for", "key", "in", "sorted", "(", "global_options", ".", "keys", "(", ")", ")", ":", "if", "key", "not", "in", "internal_opt", "and", "global_options", "[", "key", "]", "is", "not", "None", ":", "tool_options", "[", "key", "]", "=", "translate", "[", "key", "]", "(", "global_options", "[", "key", "]", ")", "return", "tool_options" ]
From an argparse namespace, get a dict of options for the tools.
[ "From", "an", "argparse", "namespace", "get", "a", "dict", "of", "options", "for", "the", "tools", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L689-L702
247,277
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_run_lint_on_file_stamped_args
def _run_lint_on_file_stamped_args(file_path, # suppress(too-many-arguments) stamp_file_path, log_technical_terms_to, linter_functions, tool_options, fix_what_you_can): """Return tuple of args and kwargs that function would be called with.""" dictionary_path = os.path.abspath("DICTIONARY") dependencies = [file_path] if os.path.exists(dictionary_path): dependencies.append(dictionary_path) kwargs = OrderedDict() kwargs["jobstamps_dependencies"] = dependencies kwargs["jobstamps_cache_output_directory"] = stamp_file_path if log_technical_terms_to: kwargs["jobstamps_output_files"] = [log_technical_terms_to] return ((file_path, linter_functions, tool_options, fix_what_you_can), kwargs)
python
def _run_lint_on_file_stamped_args(file_path, # suppress(too-many-arguments) stamp_file_path, log_technical_terms_to, linter_functions, tool_options, fix_what_you_can): """Return tuple of args and kwargs that function would be called with.""" dictionary_path = os.path.abspath("DICTIONARY") dependencies = [file_path] if os.path.exists(dictionary_path): dependencies.append(dictionary_path) kwargs = OrderedDict() kwargs["jobstamps_dependencies"] = dependencies kwargs["jobstamps_cache_output_directory"] = stamp_file_path if log_technical_terms_to: kwargs["jobstamps_output_files"] = [log_technical_terms_to] return ((file_path, linter_functions, tool_options, fix_what_you_can), kwargs)
[ "def", "_run_lint_on_file_stamped_args", "(", "file_path", ",", "# suppress(too-many-arguments)", "stamp_file_path", ",", "log_technical_terms_to", ",", "linter_functions", ",", "tool_options", ",", "fix_what_you_can", ")", ":", "dictionary_path", "=", "os", ".", "path", ".", "abspath", "(", "\"DICTIONARY\"", ")", "dependencies", "=", "[", "file_path", "]", "if", "os", ".", "path", ".", "exists", "(", "dictionary_path", ")", ":", "dependencies", ".", "append", "(", "dictionary_path", ")", "kwargs", "=", "OrderedDict", "(", ")", "kwargs", "[", "\"jobstamps_dependencies\"", "]", "=", "dependencies", "kwargs", "[", "\"jobstamps_cache_output_directory\"", "]", "=", "stamp_file_path", "if", "log_technical_terms_to", ":", "kwargs", "[", "\"jobstamps_output_files\"", "]", "=", "[", "log_technical_terms_to", "]", "return", "(", "(", "file_path", ",", "linter_functions", ",", "tool_options", ",", "fix_what_you_can", ")", ",", "kwargs", ")" ]
Return tuple of args and kwargs that function would be called with.
[ "Return", "tuple", "of", "args", "and", "kwargs", "that", "function", "would", "be", "called", "with", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L774-L798
247,278
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_run_lint_on_file_stamped
def _run_lint_on_file_stamped(*args): """Run linter functions on file_path, stamping in stamp_file_path.""" # We pass an empty dictionary as keyword arguments here to work # around a bug in frosted, which crashes when no keyword arguments # are passed # # suppress(E204) stamp_args, stamp_kwargs = _run_lint_on_file_stamped_args(*args, **{}) return jobstamp.run(_run_lint_on_file_exceptions, *stamp_args, **stamp_kwargs)
python
def _run_lint_on_file_stamped(*args): """Run linter functions on file_path, stamping in stamp_file_path.""" # We pass an empty dictionary as keyword arguments here to work # around a bug in frosted, which crashes when no keyword arguments # are passed # # suppress(E204) stamp_args, stamp_kwargs = _run_lint_on_file_stamped_args(*args, **{}) return jobstamp.run(_run_lint_on_file_exceptions, *stamp_args, **stamp_kwargs)
[ "def", "_run_lint_on_file_stamped", "(", "*", "args", ")", ":", "# We pass an empty dictionary as keyword arguments here to work", "# around a bug in frosted, which crashes when no keyword arguments", "# are passed", "#", "# suppress(E204)", "stamp_args", ",", "stamp_kwargs", "=", "_run_lint_on_file_stamped_args", "(", "*", "args", ",", "*", "*", "{", "}", ")", "return", "jobstamp", ".", "run", "(", "_run_lint_on_file_exceptions", ",", "*", "stamp_args", ",", "*", "*", "stamp_kwargs", ")" ]
Run linter functions on file_path, stamping in stamp_file_path.
[ "Run", "linter", "functions", "on", "file_path", "stamping", "in", "stamp_file_path", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L801-L813
247,279
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_ordered
def _ordered(generator, *args, **kwargs): """Sort keys of unordered_dict and store in OrderedDict.""" unordered_dict = {k: v for k, v in generator(*args, **kwargs)} keys = sorted(list(dict(unordered_dict).keys())) result = OrderedDict() for key in keys: result[key] = unordered_dict[key] return result
python
def _ordered(generator, *args, **kwargs): """Sort keys of unordered_dict and store in OrderedDict.""" unordered_dict = {k: v for k, v in generator(*args, **kwargs)} keys = sorted(list(dict(unordered_dict).keys())) result = OrderedDict() for key in keys: result[key] = unordered_dict[key] return result
[ "def", "_ordered", "(", "generator", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "unordered_dict", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "generator", "(", "*", "args", ",", "*", "*", "kwargs", ")", "}", "keys", "=", "sorted", "(", "list", "(", "dict", "(", "unordered_dict", ")", ".", "keys", "(", ")", ")", ")", "result", "=", "OrderedDict", "(", ")", "for", "key", "in", "keys", ":", "result", "[", "key", "]", "=", "unordered_dict", "[", "key", "]", "return", "result" ]
Sort keys of unordered_dict and store in OrderedDict.
[ "Sort", "keys", "of", "unordered_dict", "and", "store", "in", "OrderedDict", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L816-L824
247,280
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
_any_would_run
def _any_would_run(func, filenames, *args): """True if a linter function would be called on any of filenames.""" if os.environ.get("_POLYSQUARE_GENERIC_FILE_LINTER_NO_STAMPING", None): return True for filename in filenames: # suppress(E204) stamp_args, stamp_kwargs = _run_lint_on_file_stamped_args(filename, *args, **{}) dependency = jobstamp.out_of_date(func, *stamp_args, **stamp_kwargs) if dependency: return True return False
python
def _any_would_run(func, filenames, *args): """True if a linter function would be called on any of filenames.""" if os.environ.get("_POLYSQUARE_GENERIC_FILE_LINTER_NO_STAMPING", None): return True for filename in filenames: # suppress(E204) stamp_args, stamp_kwargs = _run_lint_on_file_stamped_args(filename, *args, **{}) dependency = jobstamp.out_of_date(func, *stamp_args, **stamp_kwargs) if dependency: return True return False
[ "def", "_any_would_run", "(", "func", ",", "filenames", ",", "*", "args", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "\"_POLYSQUARE_GENERIC_FILE_LINTER_NO_STAMPING\"", ",", "None", ")", ":", "return", "True", "for", "filename", "in", "filenames", ":", "# suppress(E204)", "stamp_args", ",", "stamp_kwargs", "=", "_run_lint_on_file_stamped_args", "(", "filename", ",", "*", "args", ",", "*", "*", "{", "}", ")", "dependency", "=", "jobstamp", ".", "out_of_date", "(", "func", ",", "*", "stamp_args", ",", "*", "*", "stamp_kwargs", ")", "if", "dependency", ":", "return", "True", "return", "False" ]
True if a linter function would be called on any of filenames.
[ "True", "if", "a", "linter", "function", "would", "be", "called", "on", "any", "of", "filenames", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L827-L844
247,281
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
main
def main(arguments=None): # suppress(unused-function) """Entry point for the linter.""" result = _parse_arguments(arguments) linter_funcs = _ordered(linter_functions_from_filters, result.whitelist, result.blacklist) global_options = vars(result) tool_options = tool_options_from_global(global_options, len(result.files)) any_would_run = _any_would_run(_run_lint_on_file_exceptions, result.files, result.stamp_file_path, result.log_technical_terms_to, linter_funcs, tool_options, result.fix_what_you_can) if any_would_run: for linter_function in linter_funcs.values(): if linter_function.before_all: linter_function.before_all(global_options, tool_options) use_multiprocessing = _should_use_multiprocessing(len(result.files)) else: use_multiprocessing = False if use_multiprocessing: mapper = parmap.map else: # suppress(E731) mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i] errors = list(itertools.chain(*mapper(_run_lint_on_file_stamped, result.files, result.stamp_file_path, result.log_technical_terms_to, linter_funcs, tool_options, result.fix_what_you_can))) for error in sorted(errors): _report_lint_error(error.failure, os.path.relpath(error.absolute_path)) if any_would_run: for linter_funcs in linter_funcs.values(): if linter_funcs.after_all: linter_funcs.after_all(global_options, tool_options) return len(errors)
python
def main(arguments=None): # suppress(unused-function) """Entry point for the linter.""" result = _parse_arguments(arguments) linter_funcs = _ordered(linter_functions_from_filters, result.whitelist, result.blacklist) global_options = vars(result) tool_options = tool_options_from_global(global_options, len(result.files)) any_would_run = _any_would_run(_run_lint_on_file_exceptions, result.files, result.stamp_file_path, result.log_technical_terms_to, linter_funcs, tool_options, result.fix_what_you_can) if any_would_run: for linter_function in linter_funcs.values(): if linter_function.before_all: linter_function.before_all(global_options, tool_options) use_multiprocessing = _should_use_multiprocessing(len(result.files)) else: use_multiprocessing = False if use_multiprocessing: mapper = parmap.map else: # suppress(E731) mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i] errors = list(itertools.chain(*mapper(_run_lint_on_file_stamped, result.files, result.stamp_file_path, result.log_technical_terms_to, linter_funcs, tool_options, result.fix_what_you_can))) for error in sorted(errors): _report_lint_error(error.failure, os.path.relpath(error.absolute_path)) if any_would_run: for linter_funcs in linter_funcs.values(): if linter_funcs.after_all: linter_funcs.after_all(global_options, tool_options) return len(errors)
[ "def", "main", "(", "arguments", "=", "None", ")", ":", "# suppress(unused-function)", "result", "=", "_parse_arguments", "(", "arguments", ")", "linter_funcs", "=", "_ordered", "(", "linter_functions_from_filters", ",", "result", ".", "whitelist", ",", "result", ".", "blacklist", ")", "global_options", "=", "vars", "(", "result", ")", "tool_options", "=", "tool_options_from_global", "(", "global_options", ",", "len", "(", "result", ".", "files", ")", ")", "any_would_run", "=", "_any_would_run", "(", "_run_lint_on_file_exceptions", ",", "result", ".", "files", ",", "result", ".", "stamp_file_path", ",", "result", ".", "log_technical_terms_to", ",", "linter_funcs", ",", "tool_options", ",", "result", ".", "fix_what_you_can", ")", "if", "any_would_run", ":", "for", "linter_function", "in", "linter_funcs", ".", "values", "(", ")", ":", "if", "linter_function", ".", "before_all", ":", "linter_function", ".", "before_all", "(", "global_options", ",", "tool_options", ")", "use_multiprocessing", "=", "_should_use_multiprocessing", "(", "len", "(", "result", ".", "files", ")", ")", "else", ":", "use_multiprocessing", "=", "False", "if", "use_multiprocessing", ":", "mapper", "=", "parmap", ".", "map", "else", ":", "# suppress(E731)", "mapper", "=", "lambda", "f", ",", "i", ",", "*", "a", ":", "[", "f", "(", "*", "(", "(", "x", ",", ")", "+", "a", ")", ")", "for", "x", "in", "i", "]", "errors", "=", "list", "(", "itertools", ".", "chain", "(", "*", "mapper", "(", "_run_lint_on_file_stamped", ",", "result", ".", "files", ",", "result", ".", "stamp_file_path", ",", "result", ".", "log_technical_terms_to", ",", "linter_funcs", ",", "tool_options", ",", "result", ".", "fix_what_you_can", ")", ")", ")", "for", "error", "in", "sorted", "(", "errors", ")", ":", "_report_lint_error", "(", "error", ".", "failure", ",", "os", ".", "path", ".", "relpath", "(", "error", ".", "absolute_path", ")", ")", "if", "any_would_run", ":", "for", "linter_funcs", "in", "linter_funcs", ".", "values", "(", ")", ":", "if", "linter_funcs", ".", "after_all", ":", "linter_funcs", ".", "after_all", "(", "global_options", ",", "tool_options", ")", "return", "len", "(", "errors", ")" ]
Entry point for the linter.
[ "Entry", "point", "for", "the", "linter", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L847-L894
247,282
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
ReprQueue.put
def put(self, item, block=True, timeout=None): """Put item into underlying queue.""" return self._queue.put(item, block, timeout)
python
def put(self, item, block=True, timeout=None): """Put item into underlying queue.""" return self._queue.put(item, block, timeout)
[ "def", "put", "(", "self", ",", "item", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "_queue", ".", "put", "(", "item", ",", "block", ",", "timeout", ")" ]
Put item into underlying queue.
[ "Put", "item", "into", "underlying", "queue", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L663-L665
247,283
polysquare/polysquare-generic-file-linter
polysquarelinter/linter.py
ReprQueue.get
def get(self, block=True, timeout=None): """Get item from underlying queue.""" return self._queue.get(block, timeout)
python
def get(self, block=True, timeout=None): """Get item from underlying queue.""" return self._queue.get(block, timeout)
[ "def", "get", "(", "self", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "_queue", ".", "get", "(", "block", ",", "timeout", ")" ]
Get item from underlying queue.
[ "Get", "item", "from", "underlying", "queue", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L667-L669
247,284
rojopolis/lycanthropy
lycanthropy/lycanthropy.py
snake_to_camel
def snake_to_camel(snake_str): ''' Convert `snake_str` from snake_case to camelCase ''' components = snake_str.split('_') if len(components) > 1: camel = (components[0].lower() + ''.join(x.title() for x in components[1:])) return camel # Not snake_case return snake_str
python
def snake_to_camel(snake_str): ''' Convert `snake_str` from snake_case to camelCase ''' components = snake_str.split('_') if len(components) > 1: camel = (components[0].lower() + ''.join(x.title() for x in components[1:])) return camel # Not snake_case return snake_str
[ "def", "snake_to_camel", "(", "snake_str", ")", ":", "components", "=", "snake_str", ".", "split", "(", "'_'", ")", "if", "len", "(", "components", ")", ">", "1", ":", "camel", "=", "(", "components", "[", "0", "]", ".", "lower", "(", ")", "+", "''", ".", "join", "(", "x", ".", "title", "(", ")", "for", "x", "in", "components", "[", "1", ":", "]", ")", ")", "return", "camel", "# Not snake_case", "return", "snake_str" ]
Convert `snake_str` from snake_case to camelCase
[ "Convert", "snake_str", "from", "snake_case", "to", "camelCase" ]
1a5ce2828714fc0e34780ac866532d4106d1a05b
https://github.com/rojopolis/lycanthropy/blob/1a5ce2828714fc0e34780ac866532d4106d1a05b/lycanthropy/lycanthropy.py#L7-L17
247,285
rojopolis/lycanthropy
lycanthropy/lycanthropy.py
snake_to_pascal
def snake_to_pascal(snake_str): ''' Convert `snake_str` from snake_case to PascalCase ''' components = snake_str.split('_') if len(components) > 1: camel = ''.join(x.title() for x in components) return camel # Not snake_case return snake_str
python
def snake_to_pascal(snake_str): ''' Convert `snake_str` from snake_case to PascalCase ''' components = snake_str.split('_') if len(components) > 1: camel = ''.join(x.title() for x in components) return camel # Not snake_case return snake_str
[ "def", "snake_to_pascal", "(", "snake_str", ")", ":", "components", "=", "snake_str", ".", "split", "(", "'_'", ")", "if", "len", "(", "components", ")", ">", "1", ":", "camel", "=", "''", ".", "join", "(", "x", ".", "title", "(", ")", "for", "x", "in", "components", ")", "return", "camel", "# Not snake_case", "return", "snake_str" ]
Convert `snake_str` from snake_case to PascalCase
[ "Convert", "snake_str", "from", "snake_case", "to", "PascalCase" ]
1a5ce2828714fc0e34780ac866532d4106d1a05b
https://github.com/rojopolis/lycanthropy/blob/1a5ce2828714fc0e34780ac866532d4106d1a05b/lycanthropy/lycanthropy.py#L24-L33
247,286
rojopolis/lycanthropy
lycanthropy/lycanthropy.py
camel_to_snake
def camel_to_snake(camel_str): ''' Convert `camel_str` from camelCase to snake_case ''' # Attribution: https://stackoverflow.com/a/1176023/633213 s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_str) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
python
def camel_to_snake(camel_str): ''' Convert `camel_str` from camelCase to snake_case ''' # Attribution: https://stackoverflow.com/a/1176023/633213 s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_str) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
[ "def", "camel_to_snake", "(", "camel_str", ")", ":", "# Attribution: https://stackoverflow.com/a/1176023/633213", "s1", "=", "re", ".", "sub", "(", "'(.)([A-Z][a-z]+)'", ",", "r'\\1_\\2'", ",", "camel_str", ")", "return", "re", ".", "sub", "(", "'([a-z0-9])([A-Z])'", ",", "r'\\1_\\2'", ",", "s1", ")", ".", "lower", "(", ")" ]
Convert `camel_str` from camelCase to snake_case
[ "Convert", "camel_str", "from", "camelCase", "to", "snake_case" ]
1a5ce2828714fc0e34780ac866532d4106d1a05b
https://github.com/rojopolis/lycanthropy/blob/1a5ce2828714fc0e34780ac866532d4106d1a05b/lycanthropy/lycanthropy.py#L40-L46
247,287
fstab50/metal
metal/cli.py
set_logging
def set_logging(cfg_obj): """ Enable or disable logging per config object parameter """ log_status = cfg_obj['LOGGING']['ENABLE_LOGGING'] if log_status: logger.disabled = False elif not log_status: logger.info( '%s: Logging disabled per local configuration file (%s) parameters.' % (inspect.stack()[0][3], cfg_obj['PROJECT']['CONFIG_PATH']) ) logger.disabled = True return log_status
python
def set_logging(cfg_obj): """ Enable or disable logging per config object parameter """ log_status = cfg_obj['LOGGING']['ENABLE_LOGGING'] if log_status: logger.disabled = False elif not log_status: logger.info( '%s: Logging disabled per local configuration file (%s) parameters.' % (inspect.stack()[0][3], cfg_obj['PROJECT']['CONFIG_PATH']) ) logger.disabled = True return log_status
[ "def", "set_logging", "(", "cfg_obj", ")", ":", "log_status", "=", "cfg_obj", "[", "'LOGGING'", "]", "[", "'ENABLE_LOGGING'", "]", "if", "log_status", ":", "logger", ".", "disabled", "=", "False", "elif", "not", "log_status", ":", "logger", ".", "info", "(", "'%s: Logging disabled per local configuration file (%s) parameters.'", "%", "(", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ",", "cfg_obj", "[", "'PROJECT'", "]", "[", "'CONFIG_PATH'", "]", ")", ")", "logger", ".", "disabled", "=", "True", "return", "log_status" ]
Enable or disable logging per config object parameter
[ "Enable", "or", "disable", "logging", "per", "config", "object", "parameter" ]
0488bbdd516a508909267cc44191f632e21156ba
https://github.com/fstab50/metal/blob/0488bbdd516a508909267cc44191f632e21156ba/metal/cli.py#L64-L78
247,288
fstab50/metal
metal/cli.py
precheck
def precheck(): """ Verify project runtime dependencies """ cfg_path = local_config['PROJECT']['CONFIG_PATH'] # enable or disable logging based on config/ defaults logging = set_logging(local_config) if os.path.exists(cfg_path): logger.info('%s: config_path parameter: %s' % (inspect.stack()[0][3], cfg_path)) logger.info( '%s: Existing configuration file found. precheck pass.' % (inspect.stack()[0][3])) return True elif not os.path.exists(cfg_path) and logging is False: logger.info( '%s: No pre-existing configuration file found at %s. Using defaults. Logging disabled.' % (inspect.stack()[0][3], cfg_path) ) return True if logging: logger.info( '%s: Logging enabled per config file (%s).' % (inspect.stack()[0][3], cfg_path) ) return True return False
python
def precheck(): """ Verify project runtime dependencies """ cfg_path = local_config['PROJECT']['CONFIG_PATH'] # enable or disable logging based on config/ defaults logging = set_logging(local_config) if os.path.exists(cfg_path): logger.info('%s: config_path parameter: %s' % (inspect.stack()[0][3], cfg_path)) logger.info( '%s: Existing configuration file found. precheck pass.' % (inspect.stack()[0][3])) return True elif not os.path.exists(cfg_path) and logging is False: logger.info( '%s: No pre-existing configuration file found at %s. Using defaults. Logging disabled.' % (inspect.stack()[0][3], cfg_path) ) return True if logging: logger.info( '%s: Logging enabled per config file (%s).' % (inspect.stack()[0][3], cfg_path) ) return True return False
[ "def", "precheck", "(", ")", ":", "cfg_path", "=", "local_config", "[", "'PROJECT'", "]", "[", "'CONFIG_PATH'", "]", "# enable or disable logging based on config/ defaults", "logging", "=", "set_logging", "(", "local_config", ")", "if", "os", ".", "path", ".", "exists", "(", "cfg_path", ")", ":", "logger", ".", "info", "(", "'%s: config_path parameter: %s'", "%", "(", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ",", "cfg_path", ")", ")", "logger", ".", "info", "(", "'%s: Existing configuration file found. precheck pass.'", "%", "(", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ")", ")", "return", "True", "elif", "not", "os", ".", "path", ".", "exists", "(", "cfg_path", ")", "and", "logging", "is", "False", ":", "logger", ".", "info", "(", "'%s: No pre-existing configuration file found at %s. Using defaults. Logging disabled.'", "%", "(", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ",", "cfg_path", ")", ")", "return", "True", "if", "logging", ":", "logger", ".", "info", "(", "'%s: Logging enabled per config file (%s).'", "%", "(", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ",", "cfg_path", ")", ")", "return", "True", "return", "False" ]
Verify project runtime dependencies
[ "Verify", "project", "runtime", "dependencies" ]
0488bbdd516a508909267cc44191f632e21156ba
https://github.com/fstab50/metal/blob/0488bbdd516a508909267cc44191f632e21156ba/metal/cli.py#L81-L107
247,289
fstab50/metal
metal/cli.py
main
def main(operation, profile, auto, debug, user_name=''): """ End-to-end renew of access keys for a specific profile in local awscli config """ if user_name: logger.info('user_name parameter given (%s) as surrogate' % user_name) try: if operation in VALID_INSTALL: print(operation) elif operation == 'list': print(operation) return True elif not operation: msg_accent = (Colors.BOLD + 'list' + Colors.RESET + ' | ' + Colors.BOLD + 'up' + Colors.RESET) msg = """You must provide a valid OPERATION for --operation parameter: --operation { """ + msg_accent + """ } """ stdout_message(msg) logger.warning('%s: No valid operation provided. Exit' % (inspect.stack()[0][3])) sys.exit(exit_codes['E_MISC']['Code']) else: msg = 'Unknown operation. Exit' stdout_message(msg) logger.warning('%s: %s' % (msg, inspect.stack()[0][3])) sys.exit(exit_codes['E_MISC']['Code']) except KeyError as e: logger.critical( '%s: Cannot find Key %s' % (inspect.stack()[0][3], str(e))) return False except OSError as e: logger.critical( '%s: problem writing to file %s. Error %s' % (inspect.stack()[0][3], output_file, str(e))) return False except Exception as e: logger.critical( '%s: Unknown error. Error %s' % (inspect.stack()[0][3], str(e))) raise e
python
def main(operation, profile, auto, debug, user_name=''): """ End-to-end renew of access keys for a specific profile in local awscli config """ if user_name: logger.info('user_name parameter given (%s) as surrogate' % user_name) try: if operation in VALID_INSTALL: print(operation) elif operation == 'list': print(operation) return True elif not operation: msg_accent = (Colors.BOLD + 'list' + Colors.RESET + ' | ' + Colors.BOLD + 'up' + Colors.RESET) msg = """You must provide a valid OPERATION for --operation parameter: --operation { """ + msg_accent + """ } """ stdout_message(msg) logger.warning('%s: No valid operation provided. Exit' % (inspect.stack()[0][3])) sys.exit(exit_codes['E_MISC']['Code']) else: msg = 'Unknown operation. Exit' stdout_message(msg) logger.warning('%s: %s' % (msg, inspect.stack()[0][3])) sys.exit(exit_codes['E_MISC']['Code']) except KeyError as e: logger.critical( '%s: Cannot find Key %s' % (inspect.stack()[0][3], str(e))) return False except OSError as e: logger.critical( '%s: problem writing to file %s. Error %s' % (inspect.stack()[0][3], output_file, str(e))) return False except Exception as e: logger.critical( '%s: Unknown error. Error %s' % (inspect.stack()[0][3], str(e))) raise e
[ "def", "main", "(", "operation", ",", "profile", ",", "auto", ",", "debug", ",", "user_name", "=", "''", ")", ":", "if", "user_name", ":", "logger", ".", "info", "(", "'user_name parameter given (%s) as surrogate'", "%", "user_name", ")", "try", ":", "if", "operation", "in", "VALID_INSTALL", ":", "print", "(", "operation", ")", "elif", "operation", "==", "'list'", ":", "print", "(", "operation", ")", "return", "True", "elif", "not", "operation", ":", "msg_accent", "=", "(", "Colors", ".", "BOLD", "+", "'list'", "+", "Colors", ".", "RESET", "+", "' | '", "+", "Colors", ".", "BOLD", "+", "'up'", "+", "Colors", ".", "RESET", ")", "msg", "=", "\"\"\"You must provide a valid OPERATION for --operation parameter:\n\n --operation { \"\"\"", "+", "msg_accent", "+", "\"\"\" }\n \"\"\"", "stdout_message", "(", "msg", ")", "logger", ".", "warning", "(", "'%s: No valid operation provided. Exit'", "%", "(", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ")", ")", "sys", ".", "exit", "(", "exit_codes", "[", "'E_MISC'", "]", "[", "'Code'", "]", ")", "else", ":", "msg", "=", "'Unknown operation. Exit'", "stdout_message", "(", "msg", ")", "logger", ".", "warning", "(", "'%s: %s'", "%", "(", "msg", ",", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ")", ")", "sys", ".", "exit", "(", "exit_codes", "[", "'E_MISC'", "]", "[", "'Code'", "]", ")", "except", "KeyError", "as", "e", ":", "logger", ".", "critical", "(", "'%s: Cannot find Key %s'", "%", "(", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ",", "str", "(", "e", ")", ")", ")", "return", "False", "except", "OSError", "as", "e", ":", "logger", ".", "critical", "(", "'%s: problem writing to file %s. Error %s'", "%", "(", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ",", "output_file", ",", "str", "(", "e", ")", ")", ")", "return", "False", "except", "Exception", "as", "e", ":", "logger", ".", "critical", "(", "'%s: Unknown error. Error %s'", "%", "(", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ",", "str", "(", "e", ")", ")", ")", "raise", "e" ]
End-to-end renew of access keys for a specific profile in local awscli config
[ "End", "-", "to", "-", "end", "renew", "of", "access", "keys", "for", "a", "specific", "profile", "in", "local", "awscli", "config" ]
0488bbdd516a508909267cc44191f632e21156ba
https://github.com/fstab50/metal/blob/0488bbdd516a508909267cc44191f632e21156ba/metal/cli.py#L141-L181
247,290
fstab50/metal
metal/cli.py
chooser_menu
def chooser_menu(): """ Master jump off point to ancillary functionality """ title = TITLE + "The" + Colors.ORANGE + " Metal" + Colors.RESET + TITLE + " Menu" + RESET menu = """ ________________________________________________________________ """ + title + """ ________________________________________________________________ ( """ + TITLE + "a" + RESET + """ ) : Install RKhunter Rootkit Scanner (v1.6) ( """ + TITLE + "b" + RESET + """ ) : Install Chkrootkit Rootkit Scanner (latest) ( """ + TITLE + "c" + RESET + """ ) : Run RKhunter Scan of Local Machine ( """ + TITLE + "d" + RESET + """ ) : Run Chkrootkit Scan of Local Machine """ print(menu) answer: str = input("\t\tEnter Choice [quit]: ") or '' if answer == 'a': return rkhunter() elif answer == 'b': print('\t\nrun chkrootkit installer\n') return chkrootkit.main() elif answer == 'c': print('\t\nrun rkhunter scan of local machine\n') elif answer == 'd': return chkrootkit_exec() return True
python
def chooser_menu(): """ Master jump off point to ancillary functionality """ title = TITLE + "The" + Colors.ORANGE + " Metal" + Colors.RESET + TITLE + " Menu" + RESET menu = """ ________________________________________________________________ """ + title + """ ________________________________________________________________ ( """ + TITLE + "a" + RESET + """ ) : Install RKhunter Rootkit Scanner (v1.6) ( """ + TITLE + "b" + RESET + """ ) : Install Chkrootkit Rootkit Scanner (latest) ( """ + TITLE + "c" + RESET + """ ) : Run RKhunter Scan of Local Machine ( """ + TITLE + "d" + RESET + """ ) : Run Chkrootkit Scan of Local Machine """ print(menu) answer: str = input("\t\tEnter Choice [quit]: ") or '' if answer == 'a': return rkhunter() elif answer == 'b': print('\t\nrun chkrootkit installer\n') return chkrootkit.main() elif answer == 'c': print('\t\nrun rkhunter scan of local machine\n') elif answer == 'd': return chkrootkit_exec() return True
[ "def", "chooser_menu", "(", ")", ":", "title", "=", "TITLE", "+", "\"The\"", "+", "Colors", ".", "ORANGE", "+", "\" Metal\"", "+", "Colors", ".", "RESET", "+", "TITLE", "+", "\" Menu\"", "+", "RESET", "menu", "=", "\"\"\"\n ________________________________________________________________\n\n \"\"\"", "+", "title", "+", "\"\"\"\n ________________________________________________________________\n\n\n ( \"\"\"", "+", "TITLE", "+", "\"a\"", "+", "RESET", "+", "\"\"\" ) : Install RKhunter Rootkit Scanner (v1.6)\n\n ( \"\"\"", "+", "TITLE", "+", "\"b\"", "+", "RESET", "+", "\"\"\" ) : Install Chkrootkit Rootkit Scanner (latest)\n\n ( \"\"\"", "+", "TITLE", "+", "\"c\"", "+", "RESET", "+", "\"\"\" ) : Run RKhunter Scan of Local Machine\n\n ( \"\"\"", "+", "TITLE", "+", "\"d\"", "+", "RESET", "+", "\"\"\" ) : Run Chkrootkit Scan of Local Machine\n\n \"\"\"", "print", "(", "menu", ")", "answer", ":", "str", "=", "input", "(", "\"\\t\\tEnter Choice [quit]: \"", ")", "or", "''", "if", "answer", "==", "'a'", ":", "return", "rkhunter", "(", ")", "elif", "answer", "==", "'b'", ":", "print", "(", "'\\t\\nrun chkrootkit installer\\n'", ")", "return", "chkrootkit", ".", "main", "(", ")", "elif", "answer", "==", "'c'", ":", "print", "(", "'\\t\\nrun rkhunter scan of local machine\\n'", ")", "elif", "answer", "==", "'d'", ":", "return", "chkrootkit_exec", "(", ")", "return", "True" ]
Master jump off point to ancillary functionality
[ "Master", "jump", "off", "point", "to", "ancillary", "functionality" ]
0488bbdd516a508909267cc44191f632e21156ba
https://github.com/fstab50/metal/blob/0488bbdd516a508909267cc44191f632e21156ba/metal/cli.py#L290-L324
247,291
fstab50/metal
metal/cli.py
SetLogging.set
def set(self, mode, disable): """ create logger object, enable or disable logging """ global logger try: if logger: if disable: logger.disabled = True else: if mode in ('STREAM', 'FILE'): logger = logd.getLogger(mode, __version__) except Exception as e: logger.exception( '%s: Problem incurred during logging setup' % inspect.stack()[0][3] ) return False return True
python
def set(self, mode, disable): """ create logger object, enable or disable logging """ global logger try: if logger: if disable: logger.disabled = True else: if mode in ('STREAM', 'FILE'): logger = logd.getLogger(mode, __version__) except Exception as e: logger.exception( '%s: Problem incurred during logging setup' % inspect.stack()[0][3] ) return False return True
[ "def", "set", "(", "self", ",", "mode", ",", "disable", ")", ":", "global", "logger", "try", ":", "if", "logger", ":", "if", "disable", ":", "logger", ".", "disabled", "=", "True", "else", ":", "if", "mode", "in", "(", "'STREAM'", ",", "'FILE'", ")", ":", "logger", "=", "logd", ".", "getLogger", "(", "mode", ",", "__version__", ")", "except", "Exception", "as", "e", ":", "logger", ".", "exception", "(", "'%s: Problem incurred during logging setup'", "%", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ")", "return", "False", "return", "True" ]
create logger object, enable or disable logging
[ "create", "logger", "object", "enable", "or", "disable", "logging" ]
0488bbdd516a508909267cc44191f632e21156ba
https://github.com/fstab50/metal/blob/0488bbdd516a508909267cc44191f632e21156ba/metal/cli.py#L123-L138
247,292
eliangcs/bisheng
bisheng/jianfan.py
_translate
def _translate(unistr, table): '''Replace characters using a table.''' if type(unistr) is str: try: unistr = unistr.decode('utf-8') # Python 3 returns AttributeError when .decode() is called on a str # This means it is already unicode. except AttributeError: pass try: if type(unistr) is not unicode: return unistr # Python 3 returns NameError because unicode is not a type. except NameError: pass chars = [] for c in unistr: replacement = table.get(c) chars.append(replacement if replacement else c) return u''.join(chars)
python
def _translate(unistr, table): '''Replace characters using a table.''' if type(unistr) is str: try: unistr = unistr.decode('utf-8') # Python 3 returns AttributeError when .decode() is called on a str # This means it is already unicode. except AttributeError: pass try: if type(unistr) is not unicode: return unistr # Python 3 returns NameError because unicode is not a type. except NameError: pass chars = [] for c in unistr: replacement = table.get(c) chars.append(replacement if replacement else c) return u''.join(chars)
[ "def", "_translate", "(", "unistr", ",", "table", ")", ":", "if", "type", "(", "unistr", ")", "is", "str", ":", "try", ":", "unistr", "=", "unistr", ".", "decode", "(", "'utf-8'", ")", "# Python 3 returns AttributeError when .decode() is called on a str", "# This means it is already unicode.", "except", "AttributeError", ":", "pass", "try", ":", "if", "type", "(", "unistr", ")", "is", "not", "unicode", ":", "return", "unistr", "# Python 3 returns NameError because unicode is not a type.", "except", "NameError", ":", "pass", "chars", "=", "[", "]", "for", "c", "in", "unistr", ":", "replacement", "=", "table", ".", "get", "(", "c", ")", "chars", ".", "append", "(", "replacement", "if", "replacement", "else", "c", ")", "return", "u''", ".", "join", "(", "chars", ")" ]
Replace characters using a table.
[ "Replace", "characters", "using", "a", "table", "." ]
cbb9b1fcfee7598ea96b6412742a273e17537195
https://github.com/eliangcs/bisheng/blob/cbb9b1fcfee7598ea96b6412742a273e17537195/bisheng/jianfan.py#L50-L70
247,293
EdwinvO/pyutillib
pyutillib/math_utils.py
eval_conditions
def eval_conditions(conditions=None, data={}): ''' Evaluates conditions and returns Boolean value. Args: conditions (tuple) for the format of the tuple, see below data (dict) the keys of which can be used in conditions Returns: (boolea) Raises: ValueError if an invalid operator value is specified TypeError if: conditions are not a 3-item tuple the arguments of the condition don't have the same type e.g. ('abc', 'eq', 3) if a boolean operator does not get boolean arguments e.g. (True, 'and', 15) The format of the condition tuple is: (arg1, op, arg2) where: arg1, arg2 can be numerical values, strings or condition tuples op is a valid operator from the operator module If arg is a string, and the string is a key in <data> it is treated as a variable with value data[arg]. Notes: * If no conditions are specified True is returned. * empty or 0 values do *not* evaluate to booleans ''' #CONSIDER: implementing addition/subtraction/multiplication/division if not conditions: return True if isinstance(conditions, str) or isinstance(conditions, unicode): conditions = str2tuple(conditions) if not isinstance(conditions, tuple) or not len(conditions) == 3: raise TypeError('conditions must be a tuple with 3 items.') arg1 = conditions[0] op = conditions[1] arg2 = conditions[2] if arg1 in data: arg1 = data[arg1] elif isinstance(arg1, tuple): arg1 = eval_conditions(arg1, data) if arg2 in data: arg2 = data[arg2] elif isinstance(arg2, tuple): arg2 = eval_conditions(arg2, data) if op in ('lt', 'le', 'eq', 'ne', 'ge', 'gt'): if not (type(arg1) in (float, int) and type(arg2) in (float,int)) and \ type(arg1) != type(arg2): raise TypeError('both arguments must have the same type {}, {}'.\ format(arg1, arg2)) elif op in ('and', 'or'): if not isinstance(arg1, bool) or not isinstance(arg2, bool): raise TypeError('boolean operator {} needs boolean arguments {},'\ ' {}'.format(op, arg1, arg2)) op += '_' else: raise ValueError('operator {} not supported', op) return getattr(operator, op)(arg1, arg2)
python
def eval_conditions(conditions=None, data={}): ''' Evaluates conditions and returns Boolean value. Args: conditions (tuple) for the format of the tuple, see below data (dict) the keys of which can be used in conditions Returns: (boolea) Raises: ValueError if an invalid operator value is specified TypeError if: conditions are not a 3-item tuple the arguments of the condition don't have the same type e.g. ('abc', 'eq', 3) if a boolean operator does not get boolean arguments e.g. (True, 'and', 15) The format of the condition tuple is: (arg1, op, arg2) where: arg1, arg2 can be numerical values, strings or condition tuples op is a valid operator from the operator module If arg is a string, and the string is a key in <data> it is treated as a variable with value data[arg]. Notes: * If no conditions are specified True is returned. * empty or 0 values do *not* evaluate to booleans ''' #CONSIDER: implementing addition/subtraction/multiplication/division if not conditions: return True if isinstance(conditions, str) or isinstance(conditions, unicode): conditions = str2tuple(conditions) if not isinstance(conditions, tuple) or not len(conditions) == 3: raise TypeError('conditions must be a tuple with 3 items.') arg1 = conditions[0] op = conditions[1] arg2 = conditions[2] if arg1 in data: arg1 = data[arg1] elif isinstance(arg1, tuple): arg1 = eval_conditions(arg1, data) if arg2 in data: arg2 = data[arg2] elif isinstance(arg2, tuple): arg2 = eval_conditions(arg2, data) if op in ('lt', 'le', 'eq', 'ne', 'ge', 'gt'): if not (type(arg1) in (float, int) and type(arg2) in (float,int)) and \ type(arg1) != type(arg2): raise TypeError('both arguments must have the same type {}, {}'.\ format(arg1, arg2)) elif op in ('and', 'or'): if not isinstance(arg1, bool) or not isinstance(arg2, bool): raise TypeError('boolean operator {} needs boolean arguments {},'\ ' {}'.format(op, arg1, arg2)) op += '_' else: raise ValueError('operator {} not supported', op) return getattr(operator, op)(arg1, arg2)
[ "def", "eval_conditions", "(", "conditions", "=", "None", ",", "data", "=", "{", "}", ")", ":", "#CONSIDER: implementing addition/subtraction/multiplication/division", "if", "not", "conditions", ":", "return", "True", "if", "isinstance", "(", "conditions", ",", "str", ")", "or", "isinstance", "(", "conditions", ",", "unicode", ")", ":", "conditions", "=", "str2tuple", "(", "conditions", ")", "if", "not", "isinstance", "(", "conditions", ",", "tuple", ")", "or", "not", "len", "(", "conditions", ")", "==", "3", ":", "raise", "TypeError", "(", "'conditions must be a tuple with 3 items.'", ")", "arg1", "=", "conditions", "[", "0", "]", "op", "=", "conditions", "[", "1", "]", "arg2", "=", "conditions", "[", "2", "]", "if", "arg1", "in", "data", ":", "arg1", "=", "data", "[", "arg1", "]", "elif", "isinstance", "(", "arg1", ",", "tuple", ")", ":", "arg1", "=", "eval_conditions", "(", "arg1", ",", "data", ")", "if", "arg2", "in", "data", ":", "arg2", "=", "data", "[", "arg2", "]", "elif", "isinstance", "(", "arg2", ",", "tuple", ")", ":", "arg2", "=", "eval_conditions", "(", "arg2", ",", "data", ")", "if", "op", "in", "(", "'lt'", ",", "'le'", ",", "'eq'", ",", "'ne'", ",", "'ge'", ",", "'gt'", ")", ":", "if", "not", "(", "type", "(", "arg1", ")", "in", "(", "float", ",", "int", ")", "and", "type", "(", "arg2", ")", "in", "(", "float", ",", "int", ")", ")", "and", "type", "(", "arg1", ")", "!=", "type", "(", "arg2", ")", ":", "raise", "TypeError", "(", "'both arguments must have the same type {}, {}'", ".", "format", "(", "arg1", ",", "arg2", ")", ")", "elif", "op", "in", "(", "'and'", ",", "'or'", ")", ":", "if", "not", "isinstance", "(", "arg1", ",", "bool", ")", "or", "not", "isinstance", "(", "arg2", ",", "bool", ")", ":", "raise", "TypeError", "(", "'boolean operator {} needs boolean arguments {},'", "' {}'", ".", "format", "(", "op", ",", "arg1", ",", "arg2", ")", ")", "op", "+=", "'_'", "else", ":", "raise", "ValueError", "(", "'operator {} not supported'", ",", "op", ")", "return", "getattr", "(", "operator", ",", "op", ")", "(", "arg1", ",", "arg2", ")" ]
Evaluates conditions and returns Boolean value. Args: conditions (tuple) for the format of the tuple, see below data (dict) the keys of which can be used in conditions Returns: (boolea) Raises: ValueError if an invalid operator value is specified TypeError if: conditions are not a 3-item tuple the arguments of the condition don't have the same type e.g. ('abc', 'eq', 3) if a boolean operator does not get boolean arguments e.g. (True, 'and', 15) The format of the condition tuple is: (arg1, op, arg2) where: arg1, arg2 can be numerical values, strings or condition tuples op is a valid operator from the operator module If arg is a string, and the string is a key in <data> it is treated as a variable with value data[arg]. Notes: * If no conditions are specified True is returned. * empty or 0 values do *not* evaluate to booleans
[ "Evaluates", "conditions", "and", "returns", "Boolean", "value", "." ]
6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/math_utils.py#L54-L114
247,294
minhhoit/yacms
yacms/utils/docs.py
deep_force_unicode
def deep_force_unicode(value): """ Recursively call force_text on value. """ if isinstance(value, (list, tuple, set)): value = type(value)(map(deep_force_unicode, value)) elif isinstance(value, dict): value = type(value)(map(deep_force_unicode, value.items())) elif isinstance(value, Promise): value = force_text(value) return value
python
def deep_force_unicode(value): """ Recursively call force_text on value. """ if isinstance(value, (list, tuple, set)): value = type(value)(map(deep_force_unicode, value)) elif isinstance(value, dict): value = type(value)(map(deep_force_unicode, value.items())) elif isinstance(value, Promise): value = force_text(value) return value
[ "def", "deep_force_unicode", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", ":", "value", "=", "type", "(", "value", ")", "(", "map", "(", "deep_force_unicode", ",", "value", ")", ")", "elif", "isinstance", "(", "value", ",", "dict", ")", ":", "value", "=", "type", "(", "value", ")", "(", "map", "(", "deep_force_unicode", ",", "value", ".", "items", "(", ")", ")", ")", "elif", "isinstance", "(", "value", ",", "Promise", ")", ":", "value", "=", "force_text", "(", "value", ")", "return", "value" ]
Recursively call force_text on value.
[ "Recursively", "call", "force_text", "on", "value", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/docs.py#L25-L35
247,295
minhhoit/yacms
yacms/utils/docs.py
build_settings_docs
def build_settings_docs(docs_path, prefix=None): """ Converts names, descriptions and defaults for settings in ``yacms.conf.registry`` into RST format for use in docs, optionally filtered by setting names with the given prefix. """ # String to use instead of setting value for dynamic defaults dynamic = "[dynamic]" lines = [".. THIS DOCUMENT IS AUTO GENERATED VIA conf.py"] for name in sorted(registry.keys()): if prefix and not name.startswith(prefix): continue setting = registry[name] settings_name = "``%s``" % name settings_label = ".. _%s:" % name setting_default = setting["default"] if isinstance(setting_default, str): if gethostname() in setting_default or ( setting_default.startswith("/") and os.path.exists(setting_default)): setting_default = dynamic if setting_default != dynamic: setting_default = repr(deep_force_unicode(setting_default)) lines.extend(["", settings_label]) lines.extend(["", settings_name, "-" * len(settings_name)]) lines.extend(["", urlize(setting["description"] or "").replace( "<a href=\"", "`").replace( "\" rel=\"nofollow\">", " <").replace( "</a>", ">`_")]) if setting["choices"]: choices = ", ".join(["%s: ``%s``" % (str(v), force_text(k)) for k, v in setting["choices"]]) lines.extend(["", "Choices: %s" % choices, ""]) lines.extend(["", "Default: ``%s``" % setting_default]) with open(os.path.join(docs_path, "settings.rst"), "w") as f: f.write("\n".join(lines).replace("u'", "'").replace("yo'", "you'").replace("&#39;", "'"))
python
def build_settings_docs(docs_path, prefix=None): """ Converts names, descriptions and defaults for settings in ``yacms.conf.registry`` into RST format for use in docs, optionally filtered by setting names with the given prefix. """ # String to use instead of setting value for dynamic defaults dynamic = "[dynamic]" lines = [".. THIS DOCUMENT IS AUTO GENERATED VIA conf.py"] for name in sorted(registry.keys()): if prefix and not name.startswith(prefix): continue setting = registry[name] settings_name = "``%s``" % name settings_label = ".. _%s:" % name setting_default = setting["default"] if isinstance(setting_default, str): if gethostname() in setting_default or ( setting_default.startswith("/") and os.path.exists(setting_default)): setting_default = dynamic if setting_default != dynamic: setting_default = repr(deep_force_unicode(setting_default)) lines.extend(["", settings_label]) lines.extend(["", settings_name, "-" * len(settings_name)]) lines.extend(["", urlize(setting["description"] or "").replace( "<a href=\"", "`").replace( "\" rel=\"nofollow\">", " <").replace( "</a>", ">`_")]) if setting["choices"]: choices = ", ".join(["%s: ``%s``" % (str(v), force_text(k)) for k, v in setting["choices"]]) lines.extend(["", "Choices: %s" % choices, ""]) lines.extend(["", "Default: ``%s``" % setting_default]) with open(os.path.join(docs_path, "settings.rst"), "w") as f: f.write("\n".join(lines).replace("u'", "'").replace("yo'", "you'").replace("&#39;", "'"))
[ "def", "build_settings_docs", "(", "docs_path", ",", "prefix", "=", "None", ")", ":", "# String to use instead of setting value for dynamic defaults", "dynamic", "=", "\"[dynamic]\"", "lines", "=", "[", "\".. THIS DOCUMENT IS AUTO GENERATED VIA conf.py\"", "]", "for", "name", "in", "sorted", "(", "registry", ".", "keys", "(", ")", ")", ":", "if", "prefix", "and", "not", "name", ".", "startswith", "(", "prefix", ")", ":", "continue", "setting", "=", "registry", "[", "name", "]", "settings_name", "=", "\"``%s``\"", "%", "name", "settings_label", "=", "\".. _%s:\"", "%", "name", "setting_default", "=", "setting", "[", "\"default\"", "]", "if", "isinstance", "(", "setting_default", ",", "str", ")", ":", "if", "gethostname", "(", ")", "in", "setting_default", "or", "(", "setting_default", ".", "startswith", "(", "\"/\"", ")", "and", "os", ".", "path", ".", "exists", "(", "setting_default", ")", ")", ":", "setting_default", "=", "dynamic", "if", "setting_default", "!=", "dynamic", ":", "setting_default", "=", "repr", "(", "deep_force_unicode", "(", "setting_default", ")", ")", "lines", ".", "extend", "(", "[", "\"\"", ",", "settings_label", "]", ")", "lines", ".", "extend", "(", "[", "\"\"", ",", "settings_name", ",", "\"-\"", "*", "len", "(", "settings_name", ")", "]", ")", "lines", ".", "extend", "(", "[", "\"\"", ",", "urlize", "(", "setting", "[", "\"description\"", "]", "or", "\"\"", ")", ".", "replace", "(", "\"<a href=\\\"\"", ",", "\"`\"", ")", ".", "replace", "(", "\"\\\" rel=\\\"nofollow\\\">\"", ",", "\" <\"", ")", ".", "replace", "(", "\"</a>\"", ",", "\">`_\"", ")", "]", ")", "if", "setting", "[", "\"choices\"", "]", ":", "choices", "=", "\", \"", ".", "join", "(", "[", "\"%s: ``%s``\"", "%", "(", "str", "(", "v", ")", ",", "force_text", "(", "k", ")", ")", "for", "k", ",", "v", "in", "setting", "[", "\"choices\"", "]", "]", ")", "lines", ".", "extend", "(", "[", "\"\"", ",", "\"Choices: %s\"", "%", "choices", ",", "\"\"", "]", ")", "lines", ".", "extend", "(", "[", "\"\"", ",", "\"Default: ``%s``\"", "%", "setting_default", "]", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "docs_path", ",", "\"settings.rst\"", ")", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "\"\\n\"", ".", "join", "(", "lines", ")", ".", "replace", "(", "\"u'\"", ",", "\"'\"", ")", ".", "replace", "(", "\"yo'\"", ",", "\"you'\"", ")", ".", "replace", "(", "\"&#39;\"", ",", "\"'\"", ")", ")" ]
Converts names, descriptions and defaults for settings in ``yacms.conf.registry`` into RST format for use in docs, optionally filtered by setting names with the given prefix.
[ "Converts", "names", "descriptions", "and", "defaults", "for", "settings", "in", "yacms", ".", "conf", ".", "registry", "into", "RST", "format", "for", "use", "in", "docs", "optionally", "filtered", "by", "setting", "names", "with", "the", "given", "prefix", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/docs.py#L38-L75
247,296
minhhoit/yacms
yacms/utils/docs.py
build_modelgraph
def build_modelgraph(docs_path, package_name="yacms"): """ Creates a diagram of all the models for yacms and the given package name, generates a smaller version and add it to the docs directory for use in model-graph.rst """ to_path = os.path.join(docs_path, "img", "graph.png") build_path = os.path.join(docs_path, "build", "_images") resized_path = os.path.join(os.path.dirname(to_path), "graph-small.png") settings = import_dotted_path(package_name + ".project_template.project_name.settings") apps = [a.rsplit(".")[1] for a in settings.INSTALLED_APPS if a.startswith("yacms.") or a.startswith(package_name + ".")] try: from django_extensions.management.commands import graph_models except ImportError: warn("Couldn't build model_graph, django_extensions not installed") else: options = {"inheritance": True, "outputfile": "graph.png", "layout": "dot"} try: graph_models.Command().execute(*apps, **options) except Exception as e: warn("Couldn't build model_graph, graph_models failed on: %s" % e) else: try: move("graph.png", to_path) except OSError as e: warn("Couldn't build model_graph, move failed on: %s" % e) # docs/img/graph.png should exist in the repo - move it to the build path. try: if not os.path.exists(build_path): os.makedirs(build_path) copyfile(to_path, os.path.join(build_path, "graph.png")) except OSError as e: warn("Couldn't build model_graph, copy to build failed on: %s" % e) try: from PIL import Image image = Image.open(to_path) image.width = 800 image.height = image.size[1] * 800 // image.size[0] image.save(resized_path, "PNG", quality=100) except Exception as e: warn("Couldn't build model_graph, resize failed on: %s" % e) return # Copy the dashboard screenshot to the build dir too. This doesn't # really belong anywhere, so we do it here since this is the only # spot we deal with doc images. d = "dashboard.png" copyfile(os.path.join(docs_path, "img", d), os.path.join(build_path, d))
python
def build_modelgraph(docs_path, package_name="yacms"): """ Creates a diagram of all the models for yacms and the given package name, generates a smaller version and add it to the docs directory for use in model-graph.rst """ to_path = os.path.join(docs_path, "img", "graph.png") build_path = os.path.join(docs_path, "build", "_images") resized_path = os.path.join(os.path.dirname(to_path), "graph-small.png") settings = import_dotted_path(package_name + ".project_template.project_name.settings") apps = [a.rsplit(".")[1] for a in settings.INSTALLED_APPS if a.startswith("yacms.") or a.startswith(package_name + ".")] try: from django_extensions.management.commands import graph_models except ImportError: warn("Couldn't build model_graph, django_extensions not installed") else: options = {"inheritance": True, "outputfile": "graph.png", "layout": "dot"} try: graph_models.Command().execute(*apps, **options) except Exception as e: warn("Couldn't build model_graph, graph_models failed on: %s" % e) else: try: move("graph.png", to_path) except OSError as e: warn("Couldn't build model_graph, move failed on: %s" % e) # docs/img/graph.png should exist in the repo - move it to the build path. try: if not os.path.exists(build_path): os.makedirs(build_path) copyfile(to_path, os.path.join(build_path, "graph.png")) except OSError as e: warn("Couldn't build model_graph, copy to build failed on: %s" % e) try: from PIL import Image image = Image.open(to_path) image.width = 800 image.height = image.size[1] * 800 // image.size[0] image.save(resized_path, "PNG", quality=100) except Exception as e: warn("Couldn't build model_graph, resize failed on: %s" % e) return # Copy the dashboard screenshot to the build dir too. This doesn't # really belong anywhere, so we do it here since this is the only # spot we deal with doc images. d = "dashboard.png" copyfile(os.path.join(docs_path, "img", d), os.path.join(build_path, d))
[ "def", "build_modelgraph", "(", "docs_path", ",", "package_name", "=", "\"yacms\"", ")", ":", "to_path", "=", "os", ".", "path", ".", "join", "(", "docs_path", ",", "\"img\"", ",", "\"graph.png\"", ")", "build_path", "=", "os", ".", "path", ".", "join", "(", "docs_path", ",", "\"build\"", ",", "\"_images\"", ")", "resized_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "to_path", ")", ",", "\"graph-small.png\"", ")", "settings", "=", "import_dotted_path", "(", "package_name", "+", "\".project_template.project_name.settings\"", ")", "apps", "=", "[", "a", ".", "rsplit", "(", "\".\"", ")", "[", "1", "]", "for", "a", "in", "settings", ".", "INSTALLED_APPS", "if", "a", ".", "startswith", "(", "\"yacms.\"", ")", "or", "a", ".", "startswith", "(", "package_name", "+", "\".\"", ")", "]", "try", ":", "from", "django_extensions", ".", "management", ".", "commands", "import", "graph_models", "except", "ImportError", ":", "warn", "(", "\"Couldn't build model_graph, django_extensions not installed\"", ")", "else", ":", "options", "=", "{", "\"inheritance\"", ":", "True", ",", "\"outputfile\"", ":", "\"graph.png\"", ",", "\"layout\"", ":", "\"dot\"", "}", "try", ":", "graph_models", ".", "Command", "(", ")", ".", "execute", "(", "*", "apps", ",", "*", "*", "options", ")", "except", "Exception", "as", "e", ":", "warn", "(", "\"Couldn't build model_graph, graph_models failed on: %s\"", "%", "e", ")", "else", ":", "try", ":", "move", "(", "\"graph.png\"", ",", "to_path", ")", "except", "OSError", "as", "e", ":", "warn", "(", "\"Couldn't build model_graph, move failed on: %s\"", "%", "e", ")", "# docs/img/graph.png should exist in the repo - move it to the build path.", "try", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "build_path", ")", ":", "os", ".", "makedirs", "(", "build_path", ")", "copyfile", "(", "to_path", ",", "os", ".", "path", ".", "join", "(", "build_path", ",", "\"graph.png\"", ")", ")", "except", "OSError", "as", "e", ":", "warn", "(", "\"Couldn't build model_graph, copy to build failed on: %s\"", "%", "e", ")", "try", ":", "from", "PIL", "import", "Image", "image", "=", "Image", ".", "open", "(", "to_path", ")", "image", ".", "width", "=", "800", "image", ".", "height", "=", "image", ".", "size", "[", "1", "]", "*", "800", "//", "image", ".", "size", "[", "0", "]", "image", ".", "save", "(", "resized_path", ",", "\"PNG\"", ",", "quality", "=", "100", ")", "except", "Exception", "as", "e", ":", "warn", "(", "\"Couldn't build model_graph, resize failed on: %s\"", "%", "e", ")", "return", "# Copy the dashboard screenshot to the build dir too. This doesn't", "# really belong anywhere, so we do it here since this is the only", "# spot we deal with doc images.", "d", "=", "\"dashboard.png\"", "copyfile", "(", "os", ".", "path", ".", "join", "(", "docs_path", ",", "\"img\"", ",", "d", ")", ",", "os", ".", "path", ".", "join", "(", "build_path", ",", "d", ")", ")" ]
Creates a diagram of all the models for yacms and the given package name, generates a smaller version and add it to the docs directory for use in model-graph.rst
[ "Creates", "a", "diagram", "of", "all", "the", "models", "for", "yacms", "and", "the", "given", "package", "name", "generates", "a", "smaller", "version", "and", "add", "it", "to", "the", "docs", "directory", "for", "use", "in", "model", "-", "graph", ".", "rst" ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/docs.py#L236-L285
247,297
minhhoit/yacms
yacms/utils/docs.py
build_requirements
def build_requirements(docs_path, package_name="yacms"): """ Updates the requirements file with yacms's version number. """ mezz_string = "yacms==" project_path = os.path.join(docs_path, "..") requirements_file = os.path.join(project_path, package_name, "project_template", "requirements.txt") with open(requirements_file, "r") as f: requirements = f.readlines() with open(requirements_file, "w") as f: f.write("yacms==%s\n" % __version__) for requirement in requirements: if requirement.strip() and not requirement.startswith(mezz_string): f.write(requirement)
python
def build_requirements(docs_path, package_name="yacms"): """ Updates the requirements file with yacms's version number. """ mezz_string = "yacms==" project_path = os.path.join(docs_path, "..") requirements_file = os.path.join(project_path, package_name, "project_template", "requirements.txt") with open(requirements_file, "r") as f: requirements = f.readlines() with open(requirements_file, "w") as f: f.write("yacms==%s\n" % __version__) for requirement in requirements: if requirement.strip() and not requirement.startswith(mezz_string): f.write(requirement)
[ "def", "build_requirements", "(", "docs_path", ",", "package_name", "=", "\"yacms\"", ")", ":", "mezz_string", "=", "\"yacms==\"", "project_path", "=", "os", ".", "path", ".", "join", "(", "docs_path", ",", "\"..\"", ")", "requirements_file", "=", "os", ".", "path", ".", "join", "(", "project_path", ",", "package_name", ",", "\"project_template\"", ",", "\"requirements.txt\"", ")", "with", "open", "(", "requirements_file", ",", "\"r\"", ")", "as", "f", ":", "requirements", "=", "f", ".", "readlines", "(", ")", "with", "open", "(", "requirements_file", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "\"yacms==%s\\n\"", "%", "__version__", ")", "for", "requirement", "in", "requirements", ":", "if", "requirement", ".", "strip", "(", ")", "and", "not", "requirement", ".", "startswith", "(", "mezz_string", ")", ":", "f", ".", "write", "(", "requirement", ")" ]
Updates the requirements file with yacms's version number.
[ "Updates", "the", "requirements", "file", "with", "yacms", "s", "version", "number", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/docs.py#L288-L302
247,298
foliant-docs/foliantcontrib.flags
foliant/preprocessors/flags.py
Preprocessor.process_flagged_blocks
def process_flagged_blocks(self, content: str) -> str: '''Replace flagged blocks either with their contents or nothing, depending on the value of ``FOLIANT_FLAGS`` environment variable and ``flags`` config value. :param content: Markdown content :returns: Markdown content without flagged blocks ''' def _sub(flagged_block): options = self.get_options(flagged_block.group('options')) required_flags = { flag.lower() for flag in re.split(self._flag_delimiters, options.get('flags', '')) if flag } | { f'target:{target.lower()}' for target in re.split(self._flag_delimiters, options.get('targets', '')) if target } | { f'backend:{backend.lower()}' for backend in re.split(self._flag_delimiters, options.get('backends', '')) if backend } env_flags = { flag.lower() for flag in re.split(self._flag_delimiters, getenv(self._flags_envvar, '')) if flag } config_flags = {flag.lower() for flag in self.options['flags']} set_flags = env_flags \ | config_flags \ | {f'target:{self.context["target"]}', f'backend:{self.context["backend"]}'} kind = options.get('kind', 'all') if (kind == 'all' and required_flags <= set_flags) \ or (kind == 'any' and required_flags & set_flags) \ or (kind == 'none' and not required_flags & set_flags): return flagged_block.group('body').strip() else: return '' return self.pattern.sub(_sub, content)
python
def process_flagged_blocks(self, content: str) -> str: '''Replace flagged blocks either with their contents or nothing, depending on the value of ``FOLIANT_FLAGS`` environment variable and ``flags`` config value. :param content: Markdown content :returns: Markdown content without flagged blocks ''' def _sub(flagged_block): options = self.get_options(flagged_block.group('options')) required_flags = { flag.lower() for flag in re.split(self._flag_delimiters, options.get('flags', '')) if flag } | { f'target:{target.lower()}' for target in re.split(self._flag_delimiters, options.get('targets', '')) if target } | { f'backend:{backend.lower()}' for backend in re.split(self._flag_delimiters, options.get('backends', '')) if backend } env_flags = { flag.lower() for flag in re.split(self._flag_delimiters, getenv(self._flags_envvar, '')) if flag } config_flags = {flag.lower() for flag in self.options['flags']} set_flags = env_flags \ | config_flags \ | {f'target:{self.context["target"]}', f'backend:{self.context["backend"]}'} kind = options.get('kind', 'all') if (kind == 'all' and required_flags <= set_flags) \ or (kind == 'any' and required_flags & set_flags) \ or (kind == 'none' and not required_flags & set_flags): return flagged_block.group('body').strip() else: return '' return self.pattern.sub(_sub, content)
[ "def", "process_flagged_blocks", "(", "self", ",", "content", ":", "str", ")", "->", "str", ":", "def", "_sub", "(", "flagged_block", ")", ":", "options", "=", "self", ".", "get_options", "(", "flagged_block", ".", "group", "(", "'options'", ")", ")", "required_flags", "=", "{", "flag", ".", "lower", "(", ")", "for", "flag", "in", "re", ".", "split", "(", "self", ".", "_flag_delimiters", ",", "options", ".", "get", "(", "'flags'", ",", "''", ")", ")", "if", "flag", "}", "|", "{", "f'target:{target.lower()}'", "for", "target", "in", "re", ".", "split", "(", "self", ".", "_flag_delimiters", ",", "options", ".", "get", "(", "'targets'", ",", "''", ")", ")", "if", "target", "}", "|", "{", "f'backend:{backend.lower()}'", "for", "backend", "in", "re", ".", "split", "(", "self", ".", "_flag_delimiters", ",", "options", ".", "get", "(", "'backends'", ",", "''", ")", ")", "if", "backend", "}", "env_flags", "=", "{", "flag", ".", "lower", "(", ")", "for", "flag", "in", "re", ".", "split", "(", "self", ".", "_flag_delimiters", ",", "getenv", "(", "self", ".", "_flags_envvar", ",", "''", ")", ")", "if", "flag", "}", "config_flags", "=", "{", "flag", ".", "lower", "(", ")", "for", "flag", "in", "self", ".", "options", "[", "'flags'", "]", "}", "set_flags", "=", "env_flags", "|", "config_flags", "|", "{", "f'target:{self.context[\"target\"]}'", ",", "f'backend:{self.context[\"backend\"]}'", "}", "kind", "=", "options", ".", "get", "(", "'kind'", ",", "'all'", ")", "if", "(", "kind", "==", "'all'", "and", "required_flags", "<=", "set_flags", ")", "or", "(", "kind", "==", "'any'", "and", "required_flags", "&", "set_flags", ")", "or", "(", "kind", "==", "'none'", "and", "not", "required_flags", "&", "set_flags", ")", ":", "return", "flagged_block", ".", "group", "(", "'body'", ")", ".", "strip", "(", ")", "else", ":", "return", "''", "return", "self", ".", "pattern", ".", "sub", "(", "_sub", ",", "content", ")" ]
Replace flagged blocks either with their contents or nothing, depending on the value of ``FOLIANT_FLAGS`` environment variable and ``flags`` config value. :param content: Markdown content :returns: Markdown content without flagged blocks
[ "Replace", "flagged", "blocks", "either", "with", "their", "contents", "or", "nothing", "depending", "on", "the", "value", "of", "FOLIANT_FLAGS", "environment", "variable", "and", "flags", "config", "value", "." ]
467b46eb77b341ba989c6165f8d3bcae9532df6d
https://github.com/foliant-docs/foliantcontrib.flags/blob/467b46eb77b341ba989c6165f8d3bcae9532df6d/foliant/preprocessors/flags.py#L16-L64
247,299
sternoru/goscalecms
goscale/views.py
form
def form(request): """ Ajax handler for Google Form submition """ if request.method == 'POST': url = request.POST['url'] submit_url = '%s%shl=%s' % ( url, '&' if '?' in url else '?', request.LANGUAGE_CODE ) params = urllib.urlencode(request.POST) f = urllib2.urlopen(submit_url, params) text = f.read() else: text = _('Error: request type has to be POST') response = http.HttpResponse(text, mimetype="text/plain") return response
python
def form(request): """ Ajax handler for Google Form submition """ if request.method == 'POST': url = request.POST['url'] submit_url = '%s%shl=%s' % ( url, '&' if '?' in url else '?', request.LANGUAGE_CODE ) params = urllib.urlencode(request.POST) f = urllib2.urlopen(submit_url, params) text = f.read() else: text = _('Error: request type has to be POST') response = http.HttpResponse(text, mimetype="text/plain") return response
[ "def", "form", "(", "request", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "url", "=", "request", ".", "POST", "[", "'url'", "]", "submit_url", "=", "'%s%shl=%s'", "%", "(", "url", ",", "'&'", "if", "'?'", "in", "url", "else", "'?'", ",", "request", ".", "LANGUAGE_CODE", ")", "params", "=", "urllib", ".", "urlencode", "(", "request", ".", "POST", ")", "f", "=", "urllib2", ".", "urlopen", "(", "submit_url", ",", "params", ")", "text", "=", "f", ".", "read", "(", ")", "else", ":", "text", "=", "_", "(", "'Error: request type has to be POST'", ")", "response", "=", "http", ".", "HttpResponse", "(", "text", ",", "mimetype", "=", "\"text/plain\"", ")", "return", "response" ]
Ajax handler for Google Form submition
[ "Ajax", "handler", "for", "Google", "Form", "submition" ]
7eee50357c47ebdfe3e573a8b4be3b67892d229e
https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/views.py#L18-L35