Make sure our protos have been compiled to python libraries.
166241
def MakeProto():
  """"""
  # Start running from one directory above the grr directory which is found by
  # this scripts's location as __file__.
  cwd = os.path.dirname(os.path.abspath(__file__))

  # Find all the .proto files.
  protos_to_compile = []
  for (root, _, files) in os.walk(cwd):
    for filename in files:
      full_filename = os.path.join(root, filename)
      if full_filename.endswith(".proto"):
        proto_stat = os.stat(full_filename)

        pb2_path = full_filename.rsplit(".", 1)[0] + "_pb2.py"
        try:
          pb2_stat = os.stat(pb2_path)
          if pb2_stat.st_mtime >= proto_stat.st_mtime:
            continue

        except (OSError, IOError):
          pass

        protos_to_compile.append(full_filename)

  if protos_to_compile:
    # Find the protoc compiler.
    protoc = os.environ.get("PROTOC", "protoc")
    try:
      output = subprocess.check_output([protoc, "--version"])
    except (IOError, OSError):
      raise RuntimeError("Unable to launch %s protoc compiler. Please "
                         "set the PROTOC environment variable.", protoc)

    if b"3.6.1" not in output:
      raise RuntimeError("Incompatible protoc compiler detected. "
                         "We need 3.6.1 not %s" % output)

    for proto in protos_to_compile:
      command = [
          protoc,
          # Write the python files next to the .proto files.
          "--python_out",
          ROOT,
          "--proto_path=%s" % ROOT,
          proto
      ]
      print(
          "Compiling %s with (cwd: %s): %s" % (proto, ROOT, " ".join(command)))
      # The protoc compiler is too dumb to deal with full paths - it expects a
      # relative path from the current working directory.
      subprocess.check_call(command, cwd=ROOT)
474364
function(protoApp, results, callback) {

    // Create some globally vars for use in and-thens
    var dir = (results.dir) ? results.dir : process.cwd();
    var dest = path.join(dir, results.name);

    /*
     * Utility function to double check just in case
     * we are in an app but it has not been registered
     */
    var isAppByFiles = function() {
      var kalaboxYaml = path.join(dest, 'kalabox.yml');
      var pkgJson = path.join(dest, 'package.json');
      return fs.existsSync(kalaboxYaml) && fs.existsSync(pkgJson);
    };

    // Check to make sure we aren't already inside another app
    // since chaos can ensue this way
    if (kbox.core.deps.contains('app') || isAppByFiles()) {
      throw new Error('Looks like an app already exists at ' + dest);
    }

    // Emit pre create event.
    kbox.core.log.status('Creating.');
    return kbox.core.events.emit('pre-create', results)

    // Make sure we are in a clean place before we get dirty
    .then(function() {
      kbox.core.log.status('Cleaning up.');
      return kbox.app.cleanup();
    })

    // Download the app skeleton and extract it to our destination
    .then(function() {
      kbox.core.log.status('Creating app structure.');
      return createAppSkeleton(protoApp, dest, results.from);
    })

    // Merge in our settings to the new app
    .then(function() {
      kbox.core.log.status('Configuring app.');
      return configureApp(protoApp, results);
    })

    // Install the new app
    .then(function() {

      // Get app config from new app
      var config = kbox.core.config.getAppConfig(dest);

      // Emit pre create event.
      kbox.core.log.status('Running pre create tasks.');
      return kbox.core.events.emit('pre-create-app', config)

      // Create a new app object
      .then(function() {
        return kbox.app.create(results.name, config, results);
      })

      // Emit post create event.
      .tap(function(app) {
        return kbox.core.events.emit('post-create-app', app);
      })

      // Report to metrics.
      .tap(function(app) {
        return kbox.metrics.reportAction(
          ['create', protoApp.name].join(':'),
          {app: app}
        );
      })

      // Install and start the SOB
      .tap(function(app) {
        app.status('Starting app.');
        // Set a flag so app.start events know if we are creating or not
        app.creating = true;
        return kbox.app.start(app);
      });

    })

    // Emit post create event.
    .tap(function(app) {
      app.status('Running post create tasks.');
      return app.events.emit('post-create');
    })

    // Print message
    .then(function(app) {
      console.log(kbox.art.appStart(app));
    })

    // Return.
    .nodeify(callback);

  }
