Position Independent Programming For Humans.
173685
def cli(context, verbose, quiet, database, sense):
    """"""
    logger = logging.getLogger()
    handler = logging.StreamHandler(sys.stderr)
    handler.setFormatter(LevelFormatter())
    logger.addHandler(handler)
    logger.setLevel(logging.WARNING + (quiet-verbose)*10)
    logging.debug(_('Subcommand: %s'), context.invoked_subcommand)
    context.obj['database'] = Database(database)
    try:
        context.obj['sense'] = SenseWithExport(sense).__enter__()
    except Exception:
        pass
383350
private void trainOnOneSample(Instance instance, int partialTreeIter, int i, int dataCount, CompletionService<ArrayList<BeamElement>> pool) throws InterruptedException, ExecutionException
    {
        boolean isPartial = instance.isPartial(options.rootFirst);

        if (partialTreeIter > i && isPartial)
            return;

        Configuration initialConfiguration = new Configuration(instance.getSentence(), options.rootFirst);
        Configuration firstOracle = initialConfiguration.clone();
        ArrayList<Configuration> beam = new ArrayList<Configuration>(options.beamWidth);
        beam.add(initialConfiguration);

        /**
         * The float is the oracle's cost
         * For more information see:
         * Yoav Goldberg and Joakim Nivre. "Training Deterministic Parsers with Non-Deterministic Oracles."
         * TACL 1 (2013): 403-414.
         * for the mean while we just use zero-cost oracles
         */
        Collection<Configuration> oracles = new HashSet<Configuration>();

        oracles.add(firstOracle);

        /**
         * For keeping track of the violations
         * For more information see:
         * Liang Huang, Suphan Fayong and Yang Guo. "Structured perceptron with inexact search."
         * In Proceedings of the 2012 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies,
         * pp. 142-151. Association for Computational Linguistics, 2012.
         */
        float maxViol = Float.NEGATIVE_INFINITY;
        Pair<Configuration, Configuration> maxViolPair = null;

        Configuration bestScoringOracle = null;
        boolean oracleInBeam = false;

        while (!ArcEager.isTerminal(beam) && beam.size() > 0)
        {
            /**
             *  generating new oracles
             *  it keeps the oracles which are in the terminal state
             */
            Collection<Configuration> newOracles = new HashSet<Configuration>();

            if (options.useDynamicOracle || isPartial)
            {
                bestScoringOracle = zeroCostDynamicOracle(instance, oracles, newOracles);
            }
            else
            {
                bestScoringOracle = staticOracle(instance, oracles, newOracles);
            }
            // try explore non-optimal transitions

            if (newOracles.size() == 0)
            {
//                System.err.println("...no oracle(" + dataCount + ")...");
                bestScoringOracle = staticOracle(instance, oracles, newOracles);
            }
            oracles = newOracles;

            TreeSet<BeamElement> beamPreserver = new TreeSet<BeamElement>();

            if (options.numOfThreads == 1 || beam.size() == 1)
            {
                beamSortOneThread(beam, beamPreserver);
            }
            else
            {
                for (int b = 0; b < beam.size(); b++)
                {
                    pool.submit(new BeamScorerThread(false, classifier, beam.get(b),
                                                     dependencyRelations, featureLength, b, options.rootFirst));
                }
                for (int b = 0; b < beam.size(); b++)
                {
                    for (BeamElement element : pool.take().get())
                    {
                        beamPreserver.add(element);
                        if (beamPreserver.size() > options.beamWidth)
                            beamPreserver.pollFirst();
                    }
                }
            }

            if (beamPreserver.size() == 0 || beam.size() == 0)
            {
                break;
            }
            else
            {
                oracleInBeam = false;

                ArrayList<Configuration> repBeam = new ArrayList<Configuration>(options.beamWidth);
                for (BeamElement beamElement : beamPreserver.descendingSet())
                {
//                    if (repBeam.size() >= options.beamWidth) // 只要beamWidth个configuration（这句是多余的）
//                        break;
                    int b = beamElement.index;
                    int action = beamElement.action;
                    int label = beamElement.label;
                    float score = beamElement.score;

                    Configuration newConfig = beam.get(b).clone();

                    ArcEager.commitAction(action, label, score, dependencyRelations, newConfig);
                    repBeam.add(newConfig);

                    if (!oracleInBeam && oracles.contains(newConfig))
                        oracleInBeam = true;
                }
                beam = repBeam;

                if (beam.size() > 0 && oracles.size() > 0)
                {
                    Configuration bestConfig = beam.get(0);
                    if (oracles.contains(bestConfig)) // 模型认为的最大分值configuration是zero cost
                    {
                        oracles = new HashSet<Configuration>();
                        oracles.add(bestConfig);
                    }
                    else // 否则
                    {
                        if (options.useRandomOracleSelection) // 随机选择一个 oracle
                        { // choosing randomly, otherwise using latent structured Perceptron
                            List<Configuration> keys = new ArrayList<Configuration>(oracles);
                            Configuration randomKey = keys.get(randGen.nextInt(keys.size()));
                            oracles = new HashSet<Configuration>();
                            oracles.add(randomKey);
                            bestScoringOracle = randomKey;
                        }
                        else // 选择 oracle中被模型认为分值最大的那个
                        {
                            oracles = new HashSet<Configuration>();
                            oracles.add(bestScoringOracle);
                        }
                    }

                    // do early update
                    if (!oracleInBeam && updateMode.equals("early"))
                        break;

                    // keep violations
                    if (!oracleInBeam && updateMode.equals("max_violation"))
                    {
                        float violation = bestConfig.getScore(true) - bestScoringOracle.getScore(true);//Math.abs(beam.get(0).getScore(true) - bestScoringOracle.getScore(true));
                        if (violation > maxViol)
                        {
                            maxViol = violation;
                            maxViolPair = new Pair<Configuration, Configuration>(bestConfig, bestScoringOracle);
                        }
                    }
                }
                else
                    break;
            }
        }

        // updating weights
        if (!oracleInBeam ||
                !bestScoringOracle.equals(beam.get(0)) // 虽然oracle在beam里面，但在最后时刻，它的得分不是最高
                )
        {
            updateWeights(initialConfiguration, maxViol, isPartial, bestScoringOracle, maxViolPair, beam);
        }
    }
