text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  #%L
  wcm.io
  %%
  Copyright (C) 2017 wcm.io
  %%
  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.
  #L%
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>io.wcm.maven</groupId>
    <artifactId>io.wcm.maven.global-parent</artifactId>
    <version>44</version>
    <relativePath />
  </parent>

  <groupId>io.wcm.qa</groupId>
  <artifactId>io.wcm.qa.parent_toplevel</artifactId>
  <version>7-SNAPSHOT</version>
  <packaging>pom</packaging>

  <name>Toplevel Parent</name>
  <description>Toplevel POM for all wcm.io QA Maven projects.</description>
  <url>${site.url}/${site.url.module.prefix}/</url>

  <scm>
    <connection>scm:git:https://github.com/wcm-io-qa/wcm-io-qa-tooling.git</connection>
    <developerConnection>scm:git:https://github.com/wcm-io-qa/wcm-io-qa-tooling.git</developerConnection>
    <url>https://github.com/wcm-io-qa/wcm-io-qa-tooling</url>
    <tag>HEAD</tag>
  </scm>

  <inceptionYear>2017</inceptionYear>

  <organization>
    <name>wcm.io QA</name>
    <url>https://qa.wcm.io</url>
  </organization>

  <issueManagement>
    <system>JIRA</system>
    <url>https://wcm-io.atlassian.net/browse/</url>
  </issueManagement>

  <developers>
    <developer>
      <name>wcm.io Community</name>
      <organization>wcm.io</organization>
      <organizationUrl>https://wcm.io</organizationUrl>
    </developer>
  </developers>

  <licenses>
    <license>
      <name>The Apache Software License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
    </license>
  </licenses>

  <properties>

    <!-- Java version -->
    <java.version>1.8</java.version>
    <build.compiler.release>8</build.compiler.release>

    <!-- site settings -->
    <site.url.module.prefix>tooling/parent_toplevel</site.url.module.prefix>
    <site.url>https://qa.wcm.io</site.url>
    <site.deploy.id>ssh-wcm.io</site.deploy.id>
    <site.deploy.url>scm:git:https://github.com/wcm-io-qa/wcm-io-qa.github.io.git</site.deploy.url>

    <!-- SonarCloud -->
    <sonar.organization>wcm-io-qa</sonar.organization>
    <sonar.host.url>https://sonarcloud.io</sonar.host.url>

  </properties>

  <build>
    <extensions>

      <!-- Add wcm.io file header to code templates -->
      <extension>
        <groupId>io.wcm.maven</groupId>
        <artifactId>io.wcm.maven.global-build-tools-mixin</artifactId>
        <version>1</version>
      </extension>

    </extensions>
    <plugins>

      <!-- license check -->
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>license-maven-plugin</artifactId>
        <executions>
          <execution>
            <phase>validate</phase>
            <goals>
              <goal>check-file-header</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <!-- GitFlow settings only for this POM -->
      <plugin>
        <groupId>com.amashchenko.maven.plugin</groupId>
        <artifactId>gitflow-maven-plugin</artifactId>
        <inherited>false</inherited>
        <configuration>
          <gitFlowConfig>
            <releaseBranchPrefix>release/${project.artifactId}-</releaseBranchPrefix>
            <hotfixBranchPrefix>hotfix/${project.artifactId}-</hotfixBranchPrefix>
            <versionTagPrefix>${project.artifactId}-</versionTagPrefix>
          </gitFlowConfig>
        </configuration>
      </plugin>

      <!-- site configuration -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <dependencies>
          <dependency>
            <groupId>io.wcm.maven.skins</groupId>
            <artifactId>reflow-velocity-tools</artifactId>
            <version>1.0.2</version>
          </dependency>
          <!-- Reflow skin requires Velocity >= 1.7  -->
          <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
          </dependency>
        </dependencies>
        <configuration>
          <generateReports>true</generateReports>
          <inputEncoding>UTF-8</inputEncoding>
          <outputEncoding>UTF-8</outputEncoding>
        </configuration>
        <executions>
          <execution>
            <id>attach-descriptor</id>
            <goals>
              <goal>attach-descriptor</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

    </plugins>

    <pluginManagement>
      <plugins>

        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>license-maven-plugin</artifactId>
          <configuration>
            <licenseName>apache_v2</licenseName>
            <addJavaLicenseAfterPackage>false</addJavaLicenseAfterPackage>
            <projectName>wcm.io</projectName>
            <excludes>
              <exclude>**/*.json</exclude>
              <exclude>**/*.html</exclude>
            </excludes>
          </configuration>
        </plugin>

        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-javadoc-plugin</artifactId>
          <configuration>
            <excludePackageNames>*.impl:*.impl.*</excludePackageNames>
            <notimestamp>true</notimestamp>
          </configuration>
        </plugin>

        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-release-plugin</artifactId>
          <configuration>
            <projectVersionPolicyId>OddEvenVersionPolicy</projectVersionPolicyId>
          </configuration>
          <dependencies>
            <dependency>
              <groupId>org.apache.maven.release</groupId>
              <artifactId>maven-release-oddeven-policy</artifactId>
              <version>${maven-release-plugin.version}</version>
            </dependency>
          </dependencies>
        </plugin>

        <plugin>
          <groupId>com.amashchenko.maven.plugin</groupId>
          <artifactId>gitflow-maven-plugin</artifactId>
          <configuration>
            <projectVersionPolicyId>OddEvenVersionPolicy</projectVersionPolicyId>
          </configuration>
          <dependencies>
            <dependency>
              <groupId>org.apache.maven.release</groupId>
              <artifactId>maven-release-oddeven-policy</artifactId>
              <version>${maven-release-plugin.version}</version>
            </dependency>
          </dependencies>
        </plugin>
      </plugins>

    </pluginManagement>
  </build>

  <reporting>
    <plugins>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-project-info-reports-plugin</artifactId>
        <inherited>true</inherited>
        <reportSets>
          <reportSet>
            <reports>
              <report>index</report>
              <report>dependencies</report>
              <report>scm</report>
              <report>licenses</report>
              <report>summary</report>
            </reports>
          </reportSet>
        </reportSets>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-changes-plugin</artifactId>
        <configuration>
          <!-- Allow HTML markup in CDATA sections in changes reports -->
          <escapeHTML>false</escapeHTML>
          <!-- Do not generate links to teamlist reports -->
          <teamlist>none</teamlist>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <reportSets>
          <reportSet>
            <reports>
              <!-- select non-aggregate reports -->
              <report>report</report>
            </reports>
          </reportSet>
        </reportSets>
      </plugin>

    </plugins>
  </reporting>

  <profiles>
    <!-- profile used for building releases and deployment to sonatype/maven central -->
    <profile>
      <id>release-profile</id>
      <activation>
        <property>
          <name>performRelease</name>
          <value>true</value>
        </property>
      </activation>
      <build>
        <plugins>
          <!-- sign the build -->
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-gpg-plugin</artifactId>
            <inherited>true</inherited>
            <executions>
              <execution>
                <id>sign-artifacts</id>
                <phase>verify</phase>
                <goals>
                  <goal>sign</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
          <!-- configure staging process at sonatype.-->
          <plugin>
            <groupId>org.sonatype.plugins</groupId>
            <artifactId>nexus-staging-maven-plugin</artifactId>
            <inherited>true</inherited>
            <extensions>true</extensions>
            <configuration>
              <serverId>ossrh</serverId>
              <nexusUrl>https://oss.sonatype.org/</nexusUrl>
              <!-- Deployed artifacts should go to staging to be reviewed before publish -->
              <autoReleaseAfterClose>false</autoReleaseAfterClose>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

  <distributionManagement>
    <site>
      <id>${site.deploy.id}</id>
      <name>Maven Site Deployment</name>
      <url>${site.deploy.url}/${site.url.module.prefix}</url>
    </site>
  </distributionManagement>

</project>


text:
@interface UIView (SimplePositioning)

@property (nonatomic) CGPoint frameOrigin;
@property (nonatomic) CGSize frameSize;

@property (nonatomic) CGFloat frameX;
@property (nonatomic) CGFloat frameY;

@property (nonatomic) CGFloat frameRight; // modifies the origin, not the size
@property (nonatomic) CGFloat frameBottom; // modifies the origin, not the size

@property (nonatomic) CGFloat frameWidth;
@property (nonatomic) CGFloat frameHeight;

@property (nonatomic) CGFloat centerX;
@property (nonatomic) CGFloat centerY;

@end

redpajama_set_name: RedPajamaGithub


text:
module Barbecue
  module Thumbnails
    extend ActiveSupport::Concern

    included do
      serialize :thumbnail_sizes, Hash
      dragonfly_accessor :photo
      before_validation :reset_thumbnails
    end

    # User w_x_h = 400x250# or similar
    #
    def thumb(w_x_h)
      if sizes = thumbnail_sizes[w_x_h]
        ret = OpenStruct.new(sizes)
        ret.url = Dragonfly.app.remote_url_for(ret.uid)
        ret
      else
        thumbnail_sizes[w_x_h] = compute_sizes(w_x_h)
        update_column(:thumbnail_sizes,thumbnail_sizes)
        OpenStruct.new(thumbnail_sizes[w_x_h])
      end
    end

    private

    def compute_sizes(size)
      thumbnail = self.photo.thumb(size, format: :jpg).encode('jpg', '-quality 80')
      {
        uid: thumbnail.store,
        signature: thumbnail.signature,
        url: thumbnail.url,
        width: thumbnail.width,
        height: thumbnail.height
      }
    end

  end
end


text:
import 'colors'

export async function stage<T>(description: string, fn: () => T): Promise<T> {
  process.stderr.write((description + '...').grey)

  try {
    const result = await fn()
    process.stderr.write(' [OK]\n'.green)
    return result

  } catch (error) {
    process.stderr.write(' [FAILED]\n'.red)
    throw error
  }
}

export function note(...descriptions: string[]) {
  process.stderr.write(descriptions.join(' ') + '\n')
}


text:
#include "io/ServerSocket.h"
#include "io/DescriptorStream.h"

#ifndef WIN32
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#else
#pragma comment(lib, "Ws2_32.lib")
#endif /* !WIN32 */
#include <memory>
#include <utility>
#include <string>
#include "io/validation.h"
#include "core/logging/LoggerConfiguration.h"

namespace org {
namespace apache {
namespace nifi {
namespace minifi {
namespace io {

ServerSocket::ServerSocket(const std::shared_ptr<SocketContext> &context, const std::string &hostname, const uint16_t port, const uint16_t listeners = -1)
    : Socket(context, hostname, port, listeners),
      running_(true),
      logger_(logging::LoggerFactory<ServerSocket>::getLogger()) {
}

ServerSocket::~ServerSocket() {
  running_ = false;
  if (server_read_thread_.joinable())
    server_read_thread_.join();
}

/**
 * Initializes the socket
 * @return result of the creation operation.
 */
void ServerSocket::registerCallback(std::function<bool()> accept_function, std::function<void(io::BaseStream *)> handler) {
  auto fx = [this](std::function<bool()> accept_function, std::function<void(io::BaseStream *stream)> handler) {
    while (running_) {
      int fd = select_descriptor(1000);
      if (fd >= 0) {
        io::DescriptorStream stream(fd);
        handler(&stream);
        close_fd(fd);
      }
    }
  };
  server_read_thread_ = std::thread(fx, std::move(accept_function), std::move(handler));
}

void ServerSocket::close_fd(int fd) {
  std::lock_guard<std::recursive_mutex> guard(selection_mutex_);
  close(fd);
  FD_CLR(fd, &total_list_);
}

} /* namespace io */
} /* namespace minifi */
} /* namespace nifi */
} /* namespace apache */
} /* namespace org */


