repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
davidfokkema/artist
artist/plot.py
PolarPlot.histogram
def histogram(self, counts, bin_edges, linestyle='solid'): """Plot a polar histogram. The user needs to supply the histogram. This method only plots the results. You can use NumPy's histogram function. :param counts: array containing the count values. :param bin_edges: array ...
python
def histogram(self, counts, bin_edges, linestyle='solid'): """Plot a polar histogram. The user needs to supply the histogram. This method only plots the results. You can use NumPy's histogram function. :param counts: array containing the count values. :param bin_edges: array ...
[ "def", "histogram", "(", "self", ",", "counts", ",", "bin_edges", ",", "linestyle", "=", "'solid'", ")", ":", "if", "len", "(", "bin_edges", ")", "-", "1", "!=", "len", "(", "counts", ")", ":", "raise", "RuntimeError", "(", "'The length of bin_edges should...
Plot a polar histogram. The user needs to supply the histogram. This method only plots the results. You can use NumPy's histogram function. :param counts: array containing the count values. :param bin_edges: array containing the bin edges in degrees (or radi...
[ "Plot", "a", "polar", "histogram", "." ]
26ae7987522622710f2910980770c50012fda47d
https://github.com/davidfokkema/artist/blob/26ae7987522622710f2910980770c50012fda47d/artist/plot.py#L1220-L1269
train
This method plots a polar histogram.
praekeltfoundation/seed-message-sender
message_sender/factory.py
GenericHttpApiSender._get_filename
def _get_filename(self, path): """ This function gets the base filename from the path, if a language code is present the filename will start from there. """ match = re.search("[a-z]{2,3}_[A-Z]{2}", path) if match: start = match.start(0) filename =...
python
def _get_filename(self, path): """ This function gets the base filename from the path, if a language code is present the filename will start from there. """ match = re.search("[a-z]{2,3}_[A-Z]{2}", path) if match: start = match.start(0) filename =...
[ "def", "_get_filename", "(", "self", ",", "path", ")", ":", "match", "=", "re", ".", "search", "(", "\"[a-z]{2,3}_[A-Z]{2}\"", ",", "path", ")", "if", "match", ":", "start", "=", "match", ".", "start", "(", "0", ")", "filename", "=", "path", "[", "st...
This function gets the base filename from the path, if a language code is present the filename will start from there.
[ "This", "function", "gets", "the", "base", "filename", "from", "the", "path", "if", "a", "language", "code", "is", "present", "the", "filename", "will", "start", "from", "there", "." ]
257b01635171b9dbe1f5f13baa810c971bb2620e
https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/factory.py#L72-L85
train
This function gets the base filename from the path.
praekeltfoundation/seed-message-sender
message_sender/factory.py
GenericHttpApiSender._override_payload
def _override_payload(self, payload): """ This function transforms the payload into a new format using the self.override_payload property. """ if self.override_payload: old_payload = payload def get_value(data, key): try: ...
python
def _override_payload(self, payload): """ This function transforms the payload into a new format using the self.override_payload property. """ if self.override_payload: old_payload = payload def get_value(data, key): try: ...
[ "def", "_override_payload", "(", "self", ",", "payload", ")", ":", "if", "self", ".", "override_payload", ":", "old_payload", "=", "payload", "def", "get_value", "(", "data", ",", "key", ")", ":", "try", ":", "parent_key", ",", "nested_key", "=", "key", ...
This function transforms the payload into a new format using the self.override_payload property.
[ "This", "function", "transforms", "the", "payload", "into", "a", "new", "format", "using", "the", "self", ".", "override_payload", "property", "." ]
257b01635171b9dbe1f5f13baa810c971bb2620e
https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/factory.py#L123-L148
train
This function transforms the payload into a new format using the self. override_payload property.
praekeltfoundation/seed-message-sender
message_sender/factory.py
WhatsAppApiSender.fire_failed_contact_lookup
def fire_failed_contact_lookup(self, msisdn): """ Fires a webhook in the event of a failed WhatsApp contact lookup. """ payload = {"address": msisdn} # We cannot user the raw_hook_event here, because we don't have a user, so we # manually filter and send the hooks for all...
python
def fire_failed_contact_lookup(self, msisdn): """ Fires a webhook in the event of a failed WhatsApp contact lookup. """ payload = {"address": msisdn} # We cannot user the raw_hook_event here, because we don't have a user, so we # manually filter and send the hooks for all...
[ "def", "fire_failed_contact_lookup", "(", "self", ",", "msisdn", ")", ":", "payload", "=", "{", "\"address\"", ":", "msisdn", "}", "# We cannot user the raw_hook_event here, because we don't have a user, so we", "# manually filter and send the hooks for all users", "hooks", "=", ...
Fires a webhook in the event of a failed WhatsApp contact lookup.
[ "Fires", "a", "webhook", "in", "the", "event", "of", "a", "failed", "WhatsApp", "contact", "lookup", "." ]
257b01635171b9dbe1f5f13baa810c971bb2620e
https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/factory.py#L321-L332
train
Fires a webhook in the event of a failed WhatsApp contact lookup.
praekeltfoundation/seed-message-sender
message_sender/factory.py
WhatsAppApiSender.get_contact
def get_contact(self, msisdn): """ Returns the WhatsApp ID for the given MSISDN """ response = self.session.post( urllib_parse.urljoin(self.api_url, "/v1/contacts"), json={"blocking": "wait", "contacts": [msisdn]}, ) response.raise_for_status() ...
python
def get_contact(self, msisdn): """ Returns the WhatsApp ID for the given MSISDN """ response = self.session.post( urllib_parse.urljoin(self.api_url, "/v1/contacts"), json={"blocking": "wait", "contacts": [msisdn]}, ) response.raise_for_status() ...
[ "def", "get_contact", "(", "self", ",", "msisdn", ")", ":", "response", "=", "self", ".", "session", ".", "post", "(", "urllib_parse", ".", "urljoin", "(", "self", ".", "api_url", ",", "\"/v1/contacts\"", ")", ",", "json", "=", "{", "\"blocking\"", ":", ...
Returns the WhatsApp ID for the given MSISDN
[ "Returns", "the", "WhatsApp", "ID", "for", "the", "given", "MSISDN" ]
257b01635171b9dbe1f5f13baa810c971bb2620e
https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/factory.py#L334-L346
train
Returns the WhatsApp ID for the given MSISDN.
praekeltfoundation/seed-message-sender
message_sender/factory.py
WhatsAppApiSender.send_custom_hsm
def send_custom_hsm(self, whatsapp_id, template_name, language, variables): """ Sends an HSM with more customizable fields than the send_hsm function """ data = { "to": whatsapp_id, "type": "hsm", "hsm": { "namespace": self.hsm_namespac...
python
def send_custom_hsm(self, whatsapp_id, template_name, language, variables): """ Sends an HSM with more customizable fields than the send_hsm function """ data = { "to": whatsapp_id, "type": "hsm", "hsm": { "namespace": self.hsm_namespac...
[ "def", "send_custom_hsm", "(", "self", ",", "whatsapp_id", ",", "template_name", ",", "language", ",", "variables", ")", ":", "data", "=", "{", "\"to\"", ":", "whatsapp_id", ",", "\"type\"", ":", "\"hsm\"", ",", "\"hsm\"", ":", "{", "\"namespace\"", ":", "...
Sends an HSM with more customizable fields than the send_hsm function
[ "Sends", "an", "HSM", "with", "more", "customizable", "fields", "than", "the", "send_hsm", "function" ]
257b01635171b9dbe1f5f13baa810c971bb2620e
https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/factory.py#L366-L386
train
Send a custom HSM with more customizable fields than the send_hsm function.
iLampard/x-utils
xutils/bar_builder/polling_thread.py
BarThread.load_data
def load_data(self): """ Overwrite this for new source data structures """ try: df = self.live_quote_arg_func(self.tickers) for index, ticker in enumerate(self.tickers): ticker_info = df.loc[index] self.ticker_dict[ticker].append(ti...
python
def load_data(self): """ Overwrite this for new source data structures """ try: df = self.live_quote_arg_func(self.tickers) for index, ticker in enumerate(self.tickers): ticker_info = df.loc[index] self.ticker_dict[ticker].append(ti...
[ "def", "load_data", "(", "self", ")", ":", "try", ":", "df", "=", "self", ".", "live_quote_arg_func", "(", "self", ".", "tickers", ")", "for", "index", ",", "ticker", "in", "enumerate", "(", "self", ".", "tickers", ")", ":", "ticker_info", "=", "df", ...
Overwrite this for new source data structures
[ "Overwrite", "this", "for", "new", "source", "data", "structures" ]
291d92832ee0e0c89bc22e10ecf2f44445e0d300
https://github.com/iLampard/x-utils/blob/291d92832ee0e0c89bc22e10ecf2f44445e0d300/xutils/bar_builder/polling_thread.py#L160-L173
train
Load data from live quote
Dav0815/TransportNSW
TransportNSW/TransportNSW.py
TransportNSW.get_departures
def get_departures(self, stop_id, route, destination, api_key): """Get the latest data from Transport NSW.""" self.stop_id = stop_id self.route = route self.destination = destination self.api_key = api_key # Build the URL including the STOP_ID and the API key url...
python
def get_departures(self, stop_id, route, destination, api_key): """Get the latest data from Transport NSW.""" self.stop_id = stop_id self.route = route self.destination = destination self.api_key = api_key # Build the URL including the STOP_ID and the API key url...
[ "def", "get_departures", "(", "self", ",", "stop_id", ",", "route", ",", "destination", ",", "api_key", ")", ":", "self", ".", "stop_id", "=", "stop_id", "self", ".", "route", "=", "route", "self", ".", "destination", "=", "destination", "self", ".", "ap...
Get the latest data from Transport NSW.
[ "Get", "the", "latest", "data", "from", "Transport", "NSW", "." ]
828aae948fd26bb2ce89637ed639129b4cfdf62a
https://github.com/Dav0815/TransportNSW/blob/828aae948fd26bb2ce89637ed639129b4cfdf62a/TransportNSW/TransportNSW.py#L36-L115
train
Get the latest data from Transport NSW.
Dav0815/TransportNSW
TransportNSW/TransportNSW.py
TransportNSW.parseEvent
def parseEvent(self, result, i): """Parse the current event and extract data.""" fmt = '%Y-%m-%dT%H:%M:%SZ' due = 0 delay = 0 real_time = 'n' number = result['stopEvents'][i]['transportation']['number'] planned = datetime.strptime(result['stopEvents'][i] ...
python
def parseEvent(self, result, i): """Parse the current event and extract data.""" fmt = '%Y-%m-%dT%H:%M:%SZ' due = 0 delay = 0 real_time = 'n' number = result['stopEvents'][i]['transportation']['number'] planned = datetime.strptime(result['stopEvents'][i] ...
[ "def", "parseEvent", "(", "self", ",", "result", ",", "i", ")", ":", "fmt", "=", "'%Y-%m-%dT%H:%M:%SZ'", "due", "=", "0", "delay", "=", "0", "real_time", "=", "'n'", "number", "=", "result", "[", "'stopEvents'", "]", "[", "i", "]", "[", "'transportatio...
Parse the current event and extract data.
[ "Parse", "the", "current", "event", "and", "extract", "data", "." ]
828aae948fd26bb2ce89637ed639129b4cfdf62a
https://github.com/Dav0815/TransportNSW/blob/828aae948fd26bb2ce89637ed639129b4cfdf62a/TransportNSW/TransportNSW.py#L117-L148
train
Parse the current event and extract data.
Dav0815/TransportNSW
TransportNSW/TransportNSW.py
TransportNSW.get_due
def get_due(self, estimated): """Min till next leave event.""" due = 0 due = round((estimated - datetime.utcnow()).seconds / 60) return due
python
def get_due(self, estimated): """Min till next leave event.""" due = 0 due = round((estimated - datetime.utcnow()).seconds / 60) return due
[ "def", "get_due", "(", "self", ",", "estimated", ")", ":", "due", "=", "0", "due", "=", "round", "(", "(", "estimated", "-", "datetime", ".", "utcnow", "(", ")", ")", ".", "seconds", "/", "60", ")", "return", "due" ]
Min till next leave event.
[ "Min", "till", "next", "leave", "event", "." ]
828aae948fd26bb2ce89637ed639129b4cfdf62a
https://github.com/Dav0815/TransportNSW/blob/828aae948fd26bb2ce89637ed639129b4cfdf62a/TransportNSW/TransportNSW.py#L150-L154
train
Min till next leave event.
Dav0815/TransportNSW
TransportNSW/TransportNSW.py
TransportNSW.get_delay
def get_delay(self, planned, estimated): """Min of delay on planned departure.""" delay = 0 # default is no delay if estimated >= planned: # there is a delay delay = round((estimated - planned).seconds / 60) else: # leaving earlier ...
python
def get_delay(self, planned, estimated): """Min of delay on planned departure.""" delay = 0 # default is no delay if estimated >= planned: # there is a delay delay = round((estimated - planned).seconds / 60) else: # leaving earlier ...
[ "def", "get_delay", "(", "self", ",", "planned", ",", "estimated", ")", ":", "delay", "=", "0", "# default is no delay", "if", "estimated", ">=", "planned", ":", "# there is a delay", "delay", "=", "round", "(", "(", "estimated", "-", "planned", ")", ".", ...
Min of delay on planned departure.
[ "Min", "of", "delay", "on", "planned", "departure", "." ]
828aae948fd26bb2ce89637ed639129b4cfdf62a
https://github.com/Dav0815/TransportNSW/blob/828aae948fd26bb2ce89637ed639129b4cfdf62a/TransportNSW/TransportNSW.py#L156-L163
train
Get the minimum delay on planned departure.
kitscribe/pycolorize
pycolorize.py
colorize
def colorize(text, color=None, **kwargs): """ Colorize the text kwargs arguments: style=, bg= """ style = None bg = None # ================ # # Keyword checking # # ================ # if 'style' in kwargs: if kwargs['style'] not in STYLE: raise WrongStyle(...
python
def colorize(text, color=None, **kwargs): """ Colorize the text kwargs arguments: style=, bg= """ style = None bg = None # ================ # # Keyword checking # # ================ # if 'style' in kwargs: if kwargs['style'] not in STYLE: raise WrongStyle(...
[ "def", "colorize", "(", "text", ",", "color", "=", "None", ",", "*", "*", "kwargs", ")", ":", "style", "=", "None", "bg", "=", "None", "# ================ #", "# Keyword checking #", "# ================ #", "if", "'style'", "in", "kwargs", ":", "if", "kwargs...
Colorize the text kwargs arguments: style=, bg=
[ "Colorize", "the", "text", "kwargs", "arguments", ":", "style", "=", "bg", "=" ]
61d9816ced51f36b4618d86aa4143450b594ea05
https://github.com/kitscribe/pycolorize/blob/61d9816ced51f36b4618d86aa4143450b594ea05/pycolorize.py#L70-L109
train
Colorize the text.
DeV1doR/aioethereum
aioethereum/client.py
create_ethereum_client
def create_ethereum_client(uri, timeout=60, *, loop=None): """Create client to ethereum node based on schema. :param uri: Host on ethereum node :type uri: str :param timeout: An optional total time of timeout call :type timeout: int :param loop: An optional *event loop* instance ...
python
def create_ethereum_client(uri, timeout=60, *, loop=None): """Create client to ethereum node based on schema. :param uri: Host on ethereum node :type uri: str :param timeout: An optional total time of timeout call :type timeout: int :param loop: An optional *event loop* instance ...
[ "def", "create_ethereum_client", "(", "uri", ",", "timeout", "=", "60", ",", "*", ",", "loop", "=", "None", ")", ":", "if", "loop", "is", "None", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "presult", "=", "urlparse", "(", "uri", ")...
Create client to ethereum node based on schema. :param uri: Host on ethereum node :type uri: str :param timeout: An optional total time of timeout call :type timeout: int :param loop: An optional *event loop* instance (uses :func:`asyncio.get_event_loop` if not specified). :t...
[ "Create", "client", "to", "ethereum", "node", "based", "on", "schema", "." ]
85eb46550d862b3ccc309914ea871ca1c7b42157
https://github.com/DeV1doR/aioethereum/blob/85eb46550d862b3ccc309914ea871ca1c7b42157/aioethereum/client.py#L246-L276
train
Create client to ethereum node based on schema.
ludeeus/GHLocalApi
examples/get_alarms.py
get_alarms
async def get_alarms(): """Get alarms and timers from GH.""" async with aiohttp.ClientSession() as session: ghlocalapi = Alarms(LOOP, session, IPADDRESS) await ghlocalapi.get_alarms() print("Alarms:", ghlocalapi.alarms)
python
async def get_alarms(): """Get alarms and timers from GH.""" async with aiohttp.ClientSession() as session: ghlocalapi = Alarms(LOOP, session, IPADDRESS) await ghlocalapi.get_alarms() print("Alarms:", ghlocalapi.alarms)
[ "async", "def", "get_alarms", "(", ")", ":", "async", "with", "aiohttp", ".", "ClientSession", "(", ")", "as", "session", ":", "ghlocalapi", "=", "Alarms", "(", "LOOP", ",", "session", ",", "IPADDRESS", ")", "await", "ghlocalapi", ".", "get_alarms", "(", ...
Get alarms and timers from GH.
[ "Get", "alarms", "and", "timers", "from", "GH", "." ]
93abdee299c4a4b65aa9dd03c77ec34e174e3c56
https://github.com/ludeeus/GHLocalApi/blob/93abdee299c4a4b65aa9dd03c77ec34e174e3c56/examples/get_alarms.py#L9-L15
train
Get alarms and timers from GH.
DeV1doR/aioethereum
aioethereum/utils.py
add_0x
def add_0x(string): """Add 0x to string at start. """ if isinstance(string, bytes): string = string.decode('utf-8') return '0x' + str(string)
python
def add_0x(string): """Add 0x to string at start. """ if isinstance(string, bytes): string = string.decode('utf-8') return '0x' + str(string)
[ "def", "add_0x", "(", "string", ")", ":", "if", "isinstance", "(", "string", ",", "bytes", ")", ":", "string", "=", "string", ".", "decode", "(", "'utf-8'", ")", "return", "'0x'", "+", "str", "(", "string", ")" ]
Add 0x to string at start.
[ "Add", "0x", "to", "string", "at", "start", "." ]
85eb46550d862b3ccc309914ea871ca1c7b42157
https://github.com/DeV1doR/aioethereum/blob/85eb46550d862b3ccc309914ea871ca1c7b42157/aioethereum/utils.py#L4-L9
train
Add 0x to string at start.
Genida/dependenpy
src/dependenpy/helpers.py
guess_depth
def guess_depth(packages): """ Guess the optimal depth to use for the given list of arguments. Args: packages (list of str): list of packages. Returns: int: guessed depth to use. """ if len(packages) == 1: return packages[0].count('.') + 2 return min(p.count('.') fo...
python
def guess_depth(packages): """ Guess the optimal depth to use for the given list of arguments. Args: packages (list of str): list of packages. Returns: int: guessed depth to use. """ if len(packages) == 1: return packages[0].count('.') + 2 return min(p.count('.') fo...
[ "def", "guess_depth", "(", "packages", ")", ":", "if", "len", "(", "packages", ")", "==", "1", ":", "return", "packages", "[", "0", "]", ".", "count", "(", "'.'", ")", "+", "2", "return", "min", "(", "p", ".", "count", "(", "'.'", ")", "for", "...
Guess the optimal depth to use for the given list of arguments. Args: packages (list of str): list of packages. Returns: int: guessed depth to use.
[ "Guess", "the", "optimal", "depth", "to", "use", "for", "the", "given", "list", "of", "arguments", "." ]
df099c17cbe735c990eca9197e39cfc5eb8a4c8e
https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/helpers.py#L45-L57
train
Guess the optimal depth to use for the given packages.
Genida/dependenpy
src/dependenpy/helpers.py
PrintMixin.print
def print(self, format=TEXT, output=sys.stdout, **kwargs): """ Print the object in a file or on standard output by default. Args: format (str): output format (csv, json or text). output (file): descriptor to an opened file (default to standard output). ...
python
def print(self, format=TEXT, output=sys.stdout, **kwargs): """ Print the object in a file or on standard output by default. Args: format (str): output format (csv, json or text). output (file): descriptor to an opened file (default to standard output). ...
[ "def", "print", "(", "self", ",", "format", "=", "TEXT", ",", "output", "=", "sys", ".", "stdout", ",", "*", "*", "kwargs", ")", ":", "if", "format", "is", "None", ":", "format", "=", "TEXT", "if", "format", "==", "TEXT", ":", "print", "(", "self...
Print the object in a file or on standard output by default. Args: format (str): output format (csv, json or text). output (file): descriptor to an opened file (default to standard output). **kwargs (): additional arguments.
[ "Print", "the", "object", "in", "a", "file", "or", "on", "standard", "output", "by", "default", "." ]
df099c17cbe735c990eca9197e39cfc5eb8a4c8e
https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/helpers.py#L16-L33
train
Print the object in a file or on standard output by default.
sengupta/twss
twss/twsslib.py
TWSS.import_training_data
def import_training_data(self, positive_corpus_file=os.path.join(os.path.dirname(__file__), "positive.txt"), negative_corpus_file=os.path.join(os.path.dirname(__file__), "negative.txt") ): """ This method imports the positive and negati...
python
def import_training_data(self, positive_corpus_file=os.path.join(os.path.dirname(__file__), "positive.txt"), negative_corpus_file=os.path.join(os.path.dirname(__file__), "negative.txt") ): """ This method imports the positive and negati...
[ "def", "import_training_data", "(", "self", ",", "positive_corpus_file", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"positive.txt\"", ")", ",", "negative_corpus_file", "=", "os", ".", "path", "...
This method imports the positive and negative training data from the two corpus files and creates the training data list.
[ "This", "method", "imports", "the", "positive", "and", "negative", "training", "data", "from", "the", "two", "corpus", "files", "and", "creates", "the", "training", "data", "list", "." ]
69269b58bc1c388f53b181ecb7c5d6ee5ee8c03f
https://github.com/sengupta/twss/blob/69269b58bc1c388f53b181ecb7c5d6ee5ee8c03f/twss/twsslib.py#L24-L48
train
This method imports the positive and negative training data from the two corpus files and creates the training data list.
sengupta/twss
twss/twsslib.py
TWSS.train
def train(self): """ This method generates the classifier. This method assumes that the training data has been loaded """ if not self.training_data: self.import_training_data() training_feature_set = [(self.extract_features(line), label) ...
python
def train(self): """ This method generates the classifier. This method assumes that the training data has been loaded """ if not self.training_data: self.import_training_data() training_feature_set = [(self.extract_features(line), label) ...
[ "def", "train", "(", "self", ")", ":", "if", "not", "self", ".", "training_data", ":", "self", ".", "import_training_data", "(", ")", "training_feature_set", "=", "[", "(", "self", ".", "extract_features", "(", "line", ")", ",", "label", ")", "for", "(",...
This method generates the classifier. This method assumes that the training data has been loaded
[ "This", "method", "generates", "the", "classifier", ".", "This", "method", "assumes", "that", "the", "training", "data", "has", "been", "loaded" ]
69269b58bc1c388f53b181ecb7c5d6ee5ee8c03f
https://github.com/sengupta/twss/blob/69269b58bc1c388f53b181ecb7c5d6ee5ee8c03f/twss/twsslib.py#L50-L59
train
This method generates the classifier for the current nltk. NaiveBayesClassifier.
sengupta/twss
twss/twsslib.py
TWSS.extract_features
def extract_features(self, phrase): """ This function will extract features from the phrase being used. Currently, the feature we are extracting are unigrams of the text corpus. """ words = nltk.word_tokenize(phrase) features = {} for word in words: ...
python
def extract_features(self, phrase): """ This function will extract features from the phrase being used. Currently, the feature we are extracting are unigrams of the text corpus. """ words = nltk.word_tokenize(phrase) features = {} for word in words: ...
[ "def", "extract_features", "(", "self", ",", "phrase", ")", ":", "words", "=", "nltk", ".", "word_tokenize", "(", "phrase", ")", "features", "=", "{", "}", "for", "word", "in", "words", ":", "features", "[", "'contains(%s)'", "%", "word", "]", "=", "("...
This function will extract features from the phrase being used. Currently, the feature we are extracting are unigrams of the text corpus.
[ "This", "function", "will", "extract", "features", "from", "the", "phrase", "being", "used", ".", "Currently", "the", "feature", "we", "are", "extracting", "are", "unigrams", "of", "the", "text", "corpus", "." ]
69269b58bc1c388f53b181ecb7c5d6ee5ee8c03f
https://github.com/sengupta/twss/blob/69269b58bc1c388f53b181ecb7c5d6ee5ee8c03f/twss/twsslib.py#L61-L71
train
This function will extract features from the phrase being used. It will extract the unigrams of the text corpus.
sengupta/twss
twss/twsslib.py
TWSS.is_twss
def is_twss(self, phrase): """ The magic function- this accepts a phrase and tells you if it classifies as an entendre """ featureset = self.extract_features(phrase) return self.classifier.classify(featureset)
python
def is_twss(self, phrase): """ The magic function- this accepts a phrase and tells you if it classifies as an entendre """ featureset = self.extract_features(phrase) return self.classifier.classify(featureset)
[ "def", "is_twss", "(", "self", ",", "phrase", ")", ":", "featureset", "=", "self", ".", "extract_features", "(", "phrase", ")", "return", "self", ".", "classifier", ".", "classify", "(", "featureset", ")" ]
The magic function- this accepts a phrase and tells you if it classifies as an entendre
[ "The", "magic", "function", "-", "this", "accepts", "a", "phrase", "and", "tells", "you", "if", "it", "classifies", "as", "an", "entendre" ]
69269b58bc1c388f53b181ecb7c5d6ee5ee8c03f
https://github.com/sengupta/twss/blob/69269b58bc1c388f53b181ecb7c5d6ee5ee8c03f/twss/twsslib.py#L73-L79
train
This function is used to determine if a phrase is a twss phrase.
sengupta/twss
twss/twsslib.py
TWSS.save
def save(self, filename='classifier.dump'): """ Pickles the classifier and dumps it into a file """ ofile = open(filename,'w+') pickle.dump(self.classifier, ofile) ofile.close()
python
def save(self, filename='classifier.dump'): """ Pickles the classifier and dumps it into a file """ ofile = open(filename,'w+') pickle.dump(self.classifier, ofile) ofile.close()
[ "def", "save", "(", "self", ",", "filename", "=", "'classifier.dump'", ")", ":", "ofile", "=", "open", "(", "filename", ",", "'w+'", ")", "pickle", ".", "dump", "(", "self", ".", "classifier", ",", "ofile", ")", "ofile", ".", "close", "(", ")" ]
Pickles the classifier and dumps it into a file
[ "Pickles", "the", "classifier", "and", "dumps", "it", "into", "a", "file" ]
69269b58bc1c388f53b181ecb7c5d6ee5ee8c03f
https://github.com/sengupta/twss/blob/69269b58bc1c388f53b181ecb7c5d6ee5ee8c03f/twss/twsslib.py#L81-L87
train
Save the classifier to a file.
sengupta/twss
twss/twsslib.py
TWSS.load
def load(self, filename='classifier.dump'): """ Unpickles the classifier used """ ifile = open(filename, 'r+') self.classifier = pickle.load(ifile) ifile.close()
python
def load(self, filename='classifier.dump'): """ Unpickles the classifier used """ ifile = open(filename, 'r+') self.classifier = pickle.load(ifile) ifile.close()
[ "def", "load", "(", "self", ",", "filename", "=", "'classifier.dump'", ")", ":", "ifile", "=", "open", "(", "filename", ",", "'r+'", ")", "self", ".", "classifier", "=", "pickle", ".", "load", "(", "ifile", ")", "ifile", ".", "close", "(", ")" ]
Unpickles the classifier used
[ "Unpickles", "the", "classifier", "used" ]
69269b58bc1c388f53b181ecb7c5d6ee5ee8c03f
https://github.com/sengupta/twss/blob/69269b58bc1c388f53b181ecb7c5d6ee5ee8c03f/twss/twsslib.py#L89-L95
train
Load the classifier used by this instance
catch22/pw
pw/__main__.py
pw
def pw( ctx, key_pattern, user_pattern, mode, strict_flag, user_flag, file, edit_subcommand, gen_subcommand, ): """Search for USER and KEY in GPG-encrypted password file.""" # install silent Ctrl-C handler def handle_sigint(*_): click.echo() ctx.exit(1) ...
python
def pw( ctx, key_pattern, user_pattern, mode, strict_flag, user_flag, file, edit_subcommand, gen_subcommand, ): """Search for USER and KEY in GPG-encrypted password file.""" # install silent Ctrl-C handler def handle_sigint(*_): click.echo() ctx.exit(1) ...
[ "def", "pw", "(", "ctx", ",", "key_pattern", ",", "user_pattern", ",", "mode", ",", "strict_flag", ",", "user_flag", ",", "file", ",", "edit_subcommand", ",", "gen_subcommand", ",", ")", ":", "# install silent Ctrl-C handler", "def", "handle_sigint", "(", "*", ...
Search for USER and KEY in GPG-encrypted password file.
[ "Search", "for", "USER", "and", "KEY", "in", "GPG", "-", "encrypted", "password", "file", "." ]
2452924bbdccad28b21290b6ce062809c3d1c5f2
https://github.com/catch22/pw/blob/2452924bbdccad28b21290b6ce062809c3d1c5f2/pw/__main__.py#L91-L182
train
Search for USER and KEY in GPG - encrypted password file.
catch22/pw
pw/__main__.py
launch_editor
def launch_editor(ctx, file): """launch editor with decrypted password database""" # do not use EDITOR environment variable (rather force user to make a concious choice) editor = os.environ.get("PW_EDITOR") if not editor: click.echo("error: no editor set in PW_EDITOR environment variables") ...
python
def launch_editor(ctx, file): """launch editor with decrypted password database""" # do not use EDITOR environment variable (rather force user to make a concious choice) editor = os.environ.get("PW_EDITOR") if not editor: click.echo("error: no editor set in PW_EDITOR environment variables") ...
[ "def", "launch_editor", "(", "ctx", ",", "file", ")", ":", "# do not use EDITOR environment variable (rather force user to make a concious choice)", "editor", "=", "os", ".", "environ", ".", "get", "(", "\"PW_EDITOR\"", ")", "if", "not", "editor", ":", "click", ".", ...
launch editor with decrypted password database
[ "launch", "editor", "with", "decrypted", "password", "database" ]
2452924bbdccad28b21290b6ce062809c3d1c5f2
https://github.com/catch22/pw/blob/2452924bbdccad28b21290b6ce062809c3d1c5f2/pw/__main__.py#L185-L231
train
launch editor with decrypted password database
catch22/pw
pw/__main__.py
generate_password
def generate_password(mode, length): """generate a random password""" # generate random password r = random.SystemRandom() length = length or RANDOM_PASSWORD_DEFAULT_LENGTH password = "".join(r.choice(RANDOM_PASSWORD_ALPHABET) for _ in range(length)) # copy or echo generated password if mod...
python
def generate_password(mode, length): """generate a random password""" # generate random password r = random.SystemRandom() length = length or RANDOM_PASSWORD_DEFAULT_LENGTH password = "".join(r.choice(RANDOM_PASSWORD_ALPHABET) for _ in range(length)) # copy or echo generated password if mod...
[ "def", "generate_password", "(", "mode", ",", "length", ")", ":", "# generate random password", "r", "=", "random", ".", "SystemRandom", "(", ")", "length", "=", "length", "or", "RANDOM_PASSWORD_DEFAULT_LENGTH", "password", "=", "\"\"", ".", "join", "(", "r", ...
generate a random password
[ "generate", "a", "random", "password" ]
2452924bbdccad28b21290b6ce062809c3d1c5f2
https://github.com/catch22/pw/blob/2452924bbdccad28b21290b6ce062809c3d1c5f2/pw/__main__.py#L234-L254
train
generate a random password
noahbenson/pimms
pimms/cmdline.py
to_argv_schema
def to_argv_schema(data, arg_names=None, arg_abbrevs=None, filters=None, defaults=None): ''' to_argv_schema(instructions) yields a valid tuple of CommandLineParser instructions for the given instructions tuple; by itself, this will only return the instructions as they are, but optional arguments (be...
python
def to_argv_schema(data, arg_names=None, arg_abbrevs=None, filters=None, defaults=None): ''' to_argv_schema(instructions) yields a valid tuple of CommandLineParser instructions for the given instructions tuple; by itself, this will only return the instructions as they are, but optional arguments (be...
[ "def", "to_argv_schema", "(", "data", ",", "arg_names", "=", "None", ",", "arg_abbrevs", "=", "None", ",", "filters", "=", "None", ",", "defaults", "=", "None", ")", ":", "if", "is_plan", "(", "data", ")", ":", "# First we must convert it to a valid instructio...
to_argv_schema(instructions) yields a valid tuple of CommandLineParser instructions for the given instructions tuple; by itself, this will only return the instructions as they are, but optional arguments (below) will override the values in the instructions if provided. to_argv_schema(plan) yields a vali...
[ "to_argv_schema", "(", "instructions", ")", "yields", "a", "valid", "tuple", "of", "CommandLineParser", "instructions", "for", "the", "given", "instructions", "tuple", ";", "by", "itself", "this", "will", "only", "return", "the", "instructions", "as", "they", "a...
9051b86d6b858a7a13511b72c48dc21bc903dab2
https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/cmdline.py#L242-L326
train
Parse the given data into a tuple of CommandLineParser arguments.
noahbenson/pimms
pimms/cmdline.py
argv_parser
def argv_parser(instructs, arg_names=None, arg_abbrevs=None, defaults=None, value_parser=True, filters=None): ''' argv_parser(instructions) is equivalent to CommandLineParser(instructions). argv_parser(plan) is equivalent to CommandLineParser(plan_to_argv_instructions(plan))....
python
def argv_parser(instructs, arg_names=None, arg_abbrevs=None, defaults=None, value_parser=True, filters=None): ''' argv_parser(instructions) is equivalent to CommandLineParser(instructions). argv_parser(plan) is equivalent to CommandLineParser(plan_to_argv_instructions(plan))....
[ "def", "argv_parser", "(", "instructs", ",", "arg_names", "=", "None", ",", "arg_abbrevs", "=", "None", ",", "defaults", "=", "None", ",", "value_parser", "=", "True", ",", "filters", "=", "None", ")", ":", "schema", "=", "to_argv_schema", "(", "instructs"...
argv_parser(instructions) is equivalent to CommandLineParser(instructions). argv_parser(plan) is equivalent to CommandLineParser(plan_to_argv_instructions(plan)). See also help(CommandLineParser) and help(to_argv_schema); all optional arguments accepted by these functions are passed along by argv_parser. ...
[ "argv_parser", "(", "instructions", ")", "is", "equivalent", "to", "CommandLineParser", "(", "instructions", ")", ".", "argv_parser", "(", "plan", ")", "is", "equivalent", "to", "CommandLineParser", "(", "plan_to_argv_instructions", "(", "plan", "))", "." ]
9051b86d6b858a7a13511b72c48dc21bc903dab2
https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/cmdline.py#L328-L343
train
A wrapper around to_argv_schema that takes a list of INDRA IN D IN D IN D IN D IN DAGS and a list of INDRA INDRA
noahbenson/pimms
pimms/cmdline.py
argv_parse
def argv_parse(schema, argv, init=None, arg_names=None, arg_abbrevs=None, value_parser=True, defaults=None, filters=None): ''' argv_parse(schema, argv) yields the tuple (unparsed_argv, params) where unparsed_argv is a list subset of argv that contains only those command line arguments that ...
python
def argv_parse(schema, argv, init=None, arg_names=None, arg_abbrevs=None, value_parser=True, defaults=None, filters=None): ''' argv_parse(schema, argv) yields the tuple (unparsed_argv, params) where unparsed_argv is a list subset of argv that contains only those command line arguments that ...
[ "def", "argv_parse", "(", "schema", ",", "argv", ",", "init", "=", "None", ",", "arg_names", "=", "None", ",", "arg_abbrevs", "=", "None", ",", "value_parser", "=", "True", ",", "defaults", "=", "None", ",", "filters", "=", "None", ")", ":", "parser", ...
argv_parse(schema, argv) yields the tuple (unparsed_argv, params) where unparsed_argv is a list subset of argv that contains only those command line arguments that were not understood by the given argument schema and params is a dictionary of parameters as parsed by the given schema. It is equivalent...
[ "argv_parse", "(", "schema", "argv", ")", "yields", "the", "tuple", "(", "unparsed_argv", "params", ")", "where", "unparsed_argv", "is", "a", "list", "subset", "of", "argv", "that", "contains", "only", "those", "command", "line", "arguments", "that", "were", ...
9051b86d6b858a7a13511b72c48dc21bc903dab2
https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/cmdline.py#L345-L398
train
Parses the given command - line arguments into a pimms IMap object.
noahbenson/pimms
pimms/cmdline.py
worklog
def worklog(columns=None, bullet=' * ', stdout=Ellipsis, stderr=Ellipsis, verbose=False): ''' worklog() yields a worklog object using sys.stdout and sys.stderr as the outputs. worklog(n) yields a worklog that formats output to n columns. The following options may be give: * bullet (default: ' *...
python
def worklog(columns=None, bullet=' * ', stdout=Ellipsis, stderr=Ellipsis, verbose=False): ''' worklog() yields a worklog object using sys.stdout and sys.stderr as the outputs. worklog(n) yields a worklog that formats output to n columns. The following options may be give: * bullet (default: ' *...
[ "def", "worklog", "(", "columns", "=", "None", ",", "bullet", "=", "' * '", ",", "stdout", "=", "Ellipsis", ",", "stderr", "=", "Ellipsis", ",", "verbose", "=", "False", ")", ":", "if", "columns", "is", "None", ":", "try", ":", "columns", "=", "int"...
worklog() yields a worklog object using sys.stdout and sys.stderr as the outputs. worklog(n) yields a worklog that formats output to n columns. The following options may be give: * bullet (default: ' * ') the bullet-text to print for each bullet. * stdout (default: Ellipsis) the file to use in pla...
[ "worklog", "()", "yields", "a", "worklog", "object", "using", "sys", ".", "stdout", "and", "sys", ".", "stderr", "as", "the", "outputs", ".", "worklog", "(", "n", ")", "yields", "a", "worklog", "that", "formats", "output", "to", "n", "columns", "." ]
9051b86d6b858a7a13511b72c48dc21bc903dab2
https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/cmdline.py#L459-L479
train
Returns a WorkLog object that formats output to a number of columns.
noahbenson/pimms
pimms/cmdline.py
WorkLog.indent
def indent(self, n=1): ''' worklog.indent() yields a duplicate worklog that is indented relative to worklog. worklog.indent(x) indents x times. ''' return WorkLog(columns=self.columns, bullet=(self.blanks + self.bullet), stdout=self.s...
python
def indent(self, n=1): ''' worklog.indent() yields a duplicate worklog that is indented relative to worklog. worklog.indent(x) indents x times. ''' return WorkLog(columns=self.columns, bullet=(self.blanks + self.bullet), stdout=self.s...
[ "def", "indent", "(", "self", ",", "n", "=", "1", ")", ":", "return", "WorkLog", "(", "columns", "=", "self", ".", "columns", ",", "bullet", "=", "(", "self", ".", "blanks", "+", "self", ".", "bullet", ")", ",", "stdout", "=", "self", ".", "stdou...
worklog.indent() yields a duplicate worklog that is indented relative to worklog. worklog.indent(x) indents x times.
[ "worklog", ".", "indent", "()", "yields", "a", "duplicate", "worklog", "that", "is", "indented", "relative", "to", "worklog", ".", "worklog", ".", "indent", "(", "x", ")", "indents", "x", "times", "." ]
9051b86d6b858a7a13511b72c48dc21bc903dab2
https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/cmdline.py#L417-L424
train
Returns a new WorkLog with the same columns and indentation.
striglia/stockfighter
stockfighter/gm.py
GM._load_data
def _load_data(self): """Internal method for querying the GM api for currently running levels and storing that state.""" url = urljoin(self.base_url, 'levels') resp = requests.get(url, headers=self.headers) # TOOD: Confirm/deny that this is a real API for the levels currenlty run...
python
def _load_data(self): """Internal method for querying the GM api for currently running levels and storing that state.""" url = urljoin(self.base_url, 'levels') resp = requests.get(url, headers=self.headers) # TOOD: Confirm/deny that this is a real API for the levels currenlty run...
[ "def", "_load_data", "(", "self", ")", ":", "url", "=", "urljoin", "(", "self", ".", "base_url", ",", "'levels'", ")", "resp", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "headers", ")", "# TOOD: Confirm/deny that this is a r...
Internal method for querying the GM api for currently running levels and storing that state.
[ "Internal", "method", "for", "querying", "the", "GM", "api", "for", "currently", "running", "levels", "and", "storing", "that", "state", "." ]
df908f5919d6f861601cd00c906a049d04253d47
https://github.com/striglia/stockfighter/blob/df908f5919d6f861601cd00c906a049d04253d47/stockfighter/gm.py#L16-L25
train
Internal method for querying the GM API for currently running levels and storing that state.
mkoura/dump2polarion
dump2polarion/csv2sqlite_cli.py
dump2sqlite
def dump2sqlite(records, output_file): """Dumps tests results to database.""" results_keys = list(records.results[0].keys()) pad_data = [] for key in REQUIRED_KEYS: if key not in results_keys: results_keys.append(key) pad_data.append("") conn = sqlite3.connect(os.pa...
python
def dump2sqlite(records, output_file): """Dumps tests results to database.""" results_keys = list(records.results[0].keys()) pad_data = [] for key in REQUIRED_KEYS: if key not in results_keys: results_keys.append(key) pad_data.append("") conn = sqlite3.connect(os.pa...
[ "def", "dump2sqlite", "(", "records", ",", "output_file", ")", ":", "results_keys", "=", "list", "(", "records", ".", "results", "[", "0", "]", ".", "keys", "(", ")", ")", "pad_data", "=", "[", "]", "for", "key", "in", "REQUIRED_KEYS", ":", "if", "ke...
Dumps tests results to database.
[ "Dumps", "tests", "results", "to", "database", "." ]
f4bd24e9d5070e282aad15f1e8bb514c0525cd37
https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/csv2sqlite_cli.py#L42-L77
train
Dumps testcases results to database.
mkoura/dump2polarion
dump2polarion/csv2sqlite_cli.py
main
def main(args=None): """Main function for cli.""" args = get_args(args) utils.init_log(args.log_level) if ".csv" not in args.input_file.lower(): logger.warning("Make sure the input file '%s' is in CSV format", args.input_file) try: records = csvtools.get_imported_data(args.input_f...
python
def main(args=None): """Main function for cli.""" args = get_args(args) utils.init_log(args.log_level) if ".csv" not in args.input_file.lower(): logger.warning("Make sure the input file '%s' is in CSV format", args.input_file) try: records = csvtools.get_imported_data(args.input_f...
[ "def", "main", "(", "args", "=", "None", ")", ":", "args", "=", "get_args", "(", "args", ")", "utils", ".", "init_log", "(", "args", ".", "log_level", ")", "if", "\".csv\"", "not", "in", "args", ".", "input_file", ".", "lower", "(", ")", ":", "logg...
Main function for cli.
[ "Main", "function", "for", "cli", "." ]
f4bd24e9d5070e282aad15f1e8bb514c0525cd37
https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/csv2sqlite_cli.py#L80-L113
train
Main function for cli.
romanorac/discomll
discomll/ensemble/core/k_medoids.py
fit
def fit(sim_mat, D_len, cidx): """ Algorithm maximizes energy between clusters, which is distinction in this algorithm. Distance matrix contains mostly 0, which are overlooked due to search of maximal distances. Algorithm does not try to retain k clusters. D: numpy array - Symmetric distance matrix k: ...
python
def fit(sim_mat, D_len, cidx): """ Algorithm maximizes energy between clusters, which is distinction in this algorithm. Distance matrix contains mostly 0, which are overlooked due to search of maximal distances. Algorithm does not try to retain k clusters. D: numpy array - Symmetric distance matrix k: ...
[ "def", "fit", "(", "sim_mat", ",", "D_len", ",", "cidx", ")", ":", "min_energy", "=", "np", ".", "inf", "for", "j", "in", "range", "(", "3", ")", ":", "# select indices in each sample that maximizes its dimension", "inds", "=", "[", "np", ".", "argmin", "(...
Algorithm maximizes energy between clusters, which is distinction in this algorithm. Distance matrix contains mostly 0, which are overlooked due to search of maximal distances. Algorithm does not try to retain k clusters. D: numpy array - Symmetric distance matrix k: int - number of clusters
[ "Algorithm", "maximizes", "energy", "between", "clusters", "which", "is", "distinction", "in", "this", "algorithm", ".", "Distance", "matrix", "contains", "mostly", "0", "which", "are", "overlooked", "due", "to", "search", "of", "maximal", "distances", ".", "Alg...
a4703daffb2ba3c9f614bc3dbe45ae55884aea00
https://github.com/romanorac/discomll/blob/a4703daffb2ba3c9f614bc3dbe45ae55884aea00/discomll/ensemble/core/k_medoids.py#L8-L41
train
Fits the algorithm to find the minimum energy between k clusters.
tweekmonster/moult
moult/printer.py
output
def output(*args, **kwargs): '''Analog of print() but with an indent option ''' indent = kwargs.pop('indent', 0) sep = kwargs.pop('sep', None) kwargs['sep'] = u'' # Sanity if sep is None: sep = u' ' indent_str = u' ' * (indent * tab_width) text = sep.join(map(str_, args)) co...
python
def output(*args, **kwargs): '''Analog of print() but with an indent option ''' indent = kwargs.pop('indent', 0) sep = kwargs.pop('sep', None) kwargs['sep'] = u'' # Sanity if sep is None: sep = u' ' indent_str = u' ' * (indent * tab_width) text = sep.join(map(str_, args)) co...
[ "def", "output", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "indent", "=", "kwargs", ".", "pop", "(", "'indent'", ",", "0", ")", "sep", "=", "kwargs", ".", "pop", "(", "'sep'", ",", "None", ")", "kwargs", "[", "'sep'", "]", "=", "u''"...
Analog of print() but with an indent option
[ "Analog", "of", "print", "()", "but", "with", "an", "indent", "option" ]
38d3a3b9002336219897ebe263ca1d8dcadbecf5
https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/printer.py#L21-L35
train
Analog of print but with an indent option
ngmarchant/oasis
oasis/oasis.py
BetaBernoulliModel._calc_theta
def _calc_theta(self): """Calculate an estimate of theta""" if self.decaying_prior: n_sampled = np.clip(self.alpha_ + self.beta_, 1, np.inf) prior_weight = 1/n_sampled alpha = self.alpha_ + prior_weight * self.alpha_0 beta = self.beta_ + prior_weight * sel...
python
def _calc_theta(self): """Calculate an estimate of theta""" if self.decaying_prior: n_sampled = np.clip(self.alpha_ + self.beta_, 1, np.inf) prior_weight = 1/n_sampled alpha = self.alpha_ + prior_weight * self.alpha_0 beta = self.beta_ + prior_weight * sel...
[ "def", "_calc_theta", "(", "self", ")", ":", "if", "self", ".", "decaying_prior", ":", "n_sampled", "=", "np", ".", "clip", "(", "self", ".", "alpha_", "+", "self", ".", "beta_", ",", "1", ",", "np", ".", "inf", ")", "prior_weight", "=", "1", "/", ...
Calculate an estimate of theta
[ "Calculate", "an", "estimate", "of", "theta" ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/oasis.py#L81-L99
train
Calculate an estimate of theta
ngmarchant/oasis
oasis/oasis.py
BetaBernoulliModel._calc_var_theta
def _calc_var_theta(self): """Calculate an estimate of the var(theta)""" if self.decaying_prior: n_sampled = np.clip(self.alpha_ + self.beta_, 1, np.inf) prior_weight = 1/n_sampled alpha = self.alpha_ + prior_weight * self.alpha_0 beta = self.beta_ + prior...
python
def _calc_var_theta(self): """Calculate an estimate of the var(theta)""" if self.decaying_prior: n_sampled = np.clip(self.alpha_ + self.beta_, 1, np.inf) prior_weight = 1/n_sampled alpha = self.alpha_ + prior_weight * self.alpha_0 beta = self.beta_ + prior...
[ "def", "_calc_var_theta", "(", "self", ")", ":", "if", "self", ".", "decaying_prior", ":", "n_sampled", "=", "np", ".", "clip", "(", "self", ".", "alpha_", "+", "self", ".", "beta_", ",", "1", ",", "np", ".", "inf", ")", "prior_weight", "=", "1", "...
Calculate an estimate of the var(theta)
[ "Calculate", "an", "estimate", "of", "the", "var", "(", "theta", ")" ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/oasis.py#L101-L113
train
Calculate an estimate of the var ( theta )
ngmarchant/oasis
oasis/oasis.py
BetaBernoulliModel.update
def update(self, ell, k): """Update the posterior and estimates after a label is sampled Parameters ---------- ell : int sampled label: 0 or 1 k : int index of stratum where label was sampled """ self.alpha_[k] += ell self.beta_[k...
python
def update(self, ell, k): """Update the posterior and estimates after a label is sampled Parameters ---------- ell : int sampled label: 0 or 1 k : int index of stratum where label was sampled """ self.alpha_[k] += ell self.beta_[k...
[ "def", "update", "(", "self", ",", "ell", ",", "k", ")", ":", "self", ".", "alpha_", "[", "k", "]", "+=", "ell", "self", ".", "beta_", "[", "k", "]", "+=", "1", "-", "ell", "self", ".", "_calc_theta", "(", ")", "if", "self", ".", "store_varianc...
Update the posterior and estimates after a label is sampled Parameters ---------- ell : int sampled label: 0 or 1 k : int index of stratum where label was sampled
[ "Update", "the", "posterior", "and", "estimates", "after", "a", "label", "is", "sampled" ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/oasis.py#L115-L131
train
Update the posterior and estimates after a label is sampled
ngmarchant/oasis
oasis/oasis.py
BetaBernoulliModel.reset
def reset(self): """Reset the instance to its initial state""" self.alpha_ = np.zeros(self._size, dtype=int) self.beta_ = np.zeros(self._size, dtype=int) self.theta_ = np.empty(self._size, dtype=float) if self.store_variance: self.var_theta_ = np.empty(self._size, dty...
python
def reset(self): """Reset the instance to its initial state""" self.alpha_ = np.zeros(self._size, dtype=int) self.beta_ = np.zeros(self._size, dtype=int) self.theta_ = np.empty(self._size, dtype=float) if self.store_variance: self.var_theta_ = np.empty(self._size, dty...
[ "def", "reset", "(", "self", ")", ":", "self", ".", "alpha_", "=", "np", ".", "zeros", "(", "self", ".", "_size", ",", "dtype", "=", "int", ")", "self", ".", "beta_", "=", "np", ".", "zeros", "(", "self", ".", "_size", ",", "dtype", "=", "int",...
Reset the instance to its initial state
[ "Reset", "the", "instance", "to", "its", "initial", "state" ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/oasis.py#L133-L145
train
Reset the instance to its initial state.
ngmarchant/oasis
oasis/oasis.py
OASISSampler._sample_item
def _sample_item(self, **kwargs): """Sample an item from the pool according to the instrumental distribution """ t = self.t_ # Update instrumental distribution self._calc_inst_pmf() if self.record_inst_hist: inst_pmf = self._inst_pmf[:,t] els...
python
def _sample_item(self, **kwargs): """Sample an item from the pool according to the instrumental distribution """ t = self.t_ # Update instrumental distribution self._calc_inst_pmf() if self.record_inst_hist: inst_pmf = self._inst_pmf[:,t] els...
[ "def", "_sample_item", "(", "self", ",", "*", "*", "kwargs", ")", ":", "t", "=", "self", ".", "t_", "# Update instrumental distribution", "self", ".", "_calc_inst_pmf", "(", ")", "if", "self", ".", "record_inst_hist", ":", "inst_pmf", "=", "self", ".", "_i...
Sample an item from the pool according to the instrumental distribution
[ "Sample", "an", "item", "from", "the", "pool", "according", "to", "the", "instrumental", "distribution" ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/oasis.py#L350-L368
train
Sample an item from the pool according to the instrumental distribution
ngmarchant/oasis
oasis/oasis.py
OASISSampler._calc_BB_prior
def _calc_BB_prior(self, theta_0): """Generate a prior for the BB model Parameters ---------- theta_0 : array-like, shape=(n_strata,) array of oracle probabilities (probability of a "1" label) for each stratum. This is just a guess. Returns -----...
python
def _calc_BB_prior(self, theta_0): """Generate a prior for the BB model Parameters ---------- theta_0 : array-like, shape=(n_strata,) array of oracle probabilities (probability of a "1" label) for each stratum. This is just a guess. Returns -----...
[ "def", "_calc_BB_prior", "(", "self", ",", "theta_0", ")", ":", "#: Easy vars", "prior_strength", "=", "self", ".", "prior_strength", "#weighted_strength = self.weights * strength", "n_strata", "=", "len", "(", "theta_0", ")", "weighted_strength", "=", "prior_strength",...
Generate a prior for the BB model Parameters ---------- theta_0 : array-like, shape=(n_strata,) array of oracle probabilities (probability of a "1" label) for each stratum. This is just a guess. Returns ------- alpha_0 : numpy.ndarray, shape=(n_s...
[ "Generate", "a", "prior", "for", "the", "BB", "model" ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/oasis.py#L379-L404
train
Calculates a prior for the BB model.
ngmarchant/oasis
oasis/oasis.py
OASISSampler._calc_F_guess
def _calc_F_guess(self, alpha, predictions, theta, weights): """Calculate an estimate of the F-measure based on the scores""" num = np.sum(predictions.T * theta * weights, axis=1) den = np.sum((1 - alpha) * theta * weights + \ alpha * predictions.T * weights, axis=1) ...
python
def _calc_F_guess(self, alpha, predictions, theta, weights): """Calculate an estimate of the F-measure based on the scores""" num = np.sum(predictions.T * theta * weights, axis=1) den = np.sum((1 - alpha) * theta * weights + \ alpha * predictions.T * weights, axis=1) ...
[ "def", "_calc_F_guess", "(", "self", ",", "alpha", ",", "predictions", ",", "theta", ",", "weights", ")", ":", "num", "=", "np", ".", "sum", "(", "predictions", ".", "T", "*", "theta", "*", "weights", ",", "axis", "=", "1", ")", "den", "=", "np", ...
Calculate an estimate of the F-measure based on the scores
[ "Calculate", "an", "estimate", "of", "the", "F", "-", "measure", "based", "on", "the", "scores" ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/oasis.py#L406-L414
train
Calculate an estimate of the F - measure based on the scores
ngmarchant/oasis
oasis/oasis.py
OASISSampler._calc_inst_pmf
def _calc_inst_pmf(self): """Calculate the epsilon-greedy instrumental distribution""" # Easy vars t = self.t_ epsilon = self.epsilon alpha = self.alpha preds = self._preds_avg_in_strata weights = self.strata.weights_[:,np.newaxis] p1 = self._BB_model.thet...
python
def _calc_inst_pmf(self): """Calculate the epsilon-greedy instrumental distribution""" # Easy vars t = self.t_ epsilon = self.epsilon alpha = self.alpha preds = self._preds_avg_in_strata weights = self.strata.weights_[:,np.newaxis] p1 = self._BB_model.thet...
[ "def", "_calc_inst_pmf", "(", "self", ")", ":", "# Easy vars", "t", "=", "self", ".", "t_", "epsilon", "=", "self", ".", "epsilon", "alpha", "=", "self", ".", "alpha", "preds", "=", "self", ".", "_preds_avg_in_strata", "weights", "=", "self", ".", "strat...
Calculate the epsilon-greedy instrumental distribution
[ "Calculate", "the", "epsilon", "-", "greedy", "instrumental", "distribution" ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/oasis.py#L416-L448
train
Calculate the epsilon - greedy instrumental distribution of the classifiers of the current object.
ngmarchant/oasis
oasis/oasis.py
OASISSampler.reset
def reset(self): """Resets the sampler to its initial state Note ---- This will destroy the label cache, instrumental distribution and history of estimates. """ super(OASISSampler, self).reset() self.strata.reset() self._BB_model.reset() ...
python
def reset(self): """Resets the sampler to its initial state Note ---- This will destroy the label cache, instrumental distribution and history of estimates. """ super(OASISSampler, self).reset() self.strata.reset() self._BB_model.reset() ...
[ "def", "reset", "(", "self", ")", ":", "super", "(", "OASISSampler", ",", "self", ")", ".", "reset", "(", ")", "self", ".", "strata", ".", "reset", "(", ")", "self", ".", "_BB_model", ".", "reset", "(", ")", "# Array to record history of instrumental distr...
Resets the sampler to its initial state Note ---- This will destroy the label cache, instrumental distribution and history of estimates.
[ "Resets", "the", "sampler", "to", "its", "initial", "state" ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/oasis.py#L450-L467
train
Resets the sampler to its initial state
djaodjin/djaodjin-deployutils
deployutils/apps/django/backends/auth.py
ProxyUserBackend.authenticate
def authenticate(self, request, remote_user=None): #pylint:disable=arguments-differ # Django <=1.8 and >=1.9 have different signatures. """ The ``username`` passed here is considered trusted. This method simply returns the ``User`` object with the given username. In ord...
python
def authenticate(self, request, remote_user=None): #pylint:disable=arguments-differ # Django <=1.8 and >=1.9 have different signatures. """ The ``username`` passed here is considered trusted. This method simply returns the ``User`` object with the given username. In ord...
[ "def", "authenticate", "(", "self", ",", "request", ",", "remote_user", "=", "None", ")", ":", "#pylint:disable=arguments-differ", "# Django <=1.8 and >=1.9 have different signatures.", "if", "not", "remote_user", ":", "remote_user", "=", "request", "if", "not", "remote...
The ``username`` passed here is considered trusted. This method simply returns the ``User`` object with the given username. In order to support older Django versions (before commit 4b9330ccc04575f9e5126529ec355a450d12e77c), if username is None, we will assume request is the ``remote_us...
[ "The", "username", "passed", "here", "is", "considered", "trusted", ".", "This", "method", "simply", "returns", "the", "User", "object", "with", "the", "given", "username", "." ]
a0fe3cf3030dbbf09025c69ce75a69b326565dd8
https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/deployutils/apps/django/backends/auth.py#L55-L117
train
This method is used to authenticate a user.
DavidMStraub/pylha
pylha/parse.py
numval
def numval(token): """Return the numerical value of token.value if it is a number""" if token.type == 'INTEGER': return int(token.value) elif token.type == 'FLOAT': return float(token.value) else: return token.value
python
def numval(token): """Return the numerical value of token.value if it is a number""" if token.type == 'INTEGER': return int(token.value) elif token.type == 'FLOAT': return float(token.value) else: return token.value
[ "def", "numval", "(", "token", ")", ":", "if", "token", ".", "type", "==", "'INTEGER'", ":", "return", "int", "(", "token", ".", "value", ")", "elif", "token", ".", "type", "==", "'FLOAT'", ":", "return", "float", "(", "token", ".", "value", ")", "...
Return the numerical value of token.value if it is a number
[ "Return", "the", "numerical", "value", "of", "token", ".", "value", "if", "it", "is", "a", "number" ]
8d65074609321e5eaf97fe962c56f6d79a3ad2b6
https://github.com/DavidMStraub/pylha/blob/8d65074609321e5eaf97fe962c56f6d79a3ad2b6/pylha/parse.py#L6-L13
train
Return the numerical value of token. value if it is a number
DavidMStraub/pylha
pylha/parse.py
tokenize
def tokenize(code): """Tokenize the string `code`""" tok_regex = '|'.join('(?P<{}>{})'.format(*pair) for pair in _tokens) tok_regex = re.compile(tok_regex, re.IGNORECASE|re.M) line_num = 1 line_start = 0 for mo in re.finditer(tok_regex, code): kind = mo.lastgroup value = mo.group...
python
def tokenize(code): """Tokenize the string `code`""" tok_regex = '|'.join('(?P<{}>{})'.format(*pair) for pair in _tokens) tok_regex = re.compile(tok_regex, re.IGNORECASE|re.M) line_num = 1 line_start = 0 for mo in re.finditer(tok_regex, code): kind = mo.lastgroup value = mo.group...
[ "def", "tokenize", "(", "code", ")", ":", "tok_regex", "=", "'|'", ".", "join", "(", "'(?P<{}>{})'", ".", "format", "(", "*", "pair", ")", "for", "pair", "in", "_tokens", ")", "tok_regex", "=", "re", ".", "compile", "(", "tok_regex", ",", "re", ".", ...
Tokenize the string `code`
[ "Tokenize", "the", "string", "code" ]
8d65074609321e5eaf97fe962c56f6d79a3ad2b6
https://github.com/DavidMStraub/pylha/blob/8d65074609321e5eaf97fe962c56f6d79a3ad2b6/pylha/parse.py#L26-L42
train
Tokenize the string code
DavidMStraub/pylha
pylha/parse.py
parse
def parse(tokens): """Parse the token list into a hierarchical data structure""" d = collections.OrderedDict() prev_line = 0 blockname = None blockline = None for token in tokens: if token.type == 'COMMENT': continue elif token.type == 'BLOCK': block = tok...
python
def parse(tokens): """Parse the token list into a hierarchical data structure""" d = collections.OrderedDict() prev_line = 0 blockname = None blockline = None for token in tokens: if token.type == 'COMMENT': continue elif token.type == 'BLOCK': block = tok...
[ "def", "parse", "(", "tokens", ")", ":", "d", "=", "collections", ".", "OrderedDict", "(", ")", "prev_line", "=", "0", "blockname", "=", "None", "blockline", "=", "None", "for", "token", "in", "tokens", ":", "if", "token", ".", "type", "==", "'COMMENT'...
Parse the token list into a hierarchical data structure
[ "Parse", "the", "token", "list", "into", "a", "hierarchical", "data", "structure" ]
8d65074609321e5eaf97fe962c56f6d79a3ad2b6
https://github.com/DavidMStraub/pylha/blob/8d65074609321e5eaf97fe962c56f6d79a3ad2b6/pylha/parse.py#L47-L78
train
Parse the token list into a hierarchical data structure
DavidMStraub/pylha
pylha/parse.py
load
def load(stream): """Parse the LHA document and produce the corresponding Python object. Accepts a string or a file-like object.""" if isinstance(stream, str): string = stream else: string = stream.read() tokens = tokenize(string) return parse(tokens)
python
def load(stream): """Parse the LHA document and produce the corresponding Python object. Accepts a string or a file-like object.""" if isinstance(stream, str): string = stream else: string = stream.read() tokens = tokenize(string) return parse(tokens)
[ "def", "load", "(", "stream", ")", ":", "if", "isinstance", "(", "stream", ",", "str", ")", ":", "string", "=", "stream", "else", ":", "string", "=", "stream", ".", "read", "(", ")", "tokens", "=", "tokenize", "(", "string", ")", "return", "parse", ...
Parse the LHA document and produce the corresponding Python object. Accepts a string or a file-like object.
[ "Parse", "the", "LHA", "document", "and", "produce", "the", "corresponding", "Python", "object", ".", "Accepts", "a", "string", "or", "a", "file", "-", "like", "object", "." ]
8d65074609321e5eaf97fe962c56f6d79a3ad2b6
https://github.com/DavidMStraub/pylha/blob/8d65074609321e5eaf97fe962c56f6d79a3ad2b6/pylha/parse.py#L80-L88
train
Parse the LHA document and produce the corresponding Python object.
djaodjin/djaodjin-deployutils
src/djd.py
build_subcommands_parser
def build_subcommands_parser(parser, module): """ Returns a parser for the subcommands defined in the *module* (i.e. commands starting with a 'pub_' prefix). """ mdefs = module.__dict__ keys = list(mdefs.keys()) keys.sort() subparsers = parser.add_subparsers(help='sub-command help') ...
python
def build_subcommands_parser(parser, module): """ Returns a parser for the subcommands defined in the *module* (i.e. commands starting with a 'pub_' prefix). """ mdefs = module.__dict__ keys = list(mdefs.keys()) keys.sort() subparsers = parser.add_subparsers(help='sub-command help') ...
[ "def", "build_subcommands_parser", "(", "parser", ",", "module", ")", ":", "mdefs", "=", "module", ".", "__dict__", "keys", "=", "list", "(", "mdefs", ".", "keys", "(", ")", ")", "keys", ".", "sort", "(", ")", "subparsers", "=", "parser", ".", "add_sub...
Returns a parser for the subcommands defined in the *module* (i.e. commands starting with a 'pub_' prefix).
[ "Returns", "a", "parser", "for", "the", "subcommands", "defined", "in", "the", "*", "module", "*", "(", "i", ".", "e", ".", "commands", "starting", "with", "a", "pub_", "prefix", ")", "." ]
a0fe3cf3030dbbf09025c69ce75a69b326565dd8
https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/src/djd.py#L38-L78
train
Builds a parser for the subcommands defined in the module.
djaodjin/djaodjin-deployutils
src/djd.py
filter_subcommand_args
def filter_subcommand_args(func, options): """ Filter out all options which are not part of the function *func* prototype and returns a set that can be used as kwargs for calling func. """ kwargs = {} argspec = inspect.getargspec(func) for arg in argspec.args: if arg in options: ...
python
def filter_subcommand_args(func, options): """ Filter out all options which are not part of the function *func* prototype and returns a set that can be used as kwargs for calling func. """ kwargs = {} argspec = inspect.getargspec(func) for arg in argspec.args: if arg in options: ...
[ "def", "filter_subcommand_args", "(", "func", ",", "options", ")", ":", "kwargs", "=", "{", "}", "argspec", "=", "inspect", ".", "getargspec", "(", "func", ")", "for", "arg", "in", "argspec", ".", "args", ":", "if", "arg", "in", "options", ":", "kwargs...
Filter out all options which are not part of the function *func* prototype and returns a set that can be used as kwargs for calling func.
[ "Filter", "out", "all", "options", "which", "are", "not", "part", "of", "the", "function", "*", "func", "*", "prototype", "and", "returns", "a", "set", "that", "can", "be", "used", "as", "kwargs", "for", "calling", "func", "." ]
a0fe3cf3030dbbf09025c69ce75a69b326565dd8
https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/src/djd.py#L81-L91
train
Filter out all options which are not part of the function func * func* and returns a set that can be used as kwargs for calling func.
djaodjin/djaodjin-deployutils
src/djd.py
pub_download
def pub_download(args, location=None, prefix=""): """Download theme packages from the stage *location*. """ download(location, remotes=args, prefix=prefix)
python
def pub_download(args, location=None, prefix=""): """Download theme packages from the stage *location*. """ download(location, remotes=args, prefix=prefix)
[ "def", "pub_download", "(", "args", ",", "location", "=", "None", ",", "prefix", "=", "\"\"", ")", ":", "download", "(", "location", ",", "remotes", "=", "args", ",", "prefix", "=", "prefix", ")" ]
Download theme packages from the stage *location*.
[ "Download", "theme", "packages", "from", "the", "stage", "*", "location", "*", "." ]
a0fe3cf3030dbbf09025c69ce75a69b326565dd8
https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/src/djd.py#L94-L97
train
Download theme packages from the stage location.
djaodjin/djaodjin-deployutils
src/djd.py
pub_upload
def pub_upload(args, location=None, prefix=""): """Upload theme packages to the stage *location*. """ upload(location, remotes=args, prefix=prefix)
python
def pub_upload(args, location=None, prefix=""): """Upload theme packages to the stage *location*. """ upload(location, remotes=args, prefix=prefix)
[ "def", "pub_upload", "(", "args", ",", "location", "=", "None", ",", "prefix", "=", "\"\"", ")", ":", "upload", "(", "location", ",", "remotes", "=", "args", ",", "prefix", "=", "prefix", ")" ]
Upload theme packages to the stage *location*.
[ "Upload", "theme", "packages", "to", "the", "stage", "*", "location", "*", "." ]
a0fe3cf3030dbbf09025c69ce75a69b326565dd8
https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/src/djd.py#L100-L103
train
Upload theme packages to the stage location.
djaodjin/djaodjin-deployutils
src/djd.py
main
def main(args): """ Main Entry Point """ try: import __main__ parser = argparse.ArgumentParser( usage='%(prog)s [options] command\n\nVersion\n %(prog)s version ' + str(__version__), formatter_class=argparse.RawTextHelpFormatter) parser.add_arg...
python
def main(args): """ Main Entry Point """ try: import __main__ parser = argparse.ArgumentParser( usage='%(prog)s [options] command\n\nVersion\n %(prog)s version ' + str(__version__), formatter_class=argparse.RawTextHelpFormatter) parser.add_arg...
[ "def", "main", "(", "args", ")", ":", "try", ":", "import", "__main__", "parser", "=", "argparse", ".", "ArgumentParser", "(", "usage", "=", "'%(prog)s [options] command\\n\\nVersion\\n %(prog)s version '", "+", "str", "(", "__version__", ")", ",", "formatter_class...
Main Entry Point
[ "Main", "Entry", "Point" ]
a0fe3cf3030dbbf09025c69ce75a69b326565dd8
https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/src/djd.py#L106-L131
train
Main entry point for the Arc.
djaodjin/djaodjin-deployutils
deployutils/apps/django/management/commands/__init__.py
build_assets
def build_assets(): """Call django_assets ./manage.py assets build if the app is present.""" cwd = os.getcwd() try: from webassets.script import GenericArgparseImplementation from django_assets.env import get_env prog = "%s assets" % os.path.basename(sys.argv[0]) impl = Gener...
python
def build_assets(): """Call django_assets ./manage.py assets build if the app is present.""" cwd = os.getcwd() try: from webassets.script import GenericArgparseImplementation from django_assets.env import get_env prog = "%s assets" % os.path.basename(sys.argv[0]) impl = Gener...
[ "def", "build_assets", "(", ")", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "try", ":", "from", "webassets", ".", "script", "import", "GenericArgparseImplementation", "from", "django_assets", ".", "env", "import", "get_env", "prog", "=", "\"%s assets\"", ...
Call django_assets ./manage.py assets build if the app is present.
[ "Call", "django_assets", ".", "/", "manage", ".", "py", "assets", "build", "if", "the", "app", "is", "present", "." ]
a0fe3cf3030dbbf09025c69ce75a69b326565dd8
https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/deployutils/apps/django/management/commands/__init__.py#L79-L91
train
Call django_assets. manage. py assets build if the app is present.
ngmarchant/oasis
oasis/druck.py
DruckSampler._sample_item
def _sample_item(self, **kwargs): """Sample an item from the strata""" if 'fixed_stratum' in kwargs: stratum_idx = kwargs['fixed_stratum'] else: stratum_idx = None if stratum_idx is not None: #: Sample in given stratum loc = self.strata._sa...
python
def _sample_item(self, **kwargs): """Sample an item from the strata""" if 'fixed_stratum' in kwargs: stratum_idx = kwargs['fixed_stratum'] else: stratum_idx = None if stratum_idx is not None: #: Sample in given stratum loc = self.strata._sa...
[ "def", "_sample_item", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "'fixed_stratum'", "in", "kwargs", ":", "stratum_idx", "=", "kwargs", "[", "'fixed_stratum'", "]", "else", ":", "stratum_idx", "=", "None", "if", "stratum_idx", "is", "not", "None...
Sample an item from the strata
[ "Sample", "an", "item", "from", "the", "strata" ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/druck.py#L157-L171
train
Sample an item from the strata
ngmarchant/oasis
oasis/druck.py
DruckSampler._update_estimate_and_sampler
def _update_estimate_and_sampler(self, ell, ell_hat, weight, extra_info, **kwargs): """Update the estimate after querying the label for an item""" stratum_idx = extra_info['stratum'] if 'calc_rates' in kwargs: calc_rates = kwargs['calc_rates'] ...
python
def _update_estimate_and_sampler(self, ell, ell_hat, weight, extra_info, **kwargs): """Update the estimate after querying the label for an item""" stratum_idx = extra_info['stratum'] if 'calc_rates' in kwargs: calc_rates = kwargs['calc_rates'] ...
[ "def", "_update_estimate_and_sampler", "(", "self", ",", "ell", ",", "ell_hat", ",", "weight", ",", "extra_info", ",", "*", "*", "kwargs", ")", ":", "stratum_idx", "=", "extra_info", "[", "'stratum'", "]", "if", "'calc_rates'", "in", "kwargs", ":", "calc_rat...
Update the estimate after querying the label for an item
[ "Update", "the", "estimate", "after", "querying", "the", "label", "for", "an", "item" ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/druck.py#L186-L209
train
Update the estimate of the model with the new values.
ngmarchant/oasis
oasis/druck.py
DruckSampler.reset
def reset(self): """Resets the sampler to its initial state Note ---- This will destroy the label cache and history of estimates """ super(DruckSampler, self).reset() self.strata.reset() self._TP_st = np.zeros([self.strata.n_strata_, self._n_class]) ...
python
def reset(self): """Resets the sampler to its initial state Note ---- This will destroy the label cache and history of estimates """ super(DruckSampler, self).reset() self.strata.reset() self._TP_st = np.zeros([self.strata.n_strata_, self._n_class]) ...
[ "def", "reset", "(", "self", ")", ":", "super", "(", "DruckSampler", ",", "self", ")", ".", "reset", "(", ")", "self", ".", "strata", ".", "reset", "(", ")", "self", ".", "_TP_st", "=", "np", ".", "zeros", "(", "[", "self", ".", "strata", ".", ...
Resets the sampler to its initial state Note ---- This will destroy the label cache and history of estimates
[ "Resets", "the", "sampler", "to", "its", "initial", "state" ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/druck.py#L211-L229
train
Resets the sampler to its initial state
coopernurse/barrister
barrister/parser.py
IdlScanner.get_checksum
def get_checksum(self): """ Returns a checksum based on the IDL that ignores comments and ordering, but detects changes to types, parameter order, and enum values. """ arr = [ ] for elem in self.parsed: s = elem_checksum(elem) if s: ...
python
def get_checksum(self): """ Returns a checksum based on the IDL that ignores comments and ordering, but detects changes to types, parameter order, and enum values. """ arr = [ ] for elem in self.parsed: s = elem_checksum(elem) if s: ...
[ "def", "get_checksum", "(", "self", ")", ":", "arr", "=", "[", "]", "for", "elem", "in", "self", ".", "parsed", ":", "s", "=", "elem_checksum", "(", "elem", ")", "if", "s", ":", "arr", ".", "append", "(", "s", ")", "arr", ".", "sort", "(", ")",...
Returns a checksum based on the IDL that ignores comments and ordering, but detects changes to types, parameter order, and enum values.
[ "Returns", "a", "checksum", "based", "on", "the", "IDL", "that", "ignores", "comments", "and", "ordering", "but", "detects", "changes", "to", "types", "parameter", "order", "and", "enum", "values", "." ]
0471b1d98d3327ba381684db496ec94c79c20848
https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/parser.py#L204-L217
train
Returns a checksum based on the IDL that ignores comments and ordering and parameter order and enum values.
ngmarchant/oasis
oasis/kad.py
KadaneSampler._sample_item
def _sample_item(self, **kwargs): """Sample an item from the pool according to the instrumental distribution """ t = self.t_ if 'fixed_stratum' in kwargs: stratum_idx = kwargs['fixed_stratum'] else: stratum_idx = None if stratum_idx is not ...
python
def _sample_item(self, **kwargs): """Sample an item from the pool according to the instrumental distribution """ t = self.t_ if 'fixed_stratum' in kwargs: stratum_idx = kwargs['fixed_stratum'] else: stratum_idx = None if stratum_idx is not ...
[ "def", "_sample_item", "(", "self", ",", "*", "*", "kwargs", ")", ":", "t", "=", "self", ".", "t_", "if", "'fixed_stratum'", "in", "kwargs", ":", "stratum_idx", "=", "kwargs", "[", "'fixed_stratum'", "]", "else", ":", "stratum_idx", "=", "None", "if", ...
Sample an item from the pool according to the instrumental distribution
[ "Sample", "an", "item", "from", "the", "pool", "according", "to", "the", "instrumental", "distribution" ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/kad.py#L105-L131
train
Sample an item from the pool according to the instrumental distribution
ngmarchant/oasis
oasis/kad.py
KadaneSampler._update_estimate_and_sampler
def _update_estimate_and_sampler(self, ell, ell_hat, weight, extra_info, **kwargs): """Update the BB models and the estimates""" stratum_idx = extra_info['stratum'] self._BB_TP.update(ell*ell_hat, stratum_idx) self._BB_PP.update(ell_hat, stratum_idx) ...
python
def _update_estimate_and_sampler(self, ell, ell_hat, weight, extra_info, **kwargs): """Update the BB models and the estimates""" stratum_idx = extra_info['stratum'] self._BB_TP.update(ell*ell_hat, stratum_idx) self._BB_PP.update(ell_hat, stratum_idx) ...
[ "def", "_update_estimate_and_sampler", "(", "self", ",", "ell", ",", "ell_hat", ",", "weight", ",", "extra_info", ",", "*", "*", "kwargs", ")", ":", "stratum_idx", "=", "extra_info", "[", "'stratum'", "]", "self", ".", "_BB_TP", ".", "update", "(", "ell", ...
Update the BB models and the estimates
[ "Update", "the", "BB", "models", "and", "the", "estimates" ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/kad.py#L133-L145
train
Update the BB models P and F - measure estimates and Samples.
ngmarchant/oasis
oasis/kad.py
KadaneSampler._update_cov_model
def _update_cov_model(self, strata_to_update='all'): """ strata_to_update : array-like or 'all' array containing stratum indices to update """ if strata_to_update == 'all': strata_to_update = self.strata.indices_ #: Otherwise assume strata_to_update is val...
python
def _update_cov_model(self, strata_to_update='all'): """ strata_to_update : array-like or 'all' array containing stratum indices to update """ if strata_to_update == 'all': strata_to_update = self.strata.indices_ #: Otherwise assume strata_to_update is val...
[ "def", "_update_cov_model", "(", "self", ",", "strata_to_update", "=", "'all'", ")", ":", "if", "strata_to_update", "==", "'all'", ":", "strata_to_update", "=", "self", ".", "strata", ".", "indices_", "#: Otherwise assume strata_to_update is valid (no duplicates etc.)", ...
strata_to_update : array-like or 'all' array containing stratum indices to update
[ "strata_to_update", ":", "array", "-", "like", "or", "all", "array", "containing", "stratum", "indices", "to", "update" ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/kad.py#L215-L241
train
Update the covariance matrix of the current instance of the class.
mkoura/dump2polarion
dump2polarion/svn_polarion.py
WorkItemCache.get_path
def get_path(num): """Gets a path from the workitem number. For example: 31942 will return 30000-39999/31000-31999/31900-31999 """ num = int(num) dig_len = len(str(num)) paths = [] for i in range(dig_len - 2): divisor = 10 ** (dig_len - i - 1) ...
python
def get_path(num): """Gets a path from the workitem number. For example: 31942 will return 30000-39999/31000-31999/31900-31999 """ num = int(num) dig_len = len(str(num)) paths = [] for i in range(dig_len - 2): divisor = 10 ** (dig_len - i - 1) ...
[ "def", "get_path", "(", "num", ")", ":", "num", "=", "int", "(", "num", ")", "dig_len", "=", "len", "(", "str", "(", "num", ")", ")", "paths", "=", "[", "]", "for", "i", "in", "range", "(", "dig_len", "-", "2", ")", ":", "divisor", "=", "10",...
Gets a path from the workitem number. For example: 31942 will return 30000-39999/31000-31999/31900-31999
[ "Gets", "a", "path", "from", "the", "workitem", "number", "." ]
f4bd24e9d5070e282aad15f1e8bb514c0525cd37
https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/svn_polarion.py#L31-L44
train
Gets a path from the workitem number.
mkoura/dump2polarion
dump2polarion/svn_polarion.py
WorkItemCache.get_tree
def get_tree(self, work_item_id): """Gets XML tree of the workitem.""" try: __, tcid = work_item_id.split("-") except ValueError: logger.warning("Couldn't load workitem %s, bad format", work_item_id) self._cache[work_item_id] = InvalidObject() retu...
python
def get_tree(self, work_item_id): """Gets XML tree of the workitem.""" try: __, tcid = work_item_id.split("-") except ValueError: logger.warning("Couldn't load workitem %s, bad format", work_item_id) self._cache[work_item_id] = InvalidObject() retu...
[ "def", "get_tree", "(", "self", ",", "work_item_id", ")", ":", "try", ":", "__", ",", "tcid", "=", "work_item_id", ".", "split", "(", "\"-\"", ")", "except", "ValueError", ":", "logger", ".", "warning", "(", "\"Couldn't load workitem %s, bad format\"", ",", ...
Gets XML tree of the workitem.
[ "Gets", "XML", "tree", "of", "the", "workitem", "." ]
f4bd24e9d5070e282aad15f1e8bb514c0525cd37
https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/svn_polarion.py#L46-L63
train
Gets XML tree of the workitem.
mkoura/dump2polarion
dump2polarion/svn_polarion.py
WorkItemCache.get_all_items
def get_all_items(self): """Walks the repo and returns work items.""" for item in os.walk(self.test_case_dir): if "workitem.xml" not in item[2]: continue case_id = os.path.split(item[0])[-1] if not (case_id and "*" not in case_id): cont...
python
def get_all_items(self): """Walks the repo and returns work items.""" for item in os.walk(self.test_case_dir): if "workitem.xml" not in item[2]: continue case_id = os.path.split(item[0])[-1] if not (case_id and "*" not in case_id): cont...
[ "def", "get_all_items", "(", "self", ")", ":", "for", "item", "in", "os", ".", "walk", "(", "self", ".", "test_case_dir", ")", ":", "if", "\"workitem.xml\"", "not", "in", "item", "[", "2", "]", ":", "continue", "case_id", "=", "os", ".", "path", ".",...
Walks the repo and returns work items.
[ "Walks", "the", "repo", "and", "returns", "work", "items", "." ]
f4bd24e9d5070e282aad15f1e8bb514c0525cd37
https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/svn_polarion.py#L135-L148
train
Walks the repo and returns work items.
ckcollab/polished
polished/backends/base.py
BaseBackend._remove_files
def _remove_files(self, directory, pattern): ''' Removes all files matching the search path Arguments: search_path -- The path you would like to remove, can contain wildcards Example: self._remove_files("output/*.html") ''' for root, dirnames, file_names...
python
def _remove_files(self, directory, pattern): ''' Removes all files matching the search path Arguments: search_path -- The path you would like to remove, can contain wildcards Example: self._remove_files("output/*.html") ''' for root, dirnames, file_names...
[ "def", "_remove_files", "(", "self", ",", "directory", ",", "pattern", ")", ":", "for", "root", ",", "dirnames", ",", "file_names", "in", "os", ".", "walk", "(", "directory", ")", ":", "for", "file_name", "in", "fnmatch", ".", "filter", "(", "file_names"...
Removes all files matching the search path Arguments: search_path -- The path you would like to remove, can contain wildcards Example: self._remove_files("output/*.html")
[ "Removes", "all", "files", "matching", "the", "search", "path" ]
5a00b2fbe569bc957d1647c0849fd344db29b644
https://github.com/ckcollab/polished/blob/5a00b2fbe569bc957d1647c0849fd344db29b644/polished/backends/base.py#L52-L64
train
Removes all files matching the pattern in the directory
bradmontgomery/django-blargg
blargg/signals.py
mail2blogger
def mail2blogger(entry, **kwargs): """This signal handler cross-posts published ``Entry``'s to Blogger. For this to work, the following settings must be non-False; e.g.: BLARGG = { 'mail2blogger': True, 'mail2blogger_email': 'user@example.com', } """ enabled = b...
python
def mail2blogger(entry, **kwargs): """This signal handler cross-posts published ``Entry``'s to Blogger. For this to work, the following settings must be non-False; e.g.: BLARGG = { 'mail2blogger': True, 'mail2blogger_email': 'user@example.com', } """ enabled = b...
[ "def", "mail2blogger", "(", "entry", ",", "*", "*", "kwargs", ")", ":", "enabled", "=", "blargg_settings", ".", "get", "(", "'mail2blogger'", ",", "False", ")", "recipient", "=", "blargg_settings", ".", "get", "(", "'mail2blogger_email'", ",", "None", ")", ...
This signal handler cross-posts published ``Entry``'s to Blogger. For this to work, the following settings must be non-False; e.g.: BLARGG = { 'mail2blogger': True, 'mail2blogger_email': 'user@example.com', }
[ "This", "signal", "handler", "cross", "-", "posts", "published", "Entry", "s", "to", "Blogger", ".", "For", "this", "to", "work", "the", "following", "settings", "must", "be", "non", "-", "False", ";", "e", ".", "g", ".", ":" ]
5d683e04723889a0d1c6d6cf1a67a3d431a2e617
https://github.com/bradmontgomery/django-blargg/blob/5d683e04723889a0d1c6d6cf1a67a3d431a2e617/blargg/signals.py#L25-L47
train
This signal handler sends cross - posts published Entry s to Blogger.
praekeltfoundation/seed-message-sender
message_sender/views.py
process_event
def process_event(message_id, event_type, event_detail, timestamp): """ Processes an event of the given details, returning a (success, message) tuple """ # Load message try: message = Outbound.objects.select_related("channel").get( vumi_message_id=message_id ) except ...
python
def process_event(message_id, event_type, event_detail, timestamp): """ Processes an event of the given details, returning a (success, message) tuple """ # Load message try: message = Outbound.objects.select_related("channel").get( vumi_message_id=message_id ) except ...
[ "def", "process_event", "(", "message_id", ",", "event_type", ",", "event_detail", ",", "timestamp", ")", ":", "# Load message", "try", ":", "message", "=", "Outbound", ".", "objects", ".", "select_related", "(", "\"channel\"", ")", ".", "get", "(", "vumi_mess...
Processes an event of the given details, returning a (success, message) tuple
[ "Processes", "an", "event", "of", "the", "given", "details", "returning", "a", "(", "success", "message", ")", "tuple" ]
257b01635171b9dbe1f5f13baa810c971bb2620e
https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/views.py#L324-L373
train
Processes an event of the given details returning a tuple containing a success and message.
praekeltfoundation/seed-message-sender
message_sender/views.py
EventListener.post
def post(self, request, *args, **kwargs): """ Checks for expect event types before continuing """ serializer = EventSerializer(data=request.data) if not serializer.is_valid(): return Response( {"accepted": False, "reason": serializer.errors}, status=4...
python
def post(self, request, *args, **kwargs): """ Checks for expect event types before continuing """ serializer = EventSerializer(data=request.data) if not serializer.is_valid(): return Response( {"accepted": False, "reason": serializer.errors}, status=4...
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "serializer", "=", "EventSerializer", "(", "data", "=", "request", ".", "data", ")", "if", "not", "serializer", ".", "is_valid", "(", ")", ":", "return",...
Checks for expect event types before continuing
[ "Checks", "for", "expect", "event", "types", "before", "continuing" ]
257b01635171b9dbe1f5f13baa810c971bb2620e
https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/views.py#L384-L409
train
Checks for expect event types before continuing
carta/ldap_tools
src/ldap_tools/group.py
API.create
def create(self, group, grouptype): """ Create an LDAP Group. Raises: ldap3.core.exceptions.LDAPNoSuchObjectResult: an object involved with the request is missing ldap3.core.exceptions.LDAPEntryAlreadyExistsResult: the entity being create...
python
def create(self, group, grouptype): """ Create an LDAP Group. Raises: ldap3.core.exceptions.LDAPNoSuchObjectResult: an object involved with the request is missing ldap3.core.exceptions.LDAPEntryAlreadyExistsResult: the entity being create...
[ "def", "create", "(", "self", ",", "group", ",", "grouptype", ")", ":", "try", ":", "self", ".", "client", ".", "add", "(", "self", ".", "__distinguished_name", "(", "group", ")", ",", "API", ".", "__object_class", "(", ")", ",", "self", ".", "__ldap...
Create an LDAP Group. Raises: ldap3.core.exceptions.LDAPNoSuchObjectResult: an object involved with the request is missing ldap3.core.exceptions.LDAPEntryAlreadyExistsResult: the entity being created already exists
[ "Create", "an", "LDAP", "Group", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/group.py#L18-L47
train
Creates an LDAP Group.
carta/ldap_tools
src/ldap_tools/group.py
API.add_user
def add_user(self, group, username): """ Add a user to the specified LDAP group. Args: group: Name of group to update username: Username of user to add Raises: ldap_tools.exceptions.InvalidResult: Results of the query were invalid. T...
python
def add_user(self, group, username): """ Add a user to the specified LDAP group. Args: group: Name of group to update username: Username of user to add Raises: ldap_tools.exceptions.InvalidResult: Results of the query were invalid. T...
[ "def", "add_user", "(", "self", ",", "group", ",", "username", ")", ":", "try", ":", "self", ".", "lookup_id", "(", "group", ")", "except", "ldap_tools", ".", "exceptions", ".", "InvalidResult", "as", "err", ":", "# pragma: no cover", "raise", "err", "from...
Add a user to the specified LDAP group. Args: group: Name of group to update username: Username of user to add Raises: ldap_tools.exceptions.InvalidResult: Results of the query were invalid. The actual exception raised inherits from ...
[ "Add", "a", "user", "to", "the", "specified", "LDAP", "group", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/group.py#L53-L73
train
Adds a user to the specified LDAP group.
carta/ldap_tools
src/ldap_tools/group.py
API.remove_user
def remove_user(self, group, username): """ Remove a user from the specified LDAP group. Args: group: Name of group to update username: Username of user to remove Raises: ldap_tools.exceptions.InvalidResult: Results of the query were ...
python
def remove_user(self, group, username): """ Remove a user from the specified LDAP group. Args: group: Name of group to update username: Username of user to remove Raises: ldap_tools.exceptions.InvalidResult: Results of the query were ...
[ "def", "remove_user", "(", "self", ",", "group", ",", "username", ")", ":", "try", ":", "self", ".", "lookup_id", "(", "group", ")", "except", "ldap_tools", ".", "exceptions", ".", "InvalidResult", "as", "err", ":", "# pragma: no cover", "raise", "err", "f...
Remove a user from the specified LDAP group. Args: group: Name of group to update username: Username of user to remove Raises: ldap_tools.exceptions.InvalidResult: Results of the query were invalid. The actual exception raised inheri...
[ "Remove", "a", "user", "from", "the", "specified", "LDAP", "group", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/group.py#L75-L95
train
Removes a user from an LDAP group.
carta/ldap_tools
src/ldap_tools/group.py
API.lookup_id
def lookup_id(self, group): """ Lookup GID for the given group. Args: group: Name of group whose ID needs to be looked up Returns: A bytestring representation of the group ID (gid) for the group specified Raises: ldap_tools.excep...
python
def lookup_id(self, group): """ Lookup GID for the given group. Args: group: Name of group whose ID needs to be looked up Returns: A bytestring representation of the group ID (gid) for the group specified Raises: ldap_tools.excep...
[ "def", "lookup_id", "(", "self", ",", "group", ")", ":", "filter", "=", "[", "\"(cn={})\"", ".", "format", "(", "group", ")", ",", "\"(objectclass=posixGroup)\"", "]", "results", "=", "self", ".", "client", ".", "search", "(", "filter", ",", "[", "'gidNu...
Lookup GID for the given group. Args: group: Name of group whose ID needs to be looked up Returns: A bytestring representation of the group ID (gid) for the group specified Raises: ldap_tools.exceptions.NoGroupsFound: No Groups w...
[ "Lookup", "GID", "for", "the", "given", "group", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/group.py#L101-L130
train
Lookup the ID of the group specified by group.
carta/ldap_tools
src/ldap_tools/group.py
CLI.create
def create(config, group, type): """Create an LDAP group.""" if type not in ('user', 'service'): raise click.BadOptionUsage( # pragma: no cover "--grouptype must be 'user' or 'service'") client = Client() client.prepare_connection() group_api = API(c...
python
def create(config, group, type): """Create an LDAP group.""" if type not in ('user', 'service'): raise click.BadOptionUsage( # pragma: no cover "--grouptype must be 'user' or 'service'") client = Client() client.prepare_connection() group_api = API(c...
[ "def", "create", "(", "config", ",", "group", ",", "type", ")", ":", "if", "type", "not", "in", "(", "'user'", ",", "'service'", ")", ":", "raise", "click", ".", "BadOptionUsage", "(", "# pragma: no cover", "\"--grouptype must be 'user' or 'service'\"", ")", "...
Create an LDAP group.
[ "Create", "an", "LDAP", "group", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/group.py#L165-L174
train
Create an LDAP group.
carta/ldap_tools
src/ldap_tools/group.py
CLI.delete
def delete(config, group, force): """Delete an LDAP group.""" if not force: if not click.confirm( 'Confirm that you want to delete group {}'.format(group)): sys.exit("Deletion of {} aborted".format(group)) client = Client() client.prepare_...
python
def delete(config, group, force): """Delete an LDAP group.""" if not force: if not click.confirm( 'Confirm that you want to delete group {}'.format(group)): sys.exit("Deletion of {} aborted".format(group)) client = Client() client.prepare_...
[ "def", "delete", "(", "config", ",", "group", ",", "force", ")", ":", "if", "not", "force", ":", "if", "not", "click", ".", "confirm", "(", "'Confirm that you want to delete group {}'", ".", "format", "(", "group", ")", ")", ":", "sys", ".", "exit", "(",...
Delete an LDAP group.
[ "Delete", "an", "LDAP", "group", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/group.py#L180-L190
train
Delete an LDAP group.
carta/ldap_tools
src/ldap_tools/group.py
CLI.add_user
def add_user(config, group, username): """Add specified user to specified group.""" client = Client() client.prepare_connection() group_api = API(client) try: group_api.add_user(group, username) except ldap_tools.exceptions.NoGroupsFound: # pragma: no cover ...
python
def add_user(config, group, username): """Add specified user to specified group.""" client = Client() client.prepare_connection() group_api = API(client) try: group_api.add_user(group, username) except ldap_tools.exceptions.NoGroupsFound: # pragma: no cover ...
[ "def", "add_user", "(", "config", ",", "group", ",", "username", ")", ":", "client", "=", "Client", "(", ")", "client", ".", "prepare_connection", "(", ")", "group_api", "=", "API", "(", "client", ")", "try", ":", "group_api", ".", "add_user", "(", "gr...
Add specified user to specified group.
[ "Add", "specified", "user", "to", "specified", "group", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/group.py#L201-L214
train
Add specified user to specified group.
carta/ldap_tools
src/ldap_tools/group.py
CLI.remove_user
def remove_user(config, group, username): """Remove specified user from specified group.""" client = Client() client.prepare_connection() group_api = API(client) try: group_api.remove_user(group, username) except ldap_tools.exceptions.NoGroupsFound: # pragma:...
python
def remove_user(config, group, username): """Remove specified user from specified group.""" client = Client() client.prepare_connection() group_api = API(client) try: group_api.remove_user(group, username) except ldap_tools.exceptions.NoGroupsFound: # pragma:...
[ "def", "remove_user", "(", "config", ",", "group", ",", "username", ")", ":", "client", "=", "Client", "(", ")", "client", ".", "prepare_connection", "(", ")", "group_api", "=", "API", "(", "client", ")", "try", ":", "group_api", ".", "remove_user", "(",...
Remove specified user from specified group.
[ "Remove", "specified", "user", "from", "specified", "group", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/group.py#L228-L241
train
Remove specified user from specified group.
carta/ldap_tools
src/ldap_tools/group.py
CLI.index
def index(config): # pragma: no cover """Display group info in raw format.""" client = Client() client.prepare_connection() group_api = API(client) print(group_api.index())
python
def index(config): # pragma: no cover """Display group info in raw format.""" client = Client() client.prepare_connection() group_api = API(client) print(group_api.index())
[ "def", "index", "(", "config", ")", ":", "# pragma: no cover", "client", "=", "Client", "(", ")", "client", ".", "prepare_connection", "(", ")", "group_api", "=", "API", "(", "client", ")", "print", "(", "group_api", ".", "index", "(", ")", ")" ]
Display group info in raw format.
[ "Display", "group", "info", "in", "raw", "format", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/group.py#L245-L250
train
Display group info in raw format.
mkoura/dump2polarion
dump2polarion/results/importer.py
_get_importer
def _get_importer(input_file): """Selects importer based on input file type.""" __, ext = os.path.splitext(input_file) ext = ext.lower() if "ostriz" in input_file: from dump2polarion.results import ostriztools importer = ostriztools.import_ostriz elif ext == ".xml": # expec...
python
def _get_importer(input_file): """Selects importer based on input file type.""" __, ext = os.path.splitext(input_file) ext = ext.lower() if "ostriz" in input_file: from dump2polarion.results import ostriztools importer = ostriztools.import_ostriz elif ext == ".xml": # expec...
[ "def", "_get_importer", "(", "input_file", ")", ":", "__", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "input_file", ")", "ext", "=", "ext", ".", "lower", "(", ")", "if", "\"ostriz\"", "in", "input_file", ":", "from", "dump2polarion", "."...
Selects importer based on input file type.
[ "Selects", "importer", "based", "on", "input", "file", "type", "." ]
f4bd24e9d5070e282aad15f1e8bb514c0525cd37
https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/results/importer.py#L14-L41
train
Selects importer based on input file type.
smnorris/bcdata
bcdata/cli.py
parse_db_url
def parse_db_url(db_url): """provided a db url, return a dict with connection properties """ u = urlparse(db_url) db = {} db["database"] = u.path[1:] db["user"] = u.username db["password"] = u.password db["host"] = u.hostname db["port"] = u.port return db
python
def parse_db_url(db_url): """provided a db url, return a dict with connection properties """ u = urlparse(db_url) db = {} db["database"] = u.path[1:] db["user"] = u.username db["password"] = u.password db["host"] = u.hostname db["port"] = u.port return db
[ "def", "parse_db_url", "(", "db_url", ")", ":", "u", "=", "urlparse", "(", "db_url", ")", "db", "=", "{", "}", "db", "[", "\"database\"", "]", "=", "u", ".", "path", "[", "1", ":", "]", "db", "[", "\"user\"", "]", "=", "u", ".", "username", "db...
provided a db url, return a dict with connection properties
[ "provided", "a", "db", "url", "return", "a", "dict", "with", "connection", "properties" ]
de6b5bbc28d85e36613b51461911ee0a72a146c5
https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/cli.py#L27-L37
train
parse a db url and return a dict with connection properties
smnorris/bcdata
bcdata/cli.py
from_like_context
def from_like_context(ctx, param, value): """Return the value for an option from the context if the option or `--all` is given, else return None.""" if ctx.obj and ctx.obj.get("like") and (value == "like" or ctx.obj.get("all_like")): return ctx.obj["like"][param.name] else: return None
python
def from_like_context(ctx, param, value): """Return the value for an option from the context if the option or `--all` is given, else return None.""" if ctx.obj and ctx.obj.get("like") and (value == "like" or ctx.obj.get("all_like")): return ctx.obj["like"][param.name] else: return None
[ "def", "from_like_context", "(", "ctx", ",", "param", ",", "value", ")", ":", "if", "ctx", ".", "obj", "and", "ctx", ".", "obj", ".", "get", "(", "\"like\"", ")", "and", "(", "value", "==", "\"like\"", "or", "ctx", ".", "obj", ".", "get", "(", "\...
Return the value for an option from the context if the option or `--all` is given, else return None.
[ "Return", "the", "value", "for", "an", "option", "from", "the", "context", "if", "the", "option", "or", "--", "all", "is", "given", "else", "return", "None", "." ]
de6b5bbc28d85e36613b51461911ee0a72a146c5
https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/cli.py#L49-L55
train
Return the value for an option from the context if the option or all_like is given else return None.
smnorris/bcdata
bcdata/cli.py
bounds_handler
def bounds_handler(ctx, param, value): """Handle different forms of bounds.""" retval = from_like_context(ctx, param, value) if retval is None and value is not None: try: value = value.strip(", []") retval = tuple(float(x) for x in re.split(r"[,\s]+", value)) asse...
python
def bounds_handler(ctx, param, value): """Handle different forms of bounds.""" retval = from_like_context(ctx, param, value) if retval is None and value is not None: try: value = value.strip(", []") retval = tuple(float(x) for x in re.split(r"[,\s]+", value)) asse...
[ "def", "bounds_handler", "(", "ctx", ",", "param", ",", "value", ")", ":", "retval", "=", "from_like_context", "(", "ctx", ",", "param", ",", "value", ")", "if", "retval", "is", "None", "and", "value", "is", "not", "None", ":", "try", ":", "value", "...
Handle different forms of bounds.
[ "Handle", "different", "forms", "of", "bounds", "." ]
de6b5bbc28d85e36613b51461911ee0a72a146c5
https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/cli.py#L58-L72
train
Handle different forms of bounds.
smnorris/bcdata
bcdata/cli.py
info
def info(dataset, indent, meta_member): """Print basic metadata about a DataBC WFS layer as JSON. Optionally print a single metadata item as a string. """ table = bcdata.validate_name(dataset) wfs = WebFeatureService(url=bcdata.OWS_URL, version="2.0.0") info = {} info["name"] = table in...
python
def info(dataset, indent, meta_member): """Print basic metadata about a DataBC WFS layer as JSON. Optionally print a single metadata item as a string. """ table = bcdata.validate_name(dataset) wfs = WebFeatureService(url=bcdata.OWS_URL, version="2.0.0") info = {} info["name"] = table in...
[ "def", "info", "(", "dataset", ",", "indent", ",", "meta_member", ")", ":", "table", "=", "bcdata", ".", "validate_name", "(", "dataset", ")", "wfs", "=", "WebFeatureService", "(", "url", "=", "bcdata", ".", "OWS_URL", ",", "version", "=", "\"2.0.0\"", "...
Print basic metadata about a DataBC WFS layer as JSON. Optionally print a single metadata item as a string.
[ "Print", "basic", "metadata", "about", "a", "DataBC", "WFS", "layer", "as", "JSON", "." ]
de6b5bbc28d85e36613b51461911ee0a72a146c5
https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/cli.py#L120-L134
train
Print basic metadata about a DataBC WFS layer as JSON.
smnorris/bcdata
bcdata/cli.py
dem
def dem(bounds, src_crs, dst_crs, out_file, resolution): """Dump BC DEM to TIFF """ if not dst_crs: dst_crs = "EPSG:3005" bcdata.get_dem(bounds, out_file=out_file, src_crs=src_crs, dst_crs=dst_crs, resolution=resolution)
python
def dem(bounds, src_crs, dst_crs, out_file, resolution): """Dump BC DEM to TIFF """ if not dst_crs: dst_crs = "EPSG:3005" bcdata.get_dem(bounds, out_file=out_file, src_crs=src_crs, dst_crs=dst_crs, resolution=resolution)
[ "def", "dem", "(", "bounds", ",", "src_crs", ",", "dst_crs", ",", "out_file", ",", "resolution", ")", ":", "if", "not", "dst_crs", ":", "dst_crs", "=", "\"EPSG:3005\"", "bcdata", ".", "get_dem", "(", "bounds", ",", "out_file", "=", "out_file", ",", "src_...
Dump BC DEM to TIFF
[ "Dump", "BC", "DEM", "to", "TIFF" ]
de6b5bbc28d85e36613b51461911ee0a72a146c5
https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/cli.py#L143-L148
train
Dump BC DEM to TIFF
smnorris/bcdata
bcdata/cli.py
dump
def dump(dataset, query, out_file, bounds): """Write DataBC features to stdout as GeoJSON feature collection. \b $ bcdata dump bc-airports $ bcdata dump bc-airports --query "AIRPORT_NAME='Victoria Harbour (Shoal Point) Heliport'" $ bcdata dump bc-airports --bounds xmin ymin xmax ymax The...
python
def dump(dataset, query, out_file, bounds): """Write DataBC features to stdout as GeoJSON feature collection. \b $ bcdata dump bc-airports $ bcdata dump bc-airports --query "AIRPORT_NAME='Victoria Harbour (Shoal Point) Heliport'" $ bcdata dump bc-airports --bounds xmin ymin xmax ymax The...
[ "def", "dump", "(", "dataset", ",", "query", ",", "out_file", ",", "bounds", ")", ":", "table", "=", "bcdata", ".", "validate_name", "(", "dataset", ")", "data", "=", "bcdata", ".", "get_data", "(", "table", ",", "query", "=", "query", ",", "bounds", ...
Write DataBC features to stdout as GeoJSON feature collection. \b $ bcdata dump bc-airports $ bcdata dump bc-airports --query "AIRPORT_NAME='Victoria Harbour (Shoal Point) Heliport'" $ bcdata dump bc-airports --bounds xmin ymin xmax ymax The values of --bounds must be in BC Albers. It ...
[ "Write", "DataBC", "features", "to", "stdout", "as", "GeoJSON", "feature", "collection", "." ]
de6b5bbc28d85e36613b51461911ee0a72a146c5
https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/cli.py#L159-L181
train
Dump DataBC features to stdout as GeoJSON feature collection.
smnorris/bcdata
bcdata/cli.py
cat
def cat(dataset, query, bounds, indent, compact, dst_crs, pagesize, sortby): """Write DataBC features to stdout as GeoJSON feature objects. """ # Note that cat does not concatenate! dump_kwds = {"sort_keys": True} if indent: dump_kwds["indent"] = indent if compact: dump_kwds["sep...
python
def cat(dataset, query, bounds, indent, compact, dst_crs, pagesize, sortby): """Write DataBC features to stdout as GeoJSON feature objects. """ # Note that cat does not concatenate! dump_kwds = {"sort_keys": True} if indent: dump_kwds["indent"] = indent if compact: dump_kwds["sep...
[ "def", "cat", "(", "dataset", ",", "query", ",", "bounds", ",", "indent", ",", "compact", ",", "dst_crs", ",", "pagesize", ",", "sortby", ")", ":", "# Note that cat does not concatenate!", "dump_kwds", "=", "{", "\"sort_keys\"", ":", "True", "}", "if", "inde...
Write DataBC features to stdout as GeoJSON feature objects.
[ "Write", "DataBC", "features", "to", "stdout", "as", "GeoJSON", "feature", "objects", "." ]
de6b5bbc28d85e36613b51461911ee0a72a146c5
https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/cli.py#L198-L211
train
Write DataBC features to stdout as GeoJSON feature objects.
smnorris/bcdata
bcdata/cli.py
bc2pg
def bc2pg(dataset, db_url, table, schema, query, append, pagesize, sortby, max_workers): """Download a DataBC WFS layer to postgres - an ogr2ogr wrapper. \b $ bcdata bc2pg bc-airports --db_url postgresql://postgres:postgres@localhost:5432/postgis The default target database can be specified by sett...
python
def bc2pg(dataset, db_url, table, schema, query, append, pagesize, sortby, max_workers): """Download a DataBC WFS layer to postgres - an ogr2ogr wrapper. \b $ bcdata bc2pg bc-airports --db_url postgresql://postgres:postgres@localhost:5432/postgis The default target database can be specified by sett...
[ "def", "bc2pg", "(", "dataset", ",", "db_url", ",", "table", ",", "schema", ",", "query", ",", "append", ",", "pagesize", ",", "sortby", ",", "max_workers", ")", ":", "src", "=", "bcdata", ".", "validate_name", "(", "dataset", ")", "src_schema", ",", "...
Download a DataBC WFS layer to postgres - an ogr2ogr wrapper. \b $ bcdata bc2pg bc-airports --db_url postgresql://postgres:postgres@localhost:5432/postgis The default target database can be specified by setting the $DATABASE_URL environment variable. https://docs.sqlalchemy.org/en/latest/core/e...
[ "Download", "a", "DataBC", "WFS", "layer", "to", "postgres", "-", "an", "ogr2ogr", "wrapper", "." ]
de6b5bbc28d85e36613b51461911ee0a72a146c5
https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/cli.py#L235-L333
train
Download a DataBC WFS layer to postgres
mgoral/subconvert
src/subconvert/parsing/Core.py
SubParser.__parseFormat
def __parseFormat(self, fmt, content, fps = 25): '''Actual parser. Please note that time_to is not required to process as not all subtitles provide it.''' headerFound = False subSection = '' for lineNo, line in enumerate(content): line = self._initialLinePrepare(line...
python
def __parseFormat(self, fmt, content, fps = 25): '''Actual parser. Please note that time_to is not required to process as not all subtitles provide it.''' headerFound = False subSection = '' for lineNo, line in enumerate(content): line = self._initialLinePrepare(line...
[ "def", "__parseFormat", "(", "self", ",", "fmt", ",", "content", ",", "fps", "=", "25", ")", ":", "headerFound", "=", "False", "subSection", "=", "''", "for", "lineNo", ",", "line", "in", "enumerate", "(", "content", ")", ":", "line", "=", "self", "....
Actual parser. Please note that time_to is not required to process as not all subtitles provide it.
[ "Actual", "parser", ".", "Please", "note", "that", "time_to", "is", "not", "required", "to", "process", "as", "not", "all", "subtitles", "provide", "it", "." ]
59701e5e69ef1ca26ce7d1d766c936664aa2cb32
https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/parsing/Core.py#L312-L353
train
Internal method for parsing a format.
mkoura/dump2polarion
dump2polarion/dumper_cli.py
get_args
def get_args(args=None): """Get command line arguments.""" parser = argparse.ArgumentParser(description="dump2polarion") parser.add_argument( "-i", "--input_file", required=True, help="Path to CSV, SQLite or JUnit reports file or importers XML file", ) parser.add_argu...
python
def get_args(args=None): """Get command line arguments.""" parser = argparse.ArgumentParser(description="dump2polarion") parser.add_argument( "-i", "--input_file", required=True, help="Path to CSV, SQLite or JUnit reports file or importers XML file", ) parser.add_argu...
[ "def", "get_args", "(", "args", "=", "None", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"dump2polarion\"", ")", "parser", ".", "add_argument", "(", "\"-i\"", ",", "\"--input_file\"", ",", "required", "=", "True", "...
Get command line arguments.
[ "Get", "command", "line", "arguments", "." ]
f4bd24e9d5070e282aad15f1e8bb514c0525cd37
https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/dumper_cli.py#L26-L61
train
Get command line arguments.
mkoura/dump2polarion
dump2polarion/dumper_cli.py
get_submit_args
def get_submit_args(args): """Gets arguments for the `submit_and_verify` method.""" submit_args = dict( testrun_id=args.testrun_id, user=args.user, password=args.password, no_verify=args.no_verify, verify_timeout=args.verify_timeout, log_file=args.job_log, ...
python
def get_submit_args(args): """Gets arguments for the `submit_and_verify` method.""" submit_args = dict( testrun_id=args.testrun_id, user=args.user, password=args.password, no_verify=args.no_verify, verify_timeout=args.verify_timeout, log_file=args.job_log, ...
[ "def", "get_submit_args", "(", "args", ")", ":", "submit_args", "=", "dict", "(", "testrun_id", "=", "args", ".", "testrun_id", ",", "user", "=", "args", ".", "user", ",", "password", "=", "args", ".", "password", ",", "no_verify", "=", "args", ".", "n...
Gets arguments for the `submit_and_verify` method.
[ "Gets", "arguments", "for", "the", "submit_and_verify", "method", "." ]
f4bd24e9d5070e282aad15f1e8bb514c0525cd37
https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/dumper_cli.py#L64-L76
train
Gets arguments for the submit_and_verify method.
mkoura/dump2polarion
dump2polarion/dumper_cli.py
process_args
def process_args(args): """Processes passed arguments.""" passed_args = args if isinstance(args, argparse.Namespace): passed_args = vars(passed_args) elif hasattr(args, "to_dict"): passed_args = passed_args.to_dict() return Box(passed_args, frozen_box=True, default_box=True)
python
def process_args(args): """Processes passed arguments.""" passed_args = args if isinstance(args, argparse.Namespace): passed_args = vars(passed_args) elif hasattr(args, "to_dict"): passed_args = passed_args.to_dict() return Box(passed_args, frozen_box=True, default_box=True)
[ "def", "process_args", "(", "args", ")", ":", "passed_args", "=", "args", "if", "isinstance", "(", "args", ",", "argparse", ".", "Namespace", ")", ":", "passed_args", "=", "vars", "(", "passed_args", ")", "elif", "hasattr", "(", "args", ",", "\"to_dict\"",...
Processes passed arguments.
[ "Processes", "passed", "arguments", "." ]
f4bd24e9d5070e282aad15f1e8bb514c0525cd37
https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/dumper_cli.py#L79-L87
train
Processes passed arguments.
mkoura/dump2polarion
dump2polarion/dumper_cli.py
submit_if_ready
def submit_if_ready(args, submit_args, config): """Submits the input XML file if it's already in the expected format.""" __, ext = os.path.splitext(args.input_file) if ext.lower() != ".xml": return None with io.open(args.input_file, encoding="utf-8") as input_file: xml = input_file.read...
python
def submit_if_ready(args, submit_args, config): """Submits the input XML file if it's already in the expected format.""" __, ext = os.path.splitext(args.input_file) if ext.lower() != ".xml": return None with io.open(args.input_file, encoding="utf-8") as input_file: xml = input_file.read...
[ "def", "submit_if_ready", "(", "args", ",", "submit_args", ",", "config", ")", ":", "__", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "args", ".", "input_file", ")", "if", "ext", ".", "lower", "(", ")", "!=", "\".xml\"", ":", "return", ...
Submits the input XML file if it's already in the expected format.
[ "Submits", "the", "input", "XML", "file", "if", "it", "s", "already", "in", "the", "expected", "format", "." ]
f4bd24e9d5070e282aad15f1e8bb514c0525cd37
https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/dumper_cli.py#L119-L139
train
Submits the input XML file if it s already in the expected format.
mkoura/dump2polarion
dump2polarion/dumper_cli.py
dumper
def dumper(args, config, transform_func=None): """Dumper main function.""" args = process_args(args) submit_args = get_submit_args(args) submit_outcome = submit_if_ready(args, submit_args, config) if submit_outcome is not None: # submitted, nothing more to do return submit_outcome ...
python
def dumper(args, config, transform_func=None): """Dumper main function.""" args = process_args(args) submit_args = get_submit_args(args) submit_outcome = submit_if_ready(args, submit_args, config) if submit_outcome is not None: # submitted, nothing more to do return submit_outcome ...
[ "def", "dumper", "(", "args", ",", "config", ",", "transform_func", "=", "None", ")", ":", "args", "=", "process_args", "(", "args", ")", "submit_args", "=", "get_submit_args", "(", "args", ")", "submit_outcome", "=", "submit_if_ready", "(", "args", ",", "...
Dumper main function.
[ "Dumper", "main", "function", "." ]
f4bd24e9d5070e282aad15f1e8bb514c0525cd37
https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/dumper_cli.py#L150-L190
train
Dumper main function.
mkoura/dump2polarion
dump2polarion/dumper_cli.py
main
def main(args=None, transform_func=None): """Main function for cli.""" args = get_args(args) utils.init_log(args.log_level) try: config = _get_config(args) except Dump2PolarionException as err: logger.fatal(err) return 1 return dumper(args, config, transform_func=trans...
python
def main(args=None, transform_func=None): """Main function for cli.""" args = get_args(args) utils.init_log(args.log_level) try: config = _get_config(args) except Dump2PolarionException as err: logger.fatal(err) return 1 return dumper(args, config, transform_func=trans...
[ "def", "main", "(", "args", "=", "None", ",", "transform_func", "=", "None", ")", ":", "args", "=", "get_args", "(", "args", ")", "utils", ".", "init_log", "(", "args", ".", "log_level", ")", "try", ":", "config", "=", "_get_config", "(", "args", ")"...
Main function for cli.
[ "Main", "function", "for", "cli", "." ]
f4bd24e9d5070e282aad15f1e8bb514c0525cd37
https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/dumper_cli.py#L193-L205
train
Main function for cli.
carta/ldap_tools
src/ldap_tools/client.py
Client.load_ldap_config
def load_ldap_config(self): # pragma: no cover """Configure LDAP Client settings.""" try: with open('{}/ldap_info.yaml'.format(self.config_dir), 'r') as FILE: config = yaml.load(FILE) self.host = config['server'] self.use...
python
def load_ldap_config(self): # pragma: no cover """Configure LDAP Client settings.""" try: with open('{}/ldap_info.yaml'.format(self.config_dir), 'r') as FILE: config = yaml.load(FILE) self.host = config['server'] self.use...
[ "def", "load_ldap_config", "(", "self", ")", ":", "# pragma: no cover", "try", ":", "with", "open", "(", "'{}/ldap_info.yaml'", ".", "format", "(", "self", ".", "config_dir", ")", ",", "'r'", ")", "as", "FILE", ":", "config", "=", "yaml", ".", "load", "(...
Configure LDAP Client settings.
[ "Configure", "LDAP", "Client", "settings", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/client.py#L24-L38
train
Load LDAP Client settings from a config file.
carta/ldap_tools
src/ldap_tools/client.py
Client.load_ldap_password
def load_ldap_password(self): # pragma: no cover """Import LDAP password from file.""" with open('{}/ldap.secret'.format(self.config_dir), 'r') as FILE: secure_config = FILE.read() self.user_pw = base64.b64decode(secure_config.encode())
python
def load_ldap_password(self): # pragma: no cover """Import LDAP password from file.""" with open('{}/ldap.secret'.format(self.config_dir), 'r') as FILE: secure_config = FILE.read() self.user_pw = base64.b64decode(secure_config.encode())
[ "def", "load_ldap_password", "(", "self", ")", ":", "# pragma: no cover", "with", "open", "(", "'{}/ldap.secret'", ".", "format", "(", "self", ".", "config_dir", ")", ",", "'r'", ")", "as", "FILE", ":", "secure_config", "=", "FILE", ".", "read", "(", ")", ...
Import LDAP password from file.
[ "Import", "LDAP", "password", "from", "file", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/client.py#L40-L44
train
Import LDAP password from file.
carta/ldap_tools
src/ldap_tools/client.py
Client.connection
def connection(self): # pragma: no cover """Establish LDAP connection.""" # self.server allows us to fetch server info # (including LDAP schema list) if we wish to # add this feature later self.server = ldap3.Server(self.host, port=self.port, get_info=ldap3.ALL) self.con...
python
def connection(self): # pragma: no cover """Establish LDAP connection.""" # self.server allows us to fetch server info # (including LDAP schema list) if we wish to # add this feature later self.server = ldap3.Server(self.host, port=self.port, get_info=ldap3.ALL) self.con...
[ "def", "connection", "(", "self", ")", ":", "# pragma: no cover", "# self.server allows us to fetch server info", "# (including LDAP schema list) if we wish to", "# add this feature later", "self", ".", "server", "=", "ldap3", ".", "Server", "(", "self", ".", "host", ",", ...
Establish LDAP connection.
[ "Establish", "LDAP", "connection", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/client.py#L46-L58
train
Establish LDAP connection.
carta/ldap_tools
src/ldap_tools/client.py
Client.add
def add(self, distinguished_name, object_class, attributes): """ Add object to LDAP. Args: distinguished_name: the DN of the LDAP record to be added object_class: The objectClass of the record to be added. This is a list of length >= 1. attrib...
python
def add(self, distinguished_name, object_class, attributes): """ Add object to LDAP. Args: distinguished_name: the DN of the LDAP record to be added object_class: The objectClass of the record to be added. This is a list of length >= 1. attrib...
[ "def", "add", "(", "self", ",", "distinguished_name", ",", "object_class", ",", "attributes", ")", ":", "self", ".", "conn", ".", "add", "(", "distinguished_name", ",", "object_class", ",", "attributes", ")" ]
Add object to LDAP. Args: distinguished_name: the DN of the LDAP record to be added object_class: The objectClass of the record to be added. This is a list of length >= 1. attributes: a dictionary of LDAP attributes to add See ldap_tools.api.g...
[ "Add", "object", "to", "LDAP", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/client.py#L60-L72
train
Adds an object to the LDAP record store.
carta/ldap_tools
src/ldap_tools/client.py
Client.search
def search(self, filter, attributes=None): """Search LDAP for records.""" if attributes is None: attributes = ['*'] if filter is None: filter = ["(objectclass=*)"] # Convert filter list into an LDAP-consumable format filterstr = "(&{})".format(''.join(fi...
python
def search(self, filter, attributes=None): """Search LDAP for records.""" if attributes is None: attributes = ['*'] if filter is None: filter = ["(objectclass=*)"] # Convert filter list into an LDAP-consumable format filterstr = "(&{})".format(''.join(fi...
[ "def", "search", "(", "self", ",", "filter", ",", "attributes", "=", "None", ")", ":", "if", "attributes", "is", "None", ":", "attributes", "=", "[", "'*'", "]", "if", "filter", "is", "None", ":", "filter", "=", "[", "\"(objectclass=*)\"", "]", "# Conv...
Search LDAP for records.
[ "Search", "LDAP", "for", "records", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/client.py#L93-L108
train
Search LDAP for records.