repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
minhhoit/yacms | yacms/utils/email.py | split_addresses | def split_addresses(email_string_list):
"""
Converts a string containing comma separated email addresses
into a list of email addresses.
"""
return [f for f in [s.strip() for s in email_string_list.split(",")] if f] | python | def split_addresses(email_string_list):
"""
Converts a string containing comma separated email addresses
into a list of email addresses.
"""
return [f for f in [s.strip() for s in email_string_list.split(",")] if f] | [
"def",
"split_addresses",
"(",
"email_string_list",
")",
":",
"return",
"[",
"f",
"for",
"f",
"in",
"[",
"s",
".",
"strip",
"(",
")",
"for",
"s",
"in",
"email_string_list",
".",
"split",
"(",
"\",\"",
")",
"]",
"if",
"f",
"]"
] | Converts a string containing comma separated email addresses
into a list of email addresses. | [
"Converts",
"a",
"string",
"containing",
"comma",
"separated",
"email",
"addresses",
"into",
"a",
"list",
"of",
"email",
"addresses",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/email.py#L15-L20 |
minhhoit/yacms | yacms/utils/email.py | subject_template | def subject_template(template, context):
"""
Loads and renders an email subject template, returning the
subject string.
"""
subject = loader.get_template(template).render(Context(context))
return " ".join(subject.splitlines()).strip() | python | def subject_template(template, context):
"""
Loads and renders an email subject template, returning the
subject string.
"""
subject = loader.get_template(template).render(Context(context))
return " ".join(subject.splitlines()).strip() | [
"def",
"subject_template",
"(",
"template",
",",
"context",
")",
":",
"subject",
"=",
"loader",
".",
"get_template",
"(",
"template",
")",
".",
"render",
"(",
"Context",
"(",
"context",
")",
")",
"return",
"\" \"",
".",
"join",
"(",
"subject",
".",
"spli... | Loads and renders an email subject template, returning the
subject string. | [
"Loads",
"and",
"renders",
"an",
"email",
"subject",
"template",
"returning",
"the",
"subject",
"string",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/email.py#L23-L29 |
minhhoit/yacms | yacms/utils/email.py | send_mail_template | def send_mail_template(subject, template, addr_from, addr_to, context=None,
attachments=None, fail_silently=None, addr_bcc=None,
headers=None):
"""
Send email rendering text and html versions for the specified
template name using the context dictionary passed in... | python | def send_mail_template(subject, template, addr_from, addr_to, context=None,
attachments=None, fail_silently=None, addr_bcc=None,
headers=None):
"""
Send email rendering text and html versions for the specified
template name using the context dictionary passed in... | [
"def",
"send_mail_template",
"(",
"subject",
",",
"template",
",",
"addr_from",
",",
"addr_to",
",",
"context",
"=",
"None",
",",
"attachments",
"=",
"None",
",",
"fail_silently",
"=",
"None",
",",
"addr_bcc",
"=",
"None",
",",
"headers",
"=",
"None",
")",... | Send email rendering text and html versions for the specified
template name using the context dictionary passed in. | [
"Send",
"email",
"rendering",
"text",
"and",
"html",
"versions",
"for",
"the",
"specified",
"template",
"name",
"using",
"the",
"context",
"dictionary",
"passed",
"in",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/email.py#L32-L66 |
minhhoit/yacms | yacms/utils/email.py | send_verification_mail | def send_verification_mail(request, user, verification_type):
"""
Sends an email with a verification link to users when
``ACCOUNTS_VERIFICATION_REQUIRED`` is ```True`` and they're signing
up, or when they reset a lost password.
The ``verification_type`` arg is both the name of the urlpattern for
... | python | def send_verification_mail(request, user, verification_type):
"""
Sends an email with a verification link to users when
``ACCOUNTS_VERIFICATION_REQUIRED`` is ```True`` and they're signing
up, or when they reset a lost password.
The ``verification_type`` arg is both the name of the urlpattern for
... | [
"def",
"send_verification_mail",
"(",
"request",
",",
"user",
",",
"verification_type",
")",
":",
"verify_url",
"=",
"reverse",
"(",
"verification_type",
",",
"kwargs",
"=",
"{",
"\"uidb36\"",
":",
"int_to_base36",
"(",
"user",
".",
"id",
")",
",",
"\"token\""... | Sends an email with a verification link to users when
``ACCOUNTS_VERIFICATION_REQUIRED`` is ```True`` and they're signing
up, or when they reset a lost password.
The ``verification_type`` arg is both the name of the urlpattern for
the verification link, as well as the names of the email templates
to... | [
"Sends",
"an",
"email",
"with",
"a",
"verification",
"link",
"to",
"users",
"when",
"ACCOUNTS_VERIFICATION_REQUIRED",
"is",
"True",
"and",
"they",
"re",
"signing",
"up",
"or",
"when",
"they",
"reset",
"a",
"lost",
"password",
".",
"The",
"verification_type",
"... | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/email.py#L69-L91 |
minhhoit/yacms | yacms/utils/email.py | send_approve_mail | def send_approve_mail(request, user):
"""
Sends an email to staff in listed in the setting
``ACCOUNTS_APPROVAL_EMAILS``, when a new user signs up and the
``ACCOUNTS_APPROVAL_REQUIRED`` setting is ``True``.
"""
approval_emails = split_addresses(settings.ACCOUNTS_APPROVAL_EMAILS)
if not approv... | python | def send_approve_mail(request, user):
"""
Sends an email to staff in listed in the setting
``ACCOUNTS_APPROVAL_EMAILS``, when a new user signs up and the
``ACCOUNTS_APPROVAL_REQUIRED`` setting is ``True``.
"""
approval_emails = split_addresses(settings.ACCOUNTS_APPROVAL_EMAILS)
if not approv... | [
"def",
"send_approve_mail",
"(",
"request",
",",
"user",
")",
":",
"approval_emails",
"=",
"split_addresses",
"(",
"settings",
".",
"ACCOUNTS_APPROVAL_EMAILS",
")",
"if",
"not",
"approval_emails",
":",
"return",
"context",
"=",
"{",
"\"request\"",
":",
"request",
... | Sends an email to staff in listed in the setting
``ACCOUNTS_APPROVAL_EMAILS``, when a new user signs up and the
``ACCOUNTS_APPROVAL_REQUIRED`` setting is ``True``. | [
"Sends",
"an",
"email",
"to",
"staff",
"in",
"listed",
"in",
"the",
"setting",
"ACCOUNTS_APPROVAL_EMAILS",
"when",
"a",
"new",
"user",
"signs",
"up",
"and",
"the",
"ACCOUNTS_APPROVAL_REQUIRED",
"setting",
"is",
"True",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/email.py#L94-L111 |
minhhoit/yacms | yacms/utils/email.py | send_approved_mail | def send_approved_mail(request, user):
"""
Sends an email to a user once their ``is_active`` status goes from
``False`` to ``True`` when the ``ACCOUNTS_APPROVAL_REQUIRED``
setting is ``True``.
"""
context = {"request": request, "user": user}
subject = subject_template("email/account_approved... | python | def send_approved_mail(request, user):
"""
Sends an email to a user once their ``is_active`` status goes from
``False`` to ``True`` when the ``ACCOUNTS_APPROVAL_REQUIRED``
setting is ``True``.
"""
context = {"request": request, "user": user}
subject = subject_template("email/account_approved... | [
"def",
"send_approved_mail",
"(",
"request",
",",
"user",
")",
":",
"context",
"=",
"{",
"\"request\"",
":",
"request",
",",
"\"user\"",
":",
"user",
"}",
"subject",
"=",
"subject_template",
"(",
"\"email/account_approved_subject.txt\"",
",",
"context",
")",
"se... | Sends an email to a user once their ``is_active`` status goes from
``False`` to ``True`` when the ``ACCOUNTS_APPROVAL_REQUIRED``
setting is ``True``. | [
"Sends",
"an",
"email",
"to",
"a",
"user",
"once",
"their",
"is_active",
"status",
"goes",
"from",
"False",
"to",
"True",
"when",
"the",
"ACCOUNTS_APPROVAL_REQUIRED",
"setting",
"is",
"True",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/email.py#L114-L124 |
OpenGov/python_data_wrap | datawrap/external/xmlparse.py | merge | def merge (dst, src):
"""put key/value pairs that exist in src but not in dst into dst"""
for key in src.keys():
if key not in dst:
dst[key] = src[key] | python | def merge (dst, src):
"""put key/value pairs that exist in src but not in dst into dst"""
for key in src.keys():
if key not in dst:
dst[key] = src[key] | [
"def",
"merge",
"(",
"dst",
",",
"src",
")",
":",
"for",
"key",
"in",
"src",
".",
"keys",
"(",
")",
":",
"if",
"key",
"not",
"in",
"dst",
":",
"dst",
"[",
"key",
"]",
"=",
"src",
"[",
"key",
"]"
] | put key/value pairs that exist in src but not in dst into dst | [
"put",
"key",
"/",
"value",
"pairs",
"that",
"exist",
"in",
"src",
"but",
"not",
"in",
"dst",
"into",
"dst"
] | train | https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L110-L114 |
OpenGov/python_data_wrap | datawrap/external/xmlparse.py | IndexToColumn | def IndexToColumn (ndx):
"""convert index to column. Eg: IndexToColumn(2) = "B", IndexToColumn(28) = "AB" """
ndx -= 1
col = chr(ndx % 26 + 65)
while (ndx > 25):
ndx = ndx // 26
col = chr(ndx % 26 + 64) + col
return col | python | def IndexToColumn (ndx):
"""convert index to column. Eg: IndexToColumn(2) = "B", IndexToColumn(28) = "AB" """
ndx -= 1
col = chr(ndx % 26 + 65)
while (ndx > 25):
ndx = ndx // 26
col = chr(ndx % 26 + 64) + col
return col | [
"def",
"IndexToColumn",
"(",
"ndx",
")",
":",
"ndx",
"-=",
"1",
"col",
"=",
"chr",
"(",
"ndx",
"%",
"26",
"+",
"65",
")",
"while",
"(",
"ndx",
">",
"25",
")",
":",
"ndx",
"=",
"ndx",
"//",
"26",
"col",
"=",
"chr",
"(",
"ndx",
"%",
"26",
"+"... | convert index to column. Eg: IndexToColumn(2) = "B", IndexToColumn(28) = "AB" | [
"convert",
"index",
"to",
"column",
".",
"Eg",
":",
"IndexToColumn",
"(",
"2",
")",
"=",
"B",
"IndexToColumn",
"(",
"28",
")",
"=",
"AB"
] | train | https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L116-L123 |
OpenGov/python_data_wrap | datawrap/external/xmlparse.py | ColumnToIndex | def ColumnToIndex (col):
"""convert column to index. Eg: ConvertInIndex("AB") = 28"""
ndx = 0
for c in col:
ndx = ndx * 26 + ord(c.upper()) - 64
return ndx | python | def ColumnToIndex (col):
"""convert column to index. Eg: ConvertInIndex("AB") = 28"""
ndx = 0
for c in col:
ndx = ndx * 26 + ord(c.upper()) - 64
return ndx | [
"def",
"ColumnToIndex",
"(",
"col",
")",
":",
"ndx",
"=",
"0",
"for",
"c",
"in",
"col",
":",
"ndx",
"=",
"ndx",
"*",
"26",
"+",
"ord",
"(",
"c",
".",
"upper",
"(",
")",
")",
"-",
"64",
"return",
"ndx"
] | convert column to index. Eg: ConvertInIndex("AB") = 28 | [
"convert",
"column",
"to",
"index",
".",
"Eg",
":",
"ConvertInIndex",
"(",
"AB",
")",
"=",
"28"
] | train | https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L125-L130 |
OpenGov/python_data_wrap | datawrap/external/xmlparse.py | ParseCellSpec | def ParseCellSpec (spec):
"""convert cell spec to row,col. Eg. ParseCellSpec("B5") = [2, 5]"""
m = __specRe.match(spec)
(column, row) = m.groups()
return (int(row), ColumnToIndex(column)) | python | def ParseCellSpec (spec):
"""convert cell spec to row,col. Eg. ParseCellSpec("B5") = [2, 5]"""
m = __specRe.match(spec)
(column, row) = m.groups()
return (int(row), ColumnToIndex(column)) | [
"def",
"ParseCellSpec",
"(",
"spec",
")",
":",
"m",
"=",
"__specRe",
".",
"match",
"(",
"spec",
")",
"(",
"column",
",",
"row",
")",
"=",
"m",
".",
"groups",
"(",
")",
"return",
"(",
"int",
"(",
"row",
")",
",",
"ColumnToIndex",
"(",
"column",
")... | convert cell spec to row,col. Eg. ParseCellSpec("B5") = [2, 5] | [
"convert",
"cell",
"spec",
"to",
"row",
"col",
".",
"Eg",
".",
"ParseCellSpec",
"(",
"B5",
")",
"=",
"[",
"2",
"5",
"]"
] | train | https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L132-L136 |
OpenGov/python_data_wrap | datawrap/external/xmlparse.py | ParseExcelXMLFile | def ParseExcelXMLFile(filename):
"""parse an excel file
typical usage:
import exceldump;
xl = exceldump.ParseExcelXMLFile("SomeExcelFile.xml")
worksheet = xl.GetWorksheets(0) # get first worksheet
print worksheet.GetCellVa... | python | def ParseExcelXMLFile(filename):
"""parse an excel file
typical usage:
import exceldump;
xl = exceldump.ParseExcelXMLFile("SomeExcelFile.xml")
worksheet = xl.GetWorksheets(0) # get first worksheet
print worksheet.GetCellVa... | [
"def",
"ParseExcelXMLFile",
"(",
"filename",
")",
":",
"excelfile",
"=",
"ExcelFile",
"(",
")",
"excelHandler",
"=",
"ExcelToSparseArrayHandler",
"(",
"excelfile",
")",
"parse",
"(",
"filename",
",",
"excelHandler",
")",
"return",
"excelfile"
] | parse an excel file
typical usage:
import exceldump;
xl = exceldump.ParseExcelXMLFile("SomeExcelFile.xml")
worksheet = xl.GetWorksheets(0) # get first worksheet
print worksheet.GetCellValue(1,1) # print contents of cell A1 | [
"parse",
"an",
"excel",
"file",
"typical",
"usage",
":",
"import",
"exceldump",
";",
"xl",
"=",
"exceldump",
".",
"ParseExcelXMLFile",
"(",
"SomeExcelFile",
".",
"xml",
")",
"worksheet",
"=",
"xl",
".",
"GetWorksheets",
"(",
"0",
")",
"#",
"get",
"first",
... | train | https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L536-L550 |
OpenGov/python_data_wrap | datawrap/external/xmlparse.py | Row.GetCellValue | def GetCellValue (self, column, default = None):
""" get a cell, return default if that cell does not exist
note that column and row START AT 1 same as excel
"""
if isinstance(column, str):
column = ColumnToIndex(column... | python | def GetCellValue (self, column, default = None):
""" get a cell, return default if that cell does not exist
note that column and row START AT 1 same as excel
"""
if isinstance(column, str):
column = ColumnToIndex(column... | [
"def",
"GetCellValue",
"(",
"self",
",",
"column",
",",
"default",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"column",
",",
"str",
")",
":",
"column",
"=",
"ColumnToIndex",
"(",
"column",
")",
"if",
"column",
"in",
"self",
":",
"if",
"\"content\"... | get a cell, return default if that cell does not exist
note that column and row START AT 1 same as excel | [
"get",
"a",
"cell",
"return",
"default",
"if",
"that",
"cell",
"does",
"not",
"exist",
"note",
"that",
"column",
"and",
"row",
"START",
"AT",
"1",
"same",
"as",
"excel"
] | train | https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L174-L183 |
OpenGov/python_data_wrap | datawrap/external/xmlparse.py | Row.GetCellValueNoFail | def GetCellValueNoFail (self, column):
""" get a cell, if it does not exist fail
note that column at row START AT 1 same as excel
"""
cell = GetCellValue(self, column)
if cell == None:
raise ValueError("cell %d... | python | def GetCellValueNoFail (self, column):
""" get a cell, if it does not exist fail
note that column at row START AT 1 same as excel
"""
cell = GetCellValue(self, column)
if cell == None:
raise ValueError("cell %d... | [
"def",
"GetCellValueNoFail",
"(",
"self",
",",
"column",
")",
":",
"cell",
"=",
"GetCellValue",
"(",
"self",
",",
"column",
")",
"if",
"cell",
"==",
"None",
":",
"raise",
"ValueError",
"(",
"\"cell %d does not exist\"",
"%",
"(",
"column",
",",
")",
")",
... | get a cell, if it does not exist fail
note that column at row START AT 1 same as excel | [
"get",
"a",
"cell",
"if",
"it",
"does",
"not",
"exist",
"fail",
"note",
"that",
"column",
"at",
"row",
"START",
"AT",
"1",
"same",
"as",
"excel"
] | train | https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L185-L192 |
OpenGov/python_data_wrap | datawrap/external/xmlparse.py | Row.GetCellStyle | def GetCellStyle (self, column):
""" get the "style" of a cell
note: this merges default, column, row and the cell's style into the actual style for you returning a dictionary of styles
The values directly from excel with the relavent XML element append... | python | def GetCellStyle (self, column):
""" get the "style" of a cell
note: this merges default, column, row and the cell's style into the actual style for you returning a dictionary of styles
The values directly from excel with the relavent XML element append... | [
"def",
"GetCellStyle",
"(",
"self",
",",
"column",
")",
":",
"if",
"isinstance",
"(",
"column",
",",
"str",
")",
":",
"column",
"=",
"ColumnToIndex",
"(",
"column",
")",
"style",
"=",
"{",
"}",
"# get style for cell\r",
"if",
"column",
"in",
"self",
":",... | get the "style" of a cell
note: this merges default, column, row and the cell's style into the actual style for you returning a dictionary of styles
The values directly from excel with the relavent XML element appended to the name. Examples of style key/value pairs
... | [
"get",
"the",
"style",
"of",
"a",
"cell",
"note",
":",
"this",
"merges",
"default",
"column",
"row",
"and",
"the",
"cell",
"s",
"style",
"into",
"the",
"actual",
"style",
"for",
"you",
"returning",
"a",
"dictionary",
"of",
"styles",
"The",
"values",
"dir... | train | https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L194-L215 |
OpenGov/python_data_wrap | datawrap/external/xmlparse.py | Worksheet.friend_addRow | def friend_addRow(self, rowNum, row):
"""used only by parser: adds a row of columns"""
self[rowNum] = row
if (rowNum > self.maxRow):
self.maxRow = rowNum
for cellNum in row.keys():
if cellNum > self.m... | python | def friend_addRow(self, rowNum, row):
"""used only by parser: adds a row of columns"""
self[rowNum] = row
if (rowNum > self.maxRow):
self.maxRow = rowNum
for cellNum in row.keys():
if cellNum > self.m... | [
"def",
"friend_addRow",
"(",
"self",
",",
"rowNum",
",",
"row",
")",
":",
"self",
"[",
"rowNum",
"]",
"=",
"row",
"if",
"(",
"rowNum",
">",
"self",
".",
"maxRow",
")",
":",
"self",
".",
"maxRow",
"=",
"rowNum",
"for",
"cellNum",
"in",
"row",
".",
... | used only by parser: adds a row of columns | [
"used",
"only",
"by",
"parser",
":",
"adds",
"a",
"row",
"of",
"columns"
] | train | https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L250-L260 |
OpenGov/python_data_wrap | datawrap/external/xmlparse.py | Worksheet.GetCellValue | def GetCellValue (self, column, row = None, default = None):
""" get a cell, return default if that cell does not exist
note that column and row START AT 1 same as excel
"""
if row == None:
(row, column) = ParseCellSpec... | python | def GetCellValue (self, column, row = None, default = None):
""" get a cell, return default if that cell does not exist
note that column and row START AT 1 same as excel
"""
if row == None:
(row, column) = ParseCellSpec... | [
"def",
"GetCellValue",
"(",
"self",
",",
"column",
",",
"row",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"if",
"row",
"==",
"None",
":",
"(",
"row",
",",
"column",
")",
"=",
"ParseCellSpec",
"(",
"column",
")",
"if",
"row",
"in",
"self",
... | get a cell, return default if that cell does not exist
note that column and row START AT 1 same as excel | [
"get",
"a",
"cell",
"return",
"default",
"if",
"that",
"cell",
"does",
"not",
"exist",
"note",
"that",
"column",
"and",
"row",
"START",
"AT",
"1",
"same",
"as",
"excel"
] | train | https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L288-L296 |
OpenGov/python_data_wrap | datawrap/external/xmlparse.py | Worksheet.GetCellValueNoFail | def GetCellValueNoFail (self, column, row = None):
""" get a cell, if it does not exist fail
note that column at row START AT 1 same as excel
"""
if row == None:
(row, column) = ParseCellSpec(column)
cell = Get... | python | def GetCellValueNoFail (self, column, row = None):
""" get a cell, if it does not exist fail
note that column at row START AT 1 same as excel
"""
if row == None:
(row, column) = ParseCellSpec(column)
cell = Get... | [
"def",
"GetCellValueNoFail",
"(",
"self",
",",
"column",
",",
"row",
"=",
"None",
")",
":",
"if",
"row",
"==",
"None",
":",
"(",
"row",
",",
"column",
")",
"=",
"ParseCellSpec",
"(",
"column",
")",
"cell",
"=",
"GetCellValue",
"(",
"self",
",",
"colu... | get a cell, if it does not exist fail
note that column at row START AT 1 same as excel | [
"get",
"a",
"cell",
"if",
"it",
"does",
"not",
"exist",
"fail",
"note",
"that",
"column",
"at",
"row",
"START",
"AT",
"1",
"same",
"as",
"excel"
] | train | https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L298-L307 |
OpenGov/python_data_wrap | datawrap/external/xmlparse.py | Worksheet.GetCellStyle | def GetCellStyle (self, column, row = None):
""" get the "style" of a cell
note: this merges default, column, row and the cell's style into the actual style for you returning a dictionary of styles
The values directly from excel with the relavent XML el... | python | def GetCellStyle (self, column, row = None):
""" get the "style" of a cell
note: this merges default, column, row and the cell's style into the actual style for you returning a dictionary of styles
The values directly from excel with the relavent XML el... | [
"def",
"GetCellStyle",
"(",
"self",
",",
"column",
",",
"row",
"=",
"None",
")",
":",
"if",
"row",
"==",
"None",
":",
"(",
"row",
",",
"column",
")",
"=",
"ParseCellSpec",
"(",
"column",
")",
"style",
"=",
"{",
"}",
"# get style for cell\r",
"if",
"r... | get the "style" of a cell
note: this merges default, column, row and the cell's style into the actual style for you returning a dictionary of styles
The values directly from excel with the relavent XML element appended to the name. Examples of style key/value pairs
... | [
"get",
"the",
"style",
"of",
"a",
"cell",
"note",
":",
"this",
"merges",
"default",
"column",
"row",
"and",
"the",
"cell",
"s",
"style",
"into",
"the",
"actual",
"style",
"for",
"you",
"returning",
"a",
"dictionary",
"of",
"styles",
"The",
"values",
"dir... | train | https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L309-L339 |
OpenGov/python_data_wrap | datawrap/external/xmlparse.py | Worksheet.GetColumnNumber | def GetColumnNumber (self, columnName):
"""returns the column number for a given column heading name, 0 if not found"""
for row in range(1, self.maxRow + 1):
for column in range(1, self.maxColumn + 1):
if self.GetCellValue(colum... | python | def GetColumnNumber (self, columnName):
"""returns the column number for a given column heading name, 0 if not found"""
for row in range(1, self.maxRow + 1):
for column in range(1, self.maxColumn + 1):
if self.GetCellValue(colum... | [
"def",
"GetColumnNumber",
"(",
"self",
",",
"columnName",
")",
":",
"for",
"row",
"in",
"range",
"(",
"1",
",",
"self",
".",
"maxRow",
"+",
"1",
")",
":",
"for",
"column",
"in",
"range",
"(",
"1",
",",
"self",
".",
"maxColumn",
"+",
"1",
")",
":"... | returns the column number for a given column heading name, 0 if not found | [
"returns",
"the",
"column",
"number",
"for",
"a",
"given",
"column",
"heading",
"name",
"0",
"if",
"not",
"found"
] | train | https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L341-L347 |
OpenGov/python_data_wrap | datawrap/external/xmlparse.py | Worksheet.DumpAsCSV | def DumpAsCSV (self, separator=",", file=sys.stdout):
"""dump as a comma separated value file"""
for row in range(1, self.maxRow + 1):
sep = ""
for column in range(1, self.maxColumn + 1):
file.write("%s\... | python | def DumpAsCSV (self, separator=",", file=sys.stdout):
"""dump as a comma separated value file"""
for row in range(1, self.maxRow + 1):
sep = ""
for column in range(1, self.maxColumn + 1):
file.write("%s\... | [
"def",
"DumpAsCSV",
"(",
"self",
",",
"separator",
"=",
"\",\"",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"for",
"row",
"in",
"range",
"(",
"1",
",",
"self",
".",
"maxRow",
"+",
"1",
")",
":",
"sep",
"=",
"\"\"",
"for",
"column",
"in",
... | dump as a comma separated value file | [
"dump",
"as",
"a",
"comma",
"separated",
"value",
"file"
] | train | https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L349-L356 |
OpenGov/python_data_wrap | datawrap/external/xmlparse.py | ExcelFile.GetWorksheet | def GetWorksheet(self, nameOrNumber):
"""get a sheet by number"""
if isinstance(nameOrNumber, int):
return self.worksheets[nameOrNumber]
else:
return self.worksheetsByName[nameOrNumber] | python | def GetWorksheet(self, nameOrNumber):
"""get a sheet by number"""
if isinstance(nameOrNumber, int):
return self.worksheets[nameOrNumber]
else:
return self.worksheetsByName[nameOrNumber] | [
"def",
"GetWorksheet",
"(",
"self",
",",
"nameOrNumber",
")",
":",
"if",
"isinstance",
"(",
"nameOrNumber",
",",
"int",
")",
":",
"return",
"self",
".",
"worksheets",
"[",
"nameOrNumber",
"]",
"else",
":",
"return",
"self",
".",
"worksheetsByName",
"[",
"n... | get a sheet by number | [
"get",
"a",
"sheet",
"by",
"number"
] | train | https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L399-L404 |
OpenGov/python_data_wrap | datawrap/external/xmlparse.py | ExcelToSparseArrayHandler.startElement | def startElement (self, name, attrs):
'''if there's a start method for this element, call it
'''
func = getattr(self, 'start_' + name, None)
if func:
func(attrs) | python | def startElement (self, name, attrs):
'''if there's a start method for this element, call it
'''
func = getattr(self, 'start_' + name, None)
if func:
func(attrs) | [
"def",
"startElement",
"(",
"self",
",",
"name",
",",
"attrs",
")",
":",
"func",
"=",
"getattr",
"(",
"self",
",",
"'start_'",
"+",
"name",
",",
"None",
")",
"if",
"func",
":",
"func",
"(",
"attrs",
")"
] | if there's a start method for this element, call it | [
"if",
"there",
"s",
"a",
"start",
"method",
"for",
"this",
"element",
"call",
"it"
] | train | https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L521-L526 |
heikomuller/sco-engine | scoengine/reqbuf_worker.py | handle_request | def handle_request(request):
"""Convert a model run request from the buffer into a message in a RabbitMQ
queue.
Parameters
----------
request : dict
Buffer entry containing 'connector' and 'request' field
"""
connector = request['connector']
hostname = connector['host']
port... | python | def handle_request(request):
"""Convert a model run request from the buffer into a message in a RabbitMQ
queue.
Parameters
----------
request : dict
Buffer entry containing 'connector' and 'request' field
"""
connector = request['connector']
hostname = connector['host']
port... | [
"def",
"handle_request",
"(",
"request",
")",
":",
"connector",
"=",
"request",
"[",
"'connector'",
"]",
"hostname",
"=",
"connector",
"[",
"'host'",
"]",
"port",
"=",
"connector",
"[",
"'port'",
"]",
"virtual_host",
"=",
"connector",
"[",
"'virtualHost'",
"... | Convert a model run request from the buffer into a message in a RabbitMQ
queue.
Parameters
----------
request : dict
Buffer entry containing 'connector' and 'request' field | [
"Convert",
"a",
"model",
"run",
"request",
"from",
"the",
"buffer",
"into",
"a",
"message",
"in",
"a",
"RabbitMQ",
"queue",
"."
] | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/reqbuf_worker.py#L19-L64 |
spookey/photon | photon/util/locations.py | get_locations | def get_locations():
'''
Compiles default locations
:returns:
A dictionary with folders as values:
* 'home_dir': Your home-directory (:file:`~`)
* 'call_dir': Where you called the first Python script from. (``argv[0]``)
* 'conf_dir': The :envvar:`XDG_CONFIG_HOME`-directory + \
``... | python | def get_locations():
'''
Compiles default locations
:returns:
A dictionary with folders as values:
* 'home_dir': Your home-directory (:file:`~`)
* 'call_dir': Where you called the first Python script from. (``argv[0]``)
* 'conf_dir': The :envvar:`XDG_CONFIG_HOME`-directory + \
``... | [
"def",
"get_locations",
"(",
")",
":",
"home_dir",
"=",
"_path",
".",
"expanduser",
"(",
"'~'",
")",
"conf_dir",
"=",
"_path",
".",
"join",
"(",
"_environ",
".",
"get",
"(",
"'XDG_CONFIG_HOME'",
",",
"_path",
".",
"join",
"(",
"home_dir",
",",
"'.config'... | Compiles default locations
:returns:
A dictionary with folders as values:
* 'home_dir': Your home-directory (:file:`~`)
* 'call_dir': Where you called the first Python script from. (``argv[0]``)
* 'conf_dir': The :envvar:`XDG_CONFIG_HOME`-directory + \
``photon`` (:file:`~/.config/photon... | [
"Compiles",
"default",
"locations"
] | train | https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/util/locations.py#L24-L70 |
spookey/photon | photon/util/locations.py | make_locations | def make_locations(locations=None, verbose=True):
'''
Creates folders
:param locations:
A list of folders to create (can be a dictionary, see note below)
:param verbose:
Warn if any folders were created
.. note::
* |params_locations_dict|
* |param_locations_none|
... | python | def make_locations(locations=None, verbose=True):
'''
Creates folders
:param locations:
A list of folders to create (can be a dictionary, see note below)
:param verbose:
Warn if any folders were created
.. note::
* |params_locations_dict|
* |param_locations_none|
... | [
"def",
"make_locations",
"(",
"locations",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"from",
"photon",
".",
"util",
".",
"structures",
"import",
"to_list",
"from",
"photon",
".",
"util",
".",
"system",
"import",
"shell_notify",
"if",
"not",
"loca... | Creates folders
:param locations:
A list of folders to create (can be a dictionary, see note below)
:param verbose:
Warn if any folders were created
.. note::
* |params_locations_dict|
* |param_locations_none| | [
"Creates",
"folders"
] | train | https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/util/locations.py#L73-L102 |
spookey/photon | photon/util/locations.py | search_location | def search_location(loc, locations=None,
critical=False, create_in=None, verbose=True):
'''
Locates files with a twist:
* Check the existence of a file using the full path in `loc`
* Search for the filename `loc` in `locations`
* Create it's enclosing folders if th... | python | def search_location(loc, locations=None,
critical=False, create_in=None, verbose=True):
'''
Locates files with a twist:
* Check the existence of a file using the full path in `loc`
* Search for the filename `loc` in `locations`
* Create it's enclosing folders if th... | [
"def",
"search_location",
"(",
"loc",
",",
"locations",
"=",
"None",
",",
"critical",
"=",
"False",
",",
"create_in",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"from",
"photon",
".",
"util",
".",
"structures",
"import",
"to_list",
"from",
"phot... | Locates files with a twist:
* Check the existence of a file using the full path in `loc`
* Search for the filename `loc` in `locations`
* Create it's enclosing folders if the file does not exist. \
use `create_in`
:param loc:
Filename to search
:param locations:
... | [
"Locates",
"files",
"with",
"a",
"twist",
":"
] | train | https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/util/locations.py#L105-L162 |
spookey/photon | photon/util/locations.py | change_location | def change_location(src, tgt, move=False, verbose=True):
'''
Copies/moves/deletes locations
:param src:
Source location where to copy from
:param tgt:
Target location where to copy to
* To backup `src`, set `tgt` explicitly to ``True``. \
`tgt` will be set to `src` + '_... | python | def change_location(src, tgt, move=False, verbose=True):
'''
Copies/moves/deletes locations
:param src:
Source location where to copy from
:param tgt:
Target location where to copy to
* To backup `src`, set `tgt` explicitly to ``True``. \
`tgt` will be set to `src` + '_... | [
"def",
"change_location",
"(",
"src",
",",
"tgt",
",",
"move",
"=",
"False",
",",
"verbose",
"=",
"True",
")",
":",
"from",
"photon",
".",
"util",
".",
"system",
"import",
"shell_notify",
"if",
"_path",
".",
"exists",
"(",
"src",
")",
":",
"if",
"tgt... | Copies/moves/deletes locations
:param src:
Source location where to copy from
:param tgt:
Target location where to copy to
* To backup `src`, set `tgt` explicitly to ``True``. \
`tgt` will be set to `src` + '_backup_' + \
:func:`util.system.get_timestamp` then
:par... | [
"Copies",
"/",
"moves",
"/",
"deletes",
"locations"
] | train | https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/util/locations.py#L165-L217 |
spookey/photon | photon/util/locations.py | backup_location | def backup_location(src, loc=None):
'''
Writes Backups of locations
:param src:
The source file/folder to backup
:param loc:
The target folder to backup into
The backup will be called `src` + :func:`util.system.get_timestamp`.
* If `loc` left to none, the backup gets wr... | python | def backup_location(src, loc=None):
'''
Writes Backups of locations
:param src:
The source file/folder to backup
:param loc:
The target folder to backup into
The backup will be called `src` + :func:`util.system.get_timestamp`.
* If `loc` left to none, the backup gets wr... | [
"def",
"backup_location",
"(",
"src",
",",
"loc",
"=",
"None",
")",
":",
"from",
"photon",
".",
"util",
".",
"system",
"import",
"get_timestamp",
"src",
"=",
"_path",
".",
"realpath",
"(",
"src",
")",
"if",
"not",
"loc",
"or",
"not",
"loc",
".",
"sta... | Writes Backups of locations
:param src:
The source file/folder to backup
:param loc:
The target folder to backup into
The backup will be called `src` + :func:`util.system.get_timestamp`.
* If `loc` left to none, the backup gets written in the same \
folder like `src` re... | [
"Writes",
"Backups",
"of",
"locations"
] | train | https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/util/locations.py#L220-L245 |
rcook/pyprelude | pyprelude/file_system.py | make_path | def make_path(*args):
"""
>>> _hack_make_path_doctest_output(make_path("/a", "b"))
'/a/b'
>>> _hack_make_path_doctest_output(make_path(["/a", "b"]))
'/a/b'
>>> _hack_make_path_doctest_output(make_path(*["/a", "b"]))
'/a/b'
>>> _hack_make_path_doctest_output(make_path("/a"))
'/a'
... | python | def make_path(*args):
"""
>>> _hack_make_path_doctest_output(make_path("/a", "b"))
'/a/b'
>>> _hack_make_path_doctest_output(make_path(["/a", "b"]))
'/a/b'
>>> _hack_make_path_doctest_output(make_path(*["/a", "b"]))
'/a/b'
>>> _hack_make_path_doctest_output(make_path("/a"))
'/a'
... | [
"def",
"make_path",
"(",
"*",
"args",
")",
":",
"paths",
"=",
"unpack_args",
"(",
"*",
"args",
")",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"*",
"[",
"p",
"for",
"p",
"in",
"paths",
"if",
"p",
"is"... | >>> _hack_make_path_doctest_output(make_path("/a", "b"))
'/a/b'
>>> _hack_make_path_doctest_output(make_path(["/a", "b"]))
'/a/b'
>>> _hack_make_path_doctest_output(make_path(*["/a", "b"]))
'/a/b'
>>> _hack_make_path_doctest_output(make_path("/a"))
'/a'
>>> _hack_make_path_doctest_output... | [
">>>",
"_hack_make_path_doctest_output",
"(",
"make_path",
"(",
"/",
"a",
"b",
"))",
"/",
"a",
"/",
"b",
">>>",
"_hack_make_path_doctest_output",
"(",
"make_path",
"(",
"[",
"/",
"a",
"b",
"]",
"))",
"/",
"a",
"/",
"b",
">>>",
"_hack_make_path_doctest_output... | train | https://github.com/rcook/pyprelude/blob/a473b34db8045e8715154b8840291d4facc8f94c/pyprelude/file_system.py#L51-L67 |
nir0s/serv | serv/serv.py | generate | def generate(command,
name,
init_system,
overwrite,
deploy,
start,
verbose,
**params):
"""Create a service.
`COMMAND` is the path to the executable to run
"""
# TODO: Add a `prefix` flag which can be used to pref... | python | def generate(command,
name,
init_system,
overwrite,
deploy,
start,
verbose,
**params):
"""Create a service.
`COMMAND` is the path to the executable to run
"""
# TODO: Add a `prefix` flag which can be used to pref... | [
"def",
"generate",
"(",
"command",
",",
"name",
",",
"init_system",
",",
"overwrite",
",",
"deploy",
",",
"start",
",",
"verbose",
",",
"*",
"*",
"params",
")",
":",
"# TODO: Add a `prefix` flag which can be used to prefix",
"# `COMMAND` with `su -c`, etc..",
"try",
... | Create a service.
`COMMAND` is the path to the executable to run | [
"Create",
"a",
"service",
"."
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L394-L412 |
nir0s/serv | serv/serv.py | status | def status(name, init_system, verbose):
"""WIP! Try at your own expense
"""
try:
status = Serv(init_system, verbose=verbose).status(name)
except ServError as ex:
sys.exit(ex)
click.echo(json.dumps(status, indent=4, sort_keys=True)) | python | def status(name, init_system, verbose):
"""WIP! Try at your own expense
"""
try:
status = Serv(init_system, verbose=verbose).status(name)
except ServError as ex:
sys.exit(ex)
click.echo(json.dumps(status, indent=4, sort_keys=True)) | [
"def",
"status",
"(",
"name",
",",
"init_system",
",",
"verbose",
")",
":",
"try",
":",
"status",
"=",
"Serv",
"(",
"init_system",
",",
"verbose",
"=",
"verbose",
")",
".",
"status",
"(",
"name",
")",
"except",
"ServError",
"as",
"ex",
":",
"sys",
".... | WIP! Try at your own expense | [
"WIP!",
"Try",
"at",
"your",
"own",
"expense"
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L432-L439 |
nir0s/serv | serv/serv.py | start | def start(name, init_system, verbose):
"""Start a service
"""
try:
Serv(init_system, verbose=verbose).start(name)
except ServError as ex:
sys.exit(ex) | python | def start(name, init_system, verbose):
"""Start a service
"""
try:
Serv(init_system, verbose=verbose).start(name)
except ServError as ex:
sys.exit(ex) | [
"def",
"start",
"(",
"name",
",",
"init_system",
",",
"verbose",
")",
":",
"try",
":",
"Serv",
"(",
"init_system",
",",
"verbose",
"=",
"verbose",
")",
".",
"start",
"(",
"name",
")",
"except",
"ServError",
"as",
"ex",
":",
"sys",
".",
"exit",
"(",
... | Start a service | [
"Start",
"a",
"service"
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L459-L465 |
nir0s/serv | serv/serv.py | Serv._parse_service_env_vars | def _parse_service_env_vars(self, env_vars):
"""Return a dict based on `key=value` pair strings.
"""
env = {}
for var in env_vars:
# Yeah yeah.. it's less performant.. splitting twice.. who cares.
k, v = var.split('=')
env.update({k: v})
return... | python | def _parse_service_env_vars(self, env_vars):
"""Return a dict based on `key=value` pair strings.
"""
env = {}
for var in env_vars:
# Yeah yeah.. it's less performant.. splitting twice.. who cares.
k, v = var.split('=')
env.update({k: v})
return... | [
"def",
"_parse_service_env_vars",
"(",
"self",
",",
"env_vars",
")",
":",
"env",
"=",
"{",
"}",
"for",
"var",
"in",
"env_vars",
":",
"# Yeah yeah.. it's less performant.. splitting twice.. who cares.",
"k",
",",
"v",
"=",
"var",
".",
"split",
"(",
"'='",
")",
... | Return a dict based on `key=value` pair strings. | [
"Return",
"a",
"dict",
"based",
"on",
"key",
"=",
"value",
"pair",
"strings",
"."
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L71-L79 |
nir0s/serv | serv/serv.py | Serv._set_service_name_from_command | def _set_service_name_from_command(self, cmd):
"""Set the name of a service according to the command.
This is only relevant if the name wasn't explicitly provided.
Note that this is risky as it sets the name according to the
name of the file the command is using. If two services
... | python | def _set_service_name_from_command(self, cmd):
"""Set the name of a service according to the command.
This is only relevant if the name wasn't explicitly provided.
Note that this is risky as it sets the name according to the
name of the file the command is using. If two services
... | [
"def",
"_set_service_name_from_command",
"(",
"self",
",",
"cmd",
")",
":",
"# TODO: Consider assign incremental integers to the name if a service",
"# with the same name already exists.",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"cmd",
")",
"logger",
".",
"i... | Set the name of a service according to the command.
This is only relevant if the name wasn't explicitly provided.
Note that this is risky as it sets the name according to the
name of the file the command is using. If two services
use the same binary, even if their args are different, th... | [
"Set",
"the",
"name",
"of",
"a",
"service",
"according",
"to",
"the",
"command",
"."
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L81-L96 |
nir0s/serv | serv/serv.py | Serv.generate | def generate(self,
cmd,
name='',
overwrite=False,
deploy=False,
start=False,
**params):
"""Generate service files and returns a list of the generated files.
It will generate configuration file(s) for t... | python | def generate(self,
cmd,
name='',
overwrite=False,
deploy=False,
start=False,
**params):
"""Generate service files and returns a list of the generated files.
It will generate configuration file(s) for t... | [
"def",
"generate",
"(",
"self",
",",
"cmd",
",",
"name",
"=",
"''",
",",
"overwrite",
"=",
"False",
",",
"deploy",
"=",
"False",
",",
"start",
"=",
"False",
",",
"*",
"*",
"params",
")",
":",
"# TODO: parsing env vars and setting the name should probably be un... | Generate service files and returns a list of the generated files.
It will generate configuration file(s) for the service and
deploy them to the tmp dir on your os.
If `deploy` is True, the service will be configured to run on the
current machine.
If `start` is True, the service... | [
"Generate",
"service",
"files",
"and",
"returns",
"a",
"list",
"of",
"the",
"generated",
"files",
"."
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L98-L145 |
nir0s/serv | serv/serv.py | Serv.remove | def remove(self, name):
"""Remove a service completely.
It will try to stop the service and then uninstall it.
The implementation is, of course, system specific.
For instance, for upstart, it will `stop <name` and then
delete /etc/init/<name>.conf.
"""
init = sel... | python | def remove(self, name):
"""Remove a service completely.
It will try to stop the service and then uninstall it.
The implementation is, of course, system specific.
For instance, for upstart, it will `stop <name` and then
delete /etc/init/<name>.conf.
"""
init = sel... | [
"def",
"remove",
"(",
"self",
",",
"name",
")",
":",
"init",
"=",
"self",
".",
"_get_implementation",
"(",
"name",
")",
"self",
".",
"_assert_service_installed",
"(",
"init",
",",
"name",
")",
"logger",
".",
"info",
"(",
"'Removing %s service %s...'",
",",
... | Remove a service completely.
It will try to stop the service and then uninstall it.
The implementation is, of course, system specific.
For instance, for upstart, it will `stop <name` and then
delete /etc/init/<name>.conf. | [
"Remove",
"a",
"service",
"completely",
"."
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L147-L160 |
nir0s/serv | serv/serv.py | Serv.status | def status(self, name=''):
"""Return a list containing a single service's info if `name`
is supplied, else returns a list of all services' info.
"""
logger.warn(
'Note that `status` is currently not so robust and may break on '
'different systems')
init = ... | python | def status(self, name=''):
"""Return a list containing a single service's info if `name`
is supplied, else returns a list of all services' info.
"""
logger.warn(
'Note that `status` is currently not so robust and may break on '
'different systems')
init = ... | [
"def",
"status",
"(",
"self",
",",
"name",
"=",
"''",
")",
":",
"logger",
".",
"warn",
"(",
"'Note that `status` is currently not so robust and may break on '",
"'different systems'",
")",
"init",
"=",
"self",
".",
"_get_implementation",
"(",
"name",
")",
"if",
"n... | Return a list containing a single service's info if `name`
is supplied, else returns a list of all services' info. | [
"Return",
"a",
"list",
"containing",
"a",
"single",
"service",
"s",
"info",
"if",
"name",
"is",
"supplied",
"else",
"returns",
"a",
"list",
"of",
"all",
"services",
"info",
"."
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L162-L173 |
nir0s/serv | serv/serv.py | Serv.stop | def stop(self, name):
"""Stop a service
"""
init = self._get_implementation(name)
self._assert_service_installed(init, name)
logger.info('Stopping service: %s...', name)
init.stop() | python | def stop(self, name):
"""Stop a service
"""
init = self._get_implementation(name)
self._assert_service_installed(init, name)
logger.info('Stopping service: %s...', name)
init.stop() | [
"def",
"stop",
"(",
"self",
",",
"name",
")",
":",
"init",
"=",
"self",
".",
"_get_implementation",
"(",
"name",
")",
"self",
".",
"_assert_service_installed",
"(",
"init",
",",
"name",
")",
"logger",
".",
"info",
"(",
"'Stopping service: %s...'",
",",
"na... | Stop a service | [
"Stop",
"a",
"service"
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L175-L181 |
nir0s/serv | serv/serv.py | Serv.start | def start(self, name):
"""Start a service
"""
init = self._get_implementation(name)
self._assert_service_installed(init, name)
logger.info('Starting service: %s...', name)
init.start() | python | def start(self, name):
"""Start a service
"""
init = self._get_implementation(name)
self._assert_service_installed(init, name)
logger.info('Starting service: %s...', name)
init.start() | [
"def",
"start",
"(",
"self",
",",
"name",
")",
":",
"init",
"=",
"self",
".",
"_get_implementation",
"(",
"name",
")",
"self",
".",
"_assert_service_installed",
"(",
"init",
",",
"name",
")",
"logger",
".",
"info",
"(",
"'Starting service: %s...'",
",",
"n... | Start a service | [
"Start",
"a",
"service"
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L183-L189 |
nir0s/serv | serv/serv.py | Serv.restart | def restart(self, name):
"""Restart a service
"""
init = self._get_implementation(name)
self._assert_service_installed(init, name)
logger.info('Restarting service: %s...', name)
init.stop()
# Here we would use status to verify that the service stopped
# be... | python | def restart(self, name):
"""Restart a service
"""
init = self._get_implementation(name)
self._assert_service_installed(init, name)
logger.info('Restarting service: %s...', name)
init.stop()
# Here we would use status to verify that the service stopped
# be... | [
"def",
"restart",
"(",
"self",
",",
"name",
")",
":",
"init",
"=",
"self",
".",
"_get_implementation",
"(",
"name",
")",
"self",
".",
"_assert_service_installed",
"(",
"init",
",",
"name",
")",
"logger",
".",
"info",
"(",
"'Restarting service: %s...'",
",",
... | Restart a service | [
"Restart",
"a",
"service"
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L191-L202 |
nir0s/serv | serv/serv.py | Serv.lookup_init_systems | def lookup_init_systems(self):
"""Return the relevant init system and its version.
This will try to look at the mapping first. If the mapping
doesn't exist, it will try to identify it automatically.
Windows lookup is not supported and `nssm` is assumed.
"""
if utils.IS_... | python | def lookup_init_systems(self):
"""Return the relevant init system and its version.
This will try to look at the mapping first. If the mapping
doesn't exist, it will try to identify it automatically.
Windows lookup is not supported and `nssm` is assumed.
"""
if utils.IS_... | [
"def",
"lookup_init_systems",
"(",
"self",
")",
":",
"if",
"utils",
".",
"IS_WIN",
":",
"logger",
".",
"debug",
"(",
"'Lookup is not supported on Windows. Assuming nssm...'",
")",
"return",
"[",
"'nssm'",
"]",
"if",
"utils",
".",
"IS_DARWIN",
":",
"logger",
".",... | Return the relevant init system and its version.
This will try to look at the mapping first. If the mapping
doesn't exist, it will try to identify it automatically.
Windows lookup is not supported and `nssm` is assumed. | [
"Return",
"the",
"relevant",
"init",
"system",
"and",
"its",
"version",
"."
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L214-L233 |
nir0s/serv | serv/serv.py | Serv._init_sys_auto_lookup | def _init_sys_auto_lookup(self):
"""Return a list of tuples of available init systems on the
current machine.
Note that in some situations (Ubuntu 14.04 for instance) more than
one init system can be found.
"""
# TODO: Instead, check for executables for systemd and upsta... | python | def _init_sys_auto_lookup(self):
"""Return a list of tuples of available init systems on the
current machine.
Note that in some situations (Ubuntu 14.04 for instance) more than
one init system can be found.
"""
# TODO: Instead, check for executables for systemd and upsta... | [
"def",
"_init_sys_auto_lookup",
"(",
"self",
")",
":",
"# TODO: Instead, check for executables for systemd and upstart",
"# systemctl for systemd and initctl for upstart.",
"# An alternative might be to check the second answer here:",
"# http://unix.stackexchange.com/questions/196166/how-to-find-o... | Return a list of tuples of available init systems on the
current machine.
Note that in some situations (Ubuntu 14.04 for instance) more than
one init system can be found. | [
"Return",
"a",
"list",
"of",
"tuples",
"of",
"available",
"init",
"systems",
"on",
"the",
"current",
"machine",
"."
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L238-L257 |
nir0s/serv | serv/serv.py | Serv._lookup_by_mapping | def _lookup_by_mapping():
"""Return a the init system based on a constant mapping of
distribution+version to init system..
See constants.py for the mapping.
A failover of the version is proposed for when no version is supplied.
For instance, Arch Linux's version will most probab... | python | def _lookup_by_mapping():
"""Return a the init system based on a constant mapping of
distribution+version to init system..
See constants.py for the mapping.
A failover of the version is proposed for when no version is supplied.
For instance, Arch Linux's version will most probab... | [
"def",
"_lookup_by_mapping",
"(",
")",
":",
"like",
"=",
"distro",
".",
"like",
"(",
")",
".",
"lower",
"(",
")",
"distribution_id",
"=",
"distro",
".",
"id",
"(",
")",
".",
"lower",
"(",
")",
"version",
"=",
"distro",
".",
"major_version",
"(",
")",... | Return a the init system based on a constant mapping of
distribution+version to init system..
See constants.py for the mapping.
A failover of the version is proposed for when no version is supplied.
For instance, Arch Linux's version will most probably be "rolling" at
any given ... | [
"Return",
"a",
"the",
"init",
"system",
"based",
"on",
"a",
"constant",
"mapping",
"of",
"distribution",
"+",
"version",
"to",
"init",
"system",
".."
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L260-L284 |
doptio/heywood | src/heywood/watchdog.py | all_files | def all_files(file_or_directory):
'return all files under file_or_directory.'
if os.path.isdir(file_or_directory):
return [os.path.join(dirname, filename)
for dirname, dirnames, filenames in os.walk(file_or_directory)
for filename in filenames]
else:
return [f... | python | def all_files(file_or_directory):
'return all files under file_or_directory.'
if os.path.isdir(file_or_directory):
return [os.path.join(dirname, filename)
for dirname, dirnames, filenames in os.walk(file_or_directory)
for filename in filenames]
else:
return [f... | [
"def",
"all_files",
"(",
"file_or_directory",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"file_or_directory",
")",
":",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"filename",
")",
"for",
"dirname",
",",
"dirnames",
"... | return all files under file_or_directory. | [
"return",
"all",
"files",
"under",
"file_or_directory",
"."
] | train | https://github.com/doptio/heywood/blob/40c2b1f28d43524a16b390fd3a4f6832f16fec41/src/heywood/watchdog.py#L41-L48 |
doptio/heywood | src/heywood/watchdog.py | super_glob | def super_glob(pattern):
'glob that understands **/ for all sub-directories recursively.'
pieces = pattern.split('/')
if '**' in pieces:
prefix = '/'.join(pieces[:pieces.index('**')])
postfix = '/'.join(pieces[pieces.index('**') + 1:])
roots = [dirname
for dirname, d... | python | def super_glob(pattern):
'glob that understands **/ for all sub-directories recursively.'
pieces = pattern.split('/')
if '**' in pieces:
prefix = '/'.join(pieces[:pieces.index('**')])
postfix = '/'.join(pieces[pieces.index('**') + 1:])
roots = [dirname
for dirname, d... | [
"def",
"super_glob",
"(",
"pattern",
")",
":",
"pieces",
"=",
"pattern",
".",
"split",
"(",
"'/'",
")",
"if",
"'**'",
"in",
"pieces",
":",
"prefix",
"=",
"'/'",
".",
"join",
"(",
"pieces",
"[",
":",
"pieces",
".",
"index",
"(",
"'**'",
")",
"]",
... | glob that understands **/ for all sub-directories recursively. | [
"glob",
"that",
"understands",
"**",
"/",
"for",
"all",
"sub",
"-",
"directories",
"recursively",
"."
] | train | https://github.com/doptio/heywood/blob/40c2b1f28d43524a16b390fd3a4f6832f16fec41/src/heywood/watchdog.py#L51-L62 |
knagra/farnsworth | base/views.py | add_context | def add_context(request):
""" Add variables to all dictionaries passed to templates. """
# Whether the user has president privileges
try:
PRESIDENT = Manager.objects.filter(
incumbent__user=request.user,
president=True,
).count() > 0
except TypeError:
PRES... | python | def add_context(request):
""" Add variables to all dictionaries passed to templates. """
# Whether the user has president privileges
try:
PRESIDENT = Manager.objects.filter(
incumbent__user=request.user,
president=True,
).count() > 0
except TypeError:
PRES... | [
"def",
"add_context",
"(",
"request",
")",
":",
"# Whether the user has president privileges",
"try",
":",
"PRESIDENT",
"=",
"Manager",
".",
"objects",
".",
"filter",
"(",
"incumbent__user",
"=",
"request",
".",
"user",
",",
"president",
"=",
"True",
",",
")",
... | Add variables to all dictionaries passed to templates. | [
"Add",
"variables",
"to",
"all",
"dictionaries",
"passed",
"to",
"templates",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L54-L99 |
knagra/farnsworth | base/views.py | landing_view | def landing_view(request):
''' The external landing.'''
revision = None
can_edit = False
edit_url = None
if "farnswiki" in settings.INSTALLED_APPS:
from wiki.models import Page
from wiki.hooks import hookset
binder = settings.WIKI_BINDERS[0]
wiki = binder.lookup()
... | python | def landing_view(request):
''' The external landing.'''
revision = None
can_edit = False
edit_url = None
if "farnswiki" in settings.INSTALLED_APPS:
from wiki.models import Page
from wiki.hooks import hookset
binder = settings.WIKI_BINDERS[0]
wiki = binder.lookup()
... | [
"def",
"landing_view",
"(",
"request",
")",
":",
"revision",
"=",
"None",
"can_edit",
"=",
"False",
"edit_url",
"=",
"None",
"if",
"\"farnswiki\"",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"from",
"wiki",
".",
"models",
"import",
"Page",
"from",
"wiki",... | The external landing. | [
"The",
"external",
"landing",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L101-L130 |
knagra/farnsworth | base/views.py | homepage_view | def homepage_view(request, message=None):
''' The view of the homepage. '''
userProfile = UserProfile.objects.get(user=request.user)
request_types = RequestType.objects.filter(enabled=True)
# List of request types for which the user is a relevant manager
manager_request_types = list()
for reques... | python | def homepage_view(request, message=None):
''' The view of the homepage. '''
userProfile = UserProfile.objects.get(user=request.user)
request_types = RequestType.objects.filter(enabled=True)
# List of request types for which the user is a relevant manager
manager_request_types = list()
for reques... | [
"def",
"homepage_view",
"(",
"request",
",",
"message",
"=",
"None",
")",
":",
"userProfile",
"=",
"UserProfile",
".",
"objects",
".",
"get",
"(",
"user",
"=",
"request",
".",
"user",
")",
"request_types",
"=",
"RequestType",
".",
"objects",
".",
"filter",... | The view of the homepage. | [
"The",
"view",
"of",
"the",
"homepage",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L133-L289 |
knagra/farnsworth | base/views.py | my_profile_view | def my_profile_view(request):
''' The view of the profile page. '''
page_name = "Profile Page"
if request.user.username == ANONYMOUS_USERNAME:
return red_home(request, MESSAGES['SPINELESS'])
userProfile = UserProfile.objects.get(user=request.user)
change_password_form = PasswordChangeForm(
... | python | def my_profile_view(request):
''' The view of the profile page. '''
page_name = "Profile Page"
if request.user.username == ANONYMOUS_USERNAME:
return red_home(request, MESSAGES['SPINELESS'])
userProfile = UserProfile.objects.get(user=request.user)
change_password_form = PasswordChangeForm(
... | [
"def",
"my_profile_view",
"(",
"request",
")",
":",
"page_name",
"=",
"\"Profile Page\"",
"if",
"request",
".",
"user",
".",
"username",
"==",
"ANONYMOUS_USERNAME",
":",
"return",
"red_home",
"(",
"request",
",",
"MESSAGES",
"[",
"'SPINELESS'",
"]",
")",
"user... | The view of the profile page. | [
"The",
"view",
"of",
"the",
"profile",
"page",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L305-L341 |
knagra/farnsworth | base/views.py | notifications_view | def notifications_view(request):
"""
Show a user their notifications.
"""
page_name = "Your Notifications"
# Copy the notifications so that they are still unread when we render the page
notifications = list(request.user.notifications.all())
request.user.notifications.mark_all_as_read()
r... | python | def notifications_view(request):
"""
Show a user their notifications.
"""
page_name = "Your Notifications"
# Copy the notifications so that they are still unread when we render the page
notifications = list(request.user.notifications.all())
request.user.notifications.mark_all_as_read()
r... | [
"def",
"notifications_view",
"(",
"request",
")",
":",
"page_name",
"=",
"\"Your Notifications\"",
"# Copy the notifications so that they are still unread when we render the page",
"notifications",
"=",
"list",
"(",
"request",
".",
"user",
".",
"notifications",
".",
"all",
... | Show a user their notifications. | [
"Show",
"a",
"user",
"their",
"notifications",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L344-L355 |
knagra/farnsworth | base/views.py | login_view | def login_view(request):
''' The view of the login page. '''
ANONYMOUS_SESSION = request.session.get('ANONYMOUS_SESSION', False)
page_name = "Login Page"
redirect_to = request.GET.get('next', reverse('homepage'))
if (request.user.is_authenticated() and not ANONYMOUS_SESSION) or (ANONYMOUS_SESSION an... | python | def login_view(request):
''' The view of the login page. '''
ANONYMOUS_SESSION = request.session.get('ANONYMOUS_SESSION', False)
page_name = "Login Page"
redirect_to = request.GET.get('next', reverse('homepage'))
if (request.user.is_authenticated() and not ANONYMOUS_SESSION) or (ANONYMOUS_SESSION an... | [
"def",
"login_view",
"(",
"request",
")",
":",
"ANONYMOUS_SESSION",
"=",
"request",
".",
"session",
".",
"get",
"(",
"'ANONYMOUS_SESSION'",
",",
"False",
")",
"page_name",
"=",
"\"Login Page\"",
"redirect_to",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'n... | The view of the login page. | [
"The",
"view",
"of",
"the",
"login",
"page",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L357-L381 |
knagra/farnsworth | base/views.py | member_profile_view | def member_profile_view(request, targetUsername):
''' View a member's Profile. '''
if targetUsername == request.user.username and targetUsername != ANONYMOUS_USERNAME:
return HttpResponseRedirect(reverse('my_profile'))
page_name = "{0}'s Profile".format(targetUsername)
targetUser = get_object_or... | python | def member_profile_view(request, targetUsername):
''' View a member's Profile. '''
if targetUsername == request.user.username and targetUsername != ANONYMOUS_USERNAME:
return HttpResponseRedirect(reverse('my_profile'))
page_name = "{0}'s Profile".format(targetUsername)
targetUser = get_object_or... | [
"def",
"member_profile_view",
"(",
"request",
",",
"targetUsername",
")",
":",
"if",
"targetUsername",
"==",
"request",
".",
"user",
".",
"username",
"and",
"targetUsername",
"!=",
"ANONYMOUS_USERNAME",
":",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"... | View a member's Profile. | [
"View",
"a",
"member",
"s",
"Profile",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L444-L465 |
knagra/farnsworth | base/views.py | request_profile_view | def request_profile_view(request):
''' The page to request a user profile on the site. '''
page_name = "Profile Request Page"
redirect_to = request.GET.get('next', reverse('homepage'))
if request.user.is_authenticated() and request.user.username != ANONYMOUS_USERNAME:
return HttpResponseRedirect... | python | def request_profile_view(request):
''' The page to request a user profile on the site. '''
page_name = "Profile Request Page"
redirect_to = request.GET.get('next', reverse('homepage'))
if request.user.is_authenticated() and request.user.username != ANONYMOUS_USERNAME:
return HttpResponseRedirect... | [
"def",
"request_profile_view",
"(",
"request",
")",
":",
"page_name",
"=",
"\"Profile Request Page\"",
"redirect_to",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'next'",
",",
"reverse",
"(",
"'homepage'",
")",
")",
"if",
"request",
".",
"user",
".",
"is_a... | The page to request a user profile on the site. | [
"The",
"page",
"to",
"request",
"a",
"user",
"profile",
"on",
"the",
"site",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L467-L518 |
knagra/farnsworth | base/views.py | manage_profile_requests_view | def manage_profile_requests_view(request):
''' The page to manage user profile requests. '''
page_name = "Admin - Manage Profile Requests"
profile_requests = ProfileRequest.objects.all()
return render_to_response('manage_profile_requests.html', {
'page_name': page_name,
'choices': UserPr... | python | def manage_profile_requests_view(request):
''' The page to manage user profile requests. '''
page_name = "Admin - Manage Profile Requests"
profile_requests = ProfileRequest.objects.all()
return render_to_response('manage_profile_requests.html', {
'page_name': page_name,
'choices': UserPr... | [
"def",
"manage_profile_requests_view",
"(",
"request",
")",
":",
"page_name",
"=",
"\"Admin - Manage Profile Requests\"",
"profile_requests",
"=",
"ProfileRequest",
".",
"objects",
".",
"all",
"(",
")",
"return",
"render_to_response",
"(",
"'manage_profile_requests.html'",
... | The page to manage user profile requests. | [
"The",
"page",
"to",
"manage",
"user",
"profile",
"requests",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L521-L529 |
knagra/farnsworth | base/views.py | modify_profile_request_view | def modify_profile_request_view(request, request_pk):
''' The page to modify a user's profile request. request_pk is the pk of the profile request. '''
page_name = "Admin - Profile Request"
profile_request = get_object_or_404(ProfileRequest, pk=request_pk)
mod_form = ModifyProfileRequestForm(
re... | python | def modify_profile_request_view(request, request_pk):
''' The page to modify a user's profile request. request_pk is the pk of the profile request. '''
page_name = "Admin - Profile Request"
profile_request = get_object_or_404(ProfileRequest, pk=request_pk)
mod_form = ModifyProfileRequestForm(
re... | [
"def",
"modify_profile_request_view",
"(",
"request",
",",
"request_pk",
")",
":",
"page_name",
"=",
"\"Admin - Profile Request\"",
"profile_request",
"=",
"get_object_or_404",
"(",
"ProfileRequest",
",",
"pk",
"=",
"request_pk",
")",
"mod_form",
"=",
"ModifyProfileRequ... | The page to modify a user's profile request. request_pk is the pk of the profile request. | [
"The",
"page",
"to",
"modify",
"a",
"user",
"s",
"profile",
"request",
".",
"request_pk",
"is",
"the",
"pk",
"of",
"the",
"profile",
"request",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L532-L587 |
knagra/farnsworth | base/views.py | custom_modify_user_view | def custom_modify_user_view(request, targetUsername):
''' The page to modify a user. '''
if targetUsername == ANONYMOUS_USERNAME:
messages.add_message(request, messages.WARNING, MESSAGES['ANONYMOUS_EDIT'])
page_name = "Admin - Modify User"
targetUser = get_object_or_404(User, username=targetUser... | python | def custom_modify_user_view(request, targetUsername):
''' The page to modify a user. '''
if targetUsername == ANONYMOUS_USERNAME:
messages.add_message(request, messages.WARNING, MESSAGES['ANONYMOUS_EDIT'])
page_name = "Admin - Modify User"
targetUser = get_object_or_404(User, username=targetUser... | [
"def",
"custom_modify_user_view",
"(",
"request",
",",
"targetUsername",
")",
":",
"if",
"targetUsername",
"==",
"ANONYMOUS_USERNAME",
":",
"messages",
".",
"add_message",
"(",
"request",
",",
"messages",
".",
"WARNING",
",",
"MESSAGES",
"[",
"'ANONYMOUS_EDIT'",
"... | The page to modify a user. | [
"The",
"page",
"to",
"modify",
"a",
"user",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L603-L690 |
knagra/farnsworth | base/views.py | custom_add_user_view | def custom_add_user_view(request):
''' The page to add a new user. '''
page_name = "Admin - Add User"
add_user_form = AddUserForm(request.POST or None, initial={
'status': UserProfile.RESIDENT,
})
if add_user_form.is_valid():
add_user_form.save()
message = MESSAGES['USER_... | python | def custom_add_user_view(request):
''' The page to add a new user. '''
page_name = "Admin - Add User"
add_user_form = AddUserForm(request.POST or None, initial={
'status': UserProfile.RESIDENT,
})
if add_user_form.is_valid():
add_user_form.save()
message = MESSAGES['USER_... | [
"def",
"custom_add_user_view",
"(",
"request",
")",
":",
"page_name",
"=",
"\"Admin - Add User\"",
"add_user_form",
"=",
"AddUserForm",
"(",
"request",
".",
"POST",
"or",
"None",
",",
"initial",
"=",
"{",
"'status'",
":",
"UserProfile",
".",
"RESIDENT",
",",
"... | The page to add a new user. | [
"The",
"page",
"to",
"add",
"a",
"new",
"user",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L693-L709 |
knagra/farnsworth | base/views.py | reset_pw_confirm_view | def reset_pw_confirm_view(request, uidb64=None, token=None):
""" View to confirm resetting password. """
return password_reset_confirm(request,
template_name="reset_confirmation.html",
uidb64=uidb64, token=token, post_reset_redirect=reverse('login')) | python | def reset_pw_confirm_view(request, uidb64=None, token=None):
""" View to confirm resetting password. """
return password_reset_confirm(request,
template_name="reset_confirmation.html",
uidb64=uidb64, token=token, post_reset_redirect=reverse('login')) | [
"def",
"reset_pw_confirm_view",
"(",
"request",
",",
"uidb64",
"=",
"None",
",",
"token",
"=",
"None",
")",
":",
"return",
"password_reset_confirm",
"(",
"request",
",",
"template_name",
"=",
"\"reset_confirmation.html\"",
",",
"uidb64",
"=",
"uidb64",
",",
"tok... | View to confirm resetting password. | [
"View",
"to",
"confirm",
"resetting",
"password",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L726-L730 |
knagra/farnsworth | base/views.py | recount_view | def recount_view(request):
"""
Recount number_of_messages for all threads and number_of_responses for all requests.
Also set the change_date for every thread to the post_date of the latest message
associated with that thread.
"""
requests_changed = 0
for req in Request.objects.all():
... | python | def recount_view(request):
"""
Recount number_of_messages for all threads and number_of_responses for all requests.
Also set the change_date for every thread to the post_date of the latest message
associated with that thread.
"""
requests_changed = 0
for req in Request.objects.all():
... | [
"def",
"recount_view",
"(",
"request",
")",
":",
"requests_changed",
"=",
"0",
"for",
"req",
"in",
"Request",
".",
"objects",
".",
"all",
"(",
")",
":",
"recount",
"=",
"Response",
".",
"objects",
".",
"filter",
"(",
"request",
"=",
"req",
")",
".",
... | Recount number_of_messages for all threads and number_of_responses for all requests.
Also set the change_date for every thread to the post_date of the latest message
associated with that thread. | [
"Recount",
"number_of_messages",
"for",
"all",
"threads",
"and",
"number_of_responses",
"for",
"all",
"requests",
".",
"Also",
"set",
"the",
"change_date",
"for",
"every",
"thread",
"to",
"the",
"post_date",
"of",
"the",
"latest",
"message",
"associated",
"with",
... | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L733-L766 |
knagra/farnsworth | base/views.py | archives_view | def archives_view(request):
""" View of the archives page. """
page_name = "Archives"
nodes, render_list = [], []
for add_context_str in settings.BASE_ARCHIVE_FUNCTIONS:
module, fun = add_context_str.rsplit(".", 1)
add_context_fun = getattr(import_module(module), fun)
# add_conte... | python | def archives_view(request):
""" View of the archives page. """
page_name = "Archives"
nodes, render_list = [], []
for add_context_str in settings.BASE_ARCHIVE_FUNCTIONS:
module, fun = add_context_str.rsplit(".", 1)
add_context_fun = getattr(import_module(module), fun)
# add_conte... | [
"def",
"archives_view",
"(",
"request",
")",
":",
"page_name",
"=",
"\"Archives\"",
"nodes",
",",
"render_list",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"add_context_str",
"in",
"settings",
".",
"BASE_ARCHIVE_FUNCTIONS",
":",
"module",
",",
"fun",
"=",
"add_con... | View of the archives page. | [
"View",
"of",
"the",
"archives",
"page",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L785-L801 |
knagra/farnsworth | base/views.py | get_updates_view | def get_updates_view(request):
"""Return a user's updates. AJAX."""
if not request.is_ajax():
raise Http404
if not request.user.is_authenticated():
return HttpResponse(json.dumps(dict()),
content_type="application/json")
try:
user_profile = UserProfi... | python | def get_updates_view(request):
"""Return a user's updates. AJAX."""
if not request.is_ajax():
raise Http404
if not request.user.is_authenticated():
return HttpResponse(json.dumps(dict()),
content_type="application/json")
try:
user_profile = UserProfi... | [
"def",
"get_updates_view",
"(",
"request",
")",
":",
"if",
"not",
"request",
".",
"is_ajax",
"(",
")",
":",
"raise",
"Http404",
"if",
"not",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"return",
"HttpResponse",
"(",
"json",
".",
"dump... | Return a user's updates. AJAX. | [
"Return",
"a",
"user",
"s",
"updates",
".",
"AJAX",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L803-L959 |
kderynski/blade-netconf-python-client | bnclient/conn.py | bnc_conn.connect | def connect(self):
if self._sStatus != 'opened':
print "Netconf Connection: Invalid Status, Could not connect to %s:%s" % (self._sHost, self._uPort)
sys.exit()
# establish ssh connection
if self._sType == 'ssh':
# setup transport connection base on socket
... | python | def connect(self):
if self._sStatus != 'opened':
print "Netconf Connection: Invalid Status, Could not connect to %s:%s" % (self._sHost, self._uPort)
sys.exit()
# establish ssh connection
if self._sType == 'ssh':
# setup transport connection base on socket
... | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_sStatus",
"!=",
"'opened'",
":",
"print",
"\"Netconf Connection: Invalid Status, Could not connect to %s:%s\"",
"%",
"(",
"self",
".",
"_sHost",
",",
"self",
".",
"_uPort",
")",
"sys",
".",
"exit",
... | end of function connect | [
"end",
"of",
"function",
"connect"
] | train | https://github.com/kderynski/blade-netconf-python-client/blob/87396921a1c75f1093adf4bb7b13428ee368b2b7/bnclient/conn.py#L91-L137 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/autoparser/generator.py | _index_idiom | def _index_idiom(el_name, index, alt=None):
"""
Generate string where `el_name` is indexed by `index` if there are enough
items or `alt` is returned.
Args:
el_name (str): Name of the `container` which is indexed.
index (int): Index of the item you want to obtain from container.
... | python | def _index_idiom(el_name, index, alt=None):
"""
Generate string where `el_name` is indexed by `index` if there are enough
items or `alt` is returned.
Args:
el_name (str): Name of the `container` which is indexed.
index (int): Index of the item you want to obtain from container.
... | [
"def",
"_index_idiom",
"(",
"el_name",
",",
"index",
",",
"alt",
"=",
"None",
")",
":",
"el_index",
"=",
"\"%s[%d]\"",
"%",
"(",
"el_name",
",",
"index",
")",
"if",
"index",
"==",
"0",
":",
"cond",
"=",
"\"%s\"",
"%",
"el_name",
"else",
":",
"cond",
... | Generate string where `el_name` is indexed by `index` if there are enough
items or `alt` is returned.
Args:
el_name (str): Name of the `container` which is indexed.
index (int): Index of the item you want to obtain from container.
alt (whatever, default None): Alternative value.
Re... | [
"Generate",
"string",
"where",
"el_name",
"is",
"indexed",
"by",
"index",
"if",
"there",
"are",
"enough",
"items",
"or",
"alt",
"is",
"returned",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/generator.py#L23-L59 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/autoparser/generator.py | _required_idiom | def _required_idiom(tag_name, index, notfoundmsg):
"""
Generate code, which make sure that `tag_name` has enoug items.
Args:
tag_name (str): Name of the container.
index (int): Index of the item you want to obtain from container.
notfoundmsg (str): Raise :class:`.UserWarning` with d... | python | def _required_idiom(tag_name, index, notfoundmsg):
"""
Generate code, which make sure that `tag_name` has enoug items.
Args:
tag_name (str): Name of the container.
index (int): Index of the item you want to obtain from container.
notfoundmsg (str): Raise :class:`.UserWarning` with d... | [
"def",
"_required_idiom",
"(",
"tag_name",
",",
"index",
",",
"notfoundmsg",
")",
":",
"cond",
"=",
"\"\"",
"if",
"index",
">",
"0",
":",
"cond",
"=",
"\" or len(el) - 1 < %d\"",
"%",
"index",
"tag_name",
"=",
"str",
"(",
"tag_name",
")",
"output",
"=",
... | Generate code, which make sure that `tag_name` has enoug items.
Args:
tag_name (str): Name of the container.
index (int): Index of the item you want to obtain from container.
notfoundmsg (str): Raise :class:`.UserWarning` with debug data and
following message.
... | [
"Generate",
"code",
"which",
"make",
"sure",
"that",
"tag_name",
"has",
"enoug",
"items",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/generator.py#L62-L89 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/autoparser/generator.py | _find_template | def _find_template(parameters, index, required=False, notfoundmsg=None):
"""
Generate ``.find()`` call for HTMLElement.
Args:
parameters (list): List of parameters for ``.find()``.
index (int): Index of the item you want to get from ``.find()`` call.
required (bool, default False): ... | python | def _find_template(parameters, index, required=False, notfoundmsg=None):
"""
Generate ``.find()`` call for HTMLElement.
Args:
parameters (list): List of parameters for ``.find()``.
index (int): Index of the item you want to get from ``.find()`` call.
required (bool, default False): ... | [
"def",
"_find_template",
"(",
"parameters",
",",
"index",
",",
"required",
"=",
"False",
",",
"notfoundmsg",
"=",
"None",
")",
":",
"output",
"=",
"IND",
"+",
"\"el = dom.find(%s)\\n\\n\"",
"%",
"repr",
"(",
"parameters",
")",
"[",
"1",
":",
"-",
"1",
"]... | Generate ``.find()`` call for HTMLElement.
Args:
parameters (list): List of parameters for ``.find()``.
index (int): Index of the item you want to get from ``.find()`` call.
required (bool, default False): Use :func:`_required_idiom` to returned
data.
notfoundmsg (s... | [
"Generate",
".",
"find",
"()",
"call",
"for",
"HTMLElement",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/generator.py#L93-L119 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/autoparser/generator.py | _wfind_template | def _wfind_template(use_dom, parameters, index, required=False,
notfoundmsg=None):
"""
Generate ``.wfind()`` call for HTMLElement.
Args:
use_dom (bool): Use ``dom`` as tag name. If ``False``, ``el`` is used.
parameters (list): List of paramete... | python | def _wfind_template(use_dom, parameters, index, required=False,
notfoundmsg=None):
"""
Generate ``.wfind()`` call for HTMLElement.
Args:
use_dom (bool): Use ``dom`` as tag name. If ``False``, ``el`` is used.
parameters (list): List of paramete... | [
"def",
"_wfind_template",
"(",
"use_dom",
",",
"parameters",
",",
"index",
",",
"required",
"=",
"False",
",",
"notfoundmsg",
"=",
"None",
")",
":",
"tag_name",
"=",
"\"dom\"",
"if",
"use_dom",
"else",
"\"el\"",
"output",
"=",
"IND",
"+",
"\"el = %s.wfind(%s... | Generate ``.wfind()`` call for HTMLElement.
Args:
use_dom (bool): Use ``dom`` as tag name. If ``False``, ``el`` is used.
parameters (list): List of parameters for ``.wfind()``.
index (int): Index of the item you want to get from ``.wfind()`` call.
required (bool, default False): Use... | [
"Generate",
".",
"wfind",
"()",
"call",
"for",
"HTMLElement",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/generator.py#L122-L154 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/autoparser/generator.py | _neigh_template | def _neigh_template(parameters, index, left=True, required=False,
notfoundmsg=None):
"""
Generate neighbour matching call for HTMLElement, which returns only
elements with required neighbours.
Args:
parameters (list): List of parameters for ``.m... | python | def _neigh_template(parameters, index, left=True, required=False,
notfoundmsg=None):
"""
Generate neighbour matching call for HTMLElement, which returns only
elements with required neighbours.
Args:
parameters (list): List of parameters for ``.m... | [
"def",
"_neigh_template",
"(",
"parameters",
",",
"index",
",",
"left",
"=",
"True",
",",
"required",
"=",
"False",
",",
"notfoundmsg",
"=",
"None",
")",
":",
"fn_string",
"=",
"\"has_neigh(%s, left=%s)\"",
"%",
"(",
"repr",
"(",
"parameters",
".",
"fn_param... | Generate neighbour matching call for HTMLElement, which returns only
elements with required neighbours.
Args:
parameters (list): List of parameters for ``.match()``.
index (int): Index of the item you want to get from ``.match()`` call.
left (bool, default True): Look for neigbour in th... | [
"Generate",
"neighbour",
"matching",
"call",
"for",
"HTMLElement",
"which",
"returns",
"only",
"elements",
"with",
"required",
"neighbours",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/generator.py#L188-L227 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/autoparser/generator.py | _generate_parser | def _generate_parser(name, path, required=False, notfoundmsg=None):
"""
Generate parser named `name` for given `path`.
Args:
name (str): Basename for the parsing function (see
:func:`_get_parser_name` for details).
path (obj): :class:`.PathCall` or :class:`.Chained` inst... | python | def _generate_parser(name, path, required=False, notfoundmsg=None):
"""
Generate parser named `name` for given `path`.
Args:
name (str): Basename for the parsing function (see
:func:`_get_parser_name` for details).
path (obj): :class:`.PathCall` or :class:`.Chained` inst... | [
"def",
"_generate_parser",
"(",
"name",
",",
"path",
",",
"required",
"=",
"False",
",",
"notfoundmsg",
"=",
"None",
")",
":",
"output",
"=",
"\"def %s(dom):\\n\"",
"%",
"_get_parser_name",
"(",
"name",
")",
"dom",
"=",
"True",
"# used specifically in _wfind_tem... | Generate parser named `name` for given `path`.
Args:
name (str): Basename for the parsing function (see
:func:`_get_parser_name` for details).
path (obj): :class:`.PathCall` or :class:`.Chained` instance.
required (bool, default False): Use :func:`_required_idiom` to ret... | [
"Generate",
"parser",
"named",
"name",
"for",
"given",
"path",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/generator.py#L245-L309 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/autoparser/generator.py | generate_parsers | def generate_parsers(config, paths):
"""
Generate parser for all `paths`.
Args:
config (dict): Original configuration dictionary used to get matches
for unittests. See
:mod:`~harvester.autoparser.conf_reader` for details.
paths (dict): Output fr... | python | def generate_parsers(config, paths):
"""
Generate parser for all `paths`.
Args:
config (dict): Original configuration dictionary used to get matches
for unittests. See
:mod:`~harvester.autoparser.conf_reader` for details.
paths (dict): Output fr... | [
"def",
"generate_parsers",
"(",
"config",
",",
"paths",
")",
":",
"output",
"=",
"\"\"\"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Interpreter version: python 2.7\n#\n# HTML parser generated by Autoparser\n# (https://github.com/edeposit/edeposit.amqp.harvester)\n#\nimport os\nimport o... | Generate parser for all `paths`.
Args:
config (dict): Original configuration dictionary used to get matches
for unittests. See
:mod:`~harvester.autoparser.conf_reader` for details.
paths (dict): Output from :func:`.select_best_paths`.
Returns:
... | [
"Generate",
"parser",
"for",
"all",
"paths",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/generator.py#L357-L410 |
nickfrostatx/walls | walls.py | load_config | def load_config(path):
"""Load the config value from various arguments."""
config = ConfigParser()
if len(config.read(path)) == 0:
stderr_and_exit("Couldn't load config {0}\n".format(path))
if not config.has_section('walls'):
stderr_and_exit('Config missing [walls] section.\n')
# P... | python | def load_config(path):
"""Load the config value from various arguments."""
config = ConfigParser()
if len(config.read(path)) == 0:
stderr_and_exit("Couldn't load config {0}\n".format(path))
if not config.has_section('walls'):
stderr_and_exit('Config missing [walls] section.\n')
# P... | [
"def",
"load_config",
"(",
"path",
")",
":",
"config",
"=",
"ConfigParser",
"(",
")",
"if",
"len",
"(",
"config",
".",
"read",
"(",
"path",
")",
")",
"==",
"0",
":",
"stderr_and_exit",
"(",
"\"Couldn't load config {0}\\n\"",
".",
"format",
"(",
"path",
"... | Load the config value from various arguments. | [
"Load",
"the",
"config",
"value",
"from",
"various",
"arguments",
"."
] | train | https://github.com/nickfrostatx/walls/blob/866f33335cf410565d6e51fdcd880770e6d089b0/walls.py#L34-L70 |
nickfrostatx/walls | walls.py | clear_dir | def clear_dir(path):
"""Empty out the image directory."""
for f in os.listdir(path):
f_path = os.path.join(path, f)
if os.path.isfile(f_path) or os.path.islink(f_path):
os.unlink(f_path) | python | def clear_dir(path):
"""Empty out the image directory."""
for f in os.listdir(path):
f_path = os.path.join(path, f)
if os.path.isfile(f_path) or os.path.islink(f_path):
os.unlink(f_path) | [
"def",
"clear_dir",
"(",
"path",
")",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"f_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"f",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"f_path",
")",
"... | Empty out the image directory. | [
"Empty",
"out",
"the",
"image",
"directory",
"."
] | train | https://github.com/nickfrostatx/walls/blob/866f33335cf410565d6e51fdcd880770e6d089b0/walls.py#L73-L78 |
nickfrostatx/walls | walls.py | smallest_url | def smallest_url(flickr, pid, min_width, min_height):
"""Return the url of the smallest photo above the dimensions.
If no such photo exists, return None.
"""
sizes = flickr.photos_getSizes(photo_id=pid, format='parsed-json')
smallest_url = None
smallest_area = None
for size in sizes['sizes'... | python | def smallest_url(flickr, pid, min_width, min_height):
"""Return the url of the smallest photo above the dimensions.
If no such photo exists, return None.
"""
sizes = flickr.photos_getSizes(photo_id=pid, format='parsed-json')
smallest_url = None
smallest_area = None
for size in sizes['sizes'... | [
"def",
"smallest_url",
"(",
"flickr",
",",
"pid",
",",
"min_width",
",",
"min_height",
")",
":",
"sizes",
"=",
"flickr",
".",
"photos_getSizes",
"(",
"photo_id",
"=",
"pid",
",",
"format",
"=",
"'parsed-json'",
")",
"smallest_url",
"=",
"None",
"smallest_are... | Return the url of the smallest photo above the dimensions.
If no such photo exists, return None. | [
"Return",
"the",
"url",
"of",
"the",
"smallest",
"photo",
"above",
"the",
"dimensions",
"."
] | train | https://github.com/nickfrostatx/walls/blob/866f33335cf410565d6e51fdcd880770e6d089b0/walls.py#L81-L97 |
nickfrostatx/walls | walls.py | download | def download(url, dest):
"""Download the image to disk."""
path = os.path.join(dest, url.split('/')[-1])
r = requests.get(url, stream=True)
r.raise_for_status()
with open(path, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
... | python | def download(url, dest):
"""Download the image to disk."""
path = os.path.join(dest, url.split('/')[-1])
r = requests.get(url, stream=True)
r.raise_for_status()
with open(path, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
... | [
"def",
"download",
"(",
"url",
",",
"dest",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dest",
",",
"url",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"stream",
... | Download the image to disk. | [
"Download",
"the",
"image",
"to",
"disk",
"."
] | train | https://github.com/nickfrostatx/walls/blob/866f33335cf410565d6e51fdcd880770e6d089b0/walls.py#L100-L109 |
nickfrostatx/walls | walls.py | run | def run(config, clear_opt=False):
"""Find an image and download it."""
flickr = flickrapi.FlickrAPI(config.get('walls', 'api_key'),
config.get('walls', 'api_secret'))
width = config.getint('walls', 'width')
height = config.getint('walls', 'height')
# Clear out the d... | python | def run(config, clear_opt=False):
"""Find an image and download it."""
flickr = flickrapi.FlickrAPI(config.get('walls', 'api_key'),
config.get('walls', 'api_secret'))
width = config.getint('walls', 'width')
height = config.getint('walls', 'height')
# Clear out the d... | [
"def",
"run",
"(",
"config",
",",
"clear_opt",
"=",
"False",
")",
":",
"flickr",
"=",
"flickrapi",
".",
"FlickrAPI",
"(",
"config",
".",
"get",
"(",
"'walls'",
",",
"'api_key'",
")",
",",
"config",
".",
"get",
"(",
"'walls'",
",",
"'api_secret'",
")",
... | Find an image and download it. | [
"Find",
"an",
"image",
"and",
"download",
"it",
"."
] | train | https://github.com/nickfrostatx/walls/blob/866f33335cf410565d6e51fdcd880770e6d089b0/walls.py#L112-L140 |
nickfrostatx/walls | walls.py | main | def main(args=sys.argv):
"""Parse the arguments, and pass the config object on to run."""
# Don't make changes to sys.argv
args = list(args)
# Remove arg[0]
args.pop(0)
# Pop off the options
clear_opt = False
if '-c' in args:
args.remove('-c')
clear_opt = True
elif ... | python | def main(args=sys.argv):
"""Parse the arguments, and pass the config object on to run."""
# Don't make changes to sys.argv
args = list(args)
# Remove arg[0]
args.pop(0)
# Pop off the options
clear_opt = False
if '-c' in args:
args.remove('-c')
clear_opt = True
elif ... | [
"def",
"main",
"(",
"args",
"=",
"sys",
".",
"argv",
")",
":",
"# Don't make changes to sys.argv",
"args",
"=",
"list",
"(",
"args",
")",
"# Remove arg[0]",
"args",
".",
"pop",
"(",
"0",
")",
"# Pop off the options",
"clear_opt",
"=",
"False",
"if",
"'-c'",
... | Parse the arguments, and pass the config object on to run. | [
"Parse",
"the",
"arguments",
"and",
"pass",
"the",
"config",
"object",
"on",
"to",
"run",
"."
] | train | https://github.com/nickfrostatx/walls/blob/866f33335cf410565d6e51fdcd880770e6d089b0/walls.py#L143-L169 |
kodexlab/reliure | reliure/offline.py | run | def run(pipeline, input_gen, options={}):
""" Run a pipeline over a input generator
>>> # if we have a simple component
>>> from reliure.pipeline import Composable
>>> @Composable
... def print_each(letters):
... for letter in letters:
... print(letter)
... yield let... | python | def run(pipeline, input_gen, options={}):
""" Run a pipeline over a input generator
>>> # if we have a simple component
>>> from reliure.pipeline import Composable
>>> @Composable
... def print_each(letters):
... for letter in letters:
... print(letter)
... yield let... | [
"def",
"run",
"(",
"pipeline",
",",
"input_gen",
",",
"options",
"=",
"{",
"}",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"\"reliure.run\"",
")",
"t0",
"=",
"time",
"(",
")",
"res",
"=",
"[",
"output",
"for",
"output",
"in",
"pipelin... | Run a pipeline over a input generator
>>> # if we have a simple component
>>> from reliure.pipeline import Composable
>>> @Composable
... def print_each(letters):
... for letter in letters:
... print(letter)
... yield letter
>>> # that we want to run over a given inp... | [
"Run",
"a",
"pipeline",
"over",
"a",
"input",
"generator"
] | train | https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/offline.py#L11-L45 |
kodexlab/reliure | reliure/offline.py | _reliure_worker | def _reliure_worker(wnum, Qin, Qout, pipeline, options={}):
""" a worker used by :func:`run_parallel`
"""
#pipeline = get_pipeline()
logger = logging.getLogger("reliure.run_parallel.worker#%s" % wnum)
logger.debug("worker created")
if options is None:
options = {}
while True:
... | python | def _reliure_worker(wnum, Qin, Qout, pipeline, options={}):
""" a worker used by :func:`run_parallel`
"""
#pipeline = get_pipeline()
logger = logging.getLogger("reliure.run_parallel.worker#%s" % wnum)
logger.debug("worker created")
if options is None:
options = {}
while True:
... | [
"def",
"_reliure_worker",
"(",
"wnum",
",",
"Qin",
",",
"Qout",
",",
"pipeline",
",",
"options",
"=",
"{",
"}",
")",
":",
"#pipeline = get_pipeline()",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"\"reliure.run_parallel.worker#%s\"",
"%",
"wnum",
")",
"lo... | a worker used by :func:`run_parallel` | [
"a",
"worker",
"used",
"by",
":",
"func",
":",
"run_parallel"
] | train | https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/offline.py#L47-L61 |
kodexlab/reliure | reliure/offline.py | run_parallel | def run_parallel(pipeline, input_gen, options={}, ncpu=4, chunksize=200):
""" Run a pipeline in parallel over a input generator cutting it into small
chunks.
>>> # if we have a simple component
>>> from reliure.pipeline import Composable
>>> # that we want to run over a given input:
>>> input =... | python | def run_parallel(pipeline, input_gen, options={}, ncpu=4, chunksize=200):
""" Run a pipeline in parallel over a input generator cutting it into small
chunks.
>>> # if we have a simple component
>>> from reliure.pipeline import Composable
>>> # that we want to run over a given input:
>>> input =... | [
"def",
"run_parallel",
"(",
"pipeline",
",",
"input_gen",
",",
"options",
"=",
"{",
"}",
",",
"ncpu",
"=",
"4",
",",
"chunksize",
"=",
"200",
")",
":",
"t0",
"=",
"time",
"(",
")",
"#FIXME: there is a know issue when pipeline results are \"big\" object, the merge ... | Run a pipeline in parallel over a input generator cutting it into small
chunks.
>>> # if we have a simple component
>>> from reliure.pipeline import Composable
>>> # that we want to run over a given input:
>>> input = "abcde"
>>> import string
>>> pipeline = Composable(lambda letters: (l.up... | [
"Run",
"a",
"pipeline",
"in",
"parallel",
"over",
"a",
"input",
"generator",
"cutting",
"it",
"into",
"small",
"chunks",
"."
] | train | https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/offline.py#L63-L116 |
kodexlab/reliure | reliure/offline.py | main | def main():
""" Small run usage exemple
"""
#TODO: need to be mv in .rst doc
from reliure.pipeline import Composable
@Composable
def doc_analyse(docs):
for doc in docs:
yield {
"title": doc,
"url": "http://lost.com/%s" % doc,
}
... | python | def main():
""" Small run usage exemple
"""
#TODO: need to be mv in .rst doc
from reliure.pipeline import Composable
@Composable
def doc_analyse(docs):
for doc in docs:
yield {
"title": doc,
"url": "http://lost.com/%s" % doc,
}
... | [
"def",
"main",
"(",
")",
":",
"#TODO: need to be mv in .rst doc",
"from",
"reliure",
".",
"pipeline",
"import",
"Composable",
"@",
"Composable",
"def",
"doc_analyse",
"(",
"docs",
")",
":",
"for",
"doc",
"in",
"docs",
":",
"yield",
"{",
"\"title\"",
":",
"do... | Small run usage exemple | [
"Small",
"run",
"usage",
"exemple"
] | train | https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/offline.py#L119-L142 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/autoparser/vectors.py | el_to_path_vector | def el_to_path_vector(el):
"""
Convert `el` to vector of foregoing elements.
Attr:
el (obj): Double-linked HTMLElement instance.
Returns:
list: HTMLElements which considered as path from root to `el`.
"""
path = []
while el.parent:
path.append(el)
el = el.pa... | python | def el_to_path_vector(el):
"""
Convert `el` to vector of foregoing elements.
Attr:
el (obj): Double-linked HTMLElement instance.
Returns:
list: HTMLElements which considered as path from root to `el`.
"""
path = []
while el.parent:
path.append(el)
el = el.pa... | [
"def",
"el_to_path_vector",
"(",
"el",
")",
":",
"path",
"=",
"[",
"]",
"while",
"el",
".",
"parent",
":",
"path",
".",
"append",
"(",
"el",
")",
"el",
"=",
"el",
".",
"parent",
"return",
"list",
"(",
"reversed",
"(",
"path",
"+",
"[",
"el",
"]",... | Convert `el` to vector of foregoing elements.
Attr:
el (obj): Double-linked HTMLElement instance.
Returns:
list: HTMLElements which considered as path from root to `el`. | [
"Convert",
"el",
"to",
"vector",
"of",
"foregoing",
"elements",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/vectors.py#L14-L29 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/autoparser/vectors.py | common_vector_root | def common_vector_root(vec1, vec2):
"""
Return common root of the two vectors.
Args:
vec1 (list/tuple): First vector.
vec2 (list/tuple): Second vector.
Usage example::
>>> common_vector_root([1, 2, 3, 4, 5], [1, 2, 8, 9, 0])
[1, 2]
Returns:
list: Common pa... | python | def common_vector_root(vec1, vec2):
"""
Return common root of the two vectors.
Args:
vec1 (list/tuple): First vector.
vec2 (list/tuple): Second vector.
Usage example::
>>> common_vector_root([1, 2, 3, 4, 5], [1, 2, 8, 9, 0])
[1, 2]
Returns:
list: Common pa... | [
"def",
"common_vector_root",
"(",
"vec1",
",",
"vec2",
")",
":",
"root",
"=",
"[",
"]",
"for",
"v1",
",",
"v2",
"in",
"zip",
"(",
"vec1",
",",
"vec2",
")",
":",
"if",
"v1",
"==",
"v2",
":",
"root",
".",
"append",
"(",
"v1",
")",
"else",
":",
... | Return common root of the two vectors.
Args:
vec1 (list/tuple): First vector.
vec2 (list/tuple): Second vector.
Usage example::
>>> common_vector_root([1, 2, 3, 4, 5], [1, 2, 8, 9, 0])
[1, 2]
Returns:
list: Common part of two vectors or blank list. | [
"Return",
"common",
"root",
"of",
"the",
"two",
"vectors",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/vectors.py#L32-L55 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/autoparser/vectors.py | find_common_root | def find_common_root(elements):
"""
Find root which is common for all `elements`.
Args:
elements (list): List of double-linked HTMLElement objects.
Returns:
list: Vector of HTMLElement containing path to common root.
"""
if not elements:
raise UserWarning("Can't find co... | python | def find_common_root(elements):
"""
Find root which is common for all `elements`.
Args:
elements (list): List of double-linked HTMLElement objects.
Returns:
list: Vector of HTMLElement containing path to common root.
"""
if not elements:
raise UserWarning("Can't find co... | [
"def",
"find_common_root",
"(",
"elements",
")",
":",
"if",
"not",
"elements",
":",
"raise",
"UserWarning",
"(",
"\"Can't find common root - no elements suplied.\"",
")",
"root_path",
"=",
"el_to_path_vector",
"(",
"elements",
".",
"pop",
"(",
")",
")",
"for",
"el... | Find root which is common for all `elements`.
Args:
elements (list): List of double-linked HTMLElement objects.
Returns:
list: Vector of HTMLElement containing path to common root. | [
"Find",
"root",
"which",
"is",
"common",
"for",
"all",
"elements",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/vectors.py#L58-L83 |
jmgilman/Neolib | neolib/daily/Daily.py | Daily.doDailies | def doDailies(usr, dailyList):
""" Does a list of dailies and yields each result
Takes a list of valid dailies, initiates each one, and then proceeds
to play each one and yield it's resulting message. Note that the names
given in the list must be the same as the daily's class fi... | python | def doDailies(usr, dailyList):
""" Does a list of dailies and yields each result
Takes a list of valid dailies, initiates each one, and then proceeds
to play each one and yield it's resulting message. Note that the names
given in the list must be the same as the daily's class fi... | [
"def",
"doDailies",
"(",
"usr",
",",
"dailyList",
")",
":",
"# Load all supported dailies",
"dailies",
"=",
"[",
"]",
"for",
"daily",
"in",
"Daily",
".",
"__subclasses__",
"(",
")",
":",
"dailies",
".",
"append",
"(",
"daily",
".",
"__name__",
")",
"# Veri... | Does a list of dailies and yields each result
Takes a list of valid dailies, initiates each one, and then proceeds
to play each one and yield it's resulting message. Note that the names
given in the list must be the same as the daily's class file.
Parameters
... | [
"Does",
"a",
"list",
"of",
"dailies",
"and",
"yields",
"each",
"result",
"Takes",
"a",
"list",
"of",
"valid",
"dailies",
"initiates",
"each",
"one",
"and",
"then",
"proceeds",
"to",
"play",
"each",
"one",
"and",
"yield",
"it",
"s",
"resulting",
"message",
... | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/daily/Daily.py#L58-L93 |
benfb/dars | dars/__init__.py | instantiateSong | def instantiateSong(fileName):
"""Create an AudioSegment with the data from the given file"""
ext = detectFormat(fileName)
if(ext == "mp3"):
return pd.AudioSegment.from_mp3(fileName)
elif(ext == "wav"):
return pd.AudioSegment.from_wav(fileName)
elif(ext == "ogg"):
return pd.A... | python | def instantiateSong(fileName):
"""Create an AudioSegment with the data from the given file"""
ext = detectFormat(fileName)
if(ext == "mp3"):
return pd.AudioSegment.from_mp3(fileName)
elif(ext == "wav"):
return pd.AudioSegment.from_wav(fileName)
elif(ext == "ogg"):
return pd.A... | [
"def",
"instantiateSong",
"(",
"fileName",
")",
":",
"ext",
"=",
"detectFormat",
"(",
"fileName",
")",
"if",
"(",
"ext",
"==",
"\"mp3\"",
")",
":",
"return",
"pd",
".",
"AudioSegment",
".",
"from_mp3",
"(",
"fileName",
")",
"elif",
"(",
"ext",
"==",
"\... | Create an AudioSegment with the data from the given file | [
"Create",
"an",
"AudioSegment",
"with",
"the",
"data",
"from",
"the",
"given",
"file"
] | train | https://github.com/benfb/dars/blob/66778de8314f7dcec50ef706abcea84a9b3d9c7e/dars/__init__.py#L11-L25 |
benfb/dars | dars/__init__.py | findGap | def findGap(song):
"""Return the position of silence in a song"""
try:
silence = pd.silence.detect_silence(song)
except IOError:
print("There isn't a song there!")
maxlength = 0
for pair in silence:
length = pair[1] - pair[0]
if length >= maxlength:
maxl... | python | def findGap(song):
"""Return the position of silence in a song"""
try:
silence = pd.silence.detect_silence(song)
except IOError:
print("There isn't a song there!")
maxlength = 0
for pair in silence:
length = pair[1] - pair[0]
if length >= maxlength:
maxl... | [
"def",
"findGap",
"(",
"song",
")",
":",
"try",
":",
"silence",
"=",
"pd",
".",
"silence",
".",
"detect_silence",
"(",
"song",
")",
"except",
"IOError",
":",
"print",
"(",
"\"There isn't a song there!\"",
")",
"maxlength",
"=",
"0",
"for",
"pair",
"in",
... | Return the position of silence in a song | [
"Return",
"the",
"position",
"of",
"silence",
"in",
"a",
"song"
] | train | https://github.com/benfb/dars/blob/66778de8314f7dcec50ef706abcea84a9b3d9c7e/dars/__init__.py#L27-L42 |
benfb/dars | dars/__init__.py | splitSong | def splitSong(songToSplit, start1, start2):
"""Split a song into two parts, one starting at start1, the other at start2"""
print "start1 " + str(start1)
print "start2 " + str(start2)
# songs = [songToSplit[:start1+2000], songToSplit[start2-2000:]]
songs = [songToSplit[:start1], songToSplit[start2:]]... | python | def splitSong(songToSplit, start1, start2):
"""Split a song into two parts, one starting at start1, the other at start2"""
print "start1 " + str(start1)
print "start2 " + str(start2)
# songs = [songToSplit[:start1+2000], songToSplit[start2-2000:]]
songs = [songToSplit[:start1], songToSplit[start2:]]... | [
"def",
"splitSong",
"(",
"songToSplit",
",",
"start1",
",",
"start2",
")",
":",
"print",
"\"start1 \"",
"+",
"str",
"(",
"start1",
")",
"print",
"\"start2 \"",
"+",
"str",
"(",
"start2",
")",
"# songs = [songToSplit[:start1+2000], songToSplit[start2-2000:]]",
"songs... | Split a song into two parts, one starting at start1, the other at start2 | [
"Split",
"a",
"song",
"into",
"two",
"parts",
"one",
"starting",
"at",
"start1",
"the",
"other",
"at",
"start2"
] | train | https://github.com/benfb/dars/blob/66778de8314f7dcec50ef706abcea84a9b3d9c7e/dars/__init__.py#L44-L50 |
benfb/dars | dars/__init__.py | saveFiles | def saveFiles(fileName1, fileName2, songs):
"""Save songs to files"""
songs[0].export(fileName1, format=detectFormat(fileName1))
songs[1].export(fileName2, format=detectFormat(fileName2)) | python | def saveFiles(fileName1, fileName2, songs):
"""Save songs to files"""
songs[0].export(fileName1, format=detectFormat(fileName1))
songs[1].export(fileName2, format=detectFormat(fileName2)) | [
"def",
"saveFiles",
"(",
"fileName1",
",",
"fileName2",
",",
"songs",
")",
":",
"songs",
"[",
"0",
"]",
".",
"export",
"(",
"fileName1",
",",
"format",
"=",
"detectFormat",
"(",
"fileName1",
")",
")",
"songs",
"[",
"1",
"]",
".",
"export",
"(",
"file... | Save songs to files | [
"Save",
"songs",
"to",
"files"
] | train | https://github.com/benfb/dars/blob/66778de8314f7dcec50ef706abcea84a9b3d9c7e/dars/__init__.py#L52-L55 |
benfb/dars | dars/__init__.py | saveFiles | def saveFiles(fileName1, fileName2, songs, artist, album, trackNum):
"""Save songs to files"""
songs[0].export(fileName1, format=detectFormat(fileName1), tags={'artist': artist, 'album': album, 'track': trackNum})
songs[1].export(fileName2, format=detectFormat(fileName2), tags={'artist': artist, 'album': al... | python | def saveFiles(fileName1, fileName2, songs, artist, album, trackNum):
"""Save songs to files"""
songs[0].export(fileName1, format=detectFormat(fileName1), tags={'artist': artist, 'album': album, 'track': trackNum})
songs[1].export(fileName2, format=detectFormat(fileName2), tags={'artist': artist, 'album': al... | [
"def",
"saveFiles",
"(",
"fileName1",
",",
"fileName2",
",",
"songs",
",",
"artist",
",",
"album",
",",
"trackNum",
")",
":",
"songs",
"[",
"0",
"]",
".",
"export",
"(",
"fileName1",
",",
"format",
"=",
"detectFormat",
"(",
"fileName1",
")",
",",
"tags... | Save songs to files | [
"Save",
"songs",
"to",
"files"
] | train | https://github.com/benfb/dars/blob/66778de8314f7dcec50ef706abcea84a9b3d9c7e/dars/__init__.py#L57-L60 |
benfb/dars | dars/__init__.py | trackSeek | def trackSeek(path, artist, album, track, trackNum, fmt):
"""Actually runs the program"""
hiddenName = "(Hidden Track).{}".format(fmt)
trackName = track + ".{}".format(fmt)
songIn = instantiateSong(path)
times = findGap(songIn)
saveFiles(trackName, hiddenName, splitSong(songIn, times[0], times[1... | python | def trackSeek(path, artist, album, track, trackNum, fmt):
"""Actually runs the program"""
hiddenName = "(Hidden Track).{}".format(fmt)
trackName = track + ".{}".format(fmt)
songIn = instantiateSong(path)
times = findGap(songIn)
saveFiles(trackName, hiddenName, splitSong(songIn, times[0], times[1... | [
"def",
"trackSeek",
"(",
"path",
",",
"artist",
",",
"album",
",",
"track",
",",
"trackNum",
",",
"fmt",
")",
":",
"hiddenName",
"=",
"\"(Hidden Track).{}\"",
".",
"format",
"(",
"fmt",
")",
"trackName",
"=",
"track",
"+",
"\".{}\"",
".",
"format",
"(",
... | Actually runs the program | [
"Actually",
"runs",
"the",
"program"
] | train | https://github.com/benfb/dars/blob/66778de8314f7dcec50ef706abcea84a9b3d9c7e/dars/__init__.py#L62-L70 |
benfb/dars | dars/__init__.py | parseArgs | def parseArgs():
"""Parses arguments passed in via the command line"""
parser = argparse.ArgumentParser()
parser.add_argument("name", help="the file you want to split")
parser.add_argument("out1", help="the name of the first file you want to output")
parser.add_argument("out2", help="the name of the... | python | def parseArgs():
"""Parses arguments passed in via the command line"""
parser = argparse.ArgumentParser()
parser.add_argument("name", help="the file you want to split")
parser.add_argument("out1", help="the name of the first file you want to output")
parser.add_argument("out2", help="the name of the... | [
"def",
"parseArgs",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"name\"",
",",
"help",
"=",
"\"the file you want to split\"",
")",
"parser",
".",
"add_argument",
"(",
"\"out1\"",
",",
"help",... | Parses arguments passed in via the command line | [
"Parses",
"arguments",
"passed",
"in",
"via",
"the",
"command",
"line"
] | train | https://github.com/benfb/dars/blob/66778de8314f7dcec50ef706abcea84a9b3d9c7e/dars/__init__.py#L72-L78 |
openpermissions/chub | chub/api.py | Resource._sub_resource | def _sub_resource(self, path):
"""
get or create sub resource
"""
if path not in self.resource_map:
self.resource_map[path] = Resource(
path, self.fetch, self.resource_map,
default_headers=self.default_headers)
return self.resource_map[... | python | def _sub_resource(self, path):
"""
get or create sub resource
"""
if path not in self.resource_map:
self.resource_map[path] = Resource(
path, self.fetch, self.resource_map,
default_headers=self.default_headers)
return self.resource_map[... | [
"def",
"_sub_resource",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
"not",
"in",
"self",
".",
"resource_map",
":",
"self",
".",
"resource_map",
"[",
"path",
"]",
"=",
"Resource",
"(",
"path",
",",
"self",
".",
"fetch",
",",
"self",
".",
"resour... | get or create sub resource | [
"get",
"or",
"create",
"sub",
"resource"
] | train | https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/api.py#L61-L69 |
openpermissions/chub | chub/api.py | Resource.prepare_request | def prepare_request(self, *args, **kw):
"""
creates a full featured HTTPRequest objects
"""
self.http_request = self.request_class(self.path, *args, **kw) | python | def prepare_request(self, *args, **kw):
"""
creates a full featured HTTPRequest objects
"""
self.http_request = self.request_class(self.path, *args, **kw) | [
"def",
"prepare_request",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"http_request",
"=",
"self",
".",
"request_class",
"(",
"self",
".",
"path",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] | creates a full featured HTTPRequest objects | [
"creates",
"a",
"full",
"featured",
"HTTPRequest",
"objects"
] | train | https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/api.py#L75-L79 |
openpermissions/chub | chub/api.py | API.token | def token(self):
"""
get the token
"""
header = self.default_headers.get('Authorization', '')
prefex = 'Bearer '
if header.startswith(prefex):
token = header[len(prefex):]
else:
token = header
return token | python | def token(self):
"""
get the token
"""
header = self.default_headers.get('Authorization', '')
prefex = 'Bearer '
if header.startswith(prefex):
token = header[len(prefex):]
else:
token = header
return token | [
"def",
"token",
"(",
"self",
")",
":",
"header",
"=",
"self",
".",
"default_headers",
".",
"get",
"(",
"'Authorization'",
",",
"''",
")",
"prefex",
"=",
"'Bearer '",
"if",
"header",
".",
"startswith",
"(",
"prefex",
")",
":",
"token",
"=",
"header",
"[... | get the token | [
"get",
"the",
"token"
] | train | https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/api.py#L99-L109 |
openpermissions/chub | chub/api.py | API._request | def _request(self):
"""
retrieve the caller frame, extract the parameters from
the caller function, find the matching function,
and fire the request
"""
caller_frame = inspect.getouterframes(inspect.currentframe())[1]
args, _, _, values = inspect.getargvalues(call... | python | def _request(self):
"""
retrieve the caller frame, extract the parameters from
the caller function, find the matching function,
and fire the request
"""
caller_frame = inspect.getouterframes(inspect.currentframe())[1]
args, _, _, values = inspect.getargvalues(call... | [
"def",
"_request",
"(",
"self",
")",
":",
"caller_frame",
"=",
"inspect",
".",
"getouterframes",
"(",
"inspect",
".",
"currentframe",
"(",
")",
")",
"[",
"1",
"]",
"args",
",",
"_",
",",
"_",
",",
"values",
"=",
"inspect",
".",
"getargvalues",
"(",
"... | retrieve the caller frame, extract the parameters from
the caller function, find the matching function,
and fire the request | [
"retrieve",
"the",
"caller",
"frame",
"extract",
"the",
"parameters",
"from",
"the",
"caller",
"function",
"find",
"the",
"matching",
"function",
"and",
"fire",
"the",
"request"
] | train | https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/api.py#L118-L131 |
openpermissions/chub | chub/api.py | Accounts.login | def login(self, email, password):
"""
login using email and password
:param email: email address
:param password: password
"""
rsp = self._request()
self.default_headers['Authorization'] = rsp.data['token']
return rsp | python | def login(self, email, password):
"""
login using email and password
:param email: email address
:param password: password
"""
rsp = self._request()
self.default_headers['Authorization'] = rsp.data['token']
return rsp | [
"def",
"login",
"(",
"self",
",",
"email",
",",
"password",
")",
":",
"rsp",
"=",
"self",
".",
"_request",
"(",
")",
"self",
".",
"default_headers",
"[",
"'Authorization'",
"]",
"=",
"rsp",
".",
"data",
"[",
"'token'",
"]",
"return",
"rsp"
] | login using email and password
:param email: email address
:param password: password | [
"login",
"using",
"email",
"and",
"password",
":",
"param",
"email",
":",
"email",
"address",
":",
"param",
"password",
":",
"password"
] | train | https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/api.py#L150-L158 |
djangomini/djangomini | djangomini/tools.py | listdir | def listdir(dir_name, get_dirs=None, get_files=None, hide_ignored=False):
"""
Return list of all dirs and files inside given dir.
Also can filter contents to return only dirs or files.
Args:
- dir_name: Which directory we need to scan (relative)
- get_dirs: Return dirs list
- get_files: Re... | python | def listdir(dir_name, get_dirs=None, get_files=None, hide_ignored=False):
"""
Return list of all dirs and files inside given dir.
Also can filter contents to return only dirs or files.
Args:
- dir_name: Which directory we need to scan (relative)
- get_dirs: Return dirs list
- get_files: Re... | [
"def",
"listdir",
"(",
"dir_name",
",",
"get_dirs",
"=",
"None",
",",
"get_files",
"=",
"None",
",",
"hide_ignored",
"=",
"False",
")",
":",
"if",
"get_dirs",
"is",
"None",
"and",
"get_files",
"is",
"None",
":",
"get_dirs",
"=",
"True",
"get_files",
"=",... | Return list of all dirs and files inside given dir.
Also can filter contents to return only dirs or files.
Args:
- dir_name: Which directory we need to scan (relative)
- get_dirs: Return dirs list
- get_files: Return files list
- hide_ignored: Exclude files and dirs with initial underscore | [
"Return",
"list",
"of",
"all",
"dirs",
"and",
"files",
"inside",
"given",
"dir",
"."
] | train | https://github.com/djangomini/djangomini/blob/cfbe2d59acf0e89e5fd442df8952f9a117a63875/djangomini/tools.py#L14-L42 |
Ffisegydd/whatis | whatis/_util.py | get_types | def get_types(obj, **kwargs):
"""Get the types of an iterable."""
max_iterable_length = kwargs.get('max_iterable_length', 100000)
it, = itertools.tee(obj, 1)
s = set()
too_big = False
for i, v in enumerate(it):
if i <= max_iterable_length:
s.add(type(v))
else:
... | python | def get_types(obj, **kwargs):
"""Get the types of an iterable."""
max_iterable_length = kwargs.get('max_iterable_length', 100000)
it, = itertools.tee(obj, 1)
s = set()
too_big = False
for i, v in enumerate(it):
if i <= max_iterable_length:
s.add(type(v))
else:
... | [
"def",
"get_types",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"max_iterable_length",
"=",
"kwargs",
".",
"get",
"(",
"'max_iterable_length'",
",",
"100000",
")",
"it",
",",
"=",
"itertools",
".",
"tee",
"(",
"obj",
",",
"1",
")",
"s",
"=",
"set"... | Get the types of an iterable. | [
"Get",
"the",
"types",
"of",
"an",
"iterable",
"."
] | train | https://github.com/Ffisegydd/whatis/blob/eef780ced61aae6d001aeeef7574e5e27e613583/whatis/_util.py#L28-L44 |
Ffisegydd/whatis | whatis/_util.py | extract_type | def extract_type(s):
"""Extract the type string from str(type(obj)) to remove the "<class..." bit."""
r = re.compile(r"<class '(.*)'>", re.MULTILINE | re.IGNORECASE)
try:
m = r.match(str(s)).group(1)
except (IndexError, AttributeError) as e:
m = None
return m | python | def extract_type(s):
"""Extract the type string from str(type(obj)) to remove the "<class..." bit."""
r = re.compile(r"<class '(.*)'>", re.MULTILINE | re.IGNORECASE)
try:
m = r.match(str(s)).group(1)
except (IndexError, AttributeError) as e:
m = None
return m | [
"def",
"extract_type",
"(",
"s",
")",
":",
"r",
"=",
"re",
".",
"compile",
"(",
"r\"<class '(.*)'>\"",
",",
"re",
".",
"MULTILINE",
"|",
"re",
".",
"IGNORECASE",
")",
"try",
":",
"m",
"=",
"r",
".",
"match",
"(",
"str",
"(",
"s",
")",
")",
".",
... | Extract the type string from str(type(obj)) to remove the "<class..." bit. | [
"Extract",
"the",
"type",
"string",
"from",
"str",
"(",
"type",
"(",
"obj",
"))",
"to",
"remove",
"the",
"<class",
"...",
"bit",
"."
] | train | https://github.com/Ffisegydd/whatis/blob/eef780ced61aae6d001aeeef7574e5e27e613583/whatis/_util.py#L52-L60 |
MacHu-GWU/windtalker-project | windtalker/cipher.py | BaseCipher.encrypt_binary | def encrypt_binary(self, binary, *args, **kwargs):
"""
input: bytes, output: bytes
"""
return self.encrypt(binary, *args, **kwargs) | python | def encrypt_binary(self, binary, *args, **kwargs):
"""
input: bytes, output: bytes
"""
return self.encrypt(binary, *args, **kwargs) | [
"def",
"encrypt_binary",
"(",
"self",
",",
"binary",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"encrypt",
"(",
"binary",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | input: bytes, output: bytes | [
"input",
":",
"bytes",
"output",
":",
"bytes"
] | train | https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/cipher.py#L55-L59 |
MacHu-GWU/windtalker-project | windtalker/cipher.py | BaseCipher.decrypt_binary | def decrypt_binary(self, binary, *args, **kwargs):
"""
input: bytes, output: bytes
"""
return self.decrypt(binary, *args, **kwargs) | python | def decrypt_binary(self, binary, *args, **kwargs):
"""
input: bytes, output: bytes
"""
return self.decrypt(binary, *args, **kwargs) | [
"def",
"decrypt_binary",
"(",
"self",
",",
"binary",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"decrypt",
"(",
"binary",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | input: bytes, output: bytes | [
"input",
":",
"bytes",
"output",
":",
"bytes"
] | train | https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/cipher.py#L61-L65 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.