text:
/*
 *                                                               _
 *   _____  _                           ____  _                 |_|
 *  |  _  |/ \   ____  ____ __ ___     / ___\/ \   __   _  ____  _
 *  | |_| || |  / __ \/ __ \\ '_  \ _ / /    | |___\ \ | |/ __ \| |
 *  |  _  || |__. ___/. ___/| | | ||_|\ \___ |  _  | |_| |. ___/| |
 *  |_/ \_|\___/\____|\____||_| |_|    \____/|_| |_|_____|\____||_|
 *
 *  ===============================================================
 *             More than a coder, More than a designer
 *  ===============================================================
 *
 *  - Document: semantic.js
 *  - Author: aleen42
 *  - Description: A semantic module for specifying the meaning notations
 *  - Create Time: Oct 12nd, 2017
 *  - Update Time: Jul 19th, 2021
 *
 */

/* global require, module */
const {TokenType} = require('../common/tokenType');

function Semantic(parser) {
    this.parser = parser;
}

Semantic.prototype.errMsg = () => null; /** catch and ignore */

Semantic.prototype.getExpressionValue = function (root) {
    if (root === null) {
        return 0;
    }

    const leftHandExpression = val => {
        if (leftNode && leftNode.tokenType === TokenType.VAR) {
            this.parser.variables.filter(item => item === leftNode)[0].content.caseParamPtr.parameter += val;
        }
        return this.getExpressionValue(leftNode || rightNode) + (rightNode ? val : 0);
    };
    const {caseOperator, caseFunc, caseConst} = root.content;
    let {leftNode, rightNode} = caseOperator;
    return ({
        [TokenType.PLUS]: () => this.getExpressionValue(leftNode) + this.getExpressionValue(rightNode),
        [TokenType.MINUS]: () => this.getExpressionValue(leftNode) - this.getExpressionValue(rightNode),
        [TokenType.MUL]: () => this.getExpressionValue(leftNode) * this.getExpressionValue(rightNode),
        [TokenType.DIV]: () => this.getExpressionValue(leftNode) / this.getExpressionValue(rightNode),
        [TokenType.MOD]: () => this.getExpressionValue(leftNode) % this.getExpressionValue(rightNode),
        [TokenType.POWER]: () => Math.pow(this.getExpressionValue(leftNode), this.getExpressionValue(rightNode)),
        [TokenType.INCREMENT]: () => leftHandExpression(1),
        [TokenType.DECREMENT]: () => leftHandExpression(-1),
        [TokenType.FUNC]: () => caseFunc.mathFunc(this.getExpressionValue(caseFunc.childNode)),
        [TokenType.CONST_ID]: () => caseConst,
        [TokenType.VAR]: () => this.parser.variables.filter(item => item === root)[0].content.caseParamPtr.parameter,
    }[root.tokenType] || (() => 0))();
};

/** calculate the coordinate according to original one and changes on it */
Semantic.prototype.calculateCoordinate = function (horizontalExpression, verticalExpression) {
    let horizontalCoordinate = this.getExpressionValue(horizontalExpression);
    let verticalCoordinate = this.getExpressionValue(verticalExpression);

    const {scaleX, scaleY, rotateAngle, originX, originY} = this.parser;

    /** scale */
    horizontalCoordinate *= scaleX;
    verticalCoordinate *= scaleY;

    /** rotate */
    const temp = horizontalCoordinate * Math.cos(rotateAngle) + verticalCoordinate * Math.sin(rotateAngle);
    verticalCoordinate = verticalCoordinate * Math.cos(rotateAngle) - horizontalCoordinate * Math.sin(rotateAngle);
    horizontalCoordinate = temp;

    /** move */
    horizontalCoordinate += originX;
    verticalCoordinate += originY;

    return {
        x: horizontalCoordinate,
        y: verticalCoordinate,
    };
};

/** loop for drawing */
Semantic.prototype.draw = function (horizontalPtr, verticalPtr) {
    const {x, y} = this.calculateCoordinate(horizontalPtr, verticalPtr);
    this.parser.drawCallback(x, y);
};

/** remove a syntax tree */
Semantic.prototype.deleteExpressionTree = function (root) {
    if (root === null) {
        return;
    }

    const content = root.content;
    const tokenType = root.tokenType;
    if ([
        TokenType.PLUS, TokenType.MINUS, TokenType.MUL, TokenType.DIV, TokenType.POWER, TokenType.MOD,
    ].includes(tokenType)) {
        const {leftNode, rightNode} = content.caseOperator;
        this.deleteExpressionTree(leftNode);
        this.deleteExpressionTree(rightNode);
    } else if (tokenType === TokenType.FUNC) {
        this.deleteExpressionTree(content.caseFunc.childNode);
    }

    /** delete the root node */
    root = null;
};

module.exports = Semantic;


text:
FROM ubuntu:12.04
MAINTAINER Neil Armitage <narmitage@vmware.com>

RUN apt-get update
RUN apt-get install -y  puppet git tar openssh-server  wget rsync rubygems
RUN mkdir -p /etc/puppet/modules
RUN mkdir -p  /var/run/sshd
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
ADD ./tungsten.ini /etc/tungsten/tungsten.ini
ADD ./start.sh /usr/bin/start.sh
RUN chmod +x /usr/bin/start.sh
EXPOSE 7  22 2112 7800 7801 7802 7803 7804 7805 10000 10001 11999 12000 9999 3306 13306
CMD bash -C '/usr/bin/start.sh';'bash'


text:
package de.mirkosertic.bytecoder.core;

import de.mirkosertic.bytecoder.api.AnyTypeMatches;

public class BytecodeObjectTypeRef implements BytecodeTypeRef {

    private final String className;

    public static BytecodeObjectTypeRef fromRuntimeClass(final Class aClass) {
        return new BytecodeObjectTypeRef(aClass.getName());
    }

    public static BytecodeObjectTypeRef fromUtf8Constant(final BytecodeUtf8Constant aConstant) {
        return new BytecodeObjectTypeRef(aConstant.stringValue().replace("/","."));
    }

    public BytecodeObjectTypeRef(final String aClassName) {
        className = aClassName;
    }

    @Override
    public String name() {
        return className;
    }

    @Override
    public boolean isPrimitive() {
        return false;
    }

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

        final BytecodeObjectTypeRef that = (BytecodeObjectTypeRef) o;

        return className.equals(that.className);
    }

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

    @Override
    public boolean isArray() {
        return false;
    }

    @Override
    public boolean matchesExactlyTo(final BytecodeTypeRef aOtherType) {
        if (!(aOtherType instanceof BytecodeObjectTypeRef)) {
            return false;
        }
        if (AnyTypeMatches.class.getName().equals(className)) {
            return true;
        }
        return className.equals(((BytecodeObjectTypeRef) aOtherType).className);
    }

    @Override
    public boolean isVoid() {
        return false;
    }

    @Override
    public Object defaultValue() {
        return null;
    }
}


text:
package com.google.u2f.tools.httpserver;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.logging.Logger;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.simpleframework.http.core.Container;
import org.simpleframework.http.core.ContainerServer;
import org.simpleframework.transport.connect.Connection;
import org.simpleframework.transport.connect.SocketConnection;

import com.google.common.collect.ImmutableSet;
import com.google.u2f.server.ChallengeGenerator;
import com.google.u2f.server.DataStore;
import com.google.u2f.server.SessionIdGenerator;
import com.google.u2f.server.U2FServer;
import com.google.u2f.server.impl.BouncyCastleCrypto;
import com.google.u2f.server.impl.MemoryDataStore;
import com.google.u2f.server.impl.U2FServerReferenceImpl;
import com.google.u2f.tools.httpserver.servlets.EnrollDataServlet;
import com.google.u2f.tools.httpserver.servlets.EnrollFinishServlet;
import com.google.u2f.tools.httpserver.servlets.RequestDispatcher;
import com.google.u2f.tools.httpserver.servlets.SignDataServlet;
import com.google.u2f.tools.httpserver.servlets.SignFinishServlet;
import com.google.u2f.tools.httpserver.servlets.StaticHandler;

public class U2fHttpServer {
  private final static Logger Log = Logger.getLogger(U2fHttpServer.class.getSimpleName());

  private final Object lock = new Object();
  private final U2FServer u2fServer;

  private long sessionIdCounter = 0;

  public static void main(String[] args) throws InterruptedException {
    new U2fHttpServer();
  }

