Predeclares all memory required and sets data structures to their initial values
506760
protected void initialize(T input , GrayS32 output ) {
		this.graph = output;
		final int N = input.width*input.height;

		regionSize.resize(N);
		threshold.resize(N);
		for( int i = 0; i < N; i++ ) {
			regionSize.data[i] = 1;
			threshold.data[i] = K;
			graph.data[i] = i; // assign a unique label to each pixel since they are all their own region initially
		}

		edges.reset();
		edgesNotMatched.reset();
	}
172468
private void preallocate() throws IOException {
    long position = fc.position();
    long triggerSize = Math.max(FSEditLog.preallocateSize / 100, 4096);
    if (position + triggerSize >= fc.size()) {
      if(FSNamesystem.LOG.isDebugEnabled()) {
        FSNamesystem.LOG.debug("Preallocating Edit log, current size "
            + fc.size());
      }
      fill.position(0);
      int written = fc.write(fill, position);
      if(FSNamesystem.LOG.isDebugEnabled()) {
        FSNamesystem.LOG.debug("Edit log size is now " + fc.size() +
            " written " + written + " bytes " + " at offset " + position);
      }
    }
  }
929509
def _lazy_turbo_mapping(initial, pre_size):
    '''
    
    '''
    size = pre_size or (2 * len(initial)) or 8
    buckets = size * [None]
    if not isinstance(initial, colls.Mapping): initial = dict(initial)
    for k, v in six.iteritems(initial):
        h = hash(k)
        index = h % size
        bucket = buckets[index]
        if bucket: bucket.append((k, v))
        else:      buckets[index] = [(k, v)]
    return LazyPMap(len(initial), ps.pvector().extend(buckets))
838444
def init():
    
    global OUTPUT
    global INCLUDED
    global CURRENT_DIR
    global ENABLED
    global INCLUDEPATH
    global IFDEFS
    global ID_TABLE
    global CURRENT_FILE

    global_.FILENAME = '(stdin)'
    OUTPUT = ''
    INCLUDED = {}
    CURRENT_DIR = ''
    pwd = get_include_path()
    INCLUDEPATH = [os.path.join(pwd, 'library'), os.path.join(pwd, 'library-asm')]
    ENABLED = True
    IFDEFS = []
    global_.has_errors = 0
    global_.error_msg_cache.clear()
    parser.defaulted_states = {}
    ID_TABLE = DefinesTable()
    del CURRENT_FILE[:]
1050000
def _initialize_processes(self, target, num_workers, description):
        # type: (_MultiprocessOffload, function, int, str) -> None
        
        if num_workers is None or num_workers < 1:
            raise ValueError('invalid num_workers: {}'.format(num_workers))
        logger.debug('initializing {}{} processes'.format(
            num_workers, ' ' + description if not None else ''))
        for _ in range(num_workers):
            proc = multiprocessing.Process(target=target)
            proc.start()
            self._procs.append(proc)
1145265
def _initialize_with_array(self, data, rowBased=True):
        """"""
        if rowBased:
            self.matrix = []
            if len(data) != self._rows:
                raise ValueError("Size of Matrix does not match")
            for col in xrange(self._columns):
                self.matrix.append([])
                for row in xrange(self._rows):
                    if len(data[row]) != self._columns:
                        raise ValueError("Size of Matrix does not match")
                    self.matrix[col].append(data[row][col])
        else:
            if len(data) != self._columns:
                raise ValueError("Size of Matrix does not match")
            for col in data:
                if len(col) != self._rows:
                    raise ValueError("Size of Matrix does not match")
            self.matrix = copy.deepcopy(data)
