text:
chrome.runtime.onMessageExternal.addListener(
    function(message, sender, sendResponse) {
      function doSendResponse(value, errorString) {
        var error = null;
        if (errorString) {
          error = {};
          error['name'] = 'ComponentExtensonError';
          error['message'] = errorString;
        }

        var errorMessage = error || chrome.extension.lastError;
        sendResponse({'value': value, 'error': errorMessage});
      }

      function getHost(url) {
        if (!url)
          return '';
        // Use the DOM to parse the URL. Since we don't add the anchor to
        // the page, this is the only reference to it and it will be
        // deleted once it's gone out of scope.
        var a = document.createElement('a');
        a.href = url;
        var origin = a.protocol + '//' + a.hostname;
        if (a.port != '')
          origin = origin + ':' + a.port;
        origin = origin + '/';
        return origin;
      }

      try {
        var requestInfo = {};
        if (sender.tab) {
          requestInfo['tabId'] = sender.tab.id;
        }

        if (sender.guestProcessId) {
          requestInfo['guestProcessId'] = sender.guestProcessId;
        }

        var method = message['method'];
        var origin = getHost(sender.url);
        if (method == 'cpu.getInfo') {
          chrome.system.cpu.getInfo(doSendResponse);
          return true;
        } else if (method == 'logging.setMetadata') {
          var metaData = message['metaData'];
          chrome.webrtcLoggingPrivate.setMetaData(
              requestInfo, origin, metaData, doSendResponse);
          return true;
        } else if (method == 'logging.start') {
          chrome.webrtcLoggingPrivate.start(
              requestInfo, origin, doSendResponse);
          return true;
        } else if (method == 'logging.uploadOnRenderClose') {
          chrome.webrtcLoggingPrivate.setUploadOnRenderClose(
              requestInfo, origin, true);
          doSendResponse();
          return false;
        } else if (method == 'logging.noUploadOnRenderClose') {
          chrome.webrtcLoggingPrivate.setUploadOnRenderClose(
              requestInfo, origin, false);
          doSendResponse();
          return false;
        } else if (method == 'logging.stop') {
          chrome.webrtcLoggingPrivate.stop(
              requestInfo, origin, doSendResponse);
          return true;
        } else if (method == 'logging.upload') {
          chrome.webrtcLoggingPrivate.upload(
              requestInfo, origin, doSendResponse);
          return true;
        } else if (method == 'logging.uploadStored') {
          var logId = message['logId'];
          chrome.webrtcLoggingPrivate.uploadStored(
              requestInfo, origin, logId, doSendResponse);
          return true;
        } else if (method == 'logging.stopAndUpload') {
          stopAllRtpDump(requestInfo, origin,
                         function(rtpDumpValue, rtpDumpErrorString) {
            if (chrome.extension.lastError !== undefined) {
              // Stopping RTP dump failed, try to stop logging but don't try
              // to upload since that will fail.
              chrome.webrtcLoggingPrivate.stop(
                  requestInfo, origin, function(stopValue, stopErrorString) {
                if (chrome.extension.lastError !== undefined) {
                  // Stopping logging also failed, report the error for logging.
                  doSendResponse(stopValue, stopErrorString);
                } else {
                  // Stopping logging succeeded, report the error for RTP dump.
                  doSendResponse(rtpDumpValue, rtpDumpErrorString);
                }
              });
            } else {
              // Stopping RTP dump succeeded.
              chrome.webrtcLoggingPrivate.stop(
                  requestInfo, origin, function(stopValue, stopErrorString) {
                if (chrome.extension.lastError !== undefined) {
                  // Stopping logging failed, report error and don't try to
                  // upload since that will fail.
                  doSendResponse(stopValue, stopErrorString);
                } else {
                  // Stopping logging succeeded.
                  chrome.webrtcLoggingPrivate.upload(
                      requestInfo, origin, doSendResponse);
                }
              });
            }
          });
          return true;
        } else if (method == 'logging.store') {
          var logId = message['logId'];
          chrome.webrtcLoggingPrivate.store(
              requestInfo, origin, logId, doSendResponse);
          return true;
        } else if (method == 'logging.discard') {
          chrome.webrtcLoggingPrivate.discard(
              requestInfo, origin, doSendResponse);
          return true;
        } else if (method == 'getSinks') {
          chrome.webrtcAudioPrivate.getSinks(doSendResponse);
          return true;
        } else if (method == 'getActiveSink') {
          chrome.webrtcAudioPrivate.getActiveSink(
              requestInfo, doSendResponse);
          return true;
        } else if (method == 'setActiveSink') {
          var sinkId = message['sinkId'];
          chrome.webrtcAudioPrivate.setActiveSink(
              requestInfo, sinkId, doSendResponse);
          return true;
        } else if (method == 'getAssociatedSink') {
          var sourceId = message['sourceId'];
          chrome.webrtcAudioPrivate.getAssociatedSink(
              origin, sourceId, doSendResponse);
          return true;
        } else if (method == 'isExtensionEnabled') {
          // This method is necessary because there may be more than one
          // version of this extension, under different extension IDs. By
          // first calling this method on the extension ID, the client can
          // check if it's loaded; if it's not, the extension system will
          // call the callback with no arguments and set
          // chrome.runtime.lastError.
          doSendResponse();
          return false;
        } else if (method == 'getNaclArchitecture') {
          chrome.runtime.getPlatformInfo(function(obj) {
            doSendResponse(obj.nacl_arch);
          });
          return true;
        } else if (method == 'logging.startRtpDump') {
          var incoming = message['incoming'] || false;
          var outgoing = message['outgoing'] || false;
          chrome.webrtcLoggingPrivate.startRtpDump(
              requestInfo, origin, incoming, outgoing, doSendResponse);
          return true;
        } else if (method == 'logging.stopRtpDump') {
          var incoming = message['incoming'] || false;
          var outgoing = message['outgoing'] || false;
          chrome.webrtcLoggingPrivate.stopRtpDump(
              requestInfo, origin, incoming, outgoing, doSendResponse);
          return true;
        } else if (method == 'logging.startAudioDebugRecordings') {
          var seconds = message['seconds'] || 0;
          chrome.webrtcLoggingPrivate.startAudioDebugRecordings(
              requestInfo, origin, seconds, doSendResponse);
          return true;
        } else if (method == 'logging.stopAudioDebugRecordings') {
          chrome.webrtcLoggingPrivate.stopAudioDebugRecordings(
              requestInfo, origin, doSendResponse);
          return true;
        } else if (method == 'logging.startWebRtcEventLogging') {
          var seconds = message['seconds'] || 0;
          chrome.webrtcLoggingPrivate.startWebRtcEventLogging(
              requestInfo, origin, seconds, doSendResponse);
          return true;
        } else if (method == 'logging.stopWebRtcEventLogging') {
          chrome.webrtcLoggingPrivate.stopWebRtcEventLogging(
              requestInfo, origin, doSendResponse);
          return true;
        }

        throw new Error('Unknown method: ' + method);
      } catch (e) {
        doSendResponse(null, e.name + ': ' + e.message);
      }
    }
);

// If Hangouts connects with a port named 'onSinksChangedListener', we
// will register a listener and send it a message {'eventName':
// 'onSinksChanged'} whenever the event fires.
function onSinksChangedPort(port) {
  function clientListener() {
    port.postMessage({'eventName': 'onSinksChanged'});
  }
  chrome.webrtcAudioPrivate.onSinksChanged.addListener(clientListener);

  port.onDisconnect.addListener(function() {
    chrome.webrtcAudioPrivate.onSinksChanged.removeListener(
        clientListener);
  });
}

// This is a one-time-use port for calling chooseDesktopMedia.  The page
// sends one message, identifying the requested source types, and the
// extension sends a single reply, with the user's selected streamId.  A port
// is used so that if the page is closed before that message is sent, the
// window picker dialog will be closed.
function onChooseDesktopMediaPort(port) {
  function sendResponse(streamId) {
    port.postMessage({'value': {'streamId': streamId}});
    port.disconnect();
  }

  port.onMessage.addListener(function(message) {
    var method = message['method'];
    if (method == 'chooseDesktopMedia') {
      var sources = message['sources'];
      var cancelId = null;
      if (port.sender.tab) {
        cancelId = chrome.desktopCapture.chooseDesktopMedia(
            sources, port.sender.tab, sendResponse);
      } else {
        var requestInfo = {};
        requestInfo['guestProcessId'] = port.sender.guestProcessId || 0;
        requestInfo['guestRenderFrameId'] =
            port.sender.guestRenderFrameRoutingId || 0;
        cancelId = chrome.webrtcDesktopCapturePrivate.chooseDesktopMedia(
            sources, requestInfo, sendResponse);
      }
      port.onDisconnect.addListener(function() {
        // This method has no effect if called after the user has selected a
        // desktop media source, so it does not need to be conditional.
        if (port.sender.tab) {
          chrome.desktopCapture.cancelChooseDesktopMedia(cancelId);
        } else {
          chrome.webrtcDesktopCapturePrivate.cancelChooseDesktopMedia(cancelId);
        }
      });
    }
  });
}

// A port for continuously reporting relevant CPU usage information to the page.
function onProcessCpu(port) {
  var tabPid = port.sender.guestProcessId || undefined;
  function processListener(processes) {
    if (tabPid == undefined) {
      // getProcessIdForTab sometimes fails, and does not call the callback.
      // (Tracked at https://crbug.com/368855.)
      // This call retries it on each process update until it succeeds.
      chrome.processes.getProcessIdForTab(port.sender.tab.id, function(x) {
        tabPid = x;
      });
      return;
    }
    var tabProcess = processes[tabPid];
    if (!tabProcess) {
      return;
    }
    var pluginProcessCpu = 0, browserProcessCpu = 0, gpuProcessCpu = 0;
    for (var pid in processes) {
      var process = processes[pid];
      if (process.type == 'browser') {
        browserProcessCpu = process.cpu;
      } else if (process.type == 'gpu') {
        gpuProcessCpu = process.cpu;
      } else if ((process.type == 'plugin' || process.type == 'nacl') &&
                 process.title.toLowerCase().indexOf('hangouts') > 0) {
        pluginProcessCpu = process.cpu;
      }
    }

    port.postMessage({
      'tabCpuUsage': tabProcess.cpu,
      'browserCpuUsage': browserProcessCpu,
      'gpuCpuUsage': gpuProcessCpu,
      'pluginCpuUsage': pluginProcessCpu
    });
  }

  chrome.processes.onUpdated.addListener(processListener);
  port.onDisconnect.addListener(function() {
    chrome.processes.onUpdated.removeListener(processListener);
  });
}

function stopAllRtpDump(requestInfo, origin, callback) {
  // Stops incoming and outgoing separately, otherwise stopRtpDump will fail if
  // either type of dump has not been started.
  chrome.webrtcLoggingPrivate.stopRtpDump(
      requestInfo, origin, true, false,
      function() {
        chrome.webrtcLoggingPrivate.stopRtpDump(
            requestInfo, origin, false, true, callback);
      });
}