88656
function Spectrum ( entry, snap, direction, singleStep ) {

        this.xPct = [];
        this.xVal = [];
        this.xSteps = [ singleStep || false ];
        this.xNumSteps = [ false ];
        this.xHighestCompleteStep = [];

        this.snap = snap;
        this.direction = direction;

        var index, ordered = [ /* [0, 'min'], [1, '50%'], [2, 'max'] */ ];

        // Map the object keys to an array.
        for ( index in entry ) {
            if ( entry.hasOwnProperty(index) ) {
                ordered.push([entry[index], index]);
            }
        }

        // Sort all entries by value (numeric sort).
        if ( ordered.length && typeof ordered[0][0] === "object" ) {
            ordered.sort(function(a, b) { return a[0][0] - b[0][0]; });
        } else {
            ordered.sort(function(a, b) { return a[0] - b[0]; });
        }


        // Convert all entries to subranges.
        for ( index = 0; index < ordered.length; index++ ) {
            handleEntryPoint(ordered[index][1], ordered[index][0], this);
        }

        // Store the actual step values.
        // xSteps is sorted in the same order as xPct and xVal.
        this.xNumSteps = this.xSteps.slice(0);

        // Convert all numeric steps to the percentage of the subrange they represent.
        for ( index = 0; index < this.xNumSteps.length; index++ ) {
            handleStepPoint(index, this.xNumSteps[index], this);
        }
    }
1310764
void rot(int n, int[] xy, int rx, int ry) {
        if (ry == 0) {
            if (rx == 1) {
                xy[0] = n - 1 - xy[0];
                xy[1] = n - 1 - xy[1];
            }
            int t = xy[0];
            xy[0] = xy[1];
            xy[1] = t;
        }
    }
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 );
	}
}
774253
def main():
    ""

    actions = """
        {LWIN}
        {PAUSE .25}
        r
        {PAUSE .25}
        Notepad.exe{ENTER}
        {PAUSE 1}
        Hello{SPACE}World!
        {PAUSE 1}
        %{F4}
        {PAUSE .25}
        n
        """
    SendKeys(actions, pause = .1)

    keys = parse_keys(actions)
    for k in keys:
        print(k)
        k.Run()
        time.sleep(.1)

    test_strings = [
        "\n"
        "(aa)some text\n",
        "(a)some{ }text\n",
        "(b)some{{}text\n",
        "(c)some{+}text\n",
        "(d)so%me{ab 4}text",
        "(e)so%me{LEFT 4}text",
        "(f)so%me{ENTER 4}text",
        "(g)so%me{^aa 4}text",
        "(h)some +(asdf)text",
        "(i)some %^+(asdf)text",
        "(j)some %^+a text+",
        "(k)some %^+a tex+{&}",
        "(l)some %^+a tex+(dsf)",
        "",
        ]

    for s in test_strings:
        print(repr(s))
        keys = parse_keys(s, with_newlines = True)
        print(keys)

        for k in keys:
            k.Run()
            time.sleep(.1)
        print()
