text:
After you have downloaded the Hyperledger Fabric Docker images and samples, you
can deploy a test network by using scripts that are provided in the
`fabric-samples` repository. The test network is provided for learning about Fabric
by running nodes on your local machine. Developers can use the
network to test their smart contracts and applications. The network is meant to
be used only as a tool for education and testing and not as a model for how to set up
a network. In general, modifications to the scripts are discouraged and could break the network. It is based on a limited configuration that should not be used as a template for deploying a production network:
- It includes two peer organizations and an ordering organization.
- For simplicity, a single node Raft ordering service is configured.
- To reduce complexity, a TLS Certificate Authority (CA) is not deployed. All certificates are issued by the root CAs.
- The sample network deploys a Fabric network with Docker Compose. Because the
nodes are isolated within a Docker Compose network, the test network is not configured to connect to other running Fabric nodes.

To learn how to use Fabric in production, see [Deploying a production network](deployment_guide_overview.html).

**Note:** These instructions have been verified to work against the
latest stable Fabric Docker images and the pre-compiled setup utilities within the
supplied tar file. If you run these commands with images or tools from the
current main branch, it is possible that you will encounter errors.

## Before you begin

Before you can run the test network, you need to install Fabric Samples in your
environment. Follow the instructions on [getting_started](getting_started.html)
to install the required software.

**Note:** The test network has been successfully verified with Docker Desktop version 2.5.0.1 and is the recommended version at this time. Higher versions may not work.

## Bring up the test network

You can find the scripts to bring up the network in the `test-network` directory
of the ``fabric-samples`` repository. Navigate to the test network directory by
using the following command:
```
cd fabric-samples/test-network
```

In this directory, you can find an annotated script, ``network.sh``, that stands
up a Fabric network using the Docker images on your local machine. You can run
``./network.sh -h`` to print the script help text:

```
Usage:
  network.sh <Mode> [Flags]
    Modes:
      up - Bring up Fabric orderer and peer nodes. No channel is created
      up createChannel - Bring up fabric network with one channel
      createChannel - Create and join a channel after the network is created
      deployCC - Deploy a chaincode to a channel (defaults to asset-transfer-basic)
      down - Bring down the network

    Flags:
    Used with network.sh up, network.sh createChannel:
    -ca <use CAs> -  Use Certificate Authorities to generate network crypto material
    -c <channel name> - Name of channel to create (defaults to "mychannel")
    -s <dbtype> - Peer state database to deploy: goleveldb (default) or couchdb
    -r <max retry> - CLI times out after certain number of attempts (defaults to 5)
    -d <delay> - CLI delays for a certain number of seconds (defaults to 3)
    -i <imagetag> - Docker image tag of Fabric to deploy (defaults to "latest")
    -cai <ca_imagetag> - Docker image tag of Fabric CA to deploy (defaults to "latest")
    -verbose - Verbose mode

    Used with network.sh deployCC
    -c <channel name> - Name of channel to deploy chaincode to
    -ccn <name> - Chaincode name.
    -ccl <language> - Programming language of the chaincode to deploy: go (default), java, javascript, typescript
    -ccv <version>  - Chaincode version. 1.0 (default), v2, version3.x, etc
    -ccs <sequence>  - Chaincode definition sequence. Must be an integer, 1 (default), 2, 3, etc
    -ccp <path>  - File path to the chaincode.
    -ccep <policy>  - (Optional) Chaincode endorsement policy using signature policy syntax. The default policy requires an endorsement from Org1 and Org2
    -cccg <collection-config>  - (Optional) File path to private data collections configuration file
    -cci <fcn name>  - (Optional) Name of chaincode initialization function. When a function is provided, the execution of init will be requested and the function will be invoked.

    -h - Print this message

 Possible Mode and flag combinations
   up -ca -r -d -s -i -cai -verbose
   up createChannel -ca -c -r -d -s -i -cai -verbose
   createChannel -c -r -d -verbose
   deployCC -ccn -ccl -ccv -ccs -ccp -cci -r -d -verbose

 Examples:
   network.sh up createChannel -ca -c mychannel -s couchdb -i 2.0.0
   network.sh createChannel -c channelName
   network.sh deployCC -ccn basic -ccp ../asset-transfer-basic/chaincode-javascript/ -ccl javascript
   network.sh deployCC -ccn mychaincode -ccp ./user/mychaincode -ccv 1 -ccl javascript
```

From inside the `test-network` directory, run the following command to remove
any containers or artifacts from any previous runs:
```
./network.sh down
```

You can then bring up the network by issuing the following command. You will
experience problems if you try to run the script from another directory:
```
./network.sh up
```

