nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/teleport/webroot/app/base/db.py
python
SQL._make_sql_query_string
(self)
return ' '.join(sql)
[]
def _make_sql_query_string(self): sql = list() sql.append('SELECT {}'.format(','.join(self._select_fields))) sql.append('FROM {}{} AS {}'.format(self._db.table_prefix, self._from['n'], self._from['a'])) for _l in self._left_join: sql.append('LEFT JOIN {}{} AS {} ON {}'.format(self._db.table_prefix, _l['n'], _l['a'], _l['on'])) if len(self._where) > 0: sql.append('WHERE {}'.format(self._where)) if len(self._group_by) > 0: sql.append('GROUP BY {}'.format(self._group_by)) if len(self._order_by) > 0: sql.append('ORDER BY {}'.format(','.join(self._order_by))) if self._limit is not None: if self._ret_total_recorder <= self._limit['page_index'] * self._limit['per_page']: self._ret_page_index = int(self._ret_total_recorder / self._limit['per_page']) if self._ret_page_index < 0: self._ret_page_index = 0 else: self._ret_page_index = self._limit['page_index'] sql.append('LIMIT {},{}'.format(self._ret_page_index * self._limit['per_page'], self._limit['per_page'])) sql.append(';') return ' '.join(sql)
[ "def", "_make_sql_query_string", "(", "self", ")", ":", "sql", "=", "list", "(", ")", "sql", ".", "append", "(", "'SELECT {}'", ".", "format", "(", "','", ".", "join", "(", "self", ".", "_select_fields", ")", ")", ")", "sql", ".", "append", "(", "'FR...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/teleport/webroot/app/base/db.py#L817-L844
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/contrib/gis/gdal/raster/band.py
python
GDALBand.__init__
(self, source, index)
[]
def __init__(self, source, index): self.source = source self._ptr = capi.get_ds_raster_band(source._ptr, index)
[ "def", "__init__", "(", "self", ",", "source", ",", "index", ")", ":", "self", ".", "source", "=", "source", "self", ".", "_ptr", "=", "capi", ".", "get_ds_raster_band", "(", "source", ".", "_ptr", ",", "index", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/contrib/gis/gdal/raster/band.py#L18-L20
PowerScript/KatanaFramework
0f6ad90a88de865d58ec26941cb4460501e75496
lib/scapy/scapy/contrib/gsm_um.py
python
alertingNetToMs
(Facility_presence=0, ProgressIndicator_presence=0, UserUser_presence=0)
return packet
ALERTING Section 9.3.1.1
ALERTING Section 9.3.1.1
[ "ALERTING", "Section", "9", ".", "3", ".", "1", ".", "1" ]
def alertingNetToMs(Facility_presence=0, ProgressIndicator_presence=0, UserUser_presence=0): """ALERTING Section 9.3.1.1""" a = TpPd(pd=0x3) b = MessageType(mesType=0x1) # 00000001 packet = a / b if Facility_presence is 1: c = FacilityHdr(ieiF=0x1C) packet = packet / c if ProgressIndicator_presence is 1: d = ProgressIndicatorHdr(ieiPI=0x1E) packet = packet / d if UserUser_presence is 1: e = UserUserHdr(ieiUU=0x7E) packet = packet / e return packet
[ "def", "alertingNetToMs", "(", "Facility_presence", "=", "0", ",", "ProgressIndicator_presence", "=", "0", ",", "UserUser_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x1", ")...
https://github.com/PowerScript/KatanaFramework/blob/0f6ad90a88de865d58ec26941cb4460501e75496/lib/scapy/scapy/contrib/gsm_um.py#L1558-L1573
ChiCheng123/SRN
fc07d7499bb5d8291cec68124fc50879f2f68147
srn/utils/anchor_helper.py
python
get_anchors_over_plane
(featmap_h, featmap_w, anchor_ratios, anchor_scales, anchor_stride)
return anchors_overplane.reshape((K * A, 4))
[]
def get_anchors_over_plane(featmap_h, featmap_w, anchor_ratios, anchor_scales, anchor_stride): # get anchors over one grid anchors_overgrid = get_anchors_over_grid(anchor_ratios, anchor_scales, anchor_stride) # spread anchors over each grid shift_x = np.arange(0, featmap_w) * anchor_stride shift_y = np.arange(0, featmap_h) * anchor_stride # [featmap_h, featmap_w] shift_x, shift_y = np.meshgrid(shift_x, shift_y) shifts = np.vstack((shift_x.ravel(), shift_y.ravel(), shift_x.ravel(), shift_y.ravel())).transpose() A = anchors_overgrid.shape[0] K = shifts.shape[0] anchors_overplane = (anchors_overgrid.reshape((1, A, 4)) + shifts.reshape((1, K, 4)).transpose((1, 0, 2))) return anchors_overplane.reshape((K * A, 4))
[ "def", "get_anchors_over_plane", "(", "featmap_h", ",", "featmap_w", ",", "anchor_ratios", ",", "anchor_scales", ",", "anchor_stride", ")", ":", "# get anchors over one grid", "anchors_overgrid", "=", "get_anchors_over_grid", "(", "anchor_ratios", ",", "anchor_scales", ",...
https://github.com/ChiCheng123/SRN/blob/fc07d7499bb5d8291cec68124fc50879f2f68147/srn/utils/anchor_helper.py#L13-L27
NervanaSystems/ngraph-python
ac032c83c7152b615a9ad129d54d350f9d6a2986
ngraph/op_graph/axes.py
python
TensorDescription.base
(self)
return self.__base or self
The viewed tensor description or None if not a view.
The viewed tensor description or None if not a view.
[ "The", "viewed", "tensor", "description", "or", "None", "if", "not", "a", "view", "." ]
def base(self): """The viewed tensor description or None if not a view.""" return self.__base or self
[ "def", "base", "(", "self", ")", ":", "return", "self", ".", "__base", "or", "self" ]
https://github.com/NervanaSystems/ngraph-python/blob/ac032c83c7152b615a9ad129d54d350f9d6a2986/ngraph/op_graph/axes.py#L1689-L1691
JoinMarket-Org/joinmarket-clientserver
8b3d21f226185e31aa10e8e16cdfc719cea4a98e
jmclient/jmclient/blockchaininterface.py
python
ElectrumWalletInterface.query_utxo_set
(self, txout, includeconf=False)
return result
Behaves as for Core; TODO make it faster if possible. Note in particular a failed connection should result in a result list containing at least one "None" which the caller can use as a flag for failure.
Behaves as for Core; TODO make it faster if possible. Note in particular a failed connection should result in a result list containing at least one "None" which the caller can use as a flag for failure.
[ "Behaves", "as", "for", "Core", ";", "TODO", "make", "it", "faster", "if", "possible", ".", "Note", "in", "particular", "a", "failed", "connection", "should", "result", "in", "a", "result", "list", "containing", "at", "least", "one", "None", "which", "the"...
def query_utxo_set(self, txout, includeconf=False): """Behaves as for Core; TODO make it faster if possible. Note in particular a failed connection should result in a result list containing at least one "None" which the caller can use as a flag for failure. """ self.current_height = self.wallet.network.blockchain.local_height if not isinstance(txout, list): txout = [txout] utxos = [[t[:64], int(t[65:])] for t in txout] result = [] for ut in utxos: address = self.wallet.network.synchronous_get(( 'blockchain.utxo.get_address', ut)) try: utxo_info = self.wallet.network.synchronous_get(( "blockchain.address.listunspent", [address])) except Exception as e: log.debug("Got exception calling listunspent: " + repr(e)) raise utxo = None for u in utxo_info: if u['tx_hash'] == ut[0] and u['tx_pos'] == ut[1]: utxo = u if utxo is None: result.append(None) continue r = { 'value': u['value'], 'address': address, 'script': btc.address_to_script(address) } if includeconf: if int(u['height']) in [0, -1]: #-1 means unconfirmed inputs r['confirms'] = 0 else: #+1 because if current height = tx height, that's 1 conf r['confirms'] = int(self.current_height) - int(u['height']) + 1 result.append(r) return result
[ "def", "query_utxo_set", "(", "self", ",", "txout", ",", "includeconf", "=", "False", ")", ":", "self", ".", "current_height", "=", "self", ".", "wallet", ".", "network", ".", "blockchain", ".", "local_height", "if", "not", "isinstance", "(", "txout", ",",...
https://github.com/JoinMarket-Org/joinmarket-clientserver/blob/8b3d21f226185e31aa10e8e16cdfc719cea4a98e/jmclient/jmclient/blockchaininterface.py#L112-L152
WikidPad/WikidPad
558109638807bc76b4672922686e416ab2d5f79c
WikidPad/lib/pwiki/timeView/WikiWideHistory.py
python
HistoryEntry.serializeFromXml
(self, xmlNode)
Set object state from data in xmlNode)
Set object state from data in xmlNode)
[ "Set", "object", "state", "from", "data", "in", "xmlNode", ")" ]
def serializeFromXml(self, xmlNode): """ Set object state from data in xmlNode) """ self.xmlNode = xmlNode self.unifiedPageName = serFromXmlUnicode(xmlNode, "unifiedName") timeStr = serFromXmlUnicode(xmlNode, "visitedTime") self.visitedTimeStamp = timegm(time.strptime(timeStr, "%Y-%m-%d/%H:%M:%S"))
[ "def", "serializeFromXml", "(", "self", ",", "xmlNode", ")", ":", "self", ".", "xmlNode", "=", "xmlNode", "self", ".", "unifiedPageName", "=", "serFromXmlUnicode", "(", "xmlNode", ",", "\"unifiedName\"", ")", "timeStr", "=", "serFromXmlUnicode", "(", "xmlNode", ...
https://github.com/WikidPad/WikidPad/blob/558109638807bc76b4672922686e416ab2d5f79c/WikidPad/lib/pwiki/timeView/WikiWideHistory.py#L64-L74
openstack/cinder
23494a6d6c51451688191e1847a458f1d3cdcaa5
cinder/volume/drivers/dell_emc/powermax/performance.py
python
PowerMaxPerformance._get_port_group_performance_stats
( self, array_id, port_group_id, f_date, l_date, metric, data_format)
return self._process_load(result, metric)
Get performance data for a given port group and performance metric. :param array_id: the array serial number -- str :param port_group_id: the port group id -- str :param f_date: first date for stats -- int :param l_date: last date for stats -- int :param metric: performance metric -- str :param data_format: performance data format -- str :returns: range average, range total, interval count -- float, float, int
Get performance data for a given port group and performance metric.
[ "Get", "performance", "data", "for", "a", "given", "port", "group", "and", "performance", "metric", "." ]
def _get_port_group_performance_stats( self, array_id, port_group_id, f_date, l_date, metric, data_format): """Get performance data for a given port group and performance metric. :param array_id: the array serial number -- str :param port_group_id: the port group id -- str :param f_date: first date for stats -- int :param l_date: last date for stats -- int :param metric: performance metric -- str :param data_format: performance data format -- str :returns: range average, range total, interval count -- float, float, int """ request_body = { utils.SYMM_ID: array_id, utils.PORT_GROUP_ID: port_group_id, utils.S_DATE: f_date, utils.E_DATE: l_date, utils.DATA_FORMAT: data_format, utils.METRICS: [metric]} port_group_uri = self.rest.build_uri( category=utils.PERFORMANCE, resource_level=utils.PORT_GROUP, resource_type=utils.METRICS, no_version=True) result = self.rest.post_request( port_group_uri, 'Port Group performance metrics', request_body) return self._process_load(result, metric)
[ "def", "_get_port_group_performance_stats", "(", "self", ",", "array_id", ",", "port_group_id", ",", "f_date", ",", "l_date", ",", "metric", ",", "data_format", ")", ":", "request_body", "=", "{", "utils", ".", "SYMM_ID", ":", "array_id", ",", "utils", ".", ...
https://github.com/openstack/cinder/blob/23494a6d6c51451688191e1847a458f1d3cdcaa5/cinder/volume/drivers/dell_emc/powermax/performance.py#L228-L255
eggnogdb/eggnog-mapper
d6e6cdf0a829f2bd85480f3f3f16e38c213cd091
eggnogmapper/search/hits_io.py
python
output_hits
(cmds, hits, out_file, resume, no_file_comments, outfmt_short)
return
[]
def output_hits(cmds, hits, out_file, resume, no_file_comments, outfmt_short): start_time = time.time() if resume == True: file_mode = 'a' else: file_mode = 'w' with open(out_file, file_mode) as OUT: # comments if not no_file_comments: print(get_call_info(), file=OUT) if cmds is not None: for cmd in cmds: print('##'+cmd, file=OUT) # header (only first time, not for further resume) if file_mode == 'w': if outfmt_short == True: print('#'+"\t".join("qseqid sseqid evalue bitscore".split(" ")), file=OUT) else: print('#'+"\t".join(("qseqid sseqid evalue bitscore qstart qend " "sstart send pident qcov scov").split(" ")), file=OUT) qn = 0 # rows # (hit, skip): hits are wrapped in a tuple with a boolean flag # to be output or not for hit, skip in hits: # only print the hit if not already present and --resume if skip == False: print('\t'.join(map(str, hit)), file=OUT) # always yield the hit yield hit qn += 1 elapsed_time = time.time() - start_time if not no_file_comments: print('## %d queries scanned' % (qn), file=OUT) print('## Total time (seconds):', elapsed_time, file=OUT) print('## Rate:', "%0.2f q/s" % ((float(qn) / elapsed_time)), file=OUT) return
[ "def", "output_hits", "(", "cmds", ",", "hits", ",", "out_file", ",", "resume", ",", "no_file_comments", ",", "outfmt_short", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "if", "resume", "==", "True", ":", "file_mode", "=", "'a'", "else", ...
https://github.com/eggnogdb/eggnog-mapper/blob/d6e6cdf0a829f2bd85480f3f3f16e38c213cd091/eggnogmapper/search/hits_io.py#L39-L83
BMW-InnovationLab/BMW-TensorFlow-Training-GUI
4f10d1f00f9ac312ca833e5b28fd0f8952cfee17
training_api/research/slim/nets/mobilenet_v1_train.py
python
train_model
()
Trains mobilenet_v1.
Trains mobilenet_v1.
[ "Trains", "mobilenet_v1", "." ]
def train_model(): """Trains mobilenet_v1.""" g, train_tensor = build_model() with g.as_default(): slim.learning.train( train_tensor, FLAGS.checkpoint_dir, is_chief=(FLAGS.task == 0), master=FLAGS.master, log_every_n_steps=FLAGS.log_every_n_steps, graph=g, number_of_steps=FLAGS.number_of_steps, save_summaries_secs=FLAGS.save_summaries_secs, save_interval_secs=FLAGS.save_interval_secs, init_fn=get_checkpoint_init_fn(), global_step=tf.train.get_global_step())
[ "def", "train_model", "(", ")", ":", "g", ",", "train_tensor", "=", "build_model", "(", ")", "with", "g", ".", "as_default", "(", ")", ":", "slim", ".", "learning", ".", "train", "(", "train_tensor", ",", "FLAGS", ".", "checkpoint_dir", ",", "is_chief", ...
https://github.com/BMW-InnovationLab/BMW-TensorFlow-Training-GUI/blob/4f10d1f00f9ac312ca833e5b28fd0f8952cfee17/training_api/research/slim/nets/mobilenet_v1_train.py#L189-L204
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/inspectlib/collector.py
python
Inspector._get_managed_files
(self)
return list(), list(), list()
Build a in-memory data of all managed files.
Build a in-memory data of all managed files.
[ "Build", "a", "in", "-", "memory", "data", "of", "all", "managed", "files", "." ]
def _get_managed_files(self): """ Build a in-memory data of all managed files. """ if self.grains_core.os_data().get("os_family") == "Debian": return self.__get_managed_files_dpkg() elif self.grains_core.os_data().get("os_family") in ["Suse", "redhat"]: return self.__get_managed_files_rpm() return list(), list(), list()
[ "def", "_get_managed_files", "(", "self", ")", ":", "if", "self", ".", "grains_core", ".", "os_data", "(", ")", ".", "get", "(", "\"os_family\"", ")", "==", "\"Debian\"", ":", "return", "self", ".", "__get_managed_files_dpkg", "(", ")", "elif", "self", "."...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/inspectlib/collector.py#L280-L289
igushev/city_visit_planner
95e868d24df1435a6f2cbbb64b9d74050aeddfe7
router/cost_accumulator.py
python
CostAccumulatorInterface.AddPointVisit
(self, point)
Add visiting point to the cost.
Add visiting point to the cost.
[ "Add", "visiting", "point", "to", "the", "cost", "." ]
def AddPointVisit(self, point): """Add visiting point to the cost.""" raise NotImplemented()
[ "def", "AddPointVisit", "(", "self", ",", "point", ")", ":", "raise", "NotImplemented", "(", ")" ]
https://github.com/igushev/city_visit_planner/blob/95e868d24df1435a6f2cbbb64b9d74050aeddfe7/router/cost_accumulator.py#L21-L23
mozillazg/baidu-pcs-python-sdk
12fe3f13b2ecda8f8bdcc5334c876e934776a5cc
baidupcs/api.py
python
PCS.video_convert
(self, remote_path, video_type, **kwargs)
return self._request('file', 'streaming', extra_params=params, **kwargs)
对视频文件进行转码,实现实时观看视频功能. 可下载支持 HLS/M3U8 的 `媒体云播放器 SDK <HLSSDK_>`__ 配合使用. .. _HLSSDK: http://developer.baidu.com/wiki/index.php?title=docs/cplat/media/sdk :param remote_path: 需要下载的视频文件路径,以/开头的绝对路径, 需含源文件的文件名。 .. warning:: * 路径长度限制为1000; * 径中不能包含以下字符:``\\\\ ? | " > < : *``; * 文件名或路径名开头结尾不能是 ``.`` 或空白字符,空白字符包括: ``\\r, \\n, \\t, 空格, \\0, \\x0B`` 。 :type remote_path: str :param video_type: 目前支持以下格式: M3U8_320_240、M3U8_480_224、M3U8_480_360、 M3U8_640_480和M3U8_854_480 :type video_type: str :return: Response 对象 .. warning:: 目前这个接口支持的源文件格式如下: +--------------------------+------------+--------------------------+ |格式名称 |扩展名 |备注 | +==========================+============+==========================+ |Apple HTTP Live Streaming |m3u8/m3u |iOS支持的视频格式 | +--------------------------+------------+--------------------------+ |ASF |asf |视频格式 | +--------------------------+------------+--------------------------+ |AVI |avi |视频格式 | +--------------------------+------------+--------------------------+ |Flash Video (FLV) |flv |Macromedia Flash视频格式 | +--------------------------+------------+--------------------------+ |GIF Animation |gif |视频格式 | +--------------------------+------------+--------------------------+ |Matroska |mkv |Matroska/WebM视频格式 | +--------------------------+------------+--------------------------+ |MOV/QuickTime/MP4 |mov/mp4/m4a/|支持3GP、3GP2、PSP、iPod | | |3gp/3g2/mj2 |之类视频格式 | +--------------------------+------------+--------------------------+ |MPEG-PS (program stream) |mpeg |也就是VOB文件/SVCD/DVD格式| +--------------------------+------------+--------------------------+ |MPEG-TS (transport stream)|ts | 即DVB传输流 | +--------------------------+------------+--------------------------+ |RealMedia |rm/rmvb | Real视频格式 | +--------------------------+------------+--------------------------+ |WebM |webm | Html视频格式 | +--------------------------+------------+--------------------------+
对视频文件进行转码,实现实时观看视频功能. 可下载支持 HLS/M3U8 的 `媒体云播放器 SDK <HLSSDK_>`__ 配合使用.
[ "对视频文件进行转码,实现实时观看视频功能", ".", "可下载支持", "HLS", "/", "M3U8", "的", "媒体云播放器", "SDK", "<HLSSDK_", ">", "__", "配合使用", "." ]
def video_convert(self, remote_path, video_type, **kwargs): """对视频文件进行转码,实现实时观看视频功能. 可下载支持 HLS/M3U8 的 `媒体云播放器 SDK <HLSSDK_>`__ 配合使用. .. _HLSSDK: http://developer.baidu.com/wiki/index.php?title=docs/cplat/media/sdk :param remote_path: 需要下载的视频文件路径,以/开头的绝对路径, 需含源文件的文件名。 .. warning:: * 路径长度限制为1000; * 径中不能包含以下字符:``\\\\ ? | " > < : *``; * 文件名或路径名开头结尾不能是 ``.`` 或空白字符,空白字符包括: ``\\r, \\n, \\t, 空格, \\0, \\x0B`` 。 :type remote_path: str :param video_type: 目前支持以下格式: M3U8_320_240、M3U8_480_224、M3U8_480_360、 M3U8_640_480和M3U8_854_480 :type video_type: str :return: Response 对象 .. warning:: 目前这个接口支持的源文件格式如下: +--------------------------+------------+--------------------------+ |格式名称 |扩展名 |备注 | +==========================+============+==========================+ |Apple HTTP Live Streaming |m3u8/m3u |iOS支持的视频格式 | +--------------------------+------------+--------------------------+ |ASF |asf |视频格式 | +--------------------------+------------+--------------------------+ |AVI |avi |视频格式 | +--------------------------+------------+--------------------------+ |Flash Video (FLV) |flv |Macromedia Flash视频格式 | +--------------------------+------------+--------------------------+ |GIF Animation |gif |视频格式 | +--------------------------+------------+--------------------------+ |Matroska |mkv |Matroska/WebM视频格式 | +--------------------------+------------+--------------------------+ |MOV/QuickTime/MP4 |mov/mp4/m4a/|支持3GP、3GP2、PSP、iPod | | |3gp/3g2/mj2 |之类视频格式 | +--------------------------+------------+--------------------------+ |MPEG-PS (program stream) |mpeg |也就是VOB文件/SVCD/DVD格式| +--------------------------+------------+--------------------------+ |MPEG-TS (transport stream)|ts | 即DVB传输流 | +--------------------------+------------+--------------------------+ |RealMedia |rm/rmvb | Real视频格式 | +--------------------------+------------+--------------------------+ |WebM |webm | Html视频格式 | +--------------------------+------------+--------------------------+ """ params = { 'path': remote_path, 'type': video_type, } return self._request('file', 'streaming', extra_params=params, **kwargs)
[ "def", "video_convert", "(", "self", ",", "remote_path", ",", "video_type", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'path'", ":", "remote_path", ",", "'type'", ":", "video_type", ",", "}", "return", "self", ".", "_request", "(", "'file'",...
https://github.com/mozillazg/baidu-pcs-python-sdk/blob/12fe3f13b2ecda8f8bdcc5334c876e934776a5cc/baidupcs/api.py#L586-L645
mike01/pypacker
7e98b2cb00c465f726490580761ad6261302b6a6
pypacker/pypacker.py
python
Packet._update_header_format
(self)
Update format of this packet header. Needs to be called on changes to dynamic fields.
Update format of this packet header. Needs to be called on changes to dynamic fields.
[ "Update", "format", "of", "this", "packet", "header", ".", "Needs", "to", "be", "called", "on", "changes", "to", "dynamic", "fields", "." ]
def _update_header_format(self): """ Update format of this packet header. Needs to be called on changes to dynamic fields. """ header_format = [self._header_format_order] self_getattr = self.__getattribute__ for name in self._header_field_names: if not self_getattr(name + "_active"): continue val = self.__getattribute__(name) if val.__class__ in HEADER_TYPES_SIMPLE: # assume bytes/int header_format.append(self_getattr(name + "_format")) # logger.debug("adding format for (simple): %r, %s, val: %s format: %s", # self.__class__, name, self_getattr(name), self_getattr(name + "_format")) else: # assume TriggerList if val.__class__ == list: # TriggerList not yet initiated: take cached value header_format.append("%ds" % len(val[0])) #logger.debug("adding format for: %r, %s, val: %s", self.__class__, name, val[0]) else: try: header_format.append("%ds" % len(val.bin())) except AttributeError as err: raise InvalidValuetypeException("Unknown value-type in %r for header" " field %r: %r, allowed: int, bytes, Packets, tuples" " (depending on context)" % (self.__class__, name[1:], type(val))) from err self._header_format = Struct("".join(header_format)) self._header_len = self._header_format.size self._header_format_changed = False
[ "def", "_update_header_format", "(", "self", ")", ":", "header_format", "=", "[", "self", ".", "_header_format_order", "]", "self_getattr", "=", "self", ".", "__getattribute__", "for", "name", "in", "self", ".", "_header_field_names", ":", "if", "not", "self_get...
https://github.com/mike01/pypacker/blob/7e98b2cb00c465f726490580761ad6261302b6a6/pypacker/pypacker.py#L873-L905
SeldonIO/alibi-detect
b5ec53cfadcd8e3463d400259f2ea1b752ed1812
alibi_detect/od/sr.py
python
SpectralResidual.__init__
(self, threshold: float = None, window_amp: int = None, window_local: int = None, padding_amp_method: Literal['constant', 'replicate', 'reflect'] = 'reflect', padding_local_method: Literal['constant', 'replicate', 'reflect'] = 'reflect', padding_amp_side: Literal['bilateral', 'left', 'right'] = 'bilateral', n_est_points: int = None, n_grad_points: int = 5, )
Outlier detector for time-series data using the spectral residual algorithm. Based on "Time-Series Anomaly Detection Service at Microsoft" (Ren et al., 2019) https://arxiv.org/abs/1906.03821 Parameters ---------- threshold Threshold used to classify outliers. Relative saliency map distance from the moving average. window_amp Window for the average log amplitude. window_local Window for the local average of the saliency map. Note that the averaging is performed over the previous `window_local` data points (i.e., is a local average of the preceding `window_local` points for the current index). padding_amp_method Padding method to be used prior to each convolution over log amplitude. Possible values: `constant` | `replicate` | `reflect`. Default value: `replicate`. - `constant` - padding with constant 0. - `replicate` - repeats the last/extreme value. - `reflect` - reflects the time series. padding_local_method Padding method to be used prior to each convolution over saliency map. Possible values: `constant` | `replicate` | `reflect`. Default value: `replicate`. - `constant` - padding with constant 0. - `replicate` - repeats the last/extreme value. - `reflect` - reflects the time series. padding_amp_side Whether to pad the amplitudes on both sides or only on one side. Possible values: `bilateral` | `left` | `right`. n_est_points Number of estimated points padded to the end of the sequence. n_grad_points Number of points used for the gradient estimation of the additional points padded to the end of the sequence.
Outlier detector for time-series data using the spectral residual algorithm. Based on "Time-Series Anomaly Detection Service at Microsoft" (Ren et al., 2019) https://arxiv.org/abs/1906.03821
[ "Outlier", "detector", "for", "time", "-", "series", "data", "using", "the", "spectral", "residual", "algorithm", ".", "Based", "on", "Time", "-", "Series", "Anomaly", "Detection", "Service", "at", "Microsoft", "(", "Ren", "et", "al", ".", "2019", ")", "ht...
def __init__(self, threshold: float = None, window_amp: int = None, window_local: int = None, padding_amp_method: Literal['constant', 'replicate', 'reflect'] = 'reflect', padding_local_method: Literal['constant', 'replicate', 'reflect'] = 'reflect', padding_amp_side: Literal['bilateral', 'left', 'right'] = 'bilateral', n_est_points: int = None, n_grad_points: int = 5, ) -> None: """ Outlier detector for time-series data using the spectral residual algorithm. Based on "Time-Series Anomaly Detection Service at Microsoft" (Ren et al., 2019) https://arxiv.org/abs/1906.03821 Parameters ---------- threshold Threshold used to classify outliers. Relative saliency map distance from the moving average. window_amp Window for the average log amplitude. window_local Window for the local average of the saliency map. Note that the averaging is performed over the previous `window_local` data points (i.e., is a local average of the preceding `window_local` points for the current index). padding_amp_method Padding method to be used prior to each convolution over log amplitude. Possible values: `constant` | `replicate` | `reflect`. Default value: `replicate`. - `constant` - padding with constant 0. - `replicate` - repeats the last/extreme value. - `reflect` - reflects the time series. padding_local_method Padding method to be used prior to each convolution over saliency map. Possible values: `constant` | `replicate` | `reflect`. Default value: `replicate`. - `constant` - padding with constant 0. - `replicate` - repeats the last/extreme value. - `reflect` - reflects the time series. padding_amp_side Whether to pad the amplitudes on both sides or only on one side. Possible values: `bilateral` | `left` | `right`. n_est_points Number of estimated points padded to the end of the sequence. n_grad_points Number of points used for the gradient estimation of the additional points padded to the end of the sequence. """ super().__init__() if threshold is None: logger.warning("No threshold level set. Need to infer threshold using `infer_threshold`.") self.threshold = threshold self.window_amp = window_amp self.window_local = window_local self.conv_amp = np.ones((1, window_amp)).reshape(-1,) / window_amp # conv_local needs a special treatment since the paper says that: # \bar{S}(xi) is the local average of the preceding z points of S(xi). # To use the same padding implementation that includes the current point we convolving, we define a modified # filter given by: [0, 1, 1, 1, ... ,1] / window_local of size `window_local + 1`. In this way # the current value is multiplied by 0 and thus neglected. Note that the 0 goes first since before the # element-wise multiplication, the filter is flipped. We only do this since the filter is asymmetric. self.conv_local = np.ones((1, window_local + 1)).reshape(-1,) / window_local self.conv_local[0] = 0 self.n_est_points = n_est_points self.n_grad_points = n_grad_points self.padding_amp_method = padding_amp_method self.padding_local_method = padding_local_method self.padding_amp_side = padding_amp_side # set metadata self.meta['detector_type'] = 'online' self.meta['data_type'] = 'time-series'
[ "def", "__init__", "(", "self", ",", "threshold", ":", "float", "=", "None", ",", "window_amp", ":", "int", "=", "None", ",", "window_local", ":", "int", "=", "None", ",", "padding_amp_method", ":", "Literal", "[", "'constant'", ",", "'replicate'", ",", ...
https://github.com/SeldonIO/alibi-detect/blob/b5ec53cfadcd8e3463d400259f2ea1b752ed1812/alibi_detect/od/sr.py#L28-L109
francisck/DanderSpritz_docs
86bb7caca5a957147f120b18bb5c31f299914904
Python/Core/Lib/lib2to3/patcomp.py
python
PatternCompiler.compile_node
(self, node)
Compiles a node, recursively. This is one big switch on the node type.
Compiles a node, recursively. This is one big switch on the node type.
[ "Compiles", "a", "node", "recursively", ".", "This", "is", "one", "big", "switch", "on", "the", "node", "type", "." ]
def compile_node(self, node): """Compiles a node, recursively. This is one big switch on the node type. """ if node.type == self.syms.Matcher: node = node.children[0] if node.type == self.syms.Alternatives: alts = [ self.compile_node(ch) for ch in node.children[::2] ] if len(alts) == 1: return alts[0] p = pytree.WildcardPattern([ [a] for a in alts ], min=1, max=1) return p.optimize() else: if node.type == self.syms.Alternative: units = [ self.compile_node(ch) for ch in node.children ] if len(units) == 1: return units[0] p = pytree.WildcardPattern([units], min=1, max=1) return p.optimize() if node.type == self.syms.NegatedUnit: pattern = self.compile_basic(node.children[1:]) p = pytree.NegatedPattern(pattern) return p.optimize() name = None nodes = node.children if len(nodes) >= 3 and nodes[1].type == token.EQUAL: name = nodes[0].value nodes = nodes[2:] repeat = None if len(nodes) >= 2 and nodes[-1].type == self.syms.Repeater: repeat = nodes[-1] nodes = nodes[:-1] pattern = self.compile_basic(nodes, repeat) if repeat is not None: children = repeat.children child = children[0] if child.type == token.STAR: min = 0 max = pytree.HUGE elif child.type == token.PLUS: min = 1 max = pytree.HUGE elif child.type == token.LBRACE: min = max = self.get_int(children[1]) if len(children) == 5: max = self.get_int(children[3]) if min != 1 or max != 1: pattern = pattern.optimize() pattern = pytree.WildcardPattern([[pattern]], min=min, max=max) if name is not None: pattern.name = name return pattern.optimize()
[ "def", "compile_node", "(", "self", ",", "node", ")", ":", "if", "node", ".", "type", "==", "self", ".", "syms", ".", "Matcher", ":", "node", "=", "node", ".", "children", "[", "0", "]", "if", "node", ".", "type", "==", "self", ".", "syms", ".", ...
https://github.com/francisck/DanderSpritz_docs/blob/86bb7caca5a957147f120b18bb5c31f299914904/Python/Core/Lib/lib2to3/patcomp.py#L60-L112
grnet/synnefo
d06ec8c7871092131cdaabf6b03ed0b504c93e43
snf-pithos-backend/pithos/backends/lib/sqlalchemy/node.py
python
Node.node_account_usage
(self, account=None, project=None, cluster=0)
return d
Return a dict of dicts with the project usage for a specific account Keyword arguments: account -- (default None: list usage for all accounts) project -- (default None: list usage for all projects) cluster -- list current, history or deleted usage (default 0: normal)
Return a dict of dicts with the project usage for a specific account
[ "Return", "a", "dict", "of", "dicts", "with", "the", "project", "usage", "for", "a", "specific", "account" ]
def node_account_usage(self, account=None, project=None, cluster=0): """Return a dict of dicts with the project usage for a specific account Keyword arguments: account -- (default None: list usage for all accounts) project -- (default None: list usage for all projects) cluster -- list current, history or deleted usage (default 0: normal) """ n1 = self.nodes.alias('n1') n2 = self.nodes.alias('n2') n3 = self.nodes.alias('n3') s = select([n3.c.path, self.policy.c.value, func.sum(self.versions.c.size)]) s = s.where(self.policy.c.key == 'project') s = s.where(self.policy.c.node == n2.c.node) s = s.where(n1.c.node == self.versions.c.node) s = s.where(self.versions.c.cluster == cluster) s = s.where(n1.c.parent == n2.c.node) s = s.where(n2.c.parent == n3.c.node) s = s.where(n3.c.parent == 0) s = s.where(n3.c.node != 0) s = s.group_by(n3.c.path, self.policy.c.value) if account: s = s.where(n3.c.path == account) if project: s = s.where(self.policy.c.value == project) r = self.conn.execute(s) rows = r.fetchall() r.close() d = defaultdict(lambda: defaultdict(dict)) for account, project, usage in rows: d[account][project][DEFAULT_DISKSPACE_RESOURCE] = \ safe_long(usage) return d
[ "def", "node_account_usage", "(", "self", ",", "account", "=", "None", ",", "project", "=", "None", ",", "cluster", "=", "0", ")", ":", "n1", "=", "self", ".", "nodes", ".", "alias", "(", "'n1'", ")", "n2", "=", "self", ".", "nodes", ".", "alias", ...
https://github.com/grnet/synnefo/blob/d06ec8c7871092131cdaabf6b03ed0b504c93e43/snf-pithos-backend/pithos/backends/lib/sqlalchemy/node.py#L538-L573
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
lib-python/2.7/plat-mac/pimp.py
python
PimpPackage_source.unpackPackageOnly
(self, output=None)
Unpack a source package and check that setup.py exists
Unpack a source package and check that setup.py exists
[ "Unpack", "a", "source", "package", "and", "check", "that", "setup", ".", "py", "exists" ]
def unpackPackageOnly(self, output=None): """Unpack a source package and check that setup.py exists""" PimpPackage.unpackPackageOnly(self, output) # Test that a setup script has been create self._buildDirname = os.path.join(self._db.preferences.buildDir, self.basename) setupname = os.path.join(self._buildDirname, "setup.py") if not os.path.exists(setupname) and not NO_EXECUTE: return "no setup.py found after unpack of archive"
[ "def", "unpackPackageOnly", "(", "self", ",", "output", "=", "None", ")", ":", "PimpPackage", ".", "unpackPackageOnly", "(", "self", ",", "output", ")", "# Test that a setup script has been create", "self", ".", "_buildDirname", "=", "os", ".", "path", ".", "joi...
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/plat-mac/pimp.py#L849-L856
mynameisfiber/high_performance_python
615341ff066772dc45125fce1866349d555524fe
07_compiling/cython/nparray_memoryview/2/julia1.py
python
calc_pure_python
(draw_output, desired_width, max_iterations)
Create a list of complex co-ordinates (zs) and complex parameters (cs), build Julia set and display
Create a list of complex co-ordinates (zs) and complex parameters (cs), build Julia set and display
[ "Create", "a", "list", "of", "complex", "co", "-", "ordinates", "(", "zs", ")", "and", "complex", "parameters", "(", "cs", ")", "build", "Julia", "set", "and", "display" ]
def calc_pure_python(draw_output, desired_width, max_iterations): """Create a list of complex co-ordinates (zs) and complex parameters (cs), build Julia set and display""" x_step = (float(x2 - x1) / float(desired_width)) y_step = (float(y1 - y2) / float(desired_width)) x = [] y = [] ycoord = y2 while ycoord > y1: y.append(ycoord) ycoord += y_step xcoord = x1 while xcoord < x2: x.append(xcoord) xcoord += x_step # build a list of co-ordinates and the initial condition for each cell. # Note that our initial condition is a constant and could easily be removed, # we use it to simulate a real-world scenario with several inputs to our # function zs = [] cs = [] for ycoord in y: for xcoord in x: zs.append(complex(xcoord, ycoord)) cs.append(complex(c_real, c_imag)) zs_np = np.array(zs, np.complex128) cs_np = np.array(cs, np.complex128) print "Length of x:", len(x) print "Total elements:", len(zs) start_time = time.time() output = calculate.calculate_z(max_iterations, zs_np, cs_np) end_time = time.time() secs = end_time - start_time print "Took", secs, "seconds" validation_sum = sum(output) print "Total sum of elements (for validation):", validation_sum
[ "def", "calc_pure_python", "(", "draw_output", ",", "desired_width", ",", "max_iterations", ")", ":", "x_step", "=", "(", "float", "(", "x2", "-", "x1", ")", "/", "float", "(", "desired_width", ")", ")", "y_step", "=", "(", "float", "(", "y1", "-", "y2...
https://github.com/mynameisfiber/high_performance_python/blob/615341ff066772dc45125fce1866349d555524fe/07_compiling/cython/nparray_memoryview/2/julia1.py#L11-L48
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/redis/client.py
python
PubSub.reset
(self)
[]
def reset(self): if self.connection: self.connection.disconnect() self.connection.clear_connect_callbacks() self.connection_pool.release(self.connection) self.connection = None self.channels = {} self.patterns = {}
[ "def", "reset", "(", "self", ")", ":", "if", "self", ".", "connection", ":", "self", ".", "connection", ".", "disconnect", "(", ")", "self", ".", "connection", ".", "clear_connect_callbacks", "(", ")", "self", ".", "connection_pool", ".", "release", "(", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/redis/client.py#L2355-L2362
shiweibsw/Translation-Tools
2fbbf902364e557fa7017f9a74a8797b7440c077
venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/chardet/universaldetector.py
python
UniversalDetector.close
(self)
return self.result
Stop analyzing the current document and come up with a final prediction. :returns: The ``result`` attribute, a ``dict`` with the keys `encoding`, `confidence`, and `language`.
Stop analyzing the current document and come up with a final prediction.
[ "Stop", "analyzing", "the", "current", "document", "and", "come", "up", "with", "a", "final", "prediction", "." ]
def close(self): """ Stop analyzing the current document and come up with a final prediction. :returns: The ``result`` attribute, a ``dict`` with the keys `encoding`, `confidence`, and `language`. """ # Don't bother with checks if we're already done if self.done: return self.result self.done = True if not self._got_data: self.logger.debug('no data received!') # Default to ASCII if it is all we've seen so far elif self._input_state == InputState.PURE_ASCII: self.result = {'encoding': 'ascii', 'confidence': 1.0, 'language': ''} # If we have seen non-ASCII, return the best that met MINIMUM_THRESHOLD elif self._input_state == InputState.HIGH_BYTE: prober_confidence = None max_prober_confidence = 0.0 max_prober = None for prober in self._charset_probers: if not prober: continue prober_confidence = prober.get_confidence() if prober_confidence > max_prober_confidence: max_prober_confidence = prober_confidence max_prober = prober if max_prober and (max_prober_confidence > self.MINIMUM_THRESHOLD): charset_name = max_prober.charset_name lower_charset_name = max_prober.charset_name.lower() confidence = max_prober.get_confidence() # Use Windows encoding name instead of ISO-8859 if we saw any # extra Windows-specific bytes if lower_charset_name.startswith('iso-8859'): if self._has_win_bytes: charset_name = self.ISO_WIN_MAP.get(lower_charset_name, charset_name) self.result = {'encoding': charset_name, 'confidence': confidence, 'language': max_prober.language} # Log all prober confidences if none met MINIMUM_THRESHOLD if self.logger.getEffectiveLevel() == logging.DEBUG: if self.result['encoding'] is None: self.logger.debug('no probers hit minimum threshold') for group_prober in self._charset_probers: if not group_prober: continue if isinstance(group_prober, CharSetGroupProber): for prober in group_prober.probers: self.logger.debug('%s %s confidence = %s', prober.charset_name, prober.language, prober.get_confidence()) else: self.logger.debug('%s %s confidence = %s', prober.charset_name, prober.language, prober.get_confidence()) return self.result
[ "def", "close", "(", "self", ")", ":", "# Don't bother with checks if we're already done", "if", "self", ".", "done", ":", "return", "self", ".", "result", "self", ".", "done", "=", "True", "if", "not", "self", ".", "_got_data", ":", "self", ".", "logger", ...
https://github.com/shiweibsw/Translation-Tools/blob/2fbbf902364e557fa7017f9a74a8797b7440c077/venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/chardet/universaldetector.py#L220-L286
Adnios/Tensorflow
69d6e04fef9d7061bef9e32f807f3f2dc132cf8e
Tensorflow 6 fc2/mnist_forward.py
python
get_bias
(shape)
return b
[]
def get_bias(shape): # 初始化的一维数组,初始化值为全 0 b = tf.Variable(tf.zeros(shape)) return b
[ "def", "get_bias", "(", "shape", ")", ":", "# 初始化的一维数组,初始化值为全 0", "b", "=", "tf", ".", "Variable", "(", "tf", ".", "zeros", "(", "shape", ")", ")", "return", "b" ]
https://github.com/Adnios/Tensorflow/blob/69d6e04fef9d7061bef9e32f807f3f2dc132cf8e/Tensorflow 6 fc2/mnist_forward.py#L21-L24
pjkundert/cpppo
4c217b6c06b88bede3888cc5ea2731f271a95086
server/enip/parser.py
python
octets_noop.__init__
( self, name=None, octets_state=state, **kwds )
[]
def __init__( self, name=None, octets_state=state, **kwds ): super( octets_noop, self ).__init__( name=name, octets_name="noop", octets_state=octets_state, **kwds )
[ "def", "__init__", "(", "self", ",", "name", "=", "None", ",", "octets_state", "=", "state", ",", "*", "*", "kwds", ")", ":", "super", "(", "octets_noop", ",", "self", ")", ".", "__init__", "(", "name", "=", "name", ",", "octets_name", "=", "\"noop\"...
https://github.com/pjkundert/cpppo/blob/4c217b6c06b88bede3888cc5ea2731f271a95086/server/enip/parser.py#L110-L112
nschloe/pygmsh
3e7eea6fae3b4cd5e9f2c2d52b3686d3e5a1a725
src/pygmsh/common/geometry.py
python
CommonGeometry.rotate
( self, obj, point: tuple[float, float, float], angle: float, axis: tuple[float, float, float], )
Rotate input_entity around a given point with a given angle. Rotation axis has to be specified. Changes the input object.
Rotate input_entity around a given point with a given angle. Rotation axis has to be specified.
[ "Rotate", "input_entity", "around", "a", "given", "point", "with", "a", "given", "angle", ".", "Rotation", "axis", "has", "to", "be", "specified", "." ]
def rotate( self, obj, point: tuple[float, float, float], angle: float, axis: tuple[float, float, float], ): """Rotate input_entity around a given point with a given angle. Rotation axis has to be specified. Changes the input object. """ self.env.rotate(obj.dim_tags, *point, *axis, angle)
[ "def", "rotate", "(", "self", ",", "obj", ",", "point", ":", "tuple", "[", "float", ",", "float", ",", "float", "]", ",", "angle", ":", "float", ",", "axis", ":", "tuple", "[", "float", ",", "float", ",", "float", "]", ",", ")", ":", "self", "....
https://github.com/nschloe/pygmsh/blob/3e7eea6fae3b4cd5e9f2c2d52b3686d3e5a1a725/src/pygmsh/common/geometry.py#L229-L241
yandex/gixy
641060d6355fbb5bd71695928a2bf14a9bcb8bf2
gixy/parser/raw_parser.py
python
_fix_comment
(string, location, tokens)
return [comment]
Returns "cleared" comment text :param string: original parse string :param location: location in the string where matching started :param tokens: list of the matched tokens, packaged as a ParseResults_ object :return: list of the cleared comment tokens
Returns "cleared" comment text
[ "Returns", "cleared", "comment", "text" ]
def _fix_comment(string, location, tokens): """ Returns "cleared" comment text :param string: original parse string :param location: location in the string where matching started :param tokens: list of the matched tokens, packaged as a ParseResults_ object :return: list of the cleared comment tokens """ comment = tokens[0][1:].strip() return [comment]
[ "def", "_fix_comment", "(", "string", ",", "location", ",", "tokens", ")", ":", "comment", "=", "tokens", "[", "0", "]", "[", "1", ":", "]", ".", "strip", "(", ")", "return", "[", "comment", "]" ]
https://github.com/yandex/gixy/blob/641060d6355fbb5bd71695928a2bf14a9bcb8bf2/gixy/parser/raw_parser.py#L176-L187
TristenHarr/MyPyBuilder
5823ae9e5fcd2d745a70425c37a3aaa432c0389d
GuiBuilder/BUILDER/PROJECTBUILDER/Demo/MainGuiBuilderDemo.py
python
DemoGui.is_int
(data, default=0)
This is used as simple form validation to check if the input is a valid integer. :param data: The raw data from a form :type data: str :param default: The lowest allowed integer :type default: int :return: integer if valid, False otherwise
This is used as simple form validation to check if the input is a valid integer.
[ "This", "is", "used", "as", "simple", "form", "validation", "to", "check", "if", "the", "input", "is", "a", "valid", "integer", "." ]
def is_int(data, default=0): """ This is used as simple form validation to check if the input is a valid integer. :param data: The raw data from a form :type data: str :param default: The lowest allowed integer :type default: int :return: integer if valid, False otherwise """ neg_flag = False if default < 0: if '-' == data[0]: neg_flag = True data = data.lstrip('-') if data.isdigit(): if neg_flag: data = '-' + data if int(data) >= default: return int(data) else: return False else: return False
[ "def", "is_int", "(", "data", ",", "default", "=", "0", ")", ":", "neg_flag", "=", "False", "if", "default", "<", "0", ":", "if", "'-'", "==", "data", "[", "0", "]", ":", "neg_flag", "=", "True", "data", "=", "data", ".", "lstrip", "(", "'-'", ...
https://github.com/TristenHarr/MyPyBuilder/blob/5823ae9e5fcd2d745a70425c37a3aaa432c0389d/GuiBuilder/BUILDER/PROJECTBUILDER/Demo/MainGuiBuilderDemo.py#L340-L363
csujedihy/lc-all-solutions
b9fd938a7b3c164f28096361993600e338c399c3
308.range-sum-query-2d-mutable/range-sum-query-2d-mutable.py
python
NumMatrix.__init__
(self, matrix)
initialize your data structure here. :type matrix: List[List[int]]
initialize your data structure here. :type matrix: List[List[int]]
[ "initialize", "your", "data", "structure", "here", ".", ":", "type", "matrix", ":", "List", "[", "List", "[", "int", "]]" ]
def __init__(self, matrix): """ initialize your data structure here. :type matrix: List[List[int]] """ if len(matrix) == 0: col = 0 else: col = len(matrix[0]) self.c = [[0] * (col + 1) for _ in range(0, len(matrix) + 1)] self.m = [[0] * (col + 1) for _ in range(0, len(matrix) + 1)] for i in range(0, len(matrix)): for j in range(0, len(matrix[0])): self.update(i, j, matrix[i][j])
[ "def", "__init__", "(", "self", ",", "matrix", ")", ":", "if", "len", "(", "matrix", ")", "==", "0", ":", "col", "=", "0", "else", ":", "col", "=", "len", "(", "matrix", "[", "0", "]", ")", "self", ".", "c", "=", "[", "[", "0", "]", "*", ...
https://github.com/csujedihy/lc-all-solutions/blob/b9fd938a7b3c164f28096361993600e338c399c3/308.range-sum-query-2d-mutable/range-sum-query-2d-mutable.py#L2-L15
etetoolkit/ete
2b207357dc2a40ccad7bfd8f54964472c72e4726
ete3/treeview/templates.py
python
apply_template
(tree_style, template)
[]
def apply_template(tree_style, template): for k, v in six.iteritems(template): setattr(tree_style, k, v)
[ "def", "apply_template", "(", "tree_style", ",", "template", ")", ":", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "template", ")", ":", "setattr", "(", "tree_style", ",", "k", ",", "v", ")" ]
https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/treeview/templates.py#L45-L47
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/lib2to3/pytree.py
python
Base.get_lineno
(self)
return node.lineno
Return the line number which generated the invocant node.
Return the line number which generated the invocant node.
[ "Return", "the", "line", "number", "which", "generated", "the", "invocant", "node", "." ]
def get_lineno(self): """Return the line number which generated the invocant node.""" node = self while not isinstance(node, Leaf): if not node.children: return node = node.children[0] return node.lineno
[ "def", "get_lineno", "(", "self", ")", ":", "node", "=", "self", "while", "not", "isinstance", "(", "node", ",", "Leaf", ")", ":", "if", "not", "node", ".", "children", ":", "return", "node", "=", "node", ".", "children", "[", "0", "]", "return", "...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/lib2to3/pytree.py#L155-L162
slackapi/python-slack-sdk
2dee6656ffacb7de0c29bb2a6c2b51ec6b5dbce7
slack_sdk/web/legacy_client.py
python
LegacyWebClient.files_sharedPublicURL
( self, *, file: str, **kwargs, )
return self.api_call("files.sharedPublicURL", params=kwargs)
Enables a file for public/external sharing. https://api.slack.com/methods/files.sharedPublicURL
Enables a file for public/external sharing. https://api.slack.com/methods/files.sharedPublicURL
[ "Enables", "a", "file", "for", "public", "/", "external", "sharing", ".", "https", ":", "//", "api", ".", "slack", ".", "com", "/", "methods", "/", "files", ".", "sharedPublicURL" ]
def files_sharedPublicURL( self, *, file: str, **kwargs, ) -> Union[Future, SlackResponse]: """Enables a file for public/external sharing. https://api.slack.com/methods/files.sharedPublicURL """ kwargs.update({"file": file}) return self.api_call("files.sharedPublicURL", params=kwargs)
[ "def", "files_sharedPublicURL", "(", "self", ",", "*", ",", "file", ":", "str", ",", "*", "*", "kwargs", ",", ")", "->", "Union", "[", "Future", ",", "SlackResponse", "]", ":", "kwargs", ".", "update", "(", "{", "\"file\"", ":", "file", "}", ")", "...
https://github.com/slackapi/python-slack-sdk/blob/2dee6656ffacb7de0c29bb2a6c2b51ec6b5dbce7/slack_sdk/web/legacy_client.py#L2858-L2868
LabPy/lantz
3e878e3f765a4295b0089d04e241d4beb7b8a65b
lantz/drivers/legacy/newport/powermeter1830c.py
python
powermeter1830c.filter
(self)
return int(self.query('F?'))
How many measurements are averaged for the displayed reading. slow: 16 measurements medium: 4 measurements fast: 1 measurement.
How many measurements are averaged for the displayed reading. slow: 16 measurements medium: 4 measurements fast: 1 measurement.
[ "How", "many", "measurements", "are", "averaged", "for", "the", "displayed", "reading", ".", "slow", ":", "16", "measurements", "medium", ":", "4", "measurements", "fast", ":", "1", "measurement", "." ]
def filter(self): """ How many measurements are averaged for the displayed reading. slow: 16 measurements medium: 4 measurements fast: 1 measurement. """ return int(self.query('F?'))
[ "def", "filter", "(", "self", ")", ":", "return", "int", "(", "self", ".", "query", "(", "'F?'", ")", ")" ]
https://github.com/LabPy/lantz/blob/3e878e3f765a4295b0089d04e241d4beb7b8a65b/lantz/drivers/legacy/newport/powermeter1830c.py#L74-L80
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit /tools/sqli/thirdparty/gprof2dot/gprof2dot.py
python
Profile.prune
(self, node_thres, edge_thres)
Prune the profile
Prune the profile
[ "Prune", "the", "profile" ]
def prune(self, node_thres, edge_thres): """Prune the profile""" # compute the prune ratios for function in self.functions.itervalues(): try: function.weight = function[TOTAL_TIME_RATIO] except UndefinedEvent: pass for call in function.calls.itervalues(): callee = self.functions[call.callee_id] if TOTAL_TIME_RATIO in call: # handle exact cases first call.weight = call[TOTAL_TIME_RATIO] else: try: # make a safe estimate call.weight = min(function[TOTAL_TIME_RATIO], callee[TOTAL_TIME_RATIO]) except UndefinedEvent: pass # prune the nodes for function_id in self.functions.keys(): function = self.functions[function_id] if function.weight is not None: if function.weight < node_thres: del self.functions[function_id] # prune the egdes for function in self.functions.itervalues(): for callee_id in function.calls.keys(): call = function.calls[callee_id] if callee_id not in self.functions or call.weight is not None and call.weight < edge_thres: del function.calls[callee_id]
[ "def", "prune", "(", "self", ",", "node_thres", ",", "edge_thres", ")", ":", "# compute the prune ratios", "for", "function", "in", "self", ".", "functions", ".", "itervalues", "(", ")", ":", "try", ":", "function", ".", "weight", "=", "function", "[", "TO...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /tools/sqli/thirdparty/gprof2dot/gprof2dot.py#L488-L523
openstack/rally
58b12c2e0bfa541bdb038be6e1679c5117b98484
rally/task/sla.py
python
SLAChecker.add_iteration
(self, iteration)
return all([sla.add_iteration(iteration) for sla in self.sla_criteria])
Process the result of a single iteration. The call to add_iteration() will return True if all the SLA checks passed, and False otherwise. :param iteration: iteration result object
Process the result of a single iteration.
[ "Process", "the", "result", "of", "a", "single", "iteration", "." ]
def add_iteration(self, iteration): """Process the result of a single iteration. The call to add_iteration() will return True if all the SLA checks passed, and False otherwise. :param iteration: iteration result object """ return all([sla.add_iteration(iteration) for sla in self.sla_criteria])
[ "def", "add_iteration", "(", "self", ",", "iteration", ")", ":", "return", "all", "(", "[", "sla", ".", "add_iteration", "(", "iteration", ")", "for", "sla", "in", "self", ".", "sla_criteria", "]", ")" ]
https://github.com/openstack/rally/blob/58b12c2e0bfa541bdb038be6e1679c5117b98484/rally/task/sla.py#L51-L59
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/idlelib/tree.py
python
TreeItem.GetIconName
(self)
Return name of icon to be displayed normally.
Return name of icon to be displayed normally.
[ "Return", "name", "of", "icon", "to", "be", "displayed", "normally", "." ]
def GetIconName(self): """Return name of icon to be displayed normally."""
[ "def", "GetIconName", "(", "self", ")", ":" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/idlelib/tree.py#L351-L352
isnowfy/pydown
71ecc891868cd2a34b7e5fe662c99474f2d0fd7f
pygments/filters/__init__.py
python
RaiseOnErrorTokenFilter.__init__
(self, **options)
[]
def __init__(self, **options): Filter.__init__(self, **options) self.exception = options.get('excclass', ErrorToken) try: # issubclass() will raise TypeError if first argument is not a class if not issubclass(self.exception, Exception): raise TypeError except TypeError: raise OptionError('excclass option is not an exception class')
[ "def", "__init__", "(", "self", ",", "*", "*", "options", ")", ":", "Filter", ".", "__init__", "(", "self", ",", "*", "*", "options", ")", "self", ".", "exception", "=", "options", ".", "get", "(", "'excclass'", ",", "ErrorToken", ")", "try", ":", ...
https://github.com/isnowfy/pydown/blob/71ecc891868cd2a34b7e5fe662c99474f2d0fd7f/pygments/filters/__init__.py#L188-L196
choasup/SIN
4851efb7b1c64180026e51ab8abcd95265c0602c
lib/datasets/imagenet3d.py
python
imagenet3d._get_default_path
(self)
return os.path.join(datasets.ROOT_DIR, 'data', 'ImageNet3D')
Return the default path where imagenet3d is expected to be installed.
Return the default path where imagenet3d is expected to be installed.
[ "Return", "the", "default", "path", "where", "imagenet3d", "is", "expected", "to", "be", "installed", "." ]
def _get_default_path(self): """ Return the default path where imagenet3d is expected to be installed. """ return os.path.join(datasets.ROOT_DIR, 'data', 'ImageNet3D')
[ "def", "_get_default_path", "(", "self", ")", ":", "return", "os", ".", "path", ".", "join", "(", "datasets", ".", "ROOT_DIR", ",", "'data'", ",", "'ImageNet3D'", ")" ]
https://github.com/choasup/SIN/blob/4851efb7b1c64180026e51ab8abcd95265c0602c/lib/datasets/imagenet3d.py#L89-L93
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/min/_pydecimal.py
python
Context.copy_decimal
(self, a)
return Decimal(a)
Returns a copy of the decimal object. >>> ExtendedContext.copy_decimal(Decimal('2.1')) Decimal('2.1') >>> ExtendedContext.copy_decimal(Decimal('-1.00')) Decimal('-1.00') >>> ExtendedContext.copy_decimal(1) Decimal('1')
Returns a copy of the decimal object.
[ "Returns", "a", "copy", "of", "the", "decimal", "object", "." ]
def copy_decimal(self, a): """Returns a copy of the decimal object. >>> ExtendedContext.copy_decimal(Decimal('2.1')) Decimal('2.1') >>> ExtendedContext.copy_decimal(Decimal('-1.00')) Decimal('-1.00') >>> ExtendedContext.copy_decimal(1) Decimal('1') """ a = _convert_other(a, raiseit=True) return Decimal(a)
[ "def", "copy_decimal", "(", "self", ",", "a", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "Decimal", "(", "a", ")" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/_pydecimal.py#L4308-L4319
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/express/_core.py
python
process_dataframe_timeline
(args)
return args
Massage input for bar traces for px.timeline()
Massage input for bar traces for px.timeline()
[ "Massage", "input", "for", "bar", "traces", "for", "px", ".", "timeline", "()" ]
def process_dataframe_timeline(args): """ Massage input for bar traces for px.timeline() """ args["is_timeline"] = True if args["x_start"] is None or args["x_end"] is None: raise ValueError("Both x_start and x_end are required") try: x_start = pd.to_datetime(args["data_frame"][args["x_start"]]) x_end = pd.to_datetime(args["data_frame"][args["x_end"]]) except (ValueError, TypeError): raise TypeError( "Both x_start and x_end must refer to data convertible to datetimes." ) # note that we are not adding any columns to the data frame here, so no risk of overwrite args["data_frame"][args["x_end"]] = (x_end - x_start).astype("timedelta64[ms]") args["x"] = args["x_end"] del args["x_end"] args["base"] = args["x_start"] del args["x_start"] return args
[ "def", "process_dataframe_timeline", "(", "args", ")", ":", "args", "[", "\"is_timeline\"", "]", "=", "True", "if", "args", "[", "\"x_start\"", "]", "is", "None", "or", "args", "[", "\"x_end\"", "]", "is", "None", ":", "raise", "ValueError", "(", "\"Both x...
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/express/_core.py#L1664-L1686
Azure/azure-devops-cli-extension
11334cd55806bef0b99c3bee5a438eed71e44037
azure-devops/azext_devops/devops_sdk/v5_0/feed/feed_client.py
python
FeedClient.get_recycle_bin_package_versions
(self, feed_id, package_id, include_urls=None)
return self._deserialize('[RecycleBinPackageVersion]', self._unwrap_collection(response))
GetRecycleBinPackageVersions. [Preview API] Get a list of package versions within the recycle bin. :param str feed_id: Name or Id of the feed. :param str package_id: The package Id (GUID Id, not the package name). :param bool include_urls: True to return REST Urls with the response. Default is True. :rtype: [RecycleBinPackageVersion]
GetRecycleBinPackageVersions. [Preview API] Get a list of package versions within the recycle bin. :param str feed_id: Name or Id of the feed. :param str package_id: The package Id (GUID Id, not the package name). :param bool include_urls: True to return REST Urls with the response. Default is True. :rtype: [RecycleBinPackageVersion]
[ "GetRecycleBinPackageVersions", ".", "[", "Preview", "API", "]", "Get", "a", "list", "of", "package", "versions", "within", "the", "recycle", "bin", ".", ":", "param", "str", "feed_id", ":", "Name", "or", "Id", "of", "the", "feed", ".", ":", "param", "st...
def get_recycle_bin_package_versions(self, feed_id, package_id, include_urls=None): """GetRecycleBinPackageVersions. [Preview API] Get a list of package versions within the recycle bin. :param str feed_id: Name or Id of the feed. :param str package_id: The package Id (GUID Id, not the package name). :param bool include_urls: True to return REST Urls with the response. Default is True. :rtype: [RecycleBinPackageVersion] """ route_values = {} if feed_id is not None: route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str') if package_id is not None: route_values['packageId'] = self._serialize.url('package_id', package_id, 'str') query_parameters = {} if include_urls is not None: query_parameters['includeUrls'] = self._serialize.query('include_urls', include_urls, 'bool') response = self._send(http_method='GET', location_id='aceb4be7-8737-4820-834c-4c549e10fdc7', version='5.0-preview.1', route_values=route_values, query_parameters=query_parameters) return self._deserialize('[RecycleBinPackageVersion]', self._unwrap_collection(response))
[ "def", "get_recycle_bin_package_versions", "(", "self", ",", "feed_id", ",", "package_id", ",", "include_urls", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "feed_id", "is", "not", "None", ":", "route_values", "[", "'feedId'", "]", "=", "self"...
https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/devops_sdk/v5_0/feed/feed_client.py#L456-L477
PythonCharmers/python-future
80523f383fbba1c6de0551e19d0277e73e69573c
src/future/backports/email/_header_value_parser.py
python
_validate_xtext
(xtext)
If input token contains ASCII non-printables, register a defect.
If input token contains ASCII non-printables, register a defect.
[ "If", "input", "token", "contains", "ASCII", "non", "-", "printables", "register", "a", "defect", "." ]
def _validate_xtext(xtext): """If input token contains ASCII non-printables, register a defect.""" non_printables = _non_printable_finder(xtext) if non_printables: xtext.defects.append(errors.NonPrintableDefect(non_printables)) if utils._has_surrogates(xtext): xtext.defects.append(errors.UndecodableBytesDefect( "Non-ASCII characters found in header token"))
[ "def", "_validate_xtext", "(", "xtext", ")", ":", "non_printables", "=", "_non_printable_finder", "(", "xtext", ")", "if", "non_printables", ":", "xtext", ".", "defects", ".", "append", "(", "errors", ".", "NonPrintableDefect", "(", "non_printables", ")", ")", ...
https://github.com/PythonCharmers/python-future/blob/80523f383fbba1c6de0551e19d0277e73e69573c/src/future/backports/email/_header_value_parser.py#L1359-L1367
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/plugins/attack/db/sqlmap/thirdparty/xdot/xdot.py
python
Lexer.__init__
(self, buf = None, pos = 0, filename = None, fp = None)
[]
def __init__(self, buf = None, pos = 0, filename = None, fp = None): if fp is not None: try: fileno = fp.fileno() length = os.path.getsize(fp.name) import mmap except: # read whole file into memory buf = fp.read() pos = 0 else: # map the whole file into memory if length: # length must not be zero buf = mmap.mmap(fileno, length, access = mmap.ACCESS_READ) pos = os.lseek(fileno, 0, 1) else: buf = '' pos = 0 if filename is None: try: filename = fp.name except AttributeError: filename = None self.buf = buf self.pos = pos self.line = 1 self.col = 1 self.filename = filename
[ "def", "__init__", "(", "self", ",", "buf", "=", "None", ",", "pos", "=", "0", ",", "filename", "=", "None", ",", "fp", "=", "None", ")", ":", "if", "fp", "is", "not", "None", ":", "try", ":", "fileno", "=", "fp", ".", "fileno", "(", ")", "le...
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/plugins/attack/db/sqlmap/thirdparty/xdot/xdot.py#L819-L849
markokr/rarfile
55fe778b5207ebba48b8158d2c25d9d536ec89de
rarfile.py
python
RarExtFile._read
(self, cnt)
Actual read that gets sanitized cnt.
Actual read that gets sanitized cnt.
[ "Actual", "read", "that", "gets", "sanitized", "cnt", "." ]
def _read(self, cnt): """Actual read that gets sanitized cnt.""" raise NotImplementedError("_read")
[ "def", "_read", "(", "self", ",", "cnt", ")", ":", "raise", "NotImplementedError", "(", "\"_read\"", ")" ]
https://github.com/markokr/rarfile/blob/55fe778b5207ebba48b8158d2c25d9d536ec89de/rarfile.py#L2245-L2247
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idc.py
python
RunTo
(ea)
return idaapi.run_to(ea)
Execute the process until the given address is reached. If no process is active, a new process is started. See the important note to the StepInto() function @return: success
Execute the process until the given address is reached. If no process is active, a new process is started. See the important note to the StepInto() function
[ "Execute", "the", "process", "until", "the", "given", "address", "is", "reached", ".", "If", "no", "process", "is", "active", "a", "new", "process", "is", "started", ".", "See", "the", "important", "note", "to", "the", "StepInto", "()", "function" ]
def RunTo(ea): """ Execute the process until the given address is reached. If no process is active, a new process is started. See the important note to the StepInto() function @return: success """ return idaapi.run_to(ea)
[ "def", "RunTo", "(", "ea", ")", ":", "return", "idaapi", ".", "run_to", "(", "ea", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idc.py#L7379-L7387
djblets/djblets
0496e1ec49e43d43d776768c9fc5b6f8af56ec2c
djblets/template/caches.py
python
clear_template_caches
()
Clear the templates caches. This clears any caches for template parse trees and related state, forcing templates to be re-parsed and re-rendered.
Clear the templates caches.
[ "Clear", "the", "templates", "caches", "." ]
def clear_template_caches(): """Clear the templates caches. This clears any caches for template parse trees and related state, forcing templates to be re-parsed and re-rendered. """ template_loaders = [] for engine in engines.all(): template_loaders += engine.engine.template_loaders for template_loader in template_loaders: template_loader.reset()
[ "def", "clear_template_caches", "(", ")", ":", "template_loaders", "=", "[", "]", "for", "engine", "in", "engines", ".", "all", "(", ")", ":", "template_loaders", "+=", "engine", ".", "engine", ".", "template_loaders", "for", "template_loader", "in", "template...
https://github.com/djblets/djblets/blob/0496e1ec49e43d43d776768c9fc5b6f8af56ec2c/djblets/template/caches.py#L19-L31
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_oa_openshift/library/oc_objectvalidator.py
python
Utils.exists
(results, _name)
return False
Check to see if the results include the name
Check to see if the results include the name
[ "Check", "to", "see", "if", "the", "results", "include", "the", "name" ]
def exists(results, _name): ''' Check to see if the results include the name ''' if not results: return False if Utils.find_result(results, _name): return True return False
[ "def", "exists", "(", "results", ",", "_name", ")", ":", "if", "not", "results", ":", "return", "False", "if", "Utils", ".", "find_result", "(", "results", ",", "_name", ")", ":", "return", "True", "return", "False" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_oa_openshift/library/oc_objectvalidator.py#L1190-L1198
mpatacchiola/dissecting-reinforcement-learning
38660b0a0d5aed077a46acb4bcb2013565304d9c
environments/mountain_car.py
python
MountainCar.step
(self, action)
return [position_t1, velocity_t1], reward, done
Perform one step in the environment following the action. @param action: an integer representing one of three actions [0, 1, 2] where 0=move_left, 1=do_not_move, 2=move_right @return: (postion_t1, velocity_t1), reward, done where reward is always negative but when the goal is reached done is True when the goal is reached
Perform one step in the environment following the action.
[ "Perform", "one", "step", "in", "the", "environment", "following", "the", "action", "." ]
def step(self, action): """Perform one step in the environment following the action. @param action: an integer representing one of three actions [0, 1, 2] where 0=move_left, 1=do_not_move, 2=move_right @return: (postion_t1, velocity_t1), reward, done where reward is always negative but when the goal is reached done is True when the goal is reached """ if(action >= 3): raise ValueError("[MOUNTAIN CAR][ERROR] The action value " + str(action) + " is out of range.") done = False reward = -0.01 action_list = [-0.2, 0, +0.2] action_t = action_list[action] velocity_t1 = self.velocity_t + \ (-self.gravity * self.mass * np.cos(3*self.position_t) + (action_t/self.mass) - (self.friction*self.velocity_t)) * self.delta_t position_t1 = self.position_t + (velocity_t1 * self.delta_t) # Check the limit condition (car outside frame) if position_t1 < -1.2: position_t1 = -1.2 velocity_t1 = 0 # Assign the new position and velocity self.position_t = position_t1 self.velocity_t= velocity_t1 self.position_list.append(position_t1) # Reward and done when the car reaches the goal if position_t1 >= 0.5: reward = +1.0 done = True # Return state_t1, reward, done return [position_t1, velocity_t1], reward, done
[ "def", "step", "(", "self", ",", "action", ")", ":", "if", "(", "action", ">=", "3", ")", ":", "raise", "ValueError", "(", "\"[MOUNTAIN CAR][ERROR] The action value \"", "+", "str", "(", "action", ")", "+", "\" is out of range.\"", ")", "done", "=", "False",...
https://github.com/mpatacchiola/dissecting-reinforcement-learning/blob/38660b0a0d5aed077a46acb4bcb2013565304d9c/environments/mountain_car.py#L69-L103
qiufengyuyi/sequence_tagging
ad6b3299ebbe32837f3d6e20c2c9190d6a8c934a
bert/modeling.py
python
BertModel.get_embedding_output
(self)
return self.embedding_output
Gets output of the embedding lookup (i.e., input to the transformer). Returns: float Tensor of shape [batch_size, seq_length, hidden_size] corresponding to the output of the embedding layer, after summing the word embeddings with the positional embeddings and the token type embeddings, then performing layer normalization. This is the input to the transformer.
Gets output of the embedding lookup (i.e., input to the transformer).
[ "Gets", "output", "of", "the", "embedding", "lookup", "(", "i", ".", "e", ".", "input", "to", "the", "transformer", ")", "." ]
def get_embedding_output(self): """Gets output of the embedding lookup (i.e., input to the transformer). Returns: float Tensor of shape [batch_size, seq_length, hidden_size] corresponding to the output of the embedding layer, after summing the word embeddings with the positional embeddings and the token type embeddings, then performing layer normalization. This is the input to the transformer. """ return self.embedding_output
[ "def", "get_embedding_output", "(", "self", ")", ":", "return", "self", ".", "embedding_output" ]
https://github.com/qiufengyuyi/sequence_tagging/blob/ad6b3299ebbe32837f3d6e20c2c9190d6a8c934a/bert/modeling.py#L268-L277
dhconnelly/paip-python
e6784004bea1d16c90a4ca75c798ae31e6ab698a
paip/othello.py
python
alphabeta
(player, board, alpha, beta, depth, evaluate)
return alpha, best_move
Find the best legal move for player, searching to the specified depth. Like minimax, but uses the bounds alpha and beta to prune branches.
Find the best legal move for player, searching to the specified depth. Like minimax, but uses the bounds alpha and beta to prune branches.
[ "Find", "the", "best", "legal", "move", "for", "player", "searching", "to", "the", "specified", "depth", ".", "Like", "minimax", "but", "uses", "the", "bounds", "alpha", "and", "beta", "to", "prune", "branches", "." ]
def alphabeta(player, board, alpha, beta, depth, evaluate): """ Find the best legal move for player, searching to the specified depth. Like minimax, but uses the bounds alpha and beta to prune branches. """ if depth == 0: return evaluate(player, board), None def value(board, alpha, beta): # Like in `minimax`, the value of a board is the opposite of its value # to the opponent. We pass in `-beta` and `-alpha` as the alpha and # beta values, respectively, for the opponent, since `alpha` represents # the best score we know we can achieve and is therefore the worst score # achievable by the opponent. Similarly, `beta` is the worst score that # our opponent can hold us to, so it is the best score that they can # achieve. return -alphabeta(opponent(player), board, -beta, -alpha, depth-1, evaluate)[0] moves = legal_moves(player, board) if not moves: if not any_legal_move(opponent(player), board): return final_value(player, board), None return value(board, alpha, beta), None best_move = moves[0] for move in moves: if alpha >= beta: # If one of the legal moves leads to a better score than beta, then # the opponent will avoid this branch, so we can quit looking. break val = value(make_move(move, player, list(board)), alpha, beta) if val > alpha: # If one of the moves leads to a better score than the current best # achievable score, then replace it with this one. alpha = val best_move = move return alpha, best_move
[ "def", "alphabeta", "(", "player", ",", "board", ",", "alpha", ",", "beta", ",", "depth", ",", "evaluate", ")", ":", "if", "depth", "==", "0", ":", "return", "evaluate", "(", "player", ",", "board", ")", ",", "None", "def", "value", "(", "board", "...
https://github.com/dhconnelly/paip-python/blob/e6784004bea1d16c90a4ca75c798ae31e6ab698a/paip/othello.py#L405-L441
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_adm_router.py
python
Router.serviceaccount
(self)
return self._serviceaccount
property for serviceaccount
property for serviceaccount
[ "property", "for", "serviceaccount" ]
def serviceaccount(self): ''' property for serviceaccount ''' return self._serviceaccount
[ "def", "serviceaccount", "(", "self", ")", ":", "return", "self", ".", "_serviceaccount" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_adm_router.py#L2773-L2775
ctxis/CAPE
dae9fa6a254ecdbabeb7eb0d2389fa63722c1e82
analyzer/windows/analyzer.py
python
remove_pid
(pid)
Remove a process to process list.
Remove a process to process list.
[ "Remove", "a", "process", "to", "process", "list", "." ]
def remove_pid(pid): """Remove a process to process list.""" if isinstance(pid, (int, long, str)): log.info("Process with pid %s has terminated", pid) PROCESS_LIST.remove(int(pid)) del_pid_from_aux_modules(int(pid))
[ "def", "remove_pid", "(", "pid", ")", ":", "if", "isinstance", "(", "pid", ",", "(", "int", ",", "long", ",", "str", ")", ")", ":", "log", ".", "info", "(", "\"Process with pid %s has terminated\"", ",", "pid", ")", "PROCESS_LIST", ".", "remove", "(", ...
https://github.com/ctxis/CAPE/blob/dae9fa6a254ecdbabeb7eb0d2389fa63722c1e82/analyzer/windows/analyzer.py#L133-L138
ctxis/canape
5f0e03424577296bcc60c2008a60a98ec5307e4b
CANAPE.Scripting/Lib/urllib.py
python
getproxies_environment
()
return proxies
Return a dictionary of scheme -> proxy server URL mappings. Scan the environment for variables named <scheme>_proxy; this seems to be the standard convention. If you need a different way, you can pass a proxies dictionary to the [Fancy]URLopener constructor.
Return a dictionary of scheme -> proxy server URL mappings.
[ "Return", "a", "dictionary", "of", "scheme", "-", ">", "proxy", "server", "URL", "mappings", "." ]
def getproxies_environment(): """Return a dictionary of scheme -> proxy server URL mappings. Scan the environment for variables named <scheme>_proxy; this seems to be the standard convention. If you need a different way, you can pass a proxies dictionary to the [Fancy]URLopener constructor. """ proxies = {} for name, value in os.environ.items(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value return proxies
[ "def", "getproxies_environment", "(", ")", ":", "proxies", "=", "{", "}", "for", "name", ",", "value", "in", "os", ".", "environ", ".", "items", "(", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "if", "value", "and", "name", "[", "-", "...
https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/urllib.py#L1323-L1337
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/chat/v2/credential.py
python
CredentialInstance.date_updated
(self)
return self._properties['date_updated']
:returns: The ISO 8601 date and time in GMT when the resource was last updated :rtype: datetime
:returns: The ISO 8601 date and time in GMT when the resource was last updated :rtype: datetime
[ ":", "returns", ":", "The", "ISO", "8601", "date", "and", "time", "in", "GMT", "when", "the", "resource", "was", "last", "updated", ":", "rtype", ":", "datetime" ]
def date_updated(self): """ :returns: The ISO 8601 date and time in GMT when the resource was last updated :rtype: datetime """ return self._properties['date_updated']
[ "def", "date_updated", "(", "self", ")", ":", "return", "self", ".", "_properties", "[", "'date_updated'", "]" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/chat/v2/credential.py#L384-L389
django/django
0a17666045de6739ae1c2ac695041823d5f827f7
django/template/defaultfilters.py
python
capfirst
(value)
return value and value[0].upper() + value[1:]
Capitalize the first character of the value.
Capitalize the first character of the value.
[ "Capitalize", "the", "first", "character", "of", "the", "value", "." ]
def capfirst(value): """Capitalize the first character of the value.""" return value and value[0].upper() + value[1:]
[ "def", "capfirst", "(", "value", ")", ":", "return", "value", "and", "value", "[", "0", "]", ".", "upper", "(", ")", "+", "value", "[", "1", ":", "]" ]
https://github.com/django/django/blob/0a17666045de6739ae1c2ac695041823d5f827f7/django/template/defaultfilters.py#L69-L71
trezor/trezor-core
18c3a6a5bd45923380312b064be96155f5a7377d
src/apps/monero/xmr/key_image.py
python
_export_key_image
( creds, subaddresses, pkey, tx_pub_key, additional_tx_pub_keys, out_idx, test=True )
return ki, sig
Generates key image for the TXO + signature for the key image
Generates key image for the TXO + signature for the key image
[ "Generates", "key", "image", "for", "the", "TXO", "+", "signature", "for", "the", "key", "image" ]
def _export_key_image( creds, subaddresses, pkey, tx_pub_key, additional_tx_pub_keys, out_idx, test=True ): """ Generates key image for the TXO + signature for the key image """ r = monero.generate_tx_spend_and_key_image_and_derivation( creds, subaddresses, pkey, tx_pub_key, additional_tx_pub_keys, out_idx ) xi, ki, recv_derivation = r[:3] phash = crypto.encodepoint(ki) sig = generate_ring_signature(phash, ki, [pkey], xi, 0, test) return ki, sig
[ "def", "_export_key_image", "(", "creds", ",", "subaddresses", ",", "pkey", ",", "tx_pub_key", ",", "additional_tx_pub_keys", ",", "out_idx", ",", "test", "=", "True", ")", ":", "r", "=", "monero", ".", "generate_tx_spend_and_key_image_and_derivation", "(", "creds...
https://github.com/trezor/trezor-core/blob/18c3a6a5bd45923380312b064be96155f5a7377d/src/apps/monero/xmr/key_image.py#L31-L45
mchristopher/PokemonGo-DesktopMap
ec37575f2776ee7d64456e2a1f6b6b78830b4fe0
app/pylibs/osx64/gevent/hub.py
python
iwait
(objects, timeout=None, count=None)
Iteratively yield *objects* as they are ready, until all (or *count*) are ready or *timeout* expired. :param objects: A sequence (supporting :func:`len`) containing objects implementing the wait protocol (rawlink() and unlink()). :keyword int count: If not `None`, then a number specifying the maximum number of objects to wait for. If ``None`` (the default), all objects are waited for. :keyword float timeout: If given, specifies a maximum number of seconds to wait. If the timeout expires before the desired waited-for objects are available, then this method returns immediately. .. seealso:: :func:`wait` .. versionchanged:: 1.1a1 Add the *count* parameter. .. versionchanged:: 1.1a2 No longer raise :exc:`LoopExit` if our caller switches greenlets in between items yielded by this function.
Iteratively yield *objects* as they are ready, until all (or *count*) are ready or *timeout* expired.
[ "Iteratively", "yield", "*", "objects", "*", "as", "they", "are", "ready", "until", "all", "(", "or", "*", "count", "*", ")", "are", "ready", "or", "*", "timeout", "*", "expired", "." ]
def iwait(objects, timeout=None, count=None): """ Iteratively yield *objects* as they are ready, until all (or *count*) are ready or *timeout* expired. :param objects: A sequence (supporting :func:`len`) containing objects implementing the wait protocol (rawlink() and unlink()). :keyword int count: If not `None`, then a number specifying the maximum number of objects to wait for. If ``None`` (the default), all objects are waited for. :keyword float timeout: If given, specifies a maximum number of seconds to wait. If the timeout expires before the desired waited-for objects are available, then this method returns immediately. .. seealso:: :func:`wait` .. versionchanged:: 1.1a1 Add the *count* parameter. .. versionchanged:: 1.1a2 No longer raise :exc:`LoopExit` if our caller switches greenlets in between items yielded by this function. """ # QQQ would be nice to support iterable here that can be generated slowly (why?) if objects is None: yield get_hub().join(timeout=timeout) return count = len(objects) if count is None else min(count, len(objects)) waiter = _MultipleWaiter() switch = waiter.switch if timeout is not None: timer = get_hub().loop.timer(timeout, priority=-1) timer.start(switch, _NONE) try: for obj in objects: obj.rawlink(switch) for _ in xrange(count): item = waiter.get() waiter.clear() if item is _NONE: return yield item finally: if timeout is not None: timer.stop() for obj in objects: unlink = getattr(obj, 'unlink', None) if unlink: try: unlink(switch) except: traceback.print_exc()
[ "def", "iwait", "(", "objects", ",", "timeout", "=", "None", ",", "count", "=", "None", ")", ":", "# QQQ would be nice to support iterable here that can be generated slowly (why?)", "if", "objects", "is", "None", ":", "yield", "get_hub", "(", ")", ".", "join", "("...
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pylibs/osx64/gevent/hub.py#L924-L978
jazzband/django-ddp
1e1954b06fe140346acea43582515991685e4e01
dddp/migrations/__init__.py
python
set_default_forwards
(app_name, operation, apps, schema_editor)
Set default value for AleaIdField.
Set default value for AleaIdField.
[ "Set", "default", "value", "for", "AleaIdField", "." ]
def set_default_forwards(app_name, operation, apps, schema_editor): """Set default value for AleaIdField.""" model = apps.get_model(app_name, operation.model_name) for obj_pk in model.objects.values_list('pk', flat=True): model.objects.filter(pk=obj_pk).update(**{ operation.name: get_meteor_id(model, obj_pk), })
[ "def", "set_default_forwards", "(", "app_name", ",", "operation", ",", "apps", ",", "schema_editor", ")", ":", "model", "=", "apps", ".", "get_model", "(", "app_name", ",", "operation", ".", "model_name", ")", "for", "obj_pk", "in", "model", ".", "objects", ...
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/migrations/__init__.py#L43-L49
spartan-array/spartan
fdcf059ce7e48688648d793d632dc5961f4e72b5
spartan/examples/ssvd/ssvd.py
python
svd
(A, k=None)
return U, S, V.T
Stochastic SVD. Parameters ---------- A : spartan matrix Array to compute the SVD on, of shape (M, N) k : int, optional Number of singular values and vectors to compute. The operations include matrix multiplication and QR decomposition. We parallelize both of them. Returns -------- U : Spartan array of shape (M, k) S : numpy array of shape (k,) V : numpy array of shape (k, k)
Stochastic SVD.
[ "Stochastic", "SVD", "." ]
def svd(A, k=None): """ Stochastic SVD. Parameters ---------- A : spartan matrix Array to compute the SVD on, of shape (M, N) k : int, optional Number of singular values and vectors to compute. The operations include matrix multiplication and QR decomposition. We parallelize both of them. Returns -------- U : Spartan array of shape (M, k) S : numpy array of shape (k,) V : numpy array of shape (k, k) """ if k is None: k = A.shape[1] Omega = expr.randn(A.shape[1], k) Y = expr.dot(A, Omega) Q, R = qr(Y) B = expr.dot(expr.transpose(Q), A) BTB = expr.dot(B, expr.transpose(B)).optimized().glom() S, U_ = np.linalg.eig(BTB) S = np.sqrt(S) # Sort by eigen values from large to small si = np.argsort(S)[::-1] S = S[si] U_ = U_[:, si] U = expr.dot(Q, U_).optimized().evaluate() V = np.dot(np.dot(expr.transpose(B).optimized().glom(), U_), np.diag(np.ones(S.shape[0]) / S)) return U, S, V.T
[ "def", "svd", "(", "A", ",", "k", "=", "None", ")", ":", "if", "k", "is", "None", ":", "k", "=", "A", ".", "shape", "[", "1", "]", "Omega", "=", "expr", ".", "randn", "(", "A", ".", "shape", "[", "1", "]", ",", "k", ")", "Y", "=", "expr...
https://github.com/spartan-array/spartan/blob/fdcf059ce7e48688648d793d632dc5961f4e72b5/spartan/examples/ssvd/ssvd.py#L7-L48
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/gdata/src/gdata/Crypto/Protocol/AllOrNothing.py
python
AllOrNothing.digest
(self, text)
return map(long_to_bytes, blocks)
digest(text:string) : [string] Perform the All-or-Nothing package transform on the given string. Output is a list of message blocks describing the transformed text, where each block is a string of bit length equal to the ciphermodule's block_size.
digest(text:string) : [string]
[ "digest", "(", "text", ":", "string", ")", ":", "[", "string", "]" ]
def digest(self, text): """digest(text:string) : [string] Perform the All-or-Nothing package transform on the given string. Output is a list of message blocks describing the transformed text, where each block is a string of bit length equal to the ciphermodule's block_size. """ # generate a random session key and K0, the key used to encrypt the # hash blocks. Rivest calls this a fixed, publically-known encryption # key, but says nothing about the security implications of this key or # how to choose it. key = self._inventkey(self.__key_size) K0 = self.__K0digit * self.__key_size # we need two cipher objects here, one that is used to encrypt the # message blocks and one that is used to encrypt the hashes. The # former uses the randomly generated key, while the latter uses the # well-known key. mcipher = self.__newcipher(key) hcipher = self.__newcipher(K0) # Pad the text so that its length is a multiple of the cipher's # block_size. Pad with trailing spaces, which will be eliminated in # the undigest() step. block_size = self.__ciphermodule.block_size padbytes = block_size - (len(text) % block_size) text = text + ' ' * padbytes # Run through the algorithm: # s: number of message blocks (size of text / block_size) # input sequence: m1, m2, ... ms # random key K' (`key' in the code) # Compute output sequence: m'1, m'2, ... m's' for s' = s + 1 # Let m'i = mi ^ E(K', i) for i = 1, 2, 3, ..., s # Let m's' = K' ^ h1 ^ h2 ^ ... hs # where hi = E(K0, m'i ^ i) for i = 1, 2, ... s # # The one complication I add is that the last message block is hard # coded to the number of padbytes added, so that these can be stripped # during the undigest() step s = len(text) / block_size blocks = [] hashes = [] for i in range(1, s+1): start = (i-1) * block_size end = start + block_size mi = text[start:end] assert len(mi) == block_size cipherblock = mcipher.encrypt(long_to_bytes(i, block_size)) mticki = bytes_to_long(mi) ^ bytes_to_long(cipherblock) blocks.append(mticki) # calculate the hash block for this block hi = hcipher.encrypt(long_to_bytes(mticki ^ i, block_size)) hashes.append(bytes_to_long(hi)) # Add the padbytes length as a message block i = i + 1 cipherblock = mcipher.encrypt(long_to_bytes(i, block_size)) mticki = padbytes ^ bytes_to_long(cipherblock) blocks.append(mticki) # calculate this block's hash hi = hcipher.encrypt(long_to_bytes(mticki ^ i, block_size)) hashes.append(bytes_to_long(hi)) # Now calculate the last message block of the sequence 1..s'. This # will contain the random session key XOR'd with all the hash blocks, # so that for undigest(), once all the hash blocks are calculated, the # session key can be trivially extracted. Calculating all the hash # blocks requires that all the message blocks be received, thus the # All-or-Nothing algorithm succeeds. mtick_stick = bytes_to_long(key) ^ reduce(operator.xor, hashes) blocks.append(mtick_stick) # we convert the blocks to strings since in Python, byte sequences are # always represented as strings. This is more consistent with the # model that encryption and hash algorithms always operate on strings. return map(long_to_bytes, blocks)
[ "def", "digest", "(", "self", ",", "text", ")", ":", "# generate a random session key and K0, the key used to encrypt the", "# hash blocks. Rivest calls this a fixed, publically-known encryption", "# key, but says nothing about the security implications of this key or", "# how to choose it.",...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/gdata/src/gdata/Crypto/Protocol/AllOrNothing.py#L63-L142
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/email/charset.py
python
Charset.encoded_header_len
(self, s)
Return the length of the encoded header string.
Return the length of the encoded header string.
[ "Return", "the", "length", "of", "the", "encoded", "header", "string", "." ]
def encoded_header_len(self, s): """Return the length of the encoded header string.""" cset = self.get_output_charset() # The len(s) of a 7bit encoding is len(s) if self.header_encoding == BASE64: return email.base64mime.base64_len(s) + len(cset) + MISC_LEN elif self.header_encoding == QP: return email.quoprimime.header_quopri_len(s) + len(cset) + MISC_LEN elif self.header_encoding == SHORTEST: lenb64 = email.base64mime.base64_len(s) lenqp = email.quoprimime.header_quopri_len(s) return min(lenb64, lenqp) + len(cset) + MISC_LEN else: return len(s)
[ "def", "encoded_header_len", "(", "self", ",", "s", ")", ":", "cset", "=", "self", ".", "get_output_charset", "(", ")", "# The len(s) of a 7bit encoding is len(s)", "if", "self", ".", "header_encoding", "==", "BASE64", ":", "return", "email", ".", "base64mime", ...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/email/charset.py#L332-L345
glutanimate/cloze-overlapper
9eabb6a9d2a6807595478647fd968e8e4bac86fc
src/cloze_overlapper/reviewer.py
python
newKeyHandler20
(reviewer, evt)
Bind mask reveal to a hotkey
Bind mask reveal to a hotkey
[ "Bind", "mask", "reveal", "to", "a", "hotkey" ]
def newKeyHandler20(reviewer, evt): """Bind mask reveal to a hotkey""" if (evt.key() == olc_keycode_reveal): onHintRevealHotkey(reviewer)
[ "def", "newKeyHandler20", "(", "reviewer", ",", "evt", ")", ":", "if", "(", "evt", ".", "key", "(", ")", "==", "olc_keycode_reveal", ")", ":", "onHintRevealHotkey", "(", "reviewer", ")" ]
https://github.com/glutanimate/cloze-overlapper/blob/9eabb6a9d2a6807595478647fd968e8e4bac86fc/src/cloze_overlapper/reviewer.py#L57-L60
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/inspect.py
python
BoundArguments.signature
(self)
return self._signature
[]
def signature(self): return self._signature
[ "def", "signature", "(", "self", ")", ":", "return", "self", ".", "_signature" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/inspect.py#L2239-L2240
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/models/pegasus/modeling_flax_pegasus.py
python
FlaxPegasusModule._get_encoder_module
(self)
return self.encoder
[]
def _get_encoder_module(self): return self.encoder
[ "def", "_get_encoder_module", "(", "self", ")", ":", "return", "self", ".", "encoder" ]
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/pegasus/modeling_flax_pegasus.py#L839-L840
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/groups/galois_group.py
python
_alg_key
(self, algorithm=None, recompute=False)
r""" Return a key for use in cached_method calls. If recompute is false, will cache using ``None`` as the key, so no recomputation will be done. If recompute is true, will cache by algorithm, yielding a recomputation for each different algorithm. EXAMPLES:: sage: from sage.groups.galois_group import _alg_key sage: R.<x> = ZZ[] sage: K.<a> = NumberField(x^3 + 2*x + 2) sage: G = K.galois_group() sage: _alg_key(G, algorithm="pari", recompute=True) 'pari'
r""" Return a key for use in cached_method calls.
[ "r", "Return", "a", "key", "for", "use", "in", "cached_method", "calls", "." ]
def _alg_key(self, algorithm=None, recompute=False): r""" Return a key for use in cached_method calls. If recompute is false, will cache using ``None`` as the key, so no recomputation will be done. If recompute is true, will cache by algorithm, yielding a recomputation for each different algorithm. EXAMPLES:: sage: from sage.groups.galois_group import _alg_key sage: R.<x> = ZZ[] sage: K.<a> = NumberField(x^3 + 2*x + 2) sage: G = K.galois_group() sage: _alg_key(G, algorithm="pari", recompute=True) 'pari' """ if recompute: algorithm = self._get_algorithm(algorithm) return algorithm
[ "def", "_alg_key", "(", "self", ",", "algorithm", "=", "None", ",", "recompute", "=", "False", ")", ":", "if", "recompute", ":", "algorithm", "=", "self", ".", "_get_algorithm", "(", "algorithm", ")", "return", "algorithm" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/groups/galois_group.py#L22-L41
datadesk/census-data-downloader
7922e3f99566a0af0afef629c682bd6c522ccaa6
census_data_downloader/__init__.py
python
download_everything
(*args, **kwargs)
Download all the data.
Download all the data.
[ "Download", "all", "the", "data", "." ]
def download_everything(*args, **kwargs): """ Download all the data. """ logger.debug("Downloading all datasets for all geographies") for klass in TABLE_LIST: obj = klass(*args, **kwargs) logger.debug(f"Downloading {klass.PROCESSED_TABLE_NAME} dataset") obj.download_everything()
[ "def", "download_everything", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "\"Downloading all datasets for all geographies\"", ")", "for", "klass", "in", "TABLE_LIST", ":", "obj", "=", "klass", "(", "*", "args", ",", "*",...
https://github.com/datadesk/census-data-downloader/blob/7922e3f99566a0af0afef629c682bd6c522ccaa6/census_data_downloader/__init__.py#L11-L19
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/tkinter/ttk.py
python
Treeview.insert
(self, parent, index, iid=None, **kw)
return res
Creates a new item and return the item identifier of the newly created item. parent is the item ID of the parent item, or the empty string to create a new top-level item. index is an integer, or the value end, specifying where in the list of parent's children to insert the new item. If index is less than or equal to zero, the new node is inserted at the beginning, if index is greater than or equal to the current number of children, it is inserted at the end. If iid is specified, it is used as the item identifier, iid must not already exist in the tree. Otherwise, a new unique identifier is generated.
Creates a new item and return the item identifier of the newly created item.
[ "Creates", "a", "new", "item", "and", "return", "the", "item", "identifier", "of", "the", "newly", "created", "item", "." ]
def insert(self, parent, index, iid=None, **kw): """Creates a new item and return the item identifier of the newly created item. parent is the item ID of the parent item, or the empty string to create a new top-level item. index is an integer, or the value end, specifying where in the list of parent's children to insert the new item. If index is less than or equal to zero, the new node is inserted at the beginning, if index is greater than or equal to the current number of children, it is inserted at the end. If iid is specified, it is used as the item identifier, iid must not already exist in the tree. Otherwise, a new unique identifier is generated.""" opts = _format_optdict(kw) if iid is not None: res = self.tk.call(self._w, "insert", parent, index, "-id", iid, *opts) else: res = self.tk.call(self._w, "insert", parent, index, *opts) return res
[ "def", "insert", "(", "self", ",", "parent", ",", "index", ",", "iid", "=", "None", ",", "*", "*", "kw", ")", ":", "opts", "=", "_format_optdict", "(", "kw", ")", "if", "iid", "is", "not", "None", ":", "res", "=", "self", ".", "tk", ".", "call"...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/tkinter/ttk.py#L1351-L1371
gawel/irc3
112e474c126f84b509c8262840d29eadcdd878ed
irc3/__init__.py
python
IrcBot.dcc
(self)
return self._dcc
return the :class:`~irc3.dcc.DCCManager`
return the :class:`~irc3.dcc.DCCManager`
[ "return", "the", ":", "class", ":", "~irc3", ".", "dcc", ".", "DCCManager" ]
def dcc(self): """return the :class:`~irc3.dcc.DCCManager`""" if self._dcc is None: self._dcc = DCCManager(self) return self._dcc
[ "def", "dcc", "(", "self", ")", ":", "if", "self", ".", "_dcc", "is", "None", ":", "self", ".", "_dcc", "=", "DCCManager", "(", "self", ")", "return", "self", ".", "_dcc" ]
https://github.com/gawel/irc3/blob/112e474c126f84b509c8262840d29eadcdd878ed/irc3/__init__.py#L370-L374
benoitc/gunicorn
76f8da24cbb992d168e01bda811452bcf3b8f5b3
gunicorn/arbiter.py
python
Arbiter.reexec
(self)
\ Relaunch the master and workers.
\ Relaunch the master and workers.
[ "\\", "Relaunch", "the", "master", "and", "workers", "." ]
def reexec(self): """\ Relaunch the master and workers. """ if self.reexec_pid != 0: self.log.warning("USR2 signal ignored. Child exists.") return if self.master_pid != 0: self.log.warning("USR2 signal ignored. Parent exists.") return master_pid = os.getpid() self.reexec_pid = os.fork() if self.reexec_pid != 0: return self.cfg.pre_exec(self) environ = self.cfg.env_orig.copy() environ['GUNICORN_PID'] = str(master_pid) if self.systemd: environ['LISTEN_PID'] = str(os.getpid()) environ['LISTEN_FDS'] = str(len(self.LISTENERS)) else: environ['GUNICORN_FD'] = ','.join( str(l.fileno()) for l in self.LISTENERS) os.chdir(self.START_CTX['cwd']) # exec the process using the original environment os.execvpe(self.START_CTX[0], self.START_CTX['args'], environ)
[ "def", "reexec", "(", "self", ")", ":", "if", "self", ".", "reexec_pid", "!=", "0", ":", "self", ".", "log", ".", "warning", "(", "\"USR2 signal ignored. Child exists.\"", ")", "return", "if", "self", ".", "master_pid", "!=", "0", ":", "self", ".", "log"...
https://github.com/benoitc/gunicorn/blob/76f8da24cbb992d168e01bda811452bcf3b8f5b3/gunicorn/arbiter.py#L397-L429
wwqgtxx/wwqLyParse
33136508e52821babd9294fdecffbdf02d73a6fc
wwqLyParse/lib/python-3.7.2-embed-win32/Crypto/Hash/HMAC.py
python
HMAC._pbkdf2_hmac_assist
(self, first_digest, iterations)
return result
Carry out the expensive inner loop for PBKDF2-HMAC
Carry out the expensive inner loop for PBKDF2-HMAC
[ "Carry", "out", "the", "expensive", "inner", "loop", "for", "PBKDF2", "-", "HMAC" ]
def _pbkdf2_hmac_assist(self, first_digest, iterations): """Carry out the expensive inner loop for PBKDF2-HMAC""" result = self._digestmod._pbkdf2_hmac_assist( self._inner, self._outer, first_digest, iterations) return result
[ "def", "_pbkdf2_hmac_assist", "(", "self", ",", "first_digest", ",", "iterations", ")", ":", "result", "=", "self", ".", "_digestmod", ".", "_pbkdf2_hmac_assist", "(", "self", ".", "_inner", ",", "self", ".", "_outer", ",", "first_digest", ",", "iterations", ...
https://github.com/wwqgtxx/wwqLyParse/blob/33136508e52821babd9294fdecffbdf02d73a6fc/wwqLyParse/lib/python-3.7.2-embed-win32/Crypto/Hash/HMAC.py#L105-L113
lfz/Guided-Denoise
8881ab768d16eaf87342da4ff7dc8271e183e205
Attackset/Iter2_v3_resv2_inresv2_random/nets/inception_v1.py
python
inception_v1_base
(inputs, final_endpoint='Mixed_5c', scope='InceptionV1')
Defines the Inception V1 base architecture. This architecture is defined in: Going deeper with convolutions Christian Szegedy, Wei Liu, Yangqing Jia, Pierre Sermanet, Scott Reed, Dragomir Anguelov, Dumitru Erhan, Vincent Vanhoucke, Andrew Rabinovich. http://arxiv.org/pdf/1409.4842v1.pdf. Args: inputs: a tensor of size [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3', 'MaxPool_3a_3x3', 'Mixed_3b', 'Mixed_3c', 'MaxPool_4a_3x3', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_4f', 'MaxPool_5a_2x2', 'Mixed_5b', 'Mixed_5c'] scope: Optional variable_scope. Returns: A dictionary from components of the network to the corresponding activation. Raises: ValueError: if final_endpoint is not set to one of the predefined values.
Defines the Inception V1 base architecture.
[ "Defines", "the", "Inception", "V1", "base", "architecture", "." ]
def inception_v1_base(inputs, final_endpoint='Mixed_5c', scope='InceptionV1'): """Defines the Inception V1 base architecture. This architecture is defined in: Going deeper with convolutions Christian Szegedy, Wei Liu, Yangqing Jia, Pierre Sermanet, Scott Reed, Dragomir Anguelov, Dumitru Erhan, Vincent Vanhoucke, Andrew Rabinovich. http://arxiv.org/pdf/1409.4842v1.pdf. Args: inputs: a tensor of size [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3', 'MaxPool_3a_3x3', 'Mixed_3b', 'Mixed_3c', 'MaxPool_4a_3x3', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_4f', 'MaxPool_5a_2x2', 'Mixed_5b', 'Mixed_5c'] scope: Optional variable_scope. Returns: A dictionary from components of the network to the corresponding activation. Raises: ValueError: if final_endpoint is not set to one of the predefined values. """ end_points = {} with tf.variable_scope(scope, 'InceptionV1', [inputs]): with slim.arg_scope( [slim.conv2d, slim.fully_connected], weights_initializer=trunc_normal(0.01)): with slim.arg_scope([slim.conv2d, slim.max_pool2d], stride=1, padding='SAME'): end_point = 'Conv2d_1a_7x7' net = slim.conv2d(inputs, 64, [7, 7], stride=2, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'MaxPool_2a_3x3' net = slim.max_pool2d(net, [3, 3], stride=2, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Conv2d_2b_1x1' net = slim.conv2d(net, 64, [1, 1], scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Conv2d_2c_3x3' net = slim.conv2d(net, 192, [3, 3], scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'MaxPool_3a_3x3' net = slim.max_pool2d(net, [3, 3], stride=2, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_3b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 64, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 96, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 128, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, 16, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 32, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 32, [1, 1], scope='Conv2d_0b_1x1') net = tf.concat( axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_3c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 128, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 128, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 192, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, 32, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 96, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 64, [1, 1], scope='Conv2d_0b_1x1') net = tf.concat( axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'MaxPool_4a_3x3' net = slim.max_pool2d(net, [3, 3], stride=2, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_4b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 192, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 96, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 208, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, 16, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 48, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 64, [1, 1], scope='Conv2d_0b_1x1') net = tf.concat( axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_4c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 160, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 112, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 224, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, 24, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 64, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 64, [1, 1], scope='Conv2d_0b_1x1') net = tf.concat( axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_4d' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 128, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 128, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 256, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, 24, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 64, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 64, [1, 1], scope='Conv2d_0b_1x1') net = tf.concat( axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_4e' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 112, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 144, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 288, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, 32, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 64, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 64, [1, 1], scope='Conv2d_0b_1x1') net = tf.concat( axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_4f' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 256, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 160, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 320, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, 32, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 128, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 128, [1, 1], scope='Conv2d_0b_1x1') net = tf.concat( axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'MaxPool_5a_2x2' net = slim.max_pool2d(net, [2, 2], stride=2, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_5b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 256, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 160, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 320, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, 32, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 128, [3, 3], scope='Conv2d_0a_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 128, [1, 1], scope='Conv2d_0b_1x1') net = tf.concat( axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_5c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 384, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 192, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 384, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, 48, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 128, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 128, [1, 1], scope='Conv2d_0b_1x1') net = tf.concat( axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if final_endpoint == end_point: return net, end_points raise ValueError('Unknown final endpoint %s' % final_endpoint)
[ "def", "inception_v1_base", "(", "inputs", ",", "final_endpoint", "=", "'Mixed_5c'", ",", "scope", "=", "'InceptionV1'", ")", ":", "end_points", "=", "{", "}", "with", "tf", ".", "variable_scope", "(", "scope", ",", "'InceptionV1'", ",", "[", "inputs", "]", ...
https://github.com/lfz/Guided-Denoise/blob/8881ab768d16eaf87342da4ff7dc8271e183e205/Attackset/Iter2_v3_resv2_inresv2_random/nets/inception_v1.py#L29-L254
joelgrus/data-science-from-scratch
d5d0f117f41b3ccab3b07f1ee1fa21cfcf69afa1
scratch/nlp.py
python
fix_unicode
(text: str)
return text.replace(u"\u2019", "'")
[]
def fix_unicode(text: str) -> str: return text.replace(u"\u2019", "'")
[ "def", "fix_unicode", "(", "text", ":", "str", ")", "->", "str", ":", "return", "text", ".", "replace", "(", "u\"\\u2019\"", ",", "\"'\"", ")" ]
https://github.com/joelgrus/data-science-from-scratch/blob/d5d0f117f41b3ccab3b07f1ee1fa21cfcf69afa1/scratch/nlp.py#L16-L17
GDQuest/krita-batch-exporter
d1f51af32f7fd026aa82e040710594516bbd9540
batch_exporter/Utils/Tree.py
python
iterLevel
(node, maxDepth=-1)
return go([node])
Visit nodes in level order. Parameters ---------- node: Node maxDepth: int Maximum depth level at which traversal will stop. Returns ------- out: iter(Node)
Visit nodes in level order.
[ "Visit", "nodes", "in", "level", "order", "." ]
def iterLevel(node, maxDepth=-1): """ Visit nodes in level order. Parameters ---------- node: Node maxDepth: int Maximum depth level at which traversal will stop. Returns ------- out: iter(Node) """ def go(nodes, depth=0): yield from nodes it = map(lambda n: go(n.children, depth + 1), nodes) it = chain(*it) if maxDepth == -1 or depth < maxDepth else iter() yield from it return go([node])
[ "def", "iterLevel", "(", "node", ",", "maxDepth", "=", "-", "1", ")", ":", "def", "go", "(", "nodes", ",", "depth", "=", "0", ")", ":", "yield", "from", "nodes", "it", "=", "map", "(", "lambda", "n", ":", "go", "(", "n", ".", "children", ",", ...
https://github.com/GDQuest/krita-batch-exporter/blob/d1f51af32f7fd026aa82e040710594516bbd9540/batch_exporter/Utils/Tree.py#L34-L55
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/rum/v20210622/models.py
python
DescribeDataLogUrlStatisticsRequest.__init__
(self)
r""" :param StartTime: 开始时间 :type StartTime: int :param Type: "analysis", "compare", "samp", "version", "ext3","nettype", "platform","isp","region","device","browser","ext1","ext2" :type Type: str :param EndTime: 结束时间 :type EndTime: int :param ID: 项目ID :type ID: int :param ExtSecond: 自定义2 :type ExtSecond: str :param Engine: 浏览器引擎 :type Engine: str :param Isp: 运营商 :type Isp: str :param From: 来源页面 :type From: str :param Level: 日志等级 :type Level: str :param Brand: 品牌 :type Brand: str :param Area: 地区 :type Area: str :param VersionNum: 版本 :type VersionNum: str :param Platform: 平台 :type Platform: str :param ExtThird: 自定义3 :type ExtThird: str :param ExtFirst: 自定义1 :type ExtFirst: str :param NetType: 网络类型 :type NetType: str :param Device: 机型 :type Device: str :param IsAbroad: 是否海外 :type IsAbroad: str :param Os: 操作系统 :type Os: str :param Browser: 浏览器 :type Browser: str :param Env: 环境区分 :type Env: str
r""" :param StartTime: 开始时间 :type StartTime: int :param Type: "analysis", "compare", "samp", "version", "ext3","nettype", "platform","isp","region","device","browser","ext1","ext2" :type Type: str :param EndTime: 结束时间 :type EndTime: int :param ID: 项目ID :type ID: int :param ExtSecond: 自定义2 :type ExtSecond: str :param Engine: 浏览器引擎 :type Engine: str :param Isp: 运营商 :type Isp: str :param From: 来源页面 :type From: str :param Level: 日志等级 :type Level: str :param Brand: 品牌 :type Brand: str :param Area: 地区 :type Area: str :param VersionNum: 版本 :type VersionNum: str :param Platform: 平台 :type Platform: str :param ExtThird: 自定义3 :type ExtThird: str :param ExtFirst: 自定义1 :type ExtFirst: str :param NetType: 网络类型 :type NetType: str :param Device: 机型 :type Device: str :param IsAbroad: 是否海外 :type IsAbroad: str :param Os: 操作系统 :type Os: str :param Browser: 浏览器 :type Browser: str :param Env: 环境区分 :type Env: str
[ "r", ":", "param", "StartTime", ":", "开始时间", ":", "type", "StartTime", ":", "int", ":", "param", "Type", ":", "analysis", "compare", "samp", "version", "ext3", "nettype", "platform", "isp", "region", "device", "browser", "ext1", "ext2", ":", "type", "Type"...
def __init__(self): r""" :param StartTime: 开始时间 :type StartTime: int :param Type: "analysis", "compare", "samp", "version", "ext3","nettype", "platform","isp","region","device","browser","ext1","ext2" :type Type: str :param EndTime: 结束时间 :type EndTime: int :param ID: 项目ID :type ID: int :param ExtSecond: 自定义2 :type ExtSecond: str :param Engine: 浏览器引擎 :type Engine: str :param Isp: 运营商 :type Isp: str :param From: 来源页面 :type From: str :param Level: 日志等级 :type Level: str :param Brand: 品牌 :type Brand: str :param Area: 地区 :type Area: str :param VersionNum: 版本 :type VersionNum: str :param Platform: 平台 :type Platform: str :param ExtThird: 自定义3 :type ExtThird: str :param ExtFirst: 自定义1 :type ExtFirst: str :param NetType: 网络类型 :type NetType: str :param Device: 机型 :type Device: str :param IsAbroad: 是否海外 :type IsAbroad: str :param Os: 操作系统 :type Os: str :param Browser: 浏览器 :type Browser: str :param Env: 环境区分 :type Env: str """ self.StartTime = None self.Type = None self.EndTime = None self.ID = None self.ExtSecond = None self.Engine = None self.Isp = None self.From = None self.Level = None self.Brand = None self.Area = None self.VersionNum = None self.Platform = None self.ExtThird = None self.ExtFirst = None self.NetType = None self.Device = None self.IsAbroad = None self.Os = None self.Browser = None self.Env = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "StartTime", "=", "None", "self", ".", "Type", "=", "None", "self", ".", "EndTime", "=", "None", "self", ".", "ID", "=", "None", "self", ".", "ExtSecond", "=", "None", "self", ".", "Engine", "=...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/rum/v20210622/models.py#L232-L297
tobspr/RenderPipeline
d8c38c0406a63298f4801782a8e44e9c1e467acf
rplibs/progressbar/__init__.py
python
ProgressBar._env_size
(self)
return int(os.environ.get('COLUMNS', self._DEFAULT_TERMSIZE)) - 1
Tries to find the term_width from the environment.
Tries to find the term_width from the environment.
[ "Tries", "to", "find", "the", "term_width", "from", "the", "environment", "." ]
def _env_size(self): 'Tries to find the term_width from the environment.' return int(os.environ.get('COLUMNS', self._DEFAULT_TERMSIZE)) - 1
[ "def", "_env_size", "(", "self", ")", ":", "return", "int", "(", "os", ".", "environ", ".", "get", "(", "'COLUMNS'", ",", "self", ".", "_DEFAULT_TERMSIZE", ")", ")", "-", "1" ]
https://github.com/tobspr/RenderPipeline/blob/d8c38c0406a63298f4801782a8e44e9c1e467acf/rplibs/progressbar/__init__.py#L193-L196
j91321/rext
5f0f6266eec445b00ef4aeba3cfffbca022e7f43
modules/misc/adb/alice_cpe_backdoor.py
python
Misc.do_set
(self, e)
[]
def do_set(self, e): args = e.split(' ') if args[0] == "mac": if validate_mac(args[1]): self.mac = args[1] print_info("MAC set to: " + self.mac + " " + lookup_mac(self.mac)) else: print_error("provide valid MAC address")
[ "def", "do_set", "(", "self", ",", "e", ")", ":", "args", "=", "e", ".", "split", "(", "' '", ")", "if", "args", "[", "0", "]", "==", "\"mac\"", ":", "if", "validate_mac", "(", "args", "[", "1", "]", ")", ":", "self", ".", "mac", "=", "args",...
https://github.com/j91321/rext/blob/5f0f6266eec445b00ef4aeba3cfffbca022e7f43/modules/misc/adb/alice_cpe_backdoor.py#L58-L65
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/distutils/command/build_ext.py
python
build_ext.get_ext_fullpath
(self, ext_name)
return os.path.join(package_dir, filename)
Returns the path of the filename for a given extension. The file is located in `build_lib` or directly in the package (inplace option).
Returns the path of the filename for a given extension.
[ "Returns", "the", "path", "of", "the", "filename", "for", "a", "given", "extension", "." ]
def get_ext_fullpath(self, ext_name): """Returns the path of the filename for a given extension. The file is located in `build_lib` or directly in the package (inplace option). """ fullname = self.get_ext_fullname(ext_name) modpath = fullname.split('.') filename = self.get_ext_filename(modpath[-1]) if not self.inplace: # no further work needed # returning : # build_dir/package/path/filename filename = os.path.join(*modpath[:-1]+[filename]) return os.path.join(self.build_lib, filename) # the inplace option requires to find the package directory # using the build_py command for that package = '.'.join(modpath[0:-1]) build_py = self.get_finalized_command('build_py') package_dir = os.path.abspath(build_py.get_package_dir(package)) # returning # package_dir/filename return os.path.join(package_dir, filename)
[ "def", "get_ext_fullpath", "(", "self", ",", "ext_name", ")", ":", "fullname", "=", "self", ".", "get_ext_fullname", "(", "ext_name", ")", "modpath", "=", "fullname", ".", "split", "(", "'.'", ")", "filename", "=", "self", ".", "get_ext_filename", "(", "mo...
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/distutils/command/build_ext.py#L640-L665
ChineseGLUE/ChineseGLUE
1591b85cf5427c2ff60f718d359ecb71d2b44879
baselines/models_pytorch/classifier_pytorch/transformers/configuration_ctrl.py
python
CTRLConfig.num_attention_heads
(self)
return self.n_head
[]
def num_attention_heads(self): return self.n_head
[ "def", "num_attention_heads", "(", "self", ")", ":", "return", "self", ".", "n_head" ]
https://github.com/ChineseGLUE/ChineseGLUE/blob/1591b85cf5427c2ff60f718d359ecb71d2b44879/baselines/models_pytorch/classifier_pytorch/transformers/configuration_ctrl.py#L138-L139
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/_vendor/requests/cookies.py
python
MockResponse.__init__
(self, headers)
Make a MockResponse for `cookielib` to read. :param headers: a httplib.HTTPMessage or analogous carrying the headers
Make a MockResponse for `cookielib` to read.
[ "Make", "a", "MockResponse", "for", "cookielib", "to", "read", "." ]
def __init__(self, headers): """Make a MockResponse for `cookielib` to read. :param headers: a httplib.HTTPMessage or analogous carrying the headers """ self._headers = headers
[ "def", "__init__", "(", "self", ",", "headers", ")", ":", "self", ".", "_headers", "=", "headers" ]
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/_vendor/requests/cookies.py#L109-L114
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/stats/crv_types.py
python
UniformDistribution.pdf
(self, x)
return Piecewise( (S.One/(right - left), And(left <= x, x <= right)), (S.Zero, True))
[]
def pdf(self, x): left, right = self.left, self.right return Piecewise( (S.One/(right - left), And(left <= x, x <= right)), (S.Zero, True))
[ "def", "pdf", "(", "self", ",", "x", ")", ":", "left", ",", "right", "=", "self", ".", "left", ",", "self", ".", "right", "return", "Piecewise", "(", "(", "S", ".", "One", "/", "(", "right", "-", "left", ")", ",", "And", "(", "left", "<=", "x...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/stats/crv_types.py#L2145-L2149
hubblestack/hubble
763142474edcecdec5fd25591dc29c3536e8f969
hubblestack/hec/dq.py
python
DiskQueue.pop
(self)
remove the next item from the queue (do not return it); useful with .peek()
remove the next item from the queue (do not return it); useful with .peek()
[ "remove", "the", "next", "item", "from", "the", "queue", "(", "do", "not", "return", "it", ")", ";", "useful", "with", ".", "peek", "()" ]
def pop(self): """ remove the next item from the queue (do not return it); useful with .peek() """ for fname in self.files: sz = os.stat(fname).st_size self.unlink_(fname) self.cn -= 1 self.sz -= sz if self.double_check_cnsz: self._count(double_check_only=True, tag='pop') break
[ "def", "pop", "(", "self", ")", ":", "for", "fname", "in", "self", ".", "files", ":", "sz", "=", "os", ".", "stat", "(", "fname", ")", ".", "st_size", "self", ".", "unlink_", "(", "fname", ")", "self", ".", "cn", "-=", "1", "self", ".", "sz", ...
https://github.com/hubblestack/hubble/blob/763142474edcecdec5fd25591dc29c3536e8f969/hubblestack/hec/dq.py#L239-L248
GalSim-developers/GalSim
a05d4ec3b8d8574f99d3b0606ad882cbba53f345
galsim/config/process.py
python
ProcessTemplate
(config, base, logger=None)
If the config dict has a 'template' item, read in the appropriate file and make any requested updates. Parameters: config: The configuration dict. base: The base configuration dict. logger: If given, a logger object to log progress. [default: None]
If the config dict has a 'template' item, read in the appropriate file and make any requested updates.
[ "If", "the", "config", "dict", "has", "a", "template", "item", "read", "in", "the", "appropriate", "file", "and", "make", "any", "requested", "updates", "." ]
def ProcessTemplate(config, base, logger=None): """If the config dict has a 'template' item, read in the appropriate file and make any requested updates. Parameters: config: The configuration dict. base: The base configuration dict. logger: If given, a logger object to log progress. [default: None] """ logger = LoggerWrapper(logger) if 'template' in config: template_string = config.pop('template') logger.debug("Processing template specified as %s",template_string) # Parse the template string if ':' in template_string: config_file, field = template_string.split(':') else: config_file, field = template_string, None # Read the config file if appropriate if config_file != '': template = ReadConfig(config_file, logger=logger)[0] else: template = base # Pull out the specified field, if any if field is not None: template = GetFromConfig(template, field) # Copy over the template config into this one. new_params = config.copy() # N.B. Already popped config['template']. config.clear() config.update(template) # Update the config with the requested changes UpdateConfig(config, new_params)
[ "def", "ProcessTemplate", "(", "config", ",", "base", ",", "logger", "=", "None", ")", ":", "logger", "=", "LoggerWrapper", "(", "logger", ")", "if", "'template'", "in", "config", ":", "template_string", "=", "config", ".", "pop", "(", "'template'", ")", ...
https://github.com/GalSim-developers/GalSim/blob/a05d4ec3b8d8574f99d3b0606ad882cbba53f345/galsim/config/process.py#L129-L165
zyfra/ebonite
b01b662c43709d152940f488574d78ff25f89ecf
src/ebonite/build/provider/utils.py
python
BuildableWithServer.__init__
(self, server_type: str)
[]
def __init__(self, server_type: str): self.server_type = server_type
[ "def", "__init__", "(", "self", ",", "server_type", ":", "str", ")", ":", "self", ".", "server_type", "=", "server_type" ]
https://github.com/zyfra/ebonite/blob/b01b662c43709d152940f488574d78ff25f89ecf/src/ebonite/build/provider/utils.py#L6-L7
dexy/dexy
323c1806e51f75435e11d2265703e68f46c8aef3
dexy/filters/standard.py
python
ClojureWhitespaceFilter.process
(self)
[]
def process(self): input_text = str(self.input_data) for i, section in enumerate(input_text.split("\n\n")): section_name = self.parse_section_name(section) if section_name: self.output_data[section_name] = section else: self.output_data["%s" % (i+1)] = section self.output_data.save()
[ "def", "process", "(", "self", ")", ":", "input_text", "=", "str", "(", "self", ".", "input_data", ")", "for", "i", ",", "section", "in", "enumerate", "(", "input_text", ".", "split", "(", "\"\\n\\n\"", ")", ")", ":", "section_name", "=", "self", ".", ...
https://github.com/dexy/dexy/blob/323c1806e51f75435e11d2265703e68f46c8aef3/dexy/filters/standard.py#L228-L237
kubeflow/pipelines
bea751c9259ff0ae85290f873170aae89284ba8e
sdk/python/kfp/containers/entrypoint_utils.py
python
import_func_from_source
(source_path: str, fn_name: str)
Imports a function from a Python file. The implementation is borrowed from https://github.com/tensorflow/tfx/blob/8f25a4d1cc92dfc8c3a684dfc8b82699513cafb5/tfx/utils/import_utils.py#L50 Args: source_path: The local path to the Python source file. fn_name: The function name, which can be found in the source file. Return: A Python function object. Raises: ImportError when failed to load the source file or cannot find the function with the given name.
Imports a function from a Python file.
[ "Imports", "a", "function", "from", "a", "Python", "file", "." ]
def import_func_from_source(source_path: str, fn_name: str) -> Callable: """Imports a function from a Python file. The implementation is borrowed from https://github.com/tensorflow/tfx/blob/8f25a4d1cc92dfc8c3a684dfc8b82699513cafb5/tfx/utils/import_utils.py#L50 Args: source_path: The local path to the Python source file. fn_name: The function name, which can be found in the source file. Return: A Python function object. Raises: ImportError when failed to load the source file or cannot find the function with the given name. """ if any([source_path.startswith(prefix) for prefix in _REMOTE_FS_PREFIX]): raise RuntimeError( 'Only local source file can be imported. Please make ' 'sure the user code is built into executor container. ' 'Got file path: %s' % source_path) try: loader = importlib.machinery.SourceFileLoader( fullname=_USER_MODULE, path=source_path, ) spec = importlib.util.spec_from_loader( loader.name, loader, origin=source_path) module = importlib.util.module_from_spec(spec) sys.modules[loader.name] = module loader.exec_module(module) except IOError: raise ImportError( '{} in {} not found in import_func_from_source()'.format( fn_name, source_path)) try: return getattr(module, fn_name) except AttributeError: raise ImportError( '{} in {} not found in import_func_from_source()'.format( fn_name, source_path))
[ "def", "import_func_from_source", "(", "source_path", ":", "str", ",", "fn_name", ":", "str", ")", "->", "Callable", ":", "if", "any", "(", "[", "source_path", ".", "startswith", "(", "prefix", ")", "for", "prefix", "in", "_REMOTE_FS_PREFIX", "]", ")", ":"...
https://github.com/kubeflow/pipelines/blob/bea751c9259ff0ae85290f873170aae89284ba8e/sdk/python/kfp/containers/entrypoint_utils.py#L58-L98
reviewboard/reviewboard
7395902e4c181bcd1d633f61105012ffb1d18e1b
reviewboard/webapi/resources/review_general_comment.py
python
ReviewGeneralCommentResource.get_list
(self, *args, **kwargs)
Returns the list of general comments made on a review.
Returns the list of general comments made on a review.
[ "Returns", "the", "list", "of", "general", "comments", "made", "on", "a", "review", "." ]
def get_list(self, *args, **kwargs): """Returns the list of general comments made on a review.""" pass
[ "def", "get_list", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "pass" ]
https://github.com/reviewboard/reviewboard/blob/7395902e4c181bcd1d633f61105012ffb1d18e1b/reviewboard/webapi/resources/review_general_comment.py#L108-L110
niosus/EasyClangComplete
3b16eb17735aaa3f56bb295fc5481b269ee9f2ef
plugin/clang/cindex.py
python
Index.read
(self, path)
return TranslationUnit(ptr) if ptr else None
Load the translation unit from the given AST file.
Load the translation unit from the given AST file.
[ "Load", "the", "translation", "unit", "from", "the", "given", "AST", "file", "." ]
def read(self, path): """Load the translation unit from the given AST file.""" ptr = TranslationUnit_read(self, path) return TranslationUnit(ptr) if ptr else None
[ "def", "read", "(", "self", ",", "path", ")", ":", "ptr", "=", "TranslationUnit_read", "(", "self", ",", "path", ")", "return", "TranslationUnit", "(", "ptr", ")", "if", "ptr", "else", "None" ]
https://github.com/niosus/EasyClangComplete/blob/3b16eb17735aaa3f56bb295fc5481b269ee9f2ef/plugin/clang/cindex.py#L1787-L1790
collinsctk/PyQYT
7af3673955f94ff1b2df2f94220cd2dab2e252af
ExtentionPackages/scapy/contrib/gsm_um.py
python
recall
()
return packet
RECALL Section 9.3.18a
RECALL Section 9.3.18a
[ "RECALL", "Section", "9", ".", "3", ".", "18a" ]
def recall(): """RECALL Section 9.3.18a""" a = TpPd(pd=0x3) b = MessageType(mesType=0xb) # 00001011 c = RecallType() d = Facility() packet = a / b / c / d return packet
[ "def", "recall", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0xb", ")", "# 00001011", "c", "=", "RecallType", "(", ")", "d", "=", "Facility", "(", ")", "packet", "=", "a", "/", "b"...
https://github.com/collinsctk/PyQYT/blob/7af3673955f94ff1b2df2f94220cd2dab2e252af/ExtentionPackages/scapy/contrib/gsm_um.py#L1971-L1978
Alex-Fabbri/Multi-News
f6476d1f114662eb93db32e9b704b7c4fe047217
code/OpenNMT-py-baselines/onmt/decoders/transformer.py
python
TransformerDecoder.__init__
(self, num_layers, d_model, heads, d_ff, attn_type, copy_attn, self_attn_type, dropout, embeddings)
[]
def __init__(self, num_layers, d_model, heads, d_ff, attn_type, copy_attn, self_attn_type, dropout, embeddings): super(TransformerDecoder, self).__init__() # Basic attributes. self.decoder_type = 'transformer' self.num_layers = num_layers self.embeddings = embeddings self.self_attn_type = self_attn_type # Build TransformerDecoder. self.transformer_layers = nn.ModuleList( [TransformerDecoderLayer(d_model, heads, d_ff, dropout, self_attn_type=self_attn_type) for _ in range(num_layers)]) # TransformerDecoder has its own attention mechanism. # Set up a separated copy attention layer, if needed. self._copy = False if copy_attn: self.copy_attn = onmt.modules.GlobalAttention( d_model, attn_type=attn_type) self._copy = True self.layer_norm = onmt.modules.LayerNorm(d_model)
[ "def", "__init__", "(", "self", ",", "num_layers", ",", "d_model", ",", "heads", ",", "d_ff", ",", "attn_type", ",", "copy_attn", ",", "self_attn_type", ",", "dropout", ",", "embeddings", ")", ":", "super", "(", "TransformerDecoder", ",", "self", ")", ".",...
https://github.com/Alex-Fabbri/Multi-News/blob/f6476d1f114662eb93db32e9b704b7c4fe047217/code/OpenNMT-py-baselines/onmt/decoders/transformer.py#L147-L170
mittagessen/kraken
9882ba0743797a2d5b0a7b562fcc7235e87323da
kraken/lib/vgsl.py
python
TorchVGSLModel.one_channel_mode
(self)
return self.user_metadata['one_channel_mode']
[]
def one_channel_mode(self): return self.user_metadata['one_channel_mode']
[ "def", "one_channel_mode", "(", "self", ")", ":", "return", "self", ".", "user_metadata", "[", "'one_channel_mode'", "]" ]
https://github.com/mittagessen/kraken/blob/9882ba0743797a2d5b0a7b562fcc7235e87323da/kraken/lib/vgsl.py#L382-L383
ctxis/CAPE
dae9fa6a254ecdbabeb7eb0d2389fa63722c1e82
lib/cuckoo/common/utils.py
python
store_temp_file
(filedata, filename, path=None)
return tmp_file_path
Store a temporary file. @param filedata: content of the original file. @param filename: name of the original file. @param path: optional path for temp directory. @return: path to the temporary file.
Store a temporary file.
[ "Store", "a", "temporary", "file", "." ]
def store_temp_file(filedata, filename, path=None): """Store a temporary file. @param filedata: content of the original file. @param filename: name of the original file. @param path: optional path for temp directory. @return: path to the temporary file. """ filename = get_filename_from_path(filename).encode("utf-8", "replace") # Reduce length (100 is arbitrary). filename = filename[:100] options = Config() # Create temporary directory path. if path: target_path = path else: tmp_path = options.cuckoo.get("tmppath", "/tmp") target_path = os.path.join(tmp_path, "cuckoo-tmp") if not os.path.exists(target_path): os.mkdir(target_path) tmp_dir = tempfile.mkdtemp(prefix="upload_", dir=target_path) tmp_file_path = os.path.join(tmp_dir, filename) with open(tmp_file_path, "wb") as tmp_file: # If filedata is file object, do chunked copy. if hasattr(filedata, "read"): chunk = filedata.read(1024) while chunk: tmp_file.write(chunk) chunk = filedata.read(1024) else: tmp_file.write(filedata) return tmp_file_path
[ "def", "store_temp_file", "(", "filedata", ",", "filename", ",", "path", "=", "None", ")", ":", "filename", "=", "get_filename_from_path", "(", "filename", ")", ".", "encode", "(", "\"utf-8\"", ",", "\"replace\"", ")", "# Reduce length (100 is arbitrary).", "filen...
https://github.com/ctxis/CAPE/blob/dae9fa6a254ecdbabeb7eb0d2389fa63722c1e82/lib/cuckoo/common/utils.py#L1480-L1514
Borda/pyImSegm
7584b40a8d5bba04d3bf46f540f22b5d923e4b03
imsegm/descriptors.py
python
cython_img2d_color_std
(img, seg, means=None)
return std
wrapper for fast implementation of colour features :param ndarray img: input RGB image :param ndarray seg: segmentation og the image :param ndarray means: precomputed feature means :return: np.array<nb_lbs, 3> matrix features per segment .. seealso:: :func:`imsegm.descriptors.numpy_img2d_color_std` >>> image = np.zeros((2, 10, 3)) >>> image[:, 2:6, 0] = 1 >>> image[:, 3:7, 1] = 3 >>> image[:, 4:9, 2] = 2 >>> segm = np.array([[0, 0, 0, 0, 0, 1, 1, 1, 1, 1], ... [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]]) >>> cython_img2d_color_std(image, segm) array([[ 0.48989794, 1.46969383, 0.80000003], [ 0.40000001, 1.46969383, 0.80000001]])
wrapper for fast implementation of colour features
[ "wrapper", "for", "fast", "implementation", "of", "colour", "features" ]
def cython_img2d_color_std(img, seg, means=None): """ wrapper for fast implementation of colour features :param ndarray img: input RGB image :param ndarray seg: segmentation og the image :param ndarray means: precomputed feature means :return: np.array<nb_lbs, 3> matrix features per segment .. seealso:: :func:`imsegm.descriptors.numpy_img2d_color_std` >>> image = np.zeros((2, 10, 3)) >>> image[:, 2:6, 0] = 1 >>> image[:, 3:7, 1] = 3 >>> image[:, 4:9, 2] = 2 >>> segm = np.array([[0, 0, 0, 0, 0, 1, 1, 1, 1, 1], ... [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]]) >>> cython_img2d_color_std(image, segm) array([[ 0.48989794, 1.46969383, 0.80000003], [ 0.40000001, 1.46969383, 0.80000001]]) """ logging.debug( 'Cython: computing Colour STD for image %r & segm %r with %i segments', img.shape, seg.shape, np.max(seg) ) _check_color_image_segm(img, seg) if means is None: means = cython_img2d_color_mean(img, seg) var = fts_cython.computeColorImage2dVariance( np.array(img, dtype=np.float32), np.array(seg, dtype=np.int32), np.array(means, dtype=np.float32) ) std = np.sqrt(var) return std
[ "def", "cython_img2d_color_std", "(", "img", ",", "seg", ",", "means", "=", "None", ")", ":", "logging", ".", "debug", "(", "'Cython: computing Colour STD for image %r & segm %r with %i segments'", ",", "img", ".", "shape", ",", "seg", ".", "shape", ",", "np", "...
https://github.com/Borda/pyImSegm/blob/7584b40a8d5bba04d3bf46f540f22b5d923e4b03/imsegm/descriptors.py#L265-L296
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/pkg_resources/_vendor/pyparsing.py
python
_MultipleMatch.__init__
( self, expr, stopOn=None)
[]
def __init__( self, expr, stopOn=None): super(_MultipleMatch, self).__init__(expr) self.saveAsList = True ender = stopOn if isinstance(ender, basestring): ender = ParserElement._literalStringClass(ender) self.not_ender = ~ender if ender is not None else None
[ "def", "__init__", "(", "self", ",", "expr", ",", "stopOn", "=", "None", ")", ":", "super", "(", "_MultipleMatch", ",", "self", ")", ".", "__init__", "(", "expr", ")", "self", ".", "saveAsList", "=", "True", "ender", "=", "stopOn", "if", "isinstance", ...
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pkg_resources/_vendor/pyparsing.py#L3851-L3857
pantsbuild/pex
473c6ac732ed4bc338b4b20a9ec930d1d722c9b4
pex/vendor/_vendored/setuptools/setuptools/_vendor/pyparsing.py
python
ParserElement.setParseAction
( self, *fns, **kwargs )
return self
Define one or more actions to perform when successfully matching parse element definition. Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)}, C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where: - s = the original string being parsed (see note below) - loc = the location of the matching substring - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object If the functions in fns modify the tokens, they can return them as the return value from fn, and the modified list of tokens will replace the original. Otherwise, fn does not need to return any value. Optional keyword arguments: - callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{parseString}<parseString>} for more information on parsing strings containing C{<TAB>}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. Example:: integer = Word(nums) date_str = integer + '/' + integer + '/' + integer date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # use parse action to convert to ints at parse time integer = Word(nums).setParseAction(lambda toks: int(toks[0])) date_str = integer + '/' + integer + '/' + integer # note that integer fields are now ints, not strings date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31]
Define one or more actions to perform when successfully matching parse element definition. Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)}, C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where: - s = the original string being parsed (see note below) - loc = the location of the matching substring - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object If the functions in fns modify the tokens, they can return them as the return value from fn, and the modified list of tokens will replace the original. Otherwise, fn does not need to return any value.
[ "Define", "one", "or", "more", "actions", "to", "perform", "when", "successfully", "matching", "parse", "element", "definition", ".", "Parse", "action", "fn", "is", "a", "callable", "method", "with", "0", "-", "3", "arguments", "called", "as", "C", "{", "f...
def setParseAction( self, *fns, **kwargs ): """ Define one or more actions to perform when successfully matching parse element definition. Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)}, C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where: - s = the original string being parsed (see note below) - loc = the location of the matching substring - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object If the functions in fns modify the tokens, they can return them as the return value from fn, and the modified list of tokens will replace the original. Otherwise, fn does not need to return any value. Optional keyword arguments: - callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{parseString}<parseString>} for more information on parsing strings containing C{<TAB>}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. Example:: integer = Word(nums) date_str = integer + '/' + integer + '/' + integer date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # use parse action to convert to ints at parse time integer = Word(nums).setParseAction(lambda toks: int(toks[0])) date_str = integer + '/' + integer + '/' + integer # note that integer fields are now ints, not strings date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31] """ self.parseAction = list(map(_trim_arity, list(fns))) self.callDuringTry = kwargs.get("callDuringTry", False) return self
[ "def", "setParseAction", "(", "self", ",", "*", "fns", ",", "*", "*", "kwargs", ")", ":", "self", ".", "parseAction", "=", "list", "(", "map", "(", "_trim_arity", ",", "list", "(", "fns", ")", ")", ")", "self", ".", "callDuringTry", "=", "kwargs", ...
https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/setuptools/setuptools/_vendor/pyparsing.py#L1250-L1286
amphibian-dev/toad
3d932169112e8474525262af15440af7f2cf8029
toad/selection.py
python
drop_vif
(frame, threshold = 3, return_drop = False, exclude = None)
return unpack_tuple(res)
variance inflation factor Args: frame (DataFrame) threshold (float): drop features until all vif is less than threshold return_drop (bool): if need to return features' name who has been dropped exclude (array-like): list of feature names that will not be dropped Returns: DataFrame: selected dataframe array: list of feature names that has been dropped
variance inflation factor
[ "variance", "inflation", "factor" ]
def drop_vif(frame, threshold = 3, return_drop = False, exclude = None): """variance inflation factor Args: frame (DataFrame) threshold (float): drop features until all vif is less than threshold return_drop (bool): if need to return features' name who has been dropped exclude (array-like): list of feature names that will not be dropped Returns: DataFrame: selected dataframe array: list of feature names that has been dropped """ cols = frame.columns.copy() if exclude is not None: cols = cols.drop(exclude) drop_list = [] while(True): vif = VIF(frame[cols]) ix = vif.idxmax() max = vif[ix] if max < threshold: break cols = cols.drop(ix) drop_list.append(ix) r = frame.drop(columns = drop_list) res = (r,) if return_drop: res += (drop_list,) return unpack_tuple(res)
[ "def", "drop_vif", "(", "frame", ",", "threshold", "=", "3", ",", "return_drop", "=", "False", ",", "exclude", "=", "None", ")", ":", "cols", "=", "frame", ".", "columns", ".", "copy", "(", ")", "if", "exclude", "is", "not", "None", ":", "cols", "=...
https://github.com/amphibian-dev/toad/blob/3d932169112e8474525262af15440af7f2cf8029/toad/selection.py#L445-L483
keenlabs/KeenClient-Python
0cd942152977ee37a0c828249c95cf3a27c8c80f
keen/client.py
python
KeenClient.median
(self, event_collection, target_property, timeframe=None, timezone=None, interval=None, filters=None, group_by=None, order_by=None, max_age=None, limit=None)
return self.api.query("median", params)
Performs a median query Finds the median of a target property for events that meet the given criteria. :param event_collection: string, the name of the collection to query :param target_property: string, the name of the event property you would like use :param timeframe: string or dict, the timeframe in which the events happened example: "previous_7_days" :param timezone: int, the timezone you'd like to use for the timeframe and interval in seconds :param interval: string, the time interval used for measuring data over time example: "daily" :param filters: array of dict, contains the filters you'd like to apply to the data example: [{"property_name":"device", "operator":"eq", "property_value":"iPhone"}] :param group_by: string or array of strings, the name(s) of the properties you would like to group your results by. example: "customer.id" or ["browser","operating_system"] :param order_by: dictionary or list of dictionary objects containing the property_name(s) to order by and the desired direction(s) of sorting. Example: {"property_name":"result", "direction":keen.direction.DESCENDING} May not be used without a group_by specified. :param limit: positive integer limiting the displayed results of a query using order_by :param max_age: an integer, greater than 30 seconds, the maximum 'staleness' you're willing to trade for increased query performance, in seconds
Performs a median query
[ "Performs", "a", "median", "query" ]
def median(self, event_collection, target_property, timeframe=None, timezone=None, interval=None, filters=None, group_by=None, order_by=None, max_age=None, limit=None): """ Performs a median query Finds the median of a target property for events that meet the given criteria. :param event_collection: string, the name of the collection to query :param target_property: string, the name of the event property you would like use :param timeframe: string or dict, the timeframe in which the events happened example: "previous_7_days" :param timezone: int, the timezone you'd like to use for the timeframe and interval in seconds :param interval: string, the time interval used for measuring data over time example: "daily" :param filters: array of dict, contains the filters you'd like to apply to the data example: [{"property_name":"device", "operator":"eq", "property_value":"iPhone"}] :param group_by: string or array of strings, the name(s) of the properties you would like to group your results by. example: "customer.id" or ["browser","operating_system"] :param order_by: dictionary or list of dictionary objects containing the property_name(s) to order by and the desired direction(s) of sorting. Example: {"property_name":"result", "direction":keen.direction.DESCENDING} May not be used without a group_by specified. :param limit: positive integer limiting the displayed results of a query using order_by :param max_age: an integer, greater than 30 seconds, the maximum 'staleness' you're willing to trade for increased query performance, in seconds """ params = self.get_params(event_collection=event_collection, timeframe=timeframe, timezone=timezone, interval=interval, filters=filters, group_by=group_by, order_by=order_by, target_property=target_property, max_age=max_age, limit=limit) return self.api.query("median", params)
[ "def", "median", "(", "self", ",", "event_collection", ",", "target_property", ",", "timeframe", "=", "None", ",", "timezone", "=", "None", ",", "interval", "=", "None", ",", "filters", "=", "None", ",", "group_by", "=", "None", ",", "order_by", "=", "No...
https://github.com/keenlabs/KeenClient-Python/blob/0cd942152977ee37a0c828249c95cf3a27c8c80f/keen/client.py#L496-L526
openstack/barbican
a9d2b133c8dc3307974f119f9a2b23a4ba82e8ce
barbican/model/migration/alembic_migrations/projects_init_ops.py
python
upgrade
()
[]
def upgrade(): op.create_table( 'tenants', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.Column('deleted_at', sa.DateTime(), nullable=True), sa.Column('deleted', sa.Boolean(), nullable=False), sa.Column('status', sa.String(length=20), nullable=False), sa.Column('keystone_id', sa.String(length=255), nullable=True), sa.PrimaryKeyConstraint('id') )
[ "def", "upgrade", "(", ")", ":", "op", ".", "create_table", "(", "'tenants'", ",", "sa", ".", "Column", "(", "'id'", ",", "sa", ".", "String", "(", "length", "=", "36", ")", ",", "nullable", "=", "False", ")", ",", "sa", ".", "Column", "(", "'cre...
https://github.com/openstack/barbican/blob/a9d2b133c8dc3307974f119f9a2b23a4ba82e8ce/barbican/model/migration/alembic_migrations/projects_init_ops.py#L25-L36
neptune-ai/open-solution-salt-identification
394f16b23b6e30543aee54701f81a06b5dd92a98
common_blocks/models.py
python
SegmentationModelWithDepth._transform
(self, datagen, validation_datagen=None, **kwargs)
return outputs
[]
def _transform(self, datagen, validation_datagen=None, **kwargs): self.model.eval() batch_gen, steps = datagen outputs = {} for batch_id, data in enumerate(batch_gen): X = data[0] D = data[1] if torch.cuda.is_available(): X = Variable(X, volatile=True).cuda() D = Variable(D, volatile=True).cuda() else: X = Variable(X, volatile=True) D = Variable(D, volatile=True) outputs_batch = self.model(X, D) if len(self.output_names) == 1: outputs.setdefault(self.output_names[0], []).append(outputs_batch.data.cpu().numpy()) else: for name, output in zip(self.output_names, outputs_batch): output_ = output.data.cpu().numpy() outputs.setdefault(name, []).append(output_) if batch_id == steps: break self.model.train() outputs = {'{}_prediction'.format(name): get_list_of_image_predictions(outputs_) for name, outputs_ in outputs.items()} return outputs
[ "def", "_transform", "(", "self", ",", "datagen", ",", "validation_datagen", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "model", ".", "eval", "(", ")", "batch_gen", ",", "steps", "=", "datagen", "outputs", "=", "{", "}", "for", "bat...
https://github.com/neptune-ai/open-solution-salt-identification/blob/394f16b23b6e30543aee54701f81a06b5dd92a98/common_blocks/models.py#L258-L286
pytroll/satpy
09e51f932048f98cce7919a4ff8bd2ec01e1ae98
satpy/readers/sar_c_safe.py
python
AzimuthNoiseReader._create_dask_slices_from_blocks
(self, chunks)
return slices
Create full-width slices from azimuth noise blocks.
Create full-width slices from azimuth noise blocks.
[ "Create", "full", "-", "width", "slices", "from", "azimuth", "noise", "blocks", "." ]
def _create_dask_slices_from_blocks(self, chunks): """Create full-width slices from azimuth noise blocks.""" current_line = 0 slices = [] while current_line < self._image_shape[0]: new_slice = self._create_dask_slice_from_block_line(current_line, chunks) slices.append(new_slice) current_line += new_slice.shape[0] return slices
[ "def", "_create_dask_slices_from_blocks", "(", "self", ",", "chunks", ")", ":", "current_line", "=", "0", "slices", "=", "[", "]", "while", "current_line", "<", "self", ".", "_image_shape", "[", "0", "]", ":", "new_slice", "=", "self", ".", "_create_dask_sli...
https://github.com/pytroll/satpy/blob/09e51f932048f98cce7919a4ff8bd2ec01e1ae98/satpy/readers/sar_c_safe.py#L272-L280
PaddlePaddle/Research
2da0bd6c72d60e9df403aff23a7802779561c4a1
ST_DM/KDD2021-MSTPAC/code/MST-PAC/frame/core/cpu_trainer.py
python
CPUTrainer.init_model_params
(self, exe, main_program, FLAGS)
return
load params of pretrained model, NOT including moment, learning_rate
load params of pretrained model, NOT including moment, learning_rate
[ "load", "params", "of", "pretrained", "model", "NOT", "including", "moment", "learning_rate" ]
def init_model_params(self, exe, main_program, FLAGS): """ load params of pretrained model, NOT including moment, learning_rate """ if FLAGS.init_train_params is not None: place = self.create_places(FLAGS)[0] self.paddle_env['factory']['net'].init_params(place) logging.info("Load pretrain params from {}.".format( FLAGS.init_train_params)) elif FLAGS.init_pretrain_model is not None: fluid.io.load_persistables( exe, FLAGS.init_pretrain_model, main_program=main_program) logging.info("Load pretrain persistables from {}.".format( FLAGS.init_pretrain_model)) return
[ "def", "init_model_params", "(", "self", ",", "exe", ",", "main_program", ",", "FLAGS", ")", ":", "if", "FLAGS", ".", "init_train_params", "is", "not", "None", ":", "place", "=", "self", ".", "create_places", "(", "FLAGS", ")", "[", "0", "]", "self", "...
https://github.com/PaddlePaddle/Research/blob/2da0bd6c72d60e9df403aff23a7802779561c4a1/ST_DM/KDD2021-MSTPAC/code/MST-PAC/frame/core/cpu_trainer.py#L178-L194
google/personfinder
475f4c0ce916036d39bae2d480cde07126550875
app/views/admin/api_keys.py
python
ApiKeyListView.get
(self, request, *args, **kwargs)
return self.render( 'admin_api_keys_list.html', admin_api_keys_url=self.build_absolute_path( '/admin/api_keys', self.env.repo or 'global'), user=self.env.user, user_email=self.env.user.email(), authorizations=auths, xsrf_token=self.xsrf_tool.generate_token( self.env.user.user_id(), 'admin_api_keys'))
Serves a view with a list of API keys.
Serves a view with a list of API keys.
[ "Serves", "a", "view", "with", "a", "list", "of", "API", "keys", "." ]
def get(self, request, *args, **kwargs): """Serves a view with a list of API keys.""" del request, args, kwargs # unused auths = model.Authorization.all().filter( 'repo = ', self.env.repo or '*') return self.render( 'admin_api_keys_list.html', admin_api_keys_url=self.build_absolute_path( '/admin/api_keys', self.env.repo or 'global'), user=self.env.user, user_email=self.env.user.email(), authorizations=auths, xsrf_token=self.xsrf_tool.generate_token( self.env.user.user_id(), 'admin_api_keys'))
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "del", "request", ",", "args", ",", "kwargs", "# unused", "auths", "=", "model", ".", "Authorization", ".", "all", "(", ")", ".", "filter", "(", "'repo ...
https://github.com/google/personfinder/blob/475f4c0ce916036d39bae2d480cde07126550875/app/views/admin/api_keys.py#L55-L68
apache/tvm
6eb4ed813ebcdcd9558f0906a1870db8302ff1e0
python/tvm/driver/tvmc/target.py
python
tokenize_target
(target)
return re.findall(target_pattern, target)
Extract a list of tokens from a target specification text. It covers some corner-cases that are not covered by the built-in module 'shlex', such as the use of "+" as a punctuation character. Example ------- For the input `foo -op1=v1 -op2="v ,2", bar -op3=v-4` we should obtain: ["foo", "-op1=v1", "-op2="v ,2"", ",", "bar", "-op3=v-4"] Parameters ---------- target : str Target options sent via CLI arguments Returns ------- list of str a list of parsed tokens extracted from the target string
Extract a list of tokens from a target specification text.
[ "Extract", "a", "list", "of", "tokens", "from", "a", "target", "specification", "text", "." ]
def tokenize_target(target): """ Extract a list of tokens from a target specification text. It covers some corner-cases that are not covered by the built-in module 'shlex', such as the use of "+" as a punctuation character. Example ------- For the input `foo -op1=v1 -op2="v ,2", bar -op3=v-4` we should obtain: ["foo", "-op1=v1", "-op2="v ,2"", ",", "bar", "-op3=v-4"] Parameters ---------- target : str Target options sent via CLI arguments Returns ------- list of str a list of parsed tokens extracted from the target string """ # Regex to tokenize the "--target" value. It is split into five parts # to match with: # 1. target and option names e.g. llvm, -mattr=, -mcpu= # 2. option values, all together, without quotes e.g. -mattr=+foo,+opt # 3. option values, when single quotes are used e.g. -mattr='+foo, +opt' # 4. option values, when double quotes are used e.g. -mattr="+foo ,+opt" # 5. commas that separate different targets e.g. "my-target, llvm" target_pattern = ( r"(\-{0,2}[\w\-]+\=?" r"(?:[\w\+\-\.]+(?:,[\w\+\-\.])*" r"|[\'][\w\+\-,\s\.]+[\']" r"|[\"][\w\+\-,\s\.]+[\"])*" r"|,)" ) return re.findall(target_pattern, target)
[ "def", "tokenize_target", "(", "target", ")", ":", "# Regex to tokenize the \"--target\" value. It is split into five parts", "# to match with:", "# 1. target and option names e.g. llvm, -mattr=, -mcpu=", "# 2. option values, all together, without quotes e.g. -mattr=+foo,+opt", "# 3. option v...
https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/python/tvm/driver/tvmc/target.py#L123-L165