  public U2fHttpServer() {
    ChallengeGenerator challengeGenerator = new ChallengeGenerator() {
      @Override
      public byte[] generateChallenge(String accountName) {
        try {
          return Hex.decodeHex("1234".toCharArray());
        } catch (DecoderException e) {
          throw new RuntimeException(e);
        }
      }
    };

    SessionIdGenerator sessionIdGenerator = new SessionIdGenerator() {
      @Override
      public String generateSessionId(String accountName) {
        return new StringBuilder()
          .append("sessionId_")
          .append(sessionIdCounter++)
          .append("_")
          .append(accountName)
          .toString();
      }
    };

    X509Certificate trustedCertificate;
    try {
      trustedCertificate = (X509Certificate) CertificateFactory.getInstance("X.509")
          .generateCertificate(new ByteArrayInputStream(Hex.decodeHex((
              "308201433081eaa0030201020209012333009941964658300a06082a8648ce3d"
                  + "040302301b3119301706035504031310476e756262792048534d2043412030"
                  + "303022180f32303132303630313030303030305a180f323036323035333132"
                  + "33353935395a30303119301706035504031310476f6f676c6520476e756262"
                  + "7920763031133011060355042d030a00012333009941964658305930130607"
                  + "2a8648ce3d020106082a8648ce3d03010703420004aabc1b97a7c391f8b1fe"
                  + "5280a65cf27890409bdc392e181ff00ccf39599461d583f3351b21602cf99e"
                  + "2fe71e7f838658b42df49f06b8446d375d2aaaa8e317a1300a06082a8648ce"
                  + "3d0403020348003045022037788207c2239373b289169cfd3500b54fe92903"
                  + "e6772ea995cd2ce4a670fba5022100dfbfe7da528600be0d6125060d029f40"
                  + "c647bc053e35226fffb66cd7f4609b49").toCharArray())));
    } catch (CertificateException e) {
      throw new RuntimeException(e);
    } catch (DecoderException e) {
      throw new RuntimeException(e);
    }
    DataStore dataStore = new MemoryDataStore(sessionIdGenerator);
    dataStore.addTrustedCertificate(trustedCertificate);

    // this implementation will only accept signatures from http://localhost:8080
    u2fServer = new U2FServerReferenceImpl(challengeGenerator, dataStore,
        new BouncyCastleCrypto(), ImmutableSet.of("http://localhost:8080"));
    Container dispatchContainer = new RequestDispatcher()
        .registerContainer("/", new StaticHandler("text/html","html/index.html"))
        .registerContainer("/enroll", new StaticHandler("text/html","html/enroll.html"))
        .registerContainer("/enrollData.js", new EnrollDataServlet(u2fServer))
        .registerContainer("/enrollFinish", new EnrollFinishServlet(u2fServer))
        .registerContainer("/sign", new StaticHandler("text/html","html/sign.html"))
        .registerContainer("/signData.js", new SignDataServlet(u2fServer))
        .registerContainer("/signFinish", new SignFinishServlet(u2fServer));

    try {
      Connection connection = new SocketConnection(new ContainerServer(dispatchContainer));

      try {
        connection.connect(new InetSocketAddress("0.0.0.0", 8080));

        synchronized (lock) {
          lock.wait();
        }
      } finally {
        connection.close();
      }
    } catch (IOException e) {
      Log.severe("Error with HTTP server: " + e);
      return;
    } catch (InterruptedException e) {
      Log.info("Interrupted");
      return;
    }
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.manaldush.telnet.protocol.processors Class Hierarchy</title>
<meta name="date" content="2017-11-07">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package com.manaldush.telnet.protocol.processors

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

com.manaldush.telnet.protocol.processors.AbortOutputProcessor (implements com.manaldush.telnet.protocol.ITelnetCommandProcessor)

com.manaldush.telnet.protocol.processors.EraseCharacterProcessor (implements com.manaldush.telnet.protocol.ITelnetCommandProcessor)

com.manaldush.telnet.protocol.processors.EraseLineProcessor (implements com.manaldush.telnet.protocol.ITelnetCommandProcessor)

com.manaldush.telnet.protocol.processors.InterruptionProcessor (implements com.manaldush.telnet.protocol.ITelnetCommandProcessor)

com.manaldush.telnet.protocol.processors.KeepAliveProcessor (implements com.manaldush.telnet.protocol.ITelnetCommandProcessor)

com.manaldush.telnet.protocol.processors.NegotiationOptionsProcessor (implements com.manaldush.telnet.protocol.ITelnetCommandProcessor)

com.manaldush.telnet.protocol.processors.SubNegotiationEndCommand (implements com.manaldush.telnet.protocol.ITelnetCommandProcessor)

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
namespace ProcessingJsonInDotNet
{
    using System.Xml.Linq;

    using Newtonsoft.Json;

    public class XmlToJsonParser
    {
        public string Parse(string fileName)
        {
            var doc = XDocument.Load(fileName);
            return JsonConvert.SerializeXNode(doc);
        }
    }
}


text:
package http_listener

import (
	"sync"
	"testing"
	"time"

	"github.com/influxdata/telegraf/plugins/parsers"
	"github.com/influxdata/telegraf/testutil"

	"bytes"
	"github.com/stretchr/testify/require"
	"net/http"
)

const (
	testMsg = "cpu_load_short,host=server01 value=12.0 1422568543702900257\n"

	testMsgs = `cpu_load_short,host=server02 value=12.0 1422568543702900257
cpu_load_short,host=server03 value=12.0 1422568543702900257
cpu_load_short,host=server04 value=12.0 1422568543702900257
cpu_load_short,host=server05 value=12.0 1422568543702900257
cpu_load_short,host=server06 value=12.0 1422568543702900257
`
	badMsg = "blahblahblah: 42\n"

	emptyMsg = ""
)

func newTestHttpListener() *HttpListener {
	listener := &HttpListener{
		ServiceAddress: ":8186",
	}
	return listener
}

func TestWriteHTTP(t *testing.T) {
	listener := newTestHttpListener()
	parser, _ := parsers.NewInfluxParser()
	listener.SetParser(parser)

	acc := &testutil.Accumulator{}
	require.NoError(t, listener.Start(acc))
	defer listener.Stop()

	time.Sleep(time.Millisecond * 25)

	// post single message to listener
	resp, err := http.Post("http://localhost:8186/write?db=mydb", "", bytes.NewBuffer([]byte(testMsg)))
	require.NoError(t, err)
	require.EqualValues(t, 204, resp.StatusCode)

	time.Sleep(time.Millisecond * 15)
	acc.AssertContainsTaggedFields(t, "cpu_load_short",
		map[string]interface{}{"value": float64(12)},
		map[string]string{"host": "server01"},
	)

	// post multiple message to listener
	resp, err = http.Post("http://localhost:8186/write?db=mydb", "", bytes.NewBuffer([]byte(testMsgs)))
	require.NoError(t, err)
	require.EqualValues(t, 204, resp.StatusCode)

	time.Sleep(time.Millisecond * 15)
	hostTags := []string{"server02", "server03",
		"server04", "server05", "server06"}
	for _, hostTag := range hostTags {
		acc.AssertContainsTaggedFields(t, "cpu_load_short",
			map[string]interface{}{"value": float64(12)},
			map[string]string{"host": hostTag},
		)
	}
}

// writes 25,000 metrics to the listener with 10 different writers
func TestWriteHTTPHighTraffic(t *testing.T) {
	listener := &HttpListener{ServiceAddress: ":8286"}
	parser, _ := parsers.NewInfluxParser()
	listener.SetParser(parser)

	acc := &testutil.Accumulator{}
	require.NoError(t, listener.Start(acc))
	defer listener.Stop()

	time.Sleep(time.Millisecond * 25)

	// post many messages to listener
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			for i := 0; i < 500; i++ {
				resp, err := http.Post("http://localhost:8286/write?db=mydb", "", bytes.NewBuffer([]byte(testMsgs)))
				require.NoError(t, err)
				require.EqualValues(t, 204, resp.StatusCode)
			}
			wg.Done()
		}()
	}

	wg.Wait()
	time.Sleep(time.Millisecond * 50)
	listener.Gather(acc)

	require.Equal(t, int64(25000), int64(acc.NMetrics()))
}

func TestReceive404ForInvalidEndpoint(t *testing.T) {
	listener := newTestHttpListener()
	listener.parser, _ = parsers.NewInfluxParser()

	acc := &testutil.Accumulator{}
	require.NoError(t, listener.Start(acc))
	defer listener.Stop()

	time.Sleep(time.Millisecond * 25)

	// post single message to listener
	resp, err := http.Post("http://localhost:8186/foobar", "", bytes.NewBuffer([]byte(testMsg)))
	require.NoError(t, err)
	require.EqualValues(t, 404, resp.StatusCode)
}

func TestWriteHTTPInvalid(t *testing.T) {
	time.Sleep(time.Millisecond * 250)

	listener := newTestHttpListener()
	listener.parser, _ = parsers.NewInfluxParser()

	acc := &testutil.Accumulator{}
	require.NoError(t, listener.Start(acc))
	defer listener.Stop()

	time.Sleep(time.Millisecond * 25)

	// post single message to listener
	resp, err := http.Post("http://localhost:8186/write?db=mydb", "", bytes.NewBuffer([]byte(badMsg)))
	require.NoError(t, err)
	require.EqualValues(t, 500, resp.StatusCode)
}

func TestWriteHTTPEmpty(t *testing.T) {
	time.Sleep(time.Millisecond * 250)

	listener := newTestHttpListener()
	listener.parser, _ = parsers.NewInfluxParser()

	acc := &testutil.Accumulator{}
	require.NoError(t, listener.Start(acc))
	defer listener.Stop()

	time.Sleep(time.Millisecond * 25)

	// post single message to listener
	resp, err := http.Post("http://localhost:8186/write?db=mydb", "", bytes.NewBuffer([]byte(emptyMsg)))
	require.NoError(t, err)
	require.EqualValues(t, 204, resp.StatusCode)
}

func TestQueryAndPingHTTP(t *testing.T) {
	time.Sleep(time.Millisecond * 250)

	listener := newTestHttpListener()
	listener.parser, _ = parsers.NewInfluxParser()

	acc := &testutil.Accumulator{}
	require.NoError(t, listener.Start(acc))
	defer listener.Stop()

	time.Sleep(time.Millisecond * 25)

	// post query to listener
	resp, err := http.Post("http://localhost:8186/query?db=&q=CREATE+DATABASE+IF+NOT+EXISTS+%22mydb%22", "", nil)
	require.NoError(t, err)
	require.EqualValues(t, 200, resp.StatusCode)

	// post ping to listener
	resp, err = http.Post("http://localhost:8186/ping", "", nil)
	require.NoError(t, err)
	require.EqualValues(t, 204, resp.StatusCode)
}


text:
package testutils

import (
	"os"
	"testing"
)

// Setenv sets os environment variable key to value.
// Registers the environment variable to be set to its original value at the end
// of the test.
//
// This prevents cross-talk between tests, as some may implicitly come to rely on other tests running before them in
// order to succeed.
func Setenv(t *testing.T, key, value string) {
	old, set := os.LookupEnv(key)
	err := os.Setenv(key, value)
	if err != nil {
		t.Fatalf("setting env variable %q: %v", key, err)
	}

	t.Cleanup(func() {
		if !set {
			err = os.Unsetenv(key)
		} else {
			err = os.Setenv(key, old)
		}
		if err != nil {
			t.Errorf("resetting env variable %q: %v", key, err)
		}
	})
}


text:
<?php
return [
    // Cache life time used for time aware queries
    'lifeTime' => 5
];


text:
<!doctype html>

  <meta charset="utf-8">
  <META http-equiv="refresh" content="0;URL=http://www.dpbolvw.net/8s75gv30v2IQRKORKOIKJSMQRRSIKNMKJKNMKRJJJ">

  <title>Ad Tracking</title>
  <meta name="description" content="Ad Tracking">
  <meta name="author" content="Ad Tracking">

This page is for ad tracking purposes.


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**resource_usage_id** | **int** | The resource usage ID. |
**resource_type** | **string** | The resource type. |
**cost** | **int** | The call cost. | [optional]
**description** | **string** | The description. | [optional]
**used_at** | **string** | The start resource using time in the selected timezone in format: YYYY-MM-DD HH:mm:SS |
**transaction_id** | **int** | The transaction ID. |
**resource_quantity** | **int** | The resource quantity. | [optional]
**unit** | **string** | The resource unit. | [optional]
**ref_call_id** | **int** | The reference to call. | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
package com.aspose.imaging.examples.Photoshop;

import com.aspose.imaging.examples.Utils;

public class DetectFlattenedPSD
{
    public static void main(String... args)
    {
		//ExStart:DetectFlattenedPSD
		String dataDir = Utils.getSharedDataDir() + "Photoshop/";
		String flattenPath = dataDir + "sample.psd";
        // Create an instance of Image class and load PSD file as image.
		com.aspose.imaging.fileformats.psd.PsdImage psdImage;
		try (com.aspose.imaging.Image objImage = com.aspose.imaging.Image.load(flattenPath))
		{

			// Cast image object to PSD image
			psdImage = (com.aspose.imaging.fileformats.psd.PsdImage) objImage;
			// do processing

			// Get the true value if PSD is flatten and false in case the PSD is not flatten.
			System.out.println(psdImage.isFlatten());
		}

        //ExEnd:DetectFlattenedPSD
    }

}


text:
/**
 * playlistjs Actions built ontop of jquery ui.
 */
(function(define) {
    "use strict";
define(['playlist', 'jQuery'], function(Playlist, $) {

    var Actionable = Playlist.Actionable;

    /**
     * A playlistjs action that displays a jquery dialog and completes when the dialog is closed.
     *
     * @param {[Object]} options:
     *     selector: [string] - optional - jquery selector on jqueryui's .dialog will be called on. If not
     *         supplied one will be created for you using the title and content options.
     *     title: [string] - optional - dialog title text
     *     content: [string | function] - optional - content o be appended into the body of the dialog.
     *     dialogOptions: [object] - optional -see http://api.jqueryui.com/dialog/
     */
    function DialogAction (options) {
        var that = this;
        var widget = options.selector ? $(options.selector) : $("<div/>", {title: options.title});

        if (typeof options.content === "string") {
            widget.append($("<p/>", {"text": options.content}));
        } else if (typeof options.content === "function") {
            widget.append(options.content());
        }

        widget.on( "dialogclose", function( event, ui ) {
            that._widget.remove();
            that.complete();
        });

        //todo prevent something?
        this._dialogOptions = options.dialogOptions;
        this._widget = widget;
        Actionable.call(this, options);
    }
    DialogAction.prototype = Object.create(Actionable.prototype);
    Playlist.registerAction("dialog", DialogAction);

    DialogAction.prototype.begin = function (value) {
        this._widget.dialog(this._dialogOptions);
    };

});

})(typeof define == 'function' && define.amd
    ? define
    : function (deps, factory) {
        "use strict";
        factory(window.Playlist, window.$);
    }
    // Boilerplate for AMD, and browser global
);


text:
<?php

namespace SlimBoilerplate\Layout;

use Slim\View;

