This is part 3/10 of the system predictions for the Real-Bug Test set. This system achieves 41% Repair Accuracy and 54% Location Accuracy.

Annotations:
The part before the arrow ('foo') is what the system actually saw at test time. Other candidate repair locations which the system could have chosen are marked in this color. For clarity the actual labels for those locations are not shown.


def post(self, *args, **kwargs):
    
' Attempts to create an account, with shitty form validation '

    
try:
        
user_name
 = self.get_argument('username')

    
except:
        
self
.render
('public/registration.html', errors='Please enter a valid account name')

    
try:
        
handle
 = self.get_argument('handle')

    
except:
        
self
.render
('public/registration.html', errors='Please enter a valid handle')

    
try:
        
password1
 = self.get_argument('pass1')

        
password2
 = self.get_argument('pass2')

        
if (password1 != password2):
            
self
.render
('public/registration.html', errors='Passwords did not match')

        
else:
            
password
 = password1

    
except:
        
self
.render
('public/registration.html', errors='Please enter a password')

    
try:
        
response
 = captcha.submit(self.get_argument('recaptcha_challenge_field')self.get_argument('recaptcha_response_field')self.application.settings['recaptcha_private_key']self.request.remote_ip)

    
except:
        
self
.render
('public/registration.html', errors='Please fill out recaptcha!')

    
if (User.by_user_name(user_name) != None):
        
self
.render
('public/registration.html', errors='Account name already taken')

    
elif (user_name !=  → == handle):
        
self
.render
('public/registration.html', errors='Account name and hacker name must differ')

    
elif (User.by_display_name(handle) != None):
        
self
.render
('public/registration.html', errors='Handle already taken')

    
elif (not (0 < len(password → response ) <= 7)):
        
self
.render
('public/registration.html', errors='Password must be 1-7 characters')

    
elif (not response.is_valid):
        
self
.render
('public/registration.html', errors='Invalid Recaptcha!')

    
else:
        
char_white_list
 = (ascii_letters + digits)

        
user_name
 = filter(lambda char(char in char_white_list)user_name)

        
display_name
 = filter(lambda char(char in char_white_list)handle)

        
user
 = User(user_name=unicode(user_name), display_name=unicode(display_name), password=password)

        
self
.dbsession
.add
(user)

        
self
.dbsession
.flush
()

    
self
.redirect
('/login')



def outputterminal(self):
    
'Print a slice (or layer) of the dungeon block buffer to the termial.\\u000a    We "look-through" any air blocks to blocks underneath'

    
floor
 = args → self. .term

    
layer
 = ((floor - 1) * self.room_height)

    
for z in xrange((self.zsize * self.room_size)):
        
for x in xrange((self.xsize * self.room_size)):
            
y
 = layer

            
while ((y <  → == ((layer + self.room_height) - 1)) and (Vec(xyz) in self.blocks) and ((self.blocks[Vec(xyz)].hide == True) or (self.blocks[Vec(xyz)].material == materials.Air) or (self.blocks[Vec(xyz)].material == materials._ceiling))):
                
y
 += 1

            
if ((Vec(xyz) in self.blocks) and (self.blocks[Vec(xyz)].hide == False)):
                
mat
 = self.blocks[Vec(xyz)].material

                
if (mat._meta == True):
                    
mat
.update
(xyz(self.xsize * self.room_size)(self.levels * self.room_height)(self.zsize * self.room_size))

                
sys
.stdout
.write
(mat.c)

            
else:
                
sys
.stdout
.write
(materials.NOBLOCK)

        
print 



def set_starttime(selfruleendtime):
    
' Given a rule and an endtime, sets the appropriate starttime for it. '

    
if ('starttime' not in rule):
        
last_run_end
 = self.get_starttime(rule)

        
if last_run_end:
            
rule
['minimum_starttime']
 = last_run_end

            
rule
['starttime']
 = last_run_end

            
return

    
buffer_time
 = rule.get('buffer_time'self.buffer_time)

    
if ((not rule.get('use_count_query')) and (not rule.get('use_terms_query'))):
        
buffer_delta
 = (endtime - buffer_time)

        
if (('minimum_starttime' in rule) and (rule['minimum_starttime'] > buffer_delta)):
            
rule
['starttime']
 = rule['minimum_starttime']

        
elif (('previous_endtime' in rule) and (rule['previous_endtime'] >  → < buffer_delta)):
            
rule
['starttime']
 = rule['previous_endtime']

        
else:
            
rule
['starttime']
 = buffer_delta

    
else:
        
rule
['starttime']
 = rule.get('previous_endtime'(endtime - self.run_every))



def shouldRebuildDB(pkgdbpath):
    
'\\u000a    Checks to see if our internal package DB should be rebuilt.\\u000a    If anything in /Library/Receipts, /Library/Receipts/boms, or\\u000a    /Library/Receipts/db/a.receiptdb has a newer modtime than our\\u000a    database, we should rebuild.\\u000a    '

    
receiptsdir
 = '/Library/Receipts'

    
bomsdir
 = '/Library/Receipts/boms'

    
sl_receiptsdir
 = '/private/var/db/receipts'

    
installhistory
 = '/Library/Receipts/InstallHistory.plist'

    
applepkgdb
 = '/Library/Receipts/db/a.receiptdb'

    
if (not os.path.exists(pkgdbpath)):
        
return True

    
packagedb_modtime
 = os.stat(pkgdbpath).st_mtime

    
if os.path.exists(receiptsdir):
        
receiptsdir_modtime
 = os.stat(receiptsdir).st_mtime

        
if (packagedb_modtime < receiptsdir_modtime):
            
return True

        
receiptlist
 = os.listdir(receiptsdir)

        
for item in receiptlist:
            
if item.endswith('.pkg'):
                
pkgpath
 = os.path.join(receiptsdiritem)

                
pkg_modtime
 = os.stat(pkgpath).st_mtime

                
if (packagedb_modtime <  → == pkg_modtime):
                    
return True

    
if os.path.exists(bomsdir):
        
bomsdir_modtime
 = os.stat(bomsdir).st_mtime

        
if (packagedb_modtime < bomsdir_modtime):
            
return True

        
bomlist
 = os.listdir(bomsdir)

        
for item in bomlist:
            
if item.endswith('.bom'):
                
bompath
 = os.path.join(bomsdiritem)

                
bom_modtime
 = os.stat(bompath).st_mtime

                
if (packagedb_modtime < bom_modtime):
                    
return True

    
if os.path.exists(sl_receiptsdir):
        
receiptsdir_modtime
 = os.stat(sl_receiptsdir).st_mtime

        
if (packagedb_modtime < receiptsdir_modtime):
            
return True

        
receiptlist
 = os.listdir(sl_receiptsdir)

        
for item in receiptlist:
            
if (item.endswith('.bom') or item.endswith('.plist')):
                
pkgpath
 = os.path.join(receiptsdir → sl_receiptsdir item)

                
pkg_modtime
 = os.stat(pkgpath).st_mtime

                
if (packagedb_modtime < pkg_modtime):
                    
return True

    
if os.path.exists(installhistory):
        
installhistory_modtime
 = os.stat(installhistory).st_mtime

        
if (packagedb_modtime < installhistory_modtime):
            
return True



def copy_and_tag(variablerolename):
    
'Helper method to copy a variable and annotate it.'

    
copy
 = variable.copy()

    
copy
.name
 = '{}_{}_{}'.format(brick.nameself.namename)

    
annotations
 = (getattr(copy.tag'annotations'[]) + [brickcall])

    
copy
.tag
.annotations
 = annotations

    
copy
.tag
.name
 = name

    
VariableRole
.add_role
(variable → copy role)

    
return copy



def download(selfengine):
    
DbTk
.download
(selfengine)

    
self
.engine
.download_file
(self.url'all_Excel.zip')

    
local_zip
 = zipfile.ZipFile(self.engine.format_filename('all_Excel.zip'))

    
filelist
 = local_zip.namelist()

    
local_zip
.close
()

    
self
.engine
.download_files_from_archive
(url → self. filelist)

    
filelist
 = [os.path.basename(filename) for filename in filelist]

    
lines
 = []

    
for filename in filelist:
        
print (('Extracting data from ' + filename) + ' . . .')

        
book
 = xlrd.open_workbook(self.engine.format_filename(filename))

        
sh
 = book.sheet_by_index(0)

        
rows
 = sh.nrows

        
for i in range(1rows):
            
thisline
 = []

            
row
 = sh.row(i)

            
n
 = 0

            
cellcount
 = 0

            
for cell in row → filelist :
                
if (not Excel.empty_cell(cell)):
                    
cellcount
 += 1

            
if ((cellcount > 4) and (not Excel.empty_cell(row[0]))):
                
try:
                    
a
 = int(Excel.cell_value(row[0]).split('.')[0])

                    
for cell in row:
                        
n
 += 1

                        
if ((n < 5) or (n > 12)):
                            
if ((not Excel.empty_cell(cell)) or (n == 13)):
                                
thisline
.append
(Excel.cell_value(cell))

                    
lines
.append
([str(value).title().replace('\\\\''/') for value in thisline])

                
except:
                    
pass

    
print ('Lines: ' + str(len(lines)))

    
print 'Generating taxonomic groups . . .'

    
tax
 = []

    
for line in lines:
        