chrome.runtime.onConnectExternal.addListener(function(port) {
  if (port.name == 'onSinksChangedListener') {
    onSinksChangedPort(port);
  } else if (port.name == 'chooseDesktopMedia') {
    onChooseDesktopMediaPort(port);
  } else if (port.name == 'processCpu') {
    onProcessCpu(port);
  } else {
    // Unknown port type.
    port.disconnect();
  }
});


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace Microsoft.Diagnostics.Runtime.Utilities
{
    public struct HResult
    {
        public const int S_OK = 0;
        public const int S_FALSE = 1;
        public const int E_FAIL = unchecked((int)0x80004005);
        public const int E_INVALIDARG = unchecked((int)0x80070057);
        public const int E_NOTIMPL = unchecked((int)0x80004001);
        public const int E_NOINTERFACE = unchecked((int)0x80004002);

        public bool IsOK => Value == S_OK;

        public int Value { get; set; }

        public HResult(int hr) => Value = hr;

        public static implicit operator HResult(int hr) => new HResult(hr);

        /// <summary>
        /// Helper to convert to int for comparisons.
        /// </summary>
        public static implicit operator int(HResult hr) => hr.Value;

        /// <summary>
        /// This makes "if (hr)" equivalent to SUCCEEDED(hr).
        /// </summary>
        public static implicit operator bool(HResult hr) => hr.Value >= 0;

        public override string ToString()
        {
            return Value switch
            {
                S_OK => "S_OK",
                S_FALSE => "S_FALSE",
                E_FAIL => "E_FAIL",
                E_INVALIDARG => "E_INVALIDARG",
                E_NOTIMPL => "E_NOTIMPL",
                E_NOINTERFACE => "E_NOINTERFACE",
                _ => $"{Value:x8}",
            };
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package  com.github.osisoft.ocs_sample_library_preview.dataviews;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import  com.github.osisoft.ocs_sample_library_preview.*;
import  com.github.osisoft.ocs_sample_library_preview.dataviews.*;

public class DataviewClient {

    private String baseUrl = null;
    private String apiVersion = null;
    private Gson mGson = null;
    private BaseClient baseClient;
    // REST API url strings
    // base of all requests
    private String requestBase = "api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}";

    //dataview path
    private String dataviewBase = requestBase + "/Dataviews";
    private String getDataviews = dataviewBase + "?skip={skip}&count={count}";
    private String dataviewPath = dataviewBase + "/{dataview_id}";
    private String getDataviewPreview = dataviewPath + "/preview/interpolated?startIndex={startIndex}&endIndex={endIndex}&interval={interval}&form={form}&count={count}";
    private String getDataviewInterpolated= dataviewPath + "/data/interpolated?startIndex={startIndex}&endIndex={endIndex}&interval={interval}&form={form}&count={count}";

    private String datagroupPath = dataviewPath + "/Datagroups";
    private String getDatagroup  = datagroupPath + "/{datagroup_id}";
    private String getDatagroups  = datagroupPath + "?skip={skip}&count={count}";

    public DataviewClient(BaseClient base) {
        baseClient = base;
        this.baseUrl = base.baseUrl;
        this.apiVersion = base.apiVersion;
        this.mGson = base.mGson;
    }

    public Dataview postDataview(String tenantId, String namespaceId, Dataview dataviewDef) throws SdsError {
        URL url = null;
        HttpURLConnection urlConnection = null;
        String inputLine;
        StringBuffer response = new StringBuffer();
        String dataviewId = dataviewDef.getId();

        try {
            url = new URL(baseUrl + dataviewPath.replace("{apiVersion}", apiVersion).replace("{tenantId}", tenantId).replace("{namespaceId}", namespaceId).replace("{dataview_id}", dataviewId));
            urlConnection = baseClient.getConnection(url, "POST");
        } catch (MalformedURLException mal) {
            System.out.println("MalformedURLException");
        } catch (IllegalStateException e) {
            e.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            String body = mGson.toJson(dataviewDef);
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            OutputStreamWriter writer = new OutputStreamWriter(out);
            writer.write(body);
            writer.close();

            int httpResult = urlConnection.getResponseCode();
            if (httpResult == HttpURLConnection.HTTP_OK || httpResult == HttpURLConnection.HTTP_CREATED) {
            } else {
                throw new SdsError(urlConnection, "create dataview request failed");
            }

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream()));

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        } catch (SdsError sdsError) {
            sdsError.print();
            throw sdsError;
        } catch (Exception e) {
            e.printStackTrace();
        }

        Dataview results = mGson.fromJson(response.toString(), new TypeToken<Dataview>(){}.getType());
        return results;
       // return response.toString();
    }

    public Dataview putDataview(String tenantId, String namespaceId, Dataview dataviewDef) throws SdsError {
        URL url = null;
        HttpURLConnection urlConnection = null;
        String inputLine;
        StringBuffer response = new StringBuffer();
        String dataviewId = dataviewDef.getId();

        try {
            url = new URL(baseUrl + dataviewPath.replace("{apiVersion}", apiVersion).replace("{tenantId}", tenantId).replace("{namespaceId}", namespaceId).replace("{dataview_id}", dataviewId));
            urlConnection = baseClient.getConnection(url, "PUT");
        } catch (MalformedURLException mal) {
            System.out.println("MalformedURLException");
        } catch (IllegalStateException e) {
            e.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            String body = mGson.toJson(dataviewDef);
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            OutputStreamWriter writer = new OutputStreamWriter(out);
            writer.write(body);
            writer.close();

            int httpResult = urlConnection.getResponseCode();
            if (httpResult == HttpURLConnection.HTTP_OK || httpResult == HttpURLConnection.HTTP_CREATED) {
            } else {
                throw new SdsError(urlConnection, "update dataview request failed");
            }

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream()));

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        } catch (SdsError sdsError) {
            sdsError.print();
            throw sdsError;
        } catch (Exception e) {
            e.printStackTrace();
        }

        Dataview results = mGson.fromJson(response.toString(), new TypeToken<Dataview>(){}.getType());
        return results;
       // return response.toString();
    }

    public String deleteDataview(String tenantId, String namespaceId, String dataviewId) throws SdsError {
        URL url = null;
        HttpURLConnection urlConnection = null;
        String inputLine;
        StringBuffer response = new StringBuffer();

        try {
            url = new URL(baseUrl + dataviewPath.replace("{apiVersion}", apiVersion).replace("{tenantId}", tenantId).replace("{namespaceId}", namespaceId).replace("{dataview_id}", dataviewId));
            urlConnection = baseClient.getConnection(url, "DELETE");
        } catch (MalformedURLException mal) {
            System.out.println("MalformedURLException");
        } catch (IllegalStateException e) {
            e.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {

            int httpResult = urlConnection.getResponseCode();
            if (httpResult == HttpURLConnection.HTTP_OK || httpResult == HttpURLConnection.HTTP_CREATED|| httpResult == HttpURLConnection.HTTP_NO_CONTENT) {
            } else {
                throw new SdsError(urlConnection, "delete dataview request failed");
            }

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream()));

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        } catch (SdsError sdsError) {
            sdsError.print();
            throw sdsError;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response.toString();
    }

    public Dataview getDataview(String tenantId, String namespaceId, String dataviewId) throws SdsError {
        URL url = null;
        HttpURLConnection urlConnection = null;
        String inputLine;
        StringBuffer response = new StringBuffer();

        try {
            url = new URL(baseUrl + dataviewPath.replace("{apiVersion}", apiVersion).replace("{tenantId}", tenantId).replace("{namespaceId}", namespaceId).replace("{dataview_id}", dataviewId));
            urlConnection = baseClient.getConnection(url, "GET");
        } catch (MalformedURLException mal) {
            System.out.println("MalformedURLException");
        } catch (IllegalStateException e) {
            e.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {

            int httpResult = urlConnection.getResponseCode();
            if (httpResult == HttpURLConnection.HTTP_OK || httpResult == HttpURLConnection.HTTP_CREATED) {
            } else {
                throw new SdsError(urlConnection, "get dataview request failed");
            }

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream()));

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        } catch (SdsError sdsError) {
            sdsError.print();
            throw sdsError;
        } catch (Exception e) {
            e.printStackTrace();
        }

        Dataview results = mGson.fromJson(response.toString(), new TypeToken<Dataview>(){}.getType());
        return results;
       // return response.toString();
    }

    public ArrayList<Dataview> getDataviews(String tenantId, String namespaceId) throws SdsError {
        URL url = null;
        HttpURLConnection urlConnection = null;
        String inputLine;
        StringBuffer response = new StringBuffer();

        try {
            url = new URL(baseUrl + dataviewBase.replace("{apiVersion}", apiVersion).replace("{tenantId}", tenantId).replace("{namespaceId}", namespaceId));
            urlConnection = baseClient.getConnection(url, "GET");
        } catch (MalformedURLException mal) {
            System.out.println("MalformedURLException");
        } catch (IllegalStateException e) {
            e.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {

            int httpResult = urlConnection.getResponseCode();
            if (httpResult == HttpURLConnection.HTTP_OK || httpResult == HttpURLConnection.HTTP_CREATED) {
            } else {
                throw new SdsError(urlConnection, "get dataviews request failed");
            }

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream()));

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        } catch (SdsError sdsError) {
            sdsError.print();
            throw sdsError;
        } catch (Exception e) {
            e.printStackTrace();
        }

        ArrayList<Dataview> results = mGson.fromJson(response.toString(), new TypeToken<ArrayList<Dataview>>(){}.getType());
        return results;
       // return response.toString();
    }

    public Datagroups getDatagroups(String tenantId, String namespaceId, String dataviewId, Integer skip, Integer count) throws SdsError {
        URL url = null;
        HttpURLConnection urlConnection = null;
        String inputLine;
        StringBuffer response = new StringBuffer();

        try {
            url = new URL(baseUrl + getDatagroups.replace("{apiVersion}", apiVersion).replace("{tenantId}", tenantId).replace("{namespaceId}", namespaceId).replace("{dataview_id}", dataviewId).replace("{skip}", skip.toString()).replace("{count}", count.toString()));
            urlConnection = baseClient.getConnection(url, "GET");
        } catch (MalformedURLException mal) {
            System.out.println("MalformedURLException");
        } catch (IllegalStateException e) {
            e.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {

            int httpResult = urlConnection.getResponseCode();
            if (httpResult == HttpURLConnection.HTTP_OK || httpResult == HttpURLConnection.HTTP_CREATED) {
            } else {
                throw new SdsError(urlConnection, "get dataview datagroups request failed");
            }

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream()));

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        } catch (SdsError sdsError) {
            sdsError.print();
            throw sdsError;
        } catch (Exception e) {
            e.printStackTrace();
        }

        Datagroups results = mGson.fromJson(response.toString(), new TypeToken<Datagroups>(){}.getType());
        return results;
       // return response.toString();
    }

    public Datagroup getDatagroup(String tenantId, String namespaceId, String dataviewId, String datagroupId) throws SdsError {
        URL url = null;
        HttpURLConnection urlConnection = null;
        String inputLine;
        StringBuffer response = new StringBuffer();

        try {
            url = new URL(baseUrl + getDatagroups.replace("{apiVersion}", apiVersion).replace("{tenantId}", tenantId).replace("{namespaceId}", namespaceId).replace("{dataview_id}", dataviewId).replace("{datagroupId}", datagroupId.toString()));
            urlConnection = baseClient.getConnection(url, "GET");
        } catch (MalformedURLException mal) {
            System.out.println("MalformedURLException");
        } catch (IllegalStateException e) {
            e.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {

            int httpResult = urlConnection.getResponseCode();
            if (httpResult == HttpURLConnection.HTTP_OK || httpResult == HttpURLConnection.HTTP_CREATED) {
            } else {
                throw new SdsError(urlConnection, "get dataview datagroup request failed");
            }

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream()));

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        } catch (SdsError sdsError) {
            sdsError.print();
            throw sdsError;
        } catch (Exception e) {
            e.printStackTrace();
        }

        Datagroup results = mGson.fromJson(response.toString(), new TypeToken<Datagroup>(){}.getType());
        return results;
       // return response.toString();
    }

    public String getDataviewPreview(String tenantId, String namespaceId, String dataviewId, String startIndex, String endIndex, String interval, String form, Integer count, String value_class) throws SdsError {
        URL url = null;
        HttpURLConnection urlConnection = null;
        String inputLine;
        StringBuffer response = new StringBuffer();

        try {
            url = new URL(baseUrl + getDataviewPreview.replace("{apiVersion}", apiVersion).replace("{tenantId}", tenantId).replace("{namespaceId}", namespaceId).replace("{dataview_id}", dataviewId).replace("{startIndex}", startIndex.toString()).replace("{endIndex}", endIndex.toString()).replace("{interval}", interval.toString()).replace("{form}", form.toString()).replace("{count}", count.toString()).replace("{value_class}", value_class.toString()));
            urlConnection = baseClient.getConnection(url, "GET");
        } catch (MalformedURLException mal) {
            System.out.println("MalformedURLException");
        } catch (IllegalStateException e) {
            e.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {

            int httpResult = urlConnection.getResponseCode();
            if (httpResult == HttpURLConnection.HTTP_OK || httpResult == HttpURLConnection.HTTP_CREATED) {
            } else {
                throw new SdsError(urlConnection, "get dataview preview request failed");
            }

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream()));

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        } catch (SdsError sdsError) {
            sdsError.print();
            throw sdsError;
        } catch (Exception e) {
            e.printStackTrace();
        }

       // Map<String,Object>[]  results = mGson.fromJson(response.toString(), new TypeToken<Map<String,Object>[]>(){}.getType());
      //  return results;
        return response.toString();
    }

    public String  getDataviewPreview(String tenantId, String namespaceId, String dataviewId) throws SdsError {
        return getDataviewPreview(tenantId, namespaceId, dataviewId, "","","","",0,"");
    }

    public String getDataviewInterpolated(String tenantId, String namespaceId, String dataviewId, String startIndex, String endIndex, String interval, String form, Integer count) throws SdsError {
        URL url = null;
        HttpURLConnection urlConnection = null;
        String inputLine;
        StringBuffer response = new StringBuffer();

        try {
            url = new URL(baseUrl + getDataviewInterpolated.replace("{apiVersion}", apiVersion).replace("{tenantId}", tenantId).replace("{namespaceId}", namespaceId).replace("{dataview_id}", dataviewId).replace("{startIndex}", startIndex.toString()).replace("{endIndex}", endIndex.toString()).replace("{interval}", interval.toString()).replace("{form}", form.toString()).replace("{count}", count.toString()));
            urlConnection = baseClient.getConnection(url, "GET");
        } catch (MalformedURLException mal) {
            System.out.println("MalformedURLException");
        } catch (IllegalStateException e) {
            e.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {

            int httpResult = urlConnection.getResponseCode();
            if (httpResult == HttpURLConnection.HTTP_OK || httpResult == HttpURLConnection.HTTP_CREATED) {
            } else {
                throw new SdsError(urlConnection, "get dataview data interpolated request failed");
            }

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream()));

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        } catch (SdsError sdsError) {
            sdsError.print();
            throw sdsError;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response.toString();
//        Map<String,Object>[]  results = mGson.fromJson(response.toString(), new TypeToken<Map<String,Object>[]>(){}.getType());
 //       return results;
       // return response.toString();
    }

}


