INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
An exception occurred in the streaming thread
def on_exception(self, exception): """An exception occurred in the streaming thread""" logger.error('Exception from stream!', exc_info=True) self.streaming_exception = exception
Checks if the list of tracked terms has changed. Returns True if changed otherwise False.
def check(self): """ Checks if the list of tracked terms has changed. Returns True if changed, otherwise False. """ new_tracking_terms = self.update_tracking_terms() terms_changed = False # any deleted terms? if self._tracking_terms_set > new_tracking_t...
Terms must be one - per - line. Blank lines will be skipped.
def update_tracking_terms(self): """ Terms must be one-per-line. Blank lines will be skipped. """ import codecs with codecs.open(self.filename,"r", encoding='utf8') as input: # read all the lines lines = input.readlines() # build a set...
Interrupt running process and provide a python prompt for interactive debugging.
def launch_debugger(frame, stream=None): """ Interrupt running process, and provide a python prompt for interactive debugging. """ d = {'_frame': frame} # Allow access to frame object. d.update(frame.f_globals) # Unless shadowed by global d.update(frame.f_locals) import code, traceba...
Break into a debugger if receives the SIGUSR1 signal
def set_debug_listener(stream): """Break into a debugger if receives the SIGUSR1 signal""" def debugger(sig, frame): launch_debugger(frame, stream) if hasattr(signal, 'SIGUSR1'): signal.signal(signal.SIGUSR1, debugger) else: logger.warn("Cannot set SIGUSR1 signal for debug mode...
Die on SIGTERM or SIGINT
def set_terminate_listeners(stream): """Die on SIGTERM or SIGINT""" def stop(signum, frame): terminate(stream.listener) # Installs signal handlers for handling SIGINT and SIGTERM # gracefully. signal.signal(signal.SIGINT, stop) signal.signal(signal.SIGTERM, stop)
Make a tweepy auth object
def get_tweepy_auth(twitter_api_key, twitter_api_secret, twitter_access_token, twitter_access_token_secret): """Make a tweepy auth object""" auth = tweepy.OAuthHandler(twitter_api_key, twitter_api_secret) auth.set_access_token(twitter_access_token,...
Create the listener that prints tweets
def construct_listener(outfile=None): """Create the listener that prints tweets""" if outfile is not None: if os.path.exists(outfile): raise IOError("File %s already exists" % outfile) outfile = open(outfile, 'wb') return PrintingListener(out=outfile)
Start and maintain the streaming connection...
def begin_stream_loop(stream, poll_interval): """Start and maintain the streaming connection...""" while should_continue(): try: stream.start_polling(poll_interval) except Exception as e: # Infinite restart logger.error("Exception while polling. Restarting in ...
Start the stream.
def start(track_file, twitter_api_key, twitter_api_secret, twitter_access_token, twitter_access_token_secret, poll_interval=15, unfiltered=False, languages=None, debug=False, outfile=None): """Start the stream.""" listener...
Print out some tweets
def on_status(self, status): """Print out some tweets""" self.out.write(json.dumps(status)) self.out.write(os.linesep) self.received += 1 return not self.terminate
Print out the current tweet rate and reset the counter
def print_status(self): """Print out the current tweet rate and reset the counter""" tweets = self.received now = time.time() diff = now - self.since self.since = now self.received = 0 if diff > 0: logger.info("Receiving tweets at %s tps", tweets / dif...
Start polling for term updates and streaming.
def start_polling(self, interval): """ Start polling for term updates and streaming. """ interval = float(interval) self.polling = True # clear the stored list of terms - we aren't tracking any self.term_checker.reset() logger.info("Starting polling for...
Restarts the stream with the current list of tracking terms.
def update_stream(self): """ Restarts the stream with the current list of tracking terms. """ need_to_restart = False # If we think we are running, but something has gone wrong in the streaming thread # Restart it. if self.stream is not None and not self.stream....
Starts a stream with teh current tracking terms
def start_stream(self): """Starts a stream with teh current tracking terms""" tracking_terms = self.term_checker.tracking_terms() if len(tracking_terms) > 0 or self.unfiltered: # we have terms to track, so build a new stream self.stream = tweepy.Stream(self.auth, self.l...
Stops the current stream. Blocks until this is done.
def stop_stream(self): """ Stops the current stream. Blocks until this is done. """ if self.stream is not None: # There is a streaming thread logger.warning("Stopping twitter stream...") self.stream.disconnect() self.stream = None ...
Apply the local presentation logic to the fetched data.
def enrich(self, tweet): """ Apply the local presentation logic to the fetched data.""" tweet = urlize_tweet(expand_tweet_urls(tweet)) # parses created_at "Wed Aug 27 13:08:45 +0000 2008" if settings.USE_TZ: tweet['datetime'] = datetime.strptime(tweet['created_at'], '%a %b %...
Generate suitable key to cache twitter tag context
def get_user_cache_key(**kwargs): """ Generate suitable key to cache twitter tag context """ key = 'get_tweets_%s' % ('_'.join([str(kwargs[key]) for key in sorted(kwargs) if kwargs[key]])) not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)])) key = not_allowed.sub('', key) ...
Generate suitable key to cache twitter tag context
def get_search_cache_key(prefix, *args): """ Generate suitable key to cache twitter tag context """ key = '%s_%s' % (prefix, '_'.join([str(arg) for arg in args if arg])) not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)])) key = not_allowed.sub('', key) return key
Turn #hashtag and
def urlize_tweet(tweet): """ Turn #hashtag and @username in a text to Twitter hyperlinks, similar to the ``urlize()`` function in Django. """ text = tweet.get('html', tweet['text']) for hash in tweet['entities']['hashtags']: text = text.replace('#%s' % hash['text'], TWITTER_HASHTAG_URL %...
Replace shortened URLs with long URLs in the twitter status and add the RT flag. Should be used before urlize_tweet
def expand_tweet_urls(tweet): """ Replace shortened URLs with long URLs in the twitter status, and add the "RT" flag. Should be used before urlize_tweet """ if 'retweeted_status' in tweet: text = 'RT @{user}: {text}'.format(user=tweet['retweeted_status']['user']['screen_name'], ...
Same power of a ^ b: param a: Number a: param b: Number b: return: a ^ b
def safe_power(a, b): """ Same power of a ^ b :param a: Number a :param b: Number b :return: a ^ b """ if abs(a) > MAX_POWER or abs(b) > MAX_POWER: raise ValueError('Number too high!') return a ** b
Performs a rabin - miller primality test
def rabin_miller(p): """ Performs a rabin-miller primality test :param p: Number to test :return: Bool of whether num is prime """ # From this stackoverflow answer: https://codegolf.stackexchange.com/questions/26739/super-speedy-totient-function if p < 2: return False if p != 2 ...
Split a string on a regex that only matches zero - width strings
def zero_width_split(pattern, string): """ Split a string on a regex that only matches zero-width strings :param pattern: Regex pattern that matches zero-width strings :param string: String to split on. :return: Split array """ splits = list((m.start(), m.end()) for m in regex.finditer(patt...
Rolls a group of dice in 2d6 3d10 d12 etc. format
def roll_group(group): """ Rolls a group of dice in 2d6, 3d10, d12, etc. format :param group: String of dice group :return: Array of results """ group = regex.match(r'^(\d*)d(\d+)$', group, regex.IGNORECASE) num_of_dice = int(group[1]) if group[1] != '' else 1 type_of_dice = int(group[2...
Returns the number of elements in a list that pass a comparison
def num_equal(result, operator, comparator): """ Returns the number of elements in a list that pass a comparison :param result: The list of results of a dice roll :param operator: Operator in string to perform comparison on: Either '+', '-', or '*' :param comparator: The value to compare ...
Rolls dice in dice notation with advanced syntax used according to tinyurl. com/ pydice
def roll_dice(roll, *, functions=True, floats=True): """ Rolls dice in dice notation with advanced syntax used according to tinyurl.com/pydice :param roll: Roll in dice notation :return: Result of roll, and an explanation string """ roll = ''.join(roll.split()) roll = regex.sub(r'(?<=d)%', ...
Evaluates an expression
def eval(self, expr): """ Evaluates an expression :param expr: Expression to evaluate :return: Result of expression """ # set a copy of the expression aside, so we can give nice errors... self.expr = expr # and evaluate: return self._eval(ast.pa...
Evaluate a node
def _eval(self, node): """ Evaluate a node :param node: Node to eval :return: Result of node """ try: handler = self.nodes[type(node)] except KeyError: raise ValueError("Sorry, {0} is not available in this evaluator".format(type(node).__na...
Evaluate a numerical node
def _eval_num(self, node): """ Evaluate a numerical node :param node: Node to eval :return: Result of node """ if self.floats: return node.n else: return int(node.n)
Evaluate a unary operator node ( ie. - 2 + 3 ) Currently just supports positive and negative
def _eval_unaryop(self, node): """ Evaluate a unary operator node (ie. -2, +3) Currently just supports positive and negative :param node: Node to eval :return: Result of node """ return self.operators[type(node.op)](self._eval(node.operand))
Evaluate a binary operator node ( ie. 2 + 3 5 * 6 3 ** 4 )
def _eval_binop(self, node): """ Evaluate a binary operator node (ie. 2+3, 5*6, 3 ** 4) :param node: Node to eval :return: Result of node """ return self.operators[type(node.op)](self._eval(node.left), self._eval(node.right))
Evaluate a function call
def _eval_call(self, node): """ Evaluate a function call :param node: Node to eval :return: Result of node """ try: func = self.functions[node.func.id] except KeyError: raise NameError(node.func.id) value = func( *(sel...
Rolls dicebag and sets last_roll and last_explanation to roll results
def roll_dice(self): # Roll dice with current roll """ Rolls dicebag and sets last_roll and last_explanation to roll results :return: Roll results. """ roll = roll_dice(self.roll, floats=self.floats, functions=self.functions) self._last_roll = roll[0] self._las...
Setter for roll verifies the roll is valid
def roll(self, value): """ Setter for roll, verifies the roll is valid :param value: Roll :return: None """ if type(value) != str: # Make sure dice roll is a str raise TypeError('Dice roll must be a string in dice notation') try: roll_dic...
Look for pdb. set_trace () commands in python files.
def run(files, temp_folder, arg=''): "Look for pdb.set_trace() commands in python files." parser = get_parser() args = parser.parse_args(arg.split()) py_files = filter_python_files(files) if args.ignore: orig_file_list = original_files(py_files, temp_folder) py_files = set(orig_file...
An iterator of valid checks that are in the installed checkers package.
def checks(): """ An iterator of valid checks that are in the installed checkers package. yields check name, check module """ checkers_dir = os.path.dirname(checkers.__file__) mod_names = [name for _, name, _ in pkgutil.iter_modules([checkers_dir])] for name in mod_names: mod = impo...
Validate the commit diff.
def files_to_check(commit_only): """ Validate the commit diff. Make copies of the staged changes for analysis. """ global TEMP_FOLDER safe_directory = tempfile.mkdtemp() TEMP_FOLDER = safe_directory files = get_files(commit_only=commit_only, copy_dest=safe_directory) try: ...
Run the configured code checks.
def main(commit_only=True): """ Run the configured code checks. Return system exit code. 1 - reject commit 0 - accept commit """ global TEMP_FOLDER exit_code = 0 hook_checks = HookConfig(get_config_file()) with files_to_check(commit_only) as files: for name, mod ...
Get copies of files for analysis.
def get_files(commit_only=True, copy_dest=None): "Get copies of files for analysis." if commit_only: real_files = bash( "git diff --cached --name-status | " "grep -v -E '^D' | " "awk '{ print ( $(NF) ) }' " ).value().strip() else: real_files = bash...
Create copies of the given list of files in the destination given.
def create_fake_copies(files, destination): """ Create copies of the given list of files in the destination given. Creates copies of the actual files to be committed using git show :<filename> Return a list of destination files. """ dest_files = [] for filename in files: leaf_d...
Get all python files from the list of files.
def filter_python_files(files): "Get all python files from the list of files." py_files = [] for f in files: # If we end in .py, or if we don't have an extension and file says that # we are a python script, then add us to the list extension = os.path.splitext(f)[-1] if exten...
Get plugin configuration.
def configuration(self, plugin): """ Get plugin configuration. Return a tuple of (on|off|default, args) """ conf = self.config.get(plugin, "default;").split(';') if len(conf) == 1: conf.append('') return tuple(conf)
Check frosted errors in the code base.
def run(files, temp_folder): "Check frosted errors in the code base." try: import frosted # NOQA except ImportError: return NO_FROSTED_MSG py_files = filter_python_files(files) cmd = 'frosted {0}'.format(' '.join(py_files)) return bash(cmd).value()
Check isort errors in the code base.
def run(files, temp_folder): """Check isort errors in the code base. For the --quiet option, at least isort >= 4.1.1 is required. https://github.com/timothycrosley/isort/blob/develop/CHANGELOG.md#411 """ try: import isort # NOQA except ImportError: return NO_ISORT_MSG py_...
Check we re not committing to a blocked branch
def run(files, temp_folder, arg=None): "Check we're not committing to a blocked branch" parser = get_parser() argos = parser.parse_args(arg.split()) current_branch = bash('git symbolic-ref HEAD').value() current_branch = current_branch.replace('refs/heads/', '').strip() if current_branch in arg...
Check coding convention of the code base.
def run(files, temp_folder, arg=None): "Check coding convention of the code base." try: import pylint except ImportError: return NO_PYLINT_MSG # set default level of threshold arg = arg or SCORE py_files = filter_python_files(files) if not py_files: return False ...
Check to see if python files are py3 compatible
def run(files, temp_folder): "Check to see if python files are py3 compatible" errors = [] for py_file in filter_python_files(files): # We only want to show errors if we CAN'T compile to py3. # but we want to show all the errors at once. b = bash('python3 -m py_compile {0}'.format(py...
Check flake8 errors in the code base.
def run(files, temp_folder): "Check flake8 errors in the code base." try: import flake8 # NOQA except ImportError: return NO_FLAKE_MSG try: from flake8.engine import get_style_guide except ImportError: # We're on a new version of flake8 from flake8.api.legacy...
Put two strategies to a classic battle of wits.
def tictactoe(w, i, player, opponent, grid=None): "Put two strategies to a classic battle of wits." grid = grid or empty_grid while True: w.render_to_terminal(w.array_from_text(view(grid))) if is_won(grid): print(whose_move(grid), "wins.") break if not success...
Return a function like f that remembers and reuses results of past calls.
def memo(f): "Return a function like f that remembers and reuses results of past calls." table = {} def memo_f(*args): try: return table[args] except KeyError: table[args] = value = f(*args) return value return memo_f
Just ask for a move.
def human_play(w, i, grid): "Just ask for a move." plaint = '' prompt = whose_move(grid) + " move? [1-9] " while True: w.render_to_terminal(w.array_from_text(view(grid) + '\n\n' + plaint + prompt)) key = c = i.next() try: ...
Play like Spock except breaking ties by drunk_value.
def max_play(w, i, grid): "Play like Spock, except breaking ties by drunk_value." return min(successors(grid), key=lambda succ: (evaluate(succ), drunk_value(succ)))
Return the expected value to the player if both players play at random.
def drunk_value(grid): "Return the expected value to the player if both players play at random." if is_won(grid): return -1 succs = successors(grid) return -average(map(drunk_value, succs)) if succs else 0
Return the value for the player to move assuming perfect play.
def evaluate(grid): "Return the value for the player to move, assuming perfect play." if is_won(grid): return -1 succs = successors(grid) return -min(map(evaluate, succs)) if succs else 0
Did the latest move win the game?
def is_won(grid): "Did the latest move win the game?" p, q = grid return any(way == (way & q) for way in ways_to_win)
Try to move: return a new grid or None if illegal.
def apply_move(grid, move): "Try to move: return a new grid, or None if illegal." p, q = grid bit = 1 << move return (q, p | bit) if 0 == (bit & (p | q)) else None
Return two results: the player s mark and their opponent s.
def player_marks(grid): "Return two results: the player's mark and their opponent's." p, q = grid return 'XO' if sum(player_bits(p)) == sum(player_bits(q)) else 'OX'
Show a grid human - readably.
def view(grid): "Show a grid human-readably." p_mark, q_mark = player_marks(grid) return grid_format % tuple(p_mark if by_p else q_mark if by_q else '.' for by_p, by_q in zip(*map(player_bits, grid)))
Helper function to parse the output file of SDPA.
def read_sdpa_out(filename, solutionmatrix=False, status=False, sdp=None): """Helper function to parse the output file of SDPA. :param filename: The name of the SDPA output file. :type filename: str. :param solutionmatrix: Optional parameter for retrieving the solution. :type solu...
Helper function to write out the SDP problem to a temporary file call the solver and parse the output.
def solve_with_sdpa(sdp, solverparameters=None): """Helper function to write out the SDP problem to a temporary file, call the solver, and parse the output. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. :param solverparameters: Optional parameters to SDPA. :ty...
Helper function to map to sparse SDPA index values.
def convert_row_to_sdpa_index(block_struct, row_offsets, row): """Helper function to map to sparse SDPA index values. """ block_index = bisect_left(row_offsets[1:], row + 1) width = block_struct[block_index] row = row - row_offsets[block_index] i, j = divmod(row, width) return block_index, i...
Write the SDP relaxation to SDPA format.
def write_to_sdpa(sdp, filename): """Write the SDP relaxation to SDPA format. :param sdp: The SDP relaxation to write. :type sdp: :class:`ncpol2sdpa.sdp`. :param filename: The name of the file. It must have the suffix ".dat-s" :type filename: str. """ # Coefficient matrices row_offsets ...
Convert the SDP relaxation to a human - readable format.
def convert_to_human_readable(sdp): """Convert the SDP relaxation to a human-readable format. :param sdp: The SDP relaxation to write. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: tuple of the objective function in a string and a matrix of strings as the symbolic representation of the mo...
Write the SDP relaxation to a human - readable format.
def write_to_human_readable(sdp, filename): """Write the SDP relaxation to a human-readable format. :param sdp: The SDP relaxation to write. :type sdp: :class:`ncpol2sdpa.sdp`. :param filename: The name of the file. :type filename: str. """ objective, matrix = convert_to_human_readable(sdp)...
Ideally we shouldn t lose the first second of events
def main(): """Ideally we shouldn't lose the first second of events""" with Input() as input_generator: def extra_bytes_callback(string): print('got extra bytes', repr(string)) print('type:', type(string)) input_generator.unget_bytes(string) time.sleep(1) ...
create request header function: param url: URL for the new: class: Request object.
def make_header(url, access_key=None, secret_key=None): ''' create request header function :param url: URL for the new :class:`Request` object. ''' nonce = nounce() url = url message = nonce + url signature = hmac.new(secret_key.encode('utf-8'), message.enc...
Adds bytes to be internal buffer to be read
def unget_bytes(self, string): """Adds bytes to be internal buffer to be read This method is for reporting bytes from an in_stream read not initiated by this Input object""" self.unprocessed_bytes.extend(string[i:i + 1] for i in range(len(string)))
Returns tuple of whether stdin is ready to read and an event.
def _wait_for_read_ready_or_timeout(self, timeout): """Returns tuple of whether stdin is ready to read and an event. If an event is returned, that event is more pressing than reading bytes on stdin to create a keyboard input event. If stdin is ready, either there are bytes to read or a ...
Returns an event or None if no events occur before timeout.
def send(self, timeout=None): """Returns an event or None if no events occur before timeout.""" if self.sigint_event and is_main_thread(): with ReplacedSigIntHandler(self.sigint_handler): return self._send(timeout) else: return self._send(timeout)
Returns the number of characters read and adds them to self. unprocessed_bytes
def _nonblocking_read(self): """Returns the number of characters read and adds them to self.unprocessed_bytes""" with Nonblocking(self.in_stream): if PY3: try: data = os.read(self.in_stream.fileno(), READ_SIZE) except BlockingIOError: ...
Returns a callback that creates events.
def event_trigger(self, event_type): """Returns a callback that creates events. Returned callback function will add an event of type event_type to a queue which will be checked the next time an event is requested.""" def callback(**kwargs): self.queued_events.append(event_ty...
Returns a callback that schedules events for the future.
def scheduled_event_trigger(self, event_type): """Returns a callback that schedules events for the future. Returned callback function will add an event of type event_type to a queue which will be checked the next time an event is requested.""" def callback(when, **kwargs): s...
Returns a callback to creates events interrupting current event requests.
def threadsafe_event_trigger(self, event_type): """Returns a callback to creates events, interrupting current event requests. Returned callback function will create an event of type event_type which will interrupt an event request if one is concurrently occuring, otherwise adding the ev...
Call a solver on the SDP relaxation. Upon successful solution it returns the primal and dual objective values along with the solution matrices.
def solve_sdp(sdp, solver=None, solverparameters=None): """Call a solver on the SDP relaxation. Upon successful solution, it returns the primal and dual objective values along with the solution matrices. :param sdpRelaxation: The SDP relaxation to be solved. :type sdpRelaxation: :class:`ncpol2sdpa....
Helper function to detect rank loop in the solution matrix.
def find_solution_ranks(sdp, xmat=None, baselevel=0): """Helper function to detect rank loop in the solution matrix. :param sdp: The SDP relaxation. :type sdp: :class:`ncpol2sdpa.sdp`. :param x_mat: Optional parameter providing the primal solution of the moment matrix. If not provided...
Given a solution of the dual problem it returns the SOS decomposition.
def get_sos_decomposition(sdp, y_mat=None, threshold=0.0): """Given a solution of the dual problem, it returns the SOS decomposition. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. :param y_mat: Optional parameter providing the dual solution of the ...
Given a solution of the dual problem and a monomial it returns the inner product of the corresponding coefficient matrix and the dual solution. It can be restricted to certain blocks.
def extract_dual_value(sdp, monomial, blocks=None): """Given a solution of the dual problem and a monomial, it returns the inner product of the corresponding coefficient matrix and the dual solution. It can be restricted to certain blocks. :param sdp: The SDP relaxation. :type sdp: :class:`ncpol2sd...
prefix is the start of the CC number as a string any number of digits. length is the length of the CC number to generate. Typically 13 or 16
def completed_number(prefix, length): """ 'prefix' is the start of the CC number as a string, any number of digits. 'length' is the length of the CC number to generate. Typically 13 or 16 """ ccnumber = prefix # generate digits while len(ccnumber) < (length - 1): digit = random.choic...
load_module is always called with the same argument as finder s find_module see How Import Works
def load_module(self, fullname): """ load_module is always called with the same argument as finder's find_module, see "How Import Works" """ mod = super(JsonLoader, self).load_module(fullname) try: with codecs.open(self.cfg_file, 'r', 'utf-8') as f: ...
Returns a message from tick () to be displayed if game is over
def process_event(self, c): """Returns a message from tick() to be displayed if game is over""" if c == "": sys.exit() elif c in key_directions: self.move_entity(self.player, *vscale(self.player.speed, key_directions[c])) else: return "try arrow keys,...
Returns a message to be displayed if game is over else None
def tick(self): """Returns a message to be displayed if game is over, else None""" for npc in self.npcs: self.move_entity(npc, *npc.towards(self.player)) for entity1, entity2 in itertools.combinations(self.entities, 2): if (entity1.x, entity1.y) == (entity2.x, entity2.y):...
Returns a FSArray of the size of the window containing msg
def array_from_text(self, msg): """Returns a FSArray of the size of the window containing msg""" rows, columns = self.t.height, self.t.width return self.array_from_text_rc(msg, rows, columns)
Renders array to terminal and places ( 0 - indexed ) cursor
def render_to_terminal(self, array, cursor_pos=(0, 0)): """Renders array to terminal and places (0-indexed) cursor Args: array (FSArray): Grid of styled characters to be rendered. * If array received is of width too small, render it anyway * If array received is of width to...
Returns the terminal ( row column ) of the cursor
def get_cursor_position(self): """Returns the terminal (row, column) of the cursor 0-indexed, like blessings cursor positions""" # TODO would this be cleaner as a parameter? in_stream = self.in_stream query_cursor_position = u"\x1b[6n" self.write(query_cursor_position) ...
Returns the how far down the cursor moved since last render.
def get_cursor_vertical_diff(self): """Returns the how far down the cursor moved since last render. Note: If another get_cursor_vertical_diff call is already in progress, immediately returns zero. (This situation is likely if get_cursor_vertical_diff is called from a...
Returns the how far down the cursor moved.
def _get_cursor_vertical_diff_once(self): """Returns the how far down the cursor moved.""" old_top_usable_row = self.top_usable_row row, col = self.get_cursor_position() if self._last_cursor_row is None: cursor_dy = 0 else: cursor_dy = row - self._last_cur...
Renders array to terminal returns the number of lines scrolled offscreen
def render_to_terminal(self, array, cursor_pos=(0, 0)): """Renders array to terminal, returns the number of lines scrolled offscreen Returns: Number of times scrolled Args: array (FSArray): Grid of styled characters to be rendered. If array received is of wid...
Call a solver on the SDP relaxation. Upon successful solution it returns the primal and dual objective values along with the solution matrices. It also sets these values in the sdpRelaxation object along with some status information.
def solve(self, solver=None, solverparameters=None): """Call a solver on the SDP relaxation. Upon successful solution, it returns the primal and dual objective values along with the solution matrices. It also sets these values in the `sdpRelaxation` object, along with some status informa...
Process a single monomial when building the moment matrix.
def _process_monomial(self, monomial, n_vars): """Process a single monomial when building the moment matrix. """ processed_monomial, coeff = separate_scalar_factor(monomial) # Are we substituting this moment? try: substitute = self.moment_substitutions[processed_monom...
Generate the moment matrix of monomials.
def _generate_moment_matrix(self, n_vars, block_index, processed_entries, monomialsA, monomialsB, ppt=False): """Generate the moment matrix of monomials. Arguments: n_vars -- current number of variables block_index -- current block index in the SDP matrix...
Returns the index of a monomial.
def _get_index_of_monomial(self, element, enablesubstitution=True, daggered=False): """Returns the index of a monomial. """ result = [] processed_element, coeff1 = separate_scalar_factor(element) if processed_element in self.moment_substitutions: ...
Calculate the sparse vector representation of a polynomial and pushes it to the F structure.
def __push_facvar_sparse(self, polynomial, block_index, row_offset, i, j): """Calculate the sparse vector representation of a polynomial and pushes it to the F structure. """ width = self.block_struct[block_index - 1] # Preprocess the polynomial for uniform handling later ...
Return dense vector representation of a polynomial. This function is nearly identical to __push_facvar_sparse but instead of pushing sparse entries to the constraint matrices it returns a dense vector.
def _get_facvar(self, polynomial): """Return dense vector representation of a polynomial. This function is nearly identical to __push_facvar_sparse, but instead of pushing sparse entries to the constraint matrices, it returns a dense vector. """ facvar = [0] * (self.n_var...
Generate localizing matrices
def __process_inequalities(self, block_index): """Generate localizing matrices Arguments: inequalities -- list of inequality constraints monomials -- localizing monomials block_index -- the current block index in constraint matrices of the SDP relaxatio...
Generate localizing matrices
def __process_equalities(self, equalities, momentequalities): """Generate localizing matrices Arguments: equalities -- list of equality constraints equalities -- list of moment equality constraints """ monomial_sets = [] n_rows = 0 le = 0 if equal...
Attempt to remove equalities by solving the linear equations.
def __remove_equalities(self, equalities, momentequalities): """Attempt to remove equalities by solving the linear equations. """ A = self.__process_equalities(equalities, momentequalities) if min(A.shape != np.linalg.matrix_rank(A)): print("Warning: equality constraints are ...
Calculates the block_struct array for the output file.
def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): """Calculates the block_struct array for the outp...
Process the constraints and generate localizing matrices. Useful only if the moment matrix already exists. Call it if you want to replace your constraints. The number of the respective types of constraints and the maximum degree of each constraint must remain the same.
def process_constraints(self, inequalities=None, equalities=None, momentinequalities=None, momentequalities=None, block_index=0, removeequalities=False): """Process the constraints and generate localizing matrices. Useful only if the moment matrix ...
Set or change the objective function of the polynomial optimization problem.
def set_objective(self, objective, extraobjexpr=None): """Set or change the objective function of the polynomial optimization problem. :param objective: Describes the objective function. :type objective: :class:`sympy.core.expr.Expr` :param extraobjexpr: Optional parameter of a ...