1024533
def Main():
  """"""
  multiprocessing.freeze_support()

  input_reader = cli_tools.StdinInputReader()
  tool = psort_tool.PsortTool(input_reader=input_reader)

  if not tool.ParseArguments():
    return False

  have_list_option = False
  if tool.list_analysis_plugins:
    tool.ListAnalysisPlugins()
    have_list_option = True

  if tool.list_output_modules:
    tool.ListOutputModules()
    have_list_option = True

  if tool.list_language_identifiers:
    tool.ListLanguageIdentifiers()
    have_list_option = True

  if tool.list_timezones:
    tool.ListTimeZones()
    have_list_option = True

  if have_list_option:
    return True

  try:
    tool.ProcessStorage()

  except (KeyboardInterrupt, errors.UserAbort):
    logging.warning('Aborted by user.')
    return False

  except errors.BadConfigOption as exception:
    logging.warning(exception)
    return False

  return True
511648
function transpileJavaScriptToPythonAndPHP (args) {

    //-------------------------------------------------------------------------

    // transpile JS → Python 3
    let python3Body = transpileJavaScriptToPython3 (args)

    //-------------------------------------------------------------------------

    // remove await from Python 2 body (transpile Python 3 → Python 2)
    let python2Body = transpilePython3ToPython2 (python3Body)

    //-------------------------------------------------------------------------

    // transpile JS → PHP
    let phpBody = transpileJavaScriptToPHP (args)

    return { python3Body, python2Body, phpBody }
}
203152
def _read_protos(self, size):
        
        _byte = self._read_unpack(size)
        _prot = ETHERTYPE.get(_byte)
        return _prot
182943
def attach_protocol(self, proto):
        
        if self._protocol is not None:
            raise RuntimeError("Already have a protocol.")
        # make sure we have nothing in self.unsaved
        self.save()
        self.__dict__['_protocol'] = proto

        # FIXME some of this is duplicated from ctor
        del self.__dict__['_accept_all_']
        self.__dict__['post_bootstrap'] = defer.Deferred()
        if proto.post_bootstrap:
            proto.post_bootstrap.addCallback(self.bootstrap)
        return self.__dict__['post_bootstrap']
393469
def israw(self, **kwargs):
        

        if self.raw is None:
            self.raw = self.stdout.isatty() and self.is_process_tty()

        return self.raw