text:
Ahshok::Deploy.with_configuration do

  namespace :config do

    task :setup, :except => { :no_release => true } do
      template = <<-EOF
      base: &base
        amazon_tag:    '#{amazon_tag}'
        amazon_key:    '#{amazon_key}'
        amazon_secret: '#{amazon_secret}'

      production:
        database_url:  'mysql://#{db_user}:#{db_pass}@#{db_server}/#{db_table}'
        <<: *base
      EOF
      config = ERB.new(template)

      run "mkdir -p #{shared_path}/config"
      put config.result(binding), "#{shared_path}/config/config.yml"
    end

    task :symlink, :except => { :no_release => true } do
      run "mv #{release_path}/config/config.yml #{release_path}/config/config.yml.bak"
      run "ln -nfs #{shared_path}/config/config.yml #{release_path}/config/config.yml"
    end

  end

  after 'deploy:setup', 'config:setup' unless fetch(:skip_config_setup, false)
  after 'deploy:finalize_update', 'config:symlink'

end


text:
package debop4s.rediscala.set

import debop4s.rediscala.AbstractRedisFunSuite
import org.springframework.beans.factory.annotation.Autowired

class DefaultSyncRedisZSetFunSuite extends AbstractRedisFunSuite {

  val zsetKey = "sort-set"

  @Autowired val zset: DefaultSyncRedisZSet = null

  test("incrBy") {
    val x1 = zset.incrBy(zsetKey, 1, "m")
    val x2 = zset.incrBy(zsetKey, 1, "m")

    x2 shouldEqual x1 + 1
  }

}


text:
[![Build Status](https://travis-ci.org/walterdolce/php-randomizer.svg?branch=develop)](https://travis-ci.org/walterdolce/php-randomizer)

PHP Randomizer
==============

Randomizer PHP module interface used to randomize things through user defined strategy classes.

Issues
------
Please report issues [here on GitHub](https://github.com/walterdolce/php-randomizer/issues "Click here to report an issue").


text:
pushd `dirname $0` > /dev/null
SCRIPTPATH=`pwd`
popd > /dev/null

# === Edit default options to match your need ===

FROM_TYPE="SER" # SER, TCP
TO_TYPE="SSL"   # TCP, SSL

COMM_BAUD=9600
SERV_ADDR=blynk-cloud.com
SERV_PORT_SSL=8441
SERV_PORT_TCP=8442
SERV_PORT_2WAY=8443
LSTN_PORT=8442

SRVR_CERT="$SCRIPTPATH/certs/server.crt"
CLNT_CERT="$SCRIPTPATH/certs/client.pem"

# === Edit the lines below only if absolutely sure what you're doing ===

usage="
    This script redirects serial communication to the server.

    You can specify port, baud rate, and server endpoint like this:
      blynk-ser.sh -c <serial port> -b <baud rate> -s <server address> -p <server port>

    The defaults are:
      -c,--comm      single available port (on Linux, OSX)
                     COM1                  (on Windows)
      -b,--baud      9600
      -s,--server    blynk-cloud.com
      -p,--port      8442

    If the specified serial port is not found, it will ask to enter another one.
    The script also tries to reestablish connection if it was lost.
"

avrdude_warn="Warning: avrdude is running
 Avoid uploading sketches and running this script at the same time.
 If you didn't run avrdude, maybe it just stuck. You can kill it using:
   killall avrdude
"

function detect_conflicts {
    # Detect if avrdude is running
    if pgrep avrdude; then echo -n "$avrdude_warn"; fi
}

detect_conflicts

# Detect socat
if ! hash socat 2>/dev/null; then
    echo "This script uses socat utility, but could not find it."
    echo
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        echo "  Try installing it using: sudo apt-get install socat"
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        echo "  Try installing it using: brew install socat"
    fi
    exit 1
fi

# Execute getopt
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    ARGS=$(getopt -o hf:c:b:l:t:s:p: -l "help,from:,comm:,baud:,listen:,to:,server:,port:,cert:" -n "blynk-gateway.sh" -- "$@");
elif [[ "$OSTYPE" == "darwin"* ]]; then
    ARGS=$(getopt hf:c:b:l:t:s:p: $*);
fi

# Bad arguments
if [ $? -ne 0 ];
then
  echo -n "$usage"
  exit 1
fi

eval set -- "$ARGS";

while true; do
  case "$1" in
    -h|--help)
      shift
      echo -n "$usage"
      exit 0
      ;;
    ####
    -f|--from)
      shift
      if [ -n "$1" ]; then
        FROM_TYPE=$1
        shift
      fi
      ;;
    -c|--comm)
      shift
      if [ -n "$1" ]; then
        COMM_PORT_USER=$1
        shift
      fi
      ;;
    -b|--baud)
      shift
      if [ -n "$1" ]; then
        COMM_BAUD=$1
        shift
      fi
      ;;
    -l|--listen)
      shift
      if [ -n "$1" ]; then
        LSTN_PORT=$1
        shift
      fi
      ;;
    ####
    -t|--to)
      shift
      if [ -n "$1" ]; then
        TO_TYPE=$1
        shift
      fi
      ;;
    -s|--server)
      shift
      if [ -n "$1" ]; then
        SERV_ADDR=$1
        shift
      fi
      ;;
    -p|--port)
      shift
      if [ -n "$1" ]; then
        SERV_PORT_SSL=$1
        SERV_PORT_TCP=$1
        SERV_PORT_2WAY=$1
        shift
      fi
      ;;
    --cert)
      shift
      if [ -n "$1" ]; then
        SRVR_CERT=$1
        shift
      fi
      ;;
    ####
    --)
      shift;
      break;
      ;;
  esac
done

# Construct command
GEN_ATTR="-d -d"

TCP_ATTR="nodelay" #,nonblock=1,rcvtimeo=1,sndtimeo=1
SER_ATTR="raw,echo=0,clocal=1,cs8,nonblock=1"

if [[ "$FROM_TYPE" == "SER" ]]; then
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        COMM_WCARD="/dev/ttyUSB* /dev/ttyACM*"
        COMM_STTY="-F"
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        COMM_WCARD="/dev/tty.usbserial* /dev/tty.usbmodem*"
        COMM_STTY="-f"
    else
        echo "Can't detect OS type!"
        exit 1
    fi

    COMM_FOUND=`ls $COMM_WCARD 2> /dev/null`
    COMM_QTY=`printf "%s\n" $COMM_FOUND | wc -l`

    if [[ ! "$COMM_PORT_USER" == "" ]]; then
        COMM_PORT=$COMM_PORT_USER
    elif [[ "$COMM_QTY" == "1" ]]; then
        # Select single available port
        COMM_PORT=$COMM_FOUND
    else
        # Ask for serial port interactively
        echo "$COMM_QTY ports found. You can specify port manually using -c option"
        echo -n "Select serial port [" $COMM_FOUND "]: "
        read COMM_PORT
    fi

    if [ ! -e "$COMM_PORT" ]; then
        echo "Can't find port: $COMM_PORT"
        echo "Please specify port manually using -c option"
        exit 1
    fi

    echo "Resetting device $COMM_PORT..."
    stty $COMM_STTY $COMM_PORT hupcl
    # Disable restarting
    #stty $COMM_STTY $COMM_PORT -hupcl

    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        FROM_ATTR="FILE:$COMM_PORT,$SER_ATTR,b$COMM_BAUD"
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        FROM_ATTR="GOPEN:$COMM_PORT,$SER_ATTR,ixoff=0,ixon=0,ispeed=$COMM_BAUD,ospeed=$COMM_BAUD,crtscts=0"
    fi
