text
stringlengths
81
112k
Returns the ID and localized name of the given quality, can be either ID type def _quality_definition(self, qid): """ Returns the ID and localized name of the given quality, can be either ID type """ qualities = self._schema["qualities"] try: return qualities[qid] except Ke...
Returns all attributes in the schema def attributes(self): """ Returns all attributes in the schema """ attrs = self._schema["attributes"] return [item_attribute(attr) for attr in sorted(attrs.values(), key=operator.itemgetter("defindex"))]
Returns a localized origin name for a given ID def origin_id_to_name(self, origin): """ Returns a localized origin name for a given ID """ try: oid = int(origin) except (ValueError, TypeError): return None return self.origins.get(oid)
Returns a list of attributes def attributes(self): """ Returns a list of attributes """ overridden_attrs = self._attributes sortmap = {"neutral": 1, "positive": 2, "negative": 3} sortedattrs = list(overridden_attrs.values()) sortedattrs.sort(key=operator.ite...
Returns a dict of classes that have the item equipped and in what slot def equipped(self): """ Returns a dict of classes that have the item equipped and in what slot """ equipped = self._item.get("equipped", []) # WORKAROUND: 0 is probably an off-by-one error # WORKAROUND: 65535 actual...
Returns a list of classes that _can_ use the item. def equipable_classes(self): """ Returns a list of classes that _can_ use the item. """ sitem = self._schema_item return [c for c in sitem.get("used_by_classes", self.equipped.keys()) if c]
Returns the item in the container, if there is one. This will be a standard item object. def contents(self): """ Returns the item in the container, if there is one. This will be a standard item object. """ rawitem = self._item.get("contained_item") if rawitem: return...
The full name of the item, generated depending on things such as its quality, rank, the schema language, and so on. def full_name(self): """ The full name of the item, generated depending on things such as its quality, rank, the schema language, and so on. """ ...
Returns a list of tuples containing the proper localized kill eater type strings and their values according to set/type/value "order" def kill_eaters(self): """ Returns a list of tuples containing the proper localized kill eater type strings and their values according to set/type/value ...
Returns the item's rank (if it has one) as a dict that includes required score, name, and level. def rank(self): """ Returns the item's rank (if it has one) as a dict that includes required score, name, and level. """ if self._rank != {}: # Don't bother doin...
Returns a list of all styles defined for the item def available_styles(self): """ Returns a list of all styles defined for the item """ styles = self._schema_item.get("styles", []) return list(map(operator.itemgetter("name"), styles))
Returns a formatted value as a string def formatted_value(self): """ Returns a formatted value as a string""" # TODO: Cleanup all of this, it's just weird and unnatural maths val = self.value pval = val ftype = self.value_type if ftype == "percentage": pval ...
Returns a formatted description string (%s* tokens replaced) or None if unavailable def formatted_description(self): """ Returns a formatted description string (%s* tokens replaced) or None if unavailable """ desc = self.description if desc: return desc.replace("%s1", self.formatte...
The attribute's type, note that this is the type of the attribute's value and not its affect on the item (i.e. negative or positive). See 'type' for that. def value_type(self): """ The attribute's type, note that this is the type of the attribute's value and not its affect on the item (...
Certain attributes have a user's account information associated with it such as a gifted or crafted item. A dict with two keys: 'persona' and 'id64'. None if the attribute has no account information attached to it. def account_info(self): """ Certain attributes have a user's account in...
Returns a dict containing tags and their localized labels as values def tags(self): """ Returns a dict containing tags and their localized labels as values """ return dict([(t, self._catalog.tags.get(t, t)) for t in self._asset.get("tags", [])])
Returns the user's vanity url if it exists, None otherwise def vanity(self): """ Returns the user's vanity url if it exists, None otherwise """ purl = self.profile_url.strip('/') if purl.find("/id/") != -1: return os.path.basename(purl)
Returns the account creation date as a localtime time.struct_time struct if public def creation_date(self): """ Returns the account creation date as a localtime time.struct_time struct if public""" timestamp = self._prof.get("timecreated") if timestamp: return time.l...
Returns a tuple of 3 elements (each of which may be None if not available): Current game app ID, server ip:port, misc. extra info (eg. game title) def current_game(self): """ Returns a tuple of 3 elements (each of which may be None if not available): Current game app ID, server ip:port,...
Returns the the user's profile level, note that this runs a separate request because the profile level data isn't in the standard player summary output even though it should be. Which is also why it's not implemented as a separate class. You won't need this output and not the profile output def...
Builds a profile object from a raw player summary object def from_def(cls, obj): """ Builds a profile object from a raw player summary object """ prof = cls(obj["steamid"]) prof._cache = obj return prof
Called when a status is withheld def on_status_withheld(self, status_id, user_id, countries): """Called when a status is withheld""" logger.info('Status %s withheld for user %s', status_id, user_id) return True
Called when a disconnect is received def on_disconnect(self, code, stream_name, reason): """Called when a disconnect is received""" logger.error('Disconnect message: %s %s %s', code, stream_name, reason) return True
Called when a non-200 status code is returned def on_error(self, status_code): """Called when a non-200 status code is returned""" logger.error('Twitter returned error code %s', status_code) self.error = status_code return False
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() term...
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 line...
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_globa...
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: ...
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, st...
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_...
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 Printing...
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 logge...
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 stre...
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: ...
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.res...
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 # Resta...
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 ...
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.stre...
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['dat...
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 ran...
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)])) ...
Turn #hashtag and @username in a text to Twitter hyperlinks, similar to the ``urlize()`` function in Django. 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']) ...
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_s...
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 ...
Performs a rabin-miller primality test :param p: Number to test :return: Bool of whether num is prime 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.s...
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 def zero_width_split(pattern, string): """ Split a string on a regex that only matches zero-width strings :param...
Rolls a group of dice in 2d6, 3d10, d12, etc. format :param group: String of dice group :return: Array of results 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...
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 :return: def num_equal(result, operator, comparator): ...
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 def roll_dice(roll, *, functions=True, floats=True): """ Rolls dice in dice notation with advanced syntax used according to tinyur...
Evaluates an expression :param expr: Expression to evaluate :return: Result of 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...
Evaluate a node :param node: Node to eval :return: Result of 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: rai...
Evaluate a numerical node :param node: Node to eval :return: Result of 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: ...
Evaluate a unary operator node (ie. -2, +3) Currently just supports positive and negative :param node: Node to eval :return: Result of node def _eval_unaryop(self, node): """ Evaluate a unary operator node (ie. -2, +3) Currently just supports positive and negative ...
Evaluate a binary operator node (ie. 2+3, 5*6, 3 ** 4) :param node: Node to eval :return: Result of node 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...
Evaluate a function call :param node: Node to eval :return: Result of node 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...
Rolls dicebag and sets last_roll and last_explanation to roll results :return: 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.r...
Setter for roll, verifies the roll is valid :param value: Roll :return: None 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 r...
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_...
An iterator of valid checks that are in the installed checkers package. yields check name, check module 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...
Validate the commit diff. Make copies of the staged changes for analysis. 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 =...
Run the configured code checks. Return system exit code. 1 - reject commit 0 - accept commit 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 ...
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() ...
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. def create_fake_copies(files, destination): """ Create copies of the given list of files in the destination given. ...
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 extensi...
Get plugin configuration. Return a tuple of (on|off|default, args) 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: c...
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(c...
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 def run(files, temp_folder): """Check isort errors in the code base. For the --quiet option, at least isort >= 4.1.1 is required. ...
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/h...
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) ...
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. ...
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 o...
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), ...
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) ...
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() ...
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. :param filename: The name of the SDPA output file. :type filename: str. :param solutionmatrix: Optional parameter for retrieving the solution. :type solutionmatrix: bool. :param status: Optional parameter for retrieving the status. :type status:...
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. :type solverparameters: dict of str. :returns: tuple of...
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] ...
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. def write_to_sdpa(sdp, filename): """Write the SDP relaxation to SDPA format. :par...
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 moment matrix def convert_to_human_readable(...
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. def write_to_human_readable(sdp, filename): """Write the SDP relaxation to a human-readable format. :pa...
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_ge...
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 ...
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 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 ...
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 SIGTSTP triggered by dsusp has been received def _wait...
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) ...
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(se...
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 event_trigger(self, event_type): """Returns a callback that creates events. Returned callback function will...
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 scheduled_event_trigger(self, event_type): """Returns a callback that schedules events for the futu...
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 event to a queue that will be checked on the next eve...
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.SdpRelaxation`. :param solver: The solver to be called, eit...
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, the solution is extracted from the sdp ob...