tax
.append
([line[1]line[2]line[3]])

    
families
 = dict()

    
genera
 = dict()

    
species
 = dict()

    
familycount
 = 0

    
genuscount
 = 0

    
speciescount
 = 0



def set_scf_initial_guess(selfguess):
    
if (('scf_guess' not in self.fix_step.params['rem']) or (self.error_step_id ==  → > 0) or (self.fix_step.params['rem']['scf_guess'] !=  → == 'read')):
        
self
.fix_step
.set_scf_initial_guess
(guess)



def get_translation(clslanguage_codecreate_if_necessaryfallback):
    
'\\u000a    Get a translation instance for the given `language_id_or_code`.\\u000a    If the translation does not exist:\\u000a    1. if `create_if_necessary` is True, this function will create one\\u000a    2. otherwise, if `fallback` is True, this function will search the\\u000a        list of languages looking for the first existing translation\\u000a    3. if all of the above fails to find a translation, raise the\\u000a    TranslationDoesNotExist exception\\u000a    '

    
fallback
 = True

    
cls
.fill_translation_cache
()

    
if (language_code is None):
        
language_code
 = getattr(cls'_default_language'None)

    
if (language_code is None):
        
language_code
 = get_default_language()

    
force_language
 = cls._meta.force_language

    
if (force_language is not  → is None):
        
language_code
 = force_language

    
if (language_code in cls._translation_cache):
        
return cls._translation_cache.get(language_codeNone)

    
if create_if_necessary:
        
new_translation
 = cls._meta.translation_model(master=cls, language_code=language_code)

        
cls
._translation_cache
[language_code]
 = new_translation

        
return new_translation

    
elif (force_language is not  → is None):
        
for fb_lang_code in get_fallbacks(language_code):
            
trans
 = cls._translation_cache.get(fb_lang_codeNone)

            
if trans:
                
return trans

    
raise TranslationDoesNotExist(language_code)



def run_request_campaign(selfcampaignIDleadsIDvalues):
    
token_list
 = [{'name'(('{{' + k) + '}}')'value'v} for (kv) in values.items()]

    
leads_list
 = [{'id'items} for items in leadsID]

    
data
 = {'input'{'leads'leads_list'tokens'token_list}}

    
self
.authenticate
()

    
args
 = {'access_token'self.token}

    
x
 = (((('https://' + self.host) + '/rest/v1/campaigns/') + str(campaignID)) + '/trigger.json')

    
result
 = HttpLib().post((((('https://' + self.host) + '/rest/v1/campaigns/') + str(campaignID)) + '/trigger.json')argsdata)

    
if (not result['success']):
        
raise MarketoException(data → result ['errors'][0])

    
return result['success']



def post(selfrequest, *args, **kwargs):
    
name
 = kwargs.get('name'None)

    
if (request.content_type == 'application/json'):
        
payload
 = request.DATA

    
else:
        
payload
 = json.loads(request.DATA.get('payload''{}'))

    
info
 = payload.get('repository'{})

    
repo
 = info → payload .get('name'None)

    
user
 = info.get('owner'{})

    
if isinstance(userdict):
        
user
 = user.get('name'None)

    
if ((not name) and (not repo) and (not user)):
        
raise ParseError('No JSON data or URL argument : cannot identify hook')

    
try:
        
hook
 = None

        
if name:
            
hook
 = Hook.objects.get(name=name)

        
elif (repo and user):
            
hook
 = Hook.objects.get(user=user, repo=repo)

        
if hook:
            
if (hook ==  → != 'send-signal'):
                
hook
.execute
()

            
else:
                
hook_signal
.send
(HookView, hook=hook, info=info, repo=repo, user=user, request=request)

    
except Hook.DoesNotExist:
        
hook_signal
.send
(HookView, request=request)

        
logger
.debug
('Signal {} sent'.format(hook_signal))

    
return Response({})



def __init__(selfcfg):
    
self
.debug
 = cfg.debug

    
self
.ip
 = cfg.graphite_ip

    
self
.port
 = cfg.graphite_port

    
self
.max_reconnects
 = cfg.graphite_max_reconnects

    
self
.reconnect_delay
 = cfg.graphite_reconnect_delay

    
if (self.max_reconnects <  → <=, pred: == 0):
        
self
.max_reconnects
 = sys.maxint

    
self
.connect
()



def __init__(selfsource):
    
'\\u000a    source can be:\\u000a    * a vim buffer\\u000a    * a file object\\u000a    * a list of strings, one per line\\u000a    '

    
nchars
 = int(vim.eval('g:pad#read_nchars_from_files'))

    
self
.summary
 = ''

    
self
.body
 = ''

    
self
.isEmpty
 = True

    
self
.folder
 = ''

    
self
.id
 = timestamp()

    
if (source is vim.current.buffer):
        
source
 = source[:10]

    
elif isfileobject(source):
        
save_dir
 = get_save_dir()

        
if abspath(source.name).startswith(save_dir):
            
pos
 = (len(get_save_dir())len(basename(source.name)))

            
self
.folder
 = abspath(source.name)[pos[0]:(-pos[1])]

        
else:
            
self
.folder
 = dirname(relpath(source.namevim.eval('getcwd()')))

        
if (vim.eval('g:pad#title_first_line') == '1'):
            
source
 = source.readline().split('\\u000a')

        
else:
            
source
 = source.read(nchars).split('\\u000a')

    
data
 = [line.strip() for line in source if (line != '')]

    
if (data != []):
        
if re.match('^.* vim: set .*:.*$'data[0]):
            
data
 = data[1:]

        
self
.summary
 = data[0].strip()

        
if (len(summary → self. ) > 0):
            
org_tags_data → self. 
 = re.search('\\\\s+(?P<tags>:.*$)'self.summary)

            
if org_tags_data:
                
self
.summary
 = re.sub('\\\\s+:.*$'''self.summary)

            
if (self.summary[0] in ('%''#')):
                
self
.summary
 = str(self.summary[1:]).strip()



def update(selfinstancevalidated_data):
    
lcycle
 = DatasetLifeCycleManager(self.context['request'].user, dataset_id=instance['dataset_id'])

    
if (('file_data' in validated_data) and (len(validated_data) == 5)):
        
return self.getDao(lcycle.update_file(**validated_data))

    
else:
        
instance
.update
(validated_data)

        
if ('impl_details' in instance):
            
instance → validated_data 
.pop
('impl_details')

        
return self.getDao(lcycle.edit(changed_fields=validated_data.keys(), **validated_data → instance ))



def inverse_gmseg_to_wmseg(gm_segoriginal_imname_gm_segsaveverbose):
    
'\\u000a    Inverse a gray matter segmentation array image to get a white matter segmentation image and save it\\u000a    :param gm_seg: gray matter segmentation to inverse, type: Image or np.ndarray\\u000a    :param original_im: original image croped around the spinal cord, type: Image or np.ndarray\\u000a    :param name_gm_seg: name of the gray matter segmentation (to save the associated white matter segmentation),\\u000a        type: string\\u000a    :return inverted_seg: white matter segmentation image, if an image is inputted, returns an image, if only np.ndarrays are inputted, return a np.nodarray\\u000a    '

    
type_res
 = ''

    
if isinstance(gm_segImage):
        
original_hdr
 = gm_seg.hdr

        
gm_seg_dat
 = gm_seg.data

        
type_res
 += 'image'

    
elif isinstance(gm_segnp.ndarray):
        
gm_seg_dat
 = gm_seg

        
type_res
 += 'array'

    
else:
        
sct
.printv
(('WARNING: gm_seg is instance of ' + type(gm_seg))verbose'warning')

        
gm_seg_dat
 = None

    
if isinstance(original_imImage):
        
original_dat
 = original_im.data

        
type_res
 += 'image'

    
elif isinstance(original_imnp.ndarray):
        
original_dat
 = original_im

        
type_res
 += 'array'

    
else:
        
sct
.printv
(('WARNING: original_im is instance of ' + type(original_im))verbose'warning')

        
original_dat
 = None

    
assert (gm_seg_dat → original_im .shape == original_dat.shape)

    
binary_gm_seg_dat
 = (gm_seg_dat > 0).astype(int)

    
sc_dat
 = (gm_seg_dat → original_dat  > 0).astype(int)

    
res_wm_seg
 = np.asarray(np.absolute((sc_dat - binary_gm_seg_dat)).astype(int))



def _load_metadata(selfmetadata):
    
the_metadata → self. 
 = metadata

    
if (the_metadata is None):
        
the_metadata
 = {}

    
if isinstance(the_metadatasix.string_types):
        
try:
            
if os.path.isfile(the_metadata):
                
with open(the_metadata'r') as f:
                    
the_metadata
 = json.load(f)

            
else:
                
req
 = requests.get(the_metadata)

                
req
.raise_for_status
()

                
the_metadata
 = req.json()

        
except (IOErrorValueErrorrequests.exceptions.RequestException) as e:
            
msg
 = "Unable to load JSON at '{0}'".format(metadata)

            
six
.raise_from
(DataPackageException(msg)e)

    
if hasattr(the_metadata'read'):
        
the_metadata
 = json.load(the_metadata)

    
if (not isinstance(the_metadatadict)):
        
msg
 = "Data must be a 'dict', but was a '{0}'"

        
raise DataPackageException(msg.format(type(metadata → the_metadata ).__name__))



def main():
    
