id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
247,300
sternoru/goscalecms
goscale/views.py
signup
def signup(request, **kwargs): """ Overrides allauth.account.views.signup """ if not ALLAUTH: return http.HttpResponse(_('allauth not installed...')) if request.method == "POST" and 'login' in request.POST: form_class = LoginForm form = form_class(request.POST) redirect_field_name = "next" success_url = get_default_redirect(request, redirect_field_name) if form.is_valid(): return form.login(request, redirect_url=success_url) response = allauth_signup(request, **kwargs) return response
python
def signup(request, **kwargs): """ Overrides allauth.account.views.signup """ if not ALLAUTH: return http.HttpResponse(_('allauth not installed...')) if request.method == "POST" and 'login' in request.POST: form_class = LoginForm form = form_class(request.POST) redirect_field_name = "next" success_url = get_default_redirect(request, redirect_field_name) if form.is_valid(): return form.login(request, redirect_url=success_url) response = allauth_signup(request, **kwargs) return response
[ "def", "signup", "(", "request", ",", "*", "*", "kwargs", ")", ":", "if", "not", "ALLAUTH", ":", "return", "http", ".", "HttpResponse", "(", "_", "(", "'allauth not installed...'", ")", ")", "if", "request", ".", "method", "==", "\"POST\"", "and", "'login'", "in", "request", ".", "POST", ":", "form_class", "=", "LoginForm", "form", "=", "form_class", "(", "request", ".", "POST", ")", "redirect_field_name", "=", "\"next\"", "success_url", "=", "get_default_redirect", "(", "request", ",", "redirect_field_name", ")", "if", "form", ".", "is_valid", "(", ")", ":", "return", "form", ".", "login", "(", "request", ",", "redirect_url", "=", "success_url", ")", "response", "=", "allauth_signup", "(", "request", ",", "*", "*", "kwargs", ")", "return", "response" ]
Overrides allauth.account.views.signup
[ "Overrides", "allauth", ".", "account", ".", "views", ".", "signup" ]
7eee50357c47ebdfe3e573a8b4be3b67892d229e
https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/views.py#L38-L52
247,301
kubernauts/pyk
pyk/toolkit.py
KubeHTTPClient.execute_operation
def execute_operation(self, method="GET", ops_path="", payload=""): """ Executes a Kubernetes operation using the specified method against a path. This is part of the low-level API. :Parameters: - `method`: The HTTP method to use, defaults to `GET` - `ops_path`: The path of the operation, for example, `/api/v1/events` which would result in an overall: `GET http://localhost:8080/api/v1/events` - `payload`: The optional payload which is relevant for `POST` or `PUT` methods only """ operation_path_URL = "".join([self.api_server, ops_path]) logging.debug("%s %s" %(method, operation_path_URL)) if payload == "": res = requests.request(method, operation_path_URL) else: logging.debug("PAYLOAD:\n%s" %(payload)) res = requests.request(method, operation_path_URL, data=payload) logging.debug("RESPONSE:\n%s" %(res.json())) return res
python
def execute_operation(self, method="GET", ops_path="", payload=""): """ Executes a Kubernetes operation using the specified method against a path. This is part of the low-level API. :Parameters: - `method`: The HTTP method to use, defaults to `GET` - `ops_path`: The path of the operation, for example, `/api/v1/events` which would result in an overall: `GET http://localhost:8080/api/v1/events` - `payload`: The optional payload which is relevant for `POST` or `PUT` methods only """ operation_path_URL = "".join([self.api_server, ops_path]) logging.debug("%s %s" %(method, operation_path_URL)) if payload == "": res = requests.request(method, operation_path_URL) else: logging.debug("PAYLOAD:\n%s" %(payload)) res = requests.request(method, operation_path_URL, data=payload) logging.debug("RESPONSE:\n%s" %(res.json())) return res
[ "def", "execute_operation", "(", "self", ",", "method", "=", "\"GET\"", ",", "ops_path", "=", "\"\"", ",", "payload", "=", "\"\"", ")", ":", "operation_path_URL", "=", "\"\"", ".", "join", "(", "[", "self", ".", "api_server", ",", "ops_path", "]", ")", "logging", ".", "debug", "(", "\"%s %s\"", "%", "(", "method", ",", "operation_path_URL", ")", ")", "if", "payload", "==", "\"\"", ":", "res", "=", "requests", ".", "request", "(", "method", ",", "operation_path_URL", ")", "else", ":", "logging", ".", "debug", "(", "\"PAYLOAD:\\n%s\"", "%", "(", "payload", ")", ")", "res", "=", "requests", ".", "request", "(", "method", ",", "operation_path_URL", ",", "data", "=", "payload", ")", "logging", ".", "debug", "(", "\"RESPONSE:\\n%s\"", "%", "(", "res", ".", "json", "(", ")", ")", ")", "return", "res" ]
Executes a Kubernetes operation using the specified method against a path. This is part of the low-level API. :Parameters: - `method`: The HTTP method to use, defaults to `GET` - `ops_path`: The path of the operation, for example, `/api/v1/events` which would result in an overall: `GET http://localhost:8080/api/v1/events` - `payload`: The optional payload which is relevant for `POST` or `PUT` methods only
[ "Executes", "a", "Kubernetes", "operation", "using", "the", "specified", "method", "against", "a", "path", ".", "This", "is", "part", "of", "the", "low", "-", "level", "API", "." ]
88531b1f09f23c049b3ad7aa9caebfc02a4a420d
https://github.com/kubernauts/pyk/blob/88531b1f09f23c049b3ad7aa9caebfc02a4a420d/pyk/toolkit.py#L40-L58
247,302
kubernauts/pyk
pyk/toolkit.py
KubeHTTPClient.create_rc
def create_rc(self, manifest_filename, namespace="default"): """ Creates an RC based on a manifest. :Parameters: - `manifest_filename`: The manifest file containing the ReplicationController definition, for example: `manifest/nginx-webserver-rc.yaml` - `namespace`: In which namespace the RC should be created, defaults to, well, `default` """ rc_manifest, rc_manifest_json = util.load_yaml(filename=manifest_filename) logging.debug("%s" %(rc_manifest_json)) create_rc_path = "".join(["/api/v1/namespaces/", namespace, "/replicationcontrollers"]) res = self.execute_operation(method="POST", ops_path=create_rc_path, payload=rc_manifest_json) try: rc_url = res.json()["metadata"]["selfLink"] except KeyError: raise ResourceCRUDException("".join(["Sorry, can not create the RC: ", rc_manifest["metadata"]["name"], ". Maybe it exists already?"])) logging.info("From %s I created the RC %s at %s" %(manifest_filename, rc_manifest["metadata"]["name"], rc_url)) return (res, rc_url)
python
def create_rc(self, manifest_filename, namespace="default"): """ Creates an RC based on a manifest. :Parameters: - `manifest_filename`: The manifest file containing the ReplicationController definition, for example: `manifest/nginx-webserver-rc.yaml` - `namespace`: In which namespace the RC should be created, defaults to, well, `default` """ rc_manifest, rc_manifest_json = util.load_yaml(filename=manifest_filename) logging.debug("%s" %(rc_manifest_json)) create_rc_path = "".join(["/api/v1/namespaces/", namespace, "/replicationcontrollers"]) res = self.execute_operation(method="POST", ops_path=create_rc_path, payload=rc_manifest_json) try: rc_url = res.json()["metadata"]["selfLink"] except KeyError: raise ResourceCRUDException("".join(["Sorry, can not create the RC: ", rc_manifest["metadata"]["name"], ". Maybe it exists already?"])) logging.info("From %s I created the RC %s at %s" %(manifest_filename, rc_manifest["metadata"]["name"], rc_url)) return (res, rc_url)
[ "def", "create_rc", "(", "self", ",", "manifest_filename", ",", "namespace", "=", "\"default\"", ")", ":", "rc_manifest", ",", "rc_manifest_json", "=", "util", ".", "load_yaml", "(", "filename", "=", "manifest_filename", ")", "logging", ".", "debug", "(", "\"%s\"", "%", "(", "rc_manifest_json", ")", ")", "create_rc_path", "=", "\"\"", ".", "join", "(", "[", "\"/api/v1/namespaces/\"", ",", "namespace", ",", "\"/replicationcontrollers\"", "]", ")", "res", "=", "self", ".", "execute_operation", "(", "method", "=", "\"POST\"", ",", "ops_path", "=", "create_rc_path", ",", "payload", "=", "rc_manifest_json", ")", "try", ":", "rc_url", "=", "res", ".", "json", "(", ")", "[", "\"metadata\"", "]", "[", "\"selfLink\"", "]", "except", "KeyError", ":", "raise", "ResourceCRUDException", "(", "\"\"", ".", "join", "(", "[", "\"Sorry, can not create the RC: \"", ",", "rc_manifest", "[", "\"metadata\"", "]", "[", "\"name\"", "]", ",", "\". Maybe it exists already?\"", "]", ")", ")", "logging", ".", "info", "(", "\"From %s I created the RC %s at %s\"", "%", "(", "manifest_filename", ",", "rc_manifest", "[", "\"metadata\"", "]", "[", "\"name\"", "]", ",", "rc_url", ")", ")", "return", "(", "res", ",", "rc_url", ")" ]
Creates an RC based on a manifest. :Parameters: - `manifest_filename`: The manifest file containing the ReplicationController definition, for example: `manifest/nginx-webserver-rc.yaml` - `namespace`: In which namespace the RC should be created, defaults to, well, `default`
[ "Creates", "an", "RC", "based", "on", "a", "manifest", "." ]
88531b1f09f23c049b3ad7aa9caebfc02a4a420d
https://github.com/kubernauts/pyk/blob/88531b1f09f23c049b3ad7aa9caebfc02a4a420d/pyk/toolkit.py#L81-L98
247,303
kubernauts/pyk
pyk/toolkit.py
KubeHTTPClient.scale_rc
def scale_rc(self, manifest_filename, namespace="default", num_replicas=0): """ Changes the replicas of an RC based on a manifest. Note that it defaults to 0, meaning to effectively disable this RC. :Parameters: - `manifest_filename`: The manifest file containing the ReplicationController definition, for example: `manifest/nginx-webserver-rc.yaml` - `namespace`: In which namespace the RC is, defaulting to `default` - `num_replicas`: How many copies of the pods that match the selector are supposed to run """ rc_manifest, rc_manifest_json = util.load_yaml(filename=manifest_filename) logging.debug("%s" %(rc_manifest_json)) rc_path = "".join(["/api/v1/namespaces/", namespace, "/replicationcontrollers/", rc_manifest["metadata"]["name"]]) rc_manifest["spec"]["replicas"] = num_replicas res = self.execute_operation(method="PUT", ops_path=rc_path, payload=util.serialize_tojson(rc_manifest)) try: rc_url = res.json()["metadata"]["selfLink"] except KeyError: raise ResourceCRUDException("".join(["Sorry, can not scale the RC: ", rc_manifest["metadata"]["name"]])) logging.info("I scaled the RC %s at %s to %d replicas" %(rc_manifest["metadata"]["name"], rc_url, num_replicas)) return (res, rc_url)
python
def scale_rc(self, manifest_filename, namespace="default", num_replicas=0): """ Changes the replicas of an RC based on a manifest. Note that it defaults to 0, meaning to effectively disable this RC. :Parameters: - `manifest_filename`: The manifest file containing the ReplicationController definition, for example: `manifest/nginx-webserver-rc.yaml` - `namespace`: In which namespace the RC is, defaulting to `default` - `num_replicas`: How many copies of the pods that match the selector are supposed to run """ rc_manifest, rc_manifest_json = util.load_yaml(filename=manifest_filename) logging.debug("%s" %(rc_manifest_json)) rc_path = "".join(["/api/v1/namespaces/", namespace, "/replicationcontrollers/", rc_manifest["metadata"]["name"]]) rc_manifest["spec"]["replicas"] = num_replicas res = self.execute_operation(method="PUT", ops_path=rc_path, payload=util.serialize_tojson(rc_manifest)) try: rc_url = res.json()["metadata"]["selfLink"] except KeyError: raise ResourceCRUDException("".join(["Sorry, can not scale the RC: ", rc_manifest["metadata"]["name"]])) logging.info("I scaled the RC %s at %s to %d replicas" %(rc_manifest["metadata"]["name"], rc_url, num_replicas)) return (res, rc_url)
[ "def", "scale_rc", "(", "self", ",", "manifest_filename", ",", "namespace", "=", "\"default\"", ",", "num_replicas", "=", "0", ")", ":", "rc_manifest", ",", "rc_manifest_json", "=", "util", ".", "load_yaml", "(", "filename", "=", "manifest_filename", ")", "logging", ".", "debug", "(", "\"%s\"", "%", "(", "rc_manifest_json", ")", ")", "rc_path", "=", "\"\"", ".", "join", "(", "[", "\"/api/v1/namespaces/\"", ",", "namespace", ",", "\"/replicationcontrollers/\"", ",", "rc_manifest", "[", "\"metadata\"", "]", "[", "\"name\"", "]", "]", ")", "rc_manifest", "[", "\"spec\"", "]", "[", "\"replicas\"", "]", "=", "num_replicas", "res", "=", "self", ".", "execute_operation", "(", "method", "=", "\"PUT\"", ",", "ops_path", "=", "rc_path", ",", "payload", "=", "util", ".", "serialize_tojson", "(", "rc_manifest", ")", ")", "try", ":", "rc_url", "=", "res", ".", "json", "(", ")", "[", "\"metadata\"", "]", "[", "\"selfLink\"", "]", "except", "KeyError", ":", "raise", "ResourceCRUDException", "(", "\"\"", ".", "join", "(", "[", "\"Sorry, can not scale the RC: \"", ",", "rc_manifest", "[", "\"metadata\"", "]", "[", "\"name\"", "]", "]", ")", ")", "logging", ".", "info", "(", "\"I scaled the RC %s at %s to %d replicas\"", "%", "(", "rc_manifest", "[", "\"metadata\"", "]", "[", "\"name\"", "]", ",", "rc_url", ",", "num_replicas", ")", ")", "return", "(", "res", ",", "rc_url", ")" ]
Changes the replicas of an RC based on a manifest. Note that it defaults to 0, meaning to effectively disable this RC. :Parameters: - `manifest_filename`: The manifest file containing the ReplicationController definition, for example: `manifest/nginx-webserver-rc.yaml` - `namespace`: In which namespace the RC is, defaulting to `default` - `num_replicas`: How many copies of the pods that match the selector are supposed to run
[ "Changes", "the", "replicas", "of", "an", "RC", "based", "on", "a", "manifest", ".", "Note", "that", "it", "defaults", "to", "0", "meaning", "to", "effectively", "disable", "this", "RC", "." ]
88531b1f09f23c049b3ad7aa9caebfc02a4a420d
https://github.com/kubernauts/pyk/blob/88531b1f09f23c049b3ad7aa9caebfc02a4a420d/pyk/toolkit.py#L100-L120
247,304
kubernauts/pyk
pyk/toolkit.py
KubeHTTPClient.create_svc
def create_svc(self, manifest_filename, namespace="default"): """ Creates a service based on a manifest. :Parameters: - `manifest_filename`: The manifest file containing the service definition, for example: `manifest/webserver-svc.yaml` - `namespace`: In which namespace the service should be created, defaults to, well, `default` """ svc_manifest, svc_manifest_json = util.load_yaml(filename=manifest_filename) logging.debug("%s" %(svc_manifest_json)) create_svc_path = "".join(["/api/v1/namespaces/", namespace, "/services"]) res = self.execute_operation(method="POST", ops_path=create_svc_path, payload=svc_manifest_json) try: svc_url = res.json()["metadata"]["selfLink"] except KeyError: raise ResourceCRUDException("".join(["Sorry, can not create the service: ", svc_manifest["metadata"]["name"], ". Maybe it exists already?"])) logging.info("From %s I created the service %s at %s" %(manifest_filename, svc_manifest["metadata"]["name"], svc_url)) return (res, svc_url)
python
def create_svc(self, manifest_filename, namespace="default"): """ Creates a service based on a manifest. :Parameters: - `manifest_filename`: The manifest file containing the service definition, for example: `manifest/webserver-svc.yaml` - `namespace`: In which namespace the service should be created, defaults to, well, `default` """ svc_manifest, svc_manifest_json = util.load_yaml(filename=manifest_filename) logging.debug("%s" %(svc_manifest_json)) create_svc_path = "".join(["/api/v1/namespaces/", namespace, "/services"]) res = self.execute_operation(method="POST", ops_path=create_svc_path, payload=svc_manifest_json) try: svc_url = res.json()["metadata"]["selfLink"] except KeyError: raise ResourceCRUDException("".join(["Sorry, can not create the service: ", svc_manifest["metadata"]["name"], ". Maybe it exists already?"])) logging.info("From %s I created the service %s at %s" %(manifest_filename, svc_manifest["metadata"]["name"], svc_url)) return (res, svc_url)
[ "def", "create_svc", "(", "self", ",", "manifest_filename", ",", "namespace", "=", "\"default\"", ")", ":", "svc_manifest", ",", "svc_manifest_json", "=", "util", ".", "load_yaml", "(", "filename", "=", "manifest_filename", ")", "logging", ".", "debug", "(", "\"%s\"", "%", "(", "svc_manifest_json", ")", ")", "create_svc_path", "=", "\"\"", ".", "join", "(", "[", "\"/api/v1/namespaces/\"", ",", "namespace", ",", "\"/services\"", "]", ")", "res", "=", "self", ".", "execute_operation", "(", "method", "=", "\"POST\"", ",", "ops_path", "=", "create_svc_path", ",", "payload", "=", "svc_manifest_json", ")", "try", ":", "svc_url", "=", "res", ".", "json", "(", ")", "[", "\"metadata\"", "]", "[", "\"selfLink\"", "]", "except", "KeyError", ":", "raise", "ResourceCRUDException", "(", "\"\"", ".", "join", "(", "[", "\"Sorry, can not create the service: \"", ",", "svc_manifest", "[", "\"metadata\"", "]", "[", "\"name\"", "]", ",", "\". Maybe it exists already?\"", "]", ")", ")", "logging", ".", "info", "(", "\"From %s I created the service %s at %s\"", "%", "(", "manifest_filename", ",", "svc_manifest", "[", "\"metadata\"", "]", "[", "\"name\"", "]", ",", "svc_url", ")", ")", "return", "(", "res", ",", "svc_url", ")" ]
Creates a service based on a manifest. :Parameters: - `manifest_filename`: The manifest file containing the service definition, for example: `manifest/webserver-svc.yaml` - `namespace`: In which namespace the service should be created, defaults to, well, `default`
[ "Creates", "a", "service", "based", "on", "a", "manifest", "." ]
88531b1f09f23c049b3ad7aa9caebfc02a4a420d
https://github.com/kubernauts/pyk/blob/88531b1f09f23c049b3ad7aa9caebfc02a4a420d/pyk/toolkit.py#L122-L139
247,305
minhhoit/yacms
yacms/core/views.py
set_site
def set_site(request): """ Put the selected site ID into the session - posted to from the "Select site" drop-down in the header of the admin. The site ID is then used in favour of the current request's domain in ``yacms.core.managers.CurrentSiteManager``. """ site_id = int(request.GET["site_id"]) if not request.user.is_superuser: try: SitePermission.objects.get(user=request.user, sites=site_id) except SitePermission.DoesNotExist: raise PermissionDenied request.session["site_id"] = site_id admin_url = reverse("admin:index") next = next_url(request) or admin_url # Don't redirect to a change view for an object that won't exist # on the selected site - go to its list view instead. if next.startswith(admin_url): parts = next.split("/") if len(parts) > 4 and parts[4].isdigit(): next = "/".join(parts[:4]) return redirect(next)
python
def set_site(request): """ Put the selected site ID into the session - posted to from the "Select site" drop-down in the header of the admin. The site ID is then used in favour of the current request's domain in ``yacms.core.managers.CurrentSiteManager``. """ site_id = int(request.GET["site_id"]) if not request.user.is_superuser: try: SitePermission.objects.get(user=request.user, sites=site_id) except SitePermission.DoesNotExist: raise PermissionDenied request.session["site_id"] = site_id admin_url = reverse("admin:index") next = next_url(request) or admin_url # Don't redirect to a change view for an object that won't exist # on the selected site - go to its list view instead. if next.startswith(admin_url): parts = next.split("/") if len(parts) > 4 and parts[4].isdigit(): next = "/".join(parts[:4]) return redirect(next)
[ "def", "set_site", "(", "request", ")", ":", "site_id", "=", "int", "(", "request", ".", "GET", "[", "\"site_id\"", "]", ")", "if", "not", "request", ".", "user", ".", "is_superuser", ":", "try", ":", "SitePermission", ".", "objects", ".", "get", "(", "user", "=", "request", ".", "user", ",", "sites", "=", "site_id", ")", "except", "SitePermission", ".", "DoesNotExist", ":", "raise", "PermissionDenied", "request", ".", "session", "[", "\"site_id\"", "]", "=", "site_id", "admin_url", "=", "reverse", "(", "\"admin:index\"", ")", "next", "=", "next_url", "(", "request", ")", "or", "admin_url", "# Don't redirect to a change view for an object that won't exist", "# on the selected site - go to its list view instead.", "if", "next", ".", "startswith", "(", "admin_url", ")", ":", "parts", "=", "next", ".", "split", "(", "\"/\"", ")", "if", "len", "(", "parts", ")", ">", "4", "and", "parts", "[", "4", "]", ".", "isdigit", "(", ")", ":", "next", "=", "\"/\"", ".", "join", "(", "parts", "[", ":", "4", "]", ")", "return", "redirect", "(", "next", ")" ]
Put the selected site ID into the session - posted to from the "Select site" drop-down in the header of the admin. The site ID is then used in favour of the current request's domain in ``yacms.core.managers.CurrentSiteManager``.
[ "Put", "the", "selected", "site", "ID", "into", "the", "session", "-", "posted", "to", "from", "the", "Select", "site", "drop", "-", "down", "in", "the", "header", "of", "the", "admin", ".", "The", "site", "ID", "is", "then", "used", "in", "favour", "of", "the", "current", "request", "s", "domain", "in", "yacms", ".", "core", ".", "managers", ".", "CurrentSiteManager", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/views.py#L53-L75
247,306
minhhoit/yacms
yacms/core/views.py
direct_to_template
def direct_to_template(request, template, extra_context=None, **kwargs): """ Replacement for Django's ``direct_to_template`` that uses ``TemplateResponse`` via ``yacms.utils.views.render``. """ context = extra_context or {} context["params"] = kwargs for (key, value) in context.items(): if callable(value): context[key] = value() return TemplateResponse(request, template, context)
python
def direct_to_template(request, template, extra_context=None, **kwargs): """ Replacement for Django's ``direct_to_template`` that uses ``TemplateResponse`` via ``yacms.utils.views.render``. """ context = extra_context or {} context["params"] = kwargs for (key, value) in context.items(): if callable(value): context[key] = value() return TemplateResponse(request, template, context)
[ "def", "direct_to_template", "(", "request", ",", "template", ",", "extra_context", "=", "None", ",", "*", "*", "kwargs", ")", ":", "context", "=", "extra_context", "or", "{", "}", "context", "[", "\"params\"", "]", "=", "kwargs", "for", "(", "key", ",", "value", ")", "in", "context", ".", "items", "(", ")", ":", "if", "callable", "(", "value", ")", ":", "context", "[", "key", "]", "=", "value", "(", ")", "return", "TemplateResponse", "(", "request", ",", "template", ",", "context", ")" ]
Replacement for Django's ``direct_to_template`` that uses ``TemplateResponse`` via ``yacms.utils.views.render``.
[ "Replacement", "for", "Django", "s", "direct_to_template", "that", "uses", "TemplateResponse", "via", "yacms", ".", "utils", ".", "views", ".", "render", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/views.py#L78-L88
247,307
minhhoit/yacms
yacms/core/views.py
edit
def edit(request): """ Process the inline editing form. """ model = apps.get_model(request.POST["app"], request.POST["model"]) obj = model.objects.get(id=request.POST["id"]) form = get_edit_form(obj, request.POST["fields"], data=request.POST, files=request.FILES) if not (is_editable(obj, request) and has_site_permission(request.user)): response = _("Permission denied") elif form.is_valid(): form.save() model_admin = ModelAdmin(model, admin.site) message = model_admin.construct_change_message(request, form, None) model_admin.log_change(request, obj, message) response = "" else: response = list(form.errors.values())[0][0] return HttpResponse(response)
python
def edit(request): """ Process the inline editing form. """ model = apps.get_model(request.POST["app"], request.POST["model"]) obj = model.objects.get(id=request.POST["id"]) form = get_edit_form(obj, request.POST["fields"], data=request.POST, files=request.FILES) if not (is_editable(obj, request) and has_site_permission(request.user)): response = _("Permission denied") elif form.is_valid(): form.save() model_admin = ModelAdmin(model, admin.site) message = model_admin.construct_change_message(request, form, None) model_admin.log_change(request, obj, message) response = "" else: response = list(form.errors.values())[0][0] return HttpResponse(response)
[ "def", "edit", "(", "request", ")", ":", "model", "=", "apps", ".", "get_model", "(", "request", ".", "POST", "[", "\"app\"", "]", ",", "request", ".", "POST", "[", "\"model\"", "]", ")", "obj", "=", "model", ".", "objects", ".", "get", "(", "id", "=", "request", ".", "POST", "[", "\"id\"", "]", ")", "form", "=", "get_edit_form", "(", "obj", ",", "request", ".", "POST", "[", "\"fields\"", "]", ",", "data", "=", "request", ".", "POST", ",", "files", "=", "request", ".", "FILES", ")", "if", "not", "(", "is_editable", "(", "obj", ",", "request", ")", "and", "has_site_permission", "(", "request", ".", "user", ")", ")", ":", "response", "=", "_", "(", "\"Permission denied\"", ")", "elif", "form", ".", "is_valid", "(", ")", ":", "form", ".", "save", "(", ")", "model_admin", "=", "ModelAdmin", "(", "model", ",", "admin", ".", "site", ")", "message", "=", "model_admin", ".", "construct_change_message", "(", "request", ",", "form", ",", "None", ")", "model_admin", ".", "log_change", "(", "request", ",", "obj", ",", "message", ")", "response", "=", "\"\"", "else", ":", "response", "=", "list", "(", "form", ".", "errors", ".", "values", "(", ")", ")", "[", "0", "]", "[", "0", "]", "return", "HttpResponse", "(", "response", ")" ]
Process the inline editing form.
[ "Process", "the", "inline", "editing", "form", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/views.py#L92-L110
247,308
minhhoit/yacms
yacms/core/views.py
search
def search(request, template="search_results.html", extra_context=None): """ Display search results. Takes an optional "contenttype" GET parameter in the form "app-name.ModelName" to limit search results to a single model. """ query = request.GET.get("q", "") page = request.GET.get("page", 1) per_page = settings.SEARCH_PER_PAGE max_paging_links = settings.MAX_PAGING_LINKS try: parts = request.GET.get("type", "").split(".", 1) search_model = apps.get_model(*parts) search_model.objects.search # Attribute check except (ValueError, TypeError, LookupError, AttributeError): search_model = Displayable search_type = _("Everything") else: search_type = search_model._meta.verbose_name_plural.capitalize() results = search_model.objects.search(query, for_user=request.user) paginated = paginate(results, page, per_page, max_paging_links) context = {"query": query, "results": paginated, "search_type": search_type} context.update(extra_context or {}) return TemplateResponse(request, template, context)
python
def search(request, template="search_results.html", extra_context=None): """ Display search results. Takes an optional "contenttype" GET parameter in the form "app-name.ModelName" to limit search results to a single model. """ query = request.GET.get("q", "") page = request.GET.get("page", 1) per_page = settings.SEARCH_PER_PAGE max_paging_links = settings.MAX_PAGING_LINKS try: parts = request.GET.get("type", "").split(".", 1) search_model = apps.get_model(*parts) search_model.objects.search # Attribute check except (ValueError, TypeError, LookupError, AttributeError): search_model = Displayable search_type = _("Everything") else: search_type = search_model._meta.verbose_name_plural.capitalize() results = search_model.objects.search(query, for_user=request.user) paginated = paginate(results, page, per_page, max_paging_links) context = {"query": query, "results": paginated, "search_type": search_type} context.update(extra_context or {}) return TemplateResponse(request, template, context)
[ "def", "search", "(", "request", ",", "template", "=", "\"search_results.html\"", ",", "extra_context", "=", "None", ")", ":", "query", "=", "request", ".", "GET", ".", "get", "(", "\"q\"", ",", "\"\"", ")", "page", "=", "request", ".", "GET", ".", "get", "(", "\"page\"", ",", "1", ")", "per_page", "=", "settings", ".", "SEARCH_PER_PAGE", "max_paging_links", "=", "settings", ".", "MAX_PAGING_LINKS", "try", ":", "parts", "=", "request", ".", "GET", ".", "get", "(", "\"type\"", ",", "\"\"", ")", ".", "split", "(", "\".\"", ",", "1", ")", "search_model", "=", "apps", ".", "get_model", "(", "*", "parts", ")", "search_model", ".", "objects", ".", "search", "# Attribute check", "except", "(", "ValueError", ",", "TypeError", ",", "LookupError", ",", "AttributeError", ")", ":", "search_model", "=", "Displayable", "search_type", "=", "_", "(", "\"Everything\"", ")", "else", ":", "search_type", "=", "search_model", ".", "_meta", ".", "verbose_name_plural", ".", "capitalize", "(", ")", "results", "=", "search_model", ".", "objects", ".", "search", "(", "query", ",", "for_user", "=", "request", ".", "user", ")", "paginated", "=", "paginate", "(", "results", ",", "page", ",", "per_page", ",", "max_paging_links", ")", "context", "=", "{", "\"query\"", ":", "query", ",", "\"results\"", ":", "paginated", ",", "\"search_type\"", ":", "search_type", "}", "context", ".", "update", "(", "extra_context", "or", "{", "}", ")", "return", "TemplateResponse", "(", "request", ",", "template", ",", "context", ")" ]
Display search results. Takes an optional "contenttype" GET parameter in the form "app-name.ModelName" to limit search results to a single model.
[ "Display", "search", "results", ".", "Takes", "an", "optional", "contenttype", "GET", "parameter", "in", "the", "form", "app", "-", "name", ".", "ModelName", "to", "limit", "search", "results", "to", "a", "single", "model", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/views.py#L113-L136
247,309
minhhoit/yacms
yacms/core/views.py
static_proxy
def static_proxy(request): """ Serves TinyMCE plugins inside the inline popups and the uploadify SWF, as these are normally static files, and will break with cross-domain JavaScript errors if ``STATIC_URL`` is an external host. URL for the file is passed in via querystring in the inline popup plugin template, and we then attempt to pull out the relative path to the file, so that we can serve it locally via Django. """ normalize = lambda u: ("//" + u.split("://")[-1]) if "://" in u else u url = normalize(request.GET["u"]) host = "//" + request.get_host() static_url = normalize(settings.STATIC_URL) for prefix in (host, static_url, "/"): if url.startswith(prefix): url = url.replace(prefix, "", 1) response = "" (content_type, encoding) = mimetypes.guess_type(url) if content_type is None: content_type = "application/octet-stream" path = finders.find(url) if path: if isinstance(path, (list, tuple)): path = path[0] if url.endswith(".htm"): # Inject <base href="{{ STATIC_URL }}"> into TinyMCE # plugins, since the path static files in these won't be # on the same domain. static_url = settings.STATIC_URL + os.path.split(url)[0] + "/" if not urlparse(static_url).scheme: static_url = urljoin(host, static_url) base_tag = "<base href='%s'>" % static_url with open(path, "r") as f: response = f.read().replace("<head>", "<head>" + base_tag) else: try: with open(path, "rb") as f: response = f.read() except IOError: return HttpResponseNotFound() return HttpResponse(response, content_type=content_type)
python
def static_proxy(request): """ Serves TinyMCE plugins inside the inline popups and the uploadify SWF, as these are normally static files, and will break with cross-domain JavaScript errors if ``STATIC_URL`` is an external host. URL for the file is passed in via querystring in the inline popup plugin template, and we then attempt to pull out the relative path to the file, so that we can serve it locally via Django. """ normalize = lambda u: ("//" + u.split("://")[-1]) if "://" in u else u url = normalize(request.GET["u"]) host = "//" + request.get_host() static_url = normalize(settings.STATIC_URL) for prefix in (host, static_url, "/"): if url.startswith(prefix): url = url.replace(prefix, "", 1) response = "" (content_type, encoding) = mimetypes.guess_type(url) if content_type is None: content_type = "application/octet-stream" path = finders.find(url) if path: if isinstance(path, (list, tuple)): path = path[0] if url.endswith(".htm"): # Inject <base href="{{ STATIC_URL }}"> into TinyMCE # plugins, since the path static files in these won't be # on the same domain. static_url = settings.STATIC_URL + os.path.split(url)[0] + "/" if not urlparse(static_url).scheme: static_url = urljoin(host, static_url) base_tag = "<base href='%s'>" % static_url with open(path, "r") as f: response = f.read().replace("<head>", "<head>" + base_tag) else: try: with open(path, "rb") as f: response = f.read() except IOError: return HttpResponseNotFound() return HttpResponse(response, content_type=content_type)
[ "def", "static_proxy", "(", "request", ")", ":", "normalize", "=", "lambda", "u", ":", "(", "\"//\"", "+", "u", ".", "split", "(", "\"://\"", ")", "[", "-", "1", "]", ")", "if", "\"://\"", "in", "u", "else", "u", "url", "=", "normalize", "(", "request", ".", "GET", "[", "\"u\"", "]", ")", "host", "=", "\"//\"", "+", "request", ".", "get_host", "(", ")", "static_url", "=", "normalize", "(", "settings", ".", "STATIC_URL", ")", "for", "prefix", "in", "(", "host", ",", "static_url", ",", "\"/\"", ")", ":", "if", "url", ".", "startswith", "(", "prefix", ")", ":", "url", "=", "url", ".", "replace", "(", "prefix", ",", "\"\"", ",", "1", ")", "response", "=", "\"\"", "(", "content_type", ",", "encoding", ")", "=", "mimetypes", ".", "guess_type", "(", "url", ")", "if", "content_type", "is", "None", ":", "content_type", "=", "\"application/octet-stream\"", "path", "=", "finders", ".", "find", "(", "url", ")", "if", "path", ":", "if", "isinstance", "(", "path", ",", "(", "list", ",", "tuple", ")", ")", ":", "path", "=", "path", "[", "0", "]", "if", "url", ".", "endswith", "(", "\".htm\"", ")", ":", "# Inject <base href=\"{{ STATIC_URL }}\"> into TinyMCE", "# plugins, since the path static files in these won't be", "# on the same domain.", "static_url", "=", "settings", ".", "STATIC_URL", "+", "os", ".", "path", ".", "split", "(", "url", ")", "[", "0", "]", "+", "\"/\"", "if", "not", "urlparse", "(", "static_url", ")", ".", "scheme", ":", "static_url", "=", "urljoin", "(", "host", ",", "static_url", ")", "base_tag", "=", "\"<base href='%s'>\"", "%", "static_url", "with", "open", "(", "path", ",", "\"r\"", ")", "as", "f", ":", "response", "=", "f", ".", "read", "(", ")", ".", "replace", "(", "\"<head>\"", ",", "\"<head>\"", "+", "base_tag", ")", "else", ":", "try", ":", "with", "open", "(", "path", ",", "\"rb\"", ")", "as", "f", ":", "response", "=", "f", ".", "read", "(", ")", "except", "IOError", ":", "return", "HttpResponseNotFound", "(", ")", "return", "HttpResponse", "(", "response", ",", "content_type", "=", "content_type", ")" ]
Serves TinyMCE plugins inside the inline popups and the uploadify SWF, as these are normally static files, and will break with cross-domain JavaScript errors if ``STATIC_URL`` is an external host. URL for the file is passed in via querystring in the inline popup plugin template, and we then attempt to pull out the relative path to the file, so that we can serve it locally via Django.
[ "Serves", "TinyMCE", "plugins", "inside", "the", "inline", "popups", "and", "the", "uploadify", "SWF", "as", "these", "are", "normally", "static", "files", "and", "will", "break", "with", "cross", "-", "domain", "JavaScript", "errors", "if", "STATIC_URL", "is", "an", "external", "host", ".", "URL", "for", "the", "file", "is", "passed", "in", "via", "querystring", "in", "the", "inline", "popup", "plugin", "template", "and", "we", "then", "attempt", "to", "pull", "out", "the", "relative", "path", "to", "the", "file", "so", "that", "we", "can", "serve", "it", "locally", "via", "Django", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/views.py#L140-L180
247,310
minhhoit/yacms
yacms/core/views.py
page_not_found
def page_not_found(request, template_name="errors/404.html"): """ Mimics Django's 404 handler but with a different template path. """ context = { "STATIC_URL": settings.STATIC_URL, "request_path": request.path, } t = get_template(template_name) return HttpResponseNotFound(t.render(context, request))
python
def page_not_found(request, template_name="errors/404.html"): """ Mimics Django's 404 handler but with a different template path. """ context = { "STATIC_URL": settings.STATIC_URL, "request_path": request.path, } t = get_template(template_name) return HttpResponseNotFound(t.render(context, request))
[ "def", "page_not_found", "(", "request", ",", "template_name", "=", "\"errors/404.html\"", ")", ":", "context", "=", "{", "\"STATIC_URL\"", ":", "settings", ".", "STATIC_URL", ",", "\"request_path\"", ":", "request", ".", "path", ",", "}", "t", "=", "get_template", "(", "template_name", ")", "return", "HttpResponseNotFound", "(", "t", ".", "render", "(", "context", ",", "request", ")", ")" ]
Mimics Django's 404 handler but with a different template path.
[ "Mimics", "Django", "s", "404", "handler", "but", "with", "a", "different", "template", "path", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/views.py#L211-L220
247,311
minhhoit/yacms
yacms/core/views.py
server_error
def server_error(request, template_name="errors/500.html"): """ Mimics Django's error handler but adds ``STATIC_URL`` to the context. """ context = {"STATIC_URL": settings.STATIC_URL} t = get_template(template_name) return HttpResponseServerError(t.render(context, request))
python
def server_error(request, template_name="errors/500.html"): """ Mimics Django's error handler but adds ``STATIC_URL`` to the context. """ context = {"STATIC_URL": settings.STATIC_URL} t = get_template(template_name) return HttpResponseServerError(t.render(context, request))
[ "def", "server_error", "(", "request", ",", "template_name", "=", "\"errors/500.html\"", ")", ":", "context", "=", "{", "\"STATIC_URL\"", ":", "settings", ".", "STATIC_URL", "}", "t", "=", "get_template", "(", "template_name", ")", "return", "HttpResponseServerError", "(", "t", ".", "render", "(", "context", ",", "request", ")", ")" ]
Mimics Django's error handler but adds ``STATIC_URL`` to the context.
[ "Mimics", "Django", "s", "error", "handler", "but", "adds", "STATIC_URL", "to", "the", "context", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/views.py#L224-L231
247,312
jribbens/hg-autohooks
hgautohooks.py
_runhook
def _runhook(ui, repo, hooktype, filename, kwargs): """Run the hook in `filename` and return its result.""" hname = hooktype + ".autohooks." + os.path.basename(filename) if filename.lower().endswith(".py"): try: mod = mercurial.extensions.loadpath(filename, "hghook.%s" % hname) except Exception: ui.write(_("loading %s hook failed:\n") % hname) raise return mercurial.hook._pythonhook(ui, repo, hooktype, hname, getattr(mod, hooktype.replace("-", "_")), kwargs, True) elif filename.lower().endswith(".sh"): return mercurial.hook._exthook(ui, repo, hname, filename, kwargs, True) return False
python
def _runhook(ui, repo, hooktype, filename, kwargs): """Run the hook in `filename` and return its result.""" hname = hooktype + ".autohooks." + os.path.basename(filename) if filename.lower().endswith(".py"): try: mod = mercurial.extensions.loadpath(filename, "hghook.%s" % hname) except Exception: ui.write(_("loading %s hook failed:\n") % hname) raise return mercurial.hook._pythonhook(ui, repo, hooktype, hname, getattr(mod, hooktype.replace("-", "_")), kwargs, True) elif filename.lower().endswith(".sh"): return mercurial.hook._exthook(ui, repo, hname, filename, kwargs, True) return False
[ "def", "_runhook", "(", "ui", ",", "repo", ",", "hooktype", ",", "filename", ",", "kwargs", ")", ":", "hname", "=", "hooktype", "+", "\".autohooks.\"", "+", "os", ".", "path", ".", "basename", "(", "filename", ")", "if", "filename", ".", "lower", "(", ")", ".", "endswith", "(", "\".py\"", ")", ":", "try", ":", "mod", "=", "mercurial", ".", "extensions", ".", "loadpath", "(", "filename", ",", "\"hghook.%s\"", "%", "hname", ")", "except", "Exception", ":", "ui", ".", "write", "(", "_", "(", "\"loading %s hook failed:\\n\"", ")", "%", "hname", ")", "raise", "return", "mercurial", ".", "hook", ".", "_pythonhook", "(", "ui", ",", "repo", ",", "hooktype", ",", "hname", ",", "getattr", "(", "mod", ",", "hooktype", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", ")", ",", "kwargs", ",", "True", ")", "elif", "filename", ".", "lower", "(", ")", ".", "endswith", "(", "\".sh\"", ")", ":", "return", "mercurial", ".", "hook", ".", "_exthook", "(", "ui", ",", "repo", ",", "hname", ",", "filename", ",", "kwargs", ",", "True", ")", "return", "False" ]
Run the hook in `filename` and return its result.
[ "Run", "the", "hook", "in", "filename", "and", "return", "its", "result", "." ]
4ade9b7d95cfa8ac58a5abb27f2c37634f869182
https://github.com/jribbens/hg-autohooks/blob/4ade9b7d95cfa8ac58a5abb27f2c37634f869182/hgautohooks.py#L48-L62
247,313
jribbens/hg-autohooks
hgautohooks.py
autohook
def autohook(ui, repo, hooktype, **kwargs): """Look for hooks inside the repository to run.""" cmd = hooktype.replace("-", "_") if not repo or not cmd.replace("_", "").isalpha(): return False result = False trusted = ui.configlist("autohooks", "trusted") if "" not in trusted: default_path = ui.config("paths", "default") if not default_path: return False for match in trusted: if default_path.startswith(match): break else: return False for hookdir in ("hg-autohooks", ".hg-autohooks"): dirname = os.path.join(repo.root, hookdir) if not os.path.exists(dirname): continue for leafname in os.listdir(dirname): if not leafname.startswith(cmd + "."): continue filename = os.path.join(dirname, leafname) result = _runhook(ui, repo, hooktype, filename, kwargs) or result return result
python
def autohook(ui, repo, hooktype, **kwargs): """Look for hooks inside the repository to run.""" cmd = hooktype.replace("-", "_") if not repo or not cmd.replace("_", "").isalpha(): return False result = False trusted = ui.configlist("autohooks", "trusted") if "" not in trusted: default_path = ui.config("paths", "default") if not default_path: return False for match in trusted: if default_path.startswith(match): break else: return False for hookdir in ("hg-autohooks", ".hg-autohooks"): dirname = os.path.join(repo.root, hookdir) if not os.path.exists(dirname): continue for leafname in os.listdir(dirname): if not leafname.startswith(cmd + "."): continue filename = os.path.join(dirname, leafname) result = _runhook(ui, repo, hooktype, filename, kwargs) or result return result
[ "def", "autohook", "(", "ui", ",", "repo", ",", "hooktype", ",", "*", "*", "kwargs", ")", ":", "cmd", "=", "hooktype", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", "if", "not", "repo", "or", "not", "cmd", ".", "replace", "(", "\"_\"", ",", "\"\"", ")", ".", "isalpha", "(", ")", ":", "return", "False", "result", "=", "False", "trusted", "=", "ui", ".", "configlist", "(", "\"autohooks\"", ",", "\"trusted\"", ")", "if", "\"\"", "not", "in", "trusted", ":", "default_path", "=", "ui", ".", "config", "(", "\"paths\"", ",", "\"default\"", ")", "if", "not", "default_path", ":", "return", "False", "for", "match", "in", "trusted", ":", "if", "default_path", ".", "startswith", "(", "match", ")", ":", "break", "else", ":", "return", "False", "for", "hookdir", "in", "(", "\"hg-autohooks\"", ",", "\".hg-autohooks\"", ")", ":", "dirname", "=", "os", ".", "path", ".", "join", "(", "repo", ".", "root", ",", "hookdir", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dirname", ")", ":", "continue", "for", "leafname", "in", "os", ".", "listdir", "(", "dirname", ")", ":", "if", "not", "leafname", ".", "startswith", "(", "cmd", "+", "\".\"", ")", ":", "continue", "filename", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "leafname", ")", "result", "=", "_runhook", "(", "ui", ",", "repo", ",", "hooktype", ",", "filename", ",", "kwargs", ")", "or", "result", "return", "result" ]
Look for hooks inside the repository to run.
[ "Look", "for", "hooks", "inside", "the", "repository", "to", "run", "." ]
4ade9b7d95cfa8ac58a5abb27f2c37634f869182
https://github.com/jribbens/hg-autohooks/blob/4ade9b7d95cfa8ac58a5abb27f2c37634f869182/hgautohooks.py#L65-L90
247,314
johnwlockwood/iter_karld_tools
iter_karld_tools/__init__.py
i_batch
def i_batch(max_size, iterable): """ Generator that iteratively batches items to a max size and consumes the items iterable as each batch is yielded. :param max_size: Max size of each batch. :type max_size: int :param iterable: An iterable :type iterable: iter """ iterable_items = iter(iterable) for items_batch in iter(lambda: tuple(islice(iterable_items, max_size)), tuple()): yield items_batch
python
def i_batch(max_size, iterable): """ Generator that iteratively batches items to a max size and consumes the items iterable as each batch is yielded. :param max_size: Max size of each batch. :type max_size: int :param iterable: An iterable :type iterable: iter """ iterable_items = iter(iterable) for items_batch in iter(lambda: tuple(islice(iterable_items, max_size)), tuple()): yield items_batch
[ "def", "i_batch", "(", "max_size", ",", "iterable", ")", ":", "iterable_items", "=", "iter", "(", "iterable", ")", "for", "items_batch", "in", "iter", "(", "lambda", ":", "tuple", "(", "islice", "(", "iterable_items", ",", "max_size", ")", ")", ",", "tuple", "(", ")", ")", ":", "yield", "items_batch" ]
Generator that iteratively batches items to a max size and consumes the items iterable as each batch is yielded. :param max_size: Max size of each batch. :type max_size: int :param iterable: An iterable :type iterable: iter
[ "Generator", "that", "iteratively", "batches", "items", "to", "a", "max", "size", "and", "consumes", "the", "items", "iterable", "as", "each", "batch", "is", "yielded", "." ]
7baaa94244c4a4959f55d4018a8899781ff111b0
https://github.com/johnwlockwood/iter_karld_tools/blob/7baaa94244c4a4959f55d4018a8899781ff111b0/iter_karld_tools/__init__.py#L41-L55
247,315
cogniteev/docido-python-sdk
docido_sdk/toolbox/http_ext.py
HttpSessionPreparer.mount_rate_limit_adapters
def mount_rate_limit_adapters(cls, session=None, rls_config=None, **kwargs): """Mount rate-limits adapters on the specified `requests.Session` object. :param py:class:`requests.Session` session: Session to mount. If not specified, then use the global `HTTP_SESSION`. :param dict rls_config: Rate-limits configuration. If not specified, then use the one defined at application level. :param kwargs: Additional keywords argument given to py:class:`docido_sdk.toolbox.rate_limits.RLRequestAdapter` constructor. """ session = session or HTTP_SESSION if rls_config is None: rls_config = RateLimiter.get_configs() for name, rl_conf in rls_config.items(): urls = rl_conf.get('urls', []) if not urls: continue rl_adapter = RLRequestAdapter(name, config=rls_config, **kwargs) for url in urls: session.mount(url, rl_adapter)
python
def mount_rate_limit_adapters(cls, session=None, rls_config=None, **kwargs): """Mount rate-limits adapters on the specified `requests.Session` object. :param py:class:`requests.Session` session: Session to mount. If not specified, then use the global `HTTP_SESSION`. :param dict rls_config: Rate-limits configuration. If not specified, then use the one defined at application level. :param kwargs: Additional keywords argument given to py:class:`docido_sdk.toolbox.rate_limits.RLRequestAdapter` constructor. """ session = session or HTTP_SESSION if rls_config is None: rls_config = RateLimiter.get_configs() for name, rl_conf in rls_config.items(): urls = rl_conf.get('urls', []) if not urls: continue rl_adapter = RLRequestAdapter(name, config=rls_config, **kwargs) for url in urls: session.mount(url, rl_adapter)
[ "def", "mount_rate_limit_adapters", "(", "cls", ",", "session", "=", "None", ",", "rls_config", "=", "None", ",", "*", "*", "kwargs", ")", ":", "session", "=", "session", "or", "HTTP_SESSION", "if", "rls_config", "is", "None", ":", "rls_config", "=", "RateLimiter", ".", "get_configs", "(", ")", "for", "name", ",", "rl_conf", "in", "rls_config", ".", "items", "(", ")", ":", "urls", "=", "rl_conf", ".", "get", "(", "'urls'", ",", "[", "]", ")", "if", "not", "urls", ":", "continue", "rl_adapter", "=", "RLRequestAdapter", "(", "name", ",", "config", "=", "rls_config", ",", "*", "*", "kwargs", ")", "for", "url", "in", "urls", ":", "session", ".", "mount", "(", "url", ",", "rl_adapter", ")" ]
Mount rate-limits adapters on the specified `requests.Session` object. :param py:class:`requests.Session` session: Session to mount. If not specified, then use the global `HTTP_SESSION`. :param dict rls_config: Rate-limits configuration. If not specified, then use the one defined at application level. :param kwargs: Additional keywords argument given to py:class:`docido_sdk.toolbox.rate_limits.RLRequestAdapter` constructor.
[ "Mount", "rate", "-", "limits", "adapters", "on", "the", "specified", "requests", ".", "Session", "object", "." ]
58ecb6c6f5757fd40c0601657ab18368da7ddf33
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/http_ext.py#L75-L102
247,316
ulf1/oxyba
oxyba/clean_add_strdec.py
clean_add_strdec
def clean_add_strdec(*args, prec=28): """add two columns that contain numbers as strings""" # load modules import pandas as pd import numpy as np import re from decimal import Decimal, getcontext getcontext().prec = prec # initialize result as 0.0 def proc_elem(*args): t = Decimal('0.0') for a in args: if isinstance(a, str): a = re.sub('[^0-9\.\-]+', '', a) if a and pd.notnull(a): t += Decimal(a) return str(t) def proc_list(arr): return [proc_elem(*row) for row in arr] def proc_ndarray(arr): return np.array(proc_list(arr)) # transform depending on provided datatypes if isinstance(args[0], (list, tuple)): return proc_list(args[0]) elif isinstance(args[0], np.ndarray): return proc_ndarray(args[0]) elif isinstance(args[0], pd.DataFrame): return pd.DataFrame(proc_ndarray(args[0].values), index=args[0].index) else: return proc_elem(*args)
python
def clean_add_strdec(*args, prec=28): """add two columns that contain numbers as strings""" # load modules import pandas as pd import numpy as np import re from decimal import Decimal, getcontext getcontext().prec = prec # initialize result as 0.0 def proc_elem(*args): t = Decimal('0.0') for a in args: if isinstance(a, str): a = re.sub('[^0-9\.\-]+', '', a) if a and pd.notnull(a): t += Decimal(a) return str(t) def proc_list(arr): return [proc_elem(*row) for row in arr] def proc_ndarray(arr): return np.array(proc_list(arr)) # transform depending on provided datatypes if isinstance(args[0], (list, tuple)): return proc_list(args[0]) elif isinstance(args[0], np.ndarray): return proc_ndarray(args[0]) elif isinstance(args[0], pd.DataFrame): return pd.DataFrame(proc_ndarray(args[0].values), index=args[0].index) else: return proc_elem(*args)
[ "def", "clean_add_strdec", "(", "*", "args", ",", "prec", "=", "28", ")", ":", "# load modules", "import", "pandas", "as", "pd", "import", "numpy", "as", "np", "import", "re", "from", "decimal", "import", "Decimal", ",", "getcontext", "getcontext", "(", ")", ".", "prec", "=", "prec", "# initialize result as 0.0", "def", "proc_elem", "(", "*", "args", ")", ":", "t", "=", "Decimal", "(", "'0.0'", ")", "for", "a", "in", "args", ":", "if", "isinstance", "(", "a", ",", "str", ")", ":", "a", "=", "re", ".", "sub", "(", "'[^0-9\\.\\-]+'", ",", "''", ",", "a", ")", "if", "a", "and", "pd", ".", "notnull", "(", "a", ")", ":", "t", "+=", "Decimal", "(", "a", ")", "return", "str", "(", "t", ")", "def", "proc_list", "(", "arr", ")", ":", "return", "[", "proc_elem", "(", "*", "row", ")", "for", "row", "in", "arr", "]", "def", "proc_ndarray", "(", "arr", ")", ":", "return", "np", ".", "array", "(", "proc_list", "(", "arr", ")", ")", "# transform depending on provided datatypes", "if", "isinstance", "(", "args", "[", "0", "]", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "proc_list", "(", "args", "[", "0", "]", ")", "elif", "isinstance", "(", "args", "[", "0", "]", ",", "np", ".", "ndarray", ")", ":", "return", "proc_ndarray", "(", "args", "[", "0", "]", ")", "elif", "isinstance", "(", "args", "[", "0", "]", ",", "pd", ".", "DataFrame", ")", ":", "return", "pd", ".", "DataFrame", "(", "proc_ndarray", "(", "args", "[", "0", "]", ".", "values", ")", ",", "index", "=", "args", "[", "0", "]", ".", "index", ")", "else", ":", "return", "proc_elem", "(", "*", "args", ")" ]
add two columns that contain numbers as strings
[ "add", "two", "columns", "that", "contain", "numbers", "as", "strings" ]
b3043116050de275124365cb11e7df91fb40169d
https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/clean_add_strdec.py#L2-L39
247,317
djtaylor/python-lsbinit
lsbinit/pid.py
_LSBPIDHandler._ps_extract_pid
def _ps_extract_pid(self, line): """ Extract PID and parent PID from an output line from the PS command """ this_pid = self.regex['pid'].sub(r'\g<1>', line) this_parent = self.regex['parent'].sub(r'\g<1>', line) # Return the main / parent PIDs return this_pid, this_parent
python
def _ps_extract_pid(self, line): """ Extract PID and parent PID from an output line from the PS command """ this_pid = self.regex['pid'].sub(r'\g<1>', line) this_parent = self.regex['parent'].sub(r'\g<1>', line) # Return the main / parent PIDs return this_pid, this_parent
[ "def", "_ps_extract_pid", "(", "self", ",", "line", ")", ":", "this_pid", "=", "self", ".", "regex", "[", "'pid'", "]", ".", "sub", "(", "r'\\g<1>'", ",", "line", ")", "this_parent", "=", "self", ".", "regex", "[", "'parent'", "]", ".", "sub", "(", "r'\\g<1>'", ",", "line", ")", "# Return the main / parent PIDs", "return", "this_pid", ",", "this_parent" ]
Extract PID and parent PID from an output line from the PS command
[ "Extract", "PID", "and", "parent", "PID", "from", "an", "output", "line", "from", "the", "PS", "command" ]
a41fc551226f61ac2bf1b8b0f3f5395db85e75a2
https://github.com/djtaylor/python-lsbinit/blob/a41fc551226f61ac2bf1b8b0f3f5395db85e75a2/lsbinit/pid.py#L33-L41
247,318
djtaylor/python-lsbinit
lsbinit/pid.py
_LSBPIDHandler.ps
def ps(self): """ Get the process information from the system PS command. """ # Get the process ID pid = self.get() # Parent / child processes parent = None children = [] # If the process is running if pid: proc = Popen(['ps', '-ef'], stdout=PIPE) for _line in proc.stdout.readlines(): line = self.unicode(_line.rstrip()) # Get the current PID / parent PID this_pid, this_parent = self._ps_extract_pid(line) try: # If scanning a child process if int(pid) == int(this_parent): children.append('{}; [{}]'.format(this_pid.rstrip(), re.sub(' +', ' ', line))) # If scanning the parent process if int(pid) == int(this_pid): parent = re.sub(' +', ' ', line) # Ignore value errors except ValueError: continue # Return the parent PID and any children processes return (parent, children)
python
def ps(self): """ Get the process information from the system PS command. """ # Get the process ID pid = self.get() # Parent / child processes parent = None children = [] # If the process is running if pid: proc = Popen(['ps', '-ef'], stdout=PIPE) for _line in proc.stdout.readlines(): line = self.unicode(_line.rstrip()) # Get the current PID / parent PID this_pid, this_parent = self._ps_extract_pid(line) try: # If scanning a child process if int(pid) == int(this_parent): children.append('{}; [{}]'.format(this_pid.rstrip(), re.sub(' +', ' ', line))) # If scanning the parent process if int(pid) == int(this_pid): parent = re.sub(' +', ' ', line) # Ignore value errors except ValueError: continue # Return the parent PID and any children processes return (parent, children)
[ "def", "ps", "(", "self", ")", ":", "# Get the process ID", "pid", "=", "self", ".", "get", "(", ")", "# Parent / child processes", "parent", "=", "None", "children", "=", "[", "]", "# If the process is running", "if", "pid", ":", "proc", "=", "Popen", "(", "[", "'ps'", ",", "'-ef'", "]", ",", "stdout", "=", "PIPE", ")", "for", "_line", "in", "proc", ".", "stdout", ".", "readlines", "(", ")", ":", "line", "=", "self", ".", "unicode", "(", "_line", ".", "rstrip", "(", ")", ")", "# Get the current PID / parent PID", "this_pid", ",", "this_parent", "=", "self", ".", "_ps_extract_pid", "(", "line", ")", "try", ":", "# If scanning a child process", "if", "int", "(", "pid", ")", "==", "int", "(", "this_parent", ")", ":", "children", ".", "append", "(", "'{}; [{}]'", ".", "format", "(", "this_pid", ".", "rstrip", "(", ")", ",", "re", ".", "sub", "(", "' +'", ",", "' '", ",", "line", ")", ")", ")", "# If scanning the parent process", "if", "int", "(", "pid", ")", "==", "int", "(", "this_pid", ")", ":", "parent", "=", "re", ".", "sub", "(", "' +'", ",", "' '", ",", "line", ")", "# Ignore value errors", "except", "ValueError", ":", "continue", "# Return the parent PID and any children processes", "return", "(", "parent", ",", "children", ")" ]
Get the process information from the system PS command.
[ "Get", "the", "process", "information", "from", "the", "system", "PS", "command", "." ]
a41fc551226f61ac2bf1b8b0f3f5395db85e75a2
https://github.com/djtaylor/python-lsbinit/blob/a41fc551226f61ac2bf1b8b0f3f5395db85e75a2/lsbinit/pid.py#L43-L78
247,319
djtaylor/python-lsbinit
lsbinit/pid.py
_LSBPIDHandler.age
def age(self): """ Get the age of the PID file. """ # Created timestamp created = self.created() # Age in seconds / minutes / hours / days age_secs = time() - created age_mins = 0 if (age_secs < 60) else (age_secs / 60) age_hours = 0 if (age_secs < 3600) else (age_mins / 60) age_days = 0 if (age_secs < 86400) else (age_hours / 24) # Return the age tuple return ( int(age_secs), int(age_mins), int(age_hours), int(age_days) )
python
def age(self): """ Get the age of the PID file. """ # Created timestamp created = self.created() # Age in seconds / minutes / hours / days age_secs = time() - created age_mins = 0 if (age_secs < 60) else (age_secs / 60) age_hours = 0 if (age_secs < 3600) else (age_mins / 60) age_days = 0 if (age_secs < 86400) else (age_hours / 24) # Return the age tuple return ( int(age_secs), int(age_mins), int(age_hours), int(age_days) )
[ "def", "age", "(", "self", ")", ":", "# Created timestamp", "created", "=", "self", ".", "created", "(", ")", "# Age in seconds / minutes / hours / days", "age_secs", "=", "time", "(", ")", "-", "created", "age_mins", "=", "0", "if", "(", "age_secs", "<", "60", ")", "else", "(", "age_secs", "/", "60", ")", "age_hours", "=", "0", "if", "(", "age_secs", "<", "3600", ")", "else", "(", "age_mins", "/", "60", ")", "age_days", "=", "0", "if", "(", "age_secs", "<", "86400", ")", "else", "(", "age_hours", "/", "24", ")", "# Return the age tuple", "return", "(", "int", "(", "age_secs", ")", ",", "int", "(", "age_mins", ")", ",", "int", "(", "age_hours", ")", ",", "int", "(", "age_days", ")", ")" ]
Get the age of the PID file.
[ "Get", "the", "age", "of", "the", "PID", "file", "." ]
a41fc551226f61ac2bf1b8b0f3f5395db85e75a2
https://github.com/djtaylor/python-lsbinit/blob/a41fc551226f61ac2bf1b8b0f3f5395db85e75a2/lsbinit/pid.py#L86-L106
247,320
djtaylor/python-lsbinit
lsbinit/pid.py
_LSBPIDHandler.birthday
def birthday(self): """ Return a string representing the age of the process. """ if isfile(self.pid_file): # Timestamp / timezone string tstamp = datetime.fromtimestamp(self.created()) tzone = tzname[0] weekday = WEEKDAY[tstamp.isoweekday()] # PID file age / age string age = self.age() age_str = '{}s ago'.format(age[0]) # Birthday string bday = '{} {} {}; {}'.format(weekday, tstamp, tzone, age_str) # Return timestamp / timestamp string return (self.created(), bday) return (None, None)
python
def birthday(self): """ Return a string representing the age of the process. """ if isfile(self.pid_file): # Timestamp / timezone string tstamp = datetime.fromtimestamp(self.created()) tzone = tzname[0] weekday = WEEKDAY[tstamp.isoweekday()] # PID file age / age string age = self.age() age_str = '{}s ago'.format(age[0]) # Birthday string bday = '{} {} {}; {}'.format(weekday, tstamp, tzone, age_str) # Return timestamp / timestamp string return (self.created(), bday) return (None, None)
[ "def", "birthday", "(", "self", ")", ":", "if", "isfile", "(", "self", ".", "pid_file", ")", ":", "# Timestamp / timezone string", "tstamp", "=", "datetime", ".", "fromtimestamp", "(", "self", ".", "created", "(", ")", ")", "tzone", "=", "tzname", "[", "0", "]", "weekday", "=", "WEEKDAY", "[", "tstamp", ".", "isoweekday", "(", ")", "]", "# PID file age / age string", "age", "=", "self", ".", "age", "(", ")", "age_str", "=", "'{}s ago'", ".", "format", "(", "age", "[", "0", "]", ")", "# Birthday string", "bday", "=", "'{} {} {}; {}'", ".", "format", "(", "weekday", ",", "tstamp", ",", "tzone", ",", "age_str", ")", "# Return timestamp / timestamp string", "return", "(", "self", ".", "created", "(", ")", ",", "bday", ")", "return", "(", "None", ",", "None", ")" ]
Return a string representing the age of the process.
[ "Return", "a", "string", "representing", "the", "age", "of", "the", "process", "." ]
a41fc551226f61ac2bf1b8b0f3f5395db85e75a2
https://github.com/djtaylor/python-lsbinit/blob/a41fc551226f61ac2bf1b8b0f3f5395db85e75a2/lsbinit/pid.py#L108-L128
247,321
djtaylor/python-lsbinit
lsbinit/pid.py
_LSBPIDHandler.make
def make(self, pnum): """ Make a PID file and populate with PID number. """ try: # Create the PID file self.mkfile(self.pid_file, pnum) except Exception as e: self.die('Failed to generate PID file: {}'.format(str(e)))
python
def make(self, pnum): """ Make a PID file and populate with PID number. """ try: # Create the PID file self.mkfile(self.pid_file, pnum) except Exception as e: self.die('Failed to generate PID file: {}'.format(str(e)))
[ "def", "make", "(", "self", ",", "pnum", ")", ":", "try", ":", "# Create the PID file", "self", ".", "mkfile", "(", "self", ".", "pid_file", ",", "pnum", ")", "except", "Exception", "as", "e", ":", "self", ".", "die", "(", "'Failed to generate PID file: {}'", ".", "format", "(", "str", "(", "e", ")", ")", ")" ]
Make a PID file and populate with PID number.
[ "Make", "a", "PID", "file", "and", "populate", "with", "PID", "number", "." ]
a41fc551226f61ac2bf1b8b0f3f5395db85e75a2
https://github.com/djtaylor/python-lsbinit/blob/a41fc551226f61ac2bf1b8b0f3f5395db85e75a2/lsbinit/pid.py#L138-L147
247,322
djtaylor/python-lsbinit
lsbinit/pid.py
_LSBPIDHandler.remove
def remove(self): """ Remove the PID file. """ if isfile(self.pid_file): try: remove(self.pid_file) except Exception as e: self.die('Failed to remove PID file: {}'.format(str(e))) else: return True
python
def remove(self): """ Remove the PID file. """ if isfile(self.pid_file): try: remove(self.pid_file) except Exception as e: self.die('Failed to remove PID file: {}'.format(str(e))) else: return True
[ "def", "remove", "(", "self", ")", ":", "if", "isfile", "(", "self", ".", "pid_file", ")", ":", "try", ":", "remove", "(", "self", ".", "pid_file", ")", "except", "Exception", "as", "e", ":", "self", ".", "die", "(", "'Failed to remove PID file: {}'", ".", "format", "(", "str", "(", "e", ")", ")", ")", "else", ":", "return", "True" ]
Remove the PID file.
[ "Remove", "the", "PID", "file", "." ]
a41fc551226f61ac2bf1b8b0f3f5395db85e75a2
https://github.com/djtaylor/python-lsbinit/blob/a41fc551226f61ac2bf1b8b0f3f5395db85e75a2/lsbinit/pid.py#L149-L159
247,323
ploneintranet/ploneintranet.workspace
src/ploneintranet/workspace/browser/views.py
SharingView.role_settings
def role_settings(self): """ Filter out unwanted to show groups """ result = super(SharingView, self).role_settings() uid = self.context.UID() filter_func = lambda x: not any(( x["id"].endswith(uid), x["id"] == "AuthenticatedUsers", x["id"] == INTRANET_USERS_GROUP_ID, )) return filter(filter_func, result)
python
def role_settings(self): """ Filter out unwanted to show groups """ result = super(SharingView, self).role_settings() uid = self.context.UID() filter_func = lambda x: not any(( x["id"].endswith(uid), x["id"] == "AuthenticatedUsers", x["id"] == INTRANET_USERS_GROUP_ID, )) return filter(filter_func, result)
[ "def", "role_settings", "(", "self", ")", ":", "result", "=", "super", "(", "SharingView", ",", "self", ")", ".", "role_settings", "(", ")", "uid", "=", "self", ".", "context", ".", "UID", "(", ")", "filter_func", "=", "lambda", "x", ":", "not", "any", "(", "(", "x", "[", "\"id\"", "]", ".", "endswith", "(", "uid", ")", ",", "x", "[", "\"id\"", "]", "==", "\"AuthenticatedUsers\"", ",", "x", "[", "\"id\"", "]", "==", "INTRANET_USERS_GROUP_ID", ",", ")", ")", "return", "filter", "(", "filter_func", ",", "result", ")" ]
Filter out unwanted to show groups
[ "Filter", "out", "unwanted", "to", "show", "groups" ]
a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba
https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/browser/views.py#L47-L56
247,324
hirokiky/uiro
uiro/db.py
initdb
def initdb(config): """ Initializing database settings by using config from .ini file. """ engine = sa.engine_from_config(config, 'sqlalchemy.') Session.configure(bind=engine)
python
def initdb(config): """ Initializing database settings by using config from .ini file. """ engine = sa.engine_from_config(config, 'sqlalchemy.') Session.configure(bind=engine)
[ "def", "initdb", "(", "config", ")", ":", "engine", "=", "sa", ".", "engine_from_config", "(", "config", ",", "'sqlalchemy.'", ")", "Session", ".", "configure", "(", "bind", "=", "engine", ")" ]
Initializing database settings by using config from .ini file.
[ "Initializing", "database", "settings", "by", "using", "config", "from", ".", "ini", "file", "." ]
8436976b21ac9b0eac4243768f5ada12479b9e00
https://github.com/hirokiky/uiro/blob/8436976b21ac9b0eac4243768f5ada12479b9e00/uiro/db.py#L13-L17
247,325
jamieleshaw/lurklib
example.py
HelloBot.on_chanmsg
def on_chanmsg(self, from_, channel, message): """ Event handler for channel messages. """ if message == 'hello': self.privmsg(channel, 'Hello, %s!' % from_[0]) print('%s said hello!' % from_[0]) elif message == '!quit': self.quit('Bye!')
python
def on_chanmsg(self, from_, channel, message): """ Event handler for channel messages. """ if message == 'hello': self.privmsg(channel, 'Hello, %s!' % from_[0]) print('%s said hello!' % from_[0]) elif message == '!quit': self.quit('Bye!')
[ "def", "on_chanmsg", "(", "self", ",", "from_", ",", "channel", ",", "message", ")", ":", "if", "message", "==", "'hello'", ":", "self", ".", "privmsg", "(", "channel", ",", "'Hello, %s!'", "%", "from_", "[", "0", "]", ")", "print", "(", "'%s said hello!'", "%", "from_", "[", "0", "]", ")", "elif", "message", "==", "'!quit'", ":", "self", ".", "quit", "(", "'Bye!'", ")" ]
Event handler for channel messages.
[ "Event", "handler", "for", "channel", "messages", "." ]
a861f35d880140422103dd78ec3239814e85fd7e
https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/example.py#L30-L36
247,326
nir0s/serv
setup.py
_get_package_data
def _get_package_data(): """Iterate over the `init` dir for directories and returns all files within them. Only files within `binaries` and `templates` will be added. """ from os import listdir as ls from os.path import join as jn x = 'init' b = jn('serv', x) dr = ['binaries', 'templates'] return [jn(x, d, f) for d in ls(b) if d in dr for f in ls(jn(b, d))]
python
def _get_package_data(): """Iterate over the `init` dir for directories and returns all files within them. Only files within `binaries` and `templates` will be added. """ from os import listdir as ls from os.path import join as jn x = 'init' b = jn('serv', x) dr = ['binaries', 'templates'] return [jn(x, d, f) for d in ls(b) if d in dr for f in ls(jn(b, d))]
[ "def", "_get_package_data", "(", ")", ":", "from", "os", "import", "listdir", "as", "ls", "from", "os", ".", "path", "import", "join", "as", "jn", "x", "=", "'init'", "b", "=", "jn", "(", "'serv'", ",", "x", ")", "dr", "=", "[", "'binaries'", ",", "'templates'", "]", "return", "[", "jn", "(", "x", ",", "d", ",", "f", ")", "for", "d", "in", "ls", "(", "b", ")", "if", "d", "in", "dr", "for", "f", "in", "ls", "(", "jn", "(", "b", ",", "d", ")", ")", "]" ]
Iterate over the `init` dir for directories and returns all files within them. Only files within `binaries` and `templates` will be added.
[ "Iterate", "over", "the", "init", "dir", "for", "directories", "and", "returns", "all", "files", "within", "them", "." ]
7af724ed49c0eb766c37c4b5287b043a8cf99e9c
https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/setup.py#L12-L24
247,327
minhhoit/yacms
yacms/utils/importing.py
path_for_import
def path_for_import(name): """ Returns the directory path for the given package or module. """ return os.path.dirname(os.path.abspath(import_module(name).__file__))
python
def path_for_import(name): """ Returns the directory path for the given package or module. """ return os.path.dirname(os.path.abspath(import_module(name).__file__))
[ "def", "path_for_import", "(", "name", ")", ":", "return", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "import_module", "(", "name", ")", ".", "__file__", ")", ")" ]
Returns the directory path for the given package or module.
[ "Returns", "the", "directory", "path", "for", "the", "given", "package", "or", "module", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/importing.py#L9-L13
247,328
roaet/wafflehaus.neutron
wafflehaus/neutron/nova_interaction/common.py
BaseConnection._make_the_call
def _make_the_call(self, method, url, body=None): """Note that a request response is being used here, not webob.""" self.log.debug("%s call to %s with body = %s" % (method, url, body)) params = {"url": url, "headers": self.headers, "verify": self.verify} if body is not None: params["data"] = body func = getattr(requests, method.lower()) try: resp = func(**params) except Exception as e: self.log.error("Call to %s failed with %s, %s" % (url, repr(e), e.message)) return None, e else: self.log.debug("Call to %s returned with status %s and body " "%s" % (url, resp.status, resp.text)) return resp.status_code, resp.json()
python
def _make_the_call(self, method, url, body=None): """Note that a request response is being used here, not webob.""" self.log.debug("%s call to %s with body = %s" % (method, url, body)) params = {"url": url, "headers": self.headers, "verify": self.verify} if body is not None: params["data"] = body func = getattr(requests, method.lower()) try: resp = func(**params) except Exception as e: self.log.error("Call to %s failed with %s, %s" % (url, repr(e), e.message)) return None, e else: self.log.debug("Call to %s returned with status %s and body " "%s" % (url, resp.status, resp.text)) return resp.status_code, resp.json()
[ "def", "_make_the_call", "(", "self", ",", "method", ",", "url", ",", "body", "=", "None", ")", ":", "self", ".", "log", ".", "debug", "(", "\"%s call to %s with body = %s\"", "%", "(", "method", ",", "url", ",", "body", ")", ")", "params", "=", "{", "\"url\"", ":", "url", ",", "\"headers\"", ":", "self", ".", "headers", ",", "\"verify\"", ":", "self", ".", "verify", "}", "if", "body", "is", "not", "None", ":", "params", "[", "\"data\"", "]", "=", "body", "func", "=", "getattr", "(", "requests", ",", "method", ".", "lower", "(", ")", ")", "try", ":", "resp", "=", "func", "(", "*", "*", "params", ")", "except", "Exception", "as", "e", ":", "self", ".", "log", ".", "error", "(", "\"Call to %s failed with %s, %s\"", "%", "(", "url", ",", "repr", "(", "e", ")", ",", "e", ".", "message", ")", ")", "return", "None", ",", "e", "else", ":", "self", ".", "log", ".", "debug", "(", "\"Call to %s returned with status %s and body \"", "\"%s\"", "%", "(", "url", ",", "resp", ".", "status", ",", "resp", ".", "text", ")", ")", "return", "resp", ".", "status_code", ",", "resp", ".", "json", "(", ")" ]
Note that a request response is being used here, not webob.
[ "Note", "that", "a", "request", "response", "is", "being", "used", "here", "not", "webob", "." ]
01f6d69ae759ec2f24f2f7cf9dcfa4a4734f7e1c
https://github.com/roaet/wafflehaus.neutron/blob/01f6d69ae759ec2f24f2f7cf9dcfa4a4734f7e1c/wafflehaus/neutron/nova_interaction/common.py#L34-L50
247,329
KnowledgeLinks/rdfframework
rdfframework/utilities/formattingfunctions.py
reduce_multiline
def reduce_multiline(string): """ reduces a multiline string to a single line of text. args: string: the text to reduce """ string = str(string) return " ".join([item.strip() for item in string.split("\n") if item.strip()])
python
def reduce_multiline(string): """ reduces a multiline string to a single line of text. args: string: the text to reduce """ string = str(string) return " ".join([item.strip() for item in string.split("\n") if item.strip()])
[ "def", "reduce_multiline", "(", "string", ")", ":", "string", "=", "str", "(", "string", ")", "return", "\" \"", ".", "join", "(", "[", "item", ".", "strip", "(", ")", "for", "item", "in", "string", ".", "split", "(", "\"\\n\"", ")", "if", "item", ".", "strip", "(", ")", "]", ")" ]
reduces a multiline string to a single line of text. args: string: the text to reduce
[ "reduces", "a", "multiline", "string", "to", "a", "single", "line", "of", "text", "." ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/formattingfunctions.py#L166-L177
247,330
KnowledgeLinks/rdfframework
rdfframework/utilities/formattingfunctions.py
format_max_width
def format_max_width(text, max_width=None, **kwargs): """ Takes a string and formats it to a max width seperated by carriage returns args: max_width: the max with for a line kwargs: indent: the number of spaces to add to the start of each line prepend: text to add to the start of each line """ ind = '' if kwargs.get("indent"): ind = ''.ljust(kwargs['indent'], ' ') prepend = ind + kwargs.get("prepend", "") if not max_width: return "{}{}".format(prepend, text) len_pre = len(kwargs.get("prepend", "")) + kwargs.get("indent", 0) test_words = text.split(" ") word_limit = max_width - len_pre if word_limit < 3: word_limit = 3 max_width = len_pre + word_limit words = [] for word in test_words: if len(word) + len_pre > max_width: n = max_width - len_pre words += [word[i:i + word_limit] for i in range(0, len(word), word_limit)] else: words.append(word) idx = 0 lines = [] idx_limit = len(words) - 1 sub_idx_limit = idx_limit while idx < idx_limit: current_len = len_pre line = prepend for i, word in enumerate(words[idx:]): if (current_len + len(word)) == max_width and line == prepend: idx += i or 1 line += word lines.append(line) if idx == idx_limit: idx -= 1 sub_idx_limit -= 1 del words[0] break if (current_len + len(word) + 1) > max_width: idx += i if idx == idx_limit: idx -= 1 sub_idx_limit -= 1 del words[0] if idx == 0: del words[0] lines.append(line) break if (i + idx) == sub_idx_limit: idx += i or 1 if line != prepend: line = " ".join([line, word]) elif word: line += word lines.append(line) else: if line != prepend: line = " ".join([line, word]) elif word: line += word current_len = len(line) return "\n".join(lines)
python
def format_max_width(text, max_width=None, **kwargs): """ Takes a string and formats it to a max width seperated by carriage returns args: max_width: the max with for a line kwargs: indent: the number of spaces to add to the start of each line prepend: text to add to the start of each line """ ind = '' if kwargs.get("indent"): ind = ''.ljust(kwargs['indent'], ' ') prepend = ind + kwargs.get("prepend", "") if not max_width: return "{}{}".format(prepend, text) len_pre = len(kwargs.get("prepend", "")) + kwargs.get("indent", 0) test_words = text.split(" ") word_limit = max_width - len_pre if word_limit < 3: word_limit = 3 max_width = len_pre + word_limit words = [] for word in test_words: if len(word) + len_pre > max_width: n = max_width - len_pre words += [word[i:i + word_limit] for i in range(0, len(word), word_limit)] else: words.append(word) idx = 0 lines = [] idx_limit = len(words) - 1 sub_idx_limit = idx_limit while idx < idx_limit: current_len = len_pre line = prepend for i, word in enumerate(words[idx:]): if (current_len + len(word)) == max_width and line == prepend: idx += i or 1 line += word lines.append(line) if idx == idx_limit: idx -= 1 sub_idx_limit -= 1 del words[0] break if (current_len + len(word) + 1) > max_width: idx += i if idx == idx_limit: idx -= 1 sub_idx_limit -= 1 del words[0] if idx == 0: del words[0] lines.append(line) break if (i + idx) == sub_idx_limit: idx += i or 1 if line != prepend: line = " ".join([line, word]) elif word: line += word lines.append(line) else: if line != prepend: line = " ".join([line, word]) elif word: line += word current_len = len(line) return "\n".join(lines)
[ "def", "format_max_width", "(", "text", ",", "max_width", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ind", "=", "''", "if", "kwargs", ".", "get", "(", "\"indent\"", ")", ":", "ind", "=", "''", ".", "ljust", "(", "kwargs", "[", "'indent'", "]", ",", "' '", ")", "prepend", "=", "ind", "+", "kwargs", ".", "get", "(", "\"prepend\"", ",", "\"\"", ")", "if", "not", "max_width", ":", "return", "\"{}{}\"", ".", "format", "(", "prepend", ",", "text", ")", "len_pre", "=", "len", "(", "kwargs", ".", "get", "(", "\"prepend\"", ",", "\"\"", ")", ")", "+", "kwargs", ".", "get", "(", "\"indent\"", ",", "0", ")", "test_words", "=", "text", ".", "split", "(", "\" \"", ")", "word_limit", "=", "max_width", "-", "len_pre", "if", "word_limit", "<", "3", ":", "word_limit", "=", "3", "max_width", "=", "len_pre", "+", "word_limit", "words", "=", "[", "]", "for", "word", "in", "test_words", ":", "if", "len", "(", "word", ")", "+", "len_pre", ">", "max_width", ":", "n", "=", "max_width", "-", "len_pre", "words", "+=", "[", "word", "[", "i", ":", "i", "+", "word_limit", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "word", ")", ",", "word_limit", ")", "]", "else", ":", "words", ".", "append", "(", "word", ")", "idx", "=", "0", "lines", "=", "[", "]", "idx_limit", "=", "len", "(", "words", ")", "-", "1", "sub_idx_limit", "=", "idx_limit", "while", "idx", "<", "idx_limit", ":", "current_len", "=", "len_pre", "line", "=", "prepend", "for", "i", ",", "word", "in", "enumerate", "(", "words", "[", "idx", ":", "]", ")", ":", "if", "(", "current_len", "+", "len", "(", "word", ")", ")", "==", "max_width", "and", "line", "==", "prepend", ":", "idx", "+=", "i", "or", "1", "line", "+=", "word", "lines", ".", "append", "(", "line", ")", "if", "idx", "==", "idx_limit", ":", "idx", "-=", "1", "sub_idx_limit", "-=", "1", "del", "words", "[", "0", "]", "break", "if", "(", "current_len", "+", "len", "(", "word", ")", "+", "1", ")", ">", "max_width", ":", "idx", "+=", "i", "if", "idx", "==", "idx_limit", ":", "idx", "-=", "1", "sub_idx_limit", "-=", "1", "del", "words", "[", "0", "]", "if", "idx", "==", "0", ":", "del", "words", "[", "0", "]", "lines", ".", "append", "(", "line", ")", "break", "if", "(", "i", "+", "idx", ")", "==", "sub_idx_limit", ":", "idx", "+=", "i", "or", "1", "if", "line", "!=", "prepend", ":", "line", "=", "\" \"", ".", "join", "(", "[", "line", ",", "word", "]", ")", "elif", "word", ":", "line", "+=", "word", "lines", ".", "append", "(", "line", ")", "else", ":", "if", "line", "!=", "prepend", ":", "line", "=", "\" \"", ".", "join", "(", "[", "line", ",", "word", "]", ")", "elif", "word", ":", "line", "+=", "word", "current_len", "=", "len", "(", "line", ")", "return", "\"\\n\"", ".", "join", "(", "lines", ")" ]
Takes a string and formats it to a max width seperated by carriage returns args: max_width: the max with for a line kwargs: indent: the number of spaces to add to the start of each line prepend: text to add to the start of each line
[ "Takes", "a", "string", "and", "formats", "it", "to", "a", "max", "width", "seperated", "by", "carriage", "returns" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/formattingfunctions.py#L224-L298
247,331
jut-io/jut-python-tools
jut/api/environment.py
get_details
def get_details(app_url=defaults.APP_URL): """ returns environment details for the app url specified """ url = '%s/environment' % app_url response = requests.get(url) if response.status_code == 200: return response.json() else: raise JutException('Unable to retrieve environment details from %s, got %s: %s' % (url, response.status_code, response.text))
python
def get_details(app_url=defaults.APP_URL): """ returns environment details for the app url specified """ url = '%s/environment' % app_url response = requests.get(url) if response.status_code == 200: return response.json() else: raise JutException('Unable to retrieve environment details from %s, got %s: %s' % (url, response.status_code, response.text))
[ "def", "get_details", "(", "app_url", "=", "defaults", ".", "APP_URL", ")", ":", "url", "=", "'%s/environment'", "%", "app_url", "response", "=", "requests", ".", "get", "(", "url", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "response", ".", "json", "(", ")", "else", ":", "raise", "JutException", "(", "'Unable to retrieve environment details from %s, got %s: %s'", "%", "(", "url", ",", "response", ".", "status_code", ",", "response", ".", "text", ")", ")" ]
returns environment details for the app url specified
[ "returns", "environment", "details", "for", "the", "app", "url", "specified" ]
65574d23f51a7bbced9bb25010d02da5ca5d906f
https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/api/environment.py#L14-L26
247,332
radjkarl/appBase
appbase/dialogs/FirstStart.py
FirstStart.accept
def accept(self, evt): """ write setting to the preferences """ # determine if application is a script file or frozen exe (pyinstaller) frozen = getattr(sys, 'frozen', False) if frozen: app_file = sys.executable else: app_file = PathStr(__main__.__file__).abspath() if self.cb_startmenu.isChecked(): # TODO: allow only logo location # icon = app_file.dirname().join('media', 'logo.ico') StartMenuEntry(self.name, app_file, icon=self.icon, console=False).create() if self.cb_mime.isChecked(): # get admin rights if not isAdmin(): try: # run this file as __main__ with admin rights: if frozen: cmd = "from %s import embeddIntoOS\nembeddIntoOS('%s', '%s', '%s')" % ( __name__, '', self.ftype, self.name) # in this case there is no python.exe and no moduly.py to call # thats why we have to import the method and execute it runAsAdmin((sys.executable, '-exec', cmd)) else: runAsAdmin((sys.executable, __file__, app_file, self.ftype, self.name)) except: print('needs admin rights to work') else: embeddIntoOS(app_file, self.ftype, self.name) QtWidgets.QDialog.accept(self)
python
def accept(self, evt): """ write setting to the preferences """ # determine if application is a script file or frozen exe (pyinstaller) frozen = getattr(sys, 'frozen', False) if frozen: app_file = sys.executable else: app_file = PathStr(__main__.__file__).abspath() if self.cb_startmenu.isChecked(): # TODO: allow only logo location # icon = app_file.dirname().join('media', 'logo.ico') StartMenuEntry(self.name, app_file, icon=self.icon, console=False).create() if self.cb_mime.isChecked(): # get admin rights if not isAdmin(): try: # run this file as __main__ with admin rights: if frozen: cmd = "from %s import embeddIntoOS\nembeddIntoOS('%s', '%s', '%s')" % ( __name__, '', self.ftype, self.name) # in this case there is no python.exe and no moduly.py to call # thats why we have to import the method and execute it runAsAdmin((sys.executable, '-exec', cmd)) else: runAsAdmin((sys.executable, __file__, app_file, self.ftype, self.name)) except: print('needs admin rights to work') else: embeddIntoOS(app_file, self.ftype, self.name) QtWidgets.QDialog.accept(self)
[ "def", "accept", "(", "self", ",", "evt", ")", ":", "# determine if application is a script file or frozen exe (pyinstaller)\r", "frozen", "=", "getattr", "(", "sys", ",", "'frozen'", ",", "False", ")", "if", "frozen", ":", "app_file", "=", "sys", ".", "executable", "else", ":", "app_file", "=", "PathStr", "(", "__main__", ".", "__file__", ")", ".", "abspath", "(", ")", "if", "self", ".", "cb_startmenu", ".", "isChecked", "(", ")", ":", "# TODO: allow only logo location\r", "# icon = app_file.dirname().join('media', 'logo.ico')\r", "StartMenuEntry", "(", "self", ".", "name", ",", "app_file", ",", "icon", "=", "self", ".", "icon", ",", "console", "=", "False", ")", ".", "create", "(", ")", "if", "self", ".", "cb_mime", ".", "isChecked", "(", ")", ":", "# get admin rights\r", "if", "not", "isAdmin", "(", ")", ":", "try", ":", "# run this file as __main__ with admin rights:\r", "if", "frozen", ":", "cmd", "=", "\"from %s import embeddIntoOS\\nembeddIntoOS('%s', '%s', '%s')\"", "%", "(", "__name__", ",", "''", ",", "self", ".", "ftype", ",", "self", ".", "name", ")", "# in this case there is no python.exe and no moduly.py to call\r", "# thats why we have to import the method and execute it\r", "runAsAdmin", "(", "(", "sys", ".", "executable", ",", "'-exec'", ",", "cmd", ")", ")", "else", ":", "runAsAdmin", "(", "(", "sys", ".", "executable", ",", "__file__", ",", "app_file", ",", "self", ".", "ftype", ",", "self", ".", "name", ")", ")", "except", ":", "print", "(", "'needs admin rights to work'", ")", "else", ":", "embeddIntoOS", "(", "app_file", ",", "self", ".", "ftype", ",", "self", ".", "name", ")", "QtWidgets", ".", "QDialog", ".", "accept", "(", "self", ")" ]
write setting to the preferences
[ "write", "setting", "to", "the", "preferences" ]
72b514e6dee7c083f01a2d0b2cc93d46df55bdcb
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/dialogs/FirstStart.py#L56-L92
247,333
openbermuda/ripl
ripl/md2slides.py
Mark2Slide.build_row
def build_row(self, line): """ Line describes an image or images to show Returns a dict with a list of dicts of image names or text items Examples: # A single image to display >>> x.build_row('foo.png') [{'image': 'foo.png'}] # Two images with text in between: >>> x.build_row('foo.png or bar.jpg') [{'image': 'foo.png'}, {'text': 'or'}, {'image': 'bar.png'}] """ items = [] row = dict(items=items) fields = line.split(' ') image_exts = ['.png', '.jpg'] # nothing there, carry on if not fields: return row for field in fields: ext = os.path.splitext(field)[-1] if ext.lower() in image_exts: items.append( dict(image=field)) else: items.append( dict(text=field)) return row
python
def build_row(self, line): """ Line describes an image or images to show Returns a dict with a list of dicts of image names or text items Examples: # A single image to display >>> x.build_row('foo.png') [{'image': 'foo.png'}] # Two images with text in between: >>> x.build_row('foo.png or bar.jpg') [{'image': 'foo.png'}, {'text': 'or'}, {'image': 'bar.png'}] """ items = [] row = dict(items=items) fields = line.split(' ') image_exts = ['.png', '.jpg'] # nothing there, carry on if not fields: return row for field in fields: ext = os.path.splitext(field)[-1] if ext.lower() in image_exts: items.append( dict(image=field)) else: items.append( dict(text=field)) return row
[ "def", "build_row", "(", "self", ",", "line", ")", ":", "items", "=", "[", "]", "row", "=", "dict", "(", "items", "=", "items", ")", "fields", "=", "line", ".", "split", "(", "' '", ")", "image_exts", "=", "[", "'.png'", ",", "'.jpg'", "]", "# nothing there, carry on", "if", "not", "fields", ":", "return", "row", "for", "field", "in", "fields", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "field", ")", "[", "-", "1", "]", "if", "ext", ".", "lower", "(", ")", "in", "image_exts", ":", "items", ".", "append", "(", "dict", "(", "image", "=", "field", ")", ")", "else", ":", "items", ".", "append", "(", "dict", "(", "text", "=", "field", ")", ")", "return", "row" ]
Line describes an image or images to show Returns a dict with a list of dicts of image names or text items Examples: # A single image to display >>> x.build_row('foo.png') [{'image': 'foo.png'}] # Two images with text in between: >>> x.build_row('foo.png or bar.jpg') [{'image': 'foo.png'}, {'text': 'or'}, {'image': 'bar.png'}]
[ "Line", "describes", "an", "image", "or", "images", "to", "show" ]
4886b1a697e4b81c2202db9cb977609e034f8e70
https://github.com/openbermuda/ripl/blob/4886b1a697e4b81c2202db9cb977609e034f8e70/ripl/md2slides.py#L114-L152
247,334
sternoru/goscalecms
goscale/models.py
Post.dict
def dict(self): """ Returns dictionary of post fields and attributes """ post_dict = { 'id': self.id, 'link': self.link, 'permalink': self.permalink, 'content_type': self.content_type, 'slug': self.slug, 'updated': self.updated, #.strftime(conf.GOSCALE_ATOM_DATETIME_FORMAT), 'published': self.published, #.strftime(conf.GOSCALE_ATOM_DATETIME_FORMAT), 'title': self.title, 'description': self.description, 'author': self.author, 'categories': self.categories[1:-1].split(',') if self.categories else None, 'summary': self.summary, } if self.attributes: attributes = simplejson.loads(self.attributes) post_dict.update(attributes) return post_dict
python
def dict(self): """ Returns dictionary of post fields and attributes """ post_dict = { 'id': self.id, 'link': self.link, 'permalink': self.permalink, 'content_type': self.content_type, 'slug': self.slug, 'updated': self.updated, #.strftime(conf.GOSCALE_ATOM_DATETIME_FORMAT), 'published': self.published, #.strftime(conf.GOSCALE_ATOM_DATETIME_FORMAT), 'title': self.title, 'description': self.description, 'author': self.author, 'categories': self.categories[1:-1].split(',') if self.categories else None, 'summary': self.summary, } if self.attributes: attributes = simplejson.loads(self.attributes) post_dict.update(attributes) return post_dict
[ "def", "dict", "(", "self", ")", ":", "post_dict", "=", "{", "'id'", ":", "self", ".", "id", ",", "'link'", ":", "self", ".", "link", ",", "'permalink'", ":", "self", ".", "permalink", ",", "'content_type'", ":", "self", ".", "content_type", ",", "'slug'", ":", "self", ".", "slug", ",", "'updated'", ":", "self", ".", "updated", ",", "#.strftime(conf.GOSCALE_ATOM_DATETIME_FORMAT),", "'published'", ":", "self", ".", "published", ",", "#.strftime(conf.GOSCALE_ATOM_DATETIME_FORMAT),", "'title'", ":", "self", ".", "title", ",", "'description'", ":", "self", ".", "description", ",", "'author'", ":", "self", ".", "author", ",", "'categories'", ":", "self", ".", "categories", "[", "1", ":", "-", "1", "]", ".", "split", "(", "','", ")", "if", "self", ".", "categories", "else", "None", ",", "'summary'", ":", "self", ".", "summary", ",", "}", "if", "self", ".", "attributes", ":", "attributes", "=", "simplejson", ".", "loads", "(", "self", ".", "attributes", ")", "post_dict", ".", "update", "(", "attributes", ")", "return", "post_dict" ]
Returns dictionary of post fields and attributes
[ "Returns", "dictionary", "of", "post", "fields", "and", "attributes" ]
7eee50357c47ebdfe3e573a8b4be3b67892d229e
https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/models.py#L66-L86
247,335
sternoru/goscalecms
goscale/models.py
Post.json
def json(self, dict=None, indent=None): """ Returns post JSON representation """ if not dict: dict = self.dict() for key, value in dict.iteritems(): if type(value) == datetime.datetime: dict[key] = value.strftime(conf.GOSCALE_ATOM_DATETIME_FORMAT) return simplejson.dumps(dict, indent=indent)
python
def json(self, dict=None, indent=None): """ Returns post JSON representation """ if not dict: dict = self.dict() for key, value in dict.iteritems(): if type(value) == datetime.datetime: dict[key] = value.strftime(conf.GOSCALE_ATOM_DATETIME_FORMAT) return simplejson.dumps(dict, indent=indent)
[ "def", "json", "(", "self", ",", "dict", "=", "None", ",", "indent", "=", "None", ")", ":", "if", "not", "dict", ":", "dict", "=", "self", ".", "dict", "(", ")", "for", "key", ",", "value", "in", "dict", ".", "iteritems", "(", ")", ":", "if", "type", "(", "value", ")", "==", "datetime", ".", "datetime", ":", "dict", "[", "key", "]", "=", "value", ".", "strftime", "(", "conf", ".", "GOSCALE_ATOM_DATETIME_FORMAT", ")", "return", "simplejson", ".", "dumps", "(", "dict", ",", "indent", "=", "indent", ")" ]
Returns post JSON representation
[ "Returns", "post", "JSON", "representation" ]
7eee50357c47ebdfe3e573a8b4be3b67892d229e
https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/models.py#L88-L96
247,336
sternoru/goscalecms
goscale/models.py
GoscaleCMSPlugin.get_cache_key
def get_cache_key(self, offset=0, limit=0, order=None, post_slug=''): """ The return of Get """ return hashlib.sha1( '.'.join([ str(self._get_data_source_url()), str(offset), str(limit), str(order), str(post_slug), ]) ).hexdigest()
python
def get_cache_key(self, offset=0, limit=0, order=None, post_slug=''): """ The return of Get """ return hashlib.sha1( '.'.join([ str(self._get_data_source_url()), str(offset), str(limit), str(order), str(post_slug), ]) ).hexdigest()
[ "def", "get_cache_key", "(", "self", ",", "offset", "=", "0", ",", "limit", "=", "0", ",", "order", "=", "None", ",", "post_slug", "=", "''", ")", ":", "return", "hashlib", ".", "sha1", "(", "'.'", ".", "join", "(", "[", "str", "(", "self", ".", "_get_data_source_url", "(", ")", ")", ",", "str", "(", "offset", ")", ",", "str", "(", "limit", ")", ",", "str", "(", "order", ")", ",", "str", "(", "post_slug", ")", ",", "]", ")", ")", ".", "hexdigest", "(", ")" ]
The return of Get
[ "The", "return", "of", "Get" ]
7eee50357c47ebdfe3e573a8b4be3b67892d229e
https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/models.py#L151-L162
247,337
sternoru/goscalecms
goscale/models.py
GoscaleCMSPlugin.get_post
def get_post(self, slug): """ This method returns a single post by slug """ cache_key = self.get_cache_key(post_slug=slug) content = cache.get(cache_key) if not content: post = Post.objects.get(slug=slug) content = self._format(post) cache_duration = conf.GOSCALE_CACHE_DURATION if post else 1 cache.set(cache_key, content, cache_duration) return content
python
def get_post(self, slug): """ This method returns a single post by slug """ cache_key = self.get_cache_key(post_slug=slug) content = cache.get(cache_key) if not content: post = Post.objects.get(slug=slug) content = self._format(post) cache_duration = conf.GOSCALE_CACHE_DURATION if post else 1 cache.set(cache_key, content, cache_duration) return content
[ "def", "get_post", "(", "self", ",", "slug", ")", ":", "cache_key", "=", "self", ".", "get_cache_key", "(", "post_slug", "=", "slug", ")", "content", "=", "cache", ".", "get", "(", "cache_key", ")", "if", "not", "content", ":", "post", "=", "Post", ".", "objects", ".", "get", "(", "slug", "=", "slug", ")", "content", "=", "self", ".", "_format", "(", "post", ")", "cache_duration", "=", "conf", ".", "GOSCALE_CACHE_DURATION", "if", "post", "else", "1", "cache", ".", "set", "(", "cache_key", ",", "content", ",", "cache_duration", ")", "return", "content" ]
This method returns a single post by slug
[ "This", "method", "returns", "a", "single", "post", "by", "slug" ]
7eee50357c47ebdfe3e573a8b4be3b67892d229e
https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/models.py#L189-L199
247,338
sternoru/goscalecms
goscale/models.py
GoscaleCMSPlugin.up_to_date
def up_to_date(self): """ Returns True if plugin posts are up to date Determined by self.updated and conf.GOSCALE_POSTS_UPDATE_FREQUENCY """ # return False if not self.updated: return False return (utils.get_datetime_now() - self.updated).seconds < conf.GOSCALE_POSTS_UPDATE_FREQUENCY
python
def up_to_date(self): """ Returns True if plugin posts are up to date Determined by self.updated and conf.GOSCALE_POSTS_UPDATE_FREQUENCY """ # return False if not self.updated: return False return (utils.get_datetime_now() - self.updated).seconds < conf.GOSCALE_POSTS_UPDATE_FREQUENCY
[ "def", "up_to_date", "(", "self", ")", ":", "# return False", "if", "not", "self", ".", "updated", ":", "return", "False", "return", "(", "utils", ".", "get_datetime_now", "(", ")", "-", "self", ".", "updated", ")", ".", "seconds", "<", "conf", ".", "GOSCALE_POSTS_UPDATE_FREQUENCY" ]
Returns True if plugin posts are up to date Determined by self.updated and conf.GOSCALE_POSTS_UPDATE_FREQUENCY
[ "Returns", "True", "if", "plugin", "posts", "are", "up", "to", "date" ]
7eee50357c47ebdfe3e573a8b4be3b67892d229e
https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/models.py#L201-L209
247,339
pjuren/pyokit
src/pyokit/scripts/pyokitMain.py
dispatch
def dispatch(args): """ Parse the command line and dispatch the appropriate script. This function just performs dispatch on the command line that a user provided. Basically, look at the first argument, which specifies the function the user wants Ribocop to perform, then dispatch to the appropriate module. """ prog_name = args[0] if prog_name not in dispatchers: raise NoSuchScriptError("No such pyokit script: " + prog_name + "\n") else: dispatchers[prog_name](args[1:])
python
def dispatch(args): """ Parse the command line and dispatch the appropriate script. This function just performs dispatch on the command line that a user provided. Basically, look at the first argument, which specifies the function the user wants Ribocop to perform, then dispatch to the appropriate module. """ prog_name = args[0] if prog_name not in dispatchers: raise NoSuchScriptError("No such pyokit script: " + prog_name + "\n") else: dispatchers[prog_name](args[1:])
[ "def", "dispatch", "(", "args", ")", ":", "prog_name", "=", "args", "[", "0", "]", "if", "prog_name", "not", "in", "dispatchers", ":", "raise", "NoSuchScriptError", "(", "\"No such pyokit script: \"", "+", "prog_name", "+", "\"\\n\"", ")", "else", ":", "dispatchers", "[", "prog_name", "]", "(", "args", "[", "1", ":", "]", ")" ]
Parse the command line and dispatch the appropriate script. This function just performs dispatch on the command line that a user provided. Basically, look at the first argument, which specifies the function the user wants Ribocop to perform, then dispatch to the appropriate module.
[ "Parse", "the", "command", "line", "and", "dispatch", "the", "appropriate", "script", "." ]
fddae123b5d817daa39496183f19c000d9c3791f
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/pyokitMain.py#L130-L143
247,340
20c/xbahn
xbahn/message.py
Message.export
def export(self, contentType): """ Export message to specified contentType via munge contentType <str> - eg. "json", "yaml" """ cls = munge.get_codec(contentType) codec = cls() return codec.dumps(self.__dict__())
python
def export(self, contentType): """ Export message to specified contentType via munge contentType <str> - eg. "json", "yaml" """ cls = munge.get_codec(contentType) codec = cls() return codec.dumps(self.__dict__())
[ "def", "export", "(", "self", ",", "contentType", ")", ":", "cls", "=", "munge", ".", "get_codec", "(", "contentType", ")", "codec", "=", "cls", "(", ")", "return", "codec", ".", "dumps", "(", "self", ".", "__dict__", "(", ")", ")" ]
Export message to specified contentType via munge contentType <str> - eg. "json", "yaml"
[ "Export", "message", "to", "specified", "contentType", "via", "munge" ]
afb27b0576841338a366d7cac0200a782bd84be6
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/message.py#L71-L79
247,341
nens/turn
turn/console.py
get_parser
def get_parser(): """ Return argument parser. """ parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter, description=__doc__, ) # connection to redis server parser.add_argument('--host', default='localhost') parser.add_argument('--port', default=6379, type=int) parser.add_argument('--db', default=0, type=int) # tools parser.add_argument('command', choices=(str('follow'), str('lock'), str('reset'), str('status'))) parser.add_argument('resources', nargs='*', metavar='RESOURCE') return parser
python
def get_parser(): """ Return argument parser. """ parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter, description=__doc__, ) # connection to redis server parser.add_argument('--host', default='localhost') parser.add_argument('--port', default=6379, type=int) parser.add_argument('--db', default=0, type=int) # tools parser.add_argument('command', choices=(str('follow'), str('lock'), str('reset'), str('status'))) parser.add_argument('resources', nargs='*', metavar='RESOURCE') return parser
[ "def", "get_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "formatter_class", "=", "argparse", ".", "RawTextHelpFormatter", ",", "description", "=", "__doc__", ",", ")", "# connection to redis server", "parser", ".", "add_argument", "(", "'--host'", ",", "default", "=", "'localhost'", ")", "parser", ".", "add_argument", "(", "'--port'", ",", "default", "=", "6379", ",", "type", "=", "int", ")", "parser", ".", "add_argument", "(", "'--db'", ",", "default", "=", "0", ",", "type", "=", "int", ")", "# tools", "parser", ".", "add_argument", "(", "'command'", ",", "choices", "=", "(", "str", "(", "'follow'", ")", ",", "str", "(", "'lock'", ")", ",", "str", "(", "'reset'", ")", ",", "str", "(", "'status'", ")", ")", ")", "parser", ".", "add_argument", "(", "'resources'", ",", "nargs", "=", "'*'", ",", "metavar", "=", "'RESOURCE'", ")", "return", "parser" ]
Return argument parser.
[ "Return", "argument", "parser", "." ]
98e806a0749ada0ddfd04b3c29fb04c15bf5ac18
https://github.com/nens/turn/blob/98e806a0749ada0ddfd04b3c29fb04c15bf5ac18/turn/console.py#L43-L60
247,342
knagra/farnsworth
managers/ajax.py
build_ajax_votes
def build_ajax_votes(request, user_profile): """Build vote information for the request.""" vote_list = '' for profile in request.upvotes.all(): vote_list += \ '<li><a title="View Profile" href="{url}">{name}</a></li>'.format( url=reverse( 'member_profile', kwargs={'targetUsername': profile.user.username} ), name='You' if profile.user == user_profile.user \ else profile.user.get_full_name(), ) in_votes = user_profile in request.upvotes.all() count = request.upvotes.all().count() return (vote_list, in_votes, count)
python
def build_ajax_votes(request, user_profile): """Build vote information for the request.""" vote_list = '' for profile in request.upvotes.all(): vote_list += \ '<li><a title="View Profile" href="{url}">{name}</a></li>'.format( url=reverse( 'member_profile', kwargs={'targetUsername': profile.user.username} ), name='You' if profile.user == user_profile.user \ else profile.user.get_full_name(), ) in_votes = user_profile in request.upvotes.all() count = request.upvotes.all().count() return (vote_list, in_votes, count)
[ "def", "build_ajax_votes", "(", "request", ",", "user_profile", ")", ":", "vote_list", "=", "''", "for", "profile", "in", "request", ".", "upvotes", ".", "all", "(", ")", ":", "vote_list", "+=", "'<li><a title=\"View Profile\" href=\"{url}\">{name}</a></li>'", ".", "format", "(", "url", "=", "reverse", "(", "'member_profile'", ",", "kwargs", "=", "{", "'targetUsername'", ":", "profile", ".", "user", ".", "username", "}", ")", ",", "name", "=", "'You'", "if", "profile", ".", "user", "==", "user_profile", ".", "user", "else", "profile", ".", "user", ".", "get_full_name", "(", ")", ",", ")", "in_votes", "=", "user_profile", "in", "request", ".", "upvotes", ".", "all", "(", ")", "count", "=", "request", ".", "upvotes", ".", "all", "(", ")", ".", "count", "(", ")", "return", "(", "vote_list", ",", "in_votes", ",", "count", ")" ]
Build vote information for the request.
[ "Build", "vote", "information", "for", "the", "request", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/managers/ajax.py#L13-L30
247,343
makyo/prose-wc
prose_wc/wc.py
setup
def setup(argv): """Sets up the ArgumentParser. Args: argv: an array of arguments """ parser = argparse.ArgumentParser( description='Compute Jekyl- and prose-aware wordcounts', epilog='Accepted filetypes: plaintext, markdown, markdown (Jekyll)') parser.add_argument('-S', '--split-hyphens', action='store_true', dest='split_hyphens', help='split hyphenated words rather than counting ' 'them as one word ("non-trivial" counts as two words ' 'rather than one)') parser.add_argument('-u', '--update', action='store_true', help='update the jekyll file in place with the counts.' ' Does nothing if the file is not a Jekyll markdown ' 'file. Implies format=yaml, invalid with input ' 'from STDIN and non-Jekyll files.') parser.add_argument('-f', '--format', nargs='?', choices=['yaml', 'json', 'default'], default='default', help='output format.') parser.add_argument('-i', '--indent', type=int, nargs='?', default=4, help='indentation depth (default: 4).') parser.add_argument('file', type=argparse.FileType('rb'), help='file to parse (or - for STDIN)') return parser.parse_args(argv)
python
def setup(argv): """Sets up the ArgumentParser. Args: argv: an array of arguments """ parser = argparse.ArgumentParser( description='Compute Jekyl- and prose-aware wordcounts', epilog='Accepted filetypes: plaintext, markdown, markdown (Jekyll)') parser.add_argument('-S', '--split-hyphens', action='store_true', dest='split_hyphens', help='split hyphenated words rather than counting ' 'them as one word ("non-trivial" counts as two words ' 'rather than one)') parser.add_argument('-u', '--update', action='store_true', help='update the jekyll file in place with the counts.' ' Does nothing if the file is not a Jekyll markdown ' 'file. Implies format=yaml, invalid with input ' 'from STDIN and non-Jekyll files.') parser.add_argument('-f', '--format', nargs='?', choices=['yaml', 'json', 'default'], default='default', help='output format.') parser.add_argument('-i', '--indent', type=int, nargs='?', default=4, help='indentation depth (default: 4).') parser.add_argument('file', type=argparse.FileType('rb'), help='file to parse (or - for STDIN)') return parser.parse_args(argv)
[ "def", "setup", "(", "argv", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Compute Jekyl- and prose-aware wordcounts'", ",", "epilog", "=", "'Accepted filetypes: plaintext, markdown, markdown (Jekyll)'", ")", "parser", ".", "add_argument", "(", "'-S'", ",", "'--split-hyphens'", ",", "action", "=", "'store_true'", ",", "dest", "=", "'split_hyphens'", ",", "help", "=", "'split hyphenated words rather than counting '", "'them as one word (\"non-trivial\" counts as two words '", "'rather than one)'", ")", "parser", ".", "add_argument", "(", "'-u'", ",", "'--update'", ",", "action", "=", "'store_true'", ",", "help", "=", "'update the jekyll file in place with the counts.'", "' Does nothing if the file is not a Jekyll markdown '", "'file. Implies format=yaml, invalid with input '", "'from STDIN and non-Jekyll files.'", ")", "parser", ".", "add_argument", "(", "'-f'", ",", "'--format'", ",", "nargs", "=", "'?'", ",", "choices", "=", "[", "'yaml'", ",", "'json'", ",", "'default'", "]", ",", "default", "=", "'default'", ",", "help", "=", "'output format.'", ")", "parser", ".", "add_argument", "(", "'-i'", ",", "'--indent'", ",", "type", "=", "int", ",", "nargs", "=", "'?'", ",", "default", "=", "4", ",", "help", "=", "'indentation depth (default: 4).'", ")", "parser", ".", "add_argument", "(", "'file'", ",", "type", "=", "argparse", ".", "FileType", "(", "'rb'", ")", ",", "help", "=", "'file to parse (or - for STDIN)'", ")", "return", "parser", ".", "parse_args", "(", "argv", ")" ]
Sets up the ArgumentParser. Args: argv: an array of arguments
[ "Sets", "up", "the", "ArgumentParser", "." ]
01a33d1a4cfdad27a283c041e1acc1b309b893c0
https://github.com/makyo/prose-wc/blob/01a33d1a4cfdad27a283c041e1acc1b309b893c0/prose_wc/wc.py#L44-L70
247,344
makyo/prose-wc
prose_wc/wc.py
prose_wc
def prose_wc(args): """Processes data provided to print a count object, or update a file. Args: args: an ArgumentParser object returned by setup() """ if args.file is None: return 1 if args.split_hyphens: INTERSTITIAL_PUNCTUATION.append(re.compile(r'-')) content = args.file.read().decode('utf-8') filename = args.file.name body = strip_frontmatter(content) parsed = markdown_to_text(body) result = wc(filename, body, parsed=parsed, is_jekyll=(body != content)) if (args.update and filename != '_stdin_' and result['counts']['type'] == 'jekyll'): update_file(filename, result, content, args.indent) else: _mockable_print({ 'yaml': yaml.safe_dump(result, default_flow_style=False, indent=args.indent), 'json': json.dumps(result, indent=args.indent), 'default': default_dump(result), }[args.format]) return 0
python
def prose_wc(args): """Processes data provided to print a count object, or update a file. Args: args: an ArgumentParser object returned by setup() """ if args.file is None: return 1 if args.split_hyphens: INTERSTITIAL_PUNCTUATION.append(re.compile(r'-')) content = args.file.read().decode('utf-8') filename = args.file.name body = strip_frontmatter(content) parsed = markdown_to_text(body) result = wc(filename, body, parsed=parsed, is_jekyll=(body != content)) if (args.update and filename != '_stdin_' and result['counts']['type'] == 'jekyll'): update_file(filename, result, content, args.indent) else: _mockable_print({ 'yaml': yaml.safe_dump(result, default_flow_style=False, indent=args.indent), 'json': json.dumps(result, indent=args.indent), 'default': default_dump(result), }[args.format]) return 0
[ "def", "prose_wc", "(", "args", ")", ":", "if", "args", ".", "file", "is", "None", ":", "return", "1", "if", "args", ".", "split_hyphens", ":", "INTERSTITIAL_PUNCTUATION", ".", "append", "(", "re", ".", "compile", "(", "r'-'", ")", ")", "content", "=", "args", ".", "file", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "filename", "=", "args", ".", "file", ".", "name", "body", "=", "strip_frontmatter", "(", "content", ")", "parsed", "=", "markdown_to_text", "(", "body", ")", "result", "=", "wc", "(", "filename", ",", "body", ",", "parsed", "=", "parsed", ",", "is_jekyll", "=", "(", "body", "!=", "content", ")", ")", "if", "(", "args", ".", "update", "and", "filename", "!=", "'_stdin_'", "and", "result", "[", "'counts'", "]", "[", "'type'", "]", "==", "'jekyll'", ")", ":", "update_file", "(", "filename", ",", "result", ",", "content", ",", "args", ".", "indent", ")", "else", ":", "_mockable_print", "(", "{", "'yaml'", ":", "yaml", ".", "safe_dump", "(", "result", ",", "default_flow_style", "=", "False", ",", "indent", "=", "args", ".", "indent", ")", ",", "'json'", ":", "json", ".", "dumps", "(", "result", ",", "indent", "=", "args", ".", "indent", ")", ",", "'default'", ":", "default_dump", "(", "result", ")", ",", "}", "[", "args", ".", "format", "]", ")", "return", "0" ]
Processes data provided to print a count object, or update a file. Args: args: an ArgumentParser object returned by setup()
[ "Processes", "data", "provided", "to", "print", "a", "count", "object", "or", "update", "a", "file", "." ]
01a33d1a4cfdad27a283c041e1acc1b309b893c0
https://github.com/makyo/prose-wc/blob/01a33d1a4cfdad27a283c041e1acc1b309b893c0/prose_wc/wc.py#L73-L100
247,345
makyo/prose-wc
prose_wc/wc.py
markdown_to_text
def markdown_to_text(body): """Converts markdown to text. Args: body: markdown (or plaintext, or maybe HTML) input Returns: Plaintext with all tags and frills removed """ # Turn our input into HTML md = markdown.markdown(body, extensions=[ 'markdown.extensions.extra' ]) # Safely parse HTML so that we don't have to parse it ourselves soup = BeautifulSoup(md, 'html.parser') # Return just the text of the parsed HTML return soup.get_text()
python
def markdown_to_text(body): """Converts markdown to text. Args: body: markdown (or plaintext, or maybe HTML) input Returns: Plaintext with all tags and frills removed """ # Turn our input into HTML md = markdown.markdown(body, extensions=[ 'markdown.extensions.extra' ]) # Safely parse HTML so that we don't have to parse it ourselves soup = BeautifulSoup(md, 'html.parser') # Return just the text of the parsed HTML return soup.get_text()
[ "def", "markdown_to_text", "(", "body", ")", ":", "# Turn our input into HTML", "md", "=", "markdown", ".", "markdown", "(", "body", ",", "extensions", "=", "[", "'markdown.extensions.extra'", "]", ")", "# Safely parse HTML so that we don't have to parse it ourselves", "soup", "=", "BeautifulSoup", "(", "md", ",", "'html.parser'", ")", "# Return just the text of the parsed HTML", "return", "soup", ".", "get_text", "(", ")" ]
Converts markdown to text. Args: body: markdown (or plaintext, or maybe HTML) input Returns: Plaintext with all tags and frills removed
[ "Converts", "markdown", "to", "text", "." ]
01a33d1a4cfdad27a283c041e1acc1b309b893c0
https://github.com/makyo/prose-wc/blob/01a33d1a4cfdad27a283c041e1acc1b309b893c0/prose_wc/wc.py#L103-L121
247,346
makyo/prose-wc
prose_wc/wc.py
wc
def wc(filename, contents, parsed=None, is_jekyll=False): """Count the words, characters, and paragraphs in a string. Args: contents: the original string to count filename (optional): the filename as provided to the CLI parsed (optional): a parsed string, expected to be plaintext only is_jekyll: whether the original contents were from a Jekyll file Returns: An object containing the various counts """ if is_jekyll: fmt = 'jekyll' else: fmt = 'md/txt' body = parsed.strip() if parsed else contents.strip() # Strip the body down to just words words = re.sub(r'\s+', ' ', body, re.MULTILINE) for punctuation in INTERSTITIAL_PUNCTUATION: words = re.sub(punctuation, ' ', words) punct = re.compile('[^\w\s]', re.U) words = punct.sub('', words) # Retrieve only non-space characters real_characters = re.sub(r'\s', '', words) # Count paragraphs in an intelligent way paragraphs = [1 if len(x) == 0 else 0 for x in contents.strip().splitlines()] for index, paragraph in enumerate(paragraphs): if paragraph == 1 and paragraphs[index + 1] == 1: paragraphs[index] = 0 return { 'counts': { 'file': filename, 'type': fmt, 'paragraphs': sum(paragraphs) + 1, 'words': len(re.split('\s+', words)), 'characters_real': len(real_characters), 'characters_total': len(words), } }
python
def wc(filename, contents, parsed=None, is_jekyll=False): """Count the words, characters, and paragraphs in a string. Args: contents: the original string to count filename (optional): the filename as provided to the CLI parsed (optional): a parsed string, expected to be plaintext only is_jekyll: whether the original contents were from a Jekyll file Returns: An object containing the various counts """ if is_jekyll: fmt = 'jekyll' else: fmt = 'md/txt' body = parsed.strip() if parsed else contents.strip() # Strip the body down to just words words = re.sub(r'\s+', ' ', body, re.MULTILINE) for punctuation in INTERSTITIAL_PUNCTUATION: words = re.sub(punctuation, ' ', words) punct = re.compile('[^\w\s]', re.U) words = punct.sub('', words) # Retrieve only non-space characters real_characters = re.sub(r'\s', '', words) # Count paragraphs in an intelligent way paragraphs = [1 if len(x) == 0 else 0 for x in contents.strip().splitlines()] for index, paragraph in enumerate(paragraphs): if paragraph == 1 and paragraphs[index + 1] == 1: paragraphs[index] = 0 return { 'counts': { 'file': filename, 'type': fmt, 'paragraphs': sum(paragraphs) + 1, 'words': len(re.split('\s+', words)), 'characters_real': len(real_characters), 'characters_total': len(words), } }
[ "def", "wc", "(", "filename", ",", "contents", ",", "parsed", "=", "None", ",", "is_jekyll", "=", "False", ")", ":", "if", "is_jekyll", ":", "fmt", "=", "'jekyll'", "else", ":", "fmt", "=", "'md/txt'", "body", "=", "parsed", ".", "strip", "(", ")", "if", "parsed", "else", "contents", ".", "strip", "(", ")", "# Strip the body down to just words", "words", "=", "re", ".", "sub", "(", "r'\\s+'", ",", "' '", ",", "body", ",", "re", ".", "MULTILINE", ")", "for", "punctuation", "in", "INTERSTITIAL_PUNCTUATION", ":", "words", "=", "re", ".", "sub", "(", "punctuation", ",", "' '", ",", "words", ")", "punct", "=", "re", ".", "compile", "(", "'[^\\w\\s]'", ",", "re", ".", "U", ")", "words", "=", "punct", ".", "sub", "(", "''", ",", "words", ")", "# Retrieve only non-space characters", "real_characters", "=", "re", ".", "sub", "(", "r'\\s'", ",", "''", ",", "words", ")", "# Count paragraphs in an intelligent way", "paragraphs", "=", "[", "1", "if", "len", "(", "x", ")", "==", "0", "else", "0", "for", "x", "in", "contents", ".", "strip", "(", ")", ".", "splitlines", "(", ")", "]", "for", "index", ",", "paragraph", "in", "enumerate", "(", "paragraphs", ")", ":", "if", "paragraph", "==", "1", "and", "paragraphs", "[", "index", "+", "1", "]", "==", "1", ":", "paragraphs", "[", "index", "]", "=", "0", "return", "{", "'counts'", ":", "{", "'file'", ":", "filename", ",", "'type'", ":", "fmt", ",", "'paragraphs'", ":", "sum", "(", "paragraphs", ")", "+", "1", ",", "'words'", ":", "len", "(", "re", ".", "split", "(", "'\\s+'", ",", "words", ")", ")", ",", "'characters_real'", ":", "len", "(", "real_characters", ")", ",", "'characters_total'", ":", "len", "(", "words", ")", ",", "}", "}" ]
Count the words, characters, and paragraphs in a string. Args: contents: the original string to count filename (optional): the filename as provided to the CLI parsed (optional): a parsed string, expected to be plaintext only is_jekyll: whether the original contents were from a Jekyll file Returns: An object containing the various counts
[ "Count", "the", "words", "characters", "and", "paragraphs", "in", "a", "string", "." ]
01a33d1a4cfdad27a283c041e1acc1b309b893c0
https://github.com/makyo/prose-wc/blob/01a33d1a4cfdad27a283c041e1acc1b309b893c0/prose_wc/wc.py#L138-L182
247,347
makyo/prose-wc
prose_wc/wc.py
update_file
def update_file(filename, result, content, indent): """Updates a Jekyll file to contain the counts form an object This just converts the results to YAML and adds to the Jekyll frontmatter. Args: filename: the Jekyll file to update result: the results object from `wc` content: the contents of the original file indent: the indentation level for dumping YAML """ # Split the file into frontmatter and content parts = re.split('---+', content, 2) # Load the frontmatter into an object frontmatter = yaml.safe_load(parts[1]) # Add the counts entry in the results object to the frontmatter frontmatter['counts'] = result['counts'] # Set the frontmatter part backed to the stringified version of the # frontmatter object parts[1] = '\n{}'.format( yaml.safe_dump(frontmatter, default_flow_style=False, indent=indent)) result = '---'.join(parts) # Write everything back to the file with open(filename, 'wb') as f: f.write(result.encode('utf-8')) print('{} updated.'.format(filename))
python
def update_file(filename, result, content, indent): """Updates a Jekyll file to contain the counts form an object This just converts the results to YAML and adds to the Jekyll frontmatter. Args: filename: the Jekyll file to update result: the results object from `wc` content: the contents of the original file indent: the indentation level for dumping YAML """ # Split the file into frontmatter and content parts = re.split('---+', content, 2) # Load the frontmatter into an object frontmatter = yaml.safe_load(parts[1]) # Add the counts entry in the results object to the frontmatter frontmatter['counts'] = result['counts'] # Set the frontmatter part backed to the stringified version of the # frontmatter object parts[1] = '\n{}'.format( yaml.safe_dump(frontmatter, default_flow_style=False, indent=indent)) result = '---'.join(parts) # Write everything back to the file with open(filename, 'wb') as f: f.write(result.encode('utf-8')) print('{} updated.'.format(filename))
[ "def", "update_file", "(", "filename", ",", "result", ",", "content", ",", "indent", ")", ":", "# Split the file into frontmatter and content", "parts", "=", "re", ".", "split", "(", "'---+'", ",", "content", ",", "2", ")", "# Load the frontmatter into an object", "frontmatter", "=", "yaml", ".", "safe_load", "(", "parts", "[", "1", "]", ")", "# Add the counts entry in the results object to the frontmatter", "frontmatter", "[", "'counts'", "]", "=", "result", "[", "'counts'", "]", "# Set the frontmatter part backed to the stringified version of the", "# frontmatter object", "parts", "[", "1", "]", "=", "'\\n{}'", ".", "format", "(", "yaml", ".", "safe_dump", "(", "frontmatter", ",", "default_flow_style", "=", "False", ",", "indent", "=", "indent", ")", ")", "result", "=", "'---'", ".", "join", "(", "parts", ")", "# Write everything back to the file", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "result", ".", "encode", "(", "'utf-8'", ")", ")", "print", "(", "'{} updated.'", ".", "format", "(", "filename", ")", ")" ]
Updates a Jekyll file to contain the counts form an object This just converts the results to YAML and adds to the Jekyll frontmatter. Args: filename: the Jekyll file to update result: the results object from `wc` content: the contents of the original file indent: the indentation level for dumping YAML
[ "Updates", "a", "Jekyll", "file", "to", "contain", "the", "counts", "form", "an", "object" ]
01a33d1a4cfdad27a283c041e1acc1b309b893c0
https://github.com/makyo/prose-wc/blob/01a33d1a4cfdad27a283c041e1acc1b309b893c0/prose_wc/wc.py#L185-L214
247,348
opinkerfi/nago
nago/core/__init__.py
log
def log(message, level="info"): """ Add a new log entry to the nago log. Arguments: level - Arbritrary string, levels should be syslog style (debug,log,info,warning,error) message - Arbritary string, the message that is to be logged. """ now = time.time() entry = {} entry['level'] = level entry['message'] = message entry['timestamp'] = now _log_entries.append(entry)
python
def log(message, level="info"): """ Add a new log entry to the nago log. Arguments: level - Arbritrary string, levels should be syslog style (debug,log,info,warning,error) message - Arbritary string, the message that is to be logged. """ now = time.time() entry = {} entry['level'] = level entry['message'] = message entry['timestamp'] = now _log_entries.append(entry)
[ "def", "log", "(", "message", ",", "level", "=", "\"info\"", ")", ":", "now", "=", "time", ".", "time", "(", ")", "entry", "=", "{", "}", "entry", "[", "'level'", "]", "=", "level", "entry", "[", "'message'", "]", "=", "message", "entry", "[", "'timestamp'", "]", "=", "now", "_log_entries", ".", "append", "(", "entry", ")" ]
Add a new log entry to the nago log. Arguments: level - Arbritrary string, levels should be syslog style (debug,log,info,warning,error) message - Arbritary string, the message that is to be logged.
[ "Add", "a", "new", "log", "entry", "to", "the", "nago", "log", "." ]
85e1bdd1de0122f56868a483e7599e1b36a439b0
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/core/__init__.py#L28-L40
247,349
opinkerfi/nago
nago/core/__init__.py
nago_access
def nago_access(access_required="master", name=None): """ Decorate other functions with this one to allow access Arguments: nago_access -- Type of access required to call this function By default only master is allowed to make that call nago_name -- What name this function will have to remote api Default is the same as the name of the function being decorated. """ def real_decorator(func): func.nago_access = access_required func.nago_name = name or func.__name__ @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper return real_decorator
python
def nago_access(access_required="master", name=None): """ Decorate other functions with this one to allow access Arguments: nago_access -- Type of access required to call this function By default only master is allowed to make that call nago_name -- What name this function will have to remote api Default is the same as the name of the function being decorated. """ def real_decorator(func): func.nago_access = access_required func.nago_name = name or func.__name__ @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper return real_decorator
[ "def", "nago_access", "(", "access_required", "=", "\"master\"", ",", "name", "=", "None", ")", ":", "def", "real_decorator", "(", "func", ")", ":", "func", ".", "nago_access", "=", "access_required", "func", ".", "nago_name", "=", "name", "or", "func", ".", "__name__", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "real_decorator" ]
Decorate other functions with this one to allow access Arguments: nago_access -- Type of access required to call this function By default only master is allowed to make that call nago_name -- What name this function will have to remote api Default is the same as the name of the function being decorated.
[ "Decorate", "other", "functions", "with", "this", "one", "to", "allow", "access" ]
85e1bdd1de0122f56868a483e7599e1b36a439b0
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/core/__init__.py#L45-L63
247,350
opinkerfi/nago
nago/core/__init__.py
get_nodes
def get_nodes(): """ Returns all nodes in a list of dicts format """ cfg_file = "/etc/nago/nago.ini" config = ConfigParser.ConfigParser() config.read(cfg_file) result = {} for section in config.sections(): if section in ['main']: continue token = section node = Node(token) for key, value in config.items(token): node[key] = value result[token] = node return result
python
def get_nodes(): """ Returns all nodes in a list of dicts format """ cfg_file = "/etc/nago/nago.ini" config = ConfigParser.ConfigParser() config.read(cfg_file) result = {} for section in config.sections(): if section in ['main']: continue token = section node = Node(token) for key, value in config.items(token): node[key] = value result[token] = node return result
[ "def", "get_nodes", "(", ")", ":", "cfg_file", "=", "\"/etc/nago/nago.ini\"", "config", "=", "ConfigParser", ".", "ConfigParser", "(", ")", "config", ".", "read", "(", "cfg_file", ")", "result", "=", "{", "}", "for", "section", "in", "config", ".", "sections", "(", ")", ":", "if", "section", "in", "[", "'main'", "]", ":", "continue", "token", "=", "section", "node", "=", "Node", "(", "token", ")", "for", "key", ",", "value", "in", "config", ".", "items", "(", "token", ")", ":", "node", "[", "key", "]", "=", "value", "result", "[", "token", "]", "=", "node", "return", "result" ]
Returns all nodes in a list of dicts format
[ "Returns", "all", "nodes", "in", "a", "list", "of", "dicts", "format" ]
85e1bdd1de0122f56868a483e7599e1b36a439b0
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/core/__init__.py#L66-L81
247,351
opinkerfi/nago
nago/core/__init__.py
generate_token
def generate_token(): """ Generate a new random security token. >>> len(generate_token()) == 50 True Returns: string """ length = 50 stringset = string.ascii_letters + string.digits token = ''.join([stringset[i % len(stringset)] for i in [ord(x) for x in os.urandom(length)]]) return token
python
def generate_token(): """ Generate a new random security token. >>> len(generate_token()) == 50 True Returns: string """ length = 50 stringset = string.ascii_letters + string.digits token = ''.join([stringset[i % len(stringset)] for i in [ord(x) for x in os.urandom(length)]]) return token
[ "def", "generate_token", "(", ")", ":", "length", "=", "50", "stringset", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", "token", "=", "''", ".", "join", "(", "[", "stringset", "[", "i", "%", "len", "(", "stringset", ")", "]", "for", "i", "in", "[", "ord", "(", "x", ")", "for", "x", "in", "os", ".", "urandom", "(", "length", ")", "]", "]", ")", "return", "token" ]
Generate a new random security token. >>> len(generate_token()) == 50 True Returns: string
[ "Generate", "a", "new", "random", "security", "token", "." ]
85e1bdd1de0122f56868a483e7599e1b36a439b0
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/core/__init__.py#L99-L111
247,352
opinkerfi/nago
nago/core/__init__.py
get_my_info
def get_my_info(): """ Return general information about this node """ result = {} result['host_name'] = platform.node() result['real_host_name'] = platform.node() result['dist'] = platform.dist() result['nago_version'] = nago.get_version() return result
python
def get_my_info(): """ Return general information about this node """ result = {} result['host_name'] = platform.node() result['real_host_name'] = platform.node() result['dist'] = platform.dist() result['nago_version'] = nago.get_version() return result
[ "def", "get_my_info", "(", ")", ":", "result", "=", "{", "}", "result", "[", "'host_name'", "]", "=", "platform", ".", "node", "(", ")", "result", "[", "'real_host_name'", "]", "=", "platform", ".", "node", "(", ")", "result", "[", "'dist'", "]", "=", "platform", ".", "dist", "(", ")", "result", "[", "'nago_version'", "]", "=", "nago", ".", "get_version", "(", ")", "return", "result" ]
Return general information about this node
[ "Return", "general", "information", "about", "this", "node" ]
85e1bdd1de0122f56868a483e7599e1b36a439b0
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/core/__init__.py#L232-L240
247,353
opinkerfi/nago
nago/core/__init__.py
Node.delete
def delete(self): """ Delete this node from config files """ cfg_file = "/etc/nago/nago.ini" config = ConfigParser.ConfigParser() config.read(cfg_file) result = {} token = self.data.pop("token", self.token) if token not in config.sections(): raise Exception("Cannot find node in config. Delete aborted.") config.remove_section(self.token) with open(cfg_file, 'w') as f: return config.write(f)
python
def delete(self): """ Delete this node from config files """ cfg_file = "/etc/nago/nago.ini" config = ConfigParser.ConfigParser() config.read(cfg_file) result = {} token = self.data.pop("token", self.token) if token not in config.sections(): raise Exception("Cannot find node in config. Delete aborted.") config.remove_section(self.token) with open(cfg_file, 'w') as f: return config.write(f)
[ "def", "delete", "(", "self", ")", ":", "cfg_file", "=", "\"/etc/nago/nago.ini\"", "config", "=", "ConfigParser", ".", "ConfigParser", "(", ")", "config", ".", "read", "(", "cfg_file", ")", "result", "=", "{", "}", "token", "=", "self", ".", "data", ".", "pop", "(", "\"token\"", ",", "self", ".", "token", ")", "if", "token", "not", "in", "config", ".", "sections", "(", ")", ":", "raise", "Exception", "(", "\"Cannot find node in config. Delete aborted.\"", ")", "config", ".", "remove_section", "(", "self", ".", "token", ")", "with", "open", "(", "cfg_file", ",", "'w'", ")", "as", "f", ":", "return", "config", ".", "write", "(", "f", ")" ]
Delete this node from config files
[ "Delete", "this", "node", "from", "config", "files" ]
85e1bdd1de0122f56868a483e7599e1b36a439b0
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/core/__init__.py#L138-L149
247,354
opinkerfi/nago
nago/core/__init__.py
Node.get_info
def get_info(self, key=None): """ Return all posted info about this node """ node_data = nago.extensions.info.node_data.get(self.token, {}) if key is None: return node_data else: return node_data.get(key, {})
python
def get_info(self, key=None): """ Return all posted info about this node """ node_data = nago.extensions.info.node_data.get(self.token, {}) if key is None: return node_data else: return node_data.get(key, {})
[ "def", "get_info", "(", "self", ",", "key", "=", "None", ")", ":", "node_data", "=", "nago", ".", "extensions", ".", "info", ".", "node_data", ".", "get", "(", "self", ".", "token", ",", "{", "}", ")", "if", "key", "is", "None", ":", "return", "node_data", "else", ":", "return", "node_data", ".", "get", "(", "key", ",", "{", "}", ")" ]
Return all posted info about this node
[ "Return", "all", "posted", "info", "about", "this", "node" ]
85e1bdd1de0122f56868a483e7599e1b36a439b0
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/core/__init__.py#L178-L184
247,355
hirokiky/matcha
matcha.py
include
def include(pattern, matching): """ Including a other matching, to get as matching pattern's child paths. """ matching.matching_records = [ MatchingRecord( PathTemplate(pattern) + child_path_template, case, child_name ) for child_path_template, case, child_name in matching.matching_records ] return matching
python
def include(pattern, matching): """ Including a other matching, to get as matching pattern's child paths. """ matching.matching_records = [ MatchingRecord( PathTemplate(pattern) + child_path_template, case, child_name ) for child_path_template, case, child_name in matching.matching_records ] return matching
[ "def", "include", "(", "pattern", ",", "matching", ")", ":", "matching", ".", "matching_records", "=", "[", "MatchingRecord", "(", "PathTemplate", "(", "pattern", ")", "+", "child_path_template", ",", "case", ",", "child_name", ")", "for", "child_path_template", ",", "case", ",", "child_name", "in", "matching", ".", "matching_records", "]", "return", "matching" ]
Including a other matching, to get as matching pattern's child paths.
[ "Including", "a", "other", "matching", "to", "get", "as", "matching", "pattern", "s", "child", "paths", "." ]
fd6dd8d233d5fc890c5b5294f9e1a8577c31e897
https://github.com/hirokiky/matcha/blob/fd6dd8d233d5fc890c5b5294f9e1a8577c31e897/matcha.py#L159-L169
247,356
hirokiky/matcha
matcha.py
make_wsgi_app
def make_wsgi_app(matching, not_found_app=not_found_app): """ Making a WSGI application from Matching object registered other WSGI applications on each 'case' argument. """ def wsgi_app(environ, start_response): environ['matcha.matching'] = matching try: matched_case, matched_dict = matching(environ) except NotMatched: return not_found_app(environ, start_response) else: environ['matcha.matched_dict'] = matched_dict return matched_case(environ, start_response) return wsgi_app
python
def make_wsgi_app(matching, not_found_app=not_found_app): """ Making a WSGI application from Matching object registered other WSGI applications on each 'case' argument. """ def wsgi_app(environ, start_response): environ['matcha.matching'] = matching try: matched_case, matched_dict = matching(environ) except NotMatched: return not_found_app(environ, start_response) else: environ['matcha.matched_dict'] = matched_dict return matched_case(environ, start_response) return wsgi_app
[ "def", "make_wsgi_app", "(", "matching", ",", "not_found_app", "=", "not_found_app", ")", ":", "def", "wsgi_app", "(", "environ", ",", "start_response", ")", ":", "environ", "[", "'matcha.matching'", "]", "=", "matching", "try", ":", "matched_case", ",", "matched_dict", "=", "matching", "(", "environ", ")", "except", "NotMatched", ":", "return", "not_found_app", "(", "environ", ",", "start_response", ")", "else", ":", "environ", "[", "'matcha.matched_dict'", "]", "=", "matched_dict", "return", "matched_case", "(", "environ", ",", "start_response", ")", "return", "wsgi_app" ]
Making a WSGI application from Matching object registered other WSGI applications on each 'case' argument.
[ "Making", "a", "WSGI", "application", "from", "Matching", "object", "registered", "other", "WSGI", "applications", "on", "each", "case", "argument", "." ]
fd6dd8d233d5fc890c5b5294f9e1a8577c31e897
https://github.com/hirokiky/matcha/blob/fd6dd8d233d5fc890c5b5294f9e1a8577c31e897/matcha.py#L177-L190
247,357
hirokiky/matcha
matcha.py
Matching.reverse
def reverse(self, matching_name, **kwargs): """ Getting a matching name and URL args and return a corresponded URL """ for record in self.matching_records: if record.name == matching_name: path_template = record.path_template break else: raise NotReversed if path_template.wildcard_name: l = kwargs.get(path_template.wildcard_name) if not l: raise NotReversed additional_path = '/'.join(l) extra_path_elements = path_template.pattern.split('/')[:-1] pattern = join_paths('/'.join(extra_path_elements), additional_path) else: pattern = path_template.pattern try: url = pattern.format(**kwargs) except KeyError: raise NotReversed return url
python
def reverse(self, matching_name, **kwargs): """ Getting a matching name and URL args and return a corresponded URL """ for record in self.matching_records: if record.name == matching_name: path_template = record.path_template break else: raise NotReversed if path_template.wildcard_name: l = kwargs.get(path_template.wildcard_name) if not l: raise NotReversed additional_path = '/'.join(l) extra_path_elements = path_template.pattern.split('/')[:-1] pattern = join_paths('/'.join(extra_path_elements), additional_path) else: pattern = path_template.pattern try: url = pattern.format(**kwargs) except KeyError: raise NotReversed return url
[ "def", "reverse", "(", "self", ",", "matching_name", ",", "*", "*", "kwargs", ")", ":", "for", "record", "in", "self", ".", "matching_records", ":", "if", "record", ".", "name", "==", "matching_name", ":", "path_template", "=", "record", ".", "path_template", "break", "else", ":", "raise", "NotReversed", "if", "path_template", ".", "wildcard_name", ":", "l", "=", "kwargs", ".", "get", "(", "path_template", ".", "wildcard_name", ")", "if", "not", "l", ":", "raise", "NotReversed", "additional_path", "=", "'/'", ".", "join", "(", "l", ")", "extra_path_elements", "=", "path_template", ".", "pattern", ".", "split", "(", "'/'", ")", "[", ":", "-", "1", "]", "pattern", "=", "join_paths", "(", "'/'", ".", "join", "(", "extra_path_elements", ")", ",", "additional_path", ")", "else", ":", "pattern", "=", "path_template", ".", "pattern", "try", ":", "url", "=", "pattern", ".", "format", "(", "*", "*", "kwargs", ")", "except", "KeyError", ":", "raise", "NotReversed", "return", "url" ]
Getting a matching name and URL args and return a corresponded URL
[ "Getting", "a", "matching", "name", "and", "URL", "args", "and", "return", "a", "corresponded", "URL" ]
fd6dd8d233d5fc890c5b5294f9e1a8577c31e897
https://github.com/hirokiky/matcha/blob/fd6dd8d233d5fc890c5b5294f9e1a8577c31e897/matcha.py#L65-L89
247,358
laysakura/nextversion
nextversion/__init__.py
nextversion
def nextversion(current_version): """Returns incremented module version number. :param current_version: version string to increment :returns: Next version string (PEP 386 compatible) if possible. If impossible (since `current_version` is too far from PEP 386), `None` is returned. """ norm_ver = verlib.suggest_normalized_version(current_version) if norm_ver is None: return None norm_ver = verlib.NormalizedVersion(norm_ver) # increment last version figure parts = norm_ver.parts # see comments of `verlib.py` to get the idea of `parts` assert(len(parts) == 3) if len(parts[2]) > 1: # postdev if parts[2][-1] == 'f': # when `post` exists but `dev` doesn't parts = _mk_incremented_parts(parts, part_idx=2, in_part_idx=-2, incval=1) else: # when both `post` and `dev` exist parts = _mk_incremented_parts(parts, part_idx=2, in_part_idx=-1, incval=1) elif len(parts[1]) > 1: # prerel parts = _mk_incremented_parts(parts, part_idx=1, in_part_idx=-1, incval=1) else: # version & extraversion parts = _mk_incremented_parts(parts, part_idx=0, in_part_idx=-1, incval=1) norm_ver.parts = parts return str(norm_ver)
python
def nextversion(current_version): """Returns incremented module version number. :param current_version: version string to increment :returns: Next version string (PEP 386 compatible) if possible. If impossible (since `current_version` is too far from PEP 386), `None` is returned. """ norm_ver = verlib.suggest_normalized_version(current_version) if norm_ver is None: return None norm_ver = verlib.NormalizedVersion(norm_ver) # increment last version figure parts = norm_ver.parts # see comments of `verlib.py` to get the idea of `parts` assert(len(parts) == 3) if len(parts[2]) > 1: # postdev if parts[2][-1] == 'f': # when `post` exists but `dev` doesn't parts = _mk_incremented_parts(parts, part_idx=2, in_part_idx=-2, incval=1) else: # when both `post` and `dev` exist parts = _mk_incremented_parts(parts, part_idx=2, in_part_idx=-1, incval=1) elif len(parts[1]) > 1: # prerel parts = _mk_incremented_parts(parts, part_idx=1, in_part_idx=-1, incval=1) else: # version & extraversion parts = _mk_incremented_parts(parts, part_idx=0, in_part_idx=-1, incval=1) norm_ver.parts = parts return str(norm_ver)
[ "def", "nextversion", "(", "current_version", ")", ":", "norm_ver", "=", "verlib", ".", "suggest_normalized_version", "(", "current_version", ")", "if", "norm_ver", "is", "None", ":", "return", "None", "norm_ver", "=", "verlib", ".", "NormalizedVersion", "(", "norm_ver", ")", "# increment last version figure", "parts", "=", "norm_ver", ".", "parts", "# see comments of `verlib.py` to get the idea of `parts`", "assert", "(", "len", "(", "parts", ")", "==", "3", ")", "if", "len", "(", "parts", "[", "2", "]", ")", ">", "1", ":", "# postdev", "if", "parts", "[", "2", "]", "[", "-", "1", "]", "==", "'f'", ":", "# when `post` exists but `dev` doesn't", "parts", "=", "_mk_incremented_parts", "(", "parts", ",", "part_idx", "=", "2", ",", "in_part_idx", "=", "-", "2", ",", "incval", "=", "1", ")", "else", ":", "# when both `post` and `dev` exist", "parts", "=", "_mk_incremented_parts", "(", "parts", ",", "part_idx", "=", "2", ",", "in_part_idx", "=", "-", "1", ",", "incval", "=", "1", ")", "elif", "len", "(", "parts", "[", "1", "]", ")", ">", "1", ":", "# prerel", "parts", "=", "_mk_incremented_parts", "(", "parts", ",", "part_idx", "=", "1", ",", "in_part_idx", "=", "-", "1", ",", "incval", "=", "1", ")", "else", ":", "# version & extraversion", "parts", "=", "_mk_incremented_parts", "(", "parts", ",", "part_idx", "=", "0", ",", "in_part_idx", "=", "-", "1", ",", "incval", "=", "1", ")", "norm_ver", ".", "parts", "=", "parts", "return", "str", "(", "norm_ver", ")" ]
Returns incremented module version number. :param current_version: version string to increment :returns: Next version string (PEP 386 compatible) if possible. If impossible (since `current_version` is too far from PEP 386), `None` is returned.
[ "Returns", "incremented", "module", "version", "number", "." ]
49a143dfe64dcb9f83c78ac2ea04774f7df32378
https://github.com/laysakura/nextversion/blob/49a143dfe64dcb9f83c78ac2ea04774f7df32378/nextversion/__init__.py#L21-L48
247,359
bobcolner/urlrap
urlrap/urlrap.py
find_date
def find_date(url): "Extract date from URL page if exists." def _clean_split(div_str): sl = [] for div in div_str.split('/'): div = div.strip().lower() if div != '': sl.append(div) return sl url_path = find_path(url) url_path_parts = _clean_split(url_path) date_parts = [] for part in url_path_parts: try: _dateparse(part) # is part date-like? date_parts.append(part) except ValueError: continue if len(date_parts) == 0: return date_str = '/'.join(date_parts) return _dateparse(date_str)
python
def find_date(url): "Extract date from URL page if exists." def _clean_split(div_str): sl = [] for div in div_str.split('/'): div = div.strip().lower() if div != '': sl.append(div) return sl url_path = find_path(url) url_path_parts = _clean_split(url_path) date_parts = [] for part in url_path_parts: try: _dateparse(part) # is part date-like? date_parts.append(part) except ValueError: continue if len(date_parts) == 0: return date_str = '/'.join(date_parts) return _dateparse(date_str)
[ "def", "find_date", "(", "url", ")", ":", "def", "_clean_split", "(", "div_str", ")", ":", "sl", "=", "[", "]", "for", "div", "in", "div_str", ".", "split", "(", "'/'", ")", ":", "div", "=", "div", ".", "strip", "(", ")", ".", "lower", "(", ")", "if", "div", "!=", "''", ":", "sl", ".", "append", "(", "div", ")", "return", "sl", "url_path", "=", "find_path", "(", "url", ")", "url_path_parts", "=", "_clean_split", "(", "url_path", ")", "date_parts", "=", "[", "]", "for", "part", "in", "url_path_parts", ":", "try", ":", "_dateparse", "(", "part", ")", "# is part date-like?", "date_parts", ".", "append", "(", "part", ")", "except", "ValueError", ":", "continue", "if", "len", "(", "date_parts", ")", "==", "0", ":", "return", "date_str", "=", "'/'", ".", "join", "(", "date_parts", ")", "return", "_dateparse", "(", "date_str", ")" ]
Extract date from URL page if exists.
[ "Extract", "date", "from", "URL", "page", "if", "exists", "." ]
62edbcb8dd9849ac579d01892baff707a841ff0f
https://github.com/bobcolner/urlrap/blob/62edbcb8dd9849ac579d01892baff707a841ff0f/urlrap/urlrap.py#L12-L34
247,360
houluy/chessboard
chessboard/__init__.py
Chessboard.compute_coordinate
def compute_coordinate(self, index): '''Compute two-dimension coordinate from one-dimension list''' j = index%self.board_size i = (index - j) // self.board_size return (i, j)
python
def compute_coordinate(self, index): '''Compute two-dimension coordinate from one-dimension list''' j = index%self.board_size i = (index - j) // self.board_size return (i, j)
[ "def", "compute_coordinate", "(", "self", ",", "index", ")", ":", "j", "=", "index", "%", "self", ".", "board_size", "i", "=", "(", "index", "-", "j", ")", "//", "self", ".", "board_size", "return", "(", "i", ",", "j", ")" ]
Compute two-dimension coordinate from one-dimension list
[ "Compute", "two", "-", "dimension", "coordinate", "from", "one", "-", "dimension", "list" ]
b834819d93d71b492f27780a58dfbb3a107d7e85
https://github.com/houluy/chessboard/blob/b834819d93d71b492f27780a58dfbb3a107d7e85/chessboard/__init__.py#L134-L138
247,361
houluy/chessboard
chessboard/__init__.py
Chessboard.print_pos
def print_pos(self, coordinates=None, pos=None): '''Print the chessboard''' if not pos: pos = self.pos self.graph = [list(map(self._transform, pos[i])) for i in self.pos_range] xaxis = ' '.join([chr(ASC_ONE + _) for _ in range(min(self.board_size, MAX_NUM))]) if (self.board_size > MAX_NUM): xaxis += ' ' xaxis += ' '.join([chr(ASC_A + _ - MAX_NUM) for _ in range(MAX_NUM, min(self.board_size, MAX_CAP))]) if (self.board_size > MAX_CAP): xaxis += ' ' xaxis += ' '.join([chr(ASC_a + _ - MAX_CAP) for _ in range(MAX_CAP, self.board_size)]) print(' ', end='') print(xaxis) for i in range(self.board_size): out = '|'.join(self.graph[i]) if i < MAX_NUM: print(chr(i + ASC_ONE), end='') elif MAX_NUM <= i < MAX_CAP: print(chr(i - MAX_NUM + ASC_A), end='') elif MAX_CAP <= i < MAX_LOW: print(chr(i - MAX_CAP + ASC_a), end='') print('|', end='') #Colorful print if coordinates: for j in range(self.board_size): if (i, j) in coordinates: new_print = cprint params = { 'color': 'w', 'bcolor': 'r', } else: new_print = print params = {} new_print(self._transform(pos[i][j]), end='', **params) print('|', end='') else: print() else: print(out, end='') print('|')
python
def print_pos(self, coordinates=None, pos=None): '''Print the chessboard''' if not pos: pos = self.pos self.graph = [list(map(self._transform, pos[i])) for i in self.pos_range] xaxis = ' '.join([chr(ASC_ONE + _) for _ in range(min(self.board_size, MAX_NUM))]) if (self.board_size > MAX_NUM): xaxis += ' ' xaxis += ' '.join([chr(ASC_A + _ - MAX_NUM) for _ in range(MAX_NUM, min(self.board_size, MAX_CAP))]) if (self.board_size > MAX_CAP): xaxis += ' ' xaxis += ' '.join([chr(ASC_a + _ - MAX_CAP) for _ in range(MAX_CAP, self.board_size)]) print(' ', end='') print(xaxis) for i in range(self.board_size): out = '|'.join(self.graph[i]) if i < MAX_NUM: print(chr(i + ASC_ONE), end='') elif MAX_NUM <= i < MAX_CAP: print(chr(i - MAX_NUM + ASC_A), end='') elif MAX_CAP <= i < MAX_LOW: print(chr(i - MAX_CAP + ASC_a), end='') print('|', end='') #Colorful print if coordinates: for j in range(self.board_size): if (i, j) in coordinates: new_print = cprint params = { 'color': 'w', 'bcolor': 'r', } else: new_print = print params = {} new_print(self._transform(pos[i][j]), end='', **params) print('|', end='') else: print() else: print(out, end='') print('|')
[ "def", "print_pos", "(", "self", ",", "coordinates", "=", "None", ",", "pos", "=", "None", ")", ":", "if", "not", "pos", ":", "pos", "=", "self", ".", "pos", "self", ".", "graph", "=", "[", "list", "(", "map", "(", "self", ".", "_transform", ",", "pos", "[", "i", "]", ")", ")", "for", "i", "in", "self", ".", "pos_range", "]", "xaxis", "=", "' '", ".", "join", "(", "[", "chr", "(", "ASC_ONE", "+", "_", ")", "for", "_", "in", "range", "(", "min", "(", "self", ".", "board_size", ",", "MAX_NUM", ")", ")", "]", ")", "if", "(", "self", ".", "board_size", ">", "MAX_NUM", ")", ":", "xaxis", "+=", "' '", "xaxis", "+=", "' '", ".", "join", "(", "[", "chr", "(", "ASC_A", "+", "_", "-", "MAX_NUM", ")", "for", "_", "in", "range", "(", "MAX_NUM", ",", "min", "(", "self", ".", "board_size", ",", "MAX_CAP", ")", ")", "]", ")", "if", "(", "self", ".", "board_size", ">", "MAX_CAP", ")", ":", "xaxis", "+=", "' '", "xaxis", "+=", "' '", ".", "join", "(", "[", "chr", "(", "ASC_a", "+", "_", "-", "MAX_CAP", ")", "for", "_", "in", "range", "(", "MAX_CAP", ",", "self", ".", "board_size", ")", "]", ")", "print", "(", "' '", ",", "end", "=", "''", ")", "print", "(", "xaxis", ")", "for", "i", "in", "range", "(", "self", ".", "board_size", ")", ":", "out", "=", "'|'", ".", "join", "(", "self", ".", "graph", "[", "i", "]", ")", "if", "i", "<", "MAX_NUM", ":", "print", "(", "chr", "(", "i", "+", "ASC_ONE", ")", ",", "end", "=", "''", ")", "elif", "MAX_NUM", "<=", "i", "<", "MAX_CAP", ":", "print", "(", "chr", "(", "i", "-", "MAX_NUM", "+", "ASC_A", ")", ",", "end", "=", "''", ")", "elif", "MAX_CAP", "<=", "i", "<", "MAX_LOW", ":", "print", "(", "chr", "(", "i", "-", "MAX_CAP", "+", "ASC_a", ")", ",", "end", "=", "''", ")", "print", "(", "'|'", ",", "end", "=", "''", ")", "#Colorful print", "if", "coordinates", ":", "for", "j", "in", "range", "(", "self", ".", "board_size", ")", ":", "if", "(", "i", ",", "j", ")", "in", "coordinates", ":", "new_print", "=", "cprint", "params", "=", "{", "'color'", ":", "'w'", ",", "'bcolor'", ":", "'r'", ",", "}", "else", ":", "new_print", "=", "print", "params", "=", "{", "}", "new_print", "(", "self", ".", "_transform", "(", "pos", "[", "i", "]", "[", "j", "]", ")", ",", "end", "=", "''", ",", "*", "*", "params", ")", "print", "(", "'|'", ",", "end", "=", "''", ")", "else", ":", "print", "(", ")", "else", ":", "print", "(", "out", ",", "end", "=", "''", ")", "print", "(", "'|'", ")" ]
Print the chessboard
[ "Print", "the", "chessboard" ]
b834819d93d71b492f27780a58dfbb3a107d7e85
https://github.com/houluy/chessboard/blob/b834819d93d71b492f27780a58dfbb3a107d7e85/chessboard/__init__.py#L165-L206
247,362
houluy/chessboard
chessboard/__init__.py
Chessboard.set_pos
def set_pos(self, pos, check=False): '''Set a chess''' self.validate_pos(pos) x, y = pos user = self.get_player() self.history[self._game_round] = copy.deepcopy(self.pos) self.pos[x][y] = user pos_str = self._cal_key(pos) self._pos_dict[pos_str] = user self._user_pos_dict[user].append(pos) self._game_round += 1 if check: winning = self.check_win_by_step(x, y, user) return winning else: return (x, y)
python
def set_pos(self, pos, check=False): '''Set a chess''' self.validate_pos(pos) x, y = pos user = self.get_player() self.history[self._game_round] = copy.deepcopy(self.pos) self.pos[x][y] = user pos_str = self._cal_key(pos) self._pos_dict[pos_str] = user self._user_pos_dict[user].append(pos) self._game_round += 1 if check: winning = self.check_win_by_step(x, y, user) return winning else: return (x, y)
[ "def", "set_pos", "(", "self", ",", "pos", ",", "check", "=", "False", ")", ":", "self", ".", "validate_pos", "(", "pos", ")", "x", ",", "y", "=", "pos", "user", "=", "self", ".", "get_player", "(", ")", "self", ".", "history", "[", "self", ".", "_game_round", "]", "=", "copy", ".", "deepcopy", "(", "self", ".", "pos", ")", "self", ".", "pos", "[", "x", "]", "[", "y", "]", "=", "user", "pos_str", "=", "self", ".", "_cal_key", "(", "pos", ")", "self", ".", "_pos_dict", "[", "pos_str", "]", "=", "user", "self", ".", "_user_pos_dict", "[", "user", "]", ".", "append", "(", "pos", ")", "self", ".", "_game_round", "+=", "1", "if", "check", ":", "winning", "=", "self", ".", "check_win_by_step", "(", "x", ",", "y", ",", "user", ")", "return", "winning", "else", ":", "return", "(", "x", ",", "y", ")" ]
Set a chess
[ "Set", "a", "chess" ]
b834819d93d71b492f27780a58dfbb3a107d7e85
https://github.com/houluy/chessboard/blob/b834819d93d71b492f27780a58dfbb3a107d7e85/chessboard/__init__.py#L235-L250
247,363
houluy/chessboard
chessboard/__init__.py
Chessboard.clear
def clear(self): '''Clear a chessboard''' self.pos = [[0 for _ in range(self.board_size)] for _ in range(self.board_size)] self.graph = copy.deepcopy(self.pos) self._game_round = 1
python
def clear(self): '''Clear a chessboard''' self.pos = [[0 for _ in range(self.board_size)] for _ in range(self.board_size)] self.graph = copy.deepcopy(self.pos) self._game_round = 1
[ "def", "clear", "(", "self", ")", ":", "self", ".", "pos", "=", "[", "[", "0", "for", "_", "in", "range", "(", "self", ".", "board_size", ")", "]", "for", "_", "in", "range", "(", "self", ".", "board_size", ")", "]", "self", ".", "graph", "=", "copy", ".", "deepcopy", "(", "self", ".", "pos", ")", "self", ".", "_game_round", "=", "1" ]
Clear a chessboard
[ "Clear", "a", "chessboard" ]
b834819d93d71b492f27780a58dfbb3a107d7e85
https://github.com/houluy/chessboard/blob/b834819d93d71b492f27780a58dfbb3a107d7e85/chessboard/__init__.py#L258-L262
247,364
houluy/chessboard
chessboard/__init__.py
Chessboard.handle_input
def handle_input(self, input_str, place=True, check=False): '''Transfer user input to valid chess position''' user = self.get_player() pos = self.validate_input(input_str) if pos[0] == 'u': self.undo(pos[1]) return pos if place: result = self.set_pos(pos, check) return result else: return pos
python
def handle_input(self, input_str, place=True, check=False): '''Transfer user input to valid chess position''' user = self.get_player() pos = self.validate_input(input_str) if pos[0] == 'u': self.undo(pos[1]) return pos if place: result = self.set_pos(pos, check) return result else: return pos
[ "def", "handle_input", "(", "self", ",", "input_str", ",", "place", "=", "True", ",", "check", "=", "False", ")", ":", "user", "=", "self", ".", "get_player", "(", ")", "pos", "=", "self", ".", "validate_input", "(", "input_str", ")", "if", "pos", "[", "0", "]", "==", "'u'", ":", "self", ".", "undo", "(", "pos", "[", "1", "]", ")", "return", "pos", "if", "place", ":", "result", "=", "self", ".", "set_pos", "(", "pos", ",", "check", ")", "return", "result", "else", ":", "return", "pos" ]
Transfer user input to valid chess position
[ "Transfer", "user", "input", "to", "valid", "chess", "position" ]
b834819d93d71b492f27780a58dfbb3a107d7e85
https://github.com/houluy/chessboard/blob/b834819d93d71b492f27780a58dfbb3a107d7e85/chessboard/__init__.py#L314-L325
247,365
houluy/chessboard
chessboard/__init__.py
Chessboard.check_win_by_step
def check_win_by_step(self, x, y, user, line_number=None): '''Check winners by current step''' if not line_number: line_number = self.win for ang in self.angle: self.win_list = [(x, y)] angs = [ang, ang + math.pi] line_num = 1 radius = 1 direction = [1, 1] while True: if line_num == line_number: return True if direction == [0, 0]: break for ind, a in enumerate(angs): target_x = int(x + radius*(sign(math.cos(a)))) if direction[ind] else -1 target_y = int(y - radius*(sign(math.sin(a)))) if direction[ind] else -1 if target_x < 0 or target_y < 0 or target_x > self.board_size - 1 or target_y > self.board_size - 1: direction[ind] = 0 elif self.pos[target_x][target_y] == user: self.win_list.append((target_x, target_y)) line_num += 1 else: direction[ind] = 0 else: radius += 1 else: return (x, y)
python
def check_win_by_step(self, x, y, user, line_number=None): '''Check winners by current step''' if not line_number: line_number = self.win for ang in self.angle: self.win_list = [(x, y)] angs = [ang, ang + math.pi] line_num = 1 radius = 1 direction = [1, 1] while True: if line_num == line_number: return True if direction == [0, 0]: break for ind, a in enumerate(angs): target_x = int(x + radius*(sign(math.cos(a)))) if direction[ind] else -1 target_y = int(y - radius*(sign(math.sin(a)))) if direction[ind] else -1 if target_x < 0 or target_y < 0 or target_x > self.board_size - 1 or target_y > self.board_size - 1: direction[ind] = 0 elif self.pos[target_x][target_y] == user: self.win_list.append((target_x, target_y)) line_num += 1 else: direction[ind] = 0 else: radius += 1 else: return (x, y)
[ "def", "check_win_by_step", "(", "self", ",", "x", ",", "y", ",", "user", ",", "line_number", "=", "None", ")", ":", "if", "not", "line_number", ":", "line_number", "=", "self", ".", "win", "for", "ang", "in", "self", ".", "angle", ":", "self", ".", "win_list", "=", "[", "(", "x", ",", "y", ")", "]", "angs", "=", "[", "ang", ",", "ang", "+", "math", ".", "pi", "]", "line_num", "=", "1", "radius", "=", "1", "direction", "=", "[", "1", ",", "1", "]", "while", "True", ":", "if", "line_num", "==", "line_number", ":", "return", "True", "if", "direction", "==", "[", "0", ",", "0", "]", ":", "break", "for", "ind", ",", "a", "in", "enumerate", "(", "angs", ")", ":", "target_x", "=", "int", "(", "x", "+", "radius", "*", "(", "sign", "(", "math", ".", "cos", "(", "a", ")", ")", ")", ")", "if", "direction", "[", "ind", "]", "else", "-", "1", "target_y", "=", "int", "(", "y", "-", "radius", "*", "(", "sign", "(", "math", ".", "sin", "(", "a", ")", ")", ")", ")", "if", "direction", "[", "ind", "]", "else", "-", "1", "if", "target_x", "<", "0", "or", "target_y", "<", "0", "or", "target_x", ">", "self", ".", "board_size", "-", "1", "or", "target_y", ">", "self", ".", "board_size", "-", "1", ":", "direction", "[", "ind", "]", "=", "0", "elif", "self", ".", "pos", "[", "target_x", "]", "[", "target_y", "]", "==", "user", ":", "self", ".", "win_list", ".", "append", "(", "(", "target_x", ",", "target_y", ")", ")", "line_num", "+=", "1", "else", ":", "direction", "[", "ind", "]", "=", "0", "else", ":", "radius", "+=", "1", "else", ":", "return", "(", "x", ",", "y", ")" ]
Check winners by current step
[ "Check", "winners", "by", "current", "step" ]
b834819d93d71b492f27780a58dfbb3a107d7e85
https://github.com/houluy/chessboard/blob/b834819d93d71b492f27780a58dfbb3a107d7e85/chessboard/__init__.py#L331-L359
247,366
houluy/chessboard
chessboard/__init__.py
Chessboard.get_not_num
def get_not_num(self, seq, num=0): '''Find the index of first non num element''' ind = next((i for i, x in enumerate(seq) if x != num), None) if ind == None: return self.board_size else: return ind
python
def get_not_num(self, seq, num=0): '''Find the index of first non num element''' ind = next((i for i, x in enumerate(seq) if x != num), None) if ind == None: return self.board_size else: return ind
[ "def", "get_not_num", "(", "self", ",", "seq", ",", "num", "=", "0", ")", ":", "ind", "=", "next", "(", "(", "i", "for", "i", ",", "x", "in", "enumerate", "(", "seq", ")", "if", "x", "!=", "num", ")", ",", "None", ")", "if", "ind", "==", "None", ":", "return", "self", ".", "board_size", "else", ":", "return", "ind" ]
Find the index of first non num element
[ "Find", "the", "index", "of", "first", "non", "num", "element" ]
b834819d93d71b492f27780a58dfbb3a107d7e85
https://github.com/houluy/chessboard/blob/b834819d93d71b492f27780a58dfbb3a107d7e85/chessboard/__init__.py#L361-L367
247,367
houluy/chessboard
chessboard/__init__.py
ChessboardExtension.compare_board
def compare_board(self, dst, src=None): '''Compare two chessboard''' if not src: src = self.pos if src == dst: return True else: #May return details return False
python
def compare_board(self, dst, src=None): '''Compare two chessboard''' if not src: src = self.pos if src == dst: return True else: #May return details return False
[ "def", "compare_board", "(", "self", ",", "dst", ",", "src", "=", "None", ")", ":", "if", "not", "src", ":", "src", "=", "self", ".", "pos", "if", "src", "==", "dst", ":", "return", "True", "else", ":", "#May return details", "return", "False" ]
Compare two chessboard
[ "Compare", "two", "chessboard" ]
b834819d93d71b492f27780a58dfbb3a107d7e85
https://github.com/houluy/chessboard/blob/b834819d93d71b492f27780a58dfbb3a107d7e85/chessboard/__init__.py#L390-L399
247,368
treycucco/bidon
bidon/data_table.py
reduce_number
def reduce_number(num): """Reduces the string representation of a number. If the number is of the format n.00..., returns n. If the decimal portion of the number has a repeating decimal, followed by up to two trailing numbers, such as: 0.3333333 or 0.343434346 It will return just one instance of the repeating decimals: 0.3 or 0.34 """ parts = str(num).split(".") if len(parts) == 1 or parts[1] == "0": return int(parts[0]) else: match = _REPEATING_NUMBER_TRIM_RE.search(parts[1]) if match: from_index, _ = match.span() if from_index == 0 and match.group(2) == "0": return int(parts[0]) else: return Decimal(parts[0] + "." + parts[1][:from_index] + match.group(2)) else: return num
python
def reduce_number(num): """Reduces the string representation of a number. If the number is of the format n.00..., returns n. If the decimal portion of the number has a repeating decimal, followed by up to two trailing numbers, such as: 0.3333333 or 0.343434346 It will return just one instance of the repeating decimals: 0.3 or 0.34 """ parts = str(num).split(".") if len(parts) == 1 or parts[1] == "0": return int(parts[0]) else: match = _REPEATING_NUMBER_TRIM_RE.search(parts[1]) if match: from_index, _ = match.span() if from_index == 0 and match.group(2) == "0": return int(parts[0]) else: return Decimal(parts[0] + "." + parts[1][:from_index] + match.group(2)) else: return num
[ "def", "reduce_number", "(", "num", ")", ":", "parts", "=", "str", "(", "num", ")", ".", "split", "(", "\".\"", ")", "if", "len", "(", "parts", ")", "==", "1", "or", "parts", "[", "1", "]", "==", "\"0\"", ":", "return", "int", "(", "parts", "[", "0", "]", ")", "else", ":", "match", "=", "_REPEATING_NUMBER_TRIM_RE", ".", "search", "(", "parts", "[", "1", "]", ")", "if", "match", ":", "from_index", ",", "_", "=", "match", ".", "span", "(", ")", "if", "from_index", "==", "0", "and", "match", ".", "group", "(", "2", ")", "==", "\"0\"", ":", "return", "int", "(", "parts", "[", "0", "]", ")", "else", ":", "return", "Decimal", "(", "parts", "[", "0", "]", "+", "\".\"", "+", "parts", "[", "1", "]", "[", ":", "from_index", "]", "+", "match", ".", "group", "(", "2", ")", ")", "else", ":", "return", "num" ]
Reduces the string representation of a number. If the number is of the format n.00..., returns n. If the decimal portion of the number has a repeating decimal, followed by up to two trailing numbers, such as: 0.3333333 or 0.343434346 It will return just one instance of the repeating decimals: 0.3 or 0.34
[ "Reduces", "the", "string", "representation", "of", "a", "number", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/data_table.py#L12-L45
247,369
treycucco/bidon
bidon/data_table.py
DataTable.is_cell_empty
def is_cell_empty(self, cell): """Checks if the cell is empty.""" if cell is None: return True elif self._is_cell_empty: return self._is_cell_empty(cell) else: return cell is None
python
def is_cell_empty(self, cell): """Checks if the cell is empty.""" if cell is None: return True elif self._is_cell_empty: return self._is_cell_empty(cell) else: return cell is None
[ "def", "is_cell_empty", "(", "self", ",", "cell", ")", ":", "if", "cell", "is", "None", ":", "return", "True", "elif", "self", ".", "_is_cell_empty", ":", "return", "self", ".", "_is_cell_empty", "(", "cell", ")", "else", ":", "return", "cell", "is", "None" ]
Checks if the cell is empty.
[ "Checks", "if", "the", "cell", "is", "empty", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/data_table.py#L87-L94
247,370
treycucco/bidon
bidon/data_table.py
DataTable.is_row_empty
def is_row_empty(self, row): """Returns True if every cell in the row is empty.""" for cell in row: if not self.is_cell_empty(cell): return False return True
python
def is_row_empty(self, row): """Returns True if every cell in the row is empty.""" for cell in row: if not self.is_cell_empty(cell): return False return True
[ "def", "is_row_empty", "(", "self", ",", "row", ")", ":", "for", "cell", "in", "row", ":", "if", "not", "self", ".", "is_cell_empty", "(", "cell", ")", ":", "return", "False", "return", "True" ]
Returns True if every cell in the row is empty.
[ "Returns", "True", "if", "every", "cell", "in", "the", "row", "is", "empty", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/data_table.py#L96-L101
247,371
treycucco/bidon
bidon/data_table.py
DataTable.serialize
def serialize(self, serialize_cell=None): """Returns a list of all rows, with serialize_cell or self.get_cell_value called on the cells of each. """ if serialize_cell is None: serialize_cell = self.get_cell_value return [[serialize_cell(cell) for cell in row] for row in self.rows]
python
def serialize(self, serialize_cell=None): """Returns a list of all rows, with serialize_cell or self.get_cell_value called on the cells of each. """ if serialize_cell is None: serialize_cell = self.get_cell_value return [[serialize_cell(cell) for cell in row] for row in self.rows]
[ "def", "serialize", "(", "self", ",", "serialize_cell", "=", "None", ")", ":", "if", "serialize_cell", "is", "None", ":", "serialize_cell", "=", "self", ".", "get_cell_value", "return", "[", "[", "serialize_cell", "(", "cell", ")", "for", "cell", "in", "row", "]", "for", "row", "in", "self", ".", "rows", "]" ]
Returns a list of all rows, with serialize_cell or self.get_cell_value called on the cells of each.
[ "Returns", "a", "list", "of", "all", "rows", "with", "serialize_cell", "or", "self", ".", "get_cell_value", "called", "on", "the", "cells", "of", "each", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/data_table.py#L103-L109
247,372
treycucco/bidon
bidon/data_table.py
DataTable.headers
def headers(self, serialize_cell=None): """Gets the first row of the data table, with serialize_cell or self.get_cell_value is called on each cell.""" if serialize_cell is None: serialize_cell = self.get_cell_value return [serialize_cell(cell) for cell in self.rows[0]]
python
def headers(self, serialize_cell=None): """Gets the first row of the data table, with serialize_cell or self.get_cell_value is called on each cell.""" if serialize_cell is None: serialize_cell = self.get_cell_value return [serialize_cell(cell) for cell in self.rows[0]]
[ "def", "headers", "(", "self", ",", "serialize_cell", "=", "None", ")", ":", "if", "serialize_cell", "is", "None", ":", "serialize_cell", "=", "self", ".", "get_cell_value", "return", "[", "serialize_cell", "(", "cell", ")", "for", "cell", "in", "self", ".", "rows", "[", "0", "]", "]" ]
Gets the first row of the data table, with serialize_cell or self.get_cell_value is called on each cell.
[ "Gets", "the", "first", "row", "of", "the", "data", "table", "with", "serialize_cell", "or", "self", ".", "get_cell_value", "is", "called", "on", "each", "cell", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/data_table.py#L111-L116
247,373
treycucco/bidon
bidon/data_table.py
DataTable.trim_empty_rows
def trim_empty_rows(self): """Remove all trailing empty rows.""" if self.nrows != 0: row_index = 0 for row_index, row in enumerate(reversed(self.rows)): if not self.is_row_empty(row): break self.nrows = len(self.rows) - row_index self.rows = self.rows[:self.nrows] return self
python
def trim_empty_rows(self): """Remove all trailing empty rows.""" if self.nrows != 0: row_index = 0 for row_index, row in enumerate(reversed(self.rows)): if not self.is_row_empty(row): break self.nrows = len(self.rows) - row_index self.rows = self.rows[:self.nrows] return self
[ "def", "trim_empty_rows", "(", "self", ")", ":", "if", "self", ".", "nrows", "!=", "0", ":", "row_index", "=", "0", "for", "row_index", ",", "row", "in", "enumerate", "(", "reversed", "(", "self", ".", "rows", ")", ")", ":", "if", "not", "self", ".", "is_row_empty", "(", "row", ")", ":", "break", "self", ".", "nrows", "=", "len", "(", "self", ".", "rows", ")", "-", "row_index", "self", ".", "rows", "=", "self", ".", "rows", "[", ":", "self", ".", "nrows", "]", "return", "self" ]
Remove all trailing empty rows.
[ "Remove", "all", "trailing", "empty", "rows", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/data_table.py#L138-L147
247,374
treycucco/bidon
bidon/data_table.py
DataTable.trim_empty_columns
def trim_empty_columns(self): """Removes all trailing empty columns.""" if self.nrows != 0 and self.ncols != 0: last_col = -1 for row in self.rows: for i in range(last_col + 1, len(row)): if not self.is_cell_empty(row[i]): last_col = i ncols = last_col + 1 self.rows = [row[:ncols] for row in self.rows] self.ncols = ncols return self
python
def trim_empty_columns(self): """Removes all trailing empty columns.""" if self.nrows != 0 and self.ncols != 0: last_col = -1 for row in self.rows: for i in range(last_col + 1, len(row)): if not self.is_cell_empty(row[i]): last_col = i ncols = last_col + 1 self.rows = [row[:ncols] for row in self.rows] self.ncols = ncols return self
[ "def", "trim_empty_columns", "(", "self", ")", ":", "if", "self", ".", "nrows", "!=", "0", "and", "self", ".", "ncols", "!=", "0", ":", "last_col", "=", "-", "1", "for", "row", "in", "self", ".", "rows", ":", "for", "i", "in", "range", "(", "last_col", "+", "1", ",", "len", "(", "row", ")", ")", ":", "if", "not", "self", ".", "is_cell_empty", "(", "row", "[", "i", "]", ")", ":", "last_col", "=", "i", "ncols", "=", "last_col", "+", "1", "self", ".", "rows", "=", "[", "row", "[", ":", "ncols", "]", "for", "row", "in", "self", ".", "rows", "]", "self", ".", "ncols", "=", "ncols", "return", "self" ]
Removes all trailing empty columns.
[ "Removes", "all", "trailing", "empty", "columns", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/data_table.py#L149-L160
247,375
treycucco/bidon
bidon/data_table.py
DataTable.clean_values
def clean_values(self): """Cleans the values in each cell. Calls either the user provided clean_value, or the class defined clean value. """ for row in self.rows: for index, cell in enumerate(row): self.set_cell_value(row, index, self.clean_value(self.get_cell_value(cell))) return self
python
def clean_values(self): """Cleans the values in each cell. Calls either the user provided clean_value, or the class defined clean value. """ for row in self.rows: for index, cell in enumerate(row): self.set_cell_value(row, index, self.clean_value(self.get_cell_value(cell))) return self
[ "def", "clean_values", "(", "self", ")", ":", "for", "row", "in", "self", ".", "rows", ":", "for", "index", ",", "cell", "in", "enumerate", "(", "row", ")", ":", "self", ".", "set_cell_value", "(", "row", ",", "index", ",", "self", ".", "clean_value", "(", "self", ".", "get_cell_value", "(", "cell", ")", ")", ")", "return", "self" ]
Cleans the values in each cell. Calls either the user provided clean_value, or the class defined clean value.
[ "Cleans", "the", "values", "in", "each", "cell", ".", "Calls", "either", "the", "user", "provided", "clean_value", "or", "the", "class", "defined", "clean", "value", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/data_table.py#L162-L169
247,376
treycucco/bidon
bidon/data_table.py
DataTable.clean_value
def clean_value(self, value): """Cleans a value, using either the user provided clean_value, or cls.reduce_value.""" if self._clean_value: return self._clean_value(value) else: return self.reduce_value(value)
python
def clean_value(self, value): """Cleans a value, using either the user provided clean_value, or cls.reduce_value.""" if self._clean_value: return self._clean_value(value) else: return self.reduce_value(value)
[ "def", "clean_value", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_clean_value", ":", "return", "self", ".", "_clean_value", "(", "value", ")", "else", ":", "return", "self", ".", "reduce_value", "(", "value", ")" ]
Cleans a value, using either the user provided clean_value, or cls.reduce_value.
[ "Cleans", "a", "value", "using", "either", "the", "user", "provided", "clean_value", "or", "cls", ".", "reduce_value", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/data_table.py#L171-L176
247,377
treycucco/bidon
bidon/data_table.py
DataTable.reduce_value
def reduce_value(cls, value): """Cleans the value by either compressing it if it is a string, or reducing it if it is a number. """ if isinstance(value, str): return to_compressed_string(value) elif isinstance(value, bool): return value elif isinstance(value, Number): return reduce_number(value) else: return value
python
def reduce_value(cls, value): """Cleans the value by either compressing it if it is a string, or reducing it if it is a number. """ if isinstance(value, str): return to_compressed_string(value) elif isinstance(value, bool): return value elif isinstance(value, Number): return reduce_number(value) else: return value
[ "def", "reduce_value", "(", "cls", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "return", "to_compressed_string", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "bool", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "Number", ")", ":", "return", "reduce_number", "(", "value", ")", "else", ":", "return", "value" ]
Cleans the value by either compressing it if it is a string, or reducing it if it is a number.
[ "Cleans", "the", "value", "by", "either", "compressing", "it", "if", "it", "is", "a", "string", "or", "reducing", "it", "if", "it", "is", "a", "number", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/data_table.py#L179-L190
247,378
rsalmei/about-time
about_time/about_time.py
about_time
def about_time(fn=None, it=None): """Measures the execution time of a block of code, and even counts iterations and the throughput of them, always with a beautiful "human" representation. There's three modes of operation: context manager, callable handler and iterator metrics. 1. Use it like a context manager: >>> with about_time() as t_whole: .... with about_time() as t_1: .... func_1() .... with about_time() as t_2: .... func_2('params') >>> print(f'func_1 time: {t_1.duration_human}') >>> print(f'func_2 time: {t_2.duration_human}') >>> print(f'total time: {t_whole.duration_human}') The actual duration in seconds is available in: >>> secs = t_whole.duration 2. You can also use it like a callable handler: >>> t_1 = about_time(func_1) >>> t_2 = about_time(lambda: func_2('params')) Use the field `result` to get the outcome of the function. Or you mix and match both: >>> with about_time() as t_whole: .... t_1 = about_time(func_1) .... t_2 = about_time(lambda: func_2('params')) 3. And you can count and, since we have duration, also measure the throughput of an iterator block, specially useful in generators, which do not have length, but you can use with any iterables: >>> def callback(t_func): .... logger.info('func: size=%d throughput=%s', t_func.count, .... t_func.throughput_human) >>> items = filter(...) >>> for item in about_time(callback, items): .... # use item any way you want. .... pass """ # has to be here to be mockable. if sys.version_info >= (3, 3): timer = time.perf_counter else: # pragma: no cover timer = time.time @contextmanager def context(): timings[0] = timer() yield handle timings[1] = timer() timings = [0.0, 0.0] handle = Handle(timings) if it is None: # use as context manager. if fn is None: return context() # use as callable handler. with context(): result = fn() return HandleResult(timings, result) # use as counter/throughput iterator. if fn is None or not callable(fn): # handles inversion of parameters. raise UserWarning('use as about_time(callback, iterable) in counter/throughput mode.') def counter(): i = -1 with context(): for i, elem in enumerate(it): yield elem fn(HandleStats(timings, i + 1)) return counter()
python
def about_time(fn=None, it=None): """Measures the execution time of a block of code, and even counts iterations and the throughput of them, always with a beautiful "human" representation. There's three modes of operation: context manager, callable handler and iterator metrics. 1. Use it like a context manager: >>> with about_time() as t_whole: .... with about_time() as t_1: .... func_1() .... with about_time() as t_2: .... func_2('params') >>> print(f'func_1 time: {t_1.duration_human}') >>> print(f'func_2 time: {t_2.duration_human}') >>> print(f'total time: {t_whole.duration_human}') The actual duration in seconds is available in: >>> secs = t_whole.duration 2. You can also use it like a callable handler: >>> t_1 = about_time(func_1) >>> t_2 = about_time(lambda: func_2('params')) Use the field `result` to get the outcome of the function. Or you mix and match both: >>> with about_time() as t_whole: .... t_1 = about_time(func_1) .... t_2 = about_time(lambda: func_2('params')) 3. And you can count and, since we have duration, also measure the throughput of an iterator block, specially useful in generators, which do not have length, but you can use with any iterables: >>> def callback(t_func): .... logger.info('func: size=%d throughput=%s', t_func.count, .... t_func.throughput_human) >>> items = filter(...) >>> for item in about_time(callback, items): .... # use item any way you want. .... pass """ # has to be here to be mockable. if sys.version_info >= (3, 3): timer = time.perf_counter else: # pragma: no cover timer = time.time @contextmanager def context(): timings[0] = timer() yield handle timings[1] = timer() timings = [0.0, 0.0] handle = Handle(timings) if it is None: # use as context manager. if fn is None: return context() # use as callable handler. with context(): result = fn() return HandleResult(timings, result) # use as counter/throughput iterator. if fn is None or not callable(fn): # handles inversion of parameters. raise UserWarning('use as about_time(callback, iterable) in counter/throughput mode.') def counter(): i = -1 with context(): for i, elem in enumerate(it): yield elem fn(HandleStats(timings, i + 1)) return counter()
[ "def", "about_time", "(", "fn", "=", "None", ",", "it", "=", "None", ")", ":", "# has to be here to be mockable.", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "3", ")", ":", "timer", "=", "time", ".", "perf_counter", "else", ":", "# pragma: no cover", "timer", "=", "time", ".", "time", "@", "contextmanager", "def", "context", "(", ")", ":", "timings", "[", "0", "]", "=", "timer", "(", ")", "yield", "handle", "timings", "[", "1", "]", "=", "timer", "(", ")", "timings", "=", "[", "0.0", ",", "0.0", "]", "handle", "=", "Handle", "(", "timings", ")", "if", "it", "is", "None", ":", "# use as context manager.", "if", "fn", "is", "None", ":", "return", "context", "(", ")", "# use as callable handler.", "with", "context", "(", ")", ":", "result", "=", "fn", "(", ")", "return", "HandleResult", "(", "timings", ",", "result", ")", "# use as counter/throughput iterator.", "if", "fn", "is", "None", "or", "not", "callable", "(", "fn", ")", ":", "# handles inversion of parameters.", "raise", "UserWarning", "(", "'use as about_time(callback, iterable) in counter/throughput mode.'", ")", "def", "counter", "(", ")", ":", "i", "=", "-", "1", "with", "context", "(", ")", ":", "for", "i", ",", "elem", "in", "enumerate", "(", "it", ")", ":", "yield", "elem", "fn", "(", "HandleStats", "(", "timings", ",", "i", "+", "1", ")", ")", "return", "counter", "(", ")" ]
Measures the execution time of a block of code, and even counts iterations and the throughput of them, always with a beautiful "human" representation. There's three modes of operation: context manager, callable handler and iterator metrics. 1. Use it like a context manager: >>> with about_time() as t_whole: .... with about_time() as t_1: .... func_1() .... with about_time() as t_2: .... func_2('params') >>> print(f'func_1 time: {t_1.duration_human}') >>> print(f'func_2 time: {t_2.duration_human}') >>> print(f'total time: {t_whole.duration_human}') The actual duration in seconds is available in: >>> secs = t_whole.duration 2. You can also use it like a callable handler: >>> t_1 = about_time(func_1) >>> t_2 = about_time(lambda: func_2('params')) Use the field `result` to get the outcome of the function. Or you mix and match both: >>> with about_time() as t_whole: .... t_1 = about_time(func_1) .... t_2 = about_time(lambda: func_2('params')) 3. And you can count and, since we have duration, also measure the throughput of an iterator block, specially useful in generators, which do not have length, but you can use with any iterables: >>> def callback(t_func): .... logger.info('func: size=%d throughput=%s', t_func.count, .... t_func.throughput_human) >>> items = filter(...) >>> for item in about_time(callback, items): .... # use item any way you want. .... pass
[ "Measures", "the", "execution", "time", "of", "a", "block", "of", "code", "and", "even", "counts", "iterations", "and", "the", "throughput", "of", "them", "always", "with", "a", "beautiful", "human", "representation", "." ]
5dd0165a3a4cf6c6f8c4ad2fbb50e44b136a3077
https://github.com/rsalmei/about-time/blob/5dd0165a3a4cf6c6f8c4ad2fbb50e44b136a3077/about_time/about_time.py#L9-L93
247,379
dansackett/django-toolset
django_toolset/templatetags/custom_filters.py
method
def method(value, arg): """Method attempts to see if the value has a specified method. Usage: {% load custom_filters %} {% if foo|method:"has_access" %} """ if hasattr(value, str(arg)): return getattr(value, str(arg)) return "[%s has no method %s]" % (value, arg)
python
def method(value, arg): """Method attempts to see if the value has a specified method. Usage: {% load custom_filters %} {% if foo|method:"has_access" %} """ if hasattr(value, str(arg)): return getattr(value, str(arg)) return "[%s has no method %s]" % (value, arg)
[ "def", "method", "(", "value", ",", "arg", ")", ":", "if", "hasattr", "(", "value", ",", "str", "(", "arg", ")", ")", ":", "return", "getattr", "(", "value", ",", "str", "(", "arg", ")", ")", "return", "\"[%s has no method %s]\"", "%", "(", "value", ",", "arg", ")" ]
Method attempts to see if the value has a specified method. Usage: {% load custom_filters %} {% if foo|method:"has_access" %}
[ "Method", "attempts", "to", "see", "if", "the", "value", "has", "a", "specified", "method", "." ]
a28cc19e32cf41130e848c268d26c1858a7cf26a
https://github.com/dansackett/django-toolset/blob/a28cc19e32cf41130e848c268d26c1858a7cf26a/django_toolset/templatetags/custom_filters.py#L9-L20
247,380
mickbad/mblibs
mblibs/fast.py
FastLogger.setLevel
def setLevel(self, level): """ Changement du niveau du Log """ if isinstance(level, int): self.logger.setLevel(level) return # level en tant que string level = level.lower() if level == "debug": self.logger.setLevel(logging.DEBUG) elif level == "info": self.logger.setLevel(logging.INFO) elif level == "warning" or level == "warning": self.logger.setLevel(logging.WARN) elif level == "error": self.logger.setLevel(logging.ERROR) else: # par défaut self.logger.setLevel(logging.INFO)
python
def setLevel(self, level): """ Changement du niveau du Log """ if isinstance(level, int): self.logger.setLevel(level) return # level en tant que string level = level.lower() if level == "debug": self.logger.setLevel(logging.DEBUG) elif level == "info": self.logger.setLevel(logging.INFO) elif level == "warning" or level == "warning": self.logger.setLevel(logging.WARN) elif level == "error": self.logger.setLevel(logging.ERROR) else: # par défaut self.logger.setLevel(logging.INFO)
[ "def", "setLevel", "(", "self", ",", "level", ")", ":", "if", "isinstance", "(", "level", ",", "int", ")", ":", "self", ".", "logger", ".", "setLevel", "(", "level", ")", "return", "# level en tant que string", "level", "=", "level", ".", "lower", "(", ")", "if", "level", "==", "\"debug\"", ":", "self", ".", "logger", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "elif", "level", "==", "\"info\"", ":", "self", ".", "logger", ".", "setLevel", "(", "logging", ".", "INFO", ")", "elif", "level", "==", "\"warning\"", "or", "level", "==", "\"warning\"", ":", "self", ".", "logger", ".", "setLevel", "(", "logging", ".", "WARN", ")", "elif", "level", "==", "\"error\"", ":", "self", ".", "logger", ".", "setLevel", "(", "logging", ".", "ERROR", ")", "else", ":", "# par défaut", "self", ".", "logger", ".", "setLevel", "(", "logging", ".", "INFO", ")" ]
Changement du niveau du Log
[ "Changement", "du", "niveau", "du", "Log" ]
c1f423ef107c94e2ab6bd253e9148f6056e0ef75
https://github.com/mickbad/mblibs/blob/c1f423ef107c94e2ab6bd253e9148f6056e0ef75/mblibs/fast.py#L499-L521
247,381
mickbad/mblibs
mblibs/fast.py
FastLogger.info
def info(self, text): """ Ajout d'un message de log de type INFO """ self.logger.info("{}{}".format(self.message_prefix, text))
python
def info(self, text): """ Ajout d'un message de log de type INFO """ self.logger.info("{}{}".format(self.message_prefix, text))
[ "def", "info", "(", "self", ",", "text", ")", ":", "self", ".", "logger", ".", "info", "(", "\"{}{}\"", ".", "format", "(", "self", ".", "message_prefix", ",", "text", ")", ")" ]
Ajout d'un message de log de type INFO
[ "Ajout", "d", "un", "message", "de", "log", "de", "type", "INFO" ]
c1f423ef107c94e2ab6bd253e9148f6056e0ef75
https://github.com/mickbad/mblibs/blob/c1f423ef107c94e2ab6bd253e9148f6056e0ef75/mblibs/fast.py#L524-L526
247,382
mickbad/mblibs
mblibs/fast.py
FastLogger.debug
def debug(self, text): """ Ajout d'un message de log de type DEBUG """ self.logger.debug("{}{}".format(self.message_prefix, text))
python
def debug(self, text): """ Ajout d'un message de log de type DEBUG """ self.logger.debug("{}{}".format(self.message_prefix, text))
[ "def", "debug", "(", "self", ",", "text", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"{}{}\"", ".", "format", "(", "self", ".", "message_prefix", ",", "text", ")", ")" ]
Ajout d'un message de log de type DEBUG
[ "Ajout", "d", "un", "message", "de", "log", "de", "type", "DEBUG" ]
c1f423ef107c94e2ab6bd253e9148f6056e0ef75
https://github.com/mickbad/mblibs/blob/c1f423ef107c94e2ab6bd253e9148f6056e0ef75/mblibs/fast.py#L529-L531
247,383
mickbad/mblibs
mblibs/fast.py
FastLogger.error
def error(self, text): """ Ajout d'un message de log de type ERROR """ self.logger.error("{}{}".format(self.message_prefix, text))
python
def error(self, text): """ Ajout d'un message de log de type ERROR """ self.logger.error("{}{}".format(self.message_prefix, text))
[ "def", "error", "(", "self", ",", "text", ")", ":", "self", ".", "logger", ".", "error", "(", "\"{}{}\"", ".", "format", "(", "self", ".", "message_prefix", ",", "text", ")", ")" ]
Ajout d'un message de log de type ERROR
[ "Ajout", "d", "un", "message", "de", "log", "de", "type", "ERROR" ]
c1f423ef107c94e2ab6bd253e9148f6056e0ef75
https://github.com/mickbad/mblibs/blob/c1f423ef107c94e2ab6bd253e9148f6056e0ef75/mblibs/fast.py#L544-L546
247,384
mickbad/mblibs
mblibs/fast.py
FastThread.run
def run(self): """ Fonctionnement du thread """ if self.debug: print("Starting " + self.name) # Lancement du programme du thread if isinstance(self.function, str): globals()[self.function](*self.args, **self.kwargs) else: self.function(*self.args, **self.kwargs) if self.debug: print("Exiting " + self.name)
python
def run(self): """ Fonctionnement du thread """ if self.debug: print("Starting " + self.name) # Lancement du programme du thread if isinstance(self.function, str): globals()[self.function](*self.args, **self.kwargs) else: self.function(*self.args, **self.kwargs) if self.debug: print("Exiting " + self.name)
[ "def", "run", "(", "self", ")", ":", "if", "self", ".", "debug", ":", "print", "(", "\"Starting \"", "+", "self", ".", "name", ")", "# Lancement du programme du thread", "if", "isinstance", "(", "self", ".", "function", ",", "str", ")", ":", "globals", "(", ")", "[", "self", ".", "function", "]", "(", "*", "self", ".", "args", ",", "*", "*", "self", ".", "kwargs", ")", "else", ":", "self", ".", "function", "(", "*", "self", ".", "args", ",", "*", "*", "self", ".", "kwargs", ")", "if", "self", ".", "debug", ":", "print", "(", "\"Exiting \"", "+", "self", ".", "name", ")" ]
Fonctionnement du thread
[ "Fonctionnement", "du", "thread" ]
c1f423ef107c94e2ab6bd253e9148f6056e0ef75
https://github.com/mickbad/mblibs/blob/c1f423ef107c94e2ab6bd253e9148f6056e0ef75/mblibs/fast.py#L781-L793
247,385
mickbad/mblibs
mblibs/fast.py
FastDate.convert
def convert(self, date_from=None, date_format=None): """ Retourne la date courante ou depuis l'argument au format datetime :param: :date_from date de référence :return datetime """ try: if date_format is None: # on détermine la date avec dateutil return dateutil.parser.parse(date_from) # il y a un format de date prédéfini return datetime.strptime(date_from, date_format) except: # échec, on prend la date courante return datetime.now()
python
def convert(self, date_from=None, date_format=None): """ Retourne la date courante ou depuis l'argument au format datetime :param: :date_from date de référence :return datetime """ try: if date_format is None: # on détermine la date avec dateutil return dateutil.parser.parse(date_from) # il y a un format de date prédéfini return datetime.strptime(date_from, date_format) except: # échec, on prend la date courante return datetime.now()
[ "def", "convert", "(", "self", ",", "date_from", "=", "None", ",", "date_format", "=", "None", ")", ":", "try", ":", "if", "date_format", "is", "None", ":", "# on détermine la date avec dateutil", "return", "dateutil", ".", "parser", ".", "parse", "(", "date_from", ")", "# il y a un format de date prédéfini", "return", "datetime", ".", "strptime", "(", "date_from", ",", "date_format", ")", "except", ":", "# échec, on prend la date courante", "return", "datetime", ".", "now", "(", ")" ]
Retourne la date courante ou depuis l'argument au format datetime :param: :date_from date de référence :return datetime
[ "Retourne", "la", "date", "courante", "ou", "depuis", "l", "argument", "au", "format", "datetime" ]
c1f423ef107c94e2ab6bd253e9148f6056e0ef75
https://github.com/mickbad/mblibs/blob/c1f423ef107c94e2ab6bd253e9148f6056e0ef75/mblibs/fast.py#L810-L827
247,386
mickbad/mblibs
mblibs/fast.py
FastDate.yesterday
def yesterday(self, date_from=None, date_format=None): """ Retourne la date d'hier depuis maintenant ou depuis une date fournie :param: :date_from date de référence :return datetime """ # date d'hier return self.delta(date_from=date_from, date_format=date_format, days=-1)
python
def yesterday(self, date_from=None, date_format=None): """ Retourne la date d'hier depuis maintenant ou depuis une date fournie :param: :date_from date de référence :return datetime """ # date d'hier return self.delta(date_from=date_from, date_format=date_format, days=-1)
[ "def", "yesterday", "(", "self", ",", "date_from", "=", "None", ",", "date_format", "=", "None", ")", ":", "# date d'hier", "return", "self", ".", "delta", "(", "date_from", "=", "date_from", ",", "date_format", "=", "date_format", ",", "days", "=", "-", "1", ")" ]
Retourne la date d'hier depuis maintenant ou depuis une date fournie :param: :date_from date de référence :return datetime
[ "Retourne", "la", "date", "d", "hier", "depuis", "maintenant", "ou", "depuis", "une", "date", "fournie" ]
c1f423ef107c94e2ab6bd253e9148f6056e0ef75
https://github.com/mickbad/mblibs/blob/c1f423ef107c94e2ab6bd253e9148f6056e0ef75/mblibs/fast.py#L884-L892
247,387
mickbad/mblibs
mblibs/fast.py
FastDate.weekday_yesterday
def weekday_yesterday(self, date_from=None, date_format=None): """ Retourne la date d'hier depuis maintenant ou depuis une date fournie seulement sur les jours de semaine. Ainsi vendredi devient jeudi et lundi devient vendredi :param: :date_from date de référence :return datetime """ # date d'hier que sur les jours de semaine return self.delta(days=-1, date_from=date_from, date_format=date_format, days_range=[1, 2, 3, 4, 5])
python
def weekday_yesterday(self, date_from=None, date_format=None): """ Retourne la date d'hier depuis maintenant ou depuis une date fournie seulement sur les jours de semaine. Ainsi vendredi devient jeudi et lundi devient vendredi :param: :date_from date de référence :return datetime """ # date d'hier que sur les jours de semaine return self.delta(days=-1, date_from=date_from, date_format=date_format, days_range=[1, 2, 3, 4, 5])
[ "def", "weekday_yesterday", "(", "self", ",", "date_from", "=", "None", ",", "date_format", "=", "None", ")", ":", "# date d'hier que sur les jours de semaine", "return", "self", ".", "delta", "(", "days", "=", "-", "1", ",", "date_from", "=", "date_from", ",", "date_format", "=", "date_format", ",", "days_range", "=", "[", "1", ",", "2", ",", "3", ",", "4", ",", "5", "]", ")" ]
Retourne la date d'hier depuis maintenant ou depuis une date fournie seulement sur les jours de semaine. Ainsi vendredi devient jeudi et lundi devient vendredi :param: :date_from date de référence :return datetime
[ "Retourne", "la", "date", "d", "hier", "depuis", "maintenant", "ou", "depuis", "une", "date", "fournie", "seulement", "sur", "les", "jours", "de", "semaine", ".", "Ainsi", "vendredi", "devient", "jeudi", "et", "lundi", "devient", "vendredi" ]
c1f423ef107c94e2ab6bd253e9148f6056e0ef75
https://github.com/mickbad/mblibs/blob/c1f423ef107c94e2ab6bd253e9148f6056e0ef75/mblibs/fast.py#L895-L905
247,388
mickbad/mblibs
mblibs/fast.py
FastDate.weekend_yesterday
def weekend_yesterday(self, date_from=None, date_format=None): """ Retourne la date d'hier depuis maintenant ou depuis une date fournie seulement sur les jours de weekend. Ainsi dimanche devient samedi et samedi devient dimanche :param: :date_from date de référence :return datetime """ # date d'hier que sur les jours de week-end return self.delta(days=-1, date_from=date_from, date_format=date_format, days_range=[6, 7])
python
def weekend_yesterday(self, date_from=None, date_format=None): """ Retourne la date d'hier depuis maintenant ou depuis une date fournie seulement sur les jours de weekend. Ainsi dimanche devient samedi et samedi devient dimanche :param: :date_from date de référence :return datetime """ # date d'hier que sur les jours de week-end return self.delta(days=-1, date_from=date_from, date_format=date_format, days_range=[6, 7])
[ "def", "weekend_yesterday", "(", "self", ",", "date_from", "=", "None", ",", "date_format", "=", "None", ")", ":", "# date d'hier que sur les jours de week-end", "return", "self", ".", "delta", "(", "days", "=", "-", "1", ",", "date_from", "=", "date_from", ",", "date_format", "=", "date_format", ",", "days_range", "=", "[", "6", ",", "7", "]", ")" ]
Retourne la date d'hier depuis maintenant ou depuis une date fournie seulement sur les jours de weekend. Ainsi dimanche devient samedi et samedi devient dimanche :param: :date_from date de référence :return datetime
[ "Retourne", "la", "date", "d", "hier", "depuis", "maintenant", "ou", "depuis", "une", "date", "fournie", "seulement", "sur", "les", "jours", "de", "weekend", ".", "Ainsi", "dimanche", "devient", "samedi", "et", "samedi", "devient", "dimanche" ]
c1f423ef107c94e2ab6bd253e9148f6056e0ef75
https://github.com/mickbad/mblibs/blob/c1f423ef107c94e2ab6bd253e9148f6056e0ef75/mblibs/fast.py#L908-L918
247,389
mickbad/mblibs
mblibs/fast.py
FastDate.working_yesterday
def working_yesterday(self, date_from=None, date_format=None): """ Retourne la date d'hier depuis maintenant ou depuis une date fournie seulement sur les jours ouvrableq. Ainsi lundi devient samedi et samedi devient vendredi :param: :date_from date de référence :return datetime """ # date d'hier que sur les jours de week-end return self.delta(days=-1, date_from=date_from, date_format=date_format, days_range=[1, 2, 3, 4, 5, 6])
python
def working_yesterday(self, date_from=None, date_format=None): """ Retourne la date d'hier depuis maintenant ou depuis une date fournie seulement sur les jours ouvrableq. Ainsi lundi devient samedi et samedi devient vendredi :param: :date_from date de référence :return datetime """ # date d'hier que sur les jours de week-end return self.delta(days=-1, date_from=date_from, date_format=date_format, days_range=[1, 2, 3, 4, 5, 6])
[ "def", "working_yesterday", "(", "self", ",", "date_from", "=", "None", ",", "date_format", "=", "None", ")", ":", "# date d'hier que sur les jours de week-end", "return", "self", ".", "delta", "(", "days", "=", "-", "1", ",", "date_from", "=", "date_from", ",", "date_format", "=", "date_format", ",", "days_range", "=", "[", "1", ",", "2", ",", "3", ",", "4", ",", "5", ",", "6", "]", ")" ]
Retourne la date d'hier depuis maintenant ou depuis une date fournie seulement sur les jours ouvrableq. Ainsi lundi devient samedi et samedi devient vendredi :param: :date_from date de référence :return datetime
[ "Retourne", "la", "date", "d", "hier", "depuis", "maintenant", "ou", "depuis", "une", "date", "fournie", "seulement", "sur", "les", "jours", "ouvrableq", ".", "Ainsi", "lundi", "devient", "samedi", "et", "samedi", "devient", "vendredi" ]
c1f423ef107c94e2ab6bd253e9148f6056e0ef75
https://github.com/mickbad/mblibs/blob/c1f423ef107c94e2ab6bd253e9148f6056e0ef75/mblibs/fast.py#L921-L931
247,390
mickbad/mblibs
mblibs/fast.py
FastDate.tomorrow
def tomorrow(self, date_from=None, date_format=None): """ Retourne la date de demain depuis maintenant ou depuis une date fournie :param: :date_from date de référence :return datetime """ # date de demain return self.delta(date_from=date_from, date_format=date_format, days=1)
python
def tomorrow(self, date_from=None, date_format=None): """ Retourne la date de demain depuis maintenant ou depuis une date fournie :param: :date_from date de référence :return datetime """ # date de demain return self.delta(date_from=date_from, date_format=date_format, days=1)
[ "def", "tomorrow", "(", "self", ",", "date_from", "=", "None", ",", "date_format", "=", "None", ")", ":", "# date de demain", "return", "self", ".", "delta", "(", "date_from", "=", "date_from", ",", "date_format", "=", "date_format", ",", "days", "=", "1", ")" ]
Retourne la date de demain depuis maintenant ou depuis une date fournie :param: :date_from date de référence :return datetime
[ "Retourne", "la", "date", "de", "demain", "depuis", "maintenant", "ou", "depuis", "une", "date", "fournie" ]
c1f423ef107c94e2ab6bd253e9148f6056e0ef75
https://github.com/mickbad/mblibs/blob/c1f423ef107c94e2ab6bd253e9148f6056e0ef75/mblibs/fast.py#L938-L946
247,391
mickbad/mblibs
mblibs/fast.py
FastDate.weekday_tomorrow
def weekday_tomorrow(self, date_from=None, date_format=None): """ Retourne la date de demain depuis maintenant ou depuis une date fournie seulement sur les jours de semaine. Ainsi vendredi devient jeudi et lundi devient vendredi :param: :date_from date de référence :return datetime """ # date de demain que sur les jours de semaine return self.delta(days=1, date_from=date_from, date_format=date_format, days_range=[1, 2, 3, 4, 5])
python
def weekday_tomorrow(self, date_from=None, date_format=None): """ Retourne la date de demain depuis maintenant ou depuis une date fournie seulement sur les jours de semaine. Ainsi vendredi devient jeudi et lundi devient vendredi :param: :date_from date de référence :return datetime """ # date de demain que sur les jours de semaine return self.delta(days=1, date_from=date_from, date_format=date_format, days_range=[1, 2, 3, 4, 5])
[ "def", "weekday_tomorrow", "(", "self", ",", "date_from", "=", "None", ",", "date_format", "=", "None", ")", ":", "# date de demain que sur les jours de semaine", "return", "self", ".", "delta", "(", "days", "=", "1", ",", "date_from", "=", "date_from", ",", "date_format", "=", "date_format", ",", "days_range", "=", "[", "1", ",", "2", ",", "3", ",", "4", ",", "5", "]", ")" ]
Retourne la date de demain depuis maintenant ou depuis une date fournie seulement sur les jours de semaine. Ainsi vendredi devient jeudi et lundi devient vendredi :param: :date_from date de référence :return datetime
[ "Retourne", "la", "date", "de", "demain", "depuis", "maintenant", "ou", "depuis", "une", "date", "fournie", "seulement", "sur", "les", "jours", "de", "semaine", ".", "Ainsi", "vendredi", "devient", "jeudi", "et", "lundi", "devient", "vendredi" ]
c1f423ef107c94e2ab6bd253e9148f6056e0ef75
https://github.com/mickbad/mblibs/blob/c1f423ef107c94e2ab6bd253e9148f6056e0ef75/mblibs/fast.py#L949-L959
247,392
mickbad/mblibs
mblibs/fast.py
FastDate.weekend_tomorrow
def weekend_tomorrow(self, date_from=None, date_format=None): """ Retourne la date de demain depuis maintenant ou depuis une date fournie seulement sur les jours de weekend. Ainsi dimanche devient samedi et samedi devient dimanche :param: :date_from date de référence :return datetime """ # date de demain que sur les jours de week-end return self.delta(days=1, date_from=date_from, date_format=date_format, days_range=[6, 7])
python
def weekend_tomorrow(self, date_from=None, date_format=None): """ Retourne la date de demain depuis maintenant ou depuis une date fournie seulement sur les jours de weekend. Ainsi dimanche devient samedi et samedi devient dimanche :param: :date_from date de référence :return datetime """ # date de demain que sur les jours de week-end return self.delta(days=1, date_from=date_from, date_format=date_format, days_range=[6, 7])
[ "def", "weekend_tomorrow", "(", "self", ",", "date_from", "=", "None", ",", "date_format", "=", "None", ")", ":", "# date de demain que sur les jours de week-end", "return", "self", ".", "delta", "(", "days", "=", "1", ",", "date_from", "=", "date_from", ",", "date_format", "=", "date_format", ",", "days_range", "=", "[", "6", ",", "7", "]", ")" ]
Retourne la date de demain depuis maintenant ou depuis une date fournie seulement sur les jours de weekend. Ainsi dimanche devient samedi et samedi devient dimanche :param: :date_from date de référence :return datetime
[ "Retourne", "la", "date", "de", "demain", "depuis", "maintenant", "ou", "depuis", "une", "date", "fournie", "seulement", "sur", "les", "jours", "de", "weekend", ".", "Ainsi", "dimanche", "devient", "samedi", "et", "samedi", "devient", "dimanche" ]
c1f423ef107c94e2ab6bd253e9148f6056e0ef75
https://github.com/mickbad/mblibs/blob/c1f423ef107c94e2ab6bd253e9148f6056e0ef75/mblibs/fast.py#L962-L972
247,393
mickbad/mblibs
mblibs/fast.py
FastDate.working_tomorrow
def working_tomorrow(self, date_from=None, date_format=None): """ Retourne la date de demain depuis maintenant ou depuis une date fournie seulement sur les jours ouvrableq. Ainsi lundi devient samedi et samedi devient vendredi :param: :date_from date de référence :return datetime """ # date de demain que sur les jours de week-end return self.delta(days=1, date_from=date_from, date_format=date_format, days_range=[1, 2, 3, 4, 5, 6])
python
def working_tomorrow(self, date_from=None, date_format=None): """ Retourne la date de demain depuis maintenant ou depuis une date fournie seulement sur les jours ouvrableq. Ainsi lundi devient samedi et samedi devient vendredi :param: :date_from date de référence :return datetime """ # date de demain que sur les jours de week-end return self.delta(days=1, date_from=date_from, date_format=date_format, days_range=[1, 2, 3, 4, 5, 6])
[ "def", "working_tomorrow", "(", "self", ",", "date_from", "=", "None", ",", "date_format", "=", "None", ")", ":", "# date de demain que sur les jours de week-end", "return", "self", ".", "delta", "(", "days", "=", "1", ",", "date_from", "=", "date_from", ",", "date_format", "=", "date_format", ",", "days_range", "=", "[", "1", ",", "2", ",", "3", ",", "4", ",", "5", ",", "6", "]", ")" ]
Retourne la date de demain depuis maintenant ou depuis une date fournie seulement sur les jours ouvrableq. Ainsi lundi devient samedi et samedi devient vendredi :param: :date_from date de référence :return datetime
[ "Retourne", "la", "date", "de", "demain", "depuis", "maintenant", "ou", "depuis", "une", "date", "fournie", "seulement", "sur", "les", "jours", "ouvrableq", ".", "Ainsi", "lundi", "devient", "samedi", "et", "samedi", "devient", "vendredi" ]
c1f423ef107c94e2ab6bd253e9148f6056e0ef75
https://github.com/mickbad/mblibs/blob/c1f423ef107c94e2ab6bd253e9148f6056e0ef75/mblibs/fast.py#L975-L985
247,394
stefanbraun-private/visitoolkit_eventsystem
visitoolkit_eventsystem/eventsystem.py
EventSystem.fire
def fire(self, *args, **kargs): """ collects results of all executed handlers """ self._time_secs_old = time.time() # allow register/unregister while execution # (a shallowcopy should be okay.. https://docs.python.org/2/library/copy.html ) with self._hlock: handler_list = copy.copy(self._handler_list) result_list = [] for handler in handler_list: if self._sync_mode: # grab results of all handlers result = self._execute(handler, *args, **kargs) if isinstance(result, tuple) and len(result) == 3 and isinstance(result[1], Exception): # error occurred one_res_tuple = (False, self._error(result), handler) else: one_res_tuple = (True, result, handler) else: # execute handlers in background, ignoring result EventSystem._async_queue.put((handler, args, kargs)) one_res_tuple = (None, None, handler) result_list.append(one_res_tuple) # update statistics time_secs_new = time.time() self.duration_secs = time_secs_new - self._time_secs_old self._time_secs_old = time_secs_new return result_list
python
def fire(self, *args, **kargs): """ collects results of all executed handlers """ self._time_secs_old = time.time() # allow register/unregister while execution # (a shallowcopy should be okay.. https://docs.python.org/2/library/copy.html ) with self._hlock: handler_list = copy.copy(self._handler_list) result_list = [] for handler in handler_list: if self._sync_mode: # grab results of all handlers result = self._execute(handler, *args, **kargs) if isinstance(result, tuple) and len(result) == 3 and isinstance(result[1], Exception): # error occurred one_res_tuple = (False, self._error(result), handler) else: one_res_tuple = (True, result, handler) else: # execute handlers in background, ignoring result EventSystem._async_queue.put((handler, args, kargs)) one_res_tuple = (None, None, handler) result_list.append(one_res_tuple) # update statistics time_secs_new = time.time() self.duration_secs = time_secs_new - self._time_secs_old self._time_secs_old = time_secs_new return result_list
[ "def", "fire", "(", "self", ",", "*", "args", ",", "*", "*", "kargs", ")", ":", "self", ".", "_time_secs_old", "=", "time", ".", "time", "(", ")", "# allow register/unregister while execution", "# (a shallowcopy should be okay.. https://docs.python.org/2/library/copy.html )", "with", "self", ".", "_hlock", ":", "handler_list", "=", "copy", ".", "copy", "(", "self", ".", "_handler_list", ")", "result_list", "=", "[", "]", "for", "handler", "in", "handler_list", ":", "if", "self", ".", "_sync_mode", ":", "# grab results of all handlers", "result", "=", "self", ".", "_execute", "(", "handler", ",", "*", "args", ",", "*", "*", "kargs", ")", "if", "isinstance", "(", "result", ",", "tuple", ")", "and", "len", "(", "result", ")", "==", "3", "and", "isinstance", "(", "result", "[", "1", "]", ",", "Exception", ")", ":", "# error occurred", "one_res_tuple", "=", "(", "False", ",", "self", ".", "_error", "(", "result", ")", ",", "handler", ")", "else", ":", "one_res_tuple", "=", "(", "True", ",", "result", ",", "handler", ")", "else", ":", "# execute handlers in background, ignoring result", "EventSystem", ".", "_async_queue", ".", "put", "(", "(", "handler", ",", "args", ",", "kargs", ")", ")", "one_res_tuple", "=", "(", "None", ",", "None", ",", "handler", ")", "result_list", ".", "append", "(", "one_res_tuple", ")", "# update statistics", "time_secs_new", "=", "time", ".", "time", "(", ")", "self", ".", "duration_secs", "=", "time_secs_new", "-", "self", ".", "_time_secs_old", "self", ".", "_time_secs_old", "=", "time_secs_new", "return", "result_list" ]
collects results of all executed handlers
[ "collects", "results", "of", "all", "executed", "handlers" ]
d606a167ac3b8edc5bfbd8de7fb7063a9a1922f1
https://github.com/stefanbraun-private/visitoolkit_eventsystem/blob/d606a167ac3b8edc5bfbd8de7fb7063a9a1922f1/visitoolkit_eventsystem/eventsystem.py#L145-L174
247,395
stefanbraun-private/visitoolkit_eventsystem
visitoolkit_eventsystem/eventsystem.py
EventSystem._execute
def _execute(self, handler, *args, **kwargs): """ executes one callback function """ # difference to Axel Events: we don't use a timeout and execute all handlers in same thread # FIXME: =>possible problem: # blocking of event firing when user gives a long- or infinitly-running callback function # (in Python it doesn't seem possible to forcefully kill a thread with clean ressource releasing, # a thread has to cooperate und behave nice... # execution and killing a process would be possible, but has data corruption problems with queues # and possible interprocess communication problems with given handler/callback function) result = None exc_info = None try: result = handler(*args, **kwargs) except Exception: exc_info = sys.exc_info() if exc_info: return exc_info return result
python
def _execute(self, handler, *args, **kwargs): """ executes one callback function """ # difference to Axel Events: we don't use a timeout and execute all handlers in same thread # FIXME: =>possible problem: # blocking of event firing when user gives a long- or infinitly-running callback function # (in Python it doesn't seem possible to forcefully kill a thread with clean ressource releasing, # a thread has to cooperate und behave nice... # execution and killing a process would be possible, but has data corruption problems with queues # and possible interprocess communication problems with given handler/callback function) result = None exc_info = None try: result = handler(*args, **kwargs) except Exception: exc_info = sys.exc_info() if exc_info: return exc_info return result
[ "def", "_execute", "(", "self", ",", "handler", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# difference to Axel Events: we don't use a timeout and execute all handlers in same thread", "# FIXME: =>possible problem:", "# blocking of event firing when user gives a long- or infinitly-running callback function", "# (in Python it doesn't seem possible to forcefully kill a thread with clean ressource releasing,", "# a thread has to cooperate und behave nice...", "# execution and killing a process would be possible, but has data corruption problems with queues", "# and possible interprocess communication problems with given handler/callback function)", "result", "=", "None", "exc_info", "=", "None", "try", ":", "result", "=", "handler", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "if", "exc_info", ":", "return", "exc_info", "return", "result" ]
executes one callback function
[ "executes", "one", "callback", "function" ]
d606a167ac3b8edc5bfbd8de7fb7063a9a1922f1
https://github.com/stefanbraun-private/visitoolkit_eventsystem/blob/d606a167ac3b8edc5bfbd8de7fb7063a9a1922f1/visitoolkit_eventsystem/eventsystem.py#L176-L195
247,396
romantolkachyov/django-bridge
django_bridge/templatetags/bridge.py
bridge
def bridge(filename): """ Add hash to filename for cache invalidation. Uses gulp-buster for cache invalidation. Adds current file hash as url arg. """ if not hasattr(settings, 'BASE_DIR'): raise Exception("You must provide BASE_DIR in settings for bridge") file_path = getattr(settings, 'BUSTERS_FILE', os.path.join('static', 'busters.json')) buster_file = os.path.join(settings.BASE_DIR, file_path) fp = file(buster_file, 'r') # TODO: may be store it somewhere to not load file every time busters_json = json.loads(fp.read()) fp.close() file_hash = busters_json.get("static/%s" % filename) path = static(filename) return "%s?%s" % (path, file_hash) if file_hash is not None else path
python
def bridge(filename): """ Add hash to filename for cache invalidation. Uses gulp-buster for cache invalidation. Adds current file hash as url arg. """ if not hasattr(settings, 'BASE_DIR'): raise Exception("You must provide BASE_DIR in settings for bridge") file_path = getattr(settings, 'BUSTERS_FILE', os.path.join('static', 'busters.json')) buster_file = os.path.join(settings.BASE_DIR, file_path) fp = file(buster_file, 'r') # TODO: may be store it somewhere to not load file every time busters_json = json.loads(fp.read()) fp.close() file_hash = busters_json.get("static/%s" % filename) path = static(filename) return "%s?%s" % (path, file_hash) if file_hash is not None else path
[ "def", "bridge", "(", "filename", ")", ":", "if", "not", "hasattr", "(", "settings", ",", "'BASE_DIR'", ")", ":", "raise", "Exception", "(", "\"You must provide BASE_DIR in settings for bridge\"", ")", "file_path", "=", "getattr", "(", "settings", ",", "'BUSTERS_FILE'", ",", "os", ".", "path", ".", "join", "(", "'static'", ",", "'busters.json'", ")", ")", "buster_file", "=", "os", ".", "path", ".", "join", "(", "settings", ".", "BASE_DIR", ",", "file_path", ")", "fp", "=", "file", "(", "buster_file", ",", "'r'", ")", "# TODO: may be store it somewhere to not load file every time", "busters_json", "=", "json", ".", "loads", "(", "fp", ".", "read", "(", ")", ")", "fp", ".", "close", "(", ")", "file_hash", "=", "busters_json", ".", "get", "(", "\"static/%s\"", "%", "filename", ")", "path", "=", "static", "(", "filename", ")", "return", "\"%s?%s\"", "%", "(", "path", ",", "file_hash", ")", "if", "file_hash", "is", "not", "None", "else", "path" ]
Add hash to filename for cache invalidation. Uses gulp-buster for cache invalidation. Adds current file hash as url arg.
[ "Add", "hash", "to", "filename", "for", "cache", "invalidation", "." ]
c2ded281feecaca108072ad1934e216f34320ce5
https://github.com/romantolkachyov/django-bridge/blob/c2ded281feecaca108072ad1934e216f34320ce5/django_bridge/templatetags/bridge.py#L11-L27
247,397
gersolar/goescalibration
goescalibration/instrument.py
calibrate
def calibrate(filename): """ Append the calibration parameters as variables of the netcdf file. Keyword arguments: filename -- the name of a netcdf file. """ params = calibration_to(filename) with nc.loader(filename) as root: for key, value in params.items(): nc.getdim(root, 'xc_1', 1) nc.getdim(root, 'yc_1', 1) if isinstance(value, list): for i in range(len(value)): nc.getvar(root, '%s_%i' % (key, i), 'f4', ('time', 'yc_1', 'xc_1' ))[:] = value[i] else: nc.getvar(root, key, 'f4', ('time', 'yc_1', 'xc_1'))[:] = value
python
def calibrate(filename): """ Append the calibration parameters as variables of the netcdf file. Keyword arguments: filename -- the name of a netcdf file. """ params = calibration_to(filename) with nc.loader(filename) as root: for key, value in params.items(): nc.getdim(root, 'xc_1', 1) nc.getdim(root, 'yc_1', 1) if isinstance(value, list): for i in range(len(value)): nc.getvar(root, '%s_%i' % (key, i), 'f4', ('time', 'yc_1', 'xc_1' ))[:] = value[i] else: nc.getvar(root, key, 'f4', ('time', 'yc_1', 'xc_1'))[:] = value
[ "def", "calibrate", "(", "filename", ")", ":", "params", "=", "calibration_to", "(", "filename", ")", "with", "nc", ".", "loader", "(", "filename", ")", "as", "root", ":", "for", "key", ",", "value", "in", "params", ".", "items", "(", ")", ":", "nc", ".", "getdim", "(", "root", ",", "'xc_1'", ",", "1", ")", "nc", ".", "getdim", "(", "root", ",", "'yc_1'", ",", "1", ")", "if", "isinstance", "(", "value", ",", "list", ")", ":", "for", "i", "in", "range", "(", "len", "(", "value", ")", ")", ":", "nc", ".", "getvar", "(", "root", ",", "'%s_%i'", "%", "(", "key", ",", "i", ")", ",", "'f4'", ",", "(", "'time'", ",", "'yc_1'", ",", "'xc_1'", ")", ")", "[", ":", "]", "=", "value", "[", "i", "]", "else", ":", "nc", ".", "getvar", "(", "root", ",", "key", ",", "'f4'", ",", "(", "'time'", ",", "'yc_1'", ",", "'xc_1'", ")", ")", "[", ":", "]", "=", "value" ]
Append the calibration parameters as variables of the netcdf file. Keyword arguments: filename -- the name of a netcdf file.
[ "Append", "the", "calibration", "parameters", "as", "variables", "of", "the", "netcdf", "file", "." ]
aab7f3e3cede9694e90048ceeaea74566578bc75
https://github.com/gersolar/goescalibration/blob/aab7f3e3cede9694e90048ceeaea74566578bc75/goescalibration/instrument.py#L37-L53
247,398
ryanjdillon/yamlord
yamlord/yamio.py
read_yaml
def read_yaml(file_path, Loader=yaml.Loader, object_pairs_hook=OrderedDict): '''Read YAML file and return as python dictionary''' # http://stackoverflow.com/a/21912744/943773 class OrderedLoader(Loader): pass def construct_mapping(loader, node): loader.flatten_mapping(node) return object_pairs_hook(loader.construct_pairs(node)) OrderedLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_mapping) with open(file_path, 'r') as f: return yaml.load(f, OrderedLoader)
python
def read_yaml(file_path, Loader=yaml.Loader, object_pairs_hook=OrderedDict): '''Read YAML file and return as python dictionary''' # http://stackoverflow.com/a/21912744/943773 class OrderedLoader(Loader): pass def construct_mapping(loader, node): loader.flatten_mapping(node) return object_pairs_hook(loader.construct_pairs(node)) OrderedLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_mapping) with open(file_path, 'r') as f: return yaml.load(f, OrderedLoader)
[ "def", "read_yaml", "(", "file_path", ",", "Loader", "=", "yaml", ".", "Loader", ",", "object_pairs_hook", "=", "OrderedDict", ")", ":", "# http://stackoverflow.com/a/21912744/943773", "class", "OrderedLoader", "(", "Loader", ")", ":", "pass", "def", "construct_mapping", "(", "loader", ",", "node", ")", ":", "loader", ".", "flatten_mapping", "(", "node", ")", "return", "object_pairs_hook", "(", "loader", ".", "construct_pairs", "(", "node", ")", ")", "OrderedLoader", ".", "add_constructor", "(", "yaml", ".", "resolver", ".", "BaseResolver", ".", "DEFAULT_MAPPING_TAG", ",", "construct_mapping", ")", "with", "open", "(", "file_path", ",", "'r'", ")", "as", "f", ":", "return", "yaml", ".", "load", "(", "f", ",", "OrderedLoader", ")" ]
Read YAML file and return as python dictionary
[ "Read", "YAML", "file", "and", "return", "as", "python", "dictionary" ]
a8abe5cd1b3294612bb466183f2f830e6666e22e
https://github.com/ryanjdillon/yamlord/blob/a8abe5cd1b3294612bb466183f2f830e6666e22e/yamlord/yamio.py#L4-L21
247,399
ryanjdillon/yamlord
yamlord/yamio.py
write_yaml
def write_yaml(data, out_path, Dumper=yaml.Dumper, **kwds): '''Write python dictionary to YAML''' import errno import os class OrderedDumper(Dumper): pass def _dict_representer(dumper, data): return dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items()) OrderedDumper.add_representer(OrderedDict, _dict_representer) # Make directory for calibration file if does not exist base_path, file_name = os.path.split(out_path) try: os.makedirs(base_path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(base_path): pass else: raise # Write dictionary to YAML with open(out_path, 'w') as f: return yaml.dump(data, f, OrderedDumper, default_flow_style=False, **kwds)
python
def write_yaml(data, out_path, Dumper=yaml.Dumper, **kwds): '''Write python dictionary to YAML''' import errno import os class OrderedDumper(Dumper): pass def _dict_representer(dumper, data): return dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items()) OrderedDumper.add_representer(OrderedDict, _dict_representer) # Make directory for calibration file if does not exist base_path, file_name = os.path.split(out_path) try: os.makedirs(base_path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(base_path): pass else: raise # Write dictionary to YAML with open(out_path, 'w') as f: return yaml.dump(data, f, OrderedDumper, default_flow_style=False, **kwds)
[ "def", "write_yaml", "(", "data", ",", "out_path", ",", "Dumper", "=", "yaml", ".", "Dumper", ",", "*", "*", "kwds", ")", ":", "import", "errno", "import", "os", "class", "OrderedDumper", "(", "Dumper", ")", ":", "pass", "def", "_dict_representer", "(", "dumper", ",", "data", ")", ":", "return", "dumper", ".", "represent_mapping", "(", "yaml", ".", "resolver", ".", "BaseResolver", ".", "DEFAULT_MAPPING_TAG", ",", "data", ".", "items", "(", ")", ")", "OrderedDumper", ".", "add_representer", "(", "OrderedDict", ",", "_dict_representer", ")", "# Make directory for calibration file if does not exist", "base_path", ",", "file_name", "=", "os", ".", "path", ".", "split", "(", "out_path", ")", "try", ":", "os", ".", "makedirs", "(", "base_path", ")", "except", "OSError", "as", "exc", ":", "# Python >2.5", "if", "exc", ".", "errno", "==", "errno", ".", "EEXIST", "and", "os", ".", "path", ".", "isdir", "(", "base_path", ")", ":", "pass", "else", ":", "raise", "# Write dictionary to YAML", "with", "open", "(", "out_path", ",", "'w'", ")", "as", "f", ":", "return", "yaml", ".", "dump", "(", "data", ",", "f", ",", "OrderedDumper", ",", "default_flow_style", "=", "False", ",", "*", "*", "kwds", ")" ]
Write python dictionary to YAML
[ "Write", "python", "dictionary", "to", "YAML" ]
a8abe5cd1b3294612bb466183f2f830e6666e22e
https://github.com/ryanjdillon/yamlord/blob/a8abe5cd1b3294612bb466183f2f830e6666e22e/yamlord/yamio.py#L24-L49