593069
function main() {
	var len;
	var min;
	var max;
	var f;
	var i;

	min = 1; // 10^min
	max = 6; // 10^max

	for ( i = min; i <= max; i++ ) {
		len = pow( 10, i );
		f = createBenchmark( len );
		bench( pkg+':len='+len, f );
	}
}
1081018
public void prepareForEnumeration() {
        if (isPreparer()) {
            for (NodeT node : nodeTable.values()) {
                // Prepare each node for traversal
                node.initialize();
                if (!this.isRootNode(node)) {
                    // Mark other sub-DAGs as non-preparer
                    node.setPreparer(false);
                }
            }
            initializeDependentKeys();
            initializeQueue();
        }
    }
1275417
def _prepare_initial_state(self, function_start, state):
        

        if state is None:
            state = self.project.factory.blank_state(mode="static",
                                                     remove_options=self._state_options_to_remove
                                                     )

        # make room for arguments passed to the function
        sp = state.regs.sp
        sp_val = state.solver.eval_one(sp)
        state.memory.set_stack_address_mapping(sp_val,
                                               state.memory.stack_id(function_start) + '_pre',
                                               0
                                               )
        state.registers.store('sp', sp - 0x100)

        # Set the stack address mapping for the initial stack
        state.memory.set_stack_size(state.arch.stack_size)
        initial_sp = state.solver.eval(state.regs.sp) # FIXME: This is bad, as it may lose tracking of multiple sp values
        initial_sp -= state.arch.bytes
        state.memory.set_stack_address_mapping(initial_sp,
                                               state.memory.stack_id(function_start),
                                               function_start
                                               )

        return state
