text:
Detect saddle points in a matrix.

So say you have a matrix like so:

```text
    1  2  3
  |---------
1 | 9  8  7
2 | 5  3  2     <--- saddle point at column 1, row 2, with value 5
3 | 6  6  7
```

It has a saddle point at column 1, row 2.

It's called a "saddle point" because it is greater than or equal to
every element in its row and less than or equal to every element in
its column.

A matrix may have zero or more saddle points.

Your code should be able to provide the (possibly empty) list of all the
saddle points for any given matrix.

The matrix can have a different number of rows and columns (Non square).

Note that you may find other definitions of matrix saddle points online,
but the tests for this exercise follow the above unambiguous definition.

## Exception messages

Sometimes it is necessary to raise an exception. When you do this, you should include a meaningful error message to
indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. Not
every exercise will require you to raise an exception, but for those that do, the tests will only pass if you include
a message.

To raise a message with an exception, just write it as an argument to the exception type. For example, instead of
`raise Exception`, you should write:

```python
raise Exception("Meaningful message indicating the source of the error")
```

## Running the tests

To run the tests, run the appropriate command below ([why they are different](https://github.com/pytest-dev/pytest/issues/1629#issue-161422224)):

- Python 2.7: `py.test saddle_points_test.py`
- Python 3.4+: `pytest saddle_points_test.py`

Alternatively, you can tell Python to run the pytest module (allowing the same command to be used regardless of Python version):
`python -m pytest saddle_points_test.py`

### Common `pytest` options

- `-v` : enable verbose output
- `-x` : stop running tests on first failure
- `--ff` : run failures from previous test before running other test cases

For other options, see `python -m pytest -h`

## Submitting Exercises

Note that, when trying to submit an exercise, make sure the solution is in the `$EXERCISM_WORKSPACE/python/saddle-points` directory.

You can find your Exercism workspace by running `exercism debug` and looking for the line that starts with `Workspace`.

For more detailed information about running tests, code style and linting,
please see [Running the Tests](http://exercism.io/tracks/python/tests).

## Source

J Dalbey's Programming Practice problems [http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html](http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html)

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.


text:
namespace luabind {

	LUABIND_API lua_State* get_main_thread(lua_State* L);

} // namespace luabind

#endif // LUABIND_GET_MAIN_THREAD_090321_HPP

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: Build Restful server with Jerseys framework
date: 2017-04-23
comments: true
tags: [JAX-RS, WebService]
---

### Introduction:
Recently I am developing an Android application, which needs to write a
server.
I choose to build a restful server, because it's most compatiable. We
don't need to build another server if we want to extend IOS, PC, Windows
Phone or any other clients. I used tomcat as
the server, mysql as database. And Jerseys as the webservice
implementation framework.

I have introduced the environment setup in the [last post][1], this time
I am going to introduce how to use Jerseys APIs.

### Architecture Overview

![architecture][4]

### Why Restful Web Service

The most significant benefit of REST architecture is easy data extract.
Imagine different data type, html, string, xml, json...... It's so
messy. With REST Architecture, everyone use json, it makes communication
easier!

The reason why web service is because its lightweight and portability.
Now we can access all the data using URL through http request, and get
json object back, which is easy to read! Clients don't need get tired of
match the server code. E.g. Server is in C, we can write client in Java,
in Python, in Perl, in anything can send http request and receive
respond. And the client's data accessing part become extremely easy!

### Web Service based on Jerseys Framework
Here is the project overview

![overview][2]

Let's break the problem from analyzing the request URL
```
e.g. localhost:8080/ProjectName/url-pattern/path1/path2
```

ProjectName is the project name

url-pattern is defined in web.xml

path1 is usually the class path defined in the top of class

path2 is usually the method path defined in the top of the method

In a real example,

```
e.g. localhost:8080/DoMeAFavorServer/rest/user/getUser
```

The project name is DoMeAFavorServer

rest is defined in web.xml

```xml
    <servlet-mapping>
        <servlet-name>jersey</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
```

user is defined in the top of UserService Class

```Java
@Path("/user")
public class UserService {
...
```

getUser is defined at the top of the getUser method

```Java
    @GET
    @Path("/getUser")
    @Produces(MediaType.APPLICATION_JSON)
    public String getUser() throws Exception
```

### Things need to take care

The web.xml file is pretty different based on different Jersey Version,
If you use Jersey-bundle-1.1.17.jar as me, then just copy paste the
following code to the web.xml, remember to change the display name, and
no underscore for the display name

```xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>DoMeAFavorServer</display-name>
    <servlet>
        <servlet-name>jersey</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>
```

Refer the [sample project][3] for reference!

[1]: http://www.leiyangblog.com/2017/04/21/Jersey-WebService-Eclipse-Environment-setup/
[2]: /assets/Jerseys/jerseys_project_overview.png
[3]: https://github.com/Ray-Young/DoMeAFavor
[4]: assets/Jerseys/architecture.png


text:
// Karma configuration
// Generated on Sat Apr 08 2017 23:03:49 GMT-0600 (MDT)

module.exports = function (config) {
  var configuration = {
    basePath: '',
    frameworks: ['jasmine', "karma-typescript"],
    files: [
      'src/**/*.ts',
      'spec/**/*.ts',
    ],
    preprocessors: {
      "**/*.ts": ["karma-typescript"],
    },
    reporters: ['progress', "karma-typescript"],
    karmaTypescriptConfig: {
      tsconfig: "./tsconfig.spec.json",
    },
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    concurrency: Infinity,
  };
  config.set(configuration);
}


text:
package com.netflix.curator.framework.recipes.leader;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.netflix.curator.framework.CuratorFramework;
import com.netflix.curator.framework.recipes.locks.InterProcessMutex;
import com.netflix.curator.utils.ThreadUtils;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Abstraction to select a "leader" amongst multiple contenders in a group of JMVs connected
 * to a Zookeeper cluster. If a group of N thread/processes contend for leadership one will randomly
 * be assigned leader until it releases leadership at which time another one from the group will randomly
 * be chosen
 */
public class LeaderSelector implements Closeable
{
    private final Logger                    log = LoggerFactory.getLogger(getClass());
    private final CuratorFramework          client;
    private final LeaderSelectorListener    listener;
    private final ExecutorService           executorService;
    private final Executor                  executor;
    private final InterProcessMutex         mutex;
    private final AtomicReference<State>    state = new AtomicReference<State>(State.LATENT);
    private final AtomicBoolean             autoRequeue = new AtomicBoolean(false);

    private volatile boolean                hasLeadership;
    private volatile String                 id = "";

    private enum State
    {
        LATENT,
        STARTED,
        CLOSED
    }

    // guarded by synchronization
    private boolean                isQueued = false;

    private static final ThreadFactory defaultThreadFactory = ThreadUtils.newThreadFactory("LeaderSelector");

    /**
     * @param client the client
     * @param leaderPath the path for this leadership group
     * @param listener listener
     */
    public LeaderSelector(CuratorFramework client, String leaderPath, LeaderSelectorListener listener)
    {
        this(client, leaderPath, defaultThreadFactory, MoreExecutors.sameThreadExecutor(), listener);
    }

    /**
     * @param client the client
     * @param leaderPath the path for this leadership group
     * @param threadFactory factory to use for making internal threads
     * @param executor the executor to run in
     * @param listener listener
     */
    public LeaderSelector(CuratorFramework client, String leaderPath, ThreadFactory threadFactory, Executor executor, LeaderSelectorListener listener)
    {
        Preconditions.checkNotNull(client, "client cannot be null");
        Preconditions.checkNotNull(leaderPath, "leaderPath cannot be null");
        Preconditions.checkNotNull(listener, "listener cannot be null");

        this.client = client;
        this.listener = listener;
        this.executor = executor;
        hasLeadership = false;

        executorService = Executors.newFixedThreadPool(1, threadFactory);
        mutex = new InterProcessMutex(client, leaderPath)
        {
            @Override
            protected byte[] getLockNodeBytes()
            {
                return (id.length() > 0) ? getIdBytes(id) : null;
            }
        };
    }

    static byte[] getIdBytes(String id)
    {
        try
        {
            return id.getBytes("UTF-8");
        }
        catch ( UnsupportedEncodingException e )
        {
            throw new Error(e); // this should never happen
        }
    }

    /**
     * By default, when {@link LeaderSelectorListener#takeLeadership(CuratorFramework)} returns, this
     * instance is not requeued. Calling this method puts the leader selector into a mode where it
     * will always requeue itself.
     */
    public void autoRequeue()
    {
        autoRequeue.set(true);
    }

    /**
     * Sets the ID to store for this leader. Will be the value returned
     * when {@link #getParticipants()} is called. IMPORTANT: must be called
     * prior to {@link #start()} to have effect.
     *
     * @param id ID
     */
    public void     setId(String id)
    {
        Preconditions.checkNotNull(id, "id cannot be null");

        this.id = id;
    }

    /**
     * Return the ID that was set via {@link #setId(String)}
     *
     * @return id
     */
    public String getId()
    {
        return id;
    }

    /**
     * Attempt leadership. This attempt is done in the background - i.e. this method returns
     * immediately.

     * IMPORTANT:  previous versions allowed this method to be called multiple times. This
     * is no longer supported. Use {@link #requeue()} for this purpose.
     */
    public void     start()
    {
        Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once");

        Preconditions.checkState(!executorService.isShutdown(), "Already started");
        Preconditions.checkState(!hasLeadership, "Already has leadership");

        client.getConnectionStateListenable().addListener(listener);
        requeue();
    }

    /**
     * Re-queue an attempt for leadership. If this instance is already queued, nothing
     * happens and false is returned. If the instance was not queued, it is re-qeued and true
     * is returned
     *
     * @return true if re-queue is successful
     */
    public synchronized boolean     requeue()
    {
        Preconditions.checkState(state.get() == State.STARTED, "close() has already been called");

        if ( !isQueued )
        {
            isQueued = true;
            executorService.submit
            (
                new Callable<Object>()
                {
                    @Override
                    public Object call() throws Exception
                    {
                        doWorkLoop();
                        return null;
                    }
                }
            );

            return true;
        }
        return false;
    }

    /**
     * Shutdown this selector and remove yourself from the leadership group
     */
    public void     close()
    {
        Preconditions.checkState(state.compareAndSet(State.STARTED, State.CLOSED), "Already closed or has not been started");

        client.getConnectionStateListenable().removeListener(listener);
        executorService.shutdownNow();
    }

    /**
     *

     *     Returns the set of current participants in the leader selection
     *

     *
     *

     *     NOTE - this method polls the ZK server. Therefore it can possibly
     *     return a value that does not match {@link #hasLeadership()} as hasLeadership
     *     uses a local field of the class.
     *

     *
     * @return participants
     * @throws Exception ZK errors, interruptions, etc.
     */
    public Collection<Participant>  getParticipants() throws Exception
    {
        Collection<String> participantNodes = mutex.getParticipantNodes();

        return getParticipants(client, participantNodes);
    }

    static Collection<Participant> getParticipants(CuratorFramework client, Collection<String> participantNodes) throws Exception
    {
        ImmutableList.Builder<Participant> builder = ImmutableList.builder();

        boolean         isLeader = true;
        for ( String path : participantNodes )
        {
            try
            {
                Participant     participant = participantForPath(client, path, isLeader);
                builder.add(participant);
            }
            catch ( KeeperException.NoNodeException ignore )
            {
                // ignore
            }

            isLeader = false;   // by definition the first node is the leader
        }

        return builder.build();
    }

    /**
     *

     *     Return the id for the current leader. If for some reason there is no
     *     current leader, a dummy participant is returned.
     *

     *
     *

     *     NOTE - this method polls the ZK server. Therefore it can possibly
     *     return a value that does not match {@link #hasLeadership()} as hasLeadership
     *     uses a local field of the class.
     *

     *
     * @return leader
     * @throws Exception ZK errors, interruptions, etc.
     */
    public Participant      getLeader() throws Exception
    {
        Collection<String>      participantNodes = mutex.getParticipantNodes();
        return getLeader(client, participantNodes);
    }

    static Participant getLeader(CuratorFramework client, Collection<String> participantNodes) throws Exception
    {
        if ( participantNodes.size() > 0 )
        {
            return participantForPath(client, participantNodes.iterator().next(), true);
        }
        return new Participant();
    }

    /**
     * Return true if leadership is currently held by this instance
     *
     * @return true/false
     */
    public boolean hasLeadership()
    {
        return hasLeadership;
    }

    private static Participant participantForPath(CuratorFramework client, String path, boolean markAsLeader) throws Exception
    {
        byte[]      bytes = client.getData().forPath(path);
        String      thisId = new String(bytes, "UTF-8");
        return new Participant(thisId, markAsLeader);
    }

    @VisibleForTesting
    void doWork() throws Exception
    {
        hasLeadership = false;
        try
        {
            mutex.acquire();

            hasLeadership = true;
            executor.execute
            (
                new Runnable()
                {
                    @Override
                    public void run()
                    {
                        try
                        {
                            listener.takeLeadership(client);
                        }
                        catch ( InterruptedException e )
                        {
                            Thread.currentThread().interrupt();
                        }
                        catch ( Throwable e )
                        {
                            log.error("The leader threw an exception", e);
                        }
                        finally
                        {
                            clearIsQueued();
                        }
                    }
                }
            );
        }
        catch ( InterruptedException e )
        {
            Thread.currentThread().interrupt();
        }
        catch ( Exception e )
        {
            log.error("mutex.acquire() threw an exception", e);
            throw e;
        }
        finally
        {
            hasLeadership = false;
            try
            {
                mutex.release();
            }
            catch ( Exception ignore )
            {
                // ignore errors - this is just a safety
            }
        }
    }

    private void doWorkLoop() throws Exception
    {
        do
        {
            try
            {
                doWork();
            }
            catch ( KeeperException.ConnectionLossException e )
            {
                if ( !autoRequeue.get() )   // autoRequeue should ignore connection loss and just keep trying
                {
                    throw e;
                }
            }
            catch ( InterruptedException ignore )
            {
                Thread.currentThread().interrupt();
                break;
            }
        } while ( autoRequeue.get() && (state.get() == State.STARTED) && !Thread.currentThread().isInterrupted() );
    }

    private synchronized void clearIsQueued()
    {
        isQueued = false;
    }
}


text:
/**
 * Extract then name of a subschema from a $ref property
 * @param url
 * @returns {*}
 */
module.exports = function(url) {
  return url.replace('#/definitions/', '')
};


text:
import unittest
import os
import json
from subprocess import call
import cairis.core.BorgFactory
from cairis.core.Borg import Borg
from cairis.core.EnvironmentParameters import EnvironmentParameters
from cairis.core.RoleParameters import RoleParameters
from cairis.core.AttackerParameters import AttackerParameters
from cairis.core.AttackerEnvironmentProperties import AttackerEnvironmentProperties
from cairis.core.ValueTypeParameters import ValueTypeParameters
from cairis.core.AssetParameters import AssetParameters
from cairis.core.AssetEnvironmentProperties import AssetEnvironmentProperties
from cairis.core.ThreatParameters import ThreatParameters
from cairis.core.ThreatEnvironmentProperties import ThreatEnvironmentProperties
from cairis.core.VulnerabilityParameters import VulnerabilityParameters
from cairis.core.VulnerabilityEnvironmentProperties import VulnerabilityEnvironmentProperties
from cairis.core.MisuseCase import MisuseCase
from cairis.core.MisuseCaseEnvironmentProperties import MisuseCaseEnvironmentProperties
from cairis.core.RiskParameters import RiskParameters
from cairis.core.ARM import DatabaseProxyException

__author__ = 'Shamal Faily'

class RiskTest(unittest.TestCase):

  def setUp(self):
    call([os.environ['CAIRIS_CFG_DIR'] + "/initdb.sh"])
    cairis.core.BorgFactory.initialise()
    f = open(os.environ['CAIRIS_SRC'] + '/test/risks.json')
    d = json.load(f)
    f.close()
    ienvs = d['environments']
    iep1 = EnvironmentParameters(ienvs[0]["theName"],ienvs[0]["theShortCode"],ienvs[0]["theDescription"])
    b = Borg()
    b.dbProxy.addEnvironment(iep1)
    iRoles = d['roles']
    irp = RoleParameters(iRoles[0]["theName"], iRoles[0]["theType"], iRoles[0]["theShortCode"], iRoles[0]["theDescription"],[])
    b.dbProxy.addRole(irp)
    iAttackers = d['attackers']
    iatkeps = [AttackerEnvironmentProperties(iAttackers[0]["theEnvironmentProperties"][0]["theName"],iAttackers[0]["theEnvironmentProperties"][0]["theRoles"],iAttackers[0]["theEnvironmentProperties"][0]["theMotives"],iAttackers[0]["theEnvironmentProperties"][0]["theCapabilities"])]
    iatk = AttackerParameters(iAttackers[0]["theName"], iAttackers[0]["theDescription"], iAttackers[0]["theImage"],[],iatkeps)
    b.dbProxy.addAttacker(iatk)
    iVtypes = d['valuetypes']
    ivt1 = ValueTypeParameters(iVtypes[0]["theName"], iVtypes[0]["theDescription"], iVtypes[0]["theType"])
    ivt2 = ValueTypeParameters(iVtypes[1]["theName"], iVtypes[1]["theDescription"], iVtypes[1]["theType"])
    b.dbProxy.addValueType(ivt1)
    b.dbProxy.addValueType(ivt2)
    iassets = d['assets']
    iaeps1 = [AssetEnvironmentProperties(iassets[0]["theEnvironmentProperties"][0][0],iassets[0]["theEnvironmentProperties"][0][1],iassets[0]["theEnvironmentProperties"][0][2])]
    iap1 = AssetParameters(iassets[0]["theName"],iassets[0]["theShortCode"],iassets[0]["theDescription"],iassets[0]["theSignificance"],iassets[0]["theType"],"0","N/A",[],[],iaeps1)
    iap2 = AssetParameters(iassets[1]["theName"],iassets[1]["theShortCode"],iassets[1]["theDescription"],iassets[1]["theSignificance"],iassets[1]["theType"],"0","N/A",[],[],iaeps1)
    iap3 = AssetParameters(iassets[2]["theName"],iassets[2]["theShortCode"],iassets[2]["theDescription"],iassets[2]["theSignificance"],iassets[2]["theType"],"0","N/A",[],[],iaeps1)
    b.dbProxy.addAsset(iap1)
    b.dbProxy.addAsset(iap2)
    b.dbProxy.addAsset(iap3)
    iThreats = d['threats']
    iteps = [ThreatEnvironmentProperties(iThreats[0]["theEnvironmentProperties"][0]["theName"],iThreats[0]["theEnvironmentProperties"][0]["theLikelihood"],iThreats[0]["theEnvironmentProperties"][0]["theAssets"],iThreats[0]["theEnvironmentProperties"][0]["theAttackers"],iThreats[0]["theEnvironmentProperties"][0]["theProperties"][0][1],iThreats[0]["theEnvironmentProperties"][0]["theProperties"][0][1])]
    itps = ThreatParameters(iThreats[0]["theName"],iThreats[0]["theType"],iThreats[0]["theMethod"],[],iteps)
    b.dbProxy.addThreat(itps)
    iVuln = d['vulnerabilities']
    iveps = [VulnerabilityEnvironmentProperties(iVuln[0]["theEnvironmentProperties"][0]["theName"],iVuln[0]["theEnvironmentProperties"][0]["theSeverity"],iVuln[0]["theEnvironmentProperties"][0]["theAssets"])]
    ivp = VulnerabilityParameters(iVuln[0]["theName"],iVuln[0]["theDescription"],iVuln[0]["theType"], [], iveps)
    b.dbProxy.addVulnerability(ivp)
    self.imc = d['misuseCase']
    self.iRisks = d['risks']

  def testRisk(self):
    imcep = [MisuseCaseEnvironmentProperties(self.imc[0]["theEnvironmentProperties"][0]["theName"],self.imc[0]["theEnvironmentProperties"][0]["theDescription"])]
    imcp = MisuseCase(int(0), self.imc[0]["theName"], imcep,self.imc[0]["theRisk"])
    irp = RiskParameters(self.iRisks[0]["theName"],self.iRisks[0]["threatName"],self.iRisks[0]["vulName"], imcp,[])
    b = Borg()
    b.dbProxy.addRisk(irp)
    oRisks = b.dbProxy.getRisks()
    o = oRisks[self.iRisks[0]["theName"]]
    self.assertEqual(irp.name(), o.name())
    self.assertEqual(irp.threat(),o.threat())
    self.assertEqual(irp.vulnerability(),o.vulnerability())

    scoreDetails = b.dbProxy.riskScore(self.iRisks[0]["threatName"],self.iRisks[0]["vulName"],imcep[0].name())
    preScore = scoreDetails[0][1]
    postScore = scoreDetails[0][2]
    self.assertEqual(preScore,9)
    self.assertEqual(postScore,9)

    imcp.theName = 'Updated risk'
    imcp.theId = o.misuseCase().id()
    irp.theRiskName = 'Updated risk'
    irp.theMisuseCase = imcp

    irp.setId(o.id())
    b.dbProxy.updateRisk(irp)
    oRisks = b.dbProxy.getRisks()
    o = oRisks['Updated risk']
    self.assertEqual(o.name(),'Updated risk')
    self.assertEqual(irp.threat(),o.threat())
    self.assertEqual(irp.vulnerability(),o.vulnerability())

    b.dbProxy.deleteRisk(o.id())

  def tearDown(self):
    pass

if __name__ == '__main__':
  unittest.main()


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
using Xunit;

namespace UnitTests.CodeTiger.CodeAnalysis.Analyzers
{
    /// <summary>
    /// Superclass of all Unit Tests for DiagnosticAnalyzers
    /// </summary>
    public abstract class DiagnosticVerifier
    {
        private const string DefaultFilePathPrefix = "Test";
        private const string CSharpDefaultFileExt = "cs";
        private const string VisualBasicDefaultExt = "vb";
        private const string TestProjectName = "TestProject";

        private static readonly MetadataReference _corlibReference
            = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
        private static readonly MetadataReference _systemCoreReference
            = MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location);
        private static readonly MetadataReference _csharpSymbolsReference
            = MetadataReference.CreateFromFile(typeof(CSharpCompilation).Assembly.Location);
        private static readonly MetadataReference _codeAnalysisReference
            = MetadataReference.CreateFromFile(typeof(Compilation).Assembly.Location);

        protected virtual DocumentationMode DocumentationMode => DocumentationMode.Parse;

        /// <summary>
        /// Get the CSharp analyzer being tested - to be implemented in non-abstract class
        /// </summary>
        protected virtual DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Get the Visual Basic analyzer being tested (C#) - to be implemented in non-abstract class
        /// </summary>
        protected virtual DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Called to test a C# DiagnosticAnalyzer when applied on the single inputted string as a source
        /// Note: input a DiagnosticResult for each Diagnostic expected
        /// </summary>
        /// <param name="source">A class in the form of a string to run the analyzer on</param>
        /// <param name="expected"> DiagnosticResults that should appear after the analyzer is run on the source
        /// </param>
        protected private void VerifyCSharpDiagnostic(string source, params DiagnosticResult[] expected)
        {
            VerifyDiagnostics(new[] { source }, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), expected);
        }

        /// <summary>
        /// Called to test a C# DiagnosticAnalyzer when applied on the single inputted string as a source
        /// Note: input a DiagnosticResult for each Diagnostic expected
        /// </summary>
        /// <param name="source">A class in the form of a string to run the analyzer on</param>
        /// <param name="expected"> DiagnosticResults that should appear after the analyzer is run on the source
        /// </param>
        protected private void VerifyCSharpDiagnostic(Tuple<string, string> source,
            params DiagnosticResult[] expected)
        {
            VerifyDiagnostics(new[] { source }, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), expected);
        }

        /// <summary>
        /// Called to test a VB DiagnosticAnalyzer when applied on the single inputted string as a source
        /// Note: input a DiagnosticResult for each Diagnostic expected
        /// </summary>
        /// <param name="source">A class in the form of a string to run the analyzer on</param>
        /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the source
        /// </param>
        protected private void VerifyBasicDiagnostic(string source, params DiagnosticResult[] expected)
        {
            VerifyDiagnostics(new[] { source }, LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), expected);
        }

        /// <summary>
        /// Called to test a C# DiagnosticAnalyzer when applied on the inputted strings as a source
        /// Note: input a DiagnosticResult for each Diagnostic expected
        /// </summary>
        /// <param name="sources">An array of strings to create source documents from to run the analyzers on
        /// </param>
        /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources
        /// </param>
        protected private void VerifyCSharpDiagnostic(string[] sources, params DiagnosticResult[] expected)
        {
            VerifyDiagnostics(sources, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), expected);
        }

        /// <summary>
        /// Called to test a VB DiagnosticAnalyzer when applied on the inputted strings as a source
        /// Note: input a DiagnosticResult for each Diagnostic expected
        /// </summary>
        /// <param name="sources">An array of strings to create source documents from to run the analyzers on
        /// </param>
        /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources
        /// </param>
        protected private void VerifyBasicDiagnostic(string[] sources, params DiagnosticResult[] expected)
        {
            VerifyDiagnostics(sources, LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), expected);
        }

        /// <summary>
        /// Create a Document from a string through creating a project that contains it.
        /// </summary>
        /// <param name="source">Classes in the form of a string</param>
        /// <param name="language">The language the source code is in</param>
        /// <returns>A Document created from the source string</returns>
        protected private Document CreateDocument(string source, string language = LanguageNames.CSharp)
        {
            return CreateProject(CreateNamedSources(new[] { source }, language), language).Documents.First();
        }

        /// <summary>
        /// General method that gets a collection of actual diagnostics found in the source after the analyzer is
        /// run, then verifies each of them.
        /// </summary>
        /// <param name="sources">An array of strings to create source documents from to run the analyzers on
        /// </param>
        /// <param name="language">The language of the classes represented by the source strings</param>
        /// <param name="analyzer">The analyzer to be run on the source code</param>
        /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources
        /// </param>
        private void VerifyDiagnostics(string[] sources, string language, DiagnosticAnalyzer analyzer,
            params DiagnosticResult[] expected)
        {
            var diagnostics = GetSortedDiagnostics(sources, language, analyzer);
            VerifyDiagnosticResults(diagnostics, analyzer, expected);
        }

        /// <summary>
        /// General method that gets a collection of actual diagnostics found in the source after the analyzer is
        /// run, then verifies each of them.
        /// </summary>
        /// <param name="sources">An array of strings to create source documents from to run the analyzers on
        /// </param>
        /// <param name="language">The language of the classes represented by the source strings</param>
        /// <param name="analyzer">The analyzer to be run on the source code</param>
        /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources
        /// </param>
        private void VerifyDiagnostics(Tuple<string, string>[] sources, string language,
            DiagnosticAnalyzer analyzer, params DiagnosticResult[] expected)
        {
            var diagnostics = GetSortedDiagnostics(sources, language, analyzer);
            VerifyDiagnosticResults(diagnostics, analyzer, expected);
        }

        /// <summary>
        /// Given classes in the form of strings, their language, and an IDiagnosticAnlayzer to apply to it, return
        /// the diagnostics found in the string after converting it to a document.
        /// </summary>
        /// <param name="sources">Classes in the form of strings</param>
        /// <param name="language">The language the source classes are in</param>
        /// <param name="analyzer">The analyzer to be run on the sources</param>
        /// <returns>An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location</returns>
        private Diagnostic[] GetSortedDiagnostics(string[] sources, string language,
            DiagnosticAnalyzer analyzer)
        {
            return GetSortedDiagnosticsFromDocuments(analyzer, GetDocuments(sources, language));
        }

        /// <summary>
        /// Given classes in the form of strings, their language, and an IDiagnosticAnlayzer to apply to it, return
        /// the diagnostics found in the string after converting it to a document.
        /// </summary>
        /// <param name="sources">Classes in the form of strings</param>
        /// <param name="language">The language the source classes are in</param>
        /// <param name="analyzer">The analyzer to be run on the sources</param>
        /// <returns>An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location</returns>
        private Diagnostic[] GetSortedDiagnostics(Tuple<string, string>[] sources, string language,
            DiagnosticAnalyzer analyzer)
        {
            return GetSortedDiagnosticsFromDocuments(analyzer, GetDocuments(sources, language));
        }

        /// <summary>
        /// Given an array of strings as sources and a language, turn them into a project and return the documents
        /// and spans of it.
        /// </summary>
        /// <param name="sources">Classes in the form of strings</param>
        /// <param name="language">The language the source code is in</param>
        /// <returns>A Tuple containing the Documents produced from the sources and their TextSpans if relevant
        /// </returns>
        private Document[] GetDocuments(string[] sources, string language)
        {
            if (language != LanguageNames.CSharp && language != LanguageNames.VisualBasic)
            {
                throw new ArgumentException("Unsupported Language");
            }

            var namedSources = CreateNamedSources(sources, language);

            var project = CreateProject(namedSources, language);
            var documents = project.Documents.ToArray();

            if (sources.Length != documents.Length)
            {
                throw new SystemException("Amount of sources did not match amount of Documents created");
            }

            return documents;
        }

        /// <summary>
        /// Given an array of strings as sources and a language, turn them into a project and return the documents
        /// and spans of it.
        /// </summary>
        /// <param name="sources">Classes in the form of strings</param>
        /// <param name="language">The language the source code is in</param>
        /// <returns>A Tuple containing the Documents produced from the sources and their TextSpans if relevant
        /// </returns>
        private Document[] GetDocuments(Tuple<string, string>[] sources, string language)
        {
            if (language != LanguageNames.CSharp && language != LanguageNames.VisualBasic)
            {
                throw new ArgumentException("Unsupported Language");
            }

            var project = CreateProject(sources, language);
            var documents = project.Documents.ToArray();

            if (sources.Length != documents.Length)
            {
                throw new SystemException("Amount of sources did not match amount of Documents created");
            }

            return documents;
        }

        /// <summary>
        /// Create a project using the inputted strings as sources.
        /// </summary>
        /// <param name="sources">Classes in the form of strings</param>
        /// <param name="language">The language the source code is in</param>
        /// <returns>A Project created out of the Documents created from the source strings</returns>
        private Project CreateProject(Tuple<string, string>[] sources,
            string language = LanguageNames.CSharp)
        {
            var projectId = ProjectId.CreateNewId(debugName: TestProjectName);

            var parseOptions = new CSharpParseOptions(documentationMode: DocumentationMode);
            var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Default, TestProjectName, TestProjectName,
                language, parseOptions: parseOptions);
            var solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectInfo)
                .AddMetadataReference(projectId, _corlibReference)
                .AddMetadataReference(projectId, _systemCoreReference)
                .AddMetadataReference(projectId, _csharpSymbolsReference)
                .AddMetadataReference(projectId, _codeAnalysisReference);

            foreach (var source in sources)
            {
                var documentId = DocumentId.CreateNewId(projectId, debugName: source.Item1);
                solution = solution.AddDocument(documentId, source.Item1, SourceText.From(source.Item2));
            }
            return solution.GetProject(projectId);
        }

        /// <summary>
        /// Given an analyzer and a document to apply it to, run the analyzer and gather an array of diagnostics
        /// found in it. The returned diagnostics are then ordered by location in the source document.
        /// </summary>
        /// <param name="analyzer">The analyzer to run on the documents</param>
        /// <param name="documents">The Documents that the analyzer will be run on</param>
        /// <returns>An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location</returns>
        protected static Diagnostic[] GetSortedDiagnosticsFromDocuments(DiagnosticAnalyzer analyzer,
            Document[] documents)
        {
            var projects = new HashSet<Project>();
            foreach (var document in documents)
            {
                projects.Add(document.Project);
            }

            var diagnostics = new List<Diagnostic>();
            foreach (var project in projects)
            {
                var compilationWithAnalyzers = project.GetCompilationAsync().Result
                    .WithAnalyzers(ImmutableArray.Create(analyzer));
                var diags = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result;
                foreach (var diag in diags)
                {
                    if (diag.Location == Location.None || diag.Location.IsInMetadata)
                    {
                        diagnostics.Add(diag);
                    }
                    else
                    {
                        for (int i = 0; i < documents.Length; i++)
                        {
                            var document = documents[i];
                            var tree = document.GetSyntaxTreeAsync().Result;
                            if (tree == diag.Location.SourceTree)
                            {
                                diagnostics.Add(diag);
                            }
                        }
                    }
                }
            }

            var results = SortDiagnostics(diagnostics);
            diagnostics.Clear();
            return results;
        }

        /// <summary>
        /// Sort diagnostics by location in source document
        /// </summary>
        /// <param name="diagnostics">The list of Diagnostics to be sorted</param>
        /// <returns>An IEnumerable containing the Diagnostics in order of Location</returns>
        private static Diagnostic[] SortDiagnostics(IEnumerable<Diagnostic> diagnostics)
        {
            return diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
        }

        /// <summary>
        /// Checks each of the actual Diagnostics found and compares them with the corresponding DiagnosticResult
        /// in the array of expected results.
        /// Diagnostics are considered equal only if the DiagnosticResultLocation, Id, Severity, and Message of the
        /// DiagnosticResult match the actual diagnostic.
        /// </summary>
        /// <param name="actualResults">The Diagnostics found by the compiler after running the analyzer on the
        /// source code</param>
        /// <param name="analyzer">The analyzer that was being run on the sources</param>
        /// <param name="expectedResults">Diagnostic Results that should have appeared in the code</param>
        private static void VerifyDiagnosticResults(IEnumerable<Diagnostic> actualResults,
            DiagnosticAnalyzer analyzer, params DiagnosticResult[] expectedResults)
        {
            int expectedCount = expectedResults.Count();
            int actualCount = actualResults.Count();

            if (expectedCount != actualCount)
            {
                string diagnosticsOutput = actualResults.Any()
                    ? FormatDiagnostics(analyzer, actualResults.ToArray())
                    : "    NONE.";

                Assert.True(false,
                    string.Format("Mismatch between number of diagnostics returned, expected \"{0}\" actual \"{1}"
                    + "\"\r\n\r\nDiagnostics:\r\n{2}\r\n", expectedCount, actualCount, diagnosticsOutput));
            }

            for (int i = 0; i < expectedResults.Length; i++)
            {
                var actual = actualResults.ElementAt(i);
                var expected = expectedResults[i];

                if (expected.Line == -1 && expected.Column == -1)
                {
                    if (actual.Location != Location.None)
                    {
                        Assert.True(false,
                            string.Format("Expected:\nA project diagnostic with No location\nActual:\n{0}",
                            FormatDiagnostics(analyzer, actual)));
                    }
                }
                else
                {
                    VerifyDiagnosticLocation(analyzer, actual, actual.Location, expected.Locations.First());
                    var additionalLocations = actual.AdditionalLocations.ToArray();

                    if (additionalLocations.Length != expected.Locations.Length - 1)
                    {
                        Assert.True(false,
                            string.Format(
                                "Expected {0} additional locations but got {1} for Diagnostic:\r\n    {2}\r\n",
                                expected.Locations.Length - 1, additionalLocations.Length,
                                FormatDiagnostics(analyzer, actual)));
                    }

                    for (int j = 0; j < additionalLocations.Length; ++j)
                    {
                        VerifyDiagnosticLocation(analyzer, actual, additionalLocations[j],
                            expected.Locations[j + 1]);
                    }
                }

                if (actual.Id != expected.Id)
                {
                    Assert.True(false,
                        string.Format(
                            "Expected diagnostic id to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
                            expected.Id, actual.Id, FormatDiagnostics(analyzer, actual)));
                }

                if (actual.Severity != expected.Severity)
                {
                    Assert.True(false,
                        string.Format("Expected diagnostic severity to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:"
                            + "\r\n    {2}\r\n", expected.Severity, actual.Severity,
                            FormatDiagnostics(analyzer, actual)));
                }

                if (actual.GetMessage() != expected.Message)
                {
                    Assert.True(false,
                        string.Format("Expected diagnostic message to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:"
                        + "\r\n    {2}\r\n", expected.Message, actual.GetMessage(),
                        FormatDiagnostics(analyzer, actual)));
                }
            }
        }

        /// <summary>
        /// Helper method to VerifyDiagnosticResult that checks the location of a diagnostic and compares it with
        /// the location in the expected DiagnosticResult.
        /// </summary>
        /// <param name="analyzer">The analyzer that was being run on the sources</param>
        /// <param name="diagnostic">The diagnostic that was found in the code</param>
        /// <param name="actual">The Location of the Diagnostic found in the code</param>
        /// <param name="expected">The DiagnosticResultLocation that should have been found</param>
        private static void VerifyDiagnosticLocation(DiagnosticAnalyzer analyzer, Diagnostic diagnostic,
            Location actual, DiagnosticResultLocation expected)
        {
            var actualSpan = actual.GetLineSpan();

            Assert.True(actualSpan.Path == expected.Path
                || (actualSpan.Path?.Contains("Test0.") == true && expected.Path?.Contains("Test.") == true),
                string.Format("Expected diagnostic to be in file \"{0}\" was actually in file \"{1}\"\r\n\r\n"
                    + "Diagnostic:\r\n    {2}\r\n", expected.Path, actualSpan.Path,
                    FormatDiagnostics(analyzer, diagnostic)));

            var actualLinePosition = actualSpan.StartLinePosition;

            // Only check line position if there is an actual line in the real diagnostic
            if (actualLinePosition.Line > 0)
            {
                if (actualLinePosition.Line + 1 != expected.Line)
                {
                    Assert.True(false,
                        string.Format("Expected diagnostic to be on line \"{0}\" was actually on line \"{1}\"\r\n"
                            + "\r\nDiagnostic:\r\n    {2}\r\n", expected.Line, actualLinePosition.Line + 1,
                            FormatDiagnostics(analyzer, diagnostic)));
                }
            }

            // Only check column position if there is an actual column position in the real diagnostic
            if (actualLinePosition.Character > 0)
            {
                if (actualLinePosition.Character + 1 != expected.Column)
                {
                    Assert.True(false,
                        string.Format("Expected diagnostic to start at column \"{0}\" was actually at column "
                            + "\"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n", expected.Column,
                            actualLinePosition.Character + 1, FormatDiagnostics(analyzer, diagnostic)));
                }
            }
        }

        /// <summary>
        /// Helper method to format a Diagnostic into an easily readable string
        /// </summary>
        /// <param name="analyzer">The analyzer that this verifier tests</param>
        /// <param name="diagnostics">The Diagnostics to be formatted</param>
        /// <returns>The Diagnostics formatted as a string</returns>
        private static string FormatDiagnostics(DiagnosticAnalyzer analyzer, params Diagnostic[] diagnostics)
        {
            var builder = new StringBuilder();
            for (int i = 0; i < diagnostics.Length; ++i)
            {
                builder.AppendLine("// " + diagnostics[i].ToString());

                var analyzerType = analyzer.GetType();
                var rules = analyzer.SupportedDiagnostics;

                foreach (var rule in rules)
                {
                    if (rule != null && rule.Id == diagnostics[i].Id)
                    {
                        var location = diagnostics[i].Location;
                        if (location == Location.None)
                        {
                            builder.AppendFormat("GetGlobalResult({0}.{1})", analyzerType.Name, rule.Id);
                        }
                        else
                        {
                            Assert.True(location.IsInSource,
                                $"Test base does not currently handle diagnostics in metadata locations."
                                + " Diagnostic in metadata: {diagnostics[i]}\r\n");

                            string resultMethodName = diagnostics[i].Location.SourceTree.FilePath.EndsWith(".cs")
                                ? "GetCSharpResultAt"
                                : "GetBasicResultAt";
                            var linePosition = diagnostics[i].Location.GetLineSpan().StartLinePosition;

                            builder.AppendFormat("{0}({1}, {2}, {3}.{4})",
                                resultMethodName,
                                linePosition.Line + 1,
                                linePosition.Character + 1,
                                analyzerType.Name,
                                rule.Id);
                        }

                        if (i != diagnostics.Length - 1)
                        {
                            builder.Append(',');
                        }

                        builder.AppendLine();
                        break;
                    }
                }
            }
            return builder.ToString();
        }

        private static Tuple<string, string>[] CreateNamedSources(string[] sources, string language)
        {
            string fileNamePrefix = DefaultFilePathPrefix;
            string fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt;

            var namedSources = sources
                .Select((source, index) => Tuple.Create($"{fileNamePrefix}{index}.{fileExt}", source))
                .ToArray();
            return namedSources;
        }
    }
}


