code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,200 为正常。" }, { "name": "errorMessage", "type": "Str...
def addPriority(self, objectName)
添加聊天室消息优先级方法 方法 @param objectName:低优先级的消息类型,每次最多提交 5 个,设置的消息类型最多不超过 20 个。(必传) @return code:返回码,200 为正常。 @return errorMessage:错误信息。
4.82095
3.572611
1.349419
desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,200 为正常。" }, { "name": "errorMessage", "type": "Str...
def setUserPushTag(self, userTag)
添加 Push 标签方法 方法 @param userTag:用户标签。 @return code:返回码,200 为正常。 @return errorMessage:错误信息。
4.377782
4.025438
1.087529
desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,200 为正常。" }, { "name": "errorMessage", "type": "Str...
def broadcastPush(self, pushMessage)
广播消息方法(fromuserid 和 message为null即为不落地的push) 方法 @param pushMessage:json数据 @return code:返回码,200 为正常。 @return errorMessage:错误信息。
4.648466
4.259288
1.091371
with open(path) as file: tfs_in_file = [line.strip() for line in file.readlines()] return tfs_in_file
def load_tf_names(path)
:param path: the path of the transcription factor list file. :return: a list of transcription factor names read from the file.
3.456974
3.135794
1.102424
desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,200 为正常。" }, { "name": "errorMessage", "type": "Str...
def sync(self, userId, groupInfo)
同步用户所属群组方法(当第一次连接融云服务器时,需要向融云服务器提交 userId 对应的用户当前所加入的所有群组,此接口主要为防止应用中用户群信息同融云已知的用户所属群信息不同步。) 方法 @param userId:被同步群信息的用户 Id。(必传) @param groupInfo:该用户的群信息,如群 Id 已经存在,则不会刷新对应群组名称,如果想刷新群组名称请调用刷新群组信息方法。 @return code:返回码,200 为正常。 @return errorMessage:错误信息。
4.31455
3.876915
1.112882
desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,200 为正常。" }, { "name": "errorMessage", "type": "Str...
def refresh(self, groupId, groupName)
刷新群组信息方法 方法 @param groupId:群组 Id。(必传) @param groupName:群名称。(必传) @return code:返回码,200 为正常。 @return errorMessage:错误信息。
3.837017
3.306556
1.160427
desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,200 为正常。" }, { "name": "errorMessage", "type": "Str...
def join(self, userId, groupId, groupName)
将用户加入指定群组,用户将可以收到该群的消息,同一用户最多可加入 500 个群,每个群最大至 3000 人。 方法 @param userId:要加入群的用户 Id,可提交多个,最多不超过 1000 个。(必传) @param groupId:要加入的群 Id。(必传) @param groupName:要加入的群 Id 对应的名称。(必传) @return code:返回码,200 为正常。 @return errorMessage:错误信息。
3.409891
2.93223
1.1629
desc = { "name": "GroupUserQueryReslut", "desc": "groupUserQuery返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,200 为正常。" }, { "name": "id", "type": "Stri...
def queryUser(self, groupId)
查询群成员方法 方法 @param groupId:群组Id。(必传) @return code:返回码,200 为正常。 @return id:群成员用户Id。 @return users:群成员列表。
3.249149
2.493173
1.303218
desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,200 为正常。" }, { "name": "errorMessage", "type": "Str...
def dismiss(self, userId, groupId)
解散群组方法。(将该群解散,所有用户都无法再接收该群的消息。) 方法 @param userId:操作解散群的用户 Id。(必传) @param groupId:要解散的群 Id。(必传) @return code:返回码,200 为正常。 @return errorMessage:错误信息。
3.652556
3.158418
1.156451
data = gntp.shim.u(data) match = GNTP_INFO_LINE_SHORT.match(data) if not match: raise errors.ParseError('INVALID_GNTP_INFO') info = match.groupdict() if info['messagetype'] == 'REGISTER': return GNTPRegister(data, password=password) elif info['messagetype'] == 'NOTIFY': return GNTPNotice(data, password=pa...
def parse_gntp(data, password=None)
Attempt to parse a message as a GNTP message :param string data: Message to be parsed :param string password: Optional password to be used to verify the message
2.616387
2.769153
0.944833
match = GNTP_INFO_LINE.match(data) if not match: raise errors.ParseError('ERROR_PARSING_INFO_LINE') info = match.groupdict() if info['encryptionAlgorithmID'] == 'NONE': info['encryptionAlgorithmID'] = None return info
def _parse_info(self, data)
Parse the first line of a GNTP message to get security and other info values :param string data: GNTP Message :return dict: Parsed GNTP Info line
5.200438
3.96456
1.311731
if not password: self.info['encryptionAlgorithmID'] = None self.info['keyHashAlgorithm'] = None return self.password = gntp.shim.b(password) self.encryptAlgo = encryptAlgo.upper() if not self.encryptAlgo in self.hash_algo: raise errors.UnsupportedError('INVALID HASH "%s"' % self.encryptAlgo) ...
def set_password(self, password, encryptAlgo='MD5')
Set a password for a GNTP Message :param string password: Null to clear password :param string encryptAlgo: Supports MD5, SHA1, SHA256, SHA512
3.762485
3.742909
1.00523
result = '' for i in range(0, len(value), 2): tmp = int(value[i:i + 2], 16) result += chr(tmp) return result
def _decode_hex(self, value)
Helper function to decode hex string to `proper` hex string :param string value: Human readable hex string :return string: Hex string
1.996886
2.334781
0.855277
self.password = password if password is None: raise errors.AuthError('Missing password') keyHash = self.info.get('keyHash', None) if keyHash is None and self.password is None: return True if keyHash is None: raise errors.AuthError('Invalid keyHash') if self.password is None: raise errors.Auth...
def _validate_password(self, password)
Validate GNTP Message against stored password
2.957209
2.859818
1.034055
for header in self._requiredHeaders: if not self.headers.get(header, False): raise errors.ParseError('Missing Notification Header: ' + header)
def validate(self)
Verify required headers
7.534352
5.015011
1.50236
info = 'GNTP/%s %s' % ( self.info.get('version'), self.info.get('messagetype'), ) if self.info.get('encryptionAlgorithmID', None): info += ' %s:%s' % ( self.info.get('encryptionAlgorithmID'), self.info.get('ivValue'), ) else: info += ' NONE' if self.info.get('keyHashAlgorithmID', No...
def _format_info(self)
Generate info line for GNTP Message :return string:
2.690513
2.520137
1.067606
d = {} for line in data.split('\r\n'): match = GNTP_HEADER.match(line) if not match: continue key = match.group(1).strip() val = match.group(2).strip() d[key] = val return d
def _parse_dict(self, data)
Helper function to parse blocks of GNTP headers into a dictionary :param string data: :return dict: Dictionary of parsed GNTP Headers
2.709296
2.365844
1.145171
data = gntp.shim.b(data) identifier = hashlib.md5(data).hexdigest() self.resources[identifier] = data return 'x-growl-resource://%s' % identifier
def add_resource(self, data)
Add binary resource :param string data: Binary Data
8.030899
9.07626
0.884825
self.password = password self.raw = gntp.shim.u(data) parts = self.raw.split('\r\n\r\n') self.info = self._parse_info(self.raw) self.headers = self._parse_dict(parts[0])
def decode(self, data, password=None)
Decode GNTP Message :param string data:
4.829224
4.726532
1.021727
'''Validate required headers and validate notification headers''' for header in self._requiredHeaders: if not self.headers.get(header, False): raise errors.ParseError('Missing Registration Header: ' + header) for notice in self.notifications: for header in self._requiredNotificationHeaders: if not n...
def validate(self)
Validate required headers and validate notification headers
3.92496
3.079982
1.274345
self.raw = gntp.shim.u(data) parts = self.raw.split('\r\n\r\n') self.info = self._parse_info(self.raw) self._validate_password(password) self.headers = self._parse_dict(parts[0]) for i, part in enumerate(parts): if i == 0: continue # Skip Header if part.strip() == '': continue notice =...
def decode(self, data, password)
Decode existing GNTP Registration message :param string data: Message to decode
4.5841
4.362544
1.050786
notice = {} notice['Notification-Name'] = name notice['Notification-Enabled'] = enabled self.notifications.append(notice) self.add_header('Notifications-Count', len(self.notifications))
def add_notification(self, name, enabled=True)
Add new Notification to Registration message :param string name: Notification Name :param boolean enabled: Enable this notification by default
4.02236
4.696564
0.856447
buff = _GNTPBuffer() buff.writeln(self._format_info()) #Headers for k, v in self.headers.items(): buff.writeheader(k, v) buff.writeln() #Notifications if len(self.notifications) > 0: for notice in self.notifications: for k, v in notice.items(): buff.writeheader(k, v) buff.writeln...
def encode(self)
Encode a GNTP Registration Message :return string: Encoded GNTP Registration message. Returned as a byte string
2.954473
2.789985
1.058956
desc = { "name": "SMSImageCodeReslut", "desc": " getImageCode 成功返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,200 为正常。" }, { "name": "url", "type": "Str...
def getImageCode(self, appKey)
获取图片验证码方法 方法 @param appKey:应用Id @return code:返回码,200 为正常。 @return url:返回的图片验证码 URL 地址。 @return verifyId:返回图片验证标识 Id。 @return errorMessage:错误信息。
3.464907
2.456741
1.410367
desc = { "name": "SMSSendCodeReslut", "desc": " SMSSendCodeReslut 成功返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,200 为正常。" }, { "name": "sessionId", "t...
def sendCode(self, mobile, templateId, region, verifyId=None, verifyCode=None)
发送短信验证码方法。 方法 @param mobile:接收短信验证码的目标手机号,每分钟同一手机号只能发送一次短信验证码,同一手机号 1 小时内最多发送 3 次。(必传) @param templateId:短信模板 Id,在开发者后台->短信服务->服务设置->短信模版中获取。(必传) @param region:手机号码所属国家区号,目前只支持中图区号 86) @param verifyId:图片验证标识 Id ,开启图片验证功能后此参数必传,否则可以不传。在获取图片验证码方法返回值中获取。 @param verifyCode:图片验证码...
2.683203
2.310571
1.161273
desc = { "name": "SMSVerifyCodeResult", "desc": " VerifyCode 返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,200 为正常。" }, { "name": "success", "type": "Bo...
def verifyCode(self, sessionId, code)
验证码验证方法 方法 @param sessionId:短信验证码唯一标识,在发送短信验证码方法,返回值中获取。(必传) @param code:短信验证码内容。(必传) @return code:返回码,200 为正常。 @return success:true 验证成功,false 验证失败。 @return errorMessage:错误信息。
3.098743
2.66484
1.162825
try: growl = notifierFactory( applicationName=applicationName, notifications=[noteType], defaultNotifications=[noteType], applicationIcon=applicationIcon, hostname=hostname, password=password, port=port, ) result = growl.register() if result is not True: return result return growl....
def mini(description, applicationName='PythonMini', noteType="Message", title="Mini Message", applicationIcon=None, hostname='localhost', password=None, port=23053, sticky=False, priority=None, callback=None, notificationIcon=None, identifier=None, notifierFactory=GrowlNotifier)
Single notification function Simple notification function in one line. Has only one required parameter and attempts to use reasonable defaults for everything else :param string description: Notification message .. warning:: For now, only URL callbacks are supported. In the future, the callback argument will...
2.914749
3.24506
0.898211
logger.info('Sending registration to %s:%s', self.hostname, self.port) register = gntp.core.GNTPRegister() register.add_header('Application-Name', self.applicationName) for notification in self.notifications: enabled = notification in self.defaultNotifications register.add_notification(notification, en...
def register(self)
Send GNTP Registration .. warning:: Before sending notifications to Growl, you need to have sent a registration message at least once
3.657849
3.472405
1.053405
logger.info('Sending notification [%s] to %s:%s', noteType, self.hostname, self.port) assert noteType in self.notifications notice = gntp.core.GNTPNotice() notice.add_header('Application-Name', self.applicationName) notice.add_header('Notification-Name', noteType) notice.add_header('Notification-Title', ...
def notify(self, noteType, title, description, icon=None, sticky=False, priority=None, callback=None, identifier=None, custom={})
Send a GNTP notifications .. warning:: Must have registered with growl beforehand or messages will be ignored :param string noteType: One of the notification names registered earlier :param string title: Notification title (usually displayed on the notification) :param string description: The main content ...
2.500509
2.51781
0.993129
sub = gntp.core.GNTPSubscribe() sub.add_header('Subscriber-ID', id) sub.add_header('Subscriber-Name', name) sub.add_header('Subscriber-Port', port) if self.password: sub.set_password(self.password, self.passwordHash) self.add_origin_info(sub) self.subscribe_hook(sub) return self._send('subscribe...
def subscribe(self, id, name, port)
Send a Subscribe request to a remote machine
3.708413
3.904917
0.949678
packet.add_header('Origin-Machine-Name', platform.node()) packet.add_header('Origin-Software-Name', 'gntp.py') packet.add_header('Origin-Software-Version', __version__) packet.add_header('Origin-Platform-Name', platform.system()) packet.add_header('Origin-Platform-Version', platform.platform())
def add_origin_info(self, packet)
Add optional Origin headers to message
2.33036
2.248643
1.036341
packet.validate() data = packet.encode() logger.debug('To : %s:%s <%s>\n%s', self.hostname, self.port, packet.__class__, data) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(self.socketTimeout) try: s.connect((self.hostname, self.port)) s.send(data) recv_data = s.recv(1024...
def _send(self, messagetype, packet)
Send the GNTP Packet
2.912779
2.729621
1.0671
desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,200 为正常。" }, { "name": "errorMessage", "type": "Str...
def add(self, word)
添加敏感词方法(设置敏感词后,App 中用户不会收到含有敏感词的消息内容,默认最多设置 50 个敏感词。) 方法 @param word:敏感词,最长不超过 32 个字符。(必传) @return code:返回码,200 为正常。 @return errorMessage:错误信息。
4.857958
3.79311
1.280732
desc = { "name": "ListWordfilterReslut", "desc": "listWordfilter返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,200 为正常。" }, { "name": "word", "type": "St...
def getList(self)
查询敏感词列表方法 方法 @return code:返回码,200 为正常。 @return word:敏感词内容。 @return errorMessage:错误信息。
3.621621
2.750404
1.31676
return cache.fetch( filename=ALLELE_XML_FILENAME, url=ALLELE_XML_URL, decompress=ALLELE_XML_DECOMPRESS, force=force_download)
def local_path(force_download=False)
Downloads allele database from IEDB, returns local path to XML file.
8.318024
6.076065
1.368982
path = cache.local_path( filename=ALLELE_XML_FILENAME, url=ALLELE_XML_URL, decompress=ALLELE_XML_DECOMPRESS) os.remove(path)
def delete()
Deletes local XML file
8.950187
7.703753
1.161796
result = [] path = local_path() etree = xml.etree.ElementTree.parse(path) for allele in etree.iterfind("MhcAlleleName"): name_element = allele.find("DisplayedRestriction") mhc_class_element = allele.find("Class") # need at least a name and an HLA class if name_elemen...
def load_alleles()
Parses the IEDB MhcAlleleName XML file and returns a list of Allele namedtuple objects containing information about that each allele's HLA class and source organism.
2.404963
2.156761
1.115081
alleles = load_alleles() result = {} for allele in alleles: for name in {allele.name}.union(allele.synonyms): result[name] = allele return result
def load_alleles_dict()
Create a dictionary mapping each unique allele name to a namedtuple containing information about that alleles class, locus, species, &c.
3.502671
3.34112
1.048352
d = {} if key_type == 'row': def add_pair(row_letter, col_letter, value): if row_letter not in d: d[row_letter] = {} d[row_letter][col_letter] = value elif key_type == 'pair': def add_pair(row_letter, col_letter, value): d[(row_letter,...
def read_pmbec_coefficients( key_type='row', verbose=True, filename=join(MATRIX_DIR, 'pmbec.mat'))
Parameters ------------ filename : str Location of PMBEC coefficient matrix key_type : str 'row' : every key is a single amino acid, which maps to a dictionary for that row 'pair' : every key is a tuple of amino acids 'pair_string' : every key is a string of two ...
2.055916
2.014321
1.02065
if not self.is_connected: await self.async_connect() try: result = await asyncio.wait_for(self._client.run( "%s && %s" % (_PATH_EXPORT_COMMAND, command)), 9) except asyncssh.misc.ChannelOpenError: if not retry: await se...
async def async_run_command(self, command, retry=False)
Run commands through an SSH connection. Connect to the SSH server if not currently connected, otherwise use the existing connection.
3.578356
3.494173
1.024093
kwargs = { 'username': self._username if self._username else None, 'client_keys': [self._ssh_key] if self._ssh_key else None, 'port': self._port, 'password': self._password if self._password else None, 'known_hosts': None } s...
async def async_connect(self)
Fetches the client or creates a new one.
2.982218
2.866883
1.04023
await self.async_connect() try: with (await self._io_lock): self._writer.write('{}\n'.format( "%s && %s" % ( _PATH_EXPORT_COMMAND, command)).encode('ascii')) data = ((await asyncio.wait_for(self._reader.read...
async def async_run_command(self, command, first_try=True)
Run a command through a Telnet connection. Connect to the Telnet server if not currently connected, otherwise use the existing connection.
4.520601
4.541283
0.995446
self._reader, self._writer = await asyncio.open_connection( self._host, self._port) with (await self._io_lock): try: await asyncio.wait_for(self._reader.readuntil(b'login: '), 9) except asyncio.streams.IncompleteReadError: _LO...
async def async_connect(self)
Connect to the ASUS-WRT Telnet server.
3.142772
2.902466
1.082794
results = [] if inspect.iscoroutinefunction(lines): lines = await lines for line in lines: if line: match = regex.search(line) if not match: _LOGGER.debug("Could not parse row: %s", line) continue results.append(match.g...
async def _parse_lines(lines, regex)
Parse the lines using the given regular expression. If a line can't be parsed it is logged and skipped in the output.
2.963259
3.015407
0.982706
devices = {} dev = await self.async_get_wl() devices.update(dev) dev = await self.async_get_arp() devices.update(dev) dev = await self.async_get_neigh(devices) devices.update(dev) if not self.mode == 'ap': dev = await self.async_get_le...
async def async_get_connected_devices(self)
Retrieve data from ASUSWRT. Calls various commands on the router and returns the superset of all responses. Some commands will not work on some routers.
3.266932
3.051907
1.070456
now = datetime.utcnow() if use_cache and self._trans_cache_timer and self._cache_time > \ (now - self._trans_cache_timer).total_seconds(): return self._transfer_rates_cache rx = await self.async_get_rx() tx = await self.async_get_tx() return ...
async def async_get_bytes_total(self, use_cache=True)
Retrieve total bytes (rx an tx) from ASUSWRT.
4.678641
3.979255
1.175758
now = datetime.utcnow() data = await self.async_get_bytes_total(use_cache) if self._rx_latest is None or self._tx_latest is None: self._latest_transfer_check = now self._rx_latest = data[0] self._tx_latest = data[1] return self._latest_tra...
async def async_get_current_transfer_rates(self, use_cache=True)
Gets current transfer rates calculated in per second in bytes.
1.96236
1.880098
1.043754
rx, tx = await self.async_get_current_transfer_rates(use_cache) return "%s/s" % convert_size(rx), "%s/s" % convert_size(tx)
async def async_current_transfer_human_readable( self, use_cache=True)
Gets current transfer rates in a human readable format.
4.919235
3.399516
1.44704
lines = table.split("\n") # drop comments lines = [line for line in lines if not line.startswith("#")] # drop CR endline characters lines = [line.replace("\r", "") for line in lines] # skip empty lines lines = [line for line in lines if line] labels = lines[0].split() if len(...
def parse_blosum_table(table, coeff_type=int, key_type='row')
Parse a table of pairwise amino acid coefficient (e.g. BLOSUM50)
2.579914
2.503725
1.03043
key_list = [] for arg in args: try: hash(arg) key_list.append(arg) except: key_list.append(repr(arg)) for (k, v) in kwargs.items(): try: hash(k) hash(v) key_list.append((k, v)) except: ke...
def _prepare_memoization_key(args, kwargs)
Make a tuple of arguments which can be used as a key for a memoized function's lookup_table. If some object can't be hashed then used its __repr__ instead.
1.629884
1.55192
1.050237
fieldsets = list(super(CreateUpdateAdmin, self).get_fieldsets( request=request, obj=obj)) # Create sets for future use fields = set() to_add = set() # Prepare a set of existing fields in fieldset for fs in fieldsets: fields = fields.unio...
def get_fieldsets(self, request, obj=None)
Add ownership info fields in fieldset with proper separation. Author: Himanshu Shankar (https://himanshus.com)
4.61357
4.364978
1.056952
# Get read only fields from super fields = list(super(CreateUpdateAdmin, self).get_readonly_fields( request=request, obj=obj)) # Loop over ownership info field for k, v in self.ownership_info['fields'].items(): # Check if model has k attribute ...
def get_readonly_fields(self, request, obj=None)
Makes `created_by`, `create_date` & `update_date` readonly when editing. Author: Himanshu Shankar (https://himanshus.com)
5.333198
5.227118
1.020294
from django.utils.six import text_type from rest_framework import HTTP_HEADER_ENCODING auth = request.data.get(self.key, b'') or request.META.get( self.header_key, b'') if isinstance(auth, text_type): # Work around django test client oddness ...
def get_authorization(self, request)
This function extracts the authorization JWT string. It first looks for specified key in header and then looks for the same in body part. Parameters ---------- request: HttpRequest This is the raw request that user has sent. Returns ------- a...
3.604425
3.476256
1.03687
from django.utils.encoding import smart_text from django.utils.translation import ugettext as _ from rest_framework import exceptions auth = self.get_authorization(request).split() auth_header_prefix = self.prefix.lower() or '' if not auth: if self....
def get_jwt_value(self, request)
This function has been overloaded and it returns the proper JWT auth string. Parameters ---------- request: HttpRequest This is the request that is received by DJango in the view. Returns ------- str This returns the extracted JWT auth toke...
2.31623
2.363623
0.979949
retcode = 0 try: ci = CliInterface() args = ci.parser.parse_args() result = args.func(args) if result is not None: print(result) retcode = 0 except Exception: retcode = 1 traceback.print_exc() sys.exit(retcode)
def main(args=None)
Call the CLI interface and wait for the result.
2.978884
2.586021
1.151918
# FIXME: Can this logic be moved into the create_parser function? ordered = False if args.ordered_list_marker is not None: list_marker = args.ordered_list_marker ordered = True elif args.unordered_list_marker is not None: list_marker = args.un...
def write_toc(self, args)
Write the table of contents.
4.466407
4.438976
1.006179
if obj is None: if isinstance(func, (type, ModuleType)): obj = func func = None elif isinstance(func, (list, tuple)) and all([isinstance(i, (ModuleType, type)) for i in func]): obj = func func = None if func is None: return functools....
def patch(func=None, obj=None, name=None, avoid_doublewrap=True)
Decorator for monkeypatching functions on modules and classes. Example:: # This replaces FooClass.bar with our method @monkeybiz.patch(FooClass) def bar(original_bar, *args, **kwargs): print "Patched!" return original_bar(*args, **kwargs) # This replaces Fo...
2.960988
3.030845
0.976951
setattr(obj, name, getattr(obj, name).original)
def unpatch(obj, name)
Undo the effects of patch(func, obj, name)
6.395557
6.509291
0.982527
from django.core.validators import validate_email from django.core.exceptions import ValidationError try: validate_email(email) return True except ValidationError: return False
def validate_email(email)
Validates an email address Source: Himanshu Shankar (https://github.com/iamhssingh) Parameters ---------- email: str Returns ------- bool
1.982278
2.267587
0.874179
blanks = [' ', '.', ',', '(', ')', '-'] for b in blanks: mobile = mobile.replace(b, '') return mobile
def get_mobile_number(mobile)
Returns a mobile number after removing blanks Author: Himanshu Shankar (https://himanshus.com) Parameters ---------- mobile: str Returns ------- str
4.493241
5.19812
0.864397
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger if int(request_data.data['paginator']) > 0: paginator = Paginator(searched_data.data, request_data.data['paginator']) try: curr = paginator.page(request_data.data['page']) ...
def paginate_data(searched_data, request_data)
Paginates the searched_data as per the request_data Source: Himanshu Shankar (https://github.com/iamhssingh) Parameters ---------- searched_data: Serializer.data It is the data received from queryset. It uses show_serializer request_data: Serializer.data ...
1.786535
1.82966
0.97643
import smtplib from django.conf import settings from django.core.mail import send_mail from sendsms import api sent = {'success': False, 'message': None} if not getattr(settings, 'EMAIL_HOST', None): raise ValueError('EMAIL_HOST must be defined in django ' ...
def send_message(message: str, subject: str, recip: list, recip_email: list, html_message: str = None)
Sends message to specified value. Source: Himanshu Shankar (https://github.com/iamhssingh) Parameters ---------- message: str Message that is to be sent to user. subject: str Subject that is to be sent to user, in case prop is an email. recip: list Recipient to whom messa...
2.757164
2.699165
1.021488
return ( request.user.is_superuser or super(IAWPOrSuperuser, self).has_object_permission( request=request, view=view, obj=obj ) )
def has_object_permission(self, request, view, obj)
Checks if user is superuser or it has permission over object Parameters ---------- request view obj Returns -------
5.272127
5.978756
0.88181
r if filename == '-': raise StdinIsNotAFileToBeWritten final_string = marker + '\n\n' + string.rstrip() + '\n\n' + marker + '\n' marker_line_positions = fpyutils.get_line_matches( filename, marker, 2, loose_matching=True) if 1 in marker_line_positions: if 2 in marker_line_p...
def write_string_on_file_between_markers(filename: str, string: str, marker: str)
r"""Write the table of contents on a single file. :parameter filename: the file that needs to be read or modified. :parameter string: the string that will be written on the file. :parameter marker: a marker that will identify the start and the end of the string. :type filenames: str :type ...
3.866281
2.983944
1.295695
r assert len(filenames) == len(strings) if len(filenames) > 0: for f in filenames: assert isinstance(f, str) if len(strings) > 0: for s in strings: assert isinstance(s, str) file_id = 0 for f in filenames: write_string_on_file_between_markers(f, s...
def write_strings_on_files_between_markers(filenames: list, strings: list, marker: str)
r"""Write the table of contents on multiple files. :parameter filenames: the files that needs to be read or modified. :parameter strings: the strings that will be written on the file. Each string is associated with one file. :parameter marker: a marker that will identify the start and the...
2.318018
2.409342
0.962096
r if len(filenames) > 0: for f in filenames: assert isinstance(f, str) if len(filenames) == 0: filenames.append('-') file_id = 0 toc_struct = list() while file_id < len(filenames): toc_struct.append( build_toc(filenames[file_id], ordered, no_links...
def build_multiple_tocs(filenames: list, ordered: bool = False, no_links: bool = False, no_indentation: bool = False, no_list_coherence: bool = False, keep_header_levels: int = 3, ...
r"""Parse files by line and build the table of contents of each file. :parameter filenames: the files that needs to be read. :parameter ordered: decides whether to build an ordered list or not. Defaults to ``False``. :parameter no_links: disables the use of links. Defaults to ``False``. ...
2.608388
2.576756
1.012276
r # header_type_prev might be 0 while header_type_curr can't. assert header_type_prev >= 0 assert header_type_curr >= 1 # Base cases for a new table of contents or a new index type. if header_type_prev == 0: header_type_prev = header_type_curr if (header_type_curr not in header_type...
def increase_index_ordered_list(header_type_count: dict, header_type_prev: int, header_type_curr: int, parser: str = 'github')
r"""Compute the current index for ordered list table of contents. :parameter header_type_count: the count of each header type. :parameter header_type_prev: the previous type of header (h[1-Inf]). :parameter header_type_curr: the current type of header (h[1-Inf]). :parameter parser: decides rules on how...
4.494183
3.757493
1.196059
r if (parser == 'github' or parser == 'cmark' or parser == 'gitlab' or parser == 'commonmarker' or parser == 'redcarpet'): assert list_marker in md_parser[parser]['list']['ordered'][ 'closing_markers'] list_marker_log = list() if (parser == 'github' or parser == 'cmark'...
def build_list_marker_log(parser: str = 'github', list_marker: str = '.') -> list
r"""Create a data structure that holds list marker information. :parameter parser: decides rules on how compute indentations. Defaults to ``github``. :parameter list_marker: a string that contains some of the first characters of the list element. Defaults to ``-``. :type parser: str :...
4.672057
4.675799
0.9992
r assert 'type' in header assert 'text_original' in header assert 'text_anchor_link' in header assert isinstance(header['type'], int) assert isinstance(header['text_original'], str) assert isinstance(header['text_anchor_link'], str) assert header['type'] >= 1 assert index >= 1 if...
def build_toc_line_without_indentation(header: dict, ordered: bool = False, no_links: bool = False, index: int = 1, parser: str = 'github', ...
r"""Return a list element of the table of contents. :parameter header: a data structure that contains the original text, the trimmed text and the type of header. :parameter ordered: if set to ``True``, numbers will be used as list ids, otherwise a dash character. Defaults to ``False`...
2.995663
2.872537
1.042863
r assert no_of_indentation_spaces >= 0 indentation = no_of_indentation_spaces * ' ' toc_line = indentation + toc_line_no_indent return toc_line
def build_toc_line(toc_line_no_indent: str, no_of_indentation_spaces: int = 0) -> str
r"""Build the TOC line. :parameter toc_line_no_indent: the TOC line without indentation. :parameter no_of_indentation_spaces: the number of indentation spaces. Defaults to ``0``. :type toc_line_no_indent: str :type no_of_indentation_spaces: int :returns: toc_line, a single line of the tabl...
3.688479
4.50115
0.819453
r result = get_atx_heading(header_text_line, keep_header_levels, parser, no_links) if result is None: return result else: header_type, header_text_trimmed = result header = { 'type': header_type, 'text_original': ...
def get_md_header(header_text_line: str, header_duplicate_counter: dict, keep_header_levels: int = 3, parser: str = 'github', no_links: bool = False) -> dict
r"""Build a data structure with the elements needed to create a TOC line. :parameter header_text_line: a single markdown line that needs to be transformed into a TOC line. :parameter header_duplicate_counter: a data structure that contains the number of occurrencies of each header anchor link...
3.776823
3.750542
1.007007
r if (parser == 'github' or parser == 'cmark' or parser == 'gitlab' or parser == 'commonmarker'): return len(line) - len(line.lstrip( ' ')) <= md_parser['github']['code fence']['min_marker_characters'] elif parser == 'redcarpet': # TODO. return False
def is_valid_code_fence_indent(line: str, parser: str = 'github') -> bool
r"""Determine if the given line has valid indentation for a code block fence. :parameter line: a single markdown line to evaluate. :parameter parser: decides rules on how to generate the anchor text. Defaults to ``github``. :type line: str :type parser: str :returns: True if the given line...
9.779804
11.178898
0.874845
r if (parser == 'github' or parser == 'cmark' or parser == 'gitlab' or parser == 'commonmarker'): markers = md_parser['github']['code fence']['marker'] marker_min_length = md_parser['github']['code fence'][ 'min_marker_characters'] if not is_valid_code_fence_inde...
def is_opening_code_fence(line: str, parser: str = 'github')
r"""Determine if the given line is possibly the opening of a fenced code block. :parameter line: a single markdown line to evaluate. :parameter parser: decides rules on how to generate the anchor text. Defaults to ``github``. :type line: str :type parser: str :returns: None if the input li...
4.546867
4.701376
0.967135
r if (parser == 'github' or parser == 'cmark' or parser == 'gitlab' or parser == 'commonmarker'): markers = md_parser['github']['code fence']['marker'] marker_min_length = md_parser['github']['code fence'][ 'min_marker_characters'] if not is_valid_code_fence_inde...
def is_closing_code_fence(line: str, fence: str, is_document_end: bool = False, parser: str = 'github') -> bool
r"""Determine if the given line is the end of a fenced code block. :parameter line: a single markdown line to evaluate. :paramter fence: a sequence of backticks or tildes marking the start of the current code block. This is usually the return value of the is_opening_code_fence function. :...
4.035496
4.156378
0.970917
r indentation_list = list() if (parser == 'github' or parser == 'cmark' or parser == 'gitlab' or parser == 'commonmarker' or parser == 'redcarpet'): for i in range(0, md_parser[parser]['header']['max_levels']): indentation_list.append(False) return indentation_list
def build_indentation_list(parser: str = 'github')
r"""Create a data structure that holds the state of indentations. :parameter parser: decides the length of the list. Defaults to ``github``. :type parser: str :returns: indentation_list, a list that contains the state of indentations given a header type. :rtype: list :raises: a bu...
7.207945
7.654863
0.941616
r assert header_type_curr >= 1 if (parser == 'github' or parser == 'cmark' or parser == 'gitlab' or parser == 'commonmarker' or parser == 'redcarpet'): assert len( indentation_list) == md_parser[parser]['header']['max_levels'] for e in indentation_list: assert isi...
def toc_renders_as_coherent_list( header_type_curr: int = 1, indentation_list: list = build_indentation_list('github'), parser: str = 'github') -> bool
r"""Check if the TOC will render as a working list. :parameter header_type_curr: the current type of header (h[1-Inf]). :parameter parser: decides rules on how to generate ordered list markers :type header_type_curr: int :type indentation_list: list :type parser: str :returns: renders_as_list ...
4.531464
4.453711
1.017458
if user.is_authenticated: return self.created_by.id == user.id return False
def is_owner(self, user)
Checks if user is the owner of object Parameters ---------- user: get_user_model() instance Returns ------- bool Author ------ Himanshu Shankar (https://himanshus.com)
4.267315
5.592319
0.763067
cmd = [] cmd.append('java') if initial_java_heap_size: cmd.append('-Xms{}'.format(initial_java_heap_size)) if maximum_java_heap_size: cmd.append('-Xmx{}'.format(maximum_java_heap_size)) cmd.append('-Dunitth.xml.report.filter={}'.format(xml_repo...
def run(xml_report_dir, xml_report_filter='TEST-', html_report_path='.', generate_exec_time_graphs=True, html_report_dir='report.th', initial_java_heap_size=None, maximum_java_heap_size=None)
Use UnitTH to generate a test history report Args: xml_report_dir (:obj:`str`): Parent directory of XML reports of individual builds to generate a history report of xml_report_filter (:obj:`str`, optional): Starts-with filter for individual reports with `xml_report_dir` that should ...
1.850922
1.847954
1.001606
b0 = data[base] b1 = data[base + 1] b2 = data[base + 2] b3 = data[base + 3] counter = b3 position = (b1 << 8) + b2 return counter, position
def get_counter(data, base)
See setCounters() / getCounters() methods in IJ source, ij/gui/PointRoi.java.
2.860515
2.851745
1.003076
return Util( url=url + id + "/", method=method, key=key, ).json_result()
def get_delete(url, id, method, key=None)
Get or delete, just change the method: "GET" or "DELETE".
9.055216
8.172688
1.107985
return youtrack.User(self._get("/admin/user/" + urlquote(login.encode('utf8'))), self)
def get_user(self, login)
http://confluence.jetbrains.net/display/YTD2/GET+user
9.259917
8.055165
1.149563
if len(users) <= 0: return known_attrs = ('login', 'fullName', 'email', 'jabber') xml = '<list>\n' for u in users: xml += ' <user ' + "".join(k + '=' + quoteattr(u[k]) + ' ' for k in u if k in known_attrs) + '/>\n' xml += '</list>' # TO...
def import_users(self, users)
Import users, returns import result (http://confluence.jetbrains.net/display/YTD2/Import+Users) Example: importUsers([{'login':'vadim', 'fullName':'vadim', 'email':'eee@ss.com', 'jabber':'fff@fff.com'}, {'login':'maxim', 'fullName':'maxim', 'email':'aaa@ss.com', 'jabber':'w...
4.792647
4.115651
1.164493
xml = '<list>\n' for l in links: # ignore typeOutward and typeInward returned by getLinks() xml += ' <link ' + "".join(attr + '=' + quoteattr(l[attr]) + ' ' for attr in l if attr not in ['typeInward', 'typeOutward']) + '/>\n' ...
def import_links(self, links)
Import links, returns import result (http://confluence.jetbrains.net/display/YTD2/Import+Links) Accepts result of getLinks() Example: importLinks([{'login':'vadim', 'fullName':'vadim', 'email':'eee@ss.com', 'jabber':'fff@fff.com'}, {'login':'maxim', 'fullName':'...
5.929141
5.481625
1.081639
return youtrack.Project(self._get("/admin/project/" + urlquote(project_id)), self)
def get_project(self, project_id)
http://confluence.jetbrains.net/display/YTD2/GET+project
11.340076
9.440511
1.201214
for s in subsystems: self.create_subsystem(project_id, s)
def create_subsystems(self, project_id, subsystems)
Accepts result of getSubsystems()
3.853673
3.683607
1.046169
for v in versions: self.create_version(project_id, v)
def create_versions(self, project_id, versions)
Accepts result of getVersions()
4.042506
3.834582
1.054223
if echo: print('$> ' + ' '.join(map(pipes.quote, cmd))) return call(cmd, **kwargs)
def run_cmd(call, cmd, *, echo=True, **kwargs)
Run a command and echo it first
3.994117
3.590648
1.112367
github_token = os.getenv(GITHUB_TOKEN_KEY) if github_token: return 'https://{0}@github.com/{1}'.format( github_token, git_repo) return 'git@github.com:{0}'.format(git_repo)
def git_remote(git_repo)
Return the URL for remote git repository. Depending on the system setup it returns ssh or https remote.
2.674408
2.612498
1.023698
build_args = options.get('buildArgs', {}) for key, value in build_args.items(): build_args[key] = value.format(**ns) return build_args
def render_build_args(options, ns)
Get docker build args dict, rendering any templated args. Args: options (dict): The dictionary for a given image from chartpress.yaml. Fields in `options['buildArgs']` will be rendered and returned, if defined. ns (dict): the namespace used when rendering templated arguments
2.601263
3.020529
0.861194
cmd = ['docker', 'build', '-t', image_name, image_path] if dockerfile_path: cmd.extend(['-f', dockerfile_path]) for k, v in (build_args or {}).items(): cmd += ['--build-arg', '{}={}'.format(k, v)] check_call(cmd)
def build_image(image_path, image_name, build_args=None, dockerfile_path=None)
Build an image Args: image_path (str): the path to the image directory image_name (str): image 'name:tag' to build build_args (dict, optional): dict of docker build arguments dockerfile_path (str, optional): path to dockerfile relative to image_path if not `image_path/Dockerfile`.
1.981444
2.319441
0.854276
d = docker_client() try: d.images.get_registry_data(image) except docker.errors.APIError: # image not found on registry, needs pushing return True else: return False
def image_needs_pushing(image)
Return whether an image needs pushing Args: image (str): the `repository:tag` image to be build. Returns: True: if image needs to be pushed (not on registry) False: if not (already present on registry)
4.180871
4.411664
0.947686
d = docker_client() # first, check for locally built image try: d.images.get(image) except docker.errors.ImageNotFound: # image not found, check registry pass else: # it exists locally, no need to check remote return False # image may need building ...
def image_needs_building(image)
Return whether an image needs building Checks if the image exists (ignores commit range), either locally or on the registry. Args: image (str): the `repository:tag` image to be build. Returns: True: if image needs to be built False: if not (image already exists)
4.901355
5.062444
0.96818
value_modifications = {} for name, options in images.items(): image_path = options.get('contextPath', os.path.join('images', name)) image_tag = tag # include chartpress.yaml itself as it can contain build args and # similar that influence the image that would be built ...
def build_images(prefix, images, tag=None, commit_range=None, push=False, chart_version=None)
Build a collection of docker images Args: prefix (str): the prefix to add to images images (dict): dict of image-specs from chartpress.yml tag (str): Specific tag to use instead of the last modified commit. If unspecified the tag for each image will be the hash of the last commit ...
3.904447
3.821247
1.021773
values_file = os.path.join(name, 'values.yaml') with open(values_file) as f: values = yaml.load(f) for key, value in values_mods.items(): parts = key.split('.') mod_obj = values for p in parts: mod_obj = mod_obj[p] print(f"Updating {values_file}: {k...
def build_values(name, values_mods)
Update name/values.yaml with modifications
2.685592
2.516671
1.067121
chart_file = os.path.join(name, 'Chart.yaml') with open(chart_file) as f: chart = yaml.load(f) if version is None: if paths is None: paths = ['.'] commit = last_modified_commit(*paths) version = chart['version'].split('-')[0] + '-' + commit chart['versi...
def build_chart(name, version=None, paths=None)
Update chart with specified version or last-modified commit in path(s)
2.422721
2.094685
1.156604
version = last_modified_commit(*paths) checkout_dir = '{}-{}'.format(name, version) check_call([ 'git', 'clone', '--no-checkout', git_remote(git_repo), checkout_dir], echo=False, ) check_call(['git', 'checkout', 'gh-pages'], cwd=checkout_dir) # package the latest ve...
def publish_pages(name, paths, git_repo, published_repo, extra_message='')
Publish helm chart index to github pages
3.404639
3.290876
1.034569
argparser = argparse.ArgumentParser(description=__doc__) argparser.add_argument('--commit-range', help='Range of commits to consider when building images') argparser.add_argument('--push', action='store_true', help='push built images to docker hub') argparser.add_argument('--publis...
def main()
Run chartpress
3.280497
3.20101
1.024832
if (value_names is None) and (not auto_attached or "[" not in cf_type): _create_custom_field_prototype(connection, cf_type, cf_name, auto_attached) return if value_names is None: value_names = set([]) else: value_names = set(value_names) field = _get_custom_field(con...
def create_custom_field(connection, cf_type, cf_name, auto_attached, value_names=None, bundle_policy="0")
Creates custom field prototype(if not exist) and sets default values bundle if needed Args: connection: An opened Connection instance. cf_type: Type of custom field to be created cf_name: Name of custom field that should be created (if not exists) auto_attached: If this field shoul...
2.771759
2.531911
1.09473
_create_custom_field_prototype(connection, cf_type, cf_name) if cf_type[0:-3] not in connection.bundle_types: value_names = None elif value_names is None: value_names = [] existing_project_fields = [item for item in connection.getProjectCustomFields(project_id) if ...
def process_custom_field(connection, project_id, cf_type, cf_name, value_names=None)
Creates custom field and attaches it to the project. If custom field already exists and has type cf_type it is attached to the project. If it has another type, LogicException is raised. If project field already exists, uses it and bundle from it. If not, creates project field and bundle with name <cf_name>_...
3.46303
3.163299
1.094753
for value in values: try: connection.addValueToBundle(bundle, value) except YouTrackException as e: if e.response.status == 409: print("Value with name [ %s ] already exists in bundle [ %s ]" % (utf8encode(value.name), utf8encode(bun...
def add_values_to_bundle_safe(connection, bundle, values)
Adds values to specified bundle. Checks, whether each value already contains in bundle. If yes, it is not added. Args: connection: An opened Connection instance. bundle: Bundle instance to add values in. values: Values, that should be added in bundle. Raises: YouTrackException:...
3.568549
3.301666
1.080833