text:
import type { AbstractControl, ValidatorFn, ValidationErrors } from "@angular/forms";
import { AbstractControlUtil } from "./../abstract-control-util";
import type { EmailOptions } from "./email-util";
import { EmailSuggestion } from "./email-util";

export class EmailValidators {
  private static emailSuggestion: EmailSuggestion = new EmailSuggestion();

  public static simple(control: AbstractControl): ValidationErrors | null {
    if (AbstractControlUtil.isNotPresent(control)) {
      return null;
    }

    const pattern = /.+@.+\..+/i;
    if (pattern.test(control.value)) {
      return null;
    }
    return { simpleEmailRule: true };
  }

  // https://www.w3.org/TR/html5/forms.html#valid-e-mail-address
  public static normal(control: AbstractControl): ValidationErrors | null {
    if (AbstractControlUtil.isNotPresent(control)) {
      return null;
    }

    const pattern =
      // tslint:disable-next-line:max-line-length
      /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
    if (pattern.test(control.value)) {
      return null;
    }
    return { normalEmailRule: true };
  }

  public static suggest(options?: EmailOptions): ValidatorFn {
    const validator = (control: AbstractControl): ValidationErrors | null => {
      if (AbstractControlUtil.isNotPresent(control)) {
        return null;
      }
      return this.emailSuggestion.suggest(control.value, options);
    };
    return validator;
  }
}


text:
package demo.algorithm;

import org.jetbrains.annotations.NotNull;

import java.util.Scanner;

/**
 * log2(1 000 000) = 20. It means, that in the worst case, the algorithm requires 20 steps to find a value in a sorted array of a million elements or to say
 * 最差的情况下一百万的数组,需要20次查找
 * Created by Administrator on 2017-05-10.
 */
public class BinarySearch {
    public static void main(String[] args) {
        // this is a integer array with size 10
        int[] a = new int[15];
        int searchV = 0, index;
        System.out.println("Enter 15 numbers");

        //now we put all th value in a previous define array with help of scanner class
        Scanner input = new Scanner(System.in);
        for (int i = 0; i < a.length; i++) {
            a[i] = input.nextInt();
        }

        System.out.print("Enter a number to search for: ");
        // take the user input which he want to search
        searchV = input.nextInt();
        index = binarySearch(a, searchV);
        if (index != -1) {
            System.out.println("Found at index: " + index);
        } else {
            System.out.println("Not Found");
        }
    }

    // here we define binary search method
    static int binarySearch(@NotNull int[] search, int find) {
        int start, end, midPt;
        start = 0;
        end = search.length - 1;

        while (start <= end) {
            midPt = (start + end) / 2;
            if (search[midPt] == find) {
                return midPt;
            } else if (search[midPt] < find) {
                start = midPt + 1;
            } else {
                end = midPt - 1;
            }
        }

        return -1;
    }

}

redpajama_set_name: RedPajamaGithub


text:
package com.twitter.finagle.example.spritzer2kestrel

import com.twitter.concurrent.{Channel, ChannelSource}
import com.twitter.finagle.builder.ClientBuilder
import com.twitter.finagle.kestrel.{Client => Kestrel}
import com.twitter.finagle.stream.{Stream, StreamResponse}
import java.net.{Socket, ConnectException}
import java.nio.charset.Charset
import org.jboss.netty.buffer.ChannelBuffer
import org.jboss.netty.buffer.ChannelBuffers.copiedBuffer
import org.jboss.netty.handler.codec.base64.Base64
import org.jboss.netty.handler.codec.http.DefaultHttpRequest
import org.jboss.netty.handler.codec.http.HttpMethod.GET
import org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1
import org.jboss.netty.util.CharsetUtil

/**
 * This example demonstrates some of the composability of Channels. The Twitter
 * "Spritzer" (about 1% of all public Tweets) is represented as a readable Channel.
 *
 * Similarly, a Kestrel queue is represented as a writable Channel. The output
 * from the Spritzer is made input (piped()) to the Kestrel queue.
 */
object Spritzer2Kestrel {
  def main(args: Array[String]) {
    assertKestrelRunning()

    val userPass = args(0) // expected format: "user:password"
    val encodedUserPass =
      Base64.encode(copiedBuffer(userPass, Charset.defaultCharset)).toString(CharsetUtil.ISO_8859_1)

    // Connect to the Spritzer:
    val spritzerClient = ClientBuilder()
      .codec(Stream())
      .hosts("stream.twitter.com:80")
      .hostConnectionLimit(1)
      .build()
    val streamResponse = {
      val request = {
        val request = new DefaultHttpRequest(HTTP_1_1, GET, "/1/statuses/sample.json")
        request.addHeader("Host", "stream.twitter.com")
        request.addHeader("Authorization", "Basic " + encodedUserPass)
        request
      }
      try {
        spritzerClient(request)()
      } catch {
        case e =>
          spritzerClient.release()
          throw e
      }
    }

    val spritzer = streamResponse.channel

    // Grab a writeable Channel connected to the Kestrel
    // queue named "queue"
    val kestrelClient = Kestrel("localhost:22133")
    val queue: ChannelSource[ChannelBuffer] = {
      kestrelClient.to("queue")
    }

    // Read from the Spritzer and write into Kestrel:
    spritzer.pipe(queue)

    // Release any resources if something goes wrong:
    (spritzer.closes or queue.closes) ensure {
      println("Connection to the Stream or Kestrel closed")
      kestrelClient.close()
      spritzerClient.release()
    }
  }

  private[this] def assertKestrelRunning() {
    try {
      new Socket("localhost", 22133)
    } catch {
      case e: ConnectException =>
        println("Error: Kestrel must be running on port 22133")
        System.exit(1)
    }
  }
}


text:
require "spec_helper"

describe OrganizationsController do
  describe "routing" do

    it "recognizes and generates #index" do
      { :get => "/organizations" }.should route_to(:controller => "organizations", :action => "index")
    end

    it "recognizes and generates #new" do
      { :get => "/organizations/new" }.should route_to(:controller => "organizations", :action => "new")
    end

    it "recognizes and generates #show" do
      { :get => "/organizations/1" }.should route_to(:controller => "organizations", :action => "show", :id => "1")
    end

    it "recognizes and generates #edit" do
      { :get => "/organizations/1/edit" }.should route_to(:controller => "organizations", :action => "edit", :id => "1")
    end

    it "recognizes and generates #create" do
      { :post => "/organizations" }.should route_to(:controller => "organizations", :action => "create")
    end

    it "recognizes and generates #update" do
      { :put => "/organizations/1" }.should route_to(:controller => "organizations", :action => "update", :id => "1")
    end

    it "recognizes and generates #destroy" do
      { :delete => "/organizations/1" }.should route_to(:controller => "organizations", :action => "destroy", :id => "1")
    end

  end
end


text:
package centaur.test.formulas

import java.time.OffsetDateTime

import cats.syntax.flatMap._
import cats.syntax.functor._
import centaur.test.Operations._
import centaur.test.Test._
import centaur.test.markers.CallMarker
import centaur.test.submit.{SubmitHttpResponse, SubmitResponse}
import centaur.test.workflow.Workflow
import centaur.test.{Operations, Test}
import centaur.{CentaurConfig, CromwellManager, CromwellTracker, ManagedCromwellServer}
import com.typesafe.scalalogging.StrictLogging
import cromwell.api.model.{Aborted, Aborting, Failed, Running, SubmittedWorkflow, Succeeded, TerminalStatus, WorkflowMetadata}

import scala.concurrent.duration._
import centaur.test.metadata.WorkflowFlatMetadata._
import spray.json.JsString
/**
  * A collection of test formulas which can be used, building upon operations by chaining them together via a
  * for comprehension. These assembled formulas can then be run by a client
  */
object TestFormulas extends StrictLogging {
  logger.info(
    s"""Running with CentaurConfig:
       |  - workflowProgressTimeout: '${CentaurConfig.workflowProgressTimeout}'
       |  - sendReceiveTimeout: '${CentaurConfig.sendReceiveTimeout}'
       |  - maxWorkflowLength: '${CentaurConfig.maxWorkflowLength}'
       |  - metadataConsistencyTimeout: '${CentaurConfig.metadataConsistencyTimeout}'
       |  - standardTestCasePath: '${CentaurConfig.standardTestCasePath}'
       |  - optionalTestPath: '${CentaurConfig.optionalTestPath}'
       |""".stripMargin.trim
  )

  private def runWorkflowUntilTerminalStatus(workflow: Workflow, status: TerminalStatus): Test[SubmittedWorkflow] = {
    for {
      _ <- checkVersion()
      s <- submitWorkflow(workflow)
      _ <- expectSomeProgress(
        workflow = s,
        testDefinition = workflow,
        expectedStatuses = Set(Running, status),
        timeout = CentaurConfig.workflowProgressTimeout,
      )
      _ <- pollUntilStatus(s, workflow, status)
    } yield s
  }

  private def runSuccessfulWorkflow(workflow: Workflow): Test[SubmittedWorkflow] = runWorkflowUntilTerminalStatus(workflow, Succeeded)
  private def runFailingWorkflow(workflow: Workflow): Test[SubmittedWorkflow] = runWorkflowUntilTerminalStatus(workflow, Failed)

  def runSuccessfulWorkflowAndVerifyTimeAndOutputs(workflowDefinition: Workflow): Test[SubmitResponse] = for {
    _ <- checkDescription(workflowDefinition, validityExpectation = Option(true))
    timeAllowance <- checkTimingRequirement(workflowDefinition.maximumAllowedTime)
    beforeTimestamp = OffsetDateTime.now().toInstant.getEpochSecond
    submittedWorkflow <- runSuccessfulWorkflow(workflowDefinition)
    afterTimestamp = OffsetDateTime.now().toInstant.getEpochSecond
    _ <- fetchAndValidateOutputs(submittedWorkflow, workflowDefinition, "ROOT NOT SUPPORTED IN TIMING/OUTPUT ONLY TESTS")
    _ <- checkFastEnough(beforeTimestamp, afterTimestamp, timeAllowance)
  } yield SubmitResponse(submittedWorkflow)

  def runSuccessfulWorkflowAndVerifyMetadata(workflowDefinition: Workflow)(implicit cromwellTracker: Option[CromwellTracker]): Test[SubmitResponse] = for {
    _ <- checkDescription(workflowDefinition, validityExpectation = Option(true))
    _ <- timingVerificationNotSupported(workflowDefinition.maximumAllowedTime)
    submittedWorkflow <- runSuccessfulWorkflow(workflowDefinition)
    metadata <- fetchAndValidateNonSubworkflowMetadata(submittedWorkflow, workflowDefinition)
    _ <- fetchAndValidateJobManagerStyleMetadata(submittedWorkflow, workflowDefinition, prefetchedOriginalNonSubWorkflowMetadata = Option(metadata.value))
    notArchivedFlatMetadata = metadata.asFlat
    workflowRoot = notArchivedFlatMetadata.value.get("workflowRoot").collectFirst { case JsString(r) => r } getOrElse "No Workflow Root"
    _ <- fetchAndValidateOutputs(submittedWorkflow, workflowDefinition, workflowRoot)
    _ <- fetchAndValidateLabels(submittedWorkflow, workflowDefinition, workflowRoot)
    _ <- validateLogs(metadata, submittedWorkflow, workflowDefinition)
    _ = cromwellTracker.track(metadata)
    _ <- validateDirectoryContentsCounts(workflowDefinition, submittedWorkflow, metadata)
  } yield SubmitResponse(submittedWorkflow)

