text:
<resources>

    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>

    <dimen name="fab_size_normal">56dp</dimen>
    <dimen name="fab_size_mini">40dp</dimen>
    <dimen name="fab_shadow_size">8dp</dimen>
    <dimen name="fab_mini_shadow_size">6dp</dimen>

    <dimen name="fab_min_significant_scroll">4dp</dimen>
    <dimen name="fab_elevation_lollipop">5dp</dimen>

    <dimen name="action_bar_elevation">7.5dp</dimen>
    <dimen name="profile_list_elevation">55dp</dimen>
    <dimen name="profile_view_edit_elevation">45dp</dimen>

    <dimen name="fab_padding">16dp</dimen>

    <dimen name="list_view_padding">16dp</dimen>
    <dimen name="toast_y_offset">64dp</dimen>

    <dimen name="adb_shell_command">12sp</dimen>
    <dimen name="logo_margin">20.51dp</dimen>
</resources>


text:
title:  "原生 Kubernetes 设置"
nav-title: Native Kubernetes
nav-parent_id: deployment
is_beta: true
nav-pos: 7
---

This page describes how to deploy a Flink session cluster natively on [Kubernetes](https://kubernetes.io).

* This will be replaced by the TOC
{:toc}

Flink's native Kubernetes integration is still experimental. There may be changes in the configuration and CLI flags in latter versions.

## Requirements

- Kubernetes 1.9 or above.
- KubeConfig, which has access to list, create, delete pods and services, configurable via `~/.kube/config`. You can verify permissions by running `kubectl auth can-i <list|create|edit|delete> pods`.
- Kubernetes DNS enabled.
- A service Account with [RBAC](#rbac) permissions to create, delete pods.

## Flink Kubernetes Session

### Start Flink Session

Follow these instructions to start a Flink Session within your Kubernetes cluster.

A session will start all required Flink services (JobManager and TaskManagers) so that you can submit programs to the cluster.
Note that you can run multiple programs per session.

{% highlight bash %}
$ ./bin/kubernetes-session.sh
{% endhighlight %}

All the Kubernetes configuration options can be found in our [configuration guide]({{ site.baseurl }}/zh/ops/config.html#kubernetes).

**Example**: Issue the following command to start a session cluster with 4 GB of memory and 2 CPUs with 4 slots per TaskManager:

In this example we override the `resourcemanager.taskmanager-timeout` setting to make
the pods with task managers remain for a longer period than the default of 30 seconds.
Although this setting may cause more cloud cost it has the effect that starting new jobs is in some scenarios
faster and during development you have more time to inspect the logfiles of your job.

{% highlight bash %}
$ ./bin/kubernetes-session.sh \
  -Dkubernetes.cluster-id=<ClusterId> \
  -Dtaskmanager.memory.process.size=4096m \
  -Dkubernetes.taskmanager.cpu=2 \
  -Dtaskmanager.numberOfTaskSlots=4 \
  -Dresourcemanager.taskmanager-timeout=3600000
{% endhighlight %}

The system will use the configuration in `conf/flink-conf.yaml`.
Please follow our [configuration guide]({{ site.baseurl }}/zh/ops/config.html) if you want to change something.

If you do not specify a particular name for your session by `kubernetes.cluster-id`, the Flink client will generate a UUID name.

### Custom Flink Docker image

If you want to use a custom Docker image to deploy Flink containers, check [the Flink Docker image documentation](docker.html),
[its tags](docker.html#image-tags), [how to customize the Flink Docker image](docker.html#customize-flink-image) and [enable plugins](docker.html#using-plugins).
If you created a custom Docker image you can provide it by setting the [`kubernetes.container.image`](../config.html#kubernetes-container-image) configuration option:

{% highlight bash %}
$ ./bin/kubernetes-session.sh \
  -Dkubernetes.cluster-id=<ClusterId> \
  -Dtaskmanager.memory.process.size=4096m \
  -Dkubernetes.taskmanager.cpu=2 \
  -Dtaskmanager.numberOfTaskSlots=4 \
  -Dresourcemanager.taskmanager-timeout=3600000 \
  -Dkubernetes.container.image=<CustomImageName>
{% endhighlight %}

### Submitting jobs to an existing Session

Use the following command to submit a Flink Job to the Kubernetes cluster.

{% highlight bash %}
$ ./bin/flink run -d -e kubernetes-session -Dkubernetes.cluster-id=<ClusterId> examples/streaming/WindowJoin.jar
{% endhighlight %}

### Accessing Job Manager UI

There are several ways to expose a Service onto an external (outside of your cluster) IP address.
This can be configured using `kubernetes.service.exposed.type`.

- `ClusterIP`: Exposes the service on a cluster-internal IP.
The Service is only reachable within the cluster. If you want to access the Job Manager ui or submit job to the existing session, you need to start a local proxy.
You can then use `localhost:8081` to submit a Flink job to the session or view the dashboard.

{% highlight bash %}
$ kubectl port-forward service/<ServiceName> 8081
{% endhighlight %}

- `NodePort`: Exposes the service on each Node's IP at a static port (the `NodePort`). `<NodeIP>:<NodePort>` could be used to contact the Job Manager Service. `NodeIP` could be easily replaced with Kubernetes ApiServer address.
You could find it in your kube config file.

- `LoadBalancer`: Default value, exposes the service externally using a cloud provider's load balancer.
Since the cloud provider and Kubernetes needs some time to prepare the load balancer, you may get a `NodePort` JobManager Web Interface in the client log.
You can use `kubectl get services/<ClusterId>` to get EXTERNAL-IP and then construct the load balancer JobManager Web Interface manually `http://<EXTERNAL-IP>:8081`.

- `ExternalName`: Map a service to a DNS name, not supported in current version.

Please reference the official documentation on [publishing services in Kubernetes](https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types) for more information.

### Attach to an existing Session

The Kubernetes session is started in detached mode by default, meaning the Flink client will exit after submitting all the resources to the Kubernetes cluster. Use the following command to attach to an existing session.

{% highlight bash %}
$ ./bin/kubernetes-session.sh -Dkubernetes.cluster-id=<ClusterId> -Dexecution.attached=true
{% endhighlight %}

### Stop Flink Session

To stop a Flink Kubernetes session, attach the Flink client to the cluster and type `stop`.

{% highlight bash %}
$ echo 'stop' | ./bin/kubernetes-session.sh -Dkubernetes.cluster-id=<ClusterId> -Dexecution.attached=true
{% endhighlight %}

#### Manual Resource Cleanup

Flink uses [Kubernetes OwnerReference's](https://kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/) to cleanup all cluster components.
All the Flink created resources, including `ConfigMap`, `Service`, `Pod`, have been set the OwnerReference to `deployment/<ClusterId>`.
When the deployment is deleted, all other resources will be deleted automatically.

{% highlight bash %}
$ kubectl delete deployment/<ClusterID>
{% endhighlight %}

## Log Files

By default, the JobManager and TaskManager only store logs under `/opt/flink/log` in each pod.
If you want to use `kubectl logs <PodName>` to view the logs, you must perform the following:

1. Add a new appender to the log4j.properties in the Flink client.
2. Add the following 'appenderRef' the rootLogger in log4j.properties `rootLogger.appenderRef.console.ref = ConsoleAppender`.
3. Remove the redirect args by adding config option `-Dkubernetes.container-start-command-template="%java% %classpath% %jvmmem% %jvmopts% %logging% %class% %args%"`.
4. Stop and start your session again. Now you could use `kubectl logs` to view your logs.

{% highlight bash %}
# Log all infos to the console
appender.console.name = ConsoleAppender
appender.console.type = CONSOLE
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %-60c %x - %m%n
{% endhighlight %}

If the pod is running, you can use `kubectl exec -it <PodName> bash` to tunnel in and view the logs or debug the process.

## Flink Kubernetes Application

### Start Flink Application

Application mode allows users to create a single image containing their Job and the Flink runtime, which will automatically create and destroy cluster components as needed. The Flink community provides base docker images [customized](docker.html#customize-flink-image) for any use case.

{% highlight dockerfile %}
FROM flink
RUN mkdir -p $FLINK_HOME/usrlib
COPY /path/of/my-flink-job-*.jar $FLINK_HOME/usrlib/my-flink-job.jar
{% endhighlight %}

Use the following command to start a Flink application.
{% highlight bash %}
$ ./bin/flink run-application -p 8 -t kubernetes-application \
  -Dkubernetes.cluster-id=<ClusterId> \
  -Dtaskmanager.memory.process.size=4096m \
  -Dkubernetes.taskmanager.cpu=2 \
  -Dtaskmanager.numberOfTaskSlots=4 \
  -Dkubernetes.container.image=<CustomImageName> \
  local:///opt/flink/usrlib/my-flink-job.jar
{% endhighlight %}

Note: Only "local" is supported as schema for application mode. This assumes that the jar is located in the image, not the Flink client.

Note: All the jars in the "$FLINK_HOME/usrlib" directory in the image will be added to user classpath.

### Stop Flink Application

When an application is stopped, all Flink cluster resources are automatically destroyed.
As always, Jobs may stop when manually canceled or, in the case of bounded Jobs, complete.

{% highlight bash %}
$ ./bin/flink cancel -t kubernetes-application -Dkubernetes.cluster-id=<ClusterID> <JobID>
{% endhighlight %}

## Kubernetes concepts

### Namespaces

[Namespaces in Kubernetes](https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/) are a way to divide cluster resources between multiple users (via resource quota).
It is similar to the queue concept in Yarn cluster. Flink on Kubernetes can use namespaces to launch Flink clusters.
The namespace can be specified using the `-Dkubernetes.namespace=default` argument when starting a Flink cluster.

[ResourceQuota](https://kubernetes.io/docs/concepts/policy/resource-quotas/) provides constraints that limit aggregate resource consumption per namespace.
It can limit the quantity of objects that can be created in a namespace by type, as well as the total amount of compute resources that may be consumed by resources in that project.

### RBAC

Role-based access control ([RBAC](https://kubernetes.io/docs/reference/access-authn-authz/rbac/)) is a method of regulating access to compute or network resources based on the roles of individual users within an enterprise.
Users can configure RBAC roles and service accounts used by Flink JobManager to access the Kubernetes API server within the Kubernetes cluster.

Every namespace has a default service account, however, the `default` service account may not have the permission to create or delete pods within the Kubernetes cluster.
Users may need to update the permission of `default` service account or specify another service account that has the right role bound.

{% highlight bash %}
$ kubectl create clusterrolebinding flink-role-binding-default --clusterrole=edit --serviceaccount=default:default
{% endhighlight %}

If you do not want to use `default` service account, use the following command to create a new `flink` service account and set the role binding.
Then use the config option `-Dkubernetes.jobmanager.service-account=flink` to make the JobManager pod using the `flink` service account to create and delete TaskManager pods.

{% highlight bash %}
$ kubectl create serviceaccount flink
$ kubectl create clusterrolebinding flink-role-binding-flink --clusterrole=edit --serviceaccount=default:flink
{% endhighlight %}

Please reference the official Kubernetes documentation on [RBAC Authorization](https://kubernetes.io/docs/reference/access-authn-authz/rbac/) for more information.

## Background / Internals

This section briefly explains how Flink and Kubernetes interact.

When creating a Flink Kubernetes session cluster, the Flink client will first connect to the Kubernetes ApiServer to submit the cluster description, including ConfigMap spec, Job Manager Service spec, Job Manager Deployment spec and Owner Reference.
Kubernetes will then create the Flink master deployment, during which time the Kubelet will pull the image, prepare and mount the volume, and then execute the start command.
After the master pod has launched, the Dispatcher and KubernetesResourceManager are available and the cluster is ready to accept one or more jobs.

When users submit jobs through the Flink client, the job graph will be generated by the client and uploaded along with users jars to the Dispatcher.
A JobMaster for that Job will be then be spawned.

The JobMaster requests resources, known as slots, from the KubernetesResourceManager.
If no slots are available, the resource manager will bring up TaskManager pods and registering them with the cluster.

{% top %}

redpajama_set_name: RedPajamaGithub


text:
var constants = {
    conversationUrl : "/api/v1/conversation/",
    feedbackUrl     : "/api/v1/feedback/",
    visitLevels     : Object.freeze({
        NONE    : 0,
        WELCOME : 1,
        POPUP   : 2
    }),
    showPopupCount : 3,
    visitLevelKey : "visitLevel",
    refinementQueryType : "REFINEMENT"
};

if (typeof(module) !== 'undefined') module.exports = constants;


text:
%{
  version: "1.0.2",
  title: "Sigils",
  excerpt: """
  Working with and creating sigils.
  """
}
---

## Sigils Overview

Elixir provides an alternative syntax for representing and working with literals.
A sigil will start with a tilde `~` followed by a character.
The Elixir core provides us with some built in sigils however, it is possible to create our own when we need to extend the language.

A list of available sigils include:

- `~C` Generates a character list **with no** escaping or interpolation
- `~c` Generates a character list **with** escaping and interpolation
- `~R` Generates a regular expression **with no** escaping or interpolation
- `~r` Generates a regular expression **with** escaping and interpolation
- `~S` Generates a string **with no** escaping or interpolation
- `~s` Generates a string **with** escaping and interpolation
- `~W` Generates a word list **with no** escaping or interpolation
- `~w` Generates a word list **with** escaping and interpolation
- `~N` Generates a `NaiveDateTime` struct
- `~U` Generates a `DateTime` struct (since Elixir 1.9.0)

A list of delimiters include:

- `<...>` A pair of pointy brackets
- `{...}` A pair of curly brackets
- `[...]` A pair of square brackets
- `(...)` A pair of parentheses
- `|...|` A pair of pipes
- `/.../` A pair of forward slashes
- `"..."` A pair of double quotes
- `'...'` A pair of single quotes

### Char List

The `~c` and `~C` sigils generate character lists respectively.
For example:

```elixir
iex> ~c/2 + 7 = #{2 + 7}/
'2 + 7 = 9'

iex> ~C/2 + 7 = #{2 + 7}/
'2 + 7 = \#{2 + 7}'
```

We can see the lowercased `~c` interpolates the calculation, whereas the uppercased `~C` sigil does not.
We will see that this uppercase / lowercase sequence is a common theme throughout the built in sigils.

### Regular Expressions

The `~r` and `~R` sigils are used to represent Regular Expressions.
We create them either on the fly or for use within the `Regex` functions.
For example:

```elixir
iex> re = ~r/elixir/
~r/elixir/

iex> "Elixir" =~ re
false

iex> "elixir" =~ re
true
```

We can see that in the first test for equality, that `Elixir` does not match with the regular expression.
This is because it is capitalized.
Because Elixir supports Perl Compatible Regular Expressions (PCRE), we can append `i` to the end of our sigil to turn off case sensitivity.

```elixir
iex> re = ~r/elixir/i
~r/elixir/i

iex> "Elixir" =~ re
true

iex> "elixir" =~ re
true
```

Further, Elixir provides the [Regex](https://hexdocs.pm/elixir/Regex.html) API which is built on top of Erlang's regular expression library.
Let's use `Regex.split/2` with a regex sigil:

```elixir
iex> string = "100_000_000"
"100_000_000"

iex> Regex.split(~r/_/, string)
["100", "000", "000"]
```

As we can see, the string `"100_000_000"` is split on the underscore thanks to our `~r/_/` sigil.
The `Regex.split` function returns a list.

### String

The `~s` and `~S` sigils are used to generate string data.
For example:

```elixir
iex> ~s/the cat in the hat on the mat/
"the cat in the hat on the mat"

iex> ~S/the cat in the hat on the mat/
"the cat in the hat on the mat"
```

What is the difference? The difference is similar to the Character List sigil that we looked at.
The answer is interpolation and the use of escape sequences.
If we take another example:

```elixir
iex> ~s/welcome to elixir #{String.downcase "SCHOOL"}/
"welcome to elixir school"

iex> ~S/welcome to elixir #{String.downcase "SCHOOL"}/
"welcome to elixir \#{String.downcase \"SCHOOL\"}"
```

### Word List

The word list sigil can come in handy from time to time.
It can save both time, keystrokes and arguably reduce the complexity within the codebase.
Take this simple example:

```elixir
iex> ~w/i love elixir school/
["i", "love", "elixir", "school"]

iex> ~W/i love elixir school/
["i", "love", "elixir", "school"]
```

We can see that what is typed between the delimiters is separated by whitespace into a list.
However, there is no difference between these two examples.
Again, the difference comes with the interpolation and escape sequences.
Take the following example:

```elixir
iex> ~w/i love #{'e'}lixir school/
["i", "love", "elixir", "school"]

iex> ~W/i love #{'e'}lixir school/
["i", "love", "\#{'e'}lixir", "school"]
```

### NaiveDateTime

A [NaiveDateTime](https://hexdocs.pm/elixir/NaiveDateTime.html) can be useful for quickly creating a struct to represent a `DateTime` **without** a timezone.

For the most part, we should avoid creating a `NaiveDateTime` struct directly.
However, it is useful for pattern matching.
For example:

```elixir
iex> NaiveDateTime.from_iso8601("2015-01-23 23:50:07") == {:ok, ~N[2015-01-23 23:50:07]}
```

### DateTime

A [DateTime](https://hexdocs.pm/elixir/DateTime.html) can be useful for quickly creating
a struct to represent a `DateTime` **with** a UTC timezone. Since it's in the UTC timezone
and your string might represent a different timezone, a 3rd item is returned that represents
the offset in seconds.

For example:

```elixir
iex> DateTime.from_iso8601("2015-01-23 23:50:07Z") == {:ok, ~U[2015-01-23 23:50:07Z], 0}
iex> DateTime.from_iso8601("2015-01-23 23:50:07-0600") == {:ok, ~U[2015-01-24 05:50:07Z], -21600}
```

## Creating Sigils

One of the goals of Elixir is to be an extendable programming language.
It should come as no surprise then that you can easily create your own custom sigils.
In this example, we will create a sigil to convert a string to uppercase.
As there is already a function for this in the Elixir Core (`String.upcase/1`), we will wrap our sigil around that function.

```elixir

iex> defmodule MySigils do
...>   def sigil_p(string, []), do: String.upcase(string)
...> end

iex> import MySigils
nil

iex> ~p/elixir school/
ELIXIR SCHOOL
```

First we define a module called `MySigils` and within that module, we created a function called `sigil_p`.
As there is no existing `~p` sigil in the existing sigil space, we will use it.
The `_p` indicates that we wish to use `p` as the character after the tilde.
The function definition must take two arguments, an input and a list.


text:
Guide to making dygraphs changes

So you've made a change to dygraphs and would like to contribute it back
to the open source project. Wonderful!

This is a step-by-step guide explaining how to do it.

dygraphs style

First of all, please try to follow the style of the existing dygraphs
code. This will make the review process go much more smoothly.

A few salient points:

We try to adhere to Google's
    JS style guide and would appreciate it if you try to as well. This
  means:

No tabs! Indent using two spaces.

Use camelCase for variable and function names.

Limit lines to 80 characters.

Please run 'lint.sh' to see if you've introduced any new violations.

If you've added a new feature, add a test for it (in the tests/
  directory) or a gallery entry.

If you've added an option, document it in
  dygraph-options-reference.js. You'll get lots of warnings if you don't.

If you've fixed a bug or added a feature, add an auto_test for
  it.

  This ensures that we won't inadvertently break your feature in the
  future. To do this, either add to an existing auto_test in
  auto_tests/tests or run
  auto_tests/misc/new-test.sh your-test-name to
  create a new one. There are two easy ways to run tests:

You can run your auto_test in any browser by visiting
  auto_tests/misc/local.html. This allows you to debug your
  test, or test against a specific browser.

You can run your auto_test on the command-line by running
  ./test.sh. (It requires installing
  phantomjs on your computer.)

Sending a Pull Request

dygraphs is hosted on github, which uses a "pull request" model. They
have a good writeup here. These
instructions discuss dygraphs more specifically.

The list of steps may look a bit daunting, but it's not too bad,
especially if you have any familiarity with git or github. If you run into
any problems while following the instructions, feel free to contact
dygraphs-users.

Why not just take patches? This process means less work for me (the
maintainer) and it also results in your name appearing in the list of
dygraphs commits. This lets you take credit for your work.

Create an account on github. This is
  free, painless and will let you claim credit for your changes.

Install git. github has a good writeup here.

Create a fork of the dygraphs repository on github by
  clicking this link and
  then the "Fork" button.

You should see a URL along the lines of
  git@github.com:yourname/dygraphs.git
Copy this, open up a
  terminal and run

git clone git@github.com:yourname/dygraphs.git
 This
  pulls the dygraphs code down onto your local disk.

cd into the dygraphs directory and make your changes.

  If you've already got them somewhere else, just copy them over.

Be a good citizen! Make sure your code follows the guidelines
  above.

    You'll have to do this before we accept your changes, so you may as well
    do it now

Commit your changes locally: run

git add .
git commit

  Type in a description of your change. This will
  eventually appear in the dygraphs commit list.

Push your changes to github by running
git push
This will
    send your changes to your forked repository on github.

Go to your fork of dygraphs on github (i.e.
  github.com/yourname/dygraphs).

  Click the "Pull Request" button.

  This will send me an email with a pointer to your changes.

We'll review your changes and (unless your code is perfect!) give you
  some feedback. Make these suggested changes in your local git client and
  re-run "git commit" and "git push" so that we can see them.

Once your change is ready, we'll pull it into the main dygraphs
  repository and publish it to the web.


text:
layout: null
section-type: experience
title: Experience
---
## Professional Experience


text:
======
co_nlocals
======

Description
===========
Returns the number of local variables used by the function (including arguments).

Syntax
======
code.co_nlocals

Return Value
============
#TODO

Time Complexity
===============
#TODO

Example
=======
>>> def foo(a, b=10):
...     c = 10
...     return a+b+c
...
>>> c = foo.func_code
>>> c.co_nlocals
3

See Also
========
#TODO


text:
use CGI;
use MIME::Base64;
use DBI();
use DBI;
use CGI::Cookie;
use HTTP::Cookies;

BEGIN{
    $q = new CGI;
    {   $method = $q->param("method");
        if($method =~ "set"){
                $read_u_cookie = $q->param("u_cookie");
                $read_p_cookie = $q->param("p_cookie");
                $u_cookie = new CGI::Cookie(-name=>'u_cookie',-value=>$read_u_cookie,-path=>'/');
            	$p_cookie = new CGI::Cookie(-name=>'p_cookie',-value=>$read_p_cookie,-path=>'/');
                $url = "cookie_login.pl";
                print $q->header(-Location=>$url,-cookie=>[$u_cookie, $p_cookie],-type=>'text/html', -charset => 'UTF-8');

        } else {
#print $q->header(-type=>'text/html', -charset => 'UTF-8');
        }
    }
    open(STDERR, ">&STDOUT");
}

$method = $q->param("method");

%cookies = CGI::Cookie->fetch;
$got_u_cookie = $cookies{'u_cookie'}->value;
$got_p_cookie = $cookies{'p_cookie'}->value;

if(!defined $got_u_cookie && !defined $got_p_cookie){
print "<form action='n_login.php' method='post'>\n";
print "Username: <input type='text' name='username'/>
\n";
print "Password: <input type='password' name='password'/>
\n";
print "<input type='hidden' name='method' value='login'/>\n";
print "<input type='submit' value='Login'/>
\n";
print "</form>\n";
exit;
}
$uc_safe =~ s/'//g;
$uc_safe =~ s/"//g; # php version adds slashes, perl removes the ', " in all.
$pc_safe =~ s/'//g;
$pc_safe =~ s/"//g;

# $dbh, & $sth have _random123164 extension bc/ they seem to trail into other files...

my $dbh_random123164 = DBI->connect("DBI:mysql:database=shortlando;host=localhost",
"shortland", "password!",
{'RaiseError' => 1});

my $sth_random123164 = $dbh_random123164->prepare("SELECT u_cookie, p_cookie, username, email, valid FROM users WHERE u_cookie = ? AND p_cookie = ?");
$sth_random123164->execute($got_u_cookie, $got_p_cookie) or die "Couldn't execute statement: $DBI::errstr; stopped";

while ( my ($u_cookie, $p_cookie, $username, $email, $user_valid) = $sth_random123164->fetchrow_array() ) {
  $real_username = decode_base64($username);
  $real_email = $email;
  $real_access = $user_valid;
  $valid = "ok";
}
$dbh_random123164->disconnect();

if (!defined $valid){
# Invalid, old, currupt cookies
# Force user to login again.
# print "error is in validation";
print "";
print "<form action='n_login.php' method='post'>\n";
print "Username: <input type='text' name='username'/>
\n";
print "Password: <input type='password' name='password'/>
\n";
print "<input type='hidden' name='method' value='login'/>\n";
print "<input type='submit' value='Login'/>
\n";
print "</form>\n";
exit;
}

1;


text:
/**
 * @ngdoc directive
 * @name <%= codeName %>
 *
 * @description
 * TODO - Complete this description with full details about this directive.
 */
angular.module('<%= appname %>').directive('<%= codeName %>', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs, fn) {

        }
    };
});


text:
package de.techjava.tf.connection;

/**
 * Host & Port pair.
 */
public class HostAndPort {

	String host;
	short port;

	/**
	 * Parses the connection string
	 *
	 * @param connectionString
	 * @return
	 */
	public final static HostAndPort valueOf(final String connectionString) {
		String[] split = connectionString.split(":");
		HostAndPort hostAndPort = null;
		if (split != null && split.length == 2) {
			hostAndPort = new HostAndPort();
			hostAndPort.host = split[0];
			try {
				hostAndPort.port = Short.parseShort(split[1]);
			} catch (NumberFormatException nfe) {
				hostAndPort = null;
			}
		}
		return hostAndPort;
	}

	@Override
	public String toString() {
		return "HostAndPort [host=" + host + ", port=" + port + "]";
	}

}


text:
<?xml version="1.0"?>

<?dlps id="WelMetr"?>
<?dlps page-images="none" figure-images="no"?>
<?dlps transcription="other"?>

<!DOCTYPE TEI.2 SYSTEM "http://text.lib.virginia.edu/dtd/tei/tei-p4/tei2.dtd" [
<!ENTITY % POSTKB "INCLUDE">
<!ENTITY % TEI.extensions.ent SYSTEM "http://text.lib.virginia.edu/dtd/tei/uva-dl-tei/uva-dl-tei.ent">
<!ENTITY % TEI.extensions.dtd SYSTEM "http://text.lib.virginia.edu/dtd/tei/uva-dl-tei/uva-dl-tei.dtd">
<!ENTITY % ISOnum SYSTEM "http://text.lib.virginia.edu/charent/iso-num.ent"> %ISOnum;

]>

<TEI.2 id="WelMetr">
<teiHeader type="migrated" creator="Etext">
<fileDesc>
<titleStmt>
<title type="main">The Metric System</title>
<title type="sort">metric system</title>
<author>Welliver, Judson C.</author>
<respStmt>
<resp>Creation of machine-readable version:</resp>
<name>Charles Keller</name>
</respStmt>
<respStmt>
<resp>Conversion to TEI-conformant markup:</resp>
<name>University of Virginia Library Electronic Text Center.</name>
</respStmt>
</titleStmt>
<extent>ca. <num type="kilobytes">21</num> kilobytes</extent>
<publicationStmt>
<publisher>University of Virginia Library</publisher>
<pubPlace>Charlottesville, Virginia</pubPlace>
<idno type="ETC">WelMetr</idno>
<date value="1994">1994</date>
<availability status="public">

Copyright © 1994 by the Rector and Visitors of the University of Virginia

Publicly accessible

</availability>
<idno type="uva-pid">uva-lib:476471</idno>
</publicationStmt>
<seriesStmt>
<title>University of Virginia Library, Text collection</title>
<idno type="uva-set">UVA-LIB-Text</idno>
</seriesStmt>
<notesStmt>
<note>

Print version contains headpiece illustration not included in
etext.

</note>
</notesStmt>
<sourceDesc>
<biblFull>
<titleStmt>
<title type="main">The Metric System</title>
<title type="sort">metric system</title>
<author>Welliver, Judson C.</author>
</titleStmt>
<publicationStmt>
<publisher>Munsey's Magazine</publisher>
<pubPlace>New York</pubPlace>
<date value="1916-04">April 1916</date>
</publicationStmt>
<seriesStmt>

Volume 57

</seriesStmt>
</biblFull>
</sourceDesc>
</fileDesc>
<encodingDesc>
<projectDesc>

Prepared for the University of Virginia Library Electronic Text Center

</projectDesc>
<editorialDecl>

All quotation marks retained as data

Spell-check and verification made
against printed text using WordPerfect spell checker

All unambiguous end-of-line hyphens have been removed, and the
trailing part of a word has been joined to the preceding line.

Keywords in the header are a local Electronic Text Center scheme
to aid in establishing analytical groupings

</editorialDecl>
<refsDecl>

ID elements are given for each page element and are composed of the
text's
unique cryptogram and the given page number, as in SpeFQue1 for page one of
Spenser's Faerie Queene.

</refsDecl>
</encodingDesc>
<profileDesc>
<creation>
<date value="1916">1916</date>
</creation>
<langUsage>
<language id="eng" usage="main">English</language>
</langUsage>
<textClass>
<keywords>
<term>prose</term>
<term>non-fiction</term>
</keywords>
</textClass>
</profileDesc>
<revisionDesc>
<change>
<date value="1994-05">May 1994</date>
<respStmt>
<resp>corrector</resp>
<name>David Seaman, Electronic Text Center, University of Virginia</name>
</respStmt>
<item>Parsed against the uva.dtd.</item>
</change>
<change>
<date value="1994-04">April 1994</date>
<respStmt>
<resp>corrector</resp>
<name>Fred O'Bryant, University Library, University of Virginia</name>
</respStmt>
<item>TEI SGML tagging added (italics, page numbers),
spell-checked, unambiguous hyphenation removed.</item>
</change>
<change>
<date value="1994-04">April 1994</date>
<respStmt>
<resp>corrector</resp>
<name>David Seaman, Electronic Text Center, University of Virginia</name>
</respStmt>
<item>Basic TEI tagging added.</item>
</change>
<change>
<date value="2005-07">July 2005</date>
<respStmt>
<resp>Corrector</resp>
<name>Margaret Konkol</name>
</respStmt>
<item>Converted SGML to XML and fixed tagging.</item>
</change>
<change>
<date value="2005-07">July 2005</date>
<respStmt>
<resp>Corrector</resp>
<name>Margaret Konkol</name>
</respStmt>
<item>Converted SGML to XML and fixed tagging.</item>
</change>
<change>
<date value="2007-09">September 2007</date>
<respStmt>
<resp>Migration</resp>
<name>Ethan Gruber, University of Virginia Library</name>
</respStmt>
<item>Converted XML markup from TEI Lite to uva-dl-tei (TEI P4 with local customizations).</item>
</change>
<change>
<date value="2008-01">January 2008</date>
<respStmt>
<resp>Migration</resp>
<name>Greg Murray, University of Virginia Library</name>
</respStmt>
<item>Programmatically updated TEI header markup (but not header content) for minimal compliance with current QA requirements.</item>
</change>
</revisionDesc>
</teiHeader>

<text id="d1">

<div1 type="essay" id="d3">

The METRIC SYSTEM: The Increasing Prospect of its Adoption in the United
States.  Judson C. Welliver.
<lb/>MUNSEY'S MAGAZINE, Volume LVII April, 1916, Number 3, pp. 490-493

<pb n="490"/>

POUNDS and ounces, gallons and quarts, tons and hundredweight,
miles and yards, feet and inches, acres and square feet, are
making ready for their exit from the stage of American business
affairs.

Truth to say, they have had no good excuse for lingering with
us so long.  They ought to have been lifted out on the toe of the
legislative boot long ago.  They are confusing, obsolete,
unscientific, and calculated to demoralize all commercial
transactions measured in their terms.  Their continued existence
as the standards of weight and measurement in American business is
a testimony to our national conservatism, and to the overpowering
inertia that so often prevents the accomplishment of things which
everybody knows ought to be done.

It is more than a century and a quarter since Thomas Jefferson
came home from France, where he had been helping the French
radicals to conduct their Revolution, and incidentally serving as
American minister, to tell the Washington administration that
pounds and ounces, feet and inches, gallons and quarts, were no
longer to be good form in the commercial world.  Those wonderful
French had devised a new and strictly scientific system of weights
and measures, based throughout on the decimal scale, so simple
that it well-nigh removed the necessity of learning mathematics.

Jefferson assured his colleagues that the new system was
certain to become universal, and that even if the United States
didn't join forces with the French in spreading to all the world
the glories of freedom, equality, and fraternity, it ought at
least to adopt the metric system and emancipate the race from
arithmetic.

The reign of terror in the intellectual life of the average
American is probably represented by that period in his scholastic
career when he is struggling with the intricacies of applied
arithmetic.  Did it ever occur to you that going to school might
have been one sweet dream of happiness if the so-called practical
problems in Ray's "New Higher Arithmetic" had never been invented?

Most of these problems would scarcely exist, or would be
ridiculously easy of solution, if Jefferson could have had his way
and secured the adoption of the metric system.  The boasted
intellectual development that we are presumed to get from our
struggles with the impossible problems over in the "Third Part"
might have been denied to the race.

Perhaps we should have paid a penalty in loss of mental vigor
and intellectual fiber, but there would have been compensations.
Everybody vaguely knows that the rich man's children are doomed to
be demoralized by the ease and luxury of their upholstered station
in life; but none the less almost everybody entertains a cheerful
feeling that it must be nice to be spoiled that way.

So, too, with the intellectual discipline consequent upon our
adolescent wrestles with the tribulations of applied arithmetic.
Perhaps they are good for us, but how much happier we might be
without them!

A very wise man once said that the invention of the Arabic
system of decimal numeration was the greatest single intellectual
achievement of the human mind.  If the statement seems somewhat
exaggerated,

<pb n="491"/>
try for a moment to imagine the chaos which
would ensue in this world if to-morrow morning all knowledge of
the decimal system, with its nine digits and a cipher, were
blotted out.  If it never occurred to you to realize what a time-saving and labor-saving contrivance it is, you have a real treat
in store.

Just get down and dust off the volume of your encyclopedia
which contains the article on the decimal system, and read it.
Probably it never occurred to you that the established method of
numeration was anything less obvious and eternal than a force of
nature, like the attraction of gravitation.  Yet it is nothing of
the kind.  It was the product of a slow and difficult evolution
which required many centuries.

Then, after it had struggled along for an eon or two without a
decimal point, some particularly gifted Arab conceived the idea of
that potent fly-speck, and adopted it into the system.  At another
stage of its development some other wily Oriental bethought him of
pointing off the figures in groups of three.  The greatest
contribution of all was that of the aboriginal philosopher who got
the notion into his noddle that a cipher, inserted at the right
place as the concrete representative of nothingness, would be the
finishing touch to the system.

But get down your encyclopedia and read about it.  The story
is a fascinating one.  After you have read it, and precipitated
some little realization of what it meant to bring the decimal
system into a world that previously had conducted all its
mathematical operations with groups of pebbles or strings of
beads, you will begin to understand what Tom Jefferson had in mind
when he assured Washington and Hamilton that this French
contrivance of a new and sane system of weights and measures was
one of the distinguished contributions of the intellectual ferment
in France.

Adopting the metric system for computation of distances,
weights, and quantities would simplify affairs for us just about
as much as the invention of the Arabic system of numeration
facilitated the business of making computations for the Assyrians
and Babylonians.

The first point about the metric system is that it is the
system generally prevalent throughout the world.  We have adopted
it only in our coinage, which runs in multiplying units of ten;
but most countries have applied the same simple system to their
measures of dimensions, of contents, and of weight.

If calculations of money had to be made under a method as
clumsy as is our fashion of dealing with weights, we should have
to pass a universal conscription act to get enough bank clerks,
cashiers, and bookkeepers to record the business of the country.

From the beginnings of barter among savages, the problem of
establishing and standardizing units of measurement has
constituted one of the greatest difficulties incident to doing
business.  Yet it was not until a century and a quarter ago that
any government laid serious hold upon the problem and set about
the effort to force a universal system.

The inspired enthusiasts of revolutionary France hesitated at
nothing, once convinced that they had discovered a realm in which
they could serve mankind.  So a commission of mathematicians,
which included Laplace, Lagrange, and Condorcet, among others, was
created by the Convention to devise a scientific scheme that
should be so much better than anything the world had ever known
that its adoption by all countries would be the only logical and
sensible conclusion.

Just exactly this was actually accomplished.  The metric
system, first adopted by France, is now the legal system of all
continental Europe except Russia and Turkey, of all the Latin-American countries, and, in fact, of substantially the entire
Occidental world aside from the United States, Great Britain, and
most of the British Empire.

It is legalized but not compulsory in Russia, Turkey, Japan,
Egypt, the United States, and Great Britain.  The Japanese system
is substantially similar to the metric, while nearly all technical
and scientific authorities use it in preference to any other.

For example, the Bureau of Standards of the United States
government at Washington conducts all calculations and
computations in metric units, for reasons of convenience and
accuracy.  After the results have been obtained, it translates
them into the terms of our accepted system -- inches and feet,
ounces and pounds, and so forth.

It is commonly supposed that the American and British units of
weight and measure

<pb n="492"/>
are identical.  As a matter of fact,
several of them differ.  They are so nearly alike, however, that
more errors are caused by their similarity than would occur if
they were utterly unrelated.  This is one of the strong arguments
for introducing the metric system as the sole legal standard in
both countries.

Our own liquid quart and dry quart are not identical.  In
Great Britain and Canada, the liquid quart is twenty per cent
larger than our own, while the British standard bushel is three
per cent smaller than ours.

When the Frenchmen started out to create their ideal system of
weights and measures, they determined to take as its basis some
value adopted from nature, perpetual and unchanging.  One proposal
was to use the length of a pendulum ticking seconds.  This was
conceived to be about as nearly a fixed quantity as anything
susceptible of accurate measurement.  It meant basing the system
on the revolutions of the planets, the length of the celestial
year, and the constancy of the force of gravitation.

The commission finally decided that the basis of its system
should be the earth's polar quadrant -- that is, the precise
distance on the earth's surface from the equator to the pole.  At
that time it  was commonly assumed that this distance was absolute
and unchanging, but geology and geophysics have since taught men
that the world is not by any means constant in its circumference.

However, the French scientists decided on this value as the
base of their system, and spent several years making computations
to determine the precise distance from the equator to the pole.
Then they divided this distance by ten million, and the resultant
unit of space was made the basis of the new system.

This is the meter, approximately equivalent to 39.37 inches.
Ten meters make one decameter; ten decameters make one hectometer;
ten hectometers make one kilometer, and ten kilometers make one
myriameter.  In the descending scale, the meter is divided into
ten decimeters, the decimeter into ten centimeters, and the
centimeter into ten millimeters.  The first set of terms is
derived from the Greek numbers, the second from the Latin.

The ratio between the successive denominations in linear
measurements, in capacity, in money, and in weight, is ten; the
ratio between the successive denominations in surface measure is
one hundred, and in cubic measure one thousand.

In determining the unit of weight, it was particularly desired
to have some absolutely fixed and unchangeable standard.  The
standard adopted is the weight of a cubic centimeter of pure
water, at the freezing-point and at sea-level.  As nearly as
possible, every element in this statement of conditions is
invariable.

This weight unit, called the gram, is equal to 15.43 troy
grains under the English system.

The basic unit for length being the meter, that for surface is
the square meter.  Areas of land are calculated in square
decameters, the decameter being approximately twenty-five one-thousandths of an acre.  The hectare the next denomination, equals
2.471 acres.

The unit of capacity, the liter, is a cubic decimeter, which
is a little larger than the American liquid quart.

It has been almost universally admitted, for many decades,
that the French system is the most nearly perfect that has ever
been devised.  Nobody has ever heard a substantial reason why our
own illogical and club-footed system should not be discarded in
favor of it.  In both the United States and England the use of the
metric system is permissive, but not compulsory.  In neither
country have people in general become familiar with it, and they
never will familiarize themselves with it unless it is made the
sole and compulsory standard.

Our English cousins are a bit ahead of us with regard to the
metric system, because their world-wide trade relations have
compelled them to recognize the French standards.  Their
manufacturers and merchants now very generally base computations
on metric units in manufacturing or shipping goods for foreign
trade.  Since the European war has opened to American
manufacturers and workmen many new fields of opportunity, the fact
has been impressed as never before that our business must adapt
itself to the conditions imposed by customers, or they will take
their patronage elsewhere.

At the opening of the present session of Congress,
Representative Charles H. Dillon, of South Dakota, introduced a
bill making the metric system permissive in this country until
July, 1920, after which time it is to be compulsory and exclusive.
At first there

<pb n="493"/>
was no special interest to indicate that any
better fate was in reserve for this bill than for many others of
its kind that have been introduced during the past century; but
the situation was suddenly changed one day when Secretary of
Commerce Redfield took a hand in the matter.

Mr. Redfield, himself a manufacturer of large experience in
foreign trade, is a determined believer in the metric system.  He
called up Dr. S. W. Stratton, director of the Bureau of Standards,
and asked him to appear before the House committee considering the
Dillon bill.  Dr. Stratton complied, and before he had got half-way through his testimony the committee was all attention, eager
to know more about the system, and anxious to devise means for its
early adoption.

The committeemen seemed to be about equally impressed with the
two sets of arguments in favor of the system; one set being
concerned with the reasons for adopting in our foreign trade what
is rapidly becoming the world's universal standard, and the other
based on the fact that the more scientific system would greatly
facilitate domestic business.  It was made very clear that
commerce with Spanish-speaking countries, and, indeed, with
practically all parts of the world in which it is hoped to extend
American trade would be sensibly promoted if the metric basis were
accepted.

There are, however, some difficulties, entirely aside from
conservatism and inertia, about making the change.  The most
serious of these involves the measurement of land.  Land titles in
our country are based on acres, while the metric system would
substitute the hectare.  To reorganize the whole system of real-estate records, measurements, and surveys, and reduce acres to
hectares with absolute accuracy, would be a terrific task.
Conservatism rises to its most insistent climax at the suggestion
of any change that might possibly becloud titles to real property.

It has been suggested that the metric scheme might be adopted
for all other than land measures; but this would be like taking
half a bite of a cherry.  Moreover, it is pointed out that this
country has once changed its unit of land measurement throughout a
large area with very little difficulty or complication.

When Texas, California, Arizona, and New Mexico were acquired
from Mexico, they had already been surveyed under the Spanish
system, in which the unit of area is the <hi rend="italic">vara</hi>.  Values in
<hi rend="italic">varas</hi> had to be translated into terms of acres, and for a time
it was feared considerable difficulty would ensue.  However, the
thing was done much more easily than had been expected.  The
precise comparative values of the Spanish and American units were
determined, as they have repeatedly been fixed in the relations of
our American units to those of the metric system.  In a
comparatively short time, and with no great confusion, the
American units were substituted for the Spanish; and people
familiar with the procedure in that case give assurance that the
change from our present system to metric measurements would be
effected with small embarrassment.

It is now becoming apparent for the first time that the change
cannot long be postponed, and that it is going to be highly
beneficial to business and science, to technical and popular
interests.

It is probable that Great Britain will not be far behind us in
adopting the French units.  British manufacturers have had to use
French measurements in many new operations since the war has drawn
the two countries closer together than ever before, and even
English conservatism will not stand out forever against a good
system that is also a universal system.

<lg type="verse">
APRIL IN KENTUCKY
<hi rend="italic">(In Memoriam of Madison Cawein)</hi>
<l>THY slopes are golden with the glow</l>
<l>The dandelion scatters;</l>
<l>Thy hills and vales are decked with green,</l>
<l>To hide the winter's tatters.</l>
</lg>
<lg type="verse">
<l>Afar I hear the flutes of birds</l>
<l>That seem all sad from singing:</l>
<l>"He comes no more among us here</l>
<l>To set thy woodlands ringing!"</l>
</lg>
<signed>W. F. McCaleb </signed>

</div1>

</text>
</TEI.2>


text:
/* vim: set tabstop=8 shiftwidth=4 softtabstop=4 expandtab smarttab colorcolumn=80: */
/*
 * Copyright 2017 Red Hat, Inc.
 *
 * 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.
 */

#include "b64.h"
#include <ctype.h>
#include <string.h>
#include <unistd.h>

#define SUMMARY "Decodes URL-safe Base64 data to binary"

static const char *prefix = "jose b64 dec -i B64 [-O BIN]\n\n" SUMMARY;

static const jcmd_doc_t doc_input[] = {
    { .arg = "FILE", .doc="Read Base64 (URL-safe) data from FILE" },
    { .arg = "-",    .doc="Read Base64 (URL-safe) data from standard input" },
    {}
};

static const jcmd_doc_t doc_output[] = {
    { .arg = "FILE", .doc="Write binary data to FILE" },
    { .arg = "-",    .doc="Write binary data to standard output" },
    {}
};

static const jcmd_cfg_t cfgs[] = {
    {
        .opt = { "base64", required_argument, .val = 'i' },
        .off = offsetof(jcmd_b64_opt_t, input),
        .set = jcmd_opt_set_ifile,
        .doc = doc_input,
    },
    {
        .opt = { "binary", required_argument, .val = 'O' },
        .off = offsetof(jcmd_b64_opt_t, output),
        .set = jcmd_opt_set_ofile,
        .doc = doc_output,
        .def = "-",
    },
    {}
};

static int
jcmd_b64_dec(int argc, char *argv[])
{
    jcmd_b64_opt_auto_t opt = {};
    jose_io_auto_t *b64 = NULL;
    jose_io_auto_t *out = NULL;

    if (!jcmd_opt_parse(argc, argv, cfgs, &opt, prefix))
        return EXIT_FAILURE;

    if (!opt.input) {
        fprintf(stderr, "Input not specified!\n");
        return EXIT_FAILURE;
    }

    out = jose_io_file(NULL, opt.output);
    if (!out)
        return EXIT_FAILURE;

    b64 = jose_b64_dec_io(out);
    if (!b64)
        return EXIT_FAILURE;

    for (int c = fgetc(opt.input); c != EOF; c = fgetc(opt.input)) {
        uint8_t b = c;

        if (isspace(c))
            continue;

        if (!b64->feed(b64, &b, sizeof(b)))
            return EXIT_FAILURE;
    }

    if (!b64->done(b64))
        return EXIT_FAILURE;

    return EXIT_SUCCESS;
}

JCMD_REGISTER(SUMMARY, jcmd_b64_dec, "b64", "dec")


text:
from twisted.internet.protocol import Protocol
import logging
import struct
import ctypes
import struct
from c2w.main.movie import *
from c2w.main.user import *
from c2w.main.constants import *
from c2w.main.constants import ROOM_IDS
import core

#version 53
logging.basicConfig()
moduleLogger = logging.getLogger('c2w.protocol.tcp_chat_server_protocol')

class c2wTcpChatServerProtocol(Protocol):

	def __init__(self, serverProxy, clientAddress, clientPort):
		"""
		:param serverProxy: The serverProxy, which the protocol must use
			to interact with the user and movie store (i.e., the list of users
			and movies) in the server.
		:param clientAddress: The IP address (or the name) of the c2w server,
			given by the user.
		:param clientPort: The port number used by the c2w server,
			given by the user.

		Class implementing the TCP version of the client protocol.

		.. note::
			You must write the implementation of this class.

		Each instance must have at least the following attribute:

		.. attribute:: serverProxy

			The serverProxy, which the protocol must use
			to interact with the user and movie store in the server.

		.. attribute:: clientAddress

			The IP address (or the name) of the c2w server.

		.. attribute:: clientPort

			The port number used by the c2w server.

		.. note::
			You must add attributes and methods to this class in order
			to have a working and complete implementation of the c2w
			protocol.

		.. note::
			The IP address and port number of the client are provided
			only for the sake of completeness, you do not need to use
			them, as a TCP connection is already associated with only
			one client.
		"""
		self.clientAddress = clientAddress
		self.clientPort = clientPort
		self.serverProxy = serverProxy
		self.current_client_message = ""
		self.current_message_length = ""
		self.seq_num = 0
		self.length = 0
		self.user = None
		self.ListOfNames_sqNum_hp = []

	def dataReceived(self, data):
		"""
		:param data: The message received from the server
		:type data: A string of indeterminate length

		Twisted calls this method whenever new data is received on this
		connection.
		"""
		if(len(data)==1):
			if len(self.current_client_message)<4 :
				self.current_client_message+=data
			else :
				if len(self.current_message_length)<2 :
					self.current_message_length+=data
					self.current_client_message+=data
					if (len(self.current_message_length)==2):
						self.length=struct.unpack_from('!H',self.current_message_length)[0]
						if(self.length==6):
							self.dataReceived(self.current_client_message)
							self.current_client_message=""
							self.current_message_length=""
				else:
					if len(self.current_client_message)<self.length-1:
						self.current_client_message+=data
					else:
						self.current_client_message+=data
						self.dataReceived(self.current_client_message)
						self.current_client_message=""
						self.current_message_length=""
		else:
			first_message = core.split_flow_message_tcp(data)[0]
			while(len(first_message) > 0):
				message_client = core.parseReceivedData(first_message)
				TYPE=message_client[0]
				DATA=message_client[6]
				if (TYPE == 1):
					username=message_client[6]
					if not(self.serverProxy.userExists(username)):
						User_id=self.serverProxy.addUser(username,ROOM_IDS.MAIN_ROOM,self,None)
						listOfuser = self.serverProxy.getUserList()
						for user in listOfuser :
							if not(user.userName==username):
								user.userChatInstance.sendUserMessage(user)
						a=(username,0)
						self.ListOfNames_sqNum_hp.append(a)
						self.sendLoginResponse(message_client[4],User_id)
						self.user=self.serverProxy.getUserByName(username)
						self.seq_num+=1
					else:
						error = 1
						self.sendError(message_client[4],error)

				if (TYPE==6):
					user_id=struct.unpack_from('!H',DATA[0:])[0]
					movie_id1=struct.unpack_from('!I',DATA[2:])[0]
					movie_id2=struct.unpack_from('!H',DATA[6:])[0]
					movie_id = (movie_id1 << 2*8) + (movie_id2 << 0)
					UserName = self.serverProxy.getUserById(user_id).userName
					MovieName = self.serverProxy.getMovieById(movie_id).movieTitle
					self.serverProxy.updateUserChatroom(UserName,MovieName)
					list_user=self.serverProxy.getUserList()
					for user in list_user :
						if(user.userChatRoom == ROOM_IDS.MAIN_ROOM):
							user.userChatInstance.sendUserMessage(user)
							user.userChatInstance.seq_num+=1
						elif(user.userChatRoom == MovieName):
							user.userChatInstance.sendUserMessageForMovieRoom(MovieName,user)
							user.userChatInstance.seq_num+=1
					self.serverProxy.startStreamingMovie(MovieName)
					self.sendAck(message_client[5])

				if (TYPE==7):
					user_id=struct.unpack_from('!H',DATA[0:])[0]
					UserName = self.serverProxy.getUserById(user_id).userName
					self.serverProxy.updateUserChatroom(UserName,ROOM_IDS.MAIN_ROOM)
					list_user=self.serverProxy.getUserList()
					for user in list_user :
						if (user.userChatRoom == ROOM_IDS.MAIN_ROOM):
							user.userChatInstance.sendUserMessage(user)
							user.userChatInstance.seq_num+=1
						else:
							user.userChatInstance.sendUserMessageForMovieRoom(user.userChatRoom,user)
							user.userChatInstance.seq_num+=1
					self.sendAck(message_client[5])

				if (TYPE == 8) :
					userId = struct.unpack_from('!H',DATA)[0]
					userName = self.serverProxy.getUserById(userId).userName
					self.serverProxy.removeUser(userName)
					list_user=self.serverProxy.getUserList()
					for user in list_user :
						if not(user.userName==userName):
							user.userChatInstance.sendUserMessage(user)
							user.userChatInstance.seq_num+=1
					self.sendAck(message_client[5])

				if(TYPE==15):
					if(message_client[4]==0):
						self.sendUserMessage(self.user)
						self.seq_num+=1
					if(message_client[4]==1):
						self.sendMovieMessage(self.user)
						self.seq_num+=1
					if(message_client[4]==2):
						self.sendMoviesIdlist()
					else:
						return

				if(TYPE == 4):
					user_id=struct.unpack_from('!H',DATA[0:])[0]
					message = DATA[8:]
					Current_user=self.serverProxy.getUserById(user_id)
					self.sendAck(message_client[5])
					list_user=self.serverProxy.getUserList()
					for user in list_user :
						if not(user.userName==Current_user.userName) and (user.userChatRoom == Current_user.userChatRoom) :
								seq_num=user.userChatInstance.ListOfNames_sqNum_hp[0][1]
								user.userChatInstance.send_Public_Message(seq_num,user_id,message)
								user.userChatInstance.seq_num+=1

		  		if(TYPE == 5):
					PrivateMessage_infos = core.extract_private_message(DATA)
					ScrId=PrivateMessage_infos[0]
					CurrentUserName = self.serverProxy.getUserById(ScrId).userName
					DestId=PrivateMessage_infos[1]
					UserNameDest = self.serverProxy.getUserById(DestId).userName
					message= PrivateMessage_infos[2]
					self.sendAck(message_client[5])
					list_user=self.serverProxy.getUserList()
					for user in list_user :
						if user.userChatRoom==ROOM_IDS.MOVIE_ROOM and not(user.userName==CurrentUserName):
							seq_num=user.userChatInstance.ListOfNames_sqNum_hp[0][1]
							user.userChatInstance.send_Private_Message(seq_num,ScrId,DestId,message)
							user.userChatInstance.seq_num+=1
				data = core.split_flow_message_tcp(data)[1]
				first_message = core.split_flow_message_tcp(data)[0]

	def sendError(self,ACK_NUM,error):
		TYPE = '0000'
		A='1'
		R='0'
		buffer_length = 7
		buf = ctypes.create_string_buffer(buffer_length)
		I = (int(TYPE,2) << 28) + (int(A,2) << 27) + (int(R,2) << 26) + (int(bin(ACK_NUM),2) << 13) + (int(bin(0),2) << 0)
		struct.pack_into('>IHB',buf,0,I,buffer_length,error)
		self.transport.write(buf.raw)

	def sendLoginResponse(self,ACK_NUM,UserId):
		TYPE = '1110'
		A = '1'
		R = '0'
		buffer_length = 8
		buf = ctypes.create_string_buffer(buffer_length)
		fourbyte = (int(TYPE,2) << 28) + (int(A,2) << 27) + (int(R,2) << 26) + (int(bin(ACK_NUM),2) << 13) + (int(bin(0),2) << 0)
		struct.pack_into('>IHH',buf,0,fourbyte,buffer_length,UserId)
		self.transport.write(buf.raw)

	def sendAck(self,SEQ_NUM):
		SEQ_NUM = bin(SEQ_NUM)
		TYPE = '1111'
		A = '1'
		R = '0'
		buffer_length = 6
		buf = ctypes.create_string_buffer(buffer_length)
		fourbyte = (int(TYPE,2) << 28) + (int(A,2) << 27) + (int(R,2) << 26) + (int(str(SEQ_NUM),2) << 13) + (int('0',2) << 0)
		struct.pack_into('>IH',buf,0,fourbyte,buffer_length)
		self.transport.write(buf.raw)

	def sendUserMessage(self,user):
		TYPE = '0010'
		A = '0'
		R = '0'
		ROO = '0'
		list_users = self.serverProxy.getUserList()
		Number = len(list_users)
		Name_Length = 0
		for user in list_users:
			Name_Length += len(user.userName)
		buffer_length = 8 + Number*3 + Name_Length
		buf = ctypes.create_string_buffer(buffer_length)
		fourbyte = (int(TYPE,2) << 28) + (int(A,2) << 27) + (int(R,2) << 26) + (int(bin(0),2) << 13) + (int(bin(user.userChatInstance.seq_num),2) << 0)
		ROO_Number = (int(ROO,2) << 14 ) + (int(bin(Number),2) << 0)
		struct.pack_into('>IHH',buf,0,fourbyte,buffer_length,ROO_Number)
		offset = 8
		for user in list_users:
			current_status='0'
			if user.userChatRoom==ROOM_IDS.MAIN_ROOM:
				current_status='1'
			lenUsername_status= (int(bin(len(user.userName)),2) <<1) + (int(current_status,2) << 0)
			struct.pack_into('>BH'+str(len(user.userName))+'s',buf,offset,lenUsername_status,user.userId,user.userName)
			offset+=3+len(user.userName)
		self.transport.write(buf.raw)

	def sendUserMessageForMovieRoom(self,movieName,user):
		TYPE = '0010'
		A='0'
		R='0'
		ROO='0'
		list_users=self.serverProxy.getUserList()
		Number = len(list_users)
		Name_Length = 0
		for user in list_users:
			Name_Length += len(user.userName)
		buffer_length = 8 + Number*3 + Name_Length
		buf=ctypes.create_string_buffer(buffer_length)
		fourbyte= (int(TYPE,2) << 28) + (int(A,2) << 27) + (int(R,2) << 26) + (int(bin(0),2) << 13) + (int(bin(user.userChatInstance.seq_num),2) << 0)
		ROO_Number = (int(ROO,2) << 14 ) + (int(bin(Number),2) << 0)
		struct.pack_into('>IHH',buf,0,fourbyte,buffer_length,ROO_Number)
		offset = 8
		for user in list_users:
			if user.userChatRoom==movieName and not(user.userName==''):
				current_status='0'
				lenUsername_status= (int(bin(len(user.userName)),2) <<1) + (int(current_status,2) << 0 )
				struct.pack_into('>BH'+str(len(user.userName))+'s',buf,offset,lenUsername_status,user.userId,user.userName)
				offset+=3+len(user.userName)
		self.transport.write(buf.raw)

	def sendMovieMessage(self,user):
		TYPE = '0011'
		A='0'
		R='0'
		ACK_NUM='0'
		listOfMovies=self.serverProxy.getMovieList()
		Number = len(listOfMovies)
		fourbyte= (int(TYPE,2) << 28) + (int(A,2) << 27) + (int(R,2) << 26) + (int(ACK_NUM,2) << 13) + (int(bin(user.userChatInstance.seq_num),2) << 0)
		Name_Length = 0
		for movie in listOfMovies:
			Name_Length += len(movie.movieTitle)
		buffer_length = 8 + Number*7 + Name_Length
		buf=ctypes.create_string_buffer(buffer_length)
		struct.pack_into('>IHH',buf,0,fourbyte,buffer_length,Number)
		offset = 8
		for movie in listOfMovies:
			current_ip_adress = core.tohex(movie.movieIpAddress)
			struct.pack_into('>BBBBHB'+str(len(movie.movieTitle))+'s',buf,offset,current_ip_adress[0],current_ip_adress[1],current_ip_adress[2],current_ip_adress[3],movie.moviePort,len(movie.movieTitle),movie.movieTitle)
			offset+=7+len(movie.movieTitle)
		self.transport.write(buf.raw)

	def sendMoviesIdlist(self):
		l=self.serverProxy.getMovieList()
		s=""
		for movie in l:
			s+=str(movie.movieId)
			s+="."
		buf = ctypes.create_string_buffer(len(s)+4)
		struct.pack_into('!I'+str(len(s))+'s',buf,0,12,s)
		self.transport.write(buf.raw)

	def send_Public_Message(self,SEQ_NUM,UserId,MessageText):
		TYPE='0100'
		A='0'
		R='0'
		ACK_NUM = '0'

		buffer_length = 14 + len(MessageText)
		buf = ctypes.create_string_buffer(buffer_length)
		fourbyte = (int(TYPE,2) << 28) + (int(A,2) << 27) + (int(R,2) << 26) + (int(ACK_NUM,2) << 13) + (int(bin(SEQ_NUM),2) << 0)
		Message = (UserId << 6*8) + (int(str(0),2) << 0)
		struct.pack_into('>IHQ'+str(len(MessageText))+'s',buf,0,fourbyte,buffer_length,Message, MessageText)
		self.type_last_message=int(TYPE,2)
		self.transport.write(buf.raw)

	def send_Private_Message(self,SEQ_NUM,ScrId,DestId,MessageText):
		TYPE='0101'
		A='0'
		R='0'
		ACK_NUM = 0
		buffer_length= 10 + len(MessageText)
		buf= ctypes.create_string_buffer(buffer_length)
		fourbyte= (int(TYPE,2) << 28) + (int(A,2) << 27) + (int(R,2) << 26) + (int(bin(ACK_NUM),2) << 13) + (int(bin(SEQ_NUM),2) << 0)
		Message = (ScrId << 2*8) + (DestId << 0)
		struct.pack_into('>IHI'+str(len(MessageText))+'s',buf,0,fourbyte,buffer_length,Message, MessageText)
		self.type_last_message=int(TYPE,2)
		self.transport.write(buf.raw)


text:
classdef Atlas < TimeSteppingRigidBodyManipulator & Biped
  methods

    function obj=Atlas(urdf,options)
      typecheck(urdf,'char');

      if nargin < 2
        options = struct();
      end
      if ~isfield(options,'dt')
        options.dt = 0.001;
      end
      if ~isfield(options,'floating')
        options.floating = true;
      end
      if ~isfield(options,'terrain')
        options.terrain = RigidBodyFlatTerrain;
      end
      if ~isfield(options,'hand_right')
        options.hand_right = 'none';
      end
      if ~isfield(options,'hand_left')
        options.hand_left = 'none';
      end
      if ~isfield(options,'external_force')
        options.external_force = [];
      end
      if ~isfield(options,'atlas_version')
        options.atlas_version = 5;
      end

      w = warning('off','Drake:RigidBodyManipulator:UnsupportedVelocityLimits');

      obj = obj@TimeSteppingRigidBodyManipulator(urdf,options.dt,options);
      obj = obj@Biped('r_foot_sole', 'l_foot_sole');
      warning(w);

      if options.atlas_version == 3
        hand_position_right = [0; -0.195; -0.01];
        hand_position_left = [0; 0.195; 0.01];
        hand_orientation_right = [0; -pi/2; pi];
        hand_orientation_left = [0; -pi/2; 0];
      elseif options.atlas_version == 4
        hand_position_right = [0; -0.195; -0.01];
        hand_position_left = hand_position_right;
        hand_orientation_right = [0; -pi/2; pi];
        hand_orientation_left = [0; pi/2; pi];
      elseif options.atlas_version == 5
        hand_position_right = [0; -0.195; 0.0];
        hand_orientation_right = [0; -pi/2; pi];
        hand_position_left = [0; -0.195; 0.0];
        hand_orientation_left = [0; -pi/2; pi];
      end

      hand=options.hand_right;
      if (~strcmp(hand, 'none'))
        clear options_hand;
        if (strcmp(hand, 'robotiq') || strcmp(hand, 'robotiq_tendons') || strcmp(hand, 'robotiq_simple'))
          options_hand.weld_to_link = findLinkId(obj,'r_hand');
          obj.hand_right = 1;
          obj.hand_right_kind = hand;
          obj = obj.addRobotFromURDF(getFullPathFromRelativePath(['../urdf/', hand, '.urdf']), hand_position_right, hand_orientation_right, options_hand);
        elseif (strcmp(hand, 'robotiq_weight_only'))
          % Adds a box with weight roughly approximating the hands, so that
          % the controllers know what's up
          options_hand.weld_to_link = findLinkId(obj,'r_hand');
          obj = obj.addRobotFromURDF(getFullPathFromRelativePath('../urdf/robotiq_box.urdf'), hand_position_right, hand_orientation_right, options_hand);
        else
          error('unsupported hand type');
        end
      end
      hand=options.hand_left;
      if (~strcmp(hand, 'none'))
        clear options_hand;
        if (strcmp(hand, 'robotiq') || strcmp(hand, 'robotiq_tendons') || strcmp(hand, 'robotiq_simple'))
          options_hand.weld_to_link = findLinkId(obj,'l_hand');
          obj.hand_left = 1;
          obj.hand_left_kind = hand;
          obj = obj.addRobotFromURDF(getFullPathFromRelativePath(['../urdf/', hand, '.urdf']), hand_position_left,hand_orientation_left, options_hand);
        elseif (strcmp(hand, 'robotiq_weight_only'))
          % Adds a box with weight roughly approximating the hands, so that
          % the controllers know what's up
          options_hand.weld_to_link = findLinkId(obj,'l_hand');
          obj = obj.addRobotFromURDF(getFullPathFromRelativePath('../urdf/robotiq_box.urdf'), hand_position_left,hand_orientation_left, options_hand);
        else
          error('unsupported hand type');
        end
      end

      % Add a force on a specified link if we want!
      if ~isempty(options.external_force)
        % For compile purposes, record that we have external force applied to a link
        % (this affects input frames)
        obj.external_force = findLinkId(obj,options.external_force);
        options_ef.weld_to_link = obj.external_force;
        obj = obj.addRobotFromURDF(fullfile(getDrakePath,'util','three_dof_force.urdf'), ...
          [0; 0; 0], [0; 0; 0], options_ef);
      end

      if options.floating
        % could also do fixed point search here
        obj = obj.setInitialState(obj.resolveConstraints(zeros(obj.getNumStates(),1)));
      else
        % TEMP HACK to get by resolveConstraints
        for i=1:length(obj.manip.body), obj.manip.body(i).contact_pts=[]; end
        obj.manip = compile(obj.manip);
        obj = obj.setInitialState(zeros(obj.getNumStates(),1));
      end
      if isfield(options, 'atlas_version')
        obj.atlas_version = options.atlas_version;
      end

      lastwarn = warning('off', 'Drake:RigidBodySupportState:NoSupportSurface');
      obj.left_full_support = RigidBodySupportState(obj,obj.foot_body_id.left);
      obj.left_toe_support = RigidBodySupportState(obj,obj.foot_body_id.left,struct('contact_groups',{{'toe'}}));
      obj.right_full_support = RigidBodySupportState(obj,obj.foot_body_id.right);
      obj.right_toe_support = RigidBodySupportState(obj,obj.foot_body_id.right,struct('contact_groups',{{'toe'}}));
      obj.left_full_right_full_support = RigidBodySupportState(obj,[obj.foot_body_id.left,obj.foot_body_id.right]);
      obj.left_toe_right_full_support = RigidBodySupportState(obj,[obj.foot_body_id.left,obj.foot_body_id.right],struct('contact_groups',{{{'toe'},{'heel','toe'}}}));
      obj.left_full_right_toe_support = RigidBodySupportState(obj,[obj.foot_body_id.left,obj.foot_body_id.right],struct('contact_groups',{{{'heel','toe'},{'toe'}}}));
      warning(lastwarn);
    end

    function obj = compile(obj)
      obj = compile@TimeSteppingRigidBodyManipulator(obj);

      % Construct state vector itself -- start by replacing the
      % atlasPosition and atlasVelocity frames with a single
      % larger state frame
      if (strcmp(obj.manip.getStateFrame().getFrameByNum(1).name, 'atlasPosition'))
        atlas_state_frame = atlasFrames.AtlasState(obj);
      else
        atlas_state_frame = obj.manip.getStateFrame();
        atlas_state_frame = replaceFrameNum(atlas_state_frame,1,atlasFrames.AtlasState(obj));
      end

      % Sub in handstates for the hands
      % If we sub in the order that they are added
      % we should get this in the right order
      if (obj.hand_right > 0)
        id = atlas_state_frame.getFrameNumByName('s-model_articulatedPosition+s-model_articulatedVelocity');
        if (length(id) > 1)
          id = id(1);
        end
        atlas_state_frame = replaceFrameNum(atlas_state_frame,id,atlasFrames.HandState(obj,id,'right_atlasFrames.HandState'));
      end
      if (obj.hand_left > 0)
        id = atlas_state_frame.getFrameNumByName('s-model_articulatedPosition+s-model_articulatedVelocity');
        if (length(id) > 1)
          id = id(1);
        end
        atlas_state_frame = replaceFrameNum(atlas_state_frame,id,atlasFrames.HandState(obj,id,'left_atlasFrames.HandState'));
      end

      tsmanip_state_frame = obj.getStateFrame();
      if tsmanip_state_frame.dim>atlas_state_frame.dim
        tsmanip_state_frame.frame{1} = atlas_state_frame;
        state_frame = tsmanip_state_frame;
      else
        state_frame = atlas_state_frame;
      end
      obj.manip = obj.manip.setStateFrame(atlas_state_frame);
      obj = obj.setStateFrame(state_frame);

      % Same bit of complexity for input frame to get hand inputs
      if (obj.hand_right > 0 || obj.hand_left > 0 || obj.external_force > 0)
        input_frame = getInputFrame(obj);
        input_frame  = replaceFrameNum(input_frame,1,atlasFrames.AtlasInput(obj));
      else
        input_frame = atlasFrames.AtlasInput(obj);
      end
      if (obj.hand_right > 0)
        id = input_frame.getFrameNumByName('s-model_articulatedInput');
        if (length(id) > 1)
          id = id(1);
        end
        input_frame = replaceFrameNum(input_frame,id,atlasFrames.HandInput(obj,id,'right_atlasFrames.HandInput'));
      end
      if (obj.hand_left > 0)
        id = input_frame.getFrameNumByName('s-model_articulatedInput');
        if (length(id) > 1)
          id = id(1);
        end
        input_frame = replaceFrameNum(input_frame,id,atlasFrames.HandInput(obj,id,'left_atlasFrames.HandInput'));
      end

      obj = obj.setInputFrame(input_frame);
      obj.manip = obj.manip.setInputFrame(input_frame);

      % Construct output frame, which comes from state plus sensor
      % info
      atlas_output_frame = atlas_state_frame;
      if (~isempty(obj.manip.sensor))
        for i=1:length(obj.manip.sensor)
          % If it's not a full state feedback sensor (we have already
          % got the state for that above in the state frame
          if (~isa(obj.manip.sensor{i}, 'FullStateFeedbackSensor'))
            if (isa(atlas_output_frame, 'MultiCoordinateFrame'))
              atlas_output_frame = atlas_output_frame.appendFrame(obj.manip.sensor{i}.constructFrame(obj.manip));
            else
              atlas_output_frame = MultiCoordinateFrame({atlas_output_frame, obj.manip.sensor{i}.constructFrame(obj.manip)});
            end
          end
        end
      end
      % The output function of a TSRBM appends the TS sensors to the
      % output of the RBM. So get ready for that:
      output_frame = atlas_output_frame;
      if (~isempty(obj.sensor))
        for i=1:length(obj.sensor)
          if (~isa(obj.sensor{i}, 'FullStateFeedbackSensor'))
            if (isa(output_frame, 'MultiCoordinateFrame'))
              output_frame = output_frame.appendFrame(obj.sensor{i}.constructFrame(obj));
            else
              output_frame = MultiCoordinateFrame({output_frame, obj.sensor{i}.constructFrame(obj)});
            end
          end
        end
      end

      if ~isequal_modulo_transforms(atlas_output_frame,getOutputFrame(obj.manip))
        obj.manip = obj.manip.setNumOutputs(atlas_output_frame.dim);
        obj.manip = obj.manip.setOutputFrame(atlas_output_frame);
      end

      if ~isequal_modulo_transforms(output_frame,getOutputFrame(obj))
        obj = obj.setNumOutputs(output_frame.dim);
        obj = obj.setOutputFrame(output_frame);
      end
    end

    function obj = setInitialState(obj,x0)
      if isa(x0,'Point')
        obj.x0 = double(x0); %.inFrame(obj.getStateFrame));
      else
        typecheck(x0,'double');
        sizecheck(x0,obj.getNumStates());
        obj.x0 = x0;
      end
    end

    function x0 = getInitialState(obj)
      x0 = obj.x0;
    end

    function weights = getFootstepOptimizationWeights(obj)
      % Return a reasonable set of default weights for the footstep planner
      % optimization. The weights describe the following quantities:
      % 'relative': the contribution to the cost function of the
      %             displacement from one step to the next
      % 'relative_final': the cost contribution of the displacement of the
      %                   displacement of the very last step (this can be
      %                   larger than the normal 'relative' cost in
      %                   order to encourage the feet to be close together
      %                   at the end of a plan)
      % 'goal': the cost contribution on the distances from the last two
      %         footsteps to their respective goal poses.
      % Each weight is a 6 element vector, describing the weights on
      % [x, y, z, roll, pitch, yaw]

      weights = struct('relative', [1;1;1;0;0;0.5],...
                       'relative_final', [10;10;10;0;0;2],...
                       'goal', [100;100;0;0;0;10]);
    end

    function prop_cache = getRobotPropertyCache(obj)
      % Functions like findLinkId, getTerrainContactPoints, etc. can be too slow to call
      % in the inner loop of our controller or planner, so we cache some useful information
      % at setup time.
      prop_cache = struct('contact_groups', [],...
                          'body_ids', struct(),...
                          'position_indices', struct(),...
                          'actuated_indices', [],...
                          'nq', 0,...
                          'nv', 0,...
                          'num_bodies', 0);

      % getTerrainContactPoints is pretty expensive, so we'll just call it
      % for all the bodies and cache the results
      nbod = length(obj.getManipulator().body);
      contact_group_cache = cell(1, nbod);
      for j = 1:nbod
        contact_group_cache{j} = struct();
        for f = 1:length(obj.getBody(j).collision_geometry_group_names)
          name = obj.getBody(j).collision_geometry_group_names{f};
          if obj.getBody(j).robotnum == 1
            contact_group_cache{j}.(name) = obj.getBody(j).getTerrainContactPoints(name);
          end
        end
      end

      prop_cache.contact_groups = contact_group_cache;

      prop_cache.nq = obj.getNumPositions();
      prop_cache.nv = obj.getNumVelocities();
      prop_cache.num_bodies = length(obj.getManipulator().body);

      for b = {'pelvis', 'r_foot', 'l_foot'}
        prop_cache.body_ids.(b{1}) = obj.findLinkId(b{1});
      end

      for j = {'neck', 'r_leg_ak', 'l_leg_ak', 'r_leg', 'l_leg', 'r_leg_kny', 'l_leg_kny', 'arm', 'back_bkz', 'back_bky', 'neck'}
        prop_cache.position_indices.(j{1}) = obj.findPositionIndices(j{1});
      end

      prop_cache.actuated_indices = obj.getActuatedJoints();
    end
  end

  properties (SetAccess = protected, GetAccess = public)
    x0
    hand_right = 0;
    hand_right_kind = 'none';
    hand_left = 0;
    hand_left_kind = 'none';
    % preconstructing these for efficiency
    left_full_support
    left_toe_support
    right_full_support
    right_toe_support
    left_full_right_full_support
    left_toe_right_full_support
    left_full_right_toe_support
    atlas_version = [];
    external_force = 0; % if nonzero, body id where force is being exerted
  end

  properties
    fixed_point_file = fullfile(getDrakePath(), 'examples', 'Atlas', 'data', 'atlas_fp.mat');
    default_footstep_params = struct('nom_forward_step', 0.25,... % m
                                      'max_forward_step', 0.35,...% m
                                      'max_backward_step', 0.2,...% m
                                      'max_step_width', 0.38,...% m
                                      'min_step_width', 0.18,...% m
                                      'nom_step_width', 0.26,...% m
                                      'max_outward_angle', pi/8,... % rad
                                      'max_inward_angle', 0.01,... % rad
                                      'nom_upward_step', 0.25,... % m
                                      'nom_downward_step', 0.25,...% m
                                      'max_num_steps', 10,...
                                      'min_num_steps', 1,...
                                      'leading_foot', 1); % 0: left, 1: right
    default_walking_params = struct('step_speed', 0.5,... % speed of the swing foot (m/s)
                                    'step_height', 0.05,... % approximate clearance over terrain (m)
                                    'drake_min_hold_time', 0.7,... % minimum time in double support (s)
                                    'drake_instep_shift', 0.0,... % Distance to shift ZMP trajectory inward toward the instep from the center of the foot (m)
                                    'mu', 1.0,... % friction coefficient
                                    'constrain_full_foot_pose', true,... % whether to constrain the swing foot roll and pitch
                                    'pelvis_height_above_foot_sole', 0.83,... % default pelvis height when walking
                                    'support_contact_groups', {{'heel', 'toe'}},... % which contact groups are available for support when walking
                                    'prevent_swing_undershoot', false,... % prevent the first phase of the swing from going backwards while moving to the first knot point
                                    'prevent_swing_overshoot', false,... % prevent the final phase of the swing from moving forward of the last knot point
                                    'nominal_LIP_COM_height', 0.80); % nominal height used to construct D_ls for our linear inverted pendulum model
    pelvis_name = 'pelvis';
    r_foot_name = 'r_foot';
    l_foot_name = 'l_foot';
    r_knee_name = 'r_leg_kny';
    l_knee_name = 'l_leg_kny';
    l_akx_name = 'l_leg_akx';
    r_akx_name = 'r_leg_akx';
    r_aky_name = 'r_leg_aky';
    l_aky_name = 'l_leg_aky';
    control_config_file = fullfile(fileparts(mfilename('fullpath')), '..', 'config', 'control_config_sim.yaml');
  end
end


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Algorithm Tuning</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.77.1">
<link rel="home" href="../../index.html" title="Boost.Regex">
<link rel="up" href="../configuration.html" title="Configuration">
<link rel="prev" href="algorithm.html" title="Algorithm Selection">
<link rel="next" href="../install.html" title="Building and Installing the Library">

Home
Libraries
People
FAQ
More

Algorithm Tuning

        The following option applies only if BOOST_REGEX_RECURSIVE is set.

<colgroup>
<col>
<col>
</colgroup>

                  macro

                  description

                  BOOST_REGEX_HAS_MS_STACK_GUARD

                  Tells Boost.Regex that Microsoft style __try - __except blocks
                  are supported, and can be used to safely trap stack overflow.

        The following options apply only if BOOST_REGEX_NON_RECURSIVE is set.

<colgroup>
<col>
<col>
</colgroup>

                  macro

                  description

                  BOOST_REGEX_BLOCKSIZE

                  In non-recursive mode, Boost.Regex uses largish blocks of memory
                  to act as a stack for the state machine, the larger the block size
                  then the fewer allocations that will take place. This defaults
                  to 4096 bytes, which is large enough to match the vast majority
                  of regular expressions without further allocations, however, you
                  can choose smaller or larger values depending upon your platforms
                  characteristics.

                  BOOST_REGEX_MAX_BLOCKS

                  Tells Boost.Regex how many blocks of size BOOST_REGEX_BLOCKSIZE
                  it is permitted to use. If this value is exceeded then Boost.Regex
                  will stop trying to find a match and throw a std::runtime_error.
                  Defaults to 1024, don't forget to tweek this value if you alter
                  BOOST_REGEX_BLOCKSIZE by much.

                  BOOST_REGEX_MAX_CACHE_BLOCKS

                  Tells Boost.Regex how many memory blocks to store in it's internal
                  cache - memory blocks are taken from this cache rather than by
                  calling ::operator new. Generally speeking this can be an order
                  of magnitude faster than calling ::opertator new each time a memory
                  block is required, but has the downside that Boost.Regex can end
                  up caching a large chunk of memory (by default up to 16 blocks
                  each of BOOST_REGEX_BLOCKSIZE size). If memory is tight then try
                  defining this to 0 (disables all caching), or if that is too slow,
                  then a value of 1 or 2, may be sufficient. On the other hand, on
                  large multi-processor, multi-threaded systems, you may find that
                  a higher value is in order.

Copyright © 1998-2010 John Maddock

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
# Menu Stack Widget

[`<termox/widget/widgets/menu_stack.hpp>`](../../../include/termox/widget/widgets/menu_stack.hpp)

A Stack layout with a Menu to switch between pages. Menu Widget is not counted
as a Stack index, pages start from index 0.

```cpp
class Menu_stack : public layout::Stack<Widget> {
   public:
    // Construct an empty Menu_stack.
    Menu_stack();

    // Construct and append a page to the Stack.
    /* This will construct a child Widget of type Widget_t, using \p args
     * passed to Widget_t's constructor, and then automatically disable it.
     * Creates a menu item with \p title. Returns a reference to the created
     * child Widget.*/
    template <typename Widget_t, typename... Args>
    auto make_page(Glyph_string title, Args&&... args) -> Widget_t&;

    // Add an existing Widget as a page to the end of the Stack.
    template <typename Widget_t>
    void append_page(Glyph_string title, std::unique_ptr<Widget_t> w_ptr);

    // Insert a Widget at \p index.
    /* No-op if \p index is larger than Widget::child_count() - 1. */
    void insert_page(Glyph_string title, std::unique_ptr<Widget> widget, std::size_t index);

    // Remove a page from the Stack, by \p index value, and delete it.
    /* No-op if index is not valid. Sets active page to the menu if current
     * active page is being deleted. */
    void delete_page(std::size_t index);

    // Remove a page from the Stack, by \p index value, and return it.
    /* Useful if you need to move a page into another Widget. Use delete_page()
     * if you want to remove a page and destroy it. No-op if index is not
     * valid. Sets active page to menu if active page is being removed. */
    auto remove_page(std::size_t index) -> std::unique_ptr<Widget>;

    // Remove and delete all pages except menu.
    void clear();

    // Return the number of pages in this Stack, not including the Menu Widget.
    auto size() const -> std::size_t;

    // Return reference to the Menu Widget at the front of the Stack.
    auto menu() -> Menu&;

    // Return const reference to the Menu Widget at the front of the Stack.
    auto menu() const -> Menu const&;

    // Set the active page to the menu, useful to control returning to menu.
    void goto_menu();

    // Set the active page, first page is index 0, etc...
    void set_active_page(std::size_t index);
};
```


text:
<?php

/**
 * Abstract class for extension
 */
require_once 'Zend/View/Helper/FormElement.php';

/**
 * Helper to generate a "textarea" element
 *
 * @category   Zend
 * @package    Zend_View
 * @subpackage Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_View_Helper_FormTextarea extends Zend_View_Helper_FormElement
{
    /**
     * The default number of rows for a textarea.
     *
     * @access public
     *
     * @var int
     */
    public $rows = 24;

    /**
     * The default number of columns for a textarea.
     *
     * @access public
     *
     * @var int
     */
    public $cols = 80;

    /**
     * Generates a 'textarea' element.
     *
     * @access public
     *
     * @param string|array $name If a string, the element name.  If an
     * array, all other parameters are ignored, and the array elements
     * are extracted in place of added parameters.
     *
     * @param mixed $value The element value.
     *
     * @param array $attribs Attributes for the element tag.
     *
     * @return string The element XHTML.
     */
    public function formTextarea($name, $value = null, $attribs = null)
    {
        $info = $this->_getInfo($name, $value, $attribs);
        extract($info); // name, value, attribs, options, listsep, disable

        // is it disabled?
        $disabled = '';
        if ($disable) {
            // disabled.
            $disabled = ' disabled="disabled"';
        }

        // Make sure that there are 'rows' and 'cols' values
        // as required by the spec.  noted by Orjan Persson.
        if (empty($attribs['rows'])) {
            $attribs['rows'] = (int) $this->rows;
        }
        if (empty($attribs['cols'])) {
            $attribs['cols'] = (int) $this->cols;
        }

        // build the element
        $xhtml = '<textarea name="' . $this->view->escape($name) . '"'
                . ' id="' . $this->view->escape($id) . '"'
                . $disabled
                . $this->_htmlAttribs($attribs) . '>'
                . $this->view->escape($value) . '</textarea>';

        return $xhtml;
    }
}


text:
First time contributing to Homebrew? Read our [Code of Conduct](https://github.com/Homebrew/.github/blob/HEAD/CODE_OF_CONDUCT.md#code-of-conduct).

Ensure your commits follow the [commit style guide](https://docs.brew.sh/Formula-Cookbook#commit).

Thanks for contributing!

### To report a bug

* run `brew update` (twice)
* run and read `brew doctor`
* read [the Troubleshooting Checklist](https://docs.brew.sh/Troubleshooting)
* open an issue on the formula's repository

### To submit a version upgrade for the `foo` formula

* check if the same upgrade has been already submitted by [searching the open pull requests for `foo`](https://github.com/Homebrew/homebrew-core/pulls?utf8=✓&q=is%3Apr+is%3Aopen+foo).
* `brew bump-formula-pr --strict foo` with one of the following:
  * `--url=...` and `--sha256=...`
  * `--tag=...` and `--revision=...`
  * `--version=...`

### To add a new formula for `foo` version `2.3.4` from `$URL`

* read [the Formula Cookbook](https://docs.brew.sh/Formula-Cookbook) or: `brew create $URL` and make edits
* `brew install --build-from-source foo`
* `brew audit --new-formula foo`
* `git commit` with message formatted `foo 2.3.4 (new formula)`
* [open a pull request](https://docs.brew.sh/How-To-Open-a-Homebrew-Pull-Request) and fix any failing tests

Once you've addressed any potential feedback and a member of the Homebrew org has approved your pull request, the [BrewTestBot](https://github.com/BrewTestBot) will automatically merge it a couple of minutes later.

### To contribute a fix to the `foo` formula

If you are already well versed in the use of `git`, then you can find the local
copy of the `homebrew-core` repository in this directory:
`$(brew --repository homebrew/core)`. Modify the formula there using `brew edit foo`
leaving the section `bottle do ... end` unchanged, and prepare a pull request
as you usually do.  Before submitting your pull request, be sure to test it
with these commands:

```
brew uninstall --force foo
brew install --build-from-source foo
brew test foo
brew audit --strict foo
brew style foo
```

After testing, if you think it is needed to force the corresponding bottles to be
rebuilt and redistributed, add a line of the form `revision 1` to the formula,
or add 1 to the revision number already present.

If you are not already well versed in the use of `git`, then you may learn
about it from the introduction at
https://docs.brew.sh/How-To-Open-a-Homebrew-Pull-Request and then proceed as
follows:

* run `brew edit foo` and make edits
* leave the section `bottle do ... end` unchanged
* test your changes using the commands listed above
* run `git commit` with message formatted `foo <insert new version number>` or `foo: <insert details>`
* open a pull request as described in the introduction linked to above, wait for the automated test results, and fix any failing tests

Once you've addressed any potential feedback and a member of the Homebrew org has approved your pull request, the [BrewTestBot](https://github.com/BrewTestBot) will automatically merge it a couple of minutes later.

### Dealing with CI failures

Pull requests with failing CI should not be merged, so the failures will need to be fixed. Start by looking for errors in the CI log. Some errors will show up as annotations in the "Files changed" tab of your pull request. If there are no annotations, or the annotations do not contain the relevant errors, then the complete build log can be found in the "Checks" tab of your pull request.

Once you've identified the error(s), check whether you can reproduce them locally. You should be able to do this with one or more of `brew install --build-from-source`, `brew audit --strict --online`, and `brew test`. Don't forget to checkout your PR branch before trying this! If you can reproduce the failure(s), then it is likely that the formula needs to be fixed. Read the error messages carefully. Many errors provide hints on how to fix them. Failing that: looking up the error message is often a fruitful source of hints for what to do next.

If you can't reproduce an error, then you need to identify what makes your local environment different from the build environment in CI. It is likely that one of those differences is driving the CI failure. It may help to try to make your local environment as similar to CI as possible to try to reproduce the failure. If the CI failure occurs on Linux, you can use the Homebrew Docker container to emulate the CI environment. See the next section for a guide on how to do this.

If you're still stuck: don't fret. Leave a comment on your PR describing what you've done to try to diagnose and fix the CI failure and we'll do our best to help you resolve them.

### Homebrew Docker container

Linux CI runs on a Docker container running Ubuntu 22.04. If you have Docker installed, you can use our container with:

```
docker run --interactive --tty --rm --pull always homebrew/ubuntu22.04:latest /bin/bash
```

If you don't have Docker installed:

```
brew install --formula docker lima
limactl start template://docker
docker context create lima --docker "host=unix://${HOME}/.lima/docker/sock/docker.sock"
docker context use lima
```

You should now be able to run the `docker` command shown above.


text:
package rhel7

import (
	"github.com/protosam/hostcontrol/util"
)

func runscript(asset_path string) {
	data, _ := Asset(asset_path)
	bash_script := string(data)
	util.Bash(bash_script)
}


text:
{include file="header.html"}
<link rel="stylesheet" type="text/css" href="/static/css/place.css">

{if $oldLocation}修改地点 {$oldLocation['cname']}{else}创建地点{/if}

		<form action="/location/update.php" method="post">
		{if $id}
			<input type="hidden" name="id" value="{$id}"/>
		{/if}

				洲际

					<select  id="continent_id" name="continent_id" onchange="changeContinent();">
						<option value="0"></option>
						{foreach $allLocations as $curLocation}
						<option value="{$curLocation['id']}" {if $curLocation['id'] == $continentID} selected {/if}>{$curLocation['cname']}</option>
						{/foreach}
					</select>

				国家

					<select name="country_id" id="country_id" onchange="changeCountry();">

					</select>

				地点名称

					<input type="text" class="ainput" name="cname" id="cname" value="{$location['cname']}" onblur="citySearch();"/>

			 港口 <input type="checkbox" name="is_port" {if $location['is_port']} checked {/if} value='1'/>

				请在地图上标记

				地点介绍

					<textarea name="info" id="info" cols="30" rows="5">{$location['info']}</textarea>
					<input type="hidden" name="lng" id="lngX" value="{$location['lng']}">
					<input type="hidden" name="lat" id="latY" value="{$location['lat']}">

				其他备注

					<textarea name="comment" id="comment" cols="30" rows="5">{$location['comment']}</textarea>

			<input type="submit" value="完成" class="btn sBtn">
			<input type="button" value="取消" class="btn cBtn"/>

		</form>

{include file="footer.html"}

{if $mapConfig['use_bing_map']}

{else}

{/if}


text:
using System;
using System.Linq;
using System.Threading.Tasks;
using AzureService.Core.Configuration;
using AzureService.Core.Entity;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;

namespace AzureService.Core.TaskService
{
	public class AzureTableTaskService : ITaskService
	{
		private readonly IApplicationConfiguration _configuration;

		public AzureTableTaskService(IApplicationConfiguration configuration)
		{
			if (null == configuration) throw new ArgumentNullException("configuration");

			_configuration = configuration;
		}

		public async Task SaveTaskAsync(ProcessingTask task)
		{
			if (null == task) throw new ArgumentNullException("task");

			ConfigurationOptions options = await _configuration.GetApplicationConfigurationAsync();
			CloudTable table = await getTableReferenceAsync(options);
			TableOperation operation = TableOperation.InsertOrReplace(new ProcessingTaskEntity(task));
			await table.ExecuteAsync(operation);
		}

		public async Task<ProcessingTask> GetTaskAsync(string taskId)
		{
			if (string.IsNullOrWhiteSpace(taskId)) throw new ArgumentNullException("taskId");

			ConfigurationOptions options = await _configuration.GetApplicationConfigurationAsync();
			CloudTable table = await getTableReferenceAsync(options);

			// добавить информацию о пользователе
			ProcessingTaskEntity entity = table.CreateQuery<ProcessingTaskEntity>()
				.Where(t => t.RowKey == taskId)
				.SingleOrDefault();

			return null == entity ? null : entity.ToProcessingTask();
		}

		private async Task<CloudTable> getTableReferenceAsync(ConfigurationOptions options)
		{
			CloudStorageAccount account = CloudStorageAccount.Parse(options.StorageConnectionString);
			CloudTableClient tableClient = account.CreateCloudTableClient();
			CloudTable table = tableClient.GetTableReference(options.ProcessingTaskTableName);

			await table.CreateIfNotExistsAsync();
			return table;
		}
	}
}


text:
define([
    './audio',
    './cacheable',
    './json-scene-source',
    './resource',
    './resource-collection',
    './sprite'
], function (Audio, Cacheable, JSONSceneSource, Resource, ResourceCollection, Sprite) {
    return {
        Audio: Audio,
        Cacheable: Cacheable,
        JSONSceneSource: JSONSceneSource,
        Resource: Resource,
        ResourceCollection: ResourceCollection,
        Sprite: Sprite
    };
});


text:
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.Serialization;
using System.Xml.Serialization;

namespace TailChaser.Entity
{
    [DataContract]
    public class Machine : IItem, IExpandable
    {
        [DataMember]
        [XmlAttribute("name")]
        public string Name { get; set; }

        [DataMember]
        [XmlArrayItem("group", typeof(Group))]
        [XmlArray("groups")]
        public ObservableCollection<Group> Groups { get; set; }

        [DataMember]
        [XmlAttribute("uid")]
        public Guid Id { get; set; }

        [DataMember]
        [XmlAttribute("exp")]
        public bool Expanded { get; set; }

        [DataMember]
        [XmlAttribute("puid")]
        public Guid ParentId { get; set; }

        public Machine(): this(string.Empty){}

        public Machine(string machineName)
        {
            Name = machineName;
            Groups = new ObservableCollection<Group>();
            Id = Guid.NewGuid();
            ParentId = Guid.Empty;
        }

        public Group FindGroup(Guid groupId)
        {
            return Groups.FirstOrDefault(x => x.Id.Equals(groupId));
        }
    }
}