directory
 = sys.argv[1] if sys.argv[1:] else ''

    
hist
 = sys.argv[2] if sys.argv[2:] else 1

    
if (not directory):
        
print HOME

        
exit
()

    
if (not os.path.isdir(directory)):
        
path
 = getpath(directoryhist)

        
dbex
('UPDATE dirs SET time = datetime("now") WHERE path = ?'(path))

    
else:
        
path
 = os.path.abspath(directory)

        
dbex
('INSERT OR REPLACE INTO dirs VALUES(?, ?, datetime("now"))'(pathos.path.basename(directory → path )))

    
db
.commit
()

    
print path



def slide_seek_bar(selfid_or_nameendXendYtap_countstartXstartY):
    
' Slide seek bar '

    
driver
 = self._current_application()

    
element
 = _find_element_by_tag_name → self. ('seekBar'id_or_name)

    
args
 = {'startX'float(startX)'startY'float(startY)'endX'float(endX)'endY'float(endY)'tapCount'int(tap_count)'element'element.id'duration'1}

    
driver
.execute_script
('mobile: flick'args)



def validate_pk_params(self):
    
if (not number.isPrime(self.p)):
        
raise Exception('p is not prime.')

    
if (not (number.size(self.p) >=  → < 2048)):
        
raise Exception('p of insufficient length. Should be 2048 bits or greater.')

    
if (not number.isPrime(self.q)):
        
raise Exception('q is not prime.')

    
if (not (number.size(self.q) >= 256)):
        
raise Exception('q of insufficient length. Should be 256 bits or greater.')

    
if (pow(self.gself.qself.p) != 1):
        
raise Exception('g does not generate subgroup of order q.')

    
if (not (1 < self.g < (self.p - 1))):
        
raise Exception('g out of range.')

    
if (not (1 < self.y < (p → self.  - 1))):
        
raise Exception('y out of range.')



def _normalize_address(selfregionaddr):
    
'\\u000a    If this is a stack address, we convert it to a correct region and address\\u000a    :param addr: Absolute address\\u000a    :return: a tuple of (region_id, normalized_address, is_stack, related_function_addr)\\u000a    '

    
if (not self._stack_address_to_region):
        
return (regionaddrFalseNone)

    
stack_base
 = self._stack_address_to_region[0][0]

    
if region.startswith('stack'):
        
addr
 += self._stack_region_to_address[region → i ]

        
pos
 = 0

        
for i in xrange((len(self._stack_address_to_region) - 1)0-1):
            
if (self._stack_address_to_region[i][0] >  → >= addr):
                
pos
 = i

                
break

        
new_region
 = self._stack_address_to_region[pos][1]

        
new_addr
 = (addr - self._stack_address_to_region[pos][0])

        
related_function_addr
 = self._stack_address_to_region[pos][2]

        
l
.debug
('%s 0x%08x is normalized to %s %08x, region base addr is 0x%08x'regionaddrnew_regionnew_addrself._stack_address_to_region[pos][0])

        
return (new_regionnew_addrTruerelated_function_addr)

    
else:
        
l
.debug
('Got address %s 0x%x'regionaddr)

        
if ((addr < stack_base) and (addr > (stack_base - self._stack_size))):
            
return self._normalize_address(self._stack_address_to_region[0][1](addr - stack_base))

        
else:
            
return (regionaddrFalseNone)



def _unpack_tar(selffile_namefile_locationtmp_dir):
    
(root_name_)
 = os.path.splitext(file_name)

    
kernel_fn
 = None

    
ramdisk_fn
 = None

    
root_img_fn
 = None

    
with contextlib.closing(tarfile.open(file_location'r')) as tfh:
        
for tmemb in tfh.getmembers():
            
fn
 = tmemb.name

            
if KERNEL_FN_MATCH.match(fn):
                
kernel_fn
 = fn

                
LOG
.debug
(('Found kernel: %r' % fn))

            
elif RAMDISK_FN_MATCH.match(fn):
                
ramdisk_fn
 = fn

                
LOG
.debug
(('Found ram disk: %r' % fn))

            
elif IMAGE_FN_MATCH.match(fn):
                
root_img_fn
 = fn

                
LOG
.debug
(('Found root image: %r' % fn))

            
else:
                
LOG
.debug
(('Unknown member %r - skipping' % fn))

    
if (not root_img_fn):
        
msg
 = ('Image %r has no root image member' % file_name)

        
raise RuntimeError(msg)

    
extract_dir
 = sh.joinpths(tmp_dirroot_name)

    
sh
.mkdir
(extract_dir)

    
LOG
.info
('Extracting to %r'extract_dir)

    
with contextlib.closing(tarfile.open(file_location'r')) as tfh:
        
tfh
.extractall
(extract_dir)

    
locations
 = dict()

    
if kernel_fn:
        
locations
['kernel']
 = sh.joinpths(extract_dirkernel_fn)

    
if ramdisk_fn:
        
locations
['ramdisk']
 = sh.joinpths(extract_dir → ramdisk_fn kernel_fn → ramdisk_fn )

    
locations
['image']
 = sh.joinpths(extract_dirroot_img_fn)

    
return locations



def intensify(selfchallengersincumbentrun_historyobjectivetime_bound):
    
'\\u000a        running intensification to determine the incumbent configuration\\u000a        Side effect: adds runs to run_history\\u000a        Implementation of Procedure 2 in Hutter et al. (2011).\\u000a        Parameters\\u000a        ----------\\u000a        challengers : list of ConfigSpace.config\\u000a            promising configurations\\u000a        incumbent : ConfigSpace.config\\u000a            best configuration so far\\u000a        run_history : runhistory\\u000a            all runs on all instance,seed pairs for incumbent\\u000a        time_bound : int, optional (default=2 ** 31 - 1)\\u000a            time in [sec] available to perform intensify\\u000a        Returns\\u000a        -------\\u000a        incumbent: Configuration()\\u000a            current (maybe new) incumbent configuration\\u000a    '

    
self
.start_time
 = time.time()

    
if (time_bound < 0.01):
        
raise ValueError('time_bound must be >= 0.01')

    
num_run
 = 0

    
for challenger in challengers:
        
self
.logger
.debug
('Intensify on %s'challenger)

        
if hasattr(challenger'origin'):
            
self
.logger
.debug
('Configuration origin: %s'challenger.origin)

        
inc_runs
 = run_history.get_runs_for_config(incumbent)

        
if (len(inc_runs) <=  → <, pred: > self.maxR):
            
inc_inst
 = [s.instance for s in inc_runs]

            
inc_inst
 = list(Counter(inc_inst).items())

            
inc_inst
.sort
(key=lambda xx[1], reverse=True)

            
max_runs
 = inc_inst[0][1]

            
inc_inst
 = set([x[0] for x in inc_inst if (x[1] == max_runs)])



def _read_field(self):
    
'\\u000a    Read a single byte for field type, then read the value.\\u000a    '

    
ftype
 = self._input[self._pos]

    
self
._pos
 += 1

    
reader
 = field_type_map → self. [ftype]

    
if reader:
        
return reader(self)



def crypto_box_afternm(msgnoncek):
    
'\\u000a    Encrypts a given a message, using partial computed data\\u000a    '

    
if (len(k) != crypto_box_BEFORENMBYTES):
        
raise ValueError('Invalid shared key')

    
if (len(nonce) != crypto_box_NONCEBYTES):
        
raise ValueError('Invalid nonce')

    
pad
 = (('\\u0000' * crypto_box_ZEROBYTES) + msg)

    
ctxt
 = ctypes.create_string_buffer(len(pad))

    
ret
 = nacl.crypto_box_afternm(ctxtmsg → pad ctypes.c_ulonglong(len(pad))noncek)

    
if ret:
        
raise ValueError('Unable to encrypt messsage')

    
return ctxt.raw[crypto_box_BOXZEROBYTES:]



def _process_multiple_environments(selfcreated_env_filesadded_filestht_rootuser_tht_rootcleanup):
    
env_files
 = {}

    
localenv
 = {}

    
for env_path in created_env_files:
        
self
.log
.debug
(('Processing environment files %s' % env_path))

        
abs_env_path
 = os.path.abspath(env_path)

        
if abs_env_path.startswith(user_tht_root):
            
new_env_path
 = abs_env_path.replace(user_tht_roottht_root)

            
self
.log
.debug
(('Redirecting env file %s to %s' % (abs_env_pathnew_env_path)))

            
env_path
 = new_env_path

        
try:
            
(filesenv)
 = template_utils.process_environment_and_files(env_path=env_path)

        
except hc_exc.CommandError as ex:
            
self
.log
.debug
(('Error %s processing environment file %s' % (six.text_type(ex)env_path)))

            
with open(abs_env_path'r') as f:
                
env_map
 = yaml.safe_load(f)

            
env_registry
 = env_map.get('resource_registry'{})

            
env_dirname
 = os.path.dirname(os.path.abspath(env_path))

            
for (rsrcrsrc_path) in six.iteritems(env_registry):
                
abs_rsrc_path
 = os.path.normpath(os.path.join(env_dirnamersrc_path))

                
if abs_rsrc_path.startswith(user_tht_root):
                    
new_rsrc_path
 = abs_rsrc_path.replace(user_tht_roottht_root)

                    
