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
chrysn/aiocoap
1f03d4ceb969b2b443c288c312d44c3b7c3e2031
aiocoap/message.py
python
Message._append_response_block
(self, next_block)
Append next block to current response message. Used when assembling incoming blockwise responses.
Append next block to current response message. Used when assembling incoming blockwise responses.
[ "Append", "next", "block", "to", "current", "response", "message", ".", "Used", "when", "assembling", "incoming", "blockwise", "responses", "." ]
def _append_response_block(self, next_block): """Append next block to current response message. Used when assembling incoming blockwise responses.""" if not self.code.is_response(): raise ValueError("_append_response_block only works on responses.") block2 = next_block.opt.block2 if not block2.is_valid_for_payload_size(len(next_block.payload)): raise error.UnexpectedBlock2("Payload size does not match Block2") if block2.start != len(self.payload): # Does not need to be implemented as long as the requesting code # sequentially clocks out data raise error.NotImplemented() if next_block.opt.etag != self.opt.etag: raise error.ResourceChanged() self.payload += next_block.payload self.opt.block2 = block2 self.token = next_block.token self.mid = next_block.mid
[ "def", "_append_response_block", "(", "self", ",", "next_block", ")", ":", "if", "not", "self", ".", "code", ".", "is_response", "(", ")", ":", "raise", "ValueError", "(", "\"_append_response_block only works on responses.\"", ")", "block2", "=", "next_block", "."...
https://github.com/chrysn/aiocoap/blob/1f03d4ceb969b2b443c288c312d44c3b7c3e2031/aiocoap/message.py#L325-L345
jgyates/genmon
2cb2ed2945f55cd8c259b09ccfa9a51e23f1341e
genmonlib/mytile.py
python
MyTile.CreateLabels
(self, Minimum, Nominal, Maximum)
return ReturnList
[]
def CreateLabels(self, Minimum, Nominal, Maximum): if Maximum - Minimum < 15: return list(range(int(self.Minimum), int(self.Maximum), 2)) elif Maximum - Minimum < 30: return list(range(int(self.Minimum), int(self.Maximum), 5)) elif Maximum - Minimum < 45: return list(range(int(self.Minimum), int(self.Maximum), 10)) else: RoundTo = 5 ReturnList = [] Range = Nominal ReturnList.append(int(round(Minimum,1))) ReturnList.append(Minimum + int(self.myround(Range * .2, RoundTo))) ReturnList.append(Minimum + int(self.myround(Range * .4, RoundTo))) ReturnList.append(Minimum + int(self.myround(Range * .6, RoundTo))) ReturnList.append(Minimum + int(self.myround(Range * .8, RoundTo))) ReturnList.append(int(self.myround(Nominal, RoundTo))) ReturnList.append(int(Maximum)) return ReturnList
[ "def", "CreateLabels", "(", "self", ",", "Minimum", ",", "Nominal", ",", "Maximum", ")", ":", "if", "Maximum", "-", "Minimum", "<", "15", ":", "return", "list", "(", "range", "(", "int", "(", "self", ".", "Minimum", ")", ",", "int", "(", "self", "....
https://github.com/jgyates/genmon/blob/2cb2ed2945f55cd8c259b09ccfa9a51e23f1341e/genmonlib/mytile.py#L232-L252
nschloe/pygmsh
3e7eea6fae3b4cd5e9f2c2d52b3686d3e5a1a725
src/pygmsh/common/geometry.py
python
CommonGeometry.add_curve_loop
(self, *args, **kwargs)
return CurveLoop(self.env, *args, **kwargs)
[]
def add_curve_loop(self, *args, **kwargs): return CurveLoop(self.env, *args, **kwargs)
[ "def", "add_curve_loop", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "CurveLoop", "(", "self", ".", "env", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/nschloe/pygmsh/blob/3e7eea6fae3b4cd5e9f2c2d52b3686d3e5a1a725/src/pygmsh/common/geometry.py#L79-L80
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
txweb2/client/http.py
python
HTTPClientChannelRequest._abortWithError
(self, errcode, text)
Abort parsing by forwarding a C{ProtocolError} to C{_error}.
Abort parsing by forwarding a C{ProtocolError} to C{_error}.
[ "Abort", "parsing", "by", "forwarding", "a", "C", "{", "ProtocolError", "}", "to", "C", "{", "_error", "}", "." ]
def _abortWithError(self, errcode, text): """ Abort parsing by forwarding a C{ProtocolError} to C{_error}. """ self._error(ProtocolError(text))
[ "def", "_abortWithError", "(", "self", ",", "errcode", ",", "text", ")", ":", "self", ".", "_error", "(", "ProtocolError", "(", "text", ")", ")" ]
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txweb2/client/http.py#L179-L183
Blizzard/heroprotocol
3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c
heroprotocol/versions/protocol77525.py
python
decode_replay_attributes_events
(contents)
return attributes
Decodes and yields each attribute from the contents byte string.
Decodes and yields each attribute from the contents byte string.
[ "Decodes", "and", "yields", "each", "attribute", "from", "the", "contents", "byte", "string", "." ]
def decode_replay_attributes_events(contents): """Decodes and yields each attribute from the contents byte string.""" buffer = BitPackedBuffer(contents, 'little') attributes = {} if not buffer.done(): attributes['source'] = buffer.read_bits(8) attributes['mapNamespace'] = buffer.read_bits(32) _ = buffer.read_bits(32) attributes['scopes'] = {} while not buffer.done(): value = {} value['namespace'] = buffer.read_bits(32) value['attrid'] = attrid = buffer.read_bits(32) scope = buffer.read_bits(8) value['value'] = buffer.read_aligned_bytes(4)[::-1].strip(b'\x00') if not scope in attributes['scopes']: attributes['scopes'][scope] = {} if not attrid in attributes['scopes'][scope]: attributes['scopes'][scope][attrid] = [] attributes['scopes'][scope][attrid].append(value) return attributes
[ "def", "decode_replay_attributes_events", "(", "contents", ")", ":", "buffer", "=", "BitPackedBuffer", "(", "contents", ",", "'little'", ")", "attributes", "=", "{", "}", "if", "not", "buffer", ".", "done", "(", ")", ":", "attributes", "[", "'source'", "]", ...
https://github.com/Blizzard/heroprotocol/blob/3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c/heroprotocol/versions/protocol77525.py#L452-L472
cloudlinux/kuberdock-platform
8b3923c19755f3868e4142b62578d9b9857d2704
kubedock/kapi/ingress.py
python
prepare_ip_sharing_task
()
Run `prepare_ip_sharing` asynchronously.
Run `prepare_ip_sharing` asynchronously.
[ "Run", "prepare_ip_sharing", "asynchronously", "." ]
def prepare_ip_sharing_task(): """Run `prepare_ip_sharing` asynchronously.""" with _notify_on_errors_context(APIError): return prepare_ip_sharing()
[ "def", "prepare_ip_sharing_task", "(", ")", ":", "with", "_notify_on_errors_context", "(", "APIError", ")", ":", "return", "prepare_ip_sharing", "(", ")" ]
https://github.com/cloudlinux/kuberdock-platform/blob/8b3923c19755f3868e4142b62578d9b9857d2704/kubedock/kapi/ingress.py#L347-L350
OpenEIT/OpenEIT
0448694e8092361ae5ccb45fba81dee543a6244b
OpenEIT/backend/bluetooth/build/lib/Adafruit_BluefruitLE/bluez_dbus/device.py
python
BluezDevice.discover
(self, service_uuids, char_uuids, timeout_sec=TIMEOUT_SEC)
Wait up to timeout_sec for the specified services and characteristics to be discovered on the device. If the timeout is exceeded without discovering the services and characteristics then an exception is thrown.
Wait up to timeout_sec for the specified services and characteristics to be discovered on the device. If the timeout is exceeded without discovering the services and characteristics then an exception is thrown.
[ "Wait", "up", "to", "timeout_sec", "for", "the", "specified", "services", "and", "characteristics", "to", "be", "discovered", "on", "the", "device", ".", "If", "the", "timeout", "is", "exceeded", "without", "discovering", "the", "services", "and", "characteristi...
def discover(self, service_uuids, char_uuids, timeout_sec=TIMEOUT_SEC): """Wait up to timeout_sec for the specified services and characteristics to be discovered on the device. If the timeout is exceeded without discovering the services and characteristics then an exception is thrown. """ # Turn expected values into a counter of each UUID for fast comparison. expected_services = set(service_uuids) expected_chars = set(char_uuids) # Loop trying to find the expected services for the device. start = time.time() while True: # Find actual services discovered for the device. actual_services = set(self.advertised) # Find actual characteristics discovered for the device. chars = map(BluezGattCharacteristic, get_provider()._get_objects(_CHARACTERISTIC_INTERFACE, self._device.object_path)) actual_chars = set(map(lambda x: x.uuid, chars)) # Compare actual discovered UUIDs with expected and return true if at # least the expected UUIDs are available. if actual_services >= expected_services and actual_chars >= expected_chars: # Found at least the expected services! return True # Couldn't find the devices so check if timeout has expired and try again. if time.time()-start >= timeout_sec: return False time.sleep(1)
[ "def", "discover", "(", "self", ",", "service_uuids", ",", "char_uuids", ",", "timeout_sec", "=", "TIMEOUT_SEC", ")", ":", "# Turn expected values into a counter of each UUID for fast comparison.", "expected_services", "=", "set", "(", "service_uuids", ")", "expected_chars"...
https://github.com/OpenEIT/OpenEIT/blob/0448694e8092361ae5ccb45fba81dee543a6244b/OpenEIT/backend/bluetooth/build/lib/Adafruit_BluefruitLE/bluez_dbus/device.py#L94-L120
riptideio/pymodbus
c5772b35ae3f29d1947f3ab453d8d00df846459f
pymodbus/utilities.py
python
unpack_bitstring
(string)
return bits
Creates bit array out of a string :param string: The modbus data packet to decode example:: bytes = 'bytes to decode' result = unpack_bitstring(bytes)
Creates bit array out of a string
[ "Creates", "bit", "array", "out", "of", "a", "string" ]
def unpack_bitstring(string): """ Creates bit array out of a string :param string: The modbus data packet to decode example:: bytes = 'bytes to decode' result = unpack_bitstring(bytes) """ byte_count = len(string) bits = [] for byte in range(byte_count): if IS_PYTHON3: value = byte2int(int(string[byte])) else: value = byte2int(string[byte]) for _ in range(8): bits.append((value & 1) == 1) value >>= 1 return bits
[ "def", "unpack_bitstring", "(", "string", ")", ":", "byte_count", "=", "len", "(", "string", ")", "bits", "=", "[", "]", "for", "byte", "in", "range", "(", "byte_count", ")", ":", "if", "IS_PYTHON3", ":", "value", "=", "byte2int", "(", "int", "(", "s...
https://github.com/riptideio/pymodbus/blob/c5772b35ae3f29d1947f3ab453d8d00df846459f/pymodbus/utilities.py#L109-L129
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/source-python/entities/dictionary.py
python
SyncedEntityDictionary.on_automatically_created
(self, index)
Called when an index is automatically added. :param int index: The index of the entity instance being added.
Called when an index is automatically added.
[ "Called", "when", "an", "index", "is", "automatically", "added", "." ]
def on_automatically_created(self, index): """Called when an index is automatically added. :param int index: The index of the entity instance being added. """
[ "def", "on_automatically_created", "(", "self", ",", "index", ")", ":" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/source-python/entities/dictionary.py#L200-L205
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/ipykernel-4.1.1-py3.3.egg/ipykernel/serialize.py
python
unpack_apply_message
(bufs, g=None, copy=True)
return f,args,kwargs
unpack f,args,kwargs from buffers packed by pack_apply_message() Returns: original f,args,kwargs
unpack f,args,kwargs from buffers packed by pack_apply_message() Returns: original f,args,kwargs
[ "unpack", "f", "args", "kwargs", "from", "buffers", "packed", "by", "pack_apply_message", "()", "Returns", ":", "original", "f", "args", "kwargs" ]
def unpack_apply_message(bufs, g=None, copy=True): """unpack f,args,kwargs from buffers packed by pack_apply_message() Returns: original f,args,kwargs""" bufs = list(bufs) # allow us to pop assert len(bufs) >= 2, "not enough buffers!" pf = buffer_to_bytes_py2(bufs.pop(0)) f = uncan(pickle.loads(pf), g) pinfo = buffer_to_bytes_py2(bufs.pop(0)) info = pickle.loads(pinfo) arg_bufs, kwarg_bufs = bufs[:info['narg_bufs']], bufs[info['narg_bufs']:] args = [] for i in range(info['nargs']): arg, arg_bufs = deserialize_object(arg_bufs, g) args.append(arg) args = tuple(args) assert not arg_bufs, "Shouldn't be any arg bufs left over" kwargs = {} for key in info['kw_keys']: kwarg, kwarg_bufs = deserialize_object(kwarg_bufs, g) kwargs[key] = kwarg assert not kwarg_bufs, "Shouldn't be any kwarg bufs left over" return f,args,kwargs
[ "def", "unpack_apply_message", "(", "bufs", ",", "g", "=", "None", ",", "copy", "=", "True", ")", ":", "bufs", "=", "list", "(", "bufs", ")", "# allow us to pop", "assert", "len", "(", "bufs", ")", ">=", "2", ",", "\"not enough buffers!\"", "pf", "=", ...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/ipykernel-4.1.1-py3.3.egg/ipykernel/serialize.py#L159-L183
fritzy/SleekXMPP
cc1d470397de768ffcc41d2ed5ac3118d19f09f5
sleekxmpp/plugins/xep_0050/stanza.py
python
Command.del_notes
(self)
Remove all notes associated with the command result.
Remove all notes associated with the command result.
[ "Remove", "all", "notes", "associated", "with", "the", "command", "result", "." ]
def del_notes(self): """ Remove all notes associated with the command result. """ notes_xml = self.findall('{%s}note' % self.namespace) for note in notes_xml: self.xml.remove(note)
[ "def", "del_notes", "(", "self", ")", ":", "notes_xml", "=", "self", ".", "findall", "(", "'{%s}note'", "%", "self", ".", "namespace", ")", "for", "note", "in", "notes_xml", ":", "self", ".", "xml", ".", "remove", "(", "note", ")" ]
https://github.com/fritzy/SleekXMPP/blob/cc1d470397de768ffcc41d2ed5ac3118d19f09f5/sleekxmpp/plugins/xep_0050/stanza.py#L166-L172
Logan1x/Python-Scripts
e611dae0c86af21aad2bf11100bcc0448aa16fd0
bin/A-Star-GUI/AStarGUI.py
python
make_grid
(rows, width)
return grid
[]
def make_grid(rows, width): grid = [] gap = width // rows # integer division: gap b/w each of these rows for i in range(rows): grid.append([]) for j in range(rows): spot = Spot(i, j, gap, rows) grid[i].append(spot) return grid
[ "def", "make_grid", "(", "rows", ",", "width", ")", ":", "grid", "=", "[", "]", "gap", "=", "width", "//", "rows", "# integer division: gap b/w each of these rows", "for", "i", "in", "range", "(", "rows", ")", ":", "grid", ".", "append", "(", "[", "]", ...
https://github.com/Logan1x/Python-Scripts/blob/e611dae0c86af21aad2bf11100bcc0448aa16fd0/bin/A-Star-GUI/AStarGUI.py#L172-L181
thinkle/gourmet
8af29c8ded24528030e5ae2ea3461f61c1e5a575
gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py
python
PdfWriter.write_header
(self, txt)
Write a header. WARNING: If this is not followed by a call to our write_paragraph(...keep_with_next=False), the header won't necessarily be written.
Write a header.
[ "Write", "a", "header", "." ]
def write_header (self, txt): """Write a header. WARNING: If this is not followed by a call to our write_paragraph(...keep_with_next=False), the header won't necessarily be written. """ self.write_paragraph( txt, style=self.styleSheet['Heading1'], keep_with_next = True )
[ "def", "write_header", "(", "self", ",", "txt", ")", ":", "self", ".", "write_paragraph", "(", "txt", ",", "style", "=", "self", ".", "styleSheet", "[", "'Heading1'", "]", ",", "keep_with_next", "=", "True", ")" ]
https://github.com/thinkle/gourmet/blob/8af29c8ded24528030e5ae2ea3461f61c1e5a575/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py#L364-L374
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/mpmath/functions/factorials.py
python
rf
(ctx, x, n)
return ctx.gammaprod([x+n], [x])
[]
def rf(ctx, x, n): return ctx.gammaprod([x+n], [x])
[ "def", "rf", "(", "ctx", ",", "x", ",", "n", ")", ":", "return", "ctx", ".", "gammaprod", "(", "[", "x", "+", "n", "]", ",", "[", "x", "]", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/mpmath/functions/factorials.py#L65-L66
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/cpdp/v20190820/models.py
python
CreateInvoiceV2Request.__init__
(self)
r""" :param InvoicePlatformId: 开票平台ID。0:高灯,1:票易通 :type InvoicePlatformId: int :param TitleType: 抬头类型:1:个人/政府事业单位;2:企业 :type TitleType: int :param BuyerTitle: 购方名称 :type BuyerTitle: str :param OrderId: 业务开票号 :type OrderId: str :param AmountHasTax: 含税总金额(单位为分) :type AmountHasTax: int :param TaxAmount: 总税额(单位为分) :type TaxAmount: int :param AmountWithoutTax: 不含税总金额(单位为分)。InvoicePlatformId 为1时,传默认值-1 :type AmountWithoutTax: int :param SellerTaxpayerNum: 销方纳税人识别号 :type SellerTaxpayerNum: str :param SellerName: 销方名称。(不填默认读取商户注册时输入的信息) :type SellerName: str :param SellerAddress: 销方地址。(不填默认读取商户注册时输入的信息) :type SellerAddress: str :param SellerPhone: 销方电话。(不填默认读取商户注册时输入的信息) :type SellerPhone: str :param SellerBankName: 销方银行名称。(不填默认读取商户注册时输入的信息) :type SellerBankName: str :param SellerBankAccount: 销方银行账号。(不填默认读取商户注册时输入的信息) :type SellerBankAccount: str :param BuyerTaxpayerNum: 购方纳税人识别号(购方票面信息),若抬头类型为2时,必传 :type BuyerTaxpayerNum: str :param BuyerAddress: 购方地址。开具专用发票时必填 :type BuyerAddress: str :param BuyerBankName: 购方银行名称。开具专用发票时必填 :type BuyerBankName: str :param BuyerBankAccount: 购方银行账号。开具专用发票时必填 :type BuyerBankAccount: str :param BuyerPhone: 购方电话。开具专用发票时必填 :type BuyerPhone: str :param BuyerEmail: 收票人邮箱。若填入,会收到发票推送邮件 :type BuyerEmail: str :param TakerPhone: 收票人手机号。若填入,会收到发票推送短信 :type TakerPhone: str :param InvoiceType: 开票类型: 1:增值税专用发票; 2:增值税普通发票; 3:增值税电子发票; 4:增值税卷式发票; 5:区块链电子发票。 若该字段不填,或值不为1-5,则认为开具”增值税电子发票” :type InvoiceType: int :param CallbackUrl: 发票结果回传地址 :type CallbackUrl: str :param Drawer: 开票人姓名。(不填默认读取商户注册时输入的信息) :type Drawer: str :param Payee: 收款人姓名。(不填默认读取商户注册时输入的信息) :type Payee: str :param Checker: 复核人姓名。(不填默认读取商户注册时输入的信息) :type Checker: str :param TerminalCode: 税盘号 :type TerminalCode: str :param LevyMethod: 征收方式。开具差额征税发票时必填2。开具普通征税发票时为空 :type LevyMethod: str :param Deduction: 差额征税扣除额(单位为分) :type Deduction: int :param Remark: 备注(票面信息) :type Remark: str :param Items: 项目商品明细 :type Items: list of CreateInvoiceItem :param Profile: 接入环境。沙箱环境填sandbox。 :type Profile: str :param UndoPart: 撤销部分商品。0-不撤销,1-撤销 :type UndoPart: int :param OrderDate: 订单下单时间(格式 YYYYMMDD) :type OrderDate: str :param Discount: 订单级别折扣(单位为分) :type Discount: int :param StoreNo: 门店编码 :type StoreNo: str :param InvoiceChannel: 开票渠道。0:APP渠道,1:线下渠道,2:小程序渠道。不填默认为APP渠道 :type InvoiceChannel: int
r""" :param InvoicePlatformId: 开票平台ID。0:高灯,1:票易通 :type InvoicePlatformId: int :param TitleType: 抬头类型:1:个人/政府事业单位;2:企业 :type TitleType: int :param BuyerTitle: 购方名称 :type BuyerTitle: str :param OrderId: 业务开票号 :type OrderId: str :param AmountHasTax: 含税总金额(单位为分) :type AmountHasTax: int :param TaxAmount: 总税额(单位为分) :type TaxAmount: int :param AmountWithoutTax: 不含税总金额(单位为分)。InvoicePlatformId 为1时,传默认值-1 :type AmountWithoutTax: int :param SellerTaxpayerNum: 销方纳税人识别号 :type SellerTaxpayerNum: str :param SellerName: 销方名称。(不填默认读取商户注册时输入的信息) :type SellerName: str :param SellerAddress: 销方地址。(不填默认读取商户注册时输入的信息) :type SellerAddress: str :param SellerPhone: 销方电话。(不填默认读取商户注册时输入的信息) :type SellerPhone: str :param SellerBankName: 销方银行名称。(不填默认读取商户注册时输入的信息) :type SellerBankName: str :param SellerBankAccount: 销方银行账号。(不填默认读取商户注册时输入的信息) :type SellerBankAccount: str :param BuyerTaxpayerNum: 购方纳税人识别号(购方票面信息),若抬头类型为2时,必传 :type BuyerTaxpayerNum: str :param BuyerAddress: 购方地址。开具专用发票时必填 :type BuyerAddress: str :param BuyerBankName: 购方银行名称。开具专用发票时必填 :type BuyerBankName: str :param BuyerBankAccount: 购方银行账号。开具专用发票时必填 :type BuyerBankAccount: str :param BuyerPhone: 购方电话。开具专用发票时必填 :type BuyerPhone: str :param BuyerEmail: 收票人邮箱。若填入,会收到发票推送邮件 :type BuyerEmail: str :param TakerPhone: 收票人手机号。若填入,会收到发票推送短信 :type TakerPhone: str :param InvoiceType: 开票类型: 1:增值税专用发票; 2:增值税普通发票; 3:增值税电子发票; 4:增值税卷式发票; 5:区块链电子发票。 若该字段不填,或值不为1-5,则认为开具”增值税电子发票” :type InvoiceType: int :param CallbackUrl: 发票结果回传地址 :type CallbackUrl: str :param Drawer: 开票人姓名。(不填默认读取商户注册时输入的信息) :type Drawer: str :param Payee: 收款人姓名。(不填默认读取商户注册时输入的信息) :type Payee: str :param Checker: 复核人姓名。(不填默认读取商户注册时输入的信息) :type Checker: str :param TerminalCode: 税盘号 :type TerminalCode: str :param LevyMethod: 征收方式。开具差额征税发票时必填2。开具普通征税发票时为空 :type LevyMethod: str :param Deduction: 差额征税扣除额(单位为分) :type Deduction: int :param Remark: 备注(票面信息) :type Remark: str :param Items: 项目商品明细 :type Items: list of CreateInvoiceItem :param Profile: 接入环境。沙箱环境填sandbox。 :type Profile: str :param UndoPart: 撤销部分商品。0-不撤销,1-撤销 :type UndoPart: int :param OrderDate: 订单下单时间(格式 YYYYMMDD) :type OrderDate: str :param Discount: 订单级别折扣(单位为分) :type Discount: int :param StoreNo: 门店编码 :type StoreNo: str :param InvoiceChannel: 开票渠道。0:APP渠道,1:线下渠道,2:小程序渠道。不填默认为APP渠道 :type InvoiceChannel: int
[ "r", ":", "param", "InvoicePlatformId", ":", "开票平台ID。0:高灯,1:票易通", ":", "type", "InvoicePlatformId", ":", "int", ":", "param", "TitleType", ":", "抬头类型:1:个人", "/", "政府事业单位;2:企业", ":", "type", "TitleType", ":", "int", ":", "param", "BuyerTitle", ":", "购方名称", ":",...
def __init__(self): r""" :param InvoicePlatformId: 开票平台ID。0:高灯,1:票易通 :type InvoicePlatformId: int :param TitleType: 抬头类型:1:个人/政府事业单位;2:企业 :type TitleType: int :param BuyerTitle: 购方名称 :type BuyerTitle: str :param OrderId: 业务开票号 :type OrderId: str :param AmountHasTax: 含税总金额(单位为分) :type AmountHasTax: int :param TaxAmount: 总税额(单位为分) :type TaxAmount: int :param AmountWithoutTax: 不含税总金额(单位为分)。InvoicePlatformId 为1时,传默认值-1 :type AmountWithoutTax: int :param SellerTaxpayerNum: 销方纳税人识别号 :type SellerTaxpayerNum: str :param SellerName: 销方名称。(不填默认读取商户注册时输入的信息) :type SellerName: str :param SellerAddress: 销方地址。(不填默认读取商户注册时输入的信息) :type SellerAddress: str :param SellerPhone: 销方电话。(不填默认读取商户注册时输入的信息) :type SellerPhone: str :param SellerBankName: 销方银行名称。(不填默认读取商户注册时输入的信息) :type SellerBankName: str :param SellerBankAccount: 销方银行账号。(不填默认读取商户注册时输入的信息) :type SellerBankAccount: str :param BuyerTaxpayerNum: 购方纳税人识别号(购方票面信息),若抬头类型为2时,必传 :type BuyerTaxpayerNum: str :param BuyerAddress: 购方地址。开具专用发票时必填 :type BuyerAddress: str :param BuyerBankName: 购方银行名称。开具专用发票时必填 :type BuyerBankName: str :param BuyerBankAccount: 购方银行账号。开具专用发票时必填 :type BuyerBankAccount: str :param BuyerPhone: 购方电话。开具专用发票时必填 :type BuyerPhone: str :param BuyerEmail: 收票人邮箱。若填入,会收到发票推送邮件 :type BuyerEmail: str :param TakerPhone: 收票人手机号。若填入,会收到发票推送短信 :type TakerPhone: str :param InvoiceType: 开票类型: 1:增值税专用发票; 2:增值税普通发票; 3:增值税电子发票; 4:增值税卷式发票; 5:区块链电子发票。 若该字段不填,或值不为1-5,则认为开具”增值税电子发票” :type InvoiceType: int :param CallbackUrl: 发票结果回传地址 :type CallbackUrl: str :param Drawer: 开票人姓名。(不填默认读取商户注册时输入的信息) :type Drawer: str :param Payee: 收款人姓名。(不填默认读取商户注册时输入的信息) :type Payee: str :param Checker: 复核人姓名。(不填默认读取商户注册时输入的信息) :type Checker: str :param TerminalCode: 税盘号 :type TerminalCode: str :param LevyMethod: 征收方式。开具差额征税发票时必填2。开具普通征税发票时为空 :type LevyMethod: str :param Deduction: 差额征税扣除额(单位为分) :type Deduction: int :param Remark: 备注(票面信息) :type Remark: str :param Items: 项目商品明细 :type Items: list of CreateInvoiceItem :param Profile: 接入环境。沙箱环境填sandbox。 :type Profile: str :param UndoPart: 撤销部分商品。0-不撤销,1-撤销 :type UndoPart: int :param OrderDate: 订单下单时间(格式 YYYYMMDD) :type OrderDate: str :param Discount: 订单级别折扣(单位为分) :type Discount: int :param StoreNo: 门店编码 :type StoreNo: str :param InvoiceChannel: 开票渠道。0:APP渠道,1:线下渠道,2:小程序渠道。不填默认为APP渠道 :type InvoiceChannel: int """ self.InvoicePlatformId = None self.TitleType = None self.BuyerTitle = None self.OrderId = None self.AmountHasTax = None self.TaxAmount = None self.AmountWithoutTax = None self.SellerTaxpayerNum = None self.SellerName = None self.SellerAddress = None self.SellerPhone = None self.SellerBankName = None self.SellerBankAccount = None self.BuyerTaxpayerNum = None self.BuyerAddress = None self.BuyerBankName = None self.BuyerBankAccount = None self.BuyerPhone = None self.BuyerEmail = None self.TakerPhone = None self.InvoiceType = None self.CallbackUrl = None self.Drawer = None self.Payee = None self.Checker = None self.TerminalCode = None self.LevyMethod = None self.Deduction = None self.Remark = None self.Items = None self.Profile = None self.UndoPart = None self.OrderDate = None self.Discount = None self.StoreNo = None self.InvoiceChannel = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "InvoicePlatformId", "=", "None", "self", ".", "TitleType", "=", "None", "self", ".", "BuyerTitle", "=", "None", "self", ".", "OrderId", "=", "None", "self", ".", "AmountHasTax", "=", "None", "self",...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cpdp/v20190820/models.py#L4519-L4635
CTF-MissFeng/bayonet
360ffeb87025a85b08b4fa56f951936d38f2c109
tools/oneforall/modules/intelligence/threatminer.py
python
do
(domain)
类统一调用入口 :param str domain: 域名
类统一调用入口
[ "类统一调用入口" ]
def do(domain): # 统一入口名字 方便多线程调用 """ 类统一调用入口 :param str domain: 域名 """ query = ThreatMiner(domain) query.run()
[ "def", "do", "(", "domain", ")", ":", "# 统一入口名字 方便多线程调用", "query", "=", "ThreatMiner", "(", "domain", ")", "query", ".", "run", "(", ")" ]
https://github.com/CTF-MissFeng/bayonet/blob/360ffeb87025a85b08b4fa56f951936d38f2c109/tools/oneforall/modules/intelligence/threatminer.py#L39-L46
mozilla-services/autopush
87e273c4581af88478d9e2658aa51d8c82a6d630
autopush/main.py
python
AutopushMultiService.add_maybe_ssl
(self, port, factory, ssl_cf)
Add a Service from factory, optionally behind TLS
Add a Service from factory, optionally behind TLS
[ "Add", "a", "Service", "from", "factory", "optionally", "behind", "TLS" ]
def add_maybe_ssl(self, port, factory, ssl_cf): # type: (int, ServerFactory, Optional[Any]) -> None """Add a Service from factory, optionally behind TLS""" self.addService( SSLServer(port, factory, contextFactory=ssl_cf, reactor=reactor) if ssl_cf else TCPServer(port, factory, reactor=reactor) )
[ "def", "add_maybe_ssl", "(", "self", ",", "port", ",", "factory", ",", "ssl_cf", ")", ":", "# type: (int, ServerFactory, Optional[Any]) -> None", "self", ".", "addService", "(", "SSLServer", "(", "port", ",", "factory", ",", "contextFactory", "=", "ssl_cf", ",", ...
https://github.com/mozilla-services/autopush/blob/87e273c4581af88478d9e2658aa51d8c82a6d630/autopush/main.py#L82-L89
posativ/acrylamid
222e2eb7b33924138498ff8186dff9f0aeb78cea
acrylamid/tasks/ping.py
python
pingback
(src, dest, dryrun=False)
Makes a pingback request to dest on behalf of src, i.e. effectively saying to dest that "the page at src is linking to you".
Makes a pingback request to dest on behalf of src, i.e. effectively saying to dest that "the page at src is linking to you".
[ "Makes", "a", "pingback", "request", "to", "dest", "on", "behalf", "of", "src", "i", ".", "e", ".", "effectively", "saying", "to", "dest", "that", "the", "page", "at", "src", "is", "linking", "to", "you", "." ]
def pingback(src, dest, dryrun=False): """Makes a pingback request to dest on behalf of src, i.e. effectively saying to dest that "the page at src is linking to you".""" def search_link(content): match = re.search(b'<link rel="pingback" href="([^"]+)" ?/?>', content) return match and match.group(1) try: r = head(dest) except (URLError, HTTPError) as e: return try: server_url = r.info().get('X-Pingback', '') or search_link(r.read(512 * 1024)) if server_url: print("Pingback", blue(urlparse(server_url).netloc), end='') print("from", green(''.join(urlparse(src)[1:3])) + ".") if not dryrun: server = xmlrpc.client.ServerProxy(server_url) server.pingback.ping(src, dest) except xmlrpclib.Fault as e: log.warn("XML-RPC fault: %d (%s)", e.faultCode, e.faultString) except xmlrpc.client.ProtocolError as e: raise AcrylamidException(e.args[0])
[ "def", "pingback", "(", "src", ",", "dest", ",", "dryrun", "=", "False", ")", ":", "def", "search_link", "(", "content", ")", ":", "match", "=", "re", ".", "search", "(", "b'<link rel=\"pingback\" href=\"([^\"]+)\" ?/?>'", ",", "content", ")", "return", "mat...
https://github.com/posativ/acrylamid/blob/222e2eb7b33924138498ff8186dff9f0aeb78cea/acrylamid/tasks/ping.py#L54-L80
amimo/dcc
114326ab5a082a42c7728a375726489e4709ca29
androguard/core/bytecodes/dvm.py
python
MethodAnnotation.get_annotations_off
(self)
return self.annotations_off
Return the offset from the start of the file to the list of annotations for the method :rtype: int
Return the offset from the start of the file to the list of annotations for the method
[ "Return", "the", "offset", "from", "the", "start", "of", "the", "file", "to", "the", "list", "of", "annotations", "for", "the", "method" ]
def get_annotations_off(self): """ Return the offset from the start of the file to the list of annotations for the method :rtype: int """ return self.annotations_off
[ "def", "get_annotations_off", "(", "self", ")", ":", "return", "self", ".", "annotations_off" ]
https://github.com/amimo/dcc/blob/114326ab5a082a42c7728a375726489e4709ca29/androguard/core/bytecodes/dvm.py#L849-L855
bitcoin-core/HWI
6871946c2176f2f9777b6ac8f0614d96d99bfa0e
hwilib/hwwclient.py
python
HardwareWalletClient.wipe_device
(self)
Wipe the device. :return: Whether the wipe was successful :raises UnavailableActionError: if appropriate for the device.
Wipe the device.
[ "Wipe", "the", "device", "." ]
def wipe_device(self) -> bool: """ Wipe the device. :return: Whether the wipe was successful :raises UnavailableActionError: if appropriate for the device. """ raise NotImplementedError("The HardwareWalletClient base class " "does not implement this method")
[ "def", "wipe_device", "(", "self", ")", "->", "bool", ":", "raise", "NotImplementedError", "(", "\"The HardwareWalletClient base class \"", "\"does not implement this method\"", ")" ]
https://github.com/bitcoin-core/HWI/blob/6871946c2176f2f9777b6ac8f0614d96d99bfa0e/hwilib/hwwclient.py#L138-L146
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/Django-1.11.29/django/contrib/gis/db/models/fields.py
python
BaseSpatialField.__init__
(self, verbose_name=None, srid=4326, spatial_index=True, **kwargs)
The initialization function for base spatial fields. Takes the following as keyword arguments: srid: The spatial reference system identifier, an OGC standard. Defaults to 4326 (WGS84). spatial_index: Indicates whether to create a spatial index. Defaults to True. Set this instead of 'db_index' for geographic fields since index creation is different for geometry columns.
The initialization function for base spatial fields. Takes the following as keyword arguments:
[ "The", "initialization", "function", "for", "base", "spatial", "fields", ".", "Takes", "the", "following", "as", "keyword", "arguments", ":" ]
def __init__(self, verbose_name=None, srid=4326, spatial_index=True, **kwargs): """ The initialization function for base spatial fields. Takes the following as keyword arguments: srid: The spatial reference system identifier, an OGC standard. Defaults to 4326 (WGS84). spatial_index: Indicates whether to create a spatial index. Defaults to True. Set this instead of 'db_index' for geographic fields since index creation is different for geometry columns. """ # Setting the index flag with the value of the `spatial_index` keyword. self.spatial_index = spatial_index # Setting the SRID and getting the units. Unit information must be # easily available in the field instance for distance queries. self.srid = srid # Setting the verbose_name keyword argument with the positional # first parameter, so this works like normal fields. kwargs['verbose_name'] = verbose_name super(BaseSpatialField, self).__init__(**kwargs)
[ "def", "__init__", "(", "self", ",", "verbose_name", "=", "None", ",", "srid", "=", "4326", ",", "spatial_index", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# Setting the index flag with the value of the `spatial_index` keyword.", "self", ".", "spatial_index",...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/Django-1.11.29/django/contrib/gis/db/models/fields.py#L88-L114
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/hive/switch.py
python
HiveDevicePlug.available
(self)
return self.device["deviceData"].get("online")
Return if the device is available.
Return if the device is available.
[ "Return", "if", "the", "device", "is", "available", "." ]
def available(self): """Return if the device is available.""" return self.device["deviceData"].get("online")
[ "def", "available", "(", "self", ")", ":", "return", "self", ".", "device", "[", "\"deviceData\"", "]", ".", "get", "(", "\"online\"", ")" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/hive/switch.py#L61-L63
osmr/imgclsmob
f2993d3ce73a2f7ddba05da3891defb08547d504
pytorch/pytorchcv/models/polynet.py
python
poly_conv1x1
(in_channels, out_channels, num_blocks)
return PolyConv( in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0, num_blocks=num_blocks)
1x1 version of the PolyNet specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. num_blocks : int Number of blocks (BatchNorm layers).
1x1 version of the PolyNet specific convolution block.
[ "1x1", "version", "of", "the", "PolyNet", "specific", "convolution", "block", "." ]
def poly_conv1x1(in_channels, out_channels, num_blocks): """ 1x1 version of the PolyNet specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. num_blocks : int Number of blocks (BatchNorm layers). """ return PolyConv( in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0, num_blocks=num_blocks)
[ "def", "poly_conv1x1", "(", "in_channels", ",", "out_channels", ",", "num_blocks", ")", ":", "return", "PolyConv", "(", "in_channels", "=", "in_channels", ",", "out_channels", "=", "out_channels", ",", "kernel_size", "=", "1", ",", "stride", "=", "1", ",", "...
https://github.com/osmr/imgclsmob/blob/f2993d3ce73a2f7ddba05da3891defb08547d504/pytorch/pytorchcv/models/polynet.py#L64-L85
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/nifi/models/verify_config_update_step_dto.py
python
VerifyConfigUpdateStepDTO.complete
(self)
return self._complete
Gets the complete of this VerifyConfigUpdateStepDTO. Whether or not this step has completed :return: The complete of this VerifyConfigUpdateStepDTO. :rtype: bool
Gets the complete of this VerifyConfigUpdateStepDTO. Whether or not this step has completed
[ "Gets", "the", "complete", "of", "this", "VerifyConfigUpdateStepDTO", ".", "Whether", "or", "not", "this", "step", "has", "completed" ]
def complete(self): """ Gets the complete of this VerifyConfigUpdateStepDTO. Whether or not this step has completed :return: The complete of this VerifyConfigUpdateStepDTO. :rtype: bool """ return self._complete
[ "def", "complete", "(", "self", ")", ":", "return", "self", ".", "_complete" ]
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/verify_config_update_step_dto.py#L85-L93
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
lib-python/2.7/optparse.py
python
OptionParser.check_values
(self, values, args)
return (values, args)
check_values(values : Values, args : [string]) -> (values : Values, args : [string]) Check that the supplied option values and leftover arguments are valid. Returns the option values and leftover arguments (possibly adjusted, possibly completely new -- whatever you like). Default implementation just returns the passed-in values; subclasses may override as desired.
check_values(values : Values, args : [string]) -> (values : Values, args : [string])
[ "check_values", "(", "values", ":", "Values", "args", ":", "[", "string", "]", ")", "-", ">", "(", "values", ":", "Values", "args", ":", "[", "string", "]", ")" ]
def check_values(self, values, args): """ check_values(values : Values, args : [string]) -> (values : Values, args : [string]) Check that the supplied option values and leftover arguments are valid. Returns the option values and leftover arguments (possibly adjusted, possibly completely new -- whatever you like). Default implementation just returns the passed-in values; subclasses may override as desired. """ return (values, args)
[ "def", "check_values", "(", "self", ",", "values", ",", "args", ")", ":", "return", "(", "values", ",", "args", ")" ]
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/optparse.py#L1406-L1417
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Tools/pynche/ColorDB.py
python
ColorDB._extractrgb
(self, mo)
return [int(x) for x in mo.group('red', 'green', 'blue')]
[]
def _extractrgb(self, mo): return [int(x) for x in mo.group('red', 'green', 'blue')]
[ "def", "_extractrgb", "(", "self", ",", "mo", ")", ":", "return", "[", "int", "(", "x", ")", "for", "x", "in", "mo", ".", "group", "(", "'red'", ",", "'green'", ",", "'blue'", ")", "]" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Tools/pynche/ColorDB.py#L77-L78
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/xml/etree/ElementTree.py
python
Element.copy
(self)
return elem
Return copy of current element. This creates a shallow copy. Subelements will be shared with the original tree.
Return copy of current element.
[ "Return", "copy", "of", "current", "element", "." ]
def copy(self): """Return copy of current element. This creates a shallow copy. Subelements will be shared with the original tree. """ elem = self.makeelement(self.tag, self.attrib) elem.text = self.text elem.tail = self.tail elem[:] = self return elem
[ "def", "copy", "(", "self", ")", ":", "elem", "=", "self", ".", "makeelement", "(", "self", ".", "tag", ",", "self", ".", "attrib", ")", "elem", ".", "text", "=", "self", ".", "text", "elem", ".", "tail", "=", "self", ".", "tail", "elem", "[", ...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/xml/etree/ElementTree.py#L190-L201
digidotcom/xbee-python
0757f4be0017530c205175fbee8f9f61be9614d1
digi/xbee/filesystem.py
python
FileSystemElement.is_dir
(self)
return self._is_dir
Returns whether the file system element is a directory. Returns: Boolean: `True` for a directory, `False` otherwise.
Returns whether the file system element is a directory.
[ "Returns", "whether", "the", "file", "system", "element", "is", "a", "directory", "." ]
def is_dir(self): """ Returns whether the file system element is a directory. Returns: Boolean: `True` for a directory, `False` otherwise. """ return self._is_dir
[ "def", "is_dir", "(", "self", ")", ":", "return", "self", ".", "_is_dir" ]
https://github.com/digidotcom/xbee-python/blob/0757f4be0017530c205175fbee8f9f61be9614d1/digi/xbee/filesystem.py#L258-L265
18F/tock
fba78bd4e08717d9eaf4d7d126cb1b9ff24cfed0
tock/api/renderers.py
python
generate_csv
(rows, fields=None, **writer_options)
This generator yields text for each written row, and optionally writes a header row. We're using DictWriter.writerow() instead of writeheader() because the latter doesn't return a value.
This generator yields text for each written row, and optionally writes a header row. We're using DictWriter.writerow() instead of writeheader() because the latter doesn't return a value.
[ "This", "generator", "yields", "text", "for", "each", "written", "row", "and", "optionally", "writes", "a", "header", "row", ".", "We", "re", "using", "DictWriter", ".", "writerow", "()", "instead", "of", "writeheader", "()", "because", "the", "latter", "doe...
def generate_csv(rows, fields=None, **writer_options): """ This generator yields text for each written row, and optionally writes a header row. We're using DictWriter.writerow() instead of writeheader() because the latter doesn't return a value. """ buff = Echo() if fields: writer = csv.DictWriter(buff, fieldnames=fields, **writer_options) header = dict((field, field) for field in fields) yield writer.writerow(header) else: writer = csv.writer(buff, **writer_options) for row in rows: yield writer.writerow(row)
[ "def", "generate_csv", "(", "rows", ",", "fields", "=", "None", ",", "*", "*", "writer_options", ")", ":", "buff", "=", "Echo", "(", ")", "if", "fields", ":", "writer", "=", "csv", ".", "DictWriter", "(", "buff", ",", "fieldnames", "=", "fields", ","...
https://github.com/18F/tock/blob/fba78bd4e08717d9eaf4d7d126cb1b9ff24cfed0/tock/api/renderers.py#L43-L57
stevezheng23/xlnet_extension_tf
3efa272c4dcd126a0d3c79fb912b8cffae5ee572
run_squad.py
python
XLNetModelBuilder._generate_onehot_label
(self, input_data, input_depth)
return tf.one_hot(input_data, depth=input_depth, on_value=1.0, off_value=0.0, dtype=tf.float32)
Generate one-hot label
Generate one-hot label
[ "Generate", "one", "-", "hot", "label" ]
def _generate_onehot_label(self, input_data, input_depth): """Generate one-hot label""" return tf.one_hot(input_data, depth=input_depth, on_value=1.0, off_value=0.0, dtype=tf.float32)
[ "def", "_generate_onehot_label", "(", "self", ",", "input_data", ",", "input_depth", ")", ":", "return", "tf", ".", "one_hot", "(", "input_data", ",", "depth", "=", "input_depth", ",", "on_value", "=", "1.0", ",", "off_value", "=", "0.0", ",", "dtype", "="...
https://github.com/stevezheng23/xlnet_extension_tf/blob/3efa272c4dcd126a0d3c79fb912b8cffae5ee572/run_squad.py#L838-L842
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/site-packages/pip/_vendor/urllib3/fields.py
python
RequestField.render_headers
(self)
return u'\r\n'.join(lines)
Renders the headers for this request field.
Renders the headers for this request field.
[ "Renders", "the", "headers", "for", "this", "request", "field", "." ]
def render_headers(self): """ Renders the headers for this request field. """ lines = [] sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location'] for sort_key in sort_keys: if self.headers.get(sort_key, False): lines.append(u'%s: %s' % (sort_key, self.headers[sort_key])) for header_name, header_value in self.headers.items(): if header_name not in sort_keys: if header_value: lines.append(u'%s: %s' % (header_name, header_value)) lines.append(u'\r\n') return u'\r\n'.join(lines)
[ "def", "render_headers", "(", "self", ")", ":", "lines", "=", "[", "]", "sort_keys", "=", "[", "'Content-Disposition'", ",", "'Content-Type'", ",", "'Content-Location'", "]", "for", "sort_key", "in", "sort_keys", ":", "if", "self", ".", "headers", ".", "get"...
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/site-packages/pip/_vendor/urllib3/fields.py#L232-L249
chriso/gauged
cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976
gauged/structures/sparse_map.py
python
SparseMap.__repr__
(self)
return '\n'.join(rows)
[]
def __repr__(self): rows = [] for position, values in self.iteritems(): row = '[ %s ] = [%s]' % \ (position, ', '.join(str(v) for v in values)) rows.append(row) return '\n'.join(rows)
[ "def", "__repr__", "(", "self", ")", ":", "rows", "=", "[", "]", "for", "position", ",", "values", "in", "self", ".", "iteritems", "(", ")", ":", "row", "=", "'[ %s ] = [%s]'", "%", "(", "position", ",", "', '", ".", "join", "(", "str", "(", "v", ...
https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/structures/sparse_map.py#L190-L196
securisec/chepy
7abcc7ebcdab6583ffd89da11b5d6d419fd1b0dd
chepy/modules/dataformat.py
python
DataFormat.from_bytes
(self)
return self
Decodes bytes to string. Returns: Chepy: The Chepy object.
Decodes bytes to string.
[ "Decodes", "bytes", "to", "string", "." ]
def from_bytes(self) -> DataFormatT: """Decodes bytes to string. Returns: Chepy: The Chepy object. """ self.state = self._convert_to_bytes().decode() return self
[ "def", "from_bytes", "(", "self", ")", "->", "DataFormatT", ":", "self", ".", "state", "=", "self", ".", "_convert_to_bytes", "(", ")", ".", "decode", "(", ")", "return", "self" ]
https://github.com/securisec/chepy/blob/7abcc7ebcdab6583ffd89da11b5d6d419fd1b0dd/chepy/modules/dataformat.py#L337-L344
openembedded/bitbake
98407efc8c670abd71d3fa88ec3776ee9b5c38f3
lib/bb/fetch2/wget.py
python
Wget.download
(self, ud, d)
return True
Fetch urls
Fetch urls
[ "Fetch", "urls" ]
def download(self, ud, d): """Fetch urls""" fetchcmd = self.basecmd if 'downloadfilename' in ud.parm: localpath = os.path.join(d.getVar("DL_DIR"), ud.localfile) bb.utils.mkdirhier(os.path.dirname(localpath)) fetchcmd += " -O %s" % shlex.quote(localpath) if ud.user and ud.pswd: fetchcmd += " --auth-no-challenge" if ud.parm.get("redirectauth", "1") == "1": # An undocumented feature of wget is that if the # username/password are specified on the URI, wget will only # send the Authorization header to the first host and not to # any hosts that it is redirected to. With the increasing # usage of temporary AWS URLs, this difference now matters as # AWS will reject any request that has authentication both in # the query parameters (from the redirect) and in the # Authorization header. fetchcmd += " --user=%s --password=%s" % (ud.user, ud.pswd) uri = ud.url.split(";")[0] if os.path.exists(ud.localpath): # file exists, but we didnt complete it.. trying again.. fetchcmd += d.expand(" -c -P ${DL_DIR} '%s'" % uri) else: fetchcmd += d.expand(" -P ${DL_DIR} '%s'" % uri) self._runwget(ud, d, fetchcmd, False) # Sanity check since wget can pretend it succeed when it didn't # Also, this used to happen if sourceforge sent us to the mirror page if not os.path.exists(ud.localpath): raise FetchError("The fetch command returned success for url %s but %s doesn't exist?!" % (uri, ud.localpath), uri) if os.path.getsize(ud.localpath) == 0: os.remove(ud.localpath) raise FetchError("The fetch of %s resulted in a zero size file?! Deleting and failing since this isn't right." % (uri), uri) return True
[ "def", "download", "(", "self", ",", "ud", ",", "d", ")", ":", "fetchcmd", "=", "self", ".", "basecmd", "if", "'downloadfilename'", "in", "ud", ".", "parm", ":", "localpath", "=", "os", ".", "path", ".", "join", "(", "d", ".", "getVar", "(", "\"DL_...
https://github.com/openembedded/bitbake/blob/98407efc8c670abd71d3fa88ec3776ee9b5c38f3/lib/bb/fetch2/wget.py#L104-L145
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twill/twill/other_packages/_mechanize_dist/_clientcookie.py
python
CookiePolicy.domain_return_ok
(self, domain, request)
return True
Return false if cookies should not be returned, given cookie domain. This is here as an optimization, to remove the need for checking every cookie with a particular domain (which may involve reading many files). The default implementations of domain_return_ok and path_return_ok (return True) leave all the work to return_ok. If domain_return_ok returns true for the cookie domain, path_return_ok is called for the cookie path. Otherwise, path_return_ok and return_ok are never called for that cookie domain. If path_return_ok returns true, return_ok is called with the Cookie object itself for a full check. Otherwise, return_ok is never called for that cookie path. Note that domain_return_ok is called for every *cookie* domain, not just for the *request* domain. For example, the function might be called with both ".acme.com" and "www.acme.com" if the request domain is "www.acme.com". The same goes for path_return_ok. For argument documentation, see the docstring for return_ok.
Return false if cookies should not be returned, given cookie domain.
[ "Return", "false", "if", "cookies", "should", "not", "be", "returned", "given", "cookie", "domain", "." ]
def domain_return_ok(self, domain, request): """Return false if cookies should not be returned, given cookie domain. This is here as an optimization, to remove the need for checking every cookie with a particular domain (which may involve reading many files). The default implementations of domain_return_ok and path_return_ok (return True) leave all the work to return_ok. If domain_return_ok returns true for the cookie domain, path_return_ok is called for the cookie path. Otherwise, path_return_ok and return_ok are never called for that cookie domain. If path_return_ok returns true, return_ok is called with the Cookie object itself for a full check. Otherwise, return_ok is never called for that cookie path. Note that domain_return_ok is called for every *cookie* domain, not just for the *request* domain. For example, the function might be called with both ".acme.com" and "www.acme.com" if the request domain is "www.acme.com". The same goes for path_return_ok. For argument documentation, see the docstring for return_ok. """ return True
[ "def", "domain_return_ok", "(", "self", ",", "domain", ",", "request", ")", ":", "return", "True" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twill/twill/other_packages/_mechanize_dist/_clientcookie.py#L452-L474
skylander86/lambda-text-extractor
6da52d077a2fc571e38bfe29c33ae68f6443cd5a
lib-linux_x64/pptx/text/fonts.py
python
_NameTable._iter_names
(self)
Generate a key/value pair for each name in this table. The key is a (platform_id, name_id) 2-tuple and the value is the unicode text corresponding to that key.
Generate a key/value pair for each name in this table. The key is a (platform_id, name_id) 2-tuple and the value is the unicode text corresponding to that key.
[ "Generate", "a", "key", "/", "value", "pair", "for", "each", "name", "in", "this", "table", ".", "The", "key", "is", "a", "(", "platform_id", "name_id", ")", "2", "-", "tuple", "and", "the", "value", "is", "the", "unicode", "text", "corresponding", "to...
def _iter_names(self): """ Generate a key/value pair for each name in this table. The key is a (platform_id, name_id) 2-tuple and the value is the unicode text corresponding to that key. """ table_format, count, strings_offset = self._table_header table_bytes = self._table_bytes for idx in range(count): platform_id, name_id, name = self._read_name( table_bytes, idx, strings_offset ) if name is None: continue yield ((platform_id, name_id), name)
[ "def", "_iter_names", "(", "self", ")", ":", "table_format", ",", "count", ",", "strings_offset", "=", "self", ".", "_table_header", "table_bytes", "=", "self", ".", "_table_bytes", "for", "idx", "in", "range", "(", "count", ")", ":", "platform_id", ",", "...
https://github.com/skylander86/lambda-text-extractor/blob/6da52d077a2fc571e38bfe29c33ae68f6443cd5a/lib-linux_x64/pptx/text/fonts.py#L324-L339
GoSecure/pyrdp
abd8b8762b6d7fd0e49d4a927b529f892b412743
pyrdp/logging/observers.py
python
SecurityLogger.__init__
(self, log: LoggerAdapter)
[]
def __init__(self, log: LoggerAdapter): super().__init__(log) self.log = log
[ "def", "__init__", "(", "self", ",", "log", ":", "LoggerAdapter", ")", ":", "super", "(", ")", ".", "__init__", "(", "log", ")", "self", ".", "log", "=", "log" ]
https://github.com/GoSecure/pyrdp/blob/abd8b8762b6d7fd0e49d4a927b529f892b412743/pyrdp/logging/observers.py#L84-L86
owncloud/pyocclient
fe5c11edc92e1dc80d9683c3a16ec929749a5343
owncloud/owncloud.py
python
ShareInfo.get_share_with_displayname
(self)
return None
Returns the share recipient displayname. If share_with_displayname cannot be returned, None is returned instead :returns: name of the share recipient
Returns the share recipient displayname. If share_with_displayname cannot be returned, None is returned instead :returns: name of the share recipient
[ "Returns", "the", "share", "recipient", "displayname", ".", "If", "share_with_displayname", "cannot", "be", "returned", "None", "is", "returned", "instead", ":", "returns", ":", "name", "of", "the", "share", "recipient" ]
def get_share_with_displayname(self): """Returns the share recipient displayname. If share_with_displayname cannot be returned, None is returned instead :returns: name of the share recipient """ if 'share_with_displayname' in self.share_info: return self.share_info['share_with_displayname'] return None
[ "def", "get_share_with_displayname", "(", "self", ")", ":", "if", "'share_with_displayname'", "in", "self", ".", "share_info", ":", "return", "self", ".", "share_info", "[", "'share_with_displayname'", "]", "return", "None" ]
https://github.com/owncloud/pyocclient/blob/fe5c11edc92e1dc80d9683c3a16ec929749a5343/owncloud/owncloud.py#L103-L110
mars-project/mars
6afd7ed86db77f29cc9470485698ef192ecc6d33
mars/deploy/oscar/session.py
python
AbstractSession.as_default
(self)
return self
Mark current session as default session.
Mark current session as default session.
[ "Mark", "current", "session", "as", "default", "session", "." ]
def as_default(self) -> "AbstractSession": """ Mark current session as default session. """ AbstractSession._default = self return self
[ "def", "as_default", "(", "self", ")", "->", "\"AbstractSession\"", ":", "AbstractSession", ".", "_default", "=", "self", "return", "self" ]
https://github.com/mars-project/mars/blob/6afd7ed86db77f29cc9470485698ef192ecc6d33/mars/deploy/oscar/session.py#L181-L186
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/cinder/cinder/volume/drivers/netapp/api.py
python
NaServer.set_vfiler
(self, vfiler)
Set the vfiler tunneling.
Set the vfiler tunneling.
[ "Set", "the", "vfiler", "tunneling", "." ]
def set_vfiler(self, vfiler): """Set the vfiler tunneling.""" self._vfiler = vfiler
[ "def", "set_vfiler", "(", "self", ",", "vfiler", ")", ":", "self", ".", "_vfiler", "=", "vfiler" ]
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/cinder/cinder/volume/drivers/netapp/api.py#L161-L163
RittmanMead/md_to_conf
964f6089c49b0e30e3bd9f74e61332c3463109e4
md2conf.py
python
process_refs
(html)
return html
Process references :param html: html string :return: modified html string
Process references
[ "Process", "references" ]
def process_refs(html): """ Process references :param html: html string :return: modified html string """ refs = re.findall('\n(\[\^(\d)\].*)|<p>(\[\^(\d)\].*)', html) if refs: for ref in refs: if ref[0]: full_ref = ref[0].replace('</p>', '').replace('<p>', '') ref_id = ref[1] else: full_ref = ref[2] ref_id = ref[3] full_ref = full_ref.replace('</p>', '').replace('<p>', '') html = html.replace(full_ref, '') href = re.search('href="(.*?)"', full_ref).group(1) superscript = '<a id="test" href="%s"><sup>%s</sup></a>' % (href, ref_id) html = html.replace('[^%s]' % ref_id, superscript) return html
[ "def", "process_refs", "(", "html", ")", ":", "refs", "=", "re", ".", "findall", "(", "'\\n(\\[\\^(\\d)\\].*)|<p>(\\[\\^(\\d)\\].*)'", ",", "html", ")", "if", "refs", ":", "for", "ref", "in", "refs", ":", "if", "ref", "[", "0", "]", ":", "full_ref", "=",...
https://github.com/RittmanMead/md_to_conf/blob/964f6089c49b0e30e3bd9f74e61332c3463109e4/md2conf.py#L291-L317
CGATOxford/cgat
326aad4694bdfae8ddc194171bb5d73911243947
CGAT/scripts/snp2counts.py
python
CounterTranscripts.collectSplicingEffects
(self, snp, r, variant, reference_base, variant_seq, variant_bases)
return intron_effects, intron_changes
compute effects of a variant on a transcript. The effects are independent of any other variants. return a list of splicing effects.
compute effects of a variant on a transcript.
[ "compute", "effects", "of", "a", "variant", "on", "a", "transcript", "." ]
def collectSplicingEffects(self, snp, r, variant, reference_base, variant_seq, variant_bases): '''compute effects of a variant on a transcript. The effects are independent of any other variants. return a list of splicing effects. ''' intron_effects, intron_changes = [], [] # collect splicing effects only if r.nc_start is None: return intron_effects, intron_changes contig = snp.chromosome lvariant = len(variant_seq) intron_seq = self.mFasta.getSequence( contig, r.strand, r.intron_start, r.intron_end).upper() is_frameshift = len(intron_seq) < self.mMinIntronSize intron_name, intron_seq5, intron_seq3 = Genomics.GetIntronType( intron_seq) variant_introns = [] if (r.nc_start - r.intron_start) >= len(intron_seq5) and (r.intron_end - r.nc_end) >= len(intron_seq3): # intronic variant - ignore if not actually overlapping with splice # site pass else: E.debug("cds=%s, variant=%s" % (str(r), str(snp))) variant_intron_seq = list(intron_seq) x, y = r.nc_start - r.intron_start, r.nc_end - r.intron_start if variant.code == "=": # add SNP assert y - x == 1, "expect only single base substitutions" if intron_seq[x:y] != reference_base: raise ValueError("expected=%s, got=%s:%s:%s, snp=%s, cds=%s" % (reference_base, intron_seq[x - 3:x], intron_seq[x:y], intron_seq[y:y + 3], str(snp), str(r))) # record multiple substitutions for base in variant_bases: if base != reference_base: variant_intron_seq[x:y] = base variant_introns.append("".join(variant_intron_seq)) intron_effects.append(SpliceEffect._make((r.intron_id, reference_base, base))) elif variant.code == "+": # add insertion # If the insertion is at an intron/exon boundary # y -x = 1. In this case attribute this to a # coding sequence change and ignore if y - x == 2: # python inserts before the index variant_intron_seq[y:y] = list(variant_seq) variant_introns.append("".join(variant_intron_seq)) intron_effects.append(SpliceEffect._make((r.intron_id, "", variant_seq))) else: if y - x != 1: raise ValueError( "expected an insert of length 1 or 2, got %i for %s" % (y - x, str(snp))) elif variant.code == "-": # add deletion if x == 0 and y == r.intron_end - r.intron_start: # deletion covers full length of intron if r.intron_id < r.exon_id: # truncate from start if intron preceding exon xx, yy = 0, y - x else: # truncate from end if intron succceding exon xx, yy = lvariant - (y - x), lvariant elif x == 0: # deletion at 3' end of intron: truncate from the end xx, yy = lvariant - (y - x), lvariant else: xx, yy = 0, y - x if intron_seq[x:y] != variant_seq[xx:yy]: raise ValueError("expected=%s, got=%s:%s:%s, %i:%i, %i:%i, snp=%s, cds=%s" % (variant_seq[xx:yy], intron_seq[x - 3:x], intron_seq[x:y], intron_seq[y:y + 3], x, y, xx, yy, str(snp), str(r))) intron_effects.append(SpliceEffect._make((r.intron_id, variant_intron_seq[ x:y], ""))) del variant_intron_seq[x:y] variant_introns.append("".join(variant_intron_seq)) for variant_intron_seq in variant_introns: variant_intron_name, variant_intron_seq5, variant_intron_seq3 = Genomics.GetIntronType( variant_intron_seq) # if intron is a frameshift, the full intron seq is returned #if is_frameshift: reference_seq, variant_seq = intron_seq, variant_inseq intron_changes.append(SpliceChange._make((r.exon_id - 1, is_frameshift, intron_name, intron_seq5, intron_seq3, variant_intron_name, variant_intron_seq5, variant_intron_seq3))) return intron_effects, intron_changes
[ "def", "collectSplicingEffects", "(", "self", ",", "snp", ",", "r", ",", "variant", ",", "reference_base", ",", "variant_seq", ",", "variant_bases", ")", ":", "intron_effects", ",", "intron_changes", "=", "[", "]", ",", "[", "]", "# collect splicing effects only...
https://github.com/CGATOxford/cgat/blob/326aad4694bdfae8ddc194171bb5d73911243947/CGAT/scripts/snp2counts.py#L893-L1009
PaddlePaddle/Research
2da0bd6c72d60e9df403aff23a7802779561c4a1
KG/DuEE_baseline/bin/finetune/sequence_label.py
python
parse_crf_ret
(np_inputs, crf_decodes, np_lens)
return out
parse_crf_ret
parse_crf_ret
[ "parse_crf_ret" ]
def parse_crf_ret(np_inputs, crf_decodes, np_lens): """parse_crf_ret""" np_inputs = np.squeeze(np_inputs) out = [] for index in range(len(np_lens)): src_ids = [_id for _id in np_inputs[index][1:np_lens[index] - 1]] tag_ids = [_id for _id in crf_decodes[index][1:np_lens[index] - 1]] out.append((list(src_ids), list(tag_ids))) return out
[ "def", "parse_crf_ret", "(", "np_inputs", ",", "crf_decodes", ",", "np_lens", ")", ":", "np_inputs", "=", "np", ".", "squeeze", "(", "np_inputs", ")", "out", "=", "[", "]", "for", "index", "in", "range", "(", "len", "(", "np_lens", ")", ")", ":", "sr...
https://github.com/PaddlePaddle/Research/blob/2da0bd6c72d60e9df403aff23a7802779561c4a1/KG/DuEE_baseline/bin/finetune/sequence_label.py#L206-L214
censys/censys-python
9528f6b600215e59e1762bbe65216437c859f877
censys/cli/commands/hnri.py
python
CensysHNRI.risks_to_string
(self, high_risks: list, medium_risks: list)
return response
Risks to printable string. Args: high_risks (list): Lists of high risks. medium_risks (list): Lists of medium risks. Raises: CensysCLIException: No information/risks found. Returns: list: Printable objects for CLI.
Risks to printable string.
[ "Risks", "to", "printable", "string", "." ]
def risks_to_string(self, high_risks: list, medium_risks: list) -> List[Any]: """Risks to printable string. Args: high_risks (list): Lists of high risks. medium_risks (list): Lists of medium risks. Raises: CensysCLIException: No information/risks found. Returns: list: Printable objects for CLI. """ len_high_risk = len(high_risks) len_medium_risk = len(medium_risks) if len_high_risk + len_medium_risk == 0: raise CensysCLIException response: List[Any] = [] if len_high_risk > 0: response.append( self.make_risks_into_table( ":exclamation: High Risks Found", high_risks, ) ) else: response.append("You don't have any High Risks in your network\n") if len_medium_risk > 0: response.append( self.make_risks_into_table( ":grey_exclamation: Medium Risks Found", medium_risks, ) ) else: response.append("You don't have any Medium Risks in your network\n") return response
[ "def", "risks_to_string", "(", "self", ",", "high_risks", ":", "list", ",", "medium_risks", ":", "list", ")", "->", "List", "[", "Any", "]", ":", "len_high_risk", "=", "len", "(", "high_risks", ")", "len_medium_risk", "=", "len", "(", "medium_risks", ")", ...
https://github.com/censys/censys-python/blob/9528f6b600215e59e1762bbe65216437c859f877/censys/cli/commands/hnri.py#L80-L118
facebookresearch/mobile-vision
f40401a44e86bb3ba9c1b66e7700e15f96b880cb
mobile_cv/arch/utils/quantize_utils.py
python
swap_syncbn_to_bn
(module)
Replaces all instances of NaiveSyncBatchNorm in module with BatchNorm2d. This is needed for FX graph mode quantization, as the swaps and fusions assume the OSS BatchNorm2d. Note: this function is recursive, and it modifies module inplace.
Replaces all instances of NaiveSyncBatchNorm in module with BatchNorm2d. This is needed for FX graph mode quantization, as the swaps and fusions assume the OSS BatchNorm2d. Note: this function is recursive, and it modifies module inplace.
[ "Replaces", "all", "instances", "of", "NaiveSyncBatchNorm", "in", "module", "with", "BatchNorm2d", ".", "This", "is", "needed", "for", "FX", "graph", "mode", "quantization", "as", "the", "swaps", "and", "fusions", "assume", "the", "OSS", "BatchNorm2d", ".", "N...
def swap_syncbn_to_bn(module): """ Replaces all instances of NaiveSyncBatchNorm in module with BatchNorm2d. This is needed for FX graph mode quantization, as the swaps and fusions assume the OSS BatchNorm2d. Note: this function is recursive, and it modifies module inplace. """ _swap_bn(module, NaiveSyncBatchNorm, torch.nn.BatchNorm2d)
[ "def", "swap_syncbn_to_bn", "(", "module", ")", ":", "_swap_bn", "(", "module", ",", "NaiveSyncBatchNorm", ",", "torch", ".", "nn", ".", "BatchNorm2d", ")" ]
https://github.com/facebookresearch/mobile-vision/blob/f40401a44e86bb3ba9c1b66e7700e15f96b880cb/mobile_cv/arch/utils/quantize_utils.py#L407-L414
truenas/middleware
b11ec47d6340324f5a32287ffb4012e5d709b934
src/middlewared/middlewared/plugins/cloud_sync.py
python
CloudSyncService.query
(self, filters, options)
return tasks_or_task
Query all Cloud Sync Tasks with `query-filters` and `query-options`.
Query all Cloud Sync Tasks with `query-filters` and `query-options`.
[ "Query", "all", "Cloud", "Sync", "Tasks", "with", "query", "-", "filters", "and", "query", "-", "options", "." ]
async def query(self, filters, options): """ Query all Cloud Sync Tasks with `query-filters` and `query-options`. """ tasks_or_task = await super().query(filters, options) jobs = {} for j in await self.middleware.call("core.get_jobs", [('OR', [("method", "=", "cloudsync.sync"), ("method", "=", "cloudsync.restore")])], {"order_by": ["id"]}): try: task_id = int(j["arguments"][0]) except (IndexError, ValueError): continue if task_id in jobs and jobs[task_id]["state"] == "RUNNING": continue jobs[task_id] = j if isinstance(tasks_or_task, list): for task in tasks_or_task: task["job"] = jobs.get(task["id"]) else: tasks_or_task["job"] = jobs.get(tasks_or_task["id"]) return tasks_or_task
[ "async", "def", "query", "(", "self", ",", "filters", ",", "options", ")", ":", "tasks_or_task", "=", "await", "super", "(", ")", ".", "query", "(", "filters", ",", "options", ")", "jobs", "=", "{", "}", "for", "j", "in", "await", "self", ".", "mid...
https://github.com/truenas/middleware/blob/b11ec47d6340324f5a32287ffb4012e5d709b934/src/middlewared/middlewared/plugins/cloud_sync.py#L724-L750
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/util/_validators.py
python
_check_for_default_values
(fname, arg_val_dict, compat_args)
Check that the keys in `arg_val_dict` are mapped to their default values as specified in `compat_args`. Note that this function is to be called only when it has been checked that arg_val_dict.keys() is a subset of compat_args
Check that the keys in `arg_val_dict` are mapped to their default values as specified in `compat_args`.
[ "Check", "that", "the", "keys", "in", "arg_val_dict", "are", "mapped", "to", "their", "default", "values", "as", "specified", "in", "compat_args", "." ]
def _check_for_default_values(fname, arg_val_dict, compat_args): """ Check that the keys in `arg_val_dict` are mapped to their default values as specified in `compat_args`. Note that this function is to be called only when it has been checked that arg_val_dict.keys() is a subset of compat_args """ for key in arg_val_dict: # try checking equality directly with '=' operator, # as comparison may have been overridden for the left # hand object try: v1 = arg_val_dict[key] v2 = compat_args[key] # check for None-ness otherwise we could end up # comparing a numpy array vs None if (v1 is not None and v2 is None) or \ (v1 is None and v2 is not None): match = False else: match = (v1 == v2) if not is_bool(match): raise ValueError("'match' is not a boolean") # could not compare them directly, so try comparison # using the 'is' operator except ValueError: match = (arg_val_dict[key] is compat_args[key]) if not match: raise ValueError(("the '{arg}' parameter is not " "supported in the pandas " "implementation of {fname}()". format(fname=fname, arg=key)))
[ "def", "_check_for_default_values", "(", "fname", ",", "arg_val_dict", ",", "compat_args", ")", ":", "for", "key", "in", "arg_val_dict", ":", "# try checking equality directly with '=' operator,", "# as comparison may have been overridden for the left", "# hand object", "try", ...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/util/_validators.py#L32-L69
janpipek/physt
e7bce911532fac5f96e4e2d54881152e7e668a41
physt/io/util.py
python
create_from_dict
( data: dict, format_name: str, check_version: bool = True )
return klass.from_dict(data)
Once dict from source data is created, turn this into histogram. Parameters ---------- data : Parsed JSON-like tree. Returns ------- histogram : A histogram (of any dimensionality)
Once dict from source data is created, turn this into histogram.
[ "Once", "dict", "from", "source", "data", "is", "created", "turn", "this", "into", "histogram", "." ]
def create_from_dict( data: dict, format_name: str, check_version: bool = True ) -> Union[HistogramBase, HistogramCollection]: """Once dict from source data is created, turn this into histogram. Parameters ---------- data : Parsed JSON-like tree. Returns ------- histogram : A histogram (of any dimensionality) """ # Version if check_version: compatible_version = data["physt_compatible"] require_compatible_version(compatible_version, format_name) # Construction histogram_type = data["histogram_type"] if histogram_type == "histogram_collection": return HistogramCollection.from_dict(data) klass: Type[HistogramBase] = find_subclass(HistogramBase, histogram_type) return klass.from_dict(data)
[ "def", "create_from_dict", "(", "data", ":", "dict", ",", "format_name", ":", "str", ",", "check_version", ":", "bool", "=", "True", ")", "->", "Union", "[", "HistogramBase", ",", "HistogramCollection", "]", ":", "# Version", "if", "check_version", ":", "com...
https://github.com/janpipek/physt/blob/e7bce911532fac5f96e4e2d54881152e7e668a41/physt/io/util.py#L13-L36
Esri/solutions-geoprocessing-toolbox
dbebeb86d05f1fc2f9e4119196384a161b4f3c2e
griddedreferencegraphic/scripts/GRGTools.py
python
CreateGRGFromPoint.__init__
(self)
Point Target GRG constructor
Point Target GRG constructor
[ "Point", "Target", "GRG", "constructor" ]
def __init__(self): ''' Point Target GRG constructor ''' self.label = "Create GRG From Point" self.description = "Create a Gridded Reference Graphic (GRG) from an selected location on the map." self.category = "Gridded Reference Graphic"
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "label", "=", "\"Create GRG From Point\"", "self", ".", "description", "=", "\"Create a Gridded Reference Graphic (GRG) from an selected location on the map.\"", "self", ".", "category", "=", "\"Gridded Reference Graphic\...
https://github.com/Esri/solutions-geoprocessing-toolbox/blob/dbebeb86d05f1fc2f9e4119196384a161b4f3c2e/griddedreferencegraphic/scripts/GRGTools.py#L197-L201
hyperledger/sawtooth-core
704cd5837c21f53642c06ffc97ba7978a77940b0
rest_api/sawtooth_rest_api/route_handlers.py
python
RouteHandler._expand_transaction
(cls, transaction)
return cls._parse_header(TransactionHeader, transaction)
Deserializes a Transaction's header.
Deserializes a Transaction's header.
[ "Deserializes", "a", "Transaction", "s", "header", "." ]
def _expand_transaction(cls, transaction): """Deserializes a Transaction's header. """ return cls._parse_header(TransactionHeader, transaction)
[ "def", "_expand_transaction", "(", "cls", ",", "transaction", ")", ":", "return", "cls", ".", "_parse_header", "(", "TransactionHeader", ",", "transaction", ")" ]
https://github.com/hyperledger/sawtooth-core/blob/704cd5837c21f53642c06ffc97ba7978a77940b0/rest_api/sawtooth_rest_api/route_handlers.py#L882-L885
iiau-tracker/SPLT
a196e603798e9be969d9d985c087c11cad1cda43
lib/object_detection/utils/visualization_utils.py
python
draw_mask_on_image_array
(image, mask, color='red', alpha=0.7)
Draws mask on an image. Args: image: uint8 numpy array with shape (img_height, img_height, 3) mask: a float numpy array of shape (img_height, img_height) with values between 0 and 1 color: color to draw the keypoints with. Default is red. alpha: transparency value between 0 and 1. (default: 0.7) Raises: ValueError: On incorrect data type for image or masks.
Draws mask on an image.
[ "Draws", "mask", "on", "an", "image", "." ]
def draw_mask_on_image_array(image, mask, color='red', alpha=0.7): """Draws mask on an image. Args: image: uint8 numpy array with shape (img_height, img_height, 3) mask: a float numpy array of shape (img_height, img_height) with values between 0 and 1 color: color to draw the keypoints with. Default is red. alpha: transparency value between 0 and 1. (default: 0.7) Raises: ValueError: On incorrect data type for image or masks. """ if image.dtype != np.uint8: raise ValueError('`image` not of type np.uint8') if mask.dtype != np.float32: raise ValueError('`mask` not of type np.float32') if np.any(np.logical_or(mask > 1.0, mask < 0.0)): raise ValueError('`mask` elements should be in [0, 1]') rgb = ImageColor.getrgb(color) pil_image = Image.fromarray(image) solid_color = np.expand_dims( np.ones_like(mask), axis=2) * np.reshape(list(rgb), [1, 1, 3]) pil_solid_color = Image.fromarray(np.uint8(solid_color)).convert('RGBA') pil_mask = Image.fromarray(np.uint8(255.0*alpha*mask)).convert('L') pil_image = Image.composite(pil_solid_color, pil_image, pil_mask) np.copyto(image, np.array(pil_image.convert('RGB')))
[ "def", "draw_mask_on_image_array", "(", "image", ",", "mask", ",", "color", "=", "'red'", ",", "alpha", "=", "0.7", ")", ":", "if", "image", ".", "dtype", "!=", "np", ".", "uint8", ":", "raise", "ValueError", "(", "'`image` not of type np.uint8'", ")", "if...
https://github.com/iiau-tracker/SPLT/blob/a196e603798e9be969d9d985c087c11cad1cda43/lib/object_detection/utils/visualization_utils.py#L293-L320
rhinstaller/anaconda
63edc8680f1b05cbfe11bef28703acba808c5174
pyanaconda/ui/gui/spokes/advstorage/dasd.py
python
DASDDialog.process_result
(self, task_proxy)
Process the result of the task. :param task_proxy: a remove task proxy
Process the result of the task.
[ "Process", "the", "result", "of", "the", "task", "." ]
def process_result(self, task_proxy): """Process the result of the task. :param task_proxy: a remove task proxy """ # Stop the spinner. self._spinner.stop() self._cancelButton.set_sensitive(True) try: # Finish the task. task_proxy.Finish() except StorageDiscoveryError as e: # Discovery has failed, show the error. self._errorLabel.set_text(str(e)) self._deviceEntry.set_sensitive(True) self._conditionNotebook.set_current_page(2) else: # Discovery succeeded. self._update_devicetree = True self._okButton.set_sensitive(True) self._conditionNotebook.set_current_page(3)
[ "def", "process_result", "(", "self", ",", "task_proxy", ")", ":", "# Stop the spinner.", "self", ".", "_spinner", ".", "stop", "(", ")", "self", ".", "_cancelButton", ".", "set_sensitive", "(", "True", ")", "try", ":", "# Finish the task.", "task_proxy", ".",...
https://github.com/rhinstaller/anaconda/blob/63edc8680f1b05cbfe11bef28703acba808c5174/pyanaconda/ui/gui/spokes/advstorage/dasd.py#L92-L113
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/xml/dom/domreg.py
python
_good_enough
(dom, features)
return 1
_good_enough(dom, features) -> Return 1 if the dom offers the features
_good_enough(dom, features) -> Return 1 if the dom offers the features
[ "_good_enough", "(", "dom", "features", ")", "-", ">", "Return", "1", "if", "the", "dom", "offers", "the", "features" ]
def _good_enough(dom, features): "_good_enough(dom, features) -> Return 1 if the dom offers the features" for f,v in features: if not dom.hasFeature(f,v): return 0 return 1
[ "def", "_good_enough", "(", "dom", ",", "features", ")", ":", "for", "f", ",", "v", "in", "features", ":", "if", "not", "dom", ".", "hasFeature", "(", "f", ",", "v", ")", ":", "return", "0", "return", "1" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/xml/dom/domreg.py#L32-L37
google-research/fixmatch
d4985a158065947dba803e626ee9a6721709c570
imagenet/utils/ema.py
python
assign_ema_vars_from_initial_values
(ema_variables, initial_values)
Assign EMA variables from initial values.
Assign EMA variables from initial values.
[ "Assign", "EMA", "variables", "from", "initial", "values", "." ]
def assign_ema_vars_from_initial_values(ema_variables, initial_values): """Assign EMA variables from initial values.""" def _assign_one_var_fn(ema_var, value): ema_var.assign(value) def _assign_all_in_cross_replica_context_fn(strategy, ema_vars, values): for ema_var, value in zip(ema_vars, values): value = strategy.extended.reduce_to( tf.distribute.ReduceOp.MEAN, value, ema_var) if ema_var.trainable: strategy.extended.update(ema_var, _assign_one_var_fn, args=(value,)) else: _assign_one_var_fn(ema_var, value) replica_context = tf.distribute.get_replica_context() if replica_context: replica_context.merge_call(_assign_all_in_cross_replica_context_fn, args=(ema_variables, initial_values)) else: if tf.distribute.in_cross_replica_context(): _assign_all_in_cross_replica_context_fn(tf.distribute.get_strategy(), ema_variables, initial_values) else: for ema_var, value in zip(ema_variables, initial_values): _assign_one_var_fn(ema_var, value)
[ "def", "assign_ema_vars_from_initial_values", "(", "ema_variables", ",", "initial_values", ")", ":", "def", "_assign_one_var_fn", "(", "ema_var", ",", "value", ")", ":", "ema_var", ".", "assign", "(", "value", ")", "def", "_assign_all_in_cross_replica_context_fn", "("...
https://github.com/google-research/fixmatch/blob/d4985a158065947dba803e626ee9a6721709c570/imagenet/utils/ema.py#L19-L45
BillBillBillBill/Tickeys-linux
2df31b8665004c58a5d4ab05277f245267d96364
tickeys/kivy/input/motionevent.py
python
MotionEvent.apply_transform_2d
(self, transform)
Apply a transformation on x, y, z, px, py, pz, ox, oy, oz, dx, dy, dz
Apply a transformation on x, y, z, px, py, pz, ox, oy, oz, dx, dy, dz
[ "Apply", "a", "transformation", "on", "x", "y", "z", "px", "py", "pz", "ox", "oy", "oz", "dx", "dy", "dz" ]
def apply_transform_2d(self, transform): '''Apply a transformation on x, y, z, px, py, pz, ox, oy, oz, dx, dy, dz ''' self.x, self.y = self.pos = transform(self.x, self.y) self.px, self.py = transform(self.px, self.py) self.ox, self.oy = transform(self.ox, self.oy) self.dx = self.x - self.px self.dy = self.y - self.py
[ "def", "apply_transform_2d", "(", "self", ",", "transform", ")", ":", "self", ".", "x", ",", "self", ".", "y", "=", "self", ".", "pos", "=", "transform", "(", "self", ".", "x", ",", "self", ".", "y", ")", "self", ".", "px", ",", "self", ".", "p...
https://github.com/BillBillBillBill/Tickeys-linux/blob/2df31b8665004c58a5d4ab05277f245267d96364/tickeys/kivy/input/motionevent.py#L410-L418
kuangliu/pytorch-cifar
49b7aa97b0c12fe0d4054e670403a16b6b834ddd
models/dpn.py
python
Bottleneck.forward
(self, x)
return out
[]
def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = F.relu(self.bn2(self.conv2(out))) out = self.bn3(self.conv3(out)) x = self.shortcut(x) d = self.out_planes out = torch.cat([x[:,:d,:,:]+out[:,:d,:,:], x[:,d:,:,:], out[:,d:,:,:]], 1) out = F.relu(out) return out
[ "def", "forward", "(", "self", ",", "x", ")", ":", "out", "=", "F", ".", "relu", "(", "self", ".", "bn1", "(", "self", ".", "conv1", "(", "x", ")", ")", ")", "out", "=", "F", ".", "relu", "(", "self", ".", "bn2", "(", "self", ".", "conv2", ...
https://github.com/kuangliu/pytorch-cifar/blob/49b7aa97b0c12fe0d4054e670403a16b6b834ddd/models/dpn.py#L27-L35
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/orm/implementation/sqlalchemy/querybuilder/main.py
python
SqlaQueryBuilder.iterall
(self, data: QueryDictType, batch_size: Optional[int])
Return an iterator over all the results of a list of lists.
Return an iterator over all the results of a list of lists.
[ "Return", "an", "iterator", "over", "all", "the", "results", "of", "a", "list", "of", "lists", "." ]
def iterall(self, data: QueryDictType, batch_size: Optional[int]) -> Iterable[List[Any]]: """Return an iterator over all the results of a list of lists.""" with self.use_query(data) as query: stmt = query.statement.execution_options(yield_per=batch_size) for resultrow in self.get_session().execute(stmt): # we discard the first item of the result row, # which is what the query was initialised with # and not one of the requested projection (see self._build) resultrow = resultrow[1:] yield [self.to_backend(rowitem) for rowitem in resultrow]
[ "def", "iterall", "(", "self", ",", "data", ":", "QueryDictType", ",", "batch_size", ":", "Optional", "[", "int", "]", ")", "->", "Iterable", "[", "List", "[", "Any", "]", "]", ":", "with", "self", ".", "use_query", "(", "data", ")", "as", "query", ...
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/orm/implementation/sqlalchemy/querybuilder/main.py#L204-L215
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/idlelib/configHandler.py
python
IdleUserConfParser.RemoveFile
(self)
Removes the user config file from disk if it exists.
Removes the user config file from disk if it exists.
[ "Removes", "the", "user", "config", "file", "from", "disk", "if", "it", "exists", "." ]
def RemoveFile(self): """ Removes the user config file from disk if it exists. """ if os.path.exists(self.file): os.remove(self.file)
[ "def", "RemoveFile", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "file", ")", ":", "os", ".", "remove", "(", "self", ".", "file", ")" ]
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/idlelib/configHandler.py#L127-L132
ctxis/canape
5f0e03424577296bcc60c2008a60a98ec5307e4b
CANAPE.Scripting/Lib/StringIO.py
python
StringIO.getvalue
(self)
return self.buf
Retrieve the entire contents of the "file" at any time before the StringIO object's close() method is called. The StringIO object can accept either Unicode or 8-bit strings, but mixing the two may take some care. If both are used, 8-bit strings that cannot be interpreted as 7-bit ASCII (that use the 8th bit) will cause a UnicodeError to be raised when getvalue() is called.
Retrieve the entire contents of the "file" at any time before the StringIO object's close() method is called.
[ "Retrieve", "the", "entire", "contents", "of", "the", "file", "at", "any", "time", "before", "the", "StringIO", "object", "s", "close", "()", "method", "is", "called", "." ]
def getvalue(self): """ Retrieve the entire contents of the "file" at any time before the StringIO object's close() method is called. The StringIO object can accept either Unicode or 8-bit strings, but mixing the two may take some care. If both are used, 8-bit strings that cannot be interpreted as 7-bit ASCII (that use the 8th bit) will cause a UnicodeError to be raised when getvalue() is called. """ _complain_ifclosed(self.closed) if self.buflist: self.buf += ''.join(self.buflist) self.buflist = [] return self.buf
[ "def", "getvalue", "(", "self", ")", ":", "_complain_ifclosed", "(", "self", ".", "closed", ")", "if", "self", ".", "buflist", ":", "self", ".", "buf", "+=", "''", ".", "join", "(", "self", ".", "buflist", ")", "self", ".", "buflist", "=", "[", "]"...
https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/StringIO.py#L258-L273
yuanli2333/Teacher-free-Knowledge-Distillation
ca9f966ea13c06ba0d427d104002d7dd9442779b
model/shufflenetv2.py
python
ShuffleUnit.forward
(self, x)
return x
[]
def forward(self, x): if self.stride == 1 and self.out_channels == self.in_channels: shortcut, residual = channel_split(x, int(self.in_channels / 2)) else: shortcut = x residual = x shortcut = self.shortcut(shortcut) residual = self.residual(residual) x = torch.cat([shortcut, residual], dim=1) x = channel_shuffle(x, 2) return x
[ "def", "forward", "(", "self", ",", "x", ")", ":", "if", "self", ".", "stride", "==", "1", "and", "self", ".", "out_channels", "==", "self", ".", "in_channels", ":", "shortcut", ",", "residual", "=", "channel_split", "(", "x", ",", "int", "(", "self"...
https://github.com/yuanli2333/Teacher-free-Knowledge-Distillation/blob/ca9f966ea13c06ba0d427d104002d7dd9442779b/model/shufflenetv2.py#L82-L95
arrigonialberto86/deepar
8d37346c7aecc7e75bf27b551795f0f8ce19c1d6
deepar/model/layers.py
python
GaussianLayer.call
(self, x)
return [output_mu, output_sig_pos]
Do the layer computation.
Do the layer computation.
[ "Do", "the", "layer", "computation", "." ]
def call(self, x): """Do the layer computation.""" output_mu = K.dot(x, self.kernel_1) + self.bias_1 output_sig = K.dot(x, self.kernel_2) + self.bias_2 output_sig_pos = K.log(1 + K.exp(output_sig)) + 1e-06 return [output_mu, output_sig_pos]
[ "def", "call", "(", "self", ",", "x", ")", ":", "output_mu", "=", "K", ".", "dot", "(", "x", ",", "self", ".", "kernel_1", ")", "+", "self", ".", "bias_1", "output_sig", "=", "K", ".", "dot", "(", "x", ",", "self", ".", "kernel_2", ")", "+", ...
https://github.com/arrigonialberto86/deepar/blob/8d37346c7aecc7e75bf27b551795f0f8ce19c1d6/deepar/model/layers.py#L42-L47
devassistant/devassistant
2dbfeaa666a64127263664d18969c55d19ecc83e
devassistant/dapi/__init__.py
python
Dap._arevalid
(self, datatype)
return len(bad) == 0, bad
Checks if the given datatype is valid in meta (for array-like types)
Checks if the given datatype is valid in meta (for array-like types)
[ "Checks", "if", "the", "given", "datatype", "is", "valid", "in", "meta", "(", "for", "array", "-", "like", "types", ")" ]
def _arevalid(self, datatype): '''Checks if the given datatype is valid in meta (for array-like types)''' # Datatype not specified if datatype not in self.meta: return datatype in Dap._optional_meta, [] # Required datatype empty if datatype in self._required_meta and not self.meta[datatype]: return False, [] # Datatype not a list if not isinstance(self.meta[datatype], list): return False, [] # Duplicates found duplicates = set([x for x in self.meta[datatype] if self.meta[datatype].count(x) > 1]) if duplicates: return False, list(duplicates) if datatype in self._badmeta: return False, self._badmeta[datatype] else: return True, [] # Checking if all items are valid bad = [] for item in self.meta[datatype]: if not Dap._meta_valid[datatype].match(item): bad.append(item) return len(bad) == 0, bad
[ "def", "_arevalid", "(", "self", ",", "datatype", ")", ":", "# Datatype not specified", "if", "datatype", "not", "in", "self", ".", "meta", ":", "return", "datatype", "in", "Dap", ".", "_optional_meta", ",", "[", "]", "# Required datatype empty", "if", "dataty...
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L620-L649
Exodus-Privacy/exodus
0be3a255fda29218227ed3a214b5ef1f6c65631a
gpapi/googleplay.py
python
GooglePlayAPI.uploadDeviceConfig
(self)
Upload the device configuration of the fake device selected in the __init__ methodi to the google account.
Upload the device configuration of the fake device selected in the __init__ methodi to the google account.
[ "Upload", "the", "device", "configuration", "of", "the", "fake", "device", "selected", "in", "the", "__init__", "methodi", "to", "the", "google", "account", "." ]
def uploadDeviceConfig(self): """Upload the device configuration of the fake device selected in the __init__ methodi to the google account.""" upload = googleplay_pb2.UploadDeviceConfigRequest() upload.deviceConfiguration.CopyFrom(self.deviceBuilder.getDeviceConfig()) headers = self.getHeaders(upload_fields=True) stringRequest = upload.SerializeToString() response = self.session.post(UPLOAD_URL, data=stringRequest, headers=headers, verify=ssl_verify, timeout=60, proxies=self.proxies_config) response = googleplay_pb2.ResponseWrapper.FromString(response.content) try: if response.payload.HasField('uploadDeviceConfigResponse'): self.device_config_token = response.payload.uploadDeviceConfigResponse self.device_config_token = self.device_config_token.uploadDeviceConfigToken except ValueError: pass
[ "def", "uploadDeviceConfig", "(", "self", ")", ":", "upload", "=", "googleplay_pb2", ".", "UploadDeviceConfigRequest", "(", ")", "upload", ".", "deviceConfiguration", ".", "CopyFrom", "(", "self", ".", "deviceBuilder", ".", "getDeviceConfig", "(", ")", ")", "hea...
https://github.com/Exodus-Privacy/exodus/blob/0be3a255fda29218227ed3a214b5ef1f6c65631a/gpapi/googleplay.py#L210-L229
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/_cone.py
python
Cone.ysrc
(self)
return self["ysrc"]
Sets the source reference on Chart Studio Cloud for `y`. The 'ysrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str
Sets the source reference on Chart Studio Cloud for `y`. The 'ysrc' property must be specified as a string or as a plotly.grid_objs.Column object
[ "Sets", "the", "source", "reference", "on", "Chart", "Studio", "Cloud", "for", "y", ".", "The", "ysrc", "property", "must", "be", "specified", "as", "a", "string", "or", "as", "a", "plotly", ".", "grid_objs", ".", "Column", "object" ]
def ysrc(self): """ Sets the source reference on Chart Studio Cloud for `y`. The 'ysrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["ysrc"]
[ "def", "ysrc", "(", "self", ")", ":", "return", "self", "[", "\"ysrc\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/_cone.py#L1720-L1731
scottslowe/learning-tools
5a2abe30e269055d89f6ff4210f0f9f52d632680
traefik/tf-ans-swarm/ec2.py
python
Ec2Inventory.connect
(self, region)
return conn
create connection to api server
create connection to api server
[ "create", "connection", "to", "api", "server" ]
def connect(self, region): ''' create connection to api server''' if self.eucalyptus: conn = boto.connect_euca(host=self.eucalyptus_host, **self.credentials) conn.APIVersion = '2010-08-31' else: conn = self.connect_to_aws(ec2, region) return conn
[ "def", "connect", "(", "self", ",", "region", ")", ":", "if", "self", ".", "eucalyptus", ":", "conn", "=", "boto", ".", "connect_euca", "(", "host", "=", "self", ".", "eucalyptus_host", ",", "*", "*", "self", ".", "credentials", ")", "conn", ".", "AP...
https://github.com/scottslowe/learning-tools/blob/5a2abe30e269055d89f6ff4210f0f9f52d632680/traefik/tf-ans-swarm/ec2.py#L534-L541
mnemosyne-proj/mnemosyne
e39e364e56343437f2e485e0b06ca714de2f2d2e
mnemosyne/pyqt_ui/preview_cards_dlg.py
python
PreviewCardsDlg.__init__
(self, cards, tag_text, **kwds)
We need to provide tag_text explicitly, since it's possible that the cards have not yet been added to the database.
We need to provide tag_text explicitly, since it's possible that the cards have not yet been added to the database.
[ "We", "need", "to", "provide", "tag_text", "explicitly", "since", "it", "s", "possible", "that", "the", "cards", "have", "not", "yet", "been", "added", "to", "the", "database", "." ]
def __init__(self, cards, tag_text, **kwds): """We need to provide tag_text explicitly, since it's possible that the cards have not yet been added to the database. """ super().__init__(**kwds) self.setupUi(self) # Needed to make sure we can process e.g. escape keys. Not yet perfect # though, as clicking on the html widget eats those keys again. self.question.setFocusProxy(self) self.answer.setFocusProxy(self) QAOptimalSplit.setup(self) self.used_for_reviewing = False self.setWindowFlags(self.windowFlags() \ | QtCore.Qt.WindowMinMaxButtonsHint) self.setWindowFlags(self.windowFlags() \ & ~ QtCore.Qt.WindowContextHelpButtonHint) self.tag_text = tag_text self.cards = cards self.index = 0 state = self.config()["preview_cards_dlg_state"] if state: self.restoreGeometry(state) self.update_dialog()
[ "def", "__init__", "(", "self", ",", "cards", ",", "tag_text", ",", "*", "*", "kwds", ")", ":", "super", "(", ")", ".", "__init__", "(", "*", "*", "kwds", ")", "self", ".", "setupUi", "(", "self", ")", "# Needed to make sure we can process e.g. escape keys...
https://github.com/mnemosyne-proj/mnemosyne/blob/e39e364e56343437f2e485e0b06ca714de2f2d2e/mnemosyne/pyqt_ui/preview_cards_dlg.py#L20-L44
nosmokingbandit/Watcher3
0217e75158b563bdefc8e01c3be7620008cf3977
lib/requests/packages/urllib3/_collections.py
python
HTTPHeaderDict.getlist
(self, key)
Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist.
Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist.
[ "Returns", "a", "list", "of", "all", "the", "values", "for", "the", "named", "field", ".", "Returns", "an", "empty", "list", "if", "the", "key", "doesn", "t", "exist", "." ]
def getlist(self, key): """Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist.""" try: vals = self._container[key.lower()] except KeyError: return [] else: if isinstance(vals, tuple): return [vals[1]] else: return vals[1:]
[ "def", "getlist", "(", "self", ",", "key", ")", ":", "try", ":", "vals", "=", "self", ".", "_container", "[", "key", ".", "lower", "(", ")", "]", "except", "KeyError", ":", "return", "[", "]", "else", ":", "if", "isinstance", "(", "vals", ",", "t...
https://github.com/nosmokingbandit/Watcher3/blob/0217e75158b563bdefc8e01c3be7620008cf3977/lib/requests/packages/urllib3/_collections.py#L257-L268
psf/requests
fa1b0a367abc8488542f7ce7c02a3614ad8aa09d
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/psf/requests/blob/fa1b0a367abc8488542f7ce7c02a3614ad8aa09d/requests/cookies.py#L104-L109
graalvm/mx
29c0debab406352df3af246be2f8973be5db69ae
mx_proftool.py
python
CompiledCodeInfo.contains
(self, pc, timestamp=None)
return False
[]
def contains(self, pc, timestamp=None): if self.code_addr <= pc < self.code_end(): # early stubs have a timestamp that is after their actual creation time # so treat any code which was never unloaded as persistent. return self.generated or timestamp is None or self.contains_timestamp(timestamp) return False
[ "def", "contains", "(", "self", ",", "pc", ",", "timestamp", "=", "None", ")", ":", "if", "self", ".", "code_addr", "<=", "pc", "<", "self", ".", "code_end", "(", ")", ":", "# early stubs have a timestamp that is after their actual creation time", "# so treat any ...
https://github.com/graalvm/mx/blob/29c0debab406352df3af246be2f8973be5db69ae/mx_proftool.py#L622-L627
wmayner/pyphi
299fccd4a8152dcfa4bb989d7d739e245343b0a5
pyphi/subsystem.py
python
Subsystem.expand_repertoire
(self, direction, repertoire, new_purview=None)
return distribution.normalize(expanded_repertoire)
Distribute an effect repertoire over a larger purview. Args: direction (Direction): |CAUSE| or |EFFECT|. repertoire (np.ndarray): The repertoire to expand. Keyword Args: new_purview (tuple[int]): The new purview to expand the repertoire over. If ``None`` (the default), the new purview is the entire network. Returns: np.ndarray: A distribution over the new purview, where probability is spread out over the new nodes. Raises: ValueError: If the expanded purview doesn't contain the original purview.
Distribute an effect repertoire over a larger purview.
[ "Distribute", "an", "effect", "repertoire", "over", "a", "larger", "purview", "." ]
def expand_repertoire(self, direction, repertoire, new_purview=None): """Distribute an effect repertoire over a larger purview. Args: direction (Direction): |CAUSE| or |EFFECT|. repertoire (np.ndarray): The repertoire to expand. Keyword Args: new_purview (tuple[int]): The new purview to expand the repertoire over. If ``None`` (the default), the new purview is the entire network. Returns: np.ndarray: A distribution over the new purview, where probability is spread out over the new nodes. Raises: ValueError: If the expanded purview doesn't contain the original purview. """ if repertoire is None: return None purview = distribution.purview(repertoire) if new_purview is None: new_purview = self.node_indices # full subsystem if not set(purview).issubset(new_purview): raise ValueError("Expanded purview must contain original purview.") # Get the unconstrained repertoire over the other nodes in the network. non_purview_indices = tuple(set(new_purview) - set(purview)) uc = self.unconstrained_repertoire(direction, non_purview_indices) # Multiply the given repertoire by the unconstrained one to get a # distribution over all the nodes in the network. expanded_repertoire = repertoire * uc return distribution.normalize(expanded_repertoire)
[ "def", "expand_repertoire", "(", "self", ",", "direction", ",", "repertoire", ",", "new_purview", "=", "None", ")", ":", "if", "repertoire", "is", "None", ":", "return", "None", "purview", "=", "distribution", ".", "purview", "(", "repertoire", ")", "if", ...
https://github.com/wmayner/pyphi/blob/299fccd4a8152dcfa4bb989d7d739e245343b0a5/pyphi/subsystem.py#L450-L488
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/multiprocessing/connection.py
python
XmlListener.accept
(self)
return ConnectionWrapper(obj, _xml_dumps, _xml_loads)
[]
def accept(self): global xmlrpclib import xmlrpclib obj = Listener.accept(self) return ConnectionWrapper(obj, _xml_dumps, _xml_loads)
[ "def", "accept", "(", "self", ")", ":", "global", "xmlrpclib", "import", "xmlrpclib", "obj", "=", "Listener", ".", "accept", "(", "self", ")", "return", "ConnectionWrapper", "(", "obj", ",", "_xml_dumps", ",", "_xml_loads", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/multiprocessing/connection.py#L464-L468
Qiskit/qiskit-terra
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
qiskit/opflow/converters/pauli_basis_change.py
python
PauliBasisChange.__init__
( self, destination_basis: Optional[Union[Pauli, PauliOp]] = None, traverse: bool = True, replacement_fn: Optional[Callable] = None, )
Args: destination_basis: The Pauli into the basis of which the operators will be converted. If None is specified, the destination basis will be the diagonal ({I, Z}^n) basis requiring only single qubit rotations. traverse: If true and the operator passed into convert contains sub-Operators, such as ListOp, traverse the Operator and apply the conversion to every applicable sub-operator within it. replacement_fn: A function specifying what to do with the basis-change ``CircuitOp`` and destination ``PauliOp`` when converting an Operator and replacing converted values. By default, this will be 1) For StateFns (or Measurements): replacing the StateFn with ComposedOp(StateFn(d), c) where c is the conversion circuit and d is the destination Pauli, so the overall beginning and ending operators are equivalent. 2) For non-StateFn Operators: replacing the origin p with c·d·c†, where c is the conversion circuit and d is the destination, so the overall beginning and ending operators are equivalent.
Args: destination_basis: The Pauli into the basis of which the operators will be converted. If None is specified, the destination basis will be the diagonal ({I, Z}^n) basis requiring only single qubit rotations. traverse: If true and the operator passed into convert contains sub-Operators, such as ListOp, traverse the Operator and apply the conversion to every applicable sub-operator within it. replacement_fn: A function specifying what to do with the basis-change ``CircuitOp`` and destination ``PauliOp`` when converting an Operator and replacing converted values. By default, this will be
[ "Args", ":", "destination_basis", ":", "The", "Pauli", "into", "the", "basis", "of", "which", "the", "operators", "will", "be", "converted", ".", "If", "None", "is", "specified", "the", "destination", "basis", "will", "be", "the", "diagonal", "(", "{", "I"...
def __init__( self, destination_basis: Optional[Union[Pauli, PauliOp]] = None, traverse: bool = True, replacement_fn: Optional[Callable] = None, ) -> None: """ Args: destination_basis: The Pauli into the basis of which the operators will be converted. If None is specified, the destination basis will be the diagonal ({I, Z}^n) basis requiring only single qubit rotations. traverse: If true and the operator passed into convert contains sub-Operators, such as ListOp, traverse the Operator and apply the conversion to every applicable sub-operator within it. replacement_fn: A function specifying what to do with the basis-change ``CircuitOp`` and destination ``PauliOp`` when converting an Operator and replacing converted values. By default, this will be 1) For StateFns (or Measurements): replacing the StateFn with ComposedOp(StateFn(d), c) where c is the conversion circuit and d is the destination Pauli, so the overall beginning and ending operators are equivalent. 2) For non-StateFn Operators: replacing the origin p with c·d·c†, where c is the conversion circuit and d is the destination, so the overall beginning and ending operators are equivalent. """ if destination_basis is not None: self.destination = destination_basis # type: ignore else: self._destination = None # type: Optional[PauliOp] self._traverse = traverse self._replacement_fn = replacement_fn or PauliBasisChange.operator_replacement_fn
[ "def", "__init__", "(", "self", ",", "destination_basis", ":", "Optional", "[", "Union", "[", "Pauli", ",", "PauliOp", "]", "]", "=", "None", ",", "traverse", ":", "bool", "=", "True", ",", "replacement_fn", ":", "Optional", "[", "Callable", "]", "=", ...
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/opflow/converters/pauli_basis_change.py#L58-L91
tensorflow/model-optimization
b278157b17d073686de3ae67ffd6e820ae862c45
tensorflow_model_optimization/python/core/sparsity/keras/pruning_utils.py
python
m_by_n_sparsity_mask_prepare
(mask, weights_shape)
return prepared_mask
Reshape and permute sparsity mask, so that it match original weights data format. This is a m_by_n sparsity helper function. Args: mask: A 2-D tensor. Must be rank 2 or 4. weights_shape: shape of weights Returns: A sparsity mask that matches weights data format. Raises: ValueError: if the input tensor is not rank 2 or 4. InvalidArgumentError: if number of elements mismatch between mask and weights, if shape of prepared mask mismatch shape of weights.
Reshape and permute sparsity mask, so that it match original weights data format.
[ "Reshape", "and", "permute", "sparsity", "mask", "so", "that", "it", "match", "original", "weights", "data", "format", "." ]
def m_by_n_sparsity_mask_prepare(mask, weights_shape): """Reshape and permute sparsity mask, so that it match original weights data format. This is a m_by_n sparsity helper function. Args: mask: A 2-D tensor. Must be rank 2 or 4. weights_shape: shape of weights Returns: A sparsity mask that matches weights data format. Raises: ValueError: if the input tensor is not rank 2 or 4. InvalidArgumentError: if number of elements mismatch between mask and weights, if shape of prepared mask mismatch shape of weights. """ tf.debugging.assert_equal( tf.size(mask), tf.reduce_prod(weights_shape), message="number of elements mismatch between mask and weights.", ) if mask.shape.rank != 2: raise ValueError(f"rank of mask(rank:{mask.shape.rank}) should be 2.") if weights_shape.rank == 2: prepared_mask = tf.transpose(mask) elif weights_shape.rank == 4: reshaped_mask = tf.reshape( mask, [ weights_shape[-1], weights_shape[0], weights_shape[1], weights_shape[2] ], ) prepared_mask = tf.transpose(reshaped_mask, perm=[1, 2, 3, 0]) else: raise ValueError( f"weight tensor with shape: {weights_shape} is not supported.") tf.debugging.assert_equal( prepared_mask.shape, weights_shape, message="shape of prepared mask mismatch shape of weights.") return prepared_mask
[ "def", "m_by_n_sparsity_mask_prepare", "(", "mask", ",", "weights_shape", ")", ":", "tf", ".", "debugging", ".", "assert_equal", "(", "tf", ".", "size", "(", "mask", ")", ",", "tf", ".", "reduce_prod", "(", "weights_shape", ")", ",", "message", "=", "\"num...
https://github.com/tensorflow/model-optimization/blob/b278157b17d073686de3ae67ffd6e820ae862c45/tensorflow_model_optimization/python/core/sparsity/keras/pruning_utils.py#L233-L281
gusibi/python-weixin
db997152673b205966146b6aab304ba6e4755bec
weixin/pay.py
python
WeixinEnterprisePayQuery.gettransferinfo
(self, partner_trade_no)
return self.make_request(method, url, kwargs)
企业付款查询 https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_3 :param partner_trade_no: 商户订单号,默认自动生成 :return: 返回的结果数据
企业付款查询 https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_3 :param partner_trade_no: 商户订单号,默认自动生成 :return: 返回的结果数据
[ "企业付款查询", "https", ":", "//", "pay", ".", "weixin", ".", "qq", ".", "com", "/", "wiki", "/", "doc", "/", "api", "/", "tools", "/", "mch_pay", ".", "php?chapter", "=", "14_3", ":", "param", "partner_trade_no", ":", "商户订单号,默认自动生成", ":", "return", ":", ...
def gettransferinfo(self, partner_trade_no): """ 企业付款查询 https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_3 :param partner_trade_no: 商户订单号,默认自动生成 :return: 返回的结果数据 """ path = 'mmpaymkttransfers/gettransferinfo' params = dict(partner_trade_no=partner_trade_no) method, url, kwargs = self.prepare_request('POST', path, params) return self.make_request(method, url, kwargs)
[ "def", "gettransferinfo", "(", "self", ",", "partner_trade_no", ")", ":", "path", "=", "'mmpaymkttransfers/gettransferinfo'", "params", "=", "dict", "(", "partner_trade_no", "=", "partner_trade_no", ")", "method", ",", "url", ",", "kwargs", "=", "self", ".", "pr...
https://github.com/gusibi/python-weixin/blob/db997152673b205966146b6aab304ba6e4755bec/weixin/pay.py#L563-L573
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/histogram2d/_ybins.py
python
YBins.end
(self)
return self["end"]
Sets the end value for the y axis bins. The last bin may not end exactly at this value, we increment the bin edge by `size` from `start` until we reach or exceed `end`. Defaults to the maximum data value. Like `start`, for dates use a date string, and for category data `end` is based on the category serial numbers. The 'end' property accepts values of any type Returns ------- Any
Sets the end value for the y axis bins. The last bin may not end exactly at this value, we increment the bin edge by `size` from `start` until we reach or exceed `end`. Defaults to the maximum data value. Like `start`, for dates use a date string, and for category data `end` is based on the category serial numbers. The 'end' property accepts values of any type
[ "Sets", "the", "end", "value", "for", "the", "y", "axis", "bins", ".", "The", "last", "bin", "may", "not", "end", "exactly", "at", "this", "value", "we", "increment", "the", "bin", "edge", "by", "size", "from", "start", "until", "we", "reach", "or", ...
def end(self): """ Sets the end value for the y axis bins. The last bin may not end exactly at this value, we increment the bin edge by `size` from `start` until we reach or exceed `end`. Defaults to the maximum data value. Like `start`, for dates use a date string, and for category data `end` is based on the category serial numbers. The 'end' property accepts values of any type Returns ------- Any """ return self["end"]
[ "def", "end", "(", "self", ")", ":", "return", "self", "[", "\"end\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/histogram2d/_ybins.py#L16-L31
scikit-hep/scikit-hep
506149b352eeb2291f24aef3f40691b5f6be2da7
skhep/math/geometry.py
python
Point3D.__ne__
(self, another)
return self._vct != another._vct
Non-equality of two points. Example ------- >>> p1 = ... >>> p2 = ... >>> print p1 != p2
Non-equality of two points.
[ "Non", "-", "equality", "of", "two", "points", "." ]
def __ne__(self, another): """Non-equality of two points. Example ------- >>> p1 = ... >>> p2 = ... >>> print p1 != p2 """ return self._vct != another._vct
[ "def", "__ne__", "(", "self", ",", "another", ")", ":", "return", "self", ".", "_vct", "!=", "another", ".", "_vct" ]
https://github.com/scikit-hep/scikit-hep/blob/506149b352eeb2291f24aef3f40691b5f6be2da7/skhep/math/geometry.py#L206-L215
dropbox/pyannotate
a7a46f394f0ba91a1b5fbf657e2393af542969ae
pyannotate_runtime/collect_types.py
python
pause
()
return stop()
Deprecated, replaced by stop().
Deprecated, replaced by stop().
[ "Deprecated", "replaced", "by", "stop", "()", "." ]
def pause(): # type: () -> None """ Deprecated, replaced by stop(). """ # In the future, do: warnings.warn("Function pause() has been replaced by start().", PendingDeprecationWarning) return stop()
[ "def", "pause", "(", ")", ":", "# type: () -> None", "# In the future, do: warnings.warn(\"Function pause() has been replaced by start().\", PendingDeprecationWarning)", "return", "stop", "(", ")" ]
https://github.com/dropbox/pyannotate/blob/a7a46f394f0ba91a1b5fbf657e2393af542969ae/pyannotate_runtime/collect_types.py#L751-L757
mandiant/capa
c0851fc643793c012f5dd764482133c25c3216c8
capa/ida/plugin/item.py
python
CapaExplorerRuleItem.__init__
(self, parent, name, namespace, count, source, can_check=True)
initialize item @param parent: parent node @param name: rule name @param namespace: rule namespace @param count: number of match for this rule @param source: rule source (tooltip)
initialize item
[ "initialize", "item" ]
def __init__(self, parent, name, namespace, count, source, can_check=True): """initialize item @param parent: parent node @param name: rule name @param namespace: rule namespace @param count: number of match for this rule @param source: rule source (tooltip) """ display = self.fmt % (name, count) if count > 1 else name super(CapaExplorerRuleItem, self).__init__(parent, [display, "", namespace], can_check) self._source = source
[ "def", "__init__", "(", "self", ",", "parent", ",", "name", ",", "namespace", ",", "count", ",", "source", ",", "can_check", "=", "True", ")", ":", "display", "=", "self", ".", "fmt", "%", "(", "name", ",", "count", ")", "if", "count", ">", "1", ...
https://github.com/mandiant/capa/blob/c0851fc643793c012f5dd764482133c25c3216c8/capa/ida/plugin/item.py#L170-L181
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/vendor/pyparsing.py
python
ParseElementEnhance.ignore
(self, other)
return self
[]
def ignore(self, other): if isinstance(other, Suppress): if other not in self.ignoreExprs: super(ParseElementEnhance, self).ignore(other) if self.expr is not None: self.expr.ignore(self.ignoreExprs[-1]) else: super(ParseElementEnhance, self).ignore(other) if self.expr is not None: self.expr.ignore(self.ignoreExprs[-1]) return self
[ "def", "ignore", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "Suppress", ")", ":", "if", "other", "not", "in", "self", ".", "ignoreExprs", ":", "super", "(", "ParseElementEnhance", ",", "self", ")", ".", "ignore", "(", ...
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/pyparsing.py#L4473-L4483
HymanLiuTS/flaskTs
286648286976e85d9b9a5873632331efcafe0b21
flasky/lib/python2.7/site-packages/requests/adapters.py
python
HTTPAdapter.proxy_manager_for
(self, proxy, **proxy_kwargs)
return manager
Return urllib3 ProxyManager for the given proxy. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The proxy to return a urllib3 ProxyManager for. :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager. :returns: ProxyManager :rtype: requests.packages.urllib3.ProxyManager
Return urllib3 ProxyManager for the given proxy.
[ "Return", "urllib3", "ProxyManager", "for", "the", "given", "proxy", "." ]
def proxy_manager_for(self, proxy, **proxy_kwargs): """Return urllib3 ProxyManager for the given proxy. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The proxy to return a urllib3 ProxyManager for. :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager. :returns: ProxyManager :rtype: requests.packages.urllib3.ProxyManager """ if proxy in self.proxy_manager: manager = self.proxy_manager[proxy] elif proxy.lower().startswith('socks'): username, password = get_auth_from_url(proxy) manager = self.proxy_manager[proxy] = SOCKSProxyManager( proxy, username=username, password=password, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs ) else: proxy_headers = self.proxy_headers(proxy) manager = self.proxy_manager[proxy] = proxy_from_url( proxy, proxy_headers=proxy_headers, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs) return manager
[ "def", "proxy_manager_for", "(", "self", ",", "proxy", ",", "*", "*", "proxy_kwargs", ")", ":", "if", "proxy", "in", "self", ".", "proxy_manager", ":", "manager", "=", "self", ".", "proxy_manager", "[", "proxy", "]", "elif", "proxy", ".", "lower", "(", ...
https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/requests/adapters.py#L161-L196
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/distutils/msvc9compiler.py
python
MSVCCompiler._remove_visual_c_ref
(self, manifest_file)
[]
def _remove_visual_c_ref(self, manifest_file): try: # Remove references to the Visual C runtime, so they will # fall through to the Visual C dependency of Python.exe. # This way, when installed for a restricted user (e.g. # runtimes are not in WinSxS folder, but in Python's own # folder), the runtimes do not need to be in every folder # with .pyd's. # Returns either the filename of the modified manifest or # None if no manifest should be embedded. manifest_f = open(manifest_file) try: manifest_buf = manifest_f.read() finally: manifest_f.close() pattern = re.compile( r"""<assemblyIdentity.*?name=("|')Microsoft\."""\ r"""VC\d{2}\.CRT("|').*?(/>|</assemblyIdentity>)""", re.DOTALL) manifest_buf = re.sub(pattern, "", manifest_buf) pattern = "<dependentAssembly>\s*</dependentAssembly>" manifest_buf = re.sub(pattern, "", manifest_buf) # Now see if any other assemblies are referenced - if not, we # don't want a manifest embedded. pattern = re.compile( r"""<assemblyIdentity.*?name=(?:"|')(.+?)(?:"|')""" r""".*?(?:/>|</assemblyIdentity>)""", re.DOTALL) if re.search(pattern, manifest_buf) is None: return None manifest_f = open(manifest_file, 'w') try: manifest_f.write(manifest_buf) return manifest_file finally: manifest_f.close() except IOError: pass
[ "def", "_remove_visual_c_ref", "(", "self", ",", "manifest_file", ")", ":", "try", ":", "# Remove references to the Visual C runtime, so they will", "# fall through to the Visual C dependency of Python.exe.", "# This way, when installed for a restricted user (e.g.", "# runtimes are not in ...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/distutils/msvc9compiler.py#L709-L746
mailgun/flanker
2bb021ee48dd3aebe7bf2aac098df61d55fc299b
flanker/addresslib/_parser/lexer.py
python
t_domain_RBRACKET
(t)
return t
r'\]
r'\]
[ "r", "\\", "]" ]
def t_domain_RBRACKET(t): r'\]' t.lexer.begin('INITIAL') return t
[ "def", "t_domain_RBRACKET", "(", "t", ")", ":", "t", ".", "lexer", ".", "begin", "(", "'INITIAL'", ")", "return", "t" ]
https://github.com/mailgun/flanker/blob/2bb021ee48dd3aebe7bf2aac098df61d55fc299b/flanker/addresslib/_parser/lexer.py#L107-L110
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/contextlib.py
python
AsyncExitStack.push_async_callback
(*args, **kwds)
return callback
Registers an arbitrary coroutine function and arguments. Cannot suppress exceptions.
Registers an arbitrary coroutine function and arguments.
[ "Registers", "an", "arbitrary", "coroutine", "function", "and", "arguments", "." ]
def push_async_callback(*args, **kwds): """Registers an arbitrary coroutine function and arguments. Cannot suppress exceptions. """ if len(args) >= 2: self, callback, *args = args elif not args: raise TypeError("descriptor 'push_async_callback' of " "'AsyncExitStack' object needs an argument") elif 'callback' in kwds: callback = kwds.pop('callback') self, *args = args import warnings warnings.warn("Passing 'callback' as keyword argument is deprecated", DeprecationWarning, stacklevel=2) else: raise TypeError('push_async_callback expected at least 1 ' 'positional argument, got %d' % (len(args)-1)) _exit_wrapper = self._create_async_cb_wrapper(callback, *args, **kwds) # We changed the signature, so using @wraps is not appropriate, but # setting __wrapped__ may still help with introspection. _exit_wrapper.__wrapped__ = callback self._push_exit_callback(_exit_wrapper, False) return callback # Allow use as a decorator
[ "def", "push_async_callback", "(", "*", "args", ",", "*", "*", "kwds", ")", ":", "if", "len", "(", "args", ")", ">=", "2", ":", "self", ",", "callback", ",", "", "*", "args", "=", "args", "elif", "not", "args", ":", "raise", "TypeError", "(", "\"...
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/contextlib.py#L590-L616
dmlc/minpy
2e44927ad0fbff9295e2acf6db636e588fdc5b42
minpy/nn/model_builder.py
python
Model.grad_and_loss
(self, data, labels)
param data: an array or a tuple of arrays param labels: an array or a tuple of arrays
param data: an array or a tuple of arrays param labels: an array or a tuple of arrays
[ "param", "data", ":", "an", "array", "or", "a", "tuple", "of", "arrays", "param", "labels", ":", "an", "array", "or", "a", "tuple", "of", "arrays" ]
def grad_and_loss(self, data, labels): # TODO specify forward # TODO multiple loss outputs # TODO multiple inputs to forward and loss function """ param data: an array or a tuple of arrays param labels: an array or a tuple of arrays """ if not isinstance(data, tuple): data = (data,) if not isinstance(labels, tuple): labels = (labels,)
[ "def", "grad_and_loss", "(", "self", ",", "data", ",", "labels", ")", ":", "# TODO specify forward", "# TODO multiple loss outputs", "# TODO multiple inputs to forward and loss function", "if", "not", "isinstance", "(", "data", ",", "tuple", ")", ":", "data", "=", "("...
https://github.com/dmlc/minpy/blob/2e44927ad0fbff9295e2acf6db636e588fdc5b42/minpy/nn/model_builder.py#L655-L664
JDASoftwareGroup/kartothek
1821ea5df60d4079d3911b3c2f17be11d8780e22
kartothek/utils/converters.py
python
converter_str_tupleset
(obj: Optional[Union[Iterable[str], str]])
return result
Convert input to tuple of unique unicode strings. ``None`` will be converted to an empty set. The input must not contain duplicate entries. Parameters ---------- obj Object to convert. Raises ------ TypeError If passed object is not string/byte-like, or if ``obj`` is known to have an unstable iteration order. ValueError If passed set contains duplicates.
Convert input to tuple of unique unicode strings. ``None`` will be converted to an empty set.
[ "Convert", "input", "to", "tuple", "of", "unique", "unicode", "strings", ".", "None", "will", "be", "converted", "to", "an", "empty", "set", "." ]
def converter_str_tupleset(obj: Optional[Union[Iterable[str], str]]) -> Tuple[str, ...]: """ Convert input to tuple of unique unicode strings. ``None`` will be converted to an empty set. The input must not contain duplicate entries. Parameters ---------- obj Object to convert. Raises ------ TypeError If passed object is not string/byte-like, or if ``obj`` is known to have an unstable iteration order. ValueError If passed set contains duplicates. """ if isinstance(obj, (dict, frozenset, set)): raise TypeError( "{obj} which has type {tname} has an unstable iteration order".format( obj=obj, tname=type(obj).__name__ ) ) result = converter_tuple(obj) result = tuple(converter_str(x) for x in result) if len(set(result)) != len(result): raise ValueError("Tuple-set contains duplicates: {}".format(", ".join(result))) return result
[ "def", "converter_str_tupleset", "(", "obj", ":", "Optional", "[", "Union", "[", "Iterable", "[", "str", "]", ",", "str", "]", "]", ")", "->", "Tuple", "[", "str", ",", "...", "]", ":", "if", "isinstance", "(", "obj", ",", "(", "dict", ",", "frozen...
https://github.com/JDASoftwareGroup/kartothek/blob/1821ea5df60d4079d3911b3c2f17be11d8780e22/kartothek/utils/converters.py#L69-L97
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/sunau.py
python
Au_read.getnframes
(self)
return 0
[]
def getnframes(self): if self._data_size == AUDIO_UNKNOWN_SIZE: return AUDIO_UNKNOWN_SIZE if self._encoding in _simple_encodings: return self._data_size // self._framesize return 0
[ "def", "getnframes", "(", "self", ")", ":", "if", "self", ".", "_data_size", "==", "AUDIO_UNKNOWN_SIZE", ":", "return", "AUDIO_UNKNOWN_SIZE", "if", "self", ".", "_encoding", "in", "_simple_encodings", ":", "return", "self", ".", "_data_size", "//", "self", "."...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/sunau.py#L233-L238
LexPredict/lexpredict-contraxsuite
1d5a2540d31f8f3f1adc442cfa13a7c007319899
contraxsuite_services/apps/document/api/v1.py
python
DocumentTypeViewSet.pre_delete
(self, request, **kwargs)
return Response(data)
Get info about related objects for ready-to-delete document type.
Get info about related objects for ready-to-delete document type.
[ "Get", "info", "about", "related", "objects", "for", "ready", "-", "to", "-", "delete", "document", "type", "." ]
def pre_delete(self, request, **kwargs): """ Get info about related objects for ready-to-delete document type. """ obj = self.get_object() data = {} # WARN! this collector takes too much time as it collects ALL objects includind # TextUnit, all ThingUsages, etc, so replaced with simplified version # using = db_router.db_for_write(obj._meta.model) # collector = NestedObjects(using=using) # collector.collect([obj]) # # full_data = collector.nested() # data['model_count'] = OrderedDict(sorted( # [(cap_words(model._meta.verbose_name_plural), len(objs)) # for model, objs in collector.model_objs.items() # if 'relationship' not in model._meta.verbose_name_plural])) data['delete_related_objects'] = dict( document_fields=obj.fields.count(), document_field_detectors_count=DocumentFieldDetector.objects.filter(field__document_type=obj).count(), documents=Document.all_objects.filter(document_type=obj).count(), documents_delete_pending=Document.all_objects.filter(document_type=obj, delete_pending=True).count(), projects=obj.project_set.count(), projects_delete_pending=obj.project_set.filter(delete_pending=True).count() ) # Get detailed data # data['document_fields'] = obj.fields.order_by('title') \ # .annotate(documents=Count('document')) \ # .values('pk', 'code', 'title') # data['projects'] = obj.project_set.order_by('name') \ # .annotate(documents=Count('document')) \ # .values('pk', 'name', 'documents') return Response(data)
[ "def", "pre_delete", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "self", ".", "get_object", "(", ")", "data", "=", "{", "}", "# WARN! this collector takes too much time as it collects ALL objects includind", "# TextUnit, all ThingUsages...
https://github.com/LexPredict/lexpredict-contraxsuite/blob/1d5a2540d31f8f3f1adc442cfa13a7c007319899/contraxsuite_services/apps/document/api/v1.py#L2949-L2983
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/interpreter/mesonmain.py
python
MesonMain.__init__
(self, build: 'build.Build', interpreter: 'Interpreter')
[]
def __init__(self, build: 'build.Build', interpreter: 'Interpreter'): super().__init__(subproject=interpreter.subproject) self.build = build self.interpreter = interpreter self.methods.update({'get_compiler': self.get_compiler_method, 'is_cross_build': self.is_cross_build_method, 'has_exe_wrapper': self.has_exe_wrapper_method, 'can_run_host_binaries': self.can_run_host_binaries_method, 'is_unity': self.is_unity_method, 'is_subproject': self.is_subproject_method, 'current_source_dir': self.current_source_dir_method, 'current_build_dir': self.current_build_dir_method, 'source_root': self.source_root_method, 'build_root': self.build_root_method, 'project_source_root': self.project_source_root_method, 'project_build_root': self.project_build_root_method, 'global_source_root': self.global_source_root_method, 'global_build_root': self.global_build_root_method, 'add_install_script': self.add_install_script_method, 'add_postconf_script': self.add_postconf_script_method, 'add_dist_script': self.add_dist_script_method, 'install_dependency_manifest': self.install_dependency_manifest_method, 'override_dependency': self.override_dependency_method, 'override_find_program': self.override_find_program_method, 'project_version': self.project_version_method, 'project_license': self.project_license_method, 'version': self.version_method, 'project_name': self.project_name_method, 'get_cross_property': self.get_cross_property_method, 'get_external_property': self.get_external_property_method, 'has_external_property': self.has_external_property_method, 'backend': self.backend_method, 'add_devenv': self.add_devenv_method, })
[ "def", "__init__", "(", "self", ",", "build", ":", "'build.Build'", ",", "interpreter", ":", "'Interpreter'", ")", ":", "super", "(", ")", ".", "__init__", "(", "subproject", "=", "interpreter", ".", "subproject", ")", "self", ".", "build", "=", "build", ...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/interpreter/mesonmain.py#L46-L79
ray-project/ray
703c1610348615dcb8c2d141a0c46675084660f5
python/ray/util/client/logsclient.py
python
LogstreamClient.log
(self, level: int, msg: str)
Log the message from the log stream. By default, calls logger.log but this can be overridden. Args: level: The loglevel of the received log message msg: The content of the message
Log the message from the log stream. By default, calls logger.log but this can be overridden.
[ "Log", "the", "message", "from", "the", "log", "stream", ".", "By", "default", "calls", "logger", ".", "log", "but", "this", "can", "be", "overridden", "." ]
def log(self, level: int, msg: str): """Log the message from the log stream. By default, calls logger.log but this can be overridden. Args: level: The loglevel of the received log message msg: The content of the message """ logger.log(level=level, msg=msg)
[ "def", "log", "(", "self", ",", "level", ":", "int", ",", "msg", ":", "str", ")", ":", "logger", ".", "log", "(", "level", "=", "level", ",", "msg", "=", "msg", ")" ]
https://github.com/ray-project/ray/blob/703c1610348615dcb8c2d141a0c46675084660f5/python/ray/util/client/logsclient.py#L98-L106
feisuzhu/thbattle
ac0dee1b2d86de7664289cf432b157ef25427ba1
src/pyglet/input/__init__.py
python
get_apple_remote
(display=None)
return None
Get the Apple remote control device. The Apple remote is the small white 6-button remote control that accompanies most recent Apple desktops and laptops. The remote can only be used with Mac OS X. :Parameters: `display` : `Display` Currently ignored. :rtype: `AppleRemote` :return: The remote device, or ``None`` if the computer does not support it.
Get the Apple remote control device. The Apple remote is the small white 6-button remote control that accompanies most recent Apple desktops and laptops. The remote can only be used with Mac OS X.
[ "Get", "the", "Apple", "remote", "control", "device", ".", "The", "Apple", "remote", "is", "the", "small", "white", "6", "-", "button", "remote", "control", "that", "accompanies", "most", "recent", "Apple", "desktops", "and", "laptops", ".", "The", "remote",...
def get_apple_remote(display=None): '''Get the Apple remote control device. The Apple remote is the small white 6-button remote control that accompanies most recent Apple desktops and laptops. The remote can only be used with Mac OS X. :Parameters: `display` : `Display` Currently ignored. :rtype: `AppleRemote` :return: The remote device, or ``None`` if the computer does not support it. ''' return None
[ "def", "get_apple_remote", "(", "display", "=", "None", ")", ":", "return", "None" ]
https://github.com/feisuzhu/thbattle/blob/ac0dee1b2d86de7664289cf432b157ef25427ba1/src/pyglet/input/__init__.py#L91-L106
yiranran/Audio-driven-TalkingFace-HeadPose
d062a00a46a5d0ebb4bf66751e7a9af92ee418e8
render-to-video/models/networks.py
python
ResnetBlock.build_conv_block
(self, dim, padding_type, norm_layer, use_dropout, use_bias)
return nn.Sequential(*conv_block)
Construct a convolutional block. Parameters: dim (int) -- the number of channels in the conv layer. padding_type (str) -- the name of padding layer: reflect | replicate | zero norm_layer -- normalization layer use_dropout (bool) -- if use dropout layers. use_bias (bool) -- if the conv layer uses bias or not Returns a conv block (with a conv layer, a normalization layer, and a non-linearity layer (ReLU))
Construct a convolutional block.
[ "Construct", "a", "convolutional", "block", "." ]
def build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias): """Construct a convolutional block. Parameters: dim (int) -- the number of channels in the conv layer. padding_type (str) -- the name of padding layer: reflect | replicate | zero norm_layer -- normalization layer use_dropout (bool) -- if use dropout layers. use_bias (bool) -- if the conv layer uses bias or not Returns a conv block (with a conv layer, a normalization layer, and a non-linearity layer (ReLU)) """ conv_block = [] p = 0 if padding_type == 'reflect': conv_block += [nn.ReflectionPad2d(1)] elif padding_type == 'replicate': conv_block += [nn.ReplicationPad2d(1)] elif padding_type == 'zero': p = 1 else: raise NotImplementedError('padding [%s] is not implemented' % padding_type) conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim), nn.ReLU(True)] if use_dropout: conv_block += [nn.Dropout(0.5)] p = 0 if padding_type == 'reflect': conv_block += [nn.ReflectionPad2d(1)] elif padding_type == 'replicate': conv_block += [nn.ReplicationPad2d(1)] elif padding_type == 'zero': p = 1 else: raise NotImplementedError('padding [%s] is not implemented' % padding_type) conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim)] return nn.Sequential(*conv_block)
[ "def", "build_conv_block", "(", "self", ",", "dim", ",", "padding_type", ",", "norm_layer", ",", "use_dropout", ",", "use_bias", ")", ":", "conv_block", "=", "[", "]", "p", "=", "0", "if", "padding_type", "==", "'reflect'", ":", "conv_block", "+=", "[", ...
https://github.com/yiranran/Audio-driven-TalkingFace-HeadPose/blob/d062a00a46a5d0ebb4bf66751e7a9af92ee418e8/render-to-video/models/networks.py#L400-L438
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/setuptools/msvc.py
python
EnvironmentInfo.HTMLHelpWorkshop
(self)
return [os.path.join(self.si.ProgramFilesx86, 'HTML Help Workshop')]
Microsoft HTML Help Workshop
Microsoft HTML Help Workshop
[ "Microsoft", "HTML", "Help", "Workshop" ]
def HTMLHelpWorkshop(self): """ Microsoft HTML Help Workshop """ if self.vc_ver < 11.0: return [] return [os.path.join(self.si.ProgramFilesx86, 'HTML Help Workshop')]
[ "def", "HTMLHelpWorkshop", "(", "self", ")", ":", "if", "self", ".", "vc_ver", "<", "11.0", ":", "return", "[", "]", "return", "[", "os", ".", "path", ".", "join", "(", "self", ".", "si", ".", "ProgramFilesx86", ",", "'HTML Help Workshop'", ")", "]" ]
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/setuptools/msvc.py#L1147-L1154
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_adm_policy_group.py
python
PolicyGroup.__init__
(self, config, verbose=False)
Constructor for PolicyGroup
Constructor for PolicyGroup
[ "Constructor", "for", "PolicyGroup" ]
def __init__(self, config, verbose=False): ''' Constructor for PolicyGroup ''' super(PolicyGroup, self).__init__(config.namespace, config.kubeconfig, verbose) self.config = config self.verbose = verbose self._rolebinding = None self._scc = None self._cluster_role_bindings = None self._role_bindings = None
[ "def", "__init__", "(", "self", ",", "config", ",", "verbose", "=", "False", ")", ":", "super", "(", "PolicyGroup", ",", "self", ")", ".", "__init__", "(", "config", ".", "namespace", ",", "config", ".", "kubeconfig", ",", "verbose", ")", "self", ".", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_adm_policy_group.py#L2005-L2015
flyte/mqtt-io
6297a22f1200a35f890c2487428ee84ab2c671cd
mqtt_io/events.py
python
EventBus.subscribe
( self, event_class: Type[Event], callback: ListenerType, )
return remove_listener
Add a coroutine to be used as a callback when the given event class is fired.
Add a coroutine to be used as a callback when the given event class is fired.
[ "Add", "a", "coroutine", "to", "be", "used", "as", "a", "callback", "when", "the", "given", "event", "class", "is", "fired", "." ]
def subscribe( self, event_class: Type[Event], callback: ListenerType, ) -> Callable[[], None]: """ Add a coroutine to be used as a callback when the given event class is fired. """ if not isinstance(event_class, type): raise TypeError( "event_class must be of type 'type'. Got type %s." % type(event_class) ) if not Event in event_class.mro(): raise TypeError("Event class must be a subclass of mqtt_io.events.Event") if not callable(callback): raise TypeError("callback must be callable. Got type %s." % type(callback)) self._listeners.setdefault(event_class, []).append(callback) def remove_listener() -> None: self._listeners[event_class].remove(callback) return remove_listener
[ "def", "subscribe", "(", "self", ",", "event_class", ":", "Type", "[", "Event", "]", ",", "callback", ":", "ListenerType", ",", ")", "->", "Callable", "[", "[", "]", ",", "None", "]", ":", "if", "not", "isinstance", "(", "event_class", ",", "type", "...
https://github.com/flyte/mqtt-io/blob/6297a22f1200a35f890c2487428ee84ab2c671cd/mqtt_io/events.py#L120-L141
leancloud/satori
701caccbd4fe45765001ca60435c0cb499477c03
satori-rules/plugin/libs/urllib3/contrib/securetransport.py
python
SecureTransportContext.verify_mode
(self)
return ssl.CERT_REQUIRED if self._verify else ssl.CERT_NONE
[]
def verify_mode(self): return ssl.CERT_REQUIRED if self._verify else ssl.CERT_NONE
[ "def", "verify_mode", "(", "self", ")", ":", "return", "ssl", ".", "CERT_REQUIRED", "if", "self", ".", "_verify", "else", "ssl", ".", "CERT_NONE" ]
https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/urllib3/contrib/securetransport.py#L790-L791
Observerspy/CS294
849aa311e276ba98c9651e0d7b28c17127782a2f
hw2/logz.py
python
configure_output_dir
(d=None)
Set output directory to d, or to /tmp/somerandomnumber if d is None
Set output directory to d, or to /tmp/somerandomnumber if d is None
[ "Set", "output", "directory", "to", "d", "or", "to", "/", "tmp", "/", "somerandomnumber", "if", "d", "is", "None" ]
def configure_output_dir(d=None): """ Set output directory to d, or to /tmp/somerandomnumber if d is None """ G.output_dir = d or "/tmp/experiments/%i"%int(time.time()) assert not osp.exists(G.output_dir), "Log dir %s already exists! Delete it first or use a different dir"%G.output_dir os.makedirs(G.output_dir) G.output_file = open(osp.join(G.output_dir, "log.txt"), 'w') atexit.register(G.output_file.close) print(colorize("Logging data to %s"%G.output_file.name, 'green', bold=True))
[ "def", "configure_output_dir", "(", "d", "=", "None", ")", ":", "G", ".", "output_dir", "=", "d", "or", "\"/tmp/experiments/%i\"", "%", "int", "(", "time", ".", "time", "(", ")", ")", "assert", "not", "osp", ".", "exists", "(", "G", ".", "output_dir", ...
https://github.com/Observerspy/CS294/blob/849aa311e276ba98c9651e0d7b28c17127782a2f/hw2/logz.py#L49-L58
nilmtk/nilmtk
d183c8bde7a5d3465ba72b38b7964d57d84f53c2
nilmtk/feature_detectors/steady_states.py
python
find_steady_states_transients
(metergroup, columns, noise_level, state_threshold, **load_kwargs)
return [pd.concat(steady_states_list), pd.concat(transients_list)]
Returns ------- steady_states, transients : pd.DataFrame
Returns ------- steady_states, transients : pd.DataFrame
[ "Returns", "-------", "steady_states", "transients", ":", "pd", ".", "DataFrame" ]
def find_steady_states_transients(metergroup, columns, noise_level, state_threshold, **load_kwargs): """ Returns ------- steady_states, transients : pd.DataFrame """ steady_states_list = [] transients_list = [] for power_df in metergroup.load(columns=columns, **load_kwargs): """ if len(power_df.columns) <= 2: # Use whatever is available power_dataframe = power_df else: # Active, reactive and apparent are available power_dataframe = power_df[[('power', 'active'), ('power', 'reactive')]] """ power_dataframe = power_df.dropna() if power_dataframe.empty: continue x, y = find_steady_states( power_dataframe, noise_level=noise_level, state_threshold=state_threshold) steady_states_list.append(x) transients_list.append(y) return [pd.concat(steady_states_list), pd.concat(transients_list)]
[ "def", "find_steady_states_transients", "(", "metergroup", ",", "columns", ",", "noise_level", ",", "state_threshold", ",", "*", "*", "load_kwargs", ")", ":", "steady_states_list", "=", "[", "]", "transients_list", "=", "[", "]", "for", "power_df", "in", "meterg...
https://github.com/nilmtk/nilmtk/blob/d183c8bde7a5d3465ba72b38b7964d57d84f53c2/nilmtk/feature_detectors/steady_states.py#L5-L33
cgoldberg/multi-mechanize
c08d5bfcf664123402e33cf2a98cff4096cc12e7
multimechanize/rpcserver.py
python
RemoteControl.get_config
(self)
[]
def get_config(self): with open('projects/%s/config.cfg' % self.project_name, 'r') as f: return f.read()
[ "def", "get_config", "(", "self", ")", ":", "with", "open", "(", "'projects/%s/config.cfg'", "%", "self", ".", "project_name", ",", "'r'", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")" ]
https://github.com/cgoldberg/multi-mechanize/blob/c08d5bfcf664123402e33cf2a98cff4096cc12e7/multimechanize/rpcserver.py#L51-L53
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/core/defchararray.py
python
chararray.__eq__
(self, other)
return equal(self, other)
Return (self == other) element-wise. See also -------- equal
Return (self == other) element-wise.
[ "Return", "(", "self", "==", "other", ")", "element", "-", "wise", "." ]
def __eq__(self, other): """ Return (self == other) element-wise. See also -------- equal """ return equal(self, other)
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "equal", "(", "self", ",", "other", ")" ]
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/core/defchararray.py#L1865-L1873
poodarchu/Det3D
01258d8cb26656c5b950f8d41f9dcc1dd62a391e
det3d/datasets/kitti/kitti_common.py
python
filter_annos_low_height
(image_annos, thresh)
return new_image_annos
[]
def filter_annos_low_height(image_annos, thresh): new_image_annos = [] for anno in image_annos: img_filtered_annotations = {} relevant_annotation_indices = [ i for i, s in enumerate(anno["bbox"]) if (s[3] - s[1]) >= thresh ] for key in anno.keys(): img_filtered_annotations[key] = anno[key][relevant_annotation_indices] new_image_annos.append(img_filtered_annotations) return new_image_annos
[ "def", "filter_annos_low_height", "(", "image_annos", ",", "thresh", ")", ":", "new_image_annos", "=", "[", "]", "for", "anno", "in", "image_annos", ":", "img_filtered_annotations", "=", "{", "}", "relevant_annotation_indices", "=", "[", "i", "for", "i", ",", ...
https://github.com/poodarchu/Det3D/blob/01258d8cb26656c5b950f8d41f9dcc1dd62a391e/det3d/datasets/kitti/kitti_common.py#L678-L688