1071696
def initialize():
    
    try:
        import multiprocessing
        ncpus = '{0}'.format(multiprocessing.cpu_count())
    except (ImportError, NotImplementedError):
        ncpus = '0'

    # Setup the command-line options and parse them.
    parser = argparse.ArgumentParser(description="Document a program or library written in modern Fortran. Any command-line options over-ride those specified in the project file.")
    parser.add_argument("project_file",help="file containing the description and settings for the project",
                        type=argparse.FileType('r'))
    parser.add_argument("-d","--src_dir",action="append",help='directories containing all source files for the project')
    parser.add_argument("-p","--page_dir",help="directory containing the optional page tree describing the project")
    parser.add_argument("-o","--output_dir",help="directory in which to place output files")
    parser.add_argument("-s","--css",help="custom style-sheet for the output")
    parser.add_argument("-r","--revision",dest="revision",help="Source code revision the project to document")
    parser.add_argument("--exclude",action="append",help="any files which should not be included in the documentation")
    parser.add_argument("--exclude_dir",action="append",help="any directories whose contents should not be included in the documentation")
    parser.add_argument("-e","--extensions",action="append",help="extensions which should be scanned for documentation (default: f90, f95, f03, f08)")
    parser.add_argument("-m","--macro",action="append",help="preprocessor macro (and, optionally, its value) to be applied to files in need of preprocessing.")
    parser.add_argument("-w","--warn",dest='warn',action='store_true',
                        help="display warnings for undocumented items")
    parser.add_argument("--no-search",dest='search',action='store_false',
                        help="don't process documentation to produce a search feature")
    parser.add_argument("-q","--quiet",dest='quiet',action='store_true',
                        help="do not print any description of progress")
    parser.add_argument("-V", "--version", action="version",
                        version="{}, version {}".format(__appname__,__version__))
    parser.add_argument("--debug",dest="dbg",action="store_true",
                        help="display traceback if fatal exception occurs")
    parser.add_argument("-I","--include",action="append",
                        help="any directories which should be searched for include files")
    # Get options from command-line
    args = parser.parse_args()
    # Set up Markdown reader
    md_ext = ['markdown.extensions.meta','markdown.extensions.codehilite',
              'markdown.extensions.extra',MathExtension(),'md_environ.environ']
    md = markdown.Markdown(extensions=md_ext, output_format="html5",
    extension_configs={})
    # Read in the project-file. This will contain global documentation (which
    # will appear on the homepage) as well as any information about the project
    # and settings for generating the documentation.
    proj_docs = args.project_file.read()
    md.convert(proj_docs)
    # Remake the Markdown object with settings parsed from the project_file
    if 'md_base_dir' in md.Meta: md_base = md.Meta['md_base_dir'][0] 
    else: md_base = os.path.dirname(args.project_file.name)
    md_ext.append('markdown_include.include')
    if 'md_extensions' in md.Meta: md_ext.extend(md.Meta['md_extensions'])
    md = markdown.Markdown(extensions=md_ext, output_format="html5",
            extension_configs={'markdown_include.include': {'base_path': md_base}})
    md.reset()
    # Re-read the project file
    proj_docs = md.convert(proj_docs)
    proj_data = md.Meta
    md.reset()
    # Get the default options, and any over-rides, straightened out
    options = ['src_dir','extensions','fpp_extensions','fixed_extensions',
               'output_dir','css','exclude',
               'project','author','author_description','author_pic',
               'summary','github','bitbucket','facebook','twitter',
               'google_plus','linkedin','email','website','project_github',
               'project_bitbucket','project_website','project_download',
               'project_sourceforge','project_url','display','hide_undoc','version',
               'year','docmark','predocmark','docmark_alt','predocmark_alt',
               'media_dir','favicon','warn','extra_vartypes','page_dir',
               'incl_src',
               'source','exclude_dir','macro','include','preprocess','quiet',
               'search','lower','sort','extra_mods','dbg','graph',
               'graph_maxdepth', 'graph_maxnodes',
               'license','extra_filetypes','preprocessor','creation_date',
               'print_creation_date','proc_internals','coloured_edges',
               'graph_dir','gitter_sidecar','mathjax_config','parallel',
               'revision', 'fixed_length_limit']
    defaults = {'src_dir':             ['./src'],
                'extensions':          ['f90','f95','f03','f08','f15'],
                'fpp_extensions':      ['F90','F95','F03','F08','F15','F','FOR'],
                'fixed_extensions':    ['f','for','F','FOR'],
                'output_dir':          './doc',
                'project':             'Fortran Program',
                'project_url':         '',
                'display':             ['public','protected'],
                'hide_undoc':          'false',
                'year':                date.today().year,
                'exclude':             [],
                'exclude_dir':         [],
                'docmark':             '!',
                'docmark_alt':         '*',
                'predocmark':          '>',
                'predocmark_alt':      '|',
                'favicon':             'default-icon',
                'extra_vartypes':      [],
                'incl_src':            'true',
                'source':              'false',
                'macro':               [],
                'include':             [],
                'preprocess':          'true',
                'preprocessor':        '',
                'proc_internals':      'false',
                'warn':                'false',
                'quiet':               'false',
                'search':              'true',
                'lower':               'false',
                'sort':                'src',
                'extra_mods':          [],
                'dbg':                 True,
                'graph':               'false',
                'graph_maxdepth':      '10000',
                'graph_maxnodes':      '1000000000',
                'license':             '',
                'extra_filetypes':     [],
                'creation_date':       '%Y-%m-%dT%H:%M:%S.%f%z',
                'print_creation_date': False,
                'coloured_edges':      'false',
                'parallel':            ncpus,
                'fixed_length_limit':  'true',
               }
    listopts = ['extensions','fpp_extensions','fixed_extensions','display',
                'extra_vartypes','src_dir','exclude','exclude_dir',
                'macro','include','extra_mods','extra_filetypes']
    # Evaluate paths relative to project file location
    if args.warn:
        args.warn = 'true'
    else:
        del args.warn
    if args.quiet:
        args.quiet = 'true'
    else:
        del args.quiet
    if not args.search:
        args.search = 'false'
    else:
        del args.search
    for option in options:
        if hasattr(args,option) and getattr(args,option):
            proj_data[option] = getattr(args,option)
        elif option in proj_data:
            # Think if there is a safe  way to evaluate any expressions found in this list
            #proj_data[option] = proj_data[option]
            if option not in listopts:
                proj_data[option] = '\n'.join(proj_data[option])
        elif option in defaults:
           proj_data[option] = defaults[option]
    base_dir = os.path.abspath(os.path.dirname(args.project_file.name))
    proj_data['base_dir'] = base_dir
    for var in ['src_dir','exclude_dir','include']:
        if var in proj_data:
            proj_data[var] = [os.path.normpath(os.path.join(base_dir,os.path.expanduser(os.path.expandvars(p)))) for p in proj_data[var]]
    for var in ['page_dir','output_dir','graph_dir','media_dir','css','mathjax_config']:
        if var in proj_data:
            proj_data[var] = os.path.normpath(os.path.join(base_dir,os.path.expanduser(os.path.expandvars(proj_data[var]))))
    if proj_data['favicon'].strip() != defaults['favicon']:
        proj_data['favicon'] = os.path.normpath(os.path.join(base_dir,os.path.expanduser(os.path.expandvars(proj_data['favicon']))))
    proj_data['display'] = [ item.lower() for item in proj_data['display'] ]
    proj_data['incl_src'] = proj_data['incl_src'].lower()
    proj_data['creation_date'] = datetime.now().strftime(proj_data['creation_date'])
    relative = (proj_data['project_url'] == '')
    proj_data['relative'] = relative
    proj_data['extensions'] += [ext for ext in proj_data['fpp_extensions'] if ext not in proj_data['extensions']]
    # Parse file extensions and comment characters for extra filetypes
    extdict = {}
    for ext in proj_data['extra_filetypes']:
        sp = ext.split()
        if len(sp) < 2: continue
        if (len(sp)==2):
            extdict[sp[0]] = (sp[1])        # (comment_char) only
        else:
            extdict[sp[0]] = (sp[1],sp[2])  # (comment_char and lexer_str)
    proj_data['extra_filetypes'] = extdict
    # Make sure no src_dir is contained within output_dir
    for projdir in proj_data['src_dir']:
        proj_path = ford.utils.split_path(projdir)
        out_path  = ford.utils.split_path(proj_data['output_dir'])
        for directory in out_path:
            if len(proj_path) == 0:
                break
            if directory == proj_path[0]:
                proj_path.remove(directory)
            else:
                break
        else:
            print('Error: directory containing source-code {} a subdirectory of output directory {}.'.format(proj_data['output_dir'],projdir))
            sys.exit(1)
    # Check that none of the docmarks are the same
    if proj_data['docmark'] == proj_data['predocmark'] != '':
        print('Error: docmark and predocmark are the same.')
        sys.exit(1)
    if proj_data['docmark'] == proj_data['docmark_alt'] != '':
        print('Error: docmark and docmark_alt are the same.')
        sys.exit(1)
    if proj_data['docmark'] == proj_data['predocmark_alt'] != '':
        print('Error: docmark and predocmark_alt are the same.')
        sys.exit(1)
    if proj_data['docmark_alt'] == proj_data['predocmark'] != '':
        print('Error: docmark_alt and predocmark are the same.')
        sys.exit(1)
    if proj_data['docmark_alt'] == proj_data['predocmark_alt'] != '':
        print('Error: docmark_alt and predocmark_alt are the same.')
        sys.exit(1)
    if proj_data['predocmark'] == proj_data['predocmark_alt'] != '':
        print('Error: predocmark and predocmark_alt are the same.')
        sys.exit(1)
    # Add gitter sidecar if specified in metadata
    if 'gitter_sidecar' in proj_data:
        proj_docs += '''
        <script>
            ((window.gitter = {{}}).chat = {{}}).options = {{
            room: '{}'
            }};
        </script>
        <script src="https://sidecar.gitter.im/dist/sidecar.v1.js" async defer></script>
        '''.format(proj_data['gitter_sidecar'].strip())
    # Handle preprocessor:
    if proj_data['preprocess'].lower() == 'true':
        if proj_data['preprocessor']:
            preprocessor = proj_data['preprocessor'].split()
        else:
            preprocessor = ['cpp','-traditional-cpp','-E', '-D__GFORTRAN__']

        # Check whether preprocessor works (reading nothing from stdin)
        try:
            devnull = open(os.devnull)
            subprocess.Popen(preprocessor, stdin=devnull, stdout=devnull,
                             stderr=devnull).communicate()
        except OSError as ex:
            print('Warning: Testing preprocessor failed')
            print('  Preprocessor command: {}'.format(preprocessor))
            print('  Exception: {}'.format(ex))
            print('  -> Preprocessing turned off')
            proj_data['preprocess'] = 'false'
        else:
            proj_data['preprocess'] = 'true'
            proj_data['preprocessor'] = preprocessor
    
    # Get correct license
    try:
        proj_data['license'] = LICENSES[proj_data['license'].lower()]
    except KeyError:
        print('Warning: license "{}" not recognized.'.format(proj_data['license']))
        proj_data['license'] = ''
    # Return project data, docs, and the Markdown reader
    md.reset()
    md.Meta = {}
    return (proj_data, proj_docs, md)