1244018
def _compiled(self):
        """"""
        # Dev Notes:
        # Because of fast locals in functions in both CPython and PyPy, getting a
        # function to execute makes the code a few times faster than
        # just executing it in the global exec scope.
        prog = [self._prog_start]

        simple_func = {  # OPS
            'w': lambda x: x,
            'r': lambda x: x,
            '~': lambda x: '(~' + x + ')',
            '&': lambda l, r: '(' + l + '&' + r + ')',
            '|': lambda l, r: '(' + l + '|' + r + ')',
            '^': lambda l, r: '(' + l + '^' + r + ')',
            'n': lambda l, r: '(~(' + l + '&' + r + '))',
            '+': lambda l, r: '(' + l + '+' + r + ')',
            '-': lambda l, r: '(' + l + '-' + r + ')',
            '*': lambda l, r: '(' + l + '*' + r + ')',
            '<': lambda l, r: 'int(' + l + '<' + r + ')',
            '>': lambda l, r: 'int(' + l + '>' + r + ')',
            '=': lambda l, r: 'int(' + l + '==' + r + ')',
            'x': lambda sel, f, t: '({}) if ({}==0) else ({})'.format(f, sel, t),
        }

        def shift(value, direction, shift_amt):
            if shift_amt == 0:
                return value
            else:
                return '(%s %s %d)' % (value, direction, shift_amt)

        def make_split():
            if split_start_bit == 0:
                bit = '(%d & %s)' % ((1 << split_length) - 1, source)
            elif len(net.args[0]) - split_start_bit == split_length:
                bit = '(%s >> %d)' % (source, split_start_bit)
            else:
                bit = '(%d & (%s >> %d))' % ((1 << split_length) - 1, source, split_start_bit)
            return shift(bit, '<<', split_res_start_bit)

        for net in self.block:
            if net.op in simple_func:
                argvals = (self._arg_varname(arg) for arg in net.args)
                expr = simple_func[net.op](*argvals)
            elif net.op == 'c':
                expr = ''
                for i in range(len(net.args)):
                    if expr is not '':
                        expr += ' | '
                    shiftby = sum(len(j) for j in net.args[i+1:])
                    expr += shift(self._arg_varname(net.args[i]), '<<', shiftby)
            elif net.op == 's':
                source = self._arg_varname(net.args[0])
                expr = ''
                split_length = 0
                split_start_bit = -2
                split_res_start_bit = -1

                for i, b in enumerate(net.op_param):
                    if b != split_start_bit + split_length:
                        if split_start_bit >= 0:
                            # create a wire
                            expr += make_split() + '|'
                        split_length = 1
                        split_start_bit = b
                        split_res_start_bit = i
                    else:
                        split_length += 1
                expr += make_split()
            elif net.op == 'm':
                read_addr = self._arg_varname(net.args[0])
                mem = net.op_param[1]
                if isinstance(net.op_param[1], RomBlock):
                    expr = 'd["%s"]._get_read_data(%s)' % (self._mem_varname(mem), read_addr)
                else:  # memories act async for reads
                    expr = 'd["%s"].get(%s, %s)' % (self._mem_varname(mem),
                                                    read_addr, self.default_value)
            elif net.op == '@':
                mem = self._mem_varname(net.op_param[1])
                write_addr, write_val, write_enable = (self._arg_varname(a) for a in net.args)
                prog.append('    if {}:'.format(write_enable))
                prog.append('        mem_ws.append(("{}", {}, {}))'
                            .format(mem, write_addr, write_val))
                continue  # memwrites are special
            else:
                raise PyrtlError('FastSimulation cannot handle primitive "%s"' % net.op)

            # prog.append('    #  ' + str(net))
            result = self._dest_varname(net.dests[0])
            if len(net.dests[0]) == self._no_mask_bitwidth[net.op](net):
                prog.append("    %s = %s" % (result, expr))
            else:
                mask = str(net.dests[0].bitmask)
                prog.append('    %s = %s & %s' % (result, mask, expr))

        # add traced wires to dict
        if self.tracer is not None:
            for wire_name in self.tracer.trace:
                wire = self.block.wirevector_by_name[wire_name]
                if not isinstance(wire, (Input, Const, Register, Output)):
                    v_wire_name = self._varname(wire)
                    prog.append('    outs["%s"] = %s' % (wire_name, v_wire_name))

        prog.append("    return regs, outs, mem_ws")
        return '\n'.join(prog)
694754
def check_dependencies(self):
        ""
        if self.test_program == 'nose':
            try:
                import nose
            except ImportError:
                sys.exit('Nosetests is not available on your system. Please install it and try to run it again')
        if self.test_program == 'py':
            try:
                import py
            except:
                sys.exit('py.test is not available on your system. Please install it and try to run it again')
        if self.test_program == 'django':
            try:
                import django
            except:
                sys.exit('django is not available on your system. Please install it and try to run it again')
        if self.test_program == 'phpunit':
            try:
                process = subprocess.check_call(['phpunit','--version']) 
            except:
                sys.exit('phpunit is not available on your system. Please install it and try to run it again')
        if self.test_program == 'tox':
            try:
                import tox
            except ImportError:
                sys.exit('tox is not available on your system. Please install it and try to run it again')
1297409
def run(files, temp_folder):
    ""
    errors = []
    for py_file in filter_python_files(files):
        # We only want to show errors if we CAN'T compile to py3.
        # but we want to show all the errors at once.
        b = bash('python3 -m py_compile {0}'.format(py_file))
        if b.stderr:
            b = bash('2to3-2.7 {file}'.format(file=py_file))
            errors.append(b.value())
    return "\n".join(errors)
