text:
**[ [TOC](../README.md) ]**

# Adaptive CK container for MLPerf™ Inference v1.0 - Object Detection - TFLite 2.4.1 with RUY

## Install Collective Knowledge (CK) with CK MLOps repo

```
python3 -m pip install ck
ck pull repo:mlcommons@ck-mlops
```

## Build Docker container with CK components and workflows for MLPerf™

```
ck build docker:ck-mlperf-inference-v1.0-object-detection-4725481db87af8d0 --tag=ubuntu-20.04
```

## Run this container interactively

```
ck run docker:ck-mlperf-inference-v1.0-object-detection-4725481db87af8d0 --tag=ubuntu-20.04
```

You can now issue standard CK commands from [here](ck-object-detection-x86-64.md) to benchmark MLPerf™ model.

## Issue a CK command to this container

### Linux
```
docker run --rm mlcommons/ck-mlperf-inference-v1.0-object-detection-4725481db87af8d0:ubuntu-20.04 \
    "ck benchmark program:object-detection-tflite-loadgen \
     --env.CK_SILENT_MODE=YES \
     --skip_print_timers \
     --dep_add_tags.compiler=gcc \
     --dep_add_tags.python=v3 \
     --dep_add_tags.mlperf-inference-src=r1.0 \
     --dep_add_tags.weights=ssd-mobilenet \
     --dep_add_tags.library=tflite,v2.4.1,with.ruy \
     --env.CK_LOADGEN_DATASET_SIZE=1024 \
     --env.CK_VERBOSE=0 \
     --env.CK_LOADGEN_SCENARIO=SingleStream \
     --env.CK_LOADGEN_MODE=PerformanceOnly \
     --env.CK_LOADGEN_TARGET_LATENCY=20 \
     --skip_stat_analysis \
     --process_multi_keys \
     --repetitions=1 \
     --record \
     --record_repo=local \
     --record_uoa=mlperf-closed-amd-tflite-v2.4.1-ruy-ssd-mobilenet-non-quantized-singlestream-performance-target-latency-20 \
     --tags=mlperf,division.closed,task.object-detection,platform.amd,inference_engine.tflite,inference_engine_version.v2.4.1,inference_engine_backend.ruy,scenario.singlestream,mode.performance,workload.ssd-mobilenet-non-quantized,preprocessed_using.pillow,target_latency.20 \
    "
```

### Windows
```
docker run --rm mlcommons/ck-mlperf-inference-v1.0-object-detection-4725481db87af8d0:ubuntu-20.04 ^
    "ck benchmark program:object-detection-tflite-loadgen ^
     --env.CK_SILENT_MODE=YES ^
     --skip_print_timers ^
     --dep_add_tags.compiler=gcc ^
     --dep_add_tags.python=v3 ^
     --dep_add_tags.mlperf-inference-src=r1.0 ^
     --dep_add_tags.weights=ssd-mobilenet ^
     --dep_add_tags.library=tflite,v2.4.1,with.ruy ^
     --env.CK_LOADGEN_DATASET_SIZE=1024 ^
     --env.CK_VERBOSE=0 ^
     --env.CK_LOADGEN_SCENARIO=SingleStream ^
     --env.CK_LOADGEN_MODE=PerformanceOnly ^
     --env.CK_LOADGEN_TARGET_LATENCY=20 ^
     --skip_stat_analysis ^
     --process_multi_keys ^
     --repetitions=1 ^
     --record ^
     --record_repo=local ^
     --record_uoa=mlperf-closed-amd-tflite-v2.4.1-ruy-ssd-mobilenet-non-quantized-singlestream-performance-target-latency-20 ^
     --tags=mlperf,division.closed,task.object-detection,platform.amd,inference_engine.tflite,inference_engine_version.v2.4.1,inference_engine_backend.ruy,scenario.singlestream,mode.performance,workload.ssd-mobilenet-non-quantized,preprocessed_using.pillow,target_latency.20 ^
    "
```

## Run a container and record experiments locally

You can run adaptive CK containers while recording experiments to local CK repositories to perform further analysis and visualization on yout host machine.

Let's create a dummy repository 'ck-experiment':
```
ck add repo:ck-experiment --quiet
```

You can then run the script "ck-object-detection-x86-64-docker-start.sh" from this directory
to pass the path to this repo to the container, run it, benchmark MLPerf™ model, and record
experiments to the above ck-experiment repository:

```
./ck-object-detection-x86-64-docker-start.sh
```

Here is the content of this script:
```
export CK_HOST_REPO_EXPERIMENTS=`ck where repo:ck-experiments`

echo ${CK_HOST_REPO_EXPERIMENTS}

export CK_LOCAL_DOCKER_SCRIPT=ck-object-detection-x86-64-docker-helper.sh
export CK_HOST_RUN_SCRIPT=$PWD/${CK_LOCAL_DOCKER_SCRIPT}
export CK_HOST_DATASETS=~/datasets

docker run \
       --volume ${CK_HOST_REPO_EXPERIMENTS}:/home/ckuser/ck-experiments \
       --volume ${CK_HOST_RUN_SCRIPT}:/home/ckuser/${CK_LOCAL_DOCKER_SCRIPT} \
       -it mlcommons/ck-mlperf-inference-v1.0-object-detection-4725481db87af8d0:ubuntu-20.04 \
       "./${CK_LOCAL_DOCKER_SCRIPT}"
```

It also passes a helper script "ck-object-detection-x86-64-docker-helper.sh" to the container:
```
echo "======================================================================="
echo "Fixing access to datasets and ck-experiments ..."
echo ""
time sudo chmod -R 777 datasets
time sudo chmod -R 777 ck-experiments

echo "====================================================================="
echo "Adding external ck-experiments repository ..."
echo ""

ck add repo:ck-experiments --path=/home/ckuser/ck-experiments --quiet

ck ls repo

pwd

ls

ck benchmark program:object-detection-tflite-loadgen \
     --env.CK_SILENT_MODE=YES \
     --skip_print_timers \
     --dep_add_tags.compiler=gcc \
     --dep_add_tags.python=v3 \
     --dep_add_tags.mlperf-inference-src=r1.0 \
     --dep_add_tags.weights=ssd-mobilenet \
     --dep_add_tags.dataset=dataset,object-detection,preprocessed,full,using-pillow \
     --dep_add_tags.library=tflite,v2.4.1,with.ruy \
     --env.CK_LOADGEN_DATASET_SIZE=50 \
     --env.USE_NMS=regular \
     --env.CK_VERBOSE=1 \
     --env.CK_LOADGEN_SCENARIO=SingleStream \
     --env.CK_LOADGEN_MODE=AccuracyOnly \
     --skip_stat_analysis \
     --process_multi_keys \
     --repetitions=1 \
     --record \
     --record_repo=ck-experiments \
     --record_uoa=mlperf-closed-amd-tflite-v2.4.1-ruy-ssd-mobilenet-non-quantized-singlestream-accuracy-target-latency-20 \
     --tags=mlperf,division.closed,task.object-detection,platform.amd,inference_engine.tflite,inference_engine_version.v2.4.1,inference_engine_backend.ruy,scenario.singlestream,mode.accuracy,workload.ssd-mobilenet-non-quantized,preprocessed_using.pillow,target_latency.20

echo "======================================================================="
cat `ck find program:object-detection-tflite-loadgen`/tmp/accuracy.txt
echo "======================================================================="

```

You can see the results in the ck-experiments from your host machine as follows:
```
ck ls experiment
```
or
```
ck ls ck-experiments:experiment:*
```

You can pack this repository.
```
ck zip repo:ck-experiments
```

CK will create "ckr-ck-experiments.zip" file that can be shared with other colleagues or workgroups.

Anyone else can now add these experiments in their own CK repositories for further analysis as follows:
```
ck unzip repo --zip=ckr-ck-experiments.zip
```

You can also visualize this data using [CK dashboards](../results/ck-dashboard.md).


text:
<!DOCTYPE html>

    <title>Fancy Tree Test Page</title>
    <link rel="stylesheet" href="react-fancy-tree.css">

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace CCDI\AdminBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class CCDIAdminBundle extends Bundle
{
}


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.graph.support;

import edu.uci.ics.jung.algorithms.layout.Layout;
import ghidra.graph.VisualGraph;
import ghidra.graph.graphs.TestEdge;
import ghidra.graph.graphs.AbstractTestVertex;
import ghidra.graph.viewer.layout.JungWrappingVisualGraphLayoutAdapter;

/**
 * A graph layout used for testing.
 */
public class TestGraphLayout extends JungWrappingVisualGraphLayoutAdapter<AbstractTestVertex, TestEdge> {

	public TestGraphLayout(Layout<AbstractTestVertex, TestEdge> jungLayout) {
		super(jungLayout);
	}

	@Override
	public TestGraphLayout cloneLayout(VisualGraph<AbstractTestVertex, TestEdge> newGraph) {

		Layout<AbstractTestVertex, TestEdge> newJungLayout = cloneJungLayout(newGraph);
		return new TestGraphLayout(newJungLayout);
	}
}


text:
package com.evolveum.midpoint.repo.sql.data.common.embedded;

import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.repo.sql.query.definition.JaxbType;
import com.evolveum.prism.xml.ns._public.types_3.PolyStringType;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

import javax.persistence.Column;
import javax.persistence.Embeddable;

import java.io.Serializable;

/**
 * @author lazyman
 */
@Embeddable
@JaxbType(type = PolyString.class)
public class RPolyString implements Serializable {

    public static final String F_NORM = "norm";
    public static final String F_ORIG = "orig";

    private String orig;
    private String norm;

    public RPolyString() {
    }

    public RPolyString(String orig, String norm) {
        this.norm = norm;
        this.orig = orig;
    }

    @Column(nullable = true)
    public String getNorm() {
        return norm;
    }

    @Column(nullable = true)
    public String getOrig() {
        return orig;
    }

    public void setNorm(String norm) {
        this.norm = norm;
    }

    public void setOrig(String orig) {
        this.orig = orig;
    }

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

        RPolyString that = (RPolyString) o;

        if (norm != null ? !norm.equals(that.norm) : that.norm != null) return false;
        if (orig != null ? !orig.equals(that.orig) : that.orig != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = orig != null ? orig.hashCode() : 0;
        result = 31 * result + (norm != null ? norm.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
    }

    public static RPolyString copyFromJAXB(PolyStringType string) {
        if (string == null) {
            return null;
        }

        return new RPolyString(string.getOrig(), string.getNorm());
    }

    public static RPolyString toRepo(PolyString string) {
        if (string == null) {
            return null;
        }

        return new RPolyString(string.getOrig(), string.getNorm());
    }

    public static PolyStringType copyToJAXB(RPolyString string, PrismContext ctx) {
        if (string == null) {
            return null;
        }

        String orig = string.getOrig();
        String norm = string.getNorm();

        PolyStringType poly = new PolyStringType();
        poly.setOrig(orig);

        if (orig != null && norm == null) {
            norm = ctx.getDefaultPolyStringNormalizer().normalize(orig);
            poly.setNorm(norm);
        } else {
            poly.setNorm(norm);
        }

        return poly;
    }

    public static PolyString fromRepo(RPolyString string, PrismContext prismContext) {
        if (string == null) {
            return null;
        }

        return copyToJAXB(string, prismContext).toPolyString();
    }
}


text:
cask 'knime' do
  version '3.3.2'
  sha256 '5502be5a3ea3454cf244436361536db884dd3bdb761861e7e3cd6e4dd8eb729a'