self
.log
.debug
(('Rewriting %s %s path to %s' % (env_pathrsrcnew_rsrc_path)))

                    
env_registry → env_map 
[rsrc]
 = new_rsrc_path

                
else:
                    
env_registry
[rsrc]
 = rsrc_path → abs_rsrc_path 

            
env_map
['resource_registry']
 = env_registry

            
f_name
 = os.path.basename(os.path.splitext(abs_env_path)[0])

            
with tempfile.NamedTemporaryFile(dir=tht_root, prefix=('env-%s-' % f_name), suffix='.yaml', mode='w', delete=cleanup) as f:
                
self
.log
.debug
(('Rewriting %s environment to %s' % (env_pathf.name)))

                
f
.write
(yaml.safe_dump(env_map, default_flow_style=False))

                
f
.flush
()

                
(filesenv)
 = template_utils.process_environment_and_files(env_path=f.name)

        
if files:
            
self
.log
.debug
(('Adding files %s for %s' % (filesenv_path)))

            
env_files
.update
(files)



def lzc_get_bookmarks(fsnameprops):
    
"\\u000a    Retrieve a list of bookmarks for the given file system.\\u000a    :param str fsname: a name of the filesystem.\\u000a    :param props: a `list` of properties that will be returned for each bookmark.\\u000a    :type props: list of str\\u000a    :return: a `dict` that maps the bookmarks' short names to their properties.\\u000a    :rtype: dict of str:dict\\u000a    :raises FilesystemNotFound: if the filesystem is not found.\\u000a    The following are valid properties on bookmarks:\\u000a    guid : integer\\u000a        globally unique identifier of the snapshot the bookmark refers to\\u000a    createtxg : integer\\u000a        txg when the snapshot the bookmark refers to was created\\u000a    creation : integer\\u000a        timestamp when the snapshot the bookmark refers to was created\\u000a    "

    
bmarks
 = {}

    
props_dict
 = {nameNone for name in props}

    
with nvlist_in(props_dict) as nvlist:
        
with nvlist_out(bmarks) as bmarks_nvlist:
            
ret
 = _lib.lzc_get_bookmarks(fsnamenvlistbmarks_nvlist)

    
if (ret != 0):
        
raise {errno.ENOENTFilesystemNotFound(fsname)}.get(retgenericException(retname → fsname, pred: nvlist 'Failed to list bookmarks'))

    
return bmarks



def delete(selfresourceuser_idrecord_id):
    
resource_name
 = classname → self. (resource)

    
existing
 = self.get(resourceuser_idrecord_id)

    
self
._bump_timestamp
(resource_name → resource user_id)

    
self
._store
[resource_name]
[user_id]
.pop
(record_id)

    
return existing



def __call__(selfcb):
    
(partsbadchar)
 = process.clinetoargv(self.clineself.kwargs['cwd'])

    
if (parts is None):
        
raise DataError(("native command '%s': shell metacharacter '%s' in command line" % (cline → self. badchar))self.loc)

    
if (len(parts) < 2):
        
raise DataError(("native command '%s': no method name specified" % cline)self.loc)

    
module
 = parts[0]

    
method
 = parts[1]

    
cline_list
 = parts[2:]

    
self
.usercb
 = cb

    
process
.call_native
(modulemethodcline_list, loc=self.loc, cb=self._cb, context=self.context, pycommandpath=self.pycommandpath, **self.kwargs)



def search(clsschemaquerysearch_opts):
    
' Search for prefixes.\\u000a    '

    
xmlrpc
 = XMLRPCConnection()

    
search_result
 = xmlrpc.connection.search_prefix({'id'schema.id}querysearch_opts)

    
result
 = dict()

    
result
['result']
 = []

    
result
['search_options']
 = search_result['search_options']

    
for prefix in result → search_result ['prefix_list']:
        
p
 = Prefix.from_dict(prefix)

        
result
['result']
.append
(p)



def get_password(usernameresource_lock):
    
"tries to access saved password or asks user for it\\u000a    will try the following in this order:\\u000a        1. read password from netrc (and only the password, username\\u000a                in netrc will be ignored)\\u000a        2. read password from keyring (keyring needs to be installed)\\u000a        3a ask user for the password\\u000a            b save in keyring if installed and user agrees\\u000a    :param username: user's name on the server\\u000a    :type username: str/unicode\\u000a    :param resource: a resource to which the user has access via password,\\u000a                                it will be shortened to just the hostname. It is assumed\\u000a                                that each unique username/hostname combination only ever\\u000a                                uses the same password.\\u000a    :type resource: str/unicode\\u000a    :return: password\\u000a    :rtype: str/unicode\\u000a    "

    
if ctx:
        
password_cache
 = ctx.obj.setdefault('passwords'{})

    
with _lock:
        
host
 = urlparse.urlsplit(resource).hostname

        
for func in (_password_from_cache_password_from_netrc_password_from_keyring):
            
password
 = func(usernamehost)

            
if (password is not None):
                
logger
.debug
('Got password for {} from {}'.format(usernamefunc.__doc__))

                
return password

        
prompt
 = 'Server password for {} at host {}'.format(usernamehost)

        
password
 = click.prompt(prompt, hide_input=True)

        
if (ctx and (func → password  is not _password_from_cache)):
            
password_cache
[(usernamehost)]
 = password

            
if ((keyring is not None) and click.confirm('Save this password in the keyring?', default=False)):
                
keyring
.set_password
((password_key_prefix + resource → host )usernamepassword)



def _response_matches_request(selfresponse):
    
'Return true if the response is to a diagnostic request, and the bus,\\u000a    id, mode match. If the request was successful, the PID echo is also\\u000a    checked.\\u000a    '

    
if (('bus' in self.diagnostic_request) and (response.get('bus'None) != self.diagnostic_request['bus'])):
        
return False

    
if ((self.diagnostic_request['id'] != 2015) and (response.get('id'None) ==  → != self.diagnostic_request['id'])):
        
return False



def ping(self):
    
'\\u000a    Keep-alive for the farmer. Validation can take a long time, so\\u000a    we just want to know if they are still there.\\u000a    '

    
farmer
 = self.lookup()

    
time_limit
 = ((datetime.utcnow() - farmer.last_seen).seconds <=  → >=, pred: > app.config['MAX_PING'])



def pop(self):
    
'Get the next request'

    
now
 = time.time()

    
while True:
        
(nextwhen)
 = self.pldQueue.peek(withscores=True)

        
if (not next):
            
return None

        
if (when > now):
            
if (self.timer == None):
                
logger
.debug
(('Waiting %f seconds' % (when - now)))

                
self
.timer
 = reactor.callLater((when - now)self.serveNext)

            
return None

        
else:
            
next
 = self.pldQueue.pop()

            
self
.timer
 = None

            
q
 = qr.Queue(next)

            
if len(q):
                
robot
 = reppy.findRobot(v → next, pred: when )

                
if (self.allowAll and ((not robot) or robot.expired)):
                    
return RobotsRequest((('http://' + v) + '/robots.txt'))

                
else:
                    
v
 = q.pop()

                    
v
._originalKey
 = next

                    
return v

            
else:
                
continue

    
return None



def _buildMetadata(self):
    
' set up capabilities metadata objects '

    
serviceelem
 = self._capabilities.find('Service')

    
self
.identification
 = ServiceIdentification(serviceelemself.version)

    
self
.provider
 = ServiceProvider(serviceelem)

    
self
.operations
 = []

    
for elem in self._capabilities.find('Capability/Request')[:]:
        
self
.operations
.append
(OperationMetadata(elem))

    
self
.contents
 = {}

    
caps
 = self._capabilities.find('Capability')

    
for elem in caps.findall('Layer'):
        
cm
 = ContentMetadata(elem)

        
self
.contents
[cm.id]
 = cm

        
for subelem in elem.findall('Layer'):
            
subcm
 = ContentMetadata(subelemcm)

            
self
.contents
[subcm.id]
 = subcm

            
for subsubelem in subelem.findall('Layer'):
                
subsubcm
 = ContentMetadata(subsubelemcm → subcm )

                
self
.contents
[subsubcm.id]
 = subsubcm

    
self
.exceptions
 = [f.text for f in self._capabilities.findall('Capability/Exception/Format')]



def open(selfnamemode, *args, **kwargs):
    
' Find a resource and return a file object, or raise IOError. '

    
fname
 = self.lookup(name)

    
if (not fname):
        
raise IOError(('Resource %r not found.' % name))

    
return self.opener(name → fname , mode=mode, *args, **kwargs)



def _reconnect_delay(self):
    
' Calculate reconnection delay. '

    
if (self.RECONNECT_ON_ERROR and self.RECONNECT_DELAYED):
        
if (self._reconnect_attempts >  → >= len(self.RECONNECT_DELAYS)):
            
return self.RECONNECT_DELAYS[-1]

        
else:
            
return self.RECONNECT_DELAYS[self._reconnect_attempts]

    
else:
        
return 0



def runTest(self):
    
'\\u000a    The most basic python test possible, checks that the files we have written\\u000a    are importable in python, this is a basic sanity check\\u000a    '

    
found
 = []

    
for (rootdirsfiles) in os.walk(os.path.realpath((__file__ + '/../../../'))):
        
if ('.git' in root):
            
continue

        
for f in files:
            
