id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
241,200
krukas/Trionyx
trionyx/trionyx/views/core.py
ListExportView.items
def items(self): """Get all list items""" query = self.get_queryset() fields = self.get_model_config().get_list_fields() for item in query.iterator(): row = OrderedDict() for field_name in self.get_current_fields(): field = fields.get(field_name) ...
python
def items(self): """Get all list items""" query = self.get_queryset() fields = self.get_model_config().get_list_fields() for item in query.iterator(): row = OrderedDict() for field_name in self.get_current_fields(): field = fields.get(field_name) ...
[ "def", "items", "(", "self", ")", ":", "query", "=", "self", ".", "get_queryset", "(", ")", "fields", "=", "self", ".", "get_model_config", "(", ")", ".", "get_list_fields", "(", ")", "for", "item", "in", "query", ".", "iterator", "(", ")", ":", "row...
Get all list items
[ "Get", "all", "list", "items" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L304-L320
241,201
krukas/Trionyx
trionyx/trionyx/views/core.py
ListExportView.csv_response
def csv_response(self): """Get csv response""" def stream(): """Create data stream generator""" stream_file = io.StringIO() csvwriter = csv.writer(stream_file, delimiter=',', quotechar='"') csvwriter.writerow(self.get_current_fields()) for in...
python
def csv_response(self): """Get csv response""" def stream(): """Create data stream generator""" stream_file = io.StringIO() csvwriter = csv.writer(stream_file, delimiter=',', quotechar='"') csvwriter.writerow(self.get_current_fields()) for in...
[ "def", "csv_response", "(", "self", ")", ":", "def", "stream", "(", ")", ":", "\"\"\"Create data stream generator\"\"\"", "stream_file", "=", "io", ".", "StringIO", "(", ")", "csvwriter", "=", "csv", ".", "writer", "(", "stream_file", ",", "delimiter", "=", ...
Get csv response
[ "Get", "csv", "response" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L322-L341
241,202
krukas/Trionyx
trionyx/trionyx/views/core.py
DetailTabView.get_delete_url
def get_delete_url(self): """Get model object delete url""" return reverse('trionyx:model-delete', kwargs={ 'app': self.get_app_label(), 'model': self.get_model_name(), 'pk': self.object.id })
python
def get_delete_url(self): """Get model object delete url""" return reverse('trionyx:model-delete', kwargs={ 'app': self.get_app_label(), 'model': self.get_model_name(), 'pk': self.object.id })
[ "def", "get_delete_url", "(", "self", ")", ":", "return", "reverse", "(", "'trionyx:model-delete'", ",", "kwargs", "=", "{", "'app'", ":", "self", ".", "get_app_label", "(", ")", ",", "'model'", ":", "self", ".", "get_model_name", "(", ")", ",", "'pk'", ...
Get model object delete url
[ "Get", "model", "object", "delete", "url" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L398-L404
241,203
krukas/Trionyx
trionyx/trionyx/views/core.py
DetailTabView.get_edit_url
def get_edit_url(self): """Get model object edit url""" return reverse('trionyx:model-edit', kwargs={ 'app': self.get_app_label(), 'model': self.get_model_name(), 'pk': self.object.id })
python
def get_edit_url(self): """Get model object edit url""" return reverse('trionyx:model-edit', kwargs={ 'app': self.get_app_label(), 'model': self.get_model_name(), 'pk': self.object.id })
[ "def", "get_edit_url", "(", "self", ")", ":", "return", "reverse", "(", "'trionyx:model-edit'", ",", "kwargs", "=", "{", "'app'", ":", "self", ".", "get_app_label", "(", ")", ",", "'model'", ":", "self", ".", "get_model_name", "(", ")", ",", "'pk'", ":",...
Get model object edit url
[ "Get", "model", "object", "edit", "url" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L406-L412
241,204
krukas/Trionyx
trionyx/trionyx/views/core.py
DetailTabView.get_model_alias
def get_model_alias(self): """Get model alias""" if self.model_alias: return self.model_alias return '{}.{}'.format(self.get_app_label(), self.get_model_name())
python
def get_model_alias(self): """Get model alias""" if self.model_alias: return self.model_alias return '{}.{}'.format(self.get_app_label(), self.get_model_name())
[ "def", "get_model_alias", "(", "self", ")", ":", "if", "self", ".", "model_alias", ":", "return", "self", ".", "model_alias", "return", "'{}.{}'", ".", "format", "(", "self", ".", "get_app_label", "(", ")", ",", "self", ".", "get_model_name", "(", ")", "...
Get model alias
[ "Get", "model", "alias" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L414-L418
241,205
krukas/Trionyx
trionyx/trionyx/views/core.py
DetailTabJsendView.handle_request
def handle_request(self, request, app, model, pk): """Render and return tab""" ModelClass = self.get_model_class() object = ModelClass.objects.get(id=pk) tab_code = request.GET.get('tab') model_alias = request.GET.get('model_alias') model_alias = model_alias if model_ali...
python
def handle_request(self, request, app, model, pk): """Render and return tab""" ModelClass = self.get_model_class() object = ModelClass.objects.get(id=pk) tab_code = request.GET.get('tab') model_alias = request.GET.get('model_alias') model_alias = model_alias if model_ali...
[ "def", "handle_request", "(", "self", ",", "request", ",", "app", ",", "model", ",", "pk", ")", ":", "ModelClass", "=", "self", ".", "get_model_class", "(", ")", "object", "=", "ModelClass", ".", "objects", ".", "get", "(", "id", "=", "pk", ")", "tab...
Render and return tab
[ "Render", "and", "return", "tab" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L442-L455
241,206
krukas/Trionyx
trionyx/trionyx/views/core.py
UpdateView.get_form
def get_form(self, form_class=None): """Get form for model""" form = super().get_form(form_class) if not getattr(form, 'helper', None): form.helper = FormHelper() form.helper.form_tag = False else: form.helper.form_tag = False return form
python
def get_form(self, form_class=None): """Get form for model""" form = super().get_form(form_class) if not getattr(form, 'helper', None): form.helper = FormHelper() form.helper.form_tag = False else: form.helper.form_tag = False return form
[ "def", "get_form", "(", "self", ",", "form_class", "=", "None", ")", ":", "form", "=", "super", "(", ")", ".", "get_form", "(", "form_class", ")", "if", "not", "getattr", "(", "form", ",", "'helper'", ",", "None", ")", ":", "form", ".", "helper", "...
Get form for model
[ "Get", "form", "for", "model" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L490-L499
241,207
krukas/Trionyx
trionyx/trionyx/views/core.py
CreateView.get_cancel_url
def get_cancel_url(self): """Get cancel url""" if self.cancel_url: return self.cancel_url ModelClass = self.get_model_class() return reverse('trionyx:model-list', kwargs={ 'app': ModelClass._meta.app_label, 'model': ModelClass._meta.model_name, ...
python
def get_cancel_url(self): """Get cancel url""" if self.cancel_url: return self.cancel_url ModelClass = self.get_model_class() return reverse('trionyx:model-list', kwargs={ 'app': ModelClass._meta.app_label, 'model': ModelClass._meta.model_name, ...
[ "def", "get_cancel_url", "(", "self", ")", ":", "if", "self", ".", "cancel_url", ":", "return", "self", ".", "cancel_url", "ModelClass", "=", "self", ".", "get_model_class", "(", ")", "return", "reverse", "(", "'trionyx:model-list'", ",", "kwargs", "=", "{",...
Get cancel url
[ "Get", "cancel", "url" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L559-L568
241,208
krukas/Trionyx
trionyx/trionyx/views/core.py
CreateView.form_valid
def form_valid(self, form): """Add success message""" response = super().form_valid(form) messages.success(self.request, "Successfully created ({})".format(self.object)) return response
python
def form_valid(self, form): """Add success message""" response = super().form_valid(form) messages.success(self.request, "Successfully created ({})".format(self.object)) return response
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "response", "=", "super", "(", ")", ".", "form_valid", "(", "form", ")", "messages", ".", "success", "(", "self", ".", "request", ",", "\"Successfully created ({})\"", ".", "format", "(", "self", "...
Add success message
[ "Add", "success", "message" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L582-L586
241,209
krukas/Trionyx
trionyx/trionyx/views/core.py
DeleteView.get_success_url
def get_success_url(self): """Get success url""" messages.success(self.request, "Successfully deleted ({})".format(self.object)) if self.success_url: return reverse(self.success_url) if 'app' in self.kwargs and 'model' in self.kwargs: return reverse('trionyx:mode...
python
def get_success_url(self): """Get success url""" messages.success(self.request, "Successfully deleted ({})".format(self.object)) if self.success_url: return reverse(self.success_url) if 'app' in self.kwargs and 'model' in self.kwargs: return reverse('trionyx:mode...
[ "def", "get_success_url", "(", "self", ")", ":", "messages", ".", "success", "(", "self", ".", "request", ",", "\"Successfully deleted ({})\"", ".", "format", "(", "self", ".", "object", ")", ")", "if", "self", ".", "success_url", ":", "return", "reverse", ...
Get success url
[ "Get", "success", "url" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L622-L634
241,210
krukas/Trionyx
trionyx/trionyx/views/core.py
DialogView.get
def get(self, request, *args, **kwargs): """Handle get request""" try: kwargs = self.load_object(kwargs) except Exception as e: return self.render_te_response({ 'title': str(e), }) if not self.has_permission(request): retur...
python
def get(self, request, *args, **kwargs): """Handle get request""" try: kwargs = self.load_object(kwargs) except Exception as e: return self.render_te_response({ 'title': str(e), }) if not self.has_permission(request): retur...
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "kwargs", "=", "self", ".", "load_object", "(", "kwargs", ")", "except", "Exception", "as", "e", ":", "return", "self", ".", "render_te_respon...
Handle get request
[ "Handle", "get", "request" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L682-L695
241,211
krukas/Trionyx
trionyx/trionyx/views/core.py
DialogView.post
def post(self, request, *args, **kwargs): """Handle post request""" try: kwargs = self.load_object(kwargs) except Exception as e: return self.render_te_response({ 'title': str(e), }) if not self.has_permission(request): ret...
python
def post(self, request, *args, **kwargs): """Handle post request""" try: kwargs = self.load_object(kwargs) except Exception as e: return self.render_te_response({ 'title': str(e), }) if not self.has_permission(request): ret...
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "kwargs", "=", "self", ".", "load_object", "(", "kwargs", ")", "except", "Exception", "as", "e", ":", "return", "self", ".", "render_te_respo...
Handle post request
[ "Handle", "post", "request" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L697-L710
241,212
krukas/Trionyx
trionyx/trionyx/views/core.py
DialogView.load_object
def load_object(self, kwargs): """Load object and model config and remove pk from kwargs""" self.object = None self.config = None self.model = self.get_model_class() kwargs.pop('app', None) kwargs.pop('model', None) if self.model and kwargs.get('pk', False): ...
python
def load_object(self, kwargs): """Load object and model config and remove pk from kwargs""" self.object = None self.config = None self.model = self.get_model_class() kwargs.pop('app', None) kwargs.pop('model', None) if self.model and kwargs.get('pk', False): ...
[ "def", "load_object", "(", "self", ",", "kwargs", ")", ":", "self", ".", "object", "=", "None", "self", ".", "config", "=", "None", "self", ".", "model", "=", "self", ".", "get_model_class", "(", ")", "kwargs", ".", "pop", "(", "'app'", ",", "None", ...
Load object and model config and remove pk from kwargs
[ "Load", "object", "and", "model", "config", "and", "remove", "pk", "from", "kwargs" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L712-L727
241,213
krukas/Trionyx
trionyx/trionyx/views/core.py
DialogView.has_permission
def has_permission(self, request): """Check if user has permission""" if not self.object and not self.permission: return True if not self.permission: return request.user.has_perm('{}_{}'.format( self.model_permission, self.object.__class__...
python
def has_permission(self, request): """Check if user has permission""" if not self.object and not self.permission: return True if not self.permission: return request.user.has_perm('{}_{}'.format( self.model_permission, self.object.__class__...
[ "def", "has_permission", "(", "self", ",", "request", ")", ":", "if", "not", "self", ".", "object", "and", "not", "self", ".", "permission", ":", "return", "True", "if", "not", "self", ".", "permission", ":", "return", "request", ".", "user", ".", "has...
Check if user has permission
[ "Check", "if", "user", "has", "permission" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L729-L740
241,214
krukas/Trionyx
trionyx/trionyx/views/core.py
DialogView.render_to_string
def render_to_string(self, template_file, context): """Render given template to string and add object to context""" context = context if context else {} if self.object: context['object'] = self.object context[self.object.__class__.__name__.lower()] = self.object r...
python
def render_to_string(self, template_file, context): """Render given template to string and add object to context""" context = context if context else {} if self.object: context['object'] = self.object context[self.object.__class__.__name__.lower()] = self.object r...
[ "def", "render_to_string", "(", "self", ",", "template_file", ",", "context", ")", ":", "context", "=", "context", "if", "context", "else", "{", "}", "if", "self", ".", "object", ":", "context", "[", "'object'", "]", "=", "self", ".", "object", "context"...
Render given template to string and add object to context
[ "Render", "given", "template", "to", "string", "and", "add", "object", "to", "context" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L742-L748
241,215
krukas/Trionyx
trionyx/trionyx/views/core.py
DialogView.render_te_response
def render_te_response(self, data): """Render data to JsonResponse""" if 'submit_label' in data and 'url' not in data: data['url'] = self.request.get_full_path() return JsonResponse(data)
python
def render_te_response(self, data): """Render data to JsonResponse""" if 'submit_label' in data and 'url' not in data: data['url'] = self.request.get_full_path() return JsonResponse(data)
[ "def", "render_te_response", "(", "self", ",", "data", ")", ":", "if", "'submit_label'", "in", "data", "and", "'url'", "not", "in", "data", ":", "data", "[", "'url'", "]", "=", "self", ".", "request", ".", "get_full_path", "(", ")", "return", "JsonRespon...
Render data to JsonResponse
[ "Render", "data", "to", "JsonResponse" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L774-L779
241,216
krukas/Trionyx
trionyx/trionyx/views/core.py
UpdateDialog.display_dialog
def display_dialog(self, *args, **kwargs): """Display form and success message when set""" form = kwargs.pop('form_instance', None) success_message = kwargs.pop('success_message', None) if not form: form = self.get_form_class()(initial=kwargs, instance=self.object) ...
python
def display_dialog(self, *args, **kwargs): """Display form and success message when set""" form = kwargs.pop('form_instance', None) success_message = kwargs.pop('success_message', None) if not form: form = self.get_form_class()(initial=kwargs, instance=self.object) ...
[ "def", "display_dialog", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "form", "=", "kwargs", ".", "pop", "(", "'form_instance'", ",", "None", ")", "success_message", "=", "kwargs", ".", "pop", "(", "'success_message'", ",", "None", ...
Display form and success message when set
[ "Display", "form", "and", "success", "message", "when", "set" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L802-L825
241,217
krukas/Trionyx
trionyx/trionyx/views/core.py
UpdateDialog.handle_dialog
def handle_dialog(self, *args, **kwargs): """Handle form and save and set success message on valid form""" form = self.get_form_class()(self.request.POST, initial=kwargs, instance=self.object) success_message = None if form.is_valid(): obj = form.save() success_m...
python
def handle_dialog(self, *args, **kwargs): """Handle form and save and set success message on valid form""" form = self.get_form_class()(self.request.POST, initial=kwargs, instance=self.object) success_message = None if form.is_valid(): obj = form.save() success_m...
[ "def", "handle_dialog", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "form", "=", "self", ".", "get_form_class", "(", ")", "(", "self", ".", "request", ".", "POST", ",", "initial", "=", "kwargs", ",", "instance", "=", "self", "...
Handle form and save and set success message on valid form
[ "Handle", "form", "and", "save", "and", "set", "success", "message", "on", "valid", "form" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L827-L838
241,218
neshkatrapati/pypresenter
pypresenter/pypresenter.py
SlideDeck.get_term_size
def get_term_size(): '''Gets the size of your terminal. May not work everywhere. YMMV.''' rows, columns = os.popen('stty size', 'r').read().split() return int(rows), int(columns)
python
def get_term_size(): '''Gets the size of your terminal. May not work everywhere. YMMV.''' rows, columns = os.popen('stty size', 'r').read().split() return int(rows), int(columns)
[ "def", "get_term_size", "(", ")", ":", "rows", ",", "columns", "=", "os", ".", "popen", "(", "'stty size'", ",", "'r'", ")", ".", "read", "(", ")", ".", "split", "(", ")", "return", "int", "(", "rows", ")", ",", "int", "(", "columns", ")" ]
Gets the size of your terminal. May not work everywhere. YMMV.
[ "Gets", "the", "size", "of", "your", "terminal", ".", "May", "not", "work", "everywhere", ".", "YMMV", "." ]
bc4cccb17523972dd60de49a34e0ed050b788ad4
https://github.com/neshkatrapati/pypresenter/blob/bc4cccb17523972dd60de49a34e0ed050b788ad4/pypresenter/pypresenter.py#L280-L283
241,219
hobson/pug-dj
pug/dj/crawlnmine/management/__init__.py
find_commands
def find_commands(management_dir): """ Given a path to a management directory, returns a list of all the command names that are available. Returns an empty list if no commands are defined. """ command_dir = os.path.join(management_dir, 'commands') try: return [f[:-3] for f in os.lis...
python
def find_commands(management_dir): """ Given a path to a management directory, returns a list of all the command names that are available. Returns an empty list if no commands are defined. """ command_dir = os.path.join(management_dir, 'commands') try: return [f[:-3] for f in os.lis...
[ "def", "find_commands", "(", "management_dir", ")", ":", "command_dir", "=", "os", ".", "path", ".", "join", "(", "management_dir", ",", "'commands'", ")", "try", ":", "return", "[", "f", "[", ":", "-", "3", "]", "for", "f", "in", "os", ".", "listdir...
Given a path to a management directory, returns a list of all the command names that are available. Returns an empty list if no commands are defined.
[ "Given", "a", "path", "to", "a", "management", "directory", "returns", "a", "list", "of", "all", "the", "command", "names", "that", "are", "available", "." ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawlnmine/management/__init__.py#L23-L35
241,220
hobson/pug-dj
pug/dj/crawlnmine/management/__init__.py
get_commands
def get_commands(): """ Returns a dictionary mapping command names to their callback applications. This works by looking for a management.commands package in django.core, and in each installed application -- if a commands package exists, all commands in that package are registered. Core comman...
python
def get_commands(): """ Returns a dictionary mapping command names to their callback applications. This works by looking for a management.commands package in django.core, and in each installed application -- if a commands package exists, all commands in that package are registered. Core comman...
[ "def", "get_commands", "(", ")", ":", "commands", "=", "dict", "(", "(", "name", ",", "'pug.crawlnmine'", ")", "for", "name", "in", "find_commands", "(", "__path__", "[", "0", "]", ")", ")", "if", "not", "settings", ".", "configured", ":", "return", "c...
Returns a dictionary mapping command names to their callback applications. This works by looking for a management.commands package in django.core, and in each installed application -- if a commands package exists, all commands in that package are registered. Core commands are always included. If a set...
[ "Returns", "a", "dictionary", "mapping", "command", "names", "to", "their", "callback", "applications", "." ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawlnmine/management/__init__.py#L49-L80
241,221
hobson/pug-dj
pug/dj/crawlnmine/management/__init__.py
ManagementUtility.autocomplete
def autocomplete(self): """ Output completion suggestions for BASH. The output of this function is passed to BASH's `COMREPLY` variable and treated as completion suggestions. `COMREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BA...
python
def autocomplete(self): """ Output completion suggestions for BASH. The output of this function is passed to BASH's `COMREPLY` variable and treated as completion suggestions. `COMREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BA...
[ "def", "autocomplete", "(", "self", ")", ":", "# Don't complete if user hasn't sourced bash_completion file.", "if", "'DJANGO_AUTO_COMPLETE'", "not", "in", "os", ".", "environ", ":", "return", "cwords", "=", "os", ".", "environ", "[", "'COMP_WORDS'", "]", ".", "spli...
Output completion suggestions for BASH. The output of this function is passed to BASH's `COMREPLY` variable and treated as completion suggestions. `COMREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used to...
[ "Output", "completion", "suggestions", "for", "BASH", "." ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawlnmine/management/__init__.py#L189-L267
241,222
maxweisspoker/simplebitcoinfuncs
simplebitcoinfuncs/miscbitcoinfuncs.py
genkeyhex
def genkeyhex(): ''' Generate new random Bitcoin private key, using os.urandom and double-sha256. Hex format. ''' while True: key = hash256( hexlify(os.urandom(40) + str(datetime.datetime.now()) .encode("utf-8"))) # 40 byt...
python
def genkeyhex(): ''' Generate new random Bitcoin private key, using os.urandom and double-sha256. Hex format. ''' while True: key = hash256( hexlify(os.urandom(40) + str(datetime.datetime.now()) .encode("utf-8"))) # 40 byt...
[ "def", "genkeyhex", "(", ")", ":", "while", "True", ":", "key", "=", "hash256", "(", "hexlify", "(", "os", ".", "urandom", "(", "40", ")", "+", "str", "(", "datetime", ".", "datetime", ".", "now", "(", ")", ")", ".", "encode", "(", "\"utf-8\"", "...
Generate new random Bitcoin private key, using os.urandom and double-sha256. Hex format.
[ "Generate", "new", "random", "Bitcoin", "private", "key", "using", "os", ".", "urandom", "and", "double", "-", "sha256", ".", "Hex", "format", "." ]
ad332433dfcc067e86d2e77fa0c8f1a27daffb63
https://github.com/maxweisspoker/simplebitcoinfuncs/blob/ad332433dfcc067e86d2e77fa0c8f1a27daffb63/simplebitcoinfuncs/miscbitcoinfuncs.py#L38-L56
241,223
maxweisspoker/simplebitcoinfuncs
simplebitcoinfuncs/miscbitcoinfuncs.py
genkey
def genkey(outcompressed=True,prefix='80'): ''' Generate new random Bitcoin private key, using os.urandom and double-sha256. ''' key = prefix + genkeyhex() if outcompressed: key = key + '01' return b58e(key)
python
def genkey(outcompressed=True,prefix='80'): ''' Generate new random Bitcoin private key, using os.urandom and double-sha256. ''' key = prefix + genkeyhex() if outcompressed: key = key + '01' return b58e(key)
[ "def", "genkey", "(", "outcompressed", "=", "True", ",", "prefix", "=", "'80'", ")", ":", "key", "=", "prefix", "+", "genkeyhex", "(", ")", "if", "outcompressed", ":", "key", "=", "key", "+", "'01'", "return", "b58e", "(", "key", ")" ]
Generate new random Bitcoin private key, using os.urandom and double-sha256.
[ "Generate", "new", "random", "Bitcoin", "private", "key", "using", "os", ".", "urandom", "and", "double", "-", "sha256", "." ]
ad332433dfcc067e86d2e77fa0c8f1a27daffb63
https://github.com/maxweisspoker/simplebitcoinfuncs/blob/ad332433dfcc067e86d2e77fa0c8f1a27daffb63/simplebitcoinfuncs/miscbitcoinfuncs.py#L59-L68
241,224
maxweisspoker/simplebitcoinfuncs
simplebitcoinfuncs/miscbitcoinfuncs.py
getandstrip_varintdata
def getandstrip_varintdata(data): ''' Takes a hex string that begins with varint data, and has extra at the end, and gets the varint integer, strips the varint bytes, and returns the integer and the remaining data. So rather than having to manually read the varint prefix, count, and strip, you can ...
python
def getandstrip_varintdata(data): ''' Takes a hex string that begins with varint data, and has extra at the end, and gets the varint integer, strips the varint bytes, and returns the integer and the remaining data. So rather than having to manually read the varint prefix, count, and strip, you can ...
[ "def", "getandstrip_varintdata", "(", "data", ")", ":", "data", "=", "strlify", "(", "data", ")", "numbytes", "=", "numvarintbytes", "(", "data", "[", ":", "2", "]", ")", "varint", "=", "data", "[", ":", "2", "*", "numbytes", "]", "data", "=", "data"...
Takes a hex string that begins with varint data, and has extra at the end, and gets the varint integer, strips the varint bytes, and returns the integer and the remaining data. So rather than having to manually read the varint prefix, count, and strip, you can do it in one function. This function will...
[ "Takes", "a", "hex", "string", "that", "begins", "with", "varint", "data", "and", "has", "extra", "at", "the", "end", "and", "gets", "the", "varint", "integer", "strips", "the", "varint", "bytes", "and", "returns", "the", "integer", "and", "the", "remainin...
ad332433dfcc067e86d2e77fa0c8f1a27daffb63
https://github.com/maxweisspoker/simplebitcoinfuncs/blob/ad332433dfcc067e86d2e77fa0c8f1a27daffb63/simplebitcoinfuncs/miscbitcoinfuncs.py#L147-L187
241,225
maxweisspoker/simplebitcoinfuncs
simplebitcoinfuncs/miscbitcoinfuncs.py
LEB128toint
def LEB128toint(LEBinput): ''' Convert unsigned LEB128 hex to integer ''' reversedbytes = hexreverse(LEBinput) binstr = "" for i in range(len(LEBinput) // 2): if i == 0: assert int(reversedbytes[2*i:(2*i + 2)],16) < 128 else: assert int(reversedbytes[2*i:...
python
def LEB128toint(LEBinput): ''' Convert unsigned LEB128 hex to integer ''' reversedbytes = hexreverse(LEBinput) binstr = "" for i in range(len(LEBinput) // 2): if i == 0: assert int(reversedbytes[2*i:(2*i + 2)],16) < 128 else: assert int(reversedbytes[2*i:...
[ "def", "LEB128toint", "(", "LEBinput", ")", ":", "reversedbytes", "=", "hexreverse", "(", "LEBinput", ")", "binstr", "=", "\"\"", "for", "i", "in", "range", "(", "len", "(", "LEBinput", ")", "//", "2", ")", ":", "if", "i", "==", "0", ":", "assert", ...
Convert unsigned LEB128 hex to integer
[ "Convert", "unsigned", "LEB128", "hex", "to", "integer" ]
ad332433dfcc067e86d2e77fa0c8f1a27daffb63
https://github.com/maxweisspoker/simplebitcoinfuncs/blob/ad332433dfcc067e86d2e77fa0c8f1a27daffb63/simplebitcoinfuncs/miscbitcoinfuncs.py#L226-L243
241,226
Nekroze/librarian
librarian/card.py
Card.add_attribute
def add_attribute(self, attribute): """ Add the given attribute to this Card. Returns the length of attributes after addition. """ self.attributes.append(attribute) return len(self.attributes)
python
def add_attribute(self, attribute): """ Add the given attribute to this Card. Returns the length of attributes after addition. """ self.attributes.append(attribute) return len(self.attributes)
[ "def", "add_attribute", "(", "self", ",", "attribute", ")", ":", "self", ".", "attributes", ".", "append", "(", "attribute", ")", "return", "len", "(", "self", ".", "attributes", ")" ]
Add the given attribute to this Card. Returns the length of attributes after addition.
[ "Add", "the", "given", "attribute", "to", "this", "Card", ".", "Returns", "the", "length", "of", "attributes", "after", "addition", "." ]
5d3da2980d91a637f80ad7164fbf204a2dd2bd58
https://github.com/Nekroze/librarian/blob/5d3da2980d91a637f80ad7164fbf204a2dd2bd58/librarian/card.py#L42-L48
241,227
Nekroze/librarian
librarian/card.py
Card.add_ability
def add_ability(self, phase, ability): """Add the given ability to this Card under the given phase. Returns the length of the abilities for the given phase after the addition. """ if phase not in self.abilities: self.abilities[phase] = [] self.abilities[phase].append(...
python
def add_ability(self, phase, ability): """Add the given ability to this Card under the given phase. Returns the length of the abilities for the given phase after the addition. """ if phase not in self.abilities: self.abilities[phase] = [] self.abilities[phase].append(...
[ "def", "add_ability", "(", "self", ",", "phase", ",", "ability", ")", ":", "if", "phase", "not", "in", "self", ".", "abilities", ":", "self", ".", "abilities", "[", "phase", "]", "=", "[", "]", "self", ".", "abilities", "[", "phase", "]", ".", "app...
Add the given ability to this Card under the given phase. Returns the length of the abilities for the given phase after the addition.
[ "Add", "the", "given", "ability", "to", "this", "Card", "under", "the", "given", "phase", ".", "Returns", "the", "length", "of", "the", "abilities", "for", "the", "given", "phase", "after", "the", "addition", "." ]
5d3da2980d91a637f80ad7164fbf204a2dd2bd58
https://github.com/Nekroze/librarian/blob/5d3da2980d91a637f80ad7164fbf204a2dd2bd58/librarian/card.py#L54-L61
241,228
Nekroze/librarian
librarian/card.py
Card.set_info
def set_info(self, key, value, append=True): """ Set any special info you wish to the given key. Each info is stored in a list and will be appended to rather then overriden unless append is False. """ if append: if key not in self.info: self.in...
python
def set_info(self, key, value, append=True): """ Set any special info you wish to the given key. Each info is stored in a list and will be appended to rather then overriden unless append is False. """ if append: if key not in self.info: self.in...
[ "def", "set_info", "(", "self", ",", "key", ",", "value", ",", "append", "=", "True", ")", ":", "if", "append", ":", "if", "key", "not", "in", "self", ".", "info", ":", "self", ".", "info", "[", "key", "]", "=", "[", "]", "self", ".", "info", ...
Set any special info you wish to the given key. Each info is stored in a list and will be appended to rather then overriden unless append is False.
[ "Set", "any", "special", "info", "you", "wish", "to", "the", "given", "key", ".", "Each", "info", "is", "stored", "in", "a", "list", "and", "will", "be", "appended", "to", "rather", "then", "overriden", "unless", "append", "is", "False", "." ]
5d3da2980d91a637f80ad7164fbf204a2dd2bd58
https://github.com/Nekroze/librarian/blob/5d3da2980d91a637f80ad7164fbf204a2dd2bd58/librarian/card.py#L67-L78
241,229
Nekroze/librarian
librarian/card.py
Card.save
def save(self): """ Converts the Card as is into a dictionary capable of reconstructing the card with ``Card.load`` or serialized to a string for storage. """ return dict(code=self.code, name=self.name, abilities=self.abilities, attributes=self.attributes, inf...
python
def save(self): """ Converts the Card as is into a dictionary capable of reconstructing the card with ``Card.load`` or serialized to a string for storage. """ return dict(code=self.code, name=self.name, abilities=self.abilities, attributes=self.attributes, inf...
[ "def", "save", "(", "self", ")", ":", "return", "dict", "(", "code", "=", "self", ".", "code", ",", "name", "=", "self", ".", "name", ",", "abilities", "=", "self", ".", "abilities", ",", "attributes", "=", "self", ".", "attributes", ",", "info", "...
Converts the Card as is into a dictionary capable of reconstructing the card with ``Card.load`` or serialized to a string for storage.
[ "Converts", "the", "Card", "as", "is", "into", "a", "dictionary", "capable", "of", "reconstructing", "the", "card", "with", "Card", ".", "load", "or", "serialized", "to", "a", "string", "for", "storage", "." ]
5d3da2980d91a637f80ad7164fbf204a2dd2bd58
https://github.com/Nekroze/librarian/blob/5d3da2980d91a637f80ad7164fbf204a2dd2bd58/librarian/card.py#L80-L86
241,230
Nekroze/librarian
librarian/card.py
Card.load
def load(self, carddict): """ Takes a carddict as produced by ``Card.save`` and sets this card instances information to the previously saved cards information. """ self.code = carddict["code"] if isinstance(self.code, text_type): self.code = eval(self.code) ...
python
def load(self, carddict): """ Takes a carddict as produced by ``Card.save`` and sets this card instances information to the previously saved cards information. """ self.code = carddict["code"] if isinstance(self.code, text_type): self.code = eval(self.code) ...
[ "def", "load", "(", "self", ",", "carddict", ")", ":", "self", ".", "code", "=", "carddict", "[", "\"code\"", "]", "if", "isinstance", "(", "self", ".", "code", ",", "text_type", ")", ":", "self", ".", "code", "=", "eval", "(", "self", ".", "code",...
Takes a carddict as produced by ``Card.save`` and sets this card instances information to the previously saved cards information.
[ "Takes", "a", "carddict", "as", "produced", "by", "Card", ".", "save", "and", "sets", "this", "card", "instances", "information", "to", "the", "previously", "saved", "cards", "information", "." ]
5d3da2980d91a637f80ad7164fbf204a2dd2bd58
https://github.com/Nekroze/librarian/blob/5d3da2980d91a637f80ad7164fbf204a2dd2bd58/librarian/card.py#L88-L106
241,231
andreycizov/python-xrpc
xrpc/examples/exceptional.py
Exceptional.ep
def ep(self, exc: Exception) -> bool: """Return False if the exception had not been handled gracefully""" if not isinstance(exc, ConnectionAbortedError): return False if len(exc.args) != 2: return False origin, reason = exc.args logging.getLogger(__name...
python
def ep(self, exc: Exception) -> bool: """Return False if the exception had not been handled gracefully""" if not isinstance(exc, ConnectionAbortedError): return False if len(exc.args) != 2: return False origin, reason = exc.args logging.getLogger(__name...
[ "def", "ep", "(", "self", ",", "exc", ":", "Exception", ")", "->", "bool", ":", "if", "not", "isinstance", "(", "exc", ",", "ConnectionAbortedError", ")", ":", "return", "False", "if", "len", "(", "exc", ".", "args", ")", "!=", "2", ":", "return", ...
Return False if the exception had not been handled gracefully
[ "Return", "False", "if", "the", "exception", "had", "not", "been", "handled", "gracefully" ]
4f916383cda7de3272962f3ba07a64f7ec451098
https://github.com/andreycizov/python-xrpc/blob/4f916383cda7de3272962f3ba07a64f7ec451098/xrpc/examples/exceptional.py#L19-L31
241,232
edeposit/edeposit.amqp.ltp
src/edeposit/amqp/ltp/ltp.py
_get_package_name
def _get_package_name(prefix=settings.TEMP_DIR, book_id=None): """ Return package path. Use uuid to generate package's directory name. Args: book_id (str, default None): UUID of the book. prefix (str, default settings.TEMP_DIR): Where the package will be stored. Default :attr...
python
def _get_package_name(prefix=settings.TEMP_DIR, book_id=None): """ Return package path. Use uuid to generate package's directory name. Args: book_id (str, default None): UUID of the book. prefix (str, default settings.TEMP_DIR): Where the package will be stored. Default :attr...
[ "def", "_get_package_name", "(", "prefix", "=", "settings", ".", "TEMP_DIR", ",", "book_id", "=", "None", ")", ":", "if", "book_id", "is", "None", ":", "book_id", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "return", "os", ".", "path", ".",...
Return package path. Use uuid to generate package's directory name. Args: book_id (str, default None): UUID of the book. prefix (str, default settings.TEMP_DIR): Where the package will be stored. Default :attr:`settings.TEMP_DIR`. Returns: str: Path to the root directory...
[ "Return", "package", "path", ".", "Use", "uuid", "to", "generate", "package", "s", "directory", "name", "." ]
df9ac7ec6cbdbeaaeed438ca66df75ea967b6d8e
https://github.com/edeposit/edeposit.amqp.ltp/blob/df9ac7ec6cbdbeaaeed438ca66df75ea967b6d8e/src/edeposit/amqp/ltp/ltp.py#L22-L37
241,233
edeposit/edeposit.amqp.ltp
src/edeposit/amqp/ltp/ltp.py
_create_package_hierarchy
def _create_package_hierarchy(prefix=settings.TEMP_DIR, book_id=None): """ Create hierarchy of directories, at it is required in specification. `root_dir` is root of the package generated using :attr:`settings.TEMP_DIR` and :func:`_get_package_name`. `orig_dir` is path to the directory, where the ...
python
def _create_package_hierarchy(prefix=settings.TEMP_DIR, book_id=None): """ Create hierarchy of directories, at it is required in specification. `root_dir` is root of the package generated using :attr:`settings.TEMP_DIR` and :func:`_get_package_name`. `orig_dir` is path to the directory, where the ...
[ "def", "_create_package_hierarchy", "(", "prefix", "=", "settings", ".", "TEMP_DIR", ",", "book_id", "=", "None", ")", ":", "root_dir", "=", "_get_package_name", "(", "book_id", "=", "book_id", ",", "prefix", "=", "prefix", ")", "if", "os", ".", "path", "....
Create hierarchy of directories, at it is required in specification. `root_dir` is root of the package generated using :attr:`settings.TEMP_DIR` and :func:`_get_package_name`. `orig_dir` is path to the directory, where the data files are stored. `metadata_dir` is path to the directory with MODS metad...
[ "Create", "hierarchy", "of", "directories", "at", "it", "is", "required", "in", "specification", "." ]
df9ac7ec6cbdbeaaeed438ca66df75ea967b6d8e
https://github.com/edeposit/edeposit.amqp.ltp/blob/df9ac7ec6cbdbeaaeed438ca66df75ea967b6d8e/src/edeposit/amqp/ltp/ltp.py#L40-L75
241,234
edeposit/edeposit.amqp.ltp
src/edeposit/amqp/ltp/ltp.py
create_ltp_package
def create_ltp_package(aleph_record, book_id, ebook_fn, data, url, urn_nbn=None): """ Create LTP package as it is specified in specification v1.0 as I understand it. Args: aleph_record (str): XML containing full aleph record. book_id (str): UUID of the book. ...
python
def create_ltp_package(aleph_record, book_id, ebook_fn, data, url, urn_nbn=None): """ Create LTP package as it is specified in specification v1.0 as I understand it. Args: aleph_record (str): XML containing full aleph record. book_id (str): UUID of the book. ...
[ "def", "create_ltp_package", "(", "aleph_record", ",", "book_id", ",", "ebook_fn", ",", "data", ",", "url", ",", "urn_nbn", "=", "None", ")", ":", "root_dir", ",", "orig_dir", ",", "meta_dir", "=", "_create_package_hierarchy", "(", "book_id", "=", "book_id", ...
Create LTP package as it is specified in specification v1.0 as I understand it. Args: aleph_record (str): XML containing full aleph record. book_id (str): UUID of the book. ebook_fn (str): Original filename of the ebook. data (str/bytes): Ebook's content. url (str): URL ...
[ "Create", "LTP", "package", "as", "it", "is", "specified", "in", "specification", "v1", ".", "0", "as", "I", "understand", "it", "." ]
df9ac7ec6cbdbeaaeed438ca66df75ea967b6d8e
https://github.com/edeposit/edeposit.amqp.ltp/blob/df9ac7ec6cbdbeaaeed438ca66df75ea967b6d8e/src/edeposit/amqp/ltp/ltp.py#L78-L139
241,235
ArtoLabs/SimpleSteem
simplesteem/steemconnectutil.py
SteemConnect.steemconnect
def steemconnect(self, accesstoken=None): ''' Initializes the SteemConnect Client class ''' if self.sc is not None: return self.sc if accesstoken is not None: self.accesstoken = accesstoken if self.accesstoken is None: self.sc = Client(...
python
def steemconnect(self, accesstoken=None): ''' Initializes the SteemConnect Client class ''' if self.sc is not None: return self.sc if accesstoken is not None: self.accesstoken = accesstoken if self.accesstoken is None: self.sc = Client(...
[ "def", "steemconnect", "(", "self", ",", "accesstoken", "=", "None", ")", ":", "if", "self", ".", "sc", "is", "not", "None", ":", "return", "self", ".", "sc", "if", "accesstoken", "is", "not", "None", ":", "self", ".", "accesstoken", "=", "accesstoken"...
Initializes the SteemConnect Client class
[ "Initializes", "the", "SteemConnect", "Client", "class" ]
ce8be0ae81f8878b460bc156693f1957f7dd34a3
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/steemconnectutil.py#L24-L39
241,236
ArtoLabs/SimpleSteem
simplesteem/steemconnectutil.py
SteemConnect.get_token
def get_token(self, code=None): ''' Uses a SteemConnect refresh token to retreive an access token ''' tokenobj = self.steemconnect().get_access_token(code) for t in tokenobj: if t == 'error': self.msg.error_message(str(tokenobj[t])) ret...
python
def get_token(self, code=None): ''' Uses a SteemConnect refresh token to retreive an access token ''' tokenobj = self.steemconnect().get_access_token(code) for t in tokenobj: if t == 'error': self.msg.error_message(str(tokenobj[t])) ret...
[ "def", "get_token", "(", "self", ",", "code", "=", "None", ")", ":", "tokenobj", "=", "self", ".", "steemconnect", "(", ")", ".", "get_access_token", "(", "code", ")", "for", "t", "in", "tokenobj", ":", "if", "t", "==", "'error'", ":", "self", ".", ...
Uses a SteemConnect refresh token to retreive an access token
[ "Uses", "a", "SteemConnect", "refresh", "token", "to", "retreive", "an", "access", "token" ]
ce8be0ae81f8878b460bc156693f1957f7dd34a3
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/steemconnectutil.py#L42-L54
241,237
ArtoLabs/SimpleSteem
simplesteem/steemconnectutil.py
SteemConnect.vote
def vote(self, voter, author, permlink, voteweight): ''' Uses a SteemConnect accses token to vote. ''' vote = Vote(voter, author, permlink, voteweight) result = self.steemconnect().broadcast( [vote.to_operation_structure()]) return result
python
def vote(self, voter, author, permlink, voteweight): ''' Uses a SteemConnect accses token to vote. ''' vote = Vote(voter, author, permlink, voteweight) result = self.steemconnect().broadcast( [vote.to_operation_structure()]) return result
[ "def", "vote", "(", "self", ",", "voter", ",", "author", ",", "permlink", ",", "voteweight", ")", ":", "vote", "=", "Vote", "(", "voter", ",", "author", ",", "permlink", ",", "voteweight", ")", "result", "=", "self", ".", "steemconnect", "(", ")", "....
Uses a SteemConnect accses token to vote.
[ "Uses", "a", "SteemConnect", "accses", "token", "to", "vote", "." ]
ce8be0ae81f8878b460bc156693f1957f7dd34a3
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/steemconnectutil.py#L67-L74
241,238
the01/python-paps
paps/si/sensorClientAdapter.py
SensorClientAdapter.on_person_new
def on_person_new(self, people): """ Add new people All people supported need to be added simultaneously, since on every call a unjoin() followed by a join() is issued :param people: People to add :type people: list[paps.people.People] :rtype: None :rais...
python
def on_person_new(self, people): """ Add new people All people supported need to be added simultaneously, since on every call a unjoin() followed by a join() is issued :param people: People to add :type people: list[paps.people.People] :rtype: None :rais...
[ "def", "on_person_new", "(", "self", ",", "people", ")", ":", "try", ":", "self", ".", "on_person_leave", "(", "[", "]", ")", "except", ":", "# Already caught and logged", "pass", "try", ":", "self", ".", "sensor_client", ".", "join", "(", "people", ")", ...
Add new people All people supported need to be added simultaneously, since on every call a unjoin() followed by a join() is issued :param people: People to add :type people: list[paps.people.People] :rtype: None :raises Exception: On error (for now just an exception)
[ "Add", "new", "people" ]
2dde5a71913e4c7b22901cf05c6ecedd890919c4
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/sensorClientAdapter.py#L48-L70
241,239
the01/python-paps
paps/si/sensorClientAdapter.py
SensorClientAdapter.on_person_update
def on_person_update(self, people): """ People have changed Should always include all people (all that were added via on_person_new) :param people: People to update :type people: list[paps.people.People] :rtype: None :raises Exception: On error (for now ...
python
def on_person_update(self, people): """ People have changed Should always include all people (all that were added via on_person_new) :param people: People to update :type people: list[paps.people.People] :rtype: None :raises Exception: On error (for now ...
[ "def", "on_person_update", "(", "self", ",", "people", ")", ":", "try", ":", "self", ".", "sensor_client", ".", "person_update", "(", "people", ")", "except", ":", "self", ".", "exception", "(", "\"Failed to update people\"", ")", "raise", "Exception", "(", ...
People have changed Should always include all people (all that were added via on_person_new) :param people: People to update :type people: list[paps.people.People] :rtype: None :raises Exception: On error (for now just an exception)
[ "People", "have", "changed" ]
2dde5a71913e4c7b22901cf05c6ecedd890919c4
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/sensorClientAdapter.py#L90-L106
241,240
diffeo/rejester
rejester/_redis.py
RedisBase.delete_namespace
def delete_namespace(self): '''Remove all keys from the namespace ''' conn = redis.Redis(connection_pool=self.pool) keys = conn.keys("%s*" % self._namespace_str) for i in xrange(0, len(keys), 10000): conn.delete(*keys[i:i+10000]) logger.debug('tearing down %r...
python
def delete_namespace(self): '''Remove all keys from the namespace ''' conn = redis.Redis(connection_pool=self.pool) keys = conn.keys("%s*" % self._namespace_str) for i in xrange(0, len(keys), 10000): conn.delete(*keys[i:i+10000]) logger.debug('tearing down %r...
[ "def", "delete_namespace", "(", "self", ")", ":", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "keys", "=", "conn", ".", "keys", "(", "\"%s*\"", "%", "self", ".", "_namespace_str", ")", "for", "i", "in", ...
Remove all keys from the namespace
[ "Remove", "all", "keys", "from", "the", "namespace" ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_redis.py#L67-L75
241,241
unitedstack/steth
stetho/agent/common/utils.py
get_interface
def get_interface(interface): """Support Centos standard physical interface, such as eth0. """ # Supported CentOS Version supported_dists = ['7.0', '6.5'] def format_centos_7_0(inf): pattern = r'<([A-Z]+)' state = re.search(pattern, stdout[0]).groups()[0] state = 'UP'...
python
def get_interface(interface): """Support Centos standard physical interface, such as eth0. """ # Supported CentOS Version supported_dists = ['7.0', '6.5'] def format_centos_7_0(inf): pattern = r'<([A-Z]+)' state = re.search(pattern, stdout[0]).groups()[0] state = 'UP'...
[ "def", "get_interface", "(", "interface", ")", ":", "# Supported CentOS Version", "supported_dists", "=", "[", "'7.0'", ",", "'6.5'", "]", "def", "format_centos_7_0", "(", "inf", ")", ":", "pattern", "=", "r'<([A-Z]+)'", "state", "=", "re", ".", "search", "(",...
Support Centos standard physical interface, such as eth0.
[ "Support", "Centos", "standard", "physical", "interface", "such", "as", "eth0", "." ]
955884ceebf3bdc474c93cc5cf555e67d16458f1
https://github.com/unitedstack/steth/blob/955884ceebf3bdc474c93cc5cf555e67d16458f1/stetho/agent/common/utils.py#L84-L147
241,242
armstrong/armstrong.apps.images
setup.py
convert_to_str
def convert_to_str(d): """ Recursively convert all values in a dictionary to strings This is required because setup() does not like unicode in the values it is supplied. """ d2 = {} for k, v in d.items(): k = str(k) if type(v) in [list, tuple]: d2[k] = [str(a) fo...
python
def convert_to_str(d): """ Recursively convert all values in a dictionary to strings This is required because setup() does not like unicode in the values it is supplied. """ d2 = {} for k, v in d.items(): k = str(k) if type(v) in [list, tuple]: d2[k] = [str(a) fo...
[ "def", "convert_to_str", "(", "d", ")", ":", "d2", "=", "{", "}", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "k", "=", "str", "(", "k", ")", "if", "type", "(", "v", ")", "in", "[", "list", ",", "tuple", "]", ":", "d2", ...
Recursively convert all values in a dictionary to strings This is required because setup() does not like unicode in the values it is supplied.
[ "Recursively", "convert", "all", "values", "in", "a", "dictionary", "to", "strings" ]
f334697ee6e2273deac12092069d02119d913e67
https://github.com/armstrong/armstrong.apps.images/blob/f334697ee6e2273deac12092069d02119d913e67/setup.py#L15-L31
241,243
racker/torment
torment/contexts/docker/compose.py
up
def up(services: Iterable[str] = ()) -> int: '''Start the specified docker-compose services. Parameters ---------- :``services``: a list of docker-compose service names to start (must be defined in docker-compose.yml) Return Value(s) --------------- The integer status ...
python
def up(services: Iterable[str] = ()) -> int: '''Start the specified docker-compose services. Parameters ---------- :``services``: a list of docker-compose service names to start (must be defined in docker-compose.yml) Return Value(s) --------------- The integer status ...
[ "def", "up", "(", "services", ":", "Iterable", "[", "str", "]", "=", "(", ")", ")", "->", "int", ":", "services", "=", "list", "(", "services", ")", "if", "not", "len", "(", "services", ")", ":", "raise", "ValueError", "(", "'empty iterable passed to u...
Start the specified docker-compose services. Parameters ---------- :``services``: a list of docker-compose service names to start (must be defined in docker-compose.yml) Return Value(s) --------------- The integer status of ``docker-compose up``.
[ "Start", "the", "specified", "docker", "-", "compose", "services", "." ]
bd5d2f978324bf9b7360edfae76d853b226c63e1
https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/contexts/docker/compose.py#L54-L75
241,244
racker/torment
torment/contexts/docker/compose.py
_call
def _call(command: str, *args, **kwargs) -> int: '''Wrapper around ``subprocess.Popen`` that sends command output to logger. .. seealso:: ``subprocess.Popen``_ Parameters ---------- :``command``: string form of the command to execute All other parameters are passed directly to ``subp...
python
def _call(command: str, *args, **kwargs) -> int: '''Wrapper around ``subprocess.Popen`` that sends command output to logger. .. seealso:: ``subprocess.Popen``_ Parameters ---------- :``command``: string form of the command to execute All other parameters are passed directly to ``subp...
[ "def", "_call", "(", "command", ":", "str", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "int", ":", "child", "=", "subprocess", ".", "Popen", "(", "command", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ...
Wrapper around ``subprocess.Popen`` that sends command output to logger. .. seealso:: ``subprocess.Popen``_ Parameters ---------- :``command``: string form of the command to execute All other parameters are passed directly to ``subprocess.Popen``. Return Value(s) ---------------...
[ "Wrapper", "around", "subprocess", ".", "Popen", "that", "sends", "command", "output", "to", "logger", "." ]
bd5d2f978324bf9b7360edfae76d853b226c63e1
https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/contexts/docker/compose.py#L78-L118
241,245
rmed/flask-waffleconf
flask_waffleconf/watcher.py
_file_watcher
def _file_watcher(state): """Watch for file changes and reload config when needed. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """ conf = state.app.config file_path = conf.get('WAFFLE_WATCHER_FILE', '/tmp/waffleconf.txt') if ...
python
def _file_watcher(state): """Watch for file changes and reload config when needed. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """ conf = state.app.config file_path = conf.get('WAFFLE_WATCHER_FILE', '/tmp/waffleconf.txt') if ...
[ "def", "_file_watcher", "(", "state", ")", ":", "conf", "=", "state", ".", "app", ".", "config", "file_path", "=", "conf", ".", "get", "(", "'WAFFLE_WATCHER_FILE'", ",", "'/tmp/waffleconf.txt'", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "f...
Watch for file changes and reload config when needed. Arguments: state (_WaffleState): Object that contains reference to app and its configstore.
[ "Watch", "for", "file", "changes", "and", "reload", "config", "when", "needed", "." ]
a75ed69101796c9f3f42eff9f91e91dc6dd13869
https://github.com/rmed/flask-waffleconf/blob/a75ed69101796c9f3f42eff9f91e91dc6dd13869/flask_waffleconf/watcher.py#L50-L74
241,246
rmed/flask-waffleconf
flask_waffleconf/watcher.py
_redis_watcher
def _redis_watcher(state): """Listen to redis channel for a configuration update notifications. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """ conf = state.app.config r = redis.client.StrictRedis( host=conf.get('WAFFLE_RE...
python
def _redis_watcher(state): """Listen to redis channel for a configuration update notifications. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """ conf = state.app.config r = redis.client.StrictRedis( host=conf.get('WAFFLE_RE...
[ "def", "_redis_watcher", "(", "state", ")", ":", "conf", "=", "state", ".", "app", ".", "config", "r", "=", "redis", ".", "client", ".", "StrictRedis", "(", "host", "=", "conf", ".", "get", "(", "'WAFFLE_REDIS_HOST'", ",", "'localhost'", ")", ",", "por...
Listen to redis channel for a configuration update notifications. Arguments: state (_WaffleState): Object that contains reference to app and its configstore.
[ "Listen", "to", "redis", "channel", "for", "a", "configuration", "update", "notifications", "." ]
a75ed69101796c9f3f42eff9f91e91dc6dd13869
https://github.com/rmed/flask-waffleconf/blob/a75ed69101796c9f3f42eff9f91e91dc6dd13869/flask_waffleconf/watcher.py#L76-L103
241,247
rmed/flask-waffleconf
flask_waffleconf/watcher.py
_file_notifier
def _file_notifier(state): """Notify of configuration update through file. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """ tstamp = time.time() state._tstamp = tstamp conf = state.app.config file_path = conf.get('WAFFLE_WA...
python
def _file_notifier(state): """Notify of configuration update through file. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """ tstamp = time.time() state._tstamp = tstamp conf = state.app.config file_path = conf.get('WAFFLE_WA...
[ "def", "_file_notifier", "(", "state", ")", ":", "tstamp", "=", "time", ".", "time", "(", ")", "state", ".", "_tstamp", "=", "tstamp", "conf", "=", "state", ".", "app", ".", "config", "file_path", "=", "conf", ".", "get", "(", "'WAFFLE_WATCHER_FILE'", ...
Notify of configuration update through file. Arguments: state (_WaffleState): Object that contains reference to app and its configstore.
[ "Notify", "of", "configuration", "update", "through", "file", "." ]
a75ed69101796c9f3f42eff9f91e91dc6dd13869
https://github.com/rmed/flask-waffleconf/blob/a75ed69101796c9f3f42eff9f91e91dc6dd13869/flask_waffleconf/watcher.py#L121-L139
241,248
rmed/flask-waffleconf
flask_waffleconf/watcher.py
_redis_notifier
def _redis_notifier(state): """Notify of configuration update through redis. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """ tstamp = time.time() state._tstamp = tstamp conf = state.app.config # Notify timestamp r = re...
python
def _redis_notifier(state): """Notify of configuration update through redis. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """ tstamp = time.time() state._tstamp = tstamp conf = state.app.config # Notify timestamp r = re...
[ "def", "_redis_notifier", "(", "state", ")", ":", "tstamp", "=", "time", ".", "time", "(", ")", "state", ".", "_tstamp", "=", "tstamp", "conf", "=", "state", ".", "app", ".", "config", "# Notify timestamp", "r", "=", "redis", ".", "client", ".", "Stric...
Notify of configuration update through redis. Arguments: state (_WaffleState): Object that contains reference to app and its configstore.
[ "Notify", "of", "configuration", "update", "through", "redis", "." ]
a75ed69101796c9f3f42eff9f91e91dc6dd13869
https://github.com/rmed/flask-waffleconf/blob/a75ed69101796c9f3f42eff9f91e91dc6dd13869/flask_waffleconf/watcher.py#L141-L154
241,249
jordanncg/Bison
bison/libs/common.py
Common.make_dir
def make_dir(cls, directory_name): """Create a directory in the system""" if not os.path.exists(directory_name): os.makedirs(directory_name)
python
def make_dir(cls, directory_name): """Create a directory in the system""" if not os.path.exists(directory_name): os.makedirs(directory_name)
[ "def", "make_dir", "(", "cls", ",", "directory_name", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "directory_name", ")", ":", "os", ".", "makedirs", "(", "directory_name", ")" ]
Create a directory in the system
[ "Create", "a", "directory", "in", "the", "system" ]
c7f04fd67d141fe26cd29db3c3fb3fc0fd0c45df
https://github.com/jordanncg/Bison/blob/c7f04fd67d141fe26cd29db3c3fb3fc0fd0c45df/bison/libs/common.py#L35-L38
241,250
edwards-lab/libGWAS
libgwas/pedigree_parser.py
Parser.load_mapfile
def load_mapfile(self, map3=False): """Load the marker data :param map3: When true, ignore the gen. distance column Builds up the marker list according to the boundary configuration """ cols = [0, 1, 3] if map3: cols = [0, 1, 2] markers = numpy.loa...
python
def load_mapfile(self, map3=False): """Load the marker data :param map3: When true, ignore the gen. distance column Builds up the marker list according to the boundary configuration """ cols = [0, 1, 3] if map3: cols = [0, 1, 2] markers = numpy.loa...
[ "def", "load_mapfile", "(", "self", ",", "map3", "=", "False", ")", ":", "cols", "=", "[", "0", ",", "1", ",", "3", "]", "if", "map3", ":", "cols", "=", "[", "0", ",", "1", ",", "2", "]", "markers", "=", "numpy", ".", "loadtxt", "(", "self", ...
Load the marker data :param map3: When true, ignore the gen. distance column Builds up the marker list according to the boundary configuration
[ "Load", "the", "marker", "data" ]
d68c9a083d443dfa5d7c5112de29010909cfe23f
https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/pedigree_parser.py#L92-L138
241,251
hobson/pug-dj
pug/dj/db.py
normalize_values_queryset
def normalize_values_queryset(values_queryset, model=None, app=None, verbosity=1): '''Shoehorn the values from one database table into another * Remove padding (leading/trailing spaces) from `CharField` and `TextField` values * Truncate all `CharField`s to the max_length of the destination `model` * Su...
python
def normalize_values_queryset(values_queryset, model=None, app=None, verbosity=1): '''Shoehorn the values from one database table into another * Remove padding (leading/trailing spaces) from `CharField` and `TextField` values * Truncate all `CharField`s to the max_length of the destination `model` * Su...
[ "def", "normalize_values_queryset", "(", "values_queryset", ",", "model", "=", "None", ",", "app", "=", "None", ",", "verbosity", "=", "1", ")", ":", "model", "=", "model", "or", "values_queryset", ".", "model", "app", "=", "app", "or", "DEFAULT_APP", "new...
Shoehorn the values from one database table into another * Remove padding (leading/trailing spaces) from `CharField` and `TextField` values * Truncate all `CharField`s to the max_length of the destination `model` * Subsititue blanks ('') for any None values destined for `null=False` fields Returns a l...
[ "Shoehorn", "the", "values", "from", "one", "database", "table", "into", "another" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L110-L150
241,252
hobson/pug-dj
pug/dj/db.py
make_choices
def make_choices(*args): """Convert a 1-D sequence into a 2-D sequence of tuples for use in a Django field choices attribute >>> make_choices(range(3)) ((0, u'0'), (1, u'1'), (2, u'2')) >>> make_choices(dict(enumerate('abcd'))) ((0, u'a'), (1, u'b'), (2, u'c'), (3, u'd')) >>> make_choices('hell...
python
def make_choices(*args): """Convert a 1-D sequence into a 2-D sequence of tuples for use in a Django field choices attribute >>> make_choices(range(3)) ((0, u'0'), (1, u'1'), (2, u'2')) >>> make_choices(dict(enumerate('abcd'))) ((0, u'a'), (1, u'b'), (2, u'c'), (3, u'd')) >>> make_choices('hell...
[ "def", "make_choices", "(", "*", "args", ")", ":", "if", "not", "args", ":", "return", "tuple", "(", ")", "if", "isinstance", "(", "args", "[", "0", "]", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "make_choices", "(", "*", "tuple", ...
Convert a 1-D sequence into a 2-D sequence of tuples for use in a Django field choices attribute >>> make_choices(range(3)) ((0, u'0'), (1, u'1'), (2, u'2')) >>> make_choices(dict(enumerate('abcd'))) ((0, u'a'), (1, u'b'), (2, u'c'), (3, u'd')) >>> make_choices('hello') (('hello', u'hello'),) ...
[ "Convert", "a", "1", "-", "D", "sequence", "into", "a", "2", "-", "D", "sequence", "of", "tuples", "for", "use", "in", "a", "Django", "field", "choices", "attribute" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L153-L172
241,253
hobson/pug-dj
pug/dj/db.py
normalize_choices
def normalize_choices(db_values, field_name, app=DEFAULT_APP, model_name='', human_readable=True, none_value='Null', blank_value='Unknown', missing_value='Unknown DB Code'): '''Output the human-readable strings associated with the list of database values for a model field. Uses the trans...
python
def normalize_choices(db_values, field_name, app=DEFAULT_APP, model_name='', human_readable=True, none_value='Null', blank_value='Unknown', missing_value='Unknown DB Code'): '''Output the human-readable strings associated with the list of database values for a model field. Uses the trans...
[ "def", "normalize_choices", "(", "db_values", ",", "field_name", ",", "app", "=", "DEFAULT_APP", ",", "model_name", "=", "''", ",", "human_readable", "=", "True", ",", "none_value", "=", "'Null'", ",", "blank_value", "=", "'Unknown'", ",", "missing_value", "="...
Output the human-readable strings associated with the list of database values for a model field. Uses the translation dictionary `CHOICES_<FIELD_NAME>` attribute for the given `model_name`. In addition, translate `None` into 'Null', or whatever string is indicated by `none_value`.
[ "Output", "the", "human", "-", "readable", "strings", "associated", "with", "the", "list", "of", "database", "values", "for", "a", "model", "field", "." ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L177-L213
241,254
hobson/pug-dj
pug/dj/db.py
get_app
def get_app(app=None, verbosity=0): """Uses django.db.djmodels.get_app and fuzzywuzzy to get the models module for a django app Retrieve an app module from an app name string, even if mispelled (uses fuzzywuzzy to find the best match) To get a list of all the apps use `get_app(None)` or `get_app([]) or get...
python
def get_app(app=None, verbosity=0): """Uses django.db.djmodels.get_app and fuzzywuzzy to get the models module for a django app Retrieve an app module from an app name string, even if mispelled (uses fuzzywuzzy to find the best match) To get a list of all the apps use `get_app(None)` or `get_app([]) or get...
[ "def", "get_app", "(", "app", "=", "None", ",", "verbosity", "=", "0", ")", ":", "# print 'get_app(', app", "if", "not", "app", ":", "# for an empty list, tuple or None, just get all apps", "if", "isinstance", "(", "app", ",", "(", "type", "(", "None", ")", ",...
Uses django.db.djmodels.get_app and fuzzywuzzy to get the models module for a django app Retrieve an app module from an app name string, even if mispelled (uses fuzzywuzzy to find the best match) To get a list of all the apps use `get_app(None)` or `get_app([]) or get_app(())` To get a single random app us...
[ "Uses", "django", ".", "db", ".", "djmodels", ".", "get_app", "and", "fuzzywuzzy", "to", "get", "the", "models", "module", "for", "a", "django", "app" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L216-L267
241,255
hobson/pug-dj
pug/dj/db.py
get_field
def get_field(field): """Return a field object based on a dot-delimited app.model.field name""" if isinstance(field, djmodels.fields.Field): return field elif isinstance(field, basestring): field = field.split('.') if len(field) == 3: model = get_model(app=field[0], model...
python
def get_field(field): """Return a field object based on a dot-delimited app.model.field name""" if isinstance(field, djmodels.fields.Field): return field elif isinstance(field, basestring): field = field.split('.') if len(field) == 3: model = get_model(app=field[0], model...
[ "def", "get_field", "(", "field", ")", ":", "if", "isinstance", "(", "field", ",", "djmodels", ".", "fields", ".", "Field", ")", ":", "return", "field", "elif", "isinstance", "(", "field", ",", "basestring", ")", ":", "field", "=", "field", ".", "split...
Return a field object based on a dot-delimited app.model.field name
[ "Return", "a", "field", "object", "based", "on", "a", "dot", "-", "delimited", "app", ".", "model", ".", "field", "name" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L380-L394
241,256
hobson/pug-dj
pug/dj/db.py
get_primary_key
def get_primary_key(model): """Get the name of the field in a model that has primary_key=True""" model = get_model(model) return (field.name for field in model._meta.fields if field.primary_key).next()
python
def get_primary_key(model): """Get the name of the field in a model that has primary_key=True""" model = get_model(model) return (field.name for field in model._meta.fields if field.primary_key).next()
[ "def", "get_primary_key", "(", "model", ")", ":", "model", "=", "get_model", "(", "model", ")", "return", "(", "field", ".", "name", "for", "field", "in", "model", ".", "_meta", ".", "fields", "if", "field", ".", "primary_key", ")", ".", "next", "(", ...
Get the name of the field in a model that has primary_key=True
[ "Get", "the", "name", "of", "the", "field", "in", "a", "model", "that", "has", "primary_key", "=", "True" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L397-L400
241,257
hobson/pug-dj
pug/dj/db.py
querysets_from_title_prefix
def querysets_from_title_prefix(title_prefix=None, model=DEFAULT_MODEL, app=DEFAULT_APP): """Return a list of Querysets from a list of model numbers""" if title_prefix is None: title_prefix = [None] filter_dicts = [] model_list = [] if isinstance(title_prefix, basestring): title_pr...
python
def querysets_from_title_prefix(title_prefix=None, model=DEFAULT_MODEL, app=DEFAULT_APP): """Return a list of Querysets from a list of model numbers""" if title_prefix is None: title_prefix = [None] filter_dicts = [] model_list = [] if isinstance(title_prefix, basestring): title_pr...
[ "def", "querysets_from_title_prefix", "(", "title_prefix", "=", "None", ",", "model", "=", "DEFAULT_MODEL", ",", "app", "=", "DEFAULT_APP", ")", ":", "if", "title_prefix", "is", "None", ":", "title_prefix", "=", "[", "None", "]", "filter_dicts", "=", "[", "]...
Return a list of Querysets from a list of model numbers
[ "Return", "a", "list", "of", "Querysets", "from", "a", "list", "of", "model", "numbers" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L481-L513
241,258
hobson/pug-dj
pug/dj/db.py
find_field_names
def find_field_names(fields, model=DEFAULT_MODEL, app=DEFAULT_APP, score_cutoff=50, pad_with_none=False): """Use fuzzy string matching to find similar model field names without consulting a synonyms list Returns: list: A list model field names (strings) sorted from most likely to least likely. []...
python
def find_field_names(fields, model=DEFAULT_MODEL, app=DEFAULT_APP, score_cutoff=50, pad_with_none=False): """Use fuzzy string matching to find similar model field names without consulting a synonyms list Returns: list: A list model field names (strings) sorted from most likely to least likely. []...
[ "def", "find_field_names", "(", "fields", ",", "model", "=", "DEFAULT_MODEL", ",", "app", "=", "DEFAULT_APP", ",", "score_cutoff", "=", "50", ",", "pad_with_none", "=", "False", ")", ":", "fields", "=", "util", ".", "listify", "(", "fields", ")", "model", ...
Use fuzzy string matching to find similar model field names without consulting a synonyms list Returns: list: A list model field names (strings) sorted from most likely to least likely. [] If no similar field names could be found in the indicated model [None] If none found and and `pad_with_n...
[ "Use", "fuzzy", "string", "matching", "to", "find", "similar", "model", "field", "names", "without", "consulting", "a", "synonyms", "list" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L709-L733
241,259
hobson/pug-dj
pug/dj/db.py
model_from_path
def model_from_path(model_path, fuzziness=False): """Find the model class for a given model path like 'project.app.model' Args: path (str): dot-delimited model path, like 'project.app.model' Returns: Django Model-based class """ app_name = '.'.join(model_path.split('.')[:-1]) m...
python
def model_from_path(model_path, fuzziness=False): """Find the model class for a given model path like 'project.app.model' Args: path (str): dot-delimited model path, like 'project.app.model' Returns: Django Model-based class """ app_name = '.'.join(model_path.split('.')[:-1]) m...
[ "def", "model_from_path", "(", "model_path", ",", "fuzziness", "=", "False", ")", ":", "app_name", "=", "'.'", ".", "join", "(", "model_path", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "model_name", "=", "model_path", ".", "split", ...
Find the model class for a given model path like 'project.app.model' Args: path (str): dot-delimited model path, like 'project.app.model' Returns: Django Model-based class
[ "Find", "the", "model", "class", "for", "a", "given", "model", "path", "like", "project", ".", "app", ".", "model" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L736-L760
241,260
hobson/pug-dj
pug/dj/db.py
find_synonymous_field
def find_synonymous_field(field, model=DEFAULT_MODEL, app=DEFAULT_APP, score_cutoff=50, root_preference=1.02): """Use a dictionary of synonyms and fuzzy string matching to find a similarly named field Returns: A single model field name (string) Examples: >>> find_synonymous_field('date', mode...
python
def find_synonymous_field(field, model=DEFAULT_MODEL, app=DEFAULT_APP, score_cutoff=50, root_preference=1.02): """Use a dictionary of synonyms and fuzzy string matching to find a similarly named field Returns: A single model field name (string) Examples: >>> find_synonymous_field('date', mode...
[ "def", "find_synonymous_field", "(", "field", ",", "model", "=", "DEFAULT_MODEL", ",", "app", "=", "DEFAULT_APP", ",", "score_cutoff", "=", "50", ",", "root_preference", "=", "1.02", ")", ":", "fields", "=", "util", ".", "listify", "(", "field", ")", "+", ...
Use a dictionary of synonyms and fuzzy string matching to find a similarly named field Returns: A single model field name (string) Examples: >>> find_synonymous_field('date', model='WikiItem') 'end_date_time' >>> find_synonymous_field('date', model='WikiItem') 'date_time' ...
[ "Use", "a", "dictionary", "of", "synonyms", "and", "fuzzy", "string", "matching", "to", "find", "a", "similarly", "named", "field" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L763-L789
241,261
hobson/pug-dj
pug/dj/db.py
find_model
def find_model(model_name, apps=settings.INSTALLED_APPS, fuzziness=0): """Find model_name among indicated Django apps and return Model class Examples: To find models in an app called "miner": >>> find_model('WikiItem', 'miner') >>> find_model('Connection', 'miner') >>> find_mod...
python
def find_model(model_name, apps=settings.INSTALLED_APPS, fuzziness=0): """Find model_name among indicated Django apps and return Model class Examples: To find models in an app called "miner": >>> find_model('WikiItem', 'miner') >>> find_model('Connection', 'miner') >>> find_mod...
[ "def", "find_model", "(", "model_name", ",", "apps", "=", "settings", ".", "INSTALLED_APPS", ",", "fuzziness", "=", "0", ")", ":", "# if it looks like a file system path rather than django project.app.model path the return it as a string", "if", "'/'", "in", "model_name", "...
Find model_name among indicated Django apps and return Model class Examples: To find models in an app called "miner": >>> find_model('WikiItem', 'miner') >>> find_model('Connection', 'miner') >>> find_model('InvalidModelName')
[ "Find", "model_name", "among", "indicated", "Django", "apps", "and", "return", "Model", "class" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L792-L814
241,262
hobson/pug-dj
pug/dj/db.py
lagged_in_date
def lagged_in_date(x=None, y=None, filter_dict=None, model='WikiItem', app=DEFAULT_APP, sort=True, limit=30000, lag=1, pad=0, truncate=True): """ Lag the y values by the specified number of samples. FIXME: sort has no effect when sequences provided in x, y instead of field names >>> lagged_in_date(x=[...
python
def lagged_in_date(x=None, y=None, filter_dict=None, model='WikiItem', app=DEFAULT_APP, sort=True, limit=30000, lag=1, pad=0, truncate=True): """ Lag the y values by the specified number of samples. FIXME: sort has no effect when sequences provided in x, y instead of field names >>> lagged_in_date(x=[...
[ "def", "lagged_in_date", "(", "x", "=", "None", ",", "y", "=", "None", ",", "filter_dict", "=", "None", ",", "model", "=", "'WikiItem'", ",", "app", "=", "DEFAULT_APP", ",", "sort", "=", "True", ",", "limit", "=", "30000", ",", "lag", "=", "1", ","...
Lag the y values by the specified number of samples. FIXME: sort has no effect when sequences provided in x, y instead of field names >>> lagged_in_date(x=[.1,.2,.3,.4], y=[1,2,3,4], limit=4, lag=1) ([0.1, 0.2, 0.3, 0.4], [0, 1, 2, 3]) >>> lagged_in_date(x=[.1,.2,.3,.4], y=[1,2,3,4], lag=1, truncate=T...
[ "Lag", "the", "y", "values", "by", "the", "specified", "number", "of", "samples", "." ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L830-L861
241,263
hobson/pug-dj
pug/dj/db.py
django_object_from_row
def django_object_from_row(row, model, field_names=None, ignore_fields=('id', 'pk'), ignore_related=True, strip=True, ignore_errors=True, verbosity=0): """Construct Django model instance from values provided in a python dict or Mapping Args: row (list or dict): Data (values of any type) to be assigned to...
python
def django_object_from_row(row, model, field_names=None, ignore_fields=('id', 'pk'), ignore_related=True, strip=True, ignore_errors=True, verbosity=0): """Construct Django model instance from values provided in a python dict or Mapping Args: row (list or dict): Data (values of any type) to be assigned to...
[ "def", "django_object_from_row", "(", "row", ",", "model", ",", "field_names", "=", "None", ",", "ignore_fields", "=", "(", "'id'", ",", "'pk'", ")", ",", "ignore_related", "=", "True", ",", "strip", "=", "True", ",", "ignore_errors", "=", "True", ",", "...
Construct Django model instance from values provided in a python dict or Mapping Args: row (list or dict): Data (values of any type) to be assigned to fields in the Django object. If `row` is a list, then the column names (header row) can be provided in `field_names`. If `row` is a list and n...
[ "Construct", "Django", "model", "instance", "from", "values", "provided", "in", "a", "python", "dict", "or", "Mapping" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1343-L1370
241,264
hobson/pug-dj
pug/dj/db.py
count_lines
def count_lines(fname, mode='rU'): '''Count the number of lines in a file Only faster way would be to utilize multiple processor cores to perform parallel reads. http://stackoverflow.com/q/845058/623735 ''' with open(fname, mode) as f: for i, l in enumerate(f): pass return ...
python
def count_lines(fname, mode='rU'): '''Count the number of lines in a file Only faster way would be to utilize multiple processor cores to perform parallel reads. http://stackoverflow.com/q/845058/623735 ''' with open(fname, mode) as f: for i, l in enumerate(f): pass return ...
[ "def", "count_lines", "(", "fname", ",", "mode", "=", "'rU'", ")", ":", "with", "open", "(", "fname", ",", "mode", ")", "as", "f", ":", "for", "i", ",", "l", "in", "enumerate", "(", "f", ")", ":", "pass", "return", "i", "+", "1" ]
Count the number of lines in a file Only faster way would be to utilize multiple processor cores to perform parallel reads. http://stackoverflow.com/q/845058/623735
[ "Count", "the", "number", "of", "lines", "in", "a", "file" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1487-L1497
241,265
hobson/pug-dj
pug/dj/db.py
write_queryset_to_csv
def write_queryset_to_csv(qs, filename): """Write a QuerySet or ValuesListQuerySet to a CSV file based on djangosnippets by zbyte64 and http://palewi.re Arguments: qs (QuerySet or ValuesListQuerySet): The records your want to write to a text file (UTF-8) filename (str): full path and file ...
python
def write_queryset_to_csv(qs, filename): """Write a QuerySet or ValuesListQuerySet to a CSV file based on djangosnippets by zbyte64 and http://palewi.re Arguments: qs (QuerySet or ValuesListQuerySet): The records your want to write to a text file (UTF-8) filename (str): full path and file ...
[ "def", "write_queryset_to_csv", "(", "qs", ",", "filename", ")", ":", "model", "=", "qs", ".", "model", "with", "open", "(", "filename", ",", "'w'", ")", "as", "fp", ":", "writer", "=", "csv", ".", "writer", "(", "fp", ")", "try", ":", "headers", "...
Write a QuerySet or ValuesListQuerySet to a CSV file based on djangosnippets by zbyte64 and http://palewi.re Arguments: qs (QuerySet or ValuesListQuerySet): The records your want to write to a text file (UTF-8) filename (str): full path and file name to write to
[ "Write", "a", "QuerySet", "or", "ValuesListQuerySet", "to", "a", "CSV", "file" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1638-L1670
241,266
hobson/pug-dj
pug/dj/db.py
make_date
def make_date(dt, date_parser=parse_date): """Coerce a datetime or string into datetime.date object Arguments: dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date to be coerced into a `datetime.time` object Returns: datetime.time: Time of day portion of a `d...
python
def make_date(dt, date_parser=parse_date): """Coerce a datetime or string into datetime.date object Arguments: dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date to be coerced into a `datetime.time` object Returns: datetime.time: Time of day portion of a `d...
[ "def", "make_date", "(", "dt", ",", "date_parser", "=", "parse_date", ")", ":", "if", "not", "dt", ":", "return", "datetime", ".", "date", "(", "1970", ",", "1", ",", "1", ")", "if", "isinstance", "(", "dt", ",", "basestring", ")", ":", "dt", "=", ...
Coerce a datetime or string into datetime.date object Arguments: dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date to be coerced into a `datetime.time` object Returns: datetime.time: Time of day portion of a `datetime` string or object >>> make_date('') ...
[ "Coerce", "a", "datetime", "or", "string", "into", "datetime", ".", "date", "object" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1764-L1791
241,267
hobson/pug-dj
pug/dj/db.py
make_time
def make_time(dt, date_parser=parse_date): """Ignore date information in a datetime string or object Arguments: dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date to be coerced into a `datetime.time` object Returns: datetime.time: Time of day portion of a `...
python
def make_time(dt, date_parser=parse_date): """Ignore date information in a datetime string or object Arguments: dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date to be coerced into a `datetime.time` object Returns: datetime.time: Time of day portion of a `...
[ "def", "make_time", "(", "dt", ",", "date_parser", "=", "parse_date", ")", ":", "if", "not", "dt", ":", "return", "datetime", ".", "time", "(", "0", ",", "0", ")", "if", "isinstance", "(", "dt", ",", "basestring", ")", ":", "try", ":", "dt", "=", ...
Ignore date information in a datetime string or object Arguments: dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date to be coerced into a `datetime.time` object Returns: datetime.time: Time of day portion of a `datetime` string or object >>> make_time(None...
[ "Ignore", "date", "information", "in", "a", "datetime", "string", "or", "object" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1794-L1824
241,268
hobson/pug-dj
pug/dj/db.py
flatten_excel
def flatten_excel(path='.', ext='xlsx', sheetname=0, skiprows=None, header=0, date_parser=parse_date, verbosity=0, output_ext=None): """Load all Excel files in the given path, write .flat.csv files, return `DataFrame` dict Arguments: path (str): file or folder to retrieve CSV files and `pandas.DataFrame`...
python
def flatten_excel(path='.', ext='xlsx', sheetname=0, skiprows=None, header=0, date_parser=parse_date, verbosity=0, output_ext=None): """Load all Excel files in the given path, write .flat.csv files, return `DataFrame` dict Arguments: path (str): file or folder to retrieve CSV files and `pandas.DataFrame`...
[ "def", "flatten_excel", "(", "path", "=", "'.'", ",", "ext", "=", "'xlsx'", ",", "sheetname", "=", "0", ",", "skiprows", "=", "None", ",", "header", "=", "0", ",", "date_parser", "=", "parse_date", ",", "verbosity", "=", "0", ",", "output_ext", "=", ...
Load all Excel files in the given path, write .flat.csv files, return `DataFrame` dict Arguments: path (str): file or folder to retrieve CSV files and `pandas.DataFrame`s from ext (str): file name extension (to filter files by) date_parser (function): if the MultiIndex can be interpretted as a da...
[ "Load", "all", "Excel", "files", "in", "the", "given", "path", "write", ".", "flat", ".", "csv", "files", "return", "DataFrame", "dict" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1915-L1941
241,269
hobson/pug-dj
pug/dj/db.py
hash_model_values
def hash_model_values(model, clear=True, hash_field='values_hash', hash_fun=hash, ignore_pk=True, ignore_fields=[]): """Hash values of DB table records to facilitate tracking changes to the DB table Intended for comparing records in one table to those in another (with potentially differing id/pk values) Fo...
python
def hash_model_values(model, clear=True, hash_field='values_hash', hash_fun=hash, ignore_pk=True, ignore_fields=[]): """Hash values of DB table records to facilitate tracking changes to the DB table Intended for comparing records in one table to those in another (with potentially differing id/pk values) Fo...
[ "def", "hash_model_values", "(", "model", ",", "clear", "=", "True", ",", "hash_field", "=", "'values_hash'", ",", "hash_fun", "=", "hash", ",", "ignore_pk", "=", "True", ",", "ignore_fields", "=", "[", "]", ")", ":", "qs", "=", "getattr", "(", "model", ...
Hash values of DB table records to facilitate tracking changes to the DB table Intended for comparing records in one table to those in another (with potentially differing id/pk values) For example, changes to a table in a read-only MS SQL database can be quickly identified and mirrored to a writeable PostG...
[ "Hash", "values", "of", "DB", "table", "records", "to", "facilitate", "tracking", "changes", "to", "the", "DB", "table" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1982-L2000
241,270
hobson/pug-dj
pug/dj/db.py
bulk_update
def bulk_update(object_list, ignore_errors=False, delete_first=False, verbosity=0): '''Bulk_create objects in provided list of model instances, delete database rows for the original pks in the object list. Returns any delta in the number of rows in the database table that resulted from the update. If nonze...
python
def bulk_update(object_list, ignore_errors=False, delete_first=False, verbosity=0): '''Bulk_create objects in provided list of model instances, delete database rows for the original pks in the object list. Returns any delta in the number of rows in the database table that resulted from the update. If nonze...
[ "def", "bulk_update", "(", "object_list", ",", "ignore_errors", "=", "False", ",", "delete_first", "=", "False", ",", "verbosity", "=", "0", ")", ":", "if", "not", "object_list", ":", "return", "0", "model", "=", "object_list", "[", "0", "]", ".", "__cla...
Bulk_create objects in provided list of model instances, delete database rows for the original pks in the object list. Returns any delta in the number of rows in the database table that resulted from the update. If nonzero, an error has likely occurred and database integrity is suspect. # delete_first = T...
[ "Bulk_create", "objects", "in", "provided", "list", "of", "model", "instances", "delete", "database", "rows", "for", "the", "original", "pks", "in", "the", "object", "list", "." ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L2561-L2614
241,271
hobson/pug-dj
pug/dj/db.py
generate_queryset_batches
def generate_queryset_batches(queryset, batch_len=1000, verbosity=1): """Filter a queryset by the pk in such a way that no batch is larger than the requested batch_len SEE ALSO: pug.nlp.util.generate_slices >>> from miner.models import TestModel >>> sum(len(list(batch)) for batch in generate_queryset_...
python
def generate_queryset_batches(queryset, batch_len=1000, verbosity=1): """Filter a queryset by the pk in such a way that no batch is larger than the requested batch_len SEE ALSO: pug.nlp.util.generate_slices >>> from miner.models import TestModel >>> sum(len(list(batch)) for batch in generate_queryset_...
[ "def", "generate_queryset_batches", "(", "queryset", ",", "batch_len", "=", "1000", ",", "verbosity", "=", "1", ")", ":", "if", "batch_len", "==", "1", ":", "for", "obj", "in", "queryset", ":", "yield", "obj", "N", "=", "queryset", ".", "count", "(", "...
Filter a queryset by the pk in such a way that no batch is larger than the requested batch_len SEE ALSO: pug.nlp.util.generate_slices >>> from miner.models import TestModel >>> sum(len(list(batch)) for batch in generate_queryset_batches(TestModel, batch_len=7)) == TestModel.objects.count() True
[ "Filter", "a", "queryset", "by", "the", "pk", "in", "such", "a", "way", "that", "no", "batch", "is", "larger", "than", "the", "requested", "batch_len" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L2617-L2673
241,272
hobson/pug-dj
pug/dj/db.py
optimize_filter_dict
def optimize_filter_dict(filter_dict, trgm=True): """Improve query speed for a Django queryset `filter` or `exclude` kwargs dict WARNING: Wtthout `trgm`, this only improves the speed of exclude filters by 0.4% Arguments: filter_dict (dict): kwargs for Django ORM queryset `filter` and `exclude` quer...
python
def optimize_filter_dict(filter_dict, trgm=True): """Improve query speed for a Django queryset `filter` or `exclude` kwargs dict WARNING: Wtthout `trgm`, this only improves the speed of exclude filters by 0.4% Arguments: filter_dict (dict): kwargs for Django ORM queryset `filter` and `exclude` quer...
[ "def", "optimize_filter_dict", "(", "filter_dict", ",", "trgm", "=", "True", ")", ":", "optimized", "=", "{", "}", "for", "k", ",", "v", "in", "filter_dict", ".", "iteritems", "(", ")", ":", "if", "k", ".", "endswith", "(", "'__in'", ")", ":", "v", ...
Improve query speed for a Django queryset `filter` or `exclude` kwargs dict WARNING: Wtthout `trgm`, this only improves the speed of exclude filters by 0.4% Arguments: filter_dict (dict): kwargs for Django ORM queryset `filter` and `exclude` queries trgm (bool): whether to assume the Django ORM t...
[ "Improve", "query", "speed", "for", "a", "Django", "queryset", "filter", "or", "exclude", "kwargs", "dict" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L2739-L2778
241,273
hobson/pug-dj
pug/dj/db.py
dump_json
def dump_json(model, batch_len=200000, use_natural_keys=True, verbosity=1): """Dump database records to .json Django fixture file, one file for each batch of `batch_len` records Files are suitable for loading with "python manage.py loaddata folder_name_containing_files/*". """ model = get_model(model) ...
python
def dump_json(model, batch_len=200000, use_natural_keys=True, verbosity=1): """Dump database records to .json Django fixture file, one file for each batch of `batch_len` records Files are suitable for loading with "python manage.py loaddata folder_name_containing_files/*". """ model = get_model(model) ...
[ "def", "dump_json", "(", "model", ",", "batch_len", "=", "200000", ",", "use_natural_keys", "=", "True", ",", "verbosity", "=", "1", ")", ":", "model", "=", "get_model", "(", "model", ")", "N", "=", "model", ".", "objects", ".", "count", "(", ")", "i...
Dump database records to .json Django fixture file, one file for each batch of `batch_len` records Files are suitable for loading with "python manage.py loaddata folder_name_containing_files/*".
[ "Dump", "database", "records", "to", ".", "json", "Django", "fixture", "file", "one", "file", "for", "each", "batch", "of", "batch_len", "records" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L2822-L2846
241,274
hobson/pug-dj
pug/dj/db.py
filter_exclude_dicts
def filter_exclude_dicts(filter_dict=None, exclude_dict=None, name='acctno', values=[], swap=False): """Produces kwargs dicts for Django Queryset `filter` and `exclude` from a list of values The last, critical step in generating Django ORM kwargs dicts from a natural language query. Properly parses "NOT" u...
python
def filter_exclude_dicts(filter_dict=None, exclude_dict=None, name='acctno', values=[], swap=False): """Produces kwargs dicts for Django Queryset `filter` and `exclude` from a list of values The last, critical step in generating Django ORM kwargs dicts from a natural language query. Properly parses "NOT" u...
[ "def", "filter_exclude_dicts", "(", "filter_dict", "=", "None", ",", "exclude_dict", "=", "None", ",", "name", "=", "'acctno'", ",", "values", "=", "[", "]", ",", "swap", "=", "False", ")", ":", "filter_dict", "=", "filter_dict", "or", "{", "}", "exclude...
Produces kwargs dicts for Django Queryset `filter` and `exclude` from a list of values The last, critical step in generating Django ORM kwargs dicts from a natural language query. Properly parses "NOT" unary operators on each field value in the list. Assumes the lists have been pre-processed to consolidate...
[ "Produces", "kwargs", "dicts", "for", "Django", "Queryset", "filter", "and", "exclude", "from", "a", "list", "of", "values" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L2849-L2876
241,275
hobson/pug-dj
pug/dj/db.py
Columns.process_kwargs
def process_kwargs(self, kwargs, prefix='default_', delete=True): """ set self attributes based on kwargs, optionally deleting kwargs that are processed """ processed = [] for k in kwargs: if hasattr(self, prefix + k): processed += [k] ...
python
def process_kwargs(self, kwargs, prefix='default_', delete=True): """ set self attributes based on kwargs, optionally deleting kwargs that are processed """ processed = [] for k in kwargs: if hasattr(self, prefix + k): processed += [k] ...
[ "def", "process_kwargs", "(", "self", ",", "kwargs", ",", "prefix", "=", "'default_'", ",", "delete", "=", "True", ")", ":", "processed", "=", "[", "]", "for", "k", "in", "kwargs", ":", "if", "hasattr", "(", "self", ",", "prefix", "+", "k", ")", ":...
set self attributes based on kwargs, optionally deleting kwargs that are processed
[ "set", "self", "attributes", "based", "on", "kwargs", "optionally", "deleting", "kwargs", "that", "are", "processed" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1105-L1116
241,276
hobson/pug-dj
pug/dj/db.py
Columns.as_column_wise_lists
def as_column_wise_lists(self, transpose=False): """Generator over the columns of lists""" # make this a generator of generators? if transpose: ans = self.from_row_wise_lists(self.as_column_wise_lists(transpose=False)) return ans #print self return self.va...
python
def as_column_wise_lists(self, transpose=False): """Generator over the columns of lists""" # make this a generator of generators? if transpose: ans = self.from_row_wise_lists(self.as_column_wise_lists(transpose=False)) return ans #print self return self.va...
[ "def", "as_column_wise_lists", "(", "self", ",", "transpose", "=", "False", ")", ":", "# make this a generator of generators?", "if", "transpose", ":", "ans", "=", "self", ".", "from_row_wise_lists", "(", "self", ".", "as_column_wise_lists", "(", "transpose", "=", ...
Generator over the columns of lists
[ "Generator", "over", "the", "columns", "of", "lists" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1257-L1264
241,277
AliGhahraei/verarandom
verarandom/_random_generator.py
VeraRandom.randint
def randint(self, a: int, b: int, n: Optional[int] = None) -> Union[List[int], int]: """ Generate n numbers as a list or a single one if no n is given. n is used to minimize the number of requests made and return type changes to be compatible with :py:mod:`random`'s interface """ ...
python
def randint(self, a: int, b: int, n: Optional[int] = None) -> Union[List[int], int]: """ Generate n numbers as a list or a single one if no n is given. n is used to minimize the number of requests made and return type changes to be compatible with :py:mod:`random`'s interface """ ...
[ "def", "randint", "(", "self", ",", "a", ":", "int", ",", "b", ":", "int", ",", "n", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "Union", "[", "List", "[", "int", "]", ",", "int", "]", ":", "max_n", "=", "self", ".", "config", ...
Generate n numbers as a list or a single one if no n is given. n is used to minimize the number of requests made and return type changes to be compatible with :py:mod:`random`'s interface
[ "Generate", "n", "numbers", "as", "a", "list", "or", "a", "single", "one", "if", "no", "n", "is", "given", "." ]
63d9a5bd2776e40368933f54e58c3f4b4f333f03
https://github.com/AliGhahraei/verarandom/blob/63d9a5bd2776e40368933f54e58c3f4b4f333f03/verarandom/_random_generator.py#L69-L76
241,278
AliGhahraei/verarandom
verarandom/_random_generator.py
VeraRandomQuota._check_quota
def _check_quota(self): """ If IP can't make requests, raise BitQuotaExceeded. Called before generating numbers. """ self._request_remaining_quota_if_unset() if self.quota_estimate < self.quota_limit: raise BitQuotaExceeded(self.quota_estimate)
python
def _check_quota(self): """ If IP can't make requests, raise BitQuotaExceeded. Called before generating numbers. """ self._request_remaining_quota_if_unset() if self.quota_estimate < self.quota_limit: raise BitQuotaExceeded(self.quota_estimate)
[ "def", "_check_quota", "(", "self", ")", ":", "self", ".", "_request_remaining_quota_if_unset", "(", ")", "if", "self", ".", "quota_estimate", "<", "self", ".", "quota_limit", ":", "raise", "BitQuotaExceeded", "(", "self", ".", "quota_estimate", ")" ]
If IP can't make requests, raise BitQuotaExceeded. Called before generating numbers.
[ "If", "IP", "can", "t", "make", "requests", "raise", "BitQuotaExceeded", ".", "Called", "before", "generating", "numbers", "." ]
63d9a5bd2776e40368933f54e58c3f4b4f333f03
https://github.com/AliGhahraei/verarandom/blob/63d9a5bd2776e40368933f54e58c3f4b4f333f03/verarandom/_random_generator.py#L171-L175
241,279
musicmetric/mmpy
src/entity.py
Entity._construct_timeseries
def _construct_timeseries(self, timeseries, constraints={}): """ wraps response_from for timeseries calls, returns the resulting dict """ self.response_from(timeseries, constraints) if self.response == None: return None return {'data':self.response['data'], ...
python
def _construct_timeseries(self, timeseries, constraints={}): """ wraps response_from for timeseries calls, returns the resulting dict """ self.response_from(timeseries, constraints) if self.response == None: return None return {'data':self.response['data'], ...
[ "def", "_construct_timeseries", "(", "self", ",", "timeseries", ",", "constraints", "=", "{", "}", ")", ":", "self", ".", "response_from", "(", "timeseries", ",", "constraints", ")", "if", "self", ".", "response", "==", "None", ":", "return", "None", "retu...
wraps response_from for timeseries calls, returns the resulting dict
[ "wraps", "response_from", "for", "timeseries", "calls", "returns", "the", "resulting", "dict" ]
2b5d975c61f9ea8c7f19f76a90b59771833ef881
https://github.com/musicmetric/mmpy/blob/2b5d975c61f9ea8c7f19f76a90b59771833ef881/src/entity.py#L58-L68
241,280
shreyaspotnis/rampage
rampage/widgets/ChannelWidgets.py
QChannelInfoBox.edit_channel_info
def edit_channel_info(self, new_ch_name, ch_dct): """Parent widget calls this whenever the user edits channel info. """ self.ch_name = new_ch_name self.dct = ch_dct if ch_dct['type'] == 'analog': fmter = fmt.green else: fmter = fmt.blue sel...
python
def edit_channel_info(self, new_ch_name, ch_dct): """Parent widget calls this whenever the user edits channel info. """ self.ch_name = new_ch_name self.dct = ch_dct if ch_dct['type'] == 'analog': fmter = fmt.green else: fmter = fmt.blue sel...
[ "def", "edit_channel_info", "(", "self", ",", "new_ch_name", ",", "ch_dct", ")", ":", "self", ".", "ch_name", "=", "new_ch_name", "self", ".", "dct", "=", "ch_dct", "if", "ch_dct", "[", "'type'", "]", "==", "'analog'", ":", "fmter", "=", "fmt", ".", "g...
Parent widget calls this whenever the user edits channel info.
[ "Parent", "widget", "calls", "this", "whenever", "the", "user", "edits", "channel", "info", "." ]
e2565aef7ee16ee06523de975e8aa41aca14e3b2
https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/widgets/ChannelWidgets.py#L135-L145
241,281
hobson/pug-dj
pug/dj/miner/views.py
connections
def connections(request, edges): """ Plot a force-directed graph based on the edges provided """ edge_list, node_list = parse.graph_definition(edges) data = {'nodes': json.dumps(node_list), 'edges': json.dumps(edge_list)} return render_to_response('miner/connections.html', data)
python
def connections(request, edges): """ Plot a force-directed graph based on the edges provided """ edge_list, node_list = parse.graph_definition(edges) data = {'nodes': json.dumps(node_list), 'edges': json.dumps(edge_list)} return render_to_response('miner/connections.html', data)
[ "def", "connections", "(", "request", ",", "edges", ")", ":", "edge_list", ",", "node_list", "=", "parse", ".", "graph_definition", "(", "edges", ")", "data", "=", "{", "'nodes'", ":", "json", ".", "dumps", "(", "node_list", ")", ",", "'edges'", ":", "...
Plot a force-directed graph based on the edges provided
[ "Plot", "a", "force", "-", "directed", "graph", "based", "on", "the", "edges", "provided" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/miner/views.py#L56-L62
241,282
hobson/pug-dj
pug/dj/miner/views.py
csv_response_from_context
def csv_response_from_context(context=None, filename=None, field_names=None, null_string='', eval_python=True): """Generate the response for a Download CSV button from data within the context dict The CSV data must be in one of these places/formats: * context as a list of lists of python values (strings f...
python
def csv_response_from_context(context=None, filename=None, field_names=None, null_string='', eval_python=True): """Generate the response for a Download CSV button from data within the context dict The CSV data must be in one of these places/formats: * context as a list of lists of python values (strings f...
[ "def", "csv_response_from_context", "(", "context", "=", "None", ",", "filename", "=", "None", ",", "field_names", "=", "None", ",", "null_string", "=", "''", ",", "eval_python", "=", "True", ")", ":", "filename", "=", "filename", "or", "context", ".", "ge...
Generate the response for a Download CSV button from data within the context dict The CSV data must be in one of these places/formats: * context as a list of lists of python values (strings for headers in first list) * context['data']['d3data'] as a string in json format (python) for a list of lists of re...
[ "Generate", "the", "response", "for", "a", "Download", "CSV", "button", "from", "data", "within", "the", "context", "dict" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/miner/views.py#L541-L592
241,283
hobson/pug-dj
pug/dj/miner/views.py
JSONView.render_to_response
def render_to_response(self, context, indent=None): "Returns a JSON response containing 'context' as payload" return self.get_json_response(self.convert_context_to_json(context, indent=indent))
python
def render_to_response(self, context, indent=None): "Returns a JSON response containing 'context' as payload" return self.get_json_response(self.convert_context_to_json(context, indent=indent))
[ "def", "render_to_response", "(", "self", ",", "context", ",", "indent", "=", "None", ")", ":", "return", "self", ".", "get_json_response", "(", "self", ".", "convert_context_to_json", "(", "context", ",", "indent", "=", "indent", ")", ")" ]
Returns a JSON response containing 'context' as payload
[ "Returns", "a", "JSON", "response", "containing", "context", "as", "payload" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/miner/views.py#L126-L128
241,284
pavelsof/ipalint
ipalint/strnorm.py
Normaliser.report
def report(self, reporter, ignore_nfd=False, ignore_ws=False): """ Adds the problems that have been found so far to the given Reporter instance. The two keyword args can be used to restrict the error types to be reported. """ if self.strip_errors and not ignore_ws: reporter.add(self.strip_errors, 'leadin...
python
def report(self, reporter, ignore_nfd=False, ignore_ws=False): """ Adds the problems that have been found so far to the given Reporter instance. The two keyword args can be used to restrict the error types to be reported. """ if self.strip_errors and not ignore_ws: reporter.add(self.strip_errors, 'leadin...
[ "def", "report", "(", "self", ",", "reporter", ",", "ignore_nfd", "=", "False", ",", "ignore_ws", "=", "False", ")", ":", "if", "self", ".", "strip_errors", "and", "not", "ignore_ws", ":", "reporter", ".", "add", "(", "self", ".", "strip_errors", ",", ...
Adds the problems that have been found so far to the given Reporter instance. The two keyword args can be used to restrict the error types to be reported.
[ "Adds", "the", "problems", "that", "have", "been", "found", "so", "far", "to", "the", "given", "Reporter", "instance", ".", "The", "two", "keyword", "args", "can", "be", "used", "to", "restrict", "the", "error", "types", "to", "be", "reported", "." ]
763e5979ede6980cbfc746b06fd007b379762eeb
https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/strnorm.py#L63-L73
241,285
peepall/FancyLogger
FancyLogger/processing/__init__.py
MultiprocessingLogger.run
def run(self): """ The main loop for the logger process. Will receive remote processes orders one by one and wait for the next one. Then return from this method when the main application calls for exit, which is a regular command. """ # Initialize the file logger self.log...
python
def run(self): """ The main loop for the logger process. Will receive remote processes orders one by one and wait for the next one. Then return from this method when the main application calls for exit, which is a regular command. """ # Initialize the file logger self.log...
[ "def", "run", "(", "self", ")", ":", "# Initialize the file logger", "self", ".", "log", "=", "getLogger", "(", ")", "# Deserialize configuration", "self", ".", "set_config_command", "=", "dill", ".", "loads", "(", "self", ".", "set_config_command", ")", "self",...
The main loop for the logger process. Will receive remote processes orders one by one and wait for the next one. Then return from this method when the main application calls for exit, which is a regular command.
[ "The", "main", "loop", "for", "the", "logger", "process", ".", "Will", "receive", "remote", "processes", "orders", "one", "by", "one", "and", "wait", "for", "the", "next", "one", ".", "Then", "return", "from", "this", "method", "when", "the", "main", "ap...
7f13f1397e76ed768fb6b6358194118831fafc6d
https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/processing/__init__.py#L225-L283
241,286
peepall/FancyLogger
FancyLogger/processing/__init__.py
MultiprocessingLogger.redraw
def redraw(self): """ Clears the console and performs a complete redraw of all progress bars and then awaiting logger messages if the minimum time elapsed since the last redraw is enough. """ # Check if the refresh time lapse has elapsed and if a change requires to redraw ...
python
def redraw(self): """ Clears the console and performs a complete redraw of all progress bars and then awaiting logger messages if the minimum time elapsed since the last redraw is enough. """ # Check if the refresh time lapse has elapsed and if a change requires to redraw ...
[ "def", "redraw", "(", "self", ")", ":", "# Check if the refresh time lapse has elapsed and if a change requires to redraw", "lapse_since_last_refresh", "=", "millis", "(", ")", "-", "self", ".", "refresh_timer", "if", "not", "lapse_since_last_refresh", ">", "self", ".", "...
Clears the console and performs a complete redraw of all progress bars and then awaiting logger messages if the minimum time elapsed since the last redraw is enough.
[ "Clears", "the", "console", "and", "performs", "a", "complete", "redraw", "of", "all", "progress", "bars", "and", "then", "awaiting", "logger", "messages", "if", "the", "minimum", "time", "elapsed", "since", "the", "last", "redraw", "is", "enough", "." ]
7f13f1397e76ed768fb6b6358194118831fafc6d
https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/processing/__init__.py#L386-L455
241,287
esterhui/pypu
pypu/servicemanager.py
servicemanager.GetServices
def GetServices(self,filename): """Returns a list of service objects handling this file type""" objlist=[] for sobj in self.services: if sobj.KnowsFile(filename) : objlist.append(sobj) if len(objlist)==0: return None return objlist
python
def GetServices(self,filename): """Returns a list of service objects handling this file type""" objlist=[] for sobj in self.services: if sobj.KnowsFile(filename) : objlist.append(sobj) if len(objlist)==0: return None return objlist
[ "def", "GetServices", "(", "self", ",", "filename", ")", ":", "objlist", "=", "[", "]", "for", "sobj", "in", "self", ".", "services", ":", "if", "sobj", ".", "KnowsFile", "(", "filename", ")", ":", "objlist", ".", "append", "(", "sobj", ")", "if", ...
Returns a list of service objects handling this file type
[ "Returns", "a", "list", "of", "service", "objects", "handling", "this", "file", "type" ]
cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/servicemanager.py#L13-L23
241,288
esterhui/pypu
pypu/servicemanager.py
servicemanager.GetServiceObj
def GetServiceObj(self,servicename): """Given a service name string, returns the object that corresponds to the service""" for sobj in self.services: if sobj.GetName().lower()==servicename.lower(): return sobj return None
python
def GetServiceObj(self,servicename): """Given a service name string, returns the object that corresponds to the service""" for sobj in self.services: if sobj.GetName().lower()==servicename.lower(): return sobj return None
[ "def", "GetServiceObj", "(", "self", ",", "servicename", ")", ":", "for", "sobj", "in", "self", ".", "services", ":", "if", "sobj", ".", "GetName", "(", ")", ".", "lower", "(", ")", "==", "servicename", ".", "lower", "(", ")", ":", "return", "sobj", ...
Given a service name string, returns the object that corresponds to the service
[ "Given", "a", "service", "name", "string", "returns", "the", "object", "that", "corresponds", "to", "the", "service" ]
cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/servicemanager.py#L25-L32
241,289
fictorial/filesysdb
filesysdb/__init__.py
object_path
def object_path(collection, id): """Returns path to the backing file of the object with the given ``id`` in the given ``collection``. Note that the ``id`` is made filesystem-safe by "normalizing" its string representation.""" _logger.debug(type(id)) _logger.debug(id) if isinstance(id, dict) ...
python
def object_path(collection, id): """Returns path to the backing file of the object with the given ``id`` in the given ``collection``. Note that the ``id`` is made filesystem-safe by "normalizing" its string representation.""" _logger.debug(type(id)) _logger.debug(id) if isinstance(id, dict) ...
[ "def", "object_path", "(", "collection", ",", "id", ")", ":", "_logger", ".", "debug", "(", "type", "(", "id", ")", ")", "_logger", ".", "debug", "(", "id", ")", "if", "isinstance", "(", "id", ",", "dict", ")", "and", "'id'", "in", "id", ":", "id...
Returns path to the backing file of the object with the given ``id`` in the given ``collection``. Note that the ``id`` is made filesystem-safe by "normalizing" its string representation.
[ "Returns", "path", "to", "the", "backing", "file", "of", "the", "object", "with", "the", "given", "id", "in", "the", "given", "collection", ".", "Note", "that", "the", "id", "is", "made", "filesystem", "-", "safe", "by", "normalizing", "its", "string", "...
bbf1e32218b71c7c15c33ada660433fffc6fa6ab
https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L49-L60
241,290
fictorial/filesysdb
filesysdb/__init__.py
load_object_at_path
def load_object_at_path(path): """Load an object from disk at explicit path""" with open(path, 'r') as f: data = _deserialize(f.read()) return aadict(data)
python
def load_object_at_path(path): """Load an object from disk at explicit path""" with open(path, 'r') as f: data = _deserialize(f.read()) return aadict(data)
[ "def", "load_object_at_path", "(", "path", ")", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "f", ":", "data", "=", "_deserialize", "(", "f", ".", "read", "(", ")", ")", "return", "aadict", "(", "data", ")" ]
Load an object from disk at explicit path
[ "Load", "an", "object", "from", "disk", "at", "explicit", "path" ]
bbf1e32218b71c7c15c33ada660433fffc6fa6ab
https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L68-L72
241,291
fictorial/filesysdb
filesysdb/__init__.py
add_collection
def add_collection(collection, cache_size=1000, cache_cls=LRUCache, **cache_args): """Add a collection named ``collection``.""" assert collection not in _db cache = cache_cls(maxsize=cache_size, missing=lambda id: load_object(col...
python
def add_collection(collection, cache_size=1000, cache_cls=LRUCache, **cache_args): """Add a collection named ``collection``.""" assert collection not in _db cache = cache_cls(maxsize=cache_size, missing=lambda id: load_object(col...
[ "def", "add_collection", "(", "collection", ",", "cache_size", "=", "1000", ",", "cache_cls", "=", "LRUCache", ",", "*", "*", "cache_args", ")", ":", "assert", "collection", "not", "in", "_db", "cache", "=", "cache_cls", "(", "maxsize", "=", "cache_size", ...
Add a collection named ``collection``.
[ "Add", "a", "collection", "named", "collection", "." ]
bbf1e32218b71c7c15c33ada660433fffc6fa6ab
https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L87-L96
241,292
fictorial/filesysdb
filesysdb/__init__.py
prepare
def prepare(base_path='data', serialize=json.dumps, deserialize=json.loads, file_ext='json'): """After you have added your collections, prepare the database for use.""" global _basepath, _deserialize, _serialize, _ext _basepath = base_path assert callable(serializ...
python
def prepare(base_path='data', serialize=json.dumps, deserialize=json.loads, file_ext='json'): """After you have added your collections, prepare the database for use.""" global _basepath, _deserialize, _serialize, _ext _basepath = base_path assert callable(serializ...
[ "def", "prepare", "(", "base_path", "=", "'data'", ",", "serialize", "=", "json", ".", "dumps", ",", "deserialize", "=", "json", ".", "loads", ",", "file_ext", "=", "'json'", ")", ":", "global", "_basepath", ",", "_deserialize", ",", "_serialize", ",", "...
After you have added your collections, prepare the database for use.
[ "After", "you", "have", "added", "your", "collections", "prepare", "the", "database", "for", "use", "." ]
bbf1e32218b71c7c15c33ada660433fffc6fa6ab
https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L103-L123
241,293
fictorial/filesysdb
filesysdb/__init__.py
each_object
def each_object(collection): """Yields each object in the given ``collection``. The objects are loaded from cache and failing that, from disk.""" c_path = collection_path(collection) paths = glob('%s/*.%s' % (c_path, _ext)) for path in paths: yield load_object_at_path(path)
python
def each_object(collection): """Yields each object in the given ``collection``. The objects are loaded from cache and failing that, from disk.""" c_path = collection_path(collection) paths = glob('%s/*.%s' % (c_path, _ext)) for path in paths: yield load_object_at_path(path)
[ "def", "each_object", "(", "collection", ")", ":", "c_path", "=", "collection_path", "(", "collection", ")", "paths", "=", "glob", "(", "'%s/*.%s'", "%", "(", "c_path", ",", "_ext", ")", ")", "for", "path", "in", "paths", ":", "yield", "load_object_at_path...
Yields each object in the given ``collection``. The objects are loaded from cache and failing that, from disk.
[ "Yields", "each", "object", "in", "the", "given", "collection", ".", "The", "objects", "are", "loaded", "from", "cache", "and", "failing", "that", "from", "disk", "." ]
bbf1e32218b71c7c15c33ada660433fffc6fa6ab
https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L131-L138
241,294
fictorial/filesysdb
filesysdb/__init__.py
each_object_id
def each_object_id(collection): """Yields each object ID in the given ``collection``. The objects are not loaded.""" c_path = collection_path(collection) paths = glob('%s/*.%s' % (c_path, _ext)) for path in paths: match = regex.match(r'.+/(.+)\.%s$' % _ext, path) yield match.groups()...
python
def each_object_id(collection): """Yields each object ID in the given ``collection``. The objects are not loaded.""" c_path = collection_path(collection) paths = glob('%s/*.%s' % (c_path, _ext)) for path in paths: match = regex.match(r'.+/(.+)\.%s$' % _ext, path) yield match.groups()...
[ "def", "each_object_id", "(", "collection", ")", ":", "c_path", "=", "collection_path", "(", "collection", ")", "paths", "=", "glob", "(", "'%s/*.%s'", "%", "(", "c_path", ",", "_ext", ")", ")", "for", "path", "in", "paths", ":", "match", "=", "regex", ...
Yields each object ID in the given ``collection``. The objects are not loaded.
[ "Yields", "each", "object", "ID", "in", "the", "given", "collection", ".", "The", "objects", "are", "not", "loaded", "." ]
bbf1e32218b71c7c15c33ada660433fffc6fa6ab
https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L141-L148
241,295
fictorial/filesysdb
filesysdb/__init__.py
save_object
def save_object(collection, obj): """Save an object ``obj`` to the given ``collection``. ``obj.id`` must be unique across all other existing objects in the given collection. If ``id`` is not present in the object, a *UUID* is assigned as the object's ``id``. Indexes already defined on the ``colle...
python
def save_object(collection, obj): """Save an object ``obj`` to the given ``collection``. ``obj.id`` must be unique across all other existing objects in the given collection. If ``id`` is not present in the object, a *UUID* is assigned as the object's ``id``. Indexes already defined on the ``colle...
[ "def", "save_object", "(", "collection", ",", "obj", ")", ":", "if", "'id'", "not", "in", "obj", ":", "obj", ".", "id", "=", "uuid", "(", ")", "id", "=", "obj", ".", "id", "path", "=", "object_path", "(", "collection", ",", "id", ")", "temp_path", ...
Save an object ``obj`` to the given ``collection``. ``obj.id`` must be unique across all other existing objects in the given collection. If ``id`` is not present in the object, a *UUID* is assigned as the object's ``id``. Indexes already defined on the ``collection`` are updated after the object ...
[ "Save", "an", "object", "obj", "to", "the", "given", "collection", "." ]
bbf1e32218b71c7c15c33ada660433fffc6fa6ab
https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L152-L176
241,296
fictorial/filesysdb
filesysdb/__init__.py
add_index
def add_index(collection, name, fields, transformer=None, unique=False, case_insensitive=False): """ Add a secondary index for a collection ``collection`` on one or more ``fields``. The values at each of the ``fields`` are loaded fro...
python
def add_index(collection, name, fields, transformer=None, unique=False, case_insensitive=False): """ Add a secondary index for a collection ``collection`` on one or more ``fields``. The values at each of the ``fields`` are loaded fro...
[ "def", "add_index", "(", "collection", ",", "name", ",", "fields", ",", "transformer", "=", "None", ",", "unique", "=", "False", ",", "case_insensitive", "=", "False", ")", ":", "assert", "len", "(", "name", ")", ">", "0", "assert", "len", "(", "fields...
Add a secondary index for a collection ``collection`` on one or more ``fields``. The values at each of the ``fields`` are loaded from existing objects and their object ids added to the index. You can later iterate the objects of an index via ``each_indexed_object``. If you update an object an...
[ "Add", "a", "secondary", "index", "for", "a", "collection", "collection", "on", "one", "or", "more", "fields", "." ]
bbf1e32218b71c7c15c33ada660433fffc6fa6ab
https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L198-L247
241,297
fictorial/filesysdb
filesysdb/__init__.py
_add_to_index
def _add_to_index(index, obj): """Adds the given object ``obj`` to the given ``index``""" id_set = index.value_map.setdefault(indexed_value(index, obj), set()) if index.unique: if len(id_set) > 0: raise UniqueConstraintError() id_set.add(obj.id)
python
def _add_to_index(index, obj): """Adds the given object ``obj`` to the given ``index``""" id_set = index.value_map.setdefault(indexed_value(index, obj), set()) if index.unique: if len(id_set) > 0: raise UniqueConstraintError() id_set.add(obj.id)
[ "def", "_add_to_index", "(", "index", ",", "obj", ")", ":", "id_set", "=", "index", ".", "value_map", ".", "setdefault", "(", "indexed_value", "(", "index", ",", "obj", ")", ",", "set", "(", ")", ")", "if", "index", ".", "unique", ":", "if", "len", ...
Adds the given object ``obj`` to the given ``index``
[ "Adds", "the", "given", "object", "obj", "to", "the", "given", "index" ]
bbf1e32218b71c7c15c33ada660433fffc6fa6ab
https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L250-L256
241,298
fictorial/filesysdb
filesysdb/__init__.py
_remove_from_index
def _remove_from_index(index, obj): """Removes object ``obj`` from the ``index``.""" try: index.value_map[indexed_value(index, obj)].remove(obj.id) except KeyError: pass
python
def _remove_from_index(index, obj): """Removes object ``obj`` from the ``index``.""" try: index.value_map[indexed_value(index, obj)].remove(obj.id) except KeyError: pass
[ "def", "_remove_from_index", "(", "index", ",", "obj", ")", ":", "try", ":", "index", ".", "value_map", "[", "indexed_value", "(", "index", ",", "obj", ")", "]", ".", "remove", "(", "obj", ".", "id", ")", "except", "KeyError", ":", "pass" ]
Removes object ``obj`` from the ``index``.
[ "Removes", "object", "obj", "from", "the", "index", "." ]
bbf1e32218b71c7c15c33ada660433fffc6fa6ab
https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L259-L264
241,299
fictorial/filesysdb
filesysdb/__init__.py
each_indexed_object
def each_indexed_object(collection, index_name, **where): """Yields each object indexed by the index with name ``name`` with ``values`` matching on indexed field values.""" index = _db[collection].indexes[index_name] for id in index.value_map.get(indexed_value(index, where), []): yield get_o...
python
def each_indexed_object(collection, index_name, **where): """Yields each object indexed by the index with name ``name`` with ``values`` matching on indexed field values.""" index = _db[collection].indexes[index_name] for id in index.value_map.get(indexed_value(index, where), []): yield get_o...
[ "def", "each_indexed_object", "(", "collection", ",", "index_name", ",", "*", "*", "where", ")", ":", "index", "=", "_db", "[", "collection", "]", ".", "indexes", "[", "index_name", "]", "for", "id", "in", "index", ".", "value_map", ".", "get", "(", "i...
Yields each object indexed by the index with name ``name`` with ``values`` matching on indexed field values.
[ "Yields", "each", "object", "indexed", "by", "the", "index", "with", "name", "name", "with", "values", "matching", "on", "indexed", "field", "values", "." ]
bbf1e32218b71c7c15c33ada660433fffc6fa6ab
https://github.com/fictorial/filesysdb/blob/bbf1e32218b71c7c15c33ada660433fffc6fa6ab/filesysdb/__init__.py#L267-L273