  def runFailingWorkflowAndVerifyMetadata(workflowDefinition: Workflow)(implicit cromwellTracker: Option[CromwellTracker]): Test[SubmitResponse] = for {
    _ <- checkDescription(workflowDefinition, validityExpectation = None)
    _ <- timingVerificationNotSupported(workflowDefinition.maximumAllowedTime)
    submittedWorkflow <- runFailingWorkflow(workflowDefinition)
    metadata <- fetchAndValidateNonSubworkflowMetadata(submittedWorkflow, workflowDefinition)
    _ <- fetchAndValidateJobManagerStyleMetadata(submittedWorkflow, workflowDefinition, prefetchedOriginalNonSubWorkflowMetadata = Option(metadata.value))
    _ = cromwellTracker.track(metadata)
    _ <- validateDirectoryContentsCounts(workflowDefinition, submittedWorkflow, metadata)
  } yield SubmitResponse(submittedWorkflow)

  def runWorkflowTwiceExpectingCaching(workflowDefinition: Workflow)(implicit cromwellTracker: Option[CromwellTracker]): Test[SubmitResponse] = {
    for {
      _ <- checkDescription(workflowDefinition, validityExpectation = Option(true))
      _ <- timingVerificationNotSupported(workflowDefinition.maximumAllowedTime)
      firstWF <- runSuccessfulWorkflow(workflowDefinition)
      secondWf <- runSuccessfulWorkflow(workflowDefinition.secondRun)
      _ <- printHashDifferential(firstWF, secondWf)
      metadata <- fetchAndValidateNonSubworkflowMetadata(secondWf, workflowDefinition, Option(firstWF.id.id))
      _ <- fetchAndValidateJobManagerStyleMetadata(secondWf, workflowDefinition, prefetchedOriginalNonSubWorkflowMetadata = None)
      _ = cromwellTracker.track(metadata)
      _ <- validateNoCacheMisses(secondWf, metadata, workflowDefinition)
      _ <- validateDirectoryContentsCounts(workflowDefinition, secondWf, metadata)
    } yield SubmitResponse(secondWf)
  }

  def runWorkflowThriceExpectingCaching(workflowDefinition: Workflow)(implicit cromwellTracker: Option[CromwellTracker]): Test[SubmitResponse] = {
    for {
      _ <- checkDescription(workflowDefinition, validityExpectation = Option(true))
      _ <- timingVerificationNotSupported(workflowDefinition.maximumAllowedTime)
      firstWf <- runSuccessfulWorkflow(workflowDefinition)
      secondWf <- runSuccessfulWorkflow(workflowDefinition.secondRun)
      metadataTwo <- fetchAndValidateNonSubworkflowMetadata(secondWf, workflowDefinition, Option(firstWf.id.id))
      _ = cromwellTracker.track(metadataTwo)
      _ <- validateNoCacheHits(secondWf, metadataTwo, workflowDefinition)
      thirdWf <- runSuccessfulWorkflow(workflowDefinition.thirdRun)
      _ <- printHashDifferential(secondWf, thirdWf)
      metadataThree <- fetchAndValidateNonSubworkflowMetadata(thirdWf, workflowDefinition, Option(secondWf.id.id))
      _ <- validateNoCacheMisses(thirdWf, metadataThree, workflowDefinition)
      _ <- validateDirectoryContentsCounts(workflowDefinition, thirdWf, metadataThree)
    } yield SubmitResponse(thirdWf)
  }

  def runWorkflowTwiceExpectingNoCaching(workflowDefinition: Workflow)(implicit cromwellTracker: Option[CromwellTracker]): Test[SubmitResponse] = {
    for {
      _ <- checkDescription(workflowDefinition, validityExpectation = Option(true))
      _ <- timingVerificationNotSupported(workflowDefinition.maximumAllowedTime)
      _ <- runSuccessfulWorkflow(workflowDefinition) // Build caches
      testWf <- runSuccessfulWorkflow(workflowDefinition.secondRun)
      metadata <- fetchAndValidateNonSubworkflowMetadata(testWf, workflowDefinition)
      _ <- fetchAndValidateJobManagerStyleMetadata(testWf, workflowDefinition, prefetchedOriginalNonSubWorkflowMetadata = None)
      _ = cromwellTracker.track(metadata)
      _ <- validateNoCacheHits(testWf, metadata, workflowDefinition)
      _ <- validateDirectoryContentsCounts(workflowDefinition, testWf, metadata)
    } yield SubmitResponse(testWf)
  }

  def runFailingWorkflowTwiceExpectingNoCaching(workflowDefinition: Workflow)(implicit cromwellTracker: Option[CromwellTracker]): Test[SubmitResponse] = {
    for {
      _ <- checkDescription(workflowDefinition, validityExpectation = None)
      _ <- timingVerificationNotSupported(workflowDefinition.maximumAllowedTime)
      _ <- runFailingWorkflow(workflowDefinition) // Build caches
      testWf <- runFailingWorkflow(workflowDefinition)
      metadata <- fetchAndValidateNonSubworkflowMetadata(testWf, workflowDefinition)
      _ <- fetchAndValidateJobManagerStyleMetadata(testWf, workflowDefinition, prefetchedOriginalNonSubWorkflowMetadata = None)
      _ = cromwellTracker.track(metadata)
      _ <- validateNoCacheHits(testWf, metadata, workflowDefinition)
      _ <- validateDirectoryContentsCounts(workflowDefinition, testWf, metadata)
    } yield SubmitResponse(testWf)
  }

  private def cromwellRestart(workflowDefinition: Workflow,
                              callMarker: CallMarker,
                              testRecover: Boolean,
                              finalStatus: TerminalStatus)(
                              implicit cromwellTracker: Option[CromwellTracker]): Test[SubmitResponse] = {
    CentaurConfig.runMode match {
      case ManagedCromwellServer(_, postRestart, withRestart) if withRestart =>
        for {
          _ <- checkDescription(workflowDefinition, validityExpectation = Option(true))
          _ <- timingVerificationNotSupported(workflowDefinition.maximumAllowedTime)
          submittedWorkflow <- submitWorkflow(workflowDefinition)
          jobId <- pollUntilCallIsRunning(workflowDefinition, submittedWorkflow, callMarker.callKey)
          _ = CromwellManager.stopCromwell(s"Scheduled restart from ${workflowDefinition.testName}")
          _ = CromwellManager.startCromwell(postRestart)
          _ <- expectSomeProgress(
            workflow = submittedWorkflow,
            testDefinition = workflowDefinition,
            expectedStatuses = Set(Running, finalStatus),
            timeout = CentaurConfig.workflowProgressTimeout,
          )
          _ <- pollUntilStatus(submittedWorkflow, workflowDefinition, finalStatus)
          metadata <- fetchAndValidateNonSubworkflowMetadata(submittedWorkflow, workflowDefinition)
          _ <- fetchAndValidateJobManagerStyleMetadata(submittedWorkflow, workflowDefinition, prefetchedOriginalNonSubWorkflowMetadata = None)
          _ = cromwellTracker.track(metadata)
          _ <- if (testRecover) {
            validateRecovered(workflowDefinition, submittedWorkflow, metadata, callMarker.callKey, jobId)
          }
          else {
            Test.successful(())
          }
          _ <- validateDirectoryContentsCounts(workflowDefinition, submittedWorkflow, metadata)
        } yield SubmitResponse(submittedWorkflow)
      case _ if finalStatus == Succeeded => runSuccessfulWorkflowAndVerifyMetadata(workflowDefinition)
      case _ if finalStatus == Failed => runFailingWorkflowAndVerifyMetadata(workflowDefinition)
      case _ => Test.invalidTestDefinition("This test can only run successful or failed workflow", workflowDefinition)
    }
  }

  def instantAbort(workflowDefinition: Workflow)(implicit cromwellTracker: Option[CromwellTracker]): Test[SubmitResponse] = for {
    _ <- checkDescription(workflowDefinition, validityExpectation = Option(true))
    _ <- timingVerificationNotSupported(workflowDefinition.maximumAllowedTime)
    submittedWorkflow <- submitWorkflow(workflowDefinition)
    _ <- abortWorkflow(submittedWorkflow)
    _ <- expectSomeProgress(
      workflow = submittedWorkflow,
      testDefinition = workflowDefinition,
      expectedStatuses = Set(Running, Aborting, Aborted),
      timeout = CentaurConfig.workflowProgressTimeout,
    )
    _ <- pollUntilStatus(submittedWorkflow, workflowDefinition, Aborted)
    metadata <- fetchAndValidateNonSubworkflowMetadata(submittedWorkflow, workflowDefinition)
    _ <- fetchAndValidateJobManagerStyleMetadata(submittedWorkflow, workflowDefinition, prefetchedOriginalNonSubWorkflowMetadata = None)
    _ = cromwellTracker.track(metadata)
    _ <- validateDirectoryContentsCounts(workflowDefinition, submittedWorkflow, metadata)
  } yield SubmitResponse(submittedWorkflow)

  def scheduledAbort(workflowDefinition: Workflow, callMarker: CallMarker, restart: Boolean)(implicit cromwellTracker: Option[CromwellTracker]): Test[SubmitResponse] = {
    def withRestart(): Unit = CentaurConfig.runMode match {
      case ManagedCromwellServer(_, postRestart, withRestart) if withRestart =>
        CromwellManager.stopCromwell(s"Scheduled restart from ${workflowDefinition.testName}")
        CromwellManager.startCromwell(postRestart)
      case _ =>
    }

    for {
      _ <- checkDescription(workflowDefinition, validityExpectation = Option(true))
      _ <- timingVerificationNotSupported(workflowDefinition.maximumAllowedTime)
      submittedWorkflow <- submitWorkflow(workflowDefinition)
      jobId <- pollUntilCallIsRunning(workflowDefinition, submittedWorkflow, callMarker.callKey)
      // The Cromwell call status could be running but the backend job might not have started yet, give it some time
      _ <- waitFor(30.seconds)
      _ <- abortWorkflow(submittedWorkflow)
      _ = if(restart) withRestart()
      _ <- expectSomeProgress(
        workflow = submittedWorkflow,
        testDefinition = workflowDefinition,
        expectedStatuses = Set(Running, Aborting, Aborted),
        timeout = CentaurConfig.workflowProgressTimeout,
      )
      _ <- pollUntilStatus(submittedWorkflow, workflowDefinition, Aborted)
      _ <- validatePAPIAborted(workflowDefinition, submittedWorkflow, jobId)
      // Wait a little to make sure that if the abort didn't work and calls start running we see them in the metadata
      _ <- waitFor(30.seconds)
      metadata <- fetchAndValidateNonSubworkflowMetadata(submittedWorkflow, workflowDefinition)
      _ <- fetchAndValidateJobManagerStyleMetadata(submittedWorkflow, workflowDefinition, prefetchedOriginalNonSubWorkflowMetadata = None)
      _ = cromwellTracker.track(metadata)
      _ <- validateDirectoryContentsCounts(workflowDefinition, submittedWorkflow, metadata)
    } yield SubmitResponse(submittedWorkflow)
  }

  def workflowRestart(workflowDefinition: Workflow,
                             callMarker: CallMarker,
                             recover: Boolean,
                             finalStatus: TerminalStatus)(
                             implicit cromwellTracker: Option[CromwellTracker]): Test[SubmitResponse] = {
    cromwellRestart(workflowDefinition, callMarker, testRecover = recover, finalStatus = finalStatus)
  }

