text:
using System;
using System.Threading;
using System.Threading.Tasks;
using DocaLabs.Http.Client.Utils.JsonSerialization;
using Machine.Specifications;

namespace DocaLabs.Http.Client.Tests.Utils.JsonSerialization
{
    [Subject(typeof(JsonSerializationProvider))]
    class when_json_serialization_provider_is_used_in_default_configuration_without_any_extension_library_with_json_serialization
    {
        It should_return_default_json_serializer =
            () => JsonSerializationProvider.Serializer.ShouldBeOfType<DefaultJsonSerializer>();

        It should_return_default_json_deserializer =
            () => JsonSerializationProvider.Deserializer.ShouldBeOfType<DefaultJsonDeserializer>();
    }

    [Subject(typeof(JsonSerializationProvider))]
    class when_changing_serializer_in_json_serialization_provider
    {
        static IJsonSerializer original_serializer;
        static IJsonSerializer new_serializer;

        Cleanup after_each =
            () => JsonSerializationProvider.Serializer = original_serializer;

        Establish context = () =>
        {
            original_serializer = JsonSerializationProvider.Serializer;
            new_serializer = new TestSerializer();
        };

        Because of =
            () => JsonSerializationProvider.Serializer = new_serializer;

        It should_return_new_serializer =
            () => JsonSerializationProvider.Serializer.ShouldBeTheSameAs(new_serializer);

        class TestSerializer : IJsonSerializer
        {
            public string Serialize(object obj)
            {
                return "";
            }
        }
    }

    [Subject(typeof(JsonSerializationProvider))]
    class when_changing_deserializer_in_json_serialization_provider
    {
        static IJsonDeserializer original_deserializer;
        static IJsonDeserializer new_deserializer;

        Cleanup after_each =
            () => JsonSerializationProvider.Deserializer = original_deserializer;

        Establish context = () =>
        {
            original_deserializer = JsonSerializationProvider.Deserializer;
            new_deserializer = new TestDeserializer();
        };

        Because of =
            () => JsonSerializationProvider.Deserializer = new_deserializer;

        It should_return_new_serializer =
            () => JsonSerializationProvider.Deserializer.ShouldBeTheSameAs(new_deserializer);

        class TestDeserializer : IJsonDeserializer
        {
            public object Deserialize(string value, Type resultType)
            {
                return null;
            }
        }
    }

    [Subject(typeof(JsonSerializationProvider))]
    class when_reloading_serialization_extensions_without_any_extension_library_with_json_serialization
    {
        Establish context = () =>
        {
            JsonSerializationProvider.Serializer = new TestSerializer();
            JsonSerializationProvider.Deserializer = new TestDeserializer();
        };

        Because of =
            () => JsonSerializationProvider.ReloadSerializationExtensions();

        It should_restore_default_json_serializer =
            () => JsonSerializationProvider.Serializer.ShouldBeOfType<DefaultJsonSerializer>();

        It should_restore_default_json_deserializer =
            () => JsonSerializationProvider.Deserializer.ShouldBeOfType<DefaultJsonDeserializer>();

        class TestSerializer : IJsonSerializer
        {
            public string Serialize(object obj)
            {
                return "";
            }
        }

        class TestDeserializer : IJsonDeserializer
        {
            public object Deserialize(string value, Type resultType)
            {
                return null;
            }
        }
    }

    [Subject(typeof(JsonSerializationProvider))]
    class when_setting_serializer_to_null_in_json_serialization_provider
    {
        static Exception exception;

        Because of =
            () => exception = Catch.Exception(() => JsonSerializationProvider.Serializer = null);

        It should_return_previously_set_serializer =
            () => JsonSerializationProvider.Serializer.ShouldBeOfType<DefaultJsonSerializer>();

        It should_throw_argument_null_exception =
            () => exception.ShouldBeOfType<ArgumentNullException>();

        It should_report_value_argument =
            () => ((ArgumentNullException) exception).ParamName.ShouldEqual("value");
    }

    [Subject(typeof(JsonSerializationProvider))]
    class when_setting_deserializer_to_null_in_json_serialization_provider
    {
        static Exception exception;

        Because of =
            () => exception = Catch.Exception(() => JsonSerializationProvider.Deserializer = null);

        It should_return_previously_set_serializer =
            () => JsonSerializationProvider.Deserializer.ShouldBeOfType<DefaultJsonDeserializer>();

        It should_throw_argument_null_exception =
            () => exception.ShouldBeOfType<ArgumentNullException>();

        It should_report_value_argument =
            () => ((ArgumentNullException)exception).ParamName.ShouldEqual("value");
    }

    [Subject(typeof(JsonSerializationProvider))]
    class when_json_serialization_provider_is_used_concurrently
    {
        static int count;
        static object locker;
        static Random random;

        Establish context = () =>
        {
            count = 0;
            locker = new object();
            random = new Random();
        };

        Because of = () => Parallel.For(0, 50000, i =>
        {
            int ii;

            lock (locker)
            {
                ii = random.Next(5);
            }

            switch (ii)
            {
                case 0:
                    JsonSerializationProvider.Serializer = new DefaultJsonSerializer();
                    break;
                case 1:
                    JsonSerializationProvider.Deserializer = new DefaultJsonDeserializer();
                    break;
                case 2:
                    JsonSerializationProvider.Serializer.ShouldBeOfType<DefaultJsonSerializer>();
                    break;
                case 3:
                    JsonSerializationProvider.Deserializer.ShouldBeOfType<DefaultJsonDeserializer>();
                    break;
                case 4:
                    JsonSerializationProvider.ReloadSerializationExtensions();
                    break;
            }

            Interlocked.Increment(ref count);
        });

        It should_execute_all_operations =
            () => count.ShouldEqual(50000);
    }
}


text:
module Main where

import System.Environment (getArgs)