class LayoutView extends View
{
	public static $template_vars = array(
		'title'              => '',
		'defaultTitle'       => SITE_NAME,
		'description'        => '',
		'defaultDescription' => '',
		'keywords'           => '',
		'js'                 => '',
		'jsCallback'         => '',
		'css'                => '',
	);
	protected $layoutFile = '_layout.php';
	protected $layoutData = array();

	public function __construct()
	{

		parent::__construct();
	}

	public static function addCss($css)
	{
        if(strpos($css, 'http') === false)
            $css = baseUrl() . $css;

		static::$template_vars['css'][] = $css;
	}

	public static function addJs($js, $callback = '')
	{
        if(strpos($js, 'http') === false)
            $js = baseUrl() . $js;

		static::$template_vars['js'][] = $js;

		if ($callback)
			static::$template_vars['jsCallback'][$js] = $callback;
	}

	public static function setDefaultTitle($text)
	{
		static::$template_vars['defaultTitle'] = $text;
	}

	public static function setDefaultDescription($text)
	{
		static::$template_vars['defaultDescription'] = $text;
	}

	public static function setTitle($text)
	{
		static::$template_vars['title'] = $text;
	}

	public static function setDescription($text)
	{
		static::$template_vars['description'] = $text;
	}

	public static function setKeywords($text)
	{
		static::$template_vars['keywords'] = $text;
	}

	public function setLayoutFile($layoutFile = NULL, $layoutData = array())
	{
		$this->layoutFile = $layoutFile;
		$this->layoutData = $layoutData;
	}

	public function setLayoutData($layoutData = array())
	{
		$this->layoutData = $layoutData;
	}

	public function render($template, $data = null)
	{
		return $this->renderLayout(parent::render($template, $data));
	}

	public function renderLayout($output)
	{
		$templatePathname = $this->getTemplatePathname($this->layoutFile);
		if (!is_file($templatePathname)) {
			throw new \RuntimeException("View cannot render `$this->layoutFile` : the layout template does not exist");
		}

		extract($this->layoutData);
		extract(static::$template_vars);

		ob_start();
		require $templatePathname;

		return ob_get_clean();
	}

}


text:
package org.eclipse.php.internal.ui.wizards;

import java.util.*;

import org.eclipse.core.runtime.*;
import org.eclipse.jface.util.SafeRunnable;
import org.eclipse.php.internal.ui.PHPUiPlugin;
import org.eclipse.php.ui.wizards.ICompositeFragmentFactory;

/**
 * Server wizard fragments registry for all the wizardAndCompositeFragments
 * extentions.
 */
public class WizardFragmentsFactoryRegistry {

	private static final String EXTENSION_POINT_NAME = "wizardAndCompositeFragments"; //$NON-NLS-1$
	private static final String FRAGMENT_TAG = "wizardAndCompositeFragment"; //$NON-NLS-1$
	private static final String ID_ATTRIBUTE = "id"; //$NON-NLS-1$
	private static final String FRAGMENTS_GROUP_ID = "fragmentsGroupID"; //$NON-NLS-1$
	private static final String CLASS_ATTRIBUTE = "class"; //$NON-NLS-1$
	private static final String PLACE_AFTER_ATTRIBUTE = "placeAfter"; //$NON-NLS-1$

	// Hold a Dictionary of Lists that contains the factories used for the
	// creation of the fragments.
	// This structure will be deleted from the memory once all the factories
	// were created.
	private Map<String, List<FragmentsFactory>> fragments;

	private static WizardFragmentsFactoryRegistry instance;

	private Map<String, Map<String, ICompositeFragmentFactory>> factories;

	public static Map<String, ICompositeFragmentFactory> getFragmentsFactories(String fragmentsGroupID) {
		WizardFragmentsFactoryRegistry registry = getInstance();
		Map<String, ICompositeFragmentFactory> factories = registry.factories.get(fragmentsGroupID);
		if (factories == null) {
			factories = new LinkedHashMap<>();
			List<FragmentsFactory> fragments = registry.fragments.get(fragmentsGroupID);
			for (int i = 0; i < fragments.size(); i++) {
				FragmentsFactory factory = fragments.get(i);
				factories.put(factory.getID(), factory.createFragmentFactory());
			}
			registry.factories.put(fragmentsGroupID, factories);
			// Clear the fragments mapping, since it is no longer needed.
			registry.fragments.remove(fragmentsGroupID);
		}
		return factories;
	}

	private WizardFragmentsFactoryRegistry() {
		factories = new HashMap<>();
		fragments = new HashMap<>();
		IExtensionRegistry registry = Platform.getExtensionRegistry();
		IConfigurationElement[] elements = registry.getConfigurationElementsFor(PHPUiPlugin.ID, EXTENSION_POINT_NAME);

		for (int i = 0; i < elements.length; i++) {
			final IConfigurationElement element = elements[i];
			if (FRAGMENT_TAG.equals(element.getName())) {
				String id = element.getAttribute(ID_ATTRIBUTE);
				String groupID = element.getAttribute(FRAGMENTS_GROUP_ID);
				String placeAfter = element.getAttribute(PLACE_AFTER_ATTRIBUTE);
				List<FragmentsFactory> list = fragments.get(groupID);
				if (list == null) {
					list = new ArrayList<>();
					fragments.put(groupID, list);
				}
				if (element.getNamespaceIdentifier().equals(PHPUiPlugin.ID)) {
					// Make sure that extentions that exists in this plugin will
					// appear ahead of all others
					// when the user-class calls for getFragmentsFactories().
					list.add(0, new FragmentsFactory(element, id, placeAfter));
				} else {
					list.add(new FragmentsFactory(element, id, placeAfter));
				}
			}
		}
		// Sort all the fragment groups
		Iterator<String> keys = fragments.keySet().iterator();
		while (keys.hasNext()) {
			sortFragmentsByPlace(fragments.get(keys.next()));
		}
	}

	// Sort the fragments according to the 'place-after' attribute
	private void sortFragmentsByPlace(List<FragmentsFactory> fragments) {
		// Scan the fragments and separate the fragments that lacks the
		// place-after property from
		// those that have it.
		List<List<FragmentsFactory>> rootsFragments = new ArrayList<>();
		List<List<FragmentsFactory>> nonRootFragments = new ArrayList<>();
		for (int i = 0; i < fragments.size(); i++) {
			FragmentsFactory factory = fragments.get(i);
			if (factory.getPlaceAfter() == null || factory.getPlaceAfter().equals("")) { //$NON-NLS-1$
				addAsList(rootsFragments, factory);
			} else {
				addAsList(nonRootFragments, factory);
			}
		}

		// Traverse over the non-root fragments and position them.
		for (int i = 0; i < nonRootFragments.size(); i++) {
			List<FragmentsFactory> fragmentsGroup = nonRootFragments.get(i);
			// try to move it to the roots fragments first (order is important).
			boolean moved = placeFragment(rootsFragments, fragmentsGroup);
			if (!moved) {
				// in case we can't find it there, try to move it inside the
				// non-roots fragments.
				moved = placeFragment(nonRootFragments, fragmentsGroup);
			}
			if (!moved) {
				// move it to the roots anyway, since there is an error in the
				// extention definitions.
				FragmentsFactory invalidFactory = getFactory(nonRootFragments, i);
				addAsList(rootsFragments, invalidFactory);
				PHPUiPlugin.log(new Status(IStatus.WARNING, PHPUiPlugin.ID, 0,
						"Invalid 'placeAfter' id (" + invalidFactory.getPlaceAfter() + ')', null)); //$NON-NLS-1$
			}
		}

		// At this stage, the root fragments should hold all the fragments
		// sorted.
		fragments.clear();
		for (int i = 0; i < rootsFragments.size(); i++) {
			List<FragmentsFactory> list = rootsFragments.get(i);
			for (int j = 0; j < list.size(); j++) {
				fragments.add(list.get(j));
			}
		}
	}

	private boolean placeFragment(List<List<FragmentsFactory>> targetFactories, List<FragmentsFactory> factoriesGroup) {
		if (factoriesGroup == null || factoriesGroup.size() == 0) {
			return true;
		}
		FragmentsFactory factory = factoriesGroup.get(0);
		String placeAfter = factory.getPlaceAfter();
		for (int i = 0; i < targetFactories.size(); i++) {
			List<FragmentsFactory> list = targetFactories.get(i);
			for (int j = 0; j < list.size(); j++) {
				FragmentsFactory nextFactory = list.get(j);
				if (nextFactory.getID().equals(placeAfter)) {
					// This list is the list we should add to
					if (list.size() > j + 1) {
						list.addAll(j + 1, factoriesGroup);
					} else {
						// add it to the end
						list.addAll(factoriesGroup);
					}
					return true;
				}
			}
		}
		return false;
	}

	private FragmentsFactory getFactory(List<List<FragmentsFactory>> nonRootFragments, int i) {
		List<FragmentsFactory> list = nonRootFragments.get(i);
		return list.get(0);
	}

	// add an element to a List by wrapping it in another List.
	private void addAsList(List<List<FragmentsFactory>> target, FragmentsFactory element) {
		List<FragmentsFactory> list = new ArrayList<>();
		list.add(element);
		target.add(list);
	}

	private static WizardFragmentsFactoryRegistry getInstance() {
		if (instance == null) {
			instance = new WizardFragmentsFactoryRegistry();
		}
		return instance;
	}

	private class FragmentsFactory {

		private IConfigurationElement element;
		private ICompositeFragmentFactory factory;
		private String id;
		private String placeAfter;

		public FragmentsFactory(IConfigurationElement element, String id, String placeAfter) {
			this.element = element;
			this.id = id;
			this.placeAfter = placeAfter;
		}

		public ICompositeFragmentFactory createFragmentFactory() {
			SafeRunner.run(new SafeRunnable(
					"Error creation extension for extension-point org.eclipse.php.server.ui.wizardAndCompositeFragments") { //$NON-NLS-1$
				@Override
				public void run() throws Exception {
					factory = (ICompositeFragmentFactory) element.createExecutableExtension(CLASS_ATTRIBUTE);
				}
			});
			return factory;
		}

		public String getID() {
			return id;
		}

		public String getPlaceAfter() {
			return placeAfter;
		}
	}

}


text:
function prec = projection(rec, dims)
  % Returns the projection of rec onto dimensions dims
  if max(dims) > rec.dim
    error('Dimension too large')
  end
  pxmin = rec.xmin(dims);
  pxmax = rec.xmax(dims);
  prec = Rec([pxmin; pxmax]);
end


text:
#ifndef CLI_EXIT_COMMAND_H
#define CLI_EXIT_COMMAND_H

#include "cli_command.h"

namespace cli {

/**
 * @brief The ExitCommand class exit command.
 * stops execution of the whole application on user's demand.
 */
class ExitCommand : public Command
{
public:
    /**
     * @brief ExitCommand constructor
     * @param is input stream.
     * @param os output stream.
     * @param params command line parameters.
     */
    ExitCommand(std::istream &is, std::ostream &os, const ParamsListType &params);

    /**
     * @brief run entering point for the command.
     * @param env environment.
     * @return exit code (bash like).
     */
    int run(Environment &env) override;

    /**
     * @brief name helper function helps identify the type of command object.
     * @return name of the command object.
     */
    std::string name() const override;
private:
    int exit_code_;
};

} // namespace cli

#endif // CLI_EXIT_COMMAND_H


text:
layout: page
title: HackYourResearch & OpenESR
tags: [about, open science, research, communs]
modified:
comments: true
image:
  feature: hyphd.jpg
  credit: Photonquantique

---

*Click ! and go directly to the french or the english version*