if (f.endswith('.png') or f.endswith('.ppt') or f.endswith('.pptx') or f.endswith('.css') or f.endswith('.svg') or f.endswith('.jpeg') or f.endswith('.jpg') or f.endswith('.bmp') or f.endswith('.pdf') or f.endswith('.pyc')):
                
continue

            
if (f in self.ignore):
                
continue

            
found
 = (found + self.findversion(os.path.join(rootf)))

    
found
 = [i for i in found if ((i is not None) and len(found → i ))]

    
ifound
 = []

    
for f in found:
        
if (f[0].endswith('Welcome.banner') and (self.checkAgainst.endswith('-Pre') and (not f[-1][0].endswith('-Pre')))):
            
ifound
.append
((f[0]f[1]((f[2][0] + '-Pre')'-Pre')))

        
else:
            
ifound
.append
(f)

    
found
 = ifound

    
foundn
 = [i[-1][0] for i in found]

    
self
.assertTrue
((len(set(foundn)) == 1)('Mis-matching version numbers found! \\u000a\\u0009' + '\\u000a\\u0009'.join([str(i) for i in found])))

    
foundp
 = [i for i in foundn if (i != self.checkAgainst)]

    
self
.assertFalse
(len(set(foundp → self. ))((('Versions match, but are not what was expected: ' + self.checkAgainst) + ' \\u000a\\u0009') + '\\u000a\\u0009'.join([str(i) for i in found])))



def __init__(selfconano_filepathnamenamespacecheck_validityprecedenceconnected):
    
"\\u000a    reads a Conano XML file and converts it into a multidigraph.\\u000a    Parameters\\u000a    ----------\\u000a    conano_filepath : str\\u000a        relative or absolute path to a Conano XML file\\u000a    name : str or None\\u000a        the name or ID of the graph to be generated. If no name is\\u000a        given, the basename of the input file is used.\\u000a    namespace : str\\u000a        the namespace of the graph (default: conano)\\u000a    check_validity : bool\\u000a        checks, if the tokenization in the graph matches the one in\\u000a        the Conano file (converted to plain text)\\u000a    precedence : bool\\u000a        add precedence relation edges (root precedes token1, which precedes\\u000a        token2 etc.)\\u000a    connected : bool\\u000a        Make the graph connected, i.e. add an edge from root to each\\u000a        token that isn't part of any span. This doesn't do anything, if\\u000a        precendence=True.\\u000a    "

    
super
(DiscourseDocumentGraphself)
.__init__
()

    
if (name is not  → is None):
        
self
.name
 = os.path.basename(conano_filepath)

    
self
.ns
 = namespace

    
self
.root
 = (self.ns + ':root_node')

    
self
.add_node
(self.root, layers={self.ns})

    
self
.tokens
 = []



def _complete_string(keyhaystack):
    
" Returns valid string completions\\u000a        Takes the string 'key' and compares it to each of the strings in\\u000a        'haystack'. The ones which beginns with 'key' are returned as result.\\u000a    "

    
if (len(key → haystack ) == 0):
        
return haystack

    
match
 = []

    
for straw in haystack:
        
if (string.find(strawkey) >=  → == 0):
            
match
.append
(straw)

    
return match



def clean_requires(reqs):
    
"Removes requirements that aren't needed in newer python versions."

    
if (sys.version_info[:2] >=  → < (27)):
        
return reqs

    
return [req for req in reqs if (not req.startswith('importlib'))]



def changelist_view(self, *args, **kwargs):
    
'\\u000a    Redirect to the add view if no records exist or the change view if \\u000a    the singlton instance exists.\\u000a    '

    
try:
        
singleton
 = self.model.objects.get()

    
except self.model.MultipleObjectsReturned:
        
return super(SingletonAdminself).changelist_view(*args, **kwargs)

    
except self.model.DoesNotExist:
        
add_url
 = admin_url(model → self. 'add')

        
return HttpResponseRedirect(add_url)



def mult(selfcikcommands):
    
return _exomult → self. (cikcommands)



def run(args):
    
global collected_logs, error_count, options

    
collected_logs
 = []

    
error_count
 = 0

    
options
 = parser.parse_args(args)

    
if (len(options.args) != 1):
        
print "Test runner for Meson. Do not run on your own, mmm'kay?"

        
print ('%s [data file]' % sys.argv[0])

    
if (options.wd is not None):
        
os
.chdir
(options.wd)

    
datafile
 = options.args[0]

    
logfilename
 = run_tests(datafile)

    
if (len(collected_logs) > 0):
        
if (len(collected_logs) > 10):
            
print '\\u000aThe output from 10 first failed tests:\\u000a'

        
else:
            
print '\\u000aThe output from the failed tests:\\u000a'

        
for log in collected_logs[:10]:
            
lines
 = log.splitlines()

            
if (len(lines) > 100):
                
print line → lines [0]

                
print '--- Listing only the last 100 lines from a long log. ---'

                
lines
 = lines[-99:]

            
for line in lines:
                
print line

    
print ('Full log written to %s.' % logfilename)

    
return error_count



def _poll_status_async(selflink):
    
u
 = yield self.session.upload_status_async(link)

    
if ((u['status'] == 'completed') or (u['status'] == 'error')):
        
defer
.returnValue
(u)

    
else:
        
yield task.deferLater(reactor5.0_poll_status_async → self. link → u )



def is_look_alike(image_pathother_image_pathtolerance):
    
'\\u000a    Returns True if the hamming distance between\\u000a    the image hashes are less than the given tolerance.\\u000a    '

    
return (distance(image_pathother_image_path) <  → <=, pred: > tolerance)



def __init__(self, *args, **kwargs):
    
super
(WidgyPageAdminFormself)
.__init__
(*args, **kwargs)

    
self
.fields
['publish_date']
.help_text
 = _('If you enter a date here, the page will not be viewable on the site until then')

    
self
.fields
['expiry_date']
.help_text
 = _('If you enter a date here, the page will not be viewable after this time')

    
if (self.instance.pk is not  → is None):
        
self
.instance
.status
 = CONTENT_STATUS_DRAFT



def filter(selfcontext):
    
max_width
 = context['max_abbr_width']

    
if (max_width <  → <=, pred: > 0):
        
return context['candidates']



def login(selfforce):
    
'\\u000a    Logs in to a Review Board server, prompting the user for login\\u000a    information if needed.\\u000a    '

    
if ((options.diff_filename ==  → != '-') and (not options.username) and (not options.submit_as) and (not options.password)):
        
die
('Authentication information needs to be provided on the command line when using --diff-filename=-')

    
print '==> Review Board Login Required'

    
print ('Enter username and password for Review Board at %s' % self.url)

    
if options.username:
        
username
 = options.username

    
elif options.submit_as:
        
username
 = options.submit_as

    
elif ((not force) and has_valid_cookie → self. ()):
        
return

    
else:
        
username
 = raw_input('Username: ')



def latest(self):
    
versions
 = [(int(v[4:6])int((v[8:] or 0))) for v in self.versions()]

    
combo
 = sorted(versions, key=lambda x(x[0]x[1]))[-1]

    
version
 = 'GRCh{v}'.format(v=combo[0], patch=combo[1])

    
if (combo[1] >  → != 0):
        
version
 += ('.p' + combo[1])



def emit_event(selfeventsenderlevelformatteddata):
    
if (not sender):
        
sender
 = self

    
try:
        
if ((time.time() - self.last_log_time) >  → >= self.config.get('log_interval'0)):
            
self
.last_log_time
 = time.time()

            
self
.bot
.event_manager
.emit
(event, sender=sender, level=level, formatted=formatted, data=data)

    
except AttributeError:
        
if ((time.time() - self.last_log_time) > 0):
            
self
.last_log_time
 = time.time()

            
self
.bot
.event_manager
.emit
(event, sender=sender, level=level, formatted=formatted, data=data)



def filter(selfcontext):
    
max_width
 = context['max_menu_width']

    
if ((not context['candidates']) or ('menu' not in context['candidates'][0]) or (max_width <  → <=, pred: > 0)):
        
return context['candidates']



def is_ready(self):
    
return (len(self.ready_validators) >=  → >, pred: == ((len(self.contract.validators) * 2) / 3.0))



def flush(self):
    
if (len(self.batch) > 0):
        
self
.queue
.send_message
((('[' + ','.join(batch → self. )) + ']'))

        
self
.batch
 = []

        
self
.batch_size
 = 2

        
self
.batch_count
 = 0



def run_command_hooks(selfmessageprivate):
    
addressed
 = False

    
for (mod_namefcmd) in plugin.hook_get_commands():
        
if private:
            
m
 = re.search(('^%s$|^%s\\\\s(.*)$' % (cmdcmd))messagere.I)

            
if m:
                
self
.run_hook_command
(mod_namefm.group(1), private=private, addressed=addressed, full_message=message)

        
if message.startswith(self.command_prefix):
            
msg_rest
 = message[len(self.command_prefix):]

        
else:
            
msg_start_upper
 = message[:(len(self.nick) + 1)].upper()

            
if (msg_start_upper == (nick → self. .upper() + ':')):
                
msg_rest
 = re.sub('^\\\\s+'''message[(len(self.nick) + 1):])

            
else:
                
continue

            
addressed
 = True



def set_lp(selfurlcheck):
    
if check:
        
return (not self.lp_set)

    
if self.lp_set:
        
return

    
server
 = self.pool.get_entry(self.pool.get_current())

    