808917
private static Set<Integer> find(final Predicate<Instruction> predicate, final List<Instruction> instructions) {
        final Set<Integer> positions = new HashSet<>();

        for (int i = 0; i < instructions.size(); i++) {
            final Instruction instruction = instructions.get(i);
            if (predicate.test(instruction)) {
                positions.add(i);
            }
        }

        return positions;
    }
166331
private void precompute() {
        sinTheta = Math.sin(theta);
        cosTheta = Math.cos(theta);
        sinPhi = Math.sin(phi);
        cosPhi = Math.cos(phi);
    }
1159087
private static void exch(long[] values, int i, int j) {
        long k = values[i];
        values[i] = values[j];
        values[j] = k;
    }
468172
def _interactive_loop(self, sin: IO[str], sout: IO[str]) -> None:
        """"""
        self._sin = sin
        self._sout = sout
        tasknum = len(all_tasks(loop=self._loop))
        s = '' if tasknum == 1 else 's'
        self._sout.write(self.intro.format(tasknum=tasknum, s=s))
        try:
            while not self._closing.is_set():
                self._sout.write(self.prompt)
                self._sout.flush()
                try:
                    user_input = sin.readline().strip()
                except Exception as e:
                    msg = 'Could not read from user input due to:\n{}\n'
                    log.exception(msg)
                    self._sout.write(msg.format(repr(e)))
                    self._sout.flush()
                else:
                    try:
                        self._command_dispatch(user_input)
                    except Exception as e:
                        msg = 'Unexpected Exception during command execution:\n{}\n'  # noqa
                        log.exception(msg)
                        self._sout.write(msg.format(repr(e)))
                        self._sout.flush()
        finally:
            self._sin = None  # type: ignore
            self._sout = None
1064370
function(input) {
  var code = 'var $_parsers = {\n';
  var parsernames = Object.keys(parsers);
  for (var i = 0; i < parsernames.length; i++) {
    code += '  ' + JSON.stringify(parsernames[i]) + ': ' +
      parsers[parsernames[i]].toString() + ',\n';
  };
  code += '}\n';
  code += compile(input) + '\nif (typeof $_end === "function") {$_end();}';
  var script = new vm.Script(code, {timeout: 4 * 60 * 1000});
  var runner = function(scope) {
    var output = '';
    var pipeOpen = false;
    var ended = false;
    var stream = new Readable({
      encoding: 'utf8',
      read: function() {
        pipeOpen = true;
        if (ended && output === '') {
          pipeOpen = this.push(null);
        } else if (output !== '') {
          pipeOpen = this.push(output);
          output = '';
        }
      },
    });
    scope.$_scope = scope;
    scope.$_write = function(data) {
      output += '' + data;
      if (pipeOpen && output !== '') {
        pipeOpen = stream.push(output);
        output = '';
      }
    };
    scope.$_end = function() {
      ended = true;
      if (pipeOpen) { stream.push(null); }
    };
    script.runInNewContext(scope)
    return stream;
  };
  runner.code = code;
  return runner;
}
166559
def run! program
      reachable = {}
      work_list = []
      program.declarations.each do |decl|
        next unless entrypoint_localization.entrypoints.include?(decl)
        reachable[decl] = Set.new(decl.names)
        work_list << decl
      end

      until work_list.empty?
        decl = work_list.shift
        decl.each do |elem|
          case elem
          when Identifier, CustomType
            d = elem.declaration
            n = elem.name
            unless d.nil? || (reachable[d] && reachable[d].include?(n))
              reachable[d] ||= Set.new
              reachable[d] << n
              work_list |= [d]
            end
          end
        end
        decl.bindings.each do |elem|
          ax = elem.each_ancestor.find{|d| d.is_a?(AxiomDeclaration)}
          unless ax.nil? || reachable[ax]
            reachable[ax] = Set.new
            work_list |= [ax]
          end
        end
      end

      program.declarations.each do |d|
        if reachable.include?(d)
          if d.instance_variable_defined?("@names")
            extras = d.names - reachable[d].to_a
            unless extras.empty?
              info "PRUNING UNUSED NAMES FROM DECLARATION"
              info
              info d.to_s.indent, (extras * ", ").indent
              info
              d.instance_variable_set "@names", reachable[d].sort
            end
          end
        else
          info "PRUNING UNUSED DECLARATION"
          info
          info d.to_s.indent
          info
          d.remove
        end
      end

    end