253317
def check_input_files(headerDir, sourceDir, containers=['vector', 'list', 'set', 'map'],
                      seqType='both', verbose=False):
    """"""
    # Check the input files for containers in their variadic form.
    result1 = False
    if seqType == "both" or seqType == "variadic":
        if verbose:
            print "Check if input files for pre-processing Boost.MPL variadic containers need fixing."
        result1 = check_input_files_for_variadic_seq(headerDir, sourceDir)
        if verbose:
            if result1:
                print "  At least one input file needs fixing!"
            else:
                print "  No input file needs fixing!"
    # Check the input files for containers in their numbered form.
    result2 = False
    result3 = False
    if seqType == "both" or seqType == "numbered":
        if verbose:
            print "Check input files for pre-processing Boost.MPL numbered containers."
        result2 = check_input_files_for_numbered_seq(headerDir, ".hpp", containers)
        result3 = check_input_files_for_numbered_seq(sourceDir, ".cpp", containers)
        if verbose:
            if result2 or result3:
                print "  At least one input file needs fixing!"
            else:
                print "  No input file needs fixing!"
    # Return result.
    return result1 or result2 or result3
907405
def Main():
  """"""
  multiprocessing.freeze_support()

  tool = psteal_tool.PstealTool()
  if not tool.ParseArguments():
    return False

  have_list_option = False

  if tool.list_timezones:
    tool.ListTimeZones()
    have_list_option = True

  if tool.list_output_modules:
    tool.ListOutputModules()
    have_list_option = True

  if tool.list_timezones:
    tool.ListTimeZones()
    have_list_option = True

  if tool.list_parsers_and_plugins:
    tool.ListParsersAndPlugins()
    have_list_option = True

  if tool.list_hashers:
    tool.ListHashers()
    have_list_option = True

  if tool.list_language_identifiers:
    tool.ListLanguageIdentifiers()
    have_list_option = True

  if have_list_option:
    return True

  try:
    tool.ExtractEventsFromSources()
    tool.AnalyzeEvents()

  except (KeyboardInterrupt, errors.UserAbort):
    logging.warning('Aborted by user.')
    return False

  except errors.SourceScannerError as exception:
    logging.warning(exception)
    return False

  return True
593268
def validate_protoquil(program: Program) -> None:
    
    valid_instruction_types = tuple([Pragma, Declare, Halt, Gate, Reset, ResetQubit, Measurement])
    for instr in program.instructions:
        if not isinstance(instr, valid_instruction_types):
            # Instructions like MOVE, NOT, JUMP, JUMP-UNLESS will fail here
            raise ValueError(f"ProtoQuil validation failed: {instr} is not allowed.")
571529
function(protoIRs) {
      var newPIRs = [];
      while (protoIRs.length) {
        var pir = protoIRs.shift();
        newPIRs.push(pir);

        // Only consider Animations for now.
        if (pir.irType !== ProtoIR.ANIMATION_TYPE)
          continue;

        var isCSS = pir.containsSliceTitle(CSS_ANIMATION_TITLE);
        var isFling = pir.containsTypeNames([INPUT_TYPE.FLING_START]);

        for (var i = 0; i < protoIRs.length; ++i) {
          var otherPIR = protoIRs[i];

          if (otherPIR.irType !== pir.irType)
            continue;

          // Don't merge CSS Animations with any other types.
          if (isCSS != otherPIR.containsSliceTitle(CSS_ANIMATION_TITLE))
            continue;

          if (!otherPIR.intersects(pir))
            continue;

          // Don't merge Fling Animations with any other types.
          if (isFling != otherPIR.containsTypeNames([INPUT_TYPE.FLING_START]))
            continue;

          pir.merge(otherPIR);
          protoIRs.splice(i, 1);
          // Don't skip the next otherPIR!
          --i;
        }
      }
      return newPIRs;
    }
865066
def from_protobuf(cls, msg):
        """"""
        if not isinstance(msg, cls._protobuf_cls):
            raise TypeError("Expected message of type "
                            "%r" % cls._protobuf_cls.__name__)
        kwargs = {k: getattr(msg, k) for k in cls._get_params()}
        return cls(**kwargs)
1125624
function ensurePrototypeTraversal(prototype) {
    if (!Object.__proto__) {
      var ancestor = Object.getPrototypeOf(prototype);
      prototype.__proto__ = ancestor;
      if (isBase(ancestor)) {
        ancestor.__proto__ = Object.getPrototypeOf(ancestor);
      }
    }
  }
780434
def _validate_importers(importers):
    
    # They could have no importers, that's chill
    if importers is None:
        return None

    def _to_importer(priority, func):
        assert isinstance(priority, int), priority
        assert callable(func), func
        return (priority, _importer_callback_wrapper(func))

    # Our code assumes tuple of tuples
    return tuple(_to_importer(priority, func) for priority, func in importers)