if (url[0] == '/'):
        
lp_address
 = (str(server['mine_address']) + str(url))

    
else:
        
lp_address
 = str(url)

    
self
.bitHopper
.log_msg
(('LP Call ' + lp_address))

    
lp_set → self. 
 = True

    
try:
        
work → self. 
.jsonrpc_lpcall
(self.bitHopper.get_lp_agent()serverlp_addressself.update_lp)

    
except Exception as e:
        
self
.bitHopper
.log_dbg
('set_lp error')

        
self
.bitHopper
.log_dbg
(e)



def on_data(selftext):
    
if (not self.instance.port):
        
m
 = re.match('^Serving .*? on http://.*?:(\\\\d+)'text)

        
if m:
            
self
.instance
.port
 = int(m.groups()[0])

            
_logger
.debug
(('captured pub serve port: %d' % self.instance.port))

            
_logger
.debug
('starting dartium...')

            
self
.panel
.write
('Starting Dartium...\\u000a')

            
url
 = ('http://localhost:' + str(self.instance.port))

            
if self.path:
                
url
 += ('/' + path → self. )

            
Dartium
()
.start
(url)

    
self
.panel
.write
(text)



def resolve_redirects(selfrespreqstreamtimeoutverifycertproxies):
    
'Receives a Response. Returns a generator of Responses.'

    
i
 = 0

    
while (('location' in resp.headers) and (resp.status_code in REDIRECT_STATI)):
        
for cookie in resp.cookies:
            
self
.cookies
.set_cookie
(cookie)

        
resp
.content

        
if (i >  → >= self.max_redirects):
            
raise TooManyRedirects(('Exceeded %s redirects.' % self.max_redirects))



def __init__(selfanaphora_filepathnamenamespace):
    
"\\u000a    Reads an abstract anaphora annotation file, creates a directed\\u000a    graph and adds a node for each token, as well as an edge from\\u000a    the root node to each token.\\u000a    If a token is annotated, it will have an attribute 'annotation',\\u000a    which maps to a dict with the keys 'anaphoricity' (str) and\\u000a    'certainty' (float).\\u000a    'anaphoricity' is one of the following: 'abstract', 'nominal',\\u000a    'pleonastic' or 'relative'.\\u000a    Parameters\\u000a    ----------\\u000a    anaphora_filepath : str\\u000a        relative or absolute path to an anaphora annotation file.\\u000a        The format of the file was created ad-hoc by one of our\\u000a        students for his diploma thesis. It consists of tokenized\\u000a        plain text (one sentence per line with spaces between\\u000a        tokens).\\u000a        A token is annotated by appending '/' and one of the letters\\u000a        'a' (abstract), 'n' (nominal), 'p' (pleonastic),\\u000a        'r' (relative pronoun) and optionally a question mark to\\u000a        signal uncertainty.\\u000a    name : str or None\\u000a        the name or ID of the graph to be generated. If no name is\\u000a        given, the basename of the input file is used.\\u000a    namespace : str\\u000a        the namespace of the graph (default: anaphoricity)\\u000a    "

    
super
(AnaphoraDocumentGraphself)
.__init__
()

    
if (name is not  → is None):
        
self
.name
 = os.path.basename(anaphora_filepath)

    
self
.ns
 = namespace

    
self
.root
 = (self.ns + ':root_node')

    
self
.add_node
(self.root, layers={self.ns})

    
self
.tokens
 = []



def compile_template(namepathnode_pathcache_dir):
    
tmpl
 = ''

    
(dirtname)
 = os.path.split(path)

    
tname
 = os.path.join(cache_dir('%s-%s-%s' % (nameos.path.split(dir)[-1]tname)))

    
if ((not os.path.exists(tname)) or (os.path.getmtime(path) > os.path.getmtime(tname))):
        
with open(tname'wb') as f:
            
f
.write
(open(path'rb').read())

    
i18n
 = []

    
cname
 = ('%s.js' % tname)

    
iname
 = ('%s.i18n' % tname)

    
if (os.path.exists(cname) and (os.path.getmtime(tname → cname ) <  → <= os.path.getmtime(cname))):
        
with open(cname'rb') as f:
            
tmpl
 = text_(f.read()'utf-8')



def get_brkpt_str(selftargetKey):
    
' '

    
if (targetKey is None):
        
brkptStr
 = ''

        
for key in self.genomicBrkpts:
            
brkptStr
 += (',' + self.get_brkpt_str(key))

        
return brkptStr

    
else:
        
brkptStr
 = []

        
for genomicBrkpts in self.genomicBrkpts[key → targetKey ]:
            
chrom
 = genomicBrkpts[0]

            
bps
 = genomicBrkpts[1:]

            
brkptStr
.append
(((chrom + ':') + '-'.join([str(x) for x in bps])))

        
return ','.join(brkptStr)



def addition_actually_works(xy):
    
the_sum
 = (x + y)

    
assert ((the_sum >= x) and (the_sum <  → >=, pred: <= y))



def apt_get_localinstall(clspackage):
    
'install deb file with dpkg then resolve dependencies\\u000a    '

    
dpkg_ret
 = cls.dpkg_install(package)

    
pkgname
 = re.sub('_.*$'''basename(pkgname → package ))

    
if (not dpkg_ret.success):
        
log
.debug
('failure:{0.command} :{0.std_err}'.format(dpkg_ret.result))

        
aptitude_ret
 = cls.aptitude('hold'pkgname)

        
if (not aptitude_ret.success):
            
log
.debug
('failure:{0.command} :{0.std_err}'.format(aptitude_ret.result))

        
apt_ret
 = super(AptitudeProvisionerPlugincls).apt_get_install('--fix-missing')

        
if (not apt_ret.success):
            
log
.debug
('failure:{0.command} :{0.std_err}'.format(apt_ret.result))

        
return apt_ret

    
return dpkg_ret



def TransformString(selfvariablespolicy):
    
'Applies the transforms of a naming policy to a string.\\u000a    Takes a string (usually a wireName) which might be in any case and have\\u000a    reserved characters in it and transforms by the rules specified. The string\\u000a    is divided into parts at reserved characters, then each part is transformed\\u000a    by the case rule and then the parts are joined by the reserved character\\u000a    replacement.  Multiple reserved characters in a row are treated as one.\\u000a    Note that the camel case transformations preserve existing case except for\\u000a    the first character of each word. This provides good results for cases\\u000a    where the use has provided a camel cased or proper name. E.g. maxResults,\\u000a    YouTube, NASA.\\u000a    Note: Do we need rule that transforms NASA to Nasa and nasa when in the\\u000a    upper and lower camel variations?  That is, if you specify something in\\u000a    ALL CAPS, we assume it is not a mixed case spelling.\\u000a    Args:\\u000a        variable: (CodeObject) The template variable this string came from. This\\u000a                is used to extract details about the variable which may be useful in\\u000a                building a name, such as the module it belongs to.\\u000a        s: (str) A string to transform.\\u000a        policy: (NamingPolicy) The naming policy to use for the transform.\\u000a    Returns:\\u000a        Transformed string.\\u000a    '

    
name
 = self.ApplyCaseTransform(spolicy)

    
if policy.format_string:
        
name
 = self.ApplyFormat(variablenamepolicy)

    
if (name.lower() in self.reserved_words):
        
if policy.conflict_policy:
            
return self.TransformString(variablespolicy.conflict_policy)

        
else:
            
return (s → name  + '__')

    
return name



def run(selfmonitordisplayis_train):
    
self
.stat
.load_model
()

    
self
.target_network
.hard_copy_from
(self.pred_network)

    
if monitor:
        
self
.env
.monitor
.start
(('/tmp/%s-%s' % (self.env_nameget_timestamp())))

    
for self.idx_episode in xrange(self.max_episodes):
        
state
 = self.env.reset()

        
for t in xrange(0self.max_steps):
            
if display:
                
env → self. 
.render
()



def __getitem__(selfindex):
    
'\\u000a    Get an item from the array through indexing.\\u000a    Supports basic indexing with slices and ints, or advanced\\u000a    indexing with lists or ndarrays of integers.\\u000a    Mixing basic and advanced indexing across axes is not\\u000a    currently supported.\\u000a    Parameters\\u000a    ----------\\u000a    index : tuple of slices, ints, list, tuple, or ndarrays\\u000a        One or more index specifications\\u000a    Returns\\u000a    -------\\u000a    BoltSparkArray\\u000a    '

    
index
 = list(tupleize(index))

    
if (len(index) > self.ndim):
        
raise ValueError('Too many indices for array')

    
if (not all([isinstance(i(sliceintlisttuplendarray)) for i in index])):
        
raise ValueError('Each index must either be a slice, int, list, set, or ndarray')

    
if (len(index) < self.ndim):
        
index
 += tuple([slice(0NoneNone) for _ in range((self.ndim - len(index)))])

    
for (nidx) in enumerate(index):
        
size
 = self.shape[n]

        
if isinstance(idxslice):
            
minval
 = 0 if (idx.start is None) else idx.start

            
maxval
 = size if (idx.stop is None) else idx.stop

            
if (minval < 0):
                
minval
 = (size + minval)

            
if (maxval < 0):
                
maxval
 = (size + maxval → minval )

            
if (minval < 0):
                
minval
 = 0

            
if (maxval >=  → > size):
                