1121149
def PositionalEncoding(x, params, **unused_kwargs):
  """"""
  if not isinstance(x, (list, tuple)):  # non-chunked inputs
    symbol_size = np.shape(x)[1]
    return x + params[:, :symbol_size, :]
  # Chunked case: apply to all chunks selecting as much as needed.
  offset = 0
  results = []
  for chunk in x:
    symbol_size = np.shape(chunk)[1]
    results.append(chunk + params[:, offset:offset + symbol_size, :])
    offset += symbol_size
  return results
583464
void writeSlot(int position, int w0, int w1, int w2, int w3)
  {
      position *= slotsize;
      int chunkpos = position >> lowbits;
      int slotpos = (position & lowmask);

    // Grow if needed
    if (chunkpos > chunks.size() - 1)
      chunks.addElement(new int[chunkalloc]);
    int[] chunk = chunks.elementAt(chunkpos);
    chunk[slotpos] = w0;
    chunk[slotpos + 1] = w1;
    chunk[slotpos + 2] = w2;
    chunk[slotpos + 3] = w3;
  }
893504
def main():
    """"""
    conf.init(), db.init(conf.DbPath)
    inqueue = LineQueue(sys.stdin).queue
    outqueue = type("", (), {"put": lambda self, x: print("\r%s" % x, end=" ")})()
    if "--quiet" in sys.argv: outqueue = None
    if conf.MouseEnabled:    inqueue.put("mouse_start")
    if conf.KeyboardEnabled: inqueue.put("keyboard_start")
    start(inqueue, outqueue)
312703
static function optimize( $useComments, &$php, $tpl, &$tree, &$resourceData )
    {
        /* If for some reason we don't have elements, simply return */
        if (! is_array( $tree[1] ) )
            return;

        $addNodeInit = false;

        /* Loop through the children of the root */
        foreach ( $tree[1] as $key => $kiddie )
        {
            /* Analyse per node type */
            switch ( $kiddie[0] )
            {
                case eZTemplate::NODE_INTERNAL_OUTPUT_SPACING_INCREASE:
                case eZTemplate::NODE_INTERNAL_SPACING_DECREASE:
                    /* Removing unnecessary whitespace changes */
                    unset( $tree[1][$key] );
                    break;
                case 3: /* Variable */
                    if ( isset( $tree[1][$key + 1] ) and
                         ( $tree[1][$key + 1][0] == eZTemplate::NODE_INTERNAL_RESOURCE_ACQUISITION ) and
                         isset( $resourceData['class-info'] ) )
                    {
                        $ret = eZTemplateOptimizer::optimizeResourceAcquisition(
                            $useComments, $php, $tpl,
                            $tree[1][$key], $tree[1][$key + 1], $resourceData );
                        /* We only unset the tree node when the optimization
                         * function returns false, as that means that the
                         * optimization could not be made. */
                        if ($ret)
                        {
                            unset( $tree[1][$key] );
                        }
                    }
                    else
                    {
                        $ret = eZTemplateOptimizer::optimizeVariable( $useComments, $php, $tpl, $tree[1][$key][2], $resourceData );
                        if ( $ret & 1 )
                            $addNodeInit = true;
                    }
                    break;
            }
        }
        if ( $addNodeInit )
        {
            $initializer = array( eZTemplate::NODE_OPTIMIZED_INIT, null, false );
            array_unshift( $tree[1], $initializer );
        }
    }
773635
def human_play(w, i, grid):
    ""
    plaint = ''
    prompt = whose_move(grid) + " move? [1-9] "
    while True:
        w.render_to_terminal(w.array_from_text(view(grid)
                                               + '\n\n' + plaint + prompt))
        key = c = i.next()
        try:
            move = int(key)
        except ValueError:
            pass
        else:
            if 1 <= move <= 9:
                successor = apply_move(grid, from_human_move(move))
                if successor: return successor
        plaint = ("Hey, that's illegal. Give me one of these digits:\n\n"
                  + (grid_format
                     % tuple(move if apply_move(grid, from_human_move(move)) else '-'
                             for move in range(1, 10))
                     + '\n\n'))