elif [[ "$FROM_TYPE" == "TCP" ]]; then
    FROM_ATTR="TCP-LISTEN:$LSTN_PORT,reuseaddr,fork,$TCP_ATTR"
else
    echo "$FROM_TYPE is not supported."
    exit 1
fi

if [[ "$TO_TYPE" == "TCP" ]]; then
    echo "Warning: Server connection may be insecure!"
    TO_ATTR="TCP:$SERV_ADDR:$SERV_PORT_TCP,$TCP_ATTR"
elif [[ "$TO_TYPE" == "SSL" ]]; then
    if [ -e "$SRVR_CERT" ]; then
        TCP_ATTR="cafile=$SRVR_CERT,$TCP_ATTR"
    else
        echo "Warning: $SRVR_CERT not found. Skipping server verification (connection may be insecure)!"
        TCP_ATTR="verify=0,$TCP_ATTR"
    fi

    if [ -e "$CLNT_CERT" ]; then
        TCP_ATTR="cert=$CLNT_CERT,$TCP_ATTR"
    fi

    TO_ATTR="openssl-connect:$SERV_ADDR:$SERV_PORT_SSL,$TCP_ATTR"
elif [[ "$TO_TYPE" == "2WAY" ]]; then
    echo "2WAY is not supported yet."
    exit 1
else
    echo "$TO_TYPE is not supported."
    exit 1
fi

# Setup exit handler
trap "echo Exited!; exit;" SIGINT SIGTERM
echo [ Press Ctrl+C to exit ]

while [ 1 ]; do
    echo Connecting: "$FROM_ATTR <-> $TO_ATTR"

    socat $GEN_ATTR "$FROM_ATTR" "$TO_ATTR"

    detect_conflicts

    echo Reconnecting in 3s...
    sleep 3
done


text:
#ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_RUNTIME_SHAPE_H_
#define TENSORFLOW_LITE_KERNELS_INTERNAL_RUNTIME_SHAPE_H_

#include <cstdint>
#include <cstring>
#include <initializer_list>
#include <iterator>

#include "tensorflow/lite/kernels/internal/compatibility.h"

namespace tflite {

template <int N>
struct Dims {
  int sizes[N];
  int strides[N];
};

class RuntimeShape {
 public:
  // Shapes with dimensions up to 5 are stored directly in the structure, while
  // larger shapes are separately allocated.
  static constexpr int kMaxSmallSize = 5;

  RuntimeShape& operator=(RuntimeShape const&) = delete;

  RuntimeShape() : size_(0) {}

  explicit RuntimeShape(int dimensions_count) : size_(dimensions_count) {
    if (dimensions_count > kMaxSmallSize) {
      dims_pointer_ = new int32_t[dimensions_count];
    }
  }

  RuntimeShape(int shape_size, int32_t value) : size_(0) {
    Resize(shape_size);
    for (int i = 0; i < shape_size; ++i) {
      SetDim(i, value);
    }
  }

  RuntimeShape(int dimensions_count, const int32_t* dims_data) : size_(0) {
    ReplaceWith(dimensions_count, dims_data);
  }

  RuntimeShape(const std::initializer_list<int> init_list) : size_(0) {
    BuildFrom(init_list);
  }

  // Avoid using this constructor.  We should be able to delete it when C++17
  // rolls out.
  RuntimeShape(RuntimeShape const& other) : size_(other.DimensionsCount()) {
    if (size_ > kMaxSmallSize) {
      dims_pointer_ = new int32_t[size_];
    }
    std::memcpy(DimsData(), other.DimsData(), sizeof(int32_t) * size_);
  }

  bool operator==(const RuntimeShape& comp) const {
    return this->size_ == comp.size_ &&
           std::memcmp(DimsData(), comp.DimsData(), size_ * sizeof(int32_t)) ==
               0;
  }

  ~RuntimeShape() {
    if (size_ > kMaxSmallSize) {
      delete[] dims_pointer_;
    }
  }

  inline int32_t DimensionsCount() const { return size_; }
  inline int32_t Dims(int i) const {
    TFLITE_DCHECK_GE(i, 0);
    TFLITE_DCHECK_LT(i, size_);
    return size_ > kMaxSmallSize ? dims_pointer_[i] : dims_[i];
  }
  inline void SetDim(int i, int32_t val) {
    TFLITE_DCHECK_GE(i, 0);
    TFLITE_DCHECK_LT(i, size_);
    if (size_ > kMaxSmallSize) {
      dims_pointer_[i] = val;
    } else {
      dims_[i] = val;
    }
  }

  inline int32_t* DimsData() {
    return size_ > kMaxSmallSize ? dims_pointer_ : dims_;
  }
  inline const int32_t* DimsData() const {
    return size_ > kMaxSmallSize ? dims_pointer_ : dims_;
  }
  // The caller must ensure that the shape is no bigger than 5-D.
  inline const int32_t* DimsDataUpTo5D() const { return dims_; }

  inline void Resize(int dimensions_count) {
    if (size_ > kMaxSmallSize) {
      delete[] dims_pointer_;
    }
    size_ = dimensions_count;
    if (dimensions_count > kMaxSmallSize) {
      dims_pointer_ = new int32_t[dimensions_count];
    }
  }

  inline void ReplaceWith(int dimensions_count, const int32_t* dims_data) {
    Resize(dimensions_count);
    int32_t* dst_dims = DimsData();
    std::memcpy(dst_dims, dims_data, dimensions_count * sizeof(int32_t));
  }

  template <typename T>
  inline void BuildFrom(const T& src_iterable) {
    const int dimensions_count =
        std::distance(src_iterable.begin(), src_iterable.end());
    Resize(dimensions_count);
    int32_t* data = DimsData();
    for (auto it : src_iterable) {
      *data = it;
      ++data;
    }
  }

  // This will probably be factored out. Old code made substantial use of 4-D
  // shapes, and so this function is used to extend smaller shapes. Note that
  // (a) as Dims<4>-dependent code is eliminated, the reliance on this should be
  // reduced, and (b) some kernels are stricly 4-D, but then the shapes of their
  // inputs should already be 4-D, so this function should not be needed.
  inline static RuntimeShape ExtendedShape(int new_shape_size,
                                           const RuntimeShape& shape) {
    return RuntimeShape(new_shape_size, shape, 1);
  }

  inline void BuildFrom(const std::initializer_list<int> init_list) {
    BuildFrom<const std::initializer_list<int>>(init_list);
  }

  // Returns the total count of elements, that is the size when flattened into a
  // vector.
  inline int FlatSize() const {
    int buffer_size = 1;
    const int* dims_data = reinterpret_cast<const int*>(DimsData());
    for (int i = 0; i < size_; i++) {
      buffer_size *= dims_data[i];
    }
    return buffer_size;
  }

  bool operator!=(const RuntimeShape& comp) const { return !((*this) == comp); }

 private:
  // For use only by ExtendedShape(), written to guarantee (return-value) copy
  // elision in C++17.
  // This creates a shape padded to the desired size with the specified value.
  RuntimeShape(int new_shape_size, const RuntimeShape& shape, int pad_value)
      : size_(0) {
    // If the following check fails, it is likely because a 4D-only kernel is
    // being used with an array of larger dimension count.
    TFLITE_CHECK_GE(new_shape_size, shape.DimensionsCount());
    Resize(new_shape_size);
    const int size_increase = new_shape_size - shape.DimensionsCount();
    for (int i = 0; i < size_increase; ++i) {
      SetDim(i, pad_value);
    }
    std::memcpy(DimsData() + size_increase, shape.DimsData(),
                sizeof(int32_t) * shape.DimensionsCount());
  }

  int32_t size_;
  union {
    int32_t dims_[kMaxSmallSize];
    int32_t* dims_pointer_;
  };
};

// Converts inference-style shape to legacy tflite::Dims<4>.
inline tflite::Dims<4> ToRuntimeDims(const tflite::RuntimeShape& array_shape) {
  tflite::Dims<4> result;
  const int dimensions_count = array_shape.DimensionsCount();
  TFLITE_CHECK_LE(dimensions_count, 4);
  int cum_prod = 1;
  for (int i = 0; i < 4; i++) {
    const int new_dim =
        (i < dimensions_count) ? array_shape.Dims(dimensions_count - 1 - i) : 1;
    result.sizes[i] = new_dim;
    result.strides[i] = cum_prod;
    cum_prod *= new_dim;
  }
  return result;
}

// TODO(b/80418076): Move to legacy ops file, update invocations.
inline RuntimeShape DimsToShape(const tflite::Dims<4>& dims) {
  return RuntimeShape(
      {dims.sizes[3], dims.sizes[2], dims.sizes[1], dims.sizes[0]});
}

// Since tensors with '0' in their shape are valid in TF, these offset functions
// allow that as long as the corresponding index is also 0. It is upto the
// calling ops to ensure that they perform verification checks on tensor shapes
// if they don't support a particular behavior.

inline int Offset(const RuntimeShape& shape, int i0, int i1, int i2, int i3) {
  TFLITE_DCHECK_EQ(shape.DimensionsCount(), 4);
  const int* dims_data = reinterpret_cast<const int*>(shape.DimsDataUpTo5D());
  TFLITE_DCHECK((dims_data[0] == 0 && i0 == 0) ||
                (i0 >= 0 && i0 < dims_data[0]));
  TFLITE_DCHECK((dims_data[1] == 0 && i1 == 0) ||
                (i1 >= 0 && i1 < dims_data[1]));
  TFLITE_DCHECK((dims_data[2] == 0 && i2 == 0) ||
                (i2 >= 0 && i2 < dims_data[2]));
  TFLITE_DCHECK((dims_data[3] == 0 && i3 == 0) ||
                (i3 >= 0 && i3 < dims_data[3]));
  return ((i0 * dims_data[1] + i1) * dims_data[2] + i2) * dims_data[3] + i3;
}

inline int Offset(const RuntimeShape& shape, int i0, int i1, int i2, int i3,
                  int i4) {
  TFLITE_DCHECK_EQ(shape.DimensionsCount(), 5);
  const int* dims_data = reinterpret_cast<const int*>(shape.DimsDataUpTo5D());
  TFLITE_DCHECK((dims_data[0] == 0 && i0 == 0) ||
                (i0 >= 0 && i0 < dims_data[0]));
  TFLITE_DCHECK((dims_data[1] == 0 && i1 == 0) ||
                (i1 >= 0 && i1 < dims_data[1]));
  TFLITE_DCHECK((dims_data[2] == 0 && i2 == 0) ||
                (i2 >= 0 && i2 < dims_data[2]));
  TFLITE_DCHECK((dims_data[3] == 0 && i3 == 0) ||
                (i3 >= 0 && i3 < dims_data[3]));
  TFLITE_DCHECK((dims_data[4] == 0 && i4 == 0) ||
                (i4 >= 0 && i4 < dims_data[4]));
  return (((i0 * dims_data[1] + i1) * dims_data[2] + i2) * dims_data[3] + i3) *
             dims_data[4] +
         i4;
}

inline int Offset(const RuntimeShape& shape, int* index) {
  return Offset(shape, index[0], index[1], index[2], index[3]);
}

}  // namespace tflite