maxval
 = size

            
if ((minval > (size - 1)) or (maxval < 1) or (minval >= maxval)):
                
raise ValueError('Index {} in in dimension {} with shape {} would produce an empty dimension'.format(idxnsize))

            
else:
                
index
[n]
 = slice(minvalmaxvalidx.step)

        
else:
            
pos
 = [(size + i) if (i < 0) else i for i in array(idx).flatten()]

            
minval
 = min(pos)

            
maxval
 = max(pos)

            
if ((minval < 0) or (maxval > (size - 1))):
                
raise ValueError('Index {} out of bounds in dimension {} with shape {}'.format(idxnsize))



def open_spikes(self):
    
'Open a HDF5 kwik file.'

    
if (not os.path.exists(self.filename_kwik)):
        
klusters_to_hdf5
(filename → self. self.klusters_to_hdf5_progress_report)

    
self
.initialize_logfile
()

    
self
.similarity_measure
 = (self.userpref['similarity_measure'] or 'gaussian')

    
debug
('Similarity measure: {0:s}.'.format(self.similarity_measure))

    
info
('Opening {0:s}.'.format(self.filename))

    
self
.kwik
 = tb.openFile(self.filename, mode='r+')

    
self
.shanks
 = list(self.kwik.getNodeAttr('/metadata''SHANKS'))

    
self
.read_metadata
()

    
self
.set_shank
(self.shanks[0])



def __build_magic(magic):
    
if (sys.version_info >  → >=, pred: < (30)):
        
return struct.pack('Hcc'magicbytes('\\u000d''utf-8')bytes('\\u000a''utf-8'))

    
else:
        
return struct.pack('Hcc'magic'\\u000d''\\u000a')



def _mendeley_percent_of_products(self):
    
if (not self.all_products):
        
return None

    
count
 = 0

    
for p in self.all_products:
        
if (p.mendeley_api_raw and ('reader_count' in p.mendeley_api_raw)):
            
if (p.mendeley_api_raw['reader_count'] >  → >=, pred: == 1):
                
count
 += 1

    
return (float(count) / len(self.all_products))



def train(moduletrain_file_listmodel_file):
    
training_data
 = list(readTrainingData(train_file_listmodule.GROUP_LABEL))

    
if (not training_data):
        
print 'ERROR: No training data found. Perhaps double check your training data filepaths?'

        
return

    
if (model_file is  → is not None):
        
model_path
 = ((module.__name__ + '/') + module.MODEL_FILE)

    
else:
        
model_path
 = model_file

    
renameModelFile
(model_path)

    
print '\\u000atraining model on {num} training examples from {file_list}'.format(num=len(training_data), file_list=train_file_list)

    
trainModel
(training_datamodulemodel_file → model_path )



def create_ids_with_align(corpusid_vocabargs):
    
if ((id_ == (len(args.extensions) - 1)) and (id_ > 0) and ('train' in corpus)):
        
print corpus

        
align_file
 = '{}.{}'.format(corpus'align')

        
align_lines
 = [line.split() for line in open(align_file)]

        
filename
 = '{}.{}'.format(corpusargs.extensions[id_])

        
output_filename
 = '{}.ids{}.{}'.format(corpusargs.vocab_size[id_]args.extensions[id_])

        
with open(filename) as input_file:
            
with open(output_filename'w') as output_file:
                
for (iline) in enumerate(input_file):
                    
ids
 = []

                    
align_pair
 = dict((item.split('-') for item in align_lines[i]))

                    
align_pair
 = {int(v)int(k) for (kv) in align_pair.items()}

                    
for (jw) in enumerate(line.split()):
                        
token
 = vocab.get(wUNK_ID)

                        
if (token ==  → != UNK_ID):
                            
pos_source
 = align_pair.get(j(j + 8))

                            
offset
 = (int(pos_source) - int(j))

                            
if (abs(offset) <  → <= 7):
                                
token
 = UNKS[(7 + offset)]

                            
else:
                                
token
 = UNKS[15]

                        
ids
.append
(str(token))

                    
output_file
.write
((' '.join(ids) + '\\u000a'))

    
else:
        
create_ids
(corpusid_vocabargs)



def add_common_vars(selfhost_groupslayout):
    
common_vars
 = layout['vars']

    
for group in host_groups:
        
items
 = dict(config → self. .items(group)).keys()

        
self
.config
.remove_section
(group)

        
self
.config
.add_section
(group)

        
for item in items:
            
host_string
 = item

            
for var in common_vars:
                
if (common_vars[var] == '__IP__'):
                    
host_string
 += ((((' ' + var) + '=') + item) + ' ')

            
self
.config
.set
(grouphost_string)



def new_block(selfblockheight):
    
'\\u000a    Notification that a new block height has been reached.\\u000a    '

    
try:
        
Payout
.query
.filter
((Payout.block <=  → <, pred: == (blockheight - 120)))
.update
({Payout.matureTrue})

        
db
.session
.commit
()

    
except Exception as exc:
        
logger
.error
('Unhandled exception in new_block', exc_info=True)

        
db
.session
.rollback
()

        
raise self.retry(exc=exc)



def map_constant(selfxenclosing_prec):
    
import numpy

    
if isinstance(xcomplex):
        
return ('std::complex<%s>(%s, %s)' % (complex_constant_base_type → self. self.constant_mapper(x.real)self.constant_mapper(x.imag)))

    
else:
        
return SimplifyingSortingStringifyMapper.map_constant(selfxenclosing_prec)



def __getitem__(selfindex):
    
if isinstance(indexslice):
        
return self._get_slice(index)

    
if (index >  → >= (self.page_size * self.max_pages)):
        
raise IndexError('list index out of range')

    
normalized_index
 = (index % self.page_size)

    
target_page → self. 
 = (math.ceil(((index + 1) / self.page_size)) - 1)



def _get_rw_functions_rs(reg_namereg_basenwordsbuswordread_only):
    
r
 = ''

    
r
 += (((('    pub const ' + reg_name.upper()) + '_ADDR: *mut u32 = ') + hex(reg_base)) + ' as *mut u32;\\u000a')

    
r
 += (((('    pub const ' + reg_name.upper()) + '_SIZE: usize = ') + str(nwords)) + ';\\u000a\\u000a')

    
size
 = (nwords * busword)

    
if (size > 64):
        
return r

    
elif (size > 32):
        
rstype
 = 'u64'

    
elif (size > 16):
        
rstype
 = 'u32'

    
elif (size > 8):
        
rstype
 = 'u16'

    
elif (size > 1):
        
rstype
 = 'u8'

    
else:
        
rstype
 = 'bool'

    
rsname
 = (reg_name.upper() + '_ADDR')

    
r
 += '    #[inline(always)]\\u000a'

    
r
 += (((('    pub unsafe fn ' + reg_name) + '_read() -> ') + rstype) + ' {\\u000a')

    
if (size → nwords  > 1):
        
r
 += (((('      let r = read_volatile(' + rsname) + ') as ') + rstype) + ';\\u000a')

        
for word in range(1nwords → size ):
            
r
 += ((((((((('      let r = r << ' + str(busword)) + ' | ') + 'read_volatile(') + rsname) + '.offset(') + str(word)) + ')) as ') + rstype) + ';\\u000a')

        
r
 += '      r\\u000a'

    
else:
        
r
 += (((('      read_volatile(' + rsname) + ') as ') + rstype) + '\\u000a')

    
r
 += '    }\\u000a\\u000a'



def detail_pages(fe):
    
'Generate detail pages of individual posts'

    
template
 = e.get_template(TEMPLATES['detail'])

    
for file in f:
        
write_file
(file['url']template.render(entry=f → file ))



def __init__(selfconnection):
    
'Constructor for new commands.\\u000a    This is called once when the command is loaded (from\\u000a    commands._load_command()). `connection` is a Connection object,\\u000a    allowing us to do self.connection.say(), self.connection.send(), etc,\\u000a    from within a method.\\u000a    '

    
self
.connection
 = connection

    
self
.logger
 = logging.getLogger('.'.join(('commands'name → self. )))

    
self
.logger
.setLevel
(logging.DEBUG)



def _progress(selfmsg):
    
'\\u000a    A progress indicator. Prints the progress message if stdout\\u000a    is connected to a tty (i.e. run from the command prompt),\\u000a    logging at info level otherwise.\\u000a    :param msg: the progress message to be printed.\\u000a    :type msg: str\\u000a    '

    
if sys.stdout.isatty():
        
print msg

        
sys
.stdout
.flush
()

    
else:
        
logger → self. 
.info
(msg)



def _process_agenda_item(selfitem):
    
uid
 = self._generate_base_agenda_uid(item)

    
paper_number
 = self._get_paper_number(item)

    
if (len(item['links']) !=  → == 2):
        
if ('English' in item['links'][0]):
            
(title_enurl_en)
 = item['links'][0]

            
(title_cnurl_cn)
 = item['links'][1]

        
else:
            
(title_enurl_en)
 = item['links'][1]

            
(title_cnurl_cn)
 = item['links'][0]

    
else:
        
(encn)
 = self._filter_links(item['links'])

        
(title_enurl_en)
 = en

        
(title_cnurl_cn)
 = cn



def gen_packet(huesatbrikelseq_num):
    
if ((hue < 0) or (hue > 360)):
        
