text:
<?php if ($paginator->getNumPages() > 1): ?>

        <?php if ($paginator->getPrevUrl()): ?>

                <a href="<?php echo $paginator->getPrevUrl(); ?>" class="btn btn-default" type="button">« Prev

        <?php endif; ?>

        <select class="form-control paginator-select-page" style="width: auto; cursor: pointer; -webkit-appearance: none; -moz-appearance: none; appearance: none;">
            <?php foreach ($paginator->getPages() as $page): ?>
                <?php if ($page['url']): ?>
                    <option value="<?php echo $page['url']; ?>"<?php if ($page['isCurrent']) echo ' selected'; ?>>
                        Page <?php echo $page['num']; ?>
                    </option>
                <?php else: ?>
                    <option disabled><?php echo $page['num']; ?></option>
                <?php endif; ?>
            <?php endforeach; ?>
        </select>

        <?php if ($paginator->getNextUrl()): ?>

                <a href="<?php echo $paginator->getNextUrl(); ?>" class="btn btn-default" type="button">Next »

        <?php endif; ?>

<?php endif; ?>

<?php /* Depends on a little bit of javascript like this being included somewhere (this example requires jquery):
    $(function() {
        $('.paginator-select-page').on('change', function() {
            document.location = $(this).val();
        });
        // Workaround to prevent iOS from zooming the page when clicking the select list:
        $('.paginator-select-page')
            .on('focus', function() {
                if (/(iPad|iPhone|iPod)/g.test(navigator.userAgent)) {
                    $(this).css('font-size', '16px');
                }
            })
            .on('blur', function() {
                if (/(iPad|iPhone|iPod)/g.test(navigator.userAgent)) {
                    $(this).css('font-size', '');
                }
            })
        ;
    });
*/ ?>

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2019 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS-IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Service for handling microphone data and mp3 audio processing.
 */

angular.module('oppia').factory('VoiceoverRecordingService', [
  '$log', '$q', '$window', function($log, $q, $window) {
    var audioContextAvailable = null,
      defer = null,
      definedAudioContext = null, // Will be defined audio context
      isAvailable = null,
      isRecording = false,
      microphone = null,
      microphoneStream = null,
      mp3Worker = null,
      processor = null;

    var _initWorker = function() {
      if (!$window.Worker) {
        $log.warn('Worker API not supported in this browser.');
        return;
      }
      if (mp3Worker === null) {
        var lameWorkerFileUrl = '/third_party/static/lamejs-1.2.0/' +
          'worker-example/worker-realtime.js';
        // Config the mp3 encoding worker.
        var config = {sampleRate: 44100, bitRate: 128};
        mp3Worker = new Worker(lameWorkerFileUrl);
        mp3Worker.onmessage = function(e) {
          // Async data flow
          defer.resolve(e.data.buf);
        };
        mp3Worker.postMessage({cmd: 'init', config: config});
      }
    };

    var _postMessage = function(buffer) {
      mp3Worker.postMessage({cmd: 'encode', buf: buffer});
    };

    var _stopWorker = function() {
      if (mp3Worker) {
        mp3Worker.terminate();
        $log.log('Ending mp3 worker');
        mp3Worker = null;
      }
    };

    var _initRecorder = function() {
      // Browser agnostic AudioContext API check.
      audioContextAvailable = $window.AudioContext ||
        $window.webkitAudioContext;
      if (audioContextAvailable) {
        // Promise required because angular is async with worker.
        defer = $q.defer();
        isAvailable = true;
        _initWorker();
      } else {
        isAvailable = false;
      }
    };

    // Setup microphone inputs for mp3 audio processing.
    var _processMicAudio = function(stream) {
      definedAudioContext = new audioContextAvailable();
      // Settings a bufferSize of 0 instructs the browser
      // to choose the best bufferSize.
      processor = definedAudioContext.createScriptProcessor(0, 1, 1);
      // Process microphone to mp3 encoding.
      processor.onaudioprocess = _onAudioProcess;

      microphone = definedAudioContext.createMediaStreamSource(stream);
      // Connect custom processor to microphone.
      microphone.connect(processor);
      // Connect to speakers as destination.
      processor.connect(definedAudioContext.destination);
    };

    // Convert directly from mic to mp3.
    var _onAudioProcess = function(event) {
      var array = event.inputBuffer.getChannelData(0);
      _postMessage(array);
    };

    var _startMicrophone = function() {
      return navigator.mediaDevices.getUserMedia({audio: true, video: false});
    };

    var _stopRecord = function() {
      if (microphone && processor) {
        // Disconnect mic and processor and stop processing.
        microphone.disconnect();
        processor.disconnect();
        processor.onaudioprocess = null;
        // Issue command to retrieve converted audio.
        mp3Worker.postMessage({cmd: 'finish'});
        // Stop microphone stream.
        microphoneStream.getTracks().forEach(function(track) {
          track.stop();
        });
        isRecording = false;
      }
    };

    var _closeRecorder = function() {
      _stopWorker();
    };

    return {
      initRecorder: function() {
        _initRecorder();
      },
      status: function() {
        return {
          isAvailable: isAvailable,
          isRecording: isRecording
        };
      },
      startRecording: function() {
        // If worker is not available then do not start recording.
        if (mp3Worker === null) {
          return null;
        }
        var navigator = _startMicrophone();
        navigator.then(function(stream) {
          isRecording = true;
          // Set microphone stream will be used for stopping track
          // stream in another function.
          microphoneStream = stream;
          _processMicAudio(stream);
        }, function() {
          $log.warn('Microphone was not started because of' +
          'user denied permission.');
          isRecording = false;
        });

        return navigator;
      },
      stopRecord: function() {
        if (mp3Worker !== null) {
          _stopRecord();
        }
      },
      getMp3Data: function() {
        return defer.promise;
      },
      closeRecorder: function() {
        _closeRecorder();
      }
    };
  }
]);


text:
<?php

namespace Blogger\BlogBundle\DataFixtures\ORM;

use Blogger\BlogBundle\Entity\Category;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;

class CategoryFixtures extends AbstractFixture implements OrderedFixtureInterface
{
    /**
     * Load data fixtures with the passed EntityManager
     *
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $category1 = new Category();
        $category1->setName('News');
        $category1->setSlug('news');
        $manager->persist($category1);

        $category2 = new Category();
        $category2->setName('Books');
        $category2->setSlug('books');
        $manager->persist($category2);

        $category3 = new Category();
        $category3->setName('Work');
        $category3->setSlug('work');
        $manager->persist($category3);

        $category4 = new Category();
        $category4->setName('Other')->setParent($category2);
        $category4->setSlug('other');
        $manager->persist($category4);

        $manager->flush();

        $this->addReference('category-1', $category1);
        $this->addReference('category-2', $category2);
        $this->addReference('category-3', $category3);
        $this->addReference('category-4', $category4);

    }

    /**
     * Get the order of this fixture
     *
     * @return integer
     */
    public function getOrder()
    {
        return 1;
    }
}


text:
Hydrogen
========

Hydrogen


text:
Repository moved
=====================