191843
def _setup_resources():
    
    target_procs = 10240
    cur_proc, max_proc = resource.getrlimit(resource.RLIMIT_NPROC)
    target_proc = min(max_proc, target_procs) if max_proc > 0 else target_procs
    resource.setrlimit(resource.RLIMIT_NPROC, (max(cur_proc, target_proc), max_proc))
    cur_hdls, max_hdls = resource.getrlimit(resource.RLIMIT_NOFILE)
    target_hdls = min(max_hdls, target_procs) if max_hdls > 0 else target_procs
    resource.setrlimit(resource.RLIMIT_NOFILE, (max(cur_hdls, target_hdls), max_hdls))
1105531
def allocate_stack(size=DEFAULT_STACK_SIZE):
    
    # Allocate memory with appropriate flags for a stack as in https://blog.fefe.de/?ts=a85c8ba7
    base = libc.mmap(
        None,
        size + GUARD_PAGE_SIZE,
        libc.PROT_READ | libc.PROT_WRITE,
        libc.MAP_PRIVATE | libc.MAP_ANONYMOUS | libc.MAP_GROWSDOWN | libc.MAP_STACK,
        -1, 0)

    try:
        # create a guard page that crashes the application when it is written to (on stack overflow)
        libc.mprotect(base, GUARD_PAGE_SIZE, libc.PROT_NONE)

        yield ctypes.c_void_p(base + size + GUARD_PAGE_SIZE)
    finally:
        libc.munmap(base, size + GUARD_PAGE_SIZE)