import Data.Either.Combinators (fromRight')
import Text.Blaze.Html.Renderer.Pretty (renderHtml)

import Parse (iParse, doc)
import Semantics (semantic)
import Compile (compile)

main :: IO ()
main = do
   [f]   <- getArgs
   s     <- readFile f
   case iParse doc f s of
        Left  err    -> print err
        Right result -> (putStr . renderHtml . compile . semantic) result

redpajama_set_name: RedPajamaGithub


text:
socket.io-p2pmesh is a WebRTC peer-to-peer mesh maintainer for node.js. It enables clients to directly communicate among each other in large networks (mesh) without ever having to communicate to the server the data which is to be transferred among clients. This takes the burden off the server which is common of large scale WebSocket applications. This component uses socket.io on the server to act as the signaler in a WebRTC connection. The client is expected to have socket.io-p2pmesh-client. The client initiates the connection, and is super easy to use.

## The Mesh Topology

The primary motivation for this was creating an efficient mesh topology that didn't overload any single client. Most existing WebRTC libraries that handle signaling allow fully connected topologies, which means that for each client in the network, it is connected to all the other clients. As you can imagine, the number of edges in a large  network grow too fast to be practical. To combat edge explosion, [Delaunay Triangulation] is used to compute an efficient network topology. On average, each client should have ~6 connections to other clients. This can be more or less for any individual client, but the average is a known property of [Delaunay Triangulation]. Below you can see how a mesh would evolve over time, with the addition and removal of clients. The blue lines represent a WebRTC connection between two clients:

![alt tag](http://i.giphy.com/xTk9ZD25IbIfVpjapO.gif)

[Delaunay Triangulation] can be computed in n-dimensional Euclidean space, although, for the present time, the mesh is computed in a 2D plane ([x,y] coords) for simplicity, as it covers many use cases.

By default, the [x,y] position of a client in the computation is completely random. This does not compute the most efficient mesh possible though. This is why, in more advanced use cases, the positioning of clients in this space can be substituted for a more desirable implementation based on the use case. Two easy, yet more efficient, examples, might be to:

1. Obtain the [lat,long] of the client's ip using some ip-geo-location lookup service. With a quick search, this looks like a free, although limited, option (https://www.npmjs.com/package/iplocation)
2. An even better approach would be to triangulate a client based on its ping to servers with known positions (physically or conceptually the network distance from the master server(s)). This would more accurately represent the network distance of clients, rather than their physical location.

## Example

It is very easy to add a p2p mesh to your application:

```js
var io = require('socket.io')(80);
var P2PMesh = require('socket.io-p2pmesh');
var p2pmesh = new P2PMesh(io);
```

That's it! When a client is connected, the mesh hooks everything up for you. The client must be running socket.io-p2pmesh-client, and connect to the namespace the mesh was provided, in the case of the example above, it would be the root namespace, but suppose you wanted to partition clients to among multiple meshes, this could be accomplished by namespacing the io instance given the P2PMesh. Likewise, the client would need to be given the correct namespace.

## API Documentation
```
//TODO - Coming soon
```
### Version
#### 0.0.1
This project is still a work in progress, and is subject to change until a stable version is reached.

### License
MIT

[//]: #
[Delaunay Triangulation]: <https://en.wikipedia.org/wiki/Delaunay_triangulation>


text:
package com.trsvax.facebook;

public enum Font {
	ARIAL,LUCIDA_GRANDE,SEGOE_UI,TAHOMA,TREBUCHET_MS,VERDANA;
}


text:
package com.lovecws.mumu.common.thirdPartyLogin.controller;

import com.alibaba.fastjson.JSONObject;
import com.lovecws.mumu.common.thirdPartyLogin.entity.LoginHelper;
import com.lovecws.mumu.common.thirdPartyLogin.entity.Resources;
import com.lovecws.mumu.common.thirdPartyLogin.entity.ThirdPartyLoginHelper;
import com.lovecws.mumu.common.thirdPartyLogin.entity.ThirdPartyUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 第三方登录控制类
 *
 * @author ShenHuaJie
 * @version 2016年5月20日 下午3:12:56
 */
@Controller
public class ThirdPartyLoginController{
	public String getService() {
		return "sysUserService";
	}

	@RequestMapping("/sns")
	public void thirdLogin(HttpServletRequest request, HttpServletResponse response, @RequestParam("t") String type) {
		String url = getRedirectUrl(request, type);
		try {
			response.sendRedirect(url);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	@RequestMapping("/sns_success")
	public String thirdLoginsuccess() {
		return "/sns/success";
	}

	@RequestMapping("/sns_bind")
	public String thirdLoginbind() {
		return "/sns/bind";
	}

	@RequestMapping("/sns_fail")
	public String thirdLoginfail() {
		return "/sns/fail";
	}

	@RequestMapping("/callback/wx")
	public String wxCallback(HttpServletRequest request, ModelMap modelMap) {
		String host = request.getHeader("host");
		try {
			String code = request.getParameter("code");
			if (StringUtils.isNotBlank(code)) {// 如果不为空
				// 获取token和openid
				Map<String, String> map = ThirdPartyLoginHelper.getWxTokenAndOpenid(code, host);
				String openId = map.get("openId");
				if (StringUtils.isNotBlank(openId)) {// 如果openID存在
					// 获取第三方用户信息存放到session中
					ThirdPartyUser thirdUser = ThirdPartyLoginHelper.getWxUserinfo(map.get("access_token"), openId);
					thirdUser.setProvider("WX");
					thirdPartyLogin(request, thirdUser);
					// 跳转到登录成功界面
					modelMap.put("retUrl", Resources.THIRDPARTY.getString("third_login_success"));
				} else {// 如果未获取到OpenID
					modelMap.put("retUrl", "-1");
				}
			} else {// 如果没有返回令牌,则直接返回到登录页面
				modelMap.put("retUrl", "-1");
			}
		} catch (Exception e) {
			modelMap.put("retUrl", "-1");
			e.printStackTrace();
		}

		return "/sns/redirect";
	}

	@RequestMapping("/callback/qq")
	public String qqCallback(HttpServletRequest request, ModelMap modelMap) {
		String host = request.getHeader("host");
		try {
			String code = request.getParameter("code");
			if (StringUtils.isNotBlank(code)) {// 如果不为空
				// 获取token和openid
				Map<String, String> map = ThirdPartyLoginHelper.getQQTokenAndOpenid(code, host);
				String openId = map.get("openId");
				if (StringUtils.isNotBlank(openId)) {// 如果openID存在
					// 获取第三方用户信息存放到session中
					ThirdPartyUser thirdUser = ThirdPartyLoginHelper.getQQUserinfo(map.get("access_token"), openId);
					thirdUser.setProvider("QQ");
					thirdPartyLogin(request, thirdUser);
					// 跳转到登录成功界面
					modelMap.put("retUrl", Resources.THIRDPARTY.getString("third_login_success"));
				} else {// 如果未获取到OpenID
					modelMap.put("retUrl", "-1");
				}
			} else {// 如果没有返回令牌,则直接返回到登录页面
				modelMap.put("retUrl", "-1");
			}
		} catch (Exception e) {
			modelMap.put("retUrl", "-1");
			e.printStackTrace();
		}

		return "/sns/redirect";
	}

	@RequestMapping("callback/sina")
	public String sinaCallback(HttpServletRequest request, ModelMap modelMap) {
		String host = request.getHeader("host");
		try {
			String code = request.getParameter("code");
			if (StringUtils.isNotBlank(code)) {// 如果不为空
				// 获取token和uid
				JSONObject json = ThirdPartyLoginHelper.getSinaTokenAndUid(code, host);
				String uid = json.getString("uid");
				if (StringUtils.isNotBlank(uid)) {// 如果uid存在
					// 获取第三方用户信息存放到session中
					ThirdPartyUser thirdUser = ThirdPartyLoginHelper.getSinaUserinfo(json.getString("access_token"),
							uid);
					thirdUser.setProvider("SINA");
					thirdPartyLogin(request, thirdUser);
					// 跳转到登录成功界面
					modelMap.put("retUrl", Resources.THIRDPARTY.getString("third_login_success"));
				} else {// 如果未获取到OpenID
						// 跳转到登录成功界面
					modelMap.put("retUrl", "-1");
				}
			} else {// 如果没有返回令牌,则直接返回到登录页面
					// 跳转到登录成功界面
				modelMap.put("retUrl", "-1");
			}
		} catch (Exception e) {
			// 跳转到登录失败界面
			modelMap.put("retUrl", "-1");
			e.printStackTrace();
		}

		return "/sns/redirect";
	}

	private void thirdPartyLogin(HttpServletRequest request, ThirdPartyUser param) {
		String clientIp = (String) request.getSession().getAttribute("USER_IP");
		LoginHelper.login("", "", clientIp);
	}

	private String getRedirectUrl(HttpServletRequest request, String type) {
		String url = "";
		String host = request.getHeader("host");
		host="www.chuasi.com";
		url = Resources.THIRDPARTY.getString("authorizeURL_" + type);
		if ("wx".equals(type)) {
			url = url + "?appid=" + Resources.THIRDPARTY.getString("app_id_" + type) + "&redirect_uri=http://" + host
					+ Resources.THIRDPARTY.getString("redirect_url_" + type) + "&response_type=code&scope="
					+ Resources.THIRDPARTY.getString("scope_" + type) + "&state=fhmj";
		} else {
			url = url + "?client_id=" + Resources.THIRDPARTY.getString("app_id_" + type) + "&response_type=code&scope="
					+ Resources.THIRDPARTY.getString("scope_" + type) + "&redirect_uri=http://" + host
					+ Resources.THIRDPARTY.getString("redirect_url_" + type);
		}
		return url;
	}
}


text:
package org.apache.eagle.storage.hbase.query.coprocessor;

import org.apache.eagle.storage.hbase.query.coprocessor.generated.AggregateProtos;
import org.apache.hadoop.hbase.client.coprocessor.Batch;

/**
 *
AggregateResultCallback Interface

 *
 * Merge coprocessor results from different regions and generate final aggregate result
 *

 *
 * @see org.apache.hadoop.hbase.client.HTableInterface
 * 		coprocessorExec(Class<T> protocol, byte[] startKey, byte[] endKey, Batch.Call<T,R> callable) throws IOException, Throwable;
 *
 */
public interface AggregateResultCallback extends Batch.Callback<AggregateProtos.AggregateResult>{
	/**
	 * Generate final result after callback from region servers
	 *
	 * @return AggregateResult
	 */
    AggregateResult result();

    /**
     * Compatible for older callback interface in 0.94 or older
     *
     * @param region
     * @param row
     * @param result
     */
    void update(byte[] region, byte[] row, AggregateResult result);
}


text:
/**
 * Service layer beans.
 */
package com.jhipsterapp.service;


text:
Managing Docker Images
======================================================================

You can give an image a new tag and then remove the old tag using docker rmi. It won't remove the image as long as it's associated to other tag.

.. code-block:: bash

  $ docker tag <old_name> <new_name>
  $ docker rmi <old_name>

Use hash from Git
------------------------------------------

One approach to tagging images is by adding the latest hash from git to the version, included as [HASH] in examples below.

You can use either the large or short versions.

.. code-block:: bash

  $ git log -1 --pretty=%H
  $ git log -1 --pretty=%h
  $ echo $(git log -1 --pretty=%H)

.. code-block:: bash

  $ docker tag organization/project:1.2.[HASH] XXXXXXXXXX.dkr.ecr.us-east-1.amazonaws.com/organization/project:1.2.[HASH]

Here the version of the project is 1.2 and we add the hash via bash command substitution. If using a script we could use an environment variable.

.. code-block:: bash

  $ docker tag organization/project:1.2.$(git log -1 --pretty=%H) XXXXXXXXXX.dkr.ecr.us-east-1.amazonaws.com/organization/project:1.2.$(git log -1 --pretty=%H)

.. code-block:: bash

  $ docker build -t XXXXXXXXXX.dkr.ecr.us-east-1.amazonaws.com/organization/project:1.2.[HASH] .
  $ docker push XXXXXXXXXX.dkr.ecr.us-east-1.amazonaws.com/organization/project:1.2.[HASH]

Use dates
------------------------------------------

For example, adding -YYYYMMDD to the version. Example shows manual approach as well as bash command substitution.

.. code-block:: bash

  $ docker tag organization/project:1.2-20181003 XXXXXXXXXX.dkr.ecr.us-east-1.amazonaws.com/organization/project:1.2-20181003
  $ docker tag organization/project:1.2-$(date +%Y%m%d) XXXXXXXXXX.dkr.ecr.us-east-1.amazonaws.com/organization/project:1.2-$(date +%Y%m%d)


text:
'use strict';

var fetch = require('node-fetch');

function wrapFetchForNode(fetch) {
  // Support schemaless URIs on the server for parity with the browser.
  // https://github.com/matthew-andrews/isomorphic-fetch/pull/10
  return function (u, options) {
    if (typeof u === 'string' && u.slice(0, 2) === '//') {
      return fetch('https:' + u, options);
    }

    return fetch(u, options);
  };
}

module.exports = function (context) {
  // Support webpack module import weirdness.
  var fetchFn = fetch.default ? fetch.default : fetch;

  // This modifies the global `node-fetch` object, which isn't great, since
  // different callers to `fetch-ponyfill` which pass a different Promise
  // implementation would each expect to have their implementation used. But,
  // given the way `node-fetch` is implemented, this is the only way to make
  // it work at all.
  if (context && context.Promise) {
    fetchFn.Promise = context.Promise;
  }

  return {
    fetch: wrapFetchForNode(fetchFn),
    Headers: fetch.Headers,
    Request: fetch.Request,
    Response: fetch.Response
  };
};


text:
beforeAll((done) => {
    global.provider.setup().then(() => done());
});

afterAll((done) => {
    global.provider.finalize().then(() => done());
});


text:
<TITLE>Review for Manon des sources (1986)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Manon des sources (1986)

reviewed by
Jeff Meyer

                             MANON OF THE SPRING
                           [**oblique spoilers**]
                                (subtitled)
                         A film review by Jeff Meyer
                          Copyright 1988 Jeff Meyer

     As anyone who has read my Seattle Film Festival reviews knows, I am a
prejudiced fellow.  And one of my biggest prejudices is French films.  I point
to their comedies and groan; I point to their dramas and grouse about
characters who I couldn't give a damn about philosophizing for hours on end
about their own petty problems (at least MY DINNER WITH ANDRE had Wally Shawn).
Sure, it's an ignorant generality to make, and I generally go to a film
regardless of national origin, but if I'm at the Festival and there's two films
of interest and one of them's French...

     What I *will* say for French films is that when they make an exception to
my bigotry, they *really* make an exception.  DIVA was an addiction for me -- I
think I saw it more times than STAR WARS.  I played LA WALLY to all hours of
the night.  I looked around for those silly blue liquid slo-mo wave machines.
The guy in the white Rolls updated The Lone Ranger to a form I could actually
enjoy again.  It was one of those films that marks a year, rather than
visa-versa.

     Well, I just completed the two-part adaptation of Pagnol's WATER OF THE
HILLS, and while I'm not infatuated with it, I am enamored of it, not to
mention being blown away and in a state of utmost admiration -- this is an
amazing film, and you should not miss it.  As many of you know, MANON OF THE
SPRING is the second part of a two-film story begun in JEAN DE FLORETTE.  I saw
the first film a year and a half ago at the Seattle Film Festival, and was
impressed and moderately entertained with its lush photography and its
demonstration of how the smallest evils could be the worst.  MANON takes the
basis of the plot in JEAN DE FLORETTE and amplifies the events of the first
film into one of the finest films I have seen this year.  PASCALI'S ISLAND was
classic tragedy being played basically on one instrument (Ben Kingsley); in
MANON, the tragedy is a symphony of photography, music, direction by Claude
Berri, and the featured performer being Yves Montand.  It is romantic, it is
heart-rending, it gives you characters whom you feel the full spectrum of
emotions for during the film's length: hatred, contempt, pity, and sympathy.
The layers of irony in this film are laid one atop another until the entire
story of JEAN DE FLORETTE has been rotated 180 degrees, and the phrase "what
goes around, comes around" is etched in your memory alongside the characters.

     The acting is good on almost all fronts: Emanuelle Beart as the grown
daughter of the hunchback Jean de Florette, who has her revenge on those
responsible for her father's death in ways both ironic and innocent, and Daniel
Auteuill as the nephew of Cesar whose adherence to his uncle's policies comes
back to haunt him in a multitude of ways.  But the performance that I will
always associate with this film, with both films, is Yves Montand as Cesar, a
casually cruel man cursed with seeing his great sin turned against him in every
manner possible.  Impersonally, one would say that he gets what he deserves in
the end, but this film and Montand delineate his character so well that I was
left thinking that *no* one deserved this kind of fate.

     But the quality of this film is not limited to the actors.  The
photography uses the wide screen to its full effect, and it lingers on people
and events and the gorgeous scenery with genius and often with perfection.
Berri directs a wedding scene towards the end which is amazing; its impact to
the plot had me holding my breath, but the way it was shot -- the wedding party
having their picture taken, their attention arrested by Cesar's approach -- is
one of those bits of cinematography that will be associated with the very best,
like the Amish rising from the wheat in the opening of WITNESS or James Dean on
the windmill in GIANT.  It has all the beauty of a painting, but is
strengthened by the fluid nature of film -- something which is uncommon in the
cinema today, where motion seems to be a reason to film in and of itself.  The
music score is as beautiful as the camera work; DOES ANYONE KNOW IF IT'S
AVAILABLE IN THE U.S.  YET?!!

Whatever else you've heard, see MANON with the following prerequisites:
        1)  See it in a wide-screen print.
        2)  See it with a good sound system.
        3)  See JEAN DE FLORETTE first.  Yes, it's understandable on its
            own, but the emotional impact MANON has after seeing its
            precursor is not something to be missed.

     I came away from MANON OF THE SPRING feeling as if I had seen a parable
about the wages of sin precisely and beautifully illustrated, using characters
both real and larger-than-life.  Pride, greed, insensitivity to your
neighbor ... all run through MANON as much more than concepts or morality.  The
portrayal of Hell that I have always found most appropriate is a state that men
and women build for themselves with their own actions; these two films reflect
the type of common cruelty that is no less mean because it is widespread, and
then pen the originators in with their own crimes, caging them with the bones
of their victim.  It is tragedy, and entertainment, and (yes) art, and I had a
damn fine time watching it.

                                        Moriarty, aka Jeff Meyer
INTERNET:     moriarty@tc.fluke.COM
Manual UUCP:  {uw-beaver, sun, microsoft}!fluke!moriarty

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
import cgi
import logging
import StringIO
import urllib

import webapp2
from webapp2_extras import json

import verify

import common
import read
import textutils
import users

import babygit.appengine
import babygit.repo
import babygit.stage

s = babygit.appengine.AEStore()

# Retrieves a prefix of a proof file, up to the named theorem. This logic is
# likely to move into the client, but for now it's a fairly straightforward
# adaptation of the older logic.
class UptoHandler(webapp2.RequestHandler):
    def __init__(self, request, response):
        self.initialize(request, response)
        self.store = s
        self.repo = babygit.repo.Repo(s)

    def get(self, arg):
        o = self.response.out
        asplit = arg.rsplit('/', 1)
        if len(asplit) < 2:
            o.write('error: expected proof_file.gh/thmname')
            return
        url = '/' + asplit[0]
        thmname = asplit[1]
        urlctx = read.UrlCtx(url)
        text = urlctx.resolve(url)
        if text is None:
            o.write('error: didn\'t find url: ' + url)
            return
        lines = text.readlines()
        digest = textutils.split_gh_file(lines)
        digestd = dict(digest)
        if digestd.has_key(thmname):
            start, end = digestd[thmname]
            lines = lines[:start]
        self.response.headers['Content-Type'] = 'text/plain; charset=UTF-8'
        o.write(''.join(lines))

class EditHandler(users.AuthenticatedHandler):
    def __init__(self, request, response):
        self.initialize(request, response)
        self.store = s
        self.repo = babygit.repo.Repo(s)

    def get(self, arg):
        o = self.response.out
        useAce = self.request.get("ace")
        asplit = arg.rsplit('/', 1)
        if len(asplit) < 2:
            o.write('expected proof_file.gh/thmname')
            return
        url = '/' + asplit[0]
        thmname = asplit[1]
        urlctx = read.UrlCtx(url)
        text = urlctx.resolve(url)
        if text is None:
            o.write('Well, didn\'t find url: ' + url)
            return
        lines = text.readlines()
        digest = textutils.split_gh_file(lines)
        digestd = dict(digest)
        logging.debug(`(thmname, json.encode(thmname), urllib.quote(arg))`)
        if self.userobj:
            auth = 'Logged in as ' + cgi.escape(self.userobj.identity)
            if self.has_write_perm:
                auth += ', ok to save.'
            else:
                auth += ', but no save permissions.'
        elif users.bypass_local_auth(self.request):
            auth = 'Not logged in, but local dev server.'
        else:
            auth = 'Not logged in, save won\'t work.'
        o.write("""
<title>Edit</title>
<link rel=stylesheet href="/static/editor.css" type="text/css">
<link rel=stylesheet href="/static/prover.css" type="text/css">
<link rel=stylesheet href="/static/common.css" type="text/css">

""")
        o.write('
')
        o.write('  ')
        o.write('  ');
        o.write('    ');
        o.write("""    edit """);
        o.write("""    dictionary """);
        o.write('  ');
        o.write('
')
        o.write('%s' % auth);
        o.write("""

Dictionary

        <button id="inferences">Inference</button>
        <button id="deductions">Deduction</button>
        <button id="unified">Unified</button>
        X

            filter: <input type="text" id="filter" class="minor-input"/>

Editor

  before: <input type="text" id="number" value="%s" class="minor-input"/>
""" % thmname)
        # TODO: Uncomment this line once we the stack working fine by itself and we can add an element
        # for closing the editor.
        # o.write("""X""")
        o.write("""

  <input type="button" id="save" onclick="log(mainpanel); GH.save(window.mainpanel.getValue(), url)" name="save" value="save"/>
  <input type="button" id="number-adder" onclick="window.direct.prover.openNumberAdder()" name="numberAdder" value="number"/>

""")
        if useAce: o.write("""

""")
        else:
            o.write('<textarea id="canvas" cols="60" rows="20" width="640" height="480" tabindex="0"></textarea>
\n')
        o.write("""
  autounify

...

\n')

def skip_blank_lines(index, lines):
    while index < len(lines) and lines[index].rstrip() == '':
        index += 1
    return index

class ErrorHandler:
    def __init__(self):
        self.first_error = None
        self.fatal_error = False
    def error_handler(self, label, msg):
        if self.first_error is None:
            self.first_error = (label, msg)
        if label == '':
            # Errors that happen inside theorem contexts can be recovered. This roughly
            # corresponds to being able to continue (-c in the command line).
            self.fatal_error = True
        return True

class SaveHandler(users.AuthenticatedHandler):
    def __init__(self, request, response):
        self.initialize(request, response)
        self.store = s
        self.repo = babygit.repo.Repo(s)

    def post(self):
        if not self.has_write_perm:
            return common.error_403(self)

        name = self.request.get('name')
        content = self.request.get('content')
        number = self.request.get('number')
        url = self.request.get('url')
        logging.debug(`url`)

        # TODO: validate the name a bit more (no / or space)

        # Edit the content into the theorem text. This is probably best done
        # client-side, but for now we'll stick with the way it worked before.

        logging.debug(`(name, content, number)`)
        urlctx = read.UrlCtx(url)
        text = urlctx.resolve(url)
        if text is None:
            lines = []
        else:
            lines = text.readlines()
        digest = textutils.split_gh_file(lines)
        digestd = dict(digest)
        # Insert before number, or at end of file if not found
        if len(digest) == 0:
            insertpt = len(lines)
        elif digestd.has_key(number):
            insertpt = digestd[number][0]
        else:
            insertpt = skip_blank_lines(digest[-1][1][1], lines)
        if digestd.has_key(name):
            start, end = digestd[name]
            end = skip_blank_lines(end, lines)
            lines[start:end] = []
            if insertpt >= end:
                insertpt -= end - start
        contentlines = content.split('\n')
        while len(contentlines) > 0 and contentlines[-1].rstrip() == '':
            contentlines.pop()
        if len(contentlines) > 0:
            if insertpt > 0 and lines[insertpt - 1].rstrip() != '':
                contentlines.insert(0, '\n')
            contentlines.append('')
        lines[insertpt:insertpt] = contentlines
        lines = [line.rstrip() for line in lines]
        newcontent = '\n'.join(lines)
        if isinstance(newcontent, unicode): newcontent = newcontent.encode('utf-8')

        o = self.response.out

        # Verify
        pipe = StringIO.StringIO(newcontent)
        urlctx = read.UrlCtx(url, pipe)
        error_handler = ErrorHandler()
        ctx = verify.VerifyCtx(urlctx, verify.run, error_handler.error_handler)
        tmpout = StringIO.StringIO()
        ctx.run(urlctx, '-', ctx, tmpout)
        logging.debug(`tmpout.getvalue()`)
        if error_handler.fatal_error:
            # TODO: plumb actual error message
            o.write(json.encode(['error', error_handler.first_error[1]]))
            return

        # Now save the new text
        git_path = str(url)
        if git_path.startswith('/'): git_path = git_path[1:]
        babygit.stage.checkout(self.repo)
        tree = babygit.stage.save(self.repo, git_path, newcontent)
        babygit.stage.add(self.repo, tree)
        author = self.identity
        msg = 'Commit from web thm editor: save ' + name + '\n'
        commitsha = babygit.stage.commit(self.repo, author, msg)
        o.write(json.encode(['ok', 'successfully saved ' + name]))


text:
<?php

namespace Candango\MyFuses\Security;

/**
 * MyFusesCredential - MyFusesCredential.php
 *
 * MyFuses credential.
 *
 * @category   security
 * @package    myfuses.util.security
 * @author     Flavio Goncalves Garcia <piraz at candango.org>
 * @since      2e0c26a744b984d6463db487a51387bb4005488e
 */
interface Credential
{
	const ALL_ACTIONS = "CAN_ACCESS_ALL_ACTIONS";

	const NO_ACTION = "CAN_ACCESS_NO_ACTION";

    public function addAttribute($attributeName, $attributeValue);

    public function getAttribute($attributeName);

    public function addRole($role);

    public function getRoles();

    public function hasRoles($roles);

    public function setRoles($roles);

    public function isExpired();

    public function setTimeout($timeout);

    public function getData();

    public function setData($data);

    /**
     * Returns if the credential is athenticated
     *
     * @return boolean
     */
    public function isAuthenticated();

    /**
     * Set credential athenticated status
     *
     * @param $authenticated boolean
     */
    public function setAuthenticated($authenticated);
}


text:
from django.conf import settings

def get(key, default):
    return getattr(settings, key, default)

# FORUM Settings
FORUM_BASE_TITLE = get('SLIMBB_FORUM_BASE_TITLE', 'Django Bulletin Board')
FORUM_META_DESCRIPTION = get('SLIMBB_FORUM_META_DESCRIPTION', '')
FORUM_META_KEYWORDS = get('SLIMBB_FORUM_META_KEYWORDS', '')
TOPIC_PAGE_SIZE = get('SLIMBB_TOPIC_PAGE_SIZE', 10)
FORUM_PAGE_SIZE = get('SLIMBB_FORUM_PAGE_SIZE', 20)
SEARCH_PAGE_SIZE = get('SLIMBB_SEARCH_PAGE_SIZE', 20)
SIGNATURE_MAX_LENGTH = get('SLIMBB_SIGNATURE_MAX_LENGTH', 1024)
SIGNATURE_MAX_LINES = get('SLIMBB_SIGNATURE_MAX_LINES', 3)
HEADER = get('SLIMBB_HEADER', 'slimbb forum')
NOFOLLOW_LINKS = get('SLIMBB_NOFOLLOW_LINKS', True)
POST_USER_SEARCH = get('SLIMBB_POST_USER_SEARCH', 1)
NOTIFICATION_HANDLER = get('SLIMBB_NOTIFICATION_HANDLER', 'slimbb.subscription.email_topic_subscribers')
JQUERY_URL = get('SLIMBB_JQUERY_URL', '//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js')

# ATTACHMENT Extension
ATTACHMENT_SUPPORT = get('SLIMBB_ATTACHMENT_SUPPORT', True)
ATTACHMENT_UPLOAD_TO = get('SLIMBB_ATTACHMENT_UPLOAD_TO', 'slimbb/attachments')
ATTACHMENT_SIZE_LIMIT = get('SLIMBB_ATTACHMENT_SIZE_LIMIT', 1024 * 1024)


text:
package com.phloc.commons.typeconvert;

public class MockImplementation implements IMockInterface
{
  private final String m_s;

  public MockImplementation ()
  {
    this ("any");
  }

  public MockImplementation (final String s)
  {
    m_s = s;
  }

  public String getAny ()
  {
    return m_s;
  }
}


text:
package org.kordamp.json.xml;

import org.custommonkey.xmlunit.XMLTestCase;
import org.kordamp.ezmorph.test.ArrayAssertions;
import org.kordamp.json.JSON;
import org.kordamp.json.JSONArray;
import org.kordamp.json.JSONFunction;
import org.kordamp.json.JSONNull;
import org.kordamp.json.JSONObject;

import java.util.Arrays;

/**
 * @author Andres Almiray
 */
public class TestXMLSerializer_writes extends XMLTestCase {
    private XMLSerializer xmlSerializer;

    public TestXMLSerializer_writes(String testName) {
        super(testName);
    }

    public static void main(String[] args) {
        junit.textui.TestRunner.run(TestXMLSerializer_writes.class);
    }

    public void testWrite_null() throws Exception {
        String expected = "<o null=\"true\"/>";
        String xml = xmlSerializer.write(null);
        assertXMLEqual(expected, xml);
    }

    public void testWriteBooleanArray() throws Exception {
        JSONArray jsonArray = JSONArray.fromObject("[true,false]");
        String expected = "<e type=\"boolean\">true</e><e type=\"boolean\">false</e>";
        String xml = xmlSerializer.write(jsonArray);
        assertXMLEqual(expected, xml);
    }

    public void testWriteEmptyObject() throws Exception {
        JSONObject jsonObject = new JSONObject();
        String expected = "<o/>";
        String xml = xmlSerializer.write(jsonObject);
        assertXMLEqual(expected, xml);
    }

    public void testWriteFunctionArray() throws Exception {
        JSONArray jsonArray = JSONArray.fromObject("[function(a){ return a; }]");
        String expected = "<e type=\"function\" params=\"a\"><![CDATA[return a;]]></e>";
        String xml = xmlSerializer.write(jsonArray);
        assertXMLEqual(expected, xml);
    }

    public void testWriteFunctionArray_noTypeHintsCompatibility() throws Exception {
        JSONArray jsonArray = JSONArray.fromObject("[function(a){ return a; }]");
        xmlSerializer.setTypeHintsCompatibility(false);
        String expected = "<e json_type=\"function\" json_params=\"a\"><![CDATA[return a;]]></e>";
        String xml = xmlSerializer.write(jsonArray);
        assertXMLEqual(expected, xml);
    }

    public void testWriteJSONArray_collapseProperties() throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.element("duplicated", "json1");
        jsonObject.accumulate("duplicated", "json2");
        jsonObject.getJSONArray("duplicated").setExpandElements(true);
        JSONArray jsonArray = new JSONArray().element(jsonObject);
        String expected = "<e class=\"object\"><duplicated type=\"string\">json1</duplicated><duplicated type=\"string\">json2</duplicated></e>";
        xmlSerializer.setExpandableProperties(new String[]{"duplicated"});
        String xml = xmlSerializer.write(jsonArray);
        assertXMLEqual(expected, xml);
        ArrayAssertions.assertEquals(new String[]{"duplicated"}, xmlSerializer.getExpandableProperties());

        jsonObject.getJSONArray("duplicated").setExpandElements(false);
        jsonArray = new JSONArray().element(jsonObject);
        expected = "<e class=\"object\"><duplicated class=\"array\"><e type=\"string\">json1</e><e type=\"string\">json2</e></duplicated></e>";
        xmlSerializer.setExpandableProperties(null);
        xml = xmlSerializer.write(jsonArray);
        assertXMLEqual(expected, xml);
        ArrayAssertions.assertEquals(new String[0], xmlSerializer.getExpandableProperties());
    }

    public void testWriteJSONNull() throws Exception {
        String expected = "<o null=\"true\"/>";
        String xml = xmlSerializer.write(JSONNull.getInstance());
        assertXMLEqual(expected, xml);
    }

    public void testWriteJSONNull_encoding() throws Exception {
        String expected = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
        String xml = xmlSerializer.write(JSONNull.getInstance(), "ISO-8859-1");
        assertTrue(xml.startsWith(expected));
    }

    public void testWriteJSONObject_collapseProperties() throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.element("duplicated", "json1");
        jsonObject.accumulate("duplicated", "json2");
        jsonObject.getJSONArray("duplicated")
            .setExpandElements(true);
        String expected = "<o><duplicated type=\"string\">json1</duplicated><duplicated type=\"string\">json2</duplicated></o>";
        xmlSerializer.setExpandableProperties(new String[]{"duplicated"});
        String xml = xmlSerializer.write(jsonObject);
        assertXMLEqual(expected, xml);
    }

    public void testWriteMultiBooleanArray() throws Exception {
        JSONArray jsonArray = JSONArray.fromObject("[true,false,[true,false]]");
        String expected = "<e type=\"boolean\">true</e><e type=\"boolean\">false</e><e class=\"array\"><e type=\"boolean\">true</e><e type=\"boolean\">false</e></e>";
        String xml = xmlSerializer.write(jsonArray);
        assertXMLEqual(expected, xml);
    }

    public void testWriteMultiNumberArray() throws Exception {
        JSONArray jsonArray = JSONArray.fromObject("[1.1,2,[3,4.4]]");
        String expected = "<e type=\"number\">1.1</e><e type=\"number\">2</e><e class=\"array\"><e type=\"number\">3</e><e type=\"number\">4.4</e></e>";
        String xml = xmlSerializer.write(jsonArray);
        assertXMLEqual(expected, xml);
    }

    public void testWriteMultiStringArray() throws Exception {
        JSONArray jsonArray = JSONArray.fromObject("['1.1','2',['3','4.4']]");
        String expected = "<e type=\"string\">1.1</e><e type=\"string\">2</e><e class=\"array\"><e type=\"string\">3</e><e type=\"string\">4.4</e></e>";
        String xml = xmlSerializer.write(jsonArray);
        assertXMLEqual(expected, xml);
    }

    public void testWriteNestedNullObject() throws Exception {
        JSONObject jsonObject = JSONObject.fromObject("{\"nested\":null}");
        String expected = "<o><nested class=\"object\" null=\"true\"/></o>";
        String xml = xmlSerializer.write(jsonObject);
        assertXMLEqual(expected, xml);
    }

    public void testWriteNullObject() throws Exception {
        JSONObject jsonObject = new JSONObject(true);
        String expected = "<o null=\"true\"/>";
        String xml = xmlSerializer.write(jsonObject);
        assertXMLEqual(expected, xml);
    }

    public void testWriteNullObject_noTypeHintsCompatibility() throws Exception {
        JSONObject jsonObject = new JSONObject(true);
        String expected = "<o json_null=\"true\"/>";
        xmlSerializer.setTypeHintsCompatibility(false);
        String xml = xmlSerializer.write(jsonObject);
        assertXMLEqual(expected, xml);
    }

    public void testWriteNullObjectArray() throws Exception {
        JSONArray jsonArray = JSONArray.fromObject("[null,null]");
        String expected = "<e class=\"object\" null=\"true\"/><e class=\"object\" null=\"true\"/>";
        String xml = xmlSerializer.write(jsonArray);
        assertXMLEqual(expected, xml);
    }

    public void testWriteNullObjectArray_noTypeHintsCompatibility() throws Exception {
        JSONArray jsonArray = JSONArray.fromObject("[null,null]");
        String expected = "<e json_class=\"object\" json_null=\"true\"/><e json_class=\"object\" json_null=\"true\"/>";
        xmlSerializer.setTypeHintsCompatibility(false);
        String xml = xmlSerializer.write(jsonArray);
        assertXMLEqual(expected, xml);
    }

    public void testWriteNumberArray() throws Exception {
        JSONArray jsonArray = JSONArray.fromObject("[1.1,2]");
        String expected = "<e type=\"number\">1.1</e><e type=\"number\">2</e>";
        String xml = xmlSerializer.write(jsonArray);
        assertXMLEqual(expected, xml);
    }

    public void testWriteObject() throws Exception {
        JSONObject jsonObject = JSONObject.fromObject("{\"name\":\"json\"}");
        String expected = "<o><name type=\"string\">json</name></o>";
        String xml = xmlSerializer.write(jsonObject);
        assertXMLEqual(expected, xml);
    }

    public void testWriteObject_full_types() throws Exception {
        JSONObject jsonObject = JSONObject.fromObject("{\"string\":\"json\",\"int\":1,\"bool\":true,\"array\":[1.1,2],\"nested_null\":null,\"nested\":{\"name\":\"json\"},\"func\":function(a){ return a; }}");
        String expected = "<o><string type=\"string\">json</string>" + "<int type=\"number\">1</int>"
            + "<bool type=\"boolean\">true</bool>"
            + "<array class=\"array\"><e type=\"number\">1.1</e><e type=\"number\">2</e></array>"
            + "<nested_null class=\"object\" null=\"true\"/>"
            + "<nested class=\"object\"><name type=\"string\">json</name></nested>"
            + "<func type=\"function\" params=\"a\"><![CDATA[return a;]]></func>" + "</o>";
        String xml = xmlSerializer.write(jsonObject);
        assertXMLEqual(expected, xml);
    }

    public void testWriteObject_withAttributes() throws Exception {
        JSONObject jsonObject = new JSONObject().element("@name", "json")
            .element("string", "json");
        String expected = "<o name=\"json\"><string type=\"string\">json</string></o>";
        String xml = xmlSerializer.write(jsonObject);
        assertXMLEqual(expected, xml);
    }

    public void testWriteObject_withNamespacePrefix() throws Exception {
        JSONObject jsonObject = JSONObject.fromObject("{\"ns:name\":\"json\"}");
        String expected = "<o><ns:name type=\"string\">json</ns:name></o>";
        xmlSerializer.setNamespaceLenient(true);
        String xml = xmlSerializer.write(jsonObject);
        assertTrue(xml.trim()
            .endsWith(expected));
    }

    public void testWriteObject_withNamespaces() throws Exception {
        JSONObject jsonObject = JSONObject.fromObject("{\"ns:name\":\"json\"}");
        String expected = "<o xmlns=\"http://json.org\" "
            + "xmlns:ns=\"http://json.org/ns-schema\"><ns:name type=\"string\" >json</ns:name></o>";
        xmlSerializer.setNamespace(null, "http://json.org");
        xmlSerializer.addNamespace("ns", "http://json.org/ns-schema");
        String xml = xmlSerializer.write(jsonObject);
        assertXMLEqual(expected, xml);
    }

    public void testWriteObject_withNamespaces_element() throws Exception {
        JSONObject jsonObject = JSONObject.fromObject("{\"ns:name\":\"json\"}");
        String expected = "<o><ns:name xmlns=\"http://json.org\" "
            + "xmlns:ns=\"http://json.org/ns-schema\" type=\"string\" >json</ns:name></o>";
        xmlSerializer.setNamespace(null, "http://json.org", "ns:name");
        xmlSerializer.addNamespace("ns", "http://json.org/ns-schema", "ns:name");
        String xml = xmlSerializer.write(jsonObject);
        assertXMLEqual(expected, xml);
    }

    public void testNamespaces() throws Exception {
        assertTrue(xmlSerializer.getElementNamespace(null).isEmpty());

        assertTrue(xmlSerializer.getRootNamespace().isEmpty());
        assertTrue(xmlSerializer.getElementNamespace("ns:name").isEmpty());

        xmlSerializer.addNamespace(null, null, "ns:name");
        assertTrue(xmlSerializer.getRootNamespace().isEmpty());
        assertTrue(xmlSerializer.getElementNamespace("ns:name").isEmpty());

        xmlSerializer.addNamespace(null, "http://json.org", null);
        assertFalse(xmlSerializer.getRootNamespace().isEmpty());
        assertTrue(xmlSerializer.getElementNamespace("ns:name").isEmpty());
        xmlSerializer.clearNamespaces();

        xmlSerializer.addNamespace(null, "http://json.org", "ns:name");
        assertTrue(xmlSerializer.getRootNamespace().isEmpty());
        assertFalse(xmlSerializer.getElementNamespace("ns:name").isEmpty());
        xmlSerializer.clearNamespaces();

        xmlSerializer.addNamespace("ns", "http://json.org/ns-schema", null);
        assertFalse(xmlSerializer.getRootNamespace().isEmpty());
        assertTrue(xmlSerializer.getElementNamespace("ns:name").isEmpty());
        xmlSerializer.clearNamespaces("ns:name");
        assertFalse(xmlSerializer.getRootNamespace().isEmpty());
        assertTrue(xmlSerializer.getElementNamespace("ns:name").isEmpty());
        xmlSerializer.clearNamespaces("");
        assertTrue(xmlSerializer.getRootNamespace().isEmpty());
        assertTrue(xmlSerializer.getElementNamespace("ns:name").isEmpty());

        xmlSerializer.addNamespace("ns", "http://json.org/ns-schema");
        xmlSerializer.addNamespace("ns", "http://json.org/ns-schema", "ns:name");
        xmlSerializer.removeNamespace("");
        assertFalse(xmlSerializer.getRootNamespace().isEmpty());
        assertFalse(xmlSerializer.getElementNamespace("ns:name").isEmpty());

        xmlSerializer.removeNamespace("ns");
        assertTrue(xmlSerializer.getRootNamespace().isEmpty());
        assertFalse(xmlSerializer.getElementNamespace("ns:name").isEmpty());

        xmlSerializer.addNamespace("ns", "http://json.org/ns-schema");
        xmlSerializer.removeNamespace("ns", null);
        assertTrue(xmlSerializer.getRootNamespace().isEmpty());
        assertFalse(xmlSerializer.getElementNamespace("ns:name").isEmpty());

        xmlSerializer.addNamespace("ns", "http://json.org/ns-schema");
        xmlSerializer.removeNamespace("ns", "ns:name");
        assertFalse(xmlSerializer.getRootNamespace().isEmpty());
        assertTrue(xmlSerializer.getElementNamespace("ns:name").isEmpty());

        xmlSerializer.clearNamespaces();

        xmlSerializer.setNamespace(null, null, "ns:name");
        assertTrue(xmlSerializer.getRootNamespace().isEmpty());
        assertTrue(xmlSerializer.getElementNamespace("ns:name").isEmpty());

        xmlSerializer.setNamespace(null, "http://json.org", null);
        assertFalse(xmlSerializer.getRootNamespace().isEmpty());
        assertTrue(xmlSerializer.getElementNamespace("ns:name").isEmpty());
        xmlSerializer.clearNamespaces();

        xmlSerializer.setNamespace(null, "http://json.org", "ns:name");
        assertTrue(xmlSerializer.getRootNamespace().isEmpty());
        assertFalse(xmlSerializer.getElementNamespace("ns:name").isEmpty());
        xmlSerializer.clearNamespaces();

        xmlSerializer.setNamespace("ns", "http://json.org/ns-schema", null);
        assertFalse(xmlSerializer.getRootNamespace().isEmpty());
        assertTrue(xmlSerializer.getElementNamespace("ns:name").isEmpty());
        xmlSerializer.clearNamespaces("ns:name");

        xmlSerializer.setNamespace("ns", "http://json.org/ns-schema", "ns:name");
        xmlSerializer.setNamespace("ns", "http://json.org/ns-schema", "ns:name");
        xmlSerializer.removeNamespace("");
        assertFalse(xmlSerializer.getRootNamespace().isEmpty());
        assertFalse(xmlSerializer.getElementNamespace("ns:name").isEmpty());
    }

    public void testWriteObject_withText() throws Exception {
        JSONObject jsonObject = new JSONObject().element("#text", "json")
            .element("string", "json");
        String expected = "<o>json<string type=\"string\">json</string></o>";
        String xml = xmlSerializer.write(jsonObject);
        assertXMLEqual(expected, xml);
    }

    public void testWriteObject_withText_2() throws Exception {
        JSONObject jsonObject = new JSONObject().element("#text", JSONArray.fromObject("['json','json']"))
            .element("string", "json");
        String expected = "<o>jsonjson<string type=\"string\">json</string></o>";
        String xml = xmlSerializer.write(jsonObject);
        assertXMLEqual(expected, xml);
    }

    public void testWriteObjectArray() throws Exception {
        JSONArray jsonArray = JSONArray.fromObject("[{\"name\":\"json\"}]");
        String expected = "<e class=\"object\"><name type=\"string\">json</name></e>";
        String xml = xmlSerializer.write(jsonArray);
        assertXMLEqual(expected, xml);
    }

    public void testWriteStringArray() throws Exception {
        JSONArray jsonArray = JSONArray.fromObject("['1','2']");
        String expected = "<e type=\"string\">1</e><e type=\"string\">2</e>";
        String xml = xmlSerializer.write(jsonArray);
        assertXMLEqual(expected, xml);
    }

    public void testWriteWithNamespace() throws Exception {
        JSONObject jsonObject = new JSONObject().element("@xmlns", "http://json.org/json/1.0")
            .element("@xmlns:ns", "http://www.w3.org/2001/XMLSchema-instance")
            .element("ns:string", "json")
            .element("ns:number", "1");
        String expected = "<o xmlns=\"http://json.org/json/1.0\""
            + " xmlns:ns=\"http://www.w3.org/2001/XMLSchema-instance\">"
            + "<ns:number type=\"string\">1</ns:number><ns:string type=\"string\">json</ns:string></o>";
        String xml = xmlSerializer.write(jsonObject);
        assertXMLEqual(expected, xml);
    }

    public void testWriteWithCustomNames_1() throws Exception {
        JSONObject root = new JSONObject()
            .element("items", JSONArray.fromObject(Arrays.asList("one", JSONObject.fromObject("{\"name\":\"json\"}"))));
        String expected = "<root><items class=\"array\"><element type=\"string\">one</element><element class=\"object\"><name type=\"string\">json</name></element></items></root>";
        xmlSerializer.setRootName("root");
        xmlSerializer.setElementName("element");
        String xml = xmlSerializer.write(root);
        assertXMLEqual(expected, xml);

        expected = "<o><items class=\"array\"><e type=\"string\">one</e><e class=\"object\"><name type=\"string\">json</name></e></items></o>";
        xmlSerializer.setRootName("");
        xmlSerializer.setElementName("");
        xml = xmlSerializer.write(root);
        assertXMLEqual(expected, xml);
    }

    public void testWriteWithCustomNames_2() throws Exception {
        JSONObject root = new JSONObject()
            .element("items", JSONArray.fromObject(Arrays.asList("one", JSONObject.fromObject("{\"name\":\"json\"}"))));
        String expected = "<object><items class=\"array\"><element type=\"string\">one</element><element class=\"object\"><name type=\"string\">json</name></element></items></object>";
        xmlSerializer.setObjectName("object");
        xmlSerializer.setElementName("element");
        String xml = xmlSerializer.write(root);
        assertXMLEqual(expected, xml);

        expected = "<o><items class=\"array\"><e type=\"string\">one</e><e class=\"object\"><name type=\"string\">json</name></e></items></o>";
        xmlSerializer.setObjectName("");
        xmlSerializer.setElementName("");
        xml = xmlSerializer.write(root);
        assertXMLEqual(expected, xml);
    }

    public void testWriteWithCustomNames_3() throws Exception {
        JSONArray root = JSONArray.fromObject("['1','2']");
        String expected = "<array><element type=\"string\">1</element><element type=\"string\">2</element></array>";
        xmlSerializer.setArrayName("array");
        xmlSerializer.setElementName("element");
        String xml = xmlSerializer.write(root);
        assertXMLEqual(expected, xml);

        expected = "<e type=\"string\">1</e><e type=\"string\">2</e>";
        xmlSerializer.setArrayName("");
        xmlSerializer.setElementName("");
        xml = xmlSerializer.write(root);
        assertXMLEqual(expected, xml);
    }

    public void testTypeHintsEnabled() throws Exception {
        JSON json = new JSONObject()
            .element("boolean", true)
            .element("number", 1)
            .element("string", "string")
            .element("fun1", JSONFunction.parse("function() {}"))
            .element("fun2", "function() {}")
            .element("object", JSONObject.fromObject("{\"name\":\"json\"}"))
            .element("array", JSONArray.fromObject("['1','2']"))
            .element("nil", JSONNull.getInstance());

        String expected = "<o><boolean type=\"boolean\">true</boolean><number type=\"number\">1</number><string type=\"string\">string</string>" +
            "<fun1 type=\"function\" params=\"\"><![CDATA[]]></fun1><fun2 type=\"function\" params=\"\"><![CDATA[]]></fun2>" +
            "<object class=\"object\"><name type=\"string\">json</name></object>" +
            "<array class=\"array\"><e type=\"string\">1</e><e type=\"string\">2</e></array><nil class=\"object\" null=\"true\"/></o>";
        String xml = xmlSerializer.write(json);
        assertXMLEqual(expected, xml);

        xmlSerializer.setTypeHintsEnabled(false);
        expected = "<o><boolean>true</boolean><number>1</number><string>string</string>" +
            "<fun1 params=\"\"><![CDATA[]]></fun1><fun2 params=\"\"><![CDATA[]]></fun2>" +
            "<object><name>json</name></object>" +
            "<array><e>1</e><e>2</e></array><nil null=\"true\"/></o>";
        xml = xmlSerializer.write(json);
        assertXMLEqual(expected, xml);
    }

    protected void setUp() throws Exception {
        super.setUp();
        xmlSerializer = new XMLSerializer();
    }
}


text:
package com.navercorp.pinpoint.collector.cluster;

import com.navercorp.pinpoint.rpc.Future;
import com.navercorp.pinpoint.rpc.ResponseMessage;
import com.navercorp.pinpoint.rpc.server.ChannelProperties;
import com.navercorp.pinpoint.rpc.server.PinpointServer;
import com.navercorp.pinpoint.thrift.io.TCommandType;
import com.navercorp.pinpoint.thrift.io.TCommandTypeVersion;
import org.apache.thrift.TBase;

import java.util.List;
import java.util.Objects;

/**
 * @author koo.taejin
 */
public class ThriftAgentConnection implements ClusterPoint<byte[]> {

    private final PinpointServer pinpointServer;

    private final AgentInfo agentInfo;

    private final List<TCommandType> supportCommandList;

    public static ClusterPoint<byte[]> newClusterPoint(PinpointServer pinpointServer, ChannelProperties channelProperties) {
        AgentInfo agentInfo = newAgentInfo(channelProperties);
        List<TCommandType> supportCommandList = SupportedCommandUtils.newSupportCommandList(channelProperties.getSupportCommand());
        return new ThriftAgentConnection(pinpointServer, agentInfo, supportCommandList);
    }

    public ThriftAgentConnection(PinpointServer pinpointServer, AgentInfo agentInfo, List<TCommandType> supportCommandList) {
        this.pinpointServer = Objects.requireNonNull(pinpointServer, "pinpointServer");
        this.agentInfo = Objects.requireNonNull(agentInfo, "agentInfo");
        this.supportCommandList = Objects.requireNonNull(supportCommandList, "supportCommandList");
    }

    private static AgentInfo newAgentInfo(ChannelProperties channelProperties) {
        String applicationName = channelProperties.getApplicationName();

        String agentId = channelProperties.getAgentId();

        long startTimeStamp = channelProperties.getStartTime();

        String version = channelProperties.getAgentVersion();

        return new AgentInfo(applicationName, agentId, startTimeStamp, version);
    }

    @Override
    public Future<ResponseMessage> request(byte[] payload) {
        return pinpointServer.request(payload);
    }

    @Override
    public AgentInfo getDestAgentInfo() {
        return agentInfo;
    }

    @Override
    public boolean isSupportCommand(TBase<?, ?> command) {
        for (TCommandType supportCommand : supportCommandList) {
            if (supportCommand.getClazz() == command.getClass()) {
                return true;
            }
        }

        TCommandTypeVersion commandVersion = TCommandTypeVersion.getVersion(agentInfo.getVersion());
        if (commandVersion.isSupportCommand(command)) {
            return true;
        }

        return false;
    }

    public PinpointServer getPinpointServer() {
        return pinpointServer;
    }

    @Override
    public String toString() {
        StringBuilder log = new StringBuilder(32);
        log.append(this.getClass().getSimpleName());
        log.append("(");
        log.append(agentInfo);
        log.append(", supportCommandList:");
        log.append(supportCommandList);
        log.append(", pinpointServer:");
        log.append(pinpointServer);
        log.append(")");

        return log.toString();
    }

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

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof ThriftAgentConnection)) {
            return false;
        }

        if (this.getPinpointServer() == ((ThriftAgentConnection) obj).getPinpointServer()) {
            return true;
        }

        return false;
    }

}


text:
__author__ = 'Kevin J. Qiu'
__email__ = 'kevin@idempotent.ca'
__version__ = '0.2.0'

from .service import MockService  # noqa


text:
using Google.Api.Ads.AdManager.Lib;
using Google.Api.Ads.AdManager.v202211;

using System;

namespace Google.Api.Ads.AdManager.Examples.CSharp.v202211
{
    /// <summary>
    /// This code example creates new companies. To determine which companies
    /// exist, run GetAllCompanies.cs.
    /// </summary>
    public class CreateCompanies : SampleBase
    {
        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get
            {
                return "This code example creates new companies. To determine which companies " +
                    "exist, run GetAllCompanies.cs.";
            }
        }

        /// <summary>
        /// Main method, to run this code example as a standalone application.
        /// </summary>
        public static void Main()
        {
            CreateCompanies codeExample = new CreateCompanies();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(new AdManagerUser());
        }

        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (CompanyService companyService = user.GetService<CompanyService>())
            {
                // Create an array to store local company objects.
                Company[] companies = new Company[5];

                for (int i = 0; i < 5; i++)
                {
                    Company company = new Company();
                    company.name = string.Format("Advertiser #{0}", i);
                    company.type = CompanyType.ADVERTISER;
                    companies[i] = company;
                }

                try
                {
                    // Create the companies on the server.
                    companies = companyService.createCompanies(companies);

                    if (companies != null && companies.Length > 0)
                    {
                        foreach (Company company in companies)
                        {
                            Console.WriteLine(
                                "A company with ID = '{0}', name = '{1}' and type = '{2}' was" +
                                " created.", company.id, company.name, company.type);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No companies created.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to create company. Exception says \"{0}\"",
                        e.Message);
                }
            }
        }
    }
}


text:
package org.apache.jackrabbit.jcr2spi;

import org.apache.jackrabbit.jcr2spi.hierarchy.HierarchyEntry;
import org.apache.jackrabbit.jcr2spi.hierarchy.HierarchyManager;
import org.apache.jackrabbit.jcr2spi.hierarchy.NodeEntry;
import org.apache.jackrabbit.jcr2spi.hierarchy.PropertyEntry;
import org.apache.jackrabbit.jcr2spi.state.ItemState;
import org.apache.jackrabbit.jcr2spi.state.ItemStateCreationListener;
import org.apache.jackrabbit.jcr2spi.state.NodeState;
import org.apache.jackrabbit.jcr2spi.state.PropertyState;
import org.apache.jackrabbit.jcr2spi.state.Status;
import org.apache.jackrabbit.jcr2spi.util.LogUtil;
import org.apache.jackrabbit.jcr2spi.version.VersionHistoryImpl;
import org.apache.jackrabbit.jcr2spi.version.VersionImpl;
import org.apache.jackrabbit.spi.Name;
import org.apache.jackrabbit.spi.Path;
import org.apache.jackrabbit.spi.commons.name.NameConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jcr.Item;
import javax.jcr.ItemNotFoundException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Workspace;
import java.util.Iterator;

/**
 * ItemManagerImpl implements the ItemManager interface.
 */
public class ItemManagerImpl implements ItemManager, ItemStateCreationListener {

    private static Logger log = LoggerFactory.getLogger(ItemManagerImpl.class);

    private final SessionImpl session;

    private final HierarchyManager hierMgr;

    /**
     * A cache for item instances created by this ItemManagerImpl.
     *
     * The ItemStates act as keys for the map. In contrast to
     * o.a.j.core the item state are copied to transient space for reading and
     * will therefor not change upon transient modifications.
     */
    private final ItemCache itemCache;

    /**
     * Creates a new per-session instance ItemManagerImpl instance.
     *
     * @param hierMgr HierarchyManager associated with the new instance
     * @param session the session associated with the new instance
     * @param cache the ItemCache to be used.
     */
    ItemManagerImpl(HierarchyManager hierMgr, SessionImpl session, ItemCache cache) {
        this.hierMgr = hierMgr;
        this.session = session;
        itemCache = cache;

        // start listening to creation of ItemStates upon batch-reading in the
        // workspace item state factory.
        Workspace wsp = session.getWorkspace();
        if (wsp instanceof WorkspaceImpl) {
            ((WorkspaceImpl) wsp).getItemStateFactory().addCreationListener(this);
        }
    }

    //--------------------------------------------------------< ItemManager >---
    /**
     * @see ItemManager#dispose()
     */
    public void dispose() {
        // stop listening
        Workspace wsp = session.getWorkspace();
        if (wsp instanceof WorkspaceImpl) {
            ((WorkspaceImpl) wsp).getItemStateFactory().removeCreationListener(this);
        }
        // ... and clear the cache.
        itemCache.clear();
    }

    /**
     * @see ItemManager#nodeExists(Path)
     */
    public boolean nodeExists(Path path) throws RepositoryException {
        try {
            // session-sanity & permissions are checked upon itemExists(ItemState)
            NodeState nodeState = hierMgr.getNodeState(path);
            return itemExists(nodeState);
        } catch (PathNotFoundException pnfe) {
            return false;
        } catch (ItemNotFoundException infe) {
            return false;
        }
    }

    /**
     * @see ItemManager#propertyExists(Path)
     */
    public boolean propertyExists(Path path) throws RepositoryException {
        try {
            // session-sanity & permissions are checked upon itemExists(ItemState)
            PropertyState propState = hierMgr.getPropertyState(path);
            return itemExists(propState);
        } catch (PathNotFoundException pnfe) {
            return false;
        } catch (ItemNotFoundException infe) {
            return false;
        }
    }

    /**
     * @see ItemManager#itemExists(HierarchyEntry)
     */
    public boolean itemExists(HierarchyEntry hierarchyEntry) throws RepositoryException {
        try {
            // session-sanity & permissions are checked upon itemExists(ItemState)
            ItemState state = hierarchyEntry.getItemState();
            return itemExists(state);
        } catch (ItemNotFoundException e) {
            return false;
        }
    }

    /**
     *
     * @param itemState
     * @return
     */
    private boolean itemExists(ItemState itemState) {
        try {
            // check sanity of session
            session.checkIsAlive();
            // return true, if ItemState is valid. Access rights are granted,
            // otherwise the state would not have been retrieved.
            return itemState.isValid();
        } catch (ItemNotFoundException infe) {
            return false;
        } catch (RepositoryException re) {
            return false;
        }
    }

    /**
     * @see ItemManager#getNode(Path)
     */
    public synchronized Node getNode(Path path) throws PathNotFoundException, RepositoryException {
        NodeEntry nodeEntry = hierMgr.getNodeEntry(path);
        try {
            return (Node) getItem(nodeEntry);
        } catch (ItemNotFoundException infe) {
            throw new PathNotFoundException(LogUtil.safeGetJCRPath(path, session.getPathResolver()));
        }
    }

    /**
     * @see ItemManager#getProperty(Path)
     */
    public synchronized Property getProperty(Path path) throws PathNotFoundException, RepositoryException {
        PropertyEntry propertyEntry = hierMgr.getPropertyEntry(path);
        try {
            return (Property) getItem(propertyEntry);
        } catch (ItemNotFoundException infe) {
            throw new PathNotFoundException(LogUtil.safeGetJCRPath(path, session.getPathResolver()));
        }
    }

    /**
     * @see ItemManager#getItem(HierarchyEntry)
     */
    public Item getItem(HierarchyEntry hierarchyEntry) throws ItemNotFoundException, RepositoryException {
        session.checkIsAlive();
        ItemState state = hierarchyEntry.getItemState();
        if (!state.isValid()) {
            throw new ItemNotFoundException(LogUtil.safeGetJCRPath(state, session.getPathResolver()));
        }

        // first try to access item from cache
        Item item = itemCache.getItem(state);
        // not yet in cache, need to create instance
        if (item == null) {
            // create instance of item
            if (hierarchyEntry.denotesNode()) {
                item = createNodeInstance((NodeState) state);
            } else {
                item = createPropertyInstance((PropertyState) state);
            }
        }
        return item;
    }

    /**
     * @see ItemManager#hasChildNodes(NodeEntry)
     */
    public synchronized boolean hasChildNodes(NodeEntry parentEntry)
            throws ItemNotFoundException, RepositoryException {
        // check sanity of session
        session.checkIsAlive();

        Iterator<NodeEntry> iter = parentEntry.getNodeEntries();
        while (iter.hasNext()) {
            try {
                // check read access by accessing the nodeState (implicit validation check)
                NodeEntry entry = iter.next();
                entry.getNodeState();
                return true;
            } catch (ItemNotFoundException e) {
                // should not occur. ignore
                log.debug("Failed to access node state.", e);
            }
        }
        return false;
    }

    /**
     * @see ItemManager#getChildNodes(NodeEntry)
     */
    public synchronized NodeIterator getChildNodes(NodeEntry parentEntry)
            throws ItemNotFoundException, RepositoryException {
        // check sanity of session
        session.checkIsAlive();

        Iterator<NodeEntry> it = parentEntry.getNodeEntries();
        return new LazyItemIterator(this, it);
    }

    /**
     * @see ItemManager#hasChildProperties(NodeEntry)
     */
    public synchronized boolean hasChildProperties(NodeEntry parentEntry)
            throws ItemNotFoundException, RepositoryException {
        // check sanity of session
        session.checkIsAlive();

        Iterator<PropertyEntry> iter = parentEntry.getPropertyEntries();
        while (iter.hasNext()) {
            try {
                PropertyEntry entry = iter.next();
                // check read access by accessing the propState (also implicit validation).
                entry.getPropertyState();
                return true;
            } catch (ItemNotFoundException e) {
                // should not occur. ignore
                log.debug("Failed to access node state.", e);
            }
        }
        return false;
    }

    /**
     * @see ItemManager#getChildProperties(NodeEntry)
     */
    public synchronized PropertyIterator getChildProperties(NodeEntry parentEntry)
            throws ItemNotFoundException, RepositoryException {
        // check sanity of session
        session.checkIsAlive();

        Iterator<PropertyEntry> propEntries = parentEntry.getPropertyEntries();
        return new LazyItemIterator(this, propEntries);
    }

    //-------------------------------------------------------------< Object >---

    /**
     * Returns the the state of this instance in a human readable format.
     */
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("ItemManager (" + super.toString() + ")\n");
        builder.append("Items in cache:\n");
        builder.append(itemCache);
        return builder.toString();
    }

    //----------------------------------------------------< private methods >---
    /**
     * @param state
     * @return a new Node instance.
     * @throws RepositoryException
     */
    private NodeImpl createNodeInstance(NodeState state) throws RepositoryException {
        // we want to be informed on life cycle changes of the new node object
        // in order to maintain item cache consistency
        ItemLifeCycleListener[] listeners = new ItemLifeCycleListener[]{itemCache};

        // check special nodes
        Name ntName = state.getNodeTypeName();
        if (NameConstants.NT_VERSION.equals(ntName)) {
            // version
            return new VersionImpl(session, state, listeners);
        } else if (NameConstants.NT_VERSIONHISTORY.equals(ntName)) {
            // version-history
            return new VersionHistoryImpl(session, state, listeners);
        } else {
            // create common node object
            return new NodeImpl(session, state, listeners);
        }
    }

    /**
     * @param state
     * @return a new Property instance.
     */
    private PropertyImpl createPropertyInstance(PropertyState state) {
        // we want to be informed on life cycle changes of the new property object
        // in order to maintain item cache consistency
        ItemLifeCycleListener[] listeners = new ItemLifeCycleListener[]{itemCache};
        // create property object
        PropertyImpl prop = new PropertyImpl(session, state, listeners);
        return prop;
    }

    //------------------------------------------< ItemStateCreationListener >---
    /**
     *
     * @param state
     */
    public void created(ItemState state) {
        if (state.isNode()) {
            try {
                createNodeInstance((NodeState) state);
            } catch (RepositoryException e) {
                // log warning and ignore
                log.warn("Unable to create Node instance: " + e.getMessage());
            }
        } else {
            createPropertyInstance((PropertyState) state);
        }
    }

    public void statusChanged(ItemState state, int previousStatus) {
        // stop listening if an state reached Status.REMOVED.
        if (Status.REMOVED == state.getStatus()) {
            state.removeListener(this);
        }
        // otherwise: nothing to do -> Item is listening to status changes and
        // forces cleanup of cache entries through it's own status changes.
    }
}


text:
<?php

declare(strict_types=1);

namespace Sonata\AdminBundle\Show;

use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Admin\FieldDescriptionCollection;
use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
use Sonata\AdminBundle\Builder\ShowBuilderInterface;
use Sonata\AdminBundle\Mapper\BaseGroupedMapper;

/**
 * This class is used to simulate the Form API.
 *
 * @final since sonata-project/admin-bundle 3.52
 *
 * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
 */
class ShowMapper extends BaseGroupedMapper
{
    /**
     * @var FieldDescriptionCollection
     */
    protected $list;

    /**
     * @var ShowBuilderInterface
     */
    protected $builder;

    public function __construct(
        ShowBuilderInterface $showBuilder,
        FieldDescriptionCollection $list,
        AdminInterface $admin
    ) {
        parent::__construct($showBuilder, $admin);
        $this->list = $list;
    }

    /**
     * @param FieldDescriptionInterface|string $name
     * @param string|null                      $type
     * @param array<string, mixed>             $fieldDescriptionOptions
     *
     * @throws \LogicException
     *
     * @return static
     */
    public function add($name, $type = null, array $fieldDescriptionOptions = [])
    {
        if (!$this->shouldApply()) {
            return $this;
        }

        $fieldKey = ($name instanceof FieldDescriptionInterface) ? $name->getName() : $name;

        $this->addFieldToCurrentGroup($fieldKey);

        if ($name instanceof FieldDescriptionInterface) {
            $fieldDescription = $name;
            $fieldDescription->mergeOptions($fieldDescriptionOptions);
        } elseif (\is_string($name)) {
            if (!$this->admin->hasShowFieldDescription($name)) {
                $fieldDescription = $this->admin->getModelManager()->getNewFieldDescriptionInstance(
                    $this->admin->getClass(),
                    $name,
                    $fieldDescriptionOptions
                );
            } else {
                throw new \LogicException(sprintf(
                    'Duplicate field name "%s" in show mapper. Names should be unique.',
                    $name
                ));
            }
        } else {
            throw new \TypeError(
                'Unknown field name in show mapper.'
                    .' Field name should be either of FieldDescriptionInterface interface or string.'
            );
        }

        // NEXT_MAJOR: Remove the argument "sonata_deprecation_mute" in the following call.
        if (null === $fieldDescription->getLabel('sonata_deprecation_mute')) {
            $fieldDescription->setOption('label', $this->admin->getLabelTranslatorStrategy()->getLabel($fieldDescription->getName(), 'show', 'label'));
        }

        $fieldDescription->setOption('safe', $fieldDescription->getOption('safe', false));

        if (!isset($fieldDescriptionOptions['role']) || $this->admin->isGranted($fieldDescriptionOptions['role'])) {
            // add the field with the FormBuilder
            $this->builder->addField($this->list, $type, $fieldDescription, $this->admin);
        }

        return $this;
    }

    public function get($name)
    {
        return $this->list->get($name);
    }

    public function has($key)
    {
        return $this->list->has($key);
    }

    public function remove($key)
    {
        $this->admin->removeShowFieldDescription($key);
        $this->list->remove($key);

        return $this;
    }

    final public function keys()
    {
        return array_keys($this->list->getElements());
    }

    public function reorder(array $keys)
    {
        $this->admin->reorderShowGroup($this->getCurrentGroupName(), $keys);

        return $this;
    }

    protected function getGroups()
    {
        // NEXT_MAJOR: Remove the argument "sonata_deprecation_mute" in the following call.

        return $this->admin->getShowGroups('sonata_deprecation_mute');
    }

    protected function setGroups(array $groups)
    {
        $this->admin->setShowGroups($groups);
    }

    protected function getTabs()
    {
        // NEXT_MAJOR: Remove the argument "sonata_deprecation_mute" in the following call.

        return $this->admin->getShowTabs('sonata_deprecation_mute');
    }

    protected function setTabs(array $tabs)
    {
        $this->admin->setShowTabs($tabs);
    }

    protected function getName()
    {
        return 'show';
    }
}


text:
var actions = require('@cdo/apps/gamelab/actions');
var expect = require('chai').expect;
var GameLabInterfaceMode = require('@cdo/apps/gamelab/constants').GameLabInterfaceMode;
var gamelabReducer = require('@cdo/apps/gamelab/reducers').gamelabReducer;

describe('gamelabReducer', function () {
  var defaultState;
  var CODE = GameLabInterfaceMode.CODE;
  var ANIMATION = GameLabInterfaceMode.ANIMATION;

  beforeEach(function () {
    defaultState = gamelabReducer(undefined, {});
  });

  it('has expected default state', function () {
    expect(defaultState.interfaceMode).to.equal(CODE);
    expect(defaultState.level).to.be.an.object;
    expect(defaultState.level.assetUrl).to.be.a.function;
    expect(defaultState.level.isEmbedView).to.be.undefined;
    expect(defaultState.level.isShareView).to.be.undefined;
  });

  describe('action: changeInterfaceMode', function () {
    var changeInterfaceMode = actions.changeInterfaceMode;

    it('returns original object when already in given mode', function () {
      expect(defaultState.interfaceMode).to.equal(CODE);
      var newState = gamelabReducer(defaultState, changeInterfaceMode(CODE));
      expect(newState).to.equal(defaultState);
      expect(newState.interfaceMode).to.equal(CODE);
    });

    it('returns a new object when in a new mode', function () {
      expect(defaultState.interfaceMode).to.equal(CODE);
      var newState = gamelabReducer(defaultState, changeInterfaceMode(ANIMATION));
      expect(newState).to.not.equal(defaultState);
      expect(newState.interfaceMode).to.equal(ANIMATION);
    });
  });

  describe('action: setInitialLevelProps', function () {
    var setInitialLevelProps = actions.setInitialLevelProps;

    it('allows setting assetUrl', function () {
      var newAssetUrlFunction = function () {};
      expect(defaultState.level.assetUrl).to.not.equal(newAssetUrlFunction);
      var newState = gamelabReducer(defaultState, setInitialLevelProps({
        assetUrl: newAssetUrlFunction
      }));
      expect(newState.level.assetUrl).to.equal(newAssetUrlFunction);
    });

    it('allows setting isEmbedView', function () {
      expect(defaultState.level.isEmbedView).to.be.undefined;
      var newState = gamelabReducer(defaultState, setInitialLevelProps({
        isEmbedView: false
      }));
      expect(newState.level.isEmbedView).to.be.false;
    });

    it('allows setting isShareView', function () {
      expect(defaultState.level.isShareView).to.be.undefined;
      var newState = gamelabReducer(defaultState, setInitialLevelProps({
        isShareView: true
      }));
      expect(newState.level.isShareView).to.be.true;
    });

    it('does not allow setting other properties', function () {
      expect(function () {
        gamelabReducer(defaultState, setInitialLevelProps({
          theAnswer: 42
        }));
      }).to.throw(Error, /Property "theAnswer" may not be set using the SET_INITIAL_LEVEL_PROPS action./);
    });

  });
});


text:
"""

"""
import stat
import os
#import mimetypes
try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO #@UnusedImport
from wsgidav.dav_provider import DAVCollection, DAVNonCollection
from wsgidav import util

__docformat__ = "reStructuredText en"

_logger = util.getModuleLogger(__name__)

#===============================================================================
# VirtualCollection
#===============================================================================

class VirtualCollection(DAVCollection):
    """Abstract base class for collections that contain a list of static members.

    Member names are passed to the constructor.
    getMember() is implemented by calling self.provider.getResourceInst()
    """
    def __init__(self, path, environ, displayInfo, memberNameList):
        DAVCollection.__init__(self, path, environ)
        if isinstance(displayInfo, basestring):
            displayInfo = { "type": displayInfo }
        assert type(displayInfo) is dict
        assert type(memberNameList) is list
        self.displayInfo = displayInfo
        self.memberNameList = memberNameList

    def getDisplayInfo(self):
        return self.displayInfo

    def getMemberNames(self):
        return self.memberNameList

    def preventLocking(self):
        """Return True, since we don't want to lock virtual collections."""
        return True

    def getMember(self, name):
#        raise NotImplementedError()
        return self.provider.getResourceInst(util.joinUri(self.path, name),
                                             self.environ)

#===============================================================================
# _VirtualNonCollection classes
#===============================================================================
class _VirtualNonCollection(DAVNonCollection):
    """Abstract base class for all non-collection resources."""
    def __init__(self, path, environ):
        DAVNonCollection.__init__(self, path, False, environ)
    def getContentLength(self):
        return None
    def getContentType(self):
        return None
    def getCreationDate(self):
        return None
    def getDisplayName(self):
        return self.name
    def getDisplayInfo(self):
        raise NotImplementedError()
    def getEtag(self):
        return None
    def getLastModified(self):
        return None
    def supportRanges(self):
        return False
#    def handleDelete(self):
#        raise DAVError(HTTP_FORBIDDEN)
#    def handleMove(self, destPath):
#        raise DAVError(HTTP_FORBIDDEN)
#    def handleCopy(self, destPath, depthInfinity):
#        raise DAVError(HTTP_FORBIDDEN)

#===============================================================================
# VirtualTextResource
#===============================================================================
class VirtualTextResource(_VirtualNonCollection):
    """A virtual file, containing a string."""
    def __init__(self, path, environ, content,
                 displayName=None, displayType=None):
        _VirtualNonCollection.__init__(self, path, environ)
        self.content = content
        self.displayName = displayName
        self.displayType = displayType
    def getContentLength(self):
        return len(self.getContent().read())
    def getContentType(self):
        if self.name.endswith(".txt"):
            return "text/plain"
        return "text/html"
    def getDisplayName(self):
        return self.displayName or self.name
    def getDisplayInfo(self):
        return {"type": "Virtual info file"}
    def preventLocking(self):
        return True
#    def getRefUrl(self):
#        refPath = "/by_key/%s/%s" % (self._data["key"], self.name)
#        return urllib.quote(self.provider.sharePath + refPath)
    def getContent(self):
        return StringIO(self.content)

#===============================================================================
# FileResource
#===============================================================================
class FileResource(_VirtualNonCollection):
    """Represents an existing file."""
    BUFFER_SIZE = 8192
    def __init__(self, path, environ, filePath):
        if not os.path.exists(filePath):
            util.warn("FileResource(%r) does not exist." % filePath)
        _VirtualNonCollection.__init__(self, path, environ)
        self.filePath = filePath
    def getContentLength(self):
        statresults = os.stat(self.filePath)
        return statresults[stat.ST_SIZE]
    def getContentType(self):
        if not os.path.isfile(self.filePath):
            return "text/html"
#        (mimetype, _mimeencoding) = mimetypes.guess_type(self.filePath)
#        if not mimetype:
#            mimetype = "application/octet-stream"
#        return mimetype
        return util.guessMimeType(self.filePath)
    def getCreationDate(self):
        statresults = os.stat(self.filePath)
        return statresults[stat.ST_CTIME]
    def getDisplayInfo(self):
        return {"type": "File"}
    def getLastModified(self):
        statresults = os.stat(self.filePath)
        return statresults[stat.ST_MTIME]
#    def getRefUrl(self):
#        refPath = "/by_key/%s/%s" % (self._data["key"], os.path.basename(self.filePath))
#        return urllib.quote(self.provider.sharePath + refPath)
    def getContent(self):
        mime = self.getContentType()
        # GC issue 57: always store as binary
#        if mime.startswith("text"):
#            return file(self.filePath, "r", FileResource.BUFFER_SIZE)
        return file(self.filePath, "rb", FileResource.BUFFER_SIZE)

#===============================================================================
# Resolvers
#===============================================================================
class DAVResolver(object):
    """Return a DAVResource object for a path (None, if not found)."""
    def __init__(self, parentResolver, name):
        self.parentResolver = parentResolver
        self.name = name
    def resolve(self, scriptName, pathInfo, environ):
        raise NotImplementedError


text:
# Color Generator
Create sets of visually distinctive colors for easy visualization in plots. The colors are generated procedurally, so you can create a large number of colors with no repetition (up to 255*7 = 1785 distinct colors). However, it is hard to notice the actual differences between colors past the first 15-20 colors.

This is a self-contained, header-only library (only dependent on STL vectors). This code is based on a stack overflow discussion available [here](http://stackoverflow.com/questions/309149/generate-distinctly-different-rgb-colors-in-graphs).

Its usage is very simple. Just #include "color_generator.h" in a cpp file and create the ColorGenerator object:

```
ColorGenerator<RGBColor> colorGenerator(NumColors); // precompute a list of NumColors
```

The `RGBColor` template type is any object that can be initialized as `T{ red_color, green_color, blue_color };`
Then, to access your generated colors:

```
RGBColor c = colorGenerator[idx]; // Color number 'idx', returns object of type 'RGBColor'
```

Or, alternatively, you query an arbitrariy (not precomputed) color:

```
RGBColor c;
colorGenerator.GenerateColor(idx /* index of color */, c /* output, passed by ref */);
```
Enjoy!


text:
export const appBgColor = '#0c0c0c';
export const itemBgColor = '#111';
export const borderColor = '#222';
export const enabledColor = '#b4ad63';
export const disabledColor = '#141c3a';
export const textColor = '#efefef';

export default {
  itemBgColor,
  appBgColor,
  borderColor,
  enabledColor,
  disabledColor,
  textColor
};