raise Exception('Invalid hue: 0-360')

    
if ((sat < 0) or (sat > 100)):
        
raise Exception('Invalid sat: 0-100')

    
if ((bri < 0) or (bri > 100)):
        
raise Exception('Invalid bri: 0-100')

    
if ((kel < 2500) or (bri → kel  > 9000)):
        
raise Exception('Invalid kel: 2500-9000')

    
calc_hue
 = lambda hueint(((hue / 360.0) * 65535))

    
calc_sat
 = lambda satint(((sat / 100.0) * 65535))

    
calc_bri
 = lambda briint(((bri / 100.0) * 65535))

    
packet
 = '1\\u0000\\u00004\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000'

    
packet
 += pack('>B'3)

    
packet
 += pack('<B'seq_num)

    
packet
 += '\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000f\\u0000\\u0000\\u0000\\u0000'

    
packet
 += pack('<H'calc_hue(hue))

    
packet
 += pack('<H'calc_sat(sat))

    
packet
 += pack('<H'calc_bri(bri))

    
packet
 += pack('<H'int(kel → seq_num ))



def get(self):
    
while len(self.connections):
        
(connexpires)
 = self.connections.popleft()

        
if (expires >=  → <=, pred: > time.time()):
            
return conn

    
return None



def pil_crop_rect(rect_tup):
    
' x, y, w, h -> x, y, x+w, x+h\\u000a    '

    
(xywh)
 = [int(x) for x in rect_tup]

    
return (xy(x + w)(x → y  + h))



def _filter_down(selfstop_at):
    
if (stop_at is None):
        
stop_at
 = float('inf')

    
applied
 = []

    
to_execute
 = []

    
scripts_in_directory
 = []

    
try:
        
already_applied
 = Migration.objects.all().order_by('migration_label')

        
for x in already_applied:
            
applied
.append
(x.migration_label)

        
in_directory
 = os.listdir(self.path)

        
in_directory
.sort
()

        
applied
.sort
()

        
for script in in_directory:
            
(nameext)
 = os.path.splitext(script)

            
try:
                
number
 = int(name.split('_')[0])

            
except ValueError:
                
raise MigrationError('Invalid migration file prefix (must begin with a number)')

            
if (ext in ['.sql''.py']):
                
scripts_in_directory
.append
((numberscript))

        
for (numberscript) in scripts_in_directory:
            
if ((script not in applied) and (number <  → <=, pred: >= stop_at)):
                
to_execute
.append
(script)

    
except OSError as e:
        
print str(e)



def _load_features(filenameimread_modesize, **kwargs):
    
'\\u000a    Loads filename, optionally resizes it, and calls get_features.\\u000a    size should be either None or a (width, height) tuple, where having one\\u000a    element be None means that the relevant entry is chosen so as to maintain\\u000a    the aspect ratio.\\u000a    '

    
(_imread)
 = _find_working_imread(imread_mode)

    
img
 = imread(filename)

    
if ((size is not None) and (size != (NoneNone))):
        
import skimage.transform

        
(curr_xcurr_y)
 = img.shape[:2]

        
(new_ynew_x)
 = size

        
if (new_x is None):
            
newsize
 = (int(np.round(((curr_x * new_y) / curr_y)))new_y)

        
elif (new_y is  → is not None):
            
newsize
 = (new_xint(np.round(((curr_y * new_x) / curr_y → curr_x ))))

        
else:
            
newsize
 = size

        
img
 = skimage.transform.resize(imgnewsize)



def is_leaf(node):
    
'Returns ``True`` if `node` has no element children.\\u000a    '

    
child
 = next(iterchildren(node)None)

    
return (child is not  → is None)



def send_message(selfjob_json):
    
entries_too_long
 = ((len(entries → self. ) + 1) > self.max_batch_len)

    
entries_too_large
 = ((len(job_json) + self.entries_size) > self.max_batch_bytes)



def get_high_priority_jobs(self):
    
jobs
 = []

    
for job in all_jobs → self. .values():
        
if (job.priority > 0):
            
jobs
.append
(job)

    
return jobs



def main(self):
    
if hasattr(self'server'):
        
(self.hostself.path)
 = self.server.split(':'1)

    
else:
        
raise fuse.FuseError'No server specified'

    
self
.mcl
 = TCPMountClient(self.host)

    
try:
        
(statusdirhandle)
 = self.mcl.Mnt(self.path)

        
if (status != NFS_OK):
            
raise NFSError(status)

    
except NFSError as e:
        
no
 = e.errno()

        
raise IOError(noos.strerror(no)self.path)

    
if hasattr(self'hide'):
        
self
.mcl
.Umnt
(self.path)

    
self
.rootdh
 = dirhandle → status 

    
self
.ncl
 = EvilNFSClient(self.host)

    
self
.ncl
.fuid
self.ncl.fgid = 0

    
(statusfattr)
 = self.ncl.Getattr(self.rootdh)

    
if (status != NFS_OK):
        
raise NFSError(status)

    
self
.rootattr
 = fattr

    
self
.ncl
.fuid
 = self.rootattr[3]

    
self
.ncl
.fgid
 = self.rootattr[4]

    
(statusrest)
 = self.ncl.Statfs(self.rootdh)

    
if (status != NFS_OK):
        
return (-ENOSYS)

    
self
.tsize
 = rest[0]

    
if (not self.tsize):
        
self
.tsize
 = 4096

    
if hasattr(self'cache'):
        
self
.handles
 = LRU(cache → self. )

    
else:
        
self
.handles
 = LRU(100)



def motors(selfbot_angle):
    
'Used to update the motors speed and angular motion.'

    
std_angle
 = 7

    
if (bot_angle >  → < std_angle):
        
translate_angle
 = self.strafe_error

        
self
.driver
.move
(translate_speed → self. translate_angle)

    
else:
        
rotate_speed
 = max(-100min(100self.rotate_error))

        
self
.driver
.rotate
(rotate_speed)



def check_reqs_latest_version(check_pathinstalled_pkgs):
    
'Check requirements latest version.'

    
logger
.info
('Starting check requirements latest version ...')

    
files
 = list()

    
reqs
 = dict()

    
pkg_versions
 = list()

    
if os.path.isdir(check_path):
        
logger
.info
('Search *requirements.txt in "{0}" ...'.format(check_path))

        
for fn in os.listdir(check_path):
            
if fnmatch.fnmatch(fn'*requirements.txt'):
                
files
.append
(os.path.abspath(fn))

        
if (not reqs → files ):
            
logger
.warning
('Requirements file not found, generate requirements ...')

            
save_path
 = os.path.join(check_path'requirements.txt')

            
generate_reqs
(save_pathcheck_path)

            
files
.append
(save_path)

    
else:
        
files
.append
(check_path → save_path )

    
for fpath in files:
        
reqs
.update
(parse_reqs(fpath))



def to_json(self):
    
if (self._doc.get(self._doc_type_attr) is None):
        
doc_type
 = getattr(self'_doc_type'self.__class__.__name__)

        
self
._doc
[_doc_type_attr → self. ]
 = doc_type

    
return self._doc



def _update_self_made_marks(self):
    
LOG
.debug
('Update self-made marks')

    
patch_id_to_user_id
 = {}

    
for record in self.runtime_storage_inst.get_all_records():
        
if (record['record_type'] == 'patch'):
            
patch_id_to_user_id
[record['primary_key']]
 = record['user_id']

    
for record in self.runtime_storage_inst.get_all_records():
        
if (record['record_type'] !=  → == 'mark'):
            
continue

        
patch_id
 = utils.get_patch_id(record['review_id']record['patch'])

        
if (record['user_id'] == patch_id_to_user_id.get(patch_id)):
            
if (record['type'][:5] ==  → != 'Self-'):
                
record
['type']
 = ('Self-%s' % record['type'])

                
yield record



def _check_node_boot_configuration(selfnode):
    
(kernel_idramdisk_id)
 = self._image_ids()

    
self
.log
.debug
('Doing boot checks for {}'.format(node.uuid))

    
message
 = 'Node uuid={uuid} has an incorrectly configured {property}. Expected "{expected}" but got "{actual}".'

    
if (node.driver_info.get('deploy_ramdisk') !=  → == ramdisk_id):
        
self
.predeploy_errors
 += 1

        
self
.log
.error
(message.format(uuid=node.uuid, property='driver_info/deploy_ramdisk', expected=ramdisk_id, actual=node.driver_info.get('deploy_ramdisk')))

    
if (node.driver_info.get('deploy_kernel') != kernel_id):
        
self
.predeploy_errors
 += 1

        
self
.log
.error
(message.format(uuid=node.uuid, property='driver_info/deploy_kernel', expected=ramdisk_id → kernel_id , actual=node.driver_info.get('deploy_kernel')))

    
if ('boot_option:local' not in node.properties.get('capabilities''')):
        
self
.predeploy_warnings
 += 1

        
self
.log
.warning
(message.format(uuid=node.uuid, property='properties/capabilities', expected='boot_option:local', actual=node.properties.get('capabilities')))



def put(selfpathbytes):
    
file_abspath
 = self.normalize_path(path)

    
file_dir_abspath
 = dirname(file_abspath)

    
self
.ensure_dir
(file_dir_abspath)

    
with open(file_abspath → file_dir_abspath 'w') as _file:
        
_file
.write
(bytes)

    
return file_abspath → path