673989
def free_memory(self):
        """"""
        self.main.free_memory()
        QTimer.singleShot(self.INITIAL_FREE_MEMORY_TIME_TRIGGER,
                          lambda: self.main.free_memory())
        QTimer.singleShot(self.SECONDARY_FREE_MEMORY_TIME_TRIGGER,
                          lambda: self.main.free_memory())
737520
def initialize(self):
    

    if self._tm is None:
      params = {
        "columnCount": self.columnCount,
        "basalInputSize": self.basalInputWidth,
        "apicalInputSize": self.apicalInputWidth,
        "cellsPerColumn": self.cellsPerColumn,
        "activationThreshold": self.activationThreshold,
        "initialPermanence": self.initialPermanence,
        "connectedPermanence": self.connectedPermanence,
        "minThreshold": self.minThreshold,
        "sampleSize": self.sampleSize,
        "permanenceIncrement": self.permanenceIncrement,
        "permanenceDecrement": self.permanenceDecrement,
        "basalPredictedSegmentDecrement": self.basalPredictedSegmentDecrement,
        "apicalPredictedSegmentDecrement": self.apicalPredictedSegmentDecrement,
        "maxSynapsesPerSegment": self.maxSynapsesPerSegment,
        "seed": self.seed,
      }

      if self.implementation == "ApicalTiebreakCPP":
        params["learnOnOneCell"] = self.learnOnOneCell
        params["maxSegmentsPerCell"] = self.maxSegmentsPerCell

        import htmresearch_core.experimental
        cls = htmresearch_core.experimental.ApicalTiebreakPairMemory

      elif self.implementation == "ApicalTiebreak":
        params["reducedBasalThreshold"] = self.reducedBasalThreshold

        import htmresearch.algorithms.apical_tiebreak_temporal_memory
        cls = htmresearch.algorithms.apical_tiebreak_temporal_memory.ApicalTiebreakPairMemory

      elif self.implementation == "ApicalDependent":
        params["reducedBasalThreshold"] = self.reducedBasalThreshold

        import htmresearch.algorithms.apical_dependent_temporal_memory
        cls = htmresearch.algorithms.apical_dependent_temporal_memory.TripleMemory

      else:
        raise ValueError("Unrecognized implementation %s" % self.implementation)

      self._tm = cls(**params)