#endif  // ENSORFLOW_LITE_KERNELS_INTERNAL_RUNTIME_SHAPE_H_


text:
Function Get-WmiObjects {
	<#
		.SYNOPSIS
			Gets instances of Windows Management Instrumentation (WMI) classes in a multithreaded way.

		.DESCRIPTION
			Gets instances of Windows Management Instrumentation (WMI) classes in a multithreaded way.

		.EXAMPLE
			PS C:\> Get-WmiObjects -ComputerName "Server1", "server2", "server3" -Class Win32_ComputerSystem | ft -Autosize

			Domain			Manufacturer Model								Name	PrimaryOwnerName TotalPhysicalMemory
			------			------------ -----								----	---------------- -------------------
			Domain.local	HP			 ProLiant DL360e Gen8				Server1	Windows User	 8419397632
			Domain.local	NEC			 Express5800/120Rh-1 [N8100-xxxxF]	Server2	Windows User	 17177952256
			Domain.local	HP			 ProLiant DL360e Gen8				Server3	Windows User	 8419397632

		.EXAMPLE
			PS C:\> "computer1", "server2" | Get-WmiObjects -Class Win32_ComputerSystem

		.INPUTS
			System.Sting

		.NOTES

		.LINK
			http://www.proxx.nl/
	#>
	Param(
		[Switch] $Amended,
		[System.Management.AuthenticationLevel]$Authentication,
		[String] $Authority,
		[Parameter(Mandatory=$true, Position=1)][String]$Class,
		[Parameter(Mandatory=$true, ValueFromPipeline=$true)] [String[]] $ComputerName,
		[PSCredential]$Credential,
		[Switch] $DirectRead,
		[Switch] $EnableAllPrivileges,
		[String] $Filter,
		[System.Management.ImpersonationLevel] $Impersonation,
		[Switch] $List,
		[String] $Locale,
		[String] $Namespace,
		[Switch] $Progress,
		[Parameter(Position=2)][String[]] $Property,
		[String] $Query,
		[Switch] $Recurse,
		[int32]$ThrottleLimit=10
	)

	Begin {
		$RunspacePool = [RunspaceFactory ]::CreateRunspacePool(1, $ThrottleLimit)
		$RunspacePool.Open()

		[Collections.Arraylist] $Queue = @()

		$Params = @{}
		if ($Amended) { 			$Params.Amended = $Amended }
		if ($Authentication) { 		$Params.Authentication = $Authentication }
		if ($Authority) { 			$Params.Authority = $Authority }
									$Params.Class = $Class
		if ($Credential) { 			$Params.Credential = $Credential }
		if ($DirectRead) {			$Params.DirectRead = $DirectRead }
		if ($EnableAllPrivileges) { $Params.EnableAllPrivileges = $EnableAllPrivileges }
		if ($Filter) { 				$Params.Filter = $Filter }
		if ($Impersonation) { 		$Params.Impersonation = $Impersonation }
		if ($List) { 				$Params.List = $List }
		if ($Locale) { 				$Params.Locale = $Locale }
		if ($Namespace) { 			$Params.Namespace = $Namespace }
		if ($Progress) {
			[int] $Count = 0
			Write-Progress -Activity "Getting WMI Objects for class: $Class"
		}
		if ($Property) { 			$Params.Property = $Property }
		if ($Query) { 				$Params.Query = $Query }
		if ($Recurse) { 			$Params.Recurse = $Recurse }

		[ScriptBlock] $ScriptBlock = {Param($Computer,$Params)
			if (Test-Connection -Count 1 -ComputerName $Computer -Quiet) { return (Get-WmiObject -ComputerName $Computer @Params) }
		}

	}
	Process {
		ForEach($Computer in $ComputerName) {
			$Job = [powershell]::Create().AddScript($ScriptBlock).AddArgument($Computer).AddArgument($Params)
			$Job.RunspacePool = $RunspacePool
			$Queue += New-Object -TypeName PSObject -Property @{
				Items = $Job
				Status = $Job.BeginInvoke()
			}
		}
	}
	End {
		$Total = $ComputerName.Count
		While($Queue){
			Foreach($Job in $Queue.ToArray()){
				If($Job.Status.IsCompleted){
					$Count++
					if ($Progress) { Write-Progress -Activity "Getting WMI Objects for class: $Class" -Status "Progress: ($Count/$Total)" -PercentComplete (($Count/$Total)  * 100) }
					Write-Output -InputObject $Job.Items.EndInvoke($Job.Status)
					$Job.Items.Dispose()
					$Queue.Remove($Job)
				}
			}
		}
		if ($Progress) { Write-Progress -Activity "Getting WMI Objects for class: $Class" -Completed }
		$RunspacePool.Close()
		$RunspacePool.Dispose()
	}
}


text:
require 'logginator'
require 'minitest/autorun'
require 'mocha/mini_test'

class MockIO

  def initialize(lines = [])
    @lines = lines
  end

  def each
    while(!@lines.empty?) do
      yield(@lines.shift)
    end
    loop {}
  end

end


text:
//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2019 Jiang Yin. All rights reserved.
// Homepage: http://gameframework.cn/
// Feedback: mailto:jiangyin@gameframework.cn
//------------------------------------------------------------

namespace PokemonUnity
{
    public sealed class SCPacketHeader : PacketHeaderBase
    {
        public override PacketType PacketType
        {
            get
            {
                return PacketType.ServerToClient;
            }
        }
    }
}


text:
package li.allan.easycache;

import java.util.concurrent.TimeUnit;

/**
 * @author lialun
 */
public interface Cache<K, V> {
    void put(K key, V value, long expireAfterCreate, TimeUnit timeUnit);

    V get(K key);

    ValueWrapper<V> getValueWrapper(K key);

    boolean contains(K key);

    void invalidate(K key);

    long expireTimestampInMills(K key);

    long size();
}


text:
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;

