INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Overrides argparse.ArgumentParser.parse_args
Enables '@'-prefixed files to be expanded before arguments are processed
by ArgumentParser.parse_args as usual | def parse_args(self, args=None, namespace=None):
""" Overrides argparse.ArgumentParser.parse_args
Enables '@'-prefixed files to be expanded before arguments are processed
by ArgumentParser.parse_args as usual
"""
self._expand_prefixed_files(args)
return super(CLICommandP... |
Extract the summary from the docstring of the command. | def extract_full_summary_from_signature(operation):
""" Extract the summary from the docstring of the command. """
lines = inspect.getdoc(operation)
regex = r'\s*(:param)\s+(.+?)\s*:(.*)'
summary = ''
if lines:
match = re.search(regex, lines)
summary = lines[:match.regs[0][0]] if mat... |
Extract parameter help from docstring of the command. | def option_descriptions(operation):
""" Extract parameter help from docstring of the command. """
lines = inspect.getdoc(operation)
if not lines:
return {}
param_breaks = ["'''", '"""', ':param', ':type', ':return', ':rtype']
option_descs = {}
lines = lines.splitlines()
index = 0
... |
Extracts basic argument data from an operation's signature and docstring
excluded_params: List of params to ignore and not extract. By default we ignore ['self', 'kwargs']. | def extract_args_from_signature(operation, excluded_params=None):
""" Extracts basic argument data from an operation's signature and docstring
excluded_params: List of params to ignore and not extract. By default we ignore ['self', 'kwargs'].
"""
args = []
try:
# only supported in python... |
Get the runtime information.
:return: Runtime information
:rtype: str | def get_runtime_version(self): # pylint: disable=no-self-use
""" Get the runtime information.
:return: Runtime information
:rtype: str
"""
import platform
version_info = '\n\n'
version_info += 'Python ({}) {}'.format(platform.system(), sys.version)
vers... |
Print version information to the out file. | def show_version(self):
""" Print version information to the out file. """
version_info = self.get_cli_version()
version_info += self.get_runtime_version()
print(version_info, file=self.out_file) |
Unregister a callable that will be called when event is raised.
:param event_name: The name of the event (see knack.events for in-built events)
:type event_name: str
:param handler: The callback that was used to register the event
:type handler: function | def unregister_event(self, event_name, handler):
""" Unregister a callable that will be called when event is raised.
:param event_name: The name of the event (see knack.events for in-built events)
:type event_name: str
:param handler: The callback that was used to register the event
... |
Raise an event. Calls each handler in turn with kwargs
:param event_name: The name of the event to raise
:type event_name: str
:param kwargs: Kwargs to be passed to all event handlers | def raise_event(self, event_name, **kwargs):
""" Raise an event. Calls each handler in turn with kwargs
:param event_name: The name of the event to raise
:type event_name: str
:param kwargs: Kwargs to be passed to all event handlers
"""
handlers = list(self._event_handle... |
The default exception handler | def exception_handler(self, ex): # pylint: disable=no-self-use
""" The default exception handler """
if isinstance(ex, CLIError):
logger.error(ex)
else:
logger.exception(ex)
return 1 |
Invoke a command.
:param args: The arguments that represent the command
:type args: list, tuple
:param initial_invocation_data: Prime the in memory collection of key-value data for this invocation.
:type initial_invocation_data: dict
:param out_file: The file to send output to. ... | def invoke(self, args, initial_invocation_data=None, out_file=None):
""" Invoke a command.
:param args: The arguments that represent the command
:type args: list, tuple
:param initial_invocation_data: Prime the in memory collection of key-value data for this invocation.
:type in... |
Get the logger for a module. If no module name is given, the current CLI logger is returned.
Example:
get_logger(__name__)
:param module_name: The module to get the logger for
:type module_name: str
:return: The logger
:rtype: logger | def get_logger(module_name=None):
""" Get the logger for a module. If no module name is given, the current CLI logger is returned.
Example:
get_logger(__name__)
:param module_name: The module to get the logger for
:type module_name: str
:return: The logger
:rtype: logger
"""
if... |
Configure the loggers with the appropriate log level etc.
:param args: The arguments from the command line
:type args: list | def configure(self, args):
""" Configure the loggers with the appropriate log level etc.
:param args: The arguments from the command line
:type args: list
"""
verbose_level = self._determine_verbose_level(args)
log_level_config = self.console_log_configs[verbose_level]
... |
Get verbose level by reading the arguments. | def _determine_verbose_level(self, args):
""" Get verbose level by reading the arguments. """
verbose_level = 0
for arg in args:
if arg == CLILogging.VERBOSE_FLAG:
verbose_level += 1
elif arg == CLILogging.DEBUG_FLAG:
verbose_level += 2
... |
Creates the argparse choices and type kwargs for a supplied enum type or list of strings | def enum_choice_list(data):
""" Creates the argparse choices and type kwargs for a supplied enum type or list of strings """
# transform enum types, otherwise assume list of string choices
if not data:
return {}
try:
choices = [x.value for x in data]
except AttributeError:
c... |
Add an argument to the argument registry
:param scope: The command level to apply the argument registration (e.g. 'mygroup mycommand')
:type scope: str
:param dest: The parameter/destination that this argument is for
:type dest: str
:param argtype: The argument type for this com... | def register_cli_argument(self, scope, dest, argtype, **kwargs):
""" Add an argument to the argument registry
:param scope: The command level to apply the argument registration (e.g. 'mygroup mycommand')
:type scope: str
:param dest: The parameter/destination that this argument is for
... |
Get the argument for the command after applying the scope hierarchy
:param command: The command that we want the argument for
:type command: str
:param name: The name of the argument
:type name: str
:return: The CLI command after all overrides in the scope hierarchy have been ap... | def get_cli_argument(self, command, name):
""" Get the argument for the command after applying the scope hierarchy
:param command: The command that we want the argument for
:type command: str
:param name: The name of the argument
:type name: str
:return: The CLI command ... |
Register an argument for the given command scope using a knack.arguments.CLIArgumentType
:param argument_dest: The destination argument to add this argument type to
:type argument_dest: str
:param arg_type: Predefined CLIArgumentType definition to register, as modified by any provided kwargs.
... | def argument(self, argument_dest, arg_type=None, **kwargs):
""" Register an argument for the given command scope using a knack.arguments.CLIArgumentType
:param argument_dest: The destination argument to add this argument type to
:type argument_dest: str
:param arg_type: Predefined CLIAr... |
Register a positional argument for the given command scope using a knack.arguments.CLIArgumentType
:param argument_dest: The destination argument to add this argument type to
:type argument_dest: str
:param arg_type: Predefined CLIArgumentType definition to register, as modified by any provided... | def positional(self, argument_dest, arg_type=None, **kwargs):
""" Register a positional argument for the given command scope using a knack.arguments.CLIArgumentType
:param argument_dest: The destination argument to add this argument type to
:type argument_dest: str
:param arg_type: Pred... |
Register an argument with type knack.arguments.ignore_type (hidden/ignored)
:param argument_dest: The destination argument to apply the ignore type to
:type argument_dest: str | def ignore(self, argument_dest, **kwargs):
""" Register an argument with type knack.arguments.ignore_type (hidden/ignored)
:param argument_dest: The destination argument to apply the ignore type to
:type argument_dest: str
"""
self._check_stale()
if not self._applicable(... |
Register extra parameters for the given command. Typically used to augment auto-command built
commands to add more parameters than the specific SDK method introspected.
:param argument_dest: The destination argument to add this argument type to
:type argument_dest: str
:param kwargs: Po... | def extra(self, argument_dest, **kwargs):
"""Register extra parameters for the given command. Typically used to augment auto-command built
commands to add more parameters than the specific SDK method introspected.
:param argument_dest: The destination argument to add this argument type to
... |
Load the arguments for the specified command
:param command: The command to load arguments for
:type command: str | def load_arguments(self, command):
""" Load the arguments for the specified command
:param command: The command to load arguments for
:type command: str
"""
from knack.arguments import ArgumentsContext
self.cli_ctx.raise_event(EVENT_CMDLOADER_LOAD_ARGUMENTS, cmd_tbl=sel... |
Constructs the command object that can then be added to the command table | def create_command(self, name, operation, **kwargs):
""" Constructs the command object that can then be added to the command table """
if not isinstance(operation, six.string_types):
raise ValueError("Operation must be a string. Got '{}'".format(operation))
name = ' '.join(name.spli... |
Load commands into the command table
:param args: List of the arguments from the command line
:type args: list
:return: The ordered command table
:rtype: collections.OrderedDict | def load_command_table(self, args): # pylint: disable=unused-argument
""" Load commands into the command table
:param args: List of the arguments from the command line
:type args: list
:return: The ordered command table
:rtype: collections.OrderedDict
"""
self.c... |
Import and load the operation handler | def _get_op_handler(operation):
""" Import and load the operation handler """
try:
mod_to_import, attr_path = operation.split('#')
op = import_module(mod_to_import)
for part in attr_path.split('.'):
op = getattr(op, part)
if isinstance(op, ... |
Convert an object to a dictionary. Use 'post_processor(original_obj, dictionary)' to update the
dictionary in the process | def todict(obj, post_processor=None): # pylint: disable=too-many-return-statements
"""
Convert an object to a dictionary. Use 'post_processor(original_obj, dictionary)' to update the
dictionary in the process
"""
if isinstance(obj, dict):
result = {k: todict(v, post_processor) for (k, v) in... |
Register a command into the command table
:param name: The name of the command
:type name: str
:param handler_name: The name of the handler that will be applied to the operations template
:type handler_name: str
:param kwargs: Kwargs to apply to the command.
... | def command(self, name, handler_name, **kwargs):
""" Register a command into the command table
:param name: The name of the command
:type name: str
:param handler_name: The name of the handler that will be applied to the operations template
:type handler_name: str
:param... |
Rudimentary parsing to get the command | def _rudimentary_get_command(self, args):
""" Rudimentary parsing to get the command """
nouns = []
command_names = self.commands_loader.command_table.keys()
for arg in args:
if arg and arg[0] != '-':
nouns.append(arg)
else:
break
... |
Executes the command invocation
:param args: The command arguments for this invocation
:type args: list
:return: The command result
:rtype: knack.util.CommandResultItem | def execute(self, args):
""" Executes the command invocation
:param args: The command arguments for this invocation
:type args: list
:return: The command result
:rtype: knack.util.CommandResultItem
"""
import colorama
self.cli_ctx.raise_event(EVENT_INVOK... |
Get the args that will be used to tab completion if completion is active. | def get_completion_args(self, is_completion=False, comp_line=None): # pylint: disable=no-self-use
""" Get the args that will be used to tab completion if completion is active. """
is_completion = is_completion or os.environ.get(ARGCOMPLETE_ENV_NAME)
comp_line = comp_line or os.environ.get('COMP... |
Produces the output using the command result.
The method does not return a result as the output is written straight to the output file.
:param obj: The command result
:type obj: knack.util.CommandResultItem
:param formatter: The formatter we should use for the command result
... | def out(self, obj, formatter=None, out_file=None): # pylint: disable=no-self-use
""" Produces the output using the command result.
The method does not return a result as the output is written straight to the output file.
:param obj: The command result
:type obj: knack.util.CommandR... |
Updates the authenticating user's current status and attaches media
for upload. In other words, it creates a Tweet with a picture attached.
Docs:
https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update_with_media | def update_status_with_media(self, **params): # pragma: no cover
"""Updates the authenticating user's current status and attaches media
for upload. In other words, it creates a Tweet with a picture attached.
Docs:
https://developer.twitter.com/en/docs/tweets/post-and-engage/api-referen... |
Uploads media file to Twitter servers. The file will be available to be attached
to a status for 60 minutes. To attach to a update, pass a list of returned media ids
to the :meth:`update_status` method using the ``media_ids`` param.
Docs:
https://developer.twitter.com/en/docs/media/uplo... | def upload_media(self, **params):
"""Uploads media file to Twitter servers. The file will be available to be attached
to a status for 60 minutes. To attach to a update, pass a list of returned media ids
to the :meth:`update_status` method using the ``media_ids`` param.
Docs:
htt... |
Adds metadata to a media element, such as image descriptions for visually impaired.
Docs:
https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-metadata-create | def create_metadata(self, **params):
""" Adds metadata to a media element, such as image descriptions for visually impaired.
Docs:
https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-metadata-create
"""
params = json.dumps(params)
return se... |
Uploads video file to Twitter servers in chunks. The file will be available to be attached
to a status for 60 minutes. To attach to a update, pass a list of returned media ids
to the :meth:`update_status` method using the ``media_ids`` param.
Upload happens in 3 stages:
- INIT call with... | def upload_video(self, media, media_type, media_category=None, size=None, check_progress=False):
"""Uploads video file to Twitter servers in chunks. The file will be available to be attached
to a status for 60 minutes. To attach to a update, pass a list of returned media ids
to the :meth:`update... |
Sets one or more hex values that control the color scheme of the
authenticating user's profile page on twitter.com.
This method is deprecated, replaced by the ``profile_link_color``
parameter to :meth:`update_profile`.
Docs:
https://developer.twitter.com/en/docs/accounts-and-us... | def update_profile_colors(self, **params): # pragma: no cover
"""Sets one or more hex values that control the color scheme of the
authenticating user's profile page on twitter.com.
This method is deprecated, replaced by the ``profile_link_color``
parameter to :meth:`update_profile`.
... |
Internal request method | def _request(self, url, method='GET', params=None, api_call=None, json_encoded=False):
"""Internal request method"""
method = method.lower()
params = params or {}
func = getattr(self.client, method)
if isinstance(params, dict) and json_encoded is False:
params, files... |
Parse and return the first error message | def _get_error_message(self, response):
"""Parse and return the first error message"""
error_message = 'An error occurred processing your request.'
try:
content = response.json()
# {"errors":[{"code":34,"message":"Sorry,
# that page does not exist"}]}
... |
Return dict of response received from Twitter's API
:param endpoint: (required) Full url or Twitter API endpoint
(e.g. search/tweets)
:type endpoint: string
:param method: (optional) Method of accessing data, either
GET, POST or DELETE. (default G... | def request(self, endpoint, method='GET', params=None, version='1.1', json_encoded=False):
"""Return dict of response received from Twitter's API
:param endpoint: (required) Full url or Twitter API endpoint
(e.g. search/tweets)
:type endpoint: string
:param meth... |
Shortcut for GET requests via :class:`request` | def get(self, endpoint, params=None, version='1.1'):
"""Shortcut for GET requests via :class:`request`"""
return self.request(endpoint, params=params, version=version) |
Shortcut for POST requests via :class:`request` | def post(self, endpoint, params=None, version='1.1', json_encoded=False):
"""Shortcut for POST requests via :class:`request`"""
return self.request(endpoint, 'POST', params=params, version=version, json_encoded=json_encoded) |
Shortcut for delete requests via :class:`request` | def delete(self, endpoint, params=None, version='1.1', json_encoded=False):
"""Shortcut for delete requests via :class:`request`"""
return self.request(endpoint, 'DELETE', params=params, version=version, json_encoded=json_encoded) |
Returns a specific header from the last API call
This will return None if the header is not present
:param header: (required) The name of the header you want to get
the value of
Most useful for the following header information:
x-rate-limit-limit,
... | def get_lastfunction_header(self, header, default_return_value=None):
"""Returns a specific header from the last API call
This will return None if the header is not present
:param header: (required) The name of the header you want to get
the value of
Most useful ... |
Returns a dict including an authorization URL, ``auth_url``, to
direct a user to
:param callback_url: (optional) Url the user is returned to after
they authorize your app (web clients only)
:param force_login: (optional) Forces the user to enter their
... | def get_authentication_tokens(self, callback_url=None, force_login=False,
screen_name=''):
"""Returns a dict including an authorization URL, ``auth_url``, to
direct a user to
:param callback_url: (optional) Url the user is returned to after
... |
Returns a dict of authorized tokens after they go through the
:class:`get_authentication_tokens` phase.
:param oauth_verifier: (required) The oauth_verifier (or a.k.a PIN
for non web apps) retrieved from the callback url querystring
:rtype: dict | def get_authorized_tokens(self, oauth_verifier):
"""Returns a dict of authorized tokens after they go through the
:class:`get_authentication_tokens` phase.
:param oauth_verifier: (required) The oauth_verifier (or a.k.a PIN
for non web apps) retrieved from the callback url querystring
... |
Returns an OAuth 2 access token to make OAuth 2 authenticated
read-only calls.
:rtype: string | def obtain_access_token(self):
"""Returns an OAuth 2 access token to make OAuth 2 authenticated
read-only calls.
:rtype: string
"""
if self.oauth_version != 2:
raise TwythonError('This method can only be called when your \
OAuth version... |
Construct a Twitter API url, encoded, with parameters
:param api_url: URL of the Twitter API endpoint you are attempting
to construct
:param \*\*params: Parameters that are accepted by Twitter for the
endpoint you're requesting
:rtype: string
Usage::
>>> from... | def construct_api_url(api_url, **params):
"""Construct a Twitter API url, encoded, with parameters
:param api_url: URL of the Twitter API endpoint you are attempting
to construct
:param \*\*params: Parameters that are accepted by Twitter for the
endpoint you're requesting
... |
Returns a generator for results that match a specified query.
:param function: Instance of a Twython function
(Twython.get_home_timeline, Twython.search)
:param \*\*params: Extra parameters to send with your request
(usually parameters accepted by the Twitter API endpoint)
:rtyp... | def cursor(self, function, return_pages=False, **params):
"""Returns a generator for results that match a specified query.
:param function: Instance of a Twython function
(Twython.get_home_timeline, Twython.search)
:param \*\*params: Extra parameters to send with your request
(u... |
Stream user
Accepted params found at:
https://dev.twitter.com/docs/api/1.1/get/user | def user(self, **params):
"""Stream user
Accepted params found at:
https://dev.twitter.com/docs/api/1.1/get/user
"""
url = 'https://userstream.twitter.com/%s/user.json' \
% self.streamer.api_version
self.streamer._request(url, params=params) |
Stream site
Accepted params found at:
https://dev.twitter.com/docs/api/1.1/get/site | def site(self, **params):
"""Stream site
Accepted params found at:
https://dev.twitter.com/docs/api/1.1/get/site
"""
url = 'https://sitestream.twitter.com/%s/site.json' \
% self.streamer.api_version
self.streamer._request(url, params=params) |
Stream statuses/filter
:param \*\*params: Parameters to send with your stream request
Accepted params found at:
https://developer.twitter.com/en/docs/tweets/filter-realtime/api-reference/post-statuses-filter | def filter(self, **params):
"""Stream statuses/filter
:param \*\*params: Parameters to send with your stream request
Accepted params found at:
https://developer.twitter.com/en/docs/tweets/filter-realtime/api-reference/post-statuses-filter
"""
url = 'https://stream.twitt... |
Stream statuses/sample
:param \*\*params: Parameters to send with your stream request
Accepted params found at:
https://developer.twitter.com/en/docs/tweets/sample-realtime/api-reference/get-statuses-sample | def sample(self, **params):
"""Stream statuses/sample
:param \*\*params: Parameters to send with your stream request
Accepted params found at:
https://developer.twitter.com/en/docs/tweets/sample-realtime/api-reference/get-statuses-sample
"""
url = 'https://stream.twitte... |
Stream statuses/firehose
:param \*\*params: Parameters to send with your stream request
Accepted params found at:
https://dev.twitter.com/docs/api/1.1/get/statuses/firehose | def firehose(self, **params):
"""Stream statuses/firehose
:param \*\*params: Parameters to send with your stream request
Accepted params found at:
https://dev.twitter.com/docs/api/1.1/get/statuses/firehose
"""
url = 'https://stream.twitter.com/%s/statuses/firehose.json'... |
Stream statuses/filter with dynamic parameters | def dynamic_filter(self):
"""Stream statuses/filter with dynamic parameters"""
url = 'https://stream.twitter.com/%s/statuses/filter.json' \
% self.streamer.api_version
self.streamer._request(url, 'POST', params=self.params) |
Internal stream request handling | def _request(self, url, method='GET', params=None):
"""Internal stream request handling"""
self.connected = True
retry_counter = 0
method = method.lower()
func = getattr(self.client, method)
params, _ = _transparent_params(params)
def _send(retry_counter):
... |
Sort algorithm implementations by speed. | def optimize(self):
"""Sort algorithm implementations by speed.
"""
# load benchmarks results
with open(LIBRARIES_FILE, 'r') as f:
libs_data = json.load(f)
# optimize
for alg, libs_names in libs_data.items():
libs = self.get_libs(alg)
i... |
Clone library manager prototype | def clone(self):
"""Clone library manager prototype
"""
obj = self.__class__()
obj.libs = deepcopy(self.libs)
return obj |
https://github.com/chrislit/abydos/blob/master/abydos/distance/_lcsseq.py
http://www.dis.uniroma1.it/~bonifaci/algo/LCSSEQ.py
http://rosettacode.org/wiki/Longest_common_subsequence#Dynamic_Programming_8 | def _dynamic(self, seq1, seq2):
"""
https://github.com/chrislit/abydos/blob/master/abydos/distance/_lcsseq.py
http://www.dis.uniroma1.it/~bonifaci/algo/LCSSEQ.py
http://rosettacode.org/wiki/Longest_common_subsequence#Dynamic_Programming_8
"""
if numpy:
lengths... |
Get distance from 0 to 1 | def normalized_distance(self, *sequences):
"""Get distance from 0 to 1
"""
return float(self.distance(*sequences)) / self.maximum(*sequences) |
Try to get answer from known external libraries. | def external_answer(self, *sequences):
"""Try to get answer from known external libraries.
"""
# if this feature disabled
if not getattr(self, 'external', False):
return
# all external libs doesn't support test_func
if hasattr(self, 'test_func') and self.test_... |
Return True if all sequences are equal. | def _ident(*elements):
"""Return True if all sequences are equal.
"""
try:
# for hashable elements
return len(set(elements)) == 1
except TypeError:
# for unhashable elements
for e1, e2 in zip(elements, elements[1:]):
if e1 !... |
Prepare sequences.
qval=None: split text by words
qval=1: do not split sequences. For text this is mean comparing by letters.
qval>1: split sequences by q-grams | def _get_sequences(self, *sequences):
"""Prepare sequences.
qval=None: split text by words
qval=1: do not split sequences. For text this is mean comparing by letters.
qval>1: split sequences by q-grams
"""
# by words
if not self.qval:
return [s.split(... |
Prepare sequences and convert it to Counters. | def _get_counters(self, *sequences):
"""Prepare sequences and convert it to Counters.
"""
# already Counters
if all(isinstance(s, Counter) for s in sequences):
return sequences
return [Counter(s) for s in self._get_sequences(*sequences)] |
Return all elements count from Counter | def _count_counters(self, counter):
"""Return all elements count from Counter
"""
if getattr(self, 'as_set', False):
return len(set(counter))
else:
return sum(counter.values()) |
source:
https://github.com/jamesturk/jellyfish/blob/master/jellyfish/_jellyfish.py#L18 | def _cicled(self, s1, s2):
"""
source:
https://github.com/jamesturk/jellyfish/blob/master/jellyfish/_jellyfish.py#L18
"""
rows = len(s1) + 1
cols = len(s2) + 1
prev = None
if numpy:
cur = numpy.arange(cols)
else:
cur = range... |
https://github.com/gw-c/arith/blob/master/arith.py | def _make_probs(self, *sequences):
"""
https://github.com/gw-c/arith/blob/master/arith.py
"""
sequences = self._get_counters(*sequences)
counts = self._sum_counters(*sequences)
if self.terminator is not None:
counts[self.terminator] = 1
total_letters =... |
gpp -- model for the graph partitioning problem
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
Returns a model, ready to be solved. | def gpp(V,E):
"""gpp -- model for the graph partitioning problem
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
Returns a model, ready to be solved.
"""
model = Model("gpp")
x = {}
y = {}
for i in V:
x[i] = model.addVar(vtype=... |
gpp -- model for the graph partitioning problem in soco
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
Returns a model, ready to be solved. | def gpp_soco(V,E):
"""gpp -- model for the graph partitioning problem in soco
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
Returns a model, ready to be solved.
"""
model = Model("gpp model -- soco")
x,s,z = {},{},{}
for i in V:
... |
make_data: prepare data for a random graph
Parameters:
- n: number of vertices
- prob: probability of existence of an edge, for each pair of vertices
Returns a tuple with a list of vertices and a list edges. | def make_data(n,prob):
"""make_data: prepare data for a random graph
Parameters:
- n: number of vertices
- prob: probability of existence of an edge, for each pair of vertices
Returns a tuple with a list of vertices and a list edges.
"""
V = range(1,n+1)
E = [(i,j) for i in V ... |
maxflow: maximize flow from source to sink, taking into account arc capacities M
Parameters:
- V: set of vertices
- M[i,j]: dictionary or capacity for arcs (i,j)
- source: flow origin
- sink: flow target
Returns a model, ready to be solved. | def maxflow(V,M,source,sink):
"""maxflow: maximize flow from source to sink, taking into account arc capacities M
Parameters:
- V: set of vertices
- M[i,j]: dictionary or capacity for arcs (i,j)
- source: flow origin
- sink: flow target
Returns a model, ready to be solved.
... |
solve_tsp -- solve the traveling salesman problem
- start with assignment model
- check flow from a source to every other node;
- if no flow, a sub-cycle has been found --> add cut
- otherwise, the solution is optimal
Parameters:
- V: set/list of nodes in the graph
... | def solve_tsp(V,c):
"""solve_tsp -- solve the traveling salesman problem
- start with assignment model
- check flow from a source to every other node;
- if no flow, a sub-cycle has been found --> add cut
- otherwise, the solution is optimal
Parameters:
- V: set/list of ... |
AND constraint | def and_constraint(v=1, sense="minimize"):
""" AND constraint """
assert v in [0,1], "v must be 0 or 1 instead of %s" % v.__repr__()
model, x, y, z = _init()
r = model.addVar("r", "B")
model.addConsAnd([x,y,z], r)
model.addCons(x==v)
model.setObjective(r, sense=sense)
_optimize("AND", mo... |
OR constraint | def or_constraint(v=0, sense="maximize"):
""" OR constraint"""
assert v in [0,1], "v must be 0 or 1 instead of %s" % v.__repr__()
model, x, y, z = _init()
r = model.addVar("r", "B")
model.addConsOr([x,y,z], r)
model.addCons(x==v)
model.setObjective(r, sense=sense)
_optimize("OR", model) |
XOR (r as boolean) standard constraint | def xors_constraint(v=1):
""" XOR (r as boolean) standard constraint"""
assert v in [0,1], "v must be 0 or 1 instead of %s" % v.__repr__()
model, x, y, z = _init()
r = True
model.addConsXor([x,y,z], r)
model.addCons(x==v)
_optimize("Standard XOR (as boolean)", model) |
XOR (r as variable) custom constraint | def xorc_constraint(v=0, sense="maximize"):
""" XOR (r as variable) custom constraint"""
assert v in [0,1], "v must be 0 or 1 instead of %s" % v.__repr__()
model, x, y, z = _init()
r = model.addVar("r", "B")
n = model.addVar("n", "I") # auxiliary
model.addCons(r+quicksum([x,y,z]) == 2*n)
mod... |
gpp -- model for the graph partitioning problem
Parameters:
- n: number of jobs
- m: number of machines
- p[i,j]: processing time of job i on machine j
Returns a model, ready to be solved. | def permutation_flow_shop(n,m,p):
"""gpp -- model for the graph partitioning problem
Parameters:
- n: number of jobs
- m: number of machines
- p[i,j]: processing time of job i on machine j
Returns a model, ready to be solved.
"""
model = Model("permutation flow shop")
x,... |
make_data: prepare matrix of m times n random processing times | def make_data(n,m):
"""make_data: prepare matrix of m times n random processing times"""
p = {}
for i in range(1,m+1):
for j in range(1,n+1):
p[i,j] = random.randint(1,10)
return p |
creates example data set | def example():
"""creates example data set"""
proc = [[2,3,1],[4,2,3],[1,4,1]]
p = {}
for i in range(3):
for j in range(3):
p[i+1,j+1] = proc[j][i]
return p |
flp_nonlinear_soco -- use
Parameters:
- I: set of customers
- J: set of facilities
- d[i]: demand for product i
- M[j]: capacity of facility j
- f[j]: fixed cost for using a facility in point j
- c[i,j]: unit cost of servicing demand point i from facility j
Retur... | def flp_nonlinear_soco(I,J,d,M,f,c):
"""flp_nonlinear_soco -- use
Parameters:
- I: set of customers
- J: set of facilities
- d[i]: demand for product i
- M[j]: capacity of facility j
- f[j]: fixed cost for using a facility in point j
- c[i,j]: unit cost of servic... |
flp_nonlinear_mselect -- use multiple selection model
Parameters:
- I: set of customers
- J: set of facilities
- d[i]: demand for customer i
- M[j]: capacity of facility j
- f[j]: fixed cost for using a facility in point j
- c[i,j]: unit cost of servicing demand poin... | def flp_nonlinear_mselect(I,J,d,M,f,c,K):
"""flp_nonlinear_mselect -- use multiple selection model
Parameters:
- I: set of customers
- J: set of facilities
- d[i]: demand for customer i
- M[j]: capacity of facility j
- f[j]: fixed cost for using a facility in point j
... |
cost: fuel cost based on "standard" parameters
(with valve-point loading effect) | def cost(a,b,c,e,f,p_min,p):
"""cost: fuel cost based on "standard" parameters
(with valve-point loading effect)
"""
return a + b*p + c*p*p + abs(e*math.sin(f*(p_min-p))) |
lower_brkpts: lower approximation of the cost function
Parameters:
- a,...,p_max: cost parameters
- n: number of breakpoints' intervals to insert between valve points
Returns: list of breakpoints in the form [(x0,y0),...,(xK,yK)] | def lower_brkpts(a,b,c,e,f,p_min,p_max,n):
"""lower_brkpts: lower approximation of the cost function
Parameters:
- a,...,p_max: cost parameters
- n: number of breakpoints' intervals to insert between valve points
Returns: list of breakpoints in the form [(x0,y0),...,(xK,yK)]
"""
EPS ... |
eld -- economic load dispatching in electricity generation
Parameters:
- U: set of generators (units)
- p_min[u]: minimum operating power for unit u
- p_max[u]: maximum operating power for unit u
- d: demand
- brk[k]: (x,y) coordinates of breakpoint k, k=0,...,K
Returns a... | def eld_complete(U,p_min,p_max,d,brk):
"""eld -- economic load dispatching in electricity generation
Parameters:
- U: set of generators (units)
- p_min[u]: minimum operating power for unit u
- p_max[u]: maximum operating power for unit u
- d: demand
- brk[k]: (x,y) coordi... |
eld -- economic load dispatching in electricity generation
Parameters:
- U: set of generators (units)
- p_min[u]: minimum operating power for unit u
- p_max[u]: maximum operating power for unit u
- d: demand
- brk[u][k]: (x,y) coordinates of breakpoint k, k=0,...,K for unit u... | def eld_another(U,p_min,p_max,d,brk):
"""eld -- economic load dispatching in electricity generation
Parameters:
- U: set of generators (units)
- p_min[u]: minimum operating power for unit u
- p_max[u]: maximum operating power for unit u
- d: demand
- brk[u][k]: (x,y) coor... |
mtz: Miller-Tucker-Zemlin's model for the (asymmetric) traveling salesman problem
(potential formulation)
Parameters:
- n: number of nodes
- c[i,j]: cost for traversing arc (i,j)
Returns a model, ready to be solved. | def mtz(n,c):
"""mtz: Miller-Tucker-Zemlin's model for the (asymmetric) traveling salesman problem
(potential formulation)
Parameters:
- n: number of nodes
- c[i,j]: cost for traversing arc (i,j)
Returns a model, ready to be solved.
"""
model = Model("atsp - mtz")
x,u = {},... |
mctransp -- model for solving the Multi-commodity Transportation Problem
Parameters:
- I: set of customers
- J: set of facilities
- K: set of commodities
- c[i,j,k]: unit transportation cost on arc (i,j) for commodity k
- d[i][k]: demand for commodity k at node i
- M[... | def mctransp(I,J,K,c,d,M):
"""mctransp -- model for solving the Multi-commodity Transportation Problem
Parameters:
- I: set of customers
- J: set of facilities
- K: set of commodities
- c[i,j,k]: unit transportation cost on arc (i,j) for commodity k
- d[i][k]: demand for ... |
mcf: multi-commodity flow formulation for the (asymmetric) traveling salesman problem
Parameters:
- n: number of nodes
- c[i,j]: cost for traversing arc (i,j)
Returns a model, ready to be solved. | def mcf(n,c):
"""mcf: multi-commodity flow formulation for the (asymmetric) traveling salesman problem
Parameters:
- n: number of nodes
- c[i,j]: cost for traversing arc (i,j)
Returns a model, ready to be solved.
"""
model = Model("mcf")
x,f = {},{}
for i in range(1,n+1):
... |
sequence: make a list of cities to visit, from set of arcs | def sequence(arcs):
"""sequence: make a list of cities to visit, from set of arcs"""
succ = {}
for (i,j) in arcs:
succ[i] = j
curr = 1 # first node being visited
sol = [curr]
for i in range(len(arcs)-2):
curr = succ[curr]
sol.append(curr)
return sol |
diet -- model for the modern diet problem
Parameters:
- F: set of foods
- N: set of nutrients
- a[i]: minimum intake of nutrient i
- b[i]: maximum intake of nutrient i
- c[j]: cost of food j
- d[j][i]: amount of nutrient i in food j
Returns a model, ready to be so... | def diet(F,N,a,b,c,d):
"""diet -- model for the modern diet problem
Parameters:
- F: set of foods
- N: set of nutrients
- a[i]: minimum intake of nutrient i
- b[i]: maximum intake of nutrient i
- c[j]: cost of food j
- d[j][i]: amount of nutrient i in food j
R... |
make_inst: prepare data for the diet model | def make_inst():
"""make_inst: prepare data for the diet model"""
F,c,d = multidict({ # cost # composition
"QPounder" : [ 1.84, {"Cal":510, "Carbo":34, "Protein":28,
"VitA":15, "VitC": 6, "Calc":30, "Iron":20}],
"McLean" : [ 2.19, {"Cal":370, "Carbo":35,... |
sils -- LP lotsizing for the single item lot sizing problem
Parameters:
- T: number of periods
- P: set of products
- f[t]: set-up costs (on period t)
- c[t]: variable costs
- d[t]: demand values
- h[t]: holding costs
Returns a model, ready to be solved. | def sils(T,f,c,d,h):
"""sils -- LP lotsizing for the single item lot sizing problem
Parameters:
- T: number of periods
- P: set of products
- f[t]: set-up costs (on period t)
- c[t]: variable costs
- d[t]: demand values
- h[t]: holding costs
Returns a model, r... |
solve_sils -- solve the lot sizing problem with cutting planes
- start with a relaxed model
- used lazy constraints to elimitate fractional setup variables with cutting planes
Parameters:
- T: number of periods
- P: set of products
- f[t]: set-up costs (on period t)
- c... | def sils_cut(T,f,c,d,h, conshdlr):
"""solve_sils -- solve the lot sizing problem with cutting planes
- start with a relaxed model
- used lazy constraints to elimitate fractional setup variables with cutting planes
Parameters:
- T: number of periods
- P: set of products
- f[... |
mk_example: book example for the single item lot sizing | def mk_example():
"""mk_example: book example for the single item lot sizing"""
T = 5
_,f,c,d,h = multidict({
1 : [3,1,5,1],
2 : [3,1,7,1],
3 : [3,3,3,1],
4 : [3,3,6,1],
5 : [3,3,4,1],
})
return T,f,c,d,h |
mctransp -- model for solving the Multi-commodity Transportation Problem
Parameters:
- I: set of customers
- J: set of facilities
- K: set of commodities
- c[i,j,k]: unit transportation cost on arc (i,j) for commodity k
- d[i][k]: demand for commodity k at node i
- M[... | def mctransp(I,J,K,c,d,M):
"""mctransp -- model for solving the Multi-commodity Transportation Problem
Parameters:
- I: set of customers
- J: set of facilities
- K: set of commodities
- c[i,j,k]: unit transportation cost on arc (i,j) for commodity k
- d[i][k]: demand for ... |
solveCuttingStock: use column generation (Gilmore-Gomory approach).
Parameters:
- w: list of item's widths
- q: number of items of a width
- B: bin/roll capacity
Returns a solution: list of lists, each of which with the cuts of a roll. | def solveCuttingStock(w,q,B):
"""solveCuttingStock: use column generation (Gilmore-Gomory approach).
Parameters:
- w: list of item's widths
- q: number of items of a width
- B: bin/roll capacity
Returns a solution: list of lists, each of which with the cuts of a roll.
"""
t =... |
mkCuttingStock: convert a bin packing instance into cutting stock format | def mkCuttingStock(s):
"""mkCuttingStock: convert a bin packing instance into cutting stock format"""
w,q = [],[] # list of different widths (sizes) of items, their quantities
for item in sorted(s):
if w == [] or item != w[-1]:
w.append(item)
q.append(1)
else:
... |
mkBinPacking: convert a cutting stock instance into bin packing format | def mkBinPacking(w,q):
"""mkBinPacking: convert a cutting stock instance into bin packing format"""
s = []
for j in range(len(w)):
for i in range(q[j]):
s.append(w[j])
return s |
transp -- model for solving the transportation problem
Parameters:
I - set of customers
J - set of facilities
c[i,j] - unit transportation cost on arc (i,j)
d[i] - demand at node i
M[j] - capacity
Returns a model, ready to be solved. | def transp(I,J,c,d,M):
"""transp -- model for solving the transportation problem
Parameters:
I - set of customers
J - set of facilities
c[i,j] - unit transportation cost on arc (i,j)
d[i] - demand at node i
M[j] - capacity
Returns a model, ready to be solved.
"""
... |
creates example data set 1 | def make_inst1():
"""creates example data set 1"""
I,d = multidict({1:80, 2:270, 3:250 , 4:160, 5:180}) # demand
J,M = multidict({1:500, 2:500, 3:500}) # capacity
c = {(1,1):4, (1,2):6, (1,3):9, # cost
(2,1):5, (2,2):4, (2,3):7,
(3,1):6, (3,2):3, (3,3):... |
creates example data set 2 | def make_inst2():
"""creates example data set 2"""
I,d = multidict({1:45, 2:20, 3:30 , 4:30}) # demand
J,M = multidict({1:35, 2:50, 3:40}) # capacity
c = {(1,1):8, (1,2):9, (1,3):14 , # {(customer,factory) : cost<float>}
(2,1):6, (2,2):12, (2,3):9 ,
(3,1):10, (... |
Prints if a value is even/odd/neither per each value in a example list
This example is made for newcomers and motivated by:
- modulus is unsupported for pyscipopt.scip.Variable and int
- variables are non-integer by default
Based on this: #172#issuecomment-394644046
Args:
number: value whi... | def parity(number):
"""
Prints if a value is even/odd/neither per each value in a example list
This example is made for newcomers and motivated by:
- modulus is unsupported for pyscipopt.scip.Variable and int
- variables are non-integer by default
Based on this: #172#issuecomment-394644046
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.