1. [Français](#français)
  - [HackYourResearch](#hackyourphd)
  - [OpenESR](#openESR)
  - [Inno3](#inno3)
2. [English](#english)
3. [Presentations](#presentations)

### Français

Cette page récapitule différents projets associatifs et entreprenariaux en cours ou déjà réalisés afin d'explorer les contours de l'enseignement supérieur et de la recherche (ESR), de la production des savoirs dans des sociétés numérisées et soumises à de nouvelles barrières "enclosures" de plus en plus subtiles et qu'il s'agit de questionner.

Ces projets sont inclus dans des démarches de recherche-action, c'est-à-dire qu'ils s'inscrivent dans l'action, le _hack_ en tant qu'approche de contournement pour tester/expérimenter des modèles alternatifs (_open_, communs) au sein de nos régimes de savoirs tout en s'appuyant sur une approche réflexive et des épistémologies situées.

## HackYourPhd -> HackYourResearch

J'ai cofondé [HackYourPhD](http://hackyourphd.org/) une communauté *Open Science* en janvier 2013 avec [Guillaume Dumas](http://www.extrospection.eu/) chercheur en sciences cognitives. HackYourPhD s'est structuré en association (loi 1901) en Août 2014 et a proposé pendant plusieurs années une veille à ce sujet, des formations à la programmation pour la recherche.

En 2020, HackYourPhD est devenu [HackYourResearch](http://hyr.science/) pour plusieurs raisons. L'_open science_ telle que nous l'explorions à ses débuts a pris un tournant institutionnel à partir de 2018. Les formations et la veille que nous faisions sur les outils numériques, les pratiques à acquérir pour une recherche plus reproductible, de qualité, etc. ont peu à peu été couvertes par les établissements de recherche et les universités. Mais il est apparu que nos questionnements sur l'Enseignement et la Recherche et la manière dont les savoirs sont produits, diffusés, réappropriés restaient toujours d'actualités. C'est pour cela que HackYourResearch est né afin de continuer à proposer un espace d'exploration et d'expérimentation sur nos façons d'éprouver la recherche et nos rapports aux savoirs comme communs.

### Nos missions

HackYourResearch :

- partager des  **actualités sur l'open science, l'Enseignement Supérieur et la Recherche** par le biais d'une veille collaborative sur les réseaux sociaux, principalement [Facebook](https://www.facebook.com/groups/hackyourresearch/) et [Twitter](https://twitter.com/hackresearch) ;

- organiser **des évènements** en France, notamment des ateliers introductifs et des débats sur l'*open science* (cf. notre page événement en [français](http://hackyourphd.org/evenements/) et en [anglais](http://hackyourphd.org/en/event/)). Nous avons mené des **ateliers de formation au code** (python) [Open Geek](https://github.com/HackYourResearch/ateliers-open-geek)

- produire des **contenus en ligne** pour faire découvrir différentes facettes de l'*open science* et les différents profils qui y participent. Le blog HackYourResearch contient divers articles, interviews mais aussi des formats plus originaux pour communiquer à ce sujet (e.g. [flyers](http://hackyourphd.org/en/flyers/)), [ebook](http://hackyourphd.org/wp-content/uploads/2016/04/Ebook_Final_VF_LD.pdf). Nous avons interviewé plus d'une soixantaine de personnes dont les propos sont disponibles sur [Archive.org](https://archive.org/details/@hackyourphd)

### Quelques évènements et ateliers organisés

- 2021 [Remix ta thèse : des souris et des profs](https://openlaw.fr/blog/retour-sur-latelier-2040-des-souris-et-des-profs)

- 2021 [Participation au GT Science Ouverte & Société du CIS (Centre Internet & Société)](https://cis.cnrs.fr/science-ouverte-et-societe/)

- 2020 [Participation à la rédaction du mémorandum Covid-19 : pour du libre et de l'open en conscience](https://covid19-open.frama.io/memo/)

- 2020 [Sprint de traduction collaborative](https://hyr.science/2020/05/26-06-20-nouvelle-date-et-nouveau-format-100-en-ligne-pour-le-sprint-dedition-et-de-traduction-collaborative-science-ouverte/) avec l'URFIST de Bordeaux

- De 2015 à 2017 : [Ateliers Open Geek](http://hackyourphd.org/ateliers-open-geek/) .
- En décembre 2015 [Hackathon HackRepNum 2015](http://hackyourphd.org/2015/11/hackrepnum-un-hackathon-recherche-autour-de-la-loi-sur-le-numerique-samedi-12-decembre-a-la-paillasse/)

## À la rencontre des acteurs de l'*open science* et des communs

Depuis 2013, donner la parole à celles et ceux qui participent à façonner le régime des savoirs dans lequel nous nous trouvons a été une ligne directrice. Cela a pris la forme d'enquêtes ethnographiques participatives et ouvertes évoluant au fil des années, mais toujours dans l'idée de montrer la diversité d'actions à l'oeuvre autour de formules telles que _open_ et communs.

### OpenESR

En 2020, avec inno3 et HackYourResearch, un temps d'échange (webinaires) a été initié. L'objectif était d'inviter différentes personnes impliquées dans des projets sur les communs et l'_open_ (au sein de la recherche ou en dehors) afin d'apprendre de ces expériences et porter un regard réflexif sur ce que "pourrait être" l'enseignement supérieur et la recherche aujourd'hui.
Le [site OpenESR](https://openesr.frama.io/rencontres) est dédié à ces rencontres.

### HackYourPhD USA et Québec (2013-2015)

Avec HackYourPhD, avant le début de mon doctorat, j'avais débuté une première exploration de la thématique *Open Science* / Science ouverte [au Québec](http://hackyourphd-quebec.strikingly.com/) puis aux Etats-Unis. Durant l'été 2013, j'ai réalisé un grand tour des USA pour rencontrer des acteurs clefs de l'*Open Science* et mieux comprendre les racines de ce mouvement. Ce projet [HackYourPhD aux States](http://hackyourphd-aux-states.strikingly.com/) a été financé par une campagne de financement participatif (*crowdfunding)*.

#### Livre : Portraits de jeunes chercheurs de la génération #OpenScience (2015)

Un livre a été publié en ligne suite au voyage HackYourPhDUSA. Il est disponible en [français](http://hackyourphd.org/wp-content/uploads/2016/04/Ebook_Final_VF_LD.pdf) et en [anglais](http://hackyourphd.org/wp-content/uploads/2016/04/Ebook_Final_ENG-ld.pdf)

#### Interviews _Open Science_

Découvrez plus de 80 interviews sur le profil HackYourPhD d'[archive.org](https://archive.org/hackyourphd)

## Inno3 (2020-...)

En 2019, j'ai rejoint le cabinet de conseil [inno3](https://inno3.fr/) spécialisé en innovation ouverte, _open data_ et _open source_ . Fondé par le juriste Benjamin Jean, nous accompagnons différents acteurs (établissements publics, entreprises, collectivités) à saisir les grands enjeux organisationels, juridiques, techniques qu'implique l'adoption du "numérique" et cela en employant des modèles ouverts et orientés vers la création de communs. J'y mène au côté d'une équipe dynamique des projets de recherche-action ancrés dans les valeurs du libre et des communs.

### DRISS : _Digital Research in Science & Society_ (2019-2020)

En 2019, j'ai crée avec Constance de Quatrebarbes une société [DRISS](https://driss.org/) (_Digital Research in Science & Society_). En premier lieu, cela nous a permis d'offrir des formations auprès d'universités et d'écoles de l'ESR. Ces formations modulaires et ancrées dans des immersions pratiques ont pour objet de donner des clefs de compréhension de l'_open_ et de la _data science_ tout en développant un regard critique et réflexif sur les transformations qu'apporte le numérique.

------

### English

This page summarizes various associative and entrepreneurial projects in progress or already completed in order to explore the scope of higher education and research (HRE), of knowledge production in digitalized societies and subjected to new "enclosures" barriers that are increasingly subtle and that need to be questioned.

These projects are included in action-research approaches, i.e. they are part of the _hack_ as a counter-action approach to test/experiment alternative models (_open_, common) within our knowledge regimes while relying on a reflexive approach and situated epistemologies.

## HackYourPhd -> HackYourResearch

I co-founded [HackYourPhD](http://hackyourphd.org/) an *Open Science* community in January 2013 with [Guillaume Dumas](http://www.extrospection.eu/) a cognitive science researcher. HackYourPhD has been structured as an association (law 1901) in August 2014 and has offered for several years a watch on this subject, training in programming for research.

In 2020, HackYourPhD became [HackYourResearch](http://hyr.science/) for several reasons. The _open science_ as we initially explored it took an institutional turn in 2018. The training and monitoring that we were doing on digital tools, on the practices to achieve more reproducible, quality research, etc. were gradually covered by research institutions and universities. But it appeared that our questions on Education and Research and the way in which knowledge is produced, disseminated and reappropriated were still relevant. That's why HackYourResearch was born in order to continue to offer a space for exploration and experimentation on our ways of experiencing research and our relationship to knowledge as common.

### Our missions

HackYourResearch :

- sharing **news on open science, higher education and research** through a collaborative watch on social networks, mainly [Facebook](https://www.facebook.com/groups/hackyourresearch/) and [Twitter](https://twitter.com/hackresearch) ;

- organises **events** in France, including introductory workshops and debates on *open science* (see our events page in [French](http://hackyourphd.org/evenements/) and [English](http://hackyourphd.org/en/event/)). We have conducted **code** (python) training workshops [Open Geek](https://github.com/HackYourResearch/ateliers-open-geek)

- produces **online content** to help people discover different aspects of *open science* and the different people involved. The HackYourResearch blog contains various articles, interviews but also more original formats to communicate on this subject (e.g. [flyers](http://hackyourphd.org/en/flyers/)), [ebook](http://hackyourphd.org/wp-content/uploads/2016/04/Ebook_Final_VF_LD.pdf). We have interviewed more than 60 people whose comments are available on [Archive.org](https://archive.org/details/@hackyourphd).

### Some organized events and workshops

- 2021 [Remix ta thèse : des souris et des profs](https://openlaw.fr/blog/retour-sur-latelier-2040-des-souris-et-des-profs)

- 2021 [Coordination of the working group Society & Open Science at the Center for Internet & Society](https://cis.cnrs.fr/science-ouverte-et-societe/)

- 2020 [Participation in the writing of the mémorandum Covid-19 : for openness with awareness](https://covid19-open.frama.io/memo/)

- 2020 [Collaborative translation sprint](https://hyr.science/2020/05/26-06-20-nouvelle-date-et-nouveau-format-100-en-ligne-pour-le-sprint-dedition-et-de-traduction-collaborative-science-ouverte/) with the URFIST of Bordeaux
- From 2015 to 2017: [Open Geek Workshops](http://hackyourphd.org/ateliers-open-geek/).
- In December 2015 [Hackathon HackRepNum 2015](http://hackyourphd.org/2015/11/hackrepnum-un-hackathon-recherche-autour-de-la-loi-sur-le-numerique-samedi-12-decembre-a-la-paillasse/)

## Meet the actors of *open science* and commons

Since 2013, giving a voice to those involved in building the knowledge regime in which we find ourselves, has been a guiding principle. This has taken the form of participatory and open ethnographic inquiries that have evolved over the years, but always with the idea of highlighting the diversity of actions at work around concepts such as _open_ and commons.

### OpenESR

In 2020, with inno3 and HackYourResearch, we have initiated an exchange session (webinars). The aim was to invite different people involved in projects on commons and _open_ (within or outside research) to learn from these experiences and take a reflexive look at what "could be" higher education and research today.
The [OpenESR website](https://openesr.frama.io/rencontres) is dedicated to these meetings.

### HackYourPhD USA and Quebec (2013-2015)

With HackYourPhD, before the beginning of my PhD, I had started a first exploration of the *Open Science* / Science ouverte [in Quebec](http://hackyourphd-quebec.strikingly.com/) and then in the United States. During the summer of 2013, I made a grand tour of the USA to meet key stakeholders of *Open Science* and better understand the roots of this movement. This project [HackYourPhD in the States](http://hackyourphd-aux-states.strikingly.com/) was financed by a participative fundraising campaign (*crowdfunding)*.

#### Book: Portraits of young researchers of the #OpenScience generation (2015)

A book has been published online following the HackYourPhDUSA trip. It is available in [French](http://hackyourphd.org/wp-content/uploads/2016/04/Ebook_Final_VF_LD.pdf) and [English](http://hackyourphd.org/wp-content/uploads/2016/04/Ebook_Final_ENG-ld.pdf).

#### Interviews _Open Science_

Discover more than 80 interviews on the HackYourPhD profile of [archive.org](https://archive.org/hackyourphd)

## Inno3 (2020-...)

In 2019, I joined the consulting firm [inno3](https://inno3.fr/) specialized in open innovation, _open data_ and _open source_ . Founded by the lawyer Benjamin Jean, we help different actors (public institutions, companies, local authorities) to understand the major organizational, legal and technical issues involved in the adoption of "digital" technologies, using open models oriented towards the creation of commons. Alongside a dynamic team, I lead action-research projects grounded in the values of the free software and commons.

### DRISS : Digital Research in Science & Society (2019-2020)

In 2019, I created with Constance de Quatrebarbes a company [DRISS](https://driss.org/) (_Digital Research in Science & Society_). First of all, this allowed us to offer training courses at universities and ESR schools. These modular training courses, based on practical immersion, aim to provide keys to understanding _open_ and _data science_ while developing a critical and reflexive view of the transformations brought about by digital technology.

----

## Présentations

*Ci-dessous, les présentations sont en anglais et en français.*

### 2019

- Juillet 2019 - Paris - [Quels enjeux pour l'open science en droit](https://openlaw.fr/evenement/quels-enjeux-pour-lopen-science-en-droit) - Open Law

- Juin 2019 - Paris - Cycle « Sciences et réseaux sociaux » – Session 2 : [Les réseaux sociaux, véritables objets de recherches scientifiques](https://socialmediaclub.fr/2019/06/04/cycle-sciences-et-reseaux-sociaux-session-2-les-reseaux-sociaux-veritables-objets-de-recherches-scientifiques/) - Social Media Club

### 2017-2018

zzzzz- Doctorat en cours - un peu de recul nécessaire sur mon engagement militant...zzzz

### 2016

- 24 Novembre 2016 - Paris - Adaweek : Table-ronde : [Entre utopie scientifique et réalités d'aujourd'hui :quel avenir pour l'open science ? Définition, mise en oeuvre des communs scientifiques](https://adaweek2016.sched.org/event/8Xwq/entre-utopie-scientifique-et-realites-daujourdhui-quel-avenir-pour-lopen-science-definition-mises-en-oeuvre-des-communs-scientifiques?iframe=no)

- 7 Novembre 2016 - Montpellier - Séminaire Doctoral : L'*Open Access* et moi organisé par les doctorant(e)s du CIRAD et de l'INRA (UMR Innovation et MOISA)

- 17 Aout 2016 - Seoul (Korea) - Presentation "Opening Science : from Society to Art" with Guillaume Dumas at [Unmake Lab](https://www.facebook.com/fab.unmake/?pnref=story) . Slides [ici](http://www.slideshare.net/gdumas/opening-science-from-society-to-art)

- 4 février 2016 - Paris - Meet-up Epidemium : Que se cache-t-il derrière cette ère de l'*Open* ? [Note de la présentation et des questions](http://bit.ly/1OWV8b9)

### 2015

- 4 juin 2015 - Paris - Wikistage SoScience
Comment concilier Open Science et recherche responsable ? [Video](http://www.wikistage.org/comment-concilier-open-science-et-recherche-responsable-celya-gruson-daniel-wikistage-soscience_d27e5bde0.html)

- 13-15 novembre 2015 - Bruxelles - OpenCon2015

- 16-17 septembre 2015 - Geneva - OKCon

### 2014

- 15-17 novembre 2015 - Washington DC - OpenCon2014

- 18 octobre 2014 - Metz - Assises du Journalisme
Table-ronde "Vulgariser l'information scientifique" aux [8e Assises du Journalisme](http://www.journalisme.com/)

- 26 septembre 2014 - Chamonix - CHAM 2014
Débat ["Citoyens : Comment accéder à l'Open Data ? »](http://www.canalcham.fr/fr/videos)

- 21-26 juin - Copenhagen - ESOF2014
ESOF 2014 ["Think Global, Act Local : how to empower your scientific community"](https://storify.com/HackYourPhd/esof2014-day-1-think-global-act-local-how-to-enga)

- 13 juin - Dijon - TEDxDijon
[Open Science, quand la recherche s'ouvre à la société](https://www.youtube.com/watch?v=E7ZmQ50b9jE&index=6&list=PLn3z9MbzvmAY1QxD97aASShLKGu1t4_zf) avec Guillaume Dumas

- 5 juin- Paris - Forum Changer d'ère
Table ronde ["Manager la complexité pour sur-vivre"](http://www.forumchangerdere.fr/ledition-2013-2) avec Joel de Rosnay, Geneviève Ferone, Blanche Segrestin

- 21 mai - Lanester - Forum Camp'TIC ""Solidarités et numérique"
Le Mouvement de l'Open Science : vers une réappropriation collective des connaissances et une conception plurielle de l'économie des connaissances. [Programme](http://www.camptic.info/2014/solidarites-et-numerique/programme/)

- 14 mars  - Paris - SoData
[Open Data : défis et enjeux en recherche](http://fr.slideshare.net/cgrusondaniel/so-data-open-data-dfis-et-enjeux-en-recherche) à [SoData](http://sodata.org/)

### 2013

- 8 juin - Paris - TEDxParisUniversités
[Thèse ou pas thèse ? Découverte de l'Open Science](https://www.youtube.com/watch?v=Xpe0qh_HKJE) (english subtitles)

- 5 juin - Paris - Forum Changer d'ère - Table ronde ["Désolé pour le dérangement, les makers sont entrain de changer le monde"](http://www.forumchangerdere.fr/programme-juin-2014) avec Cyril Lage, Jennifer Leblond, Francis Lorentz


text:
module Byebug
  module Helpers
    #
    # Utilities for interaction with strings
    #
    module StringHelper
      #
      # Converts +str+ from an_underscored-or-dasherized_string to
      # ACamelizedString.
      #
      def camelize(str)
        str.dup.split(/[_-]/).map(&:capitalize).join('')
      end

      #
      # Improves indentation and spacing in +str+ for readability in Byebug's
      # command prompt.
      #
      def prettify(str)
        "\n" + deindent(str) + "\n"
      end

      #
      # Removes a number of leading whitespace for each input line.
      #
      # @note Might be unnecessary when Ruby 2.2 support is dropped and we can
      # use squiggly heredoc's.
      #
      def deindent(str, leading_spaces: 6)
        str.gsub(/^ {#{leading_spaces}}/, '')
      end
    end
  end
end


text:
//
// This code was auto-generated by AFNOR StoredProcedureSystem, version 1.0
//

using SOURCE.Data.Context;
using SOURCE.Domaine;
using SOURCE.Business.Depots;
using System.Linq;

namespace SOURCE.Data.Depots
{
    public partial class DepotDevise : Depot<Devise>, IDepotDevise
    {
        /// <summary>
        /// Initialise une nouvelle instance du dépôt.
        /// </summary>
        /// <param name="dataContext">Contexte de la base de donnée.</param>
        public DepotDevise(ISourceDbContext dataContext)
            : base(dataContext)
        {
        }
    }
}


text:
/*
 * 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.
 */
package com.facebook.presto.metadata;

import com.facebook.presto.server.NoOpFailureDetector;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import io.airlift.discovery.client.ServiceDescriptor;
import io.airlift.discovery.client.ServiceSelector;
import io.airlift.discovery.client.testing.StaticServiceSelector;
import io.airlift.node.NodeConfig;
import io.airlift.node.NodeInfo;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import static io.airlift.discovery.client.ServiceDescriptor.serviceDescriptor;
import static io.airlift.testing.Assertions.assertEqualsIgnoreOrder;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotSame;

public class TestDiscoveryNodeManager
{
    private final NodeInfo nodeInfo = new NodeInfo("test");
    private NodeVersion expectedVersion;
    private List<Node> activeNodes;
    private List<Node> inactiveNodes;
    private ServiceSelector selector;

    @BeforeMethod
    public void setup()
    {
        expectedVersion = new NodeVersion("1");
        activeNodes = ImmutableList.of(
                new Node(nodeInfo.getNodeId(), URI.create("http://192.0.1.1"), expectedVersion),
                new Node(UUID.randomUUID().toString(), URI.create("http://192.0.2.1:8080"), expectedVersion),
                new Node(UUID.randomUUID().toString(), URI.create("http://192.0.2.3"), expectedVersion),
                new Node(UUID.randomUUID().toString(), URI.create("https://192.0.2.8"), expectedVersion));
        inactiveNodes = ImmutableList.of(
                new Node(UUID.randomUUID().toString(), URI.create("https://192.0.3.9"), NodeVersion.UNKNOWN),
                new Node(UUID.randomUUID().toString(), URI.create("https://192.0.4.9"), new NodeVersion("2"))
        );

        List<ServiceDescriptor> descriptors = new ArrayList<>();
        for (Node node : Iterables.concat(activeNodes, inactiveNodes)) {
            descriptors.add(serviceDescriptor("presto")
                    .setNodeId(node.getNodeIdentifier())
                    .addProperty("http", node.getHttpUri().toString())
                    .addProperty("node_version", node.getNodeVersion().toString())
                    .build());
        }

        selector = new StaticServiceSelector(descriptors);
    }

    @Test
    public void testGetAllNodes()
            throws Exception
    {
        DiscoveryNodeManager manager = new DiscoveryNodeManager(selector, nodeInfo, new NoOpFailureDetector(), expectedVersion);
        AllNodes allNodes = manager.getAllNodes();

        Set<Node> activeNodes = allNodes.getActiveNodes();
        assertEqualsIgnoreOrder(activeNodes, this.activeNodes);

        for (Node actual : activeNodes) {
            for (Node expected : this.activeNodes) {
                assertNotSame(actual, expected);
            }
        }

        Set<Node> inactiveNodes = allNodes.getInactiveNodes();
        assertEqualsIgnoreOrder(inactiveNodes, this.inactiveNodes);

        for (Node actual : inactiveNodes) {
            for (Node expected : this.inactiveNodes) {
                assertNotSame(actual, expected);
            }
        }
    }

    @Test
    public void testGetCurrentNode()
    {
        Node expected = activeNodes.get(0);

        NodeInfo nodeInfo = new NodeInfo(new NodeConfig()
                .setEnvironment("test")
                .setNodeId(expected.getNodeIdentifier()));

        DiscoveryNodeManager manager = new DiscoveryNodeManager(selector, nodeInfo, new NoOpFailureDetector(), expectedVersion);

        assertEquals(manager.getCurrentNode(), expected);
    }

    @SuppressWarnings("ResultOfObjectAllocationIgnored")
    @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = ".* current node not returned .*")
    public void testGetCurrentNodeRequired()
    {
        new DiscoveryNodeManager(selector, new NodeInfo("test"), new NoOpFailureDetector(), expectedVersion);
    }
}


text:
package observer.pattern;

import java.util.ArrayList;

public class Internet implements Observer {

	private Lotto lotto;
	private ArrayList<Integer> result;

	Internet(Lotto lotto) {
		this.lotto = lotto;
		result = new ArrayList<Integer>();
	}
	public void update() {
		result.clear();
		result.addAll(this.lotto.getNumbers());
	}
	public void displayResults() {
		for (Integer i : result) {
			System.out.print(i + " ");
		}
		System.out.println("");
	}
}


text:
.. Copyright 2012 tsuru authors. All rights reserved.
   Use of this source code is governed by a BSD-style
   license that can be found in the LICENSE file.

++++++++++++++++++++++++++
Building your app in tsuru
++++++++++++++++++++++++++

Tsuru is an open source polyglot cloud application platform. With Tsuru, you
don't need to think about servers at all. You can write apps in the programming
language of your choice, back it with add-on resources such as SQL and NoSQL
databases, memcached, redis, and many others. You manage your app using the
Tsuru command-line tool and you deploy code using the Git revision control
system, all running on the Tsuru infrastructure.

Install the tsuru client
++++++++++++++++++++++++

:doc:`Install the Tsuru client </apps/client/install>` for your development platform.

The the Tsuru client is a command-line tool for creating and managing apps.

Sign up
+++++++

To create an account, you use the `user-create
<http://godoc.org/github.com/globocom/tsuru/cmd/tsuru/developer#Create_a_user>`_
command:

.. highlight:: bash

::

    $ tsuru user-create youremail@domain.com

``user-create`` will ask for your password twice.

Login
+++++

To login in tsuru, you use the `login
<http://godoc.org/github.com/globocom/tsuru/cmd/tsuru/developer#Authenticate_within_remote_tsuru_server>`_
command, you will be asked for your password:

.. highlight:: bash

::

    $ tsuru login youremail@domain.com

Deploy an application
++++++++++++++++++++

Choose from the following getting started tutorials to learn how to deploy your
first application using a supported language or framework:

* :doc:`Deploying Python applications in tsuru </apps/quickstart/python>`


text:
package com.intellij.remote.ext;

import com.intellij.openapi.extensions.ExtensionPointName;

public abstract class CredentialsLanguageContribution<T> {
  public static final ExtensionPointName<CredentialsLanguageContribution> EP_NAME
    = ExtensionPointName.create("com.intellij.remote.credentialsLanguageContribution");

  public abstract CredentialsTypeEx getType();

  public abstract Class<T> getLanguageContributionClass();

  public abstract T getLanguageContribution();
}


text:
package com.mika_tk.android.spatula;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Created by Mikhael Turki on 12/12/2016.
 * <p>
 * Main annotation interface.
 */
@Retention(RUNTIME)
@Target(FIELD)
public @interface BindTypeface {
    /**
     * @return typeface index.
     */
    int value() default TypefaceMapper.regular;
}


text:
/**
 * Shim for "fixing" IE's lack of support (IE < 9) for applying slice
 * on host objects like NamedNodeMap, NodeList, and HTMLCollection
 * (technically, since host objects have been implementation-dependent,
 * at least before ES6, IE hasn't needed to work this way).
 * Also works on strings, fixes IE < 9 to allow an explicit undefined
 * for the 2nd argument (as in Firefox), and prevents errors when
 * called on other DOM objects.
*/
(function () {
    'use strict';
    var _slice = Array.prototype.slice;

    try {
        // Can't be used with DOM elements in IE < 9
        _slice.call(document.documentElement);
    }
    catch (e) { // Fails in IE < 9
        Array.prototype.slice = function (begin, end) {
            var i, arrl = this.length, a = [];
            // Although IE < 9 does not fail when applying Array.prototype.slice
            // to strings, here we do have to duck-type to avoid failing
            // with IE < 9's lack of support for string indexes
            if (this.charAt) {
                for (i = 0; i < arrl; i++) {
                    a.push(this.charAt(i));
                }
            }
            // This will work for genuine arrays, array-like objects,
            // NamedNodeMap (attributes, entities, notations),
            // NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes),
            // and will not fail on other DOM objects (as do DOM elements in IE < 9)
            else {
                // IE < 9 (at least IE < 9 mode in IE 10) does not work with
                // node.attributes (NamedNodeMap) without a dynamically checked length here
                for (i = 0; i < this.length; i++) {
                    a.push(this[i]);
                }
            }
            // IE < 9 gives errors here if end is allowed as undefined
            // (as opposed to just missing) so we default ourselves
            return _slice.call(a, begin, end || a.length);
        };
    }
}());


text:
This is a web spider to collect Child Care information from the website
http://ifp.mychild.gov.au/Search/AZSearch.aspx.
The code is written with Scrapy framework. It goes through the A to Z and fetch
the Child Care information.
There are about **197k** items.

# Data fields
Most of Child Care centres have `name`, `type`, and `address`. Other fields will be collected if possible.
- name
- type
- address
- *email* (optional)
- *phone*
- *web*

# How to run?
Clone the code and run following command
```bash
scrapy crawl mychildcare -o filename.csv
```
This will export the result to `filename.csv`, change it to `filename.json` if you prefer json format.
Please refer to th Scrapy project to get more option.

>**Suggestion**
>If you start the program by default, it goes through all letters from A to Z, which takes long time.
>Change the start_url to Z only to avoid that, and quick turn around to fix or verify it.


text:
package com.gmail.trentech.pja.commands;

import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.text.Text;

import com.gmail.trentech.pja.commands.create.CMDButton;
import com.gmail.trentech.pja.commands.create.CMDCreate;
import com.gmail.trentech.pja.commands.create.CMDDoor;
import com.gmail.trentech.pja.commands.create.CMDLever;
import com.gmail.trentech.pja.commands.create.CMDPlate;
import com.gmail.trentech.pja.commands.create.CMDSign;

public class CommandManager {

	private CommandSpec cmdButton = CommandSpec.builder()
		    .description(Text.of("Create new command button"))
		    .permission("pja.cmd.auto.create.button")
		    .arguments(GenericArguments.optional(GenericArguments.remainingJoinedStrings(Text.of("command"))))
		    .executor(new CMDButton())
		    .build();

	private CommandSpec cmdDoor = CommandSpec.builder()
		    .description(Text.of("Create new command door"))
		    .permission("pja.cmd.auto.create.door")
		    .arguments(GenericArguments.optional(GenericArguments.remainingJoinedStrings(Text.of("command"))))
		    .executor(new CMDDoor())
		    .build();

	private CommandSpec cmdLever = CommandSpec.builder()
		    .description(Text.of("Create new command lever"))
		    .permission("pja.cmd.auto.create.lever")
		    .arguments(GenericArguments.optional(GenericArguments.remainingJoinedStrings(Text.of("command"))))
		    .executor(new CMDLever())
		    .build();

	private CommandSpec cmdPlate = CommandSpec.builder()
		    .description(Text.of("Create new command pressure plate"))
		    .permission("pja.cmd.auto.create.plate")
		    .arguments(GenericArguments.optional(GenericArguments.remainingJoinedStrings(Text.of("command"))))
		    .executor(new CMDPlate())
		    .build();

	private CommandSpec cmdSign = CommandSpec.builder()
		    .description(Text.of("Create new command sign"))
		    .permission("pja.cmd.auto.create.sign")
		    .arguments(GenericArguments.optional(GenericArguments.remainingJoinedStrings(Text.of("command"))))
		    .executor(new CMDSign())
		    .build();
	private CommandSpec cmdCreate = CommandSpec.builder()
		    .description(Text.of("Create new scheduled command"))
		    .permission("pja.cmd.auto.create")
		    .child(cmdButton, "button", "b")
		    .child(cmdDoor, "door", "d")
		    .child(cmdLever, "lever", "l")
		    .child(cmdPlate, "plate", "p")
		    .child(cmdSign, "sign", "s")
		    .arguments(GenericArguments.optional(GenericArguments.string(Text.of("name")))
		    		,GenericArguments.optional(GenericArguments.string(Text.of("time")))
		    		,GenericArguments.optional(GenericArguments.string(Text.of("command")))
		    		,GenericArguments.optional(GenericArguments.string(Text.of("repeat"))))
		    .executor(new CMDCreate())
		    .build();

	private CommandSpec cmdDelete = CommandSpec.builder()
		    .description(Text.of("delete scheduled command"))
		    .permission("pja.cmd.auto.delete")
		    .arguments(GenericArguments.optional(GenericArguments.remainingJoinedStrings(Text.of("name"))))
		    .executor(new CMDDelete())
		    .build();

	private CommandSpec cmdEdit = CommandSpec.builder()
		    .description(Text.of("Edit a scheduled command"))
		    .permission("pja.cmd.auto.edit")
		    .arguments(GenericArguments.optional(GenericArguments.string(Text.of("name")))
		    		,GenericArguments.optional(GenericArguments.string(Text.of("arg0")))
		    		,GenericArguments.optional(GenericArguments.string(Text.of("arg1")))
		    		,GenericArguments.optional(GenericArguments.string(Text.of("arg2"))))
		    .executor(new CMDEdit())
		    .build();

	private CommandSpec cmdReload = CommandSpec.builder()
		    .description(Text.of("reload schedulers"))
		    .permission("pja.cmd.auto.reload")
		    .executor(new CMDReload())
		    .build();

	private CommandSpec cmdList = CommandSpec.builder()
		    .description(Text.of("list all tasks"))
		    .permission("pja.cmd.auto.list")
		    .executor(new CMDList())
		    .build();

	private CommandSpec cmdHelp = CommandSpec.builder()
		    .description(Text.of("i need help"))
		    .permission("pja.cmd.help")
		    .arguments(GenericArguments.optional(GenericArguments.string(Text.of("command"))))
		    .executor(new CMDHelp())
		    .build();

	public CommandSpec cmdAuto = CommandSpec.builder()
			.description(Text.of("Base command"))
			.permission("pja.cmd.auto")
			.child(cmdCreate, "create", "c")
			.child(cmdDelete, "delete", "d")
			.child(cmdEdit, "edit", "e")
			.child(cmdReload, "reload", "r")
			.child(cmdList, "list", "l")
			.child(cmdHelp, "help")
			.executor(new CMDAuto())
			.build();
}


text:
// Copyright (c) SimControl e.U. - Wilhelm Medetz. See LICENSE.txt in the project root for more information.

using System;
using NLog;
using SimControl.Log;

namespace SimControl.Samples.CSharp.ClassLibrary
{
    /// SampleClass implementation.
    public static class VerifyJitOptimization
    {
        /// Run
        public static void Run()
        {
            const int a = 2*2;
            int count = 0;

            for (int i = 0; i < 3; i++)
                count += a*i;

            logger.Message(LogLevel.Debug, LogMethod.GetCurrentMethodName(), "Count", count);

            try { MethodA(); }
            catch (InvalidOperationException e)
            {
                logger.Exception(LogLevel.Debug, LogMethod.GetCurrentMethodName(), null, e);
            }
        }

        private static void BadMethod() => throw new InvalidOperationException("generic bad thing");

        private static void MethodA() => MethodB();

        private static void MethodB() => MethodC();

        private static void MethodC() => BadMethod();

        private static readonly Logger logger = LogManager.GetCurrentClassLogger();
    }
}


text:
package io.github.htools.hadoop.io;

import io.github.htools.io.Datafile;
import io.github.htools.io.struct.StructuredRecordFile;
import io.github.htools.lib.ClassTools;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;

import java.io.IOException;
import java.lang.reflect.Constructor;
/**
 *
 * @author jeroen
 */
public abstract class StructuredRecordReader<F extends StructuredRecordFile, K, W extends org.apache.hadoop.io.Writable> extends org.apache.hadoop.mapreduce.RecordReader<K, W> {
    protected TaskAttemptContext context;
    protected Class fileclass;
    protected long start;
    protected long end;
    protected F structuredRecordFile;
    protected K key;
    protected W record;
    protected FileSystem filesystem;
    protected org.apache.hadoop.conf.Configuration conf;

    public StructuredRecordReader(Class fileclass) {
        this.fileclass = fileclass;
    }

    @Override
    public void initialize(InputSplit is, TaskAttemptContext tac) {
        context = tac;
        initialize(is, tac.getConfiguration());
    }

    protected F getFile(Datafile datafile) throws ClassNotFoundException {
        Constructor constructor = ClassTools.getAssignableConstructor(fileclass, StructuredRecordFile.class, Datafile.class);
        return (F) ClassTools.construct(constructor, datafile);
    }

    public void initialize(InputSplit is, org.apache.hadoop.conf.Configuration conf) {
        //log.info("initialize");
        try {
            this.conf = conf;
            filesystem = FileSystem.get(conf);
            FileSplit fileSplit = (FileSplit) is;
            Path file = fileSplit.getPath();
            start = fileSplit.getStart();
            end = start + fileSplit.getLength();
            structuredRecordFile = getFile(new Datafile(filesystem, file));
            structuredRecordFile.setOffset(start);
            structuredRecordFile.setBufferSize(FileInputFormat.getBufferSize(conf));
            structuredRecordFile.openRead();
            structuredRecordFile.findFirstRecord();
            structuredRecordFile.setCeiling(end);
            FileInputFormat.log.info("RecordReader start %d end %d buffer %d path %s", start, end, structuredRecordFile.getDatafile().getBufferSize(), file.toString());
        } catch (IOException ex) {
            FileInputFormat.log.exception(ex, "initialize( %s ) conf %s filesystem %s fsin %s", is, conf, filesystem, structuredRecordFile);
        } catch (ClassNotFoundException ex) {
            FileInputFormat.log.exception(ex, "initialize( %s ) conf %s filesystem %s fsin %s", is, conf, filesystem, structuredRecordFile);
        }
    }

    /**
     * Reads the input file, scanning for the next document, setting key and
     * entitywritable with the offset and byte contents of the document
     * read.
     *

     * @return true if a next document was read
     */
    @Override
    public boolean nextKeyValue() throws IOException {
        //log.info("nextKeyValue() hasMore %b", structuredRecordFile.hasMore());
        if (structuredRecordFile.hasMore()) {
            //log.info("nextKeyValue() offset %d ceiling %d",
            //        structuredRecordFile.getOffset(), structuredRecordFile.getCeiling());
            if (structuredRecordFile.getOffset() <= structuredRecordFile.getCeiling()) {
                if (structuredRecordFile.nextRecord()) {
                    key = nextKey();
                    //log.info("nextKeyValue() nextRecord %b", true);
                    record = (W) structuredRecordFile.readRecord();
                    //log.info("new offset %d", structuredRecordFile.getOffset());
                    return true;
                }
            }
        }
        return false;
    }

    protected abstract K nextKey();

    @Override
    public final K getCurrentKey() throws IOException, InterruptedException {
        return key;
    }

    @Override
    public final W getCurrentValue() throws IOException, InterruptedException {
        return record;
    }

    /**
     * NB this indicates progress as the data that has been read, for some
     * MapReduce tasks processing the data continues for some startTime,
     * causing the progress indicator to halt at 100%.
     *

     * @return @throws IOException
     * @throws InterruptedException
     */
    @Override
    public float getProgress() throws IOException, InterruptedException {
        return (structuredRecordFile.getOffset() - start) / (float) (end - start);
    }

    @Override
    public void close() throws IOException {
        structuredRecordFile.closeRead();
    }

}


text:
:man_page: bson_t

bson_t
======

BSON Document Abstraction

Synopsis
--------

.. code-block:: c

  #include <bson.h>

  /**
   * bson_empty:
   * @b: a bson_t.
   *
   * Checks to see if @b is an empty BSON document. An empty BSON document is
   * a 5 byte document which contains the length (4 bytes) and a single NUL
   * byte indicating end of fields.
   */
  #define bson_empty(b) /* ... */

  /**
   * bson_empty0:
   *
   * Like bson_empty() but treats NULL the same as an empty bson_t document.
   */
  #define bson_empty0(b) /* ... */

  /**
   * bson_clear:
   *
   * Easily free a bson document and set it to NULL. Use like:
   *
   * bson_t *doc = bson_new();
   * bson_clear (&doc);
   * BSON_ASSERT (doc == NULL);
   */
  #define bson_clear(bptr) /* ... */

  /**
   * BSON_MAX_SIZE:
   *
   * The maximum size in bytes of a BSON document.
   */
  #define BSON_MAX_SIZE /* ... */

  #define BSON_APPEND_ARRAY(b, key, val) \
     bson_append_array (b, key, (int) strlen (key), val)

  #define BSON_APPEND_ARRAY_BEGIN(b, key, child) \
     bson_append_array_begin (b, key, (int) strlen (key), child)

  #define BSON_APPEND_BINARY(b, key, subtype, val, len) \
     bson_append_binary (b, key, (int) strlen (key), subtype, val, len)

  #define BSON_APPEND_BOOL(b, key, val) \
     bson_append_bool (b, key, (int) strlen (key), val)

  #define BSON_APPEND_CODE(b, key, val) \
     bson_append_code (b, key, (int) strlen (key), val)

  #define BSON_APPEND_CODE_WITH_SCOPE(b, key, val, scope) \
     bson_append_code_with_scope (b, key, (int) strlen (key), val, scope)

  #define BSON_APPEND_DBPOINTER(b, key, coll, oid) \
     bson_append_dbpointer (b, key, (int) strlen (key), coll, oid)

  #define BSON_APPEND_DOCUMENT_BEGIN(b, key, child) \
     bson_append_document_begin (b, key, (int) strlen (key), child)

  #define BSON_APPEND_DOUBLE(b, key, val) \
     bson_append_double (b, key, (int) strlen (key), val)

  #define BSON_APPEND_DOCUMENT(b, key, val) \
     bson_append_document (b, key, (int) strlen (key), val)

  #define BSON_APPEND_INT32(b, key, val) \
     bson_append_int32 (b, key, (int) strlen (key), val)

  #define BSON_APPEND_INT64(b, key, val) \
     bson_append_int64 (b, key, (int) strlen (key), val)

  #define BSON_APPEND_MINKEY(b, key) \
     bson_append_minkey (b, key, (int) strlen (key))

  #define BSON_APPEND_DECIMAL128(b, key, val) \
     bson_append_decimal128 (b, key, (int) strlen (key), val)

  #define BSON_APPEND_MAXKEY(b, key) \
     bson_append_maxkey (b, key, (int) strlen (key))

  #define BSON_APPEND_NULL(b, key) bson_append_null (b, key, (int) strlen (key))

  #define BSON_APPEND_OID(b, key, val) \
     bson_append_oid (b, key, (int) strlen (key), val)

  #define BSON_APPEND_REGEX(b, key, val, opt) \
     bson_append_regex (b, key, (int) strlen (key), val, opt)

  #define BSON_APPEND_UTF8(b, key, val) \
     bson_append_utf8 (b, key, (int) strlen (key), val, (int) strlen (val))

  #define BSON_APPEND_SYMBOL(b, key, val) \
     bson_append_symbol (b, key, (int) strlen (key), val, (int) strlen (val))

  #define BSON_APPEND_TIME_T(b, key, val) \
     bson_append_time_t (b, key, (int) strlen (key), val)

  #define BSON_APPEND_TIMEVAL(b, key, val) \
     bson_append_timeval (b, key, (int) strlen (key), val)

  #define BSON_APPEND_DATE_TIME(b, key, val) \
     bson_append_date_time (b, key, (int) strlen (key), val)

  #define BSON_APPEND_TIMESTAMP(b, key, val, inc) \
     bson_append_timestamp (b, key, (int) strlen (key), val, inc)

  #define BSON_APPEND_UNDEFINED(b, key) \
     bson_append_undefined (b, key, (int) strlen (key))

  #define BSON_APPEND_VALUE(b, key, val) \
     bson_append_value (b, key, (int) strlen (key), (val))

  BSON_ALIGNED_BEGIN (128)
  typedef struct {
     uint32_t flags;       /* Internal flags for the bson_t. */
     uint32_t len;         /* Length of BSON data. */
     uint8_t padding[120]; /* Padding for stack allocation. */
  } bson_t BSON_ALIGNED_END (128);

Description
-----------

The :symbol:`bson_t` structure represents a BSON document. This structure manages the underlying BSON encoded buffer. For mutable documents, it can append new data to the document.

Performance Notes
-----------------

The :symbol:`bson_t` structure attempts to use an inline allocation within the structure to speed up performance of small documents. When this internal buffer has been exhausted, a heap allocated buffer will be dynamically allocated. Therefore, it is essential to call :symbol:`bson_destroy()` on allocated documents.

.. only:: html

  Functions
  ---------

  .. toctree::
    :titlesonly:
    :maxdepth: 1

    bson_append_array
    bson_append_array_begin
    bson_append_array_end
    bson_append_binary
    bson_append_bool
    bson_append_code
    bson_append_code_with_scope
    bson_append_date_time
    bson_append_dbpointer
    bson_append_decimal128
    bson_append_document
    bson_append_document_begin
    bson_append_document_end
    bson_append_double
    bson_append_int32
    bson_append_int64
    bson_append_iter
    bson_append_maxkey
    bson_append_minkey
    bson_append_now_utc
    bson_append_null
    bson_append_oid
    bson_append_regex
    bson_append_symbol
    bson_append_time_t
    bson_append_timestamp
    bson_append_timeval
    bson_append_undefined
    bson_append_utf8
    bson_append_value
    bson_array_as_json
    bson_as_canonical_extended_json
    bson_as_json
    bson_as_relaxed_extended_json
    bson_compare
    bson_concat
    bson_copy
    bson_copy_to
    bson_copy_to_excluding
    bson_copy_to_excluding_noinit
    bson_count_keys
    bson_destroy
    bson_destroy_with_steal
    bson_equal
    bson_get_data
    bson_has_field
    bson_init
    bson_init_from_json
    bson_init_static
    bson_new
    bson_new_from_buffer
    bson_new_from_data
    bson_new_from_json
    bson_reinit
    bson_reserve_buffer
    bson_sized_new
    bson_steal
    bson_validate
    bson_validate_with_error

Example
-------

.. code-block:: c

  static void
  create_on_heap (void)
  {
     bson_t *b = bson_new ();

     BSON_APPEND_INT32 (b, "foo", 123);
     BSON_APPEND_UTF8 (b, "bar", "foo");
     BSON_APPEND_DOUBLE (b, "baz", 1.23f);

     bson_destroy (b);
  }


text:
/** @author Brian To (bxt5647) */

import java.util.Queue;

public class TextNode extends Node {

	private String text;

	@Override
	public TextNode parse(Queue<TokenData> tokens) {
		consumeAndExpect(tokens, Token.TEXT);
		consumeAndExpect(tokens, Token.BRACE_LEFT);

		if (incomingTokenIs(tokens, Token.TEXT_LITERAL)) {
			this.text = consumeAndExpect(tokens, Token.TEXT_LITERAL).getData();
			this.text = this.text.replaceAll("[ ]", " ");
		} else if (incomingTokenIsEscapedText(tokens)) {
			StringBuilder builder = new StringBuilder();

			while (!incomingTokenIs(tokens, Token.BRACE_RIGHT)) {
				TokenData token = tokens.poll();
				String text = sanitize(token.getData());

				builder.append(" " + text + " ");
			}

			this.text = builder.toString();
		} else {
			TokenData badToken = tokens.poll();

			throw new RuntimeException(String.format(
					"Unexpected %s in text node", badToken.getToken()));
		}

		consumeAndExpect(tokens, Token.BRACE_RIGHT);

		return this;
	}

	@Override
	public String html() {
		return this.text;
	}

	private static String sanitize(String text) {
		return text
				.replaceAll("\\<", "<")
				.replaceAll("\\>", ">");
	}

	private static boolean incomingTokenIsEscapedText(Queue<TokenData> tokens) {
		return !incomingTokenIs(tokens, Token.BRACE_LEFT, Token.BRACE_RIGHT, Token.TEXT_LITERAL);
	}
}