  # download.knime.org/analytics-platform/macosx was verified as official when first introduced to the cask
  url "https://download.knime.org/analytics-platform/macosx/knime_#{version}.app.macosx.cocoa.x86_64.dmg"
  name 'KNIME Analytics Platform'
  homepage 'https://www.knime.com/'

  depends_on macos: '>= :lion'

  app "KNIME #{version}.app"
end


text:
@interface PTLCollectionViewController : UICollectionViewController

@end


text:
Details on the various actions that can be performed on the
Embedded Deployment resource, including the expected
parameters and the potential responses.

##### Contents

*   [Get](#get)

<br/>

## Get

Retrieves information on an embedded deployment

```javascript
var params = {
  applicationId: myApplicationId,
  embeddedDeploymentId: myEmbeddedDeploymentId
};

// with callbacks
client.embeddedDeployment.get(params, function (err, result) {
  if (err) { return console.error(err); }
  console.log(result);
});

// with promises
client.embeddedDeployment.get(params)
  .then(console.log)
  .catch(console.error);
```

#### Authentication
The client must be configured with a valid api access token to call this
action. The token must include at least one of the following scopes:
all.Application, all.Application.read, all.Organization, all.Organization.read, all.User, all.User.read, embeddedDeployment.*, or embeddedDeployment.get.

#### Available Parameters

| Name | Type | Required | Description | Default | Example |
| ---- | ---- | -------- | ----------- | ------- | ------- |
| applicationId | string | Y | ID associated with the application |  | 575ec8687ae143cd83dc4a97 |
| embeddedDeploymentId | string | Y | ID associated with the embedded deployment |  | 575ed78e7ae143cd83dc4aab |
| losantdomain | string | N | Domain scope of request (rarely needed) |  | example.com |

#### Successful Responses

| Code | Type | Description |
| ---- | ---- | ----------- |
| 200 | [Embedded Deployment](../lib/schemas/embeddedDeployment.json) | Embedded deployment information |

#### Error Responses

| Code | Type | Description |
| ---- | ---- | ----------- |
| 400 | [Error](../lib/schemas/error.json) | Error if malformed request |
| 404 | [Error](../lib/schemas/error.json) | Error if embedded deployment was not found |


text:
title: "Book Review: Rich Dad Poor Dad"
keywords:
  - book review
  - finance
---

[Rich Dad Poor Dad](https://amzn.to/2D7yegW) is a popular personal finance book. I don't understand why. The entire book can be summarized in one page. It duplicates entire sections. The book provides no real advice on how to become rich. It even gives outright bad financial advice. Don't waste your time. Read [A Random Walk down Wall Street](https://amzn.to/2ywALxm) and [The Little Book of Common Sense Investing](https://amzn.to/2qc0t5R) instead.

[![Rich Dad Poor Dad](/images/books/rich-dad-poor-dad.png)](https://amzn.to/2D7yegW)

## Good
- Highlights the need for financial education.
- Spend money on cash producing assets.
- Don't spend money on liabilities.

## Bad
- Erodes the value of traditional education.
- Gives very bad advice on paying debts.
- Does not provide clear tools for financial independence.


text:
function testHybridMode

options.floating = true;
p = HybridRigidBodyMode('FallingBrick.urdf',zeros(6,1),[1;zeros(7,1)],options);
xtraj = simulate(p,[0 4]);
v = p.constructVisualizer();
v.playback(xtraj);

p = HybridRigidBodyMode('FallingBrick.urdf',zeros(6,1),[1;1;zeros(6,1)],options);
xtraj = simulate(p,[0 4]);
v.playback(xtraj);


text:
"""
#
# Description:
# originally based on copy_media.py
# updated to use JSON playlists pointing to Content objects...
# should use other scripts to help with that conversion as needed
#
# copy the refrenced files to a new directory
#

# By: Charles Brandt [code at charlesbrandt dot com]

# On: 2009.04.13 20:13:01
# Also: 2009.07.25 10:23:48
# Also: 2015.03.19 18:36:23
# License:  MIT

# Requires: medley, moments

"""
from __future__ import print_function

import sys, os, re
import subprocess

from medley.helpers import load_json, save_json
from medley.content import Content
from medley.playlist import Playlist
from medley.formats import M3U

def usage():
    print(__doc__)

def copy_file(source, destination, verbose=False):
    """
    copy a single file
    """
    #if not destination:
    if os.path.exists(destination):
        print("skipping: %s" % destination)
        pass
    else:
        dest_path = os.path.dirname(destination)
        if not dest_path:
            dest_path = os.path.abspath('./')
            print("USING PATH: %s" % dest_path)
        if not os.path.exists(dest_path):
            os.makedirs(dest_path)

        #cp = subprocess.Popen("cp %s %s" % (source, destination), shell=True, stdout=subprocess.PIPE)
        #cp.wait()
        command = 'rsync -av "%s" "%s"' % (source, destination)
        rsync = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if verbose:
            print(command)
            print(rsync.communicate()[0])
        else:
            rsync.communicate()[0]

def copy_media(source, destination=''):
    if os.path.exists(source):
        pl = None
        if re.search('m3u$', source):
            #load it as an M3U:
            print("LOADING AS M3U: %s" % source)
            pl = M3U(source)
        else:
            pl = Playlist()
            pl.load(source)

        if not os.path.exists(destination):
            os.makedirs(destination)

        for content in pl:
            path = os.path.join(content.path, content.filename)
            print(path)
            if content != content.root:
                #parent_path = os.path.join(content.parent.path, content.parent.filename)
                #print parent_path
                print("Extracting segment from parent content")
                content.extract_segment(destination)
            else:
                print("only need to copy original path")
                this_dest = os.path.join(destination, content.filename)
                copy_file(path, this_dest)

            #print content.debug()
        print(pl)
    else:
        print("Couldn't find path: %s" % source)
        exit()

if __name__ == '__main__':
    source = None
    destination = None
    if len(sys.argv) > 1:
        helps = ['--help', 'help', '-h']
        for i in helps:
            if i in sys.argv:
                usage()
                exit()
        source = sys.argv[1]
        if len(sys.argv) > 2:
            destination = sys.argv[2]
        else:
            print("OUTPUT TO TEMP!")
            destination = './temp'

    copy_media(source, destination)

    if destination == './temp':
        print()
        print("OUTPUT TO TEMP!!")


text:
package com.siyeh.ig.style;

import com.intellij.codeInspection.CleanupLocalInspectionTool;
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.fixes.RemoveModifierFix;
import com.siyeh.ig.psiutils.VariableAccessUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

import static com.siyeh.InspectionGadgetsBundle.message;

public class UnnecessaryFinalOnLocalVariableOrParameterInspection extends BaseInspection implements CleanupLocalInspectionTool {

  @SuppressWarnings({"PublicField"})
  public boolean onlyWarnOnAbstractMethods = false;

  @SuppressWarnings("PublicField")
  public boolean reportLocalVariables = true;

  @SuppressWarnings("PublicField")
  public boolean reportParameters = true;

  @Override
  @NotNull
  public String buildErrorString(Object... infos) {
    final PsiVariable variable = (PsiVariable)infos[0];
    final String variableName = variable.getName();
    if (variable instanceof PsiParameter) {
      return message("unnecessary.final.on.parameter.problem.descriptor", variableName);
    }
    else {
      return message("unnecessary.final.on.local.variable.problem.descriptor", variableName);
    }
  }

  @Override
  @Nullable
  public JComponent createOptionsPanel() {
    final MultipleCheckboxOptionsPanel panel = new MultipleCheckboxOptionsPanel(this);
    final JCheckBox box1 = panel.addCheckboxEx(message("unnecessary.final.report.local.variables.option"), "reportLocalVariables");
    final JCheckBox box2 = panel.addCheckboxEx(message("unnecessary.final.report.parameters.option"), "reportParameters");
    panel.addDependentCheckBox(message("unnecessary.final.on.parameter.only.interface.option"), "onlyWarnOnAbstractMethods", box2);

    box1.addChangeListener(e -> {
      if (!box1.isSelected()) box2.setSelected(true);
    });
    box2.addChangeListener(e -> {
      if (!box2.isSelected()) box1.setSelected(true);
    });
    return panel;
  }

  @Override
  public BaseInspectionVisitor buildVisitor() {
    return new UnnecessaryFinalOnLocalVariableOrParameterVisitor();
  }

  @Override
  public InspectionGadgetsFix buildFix(Object... infos) {
    return new RemoveModifierFix(PsiModifier.FINAL);
  }

  private class UnnecessaryFinalOnLocalVariableOrParameterVisitor extends BaseInspectionVisitor {

    @Override
    public void visitDeclarationStatement(PsiDeclarationStatement statement) {
      super.visitDeclarationStatement(statement);
      if (!reportLocalVariables) {
        return;
      }
      final PsiElement[] declaredElements = statement.getDeclaredElements();
      if (declaredElements.length == 0) {
        return;
      }
      final PsiElement firstElement = declaredElements[0];
      if (!(firstElement instanceof PsiLocalVariable)) {
        return;
      }
      final PsiLocalVariable firstVariable = (PsiLocalVariable)firstElement;
      if (!firstVariable.hasModifierProperty(PsiModifier.FINAL)) {
        return;
      }
      final PsiCodeBlock containingBlock = PsiTreeUtil.getParentOfType(statement, PsiCodeBlock.class);
      if (containingBlock == null) {
        return;
      }
      for (PsiElement declaredElement : declaredElements) {
        final PsiLocalVariable variable = (PsiLocalVariable)declaredElement;
        if (isNecessaryFinal(variable, containingBlock)) {
          return;
        }
      }
      final PsiLocalVariable variable = (PsiLocalVariable)firstElement;
      registerModifierError(PsiModifier.FINAL, variable, variable);
    }

    @Override
    public void visitMethod(PsiMethod method) {
      super.visitMethod(method);
      if (!reportParameters) {
        return;
      }
      final PsiParameterList parameterList = method.getParameterList();
      final PsiParameter[] parameters = parameterList.getParameters();
      for (final PsiParameter parameter : parameters) {
        checkParameter(method, parameter);
      }
    }

    private void checkParameter(PsiMethod method, PsiParameter parameter) {
      if (!parameter.hasModifierProperty(PsiModifier.FINAL)) {
        return;
      }
      if (method.hasModifierProperty(PsiModifier.ABSTRACT)) {
        registerModifierError(PsiModifier.FINAL, parameter, parameter);
      }
      else if (!onlyWarnOnAbstractMethods) {
        check(parameter);
      }
    }

    @Override
    public void visitTryStatement(PsiTryStatement statement) {
      super.visitTryStatement(statement);
      if (onlyWarnOnAbstractMethods || !reportParameters) {
        return;
      }
      final PsiResourceList resourceList = statement.getResourceList();
      if (resourceList != null) {
        for (PsiResourceListElement element : resourceList) {
          if (element instanceof PsiResourceVariable) {
            final PsiResourceVariable variable = (PsiResourceVariable)element;
            if (variable.hasModifierProperty(PsiModifier.FINAL)) {
              registerModifierError(PsiModifier.FINAL, variable, variable);
            }
          }
        }
      }
      final PsiCatchSection[] catchSections = statement.getCatchSections();
      for (PsiCatchSection catchSection : catchSections) {
        final PsiParameter parameter = catchSection.getParameter();
        final PsiCodeBlock catchBlock = catchSection.getCatchBlock();
        if (parameter == null || catchBlock == null) {
          continue;
        }
        if (!parameter.hasModifierProperty(PsiModifier.FINAL)) {
          continue;
        }
        if (parameter.getType() instanceof PsiDisjunctionType || !isNecessaryFinal(parameter, parameter.getDeclarationScope())) {
          registerModifierError(PsiModifier.FINAL, parameter, parameter);
        }
      }
    }

    @Override
    public void visitForeachStatement(PsiForeachStatement statement) {
      super.visitForeachStatement(statement);
      if (onlyWarnOnAbstractMethods || !reportParameters) {
        return;
      }
      final PsiParameter parameter = statement.getIterationParameter();
      if (!parameter.hasModifierProperty(PsiModifier.FINAL)) {
        return;
      }
      check(parameter);
    }

    private boolean isNecessaryFinal(PsiVariable variable, PsiElement context) {
      return PsiUtil.isConstantExpression(variable.getInitializer()) ||
             !PsiUtil.isLanguageLevel8OrHigher(variable) && VariableAccessUtils.variableIsUsedInInnerClass(variable, context);
    }

    private void check(PsiParameter parameter) {
      if (!isNecessaryFinal(parameter, parameter.getDeclarationScope())) {
        registerModifierError(PsiModifier.FINAL, parameter, parameter);
      }
    }
  }
}


text:
//
//  XAuthTwitterEngine.h
//
//  Created by Aral Balkan on 28/02/2010.
//  Copyright 2010 Naklab. All rights reserved.
//
//  Based on SA_OAuthTwitterEngine Ben Gottlieb.
//
//  Some code and concepts taken from examples provided by
//  Matt Gemmell, Chris Kimpton, and Isaiah Carew
//  See ReadMe for further attributions, copyrights and license info.
//

#import "MGTwitterHTTPURLConnection.h"

#import "OAConsumer.h"
#import "OAMutableURLRequest.h"
#import "OADataFetcher.h"
#import "OAAsynchronousDataFetcher.h"
#import "OAToken.h"

#import "XAuthTwitterEngine.h"
#import "ExchangeCredentialsOperation.h"

@interface XAuthTwitterEngine (private)

- (void) requestURL:(NSURL *) url token:(OAToken *)token onSuccess:(SEL)success onFail:(SEL)fail;

- (void) setRequestToken: (OAServiceTicket *) ticket withData: (NSData *) data;
- (void) setAccessToken: (OAServiceTicket *) ticket withData: (NSData *) data;

- (NSString *) extractUsernameFromHTTPBody:(NSString *)body;

// MGTwitterEngine impliments this
// include it here just so that we
// can use this private method
- (NSString *)_queryStringWithBase:(NSString *)base parameters:(NSDictionary *)params prefixed:(BOOL)prefixed;

@end

@implementation XAuthTwitterEngine

@synthesize accessTokenURL = _accessTokenURL;
@synthesize consumerSecret = _consumerSecret, consumerKey = _consumerKey;
@synthesize accessToken = _accessToken;
@synthesize operationQueue = _operationQueue;

- (void) dealloc {
	self.accessTokenURL = nil;

	[self.operationQueue cancelAllOperations];
	[self.operationQueue release];

	[_accessToken release];
	[_consumer release];
	[super dealloc];
}

+ (XAuthTwitterEngine *) XAuthTwitterEngineWithDelegate: (NSObject *) delegate {
    return [[[XAuthTwitterEngine alloc] initXAuthWithDelegate: delegate] autorelease];
}

- (XAuthTwitterEngine *) initXAuthWithDelegate: (NSObject *) delegate {
    if (self = (id) [super initWithDelegate: delegate]) {
		self.accessTokenURL = [NSURL URLWithString: @"http://twitter.com/oauth/access_token"];
		self.operationQueue = [[NSOperationQueue alloc] init];
	}
    return self;
}

//=============================================================================================================================

#pragma mark OAuth Code
- (BOOL) OAuthSetup {
	return _consumer != nil;
}

- (OAConsumer *) consumer {
	if (_consumer) return _consumer;

	NSAssert(self.consumerKey.length > 0 && self.consumerSecret.length > 0, @"You must first set your Consumer Key and Consumer Secret properties. Visit http://twitter.com/oauth_clients/new to obtain these.");
	_consumer = [[OAConsumer alloc] initWithKey: self.consumerKey secret: self.consumerSecret];
	return _consumer;
}

- (BOOL) isAuthorized {
	if (_accessToken.key && _accessToken.secret) return YES;

	//first, check for cached creds
	NSString *accessTokenString = [_delegate respondsToSelector: @selector(cachedTwitterXAuthAccessTokenStringForUsername:)] ? [(id) _delegate cachedTwitterXAuthAccessTokenStringForUsername: self.username] : @"";

	if (accessTokenString.length) {
		[_accessToken release];
		_accessToken = [[OAToken alloc] initWithHTTPResponseBody: accessTokenString];
		[self setUsername: [self extractUsernameFromHTTPBody: accessTokenString] password: nil];
		if (_accessToken.key && _accessToken.secret) return YES;
	}

	[_accessToken release];										// no access token found.  create a new empty one
	_accessToken = [[OAToken alloc] initWithKey: nil secret: nil];
	return NO;
}

/*
//this is what we eventually want
- (void) requestAccessToken {
	[self requestURL: self.accessTokenURL token: _requestToken onSuccess: @selector(setAccessToken:withData:) onFail: @selector(outhTicketFailed:data:)];
}
*/

- (void) clearAccessToken {
	if ([_delegate respondsToSelector: @selector(storeCachedTwitterXAuthAccessTokenString:forUsername:)]) [(id) _delegate storeCachedTwitterXAuthAccessTokenString: @"" forUsername: self.username];
	[_accessToken release];
	_accessToken = nil;
	[_consumer release];
	_consumer = nil;
}

/*
- (void) setPin: (NSString *) pin {
	[_pin autorelease];
	_pin = [pin retain];

	_accessToken.pin = pin;
	_requestToken.pin = pin;
}
*/

#pragma mark -
#pragma mark Public xAuth methods

//
// Attempts to retrieve an xAuthAccessToken for the passed username and password
//
-(void)exchangeAccessTokenForUsername:(NSString *)username password:(NSString *)password
{
	//
	// Doing this as an operation that uses the synchronous OADataFetcher instead of using
	// the asynchronous OAAsynchronousDataFetcher since the latter doesn't fire the
	// fail handler when the credential exchange fails with Twitter for some reason.
	// Other (non-twitter errors) fire, so I guess something is messed up when the class
	// is used with Twitter's xAuth implementation. Oh well...
	//
	ExchangeCredentialsOperation *exchangeCredentialsOperation = [[ExchangeCredentialsOperation alloc] init];
	exchangeCredentialsOperation.username = username;
	exchangeCredentialsOperation.password = password;
	exchangeCredentialsOperation.delegate = self;
	exchangeCredentialsOperation.consumer = self.consumer;
	[self.operationQueue addOperation:exchangeCredentialsOperation];
	[exchangeCredentialsOperation release];
}

//
// Cancels the asynchronous xAuth token exchange process.
//
-(void)cancelAccessTokenExchange
{
	[self.operationQueue cancelAllOperations];
}

//
// Sets the xAuth token directly from a token string.
//
- (void)setAccessTokenFromTokenString:(NSString *)tokenString
{
	NSString *username = [self extractUsernameFromHTTPBody:tokenString];

	if (username.length > 0) {
		[self setUsername: username password: nil];
		if ([_delegate respondsToSelector: @selector(storeCachedTwitterXAuthAccessTokenString:forUsername:)]) [(id) _delegate storeCachedTwitterXAuthAccessTokenString: tokenString forUsername: username];
	}

	[_accessToken release];
	_accessToken = [[OAToken alloc] initWithHTTPResponseBody:tokenString];

}

#pragma mark -
#pragma mark Private XAuth methods

//
// Access token fetch failed.
//

- (void) accessTokenTicket:(OAServiceTicket *)ticket didFailWithError:(NSError *) error {
	if ([_delegate respondsToSelector: @selector(twitterXAuthConnectionDidFailWithError:)]) [(id) _delegate twitterXAuthConnectionDidFailWithError: error];
}

//
// access token callback
// when twitter sends us an access token this callback will fire
// we store it in our ivar as well as writing it to the keychain
//
/*
- (void) setAccessToken: (OAServiceTicket *) ticket withData: (NSData *) data {
	if (!ticket.didSucceed || !data) return;

	NSString *dataString = [[[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding] autorelease];
	if (!dataString) return;

	[self setAccessTokenFromTokenString:dataString];

}
*/

- (NSString *) extractUsernameFromHTTPBody: (NSString *) body {
	if (!body) return nil;

	NSArray					*tuples = [body componentsSeparatedByString: @"&"];
	if (tuples.count < 1) return nil;

	for (NSString *tuple in tuples) {
		NSArray *keyValueArray = [tuple componentsSeparatedByString: @"="];

		if (keyValueArray.count == 2) {
			NSString				*key = [keyValueArray objectAtIndex: 0];
			NSString				*value = [keyValueArray objectAtIndex: 1];

			if ([key isEqualToString:@"screen_name"]) return value;
		}
	}

	return nil;
}

//=============================================================================================================================
#pragma mark MGTwitterEngine Changes
//These are all verbatim from Isaiah Carew and Chris Kimpton's code

// --------------------------------------------------------------------------------
//
// these method overrides were created from the work that Chris Kimpton
// did.  i've chosen to subclass instead of directly modifying the
// MGTwitterEngine as it makes integrating MGTwitterEngine changes a bit
// easier.
//
// the code here is largely unchanged from chris's implimentation.
// i've tried to highlight the areas that differ from
// the base class implimentation.
//
// --------------------------------------------------------------------------------

#define SET_AUTHORIZATION_IN_HEADER 1

- (NSString *)_sendRequestWithMethod:(NSString *)method
                                path:(NSString *)path
                     queryParameters:(NSDictionary *)params
                                body:(NSString *)body
                         requestType:(MGTwitterRequestType)requestType
                        responseType:(MGTwitterResponseType)responseType
{
    NSString *fullPath = path;

	// --------------------------------------------------------------------------------
	// modificaiton from the base clase
	// the base class appends parameters here
	// --------------------------------------------------------------------------------
	//    if (params) {
	//        fullPath = [self _queryStringWithBase:fullPath parameters:params prefixed:YES];
	//    }
	// --------------------------------------------------------------------------------

    NSString *urlString = [NSString stringWithFormat:@"%@://%@/%@",
                           (_secureConnection) ? @"https" : @"http",
                           _APIDomain, fullPath];
    NSURL *finalURL = [NSURL URLWithString:urlString];
    if (!finalURL) {
        return nil;
    }

	//
	// Check if we're authorized. If not don't carry out the request.
	// Note: This will result in the delegate callback for the cached request token
	// ===== to be called if it doesn't already exist.
	//
	if (![self isAuthorized])
	{
		return nil;
	}

	// --------------------------------------------------------------------------------
	// modificaiton from the base clase
	// the base class creates a regular url request
	// we're going to create an oauth url request
	// --------------------------------------------------------------------------------
	//    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:finalURL
	//                                                              cachePolicy:NSURLRequestReloadIgnoringCacheData
	//                                                          timeoutInterval:URL_REQUEST_TIMEOUT];
	// --------------------------------------------------------------------------------
	NSLog(@"About to carry out request with access token: %@", _accessToken);
	OAMutableURLRequest *theRequest = [[[OAMutableURLRequest alloc] initWithURL:finalURL
																	   consumer:self.consumer
																		  token:_accessToken
																		  realm: nil
															  signatureProvider:nil] autorelease];
    if (method) {
        [theRequest setHTTPMethod:method];
    }
    [theRequest setHTTPShouldHandleCookies:NO];

    // Set headers for client information, for tracking purposes at Twitter.
    [theRequest setValue:_clientName    forHTTPHeaderField:@"X-Twitter-Client"];
    [theRequest setValue:_clientVersion forHTTPHeaderField:@"X-Twitter-Client-Version"];
    [theRequest setValue:_clientURL     forHTTPHeaderField:@"X-Twitter-Client-URL"];

    // Set the request body if this is a POST request.
    BOOL isPOST = (method && [method isEqualToString:@"POST"]);
    if (isPOST) {
        // Set request body, if specified (hopefully so), with 'source' parameter if appropriate.
        NSString *finalBody = @"";
		if (body) {
			finalBody = [finalBody stringByAppendingString:body];
		}
        if (_clientSourceToken) {
            finalBody = [finalBody stringByAppendingString:[NSString stringWithFormat:@"%@source=%@",
                                                            (body) ? @"&" : @"?" ,
                                                            _clientSourceToken]];
        }

        if (finalBody) {
            [theRequest setHTTPBody:[finalBody dataUsingEncoding:NSUTF8StringEncoding]];
        }
    }

	// --------------------------------------------------------------------------------
	// modificaiton from the base clase
	// our version "prepares" the oauth url request
	// --------------------------------------------------------------------------------
	[theRequest prepare];
    // Create a connection using this request, with the default timeout and caching policy,
    // and appropriate Twitter request and response types for parsing and error reporting.
    MGTwitterHTTPURLConnection *connection;
    connection = [[MGTwitterHTTPURLConnection alloc] initWithRequest:theRequest
                                                            delegate:self
                                                         requestType:requestType
                                                        responseType:responseType];

    if (!connection) {
        return nil;
    } else {
        [_connections setObject:connection forKey:[connection identifier]];
        [connection release];
    }

    return [connection identifier];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{

	// --------------------------------------------------------------------------------
	// modificaiton from the base clase
	// instead of answering the authentication challenge, we just ignore it.
	// seems a bit odd to me, but this is what Chris Kimpton did and it seems to work,
	// so i'm rolling with it.
	// --------------------------------------------------------------------------------
	//	if ([challenge previousFailureCount] == 0 && ![challenge proposedCredential]) {
	//		NSURLCredential *credential = [NSURLCredential credentialWithUser:_username password:_password
	//															  persistence:NSURLCredentialPersistenceForSession];
	//		[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
	//	} else {
	//		[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
	//	}
	// --------------------------------------------------------------------------------

	[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
	return;

}

@end


text:
try:
    import os
    import sys
    import base64
    import urllib
    import json
    import requests as req
except:
    print("Error: can't import library")

class Kintone:
    '''
    kintone SDK for Python is kintone REST API Library.

    '''
    #initialize
    def __init__(self):
        self.user_auth = {}
        self.token_auth = {}
        self.domain = ''
        self.basic_auth = {}

    #Request Parameters
    ##setting domain name
    def set_domain(self, domain_name):
        self.domain = domain_name

    ##setting Basic Auth information.
    def set_basic_auth(self, id, password):
        self.basic_auth = {
            'id': id,
            'password': password
        }

    #Method for Authentication
    ##setting User Information using for Authentication.
    def set_user_auth(self, login_name, password):
        self.user_auth = {
            'login_name': login_name,
            'password': password
        }

    ##setting API-Token Auth information.
    def set_token_auth(self, token):
        self.token_auth = {
            'token': token
        }

    ##setting URL by domain and guest_space_id.
    def make_url(self, api, guest_space_id=''):
        url = ''
        if (not guest_space_id):
            url = 'https://' + self.domain + '/k/v1/' + api + '.json?'
        else:
            url = 'https://' + self.domain + '/k/guest/' + str(guest_space_id) + '/v1/' + api + '.json?'
        return url

    ##setting headers
    def make_headers(self, method, is_json=True):
        headers = {
            'Host': self.domain + ':443'
        }
        #basic auth
        if (self.basic_auth):
            basic_pass = self.basic_auth['id'] + ':' + self.basic_auth['password']
            headers['Authorization'] = 'Basic ' + base64.b64encode(basic_pass.encode('utf-8'))
        #user auth
        if (self.user_auth):
            user_pass = self.user_auth['login_name'] + ':' + self.user_auth['password']
            headers['X-Cybozu-Authorization'] = base64.b64encode(user_pass.encode('utf-8'))
        #API-Token auth
        if (self.token_auth):
            headers['X-Cybozu-API-Token'] = self.token_auth['token']
        #Content-Type
        if (method == 'POST' or method == 'PUT'):
            if (is_json):
                headers['Content-Type'] = 'application/json'
        return headers

    ##adding URL parameters.
    def make_inquiry(self, params):
        inquiry_string = urllib.parse.urlencode(params)
        return inquiry_string

    #Execution REST API
    ##Getting Record.
    def get_record(self, app_id, record_id, guest_space_id=''):
        method = 'GET'
        params = {
            'app': app_id,
            'id': record_id
        }
        try:
            url = self.make_url('record', guest_space_id) + self.make_inquiry(params)
            headers_obj = self.make_headers(method)
        except:
            err = "Error: can't make URL or request headers."
            return err
        try:
            resp = req.request(method, url, headers=headers_obj)
            return json.loads(resp.text)
        except:
            err = 'Error: failed sending request.'
            #print(err)
            return err

    ##Getting Records by query.
    def get_records(self, app_id, query='', fields=[], all_records=False, guest_space_id=''):
        method = 'GET'
        params = {
            'app': app_id,
            'totalCount': True
        }
        try:
            headers_obj = self.make_headers(method)
        except:
            err = "Error: can't make request headers."
            return err
        if len(fields) > 100:
            err = 'Error: fields is needed less than 100 items.'
            return err
        if (fields):
            i = 0
            for field in fields:
                params['fields' + '[' + str(i) + ']'] = field
                i += 1
        #All records or not
        limit = 500
        if (all_records == False):
            if(query):
                params['query'] = query + ' limit ' + str(limit)
            else:
                params['query'] = 'limit ' + str(limit)
            try:
                url = self.make_url('records', guest_space_id) + self.make_inquiry(params)
            except:
                err = 'Error: failed sending request.'
                return err
            try:
                resp = req.request(method, url, headers=headers_obj)
                return json.loads(resp.text)
            except:
                err = 'Error: Failed Sending Request.'
                return err
        else:
            response = {
                'records': []
            }
            offset = 0
            while True:
                if(query):
                    params['query'] = query + ' limit ' + str(limit) + ' offset ' + str(offset)
                else:
                    params['query'] =  'limit ' + str(limit) + ' offset ' + str(offset)
                try:
                    url = self.make_url('records', guest_space_id) + self.make_inquiry(params)
                except:
                    err = "Error: can't make URL."
                    return err
                try:
                    resp = req.request(method, url, headers=headers_obj)
                    tmp_resp = json.loads(resp.text)
                    #Error:
                    if ('errors' in tmp_resp):
                        return tmp_resp
                    #Success:
                    for record in tmp_resp['records']:
                        response['records'].append(record)
                    if len(tmp_resp['records']) < limit:
                        break
                    else:
                        offset += limit
                except:
                    err = 'Error: failed sending request.'
                    return err
            return response

    ##Deleting Records
    def delete_records(self, app_id, record_ids, guest_space_id=''):
        method = 'DELETE'
        params = {
            'app': app_id
        }
        if (len(record_ids) > 100):
            err = 'Error: record_ids is needed less than 100 items.'
            return err
        if (record_ids):
            i = 0
            for id in record_ids:
                params['ids' + '[' + str(i) + ']'] = id
                i += 1
        try:
            url = self.make_url('records', guest_space_id) + self.make_inquiry(params)
            headers_obj = self.make_headers(method)
        except:
            err = "Error: can't make URL or request headers."
            return err
        try:
            resp = req.request(method, url, headers=headers_obj)
            return json.loads(resp.text)
        except:
            err = 'Error: failed sending request.'
            return err

    ##Post Record.
    def post_record(self, app_id, record={}, guest_space_id=''):
        method = 'POST'
        params = {
            'app': app_id
        }
        if (record):
            params['record'] = record
        try:
            url = self.make_url('record', guest_space_id)
            headers_obj = self.make_headers(method)
        except:
            err = "Error: can't make URL or request headers."
            #print(err)
            return err
        try:
            resp = req.request(method, url, data=json.dumps(params), headers=headers_obj)
            response = json.loads(resp.text)
            return response
        except:
            err = 'Error: failed sending request.'
            return err

    ##Post Records.
    def post_records(self, app_id, records, guest_space_id=''):
        if (len(records) > 100):
            err = 'Error: records is needed less than 100 items.'
            return err
        method = 'POST'
        params = {
            'app': app_id,
            'records': records
        }
        try:
            url = self.make_url('records', guest_space_id)
            headers_obj = self.make_headers(method)
        except:
            err = "Error: can't make URL or request headers."
            return err
        try:
            resp = req.request(method, url, data=json.dumps(params), headers=headers_obj)
            response = json.loads(resp.text)
            return response
        except:
            err = 'Error: failed sending request.'
            return err

    ##Put Record.
    def put_record(self, app_id, record_id, record={}, guest_space_id=''):
        method = 'PUT'
        params = {
            'app': app_id,
            'id': record_id
        }
        if (record):
            params['record'] = record
        try:
            url = self.make_url('record', guest_space_id)
            headers_obj = self.make_headers(method)
        except:
            err = "Error: can't make URL or request headers."
            return err
        try:
            resp = req.request(method, url, data=json.dumps(params), headers=headers_obj)
            response = json.loads(resp.text)
            return response
        except:
            err = 'Error: failed sending request.'
            return err

    ##Post Records.
    def put_records(self, app_id, records, guest_space_id=''):
        method = 'PUT'
        params = {
            'app': app_id,
            'records': records
        }
        if (len(records) > 100):
            err = 'Error: records is needed less than 100 items.'
            return err
        try:
            url = self.make_url('records', guest_space_id)
            headers_obj = self.make_headers(method)
        except:
            err = "Error: can't make URL or request headers."
            return err
        try:
            resp = req.request(method, url, data=json.dumps(params), headers=headers_obj)
            response = json.loads(resp.text)
            return response
        except:
            err = 'Error: failed sending request.'
            return err

    ##Download File
    def download_file(self, file_key=''):
        method = 'GET'
        if (not file_key):
            return 'fileKey is needed.'
        params = {
            'fileKey': file_key
        }
        try:
            url = self.make_url('file') + self.make_inquiry(params)
            headers_obj = self.make_headers(method)
        except:
            err = "Error: can't make URL or request headers."
            return err
        try:
            print(url)
            resp = req.request(method, url, headers=headers_obj)
            return resp.content # this is bytes.
        except:
            err = 'Error: failed sending request.'
            return err

    ##Upload File
    def upload_file(self, file_name, binary):
        method = 'POST'
        try:
            url = self.make_url('file')
            headers_obj = self.make_headers(method, False)
        except:
            err = "Error: can't make URL or request headers."
            return err
        try:
            files = {'file': (file_name, binary, 'application/octet-stream')}
            resp = req.request(method, url, files=files, headers=headers_obj)
            return json.loads(resp.text)
        except:
            err = 'Error: failed sending request.'
            return err


text:
""" This module retrieves dem from https://urs.earthdata.nasa.gov based on extent of positions
listed in a 3 column points file (pk, lon, lat).
parse credentials file ~/.netrc to get required user/pwd.
setup user here: https://urs.earthdata.nasa.gov/profile

Example:
        as script:
        $ python domainPlot.py "/home/joel/sim/topomap_test/" "TRUE"

        or, as import:

        import domainPlot as dplot
        dplot.main("/home/joel/sim/topomap_test/" , "TRUE")

Attributes:
    wd = "/home/joel/sim/topomap_test/"
    plotshp = TRUE

Todo:

"""
path2script = "./rsrc/domainPlot.R"

# main
def main(wd, plotshp):
    """Main entry point for the script."""
    run_rscript_fileout(path2script,[wd, plotshp])

# functions
def run_rscript_stdout(path2script , args):
    """ Function to define comands to run an Rscript. Returns an object. """
    import subprocess
    command = 'Rscript'
    cmd     = [command, path2script] + args
    print("Running:" + str(cmd))
    x = subprocess.check_output(cmd, universal_newlines=True)
    return(x)

def run_rscript_fileout(path2script , args):
    """ Function to define comands to run an Rscript. Outputs a file. """
    import subprocess
    command = 'Rscript'
    cmd     = [command, path2script] + args
    print("Running:" + str(cmd))
    subprocess.check_output(cmd)

# calling main
if __name__ == '__main__':
    import sys
    wd         = sys.argv[1]
    plotshp = sys.argv[2]

    main(wd, plotshp)


text:
export function timeToString(dateTime: number) {
  let secondsSince = (Date.now() - dateTime) / 1000;
  let unit = 'second';
  if (secondsSince > 60) {
    secondsSince = secondsSince / 60;
    unit = 'minute';

    if (secondsSince > 60) {
      secondsSince = secondsSince / 60;
      unit = 'hour';

      if (secondsSince > 24) {
        secondsSince = secondsSince / 24;
        unit = 'day';

        if (secondsSince > 365) {
          secondsSince = secondsSince / 365;
          unit = 'year';
        } else if (secondsSince > 30) {
          secondsSince = secondsSince / 30;
          unit = 'month';
        }
      }
    }
  }

  const timeStr = (secondsSince).toFixed(0);
  if (timeStr !== '1') {
    unit += 's';
  }
  return `${timeStr} ${unit} ago`;
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.time;

import com.yahoo.concurrent.UncheckedTimeoutException;

import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;

/**
 * A TimeBudget can be used to track the time of an ongoing operation, possibly with a timeout.
 *
 * @author hakon
 */
public class TimeBudget {

    private final Clock clock;
    private final Instant start;
    private final Optional<Duration> timeout;

    /** Returns a TimeBudget with a start time of now, and with the given timeout. */
    public static TimeBudget fromNow(Clock clock, Duration timeout) {
        return new TimeBudget(clock, clock.instant(), Optional.of(timeout));
    }

    public static TimeBudget from(Clock clock, Instant start, Optional<Duration> timeout) {
        return new TimeBudget(clock, start, timeout);
    }

    private TimeBudget(Clock clock, Instant start, Optional<Duration> timeout) {
        this.clock = clock;
        this.start = start;
        this.timeout = timeout.map(TimeBudget::makeNonNegative);
    }

    /** Returns time since start. */
    public Duration timePassed() {
        return nonNegativeBetween(start, clock.instant());
    }

    /** Returns the original timeout, if any. */
    public Optional<Duration> originalTimeout() {
        return timeout;
    }

    /** Returns the deadline, if present. */
    public Optional<Instant> deadline() {
        return timeout.map(start::plus);
    }

    /**
     * Returns the time until deadline, if there is one.
     *
     * @return time until deadline. It's toMillis() is guaranteed to be positive.
     * @throws UncheckedTimeoutException if the deadline has been reached or passed.
     */
    public Optional<Duration> timeLeftOrThrow() {
        return timeout.map(timeout -> {
            Duration passed = timePassed();
            Duration left = timeout.minus(passed);
            if (left.toMillis() <= 0) {
                throw new UncheckedTimeoutException("Time since start " + passed + " exceeds timeout " + timeout);
            }

            return left;
        });
    }

    /** Returns the time left, possibly negative if the deadline has passed. */
    public Optional<Duration> timeLeft() {
        return timeout.map(timeout -> timeout.minus(timePassed()));
    }

    /** Returns the time left as a new TimeBudget. */
    public TimeBudget timeLeftAsTimeBudget() {
        Instant now = clock.instant();
        return new TimeBudget(clock, now, deadline().map(d -> Duration.between(now, d)));
    }

    /** Returns a new TimeBudget with the same clock and start, but with this deadline. */
    public TimeBudget withDeadline(Instant deadline) {
        return new TimeBudget(clock, start, Optional.of(Duration.between(start, deadline)));
    }

    /** Returns a new TimeBudget with the given duration chopped off, reserved for something else. */
    public TimeBudget withReserved(Duration chunk) {
        return timeout.isEmpty() ? this : new TimeBudget(clock, start, Optional.of(timeout.get().minus(chunk)));
    }

    private static Duration nonNegativeBetween(Instant start, Instant end) {
        return makeNonNegative(Duration.between(start, end));
    }

    private static Duration makeNonNegative(Duration duration) {
        return duration.isNegative() ? Duration.ZERO : duration;
    }

}


text:
package com.github.davidmoten.rx.internal.operators;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.junit.Test;

import com.github.davidmoten.rx.Actions;
import com.github.davidmoten.rx.Transformers;
import com.github.davidmoten.rx.testing.TestingHelper;

import rx.Observable;
import rx.functions.Func1;

public class OnSubscribeMapLastTest {

    @Test
    public void testMapLastRequestAmount() {
        List<Long> list = new ArrayList<Long>();
        Observable.range(1, 10) //
                .doOnRequest(Actions.addTo(list))//
                .compose(Transformers.mapLast(new Func1<Integer, Integer>() {
                    @Override
                    public Integer call(Integer x) {
                        return x + 1;
                    }
                })).to(TestingHelper.<Integer>testWithRequest(1)) //
                .assertNotCompleted() //
                .assertValuesAndClear(1) //
                .requestMore(3) //
                .assertValues(2, 3, 4);
        assertEquals(Arrays.asList(2L, 3L), list);
    }

    @Test
    public void testMapLastHandlesRequestOverflow() {
        List<Long> list = new ArrayList<Long>();
        Observable.range(1, 5) //
                .doOnRequest(Actions.addTo(list))//
                .compose(Transformers.mapLast(new Func1<Integer, Integer>() {
                    @Override
                    public Integer call(Integer x) {
                        return x + 1;
                    }
                })).to(TestingHelper.<Integer>testWithRequest(Long.MAX_VALUE)) //
                .assertCompleted() //
                .assertValues(1, 2, 3, 4, 6);
        assertEquals(Arrays.asList(Long.MAX_VALUE), list);
    }

    @Test(expected = OutOfMemoryError.class)
    public void testMapLastHandlesFatalError() {
        Observable.range(1, 5) //
                .compose(Transformers.mapLast(new Func1<Integer, Integer>() {
                    @Override
                    public Integer call(Integer x) {
                        throw new OutOfMemoryError();
                    }
                })).subscribe();
    }

    @Test
    public void testMapLastHandlesNonFatalError() {
        final RuntimeException e = new RuntimeException();
        Observable.range(1, 5) //
                .compose(Transformers.mapLast(new Func1<Integer, Integer>() {
                    @Override
                    public Integer call(Integer x) {
                        throw e;
                    }
                })).to(TestingHelper.<Integer>test()) //
                .assertError(e);
    }

}


text:
<project name = "ZAP" basedir="." default="run">

	<property name="targetHost" value="http://localhost:8080/bodgeit/" />
	<property name="targetApp" value="${targetHost}zap-wave/" />
	<property name="bin" value="bin" />
	<property name="build" value="build" />
	<property name="src" value="." />
	<property name="lib" value="lib" />
    <property file="local.properties"/>
	<property name="zapaddr" value="localhost" />
	<property name="zapport" value="8090" />
	<property name="zapjar" value="${lib}/zap-api-v2-8.jar" />

    <taskdef name="AccessURL" classname="org.zaproxy.clientapi.ant.AccessUrlTask" classpath="${lib}/zap-api-v2-8.jar" />
    <taskdef name="ActiveScanURL" classname="org.zaproxy.clientapi.ant.ActiveScanUrlTask" classpath="${lib}/zap-api-v2-8.jar" />
    <taskdef name="ActiveScanSite" classname="org.zaproxy.clientapi.ant.ActiveScanSubtreeTask" classpath="${lib}/zap-api-v2-8.jar" />
    <taskdef name="VulnerabilityAssessment" classname="org.zaproxy.clientapi.ant.AlertCheckTask" classpath="${lib}/zap-api-v2-8.jar" />
    <taskdef name="loadSessionTask" classname="org.zaproxy.clientapi.ant.LoadSessionTask" classpath="${lib}/zap-api-v2-8.jar" />
    <taskdef name="NewZAPSession" classname="org.zaproxy.clientapi.ant.NewSessionTask" classpath="${lib}/zap-api-v2-8.jar" />
    <taskdef name="SaveZAPSession" classname="org.zaproxy.clientapi.ant.SaveSessionTask" classpath="${lib}/zap-api-v2-8.jar" />
    <taskdef name="SpiderURL" classname="org.zaproxy.clientapi.ant.SpiderUrlTask" classpath="${lib}/zap-api-v2-8.jar" />
    <taskdef name="stopZapTask" classname="org.zaproxy.clientapi.ant.StopZapTask" classpath="${lib}/zap-api-v2-8.jar" />
    <taskdef name="alert" classname="org.zaproxy.clientapi.ant.AlertTask" classpath="${lib}/zap-api-v2-8.jar" />

	<path id="3rd-party-classpath">
	    <fileset dir="${lib}">
	        <include name="**/*.jar" />
	    </fileset>
	</path>

	<target name="build">
	    <javac includeantruntime="false" srcdir="${src}" destdir="${build}">
	    	<classpath refid="3rd-party-classpath" />
	    </javac>
		<javac includeantruntime="false" srcdir="${src}" destdir="${bin}">
			    	<classpath refid="3rd-party-classpath" />
		</javac>
	</target>

	<target name="run">
	    <java classname="com_test.BodgeITTest">
	      <classpath>
	        <pathelement location="${build}" />
	        <path refid="3rd-party-classpath" />
	      </classpath>
	    </java>
	</target>

	<target name="clean">
		<delete>
			<fileset dir="." includes="**/*.txt" />
			<fileset dir="." includes="**/*.log" />
			<fileset dir="." includes="**/*.lck" />
			<fileset dir="." includes="**/*.data" />
	    </delete>
	</target>

	<target name="startZap">
        <java classname="org.zaproxy.zap.ZAP" fork="true" spawn="true" dir="${lib}">
            <arg value="-port"/>
            <arg value="${zapport}"/>
            <arg value="-dir"/>
            <arg value="${zaphome}"/>
            <classpath>
                    <pathelement location="${lib}/zap-api-v2-8.jar"/>
            </classpath>
        </java>
	</target>

    <target name="startZapDaemon">
        <java classname="org.zaproxy.zap.ZAP" fork="true" spawn="true" dir="${lib}">
            <arg value="-daemon"/>
            <arg value="-port"/>
            <arg value="${zapport}"/>
            <arg value="-dir"/>
            <arg value="${lib}"/>
            <classpath>
                    <pathelement location="${lib}/zap-api-v2-8.jar"/>
            </classpath>
        </java>
    </target>

    <target name="stopZap">
        <stopZapTask zapAddress="${zapaddr}" zapPort="${zapport}" debug="true"/>
    </target>

	<target name="ZAPDemo">
		<antcall target="build" />

		<antcall target="startZap" />

		<antcall target="startZapDaemon" />

		<NewZAPSession zapAddress="${zapaddr}" zapPort="${zapport}" debug="true" />

		<antcall target="clean" />

		<AccessURL zapAddress="${zapaddr}" zapPort="${zapport}" url="${targetHost}" debug="true"/>

		<SpiderURL zapAddress="${zapaddr}" zapPort="${zapport}" url="${targetHost}" debug="true"/>

		<record name="Report.txt" action="start" append="true" />
		<antcall target="run" />
		<record name="Report.txt" action="stop" />

		<ActiveScanURL zapAddress="${zapaddr}" zapPort="${zapport}" url="${targetHost}" debug="true"/>
		<sleep seconds="10"/>

		<ActiveScanSite zapAddress="${zapaddr}" zapPort="${zapport}" url="${targetHost}" debug="true"/>

		<tstamp>
        	<format property="timestamp" pattern="MM-dd-yyyy HH-mm-ss"/>
        </tstamp>
        <SaveZAPSession zapAddress="${zapaddr}" zapPort="${zapport}" name="${user.dir}/test ${timestamp}" debug="true"/>

		<record name="Report.txt" action="start" append="true" />
		<VulnerabilityAssessment zapAddress="${zapaddr}" zapPort="${zapport}" debug="true">
            <ignoreAlert alert="Cookie set without HttpOnly flag" />
            <ignoreAlert alert="X-Content-Type-Options header missing" />
            <ignoreAlert alert="X-Frame-Options header not set" />
			<ignoreAlert alert="Application Error disclosure" />
            <ignoreAlert alert="Cookie set without HttpOnly flag" />
			<ignoreAlert alert="Password Autocomplete in browser" />
        </VulnerabilityAssessment>
		<record name="Report.txt" action="stop" />
        <!--<stopZapTask zapAddress="${zapaddr}" zapPort="${zapport}"/>-->
    </target>

</project>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using AutoMapper;
using EasyRbac.Domain.Entity;
using EasyRbac.Domain.Relations;
using EasyRbac.DomainService.Extentions;
using EasyRbac.Dto.AppResource;
using EasyRbac.Reponsitory.BaseRepository;
using EasyRbac.Reponsitory.Helper;
using EasyRbac.Utils;
using MyUtility.CollectionExtentions;
using MyUtility.Commons.IdGenerate;

namespace EasyRbac.DomainService
{

    public class RoleResourceDomainService : IRoleResourceDomainService
    {
        private IKeyedIdGenerate _keyedIdGenerate;
        private IRepository<RoleResourceRelation> _roleResourceRel;
        private IRepository<AppResourceEntity> _appResourceRepository;
        private IMapper _mapper;
        private IIdGenerator _idGenerator;

        /// <summary>Initializes a new instance of the <see cref="T:System.Object"></see> class.</summary>
        public RoleResourceDomainService(IKeyedIdGenerate keyedIdGenerate, IRepository<RoleResourceRelation> roleResourceRel, IRepository<AppResourceEntity> appResourceRepository, IMapper mapper, IIdGenerator idGenerator)
        {
            this._keyedIdGenerate = keyedIdGenerate;
            this._roleResourceRel = roleResourceRel;
            this._appResourceRepository = appResourceRepository;
            this._mapper = mapper;
            this._idGenerator = idGenerator;
        }

        public async Task<AppResourceDto> GetAppResource(long appId, long roleId)
        {
            var rels = await this._roleResourceRel.QueryAsync(x => x.RoleId == roleId);
            var resourceIds = rels.Select(x => x.ResourceId);
            var resource = this._appResourceRepository.QueryAsync(x =>
                resourceIds.Contains(x.Id) && x.ApplicationId == appId && x.Enable);
            var lst = this._mapper.Map<List<AppResourceDto>>(resource);
            return lst.GenerateTree();
        }

        public async Task<List<string>> GetRoleResourceIds(long appid, params long[] roleId)
        {
            IEnumerable<RoleResourceRelation> rels = await this._roleResourceRel.QueryAsync(x => roleId.Contains(x.RoleId));
            var ids = rels.Select(x => x.ResourceId);
            var appResourceEntities = await this._appResourceRepository.QueryAsync(x => ids.Contains(x.Id) &&x.ApplicationId == appid && x.Enable);
            return appResourceEntities.Select(x => x.Id).ToList();
        }

        public async Task ChangeRoleResource(long roleId,long appId,List<string> newResourceIds)
        {
            using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                var appIds = await this._appResourceRepository.QueryAndSelectAsync<string>(x => x.ApplicationId == appId, x => x.Id);
                IEnumerable<RoleResourceRelation> rels = await this._roleResourceRel.QueryAsync(x => x.RoleId == roleId && appIds.Contains(x.ResourceId));
                var resourceIds = rels.Select(x => x.ResourceId);
                var (addResources,subResources) = resourceIds.CalcluteChange(newResourceIds);
                await this._roleResourceRel.DeleteAsync(x => subResources.Contains(x.ResourceId)&&x.RoleId == roleId);
                foreach (var resourceId in addResources)
                {
                    var rel = new RoleResourceRelation()
                    {
                        Id = this._idGenerator.NewId(),
                        ResourceId = resourceId,
                        RoleId = roleId
                    };
                    await this._roleResourceRel.InsertAsync(rel);
                }
                tran.Complete();
            }
        }
    }
}


text:
@charset "utf-8";

html{height:100%}
body{min-height: 100%;position: relative;font-size:14px;color:#333; background-color:#fff}
a{color:#333}a:hover,a:focus,.maincolor,.maincolor a{color:#06c}
.bg-1{ background-color:#f5fafe}
h4{line-height:30px}
/*页面框架*/
.Hui-header{position:absolute;top:0; right:0; left:0;height:52px;z-index:999;}
.Hui-aside{position: absolute;top:44px;bottom:0;left:0;padding-top:20px;width:222px;z-index:99;overflow:auto; background-color:#eee;border-right: 1px solid #e5e5e5}
.Hui-article-box{position: absolute;top:10px;right:0;bottom: 0;left:222px; z-index:1; background-color:#eee}
	.Hui-article{position: absolute;top:42px;bottom:0;left:0; right:0;overflow:auto;z-index:1}
.Hui-container{ padding:45px 0 0}
.Hui-aside,.Hui-article-box,.dislpayArrow{-moz-transition: all 0.2s ease 0s;-webkit-transition: all 0.2s ease 0s;-ms-transition: all 0.2s ease 0s;-o-transition: all 0.2s ease 0s;transition: all 0.2s ease 0s}
.big-page .Hui-article-box,.big-page .dislpayArrow,.big-page .breadcrumb{left:0px}
.big-page .Hui-aside{ left:-223px;}

/*组件*/
	/*logo*/
	.Hui-logo,.Hui-logo-m{height:52px; margin-left:20px;cursor:pointer;font-size:16px; font-weight:bold; line-height:52px}
	.Hui-logo{display:inline-block;padding-right:5px}
	.Hui-logo:hover,.Hui-logo-m:hover{text-decoration:none; color:#0C0}
	.Hui-logo-m{display:none;width:45px;margin-left:10px}
	.Hui-subtitle{ font-size:12px; color:#eee; padding-top:15px}
	.viewhome{ line-height:44px; padding-right:15px}
	.viewhome a{ color:#FFF; padding-left:20px; background:url(../images/icon_link.png) no-repeat 0 center}

	/*导航*/
	#Hui-nav{ margin-left:200px; margin-right:260px; background-color:transparent}
	#Hui-nav > ul > li{ font-weight:normal}
	#Hui-nav > ul > li,#Hui-nav > ul > li > a{height:52px; line-height:52px}
	#Hui-nav > ul > li > a:hover,#Hui-nav > ul > li.current > a{ background-color:rgba(255,255,255,0.2)}
	.Hui-userbar{ position:absolute; top:0px; right:20px}
	.Hui-userbar > li{ float:left; display:inline-block; position:relative;line-height:52px}
	.Hui-userbar > li > a{ display:inline-block; padding:0 10px;height:52px; line-height:52px}
	.Hui-userbar > li > a:hover,Hui-userbar > li.current > a{ text-decoration:none;background-color:rgba(255,255,255,0.2)}
	#Hui-msg .badge{ position:absolute; left:19px; top:10px; font-size:12px; font-weight:normal; padding:1px 5px}
	/*左侧菜单*/
	.Hui-aside .menu_dropdown h2{line-height:62px;padding-left:15px;cursor:pointer;position:relative;border-bottom: 1px solid #e5e5e5;font-weight:normal; font-weight:400; font-size: 14px; padding:0px;}
	.Hui-aside .menu_dropdown dl{ margin-bottom:0}
	.Hui-aside .menu_dropdown dt{display:block;line-height:62px;padding-left:15px;cursor:pointer;position:relative;border-bottom: 1px solid #e5e5e5;font-weight:normal}
	.Hui-aside .menu_dropdown dt .menu_dropdown-arrow{ position:absolute;overflow: hidden; top:0; right:15px;transition-duration:0.3s ;transition-property:all}
	.Hui-aside .menu_dropdown dd{ display:none}
	.Hui-aside .menu_dropdown dt.selected .menu_dropdown-arrow{transform: rotate(180deg)}
	.Hui-aside .menu_dropdown dd.selected{display:block; margin-left:0px}
	.Hui-aside .menu_dropdown ul{padding:0px}
	.Hui-aside .menu_dropdown li{line-height:35px;overflow:hidden;zoom:1}
	.Hui-aside .menu_dropdown li a{padding-left:15px; display:block;font-weight: bold; margin:0}
	.Hui-aside .menu_dropdown li a i{ font-weight: normal}
	.Hui-aside .menu_dropdown dd ul{padding:3px 8px}
	.Hui-aside .menu_dropdown dd li{line-height:32px}
	.Hui-aside .menu_dropdown dd li a{line-height:38px;padding-left:26px; border-bottom:none; font-weight:normal}
	.Hui-aside .menu_dropdown li a:hover{text-decoration:none}
	.Hui-aside .menu_dropdown li.current a,.menu_dropdown li.current a:hover{background-color:rgba(255,255,255,0.2)}
	/*菜单收缩切换*/
	.dislpayArrow{position: absolute;top: 0;bottom: 0;left:223px;width:0px; height:100%;z-index:10}
	.dislpayArrow a{ position:absolute; display:block; width:17px; height:61px;top:50%; margin-top:-30px;outline:none}
	.dislpayArrow a.open{ background-position:0 -61px}
	.dislpayArrow a:hover{ text-decoration:none; background-position:right 0}
	.dislpayArrow a.open:hover{background-position:right -61px}

	/*选项卡导航*/
	.Hui-tabNav{height:35px; padding-right:75px;overflow:hidden; position:relative;background:#efeef0 url(../images/acrossTab-2.png) repeat-x 0 -175px;}
	.Hui-tabNav-wp{position:relative; height:35px;overflow:hidden}
	.Hui-tabNav .acrossTab{ position:absolute; height:26px; line-height:26px; background:none; top:8px; left:0;padding-top:0}
	.Hui-tabNav .acrossTab li,.Hui-tabNav .acrossTab li em{background-image:url(../images/acrossTab-2.png)}
	.Hui-tabNav .acrossTab li{height:26px;line-height:26px;}
	.Hui-tabNav .acrossTab li em{ right:-16px; height: 26px; width: 16px}
	.loading {background:url(../images/loading.gif) no-repeat center; height:100px}
	.show_iframe iframe {position: absolute;bottom: 0;height: 100%;width: 100%}
	.Hui-tabNav-more {position: absolute;right:0px;width:70px;top:4px;display: none}

	/*面包屑导航*/
	.breadcrumb{background-color:#F5F5F5}

	/*页脚
		Name:			mod_footer
		Level:			Global
		Sample:
意见反馈|关于XX|诚聘英才
Copyright ©2012 guojunhui.com 郭俊辉版权所有 京ICP备10046298-4号

		Explain:页脚
		Last Modify:	jackying
	*/
	.footer{border-top:1px solid #E8E8E8;margin-top:20px;font-family:tahoma,Arial;font-size:12px;color:#999;line-height:22px;text-align:center}
	.footer p{padding-top:15px}
	.footer a,.footer a:hover{color:#999}
/*横向手机 竖向平板*/
@media (max-width: 767px) {
	html{ overflow-y:auto}
	#Hui-nav{margin-left:130px!important; margin-right:60px}
	#Hui-nav > ul > li{width:24%;font-weight:bold;font-size:16px}
	#Hui-nav > ul > li > a { display: block; padding: 0}
	.Hui-aside{ display:none;float:none; width:100%; height:auto; margin-top:0;padding-top:0;bottom:auto}
	.big-page .Hui-aside{ left:0!important}
	.Hui-subtitle,.dislpayArrow,.Hui-userbar,.Hui-tabNav{ display:none}
		.menu_dropdown dt{line-height:44px}
		.menu_dropdown li,.menu_dropdown dd li,.menu_dropdown dd li a{ line-height:44px}
  .Hui-tabNav{ position:fixed; z-index:998}
  .Hui-article{ top:44px}
  .Hui-article-box{ position:static; left:0}
  .Hui-article-box .pd-20{padding:20px 10px}
		.Hui-article{left:0}
		.Hui-container .bk-gray{ border:none}
		.Hui-container .pd-10{ padding:0}
}
/*竖向手机*/
@media (max-width: 480px) {
	#Hui-nav{margin-left:50px!important;margin-right:60px}
		.Hui-logo{ display:none}
		.Hui-logo-m{ display:inline-block; padding-right:5px}
		.Hui-subtitle,.dislpayArrow,.Hui-userbar{ display:none}
}

/*==============以下是业务相关的样式====================*/
/*权限*/
.permission-list{ border:solid 1px #eee;}
.permission-list > dt{ background-color:#efefef;padding:5px 10px}
.permission-list > dd{ padding:10px; padding-left:30px}
.permission-list > dd > dl{ border-bottom:solid 1px #eee; padding:5px 0}
.permission-list > dd > dl > dt{ display:inline-block;float:left;white-space:nowrap;width:100px}
.permission-list > dd > dl > dd{ margin-left:100px;}
.permission-list > dd > dl > dd > label{ padding-right:10px}

/*图片预览*/
.portfolio-area{ margin-right: -20px;}
.portfolio-area li{position: relative; float: left; margin-right: 20px; width:162px; height:162px;margin-top: 20px;}
.portfolio-area li.hover{ z-index:9}
.portfolio-area li .portfoliobox{ position: absolute; top: 0; left: 0; width: 152px; height: 152px;padding:5px;border: solid 1px #eee; background-color: #fff;}
.portfolio-area li .checkbox{position: absolute; top: 10px; right: 5px; cursor:pointer}
.portfolio-area li.hover .portfoliobox{ height:auto;padding-bottom:10px;box-shadow:0 1px 3px rgba(68, 68, 68,0.3);-moz-box-shadow:0 1px 3px rgba(68, 68, 68,0.3);-webkit-box-shadow:0 1px 3px rgba(68, 68, 68,0.3)}
.portfolio-area li .picbox{width: 150px; height: 150px;overflow: hidden;text-align: center;vertical-align:middle;display:table-cell; line-height:150px;}
.portfolio-area li .picbox img{max-width:150px; max-height:150px;vertical-align:middle;_margin-top: expression_r(( 150 - this.height ) / 2);}
.portfolio-area li .textbox{ display: none; margin-top: 5px;}
.portfolio-area li.hover .textbox{ display: block;}
.portfolio-area li label{ display:block; cursor:pointer}


text:
@class UIBezierPath, UIColor;

@interface StrokeView : UIView
{
    UIBezierPath *m_strokePath;
    UIColor *m_strokeColor;
    _Bool m_fill;
    int _blendMode;
}

@property(nonatomic) int blendMode; // @synthesize blendMode=_blendMode;
@property(nonatomic) _Bool fill; // @synthesize fill=m_fill;
@property(retain, nonatomic) UIColor *strokeColor; // @synthesize strokeColor=m_strokeColor;
@property(retain, nonatomic) UIBezierPath *strokePath; // @synthesize strokePath=m_strokePath;
- (void).cxx_destruct;
- (void)drawRect:(struct CGRect)arg1;
- (id)initWithFrame:(struct CGRect)arg1;

@end


text:
define([ 'chai', 'lib/directives/index' ], function(chai, directivesModule) {
  'use strict';

  /* global module:false */

  var expect = chai.expect;

  return describe('camunda-commons-ui/directives', function() {

    beforeEach(module(directivesModule.name));

    describe('bootstrap', function() {

      it('should bootstrap with module', function() { });

    });

  });

});


text:
/*This file contains all styles related to the main of the site/application.*/
.navi {
	position: relative;
	width: 100%;
	background-color: $color-curcooma-800;
	overflow-x: hidden;
	overflow-y: auto;
	order: 0;
  flex: 0 1 auto;
  align-self: stretch;
  overflow: hidden;
}


text:
<?php

namespace Magento\Review\Test\Unit\Model\ResourceModel\Review;

class CollectionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Review\Model\ResourceModel\Review\Collection
     */
    protected $model;

    /**
     * @var \Magento\Framework\DB\Select | \PHPUnit_Framework_MockObject_MockObject
     */
    protected $selectMock;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface | \PHPUnit_Framework_MockObject_MockObject
     */
    protected $storeManagerMock;

    /**
     * @var \Magento\Framework\Model\ResourceModel\Db\AbstractDb | \PHPUnit_Framework_MockObject_MockObject
     */
    protected $resourceMock;

    /**
     * @var \Magento\Framework\DB\Adapter\AdapterInterface | \PHPUnit_Framework_MockObject_MockObject
     */
    protected $readerAdapterMock;

    /**
     * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager
     */
    protected $objectManager;

    protected function setUp()
    {
        $store = $this->getMock('\Magento\Store\Model\Store', ['getId'], [], '', false);
        $store->expects($this->any())->method('getId')->will($this->returnValue(1));
        $this->storeManagerMock = $this->getMock('Magento\Store\Model\StoreManagerInterface');
        $this->storeManagerMock->expects($this->any())->method('getStore')->will($this->returnValue($store));
        $this->objectManager = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this));
        $this->resourceMock = $this->getMockBuilder('Magento\Framework\Model\ResourceModel\Db\AbstractDb')
            ->disableOriginalConstructor()
            ->setMethods(['getConnection', 'getMainTable', 'getTable'])
            ->getMockForAbstractClass();
        $this->readerAdapterMock = $this->getMockBuilder('\Magento\Framework\DB\Adapter\Pdo\Mysql')
            ->disableOriginalConstructor()
            ->setMethods(['select', 'prepareSqlCondition', 'quoteInto'])
            ->getMockForAbstractClass();
        $this->selectMock = $this->getMockBuilder('\Magento\Framework\DB\Select')
            ->disableOriginalConstructor()
            ->getMock();
        $this->readerAdapterMock->expects($this->any())
            ->method('select')
            ->willReturn($this->selectMock);
        $this->resourceMock->expects($this->any())
            ->method('getConnection')
            ->willReturn($this->readerAdapterMock);
        $this->resourceMock->expects($this->any())
            ->method('getMainTable')
            ->willReturn('maintable');
        $this->resourceMock->expects($this->any())
            ->method('getTable')
            ->willReturnCallback(function ($table) {
                return $table;
            });
        $this->model = $this->objectManager->getObject(
            '\Magento\Review\Model\ResourceModel\Review\Collection',
            [
                'storeManager' => $this->storeManagerMock,
                'resource' => $this->resourceMock,
            ]
        );

    }

    public function testInitSelect()
    {
        $this->selectMock->expects($this->once())
            ->method('join')
            ->with(
                ['detail' => 'review_detail'],
                'main_table.review_id = detail.review_id',
                ['detail_id', 'title', 'detail', 'nickname', 'customer_id']
            );
        $this->objectManager->getObject(
            '\Magento\Review\Model\ResourceModel\Review\Collection',
            [
                'storeManager' => $this->storeManagerMock,
                'resource' => $this->resourceMock,
            ]
        );
    }

    public function testAddStoreFilter()
    {
        $this->readerAdapterMock->expects($this->once())
            ->method('prepareSqlCondition');
        $this->selectMock->expects($this->once())
            ->method('join')
            ->with(
                ['store' => 'review_store'],
                'main_table.review_id=store.review_id',
                []
            );
        $this->model->addStoreFilter(1);
    }

    /**
     * @param int|string $entity
     * @param int $pkValue
     * @param string $quoteIntoArguments1
     * @param string $quoteIntoArguments2
     * @param string $quoteIntoReturn1
     * @param string $quoteIntoReturn2
     * @param int $callNum
     * @dataProvider addEntityFilterDataProvider
     */
    public function testAddEntityFilter(
        $entity,
        $pkValue,
        $quoteIntoArguments1,
        $quoteIntoArguments2,
        $quoteIntoReturn1,
        $quoteIntoReturn2,
        $callNum
    ) {
        $this->readerAdapterMock->expects($this->at(0))
            ->method('quoteInto')
            ->with($quoteIntoArguments1[0], $quoteIntoArguments1[1])
            ->willReturn($quoteIntoReturn1);
        $this->readerAdapterMock->expects($this->at(1))
            ->method('quoteInto')
            ->with($quoteIntoArguments2[0], $quoteIntoArguments2[1])
            ->willReturn($quoteIntoReturn2);
        $this->selectMock->expects($this->exactly($callNum))
            ->method('join')
            ->with(
                'review_entity',
                'main_table.entity_id=' . 'review_entity' . '.entity_id',
                ['entity_code']
            );
        $this->model->addEntityFilter($entity, $pkValue);
    }

    public function addEntityFilterDataProvider()
    {
        return [
            [
                1,
                2,
                ['main_table.entity_id=?', 1],
                ['main_table.entity_pk_value=?', 2],
                'quoteIntoReturn1',
                'quoteIntoReturn2',
                0
            ],
            [
                'entity',
                2,
                ['review_entity.entity_code=?', 'entity'],
                ['main_table.entity_pk_value=?', 2],
                'quoteIntoReturn1',
                'quoteIntoReturn2',
                1
            ]
        ];
    }

    public function testAddReviewsTotalCount()
    {
        $this->selectMock->expects($this->once())
            ->method('joinLeft')
            ->with(
                ['r' => 'review'],
                'main_table.entity_pk_value = r.entity_pk_value',
                ['total_reviews' => new \Zend_Db_Expr('COUNT(r.review_id)')]
            )->willReturnSelf();
        $this->selectMock->expects($this->once())
            ->method('group');
        $this->model->addReviewsTotalCount();
    }
}


text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.roots.ui.configuration;

import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.roots.SourceFolder;
import com.intellij.openapi.util.NlsSafe;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.JpsElement;
import org.jetbrains.jps.model.module.JpsModuleSourceRootType;

import javax.swing.*;
import java.awt.*;

/**
 * Inherit from this class and register the implementation as {@code projectStructure.sourceRootEditHandler} extension in plugin.xml to
 * specify how source roots of a custom {@link JpsModuleSourceRootType type} should be shown in Project Structure dialog. There must be only
 * one instance of this class for each {@link JpsModuleSourceRootType}.
 */
public abstract class ModuleSourceRootEditHandler<P extends JpsElement> {
  public static final ExtensionPointName<ModuleSourceRootEditHandler> EP_NAME = ExtensionPointName.create("com.intellij.projectStructure.sourceRootEditHandler");
  private final JpsModuleSourceRootType<P> myRootType;

  protected ModuleSourceRootEditHandler(JpsModuleSourceRootType<P> rootType) {
    myRootType = rootType;
  }

  @Nullable
  public static <P extends JpsElement> ModuleSourceRootEditHandler<P> getEditHandler(@NotNull JpsModuleSourceRootType<P> type) {
    //noinspection unchecked
    return EP_NAME.getExtensionList().stream().filter(editor -> editor.getRootType().equals(type)).findFirst().orElse(null);
  }

  public final JpsModuleSourceRootType<P> getRootType() {
    return myRootType;
  }

  @NotNull
  @Nls(capitalization = Nls.Capitalization.Title)
  public abstract String getRootTypeName();

  @NotNull
  public @Nls String getFullRootTypeName() {
    return ProjectBundle.message("module.paths.root.node", getRootTypeName());
  }

  @NotNull
  public abstract Icon getRootIcon();

  @NotNull
  public Icon getRootIcon(@NotNull P properties) {
    return getRootIcon();
  }

  @Nullable
  public Icon getRootFileLayerIcon() {
    return null;
  }

  @Nullable
  public abstract Icon getFolderUnderRootIcon();

  @Nullable
  public abstract CustomShortcutSet getMarkRootShortcutSet();

  @NotNull
  @Nls(capitalization = Nls.Capitalization.Title)
  public abstract String getRootsGroupTitle();

  @NotNull
  public abstract Color getRootsGroupColor();

  @NotNull
  @Nls(capitalization = Nls.Capitalization.Title)
  public String getMarkRootButtonText() {
    return getRootTypeName();
  }

  @NotNull
  @Nls(capitalization = Nls.Capitalization.Title)
  public abstract String getUnmarkRootButtonText();

  @Nullable
  public @NlsSafe String getPropertiesString(@NotNull P properties) {
    return null;
  }

  @Nullable
  public JComponent createPropertiesEditor(@NotNull SourceFolder folder, @NotNull JComponent parentComponent,
                                           @NotNull ContentRootPanel.ActionCallback callback) {
    return null;
  }
}


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

<title>com.openxc.interfaces.network</title>
<meta name="date" content="2015-06-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.openxc.interfaces.network

Contains a vehicle data source that connects to a vehicle interface via a network.

See: Description

Class Summary

Class
Description

NetworkVehicleInterface

A vehicle data source reading measurements from an OpenXC network device.

Exception Summary

Exception
Description

NetworkSourceException

Package com.openxc.interfaces.network Description

Contains a vehicle data source that connects to a vehicle interface via a network.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
#include "pch.h"

#ifndef CRYPTOPP_IMPORTS

#include "fips140.h"
#include "misc.h"
#include "trdlocal.h"	// needs to be included last for cygwin

NAMESPACE_BEGIN(CryptoPP)

// Define this to 1 to turn on FIPS 140-2 compliance features, including additional tests during
// startup, random number generation, and key generation. These tests may affect performance.
#ifndef CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2
#define CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 0
#endif

#if (CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 && !defined(THREADS_AVAILABLE))
#error FIPS 140-2 compliance requires the availability of thread local storage.
#endif

#if (CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 && !defined(OS_RNG_AVAILABLE))
#error FIPS 140-2 compliance requires the availability of OS provided RNG.
#endif

PowerUpSelfTestStatus g_powerUpSelfTestStatus = POWER_UP_SELF_TEST_NOT_DONE;

bool FIPS_140_2_ComplianceEnabled()
{
	return CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2;
}

void SimulatePowerUpSelfTestFailure()
{
	g_powerUpSelfTestStatus = POWER_UP_SELF_TEST_FAILED;
}

PowerUpSelfTestStatus CRYPTOPP_API GetPowerUpSelfTestStatus()
{
	return g_powerUpSelfTestStatus;
}

#if CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2
ThreadLocalStorage & AccessPowerUpSelfTestInProgress()
{
	static ThreadLocalStorage selfTestInProgress;
	return selfTestInProgress;
}
#endif

bool PowerUpSelfTestInProgressOnThisThread()
{
#if CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2
	return AccessPowerUpSelfTestInProgress().GetValue() != NULL;
#else
	CRYPTOPP_ASSERT(false);	// should not be called
	return false;
#endif
}

void SetPowerUpSelfTestInProgressOnThisThread(bool inProgress)
{
	CRYPTOPP_UNUSED(inProgress);
#if CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2
	AccessPowerUpSelfTestInProgress().SetValue((void *)inProgress);
#endif
}

void EncryptionPairwiseConsistencyTest_FIPS_140_Only(const PK_Encryptor &encryptor, const PK_Decryptor &decryptor)
{
	CRYPTOPP_UNUSED(encryptor), CRYPTOPP_UNUSED(decryptor);
#if CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2
	EncryptionPairwiseConsistencyTest(encryptor, decryptor);
#endif
}

void SignaturePairwiseConsistencyTest_FIPS_140_Only(const PK_Signer &signer, const PK_Verifier &verifier)
{
	CRYPTOPP_UNUSED(signer), CRYPTOPP_UNUSED(verifier);
#if CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2
	SignaturePairwiseConsistencyTest(signer, verifier);
#endif
}

NAMESPACE_END

#endif


text:
import click
import os

from sidr import default
from sidr import runfile

CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])

def validate_taxdump(value, method):
    if (os.path.isfile("%s/%s" % (value, "names.dmp")) and
        os.path.isfile("%s/%s" % (value, "nodes.dmp")) and
        os.path.isfile("%s/%s" % (value, "merged.dmp")) and
        os.path.isfile("%s/%s" % (value, "delnodes.dmp"))):
        return value
    else:
        with click.Context(method) as ctx:
            click.echo(ctx.get_help())
            raise click.BadParameter("Could not find names.dmp in taxdump, specify a value or make sure the files are present")

@click.group()
def cli():
    """
    Analyzes genomic data and attempts to classify contigs using a machine learning framework.

    SIDR uses data fron BLAST (or similar classifiers)to train a Decision Tree model to classify sequence data as either belonging to a target organism, or belonging to something else. This classification can be used to filter the data for later assembly.

    To use SIDR, you will need to construct a preliminary assembly, align your reads back to that assembly, then use BLAST to classify the assembly contigs.
    """
    pass

@cli.command(name="default", context_settings=CONTEXT_SETTINGS)
@click.option('--bam', '-b', type=click.Path(exists=True), help="Alignment of reads to preliminary assembly, in BAM format.")
@click.option('--fasta', '-f', type=click.Path(exists=True), help="Preliminary assembly, in FASTA format.")
@click.option('--blastresults', '-r', type=click.Path(exists=True), help="Classification of preliminary assembly from BLAST (or similar tools).")
@click.option('--taxdump', '-d', type=click.Path(), default=os.environ.get('BLASTDB'), help="Location of the NCBI Taxonomy dump. Default is $BLASTDB.")
#@click.option('--model', '-m', 'modelOutput', type=click.Path(), default="", help="Location to save a graphical representation of the trained decision tree (optional). Output is in the form of a DOT file.")
@click.option('--output', '-o', type=click.Path(), default="%s/classifications.txt" % os.getcwd())
@click.option('--tokeep', '-k', type=click.Path(), default="", help="Location to save the contigs identified as the target organism(optional).")
@click.option('--toremove', '-x', type=click.Path(), default="", help="Location to save the contigs identified as not belonging to the target organism (optional).")
@click.option('--binary', is_flag=True, help="Use binary target/nontarget classification.")
@click.option('--target', '-t', help="The identity of the target organism at the chosen classification level. It is recommended to use the organism's phylum.")
@click.option('--level', '-l', default="phylum", help="The classification level to use when constructing the model. Default is 'phylum'.")
# @click.option('--verbose', '-v', count=True, help="Output more debugging options, repeat to increase verbosity (unimplemented).")
def default_runner(bam, fasta, blastresults, taxdump, output, tokeep, toremove, binary, target, level):
    """
    Runs the default analysis using raw preassembly data.
    """
    modelOutput = False
    validate_taxdump(taxdump, default_runner)
    default.runAnalysis(bam, fasta, blastresults, taxdump, modelOutput, output, tokeep, toremove, binary, target, level)

@cli.command(name="runfile", context_settings=CONTEXT_SETTINGS)
@click.option('--infile', '-i', type=click.Path(exists=True), help="Comma-delimited input file.")
@click.option('--taxdump', '-d', type=click.Path(), default=os.environ.get('BLASTDB'), help="Location of the NCBI Taxonomy dump. Default is $BLASTDB.")
@click.option('--output', '-o', type=click.Path(), default="%s/classifications.txt" % os.getcwd())
#@click.option('--model', '-m', 'modelOutput', type=click.Path(), default="", help="Location to save a graphical representation of the trained decision tree (optional). Output is in the form of a DOT file.")
@click.option('--tokeep', '-k', type=click.Path(), default="", help="Location to save the contigs identified as the target organism(optional).")
@click.option('--toremove', '-x', type=click.Path(), default="", help="Location to save the contigs identified as not belonging to the target organism (optional).")
@click.option('--target', '-t', help="The identity of the target organism at the chosen classification level. It is recommended to use the organism's phylum.")
@click.option('--binary', is_flag=True, help="Use binary target/nontarget classification.")
@click.option('--level', '-l', default="phylum", help="The classification level to use when constructing the model. Default is 'phylum'.")
def runfile_runner(infile, taxdump, output, tokeep, toremove, binary, target, level):
    """
    Runs a custom analysis using pre-computed data from BBMap or other sources.

    Input data will be read for all variables which will be used to construct a Decision Tree model.
    """
    modelOutput = False
    validate_taxdump(taxdump, runfile_runner)
    runfile.runAnalysis(taxdump, infile, level, modelOutput, output, tokeep, toremove, binary, target)

""" WIP
@cli.command(name="filter", context_settings=CONTEXT_SETTINGS)
@click.option('--tokeep', '-k', type=click.Path(), default="", help="File containing list of contigs from the alignment to keep.")
@click.option('--bam', '-b', type=click.Path(exists=True), help="Alignment of reads to preliminary assembly, in BAM format.")
@click.option('-i1', type=click.Path(exists=True), help="Right read fastq to extract reads from.")
@click.option('-i2', type=click.Path(exists=True), help="Left read fastq to extract reads from.")
@click.option('-o1', type=click.Path(), help="Right read fastq to extract reads to.")
@click.option('-o2', type=click.Path(), help="Left read fastq to extract reads to.")
def filter_runner(tokeep, bam, i1, i2, o1, o2):
"""
#Filters reads aligning to the given contigs.
"""
    filterReads.runFilter(tokeep, bam, i1, i2, o1, o2)

if __name__ == "__main__":  # TODO Setuptools
    cli(prog_name="sidr")
"""