repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
twitterdev/tweet_parser
tweet_parser/getter_methods/tweet_text.py
https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/getter_methods/tweet_text.py#L218-L261
def get_quote_or_rt_text(tweet): """ Get the quoted or retweeted text in a Tweet (this is not the text entered by the posting user) - tweet: empty string (there is no quoted or retweeted text) - quote: only the text of the quoted Tweet - retweet: the text of the retweet Args: tweet (Tweet or dict): A Tweet object or dictionary Returns: str: text of the retweeted-tweet or the quoted-tweet (empty string if this is an original Tweet) Example: >>> from tweet_parser.getter_methods.tweet_text import get_quote_or_rt_text >>> # a quote tweet >>> quote = {"created_at": "Wed May 24 20:17:19 +0000 2017", ... "text": "adding my own commentary", ... "truncated": False, ... "quoted_status": { ... "created_at": "Mon May 01 05:00:05 +0000 2017", ... "truncated": False, ... "text": "an interesting Tweet" ... } ... } >>> get_quote_or_rt_text(quote) 'an interesting Tweet' """ tweet_type = get_tweet_type(tweet) if tweet_type == "tweet": return "" if tweet_type == "quote": if is_original_format(tweet): return get_full_text(tweet["quoted_status"]) else: return get_full_text(tweet["twitter_quoted_status"]) if tweet_type == "retweet": if is_original_format(tweet): return get_full_text(tweet["retweeted_status"]) else: return get_full_text(tweet["object"])
[ "def", "get_quote_or_rt_text", "(", "tweet", ")", ":", "tweet_type", "=", "get_tweet_type", "(", "tweet", ")", "if", "tweet_type", "==", "\"tweet\"", ":", "return", "\"\"", "if", "tweet_type", "==", "\"quote\"", ":", "if", "is_original_format", "(", "tweet", "...
Get the quoted or retweeted text in a Tweet (this is not the text entered by the posting user) - tweet: empty string (there is no quoted or retweeted text) - quote: only the text of the quoted Tweet - retweet: the text of the retweet Args: tweet (Tweet or dict): A Tweet object or dictionary Returns: str: text of the retweeted-tweet or the quoted-tweet (empty string if this is an original Tweet) Example: >>> from tweet_parser.getter_methods.tweet_text import get_quote_or_rt_text >>> # a quote tweet >>> quote = {"created_at": "Wed May 24 20:17:19 +0000 2017", ... "text": "adding my own commentary", ... "truncated": False, ... "quoted_status": { ... "created_at": "Mon May 01 05:00:05 +0000 2017", ... "truncated": False, ... "text": "an interesting Tweet" ... } ... } >>> get_quote_or_rt_text(quote) 'an interesting Tweet'
[ "Get", "the", "quoted", "or", "retweeted", "text", "in", "a", "Tweet", "(", "this", "is", "not", "the", "text", "entered", "by", "the", "posting", "user", ")", "-", "tweet", ":", "empty", "string", "(", "there", "is", "no", "quoted", "or", "retweeted",...
python
train
maartenbreddels/ipyvolume
ipyvolume/pylab.py
https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L789-L885
def volshow( data, lighting=False, data_min=None, data_max=None, max_shape=256, tf=None, stereo=False, ambient_coefficient=0.5, diffuse_coefficient=0.8, specular_coefficient=0.5, specular_exponent=5, downscale=1, level=[0.1, 0.5, 0.9], opacity=[0.01, 0.05, 0.1], level_width=0.1, controls=True, max_opacity=0.2, memorder='C', extent=None, ): """Visualize a 3d array using volume rendering. Currently only 1 volume can be rendered. :param data: 3d numpy array :param origin: origin of the volume data, this is to match meshes which have a different origin :param domain_size: domain size is the size of the volume :param bool lighting: use lighting or not, if set to false, lighting parameters will be overriden :param float data_min: minimum value to consider for data, if None, computed using np.nanmin :param float data_max: maximum value to consider for data, if None, computed using np.nanmax :parap int max_shape: maximum shape for the 3d cube, if larger, the data is reduced by skipping/slicing (data[::N]), set to None to disable. :param tf: transfer function (or a default one) :param bool stereo: stereo view for virtual reality (cardboard and similar VR head mount) :param ambient_coefficient: lighting parameter :param diffuse_coefficient: lighting parameter :param specular_coefficient: lighting parameter :param specular_exponent: lighting parameter :param float downscale: downscale the rendering for better performance, for instance when set to 2, a 512x512 canvas will show a 256x256 rendering upscaled, but it will render twice as fast. :param level: level(s) for the where the opacity in the volume peaks, maximum sequence of length 3 :param opacity: opacity(ies) for each level, scalar or sequence of max length 3 :param level_width: width of the (gaussian) bumps where the opacity peaks, scalar or sequence of max length 3 :param bool controls: add controls for lighting and transfer function or not :param float max_opacity: maximum opacity for transfer function controls :param extent: list of [[xmin, xmax], [ymin, ymax], [zmin, zmax]] values that define the bounds of the volume, otherwise the viewport is used :return: """ fig = gcf() if tf is None: tf = transfer_function(level, opacity, level_width, controls=controls, max_opacity=max_opacity) if data_min is None: data_min = np.nanmin(data) if data_max is None: data_max = np.nanmax(data) if memorder == 'F': data = data.T if extent is None: extent = [(0, k) for k in data.shape[::-1]] if extent: _grow_limits(*extent) vol = ipv.Volume( data_original=data, tf=tf, data_min=data_min, data_max=data_max, show_min=data_min, show_max=data_max, extent_original=extent, data_max_shape=max_shape, ambient_coefficient=ambient_coefficient, diffuse_coefficient=diffuse_coefficient, specular_coefficient=specular_coefficient, specular_exponent=specular_exponent, rendering_lighting=lighting, ) vol._listen_to(fig) if controls: widget_opacity_scale = ipywidgets.FloatLogSlider(base=10, min=-2, max=2, description="opacity") widget_brightness = ipywidgets.FloatLogSlider(base=10, min=-1, max=1, description="brightness") ipywidgets.jslink((vol, 'opacity_scale'), (widget_opacity_scale, 'value')) ipywidgets.jslink((vol, 'brightness'), (widget_brightness, 'value')) widgets_bottom = [ipywidgets.HBox([widget_opacity_scale, widget_brightness])] current.container.children += tuple(widgets_bottom) fig.volumes = fig.volumes + [vol] return vol
[ "def", "volshow", "(", "data", ",", "lighting", "=", "False", ",", "data_min", "=", "None", ",", "data_max", "=", "None", ",", "max_shape", "=", "256", ",", "tf", "=", "None", ",", "stereo", "=", "False", ",", "ambient_coefficient", "=", "0.5", ",", ...
Visualize a 3d array using volume rendering. Currently only 1 volume can be rendered. :param data: 3d numpy array :param origin: origin of the volume data, this is to match meshes which have a different origin :param domain_size: domain size is the size of the volume :param bool lighting: use lighting or not, if set to false, lighting parameters will be overriden :param float data_min: minimum value to consider for data, if None, computed using np.nanmin :param float data_max: maximum value to consider for data, if None, computed using np.nanmax :parap int max_shape: maximum shape for the 3d cube, if larger, the data is reduced by skipping/slicing (data[::N]), set to None to disable. :param tf: transfer function (or a default one) :param bool stereo: stereo view for virtual reality (cardboard and similar VR head mount) :param ambient_coefficient: lighting parameter :param diffuse_coefficient: lighting parameter :param specular_coefficient: lighting parameter :param specular_exponent: lighting parameter :param float downscale: downscale the rendering for better performance, for instance when set to 2, a 512x512 canvas will show a 256x256 rendering upscaled, but it will render twice as fast. :param level: level(s) for the where the opacity in the volume peaks, maximum sequence of length 3 :param opacity: opacity(ies) for each level, scalar or sequence of max length 3 :param level_width: width of the (gaussian) bumps where the opacity peaks, scalar or sequence of max length 3 :param bool controls: add controls for lighting and transfer function or not :param float max_opacity: maximum opacity for transfer function controls :param extent: list of [[xmin, xmax], [ymin, ymax], [zmin, zmax]] values that define the bounds of the volume, otherwise the viewport is used :return:
[ "Visualize", "a", "3d", "array", "using", "volume", "rendering", "." ]
python
train
sosreport/sos
sos/policies/__init__.py
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L591-L599
def validate_plugin(self, plugin_class, experimental=False): """ Verifies that the plugin_class should execute under this policy """ valid_subclasses = [IndependentPlugin] + self.valid_subclasses if experimental: valid_subclasses += [ExperimentalPlugin] return any(issubclass(plugin_class, class_) for class_ in valid_subclasses)
[ "def", "validate_plugin", "(", "self", ",", "plugin_class", ",", "experimental", "=", "False", ")", ":", "valid_subclasses", "=", "[", "IndependentPlugin", "]", "+", "self", ".", "valid_subclasses", "if", "experimental", ":", "valid_subclasses", "+=", "[", "Expe...
Verifies that the plugin_class should execute under this policy
[ "Verifies", "that", "the", "plugin_class", "should", "execute", "under", "this", "policy" ]
python
train
gmr/tornado-elasticsearch
tornado_elasticsearch.py
https://github.com/gmr/tornado-elasticsearch/blob/fafe0de680277ce6faceb7449ded0b33822438d0/tornado_elasticsearch.py#L269-L282
def health(self, params=None): """Coroutine. Queries cluster Health API. Returns a 2-tuple, where first element is request status, and second element is a dictionary with response data. :param params: dictionary of query parameters, will be handed over to the underlying :class:`~torando_elasticsearch.AsyncHTTPConnection` class for serialization """ status, data = yield self.transport.perform_request( "GET", "/_cluster/health", params=params) raise gen.Return((status, data))
[ "def", "health", "(", "self", ",", "params", "=", "None", ")", ":", "status", ",", "data", "=", "yield", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "\"/_cluster/health\"", ",", "params", "=", "params", ")", "raise", "gen", "."...
Coroutine. Queries cluster Health API. Returns a 2-tuple, where first element is request status, and second element is a dictionary with response data. :param params: dictionary of query parameters, will be handed over to the underlying :class:`~torando_elasticsearch.AsyncHTTPConnection` class for serialization
[ "Coroutine", ".", "Queries", "cluster", "Health", "API", "." ]
python
test
non-Jedi/gyr
gyr/matrix_objects.py
https://github.com/non-Jedi/gyr/blob/9f7bfe033b9d3bbfd3a9e8aea02e35526b53125e/gyr/matrix_objects.py#L49-L55
def user(self): """Creates a User object when requested.""" try: return self._user except AttributeError: self._user = MatrixUser(self.mxid, self.Api(identity=self.mxid)) return self._user
[ "def", "user", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_user", "except", "AttributeError", ":", "self", ".", "_user", "=", "MatrixUser", "(", "self", ".", "mxid", ",", "self", ".", "Api", "(", "identity", "=", "self", ".", "mxid", ...
Creates a User object when requested.
[ "Creates", "a", "User", "object", "when", "requested", "." ]
python
train
kislyuk/aegea
aegea/packages/github3/models.py
https://github.com/kislyuk/aegea/blob/94957e9dba036eae3052e2662c208b259c08399a/aegea/packages/github3/models.py#L176-L184
def ratelimit_remaining(self): """Number of requests before GitHub imposes a ratelimit. :returns: int """ json = self._json(self._get(self._github_url + '/rate_limit'), 200) core = json.get('resources', {}).get('core', {}) self._remaining = core.get('remaining', 0) return self._remaining
[ "def", "ratelimit_remaining", "(", "self", ")", ":", "json", "=", "self", ".", "_json", "(", "self", ".", "_get", "(", "self", ".", "_github_url", "+", "'/rate_limit'", ")", ",", "200", ")", "core", "=", "json", ".", "get", "(", "'resources'", ",", "...
Number of requests before GitHub imposes a ratelimit. :returns: int
[ "Number", "of", "requests", "before", "GitHub", "imposes", "a", "ratelimit", "." ]
python
train
rytilahti/python-songpal
songpal/device.py
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L238-L243
async def get_storage_list(self) -> List[Storage]: """Return information about connected storage devices.""" return [ Storage.make(**x) for x in await self.services["system"]["getStorageList"]({}) ]
[ "async", "def", "get_storage_list", "(", "self", ")", "->", "List", "[", "Storage", "]", ":", "return", "[", "Storage", ".", "make", "(", "*", "*", "x", ")", "for", "x", "in", "await", "self", ".", "services", "[", "\"system\"", "]", "[", "\"getStora...
Return information about connected storage devices.
[ "Return", "information", "about", "connected", "storage", "devices", "." ]
python
train
saltstack/salt
salt/grains/disks.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/disks.py#L29-L40
def disks(): ''' Return list of disk devices ''' if salt.utils.platform.is_freebsd(): return _freebsd_geom() elif salt.utils.platform.is_linux(): return _linux_disks() elif salt.utils.platform.is_windows(): return _windows_disks() else: log.trace('Disk grain does not support OS')
[ "def", "disks", "(", ")", ":", "if", "salt", ".", "utils", ".", "platform", ".", "is_freebsd", "(", ")", ":", "return", "_freebsd_geom", "(", ")", "elif", "salt", ".", "utils", ".", "platform", ".", "is_linux", "(", ")", ":", "return", "_linux_disks", ...
Return list of disk devices
[ "Return", "list", "of", "disk", "devices" ]
python
train
alefnula/tea
tea/shell/__init__.py
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L73-L91
def chdir(directory): """Change the current working directory. Args: directory (str): Directory to go to. """ directory = os.path.abspath(directory) logger.info("chdir -> %s" % directory) try: if not os.path.isdir(directory): logger.error( "chdir -> %s failed! Directory does not exist!", directory ) return False os.chdir(directory) return True except Exception as e: logger.error("chdir -> %s failed! %s" % (directory, e)) return False
[ "def", "chdir", "(", "directory", ")", ":", "directory", "=", "os", ".", "path", ".", "abspath", "(", "directory", ")", "logger", ".", "info", "(", "\"chdir -> %s\"", "%", "directory", ")", "try", ":", "if", "not", "os", ".", "path", ".", "isdir", "(...
Change the current working directory. Args: directory (str): Directory to go to.
[ "Change", "the", "current", "working", "directory", "." ]
python
train
AlecAivazis/graphql-over-kafka
nautilus/network/events/actionHandlers/rollCallHandler.py
https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/network/events/actionHandlers/rollCallHandler.py#L3-L12
async def roll_call_handler(service, action_type, payload, props, **kwds): """ This action handler responds to the "roll call" emitted by the api gateway when it is brought up with the normal summary produced by the service. """ # if the action type corresponds to a roll call if action_type == roll_call_type(): # then announce the service await service.announce()
[ "async", "def", "roll_call_handler", "(", "service", ",", "action_type", ",", "payload", ",", "props", ",", "*", "*", "kwds", ")", ":", "# if the action type corresponds to a roll call", "if", "action_type", "==", "roll_call_type", "(", ")", ":", "# then announce th...
This action handler responds to the "roll call" emitted by the api gateway when it is brought up with the normal summary produced by the service.
[ "This", "action", "handler", "responds", "to", "the", "roll", "call", "emitted", "by", "the", "api", "gateway", "when", "it", "is", "brought", "up", "with", "the", "normal", "summary", "produced", "by", "the", "service", "." ]
python
train
iotile/coretools
iotilesensorgraph/iotile/sg/output_formats/config.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/output_formats/config.py#L12-L33
def format_config(sensor_graph): """Extract the config variables from this sensor graph in ASCII format. Args: sensor_graph (SensorGraph): the sensor graph that we want to format Returns: str: The ascii output lines concatenated as a single string """ cmdfile = CommandFile("Config Variables", "1.0") for slot in sorted(sensor_graph.config_database, key=lambda x: x.encode()): for conf_var, conf_def in sorted(sensor_graph.config_database[slot].items()): conf_type, conf_val = conf_def if conf_type == 'binary': conf_val = 'hex:' + hexlify(conf_val) cmdfile.add("set_variable", slot, conf_var, conf_type, conf_val) return cmdfile.dump()
[ "def", "format_config", "(", "sensor_graph", ")", ":", "cmdfile", "=", "CommandFile", "(", "\"Config Variables\"", ",", "\"1.0\"", ")", "for", "slot", "in", "sorted", "(", "sensor_graph", ".", "config_database", ",", "key", "=", "lambda", "x", ":", "x", ".",...
Extract the config variables from this sensor graph in ASCII format. Args: sensor_graph (SensorGraph): the sensor graph that we want to format Returns: str: The ascii output lines concatenated as a single string
[ "Extract", "the", "config", "variables", "from", "this", "sensor", "graph", "in", "ASCII", "format", "." ]
python
train
google/grr
grr/core/grr_response_core/stats/stats_utils.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/stats/stats_utils.py#L158-L170
def CreateGaugeMetadata(metric_name, value_type, fields=None, docstring=None, units=None): """Helper function for creating MetricMetadata for gauge metrics.""" return rdf_stats.MetricMetadata( varname=metric_name, metric_type=rdf_stats.MetricMetadata.MetricType.GAUGE, value_type=MetricValueTypeFromPythonType(value_type), fields_defs=FieldDefinitionProtosFromTuples(fields or []), docstring=docstring, units=units)
[ "def", "CreateGaugeMetadata", "(", "metric_name", ",", "value_type", ",", "fields", "=", "None", ",", "docstring", "=", "None", ",", "units", "=", "None", ")", ":", "return", "rdf_stats", ".", "MetricMetadata", "(", "varname", "=", "metric_name", ",", "metri...
Helper function for creating MetricMetadata for gauge metrics.
[ "Helper", "function", "for", "creating", "MetricMetadata", "for", "gauge", "metrics", "." ]
python
train
gem/oq-engine
openquake/hazardlib/mfd/youngs_coppersmith_1985.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/youngs_coppersmith_1985.py#L289-L308
def _get_rate(self, mag): """ Calculate and return the annual occurrence rate for a specific bin. :param mag: Magnitude value corresponding to the center of the bin of interest. :returns: Float number, the annual occurrence rate for the :param mag value. """ mag_lo = mag - self.bin_width / 2.0 mag_hi = mag + self.bin_width / 2.0 if mag >= self.min_mag and mag < self.char_mag - DELTA_CHAR / 2: # return rate according to exponential distribution return (10 ** (self.a_val - self.b_val * mag_lo) - 10 ** (self.a_val - self.b_val * mag_hi)) else: # return characteristic rate (distributed over the characteristic # range) for the given bin width return (self.char_rate / DELTA_CHAR) * self.bin_width
[ "def", "_get_rate", "(", "self", ",", "mag", ")", ":", "mag_lo", "=", "mag", "-", "self", ".", "bin_width", "/", "2.0", "mag_hi", "=", "mag", "+", "self", ".", "bin_width", "/", "2.0", "if", "mag", ">=", "self", ".", "min_mag", "and", "mag", "<", ...
Calculate and return the annual occurrence rate for a specific bin. :param mag: Magnitude value corresponding to the center of the bin of interest. :returns: Float number, the annual occurrence rate for the :param mag value.
[ "Calculate", "and", "return", "the", "annual", "occurrence", "rate", "for", "a", "specific", "bin", "." ]
python
train
bitesofcode/projexui
projexui/windows/xdkwindow/xdkwindow.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L552-L563
def browse( parent, filename = '' ): """ Creates a new XdkWidnow for browsing an XDK file. :param parent | <QWidget> filename | <str> """ dlg = XdkWindow(parent) dlg.show() if ( filename ): dlg.loadFilename(filename)
[ "def", "browse", "(", "parent", ",", "filename", "=", "''", ")", ":", "dlg", "=", "XdkWindow", "(", "parent", ")", "dlg", ".", "show", "(", ")", "if", "(", "filename", ")", ":", "dlg", ".", "loadFilename", "(", "filename", ")" ]
Creates a new XdkWidnow for browsing an XDK file. :param parent | <QWidget> filename | <str>
[ "Creates", "a", "new", "XdkWidnow", "for", "browsing", "an", "XDK", "file", ".", ":", "param", "parent", "|", "<QWidget", ">", "filename", "|", "<str", ">" ]
python
train
PySimpleGUI/PySimpleGUI
PySimpleGUIWeb/PySimpleGUIWeb.py
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWeb/PySimpleGUIWeb.py#L5367-L5432
def EasyProgressMeter(title, current_value, max_value, *args, orientation=None, bar_color=(None, None), button_color=None, size=DEFAULT_PROGRESS_BAR_SIZE, border_width=None): ''' A ONE-LINE progress meter. Add to your code where ever you need a meter. No need for a second function call before your loop. You've got enough code to write! :param title: Title will be shown on the window :param current_value: Current count of your items :param max_value: Max value your count will ever reach. This indicates it should be closed :param args: VARIABLE number of arguements... you request it, we'll print it no matter what the item! :param orientation: :param bar_color: :param size: :param Style: :param StyleOffset: :return: False if should stop the meter ''' local_border_width = DEFAULT_PROGRESS_BAR_BORDER_WIDTH if not border_width else border_width # STATIC VARIABLE! # This is a very clever form of static variable using a function attribute # If the variable doesn't yet exist, then it will create it and initialize with the 3rd parameter EasyProgressMeter.Data = getattr(EasyProgressMeter, 'Data', EasyProgressMeterDataClass()) # if no meter currently running if EasyProgressMeter.Data.MeterID is None: # Starting a new meter print( "Please change your call of EasyProgressMeter to use OneLineProgressMeter. EasyProgressMeter will be removed soon") if int(current_value) >= int(max_value): return False del (EasyProgressMeter.Data) EasyProgressMeter.Data = EasyProgressMeterDataClass(title, 1, int(max_value), datetime.datetime.utcnow(), []) EasyProgressMeter.Data.ComputeProgressStats() message = "\n".join([line for line in EasyProgressMeter.Data.StatMessages]) EasyProgressMeter.Data.MeterID, EasyProgressMeter.Data.MeterText = _ProgressMeter(title, int(max_value), message, *args, orientation=orientation, bar_color=bar_color, size=size, button_color=button_color, border_width=local_border_width) EasyProgressMeter.Data.ParentForm = EasyProgressMeter.Data.MeterID.ParentForm return True # if exactly the same values as before, then ignore. if EasyProgressMeter.Data.MaxValue == max_value and EasyProgressMeter.Data.CurrentValue == current_value: return True if EasyProgressMeter.Data.MaxValue != int(max_value): EasyProgressMeter.Data.MeterID = None EasyProgressMeter.Data.ParentForm = None del (EasyProgressMeter.Data) EasyProgressMeter.Data = EasyProgressMeterDataClass() # setup a new progress meter return True # HAVE to return TRUE or else the new meter will thing IT is failing when it hasn't EasyProgressMeter.Data.CurrentValue = int(current_value) EasyProgressMeter.Data.MaxValue = int(max_value) EasyProgressMeter.Data.ComputeProgressStats() message = '' for line in EasyProgressMeter.Data.StatMessages: message = message + str(line) + '\n' message = "\n".join(EasyProgressMeter.Data.StatMessages) args = args + (message,) rc = _ProgressMeterUpdate(EasyProgressMeter.Data.MeterID, current_value, EasyProgressMeter.Data.MeterText, *args) # if counter >= max then the progress meter is all done. Indicate none running if current_value >= EasyProgressMeter.Data.MaxValue or not rc: EasyProgressMeter.Data.MeterID = None del (EasyProgressMeter.Data) EasyProgressMeter.Data = EasyProgressMeterDataClass() # setup a new progress meter return False # even though at the end, return True so don't cause error with the app return rc
[ "def", "EasyProgressMeter", "(", "title", ",", "current_value", ",", "max_value", ",", "*", "args", ",", "orientation", "=", "None", ",", "bar_color", "=", "(", "None", ",", "None", ")", ",", "button_color", "=", "None", ",", "size", "=", "DEFAULT_PROGRESS...
A ONE-LINE progress meter. Add to your code where ever you need a meter. No need for a second function call before your loop. You've got enough code to write! :param title: Title will be shown on the window :param current_value: Current count of your items :param max_value: Max value your count will ever reach. This indicates it should be closed :param args: VARIABLE number of arguements... you request it, we'll print it no matter what the item! :param orientation: :param bar_color: :param size: :param Style: :param StyleOffset: :return: False if should stop the meter
[ "A", "ONE", "-", "LINE", "progress", "meter", ".", "Add", "to", "your", "code", "where", "ever", "you", "need", "a", "meter", ".", "No", "need", "for", "a", "second", "function", "call", "before", "your", "loop", ".", "You", "ve", "got", "enough", "c...
python
train
ska-sa/purr
Purr/Pipe.py
https://github.com/ska-sa/purr/blob/4c848768d0485d0f88b30850d0d5372221b21b66/Purr/Pipe.py#L24-L30
def _write(self, what): """writes something to the Purr pipe""" try: open(self.pipefile, "a").write(what) except: print("Error writing to %s:" % self.pipefile) traceback.print_exc()
[ "def", "_write", "(", "self", ",", "what", ")", ":", "try", ":", "open", "(", "self", ".", "pipefile", ",", "\"a\"", ")", ".", "write", "(", "what", ")", "except", ":", "print", "(", "\"Error writing to %s:\"", "%", "self", ".", "pipefile", ")", "tra...
writes something to the Purr pipe
[ "writes", "something", "to", "the", "Purr", "pipe" ]
python
train
IBMStreams/pypi.streamsx
streamsx/spl/op.py
https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/op.py#L410-L426
def expression(value): """Create an SPL expression. Args: value: Expression as a string or another `Expression`. If value is an instance of `Expression` then a new instance is returned containing the same type and value. Returns: Expression: SPL expression from `value`. """ if isinstance(value, Expression): # Clone the expression to allow it to # be used in multiple contexts return Expression(value._type, value._value) if hasattr(value, 'spl_json'): sj = value.spl_json() return Expression(sj['type'], sj['value']) return Expression('splexpr', value)
[ "def", "expression", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Expression", ")", ":", "# Clone the expression to allow it to", "# be used in multiple contexts", "return", "Expression", "(", "value", ".", "_type", ",", "value", ".", "_value", ...
Create an SPL expression. Args: value: Expression as a string or another `Expression`. If value is an instance of `Expression` then a new instance is returned containing the same type and value. Returns: Expression: SPL expression from `value`.
[ "Create", "an", "SPL", "expression", "." ]
python
train
saltstack/salt
salt/modules/debuild_pkgbuild.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debuild_pkgbuild.py#L98-L112
def _get_build_env(env): ''' Get build environment overrides dictionary to use in build process ''' env_override = '' if env is None: return env_override if not isinstance(env, dict): raise SaltInvocationError( '\'env\' must be a Python dictionary' ) for key, value in env.items(): env_override += '{0}={1}\n'.format(key, value) env_override += 'export {0}\n'.format(key) return env_override
[ "def", "_get_build_env", "(", "env", ")", ":", "env_override", "=", "''", "if", "env", "is", "None", ":", "return", "env_override", "if", "not", "isinstance", "(", "env", ",", "dict", ")", ":", "raise", "SaltInvocationError", "(", "'\\'env\\' must be a Python ...
Get build environment overrides dictionary to use in build process
[ "Get", "build", "environment", "overrides", "dictionary", "to", "use", "in", "build", "process" ]
python
train
decryptus/sonicprobe
sonicprobe/libs/urisup.py
https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/libs/urisup.py#L565-L587
def uri_tree_precode_check(uri_tree, type_host = HOST_REG_NAME): """ Call this function to validate a raw URI tree before trying to encode it. """ scheme, authority, path, query, fragment = uri_tree # pylint: disable-msg=W0612 if scheme: if not valid_scheme(scheme): raise InvalidSchemeError, "Invalid scheme %r" % (scheme,) if authority: user, passwd, host, port = authority # pylint: disable-msg=W0612 if port and not __all_in(port, DIGIT): raise InvalidPortError, "Invalid port %r" % (port,) if type_host == HOST_IP_LITERAL: if host and (not __valid_IPLiteral(host)): raise InvalidIPLiteralError, "Invalid IP-literal %r" % (host,) elif type_host == HOST_IPV4_ADDRESS: if host and (not __valid_IPv4address(host)): raise InvalidIPv4addressError, "Invalid IPv4address %r" % (host,) if path: if authority and path[0] != '/': raise InvalidPathError, "Invalid path %r - non-absolute path can't be used with an authority" % (path,) return uri_tree
[ "def", "uri_tree_precode_check", "(", "uri_tree", ",", "type_host", "=", "HOST_REG_NAME", ")", ":", "scheme", ",", "authority", ",", "path", ",", "query", ",", "fragment", "=", "uri_tree", "# pylint: disable-msg=W0612", "if", "scheme", ":", "if", "not", "valid_s...
Call this function to validate a raw URI tree before trying to encode it.
[ "Call", "this", "function", "to", "validate", "a", "raw", "URI", "tree", "before", "trying", "to", "encode", "it", "." ]
python
train
rduplain/jeni-python
jeni.py
https://github.com/rduplain/jeni-python/blob/feca12ce5e4f0438ae5d7bec59d61826063594f1/jeni.py#L701-L739
def handle_provider(self, provider_factory, note): """Get value from provider as requested by note.""" # Implementation in separate method to support accurate book-keeping. basenote, name = self.parse_note(note) # _handle_provider could be even shorter if # Injector.apply() worked with classes, issue #9. if basenote not in self.instances: if (isinstance(provider_factory, type) and self.has_annotations(provider_factory.__init__)): args, kwargs = self.prepare_callable(provider_factory.__init__) self.instances[basenote] = provider_factory(*args, **kwargs) else: self.instances[basenote] = self.apply_regardless( provider_factory) provider = self.instances[basenote] if hasattr(provider, 'close'): self.finalizers.append(self.instances[basenote].close) provider = self.instances[basenote] get = self.partial_regardless(provider.get) try: if name is not None: return get(name=name) self.values[basenote] = get() return self.values[basenote] except UnsetError: # Use sys.exc_info to support both Python 2 and Python 3. exc_type, exc_value, tb = sys.exc_info() exc_msg = str(exc_value) if exc_msg: msg = '{}: {!r}'.format(exc_msg, note) else: msg = repr(note) six.reraise(exc_type, exc_type(msg, note=note), tb)
[ "def", "handle_provider", "(", "self", ",", "provider_factory", ",", "note", ")", ":", "# Implementation in separate method to support accurate book-keeping.", "basenote", ",", "name", "=", "self", ".", "parse_note", "(", "note", ")", "# _handle_provider could be even short...
Get value from provider as requested by note.
[ "Get", "value", "from", "provider", "as", "requested", "by", "note", "." ]
python
train
pyblish/pyblish-qml
pyblish_qml/vendor/mock.py
https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/vendor/mock.py#L243-L258
def _instance_callable(obj): """Given an object, return True if the object is callable. For classes, return True if instances would be callable.""" if not isinstance(obj, ClassTypes): # already an instance return getattr(obj, '__call__', None) is not None klass = obj # uses __bases__ instead of __mro__ so that we work with old style classes if klass.__dict__.get('__call__') is not None: return True for base in klass.__bases__: if _instance_callable(base): return True return False
[ "def", "_instance_callable", "(", "obj", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "ClassTypes", ")", ":", "# already an instance", "return", "getattr", "(", "obj", ",", "'__call__'", ",", "None", ")", "is", "not", "None", "klass", "=", "obj", ...
Given an object, return True if the object is callable. For classes, return True if instances would be callable.
[ "Given", "an", "object", "return", "True", "if", "the", "object", "is", "callable", ".", "For", "classes", "return", "True", "if", "instances", "would", "be", "callable", "." ]
python
train
wbond/oscrypto
oscrypto/_osx/tls.py
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L1273-L1302
def _shutdown(self, manual): """ Shuts down the TLS session and then shuts down the underlying socket :param manual: A boolean if the connection was manually shutdown """ if self._session_context is None: return # Ignore error during close in case other end closed already result = Security.SSLClose(self._session_context) if osx_version_info < (10, 8): result = Security.SSLDisposeContext(self._session_context) handle_sec_error(result) else: result = CoreFoundation.CFRelease(self._session_context) handle_cf_error(result) self._session_context = None if manual: self._local_closed = True try: self._socket.shutdown(socket_.SHUT_RDWR) except (socket_.error): pass
[ "def", "_shutdown", "(", "self", ",", "manual", ")", ":", "if", "self", ".", "_session_context", "is", "None", ":", "return", "# Ignore error during close in case other end closed already", "result", "=", "Security", ".", "SSLClose", "(", "self", ".", "_session_cont...
Shuts down the TLS session and then shuts down the underlying socket :param manual: A boolean if the connection was manually shutdown
[ "Shuts", "down", "the", "TLS", "session", "and", "then", "shuts", "down", "the", "underlying", "socket" ]
python
valid
CalebBell/thermo
thermo/triple.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/triple.py#L125-L193
def Pt(CASRN, AvailableMethods=False, Method=None): r'''This function handles the retrieval of a chemical's triple pressure. Lookup is based on CASRNs. Will automatically select a data source to use if no Method is provided; returns None if the data is not available. Returns data from [1]_, or attempts to calculate the vapor pressure at the triple temperature, if data is available. Parameters ---------- CASRN : string CASRN [-] Returns ------- Pt : float Triple point pressure, [Pa] methods : list, only returned if AvailableMethods == True List of methods which can be used to obtain Pt with the given inputs Other Parameters ---------------- Method : string, optional A string for the method name to use, as defined by constants in Pt_methods AvailableMethods : bool, optional If True, function will determine which methods can be used to obtain the Pt for the desired chemical, and will return methods instead of the Pt Notes ----- Examples -------- Ammonia >>> Pt('7664-41-7') 6079.5 References ---------- .. [1] Staveley, L. A. K., L. Q. Lobo, and J. C. G. Calado. "Triple-Points of Low Melting Substances and Their Use in Cryogenic Work." Cryogenics 21, no. 3 (March 1981): 131-144. doi:10.1016/0011-2275(81)90264-2. ''' def list_methods(): methods = [] if CASRN in Staveley_data.index and not np.isnan(Staveley_data.at[CASRN, 'Pt']): methods.append(STAVELEY) if Tt(CASRN) and VaporPressure(CASRN=CASRN).T_dependent_property(T=Tt(CASRN)): methods.append(DEFINITION) methods.append(NONE) return methods if AvailableMethods: return list_methods() if not Method: Method = list_methods()[0] if Method == STAVELEY: Pt = Staveley_data.at[CASRN, 'Pt'] elif Method == DEFINITION: Pt = VaporPressure(CASRN=CASRN).T_dependent_property(T=Tt(CASRN)) elif Method == NONE: Pt = None else: raise Exception('Failure in in function') return Pt
[ "def", "Pt", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "Staveley_data", ".", "index", "and", "not", "np", ".", "isna...
r'''This function handles the retrieval of a chemical's triple pressure. Lookup is based on CASRNs. Will automatically select a data source to use if no Method is provided; returns None if the data is not available. Returns data from [1]_, or attempts to calculate the vapor pressure at the triple temperature, if data is available. Parameters ---------- CASRN : string CASRN [-] Returns ------- Pt : float Triple point pressure, [Pa] methods : list, only returned if AvailableMethods == True List of methods which can be used to obtain Pt with the given inputs Other Parameters ---------------- Method : string, optional A string for the method name to use, as defined by constants in Pt_methods AvailableMethods : bool, optional If True, function will determine which methods can be used to obtain the Pt for the desired chemical, and will return methods instead of the Pt Notes ----- Examples -------- Ammonia >>> Pt('7664-41-7') 6079.5 References ---------- .. [1] Staveley, L. A. K., L. Q. Lobo, and J. C. G. Calado. "Triple-Points of Low Melting Substances and Their Use in Cryogenic Work." Cryogenics 21, no. 3 (March 1981): 131-144. doi:10.1016/0011-2275(81)90264-2.
[ "r", "This", "function", "handles", "the", "retrieval", "of", "a", "chemical", "s", "triple", "pressure", ".", "Lookup", "is", "based", "on", "CASRNs", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", ...
python
valid
mozilla-releng/scriptworker
scriptworker/client.py
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/client.py#L71-L95
def validate_task_schema(context, schema_key='schema_file'): """Validate the task definition. Args: context (scriptworker.context.Context): the scriptworker context. It must contain a task and the config pointing to the schema file schema_key: the key in `context.config` where the path to the schema file is. Key can contain dots (e.g.: 'schema_files.file_a'), in which case Raises: TaskVerificationError: if the task doesn't match the schema """ schema_path = context.config schema_keys = schema_key.split('.') for key in schema_keys: schema_path = schema_path[key] task_schema = load_json_or_yaml(schema_path, is_path=True) log.debug('Task is validated against this schema: {}'.format(task_schema)) try: validate_json_schema(context.task, task_schema) except ScriptWorkerTaskException as e: raise TaskVerificationError('Cannot validate task against schema. Task: {}.'.format(context.task)) from e
[ "def", "validate_task_schema", "(", "context", ",", "schema_key", "=", "'schema_file'", ")", ":", "schema_path", "=", "context", ".", "config", "schema_keys", "=", "schema_key", ".", "split", "(", "'.'", ")", "for", "key", "in", "schema_keys", ":", "schema_pat...
Validate the task definition. Args: context (scriptworker.context.Context): the scriptworker context. It must contain a task and the config pointing to the schema file schema_key: the key in `context.config` where the path to the schema file is. Key can contain dots (e.g.: 'schema_files.file_a'), in which case Raises: TaskVerificationError: if the task doesn't match the schema
[ "Validate", "the", "task", "definition", "." ]
python
train
square/pylink
pylink/jlink.py
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L3881-L3905
def strace_configure(self, port_width): """Configures the trace port width for tracing. Note that configuration cannot occur while STRACE is running. Args: self (JLink): the ``JLink`` instance port_width (int): the trace port width to use. Returns: ``None`` Raises: ValueError: if ``port_width`` is not ``1``, ``2``, or ``4``. JLinkException: on error. """ if port_width not in [1, 2, 4]: raise ValueError('Invalid port width: %s' % str(port_width)) config_string = 'PortWidth=%d' % port_width res = self._dll.JLINK_STRACE_Config(config_string.encode()) if res < 0: raise errors.JLinkException('Failed to configure STRACE port') return None
[ "def", "strace_configure", "(", "self", ",", "port_width", ")", ":", "if", "port_width", "not", "in", "[", "1", ",", "2", ",", "4", "]", ":", "raise", "ValueError", "(", "'Invalid port width: %s'", "%", "str", "(", "port_width", ")", ")", "config_string", ...
Configures the trace port width for tracing. Note that configuration cannot occur while STRACE is running. Args: self (JLink): the ``JLink`` instance port_width (int): the trace port width to use. Returns: ``None`` Raises: ValueError: if ``port_width`` is not ``1``, ``2``, or ``4``. JLinkException: on error.
[ "Configures", "the", "trace", "port", "width", "for", "tracing", "." ]
python
train
OpenGeoVis/espatools
espatools/read.py
https://github.com/OpenGeoVis/espatools/blob/5c04daae0f035c7efcb4096bb85a26c6959ac9ea/espatools/read.py#L137-L181
def Read(self, meta_only=False, allowed=None, cast=False): """Read the ESPA XML metadata file""" if allowed is not None and not isinstance(allowed, (list, tuple)): raise RuntimeError('`allowed` must be a list of str names.') meta = xmltodict.parse( open(self.filename, 'r').read() ).get('espa_metadata') # Handle bands seperately bands = meta.get('bands').get('band') del(meta['bands']) if not isinstance(bands, (list)): bands = [bands] meta = self.CleanDict(meta) # Get spatial refernce ras = SetProperties(RasterSet, meta) if allowed is not None: # Remove non-allowed arrays from bdict for k in list(self.bdict.keys()): if k not in allowed: del(self.bdict[k]) for i in range(len(bands)): info = self.GenerateBand(bands[i], meta_only=True, cast=cast) if allowed is not None and info.name not in allowed: continue if info.name not in self.bdict.keys() or self.bdict[info.name].data is None: b = self.GenerateBand(bands[i], meta_only=meta_only, cast=cast) self.bdict[b.name] = b elif cast and self.bdict[info.name].data.dtype != np.float32: b = self.GenerateBand(bands[i], meta_only=meta_only, cast=cast) self.bdict[b.name] = b elif not cast and self.bdict[info.name].data.dtype == np.float32: b = self.GenerateBand(bands[i], meta_only=meta_only, cast=cast) self.bdict[b.name] = b ras.bands = self.bdict if not meta_only: ras.validate() return ras
[ "def", "Read", "(", "self", ",", "meta_only", "=", "False", ",", "allowed", "=", "None", ",", "cast", "=", "False", ")", ":", "if", "allowed", "is", "not", "None", "and", "not", "isinstance", "(", "allowed", ",", "(", "list", ",", "tuple", ")", ")"...
Read the ESPA XML metadata file
[ "Read", "the", "ESPA", "XML", "metadata", "file" ]
python
train
readbeyond/aeneas
aeneas/executejob.py
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executejob.py#L187-L218
def execute(self): """ Execute the job, that is, execute all of its tasks. Each produced sync map will be stored inside the corresponding task object. :raises: :class:`~aeneas.executejob.ExecuteJobExecutionError`: if there is a problem during the job execution """ self.log(u"Executing job") if self.job is None: self.log_exc(u"The job object is None", None, True, ExecuteJobExecutionError) if len(self.job) == 0: self.log_exc(u"The job has no tasks", None, True, ExecuteJobExecutionError) job_max_tasks = self.rconf[RuntimeConfiguration.JOB_MAX_TASKS] if (job_max_tasks > 0) and (len(self.job) > job_max_tasks): self.log_exc(u"The Job has %d Tasks, more than the maximum allowed (%d)." % (len(self.job), job_max_tasks), None, True, ExecuteJobExecutionError) self.log([u"Number of tasks: '%d'", len(self.job)]) for task in self.job.tasks: try: custom_id = task.configuration["custom_id"] self.log([u"Executing task '%s'...", custom_id]) executor = ExecuteTask(task, rconf=self.rconf, logger=self.logger) executor.execute() self.log([u"Executing task '%s'... done", custom_id]) except Exception as exc: self.log_exc(u"Error while executing task '%s'" % (custom_id), exc, True, ExecuteJobExecutionError) self.log(u"Executing task: succeeded") self.log(u"Executing job: succeeded")
[ "def", "execute", "(", "self", ")", ":", "self", ".", "log", "(", "u\"Executing job\"", ")", "if", "self", ".", "job", "is", "None", ":", "self", ".", "log_exc", "(", "u\"The job object is None\"", ",", "None", ",", "True", ",", "ExecuteJobExecutionError", ...
Execute the job, that is, execute all of its tasks. Each produced sync map will be stored inside the corresponding task object. :raises: :class:`~aeneas.executejob.ExecuteJobExecutionError`: if there is a problem during the job execution
[ "Execute", "the", "job", "that", "is", "execute", "all", "of", "its", "tasks", "." ]
python
train
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L11699-L11709
def log_data_send(self, id, ofs, count, data, force_mavlink1=False): ''' Reply to LOG_REQUEST_DATA id : Log id (from LOG_ENTRY reply) (uint16_t) ofs : Offset into the log (uint32_t) count : Number of bytes (zero for end of log) (uint8_t) data : log data (uint8_t) ''' return self.send(self.log_data_encode(id, ofs, count, data), force_mavlink1=force_mavlink1)
[ "def", "log_data_send", "(", "self", ",", "id", ",", "ofs", ",", "count", ",", "data", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "log_data_encode", "(", "id", ",", "ofs", ",", "count", ",", "data"...
Reply to LOG_REQUEST_DATA id : Log id (from LOG_ENTRY reply) (uint16_t) ofs : Offset into the log (uint32_t) count : Number of bytes (zero for end of log) (uint8_t) data : log data (uint8_t)
[ "Reply", "to", "LOG_REQUEST_DATA" ]
python
train
materialsproject/pymatgen
pymatgen/core/spectrum.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/spectrum.py#L121-L126
def copy(self): """ Returns: Copy of Spectrum object. """ return self.__class__(self.x, self.y, *self._args, **self._kwargs)
[ "def", "copy", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "self", ".", "x", ",", "self", ".", "y", ",", "*", "self", ".", "_args", ",", "*", "*", "self", ".", "_kwargs", ")" ]
Returns: Copy of Spectrum object.
[ "Returns", ":", "Copy", "of", "Spectrum", "object", "." ]
python
train
alex-kostirin/pyatomac
atomac/ldtpd/core.py
https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L80-L103
def getapplist(self): """ Get all accessibility application name that are currently running @return: list of appliction name of string type on success. @rtype: list """ app_list = [] # Update apps list, before parsing the list self._update_apps() for gui in self._running_apps: name = gui.localizedName() # default type was objc.pyobjc_unicode # convert to Unicode, else exception is thrown # TypeError: "cannot marshal <type 'objc.pyobjc_unicode'> objects" try: name = unicode(name) except NameError: name = str(name) except UnicodeEncodeError: pass app_list.append(name) # Return unique application list return list(set(app_list))
[ "def", "getapplist", "(", "self", ")", ":", "app_list", "=", "[", "]", "# Update apps list, before parsing the list", "self", ".", "_update_apps", "(", ")", "for", "gui", "in", "self", ".", "_running_apps", ":", "name", "=", "gui", ".", "localizedName", "(", ...
Get all accessibility application name that are currently running @return: list of appliction name of string type on success. @rtype: list
[ "Get", "all", "accessibility", "application", "name", "that", "are", "currently", "running" ]
python
valid
ninjaaron/libaaron
libaaron/libaaron.py
https://github.com/ninjaaron/libaaron/blob/a2ee417b784ca72c89c05bddb2e3e815a6b95154/libaaron/libaaron.py#L258-L266
def pipeline(*functions, funcs=None): """like pipe, but curried: pipline(f, g, h)(*args, **kwargs) == h(g(f(*args, **kwargs))) """ if funcs: functions = funcs head, *tail = functions return lambda *args, **kwargs: pipe(head(*args, **kwargs), funcs=tail)
[ "def", "pipeline", "(", "*", "functions", ",", "funcs", "=", "None", ")", ":", "if", "funcs", ":", "functions", "=", "funcs", "head", ",", "", "*", "tail", "=", "functions", "return", "lambda", "*", "args", ",", "*", "*", "kwargs", ":", "pipe", "("...
like pipe, but curried: pipline(f, g, h)(*args, **kwargs) == h(g(f(*args, **kwargs)))
[ "like", "pipe", "but", "curried", ":" ]
python
test
apache/incubator-superset
superset/views/core.py
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L2771-L2828
def search_queries(self) -> Response: """ Search for previously run sqllab queries. Used for Sqllab Query Search page /superset/sqllab#search. Custom permission can_only_search_queries_owned restricts queries to only queries run by current user. :returns: Response with list of sql query dicts """ query = db.session.query(Query) if security_manager.can_only_access_owned_queries(): search_user_id = g.user.get_user_id() else: search_user_id = request.args.get('user_id') database_id = request.args.get('database_id') search_text = request.args.get('search_text') status = request.args.get('status') # From and To time stamp should be Epoch timestamp in seconds from_time = request.args.get('from') to_time = request.args.get('to') if search_user_id: # Filter on user_id query = query.filter(Query.user_id == search_user_id) if database_id: # Filter on db Id query = query.filter(Query.database_id == database_id) if status: # Filter on status query = query.filter(Query.status == status) if search_text: # Filter on search text query = query \ .filter(Query.sql.like('%{}%'.format(search_text))) if from_time: query = query.filter(Query.start_time > int(from_time)) if to_time: query = query.filter(Query.start_time < int(to_time)) query_limit = config.get('QUERY_SEARCH_LIMIT', 1000) sql_queries = ( query.order_by(Query.start_time.asc()) .limit(query_limit) .all() ) dict_queries = [q.to_dict() for q in sql_queries] return Response( json.dumps(dict_queries, default=utils.json_int_dttm_ser), status=200, mimetype='application/json')
[ "def", "search_queries", "(", "self", ")", "->", "Response", ":", "query", "=", "db", ".", "session", ".", "query", "(", "Query", ")", "if", "security_manager", ".", "can_only_access_owned_queries", "(", ")", ":", "search_user_id", "=", "g", ".", "user", "...
Search for previously run sqllab queries. Used for Sqllab Query Search page /superset/sqllab#search. Custom permission can_only_search_queries_owned restricts queries to only queries run by current user. :returns: Response with list of sql query dicts
[ "Search", "for", "previously", "run", "sqllab", "queries", ".", "Used", "for", "Sqllab", "Query", "Search", "page", "/", "superset", "/", "sqllab#search", "." ]
python
train
major/supernova
supernova/supernova.py
https://github.com/major/supernova/blob/4a217ae53c1c05567014b047c0b6b9dea2d383b3/supernova/supernova.py#L91-L103
def handle_stderr(stderr_pipe): """ Takes stderr from the command's output and displays it AFTER the stdout is printed by run_command(). """ stderr_output = stderr_pipe.read() if len(stderr_output) > 0: click.secho("\n__ Error Output {0}".format('_'*62), fg='white', bold=True) click.echo(stderr_output) return True
[ "def", "handle_stderr", "(", "stderr_pipe", ")", ":", "stderr_output", "=", "stderr_pipe", ".", "read", "(", ")", "if", "len", "(", "stderr_output", ")", ">", "0", ":", "click", ".", "secho", "(", "\"\\n__ Error Output {0}\"", ".", "format", "(", "'_'", "*...
Takes stderr from the command's output and displays it AFTER the stdout is printed by run_command().
[ "Takes", "stderr", "from", "the", "command", "s", "output", "and", "displays", "it", "AFTER", "the", "stdout", "is", "printed", "by", "run_command", "()", "." ]
python
train
spencerahill/aospy
aospy/utils/vertcoord.py
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L167-L228
def dp_from_p(p, ps, p_top=0., p_bot=1.1e5): """Get level thickness of pressure data, incorporating surface pressure. Level edges are defined as halfway between the levels, as well as the user- specified uppermost and lowermost values. The dp of levels whose bottom pressure is less than the surface pressure is not changed by ps, since they don't intersect the surface. If ps is in between a level's top and bottom pressures, then its dp becomes the pressure difference between its top and ps. If ps is less than a level's top and bottom pressures, then that level is underground and its values are masked. Note that postprocessing routines (e.g. at GFDL) typically mask out data wherever the surface pressure is less than the level's given value, not the level's upper edge. This masks out more levels than the """ p_str = get_dim_name(p, (internal_names.PLEVEL_STR, 'plev')) p_vals = to_pascal(p.values.copy()) # Layer edges are halfway between the given pressure levels. p_edges_interior = 0.5*(p_vals[:-1] + p_vals[1:]) p_edges = np.concatenate(([p_bot], p_edges_interior, [p_top])) p_edge_above = p_edges[1:] p_edge_below = p_edges[:-1] dp = p_edge_below - p_edge_above if not all(np.sign(dp)): raise ValueError("dp array not all > 0 : {}".format(dp)) # Pressure difference between ps and the upper edge of each pressure level. p_edge_above_xr = xr.DataArray(p_edge_above, dims=p.dims, coords=p.coords) dp_to_sfc = ps - p_edge_above_xr # Find the level adjacent to the masked, under-ground levels. change = xr.DataArray(np.zeros(dp_to_sfc.shape), dims=dp_to_sfc.dims, coords=dp_to_sfc.coords) change[{p_str: slice(1, None)}] = np.diff( np.sign(ps - to_pascal(p.copy())) ) dp_combined = xr.DataArray(np.where(change, dp_to_sfc, dp), dims=dp_to_sfc.dims, coords=dp_to_sfc.coords) # Mask levels that are under ground. above_ground = ps > to_pascal(p.copy()) above_ground[p_str] = p[p_str] dp_with_ps = dp_combined.where(above_ground) # Revert to original dim order. possible_dim_orders = [ (internal_names.TIME_STR, p_str, internal_names.LAT_STR, internal_names.LON_STR), (internal_names.TIME_STR, p_str, internal_names.LAT_STR), (internal_names.TIME_STR, p_str, internal_names.LON_STR), (internal_names.TIME_STR, p_str), (p_str, internal_names.LAT_STR, internal_names.LON_STR), (p_str, internal_names.LAT_STR), (p_str, internal_names.LON_STR), (p_str,), ] for dim_order in possible_dim_orders: try: return dp_with_ps.transpose(*dim_order) except ValueError: logging.debug("Failed transpose to dims: {}".format(dim_order)) else: logging.debug("No transpose was successful.") return dp_with_ps
[ "def", "dp_from_p", "(", "p", ",", "ps", ",", "p_top", "=", "0.", ",", "p_bot", "=", "1.1e5", ")", ":", "p_str", "=", "get_dim_name", "(", "p", ",", "(", "internal_names", ".", "PLEVEL_STR", ",", "'plev'", ")", ")", "p_vals", "=", "to_pascal", "(", ...
Get level thickness of pressure data, incorporating surface pressure. Level edges are defined as halfway between the levels, as well as the user- specified uppermost and lowermost values. The dp of levels whose bottom pressure is less than the surface pressure is not changed by ps, since they don't intersect the surface. If ps is in between a level's top and bottom pressures, then its dp becomes the pressure difference between its top and ps. If ps is less than a level's top and bottom pressures, then that level is underground and its values are masked. Note that postprocessing routines (e.g. at GFDL) typically mask out data wherever the surface pressure is less than the level's given value, not the level's upper edge. This masks out more levels than the
[ "Get", "level", "thickness", "of", "pressure", "data", "incorporating", "surface", "pressure", "." ]
python
train
NewKnowledge/punk
punk/feature_selection/pca.py
https://github.com/NewKnowledge/punk/blob/b5c96aeea74728fc64290bb0f6dabc97b827e4e9/punk/feature_selection/pca.py#L9-L61
def rank_features(self, inputs: pd.DataFrame) -> pd.DataFrame: """ Perform PCA and return a list of the indices of the most important features, ordered by contribution to first PCA component The matrix M will correspond to the absolute value of the components of the decomposiiton thus giving a matrix where each column corresponds to a principal component and rows are the components that rescale each feature. For example, pca.components_.T could look like this: array([[ 0.52237162, 0.37231836, -0.72101681, -0.26199559], [-0.26335492, 0.92555649, 0.24203288, 0.12413481], [ 0.58125401, 0.02109478, 0.14089226, 0.80115427], [ 0.56561105, 0.06541577, 0.6338014 , -0.52354627]]) So the most important feature with respect to the first principal component would be the 3rd feature as this has an absolute value of 0.58125401 which is greater than all the entries in that column. "importance_on1stpc" corresponds to the indices of most important features for the first principal. Component are in ascending order (most important feature 0, least important feature n_features-1). Params ------- data : np.ndarray, [n_samples, n_features] Training data. """ pca = PCA() try: pca.fit(normalize( \ inputs.apply(pd.to_numeric, errors='coerce') \ .applymap(lambda x: 0.0 if np.isnan(x) else x) \ .values, axis=0)) importance_on1stpc= np.argsort( \ np.absolute( \ pca.components_[0,:]))[::-1] scores = [np.absolute(pca.components_[0,i]) for i in importance_on1stpc] except: logging.exception("Failed") # If any error occurs, just return indices in original order # In the future we should consider a better error handling strategy importance_on1stpc = [i for i in range(inputs.shape[0])] scores = [0.0 for i in importance_on1stpc] return pd.DataFrame({'features': importance_on1stpc, 'scores': scores})
[ "def", "rank_features", "(", "self", ",", "inputs", ":", "pd", ".", "DataFrame", ")", "->", "pd", ".", "DataFrame", ":", "pca", "=", "PCA", "(", ")", "try", ":", "pca", ".", "fit", "(", "normalize", "(", "inputs", ".", "apply", "(", "pd", ".", "t...
Perform PCA and return a list of the indices of the most important features, ordered by contribution to first PCA component The matrix M will correspond to the absolute value of the components of the decomposiiton thus giving a matrix where each column corresponds to a principal component and rows are the components that rescale each feature. For example, pca.components_.T could look like this: array([[ 0.52237162, 0.37231836, -0.72101681, -0.26199559], [-0.26335492, 0.92555649, 0.24203288, 0.12413481], [ 0.58125401, 0.02109478, 0.14089226, 0.80115427], [ 0.56561105, 0.06541577, 0.6338014 , -0.52354627]]) So the most important feature with respect to the first principal component would be the 3rd feature as this has an absolute value of 0.58125401 which is greater than all the entries in that column. "importance_on1stpc" corresponds to the indices of most important features for the first principal. Component are in ascending order (most important feature 0, least important feature n_features-1). Params ------- data : np.ndarray, [n_samples, n_features] Training data.
[ "Perform", "PCA", "and", "return", "a", "list", "of", "the", "indices", "of", "the", "most", "important", "features", "ordered", "by", "contribution", "to", "first", "PCA", "component", "The", "matrix", "M", "will", "correspond", "to", "the", "absolute", "va...
python
train
dbtsai/python-mimeparse
mimeparse.py
https://github.com/dbtsai/python-mimeparse/blob/cf605c0994149b1a1936b3a8a597203fe3fbb62e/mimeparse.py#L14-L39
def parse_mime_type(mime_type): """Parses a mime-type into its component parts. Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xhtml', {'q', '0.5'}) :rtype: (str,str,dict) """ full_type, params = cgi.parse_header(mime_type) # Java URLConnection class sends an Accept header that includes a # single '*'. Turn it into a legal wildcard. if full_type == '*': full_type = '*/*' type_parts = full_type.split('/') if '/' in full_type else None if not type_parts or len(type_parts) > 2: raise MimeTypeParseException( "Can't parse type \"{}\"".format(full_type)) (type, subtype) = type_parts return (type.strip(), subtype.strip(), params)
[ "def", "parse_mime_type", "(", "mime_type", ")", ":", "full_type", ",", "params", "=", "cgi", ".", "parse_header", "(", "mime_type", ")", "# Java URLConnection class sends an Accept header that includes a", "# single '*'. Turn it into a legal wildcard.", "if", "full_type", "=...
Parses a mime-type into its component parts. Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xhtml', {'q', '0.5'}) :rtype: (str,str,dict)
[ "Parses", "a", "mime", "-", "type", "into", "its", "component", "parts", "." ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L300-L308
def interrupt_then_kill(self, delay=2.0): """Send INT, wait a delay and then send KILL.""" try: self.signal(SIGINT) except Exception: self.log.debug("interrupt failed") pass self.killer = ioloop.DelayedCallback(lambda : self.signal(SIGKILL), delay*1000, self.loop) self.killer.start()
[ "def", "interrupt_then_kill", "(", "self", ",", "delay", "=", "2.0", ")", ":", "try", ":", "self", ".", "signal", "(", "SIGINT", ")", "except", "Exception", ":", "self", ".", "log", ".", "debug", "(", "\"interrupt failed\"", ")", "pass", "self", ".", "...
Send INT, wait a delay and then send KILL.
[ "Send", "INT", "wait", "a", "delay", "and", "then", "send", "KILL", "." ]
python
test
wummel/dosage
dosagelib/events.py
https://github.com/wummel/dosage/blob/a0109c3a46219f280e6e5e77183674e40da0f304/dosagelib/events.py#L310-L314
def addHandler(name, basepath=None, baseurl=None, allowDownscale=False): """Add an event handler with given name.""" if basepath is None: basepath = '.' _handlers.append(_handler_classes[name](basepath, baseurl, allowDownscale))
[ "def", "addHandler", "(", "name", ",", "basepath", "=", "None", ",", "baseurl", "=", "None", ",", "allowDownscale", "=", "False", ")", ":", "if", "basepath", "is", "None", ":", "basepath", "=", "'.'", "_handlers", ".", "append", "(", "_handler_classes", ...
Add an event handler with given name.
[ "Add", "an", "event", "handler", "with", "given", "name", "." ]
python
train
samuraisam/django-json-rpc
jsonrpc/proxy.py
https://github.com/samuraisam/django-json-rpc/blob/a88d744d960e828f3eb21265da0f10a694b8ebcf/jsonrpc/proxy.py#L28-L53
def send_payload(self, params): """Performs the actual sending action and returns the result""" data = dumps({ 'jsonrpc': self.version, 'method': self.service_name, 'params': params, 'id': str(uuid.uuid1()) }).encode('utf-8') headers = { 'Content-Type': 'application/json-rpc', 'Accept': 'application/json-rpc', 'Content-Length': len(data) } try: req = urllib_request.Request(self.service_url, data, headers) resp = urllib_request.urlopen(req) except IOError as e: if isinstance(e, urllib_error.HTTPError): if e.code not in ( 401, 403 ) and e.headers['Content-Type'] == 'application/json-rpc': return e.read().decode('utf-8') # we got a jsonrpc-formatted respnose raise ServiceProxyException(e.code, e.headers, req) else: raise e return resp.read().decode('utf-8')
[ "def", "send_payload", "(", "self", ",", "params", ")", ":", "data", "=", "dumps", "(", "{", "'jsonrpc'", ":", "self", ".", "version", ",", "'method'", ":", "self", ".", "service_name", ",", "'params'", ":", "params", ",", "'id'", ":", "str", "(", "u...
Performs the actual sending action and returns the result
[ "Performs", "the", "actual", "sending", "action", "and", "returns", "the", "result" ]
python
train
opinkerfi/nago
nago/extensions/checkresults.py
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/extensions/checkresults.py#L31-L69
def post(hosts=None, services=None, check_existance=True, create_services=True, create_hosts=False): """ Puts a list of hosts into local instance of nagios checkresults Arguments: hosts -- list of dicts, like one obtained from get_checkresults services -- list of dicts, like one obtained from get_checkresults check_existance -- If True, check (and log) if objects already exist before posting create_services -- If True, autocreate non-existing services (where the host already exists) create_hosts -- If True, autocreate non-existing hosts """ nagios_config = config() nagios_config.parse_maincfg() check_result_path = nagios_config.get_cfg_value("check_result_path") fd, filename = tempfile.mkstemp(prefix='c', dir=check_result_path) if not hosts: hosts = [] if not services: services = [] if check_existance: checkresults_overhaul(hosts, services, create_services=create_services, create_hosts=create_hosts) checkresults = '### Active Check Result File Made by Nago ###\n' checkresults += 'file_time=%s' % (int(time.time())) checkresults = '' for host in hosts: checkresults += _format_checkresult(**host) for service in services: checkresults += _format_checkresult(**service) os.write(fd, checkresults) # Cleanup and make sure our file is readable by nagios os.close(fd) os.chmod(filename, 0644) # Create an ok file, so nagios knows it's ok to reap our changes file('%s.ok' % filename, 'w')
[ "def", "post", "(", "hosts", "=", "None", ",", "services", "=", "None", ",", "check_existance", "=", "True", ",", "create_services", "=", "True", ",", "create_hosts", "=", "False", ")", ":", "nagios_config", "=", "config", "(", ")", "nagios_config", ".", ...
Puts a list of hosts into local instance of nagios checkresults Arguments: hosts -- list of dicts, like one obtained from get_checkresults services -- list of dicts, like one obtained from get_checkresults check_existance -- If True, check (and log) if objects already exist before posting create_services -- If True, autocreate non-existing services (where the host already exists) create_hosts -- If True, autocreate non-existing hosts
[ "Puts", "a", "list", "of", "hosts", "into", "local", "instance", "of", "nagios", "checkresults", "Arguments", ":", "hosts", "--", "list", "of", "dicts", "like", "one", "obtained", "from", "get_checkresults", "services", "--", "list", "of", "dicts", "like", "...
python
train
slackapi/python-slackclient
slack/web/client.py
https://github.com/slackapi/python-slackclient/blob/901341c0284fd81e6d2719d6a0502308760d83e4/slack/web/client.py#L600-L603
def files_list(self, **kwargs) -> SlackResponse: """Lists & filters team files.""" self._validate_xoxp_token() return self.api_call("files.list", http_verb="GET", params=kwargs)
[ "def", "files_list", "(", "self", ",", "*", "*", "kwargs", ")", "->", "SlackResponse", ":", "self", ".", "_validate_xoxp_token", "(", ")", "return", "self", ".", "api_call", "(", "\"files.list\"", ",", "http_verb", "=", "\"GET\"", ",", "params", "=", "kwar...
Lists & filters team files.
[ "Lists", "&", "filters", "team", "files", "." ]
python
train
cnt-dev/cnt.rulebase
cnt/rulebase/const/utils.py
https://github.com/cnt-dev/cnt.rulebase/blob/d1c767c356d8ee05b23ec5b04aaac84784ee547c/cnt/rulebase/const/utils.py#L12-L24
def normalize_cjk_fullwidth_ascii(seq: str) -> str: """ Conver fullwith ASCII to halfwidth ASCII. See https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms """ def convert(char: str) -> str: code_point = ord(char) if not 0xFF01 <= code_point <= 0xFF5E: return char return chr(code_point - 0xFEE0) return ''.join(map(convert, seq))
[ "def", "normalize_cjk_fullwidth_ascii", "(", "seq", ":", "str", ")", "->", "str", ":", "def", "convert", "(", "char", ":", "str", ")", "->", "str", ":", "code_point", "=", "ord", "(", "char", ")", "if", "not", "0xFF01", "<=", "code_point", "<=", "0xFF5...
Conver fullwith ASCII to halfwidth ASCII. See https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms
[ "Conver", "fullwith", "ASCII", "to", "halfwidth", "ASCII", ".", "See", "https", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Halfwidth_and_fullwidth_forms" ]
python
train
user-cont/conu
conu/backend/podman/backend.py
https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/podman/backend.py#L36-L52
def parse_reference(reference): """ parse provided image reference into <image_repository>:<tag> :param reference: str, e.g. (registry.fedoraproject.org/fedora:27) :return: collection (tuple or list), ("registry.fedoraproject.org/fedora", "27") """ if ":" in reference: im, tag = reference.rsplit(":", 1) if "/" in tag: # this is case when there is port in the registry URI return (reference, "latest") else: return (im, tag) else: return (reference, "latest")
[ "def", "parse_reference", "(", "reference", ")", ":", "if", "\":\"", "in", "reference", ":", "im", ",", "tag", "=", "reference", ".", "rsplit", "(", "\":\"", ",", "1", ")", "if", "\"/\"", "in", "tag", ":", "# this is case when there is port in the registry URI...
parse provided image reference into <image_repository>:<tag> :param reference: str, e.g. (registry.fedoraproject.org/fedora:27) :return: collection (tuple or list), ("registry.fedoraproject.org/fedora", "27")
[ "parse", "provided", "image", "reference", "into", "<image_repository", ">", ":", "<tag", ">" ]
python
train
zarr-developers/zarr
zarr/core.py
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L1117-L1210
def set_basic_selection(self, selection, value, fields=None): """Modify data for an item or region of the array. Parameters ---------- selection : tuple An integer index or slice or tuple of int/slice specifying the requested region for each dimension of the array. value : scalar or array-like Value to be stored into the array. fields : str or sequence of str, optional For arrays with a structured dtype, one or more fields can be specified to set data for. Examples -------- Setup a 1-dimensional array:: >>> import zarr >>> import numpy as np >>> z = zarr.zeros(100, dtype=int) Set all array elements to the same scalar value:: >>> z.set_basic_selection(..., 42) >>> z[...] array([42, 42, 42, ..., 42, 42, 42]) Set a portion of the array:: >>> z.set_basic_selection(slice(10), np.arange(10)) >>> z.set_basic_selection(slice(-10, None), np.arange(10)[::-1]) >>> z[...] array([ 0, 1, 2, ..., 2, 1, 0]) Setup a 2-dimensional array:: >>> z = zarr.zeros((5, 5), dtype=int) Set all array elements to the same scalar value:: >>> z.set_basic_selection(..., 42) Set a portion of the array:: >>> z.set_basic_selection((0, slice(None)), np.arange(z.shape[1])) >>> z.set_basic_selection((slice(None), 0), np.arange(z.shape[0])) >>> z[...] array([[ 0, 1, 2, 3, 4], [ 1, 42, 42, 42, 42], [ 2, 42, 42, 42, 42], [ 3, 42, 42, 42, 42], [ 4, 42, 42, 42, 42]]) For arrays with a structured dtype, the `fields` parameter can be used to set data for a specific field, e.g.:: >>> a = np.array([(b'aaa', 1, 4.2), ... (b'bbb', 2, 8.4), ... (b'ccc', 3, 12.6)], ... dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')]) >>> z = zarr.array(a) >>> z.set_basic_selection(slice(0, 2), b'zzz', fields='foo') >>> z[:] array([(b'zzz', 1, 4.2), (b'zzz', 2, 8.4), (b'ccc', 3, 12.6)], dtype=[('foo', 'S3'), ('bar', '<i4'), ('baz', '<f8')]) Notes ----- This method provides the underlying implementation for modifying data via square bracket notation, see :func:`__setitem__` for equivalent examples using the alternative notation. See Also -------- get_basic_selection, get_mask_selection, set_mask_selection, get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection, set_orthogonal_selection, vindex, oindex, __getitem__, __setitem__ """ # guard conditions if self._read_only: err_read_only() # refresh metadata if not self._cache_metadata: self._load_metadata_nosync() # handle zero-dimensional arrays if self._shape == (): return self._set_basic_selection_zd(selection, value, fields=fields) else: return self._set_basic_selection_nd(selection, value, fields=fields)
[ "def", "set_basic_selection", "(", "self", ",", "selection", ",", "value", ",", "fields", "=", "None", ")", ":", "# guard conditions", "if", "self", ".", "_read_only", ":", "err_read_only", "(", ")", "# refresh metadata", "if", "not", "self", ".", "_cache_meta...
Modify data for an item or region of the array. Parameters ---------- selection : tuple An integer index or slice or tuple of int/slice specifying the requested region for each dimension of the array. value : scalar or array-like Value to be stored into the array. fields : str or sequence of str, optional For arrays with a structured dtype, one or more fields can be specified to set data for. Examples -------- Setup a 1-dimensional array:: >>> import zarr >>> import numpy as np >>> z = zarr.zeros(100, dtype=int) Set all array elements to the same scalar value:: >>> z.set_basic_selection(..., 42) >>> z[...] array([42, 42, 42, ..., 42, 42, 42]) Set a portion of the array:: >>> z.set_basic_selection(slice(10), np.arange(10)) >>> z.set_basic_selection(slice(-10, None), np.arange(10)[::-1]) >>> z[...] array([ 0, 1, 2, ..., 2, 1, 0]) Setup a 2-dimensional array:: >>> z = zarr.zeros((5, 5), dtype=int) Set all array elements to the same scalar value:: >>> z.set_basic_selection(..., 42) Set a portion of the array:: >>> z.set_basic_selection((0, slice(None)), np.arange(z.shape[1])) >>> z.set_basic_selection((slice(None), 0), np.arange(z.shape[0])) >>> z[...] array([[ 0, 1, 2, 3, 4], [ 1, 42, 42, 42, 42], [ 2, 42, 42, 42, 42], [ 3, 42, 42, 42, 42], [ 4, 42, 42, 42, 42]]) For arrays with a structured dtype, the `fields` parameter can be used to set data for a specific field, e.g.:: >>> a = np.array([(b'aaa', 1, 4.2), ... (b'bbb', 2, 8.4), ... (b'ccc', 3, 12.6)], ... dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')]) >>> z = zarr.array(a) >>> z.set_basic_selection(slice(0, 2), b'zzz', fields='foo') >>> z[:] array([(b'zzz', 1, 4.2), (b'zzz', 2, 8.4), (b'ccc', 3, 12.6)], dtype=[('foo', 'S3'), ('bar', '<i4'), ('baz', '<f8')]) Notes ----- This method provides the underlying implementation for modifying data via square bracket notation, see :func:`__setitem__` for equivalent examples using the alternative notation. See Also -------- get_basic_selection, get_mask_selection, set_mask_selection, get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection, set_orthogonal_selection, vindex, oindex, __getitem__, __setitem__
[ "Modify", "data", "for", "an", "item", "or", "region", "of", "the", "array", "." ]
python
train
mwickert/scikit-dsp-comm
sk_dsp_comm/rtlsdr_helper.py
https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/rtlsdr_helper.py#L305-L340
def fsk_BEP(rx_data,m,flip): """ fsk_BEP(rx_data,m,flip) Estimate the BEP of the data bits recovered by the RTL-SDR Based FSK Receiver. The reference m-sequence generated in Python was found to produce sequences running in the opposite direction relative to the m-sequences generated by the mbed. To allow error detection the reference m-sequence is flipped. Mark Wickert April 2014 """ Nbits = len(rx_data) c = dc.m_seq(m) if flip == 1: # Flip the sequence to compenstate for mbed code difference # First make it a 1xN array c.shape = (1,len(c)) c = np.fliplr(c).flatten() L = int(np.ceil(Nbits/float(len(c)))) tx_data = np.dot(c.reshape(len(c),1),np.ones((1,L))) tx_data = tx_data.T.reshape((1,len(c)*L)).flatten() tx_data = tx_data[:Nbits] # Convert to +1/-1 bits tx_data = 2*tx_data - 1 Bit_count,Bit_errors = dc.BPSK_BEP(rx_data,tx_data) print('len rx_data = %d, len tx_data = %d' % (len(rx_data),len(tx_data))) Pe = Bit_errors/float(Bit_count) print('/////////////////////////////////////') print('Bit Errors: %d' % Bit_errors) print('Bits Total: %d' % Bit_count) print(' BEP: %2.2e' % Pe) print('/////////////////////////////////////')
[ "def", "fsk_BEP", "(", "rx_data", ",", "m", ",", "flip", ")", ":", "Nbits", "=", "len", "(", "rx_data", ")", "c", "=", "dc", ".", "m_seq", "(", "m", ")", "if", "flip", "==", "1", ":", "# Flip the sequence to compenstate for mbed code difference\r", "# Firs...
fsk_BEP(rx_data,m,flip) Estimate the BEP of the data bits recovered by the RTL-SDR Based FSK Receiver. The reference m-sequence generated in Python was found to produce sequences running in the opposite direction relative to the m-sequences generated by the mbed. To allow error detection the reference m-sequence is flipped. Mark Wickert April 2014
[ "fsk_BEP", "(", "rx_data", "m", "flip", ")", "Estimate", "the", "BEP", "of", "the", "data", "bits", "recovered", "by", "the", "RTL", "-", "SDR", "Based", "FSK", "Receiver", ".", "The", "reference", "m", "-", "sequence", "generated", "in", "Python", "was"...
python
valid
ethereum/py-evm
eth/vm/logic/comparison.py
https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/logic/comparison.py#L145-L156
def byte_op(computation: BaseComputation) -> None: """ Bitwise And """ position, value = computation.stack_pop(num_items=2, type_hint=constants.UINT256) if position >= 32: result = 0 else: result = (value // pow(256, 31 - position)) % 256 computation.stack_push(result)
[ "def", "byte_op", "(", "computation", ":", "BaseComputation", ")", "->", "None", ":", "position", ",", "value", "=", "computation", ".", "stack_pop", "(", "num_items", "=", "2", ",", "type_hint", "=", "constants", ".", "UINT256", ")", "if", "position", ">=...
Bitwise And
[ "Bitwise", "And" ]
python
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L721-L757
def DownloadFile(hUcs, source, destination): """ Method provides the functionality to download file from the UCS. This method is used in BackupUcs and GetTechSupport to download the files from the Ucs. """ import urllib2 from sys import stdout from time import sleep httpAddress = "%s/%s" % (hUcs.Uri(), source) file_name = httpAddress.split('/')[-1] req = urllib2.Request(httpAddress) # send the new url with the cookie. req.add_header('Cookie', 'ucsm-cookie=%s' % (hUcs._cookie)) res = urllib2.urlopen(req) meta = res.info() file_size = int(meta.getheaders("Content-Length")[0]) print "Downloading: %s Bytes: %s" % (file_name, file_size) f = open(destination, 'wb') file_size_dl = 0 block_sz = 8192 while True: rBuffer = res.read(block_sz) if not rBuffer: break file_size_dl += len(rBuffer) f.write(rBuffer) status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) status = status + chr(8) * (len(status) + 1) stdout.write("\r%s" % status) stdout.flush() # print status f.close()
[ "def", "DownloadFile", "(", "hUcs", ",", "source", ",", "destination", ")", ":", "import", "urllib2", "from", "sys", "import", "stdout", "from", "time", "import", "sleep", "httpAddress", "=", "\"%s/%s\"", "%", "(", "hUcs", ".", "Uri", "(", ")", ",", "sou...
Method provides the functionality to download file from the UCS. This method is used in BackupUcs and GetTechSupport to download the files from the Ucs.
[ "Method", "provides", "the", "functionality", "to", "download", "file", "from", "the", "UCS", ".", "This", "method", "is", "used", "in", "BackupUcs", "and", "GetTechSupport", "to", "download", "the", "files", "from", "the", "Ucs", "." ]
python
train
dhermes/bezier
src/bezier/_helpers.py
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_helpers.py#L135-L159
def _contains_nd(nodes, point): r"""Predicate indicating if a point is within a bounding box. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): A set of points. point (numpy.ndarray): A 1D NumPy array representing a point in the same dimension as ``nodes``. Returns: bool: Indicating containment. """ min_vals = np.min(nodes, axis=1) if not np.all(min_vals <= point): return False max_vals = np.max(nodes, axis=1) if not np.all(point <= max_vals): return False return True
[ "def", "_contains_nd", "(", "nodes", ",", "point", ")", ":", "min_vals", "=", "np", ".", "min", "(", "nodes", ",", "axis", "=", "1", ")", "if", "not", "np", ".", "all", "(", "min_vals", "<=", "point", ")", ":", "return", "False", "max_vals", "=", ...
r"""Predicate indicating if a point is within a bounding box. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): A set of points. point (numpy.ndarray): A 1D NumPy array representing a point in the same dimension as ``nodes``. Returns: bool: Indicating containment.
[ "r", "Predicate", "indicating", "if", "a", "point", "is", "within", "a", "bounding", "box", "." ]
python
train
thriftrw/thriftrw-python
thriftrw/idl/parser.py
https://github.com/thriftrw/thriftrw-python/blob/4f2f71acd7a0ac716c9ea5cdcea2162aa561304a/thriftrw/idl/parser.py#L68-L74
def p_include(self, p): '''include : INCLUDE IDENTIFIER LITERAL | INCLUDE LITERAL''' if len(p) == 4: p[0] = ast.Include(name=p[2], path=p[3], lineno=p.lineno(1)) else: p[0] = ast.Include(name=None, path=p[2], lineno=p.lineno(1))
[ "def", "p_include", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", "==", "4", ":", "p", "[", "0", "]", "=", "ast", ".", "Include", "(", "name", "=", "p", "[", "2", "]", ",", "path", "=", "p", "[", "3", "]", ",", "lineno", ...
include : INCLUDE IDENTIFIER LITERAL | INCLUDE LITERAL
[ "include", ":", "INCLUDE", "IDENTIFIER", "LITERAL", "|", "INCLUDE", "LITERAL" ]
python
train
darkowlzz/pokemonNames
pokemonNames/pokemonNames.py
https://github.com/darkowlzz/pokemonNames/blob/fe4b9cf2108115c8a090193247413dcb5416fcff/pokemonNames/pokemonNames.py#L69-L90
def append_to_list(self, source, start=None, hasIndex=False): '''Appends new list to self.nameDict Argument: source -- source of new name list (filename or list) start -- starting index of new list hasIndex -- the file is already indexed ''' nfy = Numberify() try: if start is None: if type(source) is str: if hasIndex is True: newList = self.get_from_indexedFile(source) else: newList = nfy.numberify_data(source, len(self.nameDict) + 1) else: newList = nfy.numberify_data(source, start) self.nameDict = dict(self.nameDict.items() + newList.items()) self.totalCount = len(self.nameDict) except: print 'Unknown error:', exc_info()[0]
[ "def", "append_to_list", "(", "self", ",", "source", ",", "start", "=", "None", ",", "hasIndex", "=", "False", ")", ":", "nfy", "=", "Numberify", "(", ")", "try", ":", "if", "start", "is", "None", ":", "if", "type", "(", "source", ")", "is", "str",...
Appends new list to self.nameDict Argument: source -- source of new name list (filename or list) start -- starting index of new list hasIndex -- the file is already indexed
[ "Appends", "new", "list", "to", "self", ".", "nameDict", "Argument", ":", "source", "--", "source", "of", "new", "name", "list", "(", "filename", "or", "list", ")", "start", "--", "starting", "index", "of", "new", "list", "hasIndex", "--", "the", "file",...
python
train
rndusr/torf
torf/_torrent.py
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L258-L274
def piece_size(self): """ Piece size/length or ``None`` If set to ``None``, :attr:`calculate_piece_size` is called. If :attr:`size` returns ``None``, this also returns ``None``. Setting this property sets ``piece length`` in :attr:`metainfo`\ ``['info']``. """ if 'piece length' not in self.metainfo['info']: if self.size is None: return None else: self.calculate_piece_size() return self.metainfo['info']['piece length']
[ "def", "piece_size", "(", "self", ")", ":", "if", "'piece length'", "not", "in", "self", ".", "metainfo", "[", "'info'", "]", ":", "if", "self", ".", "size", "is", "None", ":", "return", "None", "else", ":", "self", ".", "calculate_piece_size", "(", ")...
Piece size/length or ``None`` If set to ``None``, :attr:`calculate_piece_size` is called. If :attr:`size` returns ``None``, this also returns ``None``. Setting this property sets ``piece length`` in :attr:`metainfo`\ ``['info']``.
[ "Piece", "size", "/", "length", "or", "None" ]
python
train
ansible/tower-cli
tower_cli/models/base.py
https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/models/base.py#L1135-L1173
def relaunch(self, pk=None, **kwargs): """Relaunch a stopped job. Fails with a non-zero exit status if the job cannot be relaunched. You must provide either a pk or parameters in the job's identity. =====API DOCS===== Relaunch a stopped job resource. :param pk: Primary key of the job resource to relaunch. :type pk: int :param `**kwargs`: Keyword arguments used to look up job resource object to relaunch if ``pk`` is not provided. :returns: A dictionary combining the JSON output of the relaunched job resource object, as well as an extra field "changed", a flag indicating if the job resource object is status-changed as expected. :rtype: dict =====API DOCS===== """ # Search for the record if pk not given if not pk: existing_data = self.get(**kwargs) pk = existing_data['id'] relaunch_endpoint = '%s%s/relaunch/' % (self.endpoint, pk) data = {} # Attempt to relaunch the job. answer = {} try: result = client.post(relaunch_endpoint, data=data).json() if 'id' in result: answer.update(result) answer['changed'] = True except exc.MethodNotAllowed: answer['changed'] = False # Return the answer. return answer
[ "def", "relaunch", "(", "self", ",", "pk", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Search for the record if pk not given", "if", "not", "pk", ":", "existing_data", "=", "self", ".", "get", "(", "*", "*", "kwargs", ")", "pk", "=", "existing_dat...
Relaunch a stopped job. Fails with a non-zero exit status if the job cannot be relaunched. You must provide either a pk or parameters in the job's identity. =====API DOCS===== Relaunch a stopped job resource. :param pk: Primary key of the job resource to relaunch. :type pk: int :param `**kwargs`: Keyword arguments used to look up job resource object to relaunch if ``pk`` is not provided. :returns: A dictionary combining the JSON output of the relaunched job resource object, as well as an extra field "changed", a flag indicating if the job resource object is status-changed as expected. :rtype: dict =====API DOCS=====
[ "Relaunch", "a", "stopped", "job", "." ]
python
valid
michael-lazar/rtv
rtv/packages/praw/__init__.py
https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/__init__.py#L1579-L1606
def set_access_credentials(self, scope, access_token, refresh_token=None, update_user=True): """Set the credentials used for OAuth2 authentication. Calling this function will overwrite any currently existing access credentials. :param scope: A set of reddit scopes the tokens provide access to :param access_token: the access token of the authentication :param refresh_token: the refresh token of the authentication :param update_user: Whether or not to set the user attribute for identity scopes """ if isinstance(scope, (list, tuple)): scope = set(scope) elif isinstance(scope, six.string_types): scope = set(scope.split()) if not isinstance(scope, set): raise TypeError('`scope` parameter must be a set') self.clear_authentication() # Update authentication settings self._authentication = scope self.access_token = access_token self.refresh_token = refresh_token # Update the user object if update_user and ('identity' in scope or '*' in scope): self.user = self.get_me()
[ "def", "set_access_credentials", "(", "self", ",", "scope", ",", "access_token", ",", "refresh_token", "=", "None", ",", "update_user", "=", "True", ")", ":", "if", "isinstance", "(", "scope", ",", "(", "list", ",", "tuple", ")", ")", ":", "scope", "=", ...
Set the credentials used for OAuth2 authentication. Calling this function will overwrite any currently existing access credentials. :param scope: A set of reddit scopes the tokens provide access to :param access_token: the access token of the authentication :param refresh_token: the refresh token of the authentication :param update_user: Whether or not to set the user attribute for identity scopes
[ "Set", "the", "credentials", "used", "for", "OAuth2", "authentication", "." ]
python
train
bennylope/django-organizations
organizations/backends/defaults.py
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/defaults.py#L153-L161
def send_reminder(self, user, sender=None, **kwargs): """Sends a reminder email to the specified user""" if user.is_active: return False token = RegistrationTokenGenerator().make_token(user) kwargs.update({"token": token}) self.email_message( user, self.reminder_subject, self.reminder_body, sender, **kwargs ).send()
[ "def", "send_reminder", "(", "self", ",", "user", ",", "sender", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "user", ".", "is_active", ":", "return", "False", "token", "=", "RegistrationTokenGenerator", "(", ")", ".", "make_token", "(", "user",...
Sends a reminder email to the specified user
[ "Sends", "a", "reminder", "email", "to", "the", "specified", "user" ]
python
train
lreis2415/PyGeoC
examples/ex08_raster_connectivity_analysis.py
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/examples/ex08_raster_connectivity_analysis.py#L91-L110
def draw_ID(ID, idx_array, drawID_raster): """Draw every pixel's ID After computing all given value's pixels connectivity, every pixel will have an ID. Then we need to draw these pixels' ID on the undrawed rasterfile. Args: ID: given ID value idx_array: pixels position set which have the given ID value drawID_raster: undrawed rasterfile Return: drawID_raster: rasterfile after drawing ID """ for i in range(idx_array.shape[0]): x = idx_array[i, 0] y = idx_array[i, 1] drawID_raster[x, y] = ID return drawID_raster
[ "def", "draw_ID", "(", "ID", ",", "idx_array", ",", "drawID_raster", ")", ":", "for", "i", "in", "range", "(", "idx_array", ".", "shape", "[", "0", "]", ")", ":", "x", "=", "idx_array", "[", "i", ",", "0", "]", "y", "=", "idx_array", "[", "i", ...
Draw every pixel's ID After computing all given value's pixels connectivity, every pixel will have an ID. Then we need to draw these pixels' ID on the undrawed rasterfile. Args: ID: given ID value idx_array: pixels position set which have the given ID value drawID_raster: undrawed rasterfile Return: drawID_raster: rasterfile after drawing ID
[ "Draw", "every", "pixel", "s", "ID", "After", "computing", "all", "given", "value", "s", "pixels", "connectivity", "every", "pixel", "will", "have", "an", "ID", ".", "Then", "we", "need", "to", "draw", "these", "pixels", "ID", "on", "the", "undrawed", "r...
python
train
boundary/pulse-api-cli
boundary/metric_markdown.py
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/metric_markdown.py#L116-L125
def getMetricsColumnLengths(self): """ Gets the maximum length of each column """ displayLen = 0 descLen = 0 for m in self.metrics: displayLen = max(displayLen, len(m['displayName'])) descLen = max(descLen, len(m['description'])) return (displayLen, descLen)
[ "def", "getMetricsColumnLengths", "(", "self", ")", ":", "displayLen", "=", "0", "descLen", "=", "0", "for", "m", "in", "self", ".", "metrics", ":", "displayLen", "=", "max", "(", "displayLen", ",", "len", "(", "m", "[", "'displayName'", "]", ")", ")",...
Gets the maximum length of each column
[ "Gets", "the", "maximum", "length", "of", "each", "column" ]
python
test
lsst-sqre/lsst-projectmeta-kit
lsstprojectmeta/github/graphql.py
https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/github/graphql.py#L80-L106
def load(cls, query_name): """Load a pre-made query. These queries are distributed with lsstprojectmeta. See :file:`lsstrojectmeta/data/githubv4/README.rst` inside the package repository for details on available queries. Parameters ---------- query_name : `str` Name of the query, such as ``'technote_repo'``. Returns ------- github_query : `GitHubQuery A GitHub query or mutation object that you can pass to `github_request` to execute the request itself. """ template_path = os.path.join( os.path.dirname(__file__), '../data/githubv4', query_name + '.graphql') with open(template_path) as f: query_data = f.read() return cls(query_data, name=query_name)
[ "def", "load", "(", "cls", ",", "query_name", ")", ":", "template_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../data/githubv4'", ",", "query_name", "+", "'.graphql'", ")", "with", "o...
Load a pre-made query. These queries are distributed with lsstprojectmeta. See :file:`lsstrojectmeta/data/githubv4/README.rst` inside the package repository for details on available queries. Parameters ---------- query_name : `str` Name of the query, such as ``'technote_repo'``. Returns ------- github_query : `GitHubQuery A GitHub query or mutation object that you can pass to `github_request` to execute the request itself.
[ "Load", "a", "pre", "-", "made", "query", "." ]
python
valid
twilio/twilio-python
twilio/rest/api/v2010/account/sip/domain/auth_types/__init__.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/sip/domain/auth_types/__init__.py#L40-L53
def calls(self): """ Access the calls :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsList :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsList """ if self._calls is None: self._calls = AuthTypeCallsList( self._version, account_sid=self._solution['account_sid'], domain_sid=self._solution['domain_sid'], ) return self._calls
[ "def", "calls", "(", "self", ")", ":", "if", "self", ".", "_calls", "is", "None", ":", "self", ".", "_calls", "=", "AuthTypeCallsList", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", "do...
Access the calls :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsList :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsList
[ "Access", "the", "calls" ]
python
train
Yelp/detect-secrets
detect_secrets/plugins/common/ini_file_parser.py
https://github.com/Yelp/detect-secrets/blob/473923ea71f1ac2b5ea1eacc49b98f97967e3d05/detect_secrets/plugins/common/ini_file_parser.py#L82-L153
def _get_value_and_line_offset(self, key, values): """Returns the index of the location of key, value pair in lines. :type key: str :param key: key, in config file. :type values: str :param values: values for key, in config file. This is plural, because you can have multiple values per key. e.g. >>> key = ... value1 ... value2 :type lines: list :param lines: a collection of lines-so-far in file :rtype: list(tuple) """ values_list = self._construct_values_list(values) if not values_list: return [] current_value_list_index = 0 output = [] lines_modified = False for index, line in enumerate(self.lines): # Check ignored lines before checking values, because # you can write comments *after* the value. if not line.strip() or self._comment_regex.match(line): continue if ( self.exclude_lines_regex and self.exclude_lines_regex.search(line) ): continue if current_value_list_index == 0: first_line_regex = re.compile(r'^\s*{}[ :=]+{}'.format( re.escape(key), re.escape(values_list[current_value_list_index]), )) if first_line_regex.match(line): output.append(( values_list[current_value_list_index], self.line_offset + index + 1, )) current_value_list_index += 1 continue if current_value_list_index == len(values_list): if index == 0: index = 1 # don't want to count the same line again self.line_offset += index self.lines = self.lines[index:] lines_modified = True break else: output.append(( values_list[current_value_list_index], self.line_offset + index + 1, )) current_value_list_index += 1 if not lines_modified: # No more lines left, if loop was not explicitly left. self.lines = [] return output
[ "def", "_get_value_and_line_offset", "(", "self", ",", "key", ",", "values", ")", ":", "values_list", "=", "self", ".", "_construct_values_list", "(", "values", ")", "if", "not", "values_list", ":", "return", "[", "]", "current_value_list_index", "=", "0", "ou...
Returns the index of the location of key, value pair in lines. :type key: str :param key: key, in config file. :type values: str :param values: values for key, in config file. This is plural, because you can have multiple values per key. e.g. >>> key = ... value1 ... value2 :type lines: list :param lines: a collection of lines-so-far in file :rtype: list(tuple)
[ "Returns", "the", "index", "of", "the", "location", "of", "key", "value", "pair", "in", "lines", "." ]
python
train
slundberg/shap
shap/benchmark/metrics.py
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/metrics.py#L324-L331
def remove_absolute_impute__r2(X, y, model_generator, method_name, num_fcounts=11): """ Remove Absolute (impute) xlabel = "Max fraction of features removed" ylabel = "1 - R^2" transform = "one_minus" sort_order = 9 """ return __run_measure(measures.remove_impute, X, y, model_generator, method_name, 0, num_fcounts, sklearn.metrics.r2_score)
[ "def", "remove_absolute_impute__r2", "(", "X", ",", "y", ",", "model_generator", ",", "method_name", ",", "num_fcounts", "=", "11", ")", ":", "return", "__run_measure", "(", "measures", ".", "remove_impute", ",", "X", ",", "y", ",", "model_generator", ",", "...
Remove Absolute (impute) xlabel = "Max fraction of features removed" ylabel = "1 - R^2" transform = "one_minus" sort_order = 9
[ "Remove", "Absolute", "(", "impute", ")", "xlabel", "=", "Max", "fraction", "of", "features", "removed", "ylabel", "=", "1", "-", "R^2", "transform", "=", "one_minus", "sort_order", "=", "9" ]
python
train
ShadowBlip/Neteria
neteria/core.py
https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/core.py#L324-L360
def send_datagram(self, message, address, message_type="unicast"): """Sends a UDP datagram packet to the requested address. Datagrams can be sent as a "unicast", "multicast", or "broadcast" message. Unicast messages are messages that will be sent to a single host, multicast messages will be delivered to all hosts listening for multicast messages, and broadcast messages will be delivered to ALL hosts on the network. Args: message (str): The raw serialized packet data to send. address (tuple): The address and port of the destination to send the packet. E.g. (address, port) message_type -- The type of packet to send. Can be "unicast", "multicast", or "broadcast". Defaults to "unicast". Returns: None """ if self.bufsize is not 0 and len(message) > self.bufsize: raise Exception("Datagram is too large. Messages should be " + "under " + str(self.bufsize) + " bytes in size.") if message_type == "broadcast": self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) elif message_type == "multicast": self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) try: logger.debug("Sending packet") self.sock.sendto(message, address) if self.stats_enabled: self.stats['bytes_sent'] += len(message) except socket.error: logger.error("Failed to send, [Errno 101]: Network is unreachable.")
[ "def", "send_datagram", "(", "self", ",", "message", ",", "address", ",", "message_type", "=", "\"unicast\"", ")", ":", "if", "self", ".", "bufsize", "is", "not", "0", "and", "len", "(", "message", ")", ">", "self", ".", "bufsize", ":", "raise", "Excep...
Sends a UDP datagram packet to the requested address. Datagrams can be sent as a "unicast", "multicast", or "broadcast" message. Unicast messages are messages that will be sent to a single host, multicast messages will be delivered to all hosts listening for multicast messages, and broadcast messages will be delivered to ALL hosts on the network. Args: message (str): The raw serialized packet data to send. address (tuple): The address and port of the destination to send the packet. E.g. (address, port) message_type -- The type of packet to send. Can be "unicast", "multicast", or "broadcast". Defaults to "unicast". Returns: None
[ "Sends", "a", "UDP", "datagram", "packet", "to", "the", "requested", "address", "." ]
python
train
Nekroze/partpy
partpy/sourcestring.py
https://github.com/Nekroze/partpy/blob/dbb7d2fb285464fc43d85bc31f5af46192d301f6/partpy/sourcestring.py#L212-L233
def get_current_line(self): """Return a SourceLine of the current line.""" if not self.has_space(): return None pos = self.pos - self.col string = self.string end = self.length output = [] while pos < len(string) and string[pos] != '\n': output.append(string[pos]) pos += 1 if pos == end: break else: output.append(string[pos]) if not output: return None return SourceLine(''.join(output), self.row)
[ "def", "get_current_line", "(", "self", ")", ":", "if", "not", "self", ".", "has_space", "(", ")", ":", "return", "None", "pos", "=", "self", ".", "pos", "-", "self", ".", "col", "string", "=", "self", ".", "string", "end", "=", "self", ".", "lengt...
Return a SourceLine of the current line.
[ "Return", "a", "SourceLine", "of", "the", "current", "line", "." ]
python
train
tariqdaouda/pyGeno
pyGeno/tools/parsers/CSVTools.py
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/CSVTools.py#L350-L355
def newLine(self) : """Appends an empty line at the end of the CSV and returns it""" l = CSVEntry(self) if self.keepInMemory : self.lines.append(l) return l
[ "def", "newLine", "(", "self", ")", ":", "l", "=", "CSVEntry", "(", "self", ")", "if", "self", ".", "keepInMemory", ":", "self", ".", "lines", ".", "append", "(", "l", ")", "return", "l" ]
Appends an empty line at the end of the CSV and returns it
[ "Appends", "an", "empty", "line", "at", "the", "end", "of", "the", "CSV", "and", "returns", "it" ]
python
train
lemieuxl/pyGenClean
pyGenClean/Ethnicity/find_outliers.py
https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/Ethnicity/find_outliers.py#L620-L649
def checkArgs(args): """Checks the arguments and options. :param args: a :py:class:`argparse.Namespace` object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` class, a message is printed to the :class:`sys.stderr` and the program exists with code 1. """ # Checking the input files if not os.path.isfile(args.mds): msg = "{}: no such file".format(args.mds) raise ProgramError(msg) if not os.path.isfile(args.population_file): msg = "{}: no such file".format(args.population_file) raise ProgramError(msg) # Checking the chosen components if args.xaxis == args.yaxis: msg = "xaxis must be different than yaxis" raise ProgramError(msg) return True
[ "def", "checkArgs", "(", "args", ")", ":", "# Checking the input files", "if", "not", "os", ".", "path", ".", "isfile", "(", "args", ".", "mds", ")", ":", "msg", "=", "\"{}: no such file\"", ".", "format", "(", "args", ".", "mds", ")", "raise", "ProgramE...
Checks the arguments and options. :param args: a :py:class:`argparse.Namespace` object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` class, a message is printed to the :class:`sys.stderr` and the program exists with code 1.
[ "Checks", "the", "arguments", "and", "options", "." ]
python
train
newfies-dialer/python-msspeak
msspeak/command_line.py
https://github.com/newfies-dialer/python-msspeak/blob/106475122be73df152865c4fe6e9388caf974085/msspeak/command_line.py#L40-L51
def validate_options(subscription_key, text): """ Perform sanity checks on threshold values """ if not subscription_key or len(subscription_key) == 0: print 'Error: Warning the option subscription_key should contain a string.' print USAGE sys.exit(3) if not text or len(text) == 0: print 'Error: Warning the option text should contain a string.' print USAGE sys.exit(3)
[ "def", "validate_options", "(", "subscription_key", ",", "text", ")", ":", "if", "not", "subscription_key", "or", "len", "(", "subscription_key", ")", "==", "0", ":", "print", "'Error: Warning the option subscription_key should contain a string.'", "print", "USAGE", "sy...
Perform sanity checks on threshold values
[ "Perform", "sanity", "checks", "on", "threshold", "values" ]
python
train
instaloader/instaloader
instaloader/instaloader.py
https://github.com/instaloader/instaloader/blob/87d877e650cd8020b04b8b51be120599a441fd5b/instaloader/instaloader.py#L94-L102
def format_field(self, value, format_spec): """Override :meth:`string.Formatter.format_field` to have our default format_spec for :class:`datetime.Datetime` objects, and to let None yield an empty string rather than ``None``.""" if isinstance(value, datetime) and not format_spec: return super().format_field(value, '%Y-%m-%d_%H-%M-%S') if value is None: return '' return super().format_field(value, format_spec)
[ "def", "format_field", "(", "self", ",", "value", ",", "format_spec", ")", ":", "if", "isinstance", "(", "value", ",", "datetime", ")", "and", "not", "format_spec", ":", "return", "super", "(", ")", ".", "format_field", "(", "value", ",", "'%Y-%m-%d_%H-%M-...
Override :meth:`string.Formatter.format_field` to have our default format_spec for :class:`datetime.Datetime` objects, and to let None yield an empty string rather than ``None``.
[ "Override", ":", "meth", ":", "string", ".", "Formatter", ".", "format_field", "to", "have", "our", "default", "format_spec", "for", ":", "class", ":", "datetime", ".", "Datetime", "objects", "and", "to", "let", "None", "yield", "an", "empty", "string", "r...
python
train
sony/nnabla
python/src/nnabla/models/imagenet/base.py
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/models/imagenet/base.py#L49-L67
def _load_nnp(self, rel_name, rel_url): ''' Args: rel_name: relative path to where donwloaded nnp is saved. rel_url: relative url path to where nnp is downloaded from. ''' from nnabla.utils.download import download path_nnp = os.path.join( get_model_home(), 'imagenet/{}'.format(rel_name)) url = os.path.join(get_model_url_base(), 'imagenet/{}'.format(rel_url)) logger.info('Downloading {} from {}'.format(rel_name, url)) dir_nnp = os.path.dirname(path_nnp) if not os.path.isdir(dir_nnp): os.makedirs(dir_nnp) download(url, path_nnp, open_file=False, allow_overwrite=False) print('Loading {}.'.format(path_nnp)) self.nnp = NnpLoader(path_nnp)
[ "def", "_load_nnp", "(", "self", ",", "rel_name", ",", "rel_url", ")", ":", "from", "nnabla", ".", "utils", ".", "download", "import", "download", "path_nnp", "=", "os", ".", "path", ".", "join", "(", "get_model_home", "(", ")", ",", "'imagenet/{}'", "."...
Args: rel_name: relative path to where donwloaded nnp is saved. rel_url: relative url path to where nnp is downloaded from.
[ "Args", ":", "rel_name", ":", "relative", "path", "to", "where", "donwloaded", "nnp", "is", "saved", ".", "rel_url", ":", "relative", "url", "path", "to", "where", "nnp", "is", "downloaded", "from", "." ]
python
train
gem/oq-engine
openquake/hmtk/plotting/mapping.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/mapping.py#L337-L361
def add_source_model( self, model, area_border='k-', border_width=1.0, point_marker='ks', point_size=2.0, overlay=False, min_depth=0., max_depth=None, alpha=1.0): """ Adds a source model to the map :param model: Source model of mixed typologies as instance of :class: openquake.hmtk.sources.source_model.mtkSourceModel """ for source in model.sources: if isinstance(source, mtkAreaSource): self._plot_area_source(source, area_border, border_width) elif isinstance(source, mtkPointSource): self._plot_point_source(source, point_marker, point_size) elif isinstance(source, mtkComplexFaultSource): self._plot_complex_fault(source, area_border, border_width, min_depth, max_depth, alpha) elif isinstance(source, mtkSimpleFaultSource): self._plot_simple_fault(source, area_border, border_width) else: pass if not overlay: plt.show()
[ "def", "add_source_model", "(", "self", ",", "model", ",", "area_border", "=", "'k-'", ",", "border_width", "=", "1.0", ",", "point_marker", "=", "'ks'", ",", "point_size", "=", "2.0", ",", "overlay", "=", "False", ",", "min_depth", "=", "0.", ",", "max_...
Adds a source model to the map :param model: Source model of mixed typologies as instance of :class: openquake.hmtk.sources.source_model.mtkSourceModel
[ "Adds", "a", "source", "model", "to", "the", "map" ]
python
train
kgori/treeCl
treeCl/tree.py
https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/tree.py#L1012-L1034
def randomise_branch_lengths( self, i=(1, 1), l=(1, 1), distribution_func=random.gammavariate, inplace=False, ): """ Replaces branch lengths with values drawn from the specified distribution_func. Parameters of the distribution are given in the tuples i and l, for interior and leaf nodes respectively. """ if not inplace: t = self.copy() else: t = self for n in t._tree.preorder_node_iter(): if n.is_internal(): n.edge.length = max(0, distribution_func(*i)) else: n.edge.length = max(0, distribution_func(*l)) t._dirty = True return t
[ "def", "randomise_branch_lengths", "(", "self", ",", "i", "=", "(", "1", ",", "1", ")", ",", "l", "=", "(", "1", ",", "1", ")", ",", "distribution_func", "=", "random", ".", "gammavariate", ",", "inplace", "=", "False", ",", ")", ":", "if", "not", ...
Replaces branch lengths with values drawn from the specified distribution_func. Parameters of the distribution are given in the tuples i and l, for interior and leaf nodes respectively.
[ "Replaces", "branch", "lengths", "with", "values", "drawn", "from", "the", "specified", "distribution_func", ".", "Parameters", "of", "the", "distribution", "are", "given", "in", "the", "tuples", "i", "and", "l", "for", "interior", "and", "leaf", "nodes", "res...
python
train
raiden-network/raiden
raiden/raiden_service.py
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L911-L936
def _initialize_messages_queues(self, chain_state: ChainState): """Initialize all the message queues with the transport. Note: All messages from the state queues must be pushed to the transport before it's started. This is necessary to avoid a race where the transport processes network messages too quickly, queueing new messages before any of the previous messages, resulting in new messages being out-of-order. The Alarm task must be started before this method is called, otherwise queues for channel closed while the node was offline won't be properly cleared. It is not bad but it is suboptimal. """ assert not self.transport, f'Transport is running. node:{self!r}' assert self.alarm.is_primed(), f'AlarmTask not primed. node:{self!r}' events_queues = views.get_all_messagequeues(chain_state) for queue_identifier, event_queue in events_queues.items(): self.start_health_check_for(queue_identifier.recipient) for event in event_queue: message = message_from_sendevent(event) self.sign(message) self.transport.send_async(queue_identifier, message)
[ "def", "_initialize_messages_queues", "(", "self", ",", "chain_state", ":", "ChainState", ")", ":", "assert", "not", "self", ".", "transport", ",", "f'Transport is running. node:{self!r}'", "assert", "self", ".", "alarm", ".", "is_primed", "(", ")", ",", "f'AlarmT...
Initialize all the message queues with the transport. Note: All messages from the state queues must be pushed to the transport before it's started. This is necessary to avoid a race where the transport processes network messages too quickly, queueing new messages before any of the previous messages, resulting in new messages being out-of-order. The Alarm task must be started before this method is called, otherwise queues for channel closed while the node was offline won't be properly cleared. It is not bad but it is suboptimal.
[ "Initialize", "all", "the", "message", "queues", "with", "the", "transport", "." ]
python
train
stanfordnlp/stanza
stanza/monitoring/summary.py
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/monitoring/summary.py#L168-L179
def flush(self): ''' Force all queued events to be written to the events file. The queue will automatically be flushed at regular time intervals, when it grows too large, and at program exit (with the usual caveats of `atexit`: this won't happen if the program is killed with a signal or `os._exit()`). ''' if self.queue: with open(self.filename, 'ab') as outfile: write_events(outfile, self.queue) del self.queue[:]
[ "def", "flush", "(", "self", ")", ":", "if", "self", ".", "queue", ":", "with", "open", "(", "self", ".", "filename", ",", "'ab'", ")", "as", "outfile", ":", "write_events", "(", "outfile", ",", "self", ".", "queue", ")", "del", "self", ".", "queue...
Force all queued events to be written to the events file. The queue will automatically be flushed at regular time intervals, when it grows too large, and at program exit (with the usual caveats of `atexit`: this won't happen if the program is killed with a signal or `os._exit()`).
[ "Force", "all", "queued", "events", "to", "be", "written", "to", "the", "events", "file", ".", "The", "queue", "will", "automatically", "be", "flushed", "at", "regular", "time", "intervals", "when", "it", "grows", "too", "large", "and", "at", "program", "e...
python
train
mwouts/jupytext
jupytext/formats.py
https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/formats.py#L279-L299
def divine_format(text): """Guess the format of the notebook, based on its content #148""" try: nbformat.reads(text, as_version=4) return 'ipynb' except nbformat.reader.NotJSONError: pass lines = text.splitlines() for comment in ['', '#'] + _COMMENT_CHARS: metadata, _, _, _ = header_to_metadata_and_cell(lines, comment) ext = metadata.get('jupytext', {}).get('text_representation', {}).get('extension') if ext: return ext[1:] + ':' + guess_format(text, ext)[0] # No metadata, but ``` on at least one line => markdown for line in lines: if line == '```': return 'md' return 'py:' + guess_format(text, '.py')[0]
[ "def", "divine_format", "(", "text", ")", ":", "try", ":", "nbformat", ".", "reads", "(", "text", ",", "as_version", "=", "4", ")", "return", "'ipynb'", "except", "nbformat", ".", "reader", ".", "NotJSONError", ":", "pass", "lines", "=", "text", ".", "...
Guess the format of the notebook, based on its content #148
[ "Guess", "the", "format", "of", "the", "notebook", "based", "on", "its", "content", "#148" ]
python
train
lepture/flask-oauthlib
flask_oauthlib/provider/oauth2.py
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L98-L116
def error_uri(self): """The error page URI. When something turns error, it will redirect to this error page. You can configure the error page URI with Flask config:: OAUTH2_PROVIDER_ERROR_URI = '/error' You can also define the error page by a named endpoint:: OAUTH2_PROVIDER_ERROR_ENDPOINT = 'oauth.error' """ error_uri = self.app.config.get('OAUTH2_PROVIDER_ERROR_URI') if error_uri: return error_uri error_endpoint = self.app.config.get('OAUTH2_PROVIDER_ERROR_ENDPOINT') if error_endpoint: return url_for(error_endpoint) return '/oauth/errors'
[ "def", "error_uri", "(", "self", ")", ":", "error_uri", "=", "self", ".", "app", ".", "config", ".", "get", "(", "'OAUTH2_PROVIDER_ERROR_URI'", ")", "if", "error_uri", ":", "return", "error_uri", "error_endpoint", "=", "self", ".", "app", ".", "config", "....
The error page URI. When something turns error, it will redirect to this error page. You can configure the error page URI with Flask config:: OAUTH2_PROVIDER_ERROR_URI = '/error' You can also define the error page by a named endpoint:: OAUTH2_PROVIDER_ERROR_ENDPOINT = 'oauth.error'
[ "The", "error", "page", "URI", "." ]
python
test
nion-software/nionswift
nion/swift/model/DisplayItem.py
https://github.com/nion-software/nionswift/blob/d43693eaf057b8683b9638e575000f055fede452/nion/swift/model/DisplayItem.py#L980-L998
def snapshot(self): """Return a new library item which is a copy of this one with any dynamic behavior made static.""" display_item = self.__class__() display_item.display_type = self.display_type # metadata display_item._set_persistent_property_value("title", self._get_persistent_property_value("title")) display_item._set_persistent_property_value("caption", self._get_persistent_property_value("caption")) display_item._set_persistent_property_value("description", self._get_persistent_property_value("description")) display_item._set_persistent_property_value("session_id", self._get_persistent_property_value("session_id")) display_item._set_persistent_property_value("calibration_style_id", self._get_persistent_property_value("calibration_style_id")) display_item._set_persistent_property_value("display_properties", self._get_persistent_property_value("display_properties")) display_item.created = self.created for graphic in self.graphics: display_item.add_graphic(copy.deepcopy(graphic)) for display_data_channel in self.display_data_channels: display_item.append_display_data_channel(copy.deepcopy(display_data_channel)) # this goes after the display data channels so that the layers don't get adjusted display_item._set_persistent_property_value("display_layers", self._get_persistent_property_value("display_layers")) return display_item
[ "def", "snapshot", "(", "self", ")", ":", "display_item", "=", "self", ".", "__class__", "(", ")", "display_item", ".", "display_type", "=", "self", ".", "display_type", "# metadata", "display_item", ".", "_set_persistent_property_value", "(", "\"title\"", ",", ...
Return a new library item which is a copy of this one with any dynamic behavior made static.
[ "Return", "a", "new", "library", "item", "which", "is", "a", "copy", "of", "this", "one", "with", "any", "dynamic", "behavior", "made", "static", "." ]
python
train
gc3-uzh-ch/elasticluster
elasticluster/providers/openstack.py
https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/providers/openstack.py#L622-L636
def get_ips(self, instance_id): """Retrieves all IP addresses associated to a given instance. :return: tuple (IPs) """ self._init_os_api() instance = self._load_instance(instance_id) try: ip_addrs = set([self.floating_ip]) except AttributeError: ip_addrs = set([]) for ip_addr in sum(instance.networks.values(), []): ip_addrs.add(ip_addr) log.debug("VM `%s` has IP addresses %r", instance_id, ip_addrs) return list(ip_addrs)
[ "def", "get_ips", "(", "self", ",", "instance_id", ")", ":", "self", ".", "_init_os_api", "(", ")", "instance", "=", "self", ".", "_load_instance", "(", "instance_id", ")", "try", ":", "ip_addrs", "=", "set", "(", "[", "self", ".", "floating_ip", "]", ...
Retrieves all IP addresses associated to a given instance. :return: tuple (IPs)
[ "Retrieves", "all", "IP", "addresses", "associated", "to", "a", "given", "instance", "." ]
python
train
rootpy/rootpy
rootpy/plotting/hist.py
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L1904-L1922
def ravel(self, name=None): """ Convert 2D histogram into 1D histogram with the y-axis repeated along the x-axis, similar to NumPy's ravel(). """ nbinsx = self.nbins(0) nbinsy = self.nbins(1) left_edge = self.xedgesl(1) right_edge = self.xedgesh(nbinsx) out = Hist(nbinsx * nbinsy, left_edge, nbinsy * (right_edge - left_edge) + left_edge, type=self.TYPE, name=name, title=self.title, **self.decorators) for i, bin in enumerate(self.bins(overflow=False)): out.SetBinContent(i + 1, bin.value) out.SetBinError(i + 1, bin.error) return out
[ "def", "ravel", "(", "self", ",", "name", "=", "None", ")", ":", "nbinsx", "=", "self", ".", "nbins", "(", "0", ")", "nbinsy", "=", "self", ".", "nbins", "(", "1", ")", "left_edge", "=", "self", ".", "xedgesl", "(", "1", ")", "right_edge", "=", ...
Convert 2D histogram into 1D histogram with the y-axis repeated along the x-axis, similar to NumPy's ravel().
[ "Convert", "2D", "histogram", "into", "1D", "histogram", "with", "the", "y", "-", "axis", "repeated", "along", "the", "x", "-", "axis", "similar", "to", "NumPy", "s", "ravel", "()", "." ]
python
train
ValvePython/steam
steam/guard.py
https://github.com/ValvePython/steam/blob/2de1364c47598410b572114e6129eab8fff71d5b/steam/guard.py#L421-L444
def generate_twofactor_code_for_time(shared_secret, timestamp): """Generate Steam 2FA code for timestamp :param shared_secret: authenticator shared secret :type shared_secret: bytes :param timestamp: timestamp to use, if left out uses current time :type timestamp: int :return: steam two factor code :rtype: str """ hmac = hmac_sha1(bytes(shared_secret), struct.pack('>Q', int(timestamp)//30)) # this will NOT stop working in 2038 start = ord(hmac[19:20]) & 0xF codeint = struct.unpack('>I', hmac[start:start+4])[0] & 0x7fffffff charset = '23456789BCDFGHJKMNPQRTVWXY' code = '' for _ in range(5): codeint, i = divmod(codeint, len(charset)) code += charset[i] return code
[ "def", "generate_twofactor_code_for_time", "(", "shared_secret", ",", "timestamp", ")", ":", "hmac", "=", "hmac_sha1", "(", "bytes", "(", "shared_secret", ")", ",", "struct", ".", "pack", "(", "'>Q'", ",", "int", "(", "timestamp", ")", "//", "30", ")", ")"...
Generate Steam 2FA code for timestamp :param shared_secret: authenticator shared secret :type shared_secret: bytes :param timestamp: timestamp to use, if left out uses current time :type timestamp: int :return: steam two factor code :rtype: str
[ "Generate", "Steam", "2FA", "code", "for", "timestamp" ]
python
train
KelSolaar/Umbra
umbra/components/addons/trace_ui/trace_ui.py
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/addons/trace_ui/trace_ui.py#L487-L497
def __view_remove_actions(self): """ Removes the View actions. """ trace_modules_action = "Actions|Umbra|Components|addons.trace_ui|Trace Module(s)" untrace_modules_action = "Actions|Umbra|Components|addons.trace_ui|Untrace Module(s)" for action in (trace_modules_action, untrace_modules_action): self.__view.removeAction(self.__engine.actions_manager.get_action(action)) self.__engine.actions_manager.unregister_action(action)
[ "def", "__view_remove_actions", "(", "self", ")", ":", "trace_modules_action", "=", "\"Actions|Umbra|Components|addons.trace_ui|Trace Module(s)\"", "untrace_modules_action", "=", "\"Actions|Umbra|Components|addons.trace_ui|Untrace Module(s)\"", "for", "action", "in", "(", "trace_modu...
Removes the View actions.
[ "Removes", "the", "View", "actions", "." ]
python
train
Fizzadar/pyinfra
pyinfra/api/inventory.py
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/inventory.py#L325-L333
def get_deploy_data(self): ''' Gets any default data attached to the current deploy, if any. ''' if self.state and self.state.deploy_data: return self.state.deploy_data return {}
[ "def", "get_deploy_data", "(", "self", ")", ":", "if", "self", ".", "state", "and", "self", ".", "state", ".", "deploy_data", ":", "return", "self", ".", "state", ".", "deploy_data", "return", "{", "}" ]
Gets any default data attached to the current deploy, if any.
[ "Gets", "any", "default", "data", "attached", "to", "the", "current", "deploy", "if", "any", "." ]
python
train
BlueBrain/hpcbench
hpcbench/toolbox/env.py
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/env.py#L35-L54
def expandvars(s, vars=None): """Perform variable substitution on the given string Supported syntax: * $VARIABLE * ${VARIABLE} * ${#VARIABLE} * ${VARIABLE:-default} :param s: message to expand :type s: str :param vars: dictionary of variables. Default is ``os.environ`` :type vars: dict :return: expanded string :rtype: str """ tpl = TemplateWithDefaults(s) return tpl.substitute(vars or os.environ)
[ "def", "expandvars", "(", "s", ",", "vars", "=", "None", ")", ":", "tpl", "=", "TemplateWithDefaults", "(", "s", ")", "return", "tpl", ".", "substitute", "(", "vars", "or", "os", ".", "environ", ")" ]
Perform variable substitution on the given string Supported syntax: * $VARIABLE * ${VARIABLE} * ${#VARIABLE} * ${VARIABLE:-default} :param s: message to expand :type s: str :param vars: dictionary of variables. Default is ``os.environ`` :type vars: dict :return: expanded string :rtype: str
[ "Perform", "variable", "substitution", "on", "the", "given", "string" ]
python
train
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/records.py
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/records.py#L160-L171
def __write_record(self, record_type, data): """Write single physical record.""" length = len(data) crc = crc32c.crc_update(crc32c.CRC_INIT, [record_type]) crc = crc32c.crc_update(crc, data) crc = crc32c.crc_finalize(crc) self.__writer.write( struct.pack(_HEADER_FORMAT, _mask_crc(crc), length, record_type)) self.__writer.write(data) self.__position += _HEADER_LENGTH + length
[ "def", "__write_record", "(", "self", ",", "record_type", ",", "data", ")", ":", "length", "=", "len", "(", "data", ")", "crc", "=", "crc32c", ".", "crc_update", "(", "crc32c", ".", "CRC_INIT", ",", "[", "record_type", "]", ")", "crc", "=", "crc32c", ...
Write single physical record.
[ "Write", "single", "physical", "record", "." ]
python
train
tanghaibao/jcvi
jcvi/compara/quota.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/quota.py#L102-L131
def make_range(clusters, extend=0): """ Convert to interval ends from a list of anchors extend modifies the xmax, ymax boundary of the box, which can be positive or negative very useful when we want to make the range as fuzzy as we specify """ eclusters = [] for cluster in clusters: xlist, ylist, scores = zip(*cluster) score = _score(cluster) xchr, xmin = min(xlist) xchr, xmax = max(xlist) ychr, ymin = min(ylist) ychr, ymax = max(ylist) # allow fuzziness to the boundary xmax += extend ymax += extend # because extend can be negative values, we don't want it to be less than min if xmax < xmin: xmin, xmax = xmax, xmin if ymax < ymin: ymin, ymax = ymax, ymin eclusters.append(((xchr, xmin, xmax), (ychr, ymin, ymax), score)) return eclusters
[ "def", "make_range", "(", "clusters", ",", "extend", "=", "0", ")", ":", "eclusters", "=", "[", "]", "for", "cluster", "in", "clusters", ":", "xlist", ",", "ylist", ",", "scores", "=", "zip", "(", "*", "cluster", ")", "score", "=", "_score", "(", "...
Convert to interval ends from a list of anchors extend modifies the xmax, ymax boundary of the box, which can be positive or negative very useful when we want to make the range as fuzzy as we specify
[ "Convert", "to", "interval", "ends", "from", "a", "list", "of", "anchors", "extend", "modifies", "the", "xmax", "ymax", "boundary", "of", "the", "box", "which", "can", "be", "positive", "or", "negative", "very", "useful", "when", "we", "want", "to", "make"...
python
train
akaszynski/pymeshfix
pymeshfix/meshfix.py
https://github.com/akaszynski/pymeshfix/blob/51873b25d8d46168479989a528db8456af6748f4/pymeshfix/meshfix.py#L37-L74
def load_arrays(self, v, f): """Loads triangular mesh from vertex and face numpy arrays. Both vertex and face arrays should be 2D arrays with each vertex containing XYZ data and each face containing three points. Parameters ---------- v : np.ndarray n x 3 vertex array. f : np.ndarray n x 3 face array. """ # Check inputs if not isinstance(v, np.ndarray): try: v = np.asarray(v, np.float) if v.ndim != 2 and v.shape[1] != 3: raise Exception('Invalid vertex format. Shape ' + 'should be (npoints, 3)') except BaseException: raise Exception( 'Unable to convert vertex input to valid numpy array') if not isinstance(f, np.ndarray): try: f = np.asarray(f, ctypes.c_int) if f.ndim != 2 and f.shape[1] != 3: raise Exception('Invalid face format. ' + 'Shape should be (nfaces, 3)') except BaseException: raise Exception('Unable to convert face input to valid' + ' numpy array') self.v = v self.f = f
[ "def", "load_arrays", "(", "self", ",", "v", ",", "f", ")", ":", "# Check inputs", "if", "not", "isinstance", "(", "v", ",", "np", ".", "ndarray", ")", ":", "try", ":", "v", "=", "np", ".", "asarray", "(", "v", ",", "np", ".", "float", ")", "if...
Loads triangular mesh from vertex and face numpy arrays. Both vertex and face arrays should be 2D arrays with each vertex containing XYZ data and each face containing three points. Parameters ---------- v : np.ndarray n x 3 vertex array. f : np.ndarray n x 3 face array.
[ "Loads", "triangular", "mesh", "from", "vertex", "and", "face", "numpy", "arrays", "." ]
python
train
materialsproject/pymatgen
pymatgen/core/structure.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/structure.py#L134-L139
def group_by_types(self): """Iterate over species grouped by type""" for t in self.types_of_specie: for site in self: if site.specie == t: yield site
[ "def", "group_by_types", "(", "self", ")", ":", "for", "t", "in", "self", ".", "types_of_specie", ":", "for", "site", "in", "self", ":", "if", "site", ".", "specie", "==", "t", ":", "yield", "site" ]
Iterate over species grouped by type
[ "Iterate", "over", "species", "grouped", "by", "type" ]
python
train
iotile/coretools
iotilegateway/iotilegateway/supervisor/client.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L394-L406
async def register_agent(self, short_name): """Register to act as the RPC agent for this service. After this call succeeds, all requests to send RPCs to this service will be routed through this agent. Args: short_name (str): A unique short name for this service that functions as an id """ await self.send_command(OPERATIONS.CMD_SET_AGENT, {'name': short_name}, MESSAGES.SetAgentResponse)
[ "async", "def", "register_agent", "(", "self", ",", "short_name", ")", ":", "await", "self", ".", "send_command", "(", "OPERATIONS", ".", "CMD_SET_AGENT", ",", "{", "'name'", ":", "short_name", "}", ",", "MESSAGES", ".", "SetAgentResponse", ")" ]
Register to act as the RPC agent for this service. After this call succeeds, all requests to send RPCs to this service will be routed through this agent. Args: short_name (str): A unique short name for this service that functions as an id
[ "Register", "to", "act", "as", "the", "RPC", "agent", "for", "this", "service", "." ]
python
train
dbader/schedule
schedule/__init__.py
https://github.com/dbader/schedule/blob/5d2653c28b1029f1e9ddc85cd9ef26c29a79fcea/schedule/__init__.py#L96-L110
def run_all(self, delay_seconds=0): """ Run all jobs regardless if they are scheduled to run or not. A delay of `delay` seconds is added between each job. This helps distribute system load generated by the jobs more evenly over time. :param delay_seconds: A delay added between every executed job """ logger.info('Running *all* %i jobs with %is delay inbetween', len(self.jobs), delay_seconds) for job in self.jobs[:]: self._run_job(job) time.sleep(delay_seconds)
[ "def", "run_all", "(", "self", ",", "delay_seconds", "=", "0", ")", ":", "logger", ".", "info", "(", "'Running *all* %i jobs with %is delay inbetween'", ",", "len", "(", "self", ".", "jobs", ")", ",", "delay_seconds", ")", "for", "job", "in", "self", ".", ...
Run all jobs regardless if they are scheduled to run or not. A delay of `delay` seconds is added between each job. This helps distribute system load generated by the jobs more evenly over time. :param delay_seconds: A delay added between every executed job
[ "Run", "all", "jobs", "regardless", "if", "they", "are", "scheduled", "to", "run", "or", "not", "." ]
python
train
tnkteja/myhelp
virtualEnvironment/lib/python2.7/site-packages/pip/req/req_install.py
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/req/req_install.py#L235-L264
def correct_build_location(self): """If the build location was a temporary directory, this will move it to a new more permanent location""" if self.source_dir is not None: return assert self.req is not None assert self._temp_build_dir old_location = self._temp_build_dir new_build_dir = self._ideal_build_dir del self._ideal_build_dir if self.editable: name = self.name.lower() else: name = self.name new_location = os.path.join(new_build_dir, name) if not os.path.exists(new_build_dir): logger.debug('Creating directory %s', new_build_dir) _make_build_dir(new_build_dir) if os.path.exists(new_location): raise InstallationError( 'A package already exists in %s; please remove it to continue' % display_path(new_location)) logger.debug( 'Moving package %s from %s to new location %s', self, display_path(old_location), display_path(new_location), ) shutil.move(old_location, new_location) self._temp_build_dir = new_location self.source_dir = new_location self._egg_info_path = None
[ "def", "correct_build_location", "(", "self", ")", ":", "if", "self", ".", "source_dir", "is", "not", "None", ":", "return", "assert", "self", ".", "req", "is", "not", "None", "assert", "self", ".", "_temp_build_dir", "old_location", "=", "self", ".", "_te...
If the build location was a temporary directory, this will move it to a new more permanent location
[ "If", "the", "build", "location", "was", "a", "temporary", "directory", "this", "will", "move", "it", "to", "a", "new", "more", "permanent", "location" ]
python
test
kensho-technologies/graphql-compiler
graphql_compiler/compiler/directive_helpers.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/directive_helpers.py#L132-L137
def validate_vertex_directives(directives): """Validate the directives that appear at a vertex field.""" for directive_name in six.iterkeys(directives): if directive_name in PROPERTY_ONLY_DIRECTIVES: raise GraphQLCompilationError( u'Found property-only directive {} set on vertex.'.format(directive_name))
[ "def", "validate_vertex_directives", "(", "directives", ")", ":", "for", "directive_name", "in", "six", ".", "iterkeys", "(", "directives", ")", ":", "if", "directive_name", "in", "PROPERTY_ONLY_DIRECTIVES", ":", "raise", "GraphQLCompilationError", "(", "u'Found prope...
Validate the directives that appear at a vertex field.
[ "Validate", "the", "directives", "that", "appear", "at", "a", "vertex", "field", "." ]
python
train
pyroscope/pyrobase
src/pyrobase/fmt.py
https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/fmt.py#L146-L185
def to_utf8(text): """ Enforce UTF8 encoding. """ # return empty/false stuff unaltered if not text: if isinstance(text, string_types): text = "" return text try: # Is it a unicode string, or pure ascii? return text.encode("utf8") except UnicodeDecodeError: try: # Is it a utf8 byte string? if text.startswith(codecs.BOM_UTF8): text = text[len(codecs.BOM_UTF8):] return text.decode("utf8").encode("utf8") except UnicodeDecodeError: # Check BOM if text.startswith(codecs.BOM_UTF16_LE): encoding = "utf-16le" text = text[len(codecs.BOM_UTF16_LE):] elif text.startswith(codecs.BOM_UTF16_BE): encoding = "utf-16be" text = text[len(codecs.BOM_UTF16_BE):] else: # Assume CP-1252 encoding = "cp1252" try: return text.decode(encoding).encode("utf8") except UnicodeDecodeError as exc: for line in text.splitlines(): try: line.decode(encoding).encode("utf8") except UnicodeDecodeError: log.warn("Cannot transcode the following into UTF8 cause of %s: %r" % (exc, line)) break return text
[ "def", "to_utf8", "(", "text", ")", ":", "# return empty/false stuff unaltered", "if", "not", "text", ":", "if", "isinstance", "(", "text", ",", "string_types", ")", ":", "text", "=", "\"\"", "return", "text", "try", ":", "# Is it a unicode string, or pure ascii?"...
Enforce UTF8 encoding.
[ "Enforce", "UTF8", "encoding", "." ]
python
train
asciimoo/exrex
exrex.py
https://github.com/asciimoo/exrex/blob/69733409042b526da584c675907a316ad708a8d4/exrex.py#L294-L382
def sre_to_string(sre_obj, paren=True): """sre_parse object to string :param sre_obj: Output of sre_parse.parse() :type sre_obj: list :rtype: str """ ret = u'' for i in sre_obj: if i[0] == sre_parse.IN: prefix = '' if len(i[1]) and i[1][0][0] == sre_parse.NEGATE: prefix = '^' ret += u'[{0}{1}]'.format(prefix, sre_to_string(i[1], paren=paren)) elif i[0] == sre_parse.LITERAL: u = unichr(i[1]) ret += u if u not in sre_parse.SPECIAL_CHARS else '\\{0}'.format(u) elif i[0] == sre_parse.CATEGORY: ret += REVERSE_CATEGORIES[i[1]] elif i[0] == sre_parse.ANY: ret += '.' elif i[0] == sre_parse.BRANCH: # TODO simplifications here parts = [sre_to_string(x, paren=paren) for x in i[1][1]] if not any(parts): continue if i[1][0]: if len(parts) == 1: paren = False prefix = '' else: prefix = '?:' branch = '|'.join(parts) if paren: ret += '({0}{1})'.format(prefix, branch) else: ret += '{0}'.format(branch) elif i[0] == sre_parse.SUBPATTERN: subexpr = i[1][1] if IS_PY36_OR_GREATER and i[0] == sre_parse.SUBPATTERN: subexpr = i[1][3] if i[1][0]: ret += '({0})'.format(sre_to_string(subexpr, paren=False)) else: ret += '{0}'.format(sre_to_string(subexpr, paren=paren)) elif i[0] == sre_parse.NOT_LITERAL: ret += '[^{0}]'.format(unichr(i[1])) elif i[0] == sre_parse.MAX_REPEAT: if i[1][0] == i[1][1]: range_str = '{{{0}}}'.format(i[1][0]) else: if i[1][0] == 0 and i[1][1] - i[1][0] == sre_parse.MAXREPEAT: range_str = '*' elif i[1][0] == 1 and i[1][1] - i[1][0] == sre_parse.MAXREPEAT - 1: range_str = '+' else: range_str = '{{{0},{1}}}'.format(i[1][0], i[1][1]) ret += sre_to_string(i[1][2], paren=paren) + range_str elif i[0] == sre_parse.MIN_REPEAT: if i[1][0] == 0 and i[1][1] == sre_parse.MAXREPEAT: range_str = '*?' elif i[1][0] == 1 and i[1][1] == sre_parse.MAXREPEAT: range_str = '+?' elif i[1][1] == sre_parse.MAXREPEAT: range_str = '{{{0},}}?'.format(i[1][0]) else: range_str = '{{{0},{1}}}?'.format(i[1][0], i[1][1]) ret += sre_to_string(i[1][2], paren=paren) + range_str elif i[0] == sre_parse.GROUPREF: ret += '\\{0}'.format(i[1]) elif i[0] == sre_parse.AT: if i[1] == sre_parse.AT_BEGINNING: ret += '^' elif i[1] == sre_parse.AT_END: ret += '$' elif i[0] == sre_parse.NEGATE: pass elif i[0] == sre_parse.RANGE: ret += '{0}-{1}'.format(unichr(i[1][0]), unichr(i[1][1])) elif i[0] == sre_parse.ASSERT: if i[1][0]: ret += '(?={0})'.format(sre_to_string(i[1][1], paren=False)) else: ret += '{0}'.format(sre_to_string(i[1][1], paren=paren)) elif i[0] == sre_parse.ASSERT_NOT: pass else: print('[!] cannot handle expression "%s"' % str(i)) return ret
[ "def", "sre_to_string", "(", "sre_obj", ",", "paren", "=", "True", ")", ":", "ret", "=", "u''", "for", "i", "in", "sre_obj", ":", "if", "i", "[", "0", "]", "==", "sre_parse", ".", "IN", ":", "prefix", "=", "''", "if", "len", "(", "i", "[", "1",...
sre_parse object to string :param sre_obj: Output of sre_parse.parse() :type sre_obj: list :rtype: str
[ "sre_parse", "object", "to", "string" ]
python
valid
CityOfZion/neo-python
neo/Implementations/Notifications/LevelDB/NotificationDB.py
https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Implementations/Notifications/LevelDB/NotificationDB.py#L121-L213
def on_persist_completed(self, block): """ Called when a block has been persisted to disk. Used as a hook to persist notification data. Args: block (neo.Core.Block): the currently persisting block """ if len(self._events_to_write): addr_db = self.db.prefixed_db(NotificationPrefix.PREFIX_ADDR) block_db = self.db.prefixed_db(NotificationPrefix.PREFIX_BLOCK) contract_db = self.db.prefixed_db(NotificationPrefix.PREFIX_CONTRACT) block_write_batch = block_db.write_batch() contract_write_batch = contract_db.write_batch() block_count = 0 block_bytes = self._events_to_write[0].block_number.to_bytes(4, 'little') for evt in self._events_to_write: # type:NotifyEvent # write the event for both or one of the addresses involved in the transfer write_both = True hash_data = evt.ToByteArray() bytes_to = bytes(evt.addr_to.Data) bytes_from = bytes(evt.addr_from.Data) if bytes_to == bytes_from: write_both = False total_bytes_to = addr_db.get(bytes_to + NotificationPrefix.PREFIX_COUNT) total_bytes_from = addr_db.get(bytes_from + NotificationPrefix.PREFIX_COUNT) if not total_bytes_to: total_bytes_to = b'\x00' if not total_bytes_from: total_bytes_from = b'x\00' addr_to_key = bytes_to + total_bytes_to addr_from_key = bytes_from + total_bytes_from with addr_db.write_batch() as b: b.put(addr_to_key, hash_data) if write_both: b.put(addr_from_key, hash_data) total_bytes_to = int.from_bytes(total_bytes_to, 'little') + 1 total_bytes_from = int.from_bytes(total_bytes_from, 'little') + 1 new_bytes_to = total_bytes_to.to_bytes(4, 'little') new_bytes_from = total_bytes_from.to_bytes(4, 'little') b.put(bytes_to + NotificationPrefix.PREFIX_COUNT, new_bytes_to) if write_both: b.put(bytes_from + NotificationPrefix.PREFIX_COUNT, new_bytes_from) # write the event to the per-block database per_block_key = block_bytes + block_count.to_bytes(4, 'little') block_write_batch.put(per_block_key, hash_data) block_count += 1 # write the event to the per-contract database contract_bytes = bytes(evt.contract_hash.Data) count_for_contract = contract_db.get(contract_bytes + NotificationPrefix.PREFIX_COUNT) if not count_for_contract: count_for_contract = b'\x00' contract_event_key = contract_bytes + count_for_contract contract_count_int = int.from_bytes(count_for_contract, 'little') + 1 new_contract_count = contract_count_int.to_bytes(4, 'little') contract_write_batch.put(contract_bytes + NotificationPrefix.PREFIX_COUNT, new_contract_count) contract_write_batch.put(contract_event_key, hash_data) # finish off the per-block write batch and contract write batch block_write_batch.write() contract_write_batch.write() self._events_to_write = [] if len(self._new_contracts_to_write): token_db = self.db.prefixed_db(NotificationPrefix.PREFIX_TOKEN) token_write_batch = token_db.write_batch() for token_event in self._new_contracts_to_write: try: hash_data = token_event.ToByteArray() # used to fail here hash_key = token_event.contract.Code.ScriptHash().ToBytes() token_write_batch.put(hash_key, hash_data) except Exception as e: logger.debug(f"Failed to write new contract, reason: {e}") token_write_batch.write() self._new_contracts_to_write = []
[ "def", "on_persist_completed", "(", "self", ",", "block", ")", ":", "if", "len", "(", "self", ".", "_events_to_write", ")", ":", "addr_db", "=", "self", ".", "db", ".", "prefixed_db", "(", "NotificationPrefix", ".", "PREFIX_ADDR", ")", "block_db", "=", "se...
Called when a block has been persisted to disk. Used as a hook to persist notification data. Args: block (neo.Core.Block): the currently persisting block
[ "Called", "when", "a", "block", "has", "been", "persisted", "to", "disk", ".", "Used", "as", "a", "hook", "to", "persist", "notification", "data", ".", "Args", ":", "block", "(", "neo", ".", "Core", ".", "Block", ")", ":", "the", "currently", "persisti...
python
train
ramrod-project/database-brain
schema/brain/queries/writes.py
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/queries/writes.py#L20-L29
def waiting_filter(lte_time, conn=None): """ generates a filter for status==waiting and time older than lte_time """ if RBO.index_list().contains(IDX_OUTPUT_JOB_ID).run(conn): return (r.row[START_FIELD] <= lte_time) else: return ((r.row[STATUS_FIELD] == WAITING) & (r.row[START_FIELD] <= lte_time))
[ "def", "waiting_filter", "(", "lte_time", ",", "conn", "=", "None", ")", ":", "if", "RBO", ".", "index_list", "(", ")", ".", "contains", "(", "IDX_OUTPUT_JOB_ID", ")", ".", "run", "(", "conn", ")", ":", "return", "(", "r", ".", "row", "[", "START_FIE...
generates a filter for status==waiting and time older than lte_time
[ "generates", "a", "filter", "for", "status", "==", "waiting", "and", "time", "older", "than", "lte_time" ]
python
train
dwavesystems/dwave-system
dwave/system/cache/cache_manager.py
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/cache/cache_manager.py#L34-L60
def cache_file(app_name=APPNAME, app_author=APPAUTHOR, filename=DATABASENAME): """Returns the filename (including path) for the data cache. The path will depend on the operating system, certain environmental variables and whether it is being run inside a virtual environment. See `homebase <https://github.com/dwavesystems/homebase>`_. Args: app_name (str, optional): The application name. Default is given by :obj:`.APPNAME`. app_author (str, optional): The application author. Default is given by :obj:`.APPAUTHOR`. filename (str, optional): The name of the database file. Default is given by :obj:`DATABASENAME`. Returns: str: The full path to the file that can be used as a cache. Notes: Creates the directory if it does not already exist. If run inside of a virtual environment, the cache will be stored in `/path/to/virtualenv/data/app_name` """ user_data_dir = homebase.user_data_dir(app_name=app_name, app_author=app_author, create=True) return os.path.join(user_data_dir, filename)
[ "def", "cache_file", "(", "app_name", "=", "APPNAME", ",", "app_author", "=", "APPAUTHOR", ",", "filename", "=", "DATABASENAME", ")", ":", "user_data_dir", "=", "homebase", ".", "user_data_dir", "(", "app_name", "=", "app_name", ",", "app_author", "=", "app_au...
Returns the filename (including path) for the data cache. The path will depend on the operating system, certain environmental variables and whether it is being run inside a virtual environment. See `homebase <https://github.com/dwavesystems/homebase>`_. Args: app_name (str, optional): The application name. Default is given by :obj:`.APPNAME`. app_author (str, optional): The application author. Default is given by :obj:`.APPAUTHOR`. filename (str, optional): The name of the database file. Default is given by :obj:`DATABASENAME`. Returns: str: The full path to the file that can be used as a cache. Notes: Creates the directory if it does not already exist. If run inside of a virtual environment, the cache will be stored in `/path/to/virtualenv/data/app_name`
[ "Returns", "the", "filename", "(", "including", "path", ")", "for", "the", "data", "cache", "." ]
python
train
sergiocorreia/panflute
panflute/tools.py
https://github.com/sergiocorreia/panflute/blob/65c2d570c26a190deb600cab5e2ad8a828a3302e/panflute/tools.py#L277-L297
def shell(args, wait=True, msg=None): """ Execute the external command and get its exitcode, stdout and stderr. """ # Fix Windows error if passed a string if isinstance(args, str): args = shlex.split(args, posix=(os.name != "nt")) if os.name == "nt": args = [arg.replace('/', '\\') for arg in args] if wait: proc = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) out, err = proc.communicate(input=msg) exitcode = proc.returncode if exitcode != 0: raise IOError(err) return out else: DETACHED_PROCESS = 0x00000008 proc = Popen(args, creationflags=DETACHED_PROCESS)
[ "def", "shell", "(", "args", ",", "wait", "=", "True", ",", "msg", "=", "None", ")", ":", "# Fix Windows error if passed a string", "if", "isinstance", "(", "args", ",", "str", ")", ":", "args", "=", "shlex", ".", "split", "(", "args", ",", "posix", "=...
Execute the external command and get its exitcode, stdout and stderr.
[ "Execute", "the", "external", "command", "and", "get", "its", "exitcode", "stdout", "and", "stderr", "." ]
python
train
michael-lazar/rtv
rtv/packages/praw/objects.py
https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/objects.py#L1294-L1318
def mark_as_nsfw(self, unmark_nsfw=False): """Mark as Not Safe For Work. Requires that the currently authenticated user is the author of the submission, has the modposts oauth scope or has user/password authentication as a mod of the subreddit. :returns: The json response from the server. """ def mark_as_nsfw_helper(self): # pylint: disable=W0613 # It is necessary to have the 'self' argument as it's needed in # restrict_access to determine what class the decorator is # operating on. url = self.reddit_session.config['unmarknsfw' if unmark_nsfw else 'marknsfw'] data = {'id': self.fullname} return self.reddit_session.request_json(url, data=data) is_author = (self.reddit_session.is_logged_in() and self.author == self.reddit_session.user) if is_author: return mark_as_nsfw_helper(self) else: return restrict_access('modposts')(mark_as_nsfw_helper)(self)
[ "def", "mark_as_nsfw", "(", "self", ",", "unmark_nsfw", "=", "False", ")", ":", "def", "mark_as_nsfw_helper", "(", "self", ")", ":", "# pylint: disable=W0613", "# It is necessary to have the 'self' argument as it's needed in", "# restrict_access to determine what class the decora...
Mark as Not Safe For Work. Requires that the currently authenticated user is the author of the submission, has the modposts oauth scope or has user/password authentication as a mod of the subreddit. :returns: The json response from the server.
[ "Mark", "as", "Not", "Safe", "For", "Work", "." ]
python
train
bokeh/bokeh
bokeh/embed/util.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/util.py#L67-L168
def OutputDocumentFor(objs, apply_theme=None, always_new=False): ''' Find or create a (possibly temporary) Document to use for serializing Bokeh content. Typical usage is similar to: .. code-block:: python with OutputDocumentFor(models): (docs_json, [render_item]) = standalone_docs_json_and_render_items(models) Inside the context manager, the models will be considered to be part of a single Document, with any theme specified, which can thus be serialized as a unit. Where possible, OutputDocumentFor attempts to use an existing Document. However, this is not possible in three cases: * If passed a series of models that have no Document at all, a new Document will be created, and all the models will be added as roots. After the context manager exits, the new Document will continue to be the models' document. * If passed a subset of Document.roots, then OutputDocumentFor temporarily "re-homes" the models in a new bare Document that is only available inside the context manager. * If passed a list of models that have differnet documents, then OutputDocumentFor temporarily "re-homes" the models in a new bare Document that is only available inside the context manager. OutputDocumentFor will also perfom document validation before yielding, if ``settings.perform_document_validation()`` is True. objs (seq[Model]) : a sequence of Models that will be serialized, and need a common document apply_theme (Theme or FromCurdoc or None, optional): Sets the theme for the doc while inside this context manager. (default: None) If None, use whatever theme is on the document that is found or created If FromCurdoc, use curdoc().theme, restoring any previous theme afterwards If a Theme instance, use that theme, restoring any previous theme afterwards always_new (bool, optional) : Always return a new document, even in cases where it is otherwise possible to use an existing document on models. Yields: Document ''' # Note: Comms handling relies on the fact that the new_doc returned # has models with the same IDs as they were started with if not isinstance(objs, collections_abc.Sequence) or len(objs) == 0 or not all(isinstance(x, Model) for x in objs): raise ValueError("OutputDocumentFor expects a sequence of Models") def finish(): pass docs = set(x.document for x in objs) if None in docs: docs.remove(None) if always_new: def finish(): # NOQA _dispose_temp_doc(objs) doc = _create_temp_doc(objs) else: if len(docs) == 0: doc = Document() for model in objs: doc.add_root(model) # handle a single shared document elif len(docs) == 1: doc = docs.pop() # we are not using all the roots, make a quick clone for outputting purposes if set(objs) != set(doc.roots): def finish(): # NOQA _dispose_temp_doc(objs) doc = _create_temp_doc(objs) # we are using all the roots of a single doc, just use doc as-is pass # models have mixed docs, just make a quick clone else: def finish(): # NOQA _dispose_temp_doc(objs) doc = _create_temp_doc(objs) if settings.perform_document_validation(): doc.validate() _set_temp_theme(doc, apply_theme) yield doc _unset_temp_theme(doc) finish()
[ "def", "OutputDocumentFor", "(", "objs", ",", "apply_theme", "=", "None", ",", "always_new", "=", "False", ")", ":", "# Note: Comms handling relies on the fact that the new_doc returned", "# has models with the same IDs as they were started with", "if", "not", "isinstance", "("...
Find or create a (possibly temporary) Document to use for serializing Bokeh content. Typical usage is similar to: .. code-block:: python with OutputDocumentFor(models): (docs_json, [render_item]) = standalone_docs_json_and_render_items(models) Inside the context manager, the models will be considered to be part of a single Document, with any theme specified, which can thus be serialized as a unit. Where possible, OutputDocumentFor attempts to use an existing Document. However, this is not possible in three cases: * If passed a series of models that have no Document at all, a new Document will be created, and all the models will be added as roots. After the context manager exits, the new Document will continue to be the models' document. * If passed a subset of Document.roots, then OutputDocumentFor temporarily "re-homes" the models in a new bare Document that is only available inside the context manager. * If passed a list of models that have differnet documents, then OutputDocumentFor temporarily "re-homes" the models in a new bare Document that is only available inside the context manager. OutputDocumentFor will also perfom document validation before yielding, if ``settings.perform_document_validation()`` is True. objs (seq[Model]) : a sequence of Models that will be serialized, and need a common document apply_theme (Theme or FromCurdoc or None, optional): Sets the theme for the doc while inside this context manager. (default: None) If None, use whatever theme is on the document that is found or created If FromCurdoc, use curdoc().theme, restoring any previous theme afterwards If a Theme instance, use that theme, restoring any previous theme afterwards always_new (bool, optional) : Always return a new document, even in cases where it is otherwise possible to use an existing document on models. Yields: Document
[ "Find", "or", "create", "a", "(", "possibly", "temporary", ")", "Document", "to", "use", "for", "serializing", "Bokeh", "content", "." ]
python
train
automl/HpBandSter
hpbandster/optimizers/config_generators/lcnet.py
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/optimizers/config_generators/lcnet.py#L63-L103
def get_config(self, budget): """ function to sample a new configuration This function is called inside Hyperband to query a new configuration Parameters: ----------- budget: float the budget for which this configuration is scheduled returns: config should return a valid configuration """ self.lock.acquire() if not self.is_trained: c = self.config_space.sample_configuration().get_array() else: candidates = np.array([self.config_space.sample_configuration().get_array() for _ in range(self.n_candidates)]) # We are only interested on the asymptotic value projected_candidates = np.concatenate((candidates, np.ones([self.n_candidates, 1])), axis=1) # Compute the upper confidence bound of the function at the asymptote m, v = self.model.predict(projected_candidates) ucb_values = m + self.delta * np.sqrt(v) print(ucb_values) # Sample a configuration based on the ucb values p = np.ones(self.n_candidates) * (ucb_values / np.sum(ucb_values)) idx = np.random.choice(self.n_candidates, 1, False, p) c = candidates[idx][0] config = ConfigSpace.Configuration(self.config_space, vector=c) self.lock.release() return config.get_dictionary(), {}
[ "def", "get_config", "(", "self", ",", "budget", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "if", "not", "self", ".", "is_trained", ":", "c", "=", "self", ".", "config_space", ".", "sample_configuration", "(", ")", ".", "get_array", "(", ...
function to sample a new configuration This function is called inside Hyperband to query a new configuration Parameters: ----------- budget: float the budget for which this configuration is scheduled returns: config should return a valid configuration
[ "function", "to", "sample", "a", "new", "configuration" ]
python
train
baccuslab/shannon
shannon/discrete.py
https://github.com/baccuslab/shannon/blob/38abb4d9e53208ffd1c4149ef9fdf3abceccac48/shannon/discrete.py#L71-L113
def combine_symbols(*args): ''' Combine different symbols into a 'super'-symbol args can be an iterable of iterables that support hashing see example for 2D ndarray input usage: 1) combine two symbols, each a number into just one symbol x = numpy.random.randint(0,4,1000) y = numpy.random.randint(0,2,1000) z = combine_symbols(x,y) 2) combine a letter and a number s = 'abcd' x = numpy.random.randint(0,4,1000) y = [s[randint(4)] for i in range(1000)] z = combine_symbols(x,y) 3) suppose you are running an experiment and for each sample, you measure 3 different properties and you put the data into a 2d ndarray such that: samples_N, properties_N = data.shape and you want to combine all 3 different properties into just 1 symbol In this case you have to find a way to impute each property as an independent array combined_symbol = combine_symbols(*data.T) 4) if data from 3) is such that: properties_N, samples_N = data.shape then run: combined_symbol = combine_symbols(*data) ''' for arg in args: if len(arg)!=len(args[0]): raise ValueError("combine_symbols got inputs with different sizes") return tuple(zip(*args))
[ "def", "combine_symbols", "(", "*", "args", ")", ":", "for", "arg", "in", "args", ":", "if", "len", "(", "arg", ")", "!=", "len", "(", "args", "[", "0", "]", ")", ":", "raise", "ValueError", "(", "\"combine_symbols got inputs with different sizes\"", ")", ...
Combine different symbols into a 'super'-symbol args can be an iterable of iterables that support hashing see example for 2D ndarray input usage: 1) combine two symbols, each a number into just one symbol x = numpy.random.randint(0,4,1000) y = numpy.random.randint(0,2,1000) z = combine_symbols(x,y) 2) combine a letter and a number s = 'abcd' x = numpy.random.randint(0,4,1000) y = [s[randint(4)] for i in range(1000)] z = combine_symbols(x,y) 3) suppose you are running an experiment and for each sample, you measure 3 different properties and you put the data into a 2d ndarray such that: samples_N, properties_N = data.shape and you want to combine all 3 different properties into just 1 symbol In this case you have to find a way to impute each property as an independent array combined_symbol = combine_symbols(*data.T) 4) if data from 3) is such that: properties_N, samples_N = data.shape then run: combined_symbol = combine_symbols(*data)
[ "Combine", "different", "symbols", "into", "a", "super", "-", "symbol" ]
python
train
open511/open511
open511/utils/schedule.py
https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/utils/schedule.py#L53-L56
def intervals(self, range_start=datetime.datetime.min, range_end=datetime.datetime.max): """Returns a list of tuples of start/end datetimes for when the schedule is active during the provided range.""" raise NotImplementedError
[ "def", "intervals", "(", "self", ",", "range_start", "=", "datetime", ".", "datetime", ".", "min", ",", "range_end", "=", "datetime", ".", "datetime", ".", "max", ")", ":", "raise", "NotImplementedError" ]
Returns a list of tuples of start/end datetimes for when the schedule is active during the provided range.
[ "Returns", "a", "list", "of", "tuples", "of", "start", "/", "end", "datetimes", "for", "when", "the", "schedule", "is", "active", "during", "the", "provided", "range", "." ]
python
valid
tk0miya/tk.phpautodoc
src/phply/phpparse.py
https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phpparse.py#L851-L853
def p_reference_variable_array_offset(p): 'reference_variable : reference_variable LBRACKET dim_offset RBRACKET' p[0] = ast.ArrayOffset(p[1], p[3], lineno=p.lineno(2))
[ "def", "p_reference_variable_array_offset", "(", "p", ")", ":", "p", "[", "0", "]", "=", "ast", ".", "ArrayOffset", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "2", ")", ")" ]
reference_variable : reference_variable LBRACKET dim_offset RBRACKET
[ "reference_variable", ":", "reference_variable", "LBRACKET", "dim_offset", "RBRACKET" ]
python
train