namespace BlueConcord.IdentityServer.Host.Migrations.ClientConfig
{
    public partial class ClientConfig01 : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Clients",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    AbsoluteRefreshTokenLifetime = table.Column<int>(nullable: false),
                    AccessTokenLifetime = table.Column<int>(nullable: false),
                    AccessTokenType = table.Column<int>(nullable: false),
                    AllowAccessToAllScopes = table.Column<bool>(nullable: false),
                    AllowAccessTokensViaBrowser = table.Column<bool>(nullable: false),
                    AllowPromptNone = table.Column<bool>(nullable: false),
                    AllowRememberConsent = table.Column<bool>(nullable: false),
                    AlwaysSendClientClaims = table.Column<bool>(nullable: false),
                    AuthorizationCodeLifetime = table.Column<int>(nullable: false),
                    ClientId = table.Column<string>(maxLength: 100, nullable: false),
                    ClientName = table.Column<string>(maxLength: 255, nullable: false),
                    ClientUri = table.Column<string>(maxLength: 400, nullable: true),
                    EnableLocalLogin = table.Column<bool>(nullable: false),
                    Enabled = table.Column<bool>(nullable: false),
                    IdentityTokenLifetime = table.Column<int>(nullable: false),
                    IncludeJwtId = table.Column<bool>(nullable: false),
                    LogoUri = table.Column<string>(nullable: true),
                    LogoutSessionRequired = table.Column<bool>(nullable: false),
                    LogoutUri = table.Column<string>(nullable: true),
                    PrefixClientClaims = table.Column<bool>(nullable: false),
                    RefreshTokenExpiration = table.Column<int>(nullable: false),
                    RefreshTokenUsage = table.Column<int>(nullable: false),
                    RequireConsent = table.Column<bool>(nullable: false),
                    SlidingRefreshTokenLifetime = table.Column<int>(nullable: false),
                    UpdateAccessTokenOnRefresh = table.Column<bool>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Clients", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "ClientClaims",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    ClientId = table.Column<Guid>(nullable: false),
                    Type = table.Column<string>(maxLength: 255, nullable: false),
                    Value = table.Column<string>(maxLength: 255, nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_ClientClaims", x => x.Id);
                    table.ForeignKey(
                        name: "FK_ClientClaims_Clients_ClientId",
                        column: x => x.ClientId,
                        principalTable: "Clients",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "ClientCorsOrigins",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    ClientId = table.Column<Guid>(nullable: false),
                    Origin = table.Column<string>(maxLength: 255, nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_ClientCorsOrigins", x => x.Id);
                    table.ForeignKey(
                        name: "FK_ClientCorsOrigins_Clients_ClientId",
                        column: x => x.ClientId,
                        principalTable: "Clients",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "ClientGrantTypes",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    ClientId = table.Column<Guid>(nullable: false),
                    GrantType = table.Column<string>(maxLength: 100, nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_ClientGrantTypes", x => x.Id);
                    table.ForeignKey(
                        name: "FK_ClientGrantTypes_Clients_ClientId",
                        column: x => x.ClientId,
                        principalTable: "Clients",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "ClientPostLogoutRedirectUris",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    ClientId = table.Column<Guid>(nullable: false),
                    Uri = table.Column<string>(maxLength: 400, nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_ClientPostLogoutRedirectUris", x => x.Id);
                    table.ForeignKey(
                        name: "FK_ClientPostLogoutRedirectUris_Clients_ClientId",
                        column: x => x.ClientId,
                        principalTable: "Clients",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "ClientProviderRestrictions",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    ClientId = table.Column<Guid>(nullable: false),
                    Provider = table.Column<string>(maxLength: 100, nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_ClientProviderRestrictions", x => x.Id);
                    table.ForeignKey(
                        name: "FK_ClientProviderRestrictions_Clients_ClientId",
                        column: x => x.ClientId,
                        principalTable: "Clients",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "ClientRedirectUris",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    ClientId = table.Column<Guid>(nullable: false),
                    Uri = table.Column<string>(maxLength: 400, nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_ClientRedirectUris", x => x.Id);
                    table.ForeignKey(
                        name: "FK_ClientRedirectUris_Clients_ClientId",
                        column: x => x.ClientId,
                        principalTable: "Clients",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "ClientScopes",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    ClientId = table.Column<Guid>(nullable: false),
                    Scope = table.Column<string>(maxLength: 300, nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_ClientScopes", x => x.Id);
                    table.ForeignKey(
                        name: "FK_ClientScopes_Clients_ClientId",
                        column: x => x.ClientId,
                        principalTable: "Clients",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "ClientSecrets",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    ClientId = table.Column<Guid>(nullable: false),
                    Description = table.Column<string>(maxLength: 1020, nullable: true),
                    Expiration = table.Column<DateTime>(nullable: true),
                    Type = table.Column<string>(maxLength: 255, nullable: true),
                    Value = table.Column<string>(maxLength: 100, nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_ClientSecrets", x => x.Id);
                    table.ForeignKey(
                        name: "FK_ClientSecrets_Clients_ClientId",
                        column: x => x.ClientId,
                        principalTable: "Clients",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateIndex(
                name: "IX_Clients_ClientId",
                table: "Clients",
                column: "ClientId",
                unique: true);

            migrationBuilder.CreateIndex(
                name: "IX_ClientClaims_ClientId",
                table: "ClientClaims",
                column: "ClientId");

            migrationBuilder.CreateIndex(
                name: "IX_ClientCorsOrigins_ClientId",
                table: "ClientCorsOrigins",
                column: "ClientId");

            migrationBuilder.CreateIndex(
                name: "IX_ClientGrantTypes_ClientId",
                table: "ClientGrantTypes",
                column: "ClientId");

            migrationBuilder.CreateIndex(
                name: "IX_ClientPostLogoutRedirectUris_ClientId",
                table: "ClientPostLogoutRedirectUris",
                column: "ClientId");

            migrationBuilder.CreateIndex(
                name: "IX_ClientProviderRestrictions_ClientId",
                table: "ClientProviderRestrictions",
                column: "ClientId");

            migrationBuilder.CreateIndex(
                name: "IX_ClientRedirectUris_ClientId",
                table: "ClientRedirectUris",
                column: "ClientId");

            migrationBuilder.CreateIndex(
                name: "IX_ClientScopes_ClientId",
                table: "ClientScopes",
                column: "ClientId");

            migrationBuilder.CreateIndex(
                name: "IX_ClientSecrets_ClientId",
                table: "ClientSecrets",
                column: "ClientId");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "ClientClaims");

            migrationBuilder.DropTable(
                name: "ClientCorsOrigins");

            migrationBuilder.DropTable(
                name: "ClientGrantTypes");

            migrationBuilder.DropTable(
                name: "ClientPostLogoutRedirectUris");

            migrationBuilder.DropTable(
                name: "ClientProviderRestrictions");

            migrationBuilder.DropTable(
                name: "ClientRedirectUris");

            migrationBuilder.DropTable(
                name: "ClientScopes");

            migrationBuilder.DropTable(
                name: "ClientSecrets");

            migrationBuilder.DropTable(
                name: "Clients");
        }
    }
}


text:
package com.skysport.interfaces.action.develop;

import com.skysport.core.action.BaseAction;
import com.skysport.core.annotation.SystemControllerLog;
import com.skysport.core.bean.system.SelectItem2;
import com.skysport.interfaces.bean.develop.ProjectBomInfo;
import com.skysport.interfaces.bean.form.develop.ProjectQueryForm;
import com.skysport.interfaces.constant.WebConstants;
import com.skysport.interfaces.model.common.uploadfile.IUploadFileInfoService;
import com.skysport.interfaces.model.common.uploadfile.helper.UploadFileHelper;
import com.skysport.interfaces.model.develop.project.helper.ProjectHelper;
import com.skysport.interfaces.model.develop.project.service.IProjectItemService;
import com.skysport.interfaces.model.develop.quoted.service.IQuotedService;
import com.skysport.interfaces.utils.BuildSeqNoHelper;
import com.skysport.interfaces.utils.SeqCreateUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

/**
 * 类说明:子项目
 * Created by zhangjh on 2015/8/26.
 */
@Scope("prototype")
@Controller
@RequestMapping("/development/project_item")
public class ProjectItemAction extends BaseAction<ProjectBomInfo> {

    @Resource(name = "projectItemManageService")
    private IProjectItemService projectItemManageService;

    @Resource(name = "quotedService")
    private IQuotedService quotedService;

    @Resource(name = "uploadFileInfoService")
    private IUploadFileInfoService uploadFileInfoService;

    /**
     * 此方法描述的是:展示list页面	 *
     *
     * @author: zhangjh
     * @version: 2015年4月29日 下午5:34:53
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    @SystemControllerLog(description = "打开子项目列表页面")
    public ModelAndView search() {
        ModelAndView mav = new ModelAndView("/development/project/project-item-list");
        return mav;
    }

    /**
     * 此方法描述的是:展示add页面
     *
     * @author: zhangjh
     * @version: 2015年4月29日 下午5:34:53
     */
    @RequestMapping(value = "/add/{natrualKey}", method = RequestMethod.GET)
    @ResponseBody
    @SystemControllerLog(description = "新增子项目")
    public ModelAndView add(@PathVariable String natrualKey, HttpServletRequest request) {
        String taskId = (String) request.getAttribute("taskId");
        String processInstanceId = (String) request.getAttribute("processInstanceId");
        ModelAndView mav = new ModelAndView("/development/project/project-item-add");
        mav.addObject("natrualkey", natrualKey);
        mav.addObject("taskId", taskId);
        mav.addObject("processInstanceId", processInstanceId);
        return mav;
    }

    /**
     * @return 导出报价表
     * @throws IOException
     */
    @RequestMapping("/download_offer/{natrualkeys}")
    @SystemControllerLog(description = "导出报价表")
    public ModelAndView downloadOffer(@PathVariable String natrualkeys, HttpServletRequest request, HttpServletResponse response) throws IOException, InvalidFormatException {
        quotedService.downloadOffer(request, response, natrualkeys);
        return null;
    }

    /**
     * @return 导出面辅料详细
     * @throws IOException
     */
    @RequestMapping("/export_materialdetail/{natrualkeys}")
    @SystemControllerLog(description = "导出面辅料详细")
    public ModelAndView exportMaterialDetail(@PathVariable String natrualkeys, HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, NoSuchMethodException, IOException, IllegalAccessException, InvalidFormatException {
        String resourcePath = WebConstants.RESOURCE_PATH_BOM;
        String fileTypeName = WebConstants.BOM_DETAIL_CN_NAME;
        projectItemManageService.exportMaterialDetail(request, response, natrualkeys,resourcePath,fileTypeName);
        return null;
    }

    /**
     * @return 导出采购表
     * @throws IOException
     */
    @RequestMapping("/export_materialpurchasedetail/{natrualkeys}")
    @SystemControllerLog(description = "导出采购详细")
    public ModelAndView exportMaterialPurchaseDetail(@PathVariable String natrualkeys, HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, NoSuchMethodException, IOException, IllegalAccessException, InvalidFormatException {
        String resourcePath = WebConstants.RESOURCE_PATH_PURCHASE;
        String fileTypeName = WebConstants.BOM_PURCHASE_CN_NAME;
        projectItemManageService.exportMaterialDetail(request, response, natrualkeys,resourcePath,fileTypeName);

        return null;
    }

    /**
     * 此方法描述的是:
     *
     * @author: zhangjh
     * @version: 2015年4月29日 下午5:34:53
     */
    @RequestMapping(value = "/search")
    @ResponseBody
    @SystemControllerLog(description = "查询子项目信息列表")
    public Map<String, Object> search(HttpServletRequest request) {
        //组件queryFory的参数
        ProjectQueryForm queryForm = new ProjectQueryForm();
        queryForm.setDataTablesInfo(convertToDataTableQrInfo(WebConstants.PROJECT_ITEM_TABLE_COLUMN, request));
        ProjectBomInfo bomInfo = ProjectHelper.SINGLETONE.getProjectBomInfo(request);
        queryForm.setProjectBomInfo(bomInfo);
        Map<String, Object> resultMap = buildSearchJsonMap(queryForm, request, projectItemManageService);
        return resultMap;
    }

    @Override
    public void turnIdToName(List<ProjectBomInfo> infos) {
        ProjectHelper.SINGLETONE.turnIdToName(infos);
    }

    /**
     * 此方法描述的是:
     *
     * @author: zhangjh
     * @version: 2015年4月29日 下午5:35:09
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    @SystemControllerLog(description = "子项目")
    public Map<String, Object> edit(@RequestBody ProjectBomInfo info) {

        projectItemManageService.edit(info);
        return rtnSuccessResultMap("更新成功");

    }

    /**
     * 此方法描述的是:项目新增
     *
     * @author: zhangjh
     * @version: 2015年4月29日 下午5:35:09
     */
    @RequestMapping(value = "/new", method = RequestMethod.POST)
    @ResponseBody
    @SystemControllerLog(description = "增加子项目")
    public Map<String, Object> add(ProjectBomInfo info) {

        String kind_name = ProjectHelper.SINGLETONE.buildKindName(info);
        String seqNo = BuildSeqNoHelper.SINGLETONE.getFullSeqNo(kind_name, WebConstants.PROJECT_SEQ_NO_LENGTH);

//        //年份+客户+地域+系列+NNN
//        String projectId = kind_name + seqNo;
        String projectId = SeqCreateUtils.SINGLETONE.newRrojectSeq(info.getSeriesId());
        //设置ID
        info.setNatrualkey(projectId);
        info.setSeqNo(seqNo);

        //保存项目信息
        projectItemManageService.add(info);
        return rtnSuccessResultMap("新增成功");

    }

    /**
     * @param natrualKey 主键id
     * @return 根据主键id找出详细信息
     */
    @RequestMapping(value = "/info/{natrualKey}", method = RequestMethod.GET)
    @ResponseBody
    @SystemControllerLog(description = "查询子项目")
    public ProjectBomInfo info(@PathVariable String natrualKey) {

        ProjectBomInfo info = projectItemManageService.queryInfoByNatrualKey(natrualKey);
        projectItemManageService.setStatuCodeAlive(info, natrualKey);
        if (null != info) {
            Map<String, Object> fileinfosMap = UploadFileHelper.SINGLETONE.getFileInfoMap(uploadFileInfoService, natrualKey);
            info.setFileinfosMap(fileinfosMap);
        }
        return info;
    }

    /**
     * @param natrualKey
     * @return
     */
    @RequestMapping(value = "/del/{natrualKey}", method = RequestMethod.DELETE)
    @ResponseBody
    @SystemControllerLog(description = "删除子项目")
    public Map<String, Object> del(@PathVariable String natrualKey) {
        projectItemManageService.del(natrualKey);
        return rtnSuccessResultMap("删除成功");
    }

    @RequestMapping(value = "/select", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> querySelectList(HttpServletRequest request) {
        String name = request.getParameter("name");
        List<SelectItem2> commonBeans = projectItemManageService.querySelectList(name);
        return rtSelectResultMap(commonBeans);
    }
}


text:
package com.zmarkan.feedzillamodels;

/**
 * Created by zan on 10/01/15.
 */
public class Article {
    private String author;
    private String publish_date;
    private String source;
    private String source_url;
    private String summary;
    private String title;
    private String url;

    public String getAuthor() {
        return author;
    }

    public String getPublish_date() {
        return publish_date;
    }

    public String getSource() {
        return source;
    }

    public String getSource_url() {
        return source_url;
    }

    public String getSummary() {
        return summary;
    }

    public String getTitle() {
        return title;
    }

    public String getUrl() {
        return url;
    }
}


text:
var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var swig = require('swig');
var Firebase = require('firebase');
var io = require("socket.io");

var routes = require('./routes/index');

var app = express();
var server = http.Server(app);
var io = io(server);

// view engine setup
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// app.use(function(req, res, next) {
//   req.io = io;
//   next();
// });
// TODO: set cache to true in production
app.set('view cache', false);
swig.setDefaults({ cache: false });

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
// app.http().io();
app.use('/', routes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;


text:
package org.apache.sis.measure;

import javax.measure.Unit;
import javax.measure.Quantity;
import javax.measure.quantity.Time;
import javax.measure.quantity.Angle;
import javax.measure.quantity.Length;
import javax.measure.format.ParserException;
import org.apache.sis.util.Static;
import org.apache.sis.util.ArgumentChecks;
import org.apache.sis.util.resources.Errors;

/**
 * Provides static methods working on {@link Quantity} instances.
 * Apache SIS implementation of quantities has the following characteristics:
 *
 *

 *
Values are stored with {@code double} precision.

 *
All quantities implement the specific subtype (e.g. {@link Length} instead of {@code Quantity<Length>}).

 *
Quantities are immutable, {@link Comparable} and {@link java.io.Serializable}.

 *

 *
 * @author  Martin Desruisseaux (Geomatys)
 * @version 0.8
 * @since   0.8
 * @module
 */
public final class Quantities extends Static {
    /**
     * Do not allow instantiation of this class.
     */
    private Quantities() {
    }

    /**
     * Creates a quantity for the given value and unit of measurement symbol.
     * This is a convenience method that combines a call to {@link Units#valueOf(String)}
     * with {@link #create(double, Unit)}.
     *
     * @param  value  the quantity magnitude.
     * @param  unit   symbol of the unit of measurement associated to the given value.
     * @return a quantity of the given type for the given value and unit of measurement.
     * @throws ParserException if the given symbol can not be parsed.
     */
    public static Quantity<?> create(final double value, final String unit) {
        return create(value, Units.valueOf(unit));
    }

    /**
     * Creates a quantity for the given value and unit of measurement.
     *
     * @param  <Q>    the quantity type (e.g. {@link Length}, {@link Angle}, {@link Time}, etc.).
     * @param  value  the quantity magnitude.
     * @param  unit   the unit of measurement associated to the given value.
     * @return a quantity of the given type for the given value and unit of measurement.
     * @throws IllegalArgumentException if the given unit class is not a supported implementation.
     *
     * @see UnitServices#getQuantityFactory(Class)
     */
    public static <Q extends Quantity<Q>> Q create(final double value, final Unit<Q> unit) {
        ArgumentChecks.ensureNonNull("unit", unit);
        final Unit<Q> system = unit.getSystemUnit();
        if (system instanceof SystemUnit<?>) {
            final ScalarFactory<Q> factory = ((SystemUnit<Q>) system).factory;
            if (factory != null) {
                return factory.create(value, unit);
            } else {
                return ScalarFallback.factory(value, unit, ((SystemUnit<Q>) system).quantity);
            }
        } else {
            throw new IllegalArgumentException(Errors.format(Errors.Keys.UnsupportedImplementation_1, unit.getClass()));
        }
    }

    /**
     * Returns the given quantity as an instance of the specific {@code Quantity} subtype.
     * For example this method can be used for converting a {@code Quantity<Length>} to a {@link Length}.
     * If the given quantity already implements the specific interface, then it is returned as-is.
     *
     * @param  <Q>      the quantity type (e.g. {@link Length}, {@link Angle}, {@link Time}, etc.), or {@code null}.
     * @param  quantity the quantity to convert to the specific subtype.
     * @return the given quantity as a specific subtype (may be {@code quantity} itself), or {@code null} if the given quantity was null.
     * @throws IllegalArgumentException if the unit class associated to the given quantity is not a supported implementation.
     */
    @SuppressWarnings("unchecked")
    public static <Q extends Quantity<Q>> Q castOrCopy(final Quantity<Q> quantity) {
        if (quantity != null) {
            final Unit<Q> unit   = quantity.getUnit();
            final Unit<Q> system = unit.getSystemUnit();
            if (!(system instanceof SystemUnit<?>)) {
                throw new IllegalArgumentException(Errors.format(Errors.Keys.UnsupportedImplementation_1, unit.getClass()));
            }
            final Class<Q> type = ((SystemUnit<Q>) system).quantity;
            if (!type.isInstance(quantity)) {
                final ScalarFactory<Q> factory = ((SystemUnit<Q>) system).factory;
                final double value = AbstractConverter.doubleValue(quantity.getValue());
                if (factory != null) {
                    return factory.create(value, unit);
                } else {
                    return ScalarFallback.factory(value, unit, type);
                }
            }
        }
        return (Q) quantity;
    }
}


text:
#ifndef __JSON_SERDES_HPP__
#define __JSON_SERDES_HPP__

#include <stdint.h>
#include <unordered_set>
#include <string>

namespace json
{
	using ctx_env = std::unordered_map<std::string, void*>;

	template <typename T>
	struct translator;

	template <typename T>
	inline value pack(const T& ctx, ctx_env& env) {
		translator<T> p;
		return p.pack(&ctx, env);
	}

	template <typename T>
	inline T unpack(const value& v, ctx_env& env) {
		translator<T> p;
		T ctx;
		if (!p.unpack(v, &ctx, env))
			return T{};
		return ctx;
	}

	template <typename T>
	inline bool unpack(T& ctx, const value& v, ctx_env& env) {
		translator<T> p;
		return p.unpack(v, &ctx, env);
	}

	template <typename T>
	inline value pack(const T& ctx) {
		ctx_env env;
		return pack(ctx, env);
	}

	template <typename T>
	inline T unpack(const value& v) {
		ctx_env env;
		return unpack<T>(v, env);
	}

	template <typename T>
	inline bool unpack(T& ctx, const value& v) {
		ctx_env env;
		return unpack(ctx, v, env);
	}

	struct base_translator {
		virtual ~base_translator() {}
		virtual value pack(const void* ctx, ctx_env&) = 0;
		virtual bool unpack(const value& v, void* ctx, ctx_env&) = 0;
	};

	struct inplace_translator {
		virtual ~inplace_translator() = default;
		virtual void pack(map& out, const void* ctx, ctx_env&) = 0;
		virtual bool unpack(const map& out, void* ctx, ctx_env&) = 0;
	};

	struct named_translator : base_translator {
		virtual const std::string& name() const = 0;
		virtual bool valid(const void*) const { return true; }
		virtual bool optional() const { return false; }
		virtual void clean(void* ctx) const = 0;
		virtual inplace_translator* inplace() { return nullptr; }
	};

	template <typename T>
	struct simple_translator : base_translator {
		value pack(const void* ctx, ctx_env&) override {
			return *static_cast<const T*>(ctx);
		}
		bool unpack(const value& v, void* ctx, ctx_env&) override {
			constexpr type expected = type_to_value<T>::value;
			T& ref = *static_cast<T*>(ctx);
			ref = T(v.as<expected>());
			return true;
		}
	};

	template <typename C>
	struct container_translator : base_translator
	{
		value pack(const void* ctx, ctx_env& env) override {
			vector out;
			const C& container = *static_cast<const C*>(ctx);
			for (auto&& item : container)
				out.add(json::pack(item, env));
			return out;
		}

		bool unpack(const value& v, void* ctx, ctx_env& env) override {
			auto in = get<VECTOR>(v);
			C& out = *static_cast<C*>(ctx);
			out.clear();

			using value_t = typename C::value_type;

			translator<value_t> sub;
			for (auto&& item : in) {
				value_t new_ctx;
				if (!sub.unpack(item, &new_ctx, env))
					return false;

				out.push_back(new_ctx);
			}

			return true;
		}
	};

	template <typename T>
	struct translator<std::unordered_set<T>> : base_translator
	{
		value pack(const void* ctx, ctx_env& env) override {
			vector out;
			const std::unordered_set<T>& container = *static_cast<const std::unordered_set<T>*>(ctx);
			for (auto&& item : container)
				out.add(json::pack(item, env));
			return out;
		}

		bool unpack(const value& v, void* ctx, ctx_env& env) override {
			auto in = get<VECTOR>(v);
			std::unordered_set<T>& out = *static_cast<std::unordered_set<T>*>(ctx);
			out.clear();

			translator<T> sub;
			for (auto&& item : in) {
				T new_ctx;
				if (!sub.unpack(item, &new_ctx, env))
					return false;

				out.insert(new_ctx);
			}

			return true;
		}
	};

	template <typename T>
	struct translator<std::unordered_map<std::string, T>> : base_translator
	{
		value pack(const void* ctx, ctx_env& env) override {
			map out;
			using C = std::unordered_map<std::string, T>;
			const C& container = *static_cast<const C*>(ctx);
			for (auto&& item : container)
				out.add(item.first, json::pack(item.second, env));
			return out;
		}

		bool unpack(const value& v, void* ctx, ctx_env& env) override {
			auto in = get<MAP>(v);
			using C = std::unordered_map<std::string, T>;
			C& out = *static_cast<C*>(ctx);
			out.clear();

			using value_t = T;
			translator<value_t> sub;
			for (auto&& item : in) {
				value_t& new_ctx = out[item.first];
				if (!sub.unpack(item.second, &new_ctx, env))
					return false;
			}

			return true;
		}
	};

#define SIMPLE_TRANSLATOR(type) \
	template <> \
	struct translator<type>: simple_translator<type>{}

#define CONTAINER_TRANSLATOR(C) \
	template <typename T> \
	struct translator<C<T>> : container_translator<C<T>>{}

	SIMPLE_TRANSLATOR(std::nullptr_t);
	SIMPLE_TRANSLATOR(bool);
	SIMPLE_TRANSLATOR(std::string);
	SIMPLE_TRANSLATOR(int8_t);
	SIMPLE_TRANSLATOR(int16_t);
	SIMPLE_TRANSLATOR(int32_t);
	SIMPLE_TRANSLATOR(int64_t);
	SIMPLE_TRANSLATOR(float);
	SIMPLE_TRANSLATOR(double);
	CONTAINER_TRANSLATOR(std::vector);
	CONTAINER_TRANSLATOR(std::list);

	template <typename T, size_t length>
	struct translator<std::array<T, length>> : base_translator {
		using C = std::array<T, length>;

		value pack(const void* ctx, ctx_env& env) override {
			vector out;
			const C& container = *static_cast<const C*>(ctx);
			for (auto&& item : container)
				out.add(json::pack(item, env));
			return out;
		}

		bool unpack(const value& v, void* ctx, ctx_env& env) override {
			auto in = get<VECTOR>(v);
			C& out = *static_cast<C*>(ctx);

			using value_t = typename C::value_type;

			size_t index = 0;
			translator<value_t> sub;
			for (auto&& item : in) {
				if (index == length)
					return false;

				if (!sub.unpack(item, &out[index], env))
					return false;

				++index;
			}

			while (index < length) {
				out[index] = value_t();
				++index;
			}

			return true;
		}
	};

	template <typename T, typename P>
	struct member_translator : named_translator
	{
		std::string m_name;
		P T::* m_prop;

		member_translator(const std::string& name, P T::* prop) : m_name(name), m_prop(prop) {}
		const std::string& name() const override { return m_name; }
		value pack(const void* ctx, ctx_env& env) override {
			auto ptr = static_cast<const T*>(ctx);
			return json::pack(ptr->*m_prop, env);
		}

		bool unpack(const value& v, void* ctx, ctx_env& env) override {
			auto ptr = static_cast<T*>(ctx);
			translator<P> p;
			return p.unpack(v, &(ptr->*m_prop), env);
		}

		void clean(void* ctx) const override {
			auto ptr = static_cast<T*>(ctx);
			ptr->*m_prop = P();
		}
	};

	template <typename T>
	inline bool is_empty(const T& val) {
		return val == T();
	}

	template <typename T>
	inline bool is_empty(const std::vector<T>& val) {
		return val.empty();
	}

	template <typename T, typename P>
	struct member_opt_translator : member_translator<T, P>
	{
		member_opt_translator(const std::string& name, P T::* prop) : member_translator<T, P>(name, prop) {}

		bool valid(const void* ctx) const override {
			auto __prop = member_translator<T, P>::m_prop;
			auto ptr = static_cast<const T*>(ctx);
			auto prop = ptr->*__prop;
			return !is_empty(prop);
		}
		bool optional() const override { return true; }

		void clean(void* ctx) const override {
			auto __prop = member_translator<T, P>::m_prop;
			auto ptr = static_cast<T*>(ctx);
			ptr->*__prop = P();
		}
	};

	namespace impl
	{
		template <typename C>
		const typename C::value_type& front(const C& container) {
			return container.front();
		}

		template <typename T>
		const T& front(const std::unordered_map<std::string, T>& container) {
			return container.begin()->second;
		}

		template <typename C>
		typename C::value_type& front(C& container) {
			container.push_back(typename C::value_type{});
			return container.front();
		}

		template <typename T>
		T& front(std::unordered_map<std::string, T>& container) {
			return container[""];
		}

		template <typename C> struct item_expected : std::integral_constant<type, VECTOR> { using value_type = typename C::value_type; };
		template <typename T> struct item_expected<std::unordered_map<std::string, T>> : std::integral_constant<type, MAP>{ using value_type = T; };

	}

	template <typename T, typename P>
	struct member_item_translator : named_translator
	{
		std::string m_name;
		P T::* m_prop;

		member_item_translator(const std::string& name, P T::* prop) : m_name(name), m_prop(prop) {}
		const std::string& name() const override { return m_name; }
		value pack(const void* ctx, ctx_env& env) override {
			auto ptr = static_cast<const T*>(ctx);
			const auto& prop = ptr->*m_prop;
			if (prop.size() == 1) {
				return json::pack(json::impl::front(prop), env);
			}
			return json::pack(prop, env);
		}

		bool unpack(const value& v, void* ctx, ctx_env& env) override {
			auto ptr = static_cast<const T*>(ctx);
			P& prop = const_cast<P&>(ptr->*m_prop);
			prop.clear();

			if (v.is<impl::item_expected<P>::value>()) {
				translator<P> p;
				return p.unpack(v, &prop, env);
			}

			using item_t = typename impl::item_expected<P>::value_type;
			translator<item_t> p;
			item_t& new_ctx = impl::front(prop);
			return p.unpack(v, &new_ctx, env);
		}

		bool valid(const void* ctx) const override {
			auto ptr = static_cast<const T*>(ctx);
			auto prop = ptr->*m_prop;
			return !prop.empty();
		}

		void clean(void* ctx) const override {
			auto ptr = static_cast<T*>(ctx);
			ptr->*m_prop = P();
		}
	};

	struct struct_translator: base_translator
	{
		using props_t = std::vector<std::unique_ptr<named_translator>>;
		props_t m_props;

		ctx_env env_;

		template <typename P, typename T>
		void add_prop(const std::string& name, P T::* prop) {
			m_props.emplace_back(std::make_unique<member_translator<T, P>>(name, prop));
		}

		template <typename P, typename T>
		void add_opt_prop(const std::string& name, P T::* prop) {
			m_props.emplace_back(std::make_unique<member_opt_translator<T, P>>(name, prop));
		}

		template <typename P, typename T>
		void add_item_prop(const std::string& name, P T::* prop) {
			m_props.emplace_back(std::make_unique<member_item_translator<T, P>>(name, prop));
		}

		void add(std::unique_ptr<named_translator> tr) { m_props.emplace_back(std::move(tr)); }

		value pack(const void* ctx, ctx_env& env) override {
			env_ = env;
			map obj;
			for (auto&& prop : m_props) {
				auto inplace = prop->inplace();
				if (inplace) {
					inplace->pack(obj, ctx, env_);
					continue;
				}
				if (!prop->valid(ctx))
					continue;

				obj.add(prop->name(), prop->pack(ctx, env_));
			}
			return obj;
		}

		bool unpack(const value& v, void* ctx, ctx_env& env) override {
			env_ = env;
			if (!v.is<MAP>())
				return false;

			auto obj = get<MAP>(v);

			for (auto&& prop : m_props) {
				auto inplace = prop->inplace();
				if (inplace) {
					if (!inplace->unpack(obj, ctx, env_))
						return false;
					continue;
				}
				auto it = obj.find(prop->name());

				if (it == obj.end()) {
					if (!prop->optional())
						return false;
					prop->clean(ctx);
					continue;
				}

				if (!prop->unpack(it->second, ctx, env_))
					return false;
			}

			return true;
		}
	};

#define JSON_STRUCT(name) \
	template <> \
	struct translator<name> : struct_translator { \
		using my_type = name; \
		translator(); \
	}; \
	inline translator<name>::translator()

#define JSON_STRUCT_(name, base) \
	template <> \
	struct translator<name> : translator<base>{ \
		using my_type = name; \
		translator(); \
	}; \
	inline translator<name>::translator()

#define JSON_NAMED_PROP(name, prop) \
	this->add_prop(name, &my_type::prop)

#define JSON_PROP(prop) JSON_NAMED_PROP(#prop, prop)

#define JSON_OPT_NAMED_PROP(name, prop) \
	this->add_opt_prop(name, &my_type::prop)

#define JSON_OPT_PROP(prop) JSON_OPT_NAMED_PROP(#prop, prop)

#define JSON_ITEM_NAMED_PROP(name, prop) \
	this->add_item_prop(name, &my_type::prop)

#define JSON_ITEM_PROP(prop) JSON_ITEM_NAMED_PROP(#prop, prop)
}

#endif // __JSON_SERDES_HPP__


text:
import { Resolvable, flatten, values } from '@uirouter/core';

import { normalizeResolvables } from '../utils';

function prepare(resolvable) {
    const policy = resolvable.policy || {};
    return new Resolvable(
        resolvable,
        (...args) => resolvable.resolveFn(...args),
        resolvable.deps,
        { ...policy, async: 'NOWAIT' },
        resolvable.data,
    );
}

export default (state, parent) => {
    const allStateResolvables = flatten(state.path.map(node => node.resolvables))
        .filter(r => r)
        .map(r => r.token);

    const resolves = flatten(values(state.views).map(v => normalizeResolvables(v.resolve)))
        .filter(r => r && allStateResolvables.indexOf(r) === -1);

    const resolvables = parent(state);
    if (resolves.length === 0) return resolvables;

    const prepared = resolves.map(r => prepare(r));
    return [
        ...resolvables,
        ...prepared,
    ];
}


text:
class CommentsController < ApplicationController

  before_action :authenticate,                              except: [ :for_feed ]
  before_action -> { require_permission_to 'write_comments'},  except: [ :create, :for_feed ]

  def index
    @comments = Comment.by_recent.paginate(:page => params[:page], :per_page => 50)
    switch_to_admin_layout
  end

  # comments are shown within a page
  # new comments are created by users from within a page

  def edit
    @comment = Comment.find(params[:id])
    switch_to_admin_layout
  end

  def create
    @comment = Comment.new(comment_params)
    @comment.author_id = current_user.id
    @comment.locale = I18n.locale.to_s
    @comment.status = 'pending' # translation not done with globalize3 but with locale files upon showing status to user
    if @comment.save
      Activity.create doer_id: current_user.id, message: "left a comment attached to: #{view_context.link_to (@comment.commentable.try(:name) || @comment.commentable.try(:title) || 'unknown'), @comment.commentable}."
      redirect_to @comment.commentable, notice: t('comments.create.notice')
    else
      flash[:warning] = t('comments.create.warning')
      redirect_to @comment.commentable
    end
  end

  def update
    @comment = Comment.find(params[:id])
    if @comment.update_attributes(comment_params)
      redirect_to comments_path, notice: t('comments.update.notice')
    else
      flash[:warning] = t('comments.update.warning')
      render action: "edit", warning: t('comments.update.warning'), layout: 'admin'
    end
  end

  def destroy
    @comment = Comment.find(params[:id])
    @comment.destroy
    redirect_to comments_url, notice: t('comments.destroy.notice')
  end

  def accept
    @comment = Comment.find params[:id]
    @comment.status = 'accepted'
    if @comment.save
      redirect_to :back, notice: t('comments.moderation.accept.notice')
    else
      flash[:warning] = t('comments.moderation.accept.warning')
      redirect_to comments_path
    end
  end

  def block
    @comment = Comment.find params[:id]
    @comment.status = 'blocked'
    if @comment.save
      redirect_to :back, notice: t('comments.moderation.block.notice')
    else
      flash[:warning] = t('commentns.moderation.block.warning')
      redirect_to comments_path
    end
  end

  def pending
    @comments = Comment.pending.by_created.paginate(:page => params[:page], :per_page => 50)
    switch_to_admin_layout
  end

  def accepted
    @comments = Comment.accepted.by_recent.paginate(:page => params[:page], :per_page => 50)
    switch_to_admin_layout
  end

  def blocked
    @comments = Comment.blocked.by_recent.paginate(:page => params[:page], :per_page => 50)
    switch_to_admin_layout
  end

  def for_feed
    @comments = Comment.showable.for_locale(I18n.locale).by_recently_created.limit(50)
    respond_to do |format|
      format.html { redirect_to root_path }
      format.atom
    end
  end

  private

  # Never trust parameters from the scary internet, only allow the white list through.
  def comment_params
    params.require(:comment).permit(:body, :commentable_type, :commentable_id)
    # non-accessible attributes: author_id, :status, :locale
  end

end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/*
 * Description of cAdmin
 *
 * @author 5-09
 */

class cSesion extends CI_Controller {
	public function __construct(){
		parent::__construct();

		$this->load->database();

		$this->load->helper(array("form", "url"));
		$this->load->library(array('form_validation'));

		$this->load->model("mAdmin");
	}

	public function index(){
		$this->load->view('vLogin');
	}

	public function login(){
		$nick = $this->input->post("txtNickname");
		$pass = $this->input->post("txtPassword");
		$user = $this->mAdmin->seeField("user", "nick", $nick);
		if($user->num_rows() == 0)
		{
			$this->index();
		}
		else
		{
			$infoUser = $user->row();
			if ($infoUser->nick == $nick && $infoUser->password == $pass && $infoUser->type == 1) {
				$info = array(
					'nick' 			=> $nick,
					'password' 	=> $pass,
				);
				// $this->session->set_userdata($info);
				redirect("/cAdmin/index");
			}
			else{
				$this->index();
			}
		}
	}

	public function logout(){
		$this->session->sess_destroy();
		redirect("/formulario/index");
	}
}?>


text:
package com.salesfront.commons.shared.implementations;

/**
 * Created by ahtremblay on 15-10-07.
 */
public interface RandomProvider {
    int nextInt(int bound);
}


text:
/* global describe, beforeEach, it, expect */

'use strict';

var IndexPage = require('./pages/index_page');

describe('The dashboard app', function() {

    var todoPage;

    beforeEach(function() {
        todoPage = new IndexPage();
        todoPage.open();
    });

    it('should list several switch buttons', function() {
        expect(todoPage.switchButton(0).getText()).toEqual('Kitchen-lamp1');
        expect(todoPage.switchButton(1).getText()).toEqual('Kitchen-lamp2');
    });
});