1290075
private void allocateElements(int numElements) {
        int initialCapacity = MIN_INITIAL_CAPACITY;
        // Find the best power of two to hold elements.
        // Tests "<=" because arrays aren't kept full.
        if (numElements >= initialCapacity) {
            initialCapacity = numElements;
            initialCapacity |= (initialCapacity >>>  1);
            initialCapacity |= (initialCapacity >>>  2);
            initialCapacity |= (initialCapacity >>>  4);
            initialCapacity |= (initialCapacity >>>  8);
            initialCapacity |= (initialCapacity >>> 16);
            initialCapacity++;

            if (initialCapacity < 0)    // Too many elements, must back off
                initialCapacity >>>= 1; // Good luck allocating 2^30 elements
        }
        elements = new Object[initialCapacity];
    }
1232764
def init():
    
    global ASMS
    global ASMCOUNT
    global AT_END
    global FLAG_end_emitted
    global FLAG_use_function_exit

    __common.init()

    ASMS = {}
    ASMCOUNT = 0
    AT_END = []
    FLAG_use_function_exit = False
    FLAG_end_emitted = False

    # Default code ORG
    OPTIONS.add_option('org', int, 32768)
    # Default HEAP SIZE (Dynamic memory) in bytes
    OPTIONS.add_option('heap_size', int, 4768)  # A bit more than 4K
    # Labels for HEAP START (might not be used if not needed)
    OPTIONS.add_option('heap_start_label', str, 'ZXBASIC_MEM_HEAP')
    # Labels for HEAP SIZE (might not be used if not needed)
    OPTIONS.add_option('heap_size_label', str, 'ZXBASIC_HEAP_SIZE')
    # Flag for headerless mode (No prologue / epilogue)
    OPTIONS.add_option('headerless', bool, False)
1046672
def _setup(self):
        

        cls = self.__class__
        cls._field_map = {}
        cls._field_ids = []
        cls._precomputed_specs = []
        for index, field in enumerate(cls._fields):
            if len(field) < 3:
                field = field + ({},)
                cls._fields[index] = field
            cls._field_map[field[0]] = index
            cls._field_ids.append(_build_id_tuple(field[2], field[1]))

        if cls._oid_pair is not None:
            cls._oid_nums = (cls._field_map[cls._oid_pair[0]], cls._field_map[cls._oid_pair[1]])

        for index, field in enumerate(cls._fields):
            has_callback = cls._spec_callbacks is not None and field[0] in cls._spec_callbacks
            is_mapped_oid = cls._oid_nums is not None and cls._oid_nums[1] == index
            if has_callback or is_mapped_oid:
                cls._precomputed_specs.append(None)
            else:
                cls._precomputed_specs.append((field[0], field[1], field[1], field[2], None))