This repository has been moved to [https://github.com/hybris/raml-validation-proxy](https://github.com/hybris/raml-validation-proxy)

Old content
=====================

raml-validation-proxy
-----------

A lot of RESTful services using [RESTful API Modeling Language][8] to define their APIs.
This service utilizes RESTful services test harness to verify if implementation follows API contract.

It creates http proxy to record requests and responses from oryginal service. After the tests json report can be generated.

It is built on [Vert.x][7] embedded server with Java 8 and [Maven](http://maven.apache.org/).

Roadmap
-----------

Following features are planned:

* Easier configuration.
* Integration with [Maven Failsafe][9].
* Integration with [JUnit][10].
* [Gradle][11] build.
* Request and response body verification.
* Missing examples in RAML.
* RAML verification against wadl file.

How to start
-----------

#### Installing raml parser.

Download [raml-java-parser](https://github.com/raml-org/raml-java-parser).

Install in local repository:
```sh
mvn install
```

#### Starting proxy server.

```sh
mvn compile
mvn exec:java
```

#### Running your tests

By default proxy server listens on [http://localhost:8081][5] and redirect calls to [http://localhost:8080][6].
Remember to set URL location to your RAML file (Check config section for details).

#### Showing report

Open in your browser:

* [http://localhost:8081/raml-validation-proxy/raml_report.json][1] Report with discrepancies with RAML and tests. See report section for detais.
* [http://localhost:8081/raml-validation-proxy/proxy_log.json][2] Recorded requests report.
* [http://localhost:8081/raml-validation-proxy/raml_log.json][3] Parsed RAML file report.
* [http://localhost:8081/raml-validation-proxy/restart][4] Restarts testing session. Reports are cleared.

Configuration
-----------

Application is looking for *ramlvalidation_config.json* file on the classpath.

Example configuration with default values:

```json
{
   "target.host" : "localhost",
   "target.port" : 8080,
   "proxy.port" : 8081,
   "raml.resource" : "http://localhost:8080/service.raml",
   "ignored.resources" : [ "request.header.Host", "response.header.Date", "request.header.Accept", "request.header.Connection", "response.header.Server", "request.header.Content-Length", "response.header.Content-Length"
   ]
}
```

Report
-----------

What is checked:

* URLs,
* http methods,
* status codes,
* header names,
* header values (examples and defaults defined in RAML),
* query parameter names,
* query parameters values (examples and defaults defined in RAML).

In case checked value verification failed following messages are added to report:

* **NOT_USED_IN_TEST** : Defined in RAML file but no found in any request or response.
* **NOT_DEFINED_IN_RAML** : Found in request or response but not dfined in RAML file.

#### Example

```json
{
  "/cars/{id}/resource": {
    "POST" : {
      "request.header.Count" : {
        "many" : "NOT_USED_IN_TEST"
      },
      "request.header.Accept" : "NOT_USED_IN_TEST",
      "response.status" : {
        "409" : "NOT_USED_IN_TEST"
      },
      "response.header.Content-Type" : "NOT_DEFINED_IN_RAML"
    }
  },
  "/cars" : "NOT_USED_IN_TEST",
  "/cars/123" : "NOT_DEFINED_IN_RAML"
}
```

  [1]: http://localhost:8081/raml-validation-proxy/raml_report.json
  [2]: http://localhost:8081/raml-validation-proxy/proxy_log.json
  [3]: http://localhost:8081/raml-validation-proxy/raml_log.json
  [4]: http://localhost:8081/raml-validation-proxy/restart
  [5]: http://localhost:8080
  [6]: http://localhost:8081
  [7]: http://vertx.io/embedding_manual.html
  [8]: http://raml.org/
  [9]: http://maven.apache.org/surefire/maven-failsafe-plugin/
  [10]: http://junit.org/
  [11]: http://www.gradle.org/


text:
		{% for i in range(10) %}
			{{i}}
		{% endfor %}

 {

		{% for field in fields %}

			{{field.legend}}:

				{% if field.type == 'text' %}
					"{{opentag}} {{field.legend}} {{ closetag }}" {% if not loop.last %},{% endif %}
					<input type="text" class="gnp-input" data-gnp-type="{{field.type}}" name="{{field.legend}}"  />
				{% elif field.type == 'date' %}
					"{{opentag}} {{field.legend}} {{ closetag }}" {% if not loop.last %},{% endif %}
					<input type="date" class="gnp-input" data-gnp-type="{{field.type}}" name="{{field.legend}}" />
				{% elif field.type == 'md' %}
					"{{opentag}} _gnp_files.{{field.legend}} {{ closetag }}" {% if not loop.last %},{% endif %}
					<input type="file" class="gnp-file-input" accept=".{{field.type}}" data-gnp-type="{{field.type}}" name="{{field.legend}}"/>
				{% endif %}

		{% endfor %}

 }

		<input type="button" class="gnp-button" id="gnp-save" value="save" />
		<input type="button" class="gnp-button" id="gnp-publish" value="publish" />


text:
import t from 'tcomb-validation';
import { expect } from 'chai';
import {
  makeTest,
  makeSuite,
  makeReport,
  parseSuite,
  PASSED,
  FAILED,
  BEFORE,
  BEFORE_EACH,
  AFTER,
  AFTER_EACH,
  FAILED_BEFORE,
  FAILED_BEFORE_EACH,
  FAILED_AFTER,
  FAILED_AFTER_EACH,
} from './index';
import * as types from '../../src/bin/types';

const passed = makeTest('passed', { hook: 'beforeEach' });
const failed = makeTest('failed', { hook: 'after' });
const pending = makeTest('pending');
const skipped = makeTest('skipped');
const tests = { passed, failed, pending, skipped };

const suite = [[BEFORE, BEFORE_EACH, AFTER, AFTER_EACH, PASSED, FAILED]];

const suiteFailedBefore = [
  [FAILED_BEFORE, BEFORE_EACH, AFTER, AFTER_EACH, PASSED, FAILED],
];

const suiteFailedBeforeEach = [
  [BEFORE, FAILED_BEFORE_EACH, AFTER, AFTER_EACH, PASSED, FAILED],
];

const suiteFailedAfter = [
  [BEFORE, BEFORE_EACH, FAILED_AFTER, AFTER_EACH, PASSED, FAILED],
];

const suiteFailedAfterEach = [
  [BEFORE, BEFORE_EACH, AFTER, FAILED_AFTER_EACH, PASSED, FAILED],
];

describe('test fixtures', () => {
  Object.keys(tests).forEach(type => {
    it(`should validate test type: ${type}`, () => {
      const result = t.validate(tests[type], types.Test, { strict: true });
      const errMsgs = result.errors.map(err => err.message);
      expect(errMsgs).to.deep.equal([]);
      expect(result.isValid()).to.equal(true);
    });
  });
});

describe('suite fixtures', () => {
  it('should validate suite', () => {
    const parsed = makeSuite(parseSuite(suite));
    const result = t.validate(parsed, types.Suite, { strict: true });
    const errMsgs = result.errors.map(err => err.message);
    expect(errMsgs).to.deep.equal([]);
    expect(result.isValid()).to.equal(true);
  });
});

describe('report stats', () => {
  function shouldMatchStats(
    stats,
    numSuites,
    numTests,
    numPasses,
    numPending,
    numFailures,
    numTestsReg,
    passPct,
    pendPct,
    numOther,
    numSkipped
  ) {
    expect(stats).to.have.property('suites', numSuites);
    expect(stats).to.have.property('tests', numTests);
    expect(stats).to.have.property('passes', numPasses);
    expect(stats).to.have.property('pending', numPending);
    expect(stats).to.have.property('failures', numFailures);
    expect(stats.start).to.be.a('string');
    expect(stats.end).to.be.a('string');
    expect(stats).to.have.property('testsRegistered', numTestsReg);
    expect(stats).to.have.property('passPercent', passPct);
    expect(stats).to.have.property('pendingPercent', pendPct);
    expect(stats).to.have.property('other', numOther);
    expect(stats.hasOther).to.equal(!!numOther);
    expect(stats).to.have.property('skipped', numSkipped);
    expect(stats.hasSkipped).to.equal(!!numSkipped);
  }

  it('should have expected stats', () => {
    const report = makeReport(suite);
    shouldMatchStats(report.stats, 1, 2, 1, 0, 1, 2, 50, 0, 0, 0);
  });

  it('should have expected stats - failed before', () => {
    const report = makeReport(suiteFailedBefore);
    shouldMatchStats(report.stats, 1, 0, 0, 0, 0, 2, 0, 0, 1, 2);
  });

  it('should have expected stats - failed beforeEach', () => {
    const report = makeReport(suiteFailedBeforeEach);
    shouldMatchStats(report.stats, 1, 0, 0, 0, 0, 2, 0, 0, 1, 2);
  });

  it('should have expected stats - failed after', () => {
    const report = makeReport(suiteFailedAfter);
    shouldMatchStats(report.stats, 1, 2, 1, 0, 1, 2, 50, 0, 1, 0);
  });

  it('should have expected stats - failed afterEach', () => {
    const report = makeReport(suiteFailedAfterEach);
    shouldMatchStats(report.stats, 1, 1, 1, 0, 0, 2, 50, 0, 1, 1);
  });
});

describe('report fixtures', () => {
  it('should validate report', () => {
    const report = makeReport(suite);
    const result = t.validate(report, types.TestReport, { strict: true });
    const errMsgs = result.errors.map(err => err.message);
    expect(errMsgs).to.deep.equal([]);
    expect(result.isValid()).to.equal(true);
  });
});


text:
package org.vitrivr.cineast.core.temporal.sequential;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.vitrivr.cineast.core.data.StringDoublePair;
import org.vitrivr.cineast.core.data.TemporalObject;
import org.vitrivr.cineast.core.data.entities.MediaSegmentDescriptor;
import org.vitrivr.cineast.core.temporal.TemporalTestCases;

public class SequentialTemporalScoringAlgorithmTest {

  @Test
  @DisplayName("Sanity temporal scoring")
  public void testSanity() {
    Map<String, MediaSegmentDescriptor> emptyMap = new HashMap<>();
    List<List<StringDoublePair>> emptyList = new ArrayList<>();
    SequentialTemporalScoringAlgorithm testAlgorithm = new SequentialTemporalScoringAlgorithm(emptyMap, emptyList, -1f);
    List<TemporalObject> result = testAlgorithm.score();
    assert result.size() == 0;
  }

  @Test
  @DisplayName("First temporal test case")
  public void testTemporalTestCase1() {
    TemporalTestCases temporalTestCases = new TemporalTestCases();
    temporalTestCases.buildTestCase1();
    SequentialTemporalScoringAlgorithm testAlgorithm = new SequentialTemporalScoringAlgorithm(temporalTestCases.getSegmentMap(), temporalTestCases.getContainerResults(), temporalTestCases.getMaxLength());
    List<TemporalObject> result = testAlgorithm.score();

    assert temporalTestCases.assertListSame(temporalTestCases.getExpectedResults(), result);
    assert result.size() == 2;
  }

  @Test
  @DisplayName("Second temporal test case")
  public void testTemporalTestCase2() {
    TemporalTestCases temporalTestCases = new TemporalTestCases();
    temporalTestCases.buildTestCase2();
    SequentialTemporalScoringAlgorithm testAlgorithm = new SequentialTemporalScoringAlgorithm(temporalTestCases.getSegmentMap(), temporalTestCases.getContainerResults(), temporalTestCases.getMaxLength());
    List<TemporalObject> result = testAlgorithm.score();

    assert temporalTestCases.assertListSame(temporalTestCases.getExpectedResults(), result);
    assert result.size() == 1;
  }

  @Test
  @DisplayName("Third temporal test case")
  public void testTemporalTestCase3() {
    TemporalTestCases temporalTestCases = new TemporalTestCases();
    temporalTestCases.buildTestCase3();
    SequentialTemporalScoringAlgorithm testAlgorithm = new SequentialTemporalScoringAlgorithm(temporalTestCases.getSegmentMap(), temporalTestCases.getContainerResults(), temporalTestCases.getMaxLength());
    List<TemporalObject> result = testAlgorithm.score();

    assert temporalTestCases.assertListSame(temporalTestCases.getExpectedResults(), result);
    assert result.size() == 1;
  }

  @Test
  @DisplayName("Fourth temporal test case")
  public void testTemporalTestCase4() {
    TemporalTestCases temporalTestCases = new TemporalTestCases();
    temporalTestCases.buildTestCase4();
    SequentialTemporalScoringAlgorithm testAlgorithm = new SequentialTemporalScoringAlgorithm(temporalTestCases.getSegmentMap(), temporalTestCases.getContainerResults(), temporalTestCases.getMaxLength());
    List<TemporalObject> result = testAlgorithm.score();

    assert temporalTestCases.assertListSame(temporalTestCases.getExpectedResults(), result);
    assert result.size() == 3;
  }

}


text:
package minitwit;

import static org.junit.jupiter.api.Assertions.*;

import java.io.*;

import jakarta.ws.rs.client.*;
import jakarta.ws.rs.core.*;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.minijax.mustache.*;
import org.minijax.rs.*;
import org.minijax.rs.persistence.*;
import org.minijax.rs.test.*;
import org.minijax.security.*;
import org.minijax.view.*;

import minitwit.Minitwit.Dao;
import minitwit.Minitwit.User;

class MinitwitTest extends MinijaxTest {
    public static User alice;
    public static Cookie aliceCookie;
    public static User bob;
    public static Cookie bobCookie;

    @BeforeAll
    public static void setUpMinitwit() throws IOException {
        getServer()
                .property("jakarta.persistence.jdbc.url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1")
                .register(PersistenceFeature.class)
                .register(MustacheFeature.class)
                .register(new SecurityFeature(User.class, Dao.class))
                .register(Minitwit.class);

        try (final MinijaxRequestContext ctx = createRequestContext()) {
            final Dao dao = ctx.getResource(Dao.class);
            alice = new User();
            alice.setName("Alice Smith");
            alice.setHandle("alice");
            alice.setEmail("alice@example.com");
            alice.setPassword("alicepwd");
            alice.setRoles("user");
            dao.create(alice);

            aliceCookie = ctx.getResource(Security.class).loginAs(alice);

            bob = new User();
            bob.setName("Bob Johnson");
            bob.setHandle("bob");
            bob.setEmail("bob@example.com");
            bob.setPassword("bobpwd");
            bob.setRoles("bob");
            dao.create(bob);

            bobCookie = ctx.getResource(Security.class).loginAs(bob);
        }
    }

    @Test
    void testAnonymous() {
        final Response response = target("/").request().get();
        assertNotNull(response);
        assertEquals(303, response.getStatus());
        assertEquals("/public", response.getHeaderString("Location"));
    }

    @Test
    void testPublicTimeline() {
        final Response response = target("/public").request().get();
        assertNotNull(response);
        assertEquals(200, response.getStatus());

        final View view = (View) response.getEntity();
        assertNotNull(view);
        assertEquals("timeline", view.getTemplateName());
        assertNotNull(view.getModel().get("messages"));
    }

    @Test
    void testPersonalTimeline() throws Exception {
        final Response response = target("/").request().cookie(aliceCookie).get();
        assertNotNull(response);
        assertEquals(200, response.getStatus());

        final View view = (View) response.getEntity();
        assertNotNull(view);
        assertEquals("timeline", view.getTemplateName());
        assertNotNull(view.getModel().get("messages"));
    }

    @Test
    void testDifferentUserTimeline() throws Exception {
        final Response response = target("/bob").request().cookie(aliceCookie).get();
        assertNotNull(response);
        assertEquals(200, response.getStatus());

        final View view = (View) response.getEntity();
        assertNotNull(view);
        assertEquals("timeline", view.getTemplateName());
        assertNotNull(view.getModel().get("messages"));
    }

    @Test
    void testFollowUser() throws Exception {
        assertFalse(alice.following.contains(bob));

        final Response response = target("/bob/follow").request().cookie(aliceCookie).get();
        assertNotNull(response);
        assertEquals(303, response.getStatus());

        try (final MinijaxRequestContext ctx = createRequestContext()) {
            final Dao dao = ctx.getResource(Dao.class);
            assertTrue(dao.read(User.class, alice.getId()).following.contains(bob));
        }
    }

    @Test
    void testLoginPage() throws Exception {
        final View view = target("/login").request().get(View.class);
        assertNotNull(view);
        assertEquals("login", view.getTemplateName());
    }

    @Test
    void testEmptyLogin() throws Exception {
        final Form form = new Form();

        final View view = target("/login").request().post(Entity.form(form), View.class);
        assertNotNull(view);
        assertNotNull(view.getModel().get("error"));
    }

    @Test
    void testSuccessfulLogin() throws Exception {
        final Form form = new Form();
        form.param("email", "alice@example.com");
        form.param("password", "alicepwd");

        final Response response = target("/login").request().post(Entity.form(form));
        assertNotNull(response);
        assertEquals(303, response.getStatus());
        assertFalse(response.getCookies().isEmpty());
    }

    @Test
    void testRegisterPage() throws Exception {
        final View view = target("/register").request().get(View.class);
        assertNotNull(view);
        assertEquals("register", view.getTemplateName());
    }

    @Test
    void testSuccessfulRegister() throws Exception {
        final Form form = new Form();
        form.param("handle", "new_user");
        form.param("email", "new_user@example.com");
        form.param("password", "new_user_pwd");

        final Response response = target("/register").request().post(Entity.form(form));
        assertNotNull(response);
        assertEquals(303, response.getStatus());
        assertFalse(response.getCookies().isEmpty());
    }

    @Test
    void testUnauthenticatedAddMessage() throws Exception {
        final Form form = new Form();
        form.param("text", "Hello world");

        final Response response = target("/addmessage").request().post(Entity.form(form));
        assertNotNull(response);
        assertEquals(401, response.getStatus());
    }

    @Test
    void testMissingCsrfAddMessage() throws Exception {
        final Form form = new Form();
        form.param("text", "Hello world");

        final Response response = target("/addmessage").request().cookie(aliceCookie).post(Entity.form(form));
        assertNotNull(response);
        assertEquals(400, response.getStatus());
    }

    @Test
    void testIncorrectCsrfAddMessage() throws Exception {
        final Form form = new Form();
        form.param("text", "Hello world");
        form.param("csrf", "nope");

        final Response response = target("/addmessage").request().cookie(aliceCookie).post(Entity.form(form));
        assertNotNull(response);
        assertEquals(400, response.getStatus());
    }

    @Test
    void testSuccessfulAddMessage() throws Exception {
        final Form form = new Form();
        form.param("text", "Hello world");
        form.param("csrf", aliceCookie.getValue());

        final Response response = target("/addmessage").request().cookie(aliceCookie).post(Entity.form(form));
        assertNotNull(response);
        assertEquals(303, response.getStatus());
    }

    @Test
    void testGravatarUrl() throws IOException {
        final User user = new User();
        user.setEmail("cody@ebberson.com");
        assertEquals("https://www.gravatar.com/avatar/9e46d967afb5e2fd13b2802c1e64112d?d=identicon&s=80", user.gravatarUrl());
    }
}


text:
<?php

// require config file
require_once('../config.php');

$postdata = file_get_contents("php://input");
    $request = json_decode($postdata);
    @$uid = $request->uid;
    @$recent = $request->recent;

$sql = "UPDATE `users` SET `recent`='$recent' WHERE `uid`='$uid';";

if ($conn->query($sql) === TRUE) {
    echo "User recent saved sucessfuly";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>


text:
name: encryptwallet
btcversion: 22.0.0
btcgroup: wallet
permalink: en/doc/22.0.0/rpc/wallet/encryptwallet/
---

encryptwallet "passphrase"

Encrypts the wallet with 'passphrase'. This is for first time encryption.
After this, any calls that interact with private keys such as sending or signing
will require the passphrase to be set prior the making these calls.
Use the walletpassphrase call for this, and then walletlock call.
If the wallet is already encrypted, use the walletpassphrasechange call.

Arguments:
1. passphrase    (string, required) The pass phrase to encrypt the wallet with. It must be at least 1 character, but should be long.

Result:
"str"    (string) A string with further instructions

Examples:

Encrypt your wallet
> bitcoin-cli encryptwallet "my pass phrase"

Now set the passphrase to use the wallet, such as for signing or sending bitcoin
> bitcoin-cli walletpassphrase "my pass phrase"

Now we can do something like sign
> bitcoin-cli signmessage "address" "test message"

Now lock the wallet again by removing the passphrase
> bitcoin-cli walletlock

As a JSON-RPC call
> curl --user myusername --data-binary '{"jsonrpc": "1.0", "id": "curltest", "method": "encryptwallet", "params": ["my pass phrase"]}' -H 'content-type: text/plain;' http://127.0.0.1:8332/


text:
package com.pivot13.test.support;

import org.junit.Test;

import static com.pivotallabs.robolectricgem.expect.Expect.expect;

public class JsonEditorTest {

    @Test
    public void exampleOfUsingThisClassToEditJson() throws Exception {
        String json = "[1, 2, {\"a\": [[7, 8], 3, 4], \"b\": 10}, 5, 999]";
        String expectedEditedJson = "[1.5,\"hello\",{\"a\":[[true,8],3,4],\"b\":1,\"new_prop\":\"value\"},[\"more_json\"]]";

        // extreme chaining example
        String editedJson = new JsonEditor(json)
                .set(0, 1.5)
                .set(1, "hello")
                .child(2) // move the current position of the editor to the third child
                .set("b", 1) // set an existing property; throws an exception if the property does not exist
                .put("new_prop", "value") // put a property that does not exist
                .child("a").child(0) // move deeper in the tree
                .set(0, true)
                .root() // move back to the root node
                .set(3, new JsonEditor("[\"more_json\"]"))
                .remove(4)
                .toJson();

        expect(editedJson).toEqual(expectedEditedJson);

        // same example with less chaining
        JsonEditor e = new JsonEditor(json);
        e.root().set(0, 1.5);
        e.root().set(1, "hello");
        e.root().child(2).put("new_prop", "value").set("b", 1);
        e.root().child(2).child("a").child(0).set(0, true);
        e.root().set(3, new JsonEditor("[\"more_json\"]"));
        e.root().remove(4);

        expect(e.toJson()).toEqual(expectedEditedJson);
    }

    @Test(expected = JsonEditor.JsonEditorException.class)
    public void constructor_shouldThrowException_whenJsonIsInvalid() throws Exception {
        new JsonEditor("this is not valid json");
    }

    @Test(expected = JsonEditor.JsonEditorException.class)
    public void constructor_shouldThrowException_whenJsonIsInvalid2() throws Exception {
        new JsonEditor("42");
    }

    @Test(expected = ArrayIndexOutOfBoundsException.class)
    public void arrayChild_shouldThrowException_whenArrayIsEmpty() throws Exception {
        new JsonEditor("[]").child(0);
    }

    @Test(expected = JsonEditor.NotAnArrayNodeException.class)
    public void arrayChild_shouldThrowException_whenItIsUsedOnAnObject() throws Exception {
        new JsonEditor("{}").child(0);
    }

    @Test(expected = JsonEditor.NotAnArrayNodeException.class)
    public void arrayChild_shouldThrowException_whenItIsUsedOnABasicDataType() throws Exception {
        new JsonEditor("[1]").child(0).child(0);
    }

    @Test
    public void arrayChild_shouldMoveTheCurrentNodeToAnElementOfTheArray() throws Exception {
        String arrayJson = "[1, 2, 3]";
        expect(new JsonEditor(arrayJson).child(0).valueAsNumber()).toEqual(1);
        expect(new JsonEditor(arrayJson).child(2).valueAsNumber()).toEqual(3);
    }

    @Test
    public void arrayChild_shouldSupportChainedCalls_toTraverseTheDomTree() throws Exception {
        String arrayJson = "[[1, 2, 3], 4, 5]";
        expect(new JsonEditor(arrayJson).child(0).child(0).valueAsNumber()).toEqual(1);
        expect(new JsonEditor(arrayJson).child(0).child(2).valueAsNumber()).toEqual(3);

        String deeperArrayJson = "[[11, 22, [111, 222, [1111, 2222]]], 2, 3]";
        expect(new JsonEditor(deeperArrayJson).child(0).child(2).child(1).valueAsNumber()).toEqual(222);
        expect(new JsonEditor(deeperArrayJson).child(0).child(2).child(2).child(1).valueAsNumber()).toEqual(2222);
    }

    @Test(expected = JsonEditor.NotAnObjectNodeException.class)
    public void objectChild_shouldThrowException_whenNodeIsNotAnObject() throws Exception {
        new JsonEditor("[]").child("property_name");
    }

    @Test(expected = JsonEditor.NoSuchPropertyException.class)
    public void objectChild_shouldThrowException_whenPropertyDoesNotExistOnObject() throws Exception {
        new JsonEditor("{\"a\": 1}").child("this property does not exist");
    }

    @Test
    public void objectChild_shouldMoveTheCurrentNodeToTheValueOfThatPropertyOfTheObject() throws Exception {
        expect(new JsonEditor("{\"a\": 1}").child("a").valueAsNumber()).toEqual(1);
    }

    @Test
    public void objectChild_shouldSupportChainedCalls_toTraverseTheDomTree() throws Exception {
        String objectJson = "{\"a\": {\"aa\": 42}}";
        expect(new JsonEditor(objectJson).child("a").child("aa").valueAsNumber()).toEqual(42);

        String nestedObjectJson = "{\"a\": 1, \"b\": {\"aa\": 22, \"bb\": {\"aaa\": 555, \"bbb\": 777}}}";
        expect(new JsonEditor(nestedObjectJson).child("b").child("bb").child("aaa").valueAsNumber()).toEqual(555);
    }

    @Test
    public void child_shouldSupportChainedCalls_mixingArrayChildAndObjectChild() throws Exception {
        String arrayJson = "[{\"a\": {\"aa\": [42, 99]}}]";
        expect(new JsonEditor(arrayJson).child(0).child("a").child("aa").child(1).valueAsNumber()).toEqual(99);
    }

    @Test
    public void valueAsNumber_shouldReturnNumberForNumericNodes() throws Exception {
        String arrayJson = "[1.5, 2.1, 3.9]";
        expect(new JsonEditor(arrayJson).child(0).valueAsNumber()).toEqual(1.5);
        expect(new JsonEditor(arrayJson).child(2).valueAsNumber()).toEqual(3.9);
    }

    @Test(expected = JsonEditor.NotANumericNodeException.class)
    public void valueAsNumber_shouldThrowException_whenTheNodeIsNotANumericNode() throws Exception {
        new JsonEditor("[false]").child(0).valueAsNumber();
    }

    @Test(expected = JsonEditor.NotANumericNodeException.class)
    public void valueAsNumber_shouldThrowException_whenTheNodeIsANullNode() throws Exception {
        new JsonEditor("[null]").child(0).valueAsNumber();
    }

    @Test
    public void valueAsBoolean_shouldReturnBooleanForBooleanNodes() throws Exception {
        String arrayJson = "[false, false, true]";
        expect(new JsonEditor(arrayJson).child(0).valueAsBoolean()).toBeFalse();
        expect(new JsonEditor(arrayJson).child(2).valueAsBoolean()).toBeTrue();
    }

    @Test(expected = JsonEditor.NotABooleanNodeException.class)
    public void valueAsBoolean_shouldThrowException_whenTheNodeIsNotABooleanNode() throws Exception {
        new JsonEditor("[1]").child(0).valueAsBoolean();
    }

    @Test(expected = JsonEditor.NotABooleanNodeException.class)
    public void valueAsBoolean_shouldThrowException_whenTheNodeIsANullNode() throws Exception {
        new JsonEditor("[null]").child(0).valueAsBoolean();
    }

    @Test
    public void valueAsString_shouldReturnStringForBooleanNodes() throws Exception {
        String arrayJson = "[\"string one\", \"string two\", \"string three\"]";
        expect(new JsonEditor(arrayJson).child(0).valueAsString()).toEqual("string one");
        expect(new JsonEditor(arrayJson).child(2).valueAsString()).toEqual("string three");
    }

    @Test(expected = JsonEditor.NotAStringNodeException.class)
    public void valueAsString_shouldThrowException_whenTheNodeIsNotAStringNode() throws Exception {
        new JsonEditor("[1]").child(0).valueAsString();
    }

    @Test(expected = JsonEditor.NotAStringNodeException.class)
    public void valueAsString_shouldThrowException_whenTheNodeIsANullNode() throws Exception {
        new JsonEditor("[null]").child(0).valueAsString();
    }

    @Test
    public void isNullValue_shouldCheckIfTheNodeIsANullNode() throws Exception {
        String arrayJson = "[null, 1]";
        expect(new JsonEditor(arrayJson).child(0).isNullValue()).toBeTrue();
        expect(new JsonEditor(arrayJson).child(1).isNullValue()).toBeFalse();
    }

    @Test
    public void arraySetBoolean_shouldChangeTheValueAtTheGivenIndexInTheArray() throws Exception {
        JsonEditor editor = new JsonEditor("[1]");
        expect(editor.root().child(0).valueAsNumber()).toEqual(1);

        editor.root().set(0, true);
        expect(editor.root().child(0).valueAsBoolean()).toBeTrue();

        editor.root().set(0, false);
        expect(editor.root().child(0).valueAsBoolean()).toBeFalse();
    }

    @Test
    public void arraySetInt_shouldChangeTheValueAtTheGivenIndexInTheArray() throws Exception {
        JsonEditor editor = new JsonEditor("[1]");
        editor.set(0, 3);
        expect(editor.child(0).valueAsNumber()).toEqual(3);
    }

    @Test
    public void arraySetInt_shouldSupportChainedCalls_toTraverseTheDomTree() throws Exception {
        String arrayJson = "[1, 2, 3]";

        JsonEditor editor = new JsonEditor(arrayJson);
        expect(editor.set(0, 4).child(0).valueAsNumber()).toEqual(4);

        editor = new JsonEditor(arrayJson);
        editor.set(0, 4).set(1, 5);
        expect(editor.child(0).valueAsNumber()).toEqual(4);
        expect(editor.root().child(1).valueAsNumber()).toEqual(5);
    }

    @Test
    public void arraySetDouble_shouldChangeTheValueAtTheGivenIndexInTheArray() throws Exception {
        JsonEditor editor = new JsonEditor("[1]");
        editor.set(0, 3.66);
        expect(editor.child(0).valueAsNumber()).toEqual(3.66);
    }

    @Test
    public void arraySetLong_shouldChangeTheValueAtTheGivenIndexInTheArray() throws Exception {
        JsonEditor editor = new JsonEditor("[1]");
        editor.set(0, 344L);
        expect(editor.child(0).valueAsNumber()).toEqual(344L);
    }

    @Test
    public void arraySetString_shouldChangeTheValueAtTheGivenIndexInTheArray() throws Exception {
        JsonEditor editor = new JsonEditor("[1]");
        editor.set(0, "new value");
        expect(editor.child(0).valueAsString()).toEqual("new value");
    }

    @Test
    public void arraySetJsonEditor_shouldChangeTheValueAtTheGivenIndexInTheArray_basedOnTheCurrentPositionOfTheEditor() throws Exception {
        JsonEditor editor = new JsonEditor("[1]");
        editor.set(0, new JsonEditor("[1, [2, 3]]").child(1));
        expect(editor.child(0).child(1).valueAsNumber()).toEqual(3);
        expect(editor.root().toJson()).toEqual("[[2,3]]");
    }

    @Test
    public void arraySetJsonEditor_shouldNotCrash_whenCreatingAPotentialLoopInTheDom() throws Exception {
        JsonEditor editor = new JsonEditor("[1]");
        expect(editor.set(0, editor).toJson()).toEqual("[[1]]");
    }

    @Test(expected = JsonEditor.NotAnArrayNodeException.class)
    public void arraySet_shouldThrowException_whenItIsNotUsedOnAnArray() throws Exception {
        new JsonEditor("{}").set(0, 2);
    }

    @Test(expected = ArrayIndexOutOfBoundsException.class)
    public void arraySet_shouldThrowException_whenArrayIsEmpty() throws Exception {
        new JsonEditor("[]").set(0, 2);
    }

    @Test(expected = JsonEditor.NotAnObjectNodeException.class)
    public void objectSetInt_shouldThrowException_whenItIsNotUsedOnAnObject() throws Exception {
        new JsonEditor("[]").set("a", 2);
    }

    @Test(expected = JsonEditor.NoSuchPropertyException.class)
    public void objectSetInt_shouldThrowException_whenPropertyDoesNotExist() throws Exception {
        new JsonEditor("{}").set("a", 2);
    }

    @Test
    public void objectSetInt_shouldChangeTheValueAtTheGivenPropertyInTheObject() throws Exception {
        expect(new JsonEditor("{\"a\": 0}").set("a", 3).child("a").valueAsNumber()).toEqual(3);
    }

    @Test
    public void objectSetInt_shouldSupportChainedCalls_toTraverseTheDomTree() throws Exception {
        String objectJson = "{\"a\": 2, \"b\": 3}";

        JsonEditor editor = new JsonEditor(objectJson);
        expect(editor.set("a", 4).child("a").valueAsNumber()).toEqual(4);

        editor = new JsonEditor(objectJson);
        editor.set("a", 4).set("b", 5);
        expect(editor.child("a").valueAsNumber()).toEqual(4);
        expect(editor.root().child("b").valueAsNumber()).toEqual(5);
    }

    @Test(expected = JsonEditor.NoSuchPropertyException.class)
    public void objectSetLong_shouldThrowException_whenPropertyDoesNotExist() throws Exception {
        new JsonEditor("{}").set("a", 2L);
    }

    @Test
    public void objectSetLong_shouldChangeTheValueAtTheGivenPropertyInTheObject() throws Exception {
        expect(new JsonEditor("{\"a\": 0}").set("a", 3L).child("a").valueAsNumber()).toEqual(3L);
    }

    @Test(expected = JsonEditor.NoSuchPropertyException.class)
    public void objectSetDouble_shouldThrowException_whenPropertyDoesNotExist() throws Exception {
        new JsonEditor("{}").set("a", 9.55);
    }

    @Test
    public void objectSetDouble_shouldChangeTheValueAtTheGivenPropertyInTheObject() throws Exception {
        expect(new JsonEditor("{\"a\": 0}").set("a", 9.55).child("a").valueAsNumber()).toEqual(9.55);
    }

    @Test(expected = JsonEditor.NoSuchPropertyException.class)
    public void objectSetBoolean_shouldThrowException_whenPropertyDoesNotExist() throws Exception {
        new JsonEditor("{}").set("a", false);
    }

    @Test
    public void objectSetBoolean_shouldChangeTheValueAtTheGivenPropertyInTheObject() throws Exception {
        expect(new JsonEditor("{\"a\": 0}").set("a", false).child("a").valueAsBoolean()).toBeFalse();
    }

    @Test(expected = JsonEditor.NoSuchPropertyException.class)
    public void objectSetString_shouldThrowException_whenPropertyDoesNotExist() throws Exception {
        new JsonEditor("{}").set("a", "new value");
    }

    @Test
    public void objectSetString_shouldChangeTheValueAtTheGivenPropertyInTheObject() throws Exception {
        expect(new JsonEditor("{\"a\": 0}").set("a", "new value").child("a").valueAsString()).toEqual("new value");
    }

    @Test(expected = JsonEditor.NoSuchPropertyException.class)
    public void objectSetJsonEditor_shouldThrowException_whenPropertyDoesNotExist() throws Exception {
        new JsonEditor("{}").set("a", new JsonEditor("[1, [2, 3]]"));
    }

    @Test
    public void objectSetJsonEditor_shouldChangeTheValueAtTheGivenPropertyInTheObject_basedOnTheFocusedNodeOfTheEditor() throws Exception {
        JsonEditor editor = new JsonEditor("{\"a\": 0}");

        editor.set("a", new JsonEditor("[1, [2, 3]]").child(1));
        expect(editor.child("a").child(1).valueAsNumber()).toEqual(3);
        expect(editor.root().toJson()).toEqual("{\"a\":[2,3]}");
    }

    @Test
    public void objectSetJsonEditor_shouldNotCrash_whenCreatingAPotentialLoopInTheDom() throws Exception {
        JsonEditor editor = new JsonEditor("{\"a\": 0}");
        expect(editor.set("a", editor).toJson()).toEqual("{\"a\":{\"a\":0}}");
    }

    @Test(expected = JsonEditor.NotAnObjectNodeException.class)
    public void objectPutInt_shouldThrowException_whenItIsNotUsedOnAnObject() throws Exception {
        new JsonEditor("[]").put("a", 2);
    }

    @Test
    public void objectPutInt_shouldPutTheValueAtTheGivenPropertyInTheObject() throws Exception {
        expect(new JsonEditor("{\"a\": 0}").put("a", 3).child("a").valueAsNumber()).toEqual(3);
        expect(new JsonEditor("{\"a\": 0}").put("no such property", 4).child("no such property").valueAsNumber()).toEqual(4);
    }

    @Test
    public void objectPutInt_shouldSupportChainedCalls_toTraverseTheDomTree() throws Exception {
        String objectJson = "{\"a\": 2, \"b\": 3}";

        JsonEditor editor = new JsonEditor(objectJson);
        expect(editor.put("a", 4).child("a").valueAsNumber()).toEqual(4);

        editor = new JsonEditor(objectJson);
        editor.put("a", 4).put("b", 5);
        expect(editor.child("a").valueAsNumber()).toEqual(4);
        expect(editor.root().child("b").valueAsNumber()).toEqual(5);
    }

    @Test
    public void objectPutLong_shouldPutTheValueAtTheGivenPropertyInTheObject() throws Exception {
        expect(new JsonEditor("{\"a\": 0}").put("a", 3L).child("a").valueAsNumber()).toEqual(3L);
        expect(new JsonEditor("{\"a\": 0}").put("no such property", 4L).child("no such property").valueAsNumber()).toEqual(4L);
    }

    @Test
    public void objectPutBoolean_shouldPutTheValueAtTheGivenPropertyInTheObject() throws Exception {
        expect(new JsonEditor("{\"a\": 0}").put("a", false).child("a").valueAsBoolean()).toBeFalse();
        expect(new JsonEditor("{\"a\": 0}").put("no such property", true).child("no such property").valueAsBoolean()).toBeTrue();
    }

    @Test
    public void objectPutDouble_shouldPutTheValueAtTheGivenPropertyInTheObject() throws Exception {
        expect(new JsonEditor("{\"a\": 0}").put("a", 9.55).child("a").valueAsNumber()).toEqual(9.55);
        expect(new JsonEditor("{\"a\": 0}").put("no such property", 999.55).child("no such property").valueAsNumber()).toEqual(999.55);
    }

    @Test
    public void objectPutString_shouldPutTheValueAtTheGivenPropertyInTheObject() throws Exception {
        expect(new JsonEditor("{\"a\": 0}").put("a", "new value").child("a").valueAsString()).toEqual("new value");
        expect(new JsonEditor("{\"a\": 0}").put("no such property", "String value").child("no such property").valueAsString()).toEqual("String value");
    }

    @Test
    public void objectPutJsonEditor_shouldPutTheValueAtTheGivenPropertyInTheObject_basedOnTheFocusedNodeOfTheEditor() throws Exception {
        JsonEditor editor = new JsonEditor("{\"a\": 0}");

        editor.put("a", new JsonEditor("[1, [2, 3]]").child(1));
        expect(editor.child("a").child(1).valueAsNumber()).toEqual(3);
        expect(editor.root().toJson()).toEqual("{\"a\":[2,3]}");

        editor = new JsonEditor("{\"a\": 0}");
        editor.put("no such property", new JsonEditor("[111, [2222, 3333]]").child(1));
        expect(editor.child("no such property").child(0).valueAsNumber()).toEqual(2222);
        expect(editor.root().toJson()).toEqual("{\"a\":0,\"no such property\":[2222,3333]}");

    }

    @Test
    public void objectPutJsonEditor_shouldNotCrash_whenCreatingAPotentialLoopInTheDom() throws Exception {
        JsonEditor editor = new JsonEditor("{\"a\": 0}");
        expect(editor.put("a", editor).toJson()).toEqual("{\"a\":{\"a\":0}}");
    }

    @Test
    public void arrayRemove_shouldRemoveTheSpecifiedIndexFromTheArray() throws Exception {
        JsonEditor editor = new JsonEditor("[0, 1, 2]");
        expect(editor.remove(1).toJson()).toEqual("[0,2]");
    }

    @Test(expected = ArrayIndexOutOfBoundsException.class)
    public void arrayRemove_shouldThrowException_whenIndexIsOutOfBounds() throws Exception {
        JsonEditor editor = new JsonEditor("[0, 1, 2]");
        expect(editor.remove(5).toJson()).toEqual("[0,2]");
    }

    @Test
    public void objectRemove_shouldRemoveTheSpecifiedPropertyFromTheObject() throws Exception {
        JsonEditor editor = new JsonEditor("{\"a\": 0, \"b\": 1}");
        expect(editor.remove("a").toJson()).toEqual("{\"b\":1}");
        expect(editor.remove("does not exist").toJson()).toEqual("{\"b\":1}");
    }

    @Test
    public void root_shouldReturnTheEditorBackToTheRootOfTheDomTree() throws Exception {
        String json = "[1, {\"a\": 2}]";
        expect(new JsonEditor(json).child(1).child("a").root().child(0).valueAsNumber()).toEqual(1);
    }

    @Test
    public void toJson_shouldConvertTheCurrentNodeOfTheDomToJson_whenThatNodeIsAnArrayOrObject() throws Exception {
        String json = "[1, {\"a\": 2}]";
        expect(new JsonEditor(json).child(1).child("a").root().toJson()).toEqual(json.replace(" ", ""));
        expect(new JsonEditor(json).child(1).toJson()).toEqual("{\"a\":2}");
    }

    @Test(expected = JsonEditor.NotAnArrayOrObjectNodeException.class)
    public void toJson_shouldThrowException_whenTheCurrentNodeIsNotAnArrayOrObject() throws Exception {
        new JsonEditor("[1, {\"a\": 2}]").child(1).child("a").toJson();
    }

    @Test
    public void arrayAppendInt_shouldAddAnElementToTheEndOfAnArray() {
        JsonEditor editor = new JsonEditor("{\"a\": [1, 2]}");
        expect(editor.child("a").append(42).root().toJson()).toEqual("{\"a\":[1,2,42]}");
    }

    @Test
    public void arrayAppendString_shouldAddAnElementToTheEndOfAnArray() {
        JsonEditor editor = new JsonEditor("{\"a\": [1, 2]}");
        expect(editor.child("a").append("foo").root().toJson()).toEqual("{\"a\":[1,2,\"foo\"]}");
    }

    @Test
    public void arrayAppendBoolean_shouldAddAnElementToTheEndOfAnArray() {
        JsonEditor editor = new JsonEditor("{\"a\": [1, 2]}");
        expect(editor.child("a").append(true).root().toJson()).toEqual("{\"a\":[1,2,true]}");
    }

    @Test
    public void arrayAppendDouble_shouldAddAnElementToTheEndOfAnArray() {
        JsonEditor editor = new JsonEditor("{\"a\": [1, 2]}");
        expect(editor.child("a").append(42.2).root().toJson()).toEqual("{\"a\":[1,2,42.2]}");
    }

    @Test
    public void arrayAppendLong_shouldAddAnElementToTheEndOfAnArray() {
        JsonEditor editor = new JsonEditor("{\"a\": [1, 2]}");
        expect(editor.child("a").append(42L).root().toJson()).toEqual("{\"a\":[1,2,42]}");
    }

    @Test
    public void arrayAppendJsonEditor_shouldAppendTheValueToTheEndOfTheArray_basedOnTheCurrentPositionOfTheEditor() throws Exception {
        JsonEditor editor = new JsonEditor("[1]");
        editor.append(new JsonEditor("[1, [2, 3]]").child(1)).root();
        expect(editor.toJson()).toEqual("[1,[2,3]]");
    }

    @Test
    public void arrayAppendJsonEditor_shouldAppendValueNodesToTheEndOfTheArray_basedOnTheCurrentPositionOfTheEditor() throws Exception {
        JsonEditor editor = new JsonEditor("[1]");
        editor.append(new JsonEditor("[2]").child(0)).root();
        expect(editor.toJson()).toEqual("[1,2]");
    }

    @Test
    public void arrayInsertJsonEditor_shouldInsertTheValueAtTheGivenIndexInTheArray_basedOnTheCurrentPositionOfTheEditor() throws Exception {
        JsonEditor editor = new JsonEditor("[1]");
        editor.insert(0, new JsonEditor("[1, [2, 3]]").child(1)).root();
        expect(editor.toJson()).toEqual("[[2,3],1]");
    }

    @Test
    public void arrayInsertString_shouldInsertAnElementIntoAnArray() {
        JsonEditor editor = new JsonEditor("{\"a\": [1, 2]}");
        expect(editor.child("a").insert(1, "foo").root().toJson()).toEqual("{\"a\":[1,\"foo\",2]}");
    }

    @Test
    public void arrayInsertBoolean_shouldInsertAnElementIntoAnArray() {
        JsonEditor editor = new JsonEditor("{\"a\": [1, 2]}");
        expect(editor.child("a").insert(1, true).root().toJson()).toEqual("{\"a\":[1,true,2]}");
    }

    @Test
    public void arrayInsertDouble_shouldInsertAnElementIntoAnArray() {
        JsonEditor editor = new JsonEditor("{\"a\": [1, 2]}");
        expect(editor.child("a").insert(1, 42.2).root().toJson()).toEqual("{\"a\":[1,42.2,2]}");
    }

    @Test
    public void arrayInsertLong_shouldInsertAnElementIntoAnArray() {
        JsonEditor editor = new JsonEditor("{\"a\": [1, 2]}");
        expect(editor.child("a").insert(1, 42L).root().toJson()).toEqual("{\"a\":[1,42,2]}");
    }

    @Test
    public void arrayInsertInt_shouldInsertAnElementIntoAnArray() {
        JsonEditor editor = new JsonEditor("{\"a\": [1, 3, 4]}");
        expect(editor.child("a").insert(1, 2).root().toJson()).toEqual("{\"a\":[1,2,3,4]}");
        expect(new JsonEditor("[]").insert(0, 44).root().toJson()).toEqual("[44]");
    }

    @Test(expected = ArrayIndexOutOfBoundsException.class)
    public void arrayInsertInt_withIndexTooLarge_shouldThrow() {
        new JsonEditor("[1, 2]").insert(2, 2);
    }

    @Test(expected = ArrayIndexOutOfBoundsException.class)
    public void arrayInsertInt_withIndexBelowZero_shouldThrow() {
        new JsonEditor("[1, 2]").insert(-1, 2);
    }

    @Test(expected = JsonEditor.NotAnArrayNodeException.class)
    public void arrayInsertInt_onAnObject_shouldThrow() {
        new JsonEditor("{}").insert(0, 2);
    }

    @Test
    public void arrayLength_shouldReturnTheLengthOfAnArray() {
        expect(new JsonEditor("[]").length()).toEqual(0);
        expect(new JsonEditor("{\"a\": [1, 2, 3, 4]}").child("a").length()).toEqual(4);
    }

    @Test(expected = JsonEditor.NotAnArrayNodeException.class)
    public void arrayLength_onAnObject_shouldThrow() {
        new JsonEditor("{}").length();
    }

    @Test
    public void isArray_shouldReturnTrueOnlyForArrays() {
        JsonEditor editor = new JsonEditor("{\"a\": [{}, 2]}");
        expect(editor.child("a").isArray()).toBeTrue();
        expect(editor.root().child("a").child(0).isArray()).toBeFalse();
        expect(editor.root().child("a").child(1).isArray()).toBeFalse();
    }

    @Test
    public void isObject_shouldReturnTrueOnlyForObjects() {
        JsonEditor editor = new JsonEditor("{\"a\": [{}, 2]}");
        expect(editor.isObject()).toBeTrue();
        expect(editor.child("a").isObject()).toBeFalse();
    }

    @Test(expected = JsonEditor.RootNodeHasNoParent.class)
    public void parent_whenUsedOnRootNode_shouldThrow() {
        new JsonEditor("[]").parent();
    }

    @Test(expected = JsonEditor.RootNodeHasNoParent.class)
    public void parent_whenUsedOnRootNodeAfterTraversingBackAndForth_shouldThrow() {
        String jsonString = "{\"a\":[1,{\"b\":42}],\"c\":[[44]]}";
        JsonEditor editor = new JsonEditor(jsonString);
        editor.root().child("c").child(0).child(0).root().child("a").parent().parent();
    }

    @Test
    public void parent_shouldNavigateBackToTheParentOfTheCurrentNode() {
        String jsonString = "{\"a\":[1,{\"b\":42}],\"c\":[[44]]}";
        JsonEditor editor = new JsonEditor(jsonString);
        expect(editor.child("a").parent().toJson()).toEqual(jsonString);
        expect(editor.root().child("a").child(0).parent().toJson()).toEqual("[1,{\"b\":42}]");
        expect(editor.root().child("a").child(1).child("b").parent().toJson()).toEqual("{\"b\":42}");
    }

    @Test
    public void removeAll_shouldClearObjectNodesAndArrayNodes() {
        expect(new JsonEditor("[]").removeAll().toJson()).toEqual("[]");
        expect(new JsonEditor("[1, 2]").removeAll().toJson()).toEqual("[]");
        expect(new JsonEditor("{}").removeAll().toJson()).toEqual("{}");
        expect(new JsonEditor("{\"a\": 1}").removeAll().toJson()).toEqual("{}");
    }

    @Test(expected = JsonEditor.NotAnArrayOrObjectNodeException.class)
    public void removeAll_whenUsedOnNonContainer_shouldThrow() {
        new JsonEditor("[42]").child(0).removeAll();
    }

    @Test(expected = JsonEditor.NotAnObjectNodeException.class)
    public void keySet_whenUsedOnNonObject_shouldThrow() {
        new JsonEditor("[42]").child(0).keySet();
    }

    @Test
    public void keySet_shouldReturnAllKeysAsASet() {
        expect(new JsonEditor("{\"c\":1, \"a\":2, \"b\":3}").keySet()).toContain("a", "b", "c");
        expect(new JsonEditor("{}").keySet()).toBeEmpty();
    }

    @Test
    public void toString_shouldShowPathToCurrentNode() {
        String jsonString = "{\"a\":[1,{\"b\":42}],\"c\":[[44]]}";
        JsonEditor editor = new JsonEditor(jsonString);
        expect(editor.toString()).toContain("focus=ROOT}");
        expect(editor.child("a").toString()).toContain("focus=ROOT['a']}");
        expect(editor.child(0).toString()).toContain("focus=ROOT['a'][0]}");
        expect(editor.parent().toString()).toContain("focus=ROOT['a']}");
        expect(editor.root().toString()).toContain("focus=ROOT}");
    }

}


text:
from django.apps import AppConfig
from django.db.models.signals import pre_save

def handle_soundcloud_malformed_widths_for_oembeds(sender, instance, **kwargs):
    """
    A signal receiver that prevents soundcloud from triggering ValueErrors
    when we save an OEmbedItem.
    Soundcloud returns "100%", instead of an integer for an OEmbed's width property.
    This is against the OEmbed spec, but actually makes sense in the context of
    responsive design. Unfortunately, the OEmbedItems can only store integers in
    the `width` field, so this becomes a 500 throwing issue.
    The issue is tracked https://github.com/edoburu/django-fluent-contents/issues/65
    """
    if instance.width == '100%':
        instance.width = -100

class AppConfig(AppConfig):
    name = 'fluent_contents.plugins.oembeditem'

    def ready(self):
        from fluent_contents.plugins.oembeditem.models import OEmbedItem
        pre_save.connect(handle_soundcloud_malformed_widths_for_oembeds, sender=OEmbedItem)


text:
#import "KAAMqttFrame.h"

/**
 *  DISCONNECT reason
 *  NONE                        0x00    No error
 *  BAD_REQUEST                 0x01    Client sent a corrupted data
 *  INTERNAL_ERROR              0x02    Internal error has been occurred
 */
typedef enum {
    DISCONNECT_REASON_NONE = 0x00,
    DISCONNECT_REASON_BAD_REQUEST = 0x01,
    DISCONNECT_REASON_INTERNAL_ERROR = 0x02
} DisconnectReason;

#define DISCONNECT_REMAINING_LEGTH_V1 2

/**
 * Disconnect message class.

 * The DISCONNECT message is sent from the client to the server to indicate that it is about to close
 * its TCP/IP connection. This provides a clean disconnection, rather than just dropping the line.

 * If the client had connected with the clean session flag set,
 * then all previously maintained information about the client will be discarded.

 * A server should not rely on the client to close the TCP/IP connection after receiving a DISCONNECT.
 */
@interface KAATcpDisconnect : KAAMqttFrame

@property (nonatomic) DisconnectReason reason;

- (instancetype)initWithDisconnectReason:(DisconnectReason)reason;

@end


text:
namespace UnityEngine.UI
{
    public interface IMaterialModifier
    {
        Material GetModifiedMaterial(Material baseMaterial);
    }
}


text:
import { SourceMapConsumer, MappedPosition, StartOfSourceMap } from './source-map-consumer';
import { SourceMapGenerator } from './source-map-generator';

export interface CodeWithSourceMap {
  code: string;
  map: SourceMapGenerator;
}

export class SourceNode {
  constructor();
  constructor(line: number, column: number, source: string);
  constructor(line: number, column: number, source: string, chunk?: string, name?: string);
  public static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode;
  public add(chunk: string): void;
  public prepend(chunk: string): void;
  public setSourceContent(sourceFile: string, sourceContent: string): void;
  public walk(fn: (chunk: string, mapping: MappedPosition) => void): void;
  public walkSourceContents(fn: (file: string, content: string) => void): void;
  public join(sep: string): SourceNode;
  public replaceRight(pattern: string, replacement: string): SourceNode;
  public toString(): string;
  public toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap;
}


text:
namespace SSCases
{
    public class Case
    {
        public Case(string pattern,
                    string sequence,
                    ExpectedResult result)
        {
            Pattern = pattern;
            Sequence = sequence;
            Result = result;
        }

        protected Case() { }

        public string Pattern { get; protected set; }

        public string Sequence { get; protected set; }

        public ExpectedResult Result { get; protected set; }

        public override string ToString()
        {
            return string.Format("{0}  :  {1}", Pattern, Sequence);
        }

        public class ExpectedResult
        {
            public static readonly ExpectedResult NotFound =
                               new NotFoundExpectedResult();

            public ExpectedResult(
                bool exists,
                int findFirst,
                int findLast,
                int[] findAll)
            {
                Exists = exists;
                FindFirst = findFirst;
                FindLast = findLast;
                FindAll = findAll;
            }

            public bool Exists { get; private set; }

            public int FindFirst { get; private set; }

            public int FindLast { get; private set; }

            public int[] FindAll { get; private set; }
        }

        private class NotFoundExpectedResult : ExpectedResult
        {
            public NotFoundExpectedResult()
                : base(false, -1, -1, new int[0]) { }
        }
    }
}


text:
package com.paritytrading.philadelphia.client;

import static java.nio.charset.StandardCharsets.*;
import static java.util.Collections.*;

import com.paritytrading.philadelphia.FIXConfig;
import com.paritytrading.philadelphia.FIXVersion;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigException;
import com.typesafe.config.ConfigFactory;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ClosedChannelException;
import java.nio.file.Files;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;
import java.util.stream.Stream;
import org.jline.reader.EndOfFileException;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.reader.UserInterruptException;
import org.jline.reader.impl.completer.ArgumentCompleter;
import org.jline.reader.impl.completer.NullCompleter;
import org.jline.reader.impl.completer.StringsCompleter;

class TerminalClient implements Closeable {

    static final Command[] COMMANDS = {
        new SendCommand(),
        new MessagesCommand(),
        new HelpCommand(),
        new ExitCommand(),
        new SleepCommand(),
        new WaitCommand(),
    };

    static final String[] COMMAND_NAMES = Stream.of(COMMANDS)
            .map(Command::getName)
            .toArray(String[]::new);

    private static final Locale LOCALE = Locale.US;

    private final Messages messages;

    private final Session session;

    private boolean closed;

    private TerminalClient(Messages messages, Session session) {
        this.messages = messages;
        this.session  = session;
    }

    static TerminalClient open(InetSocketAddress address, FIXConfig config) throws IOException {
        Messages messages = new Messages();

        Session session = Session.open(address, config, messages, messages);

        return new TerminalClient(messages, session);
    }

    Messages getMessages() {
        return messages;
    }

    Session getSession() {
        return session;
    }

    void run(List<String> lines) throws IOException {
        LineReader reader = LineReaderBuilder.builder()
            .completer(new ArgumentCompleter(
                        new StringsCompleter(COMMAND_NAMES),
                        new NullCompleter()))
            .build();

        if (lines.isEmpty())
            printf("Type 'help' for help.\n");

        for (String line : lines) {
            if (closed)
                break;

            printf("< %s\n", line);

            execute(line);
        }

        while (!closed) {
            String line = reader.readLine("> ");
            if (line == null)
                break;

            execute(line);
        }

        close();
    }

    private void execute(String line) throws IOException {
        if (line.trim().startsWith("#"))
            return;

        Scanner scanner = scan(line);

        if (!scanner.hasNext())
            return;

        Command command = findCommand(scanner.next());
        if (command == null) {
            printf("error: Unknown command\n");
            return;
        }

        try {
            command.execute(this, scanner);
        } catch (IllegalArgumentException e) {
            printf("Usage: %s\n", command.getUsage());
        } catch (ClosedChannelException e) {
            printf("error: Connection closed\n");
        }
    }

    @Override
    public void close() {
        session.close();

        closed = true;
    }

    static Command findCommand(String name) {
        for (Command command : COMMANDS) {
            if (name.equals(command.getName()))
                return command;
        }

        return null;
    }

    static void printf(String format, Object... args) {
        System.out.printf(LOCALE, format, args);
    }

    private Scanner scan(String text) {
        Scanner scanner = new Scanner(text);
        scanner.useLocale(LOCALE);

        return scanner;
    }

    public static void main(String[] args) {
        if (args.length != 1 && args.length != 2)
            usage();

        try {
            Config config = config(args[0]);

            List<String> lines = emptyList();

            if (args.length == 2)
                lines = readAllLines(args[1]);

            main(config, lines);
        } catch (EndOfFileException | UserInterruptException e) {
            // Ignore.
        } catch (ConfigException | FileNotFoundException e) {
            error(e);
        } catch (IOException e) {
            fatal(e);
        }
    }

    private static void main(Config config, List<String> lines) throws IOException {
        String version      = config.getString("fix.version");
        String senderCompId = config.getString("fix.sender-comp-id");
        String targetCompId = config.getString("fix.target-comp-id");
        int    heartBtInt   = config.getInt("fix.heart-bt-int");
        String address      = config.getString("fix.address");
        int    port         = config.getInt("fix.port");

        FIXConfig.Builder builder = FIXConfig.newBuilder()
            .setVersion(FIXVersion.valueOf(version))
            .setSenderCompID(senderCompId)
            .setTargetCompID(targetCompId)
            .setHeartBtInt(heartBtInt)
            .setMaxFieldCount(1024)
            .setFieldCapacity(1024)
            .setRxBufferCapacity(1024 * 1024)
            .setTxBufferCapacity(1024 * 1024);

        TerminalClient.open(new InetSocketAddress(address, port), builder.build()).run(lines);
    }

    private static List<String> readAllLines(String filename) throws IOException {
        return Files.readAllLines(new File(filename).toPath(), UTF_8);
    }

    private static Config config(String filename) throws FileNotFoundException {
        File file = new File(filename);
        if (!file.exists() || !file.isFile())
            throw new FileNotFoundException(filename + ": No such file");

        return ConfigFactory.parseFile(file);
    }

    private static void usage() {
        System.err.println("Usage: philadelphia-client <configuration-file> [<input-file>]");
        System.exit(2);
    }

    private static void error(Throwable throwable) {
        System.err.println("error: " + throwable.getMessage());
        System.exit(1);
    }

    private static void fatal(Throwable throwable) {
        System.err.println("fatal: " + throwable.getMessage());
        System.err.println();
        throwable.printStackTrace(System.err);
        System.err.println();
        System.exit(1);
    }

}


text:
<?php namespace net\xp_framework\unittest\core\generics;

/**
 * Generic array filter
 *
 * ```php
 * // Set up filter as anonymous class
 * $webmethods= create('new ArrayFilter<Method>', [], '{
 *   protected function accept($method) {
 *     return $method->hasAnnotation("webmethod");
 *   }
 * }');
 *
 * // Iterate over filtered array
 * foreach ($webmethods->filter($class->getMethods()) as $method) {
 *   Console::writeLine("Webmethod: ", $method);
 * }
 * ```
 */
#[@generic(self= 'T')]
abstract class ArrayFilter {

  /**
   * Accept method - called for each element in the specified list.
   * Return TRUE if the passed element should be included in the
   * filtered list, FALSE otherwise
   *
   * @param   T element
   * @return  bool
   */
  #[@generic(params= 'T')]
  protected abstract function accept($element);

  /**
   * Filter a list of elements
   *
   * @param   T[] elements
   * @return  T[] filtered
   */
  #[@generic(params= 'T[]', return= 'T[]')]
  public function filter($elements) {
    $filtered= [];
    foreach ($elements as $element) {
      if ($this->accept($element)) $filtered[]= $element;
    }
    return $filtered;
  }
}


text:
export interface Auction
{
  id: string;
  title: string;
  bid: number;
  state: string;
}

export interface AuctionListener
{
  onNew(auction:Auction);

  onUpdate(auctions:Auction[]);
}


text:
PixiJS v4 filter to render DisplayObject as an LED display.

Demo: See https://marekventur.github.io/pixi-filters/examples

## Installation

```bash
npm install pixi-filter-led
```

## Usage

```js
import {LedFilter} from 'pixi-filter-led';

const container = new PIXI.Container();
container.filters = [new LedFilter({size: 10})];
```

## Documentation

See https://marekventur.github.io/pixi-filters/docs


text:
module RailsMetadata
  VERSION = "0.0.8"
end


text:
class CreateWishes < ActiveRecord::Migration
  def change
    create_table :wishes do |t|
      t.string :meal, null: false
      t.string :temporality, null: false
      t.belongs_to :creator, null: false
      t.timestamps null: false
    end
  end
end


text:
<?php

namespace ZfrCors;

use Zend\EventManager\EventInterface;
use Zend\ModuleManager\Feature\BootstrapListenerInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;

/**
 * @licence MIT
 * @author  Florent Blaison <florent.blaison@gmail.com>
 */
class Module implements BootstrapListenerInterface, ConfigProviderInterface
{

    /**
     * {@inheritDoc}
     */
    public function onBootstrap(EventInterface $event)
    {
        /* @var $application \Zend\Mvc\Application */
        $application     = $event->getTarget();
        $serviceManager  = $application->getServiceManager();
        $eventManager    = $application->getEventManager();

        $eventManager->attach($serviceManager->get('ZfrCors\Mvc\CorsRequestListener'));
    }

    /**
     * {@inheritDoc}
     */
    public function getConfig()
    {
        return include __DIR__ . '/../../config/module.config.php';
    }
}


text:
using System;
using System.Xml.Linq;

namespace vm.Aspects.Linq.Expressions.Serialization
{
    /// <summary>
    /// Represents the serialization behavior for various types of objects.
    /// </summary>
    public interface IConstantXmlSerializer
    {
        /// <summary>
        /// Serializes the specified constant.
        /// </summary>
        /// <param name="constant">The constant to be serialized.</param>
        /// <param name="type">The type of the constant (if needed).</param>
        /// <returns>The XElement generated by the serializer representing the type and the value of the <paramref name="constant"/>.</returns>
        XElement Serialize(object constant, Type type);

        /// <summary>
        /// Deserializes an object from the specified XML element.
        /// </summary>
        /// <param name="element">The XML element to deserialize from.</param>
        /// <param name="type">The type of the constant (if needed).</param>
        /// <returns>The deserialized object.</returns>
        object Deserialize(XElement element, Type type);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<PRONOM-Report xmlns="http://pronom.nationalarchives.gov.uk">
  <report_format_detail>
    <FileFormat>
      <FormatID>1735</FormatID>
      <FormatName>Magick Image File Format</FormatName>
      <FormatVersion>
      </FormatVersion>
      <FormatAliases>
      </FormatAliases>
      <FormatFamilies>
      </FormatFamilies>
      <FormatTypes>Image (Raster)</FormatTypes>
      <FormatDisclosure>
      </FormatDisclosure>
      <FormatDescription>The Magick Image File Format (MIFF) is ImageMagick's own format for storing bitmap images. It stores all metadata known to ImageMagick.</FormatDescription>
      <BinaryFileFormat>
      </BinaryFileFormat>
      <ByteOrders>
      </ByteOrders>
      <ReleaseDate>
      </ReleaseDate>
      <WithdrawnDate>
      </WithdrawnDate>
      <ProvenanceSourceID>1</ProvenanceSourceID>
      <ProvenanceName>Digital Preservation Department / The National Archives</ProvenanceName>
      <ProvenanceSourceDate>08 Jul 2016</ProvenanceSourceDate>
      <ProvenanceDescription>
      </ProvenanceDescription>
      <LastUpdatedDate>08 Jul 2016</LastUpdatedDate>
      <FormatNote>
      </FormatNote>
      <FormatRisk>
      </FormatRisk>
      <TechnicalEnvironment>
      </TechnicalEnvironment>
      <FileFormatIdentifier>
        <Identifier>fmt/930</Identifier>
        <IdentifierType>PUID</IdentifierType>
      </FileFormatIdentifier>
      <ExternalSignature>
        <ExternalSignatureID>1885</ExternalSignatureID>
        <Signature>mif</Signature>
        <SignatureType>File extension</SignatureType>
      </ExternalSignature>
      <InternalSignature>
        <SignatureID>1274</SignatureID>
        <SignatureName>Magick Image File Format</SignatureName>
        <SignatureNote>BOF max offset 256: id=ImageMagick[new line]{0-256}:[new line]
Specification: http://www.imagemagick.org/script/miff.php</SignatureNote>
        <ByteSequence>
          <ByteSequenceID>1546</ByteSequenceID>
          <PositionType>Absolute from BOF</PositionType>
          <Offset>0</Offset>
          <MaxOffset>256</MaxOffset>
          <IndirectOffsetLocation>
          </IndirectOffsetLocation>
          <IndirectOffsetLength>
          </IndirectOffsetLength>
          <Endianness>
          </Endianness>
          <ByteSequenceValue>69643D496D6167654D616769636B{0-256}3A0A</ByteSequenceValue>
        </ByteSequence>
      </InternalSignature>
    </FileFormat>
    <SearchCriteria>Criteria</SearchCriteria>
  </report_format_detail>
</PRONOM-Report>


text:
<?php

	$username = $_POST['userName'];
	$classname = $_POST['className'];
	$comment = $_POST['comment'];

	$total = $username.",".$classname.",".$comment.";";
	$fp = fopen('comments.txt', 'a+');
	fwrite($fp, $total);
	fclose ($fp);

	header('Location: /pages/comments.html');


text:
  {% if include.image.url %}
    {% assign path = include.image.url | slice:0,1 %}

  {% endif %}

  {% if include.image.url %}{% endif %}


text:
"""
Accept or discard sequences XXX, based on the given counting
hash table.  Output sequences will be placed in 'infile.medpctfilt'.

% python sandbox/filter-median-and-pct.py <counting.ct> <data1> [ <data2> <...> ]

Use '-h' for parameter help.
"""
import sys
import screed.fasta
import os
import khmer
from khmer.thread_utils import ThreadedSequenceProcessor, verbose_loader

from khmer.khmer_args import build_counting_args

import random

###

DEFAULT_COVERAGE = 20

def main():
    parser = build_counting_multifile_args()
    parser.add_argument('--coverage', '-C', dest='coverage',
                        default=DEFAULT_COVERAGE, type=int)
    args = parser.parse_args()

    counting_ht = args.input_table
    infiles = args.input_filenames

    print('file with ht: %s' % counting_ht)

    print('loading hashtable')
    ht = khmer.load_countgraph(counting_ht)
    K = ht.ksize()

    xxxfp = None

    print("K:", K)

    # the filtering function.
    def process_fn(record):
        name = record['name']
        seq = record['sequence']

        med, avg, dev = ht.get_median_count(seq)
        pct = dev / avg * 100

        xxxfp.write('%s %s %s %s %s\n' % (med, avg, dev, pct, name))

        if random.randint(1, med) > args.coverage or pct > 100:
            return None, None

        return name, seq

    # the filtering loop
    for infile in infiles:
        print('filtering', infile)
        xxxfp = open(os.path.basename(infile) + '.medpctfilt.stats', 'w')
        outfile = os.path.basename(infile) + '.medpctfilt'
        outfp = open(outfile, 'w')

        for n, record in enumerate(screed.open(infile)):
            if n % 100000 == 0:
                print('...', n)

            name, seq = process_fn(record)
            if name and seq:
                print('>%s\n%s' % (name, seq), file=outfp)

        print('output in', outfile)

if __name__ == '__main__':
    main()


text:
package rescala.fullmv

import rescala.compat.SignalCompatBundle
import rescala.core.Core
import rescala.fullmv.mirrors.localcloning.{FullMVTurnLocalCloneBundle, ReactiveLocalCloneBundle}
import rescala.fullmv.mirrors.{FullMVTurnReflectionBundle, Mirror, ReactiveMirrorBundle, ReactiveReflectionBundle}
import rescala.fullmv.sgt.synchronization.SubsumableLockBundle
import rescala.fullmv.tasks.TaskBundle
import rescala.fullmv.transmitter.ReactiveTransmittableBundle
import rescala.interface.RescalaInterface
import rescala.operator.{DefaultImplementations, EventBundle, Observing, SignalBundle, Sources}

import scala.concurrent.duration.Duration
import scala.util.DynamicVariable

object DistributedFullMVApi extends FullMVBundle with FullMVTurnLocalCloneBundle with Mirror with TurnImplBundle
    with TaskBundle with FullMvStateBundle with SubsumableLockBundle with FullMVTurnReflectionBundle
    with ReactiveLocalCloneBundle with RescalaInterface with SignalCompatBundle with EventBundle with SignalBundle
    with Sources with DefaultImplementations with Observing with Core
    with ReactiveReflectionBundle with ReactiveMirrorBundle with ReactiveTransmittableBundle {

  val scopedScheduler: DynamicVariable[FullMVEngine] = new DynamicVariable(new FullMVEngine(
    Duration.Inf,
    "I dedicate this scheduler to Manuel and Edlira, may they rest independent classes."
  ))

  override def scheduler: FullMVEngine = scopedScheduler.value
}


text:
playground for [square/flow](https://github.com/square/flow)

![](http://i.gyazo.com/48cbef0b6ca5790b2d9851543acc9f54.gif)

## SEE ALSO

- [square/flow](https://github.com/square/flow)
- [flow/flow-sample](https://github.com/square/flow/tree/master/flow-sample)
- [alexfu/flow-sample - An overly simplistic use case for Flow](https://github.com/alexfu/flow-sample)
- [Advocating Against Android Fragments](http://corner.squareup.com/2014/10/advocating-against-android-fragments.html)
- [【翻訳】Android Fragmentへの反対声明 - ninjinkun's diary](http://ninjinkun.hatenablog.com/entry/2014/10/16/234611)


text:
NearbyShareOnDemandScheduler::NearbyShareOnDemandScheduler(
    bool retry_failures,
    bool require_connectivity,
    const std::string& pref_name,
    PrefService* pref_service,
    OnRequestCallback callback,
    const base::Clock* clock)
    : NearbyShareSchedulerBase(retry_failures,
                               require_connectivity,
                               pref_name,
                               pref_service,
                               std::move(callback),
                               clock) {}

NearbyShareOnDemandScheduler::~NearbyShareOnDemandScheduler() = default;

absl::optional<base::TimeDelta>
NearbyShareOnDemandScheduler::TimeUntilRecurringRequest(base::Time now) const {
  return absl::nullopt;
}


text:
<?php

/* FOSUserBundle:Security:login.html.twig */
class __TwigTemplate_3d289318992a7da69cb7d2f1064c5afc231d2b7d5916f0cf7f3e0bec2711c6bb extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("FOSUserBundle::layout.html.twig");

        $this->blocks = array(
            'fos_user_content' => array($this, 'block_fos_user_content'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "FOSUserBundle::layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_fos_user_content($context, array $blocks = array())
    {
        // line 4
        echo "

        ";
        // line 6
        if ($this->getContext($context, "error")) {
            // line 7
            echo "
";
            echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans($this->getContext($context, "error"), array(), "FOSUserBundle"), "html", null, true);
            echo "

        ";
        }
        // line 9
        echo "        <form form-horizontal action=\"";
        echo $this->env->getExtension('routing')->getPath("fos_user_security_check");
        echo "\" method=\"post\">

                ";
        // line 11
        echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("security.login.username", array(), "FOSUserBundle"), "html", null, true);
        echo "
                <input type=\"text\" name=\"_username\" required=\"required\" type=\"email\" class=\"form-control\" id=\"InputEmail1\" placeholder=\"Email\" />

                ";
        // line 16
        echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("security.login.password", array(), "FOSUserBundle"), "html", null, true);
        echo "
                <input type=\"password\" name=\"_password\" class=\"form-control\" id=\"InputPassword1\" placeholder=\"********\" required=\"required\" />

                <input type=\"checkbox\" id=\"remember_me\" name=\"_remember_me\" value=\"on\" />
                ";
        // line 22
        echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("security.login.remember_me", array(), "FOSUserBundle"), "html", null, true);
        echo "

            <input type=\"hidden\" name=\"_csrf_token\" value=\"";
        // line 25
        echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "fos_csrf_provider"), "generateCsrfToken", array(0 => "authenticate"), "method"), "html", null, true);
        echo "\" />

            <input type=\"submit\" id=\"_submit\" name=\"_submit\" value=\"";
        // line 28
        echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("security.login.submit", array(), "FOSUserBundle"), "html", null, true);
        echo "\" class=\"btn btn-primary\">
        </form>

";
    }

    public function getTemplateName()
    {
        return "FOSUserBundle:Security:login.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  78 => 28,  72 => 25,  66 => 22,  57 => 16,  49 => 11,  43 => 9,  37 => 7,  35 => 6,  31 => 4,  28 => 3,);
    }
}


text:
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using System.Net;
using System;

namespace MonoCross.Utilities.Network
{
    /// <summary>
    /// Provides methods for handling HTTP web responses.
    /// </summary>
    public static class NetworkUtils
    {
        /// <summary>
        /// Converts the specified object into a serialized XML string.
        /// </summary>
        /// <param name="obj">The object to serialize.</param>
        /// <returns>The byte array from the object.</returns>
        public static byte[] XmlSerializeObjectToBytes(object obj)
        {
            byte[] byteData = null;

            MemoryStream stream = new MemoryStream();

            XmlSerializer ser = new XmlSerializer(obj.GetType());
            XmlWriter writer = null;
            try
            {
                writer = XmlWriter.Create(stream, new XmlWriterSettings()
                {
                    Encoding = Encoding.UTF8
                });

                ser.Serialize(stream, obj);
                byteData = stream.ToArray();

                //Encoding enc = Encoding.GetEncoding( "utf-8" );
                //string a = enc.GetString( byteData, 0, byteData.Length );

            }
            finally
            {
                if (writer != null)
                    ((IDisposable)writer).Dispose();
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
            }

            return byteData;
        }

        /// <summary>
        /// Converts the specified string into a byte array using UTF8 encoding.
        /// </summary>
        /// <param name="str">The string to convert to a byte array.</param>
        /// <returns>The byte array from the string.</returns>
        public static byte[] StrToByteArray(string str)
        {
            if (str == null)
                return null;

            UTF8Encoding encoding = new UTF8Encoding();
            return encoding.GetBytes(str);
        }

        /// <summary>
        /// Converts the specified byte array into a string using UTF8 encoding.  If the conversion fails, null is returned.
        /// </summary>
        /// <param name="byteData">The byte array to convert to a string.</param>
        /// <returns>The string from the byte array, or null if the conversion fails.</returns>
        public static string ByteArrayToStr(byte[] byteData)
        {
            if (byteData == null)
                return null;

            try
            {
                Encoding enc = Encoding.GetEncoding("utf-8");
                return enc.GetString(byteData, 0, byteData.Length);
            }
            catch
            {
                // swallow exception if cannot convert to UTF8 string.
            }

            return null;
        }

        /// <summary>
        /// Reads data from the specified stream until the end is reached and returns the data as a byte array.
        /// An IOException is thrown if any of the underlying IO calls fail.
        /// </summary>
        /// <param name="stream">The stream to read data from.</param>
        public static byte[] StreamToByteArray(Stream stream)
        {
            byte[] buffer = new byte[32768];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                try
                {
                    while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                        ms.Write(buffer, 0, read);
                    return ms.ToArray();
                }
                finally
                {
                    if (ms != null)
                    {
                        ms.Close();
                        ms.Dispose();
                    }
                }
            }
        }

        /// <summary>
        /// Returns a <see cref="WebResponse"/> object from the specified <see cref="HttpWebResponse"/>.
        /// </summary>
        /// <param name="response">The <see cref="HttpWebResponse"/> from which to create the <see cref="WebResponse"/>.</param>
        /// <returns></returns>
        public static WebResponse ExtractResponse(HttpWebResponse response)
        {
            return ExtractResponse(response, null);
        }

        /// <summary>
        /// Returns a <see cref="WebResponse"/> object from the specified <see cref="HttpWebResponse"/> and optionally saves the response bytes to a file.
        /// </summary>
        /// <param name="response">The <see cref="HttpWebResponse"/> from which to create the <see cref="WebResponse"/>.</param>
        /// <param name="filename">The name of the file to save the response bytes to, or null if saving is not desired.</param>
        /// <returns></returns>
        public static WebResponse ExtractResponse(HttpWebResponse response, string filename)
        {
            WebResponse webResponse = null;
            Stream streamResponse = response.GetResponseStream();

            StreamReader streamRead = null;
            try
            {
                webResponse = new WebResponse();
                webResponse.ResponseBytes = StreamToByteArray(streamResponse);
                webResponse.ResponseString = ByteArrayToStr(webResponse.ResponseBytes);
                webResponse.ResponseHeaders = response.Headers;

                if (!string.IsNullOrEmpty(filename))
                    Device.File.Save(filename, webResponse.ResponseBytes);
            }
            finally
            {
                // Close the stream object
                if (streamResponse != null)
                    streamResponse.Dispose();
                if (streamRead != null)
                    streamRead.Dispose();
            }

            return webResponse;
        }
    }

    /// <summary>
    /// Represents a network response from a web server.
    /// </summary>
    public class WebResponse
    {
        /// <summary>
        /// Gets or sets the body of the response from the server as an array of <see cref="System.Byte"/>s.
        /// </summary>
        public byte[] ResponseBytes
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the body of the response from the server as a <see cref="System.String"/>.
        /// </summary>
        public string ResponseString
        {
            get;
            set;
        }

        /// <summary>
        /// Gets the headers contained in the server's response.
        /// </summary>
        /// <value>The response headers.</value>
        public WebHeaderCollection ResponseHeaders
        {
            get;
            internal set;
        }
    }
}


text:
@interface ParcelOperationCell ()

@property (weak, nonatomic) IBOutlet UILabel *postOfficeNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *postOfficeIndexLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UILabel *eventDescriptionLabel;

@end

@implementation ParcelOperationCell

- (void)setParcelOperation:(UPParcelTrackerOperation *)parcelOperation
{
    _parcelOperation = parcelOperation;
    [self updateUI];
}

- (void)updateUI
{
    self.postOfficeNameLabel.text = self.parcelOperation.postOfficeName;
    self.postOfficeIndexLabel.text = self.parcelOperation.postOfficeIndex;
    self.eventDescriptionLabel.text = self.parcelOperation.operationDescription;

    NSDateFormatter *numberFormatter = [NSDateFormatter new];
    numberFormatter.dateFormat = @"hh:mm";
    self.timeLabel.text = [numberFormatter stringFromDate:self.parcelOperation.date];
}

@end


text:
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Xunit;

namespace Meziantou.Extensions.Logging.InMemory.Tests;

public sealed partial class InMemoryLoggerTests
{
    private static readonly Action<ILogger, int, Exception> SampleMessage = LoggerMessage.Define<int>(LogLevel.Information, new EventId(1, "Sample Event Id"), "Test {Number}");

    [Fact]
    public void WithoutScope()
    {
        var logger = new InMemoryLogger("my_category");
#pragma warning disable CA1848 // Use the LoggerMessage delegates
        logger.LogInformation("Test");
#pragma warning restore CA1848

        var log = logger.Logs.Informations.Single();
        log.Message.Should().Be("Test");
        log.State.Should().BeEquivalentTo(new[] { KeyValuePair.Create<string, object>("{OriginalFormat}", "Test") });
        log.Scopes.Should().BeEquivalentTo(Array.Empty<object>());

        log.ToString().Should().Be("[my_category] Information: Test\n  => [{\"Key\":\"{OriginalFormat}\",\"Value\":\"Test\"}]");
    }

    [Fact]
    public void WithScope()
    {
        var logger = new InMemoryLogger("my_category");
        using (logger.BeginScope(new { Name = "test" }))
        using (logger.BeginScope(new { Age = 52, Name = "John" }))
        {
#pragma warning disable CA1848 // Use the LoggerMessage delegates
            logger.LogInformation("Test {Number}", 1);
#pragma warning restore CA1848
        }

        var log = logger.Logs.Informations.Single();
        log.Message.Should().Be("Test 1");
        log.State.Should().BeEquivalentTo(new[] { KeyValuePair.Create<string, object>("Number", 1), KeyValuePair.Create<string, object>("{OriginalFormat}", "Test {Number}") });
        log.Scopes.Should().BeEquivalentTo(new object[] { new { Age = 52, Name = "John" }, new { Name = "test" } });

        log.ToString().Should().Be("[my_category] Information: Test 1\n  => [{\"Key\":\"Number\",\"Value\":1},{\"Key\":\"{OriginalFormat}\",\"Value\":\"Test {Number}\"}]\n  => {\"Name\":\"test\"}\n  => {\"Age\":52,\"Name\":\"John\"}");
    }

    [Fact]
    public void WithScope_LoggerMessage()
    {
        var logger = new InMemoryLogger("my_category");
        using (logger.BeginScope(new { Name = "test" }))
        using (logger.BeginScope(new { Age = 52, Name = "John" }))
        {
            SampleMessage(logger, 1, null);
        }

        var log = logger.Logs.Informations.Single();
        log.Message.Should().Be("Test 1");
        log.State.Should().BeEquivalentTo(new[] { KeyValuePair.Create<string, object>("Number", 1), KeyValuePair.Create<string, object>("{OriginalFormat}", "Test {Number}") });
        log.Scopes.Should().BeEquivalentTo(new object[] { new { Age = 52, Name = "John" }, new { Name = "test" } });

        log.ToString().Should().Be("[my_category] Information (1 Sample Event Id): Test 1\n  => [{\"Key\":\"Number\",\"Value\":1},{\"Key\":\"{OriginalFormat}\",\"Value\":\"Test {Number}\"}]\n  => {\"Name\":\"test\"}\n  => {\"Age\":52,\"Name\":\"John\"}");
    }

    [LoggerMessage(Level = LogLevel.Information, Message = "Value is {value}")]
    private static partial void Log(ILogger logger, int value);

    [Fact]
    public void LogManyMessages()
    {
        var logger = new InMemoryLogger("my_category");
        Parallel.For(0, 100_000, i => Log(logger, 1));

        logger.Logs.Should().HaveCount(100_000);
    }
}


text:
.modal-content{border-radius:2px;}
.modal-header {border-bottom: 1px solid rgba(0, 0, 0, 0);border-top-left-radius: 3px;border-top-right-radius: 3px;margin-bottom: 16px;padding: 16px 16px 0;}
.modal-header.pmd-modal-bordered{border-bottom:1px solid #e5e5e5;padding-bottom:16px;}
.modal-header h2.pmd-card-title-text{font-weight:500;}
.pmd-modal-list{ margin-bottom:16px; margin-top:16px;}
.modal-body{color: rgba(0, 0, 0, 0.84);margin-bottom:16px;margin-top:16px;padding:0 16px;}
.modal-body .list-group-item{}
.modal-body > p:last-child{margin-bottom:0;}
.modal-footer{padding:16px;}
.pmd-modal-action{padding:8px 4px;}
.pmd-modal-action .btn.pmd-btn-fab {padding: 0;}
.pmd-modal-action.pmd-modal-bordered {border-top:1px solid #e5e5e5;}
.pmd-modal-action .btn {min-width: inherit;padding: 10px 8px;margin-bottom: 8px;margin-left: 4px;margin-right: 4px;margin-top:8px;}
.pmd-modal-action .btn:first-child {margin-left: 12px;}
.pmd-modal-action .btn.pmd-btn-flat:first-child{margin-left: 4px;}
.pmd-modal-action .pmd-btn-flat{margin:0 4px 0 0;}
.modal .radio, .modal .checkbox{margin:16px 0;}
.modal .radio-options > label{padding-left:32px;}
.modal .list-group.pmd-list-avatar{margin:8px 4px;padding:0}
.modal .list-group:last-child{margin-bottom:0;}

/* Form css */
.form-horizontal .form-group{ margin-left:0; margin-right:0;}


text:
'use strict';

const fs = jest.genMockFromModule('fs');

const mockFiles = new Map();
function __setMockFiles(newMockFiles) {
  mockFiles.clear();
  Object.keys(newMockFiles).forEach(fileName => {
    mockFiles.set(fileName, newMockFiles[fileName]);
  });
}

fs.__setMockFiles = __setMockFiles;
fs.readFileSync = jest.fn(file => mockFiles.get(file));

module.exports = fs;


text:
def load_json_file(path)
  File.open(path,'rb') do |file|
    return JSON.load(file)
  end
end