  def submitInvalidWorkflow(workflow: Workflow, expectedSubmitResponse: SubmitHttpResponse): Test[SubmitResponse] = {
    for {
      _ <- checkDescription(workflow, validityExpectation = None)
      _ <- timingVerificationNotSupported(workflow.maximumAllowedTime)
      actualSubmitResponse <- Operations.submitInvalidWorkflow(workflow)
      _ <- validateSubmitFailure(workflow, expectedSubmitResponse, actualSubmitResponse)
    } yield actualSubmitResponse
  }

  def papiUpgrade(workflowDefinition: Workflow, callMarker: CallMarker)(implicit cromwellTracker: Option[CromwellTracker]): Test[SubmitResponse] = {
    CentaurConfig.runMode match {
      case ManagedCromwellServer(_, postRestart, withRestart) if withRestart =>
        for {
          _ <- checkDescription(workflowDefinition, validityExpectation = Option(true))
          _ <- timingVerificationNotSupported(workflowDefinition.maximumAllowedTime)
          first <- submitWorkflow(workflowDefinition)
          _ <- pollUntilCallIsRunning(workflowDefinition, first, callMarker.callKey)
          _ = CromwellManager.stopCromwell(s"Scheduled restart from ${workflowDefinition.testName}")
          _ = CromwellManager.startCromwell(postRestart)
          _ <- expectSomeProgress(
            workflow = first,
            testDefinition = workflowDefinition,
            expectedStatuses = Set(Running, Succeeded),
            timeout = CentaurConfig.workflowProgressTimeout,
          )
          _ <- pollUntilStatus(first, workflowDefinition, Succeeded)
          _ <- checkDescription(workflowDefinition.secondRun, validityExpectation = Option(true))
          second <- runSuccessfulWorkflow(workflowDefinition.secondRun) // Same WDL and config but a "backend" runtime option targeting PAPI v2.
          _ <- printHashDifferential(first, second)
          metadata <- fetchAndValidateNonSubworkflowMetadata(second, workflowDefinition, Option(first.id.id))
          _ <- fetchAndValidateJobManagerStyleMetadata(second, workflowDefinition, prefetchedOriginalNonSubWorkflowMetadata = None)
          _ = cromwellTracker.track(metadata)
          _ <- validateNoCacheMisses(second, metadata, workflowDefinition)
          _ <- validateDirectoryContentsCounts(workflowDefinition, second, metadata)
        } yield SubmitResponse(second)
      case _ => Test.invalidTestDefinition("Configuration not supported by PapiUpgradeTest", workflowDefinition)
    }
  }

  implicit class EnhancedCromwellTracker(val tracker: Option[CromwellTracker]) extends AnyVal {
    def track(metadata: WorkflowMetadata): Unit = tracker foreach { _.track(metadata) }
  }
}


text:
class Admin::SearchesController < Admin::AdminController
  def show
    if petition_search?
      redirect_to admin_petitions_url(search_params)
    elsif signature_search?
      redirect_to admin_signatures_url(search_params)
    else
      redirect_to admin_root_url, notice: "Sorry, we didn't understand your query"
    end
  end

  private

  def petition_search?
    params[:type] == "petition"
  end

  def signature_search?
    params[:type] == "signature"
  end

  def search_params
    if petition_search?
      if params[:match] == "none"
        params.permit(:q, :match)
      elsif params[:tags].present?
        params.permit(:q, :match, tags: [])
      else
        params.permit(:q)
      end
    elsif signature_search?
      params.permit(:q)
    else
      {}
    end
  end
end


text:
"""A script for logging into Keycloak and getting a Bearer access token.

Because the token is backed by a Keycloak session it will expire after a short
period of time (the lifetime of the session before it expires).

The Keycloak token is save to a file called "keycloak.token" in the current directory.

Environmental Variables:
    AWS_CREDENTIALS : File path to a JSON encode file containing the following keys
                      "aws_access_key" and "aws_secret_key"

Author:
    Derek Pryor <Derek.Pryor@jhuapl.edu>
"""

import argparse
import os
import sys
import getpass
import json
import ssl

from urllib.request import Request, urlopen
from urllib.parse import urlencode
from urllib.error import HTTPError

import alter_path
from lib import utils

def request(url, params = None, headers = {}, method = None, convert = urlencode):
    """Make an HTTP(S) query and return the results.

        Note: If the url starts with "https" SSL hostname and cert checking is disabled

    Args:
        url (string) : URL to query
        params : None or an object that will be passed to the convert argument
                 to produce a string
        headers (dict) : Dictionary of HTTP headers
        method (None|string) : HTTP method to use or None for the default method
                               based on the different arguments
        convert : Function to convert params into a string
                  Defaults to urlencode, taking a dict and making a url encoded string

    Returns:
        (string) : Data returned from the request. If an error occured, the error
                   is printed and any data returned by the server is returned.
    """
    rq = Request(
        url,
        data = None if params is None else convert(params).encode("utf-8"),
        headers = headers,
        method = method
    )

    if url.startswith("https"):
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
    else:
        ctx = None

    try:
        response = urlopen(rq, context=ctx).read().decode("utf-8")
        return response
    except HTTPError as e:
        print(e, file=sys.stderr)
        print(e.read().decode("utf-8"), file=sys.stderr)
        return None

if __name__ == "__main__":
    os.chdir(os.path.abspath(os.path.dirname(__file__)))

    parser = argparse.ArgumentParser(description = "Script to get a KeyCloak Bearer Token",
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--username", default = None, help = "KeyCloak Username ('-' to read from stdin)")
    parser.add_argument("--password", default = None, help = "KeyCloak Password ('-' to read from stdin)")
    parser.add_argument("--output", "-o", default = '-', help = "File to save the token to ('-' to write to stdout (DEFAULT))")
    parser.add_argument("hostname", help="Pulic hostname of the target Authentication server to get the bearer token for")

    args = parser.parse_args()

    if args.username is None:
        username = input("Username: ")
    else:
        username = args.username
        if username == '-':
            username = sys.stdin.readline().strip()

    if args.password is None:
        password = getpass.getpass()
    else:
        password = args.password
        if password == '-':
            password = sys.stdin.readline().strip()

    if not args.hostname.lower().startswith("auth"):
        print("Hostname doesn't start with 'auth'", file=sys.stderr)

    url = "https://" + args.hostname + "/auth/realms/BOSS/protocol/openid-connect/token"
    print(url)
    params = {
        "grant_type": "password",
        "client_id": "endpoint",
        "username": username,
        "password": password,
    }
    headers = {
        "Content-Type": "application/x-www-form-urlencoded",
    }

    response = request(url, params, headers)
    if response is None:
        sys.exit(1)

    # DP NOTE: Prints are done to stderr so that stdout can be redirected / piped
    #          without capturing status information from the program
    response = json.loads(response)
    if "access_token" not in response:
        print("Didn't get a token, exiting...", file=sys.stderr)
        sys.exit(1)

    token = response["access_token"]
    with utils.open_(args.output, "w") as fh:
        fh.write(token)
        print("Token writen to '{}'".format(args.output), file=sys.stderr)
        sys.exit(0)


text:
> Submit crash reports to a remote server.

Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer-process)

The following is an example of automatically submitting a crash report to a
remote server:

```javascript
const {crashReporter} = require('electron')

crashReporter.start({
  productName: 'YourName',
  companyName: 'YourCompany',
  submitURL: 'https://your-domain.com/url-to-submit',
  autoSubmit: true
})
```

For setting up a server to accept and process crash reports, you can use
following projects:

* [socorro](https://github.com/mozilla/socorro)
* [mini-breakpad-server](https://github.com/electron/mini-breakpad-server)

Crash reports are saved locally in an application-specific temp directory folder.
For a `productName` of `YourName`, crash reports will be stored in a folder
named `YourName Crashes` inside the temp directory. You can customize this temp
directory location for your app by calling the `app.setPath('temp', '/my/custom/temp')`
API before starting the crash reporter.

## Methods

The `crashReporter` module has the following methods:

### `crashReporter.start(options)`

* `options` Object
  * `companyName` String (optional)
  * `submitURL` String - URL that crash reports will be sent to as POST.
  * `productName` String (optional) - Defaults to `app.getName()`.
  * `uploadToServer` Boolean (optional) _macOS_ - Whether crash reports should be sent to the server
    Default is `true`.
  * `ignoreSystemCrashHandler` Boolean (optional) - Default is `false`.
  * `extra` Object (optional) - An object you can define that will be sent along with the
    report. Only string properties are sent correctly, Nested objects are not
    supported.

You are required to call this method before using any other `crashReporter` APIs
and in each process (main/renderer) from which you want to collect crash reports.
You can pass different options to `crashReporter.start` when calling from different processes.

**Note:** On Windows and Linux, Electron uses `breakpad` for crash collection and reporting.
Crashes can be collected from the main and renderer process, but not from the child processes
created via the `child_process` module.

**Note:** On macOS, Electron uses a new `crashpad` client for crash collection and reporting.
Crashes can be collected from the main, renderer and any of the child processes created via the `child_process` module.
If you want to enable crash reporting, initializing `crashpad` from the main process using `crashReporter.start` is required
regardless of which process you want to collect crashes from. Once initialized this way, the crashpad handler collects
crashes from all processes. You still have to call `crashReporter.start` from the renderer process, otherwise crashes from
renderer processes will get reported without `companyName`, `productName` or any of the `extra` information.

### `crashReporter.getLastCrashReport()`

Returns [`CrashReport`](structures/crash-report.md):

Returns the date and ID of the last crash report. If no crash reports have been
sent or the crash reporter has not been started, `null` is returned.

### `crashReporter.getUploadedReports()`

Returns [`CrashReport[]`](structures/crash-report.md):

Returns all uploaded crash reports. Each report contains the date and uploaded
ID.

### `crashReporter.getUploadToServer()` _macOS_

Returns `Boolean` - Whether reports should be submitted to the server.  Set through
the `start` method or `setUploadToServer`.

**Note:** This API can only be called from the main process.

### `crashReporter.setUploadToServer(uploadToServer)` _macOS_

* `uploadToServer` Boolean _macOS_ - Whether reports should be submitted to the server

This would normally be controlled by user preferences. This has no effect if
called before `start` is called.

**Note:** This API can only be called from the main process.

## Crash Report Payload

The crash reporter will send the following data to the `submitURL` as
a `multipart/form-data` `POST`:

* `ver` String - The version of Electron.
* `platform` String - e.g. 'win32'.
* `process_type` String - e.g. 'renderer'.
* `guid` String - e.g. '5e1286fc-da97-479e-918b-6bfb0c3d1c72'
* `_version` String - The version in `package.json`.
* `_productName` String - The product name in the `crashReporter` `options`
  object.
* `prod` String - Name of the underlying product. In this case Electron.
* `_companyName` String - The company name in the `crashReporter` `options`
  object.
* `upload_file_minidump` File - The crash report in the format of `minidump`.
* All level one properties of the `extra` object in the `crashReporter`
  `options` object.


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>The Case of Azure Websites and Continuous Deployment | TripDubRoot</title>
	<meta name="description" content="TL;DR: Build a site to do wireless surveys: https://wlansurvey.azurewebsites.net/So this post has a misleading title... Because I'm not going to explain how ...">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta http-equiv="X-Frame-Options" content="sameorigin">

	<link rel="stylesheet" href="/css/main.css">

	<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">

	<link rel="canonical" href="http://tripdubroot.com/azure/development/devops/2015/03/03/the-case-of-azure-websites-and-continuous-deployment.html">

	<link rel="alternate" type="application/atom+xml" title="TripDubRoot" href="http://tripdubroot.com/feed.xml" />

	<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">

	<link href="//fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,700italic,400italic" rel="stylesheet" type="text/css">

	<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min.css">

			TripDubRoot

					About

The Case of Azure Websites and Continuous Deployment

    March 3, 2015
     - {"login"=>"adminian", "email"=>"ian.philpot@microsoft.com", "display_name"=>"adminian", "first_name"=>"", "last_name"=>""}

TL;DR: Build a site to do wireless surveys: https://wlansurvey.azurewebsites.net/

So this post has a misleading title... Because I'm not going to explain how this works, Azure Websites continuous deployment is not anything really new, and also It's well documented here and here.

Anyhow, the family and I recently moved into a new house. Our ISP was out today, running cables and getting things setup. Since I didn't really know how well my wireless router was going to cover the house, I asked Nick the fella working on getting me back online, if he had the ability to do a wireless survey of my house.

Nick said, "Well they give us this Airport Utillity app on our phone. I can tell you what the db levels are, but I'm not really sure what they mean".

Problem: This person should be able to tell me what my signal quality is, room by room.

Solution: Five minutes googling with bing lead me to a Stack Overflow post that sounded smart enough and even had math explaining how to go from dBm to Quality percentage. Time to deploy something to Azure.

Enter Azure Websites Continuous Deployment. While he finished up the house, I started writing some quick code, pushed to GitHub, and setup my website in Azure to deploy from... you guessed it GitHub.

At this point you maybe asking: "Pray tell, how did you deploy to Azure with no internet connectivity?".

To that I say: "With my Verizon Jetpack, of course".

By the time he was finished, I'd installed the Airport Utility app on my iPhone. Ran around the house gathering the dBm metrics for each room, and plugged them into: http://wlansurvey.azurewebsites.net.

He was a little shocked, but took down the web address and said he was going to tell all the guys at the office.

Awesome! Hope you all had a great weekend... I spent mine moving.

Please enable JavaScript to view the comments powered by Disqus.

Powered by Jekyll with Type Theme


text:
#include "fsl_spi.h"
#include "fsl_flexcomm.h"

/*******************************************************************************
 * Definitons
 ******************************************************************************/
/* Note:  FIFOCFG[SIZE] has always value 1 = 8 items depth */
#define SPI_FIFO_DEPTH(base) ((((base)->FIFOCFG & SPI_FIFOCFG_SIZE_MASK) >> SPI_FIFOCFG_SIZE_SHIFT) << 3)

/* Convert transfer count to transfer bytes. dataWidth is a
 * range <0,15>. Range <8,15> represents 2B transfer */
#define SPI_COUNT_TO_BYTES(dataWidth, count) ((count) << ((dataWidth) >> 3U))
#define SPI_BYTES_TO_COUNT(dataWidth, bytes) ((bytes) >> ((dataWidth) >> 3U))

/*******************************************************************************
 * Variables
 ******************************************************************************/
/*! @brief internal SPI config array */
static spi_config_t g_configs[FSL_FEATURE_SOC_SPI_COUNT] = {(spi_data_width_t)0};

/*! @brief IRQ name array */
static const IRQn_Type s_spiIRQ[] = SPI_IRQS;

/*******************************************************************************
 * Code
 ******************************************************************************/

void *SPI_GetConfig(SPI_Type *base)
{
    int32_t instance;
    instance = FLEXCOMM_GetInstance(base);
    if (instance < 0)
    {
        return NULL;
    }
    return &g_configs[instance];
}

void SPI_MasterGetDefaultConfig(spi_master_config_t *config)
{
    assert(NULL != config);

    config->enableLoopback = false;
    config->enableMaster = true;
    config->polarity = kSPI_ClockPolarityActiveHigh;
    config->phase = kSPI_ClockPhaseFirstEdge;
    config->direction = kSPI_MsbFirst;
    config->baudRate_Bps = 500000U;
    config->dataWidth = kSPI_Data8Bits;
    config->sselNum = kSPI_Ssel0;
    config->txWatermark = kSPI_TxFifo0;
    config->rxWatermark = kSPI_RxFifo1;
}

status_t SPI_MasterInit(SPI_Type *base, const spi_master_config_t *config, uint32_t srcClock_Hz)
{
    int32_t result = 0, instance = 0;
    uint32_t tmp;

    /* assert params */
    assert(!((NULL == base) || (NULL == config) || (0 == srcClock_Hz)));
    if ((NULL == base) || (NULL == config) || (0 == srcClock_Hz))
    {
        return kStatus_InvalidArgument;
    }

    /* initialize flexcomm to SPI mode */
    result = FLEXCOMM_Init(base, FLEXCOMM_PERIPH_SPI);
    assert(kStatus_Success == result);
    if (kStatus_Success != result)
    {
        return result;
    }

    /* set divider */
    result = SPI_MasterSetBaud(base, config->baudRate_Bps, srcClock_Hz);
    if (kStatus_Success != result)
    {
        return result;
    }
    /* get instance number */
    instance = FLEXCOMM_GetInstance(base);
    assert(instance >= 0);

    /* store configuration */
    g_configs[instance].dataWidth = config->dataWidth;
    g_configs[instance].sselNum = config->sselNum;
    /* enable FIFOs */
    base->FIFOCFG |= SPI_FIFOCFG_EMPTYTX_MASK | SPI_FIFOCFG_EMPTYRX_MASK;
    base->FIFOCFG |= SPI_FIFOCFG_ENABLETX_MASK | SPI_FIFOCFG_ENABLERX_MASK;
    /* trigger level - empty txFIFO, one item in rxFIFO */
    tmp = base->FIFOTRIG & (~(SPI_FIFOTRIG_RXLVL_MASK | SPI_FIFOTRIG_TXLVL_MASK));
    tmp |= SPI_FIFOTRIG_TXLVL(config->txWatermark) | SPI_FIFOTRIG_RXLVL(config->rxWatermark);
    /* enable generating interrupts for FIFOTRIG levels */
    tmp |= SPI_FIFOTRIG_TXLVLENA_MASK | SPI_FIFOTRIG_RXLVLENA_MASK;
    /* set FIFOTRIG */
    base->FIFOTRIG = tmp;
    /* configure SPI mode */
    tmp = base->CFG;
    tmp &= ~(SPI_CFG_MASTER_MASK | SPI_CFG_LSBF_MASK | SPI_CFG_CPHA_MASK | SPI_CFG_CPOL_MASK | SPI_CFG_LOOP_MASK);
    /* phase */
    tmp |= SPI_CFG_CPHA(config->phase);
    /* polarity */
    tmp |= SPI_CFG_CPOL(config->polarity);
    /* direction */
    tmp |= SPI_CFG_LSBF(config->direction);
    /* master mode */
    tmp |= SPI_CFG_MASTER(1);
    /* loopback */
    tmp |= SPI_CFG_LOOP(config->enableLoopback);
    base->CFG = tmp;
    SPI_Enable(base, config->enableMaster);
    return kStatus_Success;
}

void SPI_SlaveGetDefaultConfig(spi_slave_config_t *config)
{
    assert(NULL != config);

    config->enableSlave = true;
    config->polarity = kSPI_ClockPolarityActiveHigh;
    config->phase = kSPI_ClockPhaseFirstEdge;
    config->direction = kSPI_MsbFirst;
    config->dataWidth = kSPI_Data8Bits;
    config->txWatermark = kSPI_TxFifo0;
    config->rxWatermark = kSPI_RxFifo1;
}

status_t SPI_SlaveInit(SPI_Type *base, const spi_slave_config_t *config)
{
    int32_t result = 0, instance;
    uint32_t tmp;

    /* assert params */
    assert(!((NULL == base) || (NULL == config)));
    if ((NULL == base) || (NULL == config))
    {
        return kStatus_InvalidArgument;
    }
    /* configure flexcomm to SPI, enable clock gate */
    result = FLEXCOMM_Init(base, FLEXCOMM_PERIPH_SPI);
    assert(kStatus_Success == result);
    if (kStatus_Success != result)
    {
        return result;
    }

    instance = FLEXCOMM_GetInstance(base);

    /* store configuration */
    g_configs[instance].dataWidth = config->dataWidth;
    /* empty and enable FIFOs */
    base->FIFOCFG |= SPI_FIFOCFG_EMPTYTX_MASK | SPI_FIFOCFG_EMPTYRX_MASK;
    base->FIFOCFG |= SPI_FIFOCFG_ENABLETX_MASK | SPI_FIFOCFG_ENABLERX_MASK;
    /* trigger level - empty txFIFO, one item in rxFIFO */
    tmp = base->FIFOTRIG & (~(SPI_FIFOTRIG_RXLVL_MASK | SPI_FIFOTRIG_TXLVL_MASK));
    tmp |= SPI_FIFOTRIG_TXLVL(config->txWatermark) | SPI_FIFOTRIG_RXLVL(config->rxWatermark);
    /* enable generating interrupts for FIFOTRIG levels */
    tmp |= SPI_FIFOTRIG_TXLVLENA_MASK | SPI_FIFOTRIG_RXLVLENA_MASK;
    /* set FIFOTRIG */
    base->FIFOTRIG = tmp;
    /* configure SPI mode */
    tmp = base->CFG;
    tmp &= ~(SPI_CFG_MASTER_MASK | SPI_CFG_LSBF_MASK | SPI_CFG_CPHA_MASK | SPI_CFG_CPOL_MASK);
    /* phase */
    tmp |= SPI_CFG_CPHA(config->phase);
    /* polarity */
    tmp |= SPI_CFG_CPOL(config->polarity);
    /* direction */
    tmp |= SPI_CFG_LSBF(config->direction);
    base->CFG = tmp;
    SPI_Enable(base, config->enableSlave);
    return kStatus_Success;
}

void SPI_Deinit(SPI_Type *base)
{
    /* Assert arguments */
    assert(NULL != base);
    /* Disable interrupts, disable dma requests, disable peripheral */
    base->FIFOINTENCLR = SPI_FIFOINTENCLR_TXERR_MASK | SPI_FIFOINTENCLR_RXERR_MASK | SPI_FIFOINTENCLR_TXLVL_MASK |
                         SPI_FIFOINTENCLR_RXLVL_MASK;
    base->FIFOCFG &= ~(SPI_FIFOCFG_DMATX_MASK | SPI_FIFOCFG_DMARX_MASK);
    base->CFG &= ~(SPI_CFG_ENABLE_MASK);
}

void SPI_EnableTxDMA(SPI_Type *base, bool enable)
{
    if (enable)
    {
        base->FIFOCFG |= SPI_FIFOCFG_DMATX_MASK;
    }
    else
    {
        base->FIFOCFG &= ~SPI_FIFOCFG_DMATX_MASK;
    }
}

void SPI_EnableRxDMA(SPI_Type *base, bool enable)
{
    if (enable)
    {
        base->FIFOCFG |= SPI_FIFOCFG_DMARX_MASK;
    }
    else
    {
        base->FIFOCFG &= ~SPI_FIFOCFG_DMARX_MASK;
    }
}

status_t SPI_MasterSetBaud(SPI_Type *base, uint32_t baudrate_Bps, uint32_t srcClock_Hz)
{
    uint32_t tmp;

    /* assert params */
    assert(!((NULL == base) || (0 == baudrate_Bps) || (0 == srcClock_Hz)));
    if ((NULL == base) || (0 == baudrate_Bps) || (0 == srcClock_Hz))
    {
        return kStatus_InvalidArgument;
    }

    /* calculate baudrate */
    tmp = (srcClock_Hz / baudrate_Bps) - 1;
    if (tmp > 0xFFFF)
    {
        return kStatus_SPI_BaudrateNotSupport;
    }
    base->DIV &= ~SPI_DIV_DIVVAL_MASK;
    base->DIV |= SPI_DIV_DIVVAL(tmp);
    return kStatus_Success;
}

void SPI_WriteData(SPI_Type *base, uint16_t data, uint32_t configFlags)
{
    uint32_t control = 0;
    int32_t instance;

    /* check params */
    assert(NULL != base);
    /* get and check instance */
    instance = FLEXCOMM_GetInstance(base);
    assert(!(instance < 0));
    if (instance < 0)
    {
        return;
    }

    /* set data width */
    control |= SPI_FIFOWR_LEN(g_configs[instance].dataWidth);
    /* set sssel */
    control |= (SPI_DEASSERT_ALL & (~SPI_DEASSERTNUM_SSEL(g_configs[instance].sselNum)));
    /* mask configFlags */
    control |= (configFlags & SPI_FIFOWR_FLAGS_MASK);
    /* control should not affect lower 16 bits */
    assert(!(control & 0xFFFF));
    base->FIFOWR = data | control;
}

status_t SPI_MasterTransferCreateHandle(SPI_Type *base,
                                        spi_master_handle_t *handle,
                                        spi_master_callback_t callback,
                                        void *userData)
{
    int32_t instance = 0;

    /* check 'base' */
    assert(!(NULL == base));
    if (NULL == base)
    {
        return kStatus_InvalidArgument;
    }
    /* check 'handle' */
    assert(!(NULL == handle));
    if (NULL == handle)
    {
        return kStatus_InvalidArgument;
    }
    /* get flexcomm instance by 'base' param */
    instance = FLEXCOMM_GetInstance(base);
    assert(!(instance < 0));
    if (instance < 0)
    {
        return kStatus_InvalidArgument;
    }

    memset(handle, 0, sizeof(*handle));
    /* Initialize the handle */
    if (base->CFG & SPI_CFG_MASTER_MASK)
    {
        FLEXCOMM_SetIRQHandler(base, (flexcomm_irq_handler_t)(uintptr_t)SPI_MasterTransferHandleIRQ, handle);
    }
    else
    {
        FLEXCOMM_SetIRQHandler(base, (flexcomm_irq_handler_t)(uintptr_t)SPI_SlaveTransferHandleIRQ, handle);
    }

    handle->dataWidth = g_configs[instance].dataWidth;
    /* in slave mode, the sselNum is not important */
    handle->sselNum = g_configs[instance].sselNum;
    handle->txWatermark = (spi_txfifo_watermark_t)SPI_FIFOTRIG_TXLVL_GET(base);
    handle->rxWatermark = (spi_rxfifo_watermark_t)SPI_FIFOTRIG_RXLVL_GET(base);
    handle->callback = callback;
    handle->userData = userData;

    /* Enable SPI NVIC */
    EnableIRQ(s_spiIRQ[instance]);

    return kStatus_Success;
}

status_t SPI_MasterTransferBlocking(SPI_Type *base, spi_transfer_t *xfer)
{
    int32_t instance;
    uint32_t tx_ctrl = 0, last_ctrl = 0;
    uint32_t tmp32, rxRemainingBytes, txRemainingBytes, dataWidth;
    uint32_t toReceiveCount = 0;
    uint8_t *txData, *rxData;
    uint32_t fifoDepth;

    /* check params */
    assert(!((NULL == base) || (NULL == xfer) || ((NULL == xfer->txData) && (NULL == xfer->rxData))));
    if ((NULL == base) || (NULL == xfer) || ((NULL == xfer->txData) && (NULL == xfer->rxData)))
    {
        return kStatus_InvalidArgument;
    }

    fifoDepth = SPI_FIFO_DEPTH(base);
    txData = xfer->txData;
    rxData = xfer->rxData;
    txRemainingBytes = txData ? xfer->dataSize : 0;
    rxRemainingBytes = rxData ? xfer->dataSize : 0;

    instance = FLEXCOMM_GetInstance(base);
    assert(instance >= 0);
    dataWidth = g_configs[instance].dataWidth;

    /* dataSize (in bytes) is not aligned to 16bit (2B) transfer */
    assert(!((dataWidth > kSPI_Data8Bits) && (xfer->dataSize & 0x1)));
    if ((dataWidth > kSPI_Data8Bits) && (xfer->dataSize & 0x1))
    {
        return kStatus_InvalidArgument;
    }

    /* clear tx/rx errors and empty FIFOs */
    base->FIFOCFG |= SPI_FIFOCFG_EMPTYTX_MASK | SPI_FIFOCFG_EMPTYRX_MASK;
    base->FIFOSTAT |= SPI_FIFOSTAT_TXERR_MASK | SPI_FIFOSTAT_RXERR_MASK;
    /* select slave to talk with */
    tx_ctrl |= (SPI_DEASSERT_ALL & (~SPI_DEASSERTNUM_SSEL(g_configs[instance].sselNum)));
    /* set width of data - range asserted at entry */
    tx_ctrl |= SPI_FIFOWR_LEN(dataWidth);
    /* end of transfer */
    last_ctrl |= (xfer->configFlags & (uint32_t)kSPI_FrameAssert) ? (uint32_t)kSPI_FrameAssert : 0;
    /* delay end of transfer */
    last_ctrl |= (xfer->configFlags & (uint32_t)kSPI_FrameDelay) ? (uint32_t)kSPI_FrameDelay : 0;
    /* last index of loop */
    while (txRemainingBytes || rxRemainingBytes || toReceiveCount)
    {
        /* if rxFIFO is not empty */
        if (base->FIFOSTAT & SPI_FIFOSTAT_RXNOTEMPTY_MASK)
        {
            tmp32 = base->FIFORD;
            /* rxBuffer is not empty */
            if (rxRemainingBytes)
            {
                *(rxData++) = tmp32;
                rxRemainingBytes--;
                /* read 16 bits at once */
                if (dataWidth > 8)
                {
                    *(rxData++) = tmp32 >> 8;
                    rxRemainingBytes--;
                }
            }
            /* decrease number of data expected to receive */
            toReceiveCount -= 1;
        }
        /* transmit if txFIFO is not full and data to receive does not exceed FIFO depth */
        if ((base->FIFOSTAT & SPI_FIFOSTAT_TXNOTFULL_MASK) && (toReceiveCount < fifoDepth) &&
            ((txRemainingBytes) || (rxRemainingBytes >= SPI_COUNT_TO_BYTES(dataWidth, toReceiveCount + 1))))
        {
            /* txBuffer is not empty */
            if (txRemainingBytes)
            {
                tmp32 = *(txData++);
                txRemainingBytes--;
                /* write 16 bit at once */
                if (dataWidth > 8)
                {
                    tmp32 |= ((uint32_t)(*(txData++))) << 8U;
                    txRemainingBytes--;
                }
                if (!txRemainingBytes)
                {
                    tx_ctrl |= last_ctrl;
                }
            }
            else
            {
                tmp32 = SPI_DUMMYDATA;
                /* last transfer */
                if (rxRemainingBytes == SPI_COUNT_TO_BYTES(dataWidth, toReceiveCount + 1))
                {
                    tx_ctrl |= last_ctrl;
                }
            }
            /* send data */
            tmp32 = tx_ctrl | tmp32;
            base->FIFOWR = tmp32;
            toReceiveCount += 1;
        }
    }
    /* wait if TX FIFO of previous transfer is not empty */
    while (!(base->FIFOSTAT & SPI_FIFOSTAT_TXEMPTY_MASK))
    {
    }
    return kStatus_Success;
}

status_t SPI_MasterTransferNonBlocking(SPI_Type *base, spi_master_handle_t *handle, spi_transfer_t *xfer)
{
    /* check params */
    assert(
        !((NULL == base) || (NULL == handle) || (NULL == xfer) || ((NULL == xfer->txData) && (NULL == xfer->rxData))));
    if ((NULL == base) || (NULL == handle) || (NULL == xfer) || ((NULL == xfer->txData) && (NULL == xfer->rxData)))
    {
        return kStatus_InvalidArgument;
    }

    /* dataSize (in bytes) is not aligned to 16bit (2B) transfer */
    assert(!((handle->dataWidth > kSPI_Data8Bits) && (xfer->dataSize & 0x1)));
    if ((handle->dataWidth > kSPI_Data8Bits) && (xfer->dataSize & 0x1))
    {
        return kStatus_InvalidArgument;
    }

    /* Check if SPI is busy */
    if (handle->state == kStatus_SPI_Busy)
    {
        return kStatus_SPI_Busy;
    }

    /* Set the handle information */
    handle->txData = xfer->txData;
    handle->rxData = xfer->rxData;
    /* set count */
    handle->txRemainingBytes = xfer->txData ? xfer->dataSize : 0;
    handle->rxRemainingBytes = xfer->rxData ? xfer->dataSize : 0;
    handle->totalByteCount = xfer->dataSize;
    /* other options */
    handle->toReceiveCount = 0;
    handle->configFlags = xfer->configFlags;
    /* Set the SPI state to busy */
    handle->state = kStatus_SPI_Busy;
    /* clear FIFOs when transfer starts */
    base->FIFOCFG |= SPI_FIFOCFG_EMPTYTX_MASK | SPI_FIFOCFG_EMPTYRX_MASK;
    base->FIFOSTAT |= SPI_FIFOSTAT_TXERR_MASK | SPI_FIFOSTAT_RXERR_MASK;
    /* enable generating txIRQ and rxIRQ, first transfer is fired by empty txFIFO */
    base->FIFOINTENSET |= SPI_FIFOINTENSET_TXLVL_MASK | SPI_FIFOINTENSET_RXLVL_MASK;
    return kStatus_Success;
}

status_t SPI_MasterTransferGetCount(SPI_Type *base, spi_master_handle_t *handle, size_t *count)
{
    assert(NULL != handle);

    if (!count)
    {
        return kStatus_InvalidArgument;
    }

    /* Catch when there is not an active transfer. */
    if (handle->state != kStatus_SPI_Busy)
    {
        *count = 0;
        return kStatus_NoTransferInProgress;
    }

    *count = handle->totalByteCount - handle->rxRemainingBytes;
    return kStatus_Success;
}

void SPI_MasterTransferAbort(SPI_Type *base, spi_master_handle_t *handle)
{
    assert(NULL != handle);

    /* Disable interrupt requests*/
    base->FIFOINTENSET &= ~(SPI_FIFOINTENSET_TXLVL_MASK | SPI_FIFOINTENSET_RXLVL_MASK);
    /* Empty FIFOs */
    base->FIFOCFG |= SPI_FIFOCFG_EMPTYTX_MASK | SPI_FIFOCFG_EMPTYRX_MASK;

    handle->state = kStatus_SPI_Idle;
    handle->txRemainingBytes = 0;
    handle->rxRemainingBytes = 0;
}

static void SPI_TransferHandleIRQInternal(SPI_Type *base, spi_master_handle_t *handle)
{
    uint32_t tx_ctrl = 0, last_ctrl = 0, tmp32;
    bool loopContinue;
    uint32_t fifoDepth;

    /* check params */
    assert((NULL != base) && (NULL != handle) && ((NULL != handle->txData) || (NULL != handle->rxData)));

    fifoDepth = SPI_FIFO_DEPTH(base);
    /* select slave to talk with */
    tx_ctrl |= (SPI_DEASSERT_ALL & SPI_ASSERTNUM_SSEL(handle->sselNum));
    /* set width of data */
    tx_ctrl |= SPI_FIFOWR_LEN(handle->dataWidth);
    /* end of transfer */
    last_ctrl |= (handle->configFlags & (uint32_t)kSPI_FrameAssert) ? (uint32_t)kSPI_FrameAssert : 0;
    /* delay end of transfer */
    last_ctrl |= (handle->configFlags & (uint32_t)kSPI_FrameDelay) ? (uint32_t)kSPI_FrameDelay : 0;
    do
    {
        loopContinue = false;

        /* rxFIFO is not empty */
        if (base->FIFOSTAT & SPI_FIFOSTAT_RXNOTEMPTY_MASK)
        {
            tmp32 = base->FIFORD;
            /* rxBuffer is not empty */
            if (handle->rxRemainingBytes)
            {
                /* low byte must go first */
                *(handle->rxData++) = tmp32;
                handle->rxRemainingBytes--;
                /* read 16 bits at once */
                if (handle->dataWidth > kSPI_Data8Bits)
                {
                    *(handle->rxData++) = tmp32 >> 8;
                    handle->rxRemainingBytes--;
                }
            }
            /* decrease number of data expected to receive */
            handle->toReceiveCount -= 1;
            loopContinue = true;
        }

        /* - txFIFO is not full
         * - we cannot cause rxFIFO overflow by sending more data than is the depth of FIFO
         * - txBuffer is not empty or the next 'toReceiveCount' data can fit into rxBuffer
         */
        if ((base->FIFOSTAT & SPI_FIFOSTAT_TXNOTFULL_MASK) && (handle->toReceiveCount < fifoDepth) &&
            ((handle->txRemainingBytes) ||
             (handle->rxRemainingBytes >= SPI_COUNT_TO_BYTES(handle->dataWidth, handle->toReceiveCount + 1))))
        {
            /* txBuffer is not empty */
            if (handle->txRemainingBytes)
            {
                /* low byte must go first */
                tmp32 = *(handle->txData++);
                handle->txRemainingBytes--;
                /* write 16 bit at once */
                if (handle->dataWidth > kSPI_Data8Bits)
                {
                    tmp32 |= ((uint32_t)(*(handle->txData++))) << 8U;
                    handle->txRemainingBytes--;
                }
                /* last transfer */
                if (!handle->txRemainingBytes)
                {
                    tx_ctrl |= last_ctrl;
                }
            }
            else
            {
                tmp32 = SPI_DUMMYDATA;
                /* last transfer */
                if (handle->rxRemainingBytes == SPI_COUNT_TO_BYTES(handle->dataWidth, handle->toReceiveCount + 1))
                {
                    tx_ctrl |= last_ctrl;
                }
            }
            /* send data */
            tmp32 = tx_ctrl | tmp32;
            base->FIFOWR = tmp32;
            /* increase number of expected data to receive */
            handle->toReceiveCount += 1;
            loopContinue = true;
        }
    } while (loopContinue);
}

void SPI_MasterTransferHandleIRQ(SPI_Type *base, spi_master_handle_t *handle)
{
    assert((NULL != base) && (NULL != handle));

    /* IRQ behaviour:
     * - first interrupt is triggered by empty txFIFO. The transfer function
     *   then tries empty rxFIFO and fill txFIFO interleaved that results to
     *   strategy to process as many items as possible.
     * - the next IRQs can be:
     *      rxIRQ from nonempty rxFIFO which requires to empty rxFIFO.
     *      txIRQ from empty txFIFO which requires to refill txFIFO.
     * - last interrupt is triggered by empty txFIFO. The last state is
     *   known by empty rxBuffer and txBuffer. If there is nothing to receive
     *   or send - both operations have been finished and interrupts can be
     *   disabled.
     */

    /* Data to send or read or expected to receive */
    if ((handle->txRemainingBytes) || (handle->rxRemainingBytes) || (handle->toReceiveCount))
    {
        /* Transmit or receive data */
        SPI_TransferHandleIRQInternal(base, handle);
        /* No data to send or read or receive. Transfer ends. Set txTrigger to 0 level and
         * enable txIRQ to confirm when txFIFO becomes empty */
        if ((!handle->txRemainingBytes) && (!handle->rxRemainingBytes) && (!handle->toReceiveCount))
        {
            base->FIFOTRIG = base->FIFOTRIG & (~SPI_FIFOTRIG_TXLVL_MASK);
            base->FIFOINTENSET |= SPI_FIFOINTENSET_TXLVL_MASK;
        }
        else
        {
            uint32_t rxRemainingCount = SPI_BYTES_TO_COUNT(handle->dataWidth, handle->rxRemainingBytes);
            /* If, there are no data to send or rxFIFO is already filled with necessary number of dummy data,
             * disable txIRQ. From this point only rxIRQ is used to receive data without any transmission */
            if ((!handle->txRemainingBytes) && (rxRemainingCount <= handle->toReceiveCount))
            {
                base->FIFOINTENCLR = SPI_FIFOINTENCLR_TXLVL_MASK;
            }
            /* Nothing to receive or transmit, but we still have pending data which are bellow rxLevel.
             * Cannot clear rxFIFO, txFIFO might be still active */
            if (rxRemainingCount == 0)
            {
                if ((handle->txRemainingBytes == 0) && (handle->toReceiveCount != 0) &&
                    (handle->toReceiveCount < SPI_FIFOTRIG_RXLVL_GET(base) + 1))
                {
                    base->FIFOTRIG =
                        (base->FIFOTRIG & (~SPI_FIFOTRIG_RXLVL_MASK)) | SPI_FIFOTRIG_RXLVL(handle->toReceiveCount - 1);
                }
            }
            /* Expected to receive less data than rxLevel value, we have to update rxLevel */
            else
            {
                if (rxRemainingCount < (SPI_FIFOTRIG_RXLVL_GET(base) + 1))
                {
                    base->FIFOTRIG =
                        (base->FIFOTRIG & (~SPI_FIFOTRIG_RXLVL_MASK)) | SPI_FIFOTRIG_RXLVL(rxRemainingCount - 1);
                }
            }
        }
    }
    else
    {
        /* Empty txFIFO is confirmed. Disable IRQs and restore triggers values */
        base->FIFOINTENCLR = SPI_FIFOINTENCLR_RXLVL_MASK | SPI_FIFOINTENCLR_TXLVL_MASK;
        base->FIFOTRIG = (base->FIFOTRIG & (~(SPI_FIFOTRIG_RXLVL_MASK | SPI_FIFOTRIG_RXLVL_MASK))) |
                         SPI_FIFOTRIG_RXLVL(handle->rxWatermark) | SPI_FIFOTRIG_TXLVL(handle->txWatermark);
        /* set idle state and call user callback */
        handle->state = kStatus_SPI_Idle;
        if (handle->callback)
        {
            (handle->callback)(base, handle, handle->state, handle->userData);
        }
    }
}


text:
import org.intellij.lang.annotations.Pattern;

public class StaticNestedClass {
  public void createNested(String s1, String s2) {
    new Nested(s1, s2);
  }

  private static class Nested {
    Nested(String s1, @Pattern("\\d+") String s2) { }
  }
}


text:
package com.devexmile.tunetz;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

/**
 * Created by ismailmsuya on 3/18/16.
 */
public class MyNotification extends Notification {
    private Context ctx;
    private NotificationManager mNotificationManager;

    public MyNotification(Context ctx) {
        super();
        this.ctx = ctx;
        String ns = Context.NOTIFICATION_SERVICE;
        mNotificationManager = (NotificationManager) ctx.getSystemService(ns);
        CharSequence tickerText = "Shortcuts";
        long when = System.currentTimeMillis();
        Notification.Builder builder = new Notification.Builder(ctx);
        Notification notification = builder.getNotification();
        notification.when = when;
        notification.tickerText = tickerText;
        notification.icon = R.drawable.tunetz_head;

        RemoteViews contentView = new RemoteViews(ctx.getPackageName(), R.layout.notification_layout);

        //set the button listeners
        setListeners(contentView);

        notification.contentView = contentView;
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        CharSequence contentTitle = "From Shortcuts";
        mNotificationManager.notify(548853, notification);
    }

    public void setListeners(RemoteViews view) {
        //TODO screencapture listener
        //adb shell /system/bin/screencap -p storage/sdcard0/SimpleAndroidTest/test.png
        Intent radio = new Intent(ctx, com.devexmile.tunetz.HelperActivity.class);
        radio.putExtra("DO", "radio");
        PendingIntent pRadio = PendingIntent.getActivity(ctx, 0, radio, 0);
        view.setOnClickPendingIntent(R.id.radio, pRadio);

        //TODO screen size listener
        Intent volume = new Intent(ctx, com.devexmile.tunetz.HelperActivity.class);
        volume.putExtra("DO", "volume");
        PendingIntent pVolume = PendingIntent.getActivity(ctx, 1, volume, 0);
        view.setOnClickPendingIntent(R.id.volume, pVolume);

        //reboot listener
        Intent reboot = new Intent(ctx, com.devexmile.tunetz.HelperActivity.class);
        reboot.putExtra("DO", "reboot");
        PendingIntent pReboot = PendingIntent.getActivity(ctx, 5, reboot, 0);
        view.setOnClickPendingIntent(R.id.reboot, pReboot);

        //top listener
        Intent top = new Intent(ctx, com.devexmile.tunetz.HelperActivity.class);
        top.putExtra("DO", "top");
        PendingIntent pTop = PendingIntent.getActivity(ctx, 3, top, 0);
        view.setOnClickPendingIntent(R.id.top, pTop);

        //app listener
        Intent app = new Intent(ctx, com.devexmile.tunetz.HelperActivity.class);
        app.putExtra("DO", "app");
        PendingIntent pApp = PendingIntent.getActivity(ctx, 4, app, 0);
        view.setOnClickPendingIntent(R.id.app, pApp);
    }
}


text:
using System;
using Skybrud.Social.Json;

namespace Skybrud.Social.Google.YouTube.Objects.Videos {

    /// <see>
    ///     <cref>https://developers.google.com/youtube/v3/docs/videos#snippet</cref>
    /// </see>
    public class YouTubeVideoSnippet : GoogleApiObject {

        #region Properties

        ///
        /// Gets or sets the publish date of the video.
        ///
        public DateTime PublishedAt { get; private set; }

        ///
        /// Gets or sets the ID of the parent channel.
        ///
        public string ChannelId { get; private set; }

        ///
        /// Gets or sets the title of the YouTube video.
        ///
        public string Title { get; private set; }

        ///
        /// Gets or sets the description of the video.
        ///
        public string Description { get; private set; }

        ///
        /// Gets or set information about the thumbnails available for the video.
        ///
        public YouTubeVideoThumbnails Thumbnails { get; private set; }

        ///
        /// Gets or sets the title of the parent channel.
        ///
        public string ChannelTitle { get; private set; }

        ///
        /// Gets an array with all tags of the video.
        ///
        public string[] Tags { get; private set; }

        public string CategoryId { get; private set; }

        ///
        /// Gets or sets the "liveBroadcastContent" property.
        ///
        public YouTubeVideoLiveBroadcastContent LiveBroadcastContent { get; private set; }

        #endregion

        #region Constructors

        private YouTubeVideoSnippet(JsonObject obj) : base(obj) { }

        #endregion

        #region Static methods

        ///
        /// Gets an instance of YouTubeVideoSnippet from the specified JsonObject.
        ///
        /// <param name="obj">The instance of JsonObject to parse.</param>
        public static YouTubeVideoSnippet Parse(JsonObject obj) {

            // Check whether "obj" is NULL
            if (obj == null) return null;

            // Parse the "liveBroadcastContent" property
            YouTubeVideoLiveBroadcastContent broadcast;
            string strBroadcast = obj.GetString("liveBroadcastContent");
            if (!Enum.TryParse(strBroadcast, true, out broadcast)) {
                throw new Exception("Unknown value for liveBroadcastContent \"" + strBroadcast + "\" - please create an issue so it can be fixed https://github.com/abjerner/Skybrud.Social/issues/new");
            }

            // Get the array of tags (may not be present)
            JsonArray tags = obj.GetArray("tags");

            // Initialize the snippet object
            YouTubeVideoSnippet snippet = new YouTubeVideoSnippet(obj) {
                PublishedAt = obj.GetDateTime("publishedAt"),
                ChannelId = obj.GetString("channelId"),
                Title = obj.GetString("title"),
                Description = obj.GetString("description"),
                Thumbnails = obj.GetObject("thumbnails", YouTubeVideoThumbnails.Parse),
                ChannelTitle = obj.GetString("channelTitle"),
                Tags = tags == null ? new string[0] : obj.GetArray("tags").Cast<string>(),
                CategoryId = obj.GetString("categoryId"),
                LiveBroadcastContent = broadcast
            };

            return snippet;

        }

        #endregion

    }

}


text:
% -------------------------------------------------------------------------- %
% OpenSim Moco: testSWIGAdditionalInterface.m                                %
% -------------------------------------------------------------------------- %
% Copyright (c) 2017 Stanford University and the Authors                     %
%                                                                            %
% Author(s): Christopher Dembia                                              %
%                                                                            %
% 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.                                             %
% -------------------------------------------------------------------------- %
import org.opensim.modeling.*;

%% Bounds.

model = Model();
model.setName('sliding_mass');
model.set_gravity(Vec3(0, 0, 0));
body = Body('body', 2.0, Vec3(0), Inertia(0));
model.addComponent(body);

joint = SliderJoint('slider', model.getGround(), body);
coord = joint.updCoordinate();
coord.setName('position');
model.addComponent(joint);

actu = CoordinateActuator();
actu.setCoordinate(coord);
actu.setName('actuator');
model.addComponent(actu);
model.finalizeConnections();

study = MocoStudy();
study.setName('sliding_mass');

mp = study.updProblem();
ph0 = mp.getPhase();

mp.setModel(model);

almostEqual = @(x, y) abs(x - y) < 1e-15;

mp.setTimeBounds(MocoInitialBounds(0.), MocoFinalBounds(0.1, 5.));
assert(ph0.getTimeInitialBounds().getLower() == 0);
assert(ph0.getTimeInitialBounds().getUpper() == 0);
assert(almostEqual(ph0.getTimeFinalBounds().getLower(), 0.1));
assert(almostEqual(ph0.getTimeFinalBounds().getUpper(), 5.0));

mp.setTimeBounds([0.2, 0.3], [3.5]);
assert(almostEqual(ph0.getTimeInitialBounds().getLower(), 0.2));
assert(almostEqual(ph0.getTimeInitialBounds().getUpper(), 0.3));
assert(almostEqual(ph0.getTimeFinalBounds().getLower(), 3.5));
assert(almostEqual(ph0.getTimeFinalBounds().getUpper(), 3.5));

% Use setter on MocoPhase.
ph0.setTimeBounds([2.2, 2.3], [4.5]);
assert(almostEqual(ph0.getTimeInitialBounds().getLower(), 2.2));
assert(almostEqual(ph0.getTimeInitialBounds().getUpper(), 2.3));
assert(almostEqual(ph0.getTimeFinalBounds().getLower(), 4.5));
assert(almostEqual(ph0.getTimeFinalBounds().getUpper(), 4.5));

mp.setStateInfo('/slider/position/value', MocoBounds(-5, 5), ...
    MocoInitialBounds(0));
assert(-5 == ph0.getStateInfo('/slider/position/value').getBounds().getLower());
assert( 5 == ph0.getStateInfo('/slider/position/value').getBounds().getUpper());
assert(isnan(ph0.getStateInfo('/slider/position/value').getFinalBounds().getLower()));
assert(isnan(ph0.getStateInfo('/slider/position/value').getFinalBounds().getUpper()));
mp.setStateInfo('/slider/position/speed', [-50, 50], [-3], 1.5);
assert(-50 == ph0.getStateInfo('/slider/position/speed').getBounds().getLower());
assert( 50 == ph0.getStateInfo('/slider/position/speed').getBounds().getUpper());
assert(-3 == ph0.getStateInfo('/slider/position/speed').getInitialBounds().getLower());
assert(-3 == ph0.getStateInfo('/slider/position/speed').getInitialBounds().getUpper());
assert(almostEqual(1.5, ...
    ph0.getStateInfo('/slider/position/speed').getFinalBounds().getLower()));
assert(almostEqual(1.5, ...
    ph0.getStateInfo('/slider/position/speed').getFinalBounds().getUpper()));

% Use setter on MocoPhase.
ph0.setStateInfo('/slider/position/speed', [-6, 10], [-4, 3], [0]);
assert(-6 == ph0.getStateInfo('/slider/position/speed').getBounds().getLower());
assert(10 == ph0.getStateInfo('/slider/position/speed').getBounds().getUpper());
assert(-4 == ph0.getStateInfo('/slider/position/speed').getInitialBounds().getLower());
assert( 3 == ph0.getStateInfo('/slider/position/speed').getInitialBounds().getUpper());
assert(0 == ph0.getStateInfo('/slider/position/speed').getFinalBounds().getLower());
assert(0 == ph0.getStateInfo('/slider/position/speed').getFinalBounds().getUpper());

% Controls.
mp.setControlInfo('/actuator', MocoBounds(-50, 50));
assert(-50 == ph0.getControlInfo('/actuator').getBounds().getLower());
assert( 50 == ph0.getControlInfo('/actuator').getBounds().getUpper());
mp.setControlInfo('/actuator', [18]);
assert(18 == ph0.getControlInfo('/actuator').getBounds().getLower());
assert(18 == ph0.getControlInfo('/actuator').getBounds().getUpper());

%% MocoTrajectory
time = Vector(3, 0);
time.set(0, 0);
time.set(1, 0.1);
time.set(2, 0.2);
sn = StdVectorString();
sn.add('s0');
sn.add('s1');
cn = StdVectorString();
cn.add('c0');
cn.add('c1');
cn.add('c2');
mn = StdVectorString();
mn.add('m0');
dn = StdVectorString();
dn.add('d0');
pn = StdVectorString();
pn.add('p0');
pn.add('p1');
st = Matrix(3, 2);
ct = Matrix(3, 3);
mt = Matrix(3, 1);
dt = Matrix(3, 1);
p = RowVector(2, 0.0);
it = MocoTrajectory(time, sn, cn, mn, dn, pn, st, ct, mt, dt, p);

it.setTime([15, 25, 35]);
assert(it.getTime().get(0) == 15);
assert(it.getTime().get(1) == 25);
assert(it.getTime().get(2) == 35);
timeMat = it.getTimeMat();
assert(timeMat(1) == 15);
assert(timeMat(2) == 25);
assert(timeMat(3) == 35);

it.setState('s0', [5, 3, 10]);
s0traj = it.getState('s0');
assert(s0traj.get(0) == 5);
assert(s0traj.get(1) == 3);
assert(s0traj.get(2) == 10);
it.setState('s1', [2, 6, 1]);
s1traj = it.getState('s1');
assert(s1traj.get(0) == 2);
assert(s1traj.get(1) == 6);
assert(s1traj.get(2) == 1);
s1trajMat = it.getStateMat('s1');
assert(s1trajMat(1) == 2);
assert(s1trajMat(2) == 6);
assert(s1trajMat(3) == 1);

it.setControl('c0', [10, 46, -5]);
c0traj = it.getControl('c0');
assert(c0traj.get(0) == 10);
assert(c0traj.get(1) == 46);
assert(c0traj.get(2) == -5);
it.setControl('c2', [5, 12, -1]);
c2traj = it.getControl('c2');
assert(c2traj.get(0) == 5);
assert(c2traj.get(1) == 12);
assert(c2traj.get(2) == -1);
c2trajMat = it.getControlMat('c2');
assert(c2trajMat(1) == 5);
assert(c2trajMat(2) == 12);
assert(c2trajMat(3) == -1);

it.setMultiplier('m0', [326, 1, 42]);
m0traj = it.getMultiplier('m0');
assert(m0traj.get(0) == 326);
assert(m0traj.get(1) == 1);
assert(m0traj.get(2) == 42);
m0trajMat = it.getMultiplierMat('m0');
assert(m0trajMat(1) == 326);
assert(m0trajMat(2) == 1);
assert(m0trajMat(3) == 42);

it.setDerivative('d0', [-10, 477, 125]);
d0traj = it.getDerivative('d0');
assert(d0traj.get(0) == -10);
assert(d0traj.get(1) == 477);
assert(d0traj.get(2) == 125);
d0trajMat = it.getDerivativeMat('d0');
assert(d0trajMat(1) == -10);
assert(d0trajMat(2) == 477);
assert(d0trajMat(3) == 125);

it.setParameter('p0', 25);
it.setParameter('p1', 30);
p = it.getParameters();
assert(p.get(0) == 25);
assert(p.get(1) == 30);
pMat = it.getParametersMat();
assert(pMat(1) == 25);
assert(pMat(2) == 30);
p0 = it.getParameter('p0');
assert(p0 == 25);

st = it.getStatesTrajectoryMat();
assert(st(1, 1) == 5);
assert(st(3, 2) == 1);
ct = it.getControlsTrajectoryMat();
assert(ct(1, 1) == 10);
assert(ct(3, 3) == -1);
mt = it.getMultipliersTrajectoryMat();
assert(mt(1, 1) == 326);
assert(mt(3, 1) == 42);
dt = it.getDerivativesTrajectoryMat();
assert(dt(2, 1) == 477);
assert(dt(3, 1) == 125);

pr = mp.createRep();
assert(pr.createStateInfoNames().size() == 2);


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

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
Language (PMD 4.2.6 API)
</TITLE>

<META NAME="date" CONTENT="2011-09-14">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

net.sourceforge.pmd

Class Language

java.lang.Object
  net.sourceforge.pmd.Language

public final class Language
extends java.lang.Object

Enumeration of languages for which a rule can be written.

 This has no 1-on-1 mapping to the SourceType enumeration, because rules will often
 apply to all versions of a programming language, and SourceType is version-specific.

Author:

pieter_van_raemdonck - Application Engineers NV/SA - www.ae.be

Field Summary

static Language
JAVA

static Language
JSP

Method Summary

 boolean
equals(java.lang.Object obj)

static Language
getByName(java.lang.String name)

          Get the RuleLanguage that corresponds to the given name.

 java.lang.String
getName()

 int
hashCode()

 java.lang.String
toString()

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Field Detail

JAVA

public static final Language JAVA

JSP

public static final Language JSP

Method Detail

getByName

public static Language getByName(java.lang.String name)

Get the RuleLanguage that corresponds to the given name.

Parameters:
name - the common name of the rule language; this must correspond to one of
             the name constants.

Returns:
the corresponding RuleLanuage; or null if the name is not recognized

getName

public java.lang.String getName()

Returns:
Returns the name.

equals

public boolean equals(java.lang.Object obj)

Overrides:
equals in class java.lang.Object

hashCode

public int hashCode()

Overrides:
hashCode in class java.lang.Object

toString

public java.lang.String toString()

Overrides:
toString in class java.lang.Object

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2002-2011 InfoEther. All Rights Reserved.


text:
using System.Diagnostics;
using System.Linq.Expressions;

namespace Mntone.XPath.Internal.Conditions
{
	[DebuggerDisplay("Name = {this.Name}, Value = {this.Value}")]
	internal sealed class AttributeXPathCondition : XPathCondition
	{
		public string Name { get; }
		public string Value { get; }

		public AttributeXPathCondition(string name, string value)
		{
			this.Name = name;
			this.Value = value;
		}

		public override Expression Build<T>(ParameterExpression parameter, IXPathRetriveConfig<T> config)
		{
			return Expression.Equal(
				Expression.Invoke(config.AttributeValueGetter, parameter, Expression.Constant(this.Name, typeof(string))),
				Expression.Constant(this.Value, typeof(string)));
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    >

  <PreferenceCategory android:title="@string/original_category">
    <Preference android:title="@string/original_preference"/>
    <Preference
        android:title="@string/original_preference"
        android:summary="@string/original_summary"
        />
    <Preference
        android:title="@string/original_preference"
        android:summary="@string/original_summary_with_icon"
        android:icon="@mipmap/ic_launcher"
        />
    <CheckBoxPreference
        android:title="@string/original_checkbox_preference"
        android:summaryOn="@string/original_checkbox_summary_on"
        android:summaryOff="@string/original_checkbox_summary_off"
        />
  </PreferenceCategory>

  <com.jenzz.materialpreference.PreferenceCategory android:title="@string/material_category">
    <com.jenzz.materialpreference.Preference android:title="@string/material_preference"/>
    <com.jenzz.materialpreference.Preference
        android:title="@string/material_preference"
        android:summary="@string/material_summary"
        />
    <com.jenzz.materialpreference.Preference
        android:title="@string/material_preference"
        android:summary="@string/material_summary_with_icon"
        android:icon="@mipmap/ic_launcher"
        />
    <com.jenzz.materialpreference.CheckBoxPreference
        android:title="@string/material_checkbox_preference"
        android:summaryOn="@string/material_checkbox_summary_on"
        android:summaryOff="@string/material_checkbox_summary_off"
        />
  </com.jenzz.materialpreference.PreferenceCategory>

</PreferenceScreen>


text:
package com.anrisoftware.simplerest.oanda.core;

import static java.lang.String.format;

import java.net.URI;
import java.net.URISyntaxException;

import javax.inject.Singleton;

import org.apache.commons.lang3.builder.Builder;

/**
 * Constructs the Oanda account URI from environment variables.
 * <ul>
 * <li>{@code "user.oanda.account.number"}
 * <li>{@code "user.oanda.account.token"}
 * </ul>
 *
 * @author Erwin Müller, erwin.mueller@deventm.de
 * @since 1.0
 */
@Singleton
public class DefaultOandaAccountURIFromEnv implements Builder<URI> {

    /**
     * Checks if the Oanda account environment variables are available.
     *
     * @return {@code true} if available.
     */
    public static boolean haveOandaAccountEnv() {
        return accountNumber != null && accessToken != null;
    }

    /**
     * Creates the Oanda account URI from the environment variables.
     *
     * @return the {@link URI} URI.
     *
     * @throws BuildAccountURIException
     *             if the URI is invalid.
     */
    @Override
    public URI build() {
        String string = format("oanda:%s:%s", accountNumber, accessToken);
        try {
            return new URI(string);
        } catch (URISyntaxException e) {
            throw new BuildAccountURIException(e, string);
        }
    }

    public static final String OANDA_ACCOUNT_NUMBER_PROPERTY = "user.oanda.account.number";

    public static final String OANDA_ACCOUNT_TOKEN_PROPERTY = "user.oanda.account.token";

    private static final String accountNumber = System
            .getProperty(OANDA_ACCOUNT_NUMBER_PROPERTY);

    private static final String accessToken = System
            .getProperty(OANDA_ACCOUNT_TOKEN_PROPERTY);

}


text:
<!-- <meta>
{
    "title":"Reinstall",
    "description":"Learn more about reinstalling a server at Packet!",
    "tag":["Reinstall", "Server"],
    "seo-title": "Reinstall - Packet Developer Docs",
    "seo-description": "Learn more about reinstalling a server at Packet!",
    "og-title": "Reinstall",
    "og-description": "Learn more about reinstalling a server at Packet!",
    "og-image": "/images/packet-product-docs.png"
}
</meta> -->

The Server Reinstall feature enables you to provision a new instance on the same hardware, which is perfect if you want to keep the assigned IP addresses, userdata, etc.

Reinstalls take a little longer than a normal fresh provision, since the server has to go through a deprovision process first. During deprov, we bring the server back to a "ready state", which involves wiping the disks, checking firmware, and other elements. As such, **a reinstall will fully wipe any data on the server**. After the the deprovision is complete, we'll install the OS again through a normal provision, but using the same hardware and IP addresses assigned previously.

Any Block storage volume needs to be properly detached, in order for it not to be impacted, but you will need to re-attach it once your server is re-installed.

You can find the reinstall feature via the device view page and under server actions.

![device-reinstall](/images/device-reinstall/device-reinstall.png)

If API is your thing, you can do the following payload:

```
curl -X POST -H 'X-Auth-Token: {token}' -H 'Content-Type: application/json' "https://api.packet.net/devices/{server_uuid}/actions" -d '{"type":"reinstall"}'
```


text:
<?php

namespace Centreon\Tests\Domain\Repository;

use Centreon\Domain\Entity\Image;
use Centreon\Domain\Entity\ImageDir;
use Centreon\Domain\Repository\ImagesRepository;
use PHPUnit\Framework\TestCase;
use Centreon\Test\Mock\CentreonDB;
use Centreon\Tests\Resources\Traits;

/**
 * @group Centreon
 * @group ORM-repository
 */
class ImagesRepositoryTest extends TestCase
{
    use Traits\CheckListOfIdsTrait;

    /**
     * @var array
     */
    protected $datasets = [];

    /**
     * @var \Centreon\Domain\Repository\ImagesRepository
     */
    protected $repository;

    /**
     * {@inheritdoc}
     */
    protected function setUp(): void
    {
        $db = new CentreonDB;
        $this->datasets = [
            [
                'query' => "SELECT * FROM `view_img_dir`,`view_img_dir_relation` vidr,`view_img` "
                    . "WHERE `img_id` = `vidr`.`img_img_id` AND `dir_id` = `vidr`.`dir_dir_parent_id` "
                    . "ORDER BY `dir_name`, `img_name`",
                'data' => [
                    [
                        'img_id' => '1',
                        'img_name' => 'centreon',
                        'img_path' => 'centreon.png'
                    ],
                ],
            ],
            [
                'query' => "SELECT * FROM `view_img_dir`,`view_img_dir_relation` vidr,`view_img` "
                . "WHERE `img_id` = `vidr`.`img_img_id` AND `dir_id` = `vidr`.`dir_dir_parent_id` "
                . "AND `img_name` LIKE :search AND `img_id` IN (:id0) "
                . "LIMIT :limit OFFSET :offset ORDER BY `dir_name`, `img_name`",
                'data' => [
                    [
                        'img_id' => '1',
                        'img_name' => 'centreon',
                        'img_path' => 'centreon.png'
                    ],
                ],
            ],
            [
                'query' => "SELECT FOUND_ROWS() AS number",
                'data' => [
                    [
                        'number' => '10',
                    ],
                ],
            ],
        ];
        foreach ($this->datasets as $dataset) {
            $db->addResultSet($dataset['query'], $dataset['data']);
            unset($dataset);
        }
        $this->repository = new ImagesRepository($db);
    }

    /**
     * Test the method checkListOfIds
     */
    public function testCheckListOfIds(): void
    {
        $this->checkListOfIdsTrait(
            ImagesRepository::class,
            'checkListOfIds',
            Image::TABLE,
            'img_id'
        );
    }

    /**
     * Test the method getPaginationList
     */
    public function testGetPaginationList(): void
    {
        $result = $this->repository->getPaginationList();
        $expectedImage = new Image();
        if (
            array_key_exists('img_id', $result[0])
            && array_key_exists('img_name', $result[0])
            && array_key_exists('img_path', $result[0])
        ) {
            $expectedImage->setImgId($result[0]['img_id']);
            $expectedImage->setImgName($result[0]['img_name']);
            $expectedImage->setImgPath($result[0]['img_path']);
        }

        $data = $this->datasets[0]['data'][0];
        $entity = new Image();
        $entity->setImgId($data['img_id']);
        $entity->setImgName($data['img_name']);
        $entity->setImgPath($data['img_path']);

        $this->assertEquals($entity, $expectedImage);
    }

    /**
     * Test the method getPaginationList with a different arguments
     */
    public function testGetPaginationListWithArguments(): void
    {
        $filters = [
            'search' => 'name',
            'ids' => ['ids'],
        ];
        $limit = 1;
        $offset = 0;

        $result = $this->repository->getPaginationList($filters, $limit, $offset);
        $expectedImage = new Image();
        if (
            array_key_exists('img_id', $result[0])
            && array_key_exists('img_name', $result[0])
            && array_key_exists('img_path', $result[0])
        ) {
            $expectedImage->setImgId($result[0]['img_id']);
            $expectedImage->setImgName($result[0]['img_name']);
            $expectedImage->setImgPath($result[0]['img_path']);
        }

        $data = $this->datasets[1]['data'][0];
        $entity = new Image();
        $entity->setImgId($data['img_id']);
        $entity->setImgName($data['img_name']);
        $entity->setImgPath($data['img_path']);

        $this->assertEquals($entity, $expectedImage);
    }

    /**
     * Test the method getPaginationTotal
     */
    public function testGetPaginationListTotal(): void
    {
        $total = (int)$this->datasets[2]['data'][0]['number'];
        $result = $this->repository->getPaginationListTotal();
        $this->assertEquals($total, $result);
    }
}


text:
Telescope.menus.register("userMenu", [
  {
    route: function () {
      return Router.path('user_profile', {_idOrSlug: Meteor.user().telescope.slug});
    },
    label: 'profile',
    description: 'view_your_profile'
  },
  {
    route: function () {
      return Router.path('user_edit', {slug: Meteor.user().telescope.slug});
    },
    label: 'edit_account',
    description: 'edit_your_profile'
  },
  {
    route: 'settings',
    label: 'settings',
    description: 'settings',
    adminOnly: true
  },
  {
    route: 'signOut',
    label: 'sign_out',
    description: 'sign_out'
  }
]);