text:
<?php
/**
 * 应用核心自动装载类  \Core\ClassLoader
 * @author Lancer He <lancer.he@gmail.com>
 * @since  2014-06-23
 */
namespace Core;

class ClassLoader {

    /**
     * Class mapping ex: array('Service' => APPLICATION_SERVICES_PATH)
     * @var array
     */
    protected $_mapper = array();

    /**
     * is class could be load
     * @var boolean
     */
    protected $_loader = false;

    /**
     * add class map
     * @param  array $mapper array('Service' => APPLICATION_SERVICES_PATH)
     * @return void
     */
    public function addClassMap($mapper) {
        $this->_mapper = $mapper;
    }

    /**
     * Autoload
     * @param  string $class  Class name which need to autoload.
     * @return boolean
     */
    public function loader($class) {
        $this->_loader = false;
        foreach ($this->_mapper as $prefix => $dir) {
            if ( 0 !== strncmp($class, $prefix, strlen($prefix))) {
                continue;
            }
            $this->_loader = true;
            break;
        }
        if ( ! $this->_loader ) {
            return false;
        }
        $parts  = explode('\\', $class);
        $prefix = array_shift($parts);
        $file   = array_pop($parts);
        $path = rtrim($dir, '/') . DIRECTORY_SEPARATOR;
        if ( ! empty($parts) ) {
            $path .= strtolower(implode(DIRECTORY_SEPARATOR, $parts)) . DIRECTORY_SEPARATOR;
        }
        $path .= $file . '.php';
        // go through the directories to find classes
        if (is_readable($path)) {
            require $path;
            return true;
        }
        return false;
    }
}