This command creates a Fabric network that consists of two peer nodes, one
ordering node. No channel is created when you run `./network.sh up`, though we
will get there in a [future step](#creating-a-channel). If the command completes
successfully, you will see the logs of the nodes being created:
```
Creating network "fabric_test" with the default driver
Creating volume "net_orderer.example.com" with default driver
Creating volume "net_peer0.org1.example.com" with default driver
Creating volume "net_peer0.org2.example.com" with default driver
Creating peer0.org2.example.com ... done
Creating orderer.example.com    ... done
Creating peer0.org1.example.com ... done
Creating cli                    ... done
CONTAINER ID   IMAGE                               COMMAND             CREATED         STATUS                  PORTS                                            NAMES
1667543b5634   hyperledger/fabric-tools:latest     "/bin/bash"         1 second ago    Up Less than a second                                                    cli
b6b117c81c7f   hyperledger/fabric-peer:latest      "peer node start"   2 seconds ago   Up 1 second             0.0.0.0:7051->7051/tcp                           peer0.org1.example.com
703ead770e05   hyperledger/fabric-orderer:latest   "orderer"           2 seconds ago   Up Less than a second   0.0.0.0:7050->7050/tcp, 0.0.0.0:7053->7053/tcp   orderer.example.com
718d43f5f312   hyperledger/fabric-peer:latest      "peer node start"   2 seconds ago   Up 1 second             7051/tcp, 0.0.0.0:9051->9051/tcp                 peer0.org2.example.com
```

If you don't get this result, jump down to [Troubleshooting](#troubleshooting)
for help on what might have gone wrong. By default, the network uses the
cryptogen tool to bring up the network. However, you can also
[bring up the network with Certificate Authorities](#bring-up-the-network-with-certificate-authorities).

### The components of the test network

After your test network is deployed, you can take some time to examine its
components. Run the following command to list all of Docker containers that
are running on your machine. You should see the three nodes that were created by
the `network.sh` script:
```
docker ps -a
```

Each node and user that interacts with a Fabric network needs to belong to an
organization in order to participate in the network. The test
network includes two peer organizations, Org1 and Org2. It also includes a single
orderer organization that maintains the ordering service of the network.

[Peers](peers/peers.html) are the fundamental components of any Fabric network.
Peers store the blockchain ledger and validate transactions before they are
committed to the ledger. Peers run the smart contracts that contain the business
logic that is used to manage the assets on the blockchain ledger.

Every peer in the network needs to belong to an organization. In the
test network, each organization operates one peer each, `peer0.org1.example.com`
and `peer0.org2.example.com`.

Every Fabric network also includes an [ordering service](orderer/ordering_service.html).
While peers validate transactions and add blocks of transactions to the
blockchain ledger, they do not decide on the order of transactions or include
them into new blocks. On a distributed network, peers may be running far away
from each other and not have a common view of when a transaction was created.
Coming to consensus on the order of transactions is a costly process that would
create overhead for the peers.

An ordering service allows peers to focus on validating transactions and
committing them to the ledger. After ordering nodes receive endorsed transactions
from clients, they come to consensus on the order of transactions and then add
them to blocks. The blocks are then distributed to peer nodes, which add the
blocks to the blockchain ledger.

The sample network uses a single node Raft ordering service that is operated by
the orderer organization. You can see the ordering node running on your machine
as `orderer.example.com`. While the test network only uses a single node ordering
service, a production network would have multiple ordering nodes, operated by one or
multiple orderer organizations. The different ordering nodes would use the Raft
consensus algorithm to come to agreement on the order of transactions across
the network.

## Creating a channel

Now that we have peer and orderer nodes running on our machine, we can use the
script to create a Fabric channel for transactions between Org1 and Org2.
Channels are a private layer of communication between specific network members.
Channels can be used only by organizations that are invited to the channel, and
are invisible to other members of the network. Each channel has a separate
blockchain ledger. Organizations that have been invited "join" their peers to
the channel to store the channel ledger and validate the transactions on the
channel.

You can use the `network.sh` script to create a channel between Org1 and Org2
and join their peers to the channel. Run the following command to create a
channel with the default name of `mychannel`:
```
./network.sh createChannel
```
If the command was successful, you can see the following message printed in your
logs:
```
========= Channel successfully joined ===========
```

You can also use the channel flag to create a channel with custom name. As an
example, the following command would create a channel named `channel1`:
```
./network.sh createChannel -c channel1
```

The channel flag also allows you to create multiple channels by specifying
different channel names. After you create `mychannel` or `channel1`, you can use
the command below to create a second channel named `channel2`:
```
./network.sh createChannel -c channel2
```

**NOTE:** Make sure the name of the channel applies the following restrictions:

  - contains only lower case ASCII alphanumerics, dots '.', and dashes '-'
  - is shorter than 250 characters
  - starts with a letter

If you want to bring up the network and create a channel in a single step, you
can use the `up` and `createChannel` modes together:
```
./network.sh up createChannel
```

## Starting a chaincode on the channel

After you have created a channel, you can start using [smart contracts](smartcontract/smartcontract.html) to
interact with the channel ledger. Smart contracts contain the business logic
that governs assets on the blockchain ledger. Applications run by members of the
network can invoke smart contracts to create assets on the ledger, as well as
change and transfer those assets. Applications also query smart contracts to
read data on the ledger.

To ensure that transactions are valid, transactions created using smart contracts
typically need to be signed by multiple organizations to be committed to the
channel ledger. Multiple signatures are integral to the trust model of Fabric.
Requiring multiple endorsements for a transaction prevents one organization on
a channel from tampering with the ledger on their peer or using business logic
that was not agreed to. To sign a transaction, each organization needs to invoke
and execute the smart contract on their peer, which then signs the output of the
transaction. If the output is consistent and has been signed by enough
organizations, the transaction can be committed to the ledger. The policy that
specifies the set organizations on the channel that need to execute the smart
contract is referred to as the endorsement policy, which is set for each
chaincode as part of the chaincode definition.

In Fabric, smart contracts are deployed on the network in packages referred to
as chaincode. A Chaincode is installed on the peers of an organization and then
deployed to a channel, where it can then be used to endorse transactions and
interact with the blockchain ledger. Before a chaincode can be deployed to a
channel, the members of the channel need to agree on a chaincode definition that
establishes chaincode governance. When the required number of organizations
agree, the chaincode definition can be committed to the channel, and the
chaincode is ready to be used.

After you have used the `network.sh` to create a channel, you can start a
chaincode on the channel using the following command:
```
./network.sh deployCC -ccn basic -ccp ../asset-transfer-basic/chaincode-go -ccl go
```
The `deployCC` subcommand will install the **asset-transfer (basic)** chaincode on
``peer0.org1.example.com`` and ``peer0.org2.example.com`` and then deploy
the chaincode on the channel specified using the channel flag (or `mychannel`
if no channel is specified).  If you are deploying a chaincode for the first
time, the script will install the chaincode dependencies. You can use the
language flag, `-l`, to install the Go, typescript or javascript versions of the chaincode.
You can find the asset-transfer (basic) chaincode in the `asset-transfer-basic` folder of the `fabric-samples`
directory. This folder contains sample chaincode that are provided as examples and
used by tutorials to highlight Fabric features.

## Interacting with the network

After you bring up the test network, you can use the `peer` CLI to interact
with your network. The `peer` CLI allows you to invoke deployed smart contracts,
update channels, or install and deploy new smart contracts from the CLI.

Make sure that you are operating from the `test-network` directory. If you
followed the instructions to [install the Samples, Binaries and Docker Images](install.html),
You can find the `peer` binaries in the `bin` folder of the `fabric-samples`
repository. Use the following command to add those binaries to your CLI Path:
```
export PATH=${PWD}/../bin:$PATH
```
You also need to set the `FABRIC_CFG_PATH` to point to the `core.yaml` file in
the `fabric-samples` repository:
```
export FABRIC_CFG_PATH=$PWD/../config/
```
You can now set the environment variables that allow you to operate the `peer`
 CLI as Org1:
```
# Environment variables for Org1

export CORE_PEER_TLS_ENABLED=true
export CORE_PEER_LOCALMSPID="Org1MSP"
export CORE_PEER_TLS_ROOTCERT_FILE=${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
export CORE_PEER_MSPCONFIGPATH=${PWD}/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
export CORE_PEER_ADDRESS=localhost:7051
```

The `CORE_PEER_TLS_ROOTCERT_FILE` and `CORE_PEER_MSPCONFIGPATH` environment
variables point to the Org1 crypto material in the `organizations` folder.

If you used `./network.sh deployCC -ccl go` to install and start the asset-transfer (basic) chaincode, you can invoke the `InitLedger` function of the (Go) chaincode to put an initial list of assets on the ledger (if using typescript or javascript `./network.sh deployCC -ccl javascript` for example, you will invoke the `InitLedger` function of the respective chaincodes).

Run the following command to initialize the ledger with assets:
```
peer chaincode invoke -o localhost:7050 --ordererTLSHostnameOverride orderer.example.com --tls --cafile "${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem" -C mychannel -n basic --peerAddresses localhost:7051 --tlsRootCertFiles "${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt" --peerAddresses localhost:9051 --tlsRootCertFiles "${PWD}/organizations/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt" -c '{"function":"InitLedger","Args":[]}'
```
If successful, you should see similar output to below:
```
-> INFO 001 Chaincode invoke successful. result: status:200
```
You can now query the ledger from your CLI. Run the following command to get the list of assets that were added to your channel ledger:
```
peer chaincode query -C mychannel -n basic -c '{"Args":["GetAllAssets"]}'
```
If successful, you should see the following output:
```
[
  {"ID": "asset1", "color": "blue", "size": 5, "owner": "Tomoko", "appraisedValue": 300},
  {"ID": "asset2", "color": "red", "size": 5, "owner": "Brad", "appraisedValue": 400},
  {"ID": "asset3", "color": "green", "size": 10, "owner": "Jin Soo", "appraisedValue": 500},
  {"ID": "asset4", "color": "yellow", "size": 10, "owner": "Max", "appraisedValue": 600},
  {"ID": "asset5", "color": "black", "size": 15, "owner": "Adriana", "appraisedValue": 700},
  {"ID": "asset6", "color": "white", "size": 15, "owner": "Michel", "appraisedValue": 800}
]
```
Chaincodes are invoked when a network member wants to transfer or change an asset on the ledger. Use the following command to change the owner of an asset on the ledger by invoking the asset-transfer (basic) chaincode:
```
peer chaincode invoke -o localhost:7050 --ordererTLSHostnameOverride orderer.example.com --tls --cafile "${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem" -C mychannel -n basic --peerAddresses localhost:7051 --tlsRootCertFiles "${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt" --peerAddresses localhost:9051 --tlsRootCertFiles "${PWD}/organizations/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt" -c '{"function":"TransferAsset","Args":["asset6","Christopher"]}'
```

If the command is successful, you should see the following response:
```
2019-12-04 17:38:21.048 EST [chaincodeCmd] chaincodeInvokeOrQuery -> INFO 001 Chaincode invoke successful. result: status:200
```
Because the endorsement policy for the asset-transfer (basic) chaincode requires the transaction
to be signed by Org1 and Org2, the chaincode invoke command needs to target both
`peer0.org1.example.com` and `peer0.org2.example.com` using the `--peerAddresses`
flag. Because TLS is enabled for the network, the command also needs to reference
the TLS certificate for each peer using the `--tlsRootCertFiles` flag.

After we invoke the chaincode, we can use another query to see how the invoke
changed the assets on the blockchain ledger. Since we already queried the Org1
peer, we can take this opportunity to query the chaincode running on the Org2
peer. Set the following environment variables to operate as Org2:
```
# Environment variables for Org2

export CORE_PEER_TLS_ENABLED=true
export CORE_PEER_LOCALMSPID="Org2MSP"
export CORE_PEER_TLS_ROOTCERT_FILE=${PWD}/organizations/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt
export CORE_PEER_MSPCONFIGPATH=${PWD}/organizations/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp
export CORE_PEER_ADDRESS=localhost:9051
```

You can now query the asset-transfer (basic) chaincode running on `peer0.org2.example.com`:
```
peer chaincode query -C mychannel -n basic -c '{"Args":["ReadAsset","asset6"]}'
```

The result will show that `"asset6"` was transferred to Christopher:
```
{"ID":"asset6","color":"white","size":15,"owner":"Christopher","appraisedValue":800}
```

## Bring down the network

When you are finished using the test network, you can bring down the network
with the following command:
```
./network.sh down
```

The command will stop and remove the node and chaincode containers, delete the
organization crypto material, and remove the chaincode images from your Docker
Registry. The command also removes the channel artifacts and docker volumes from
previous runs, allowing you to run `./network.sh up` again if you encountered
any problems.

## Next steps

Now that you have used the test network to deploy Hyperledger Fabric on your
local machine, you can use the tutorials to start developing your own solution:

- Learn how to deploy your own smart contracts to the test network using the
[Deploying a smart contract to a channel](deploy_chaincode.html) tutorial.
- Visit the [Running a Fabric Application](write_first_app.html) tutorial
to learn how to use the APIs provided by the Fabric SDKs to invoke smart
contracts from your client applications.
- If you are ready to deploy a more complicated smart contract to the network, follow
the [commercial paper tutorial](tutorial/commercial_paper.html) to explore a
use case in which two organizations use a blockchain network to trade commercial
paper.

You can find the complete list of Fabric tutorials on the [tutorials](tutorials.html)
page.

## Bring up the network with Certificate Authorities

Hyperledger Fabric uses public key infrastructure (PKI) to verify the actions of
all network participants. Every node, network administrator, and user submitting
transactions needs to have a public certificate and private key to verify their
identity. These identities need to have a valid root of trust, establishing
that the certificates were issued by an organization that is a member of the
network. The `network.sh` script creates all of the cryptographic material
that is required to deploy and operate the network before it creates the peer
and ordering nodes.

By default, the script uses the cryptogen tool to create the certificates
and keys. The tool is provided for development and testing, and can quickly
create the required crypto material for Fabric organizations with a valid root
of trust. When you run `./network.sh up`, you can see the cryptogen tool creating
the certificates and keys for Org1, Org2, and the Orderer Org.

```
creating Org1, Org2, and ordering service organization with crypto from 'cryptogen'

/Usr/fabric-samples/test-network/../bin/cryptogen

##########################################################
##### Generate certificates using cryptogen tool #########
##########################################################

##########################################################
############ Create Org1 Identities ######################
##########################################################
+ cryptogen generate --config=./organizations/cryptogen/crypto-config-org1.yaml --output=organizations
org1.example.com
+ res=0
+ set +x
##########################################################
############ Create Org2 Identities ######################
##########################################################
+ cryptogen generate --config=./organizations/cryptogen/crypto-config-org2.yaml --output=organizations
org2.example.com
+ res=0
+ set +x
##########################################################
############ Create Orderer Org Identities ###############
##########################################################
+ cryptogen generate --config=./organizations/cryptogen/crypto-config-orderer.yaml --output=organizations
+ res=0
+ set +x
```

However, the test network script also provides the option to bring up the network using
Certificate Authorities (CAs). In a production network, each organization
operates a CA (or multiple intermediate CAs) that creates the identities that
belong to their organization. All of the identities created by a CA run by the
organization share the same root of trust. Although it takes more time than
using cryptogen, bringing up the test network using CAs provides an introduction
to how a network is deployed in production. Deploying CAs also allows you to enroll
client identities with the Fabric SDKs and create a certificate and private key
for your applications.

If you would like to bring up a network using Fabric CAs, first run the following
command to bring down any running networks:
```
./network.sh down
```

You can then bring up the network with the CA flag:
```
./network.sh up -ca
```

After you issue the command, you can see the script bringing up three CAs, one
for each organization in the network.
```
##########################################################
##### Generate certificates using Fabric CA's ############
##########################################################
Creating network "net_default" with the default driver
Creating ca_org2    ... done
Creating ca_org1    ... done
Creating ca_orderer ... done
```

It is worth taking time to examine the logs generated by the `./network.sh`
script after the CAs have been deployed. The test network uses the Fabric CA
client to register node and user identities with the CA of each organization. The
script then uses the enroll command to generate an MSP folder for each identity.
The MSP folder contains the certificate and private key for each identity, and
establishes the identity's role and membership in the organization that operated
the CA. You can use the following command to examine the MSP folder of the Org1
admin user:
```
tree organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/
```
The command will reveal the MSP folder structure and configuration file:
```
organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/
└── msp
    ├── IssuerPublicKey
    ├── IssuerRevocationPublicKey
    ├── cacerts
    │   └── localhost-7054-ca-org1.pem
    ├── config.yaml
    ├── keystore
    │   └── 58e81e6f1ee8930df46841bf88c22a08ae53c1332319854608539ee78ed2fd65_sk
    ├── signcerts
    │   └── cert.pem
    └── user
```
You can find the certificate of the admin user in the `signcerts` folder and the
private key in the `keystore` folder. To learn more about MSPs, see the [Membership Service Provider](membership/membership.html)
concept topic.

Both cryptogen and the Fabric CAs generate the cryptographic material for each organization
in the `organizations` folder. You can find the commands that are used to set up the
network in the `registerEnroll.sh` script in the `organizations/fabric-ca` directory.
To learn more about how you would use the Fabric CA to deploy a Fabric network,
visit the [Fabric CA operations guide](https://hyperledger-fabric-ca.readthedocs.io/en/latest/operations_guide.html).
You can learn more about how Fabric uses PKI by visiting the [identity](identity/identity.html)
and [membership](membership/membership.html) concept topics.

## What's happening behind the scenes?

If you are interested in learning more about the sample network, you can
investigate the files and scripts in the `test-network` directory. The steps
below provide a guided tour of what happens when you issue the command of
`./network.sh up`.

- `./network.sh` creates the certificates and keys for two peer organizations
  and the orderer organization. By default, the script uses the cryptogen tool
  using the configuration files located in the `organizations/cryptogen` folder.
  If you use the `-ca` flag to create Certificate Authorities, the script uses
  Fabric CA server configuration files and `registerEnroll.sh` script located in
  the `organizations/fabric-ca` folder. Both cryptogen and the Fabric CAs create
  the crypto material and MSP folders for all three organizations in the
  `organizations` folder.

- Once the organization crypto material has been generated, the `network.sh` can bring up the nodes of the network. The
  script uses the ``docker-compose-test-net.yaml`` file in the `docker` folder
  to create the peer and orderer nodes. The `docker` folder also contains the
  ``docker-compose-e2e.yaml`` file that brings up the nodes of the network
  alongside three Fabric CAs. This file is meant to be used to run end-to-end
  tests by the Fabric SDK. Refer to the [Node SDK](https://github.com/hyperledger/fabric-sdk-node)
  repo for details on running these tests.

- If you use the `createChannel` subcommand, `./network.sh` runs the
  `createChannel.sh` script in the `scripts` folder to create a channel
  using the supplied channel name. The script uses the `configtxgen` tool to create the channel genesis block
  based on the `TwoOrgsApplicationGenesis` channel profile in the `configtx/configtx.yaml` file. After creating the channel, the script uses the peer cli to join ``peer0.org1.example.com`` and ``peer0.org2.example.com`` to the channel, and make both of the peers anchor peers.

- If you issue the `deployCC` command, `./network.sh` runs the ``deployCC.sh``
  script to install the **asset-transfer (basic)** chaincode on both peers and then define then
  chaincode on the channel. Once the chaincode definition is committed to the
  channel, the peer cli initializes the chaincode using the `Init` and invokes
  the chaincode to put initial data on the ledger.

## Troubleshooting

If you have any problems with the tutorial, review the following:

-  You should always start your network fresh. You can use the following command
   to remove the artifacts, crypto material, containers, volumes, and chaincode
   images from previous runs:
   ```
   ./network.sh down
   ```
   You **will** see errors if you do not remove old containers, images, and
   volumes.

-  If you see Docker errors, first check your Docker version ([Prerequisites](prereqs.html)),
   and then try restarting your Docker process. Problems with Docker are
   oftentimes not immediately recognizable. For example, you may see errors
   that are the result of your node not being able to access the crypto material
   mounted within a container.

   If problems persist, you can remove your images and start from scratch:
   ```
   docker rm -f $(docker ps -aq)
   docker rmi -f $(docker images -q)
   ```
-  If you are running Docker Desktop on macOS and experience the following error during chaincode installation:
   ```
   Error: chaincode install failed with status: 500 - failed to invoke backing implementation of 'InstallChaincode': could not build chaincode: docker build failed: docker image inspection failed: Get "http://unix.sock/images/dev-peer0.org1.example.com-basic_1.0-4ec191e793b27e953ff2ede5a8bcc63152cecb1e4c3f301a26e22692c61967ad-42f57faac8360472e47cbbbf3940e81bba83439702d085878d148089a1b213ca/json": dial unix /host/var/run/docker.sock: connect: no such file or directory
   Chaincode installation on peer0.org1 has failed
   Deploying chaincode failed
   ```

   This problem is caused by a newer version of Docker Desktop for macOS. To resolve this issue, in the Docker Desktop preferences, uncheck the box `Use gRPC FUSE for file sharing` to use the legacy osxfs file sharing instead and click **Apply & Restart**.

-  If you see errors on your create, approve, commit, invoke or query commands,
   make sure you have properly updated the channel name and chaincode name.
   There are placeholder values in the supplied sample commands.

-  If you see the error below:
   ```
   Error: Error endorsing chaincode: rpc error: code = 2 desc = Error installing chaincode code mycc:1.0(chaincode /var/hyperledger/production/chaincodes/mycc.1.0 exits)
   ```

   You likely have chaincode images (e.g. ``dev-peer1.org2.example.com-asset-transfer-1.0`` or
   ``dev-peer0.org1.example.com-asset-transfer-1.0``) from prior runs. Remove them and try
   again.
   ```
   docker rmi -f $(docker images | grep dev-peer[0-9] | awk '{print $3}')
   ```

-  If you see the below error:

   ```
   [configtx/tool/localconfig] Load -> CRIT 002 Error reading configuration: Unsupported Config Type ""
   panic: Error reading configuration: Unsupported Config Type ""
   ```

   Then you did not set the ``FABRIC_CFG_PATH`` environment variable properly. The
   configtxgen tool needs this variable in order to locate the configtx.yaml. Go
   back and execute an ``export FABRIC_CFG_PATH=$PWD/configtx/configtx.yaml``,
   then recreate your channel artifacts.

-  If you see an error stating that you still have "active endpoints", then prune
   your Docker networks. This will wipe your previous networks and start you with a
   fresh environment:
   ```
   docker network prune
   ```

   You will see the following message:
   ```
   WARNING! This will remove all networks not used by at least one container.
   Are you sure you want to continue? [y/N]
   ```
   Select ``y``.

-  If you try to create a channel with the command `./network.sh createChannel`,
   and it fails with the following error:
   ```
   [comm.tls] ClientHandshake -> ERRO 003 Client TLS handshake failed after 1.908956ms with error: EOF remoteaddress=127.0.0.1:7051
   Error: error getting endorser client for channel: endorser client failed to connect to localhost:7051: failed to create new connection: context deadline exceeded
   After 5 attempts, peer0.org1 has failed to join channel 'mychannel'
   ```

   You need to uninstall Docker Desktop and reinstall the recommended version 2.5.0.1. Then, reclone the `fabric-samples`
   repository before reattempting the commands.

-  If you see an error similar to the following:
   ```
   /bin/bash: ./scripts/createChannel.sh: /bin/bash^M: bad interpreter: No such file or directory
   ```

   Ensure that the file in question (**createChannel.sh** in this example) is
   encoded in the Unix format. This was most likely caused by not setting
   ``core.autocrlf`` to ``false`` in your Git configuration (see
    [Windows](prereqs.html#windows)). There are several ways of fixing this. If you have
   access to the vim editor for instance, open the file:
   ```
   vim ./fabric-samples/test-network/scripts/createChannel.sh
   ```

   Then change its format by executing the following vim command:
   ```
   :set ff=unix
   ```

If you continue to see errors, share your logs on the **fabric-questions**
channel on [Hyperledger Rocket Chat](https://chat.hyperledger.org/home) or on
[StackOverflow](https://stackoverflow.com/questions/tagged/hyperledger-fabric).

<!--- Licensed under Creative Commons Attribution 4.0 International License
https://creativecommons.org/licenses/by/4.0/ -->


text:
package languages.wdl.draft2

import com.typesafe.config.ConfigFactory
import common.assertion.CromwellTimeoutSpec
import common.assertion.ErrorOrAssertions._
import common.validation.Validation._
import languages.wdl.draft2.ArrayCoercionsSpec._
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import wdl.draft2.model.WdlNamespaceWithWorkflow
import wdl.draft2.model.expression.NoFunctions
import wom.core.WorkflowSource
import wom.expression.EmptyIoFunctionSet
import wom.types.{WomArrayType, WomSingleFileType, WomStringType}
import wom.values.{WomArray, WomSingleFile, WomString}

class ArrayCoercionsSpec extends AnyFlatSpec with CromwellTimeoutSpec with Matchers {

  var factory: WdlDraft2LanguageFactory = new WdlDraft2LanguageFactory(ConfigFactory.parseString(ConfigString))
  val arrayLiteralNamespace: WdlNamespaceWithWorkflow = WdlNamespaceWithWorkflow.load(ArrayDeclarationWorkflow, List.empty).get

  "A static Array[File] declaration" should "be a valid declaration" in {
    val declaration = arrayLiteralNamespace.workflow.declarations.find {_.unqualifiedName == "arr"}.getOrElse {
      fail("Expected declaration 'arr' to be found")
    }
    val expression = declaration.expression.getOrElse {
      fail("Expected an expression for declaration 'arr'")
    }
    expression.evaluate((_: String) => fail("No lookups"), NoFunctions).toChecked.shouldBeValid(
      WomArray(WomArrayType(WomStringType), Seq(WomString("f1"), WomString("f2"), WomString("f3")))
    )
  }

  "An Array[File]" should "be usable as an input" in {
    val expectedArray = WomArray(
      WomArrayType(WomSingleFileType),
      Seq(WomSingleFile("f1"), WomSingleFile("f2"), WomSingleFile("f3"))
    )
    val catTask = arrayLiteralNamespace.findTask("cat").getOrElse {
      fail("Expected to find task 'cat'")
    }
    val command = catTask.instantiateCommand(catTask.inputsFromMap(Map("cat.files" -> expectedArray)), NoFunctions).getOrElse {
      fail("Expected instantiation to work")
    }
    command.head.commandString shouldEqual "cat -s f1 f2 f3"
  }

  "An Array[String] input" should "coerce to an Array[File] input declaration" in {
    createExecutable(ArrayDeclarationWorkflow)
  }

  "An Array[Array[String]] input" should "coerce to Array[Array[File]] input declaration" in {
    createExecutable(ArrayOfArraysDeclarationWorkflow)
  }

  private def createExecutable(workflowSource: WorkflowSource): Unit = {
    val result = for {
      bundle <- factory.getWomBundle(workflowSource, None, "{}", List.empty, List.empty)
      _ <- factory.createExecutable(bundle, inputs = "{}", ioFunctions = new EmptyIoFunctionSet)
    } yield ()

    result match {
      case Left(errors) => fail("Bad things have happened: " + errors.toList.mkString(", "))
      case Right(_) =>
    }
  }
}

object ArrayCoercionsSpec {
  val ConfigString =
    """
      |{
      |  enabled: true
      |  strict-validation: true
      |}""".stripMargin

  val ArrayDeclarationWorkflow =
    s"""
       |task cat {
       |  Array[File]+ files
       |  command {
       |    cat -s $${sep = ' ' files}
       |  }
       |  output {
       |    Array[String] lines = read_lines(stdout())
       |  }
       |}
       |
       |workflow wf {
       |  Array[File] arr = ["f1", "f2", "f3"]
       |  call cat {input: files = arr}
       |}
      """.stripMargin

  val ArrayOfArraysDeclarationWorkflow =
    s"""
       |task subtask {
       |  Array[File] a
       |  command {
       |    cat $${sep = " " a}
       |  }
       |  output {
       |    String concatenated = read_string(stdout())
       |  }
       |}
       |
       |workflow wf {
       |  Array[Array[File]] nested_file = [["f1","f2"],["f3","f4"]]
       |
       |  scatter(n in nested_file) {
       |    call subtask {
       |      input: a = n
       |    }
       |  }
       |}
      """.stripMargin
}

redpajama_set_name: RedPajamaGithub


text:
namespace Apache.Ignite.Examples.Sql
{
    using System;
    using System.Linq;
    using Apache.Ignite.Core;
    using Apache.Ignite.Core.Cache;
    using Apache.Ignite.Core.Cache.Affinity;
    using Apache.Ignite.Core.Cache.Configuration;
    using Apache.Ignite.Core.Cache.Query;
    using Apache.Ignite.ExamplesDll.Binary;
    using Apache.Ignite.Linq;

    ///
    /// This example populates cache with sample data and runs several LINQ queries over this data.
    /// <para />
    /// 1) Build the project Apache.Ignite.ExamplesDll (select it -> right-click -> Build).
    /// 2) Set this class as startup object (Apache.Ignite.Examples project -> right-click -> Properties ->
    ///     Application -> Startup object);
    /// 3) Start example (F5 or Ctrl+F5).
    /// <para />
    /// This example can be run with standalone Apache Ignite.NET node:
    /// 1) Run %IGNITE_HOME%/platforms/dotnet/bin/Apache.Ignite.exe:
    /// Apache.Ignite.exe -configFileName=platforms\dotnet\examples\apache.ignite.examples\app.config
    /// 2) Start example.
    ///
    public class LinqExample
    {
        /// Organization cache name.
        private const string OrganizationCacheName = "dotnet_cache_query_organization";

        /// Employee cache name.
        private const string EmployeeCacheName = "dotnet_cache_query_employee";

        /// Colocated employee cache name.
        private const string EmployeeCacheNameColocated = "dotnet_cache_query_employee_colocated";

        [STAThread]
        public static void Main()
        {
            using (var ignite = Ignition.StartFromApplicationConfiguration())
            {
                Console.WriteLine();
                Console.WriteLine(">>> Cache LINQ example started.");

                var employeeCache = ignite.GetOrCreateCache<int, Employee>(
                    new CacheConfiguration(EmployeeCacheName, new QueryEntity(typeof(int), typeof(Employee))));

                var employeeCacheColocated = ignite.GetOrCreateCache<AffinityKey, Employee>(
                    new CacheConfiguration(EmployeeCacheNameColocated,
                        new QueryEntity(typeof(AffinityKey), typeof(Employee))));

                var organizationCache = ignite.GetOrCreateCache<int, Organization>(
                    new CacheConfiguration(OrganizationCacheName, new QueryEntity(typeof(int), typeof(Organization))));

                // Populate cache with sample data entries.
                PopulateCache(employeeCache);
                PopulateCache(employeeCacheColocated);
                PopulateCache(organizationCache);

                // Run SQL query example.
                QueryExample(employeeCache);

                // Run compiled SQL query example.
                CompiledQueryExample(employeeCache);

                // Run SQL query with join example.
                JoinQueryExample(employeeCacheColocated, organizationCache);

                // Run SQL query with distributed join example.
                DistributedJoinQueryExample(employeeCache, organizationCache);

                // Run SQL fields query example.
                FieldsQueryExample(employeeCache);

                Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine(">>> Example finished, press any key to exit ...");
            Console.ReadKey();
        }

        ///
        /// Queries employees that have provided ZIP code in address.
        ///
        /// <param name="cache">Cache.</param>
        private static void QueryExample(ICache<int, Employee> cache)
        {
            const int zip = 94109;

            IQueryable<ICacheEntry<int, Employee>> qry =
                cache.AsCacheQueryable().Where(emp => emp.Value.Address.Zip == zip);

            Console.WriteLine();
            Console.WriteLine(">>> Employees with zipcode " + zip + ":");

            foreach (ICacheEntry<int, Employee> entry in qry)
                Console.WriteLine(">>>    " + entry.Value);
        }

        ///
        /// Queries employees that have provided ZIP code in address with a compiled query.
        ///
        /// <param name="cache">Cache.</param>
        private static void CompiledQueryExample(ICache<int, Employee> cache)
        {
            const int zip = 94109;

            var cache0 = cache.AsCacheQueryable();

            // Compile cache query to eliminate LINQ overhead on multiple runs.
            Func<int, IQueryCursor<ICacheEntry<int, Employee>>> qry =
                CompiledQuery.Compile((int z) => cache0.Where(emp => emp.Value.Address.Zip == z));

            Console.WriteLine();
            Console.WriteLine(">>> Employees with zipcode {0} using compiled query:", zip);

            foreach (ICacheEntry<int, Employee> entry in qry(zip))
                Console.WriteLine(">>>    " + entry.Value);
        }

        ///
        /// Queries employees that work for organization with provided name.
        ///
        /// <param name="employeeCache">Employee cache.</param>
        /// <param name="organizationCache">Organization cache.</param>
        private static void JoinQueryExample(ICache<AffinityKey, Employee> employeeCache,
            ICache<int, Organization> organizationCache)
        {
            const string orgName = "Apache";

            IQueryable<ICacheEntry<AffinityKey, Employee>> employees = employeeCache.AsCacheQueryable();
            IQueryable<ICacheEntry<int, Organization>> organizations = organizationCache.AsCacheQueryable();

            IQueryable<ICacheEntry<AffinityKey, Employee>> qry =
                from employee in employees
                from organization in organizations
                where employee.Value.OrganizationId == organization.Key && organization.Value.Name == orgName
                select employee;

            Console.WriteLine();
            Console.WriteLine(">>> Employees working for " + orgName + ":");

            foreach (ICacheEntry<AffinityKey, Employee> entry in qry)
                Console.WriteLine(">>>     " + entry.Value);
        }

        ///
        /// Queries employees that work for organization with provided name.
        ///
        /// <param name="employeeCache">Employee cache.</param>
        /// <param name="organizationCache">Organization cache.</param>
        private static void DistributedJoinQueryExample(ICache<int, Employee> employeeCache,
            ICache<int, Organization> organizationCache)
        {
            const string orgName = "Apache";

            var queryOptions = new QueryOptions
            {
                EnableDistributedJoins = true,
                Timeout = new TimeSpan(0, 1, 0)
            };

            IQueryable<ICacheEntry<int, Employee>> employees = employeeCache.AsCacheQueryable(queryOptions);
            IQueryable<ICacheEntry<int, Organization>> organizations = organizationCache.AsCacheQueryable(queryOptions);

            IQueryable<ICacheEntry<int, Employee>> qry =
                from employee in employees
                from organization in organizations
                where employee.Value.OrganizationId == organization.Key && organization.Value.Name == orgName
                select employee;

            Console.WriteLine();
            Console.WriteLine(">>> Employees working for " + orgName + ":");

            foreach (ICacheEntry<int, Employee> entry in qry)
                Console.WriteLine(">>>     " + entry.Value);
        }

        ///
        /// Queries names and salaries for all employees.
        ///
        /// <param name="cache">Cache.</param>
        private static void FieldsQueryExample(ICache<int, Employee> cache)
        {
            var qry = cache.AsCacheQueryable().Select(entry => new {entry.Value.Name, entry.Value.Salary});

            Console.WriteLine();
            Console.WriteLine(">>> Employee names and their salaries:");

            foreach (var row in qry)
                Console.WriteLine(">>>     [Name=" + row.Name + ", salary=" + row.Salary + ']');
        }

        ///
        /// Populate cache with data for this example.
        ///
        /// <param name="cache">Cache.</param>
        private static void PopulateCache(ICache<int, Organization> cache)
        {
            cache.Put(1, new Organization(
                "Apache",
                new Address("1065 East Hillsdale Blvd, Foster City, CA", 94404),
                OrganizationType.Private,
                DateTime.Now));

            cache.Put(2, new Organization(
                "Microsoft",
                new Address("1096 Eddy Street, San Francisco, CA", 94109),
                OrganizationType.Private,
                DateTime.Now));
        }

        ///
        /// Populate cache with data for this example.
        ///
        /// <param name="cache">Cache.</param>
        private static void PopulateCache(ICache<AffinityKey, Employee> cache)
        {
            cache.Put(new AffinityKey(1, 1), new Employee(
                "James Wilson",
                12500,
                new Address("1096 Eddy Street, San Francisco, CA", 94109),
                new[] {"Human Resources", "Customer Service"},
                1));

            cache.Put(new AffinityKey(2, 1), new Employee(
                "Daniel Adams",
                11000,
                new Address("184 Fidler Drive, San Antonio, TX", 78130),
                new[] {"Development", "QA"},
                1));

            cache.Put(new AffinityKey(3, 1), new Employee(
                "Cristian Moss",
                12500,
                new Address("667 Jerry Dove Drive, Florence, SC", 29501),
                new[] {"Logistics"},
                1));

            cache.Put(new AffinityKey(4, 2), new Employee(
                "Allison Mathis",
                25300,
                new Address("2702 Freedom Lane, San Francisco, CA", 94109),
                new[] {"Development"},
                2));

            cache.Put(new AffinityKey(5, 2), new Employee(
                "Breana Robbin",
                6500,
                new Address("3960 Sundown Lane, Austin, TX", 78130),
                new[] {"Sales"},
                2));

            cache.Put(new AffinityKey(6, 2), new Employee(
                "Philip Horsley",
                19800,
                new Address("2803 Elsie Drive, Sioux Falls, SD", 57104),
                new[] {"Sales"},
                2));

            cache.Put(new AffinityKey(7, 2), new Employee(
                "Brian Peters",
                10600,
                new Address("1407 Pearlman Avenue, Boston, MA", 12110),
                new[] {"Development", "QA"},
                2));
        }

        ///
        /// Populate cache with data for this example.
        ///
        /// <param name="cache">Cache.</param>
        private static void PopulateCache(ICache<int, Employee> cache)
        {
            cache.Put(1, new Employee(
                "James Wilson",
                12500,
                new Address("1096 Eddy Street, San Francisco, CA", 94109),
                new[] {"Human Resources", "Customer Service"},
                1));

            cache.Put(2, new Employee(
                "Daniel Adams",
                11000,
                new Address("184 Fidler Drive, San Antonio, TX", 78130),
                new[] {"Development", "QA"},
                1));

            cache.Put(3, new Employee(
                "Cristian Moss",
                12500,
                new Address("667 Jerry Dove Drive, Florence, SC", 29501),
                new[] {"Logistics"},
                1));

            cache.Put(4, new Employee(
                "Allison Mathis",
                25300,
                new Address("2702 Freedom Lane, San Francisco, CA", 94109),
                new[] {"Development"},
                2));

            cache.Put(5, new Employee(
                "Breana Robbin",
                6500,
                new Address("3960 Sundown Lane, Austin, TX", 78130),
                new[] {"Sales"},
                2));

            cache.Put(6, new Employee(
                "Philip Horsley",
                19800,
                new Address("2803 Elsie Drive, Sioux Falls, SD", 57104),
                new[] {"Sales"},
                2));

            cache.Put(7, new Employee(
                "Brian Peters",
                10600,
                new Address("1407 Pearlman Avenue, Boston, MA", 12110),
                new[] {"Development", "QA"},
                2));
        }
    }
}


text:
package net.erdfelt.android.sdkfido.tasks;

import static org.hamcrest.Matchers.*;
import net.erdfelt.android.sdkfido.TaskQueue;
import net.erdfelt.android.sdkfido.WorkDir;
import net.erdfelt.android.sdkfido.git.GitFactory;
import net.erdfelt.android.sdkfido.git.GitMirrors;
import net.erdfelt.android.sdkfido.git.IGit;
import net.erdfelt.android.sdkfido.logging.Logging;
import net.erdfelt.android.sdkfido.sdks.Repo;

import org.eclipse.jetty.toolchain.test.TestingDir;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;

public class GitCloneTaskTest {
    @Rule
    public TestingDir testdir = new TestingDir();

    static {
        Logging.config();
    }

    @Test
    public void testCloneAndBranchLauncher() throws Throwable {
        testdir.ensureEmpty();

        GitMirrors mirrors = GitMirrors.load();
        GitFactory.setMirrors(mirrors);

        WorkDir workdir = new WorkDir(testdir.getFile("work"));

        Repo repo = new Repo();
        repo.setUrl("git://android.git.kernel.org/platform/packages/apps/Launcher.git");
        String branchName = "android-sdk-2.0.1_r1";

        IGit git = workdir.getGitRepo(repo.getUrl());

        GitCloneTask gitclone = new GitCloneTask(git, repo.getUrl());
        GitSwitchBranchTask gitbranch = new GitSwitchBranchTask(git, branchName);

        TaskQueue tasks = new TaskQueue();

        gitclone.run(tasks);
        gitbranch.run(tasks);

        Assert.assertThat("Branch name", git.getCurrentBranch(), is("refs/tags/" + branchName));
    }
}


text:
package fosite_test

import (
	"net/http"
	"testing"

	"github.com/golang/mock/gomock"
	"github.com/stretchr/testify/assert"

	. "github.com/ory/fosite"
	. "github.com/ory/fosite/internal"
)

func TestWriteAccessResponse(t *testing.T) {
	f := &Fosite{}
	header := http.Header{}
	ctrl := gomock.NewController(t)
	rw := NewMockResponseWriter(ctrl)
	ar := NewMockAccessRequester(ctrl)
	resp := NewMockAccessResponder(ctrl)
	defer ctrl.Finish()

	rw.EXPECT().Header().AnyTimes().Return(header)
	rw.EXPECT().WriteHeader(http.StatusOK)
	rw.EXPECT().Write(gomock.Any())
	resp.EXPECT().ToMap().Return(map[string]interface{}{})

	f.WriteAccessResponse(rw, ar, resp)
	assert.Equal(t, "application/json;charset=UTF-8", header.Get("Content-Type"))
	assert.Equal(t, "no-store", header.Get("Cache-Control"))
	assert.Equal(t, "no-cache", header.Get("Pragma"))
}


text:
from Tkinter import *
from PIL import Image, ImageTk
import tkFileDialog
from __main__ import *
import os,sys

def reset():
	os.remove("current.txt")
	sys.exit()

master = Tk()
master.title("DCM - Home Cinema")
top = Label(master, text="Cinema!", font=("Helvetica", 50))
top.grid()
def adverts():
    global advertselector
    advertselector = tkFileDialog.askopenfilename(filetypes = (("Digital Cinema Advertising Package", "*.dca.mp4"),("All files", "*.*") ))
def hdmi():
    master.destroy()
    c = open('current.txt', 'a')
    c.close()
    w = open('current.txt', 'w')
    w.write('/home/pi/Desktop/majestic-pi/' + dim.get() + '/intro.mp4\r\n')
    w.write('/home/pi/Desktop/majestic-pi/' + dim.get() + '/glasses.mp4\r\n')
    w.write('/home/pi/Desktop/majestic-pi/' + dim.get() + '/mimics/' + cinema.get() + '/1.mp4\r\n')
    w.write(dcp.get() + 'trailer.mp4' + '\r\n')
    w.write('/home/pi/Desktop/majestic-pi/' + dim.get() + '/mimics/' + cinema.get() + '/2.mp4\r\n')
    w.write(advertselector + '\r\n')
    w.write('/home/pi/Desktop/majestic-pi/' + dim.get() + '/mimics/' + cinema.get() + '/3.mp4\r\n')
    w.write('/home/pi/Desktop/majestic-pi/' + dim.get() + '/mimics/' + cinema.get() + '/soundintro.mp4\r\n')
    w.write(dcp.get() + 'filmintro.mp4' + '\r\n')
    w.write(dcp.get() + 'film.mp4' + '\r\n')
    w.write('/home/pi/Desktop/majestic-pi/' + dim.get() + '/mimics/' + cinema.get() + '/4.mp4\r\n')
    w.close()
    os.system("python prepare.py & sudo python play.py")

dcp = StringVar(master)
dcp.set("Choose")

drivelabel = Label(master, text="Select DCP:")
drive = OptionMenu(master, dcp, "C:/", "F:/", "G:/", "D:/")
drivelabel.grid(row=1)
drive.grid(row=1, column=1)

advertlabel = Label(master, text="Select Advert Package:")
advertbutton = Button(master, text="Browse", command=adverts)
advertlabel.grid(row=2)
advertbutton.grid(row=2, column=1)

cinema = StringVar(master)
cinema.set("Choose")
cinemalabel = Label(master, text="Choose Cinema Mimic:")
pick = OptionMenu(master, cinema, "Odeon", "Vue", "Cineworld")
cinemalabel.grid(row=4)
pick.grid(row=4, column=1)

dim = StringVar(master)
dim.set("Choose")

drivelabel = Label(master, text="Enable 3D:")
drive = OptionMenu(master, dim, "3D", "2D")
drivelabel.grid(row=5)
drive.grid(row=5, column=1)

img = Image.open("go.png")
go = ImageTk.PhotoImage(img)
label = Button(master, image=go, command=hdmi)
label.grid()

mainloop()


text:
package seedu.todo.ui;

import java.net.URL;

import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import seedu.todo.MainApp;

// @@author A0139812A
/**
 * A utility class to load UiParts from FXML files.
 * Modified from original codebase to support two-step
 * loading and rendering (see {@link UiManager}).
 */
public class UiPartLoader {
    private final static String FXML_FILE_FOLDER = "/ui/";
    private final static String FXML_ERROR_MESSAGE = "FXML Load Error for ";
    private final static String INSTANTION_EXCEPTION_ERROR_MESSAGE = "Could not instantiate ";

    /**
     * Loads the UiPart and returns the view controller.
     *
     * @param primaryStage The primary stage for the view.
     * @param placeholder  The placeholder where the loaded Ui Part is added.
     * @param uiPartClass  The UiPart class to load.
     * @param <T>          The type of the UiPart
     */
    public static <T extends UiPart> T loadUiPart(Stage primaryStage, Pane placeholder, Class<T> uiPartClass) {
        FXMLLoader loader = new FXMLLoader();

        // Get FXML path
        T instance = null;
        try {
            instance = uiPartClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            String errorMessage = INSTANTION_EXCEPTION_ERROR_MESSAGE + uiPartClass.getName();
            throw new RuntimeException(errorMessage, e);
        }
        String fxmlPath = instance.getFxmlPath();

        // Continue with loading
        loader.setLocation(getFXMLResource(fxmlPath));
        Node mainNode = loadLoader(loader, fxmlPath);

        T controller = loader.getController();
        controller.setStage(primaryStage);
        controller.setPlaceholder(placeholder);
        controller.setNode(mainNode);
        return controller;
    }

    private static Node loadLoader(FXMLLoader loader, String fxmlFileName) {
        try {
            return loader.load();
        } catch (Exception e) {
            String errorMessage = FXML_ERROR_MESSAGE + fxmlFileName;
            throw new RuntimeException(errorMessage, e);
        }
    }

    private static URL getFXMLResource(String fxmlPath) {
        return MainApp.class.getResource(FXML_FILE_FOLDER + fxmlPath);
    }

}


text:
message(STATUS "Configuring for platform Windows/MSVC.")

set(WIN32_COMPILE_DEFS
    WIN32                       # Windows system
    UNICODE                     # Use unicode
    _UNICODE                    # Use unicode
    _SCL_SECURE_NO_WARNINGS     # Calling any one of the potentially unsafe methods in the Standard C++ Library
    _CRT_SECURE_NO_DEPRECATE    # Disable CRT deprecation warnings
)

set(DEFAULT_COMPILE_DEFS_DEBUG
    ${WIN32_COMPILE_DEFS}
    _DEBUG                      # Debug build
)

set(DEFAULT_COMPILE_DEFS_RELEASE
    ${WIN32_COMPILE_DEFS}
    NDEBUG                      # Release build
)

set(WIN32_COMPILE_FLAGS
    /nologo                             # surpess startup banner
    /Zc:wchar_t                         # treat wchar_t as built-in type: yes
    /Zc:forScope                        # for loop variables goes out of scope after for loop ends
    /fp:fast                            # fast floating point arithmetic
    /MP                                 # Multithreaded build
    /wd4251
    /W4                                 # warning level 4: enable all warnings
    /WX                                 # treat warnings as errors
    /GR                                 # runtime type information (enables dynamic_cast)

    #Release Flags
    $<$<CONFIG:Release>:/GL>            # whole program optimization: enable link-time code generation
    $<$<CONFIG:Release>:/GS->           # buffer security check: no
    $<$<CONFIG:Release>:/GF>            # enable string pooling
    $<$<CONFIG:Release>:/Ox>            # full optimization
    $<$<CONFIG:Release>:/Ot>            # prefer fast code

    #Debug Flags
    $<$<CONFIG:Debug>:/Zi>              # debug information format: program database
    $<$<CONFIG:Debug>:/Od>              # no optimization

    # Mixed
    /MD$<$<CONFIG:Debug>:d>              # MD[d] -> Use dynamic multithreaded MSVCRT (runtime library) [with debug symbols]
)

set(DEFAULT_COMPILE_FLAGS ${WIN32_COMPILE_FLAGS})

set(WIN32_LINKER_FLAGS
    "/NOLOGO /INCREMENTAL:NO /NXCOMPAT /DYNAMICBASE:NO"
    # NOLOGO                                            -> suppress logo
    # INCREMENTAL:NO                                    -> enable incremental linking: no
    # MANIFEST                                          -> generate manifest: yes
    # MANIFESTUAC:"level='asInvoker' uiAccess='false'"  -> uac execution level: asinvoker, uac bypass ui protection: false
    # NXCOMPAT                                          -> data execution prevention (dep): image is compatible with dep
    # DYNAMICBASE:NO                                    -> randomized base address: disable image randomization
)

set(DEFAULT_LINKER_FLAGS_DEBUG
    "${WIN32_LINKER_FLAGS} /DEBUG"
    # DEBUG        -> create debug info
)

set(DEFAULT_LINKER_FLAGS_RELEASE
    "${WIN32_LINKER_FLAGS} /OPT:REF /LTCG /OPT:ICF /DELAY:UNLOAD"
    # OPT:REF      -> references: eliminate unreferenced data
    # OPT:ICF      -> enable comdat folding: remove redundant comdats
    # LTCG         -> link time code generation: use link time code generation
    # DELAY:UNLOAD -> delay loaded dll: support unload
)

set(DEFAULT_LIBRARIAN_FLAGS_DEBUG # Flags for the visual c++ librarian (kind of a linker for static libraries)
    "/NOLOGO"
)

set(DEFAULT_LIBRARIAN_FLAGS_RELEASE # Flags for the visual c++ librarian (kind of a linker for static libraries)
    "/NOLOGO /LTCG"
)

# Add platform specific libraries for linking
set(EXTRA_LIBS "")


text:
//
//  InstancedMeshRenderer.cpp
//  Splash
//
//  Created by Kristofer Schlachter on 6/19/14.
//
//

#include "InstancedMeshRenderer.h"
#include "mesh.h"
#include "Texture.h"
#include "ImageUtils.h"
#include "RenderManager.h"

//Get rid of this once we have a texture class working
#include "OpenGLHelper.h"

namespace renderlib{

InstancedMeshRenderer::InstancedMeshRenderer()
{
  _renderSortValue = IRenderable::DefaultSortValue;
}

InstancedMeshRenderer::~InstancedMeshRenderer()
{

  delete _shader;
  delete _cubeMesh;
  delete _roomMesh;
}

void InstancedMeshRenderer::init()
{
  //For now just hard code some stuff in here to see if everything else works!
  _shader = new Shader();
  _shader->registerShader("shaders/vertShader.glsl", ShaderType::VERTEX);
  _shader->registerShader("shaders/fragShader.glsl", ShaderType::FRAGMENT);
  _shader->compileShaders();
  _shader->linkShaders();

  _cubeMesh = new Mesh();
  //_mesh->createScreenQuad(Vector2(-1,-1), Vector2(1,1));
  _cubeMesh->createCube();
  _cubeMesh->bindAttributesToVAO(*_shader);

  _roomMesh = new Mesh();
  //_mesh->createScreenQuad(Vector2(-1,-1), Vector2(1,1));
  _roomMesh->createCube();
  _roomMesh->bindAttributesToVAO(*_shader);
  _mvp.identity();

  _cubeTexture.loadPNG("assets/companion_cube.png",TextureFilterMode::LINEAR, TextureClampMode::CLAMP_TO_EDGE);
  _wallTexture.loadPNG("assets/tiles.png",TextureFilterMode::LINEAR, TextureClampMode::CLAMP_TO_EDGE);
  //_renderTexture.setupFBO(1024,1024,true, GL_RGBA8, GL_RGBA,TextureDataType::TDT_UBYTE);
  //_renderTexture.setupDebugData(Vector2(0.0f, 0.0f), Vector2(1.0f, 1.0f));
  //_renderTexture.setClearColor(Color(0.0f, 0.0f, 0.2f, 1.0f));

}

void InstancedMeshRenderer::update(float time)
{

  // Conversion from Euler angles (in radians) to Quaternion
  //vec3 EulerAngles(time*0.3, time*0.1, 0);
  vec3 EulerAngles(time, time, 0);
  quat q = quat(EulerAngles);
  _m = glm::mat4_cast(q);

  //_m = Matrix4::rotationZYX(Vector3(time*0.2f, time*0.3,0));
  /*
  Point3 EyePosition(0, 0, 5);

  Vector3 up(0, 1, 0); Point3 target(0);
  Matrix4 ViewMatrix = Matrix4::lookAt(EyePosition, target, up);

  _m = Matrix4::rotationZYX(Vector3(time*0.2f, time*0.3,0));
  Matrix4 ModelviewMatrix = ViewMatrix * _m;

  float n = 1.0f;
  float f = 100.0f;
  float fieldOfView = 0.7f;

  Matrix4 ProjectionMatrix = Matrix4::perspective(fieldOfView, 1, n, f);
  _mvp = ProjectionMatrix * ViewMatrix * _m;
  //_m = Matrix4::rotation(-time * 0.25f, Vector3::yAxis());
  _mvpRot = ProjectionMatrix * ViewMatrix * _m;
 */

  //Overriding everything. using camera

}

void InstancedMeshRenderer::preRender()
{

}

void InstancedMeshRenderer::draw()
{
  glDisable(GL_DEPTH_TEST);
  glDisable(GL_CULL_FACE);
  Camera& cam = RenderManager::getInstance().getMainCamera();
  mat4 view = cam.getModelview();
  mat4 proj = cam.getProjection();
  _shader->bind();

  mat4 m = glm::scale(vec3(40,40,40));

  _wallTexture.bindToChannel(0);
  _shader->setUniform("ModelViewProjection", proj * view * m);
  _shader->setUniform("ModelView", view * m);
  _shader->setUniform("NormalTransform", m);
  _shader->setUniform("texture0", 0);
  _roomMesh->drawBuffers();

  glEnable(GL_DEPTH_TEST);
  glEnable(GL_CULL_FACE);
  _cubeTexture.bindToChannel(0);
  _shader->setUniform("ModelViewProjection", proj * view * _m);
  _shader->setUniform("ModelView", view * _m);
  _shader->setUniform("NormalTransform", _m);
  _shader->setUniform("texture0", 0);
  _cubeMesh->drawBuffers();

  _shader->unbind();
}

void InstancedMeshRenderer::postRender()
{

}

}// namespace renderlib


text:
extern "C" long __cdecl _InterlockedIncrement( long volatile * );
extern "C" long __cdecl _InterlockedDecrement( long volatile * );
extern "C" long __cdecl _InterlockedCompareExchange( long volatile *, long, long );
extern "C" long __cdecl _InterlockedExchange( long volatile *, long );
extern "C" long __cdecl _InterlockedExchangeAdd( long volatile *, long );

# define NDNBOOST_INTERLOCKED_INCREMENT _InterlockedIncrement
# define NDNBOOST_INTERLOCKED_DECREMENT _InterlockedDecrement
# define NDNBOOST_INTERLOCKED_COMPARE_EXCHANGE _InterlockedCompareExchange
# define NDNBOOST_INTERLOCKED_EXCHANGE _InterlockedExchange
# define NDNBOOST_INTERLOCKED_EXCHANGE_ADD _InterlockedExchangeAdd

#else
// under Windows CE we still have old-style Interlocked* functions

extern "C" long __cdecl InterlockedIncrement( long* );
extern "C" long __cdecl InterlockedDecrement( long* );
extern "C" long __cdecl InterlockedCompareExchange( long*, long, long );
extern "C" long __cdecl InterlockedExchange( long*, long );
extern "C" long __cdecl InterlockedExchangeAdd( long*, long );

# define NDNBOOST_INTERLOCKED_INCREMENT InterlockedIncrement
# define NDNBOOST_INTERLOCKED_DECREMENT InterlockedDecrement
# define NDNBOOST_INTERLOCKED_COMPARE_EXCHANGE InterlockedCompareExchange
# define NDNBOOST_INTERLOCKED_EXCHANGE InterlockedExchange
# define NDNBOOST_INTERLOCKED_EXCHANGE_ADD InterlockedExchangeAdd

#endif

# define NDNBOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest,exchange,compare) \
    ((void*)NDNBOOST_INTERLOCKED_COMPARE_EXCHANGE((long*)(dest),(long)(exchange),(long)(compare)))
# define NDNBOOST_INTERLOCKED_EXCHANGE_POINTER(dest,exchange) \
    ((void*)NDNBOOST_INTERLOCKED_EXCHANGE((long*)(dest),(long)(exchange)))

#elif defined( NDNBOOST_MSVC ) || defined( NDNBOOST_INTEL_WIN )

#if defined( NDNBOOST_MSVC ) && NDNBOOST_MSVC >= 1600

#include <intrin.h>

#elif defined( __CLRCALL_PURE_OR_CDECL )

extern "C" long __CLRCALL_PURE_OR_CDECL _InterlockedIncrement( long volatile * );
extern "C" long __CLRCALL_PURE_OR_CDECL _InterlockedDecrement( long volatile * );
extern "C" long __CLRCALL_PURE_OR_CDECL _InterlockedCompareExchange( long volatile *, long, long );
extern "C" long __CLRCALL_PURE_OR_CDECL _InterlockedExchange( long volatile *, long );
extern "C" long __CLRCALL_PURE_OR_CDECL _InterlockedExchangeAdd( long volatile *, long );

#else

extern "C" long __cdecl _InterlockedIncrement( long volatile * );
extern "C" long __cdecl _InterlockedDecrement( long volatile * );
extern "C" long __cdecl _InterlockedCompareExchange( long volatile *, long, long );
extern "C" long __cdecl _InterlockedExchange( long volatile *, long );
extern "C" long __cdecl _InterlockedExchangeAdd( long volatile *, long );

#endif

# pragma intrinsic( _InterlockedIncrement )
# pragma intrinsic( _InterlockedDecrement )
# pragma intrinsic( _InterlockedCompareExchange )
# pragma intrinsic( _InterlockedExchange )
# pragma intrinsic( _InterlockedExchangeAdd )

# if defined(_M_IA64) || defined(_M_AMD64)

extern "C" void* __cdecl _InterlockedCompareExchangePointer( void* volatile *, void*, void* );
extern "C" void* __cdecl _InterlockedExchangePointer( void* volatile *, void* );

#  pragma intrinsic( _InterlockedCompareExchangePointer )
#  pragma intrinsic( _InterlockedExchangePointer )

#  define NDNBOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER _InterlockedCompareExchangePointer
#  define NDNBOOST_INTERLOCKED_EXCHANGE_POINTER _InterlockedExchangePointer

# else

#  define NDNBOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest,exchange,compare) \
    ((void*)NDNBOOST_INTERLOCKED_COMPARE_EXCHANGE((long volatile*)(dest),(long)(exchange),(long)(compare)))
#  define NDNBOOST_INTERLOCKED_EXCHANGE_POINTER(dest,exchange) \
    ((void*)NDNBOOST_INTERLOCKED_EXCHANGE((long volatile*)(dest),(long)(exchange)))

# endif

# define NDNBOOST_INTERLOCKED_INCREMENT _InterlockedIncrement
# define NDNBOOST_INTERLOCKED_DECREMENT _InterlockedDecrement
# define NDNBOOST_INTERLOCKED_COMPARE_EXCHANGE _InterlockedCompareExchange
# define NDNBOOST_INTERLOCKED_EXCHANGE _InterlockedExchange
# define NDNBOOST_INTERLOCKED_EXCHANGE_ADD _InterlockedExchangeAdd

#elif defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32__ ) || defined( __CYGWIN__ )

#if defined(__MINGW64__)
#define NDNBOOST_INTERLOCKED_IMPORT
#else
#define NDNBOOST_INTERLOCKED_IMPORT __declspec(dllimport)
#endif

namespace ndnboost
{

namespace detail
{

extern "C" NDNBOOST_INTERLOCKED_IMPORT long __stdcall InterlockedIncrement( long volatile * );
extern "C" NDNBOOST_INTERLOCKED_IMPORT long __stdcall InterlockedDecrement( long volatile * );
extern "C" NDNBOOST_INTERLOCKED_IMPORT long __stdcall InterlockedCompareExchange( long volatile *, long, long );
extern "C" NDNBOOST_INTERLOCKED_IMPORT long __stdcall InterlockedExchange( long volatile *, long );
extern "C" NDNBOOST_INTERLOCKED_IMPORT long __stdcall InterlockedExchangeAdd( long volatile *, long );

# if defined(_M_IA64) || defined(_M_AMD64)
extern "C" NDNBOOST_INTERLOCKED_IMPORT void* __stdcall InterlockedCompareExchangePointer( void* volatile *, void*, void* );
extern "C" NDNBOOST_INTERLOCKED_IMPORT void* __stdcall InterlockedExchangePointer( void* volatile *, void* );
# endif

} // namespace detail

} // namespace ndnboost

# define NDNBOOST_INTERLOCKED_INCREMENT ::ndnboost::detail::InterlockedIncrement
# define NDNBOOST_INTERLOCKED_DECREMENT ::ndnboost::detail::InterlockedDecrement
# define NDNBOOST_INTERLOCKED_COMPARE_EXCHANGE ::ndnboost::detail::InterlockedCompareExchange
# define NDNBOOST_INTERLOCKED_EXCHANGE ::ndnboost::detail::InterlockedExchange
# define NDNBOOST_INTERLOCKED_EXCHANGE_ADD ::ndnboost::detail::InterlockedExchangeAdd

# if defined(_M_IA64) || defined(_M_AMD64)
#  define NDNBOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER ::ndnboost::detail::InterlockedCompareExchangePointer
#  define NDNBOOST_INTERLOCKED_EXCHANGE_POINTER ::ndnboost::detail::InterlockedExchangePointer
# else
#  define NDNBOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest,exchange,compare) \
    ((void*)NDNBOOST_INTERLOCKED_COMPARE_EXCHANGE((long volatile*)(dest),(long)(exchange),(long)(compare)))
#  define NDNBOOST_INTERLOCKED_EXCHANGE_POINTER(dest,exchange) \
    ((void*)NDNBOOST_INTERLOCKED_EXCHANGE((long volatile*)(dest),(long)(exchange)))
# endif

#else

# error "Interlocked intrinsics not available"

#endif

#endif // #ifndef NDNBOOST_DETAIL_INTERLOCKED_HPP_INCLUDED


text:
package lsh.ext.gson.ext.java.time;

import java.time.Month;

import com.google.gson.TypeAdapter;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lsh.ext.gson.adapters.AbstractToStringStringTypeAdapter;

/**
 * A type adapter for {@link Month}.
 *
 * @author Lyubomyr Shaydariv
 */
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public final class MonthTypeAdapter
		extends AbstractToStringStringTypeAdapter<Month> {

	private static final TypeAdapter<Month> instance = new MonthTypeAdapter();

	/**
	 * @return An instance of {@link MonthTypeAdapter}.
	 */
	public static TypeAdapter<Month> getInstance() {
		return instance;
	}

	@Override
	protected Month fromString(final String string) {
		return Month.valueOf(string);
	}

}


text:
package io.fabric8.karaf.cm;

import java.util.Dictionary;
import java.util.concurrent.atomic.AtomicReference;

import io.fabric8.karaf.core.properties.PlaceholderResolver;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.ConfigurationPolicy;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.Service;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.ConfigurationPlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static io.fabric8.karaf.cm.KubernetesConstants.FABRIC8_CONFIG_PLUGIN_ENABLED;
import static io.fabric8.karaf.cm.KubernetesConstants.FABRIC8_CONFIG_PLUGIN_ENABLED_DEFAULT;
import static io.fabric8.kubernetes.client.utils.Utils.getSystemPropertyOrEnvVar;

@Component(
    immediate = true,
    policy = ConfigurationPolicy.IGNORE,
    createPid = false
)
@Reference(
    name = "resolver",
    cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE,
    policy = ReferencePolicy.DYNAMIC,
    referenceInterface = PlaceholderResolver.class
)
@Properties({
    @Property(name = ConfigurationPlugin.CM_RANKING, value = "10", classValue = Integer.class)
})
@Service(ConfigurationPlugin.class)
public class PlaceholderResolverConfigurationPlugin implements ConfigurationPlugin {
    private static final Logger LOGGER = LoggerFactory.getLogger(PlaceholderResolverConfigurationPlugin.class);

    private final AtomicReference<PlaceholderResolver> resolver;
    private boolean enabled;

    public PlaceholderResolverConfigurationPlugin() {
        this.resolver = new AtomicReference<>();
        this.enabled = FABRIC8_CONFIG_PLUGIN_ENABLED_DEFAULT;
    }

    // ***********************
    // Lifecycle
    // ***********************

    @Activate
    void activate() {
        enabled = getSystemPropertyOrEnvVar(FABRIC8_CONFIG_PLUGIN_ENABLED, enabled);
        LOGGER.debug("Configuration update is {}", enabled ? "ENABLED" : "DISABLED");
    }

    // ****************************
    // Binding
    // ****************************

    protected void bindResolver(PlaceholderResolver resolver) {
        this.resolver.set(resolver);
    }

    protected void unbindResolver(PlaceholderResolver resolver) {
        this.resolver.compareAndSet(resolver, null);
    }

    // ***********************
    // ConfigurationPlugin
    // ***********************

    @Override
    public void modifyConfiguration(ServiceReference<?> reference, Dictionary<String, Object> dictionary) {
        PlaceholderResolver res = resolver.get();
        if (enabled && res != null) {
            res.replaceAll(dictionary);
        }
    }
}


text:
using pegleg.cs.Unicode;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace pegleg.cs.Parsing.Expressions {
  public class CodePointParsingExpression : BaseParsingExpression<Nil> {
    private readonly ICodePointCriteria _criteria;

    public CodePointParsingExpression(ICodePointCriteria criteria) {
      if(null == criteria) throw Xception.Because.ArgumentNull(() => criteria);

      _criteria = criteria;
    }

    public override IMatchingResult<Nil> Matches(MatchingContext context) {
      int length;
      if(context.ConsumesCodePointCriteria(_criteria, out length))
        return SuccessfulMatchingResult.Create(Nil.Value, length);

      return UnsuccessfulMatchingResult.Create(this);
    }

    public override T HandleWith<T>(IParsingExpressionHandler<T> handler) {
      return handler.Handle(this);
    }
  }
}


text:
import java.io.IOException;
import java.util.Scanner;

public class LimpaConsole {
    public static void main(String[] args) throws IOException, InterruptedException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Teste");
        String texto = scanner.next();

        //Limpa a tela no windows, no linux e no MacOS
        if (System.getProperty("os.name").contains("Windows"))
            new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
        else
            Runtime.getRuntime().exec("clear");

    }
}


text:
/* extracted/borrowed from https://github.com/dundalek/recline-warehouse */
/*jshint multistr:true */

this.recline = this.recline || {};
this.recline.View = this.recline.View || {};

(function(_, $, my) {

/** Export View */
my.Export = Backbone.View.extend({
  className: 'recline-export-view',
  template: _.template(
    '
Export
 \

  \

 \
        <% _.each(exporters, function(item, idx) { %> \
        <a href="#" class="btn btn-default <%- idx === exporter ? \'active\' : \'\' %> exporter" data-exporter="<%- idx %>"><%- item.label %> \
        <% }); %> \

 \
      <% if (options.size) { %> \
      <button class="export-all btn btn-primary">Export all</button> \
      <% } %> \
       \
        <input type="checkbox" class="include-headers" <%- options.includeHeaders ? \'checked="checked"\' : \'\' %> > Include headers \
       \

 \
    <% if (preview) { %> \

 \

Preview
 \
      <textarea class="form-control export-preview"><%- preview %></textarea> \

 \
    <% } %>'
  ),
  events: {
    'click .export-all': 'onExportAll',
    'click a.exporter': 'onExporterChange',
    'change .include-headers': 'onIncludeHeadersChange'
  },

  exporters: [
    {
      label: 'CSV',
      fn: recline.Data.Export.CSV,
      charset: 'text/csv'
    },
    // {
    //   label: 'JSON',
    //   fn: recline.Data.Export.JSON,
    //   charset: 'text/attachment'
    // }
  ],

  initialize: function() {
    this.options = _.extend({size: 10, includeHeaders: false}, this.options);
    this.el = $(this.el);
    this.exporter = 0;
    this.render();

    this.model.records.on('reset', this.render, this);
    if (this.options.grid) {
      this.options.grid.state.on('change', this.render, this);
    }
  },

  render: function() {
    var fields = this.model.fields.pluck('id');

    // load column info from grid
    if (this.options.grid) {
      var grid = this.options.grid;
      // change order of columns
      var gridFields = grid.state.get('columnsOrder');
      if (gridFields.length > 0) {
        fields = gridFields;
      }
      // do not export hidden columns
      fields = _.difference(fields, grid.state.get('hiddenColumns'));
    }

    // setup options for exporter
    var opts = {
      fields: fields,
      headers: this.options.includeHeaders
    };
    if (this.options.size) {
      opts.size = this.options.size;
    }

    // export and render
    this.preview = this.exporters[this.exporter].fn(this.model, opts);
    var htmls = this.template(this);
    this.el.html(htmls);
  },

  onExporterChange: function(e) {
    e.preventDefault();
    this.exporter = parseInt($(e.target).attr('data-exporter'));
    this.render();
  },

  onIncludeHeadersChange: function(e) {
    this.options.includeHeaders = $(e.target).is(':checked');
    this.render();
  },

  onExportAll: function(e) {
    var size = this.options.size;
    // display all data and send to browser to download
    this.options.size = null;
    var exporter_id = parseInt($(".exporter-group .active").data("exporter"))
    var exporting_as = this.exporters[exporter_id]
    console.log(exporting_as)
    this.render();
    document.location.href = 'data:'+exporting_as.charset+';charset=utf-8,'+encodeURIComponent($("textarea.export-preview").last().html())
    // set size back to normal
    this.options.size = size;
  }
});

})(_, jQuery, recline.View);


text:
package org.itevents.service.transactional;

import org.itevents.dao.CityDao;
import org.itevents.model.City;
import org.itevents.service.CityService;
import org.itevents.test_utils.BuilderUtil;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/applicationContext.xml"})
@Transactional
public class MyBatisCityServiceTest {

    @InjectMocks
    @Inject
    private CityService cityService;
    @Mock
    private CityDao cityDao;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void shouldFindCityById() throws Exception {
        int ID_1 = 1;

        cityService.getCity(ID_1);

        verify(cityDao).getCity(ID_1);
    }

    @Test
    public void shouldAddCity() throws Exception {
        City testCity = BuilderUtil.buildCityTest();

        cityService.addCity(testCity);

        verify(cityDao).addCity(testCity);
    }

    @Test
    public void shouldGetAllCities() {
        cityService.getAllCities();

        verify(cityDao).getAllCities();
    }

    @Test
    public void shouldRemoveCity() {
        City expectedCity = BuilderUtil.buildCityTest();

        when(cityDao.getCity(expectedCity.getId())).thenReturn(expectedCity);
        doNothing().when(cityDao).removeCity(expectedCity);

        City returnedCity = cityService.removeCity(expectedCity);

        verify(cityDao).getCity(expectedCity.getId());
        verify(cityDao).removeCity(expectedCity);
        assertEquals(expectedCity, returnedCity);
    }

    @Test
    public void shouldNotRemoveNonExistingCity() {
        City testCity = BuilderUtil.buildCityTest();

        when(cityDao.getCity(testCity.getId())).thenReturn(null);
        doNothing().when(cityDao).removeCity(testCity);

        City returnedCity = cityService.removeCity(testCity);

        verify(cityDao).getCity(testCity.getId());
        verify(cityDao, never()).removeCity(any(City.class));
        assertNull(returnedCity);
    }
}


text:
<?xml version='1.0'?>
<root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
       xsi:noNamespaceSchemaLocation="unsignedByte.xsd" >
  <complexTest>
  <!-- value=256 -->
    <comp_foo>256</comp_foo>
  </complexTest>

  <simpleTest>256</simpleTest>
</root>


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace UmbracoVault.TypeHandlers
{
    public interface ITypeHandler
    {
        /// <summary>
        /// Returns a strongly-typed object given a object value of it, and its expected type
        /// </summary>
        /// <typeparam name="T">The expected type to be returned</typeparam>
        /// <param name="input">The object representation of the desired value</param>
        /// <returns>A strongly-typed representation of the value</returns>
        object GetAsType<T>(object input);

        /// <summary>
        /// Returns the type supported by this TypeHandler
        /// </summary>
        Type TypeSupported { get; }
    }
}


text:
package com.elderbyte.vidada.domain.documents.browser.router;

import com.elderbyte.common.ArgumentNullException;
import org.springframework.util.StringUtils;

public class RouteMapping<T> implements Comparable<RouteMapping> {

        private final String pathTemplate;
        private final BrowseRouteHandler<T> handler;

        private final int deepness;

        public RouteMapping(String pathTemplate, BrowseRouteHandler handler) {

            if(pathTemplate == null) throw new ArgumentNullException("pathTemplate");
            if(handler == null) throw new ArgumentNullException("handler");

            this.pathTemplate = pathTemplate;
            this.handler = handler;
            this.deepness = StringUtils.countOccurrencesOf(pathTemplate, "/");
        }

        public String getPathTemplate() {
            return pathTemplate;
        }

        public BrowseRouteHandler<T> getHandler() {
            return handler;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            RouteMapping that = (RouteMapping) o;

            return pathTemplate.equals(that.pathTemplate);
        }

        @Override
        public int hashCode() {
            return pathTemplate.hashCode();
        }

        @Override
        public int compareTo(RouteMapping o) {
            int cmp = Integer.compare(this.deepness, o.deepness);
            return cmp != 0 ? cmp : pathTemplate.compareTo(o.pathTemplate);
        }
    }


text:
'''Various helpers for doing advanced things with dictionaries.'''

def get_fields(s):
    '''Return a set of field names referenced as formatting keys in the given
    string. I thought there would be an easier way to get this, but I can't
    find one. E.g. get_fields('%(hello)s %(world)s') returns
    set('hello', 'world').'''
    class FakeDict(dict):
        def __init__(self):
            super(FakeDict, self).__init__()
            self.referenced = set()
        def __getitem__(self, key):
            self.referenced.add(key)
            return ''
    f = FakeDict()
    s % f # Value deliberately discarded
    return f.referenced

class Guard(object):
    '''Representation of a condition required for some action. See usage in
    Template.py.'''
    def __init__(self, guard_fn):
        self.guard_fn = guard_fn

    def __call__(self, arg):
        return self.guard_fn(arg)


text:
META = {
        'author': 'George Argyros, Ioannis Stais',
        'description': 'Folder containing grammars',
        'type':'Folder',
        'comments': []
}


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Network.Models
{
    public partial class BastionActiveSession
    {
        internal static BastionActiveSession DeserializeBastionActiveSession(JsonElement element)
        {
            Optional<string> sessionId = default;
            Optional<object> startTime = default;
            Optional<string> targetSubscriptionId = default;
            Optional<string> resourceType = default;
            Optional<string> targetHostName = default;
            Optional<string> targetResourceGroup = default;
            Optional<string> userName = default;
            Optional<string> targetIpAddress = default;
            Optional<BastionConnectProtocol> protocol = default;
            Optional<string> targetResourceId = default;
            Optional<float> sessionDurationInMins = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("sessionId"))
                {
                    sessionId = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("startTime"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    startTime = property.Value.GetObject();
                    continue;
                }
                if (property.NameEquals("targetSubscriptionId"))
                {
                    targetSubscriptionId = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("resourceType"))
                {
                    resourceType = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("targetHostName"))
                {
                    targetHostName = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("targetResourceGroup"))
                {
                    targetResourceGroup = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("userName"))
                {
                    userName = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("targetIpAddress"))
                {
                    targetIpAddress = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("protocol"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    protocol = new BastionConnectProtocol(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("targetResourceId"))
                {
                    targetResourceId = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("sessionDurationInMins"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    sessionDurationInMins = property.Value.GetSingle();
                    continue;
                }
            }
            return new BastionActiveSession(sessionId.Value, startTime.Value, targetSubscriptionId.Value, resourceType.Value, targetHostName.Value, targetResourceGroup.Value, userName.Value, targetIpAddress.Value, Optional.ToNullable(protocol), targetResourceId.Value, Optional.ToNullable(sessionDurationInMins));
        }
    }
}


text:
module Main where

import TurnirShell

main :: IO ()
main = run