text:
This repository contains common php snippets for Vim.

## Installation

This plugin requires [Ultisnips](https://github.com/SirVer/ultisnips) and [sniphpets](https://github.com/sniphpets/sniphpets)

### Using [pathogen](https://github.com/tpope/vim-pathogen)

```sh
git clone https://github.com/sniphpets/sniphpets-common.git ~/.vim/bundle/sniphpets-common
```

### Using [vundle](https://github.com/gmarik/vundle)

Add to your vimrc:

```vim
Plugin 'sniphpets/sniphpets-common'
```

## License

Copyright (c) Voronkovich Oleg. Distributed under the MIT.


text:
package pl.edu.agh.dsm.catalog.web.view.dto;

import java.util.UUID;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnore;

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class MeasurementDto {

	@JsonIgnore
	private UUID id;
	private String resource;
	private String metric;
	private String unit;
	@JsonIgnore
	private String monitor;

	public MeasurementDto(UUID id, String resource, String metric, String unit,
			String monitor) {
		this.id = id;
		this.resource = resource;
		this.metric = metric;
		this.unit = unit;
		this.monitor = monitor;
	}

	public MeasurementDto() {
	}

	public UUID getId() {
		return this.id;
	}

	public String getResource() {
		return this.resource;
	}

	public String getMetric() {
		return this.metric;
	}

	public String getUnit() {
		return this.unit;
	}

	public String getMonitor() {
		return monitor;
	}

	public boolean equals(Object o) {
		if (o == this)
			return true;
		if (!(o instanceof MeasurementDto))
			return false;
		final MeasurementDto other = (MeasurementDto) o;
		if (!other.canEqual((Object) this))
			return false;
		final Object this$id = this.getId();
		final Object other$id = other.getId();
		if (this$id == null ? other$id != null : !this$id.equals(other$id))
			return false;
		final Object this$resource = this.getResource();
		final Object other$resource = other.getResource();
		if (this$resource == null ? other$resource != null : !this$resource
				.equals(other$resource))
			return false;
		final Object this$metric = this.getMetric();
		final Object other$metric = other.getMetric();
		if (this$metric == null ? other$metric != null : !this$metric
				.equals(other$metric))
			return false;
		final Object this$unit = this.getUnit();
		final Object other$unit = other.getUnit();
		if (this$unit == null ? other$unit != null : !this$unit
				.equals(other$unit))
			return false;
		return true;
	}

	public int hashCode() {
		final int PRIME = 59;
		int result = 1;
		final Object $id = this.getId();
		result = result * PRIME + ($id == null ? 0 : $id.hashCode());
		final Object $resource = this.getResource();
		result = result * PRIME
				+ ($resource == null ? 0 : $resource.hashCode());
		final Object $metric = this.getMetric();
		result = result * PRIME + ($metric == null ? 0 : $metric.hashCode());
		final Object $unit = this.getUnit();
		result = result * PRIME + ($unit == null ? 0 : $unit.hashCode());
		return result;
	}

	public boolean canEqual(Object other) {
		return other instanceof MeasurementDto;
	}

	@Override
	public String toString() {
		return "MeasurementDto [id=" + id + ", resource=" + resource
				+ ", metric=" + metric + ", unit=" + unit + ", monitor="
				+ monitor + "]";
	}
}


text:
package com.intellij.lang.folding;

import com.intellij.lang.ASTNode;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import consulo.annotation.access.RequiredReadAction;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import java.util.Objects;

/**
 * Allows a custom language plugin to define rules for folding code in the language handled
 * by the plugin.
 *
 * @author max
 * @see com.intellij.lang.folding.LanguageFolding#forLanguage(com.intellij.lang.Language)
 */

public abstract class FoldingBuilderEx implements FoldingBuilder {
  /**
   * Builds the folding regions for the specified node in the AST tree and its children.
   *
   * @param root     the element for which folding is requested.
   * @param document the document for which folding is built. Can be used to retrieve line
   *                 numbers for folding regions.
   * @param quick    whether the result should be provided as soon as possible. Is true, when
   *                 an editor is opened and we need to auto-fold something immediately, like Java imports.
   *                 If true, one should perform no reference resolving and avoid complex checks if possible.
   * @return the array of folding descriptors.
   */
  @Nonnull
  @RequiredReadAction
  public abstract FoldingDescriptor[] buildFoldRegions(@Nonnull PsiElement root, @Nonnull Document document, boolean quick);

  @Override
  @RequiredReadAction
  @Nonnull
  public FoldingDescriptor[] buildFoldRegions(@Nonnull ASTNode node, @Nonnull Document document) {
    return buildFoldRegions(Objects.requireNonNull(node.getPsi()), document, false);
  }

  /**
   * Returns the text which is displayed in the editor for the folding region related to the
   * specified node when the folding region is collapsed.
   *
   *
   * @param node the node for which the placeholder text is requested.
   * @param range text range within whole file to fold
   * @return the placeholder text.
   */
  @Nullable
  @RequiredReadAction
  public String getPlaceholderText(@Nonnull ASTNode node, @Nonnull TextRange range){
    return getPlaceholderText(node);
  }

  /**
   * Returns the default collapsed state for the folding region related to the specified node.
   *
   * @param node the node for which the collapsed state is requested.
   * @return true if the region is collapsed by default, false otherwise.
   */
  @Override
  @RequiredReadAction
  public abstract boolean isCollapsedByDefault(@Nonnull ASTNode node);
}


text:
'''imshow with masked array input and out-of-range colors.

'''

from pylab import *
import matplotlib.numerix.npyma as ma
import matplotlib.colors as colors

delta = 0.025
x = y = arange(-3.0, 3.0, delta)
X, Y = meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10 * (Z2-Z1)  # difference of Gaussians

# Set up a colormap:
palette = cm.gray
palette.set_over('r', 1.0)
palette.set_under('g', 1.0)
palette.set_bad('b', 1.0)
# Alternatively, we could use
# palette.set_bad(alpha = 0.0)
# to make the bad region transparent.  This is the default.
# If you comment out all the palette.set* lines, you will see
# all the defaults; under and over will be colored with the
# first and last colors in the palette, respectively.
Zm = ma.masked_where(Z > 1.2, Z)

# By setting vmin and vmax in the norm, we establish the
# range to which the regular palette color scale is applied.
# Anything above that range is colored based on palette.set_over, etc.

im = imshow(Zm, interpolation='bilinear',
    cmap=palette,
    norm = colors.Normalize(vmin = -1.0, vmax = 1.0, clip = False),
    origin='lower', extent=[-3,3,-3,3])
title('Green=low, Red=high, Blue=bad')
colorbar(im, extend='both', shrink=0.8)
show()


text:
"""

"""
from __future__ import print_function
import numpy
import random
from rdkit.ML.DecTree import QuantTree, ID3
from rdkit.ML.InfoTheory import entropy
from rdkit.ML.Data import Quantize
from rdkit.six.moves import range

def FindBest(resCodes, examples, nBoundsPerVar, nPossibleRes, nPossibleVals, attrs, exIndices=None,
             **kwargs):
  bestGain = -1e6
  best = -1
  bestBounds = []

  if exIndices is None:
    exIndices = list(range(len(examples)))

  if not len(exIndices):
    return best, bestGain, bestBounds

  nToTake = kwargs.get('randomDescriptors', 0)
  if nToTake > 0:
    nAttrs = len(attrs)
    if nToTake < nAttrs:
      ids = list(range(nAttrs))
      random.shuffle(ids, random=random.random)
      tmp = [attrs[x] for x in ids[:nToTake]]
      attrs = tmp

  for var in attrs:
    nBounds = nBoundsPerVar[var]
    if nBounds > 0:
      #vTable = map(lambda x,z=var:x[z],examples)
      try:
        vTable = [examples[x][var] for x in exIndices]
      except IndexError:
        print('index error retrieving variable: %d' % var)
        raise
      qBounds, gainHere = Quantize.FindVarMultQuantBounds(vTable, nBounds, resCodes, nPossibleRes)
      #print('\tvar:',var,qBounds,gainHere)
    elif nBounds == 0:
      vTable = ID3.GenVarTable((examples[x] for x in exIndices), nPossibleVals, [var])[0]
      gainHere = entropy.InfoGain(vTable)
      qBounds = []
    else:
      gainHere = -1e6
      qBounds = []
    if gainHere > bestGain:
      bestGain = gainHere
      bestBounds = qBounds
      best = var
    elif bestGain == gainHere:
      if len(qBounds) < len(bestBounds):
        best = var
        bestBounds = qBounds
  if best == -1:
    print('best unaltered')
    print('\tattrs:', attrs)
    print('\tnBounds:', take(nBoundsPerVar, attrs))
    print('\texamples:')
    for example in (examples[x] for x in exIndices):
      print('\t\t', example)

  if 0:
    print('BEST:', len(exIndices), best, bestGain, bestBounds)
    if (len(exIndices) < 10):
      print(len(exIndices), len(resCodes), len(examples))
      exs = [examples[x] for x in exIndices]
      vals = [x[best] for x in exs]
      sortIdx = numpy.argsort(vals)
      sortVals = [exs[x] for x in sortIdx]
      sortResults = [resCodes[x] for x in sortIdx]
      for i in range(len(vals)):
        print('   ', i, ['%.4f' % x for x in sortVals[i][1:-1]], sortResults[i])
  return best, bestGain, bestBounds

def BuildQuantTree(examples, target, attrs, nPossibleVals, nBoundsPerVar, depth=0, maxDepth=-1,
                   exIndices=None, **kwargs):
  """
    **Arguments**

      - examples: a list of lists (nInstances x nVariables+1) of variable
        values + instance values

      - target: an int

      - attrs: a list of ints indicating which variables can be used in the tree

      - nPossibleVals: a list containing the number of possible values of
                   every variable.

      - nBoundsPerVar: the number of bounds to include for each variable

      - depth: (optional) the current depth in the tree

      - maxDepth: (optional) the maximum depth to which the tree
                   will be grown
    **Returns**

     a QuantTree.QuantTreeNode with the decision tree

    **NOTE:** This code cannot bootstrap (start from nothing...)
          use _QuantTreeBoot_ (below) for that.
  """
  tree = QuantTree.QuantTreeNode(None, 'node')
  tree.SetData(-666)
  nPossibleRes = nPossibleVals[-1]

  if exIndices is None:
    exIndices = list(range(len(examples)))

  # counts of each result code:
  resCodes = [int(x[-1]) for x in (examples[y] for y in exIndices)]
  counts = [0] * nPossibleRes
  for res in resCodes:
    counts[res] += 1
  nzCounts = numpy.nonzero(counts)[0]

  if len(nzCounts) == 1:
    # bottomed out because there is only one result code left
    #  with any counts (i.e. there's only one type of example
    #  left... this is GOOD!).
    res = nzCounts[0]
    tree.SetLabel(res)
    tree.SetName(str(res))
    tree.SetTerminal(1)
  elif len(attrs) == 0 or (maxDepth >= 0 and depth > maxDepth):
    # Bottomed out: no variables left or max depth hit
    #  We don't really know what to do here, so
    #  use the heuristic of picking the most prevalent
    #  result
    v = numpy.argmax(counts)
    tree.SetLabel(v)
    tree.SetName('%d?' % v)
    tree.SetTerminal(1)
  else:
    # find the variable which gives us the largest information gain
    best, bestGain, bestBounds = FindBest(resCodes, examples, nBoundsPerVar, nPossibleRes,
                                          nPossibleVals, attrs, exIndices=exIndices, **kwargs)
    # remove that variable from the lists of possible variables
    nextAttrs = attrs[:]
    if not kwargs.get('recycleVars', 0):
      nextAttrs.remove(best)

    # set some info at this node
    tree.SetName('Var: %d' % (best))
    tree.SetLabel(best)
    tree.SetQuantBounds(bestBounds)
    tree.SetTerminal(0)

    # loop over possible values of the new variable and
    #  build a subtree for each one
    indices = exIndices[:]
    if len(bestBounds) > 0:
      for bound in bestBounds:
        nextExamples = []
        for index in indices[:]:
          ex = examples[index]
          if ex[best] < bound:
            nextExamples.append(index)
            indices.remove(index)

        if len(nextExamples) == 0:
          # this particular value of the variable has no examples,
          #  so there's not much sense in recursing.
          #  This can (and does) happen.
          v = numpy.argmax(counts)
          tree.AddChild('%d' % v, label=v, data=0.0, isTerminal=1)
        else:
          # recurse
          tree.AddChildNode(
            BuildQuantTree(examples, best, nextAttrs, nPossibleVals, nBoundsPerVar, depth=depth + 1,
                           maxDepth=maxDepth, exIndices=nextExamples, **kwargs))
      # add the last points remaining
      nextExamples = []
      for index in indices:
        nextExamples.append(index)
      if len(nextExamples) == 0:
        v = numpy.argmax(counts)
        tree.AddChild('%d' % v, label=v, data=0.0, isTerminal=1)
      else:
        tree.AddChildNode(
          BuildQuantTree(examples, best, nextAttrs, nPossibleVals, nBoundsPerVar, depth=depth + 1,
                         maxDepth=maxDepth, exIndices=nextExamples, **kwargs))
    else:
      for val in range(nPossibleVals[best]):
        nextExamples = []
        for idx in exIndices:
          if examples[idx][best] == val:
            nextExamples.append(idx)
        if len(nextExamples) == 0:
          v = numpy.argmax(counts)
          tree.AddChild('%d' % v, label=v, data=0.0, isTerminal=1)
        else:
          tree.AddChildNode(
            BuildQuantTree(examples, best, nextAttrs, nPossibleVals, nBoundsPerVar, depth=depth + 1,
                           maxDepth=maxDepth, exIndices=nextExamples, **kwargs))
  return tree

def QuantTreeBoot(examples, attrs, nPossibleVals, nBoundsPerVar, initialVar=None, maxDepth=-1,
                  **kwargs):
  """ Bootstrapping code for the QuantTree

    If _initialVar_ is not set, the algorithm will automatically
     choose the first variable in the tree (the standard greedy
     approach).  Otherwise, _initialVar_ will be used as the first
     split.

  """
  attrs = list(attrs)
  for i in range(len(nBoundsPerVar)):
    if nBoundsPerVar[i] == -1 and i in attrs:
      attrs.remove(i)

  tree = QuantTree.QuantTreeNode(None, 'node')
  nPossibleRes = nPossibleVals[-1]
  tree._nResultCodes = nPossibleRes

  resCodes = [int(x[-1]) for x in examples]
  counts = [0] * nPossibleRes
  for res in resCodes:
    counts[res] += 1
  if initialVar is None:
    best, gainHere, qBounds = FindBest(resCodes, examples, nBoundsPerVar, nPossibleRes,
                                       nPossibleVals, attrs, **kwargs)
  else:
    best = initialVar
    if nBoundsPerVar[best] > 0:
      vTable = map(lambda x, z=best: x[z], examples)
      qBounds, gainHere = Quantize.FindVarMultQuantBounds(vTable, nBoundsPerVar[best], resCodes,
                                                          nPossibleRes)
    elif nBoundsPerVar[best] == 0:
      vTable = ID3.GenVarTable(examples, nPossibleVals, [best])[0]
      gainHere = entropy.InfoGain(vTable)
      qBounds = []
    else:
      gainHere = -1e6
      qBounds = []

  tree.SetName('Var: %d' % (best))
  tree.SetData(gainHere)
  tree.SetLabel(best)
  tree.SetTerminal(0)
  tree.SetQuantBounds(qBounds)
  nextAttrs = list(attrs)
  if not kwargs.get('recycleVars', 0):
    nextAttrs.remove(best)

  indices = list(range(len(examples)))
  if len(qBounds) > 0:
    for bound in qBounds:
      nextExamples = []
      for index in list(indices):
        ex = examples[index]
        if ex[best] < bound:
          nextExamples.append(ex)
          indices.remove(index)

      if len(nextExamples):
        tree.AddChildNode(
          BuildQuantTree(nextExamples, best, nextAttrs, nPossibleVals, nBoundsPerVar, depth=1,
                         maxDepth=maxDepth, **kwargs))
      else:
        v = numpy.argmax(counts)
        tree.AddChild('%d??' % (v), label=v, data=0.0, isTerminal=1)
    # add the last points remaining
    nextExamples = []
    for index in indices:
      nextExamples.append(examples[index])
    if len(nextExamples) != 0:
      tree.AddChildNode(
        BuildQuantTree(nextExamples, best, nextAttrs, nPossibleVals, nBoundsPerVar, depth=1,
                       maxDepth=maxDepth, **kwargs))
    else:
      v = numpy.argmax(counts)
      tree.AddChild('%d??' % (v), label=v, data=0.0, isTerminal=1)
  else:
    for val in range(nPossibleVals[best]):
      nextExamples = []
      for example in examples:
        if example[best] == val:
          nextExamples.append(example)
      if len(nextExamples) != 0:
        tree.AddChildNode(
          BuildQuantTree(nextExamples, best, nextAttrs, nPossibleVals, nBoundsPerVar, depth=1,
                         maxDepth=maxDepth, **kwargs))
      else:
        v = numpy.argmax(counts)
        tree.AddChild('%d??' % (v), label=v, data=0.0, isTerminal=1)
  return tree

def TestTree():
  """ testing code for named trees

  """
  examples1 = [['p1', 0, 1, 0, 0], ['p2', 0, 0, 0, 1], ['p3', 0, 0, 1, 2], ['p4', 0, 1, 1, 2],
               ['p5', 1, 0, 0, 2], ['p6', 1, 0, 1, 2], ['p7', 1, 1, 0, 2], ['p8', 1, 1, 1, 0]]
  attrs = list(range(1, len(examples1[0]) - 1))
  nPossibleVals = [0, 2, 2, 2, 3]
  t1 = ID3.ID3Boot(examples1, attrs, nPossibleVals, maxDepth=1)
  t1.Print()

def TestQuantTree():
  """ testing code for named trees

  """
  examples1 = [['p1', 0, 1, 0.1, 0], ['p2', 0, 0, 0.1, 1], ['p3', 0, 0, 1.1, 2],
               ['p4', 0, 1, 1.1, 2], ['p5', 1, 0, 0.1, 2], ['p6', 1, 0, 1.1, 2],
               ['p7', 1, 1, 0.1, 2], ['p8', 1, 1, 1.1, 0]]
  attrs = list(range(1, len(examples1[0]) - 1))
  nPossibleVals = [0, 2, 2, 0, 3]
  boundsPerVar = [0, 0, 0, 1, 0]

  print('base')
  t1 = QuantTreeBoot(examples1, attrs, nPossibleVals, boundsPerVar)
  t1.Pickle('test_data/QuantTree1.pkl')
  t1.Print()

  print('depth limit')
  t1 = QuantTreeBoot(examples1, attrs, nPossibleVals, boundsPerVar, maxDepth=1)
  t1.Pickle('test_data/QuantTree1.pkl')
  t1.Print()

def TestQuantTree2():
  """ testing code for named trees

  """
  examples1 = [['p1', 0.1, 1, 0.1, 0], ['p2', 0.1, 0, 0.1, 1], ['p3', 0.1, 0, 1.1, 2],
               ['p4', 0.1, 1, 1.1, 2], ['p5', 1.1, 0, 0.1, 2], ['p6', 1.1, 0, 1.1, 2],
               ['p7', 1.1, 1, 0.1, 2], ['p8', 1.1, 1, 1.1, 0]]
  attrs = list(range(1, len(examples1[0]) - 1))
  nPossibleVals = [0, 0, 2, 0, 3]
  boundsPerVar = [0, 1, 0, 1, 0]

  t1 = QuantTreeBoot(examples1, attrs, nPossibleVals, boundsPerVar)
  t1.Print()
  t1.Pickle('test_data/QuantTree2.pkl')

  for example in examples1:
    print(example, t1.ClassifyExample(example))

if __name__ == "__main__":
  TestTree()
  TestQuantTree()
  #TestQuantTree2()


text:
X-Axis

Field Name <tip>Only one field for the x-axis</tip>

    <input bs-typeahead="fields.list" ng-options="field for field in fields.list" type="text" class="input-medium" ng-model="panel.field" ng-change="set_refresh(true)">

Max Rows <tip>Maximum number of rows to retrieve for the result set.</tip>

    <input ng-change="set_refresh(true)" placeholder="10000" type="number" class="input-small" ng-model="panel.max_rows">

Left Y-Axis (Required)

Y-Axis Field(s) <tip>Field(s) to be plotted on the chart(comma separated)</tip>

    <input type="text" class="input-medium" placeholder="open,high,low,close" ng-model="panel.fl" ng-change="set_refresh(true)">

Y-Axis Label <tip>The label to be viewed on the top of Y-Axis</tip>

    <input type="text" class="input-small" placeholder="Rates" ng-model="panel.yAxis" ng-change="set_refresh(true)">

Interpolation Method <tip>D3 Interpolation method for missing or NaN values</tip>

    <select ng-change="set_refresh(true)" placeholder="10000" class="input-medium" ng-model="panel.interpolate" ng-options="f for f in ['linear','step-before','basis','basis-open','basis-closed','cardinal','cardinal-open','cardinal-closed','monotone']"></select>

Show Legend <tip>Shows legend for this series when checked</tip>

    <input type="checkbox" ng-model="panel.showLegend" ng-checked="panel.showLegend">

Add another Y-Axis <tip>Add another y-axis to the right</tip>

    <input type="checkbox" ng-model="panel.rightYEnabled" ng-checked="panel.rightYEnabled">

Right Y-Axis (Optional)

Y-Axis Field(s) <tip>Field(s) to be plotted on the chart(comma separated)</tip>

    <input type="text" class="input-medium" ng-model="panel.right_fl" ng-change="set_refresh(true)">

Y-Axis Label <tip>The label to be viewed on the top of Y-Axis</tip>

    <input type="text" class="input-small" ng-model="panel.right_yAxis" ng-change="set_refresh(true)">

Interpolation Method <tip>D3 Interpolation method for missing or NaN values</tip>

    <select ng-change="set_refresh(true)" placeholder="10000" class="input-medium" ng-model="panel.right_interpolate" ng-options="f for f in ['linear','step-before','basis','basis-open','basis-closed','cardinal','cardinal-open','cardinal-closed','monotone']"></select>

Show Legend <tip>Shows legend for this series when checked</tip>

    <input type="checkbox" ng-model="panel.showRightLegend" ng-checked="panel.showRightLegend">


text:
/**
 * @file ReturnValue.h
 *
 * @brief Encapsulates a return value from a method
 *
 * @date Dec 1, 2011
 * @author Alex Cunningham
 * @author Richard Roberts
 */

#include <vector>
#include <map>

#include "FileWriter.h"
#include "TypeAttributesTable.h"

#pragma once

namespace wrap {

struct ReturnValue {

	typedef enum {
		CLASS,
		EIGEN,
		BASIS,
		VOID
	} return_category;

	ReturnValue(bool enable_verbosity = true)
	: verbose(enable_verbosity), isPtr1(false), isPtr2(false),
	  isPair(false), category1(VOID), category2(VOID)
	{}

	bool verbose;
	std::string type1, type2;
	bool isPtr1, isPtr2, isPair;
	std::vector<std::string> namespaces1, namespaces2;

	return_category category1, category2;

	typedef enum {
		arg1, arg2, pair
	} pairing;

	std::string return_type(bool add_ptr, pairing p) const;

	std::string qualifiedType1(const std::string& delim = "") const;
	std::string qualifiedType2(const std::string& delim = "") const;

	std::string matlab_returnType() const;

	void wrap_result(const std::string& result, FileWriter& file, const TypeAttributesTable& typeAttributes) const;

	void wrapTypeUnwrap(FileWriter& wrapperFile) const;

};

} // \namespace wrap


text:
<!DOCTYPE html>

  <title>Cluster App</title>
  <link rel="stylesheet" type="text/css" href="css/angular-material.css">
  <link rel="stylesheet" href="css/md-data-table.css" type="text/css"/>
  <link rel="stylesheet" href="css/clusterLayout.css" type="text/css"/>

<md-toolbar flex="33">

</md-toolbar>

  <md-content class="md-whiteframe-z2 move-up" flex="80">

    <md-card flex="auto" width="100%" class="custBackground1">

      <md-toolbar layout="column" class="md-tall">

              <md-button style="width: 25%" class="md-raised md-primary" href="#/cluster/list">Cluster Manage</md-button>
              <md-button style="width: 25%"  class="md-raised md-primary" href="#/network/list">Networks</md-button>
              <md-button style="width: 25%"  class="md-raised md-primary" href="#/cluster/configlist">Configurations</md-button>

      </md-toolbar>

      <md-card-content ng-view>
      </md-card-content>
    </md-card>

  </md-content>


text:
FROM fedora:24

RUN dnf -y --setopt=deltarpm=false install yum-utils

RUN rpm --import "http://keyserver.ubuntu.com/pks/lookup?op=get&search=0x3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF"

RUN yum-config-manager --add-repo http://download.mono-project.com/repo/centos/ && \
dnf -y --setopt=deltarpm=false update

RUN dnf -y --setopt=deltarpm=false install fsharp mono-complete

RUN dnf -y --setopt=deltarpm=false install zsh

# https://github.com/fsharp-editing/Forge/releases/download/1.3.2/forge.zip
COPY ./forge.zip /root

RUN mkdir /opt/forge && cd /opt/forge && unzip /root/forge.zip && ln -vnsf /opt/forge/forge.sh /usr/local/bin/forge


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Fl. Angl. , Edn 2 2: 639 (1778)

#### Original name
Peziza stipitata Huds., 1778

### Remarks
null


text:
class Folio::Users::InvitationsController < Devise::InvitationsController
  include Folio::Users::DeviseControllerBase

  before_action :disallow_public_invitations_if_needed, only: %i[create new]

  def show
    if session[:folio_user_invited_email]
      @email = session[:folio_user_invited_email]
    else
      redirect_to new_user_invitation_path
    end
  end

  def create
    self.resource = invite_resource
    resource_invited = resource.errors.empty?

    respond_to do |format|
      # need to override devise invitable here with devise default
      format.html do
        yield resource if block_given?

        if resource_invited
          if is_flashing_format? && self.resource.invitation_sent_at
            set_flash_message :notice, :send_instructions, email: self.resource.email
          end
          if self.method(:after_invite_path_for).arity == 1
            respond_with resource, location: after_invite_path_for(current_inviter)
          else
            respond_with resource, location: after_invite_path_for(current_inviter, resource)
          end
        else
          respond_with_navigational(resource) { render :new, status: :unprocessable_entity }
        end
      end
      # custom fro JSON api
      format.json do
        @force_flash = true

        if resource_invited
          if is_flashing_format? && self.resource.invitation_sent_at
            set_flash_message :notice, :send_instructions, email: self.resource.email
          end

          if Rails.application.config.folio_users_after_ajax_sign_up_redirect
            json = {
              data: {
                url: stored_location_for(:user).presence || after_invite_path_for(current_inviter, resource),
              }
            }
          else
            json = {
              data: {
                url: after_invite_path_for(current_inviter, resource),
              }
            }
          end

          render json:, status: 200
        else
          message = t("folio.users.invitations.create.failure")

          errors = [{ status: 401, title: "Unauthorized", detail: message }]
          cell_flash = ActionDispatch::Flash::FlashHash.new
          cell_flash[:alert] = message

          html = cell("folio/devise/invitations/new",
                      resource:,
                      resource_name: :user,
                      modal: true,
                      flash: cell_flash).show

          render json: { errors:, data: html }, status: 401
        end
      end
    end
  end

  def after_invite_path_for(_inviter, resource)
    session[:folio_user_invited_email] = resource.email
    user_invitation_path
  end

  def is_flashing_format?
    if @force_flash
      true
    else
      super
    end
  end

  private
    def update_resource_params
      params.require(:user).permit(*Folio::User.controller_strong_params_for_create).to_h.merge(super)
    end

    def disallow_public_invitations_if_needed
      return if Rails.application.config.folio_users_publicly_invitable
      fail "Not allowed to publicly invite."
    end
end


text:
<?php

namespace Tests\Yepsua\Commons\Collection\Node;

use PHPUnit_Framework_TestCase;
use Yepsua\Commons\Collection\Node\TreeNode;

class TreeNodeTest extends PHPUnit_Framework_TestCase
{
    public function testList()
    {
        $parent = new TreeNode();

        $child1 = new TreeNode($parent);
        $child2 = new TreeNode($parent);

        $this->assertEquals(2, $parent->length());

        $this->assertEquals($parent, $child1->getParentNode());
        $this->assertEquals($parent, $child2->getParentNode());
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sphaerella tingens f. dianthicola Gonz. Frag.

### Remarks
null