text:
<?php
	//Post Values
	$page = (int)$_POST['page']; //Requested Page
	$limit = (int)$_POST['rows']; //get how many rows we want to have in the grid

	$page = $page > 0 ? $page : 1;
	$limit = $limit > 0 ? $limit : 5;

	# connect to the database
	try {

	  //Put Your DB Information
	  $db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
	  $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

	}catch(PDOException $e) {
		//echo "Can't connect to DB: ". $e->getMessage();
		die("Can't connect to DB");
	}

	//Get all records in table
	$sth = $db->query('SELECT * FROM contacts');
	$records = count($sth->fetchAll(PDO::FETCH_ASSOC));

	$totalPages = $records > 0 ? ceil($records/$limit) : 0;

	//Page argument cannot be greater than $totalPages
	$page = $page > $totalPages ? $totalPages : $page;

	//die($limit . " * " . $page);

	$offset = ($limit * $page) - $limit ;

    $sql ='SELECT * FROM contacts LIMIT :offset, :limit ';
    $stmt = $db->prepare($sql);
    $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
	$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    //print_r($result);

	$response = new stdClass();
	$response->page = $page;
	$response->total = $totalPages;
	$response->records = $records;

    foreach ($result as $i => $row){

		$response->rows[$i]['id'] = $row[id];
		$response->rows[$i]['data'] = array(
			$row["id"],
			$row["first_name"],
			$row["last_name"],
			$row["email"],
			$row["phone"]
		);
    }
	echo json_encode($response);
?>


text:
function kkl_backend_addFilter(url, filterParameter, newValue) {
    var newurl = url;
    var regex = new RegExp('[\\?&]' + filterParameter + '=([^&#]*)');
    var results = regex.exec(url);

    if (results == null) {
        // append
        newurl += "&" + filterParameter + "=" + newValue;
    } else {
        // replace
        var pattern = '(' + filterParameter + '=)[^\&]+';
        var re = new RegExp(pattern, "g");

        newurl = url.replace(re, '$1' + newValue);
    }

    return newurl;
}

jQuery(document).ready(function () {
    var href = jQuery(location).attr('href');
    if (href.includes('page=kkl_')) {
        jQuery('#toplevel_page_kkl_ligatool').addClass("current");
        jQuery('#toplevel_page_kkl_ligatool a').addClass("current");
    }

    jQuery('.pickfixture').datetimepicker({
        dateFormat: "yy-mm-dd",
        timeFormat: "HH:mm",
        defaultTime: "20:00"
    });
});

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace EBT\Compress;

/**
 * GzencodeCompressorTrait
 */
trait GzencodeCompressorTrait
{
    /**
     * @var int
     */
    protected $level = -1;

    /**
     * {@inheritDoc}
     */
    public function getCompressorName()
    {
        return GzencodeCompressor::NAME;
    }

    /**
     * {@inheritDoc}
     */
    protected function compress($data)
    {
        return gzencode($data);
    }

    /**
     * {@inheritDoc}
     */
    protected function uncompress($data)
    {
        return gzdecode($data);
    }

    /**
     * {@inheritDoc}
     */
    public function compressUTF8encoded()
    {
        return false;
    }
}


text:
namespace views {

class MenuButton;
class Widget;

// Used internally by MenuRunner to show the menu. Can be set in tests (see
// MenuRunnerTestApi) for mocking running of the menu.
class VIEWS_EXPORT MenuRunnerHandler {
 public:
  virtual ~MenuRunnerHandler() {}
  virtual MenuRunner::RunResult RunMenuAt(Widget* parent,
                                          MenuButton* button,
                                          const gfx::Rect& bounds,
                                          MenuItemView::AnchorPosition anchor,
                                          ui::MenuSourceType source_type,
                                          int32 types) = 0;
};

}  // namespace views

#endif  // UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_HANDLER_H_


text:
import { Component } from '@angular/core';
import { ToastService } from '../../../component';

interface MsgData {
    type: 'success' | 'info' | 'warn' | 'error' | string;
    message: string;
    duration?: number;
}

@Component({
    selector: 'demo-toast-base',
    templateUrl: './toast-base.html',
    styleUrls: ['./toast-base.less']
})
export class ToastBaseDemo {
    private messages: MsgData[] = [
        {
            type: 'success',
            message: '恭喜您,您的请求已成功处理',
            duration: 3000
        },
        {
            type: 'warn',
            message: '警告,请确认后再操作',
            duration: 3000
        },
        {
            type: 'info',
            message: '提醒,您的报价低于计划预期',
            duration: 3000
        },
        {
            type: 'error',
            message: '错误,系统未知错误',
            duration: 3000
        }
    ];

    constructor(protected toastService: ToastService) {
    }

    messageMap() {
        return this.messages.reduce((result, current) => {
            result[current.type] = current;
            return result;
        }, {});
    }

    showToast(type: string) {
        if (type === 'all') {
            this.messages.forEach((item) => {
                this.toastService.create(item.type, item.message, {
                    duration: item.duration
                });
            });
        }
        else {
            let options = this.messageMap()[type];
            this.toastService.create(options.type, options.message, {
                duration: options.duration
            });
        }
    }
}


text:
A simple breadcrumbs' generator helper.

### Features

  * Well tested with maximum code quality.
  * Easy setup & configuration.
  * Laravel `5.x` to ` 8.x` are supported.
  * Twitter Bootstrap `v3 | v4` are supported.
  * ZURB Foundation `v5 | v6` are supported.
  * Well documented & IDE Friendly.
  * Made with :heart: & :coffee:.

## Table of contents

  1. [Installation and Setup](1-Installation-and-Setup.md)
  2. [Configuration](2-Configuration.md)
  3. [Usage](3-Usage.md)


text:
import tkinter as tk
import tkinter.messagebox as tkmbox
import numpy as np
import gamecfg

# The main class
class Square(tk.Canvas):
	"""A Square is a canvas on which nought or cross can be played"""

	# Cross starts, board of length m, and the game has no result yet
	crossToPlay = True
	result = None
	m = gamecfg.n

	# moveList, squareDict and state are all representations of the board
	moveList = []
	squareDict = {}
	state = np.zeros((m, m))

	def __init__(self, name, master=None, size=None, colour=None):
		super().__init__(master, width=size, height=size, bg=colour)
		self.bind("<Button-1>", self.tic)
		self.config(highlightbackground="Black")
		self.config(highlightthickness=1)

		self.symbol = None
		self.name = name
		self.topLeft = size * 0.15
		self.bottomRight = size * 0.85
		# Add itself to the dict of squares
		Square.squareDict[self.name] = self

	def __repr__(self):
		if self.symbol:
			return("{} Controlled Square at {}".format(self.symbol, self.name))
		else:
			return("Empty Square at {}".format(self.name))

	def draw(self):
		"""This will draw a nought or cross on itself,
		depending on who is to play."""
		if not self.symbol and not self.result:
			tl = self.topLeft
			br = self.bottomRight
			if Square.crossToPlay:
				self.create_line(tl, tl, br, br)
				self.create_line(tl, br, br, tl)
				self.symbol = 'X'
				Square.state[self.name] = 1
			else:
				self.create_oval(tl, tl, br, br)
				self.symbol = 'O'
				Square.state[self.name] = Square.m + 1
			Square.crossToPlay = not Square.crossToPlay
			Square.moveList.append(self)
			Square.print()
			Square.setResult(winCheck(Square.state))

	def tic(self, event):
		""""A tic is a player clicking on a square"""
		self.draw()
		self.master.update()
		self.after(gamecfg.engineWait, computerMove())

	def tac(self):
		"""A tac is the computer playing"""
		self.draw()

	def clear(self):
		""""This will clear the selected Square."""
		if self.symbol:
			self.delete("all")
			self.symbol = None
			Square.result = None
			Square.crossToPlay = not Square.crossToPlay
			Square.print()
			Square.state[self.name] = 0

	@classmethod
	def undo(cls):
		cls.moveList.pop().clear()

	@classmethod
	def print(cls):
		print('Moves:', *[square.name for square in cls.moveList])

	@classmethod
	def setResult(cls, result):
		if result:
			cls.result = result
			if result != 'D':
				tkmbox.showinfo("The game has ended.", "The winner of the game was {}!".format(result))
			else:
				tkmbox.showinfo("The game has ended.", "The game was a draw!")

def winCheck(state):
	"""Takes a position, and returns the outcome of that game"""
	# Sums which correspond to a line across a column
	winNums = list(state.sum(axis=0))
	# Sums which correspond to a line across a row
	winNums.extend(list(state.sum(axis=1)))
	# Sums which correspond to a line across the main diagonal
	winNums.append(state.trace())
	# Sums which correspond to a line across the off diagonal
	winNums.append(np.flipud(state).trace())

	if Square.m in winNums:
		return 'X'
	elif (Square.m**2 + Square.m) in winNums:
		return 'O'
	elif np.count_nonzero(state) == Square.m**2:
		return 'D'
	else:
		return None

def moveFind(state):
	"""Takes a position as an nparray and determines the legal moves"""
	moveChoices = []

	# Iterate over state, to determine which squares are empty
	it = np.nditer(state, flags=['multi_index'])
	while not it.finished:
		if it[0] == 0:
			moveChoices.append(it.multi_index)
		it.iternext()
	return moveChoices

def moveSim(state, move, player):
	"""Create the state of the player having moved without interfering with the board"""
	simState = state.copy()
	if player == 1:
		simState[move] = 1
	else:
		simState[move] = gamecfg.n + 1
	return simState

def positionScore(state):
	"""The game is either won or lost"""
	if winCheck(state) == 'X':
		return 100 - np.count_nonzero(state)
	elif winCheck(state) == 'O':
		return -100 + np.count_nonzero(state)
	else:
		return 0

def negaMax(state, depth, alpha, beta, colour):
	"""Recursively find the best move via a negamax search"""
	depth = min(depth, np.count_nonzero(state==0))
	if depth == 0 or positionScore(state) != 0:
		return positionScore(state) * colour

	highScore = -100

	moveList = moveFind(state)
	for move in moveList:
		score = -negaMax(moveSim(state, move, colour), depth -1, -beta, -alpha, -colour)
		highScore = max(score, highScore)
		alpha = max(alpha, highScore)
		if alpha >= beta:
			break

	return highScore

# This function is called safely anytime it might be the computer's turn
def computerMove():
	# Decide whether or not the computer is to play
	if gamecfg.engineIsCross == Square.crossToPlay and not Square.result:
		if gamecfg.engineIsCross:
			player = 1
		else:
			player = -1
		moveScores = {}
		for move in moveFind(Square.state):
			moveScores[move] = negaMax(moveSim(Square.state, move, player), gamecfg.lvl, -100, 100, player * -1)

		Square.squareDict[min(moveScores.keys(), key=(lambda k: moveScores[k]))].tac()
		print(moveScores)

def clearAll():
	while Square.moveList:
		Square.moveList.pop().clear()
	computerMove()

def main():
	root = tk.Tk()
	root.title("Tic Tac Toe")

	# Creating the board, 600 x 600 pixels, n squares across
	m = gamecfg.n
	size = 600 // m
	squares = [(rank, file) for rank in range(m) for file in range(m)]

	for (rank, file) in squares:
		if ((rank + file) % 2):
			colour = 'gainsboro'
		else:
			colour = 'papaya whip'

		square = Square((rank, file), master=root, size=size, colour=colour)
		square.grid(row=rank, column=file)

	# Creating File Menu
	menu = tk.Menu(root)
	root.config(menu=menu)

	fileMenu = tk.Menu(menu)
	menu.add_cascade(label="File", menu=fileMenu)
	# Undo calls the clear function on the most recently played square.
	fileMenu.add_command(label="Undo", command=lambda: Square.moveList.pop().clear())
	fileMenu.add_command(label="State", command=lambda: print(Square.state))
	fileMenu.add_command(label="Result", command=lambda: print(Square.result))
	fileMenu.add_command(label="Restart", command=lambda: clearAll())
	computerMove()
	root.mainloop()

if __name__ == '__main__':
	main()


text:
package com.sherpasteven.sscte.Models;

import android.test.AndroidTestCase;

import junit.framework.TestCase;

import java.util.ArrayList;

/**
 * Created by joshua on 30/11/15.
 */
public class TradeTest extends AndroidTestCase {

    Trader joshua;
    Trader salim;
    Card card1;
    Card card2;
    ArrayList<Card> setupCards;

    public void setUp() throws Exception {
        super.setUp();

        User salimuser = new User("salim", "Canada", "salim@ualberta.ca", this.getContext());
        User joshuauser = new User("joshua", "Canada", "jjwhite@ualberta.ca", this.getContext());
        card1 = new Card("charizard", 2, new Quality(73), "Pokemon", "Basic XY Red",
                true, "Gently bent edge, 100HP", joshuauser);

        card2 = new Card("Blue Eyes White Dragon", 9, new Quality(3), "YuGiOh", "stupid series",
                true, "Dime a dozen", salimuser);

        salimuser.addInventoryItem(card1);
        salim = new Trader(salimuser, getContext());

        joshuauser.addInventoryItem(card2);
        joshua = new Trader(joshuauser, this.getContext());

    }

    public void tearDown() throws Exception {

    }

    public void testSetStatus() throws Exception {
        Trade trade = new Trade(joshua, salim);
        assertEquals(trade.getStatus(), "PENDING");
        trade.setStatus("ACCEPTED");
        assertEquals(trade.getStatus(), "ACCEPTED");

    }

    public void testCounterOffer() throws Exception {

        Trade trade = new Trade(joshua, salim);
        trade.addOwnerList(salim.getInventoryItem(0));
        trade.addBorrowList(joshua.getInventoryItem(0));

        assertEquals(trade.getBorrower(), joshua);
        assertEquals(trade.getOwner(), salim);
        //assertEquals();

    }
}


text:
import truncate from '../truncate';

describe('"truncate"', () => {
  describe('Returns the given entry as is, when "maxLength" is', () => {
    it('Not given', () => {
      const str = 'This is not truncated';
      expect(truncate(str)).toBe(str);
    });

    it('Grater than the length of the entry', () => {
      const str = 'Short string';
      expect(truncate(str, { maxLength: 20 })).toBe(str);
    });
  });

  describe('Truncates the given entry and adds a given end to it', () => {
    it('Adds default end ("...")', () => {
      expect(truncate('Truncated string', { maxLength: 10 })).toBe('Truncated ...');
    });

    it.each(['???', '_'])('Adds custom end: "%s"', (end) => {
      expect(truncate('Truncated string', { maxLength: 10, end })).toBe('Truncated ' + end);
    });
  });
});


text:
package com.ibm.watson.text_to_speech.v1;

import com.ibm.cloud.sdk.core.security.Authenticator;
import com.ibm.cloud.sdk.core.security.IamAuthenticator;
import com.ibm.watson.text_to_speech.v1.model.Voices;

public class TextToSpeechExample {

  public static void main(String[] args) {
    Authenticator authenticator = new IamAuthenticator("<iam_api_key>");
    TextToSpeech service = new TextToSpeech(authenticator);

    Voices voices = service.listVoices().execute().getResult();
    System.out.println(voices);
  }
}


text:
version: v1.0.1
category: Tutorial
title: 'Supported Platforms'
redirect_from:
    - /docs/v0.24.0/tutorial/supported-platforms/
    - /docs/v0.25.0/tutorial/supported-platforms/
    - /docs/v0.26.0/tutorial/supported-platforms/
    - /docs/v0.27.0/tutorial/supported-platforms/
    - /docs/v0.28.0/tutorial/supported-platforms/
    - /docs/v0.29.0/tutorial/supported-platforms/
    - /docs/v0.30.0/tutorial/supported-platforms/
    - /docs/v0.31.0/tutorial/supported-platforms/
    - /docs/v0.32.0/tutorial/supported-platforms/
    - /docs/v0.33.0/tutorial/supported-platforms/
    - /docs/v0.34.0/tutorial/supported-platforms/
    - /docs/v0.35.0/tutorial/supported-platforms/
    - /docs/v0.36.0/tutorial/supported-platforms/
    - /docs/v0.36.3/tutorial/supported-platforms/
    - /docs/v0.36.4/tutorial/supported-platforms/
    - /docs/v0.36.5/tutorial/supported-platforms/
    - /docs/v0.36.6/tutorial/supported-platforms/
    - /docs/v0.36.7/tutorial/supported-platforms/
    - /docs/v0.36.8/tutorial/supported-platforms/
    - /docs/v0.36.9/tutorial/supported-platforms/
    - /docs/v0.36.10/tutorial/supported-platforms/
    - /docs/v0.36.11/tutorial/supported-platforms/
    - /docs/v0.37.0/tutorial/supported-platforms/
    - /docs/v0.37.1/tutorial/supported-platforms/
    - /docs/v0.37.2/tutorial/supported-platforms/
    - /docs/v0.37.3/tutorial/supported-platforms/
    - /docs/v0.37.4/tutorial/supported-platforms/
    - /docs/v0.37.5/tutorial/supported-platforms/
    - /docs/v0.37.6/tutorial/supported-platforms/
    - /docs/v0.37.7/tutorial/supported-platforms/
    - /docs/v0.37.8/tutorial/supported-platforms/
    - /docs/v1.0.0/tutorial/supported-platforms/
    - /docs/v1.0.1/tutorial/supported-platforms/
    - /docs/latest/tutorial/supported-platforms/
source_url: 'https://github.com/electron/electron/blob/master/docs/tutorial/supported-platforms.md'
---

# Supported Platforms

Following platforms are supported by Electron:

### OS X

Only 64bit binaries are provided for OS X, and the minimum OS X version
supported is OS X 10.9.

### Windows

Windows 7 and later are supported, older operating systems are not supported
(and do not work).

Both `x86` and `amd64` (x64) binaries are provided for Windows. Please note, the
`ARM` version of Windows is not supported for now.

### Linux

The prebuilt `ia32`(`i686`) and `x64`(`amd64`) binaries of Electron are built on
Ubuntu 12.04, the `arm` binary is built against ARM v7 with hard-float ABI and
NEON for Debian Wheezy.

Whether the prebuilt binary can run on a distribution depends on whether the
distribution includes the libraries that Electron is linked to on the building
platform, so only Ubuntu 12.04 is guaranteed to work, but following platforms
are also verified to be able to run the prebuilt binaries of Electron:

* Ubuntu 12.04 and later
* Fedora 21
* Debian 8


text:
package org.jfl2.core.conf.elements;

import javax.xml.bind.annotation.XmlAttribute;

public class MainFrameHistory {
    @XmlAttribute
    public Double displayX;
    @XmlAttribute
    public Double displayY;
    @XmlAttribute
    public Double width = 800D;
    @XmlAttribute
    public Double height = 500D;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  #%L
  wcm.io
  %%
  Copyright (C) 2015 wcm.io
  %%
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
       http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  #L%
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>io.wcm.devops.conga.definitions</groupId>
    <artifactId>io.wcm.devops.conga.definitions.aem.parent</artifactId>
    <version>1.13.1-SNAPSHOT</version>
    <relativePath>parent/pom.xml</relativePath>
  </parent>

  <groupId>io.wcm.devops.conga.definitions</groupId>
  <artifactId>io.wcm.devops.conga.definitions.aem.root</artifactId>
  <version>1.13.1-SNAPSHOT</version>
  <packaging>pom</packaging>

  <name>CONGA AEM Definitions</name>
  <description>Root POM for wcm.io CONGA Roles and Templates for AEM.</description>
  <url>${site.url}/${site.url.module.prefix}/</url>

  <scm>
    <connection>scm:git:https://github.com/wcm-io-devops/conga-aem-definitions.git</connection>
    <developerConnection>scm:git:https://github.com/wcm-io-devops/conga-aem-definitions.git</developerConnection>
    <url>https://github.com/wcm-io-devops/conga-aem-definitions</url>
    <tag>HEAD</tag>
  </scm>

  <properties>
    <site.url.module.prefix>conga/definitions/aem</site.url.module.prefix>
  </properties>

  <modules>
    <module>parent</module>
    <module>conga-aem-definitions</module>
    <module>example</module>
  </modules>

  <build>
    <plugins>

      <!-- do not deploy this hierarchy pom into maven repository -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-deploy-plugin</artifactId>
        <configuration>
          <skip>true</skip>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <configuration>
          <topSiteURL>${site.deploy.url}</topSiteURL>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-scm-publish-plugin</artifactId>
        <configuration>
          <subDirectory>${site.url.module.prefix}</subDirectory>
          <skipDeletedFiles>true</skipDeletedFiles>
        </configuration>
      </plugin>

    </plugins>
  </build>

  <distributionManagement>
    <site>
      <id>${site.deploy.id}</id>
      <url>${site.deploy.url}</url>
    </site>
  </distributionManagement>

</project>


text:
describe('GraphQLService', function() {
  const ME_ID_REQUEST = '{ me { id } }';
  const ME_ID_SUCCESS_RESPONSE = {
    statusCode: 200,
    data: [
        {
            errors: [],
            data: {
              me: {
                id: 123456
              }
            }
        }
    ]
  };
  beforeEach(function() {
    if (typeof Qminder === 'undefined') {
      Qminder = this.Qminder;
    }
    if (typeof sinon === 'undefined') {
      sinon = this.sinon;
    }
    Qminder.setKey('EXAMPLE_API_KEY');
    Qminder.setServer('api.qminder.com');

    // Stub ApiBase.request to feed specific data to API
    this.requestStub = sinon.stub(Qminder.ApiBase, 'queryGraph');
  });

  describe('Qminder.graphql.query', function() {
    beforeEach(function() {
      this.requestStub.onFirstCall().resolves(ME_ID_SUCCESS_RESPONSE);
    });
    it('calls ApiBase.queryGraph with the correct parameters', function() {
      Qminder.graphql.query(ME_ID_REQUEST).then(() => {
        expect(this.requestStub.calledWith(ME_ID_REQUEST, undefined)).toBeTruthy();
      });
    });
    it('calls ApiBase.queryGraph with both query & variables', function() {
      const variables = { x: 5, y: 4 };
      Qminder.graphql.query(ME_ID_REQUEST, variables).then(() => {
        expect(this.requestStub.calledWith(ME_ID_REQUEST, variables)).toBeTruthy();
      });
    });
    it('collapses whitespace and newlines', function() {
      const query = `
        {
          me {
            id
          }
        }
      `;
      Qminder.graphql.query(query).then(() => {
        expect(this.requestStub.calledWith(ME_ID_REQUEST, undefined)).toBeTruthy();
      });
    });

    it('throws when query is missing', function() {
      expect(() => Qminder.graphql.query()).toThrow();
      expect(this.requestStub.callCount).toBe(0);
    });

  });

  afterEach(function() {
    Qminder.ApiBase.queryGraph.restore();
  });
});


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

// Tests for pointer utilities.

#include "absl/memory/memory.h"

#include <sys/types.h>

#include <cstddef>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>

#include "gmock/gmock.h"
#include "gtest/gtest.h"

namespace {

using ::testing::ElementsAre;
using ::testing::Return;

// This class creates observable behavior to verify that a destructor has
// been called, via the instance_count variable.
class DestructorVerifier {
 public:
  DestructorVerifier() { ++instance_count_; }
  DestructorVerifier(const DestructorVerifier&) = delete;
  DestructorVerifier& operator=(const DestructorVerifier&) = delete;
  ~DestructorVerifier() { --instance_count_; }

  // The number of instances of this class currently active.
  static int instance_count() { return instance_count_; }

 private:
  // The number of instances of this class currently active.
  static int instance_count_;
};

int DestructorVerifier::instance_count_ = 0;

TEST(WrapUniqueTest, WrapUnique) {
  // Test that the unique_ptr is constructed properly by verifying that the
  // destructor for its payload gets called at the proper time.
  {
    auto dv = new DestructorVerifier;
    EXPECT_EQ(1, DestructorVerifier::instance_count());
    std::unique_ptr<DestructorVerifier> ptr = absl::WrapUnique(dv);
    EXPECT_EQ(1, DestructorVerifier::instance_count());
  }
  EXPECT_EQ(0, DestructorVerifier::instance_count());
}
TEST(MakeUniqueTest, Basic) {
  std::unique_ptr<std::string> p = absl::make_unique<std::string>();
  EXPECT_EQ("", *p);
  p = absl::make_unique<std::string>("hi");
  EXPECT_EQ("hi", *p);
}

// InitializationVerifier fills in a pattern when allocated so we can
// distinguish between its default and value initialized states (without
// accessing truly uninitialized memory).
struct InitializationVerifier {
  static constexpr int kDefaultScalar = 0x43;
  static constexpr int kDefaultArray = 0x4B;

  static void* operator new(size_t n) {
    void* ret = ::operator new(n);
    memset(ret, kDefaultScalar, n);
    return ret;
  }

  static void* operator new[](size_t n) {
    void* ret = ::operator new[](n);
    memset(ret, kDefaultArray, n);
    return ret;
  }

  int a;
  int b;
};

TEST(Initialization, MakeUnique) {
  auto p = absl::make_unique<InitializationVerifier>();

  EXPECT_EQ(0, p->a);
  EXPECT_EQ(0, p->b);
}

TEST(Initialization, MakeUniqueArray) {
  auto p = absl::make_unique<InitializationVerifier[]>(2);

  EXPECT_EQ(0, p[0].a);
  EXPECT_EQ(0, p[0].b);
  EXPECT_EQ(0, p[1].a);
  EXPECT_EQ(0, p[1].b);
}

struct MoveOnly {
  MoveOnly() = default;
  explicit MoveOnly(int i1) : ip1{new int{i1}} {}
  MoveOnly(int i1, int i2) : ip1{new int{i1}}, ip2{new int{i2}} {}
  std::unique_ptr<int> ip1;
  std::unique_ptr<int> ip2;
};

struct AcceptMoveOnly {
  explicit AcceptMoveOnly(MoveOnly m) : m_(std::move(m)) {}
  MoveOnly m_;
};

TEST(MakeUniqueTest, MoveOnlyTypeAndValue) {
  using ExpectedType = std::unique_ptr<MoveOnly>;
  {
    auto p = absl::make_unique<MoveOnly>();
    static_assert(std::is_same<decltype(p), ExpectedType>::value,
                  "unexpected return type");
    EXPECT_TRUE(!p->ip1);
    EXPECT_TRUE(!p->ip2);
  }
  {
    auto p = absl::make_unique<MoveOnly>(1);
    static_assert(std::is_same<decltype(p), ExpectedType>::value,
                  "unexpected return type");
    EXPECT_TRUE(p->ip1 && *p->ip1 == 1);
    EXPECT_TRUE(!p->ip2);
  }
  {
    auto p = absl::make_unique<MoveOnly>(1, 2);
    static_assert(std::is_same<decltype(p), ExpectedType>::value,
                  "unexpected return type");
    EXPECT_TRUE(p->ip1 && *p->ip1 == 1);
    EXPECT_TRUE(p->ip2 && *p->ip2 == 2);
  }
}

TEST(MakeUniqueTest, AcceptMoveOnly) {
  auto p = absl::make_unique<AcceptMoveOnly>(MoveOnly());
  p = std::unique_ptr<AcceptMoveOnly>(new AcceptMoveOnly(MoveOnly()));
}

struct ArrayWatch {
  void* operator new[](size_t n) {
    allocs().push_back(n);
    return ::operator new[](n);
  }
  void operator delete[](void* p) { return ::operator delete[](p); }
  static std::vector<size_t>& allocs() {
    static auto& v = *new std::vector<size_t>;
    return v;
  }
};

TEST(Make_UniqueTest, Array) {
  // Ensure state is clean before we start so that these tests
  // are order-agnostic.
  ArrayWatch::allocs().clear();

  auto p = absl::make_unique<ArrayWatch[]>(5);
  static_assert(std::is_same<decltype(p), std::unique_ptr<ArrayWatch[]>>::value,
                "unexpected return type");
  EXPECT_THAT(ArrayWatch::allocs(), ElementsAre(5 * sizeof(ArrayWatch)));
}

TEST(Make_UniqueTest, NotAmbiguousWithStdMakeUnique) {
  // Ensure that absl::make_unique is not ambiguous with std::make_unique.
  // In C++14 mode, the below call to make_unique has both types as candidates.
  struct TakesStdType {
    explicit TakesStdType(const std::vector<int>& vec) {}
  };
  using absl::make_unique;
  (void)make_unique<TakesStdType>(std::vector<int>());
}

#if 0
// These tests shouldn't compile.
TEST(MakeUniqueTestNC, AcceptMoveOnlyLvalue) {
  auto m = MoveOnly();
  auto p = absl::make_unique<AcceptMoveOnly>(m);
}
TEST(MakeUniqueTestNC, KnownBoundArray) {
  auto p = absl::make_unique<ArrayWatch[5]>();
}
#endif

TEST(RawPtrTest, RawPointer) {
  int i = 5;
  EXPECT_EQ(&i, absl::RawPtr(&i));
}

TEST(RawPtrTest, SmartPointer) {
  int* o = new int(5);
  std::unique_ptr<int> p(o);
  EXPECT_EQ(o, absl::RawPtr(p));
}

class IntPointerNonConstDeref {
 public:
  explicit IntPointerNonConstDeref(int* p) : p_(p) {}
  friend bool operator!=(const IntPointerNonConstDeref& a, std::nullptr_t) {
    return a.p_ != nullptr;
  }
  int& operator*() { return *p_; }

 private:
  std::unique_ptr<int> p_;
};

TEST(RawPtrTest, SmartPointerNonConstDereference) {
  int* o = new int(5);
  IntPointerNonConstDeref p(o);
  EXPECT_EQ(o, absl::RawPtr(p));
}

TEST(RawPtrTest, NullValuedRawPointer) {
  int* p = nullptr;
  EXPECT_EQ(nullptr, absl::RawPtr(p));
}

TEST(RawPtrTest, NullValuedSmartPointer) {
  std::unique_ptr<int> p;
  EXPECT_EQ(nullptr, absl::RawPtr(p));
}

TEST(RawPtrTest, Nullptr) {
  auto p = absl::RawPtr(nullptr);
  EXPECT_TRUE((std::is_same<std::nullptr_t, decltype(p)>::value));
  EXPECT_EQ(nullptr, p);
}

TEST(RawPtrTest, Null) {
  auto p = absl::RawPtr(nullptr);
  EXPECT_TRUE((std::is_same<std::nullptr_t, decltype(p)>::value));
  EXPECT_EQ(nullptr, p);
}

TEST(RawPtrTest, Zero) {
  auto p = absl::RawPtr(nullptr);
  EXPECT_TRUE((std::is_same<std::nullptr_t, decltype(p)>::value));
  EXPECT_EQ(nullptr, p);
}

TEST(ShareUniquePtrTest, Share) {
  auto up = absl::make_unique<int>();
  int* rp = up.get();
  auto sp = absl::ShareUniquePtr(std::move(up));
  EXPECT_EQ(sp.get(), rp);
}

TEST(ShareUniquePtrTest, ShareNull) {
  struct NeverDie {
    using pointer = void*;
    void operator()(pointer) {
      ASSERT_TRUE(false) << "Deleter should not have been called.";
    }
  };

  std::unique_ptr<void, NeverDie> up;
  auto sp = absl::ShareUniquePtr(std::move(up));
}

TEST(WeakenPtrTest, Weak) {
  auto sp = std::make_shared<int>();
  auto wp = absl::WeakenPtr(sp);
  EXPECT_EQ(sp.get(), wp.lock().get());
  sp.reset();
  EXPECT_TRUE(wp.expired());
}

// Should not compile.
/*
TEST(RawPtrTest, NotAPointer) {
  absl::RawPtr(1.5);
}
*/

template <typename T>
struct SmartPointer {
  using difference_type = char;
};

struct PointerWith {
  using element_type = int32_t;
  using difference_type = int16_t;
  template <typename U>
  using rebind = SmartPointer<U>;

  static PointerWith pointer_to(
      element_type& r) {  // NOLINT(runtime/references)
    return PointerWith{&r};
  }

  element_type* ptr;
};

template <typename... Args>
struct PointerWithout {};

TEST(PointerTraits, Types) {
  using TraitsWith = absl::pointer_traits<PointerWith>;
  EXPECT_TRUE((std::is_same<TraitsWith::pointer, PointerWith>::value));
  EXPECT_TRUE((std::is_same<TraitsWith::element_type, int32_t>::value));
  EXPECT_TRUE((std::is_same<TraitsWith::difference_type, int16_t>::value));
  EXPECT_TRUE((
      std::is_same<TraitsWith::rebind<int64_t>, SmartPointer<int64_t>>::value));

  using TraitsWithout = absl::pointer_traits<PointerWithout<double, int>>;
  EXPECT_TRUE((std::is_same<TraitsWithout::pointer,
                            PointerWithout<double, int>>::value));
  EXPECT_TRUE((std::is_same<TraitsWithout::element_type, double>::value));
  EXPECT_TRUE(
      (std::is_same<TraitsWithout ::difference_type, std::ptrdiff_t>::value));
  EXPECT_TRUE((std::is_same<TraitsWithout::rebind<int64_t>,
                            PointerWithout<int64_t, int>>::value));

  using TraitsRawPtr = absl::pointer_traits<char*>;
  EXPECT_TRUE((std::is_same<TraitsRawPtr::pointer, char*>::value));
  EXPECT_TRUE((std::is_same<TraitsRawPtr::element_type, char>::value));
  EXPECT_TRUE(
      (std::is_same<TraitsRawPtr::difference_type, std::ptrdiff_t>::value));
  EXPECT_TRUE((std::is_same<TraitsRawPtr::rebind<int64_t>, int64_t*>::value));
}

TEST(PointerTraits, Functions) {
  int i;
  EXPECT_EQ(&i, absl::pointer_traits<PointerWith>::pointer_to(i).ptr);
  EXPECT_EQ(&i, absl::pointer_traits<int*>::pointer_to(i));
}

TEST(AllocatorTraits, Typedefs) {
  struct A {
    struct value_type {};
  };
  EXPECT_TRUE((
      std::is_same<A,
                   typename absl::allocator_traits<A>::allocator_type>::value));
  EXPECT_TRUE(
      (std::is_same<A::value_type,
                    typename absl::allocator_traits<A>::value_type>::value));

  struct X {};
  struct HasPointer {
    using value_type = X;
    using pointer = SmartPointer<X>;
  };
  EXPECT_TRUE((std::is_same<SmartPointer<X>, typename absl::allocator_traits<
                                                 HasPointer>::pointer>::value));
  EXPECT_TRUE(
      (std::is_same<A::value_type*,
                    typename absl::allocator_traits<A>::pointer>::value));

  EXPECT_TRUE(
      (std::is_same<
          SmartPointer<const X>,
          typename absl::allocator_traits<HasPointer>::const_pointer>::value));
  EXPECT_TRUE(
      (std::is_same<const A::value_type*,
                    typename absl::allocator_traits<A>::const_pointer>::value));

  struct HasVoidPointer {
    using value_type = X;
    struct void_pointer {};
  };

  EXPECT_TRUE((std::is_same<HasVoidPointer::void_pointer,
                            typename absl::allocator_traits<
                                HasVoidPointer>::void_pointer>::value));
  EXPECT_TRUE(
      (std::is_same<SmartPointer<void>, typename absl::allocator_traits<
                                            HasPointer>::void_pointer>::value));

  struct HasConstVoidPointer {
    using value_type = X;
    struct const_void_pointer {};
  };

  EXPECT_TRUE(
      (std::is_same<HasConstVoidPointer::const_void_pointer,
                    typename absl::allocator_traits<
                        HasConstVoidPointer>::const_void_pointer>::value));
  EXPECT_TRUE((std::is_same<SmartPointer<const void>,
                            typename absl::allocator_traits<
                                HasPointer>::const_void_pointer>::value));

  struct HasDifferenceType {
    using value_type = X;
    using difference_type = int;
  };
  EXPECT_TRUE(
      (std::is_same<int, typename absl::allocator_traits<
                             HasDifferenceType>::difference_type>::value));
  EXPECT_TRUE((std::is_same<char, typename absl::allocator_traits<
                                      HasPointer>::difference_type>::value));

  struct HasSizeType {
    using value_type = X;
    using size_type = unsigned int;
  };
  EXPECT_TRUE((std::is_same<unsigned int, typename absl::allocator_traits<
                                              HasSizeType>::size_type>::value));
  EXPECT_TRUE((std::is_same<unsigned char, typename absl::allocator_traits<
                                               HasPointer>::size_type>::value));

  struct HasPropagateOnCopy {
    using value_type = X;
    struct propagate_on_container_copy_assignment {};
  };

  EXPECT_TRUE(
      (std::is_same<HasPropagateOnCopy::propagate_on_container_copy_assignment,
                    typename absl::allocator_traits<HasPropagateOnCopy>::
                        propagate_on_container_copy_assignment>::value));
  EXPECT_TRUE(
      (std::is_same<std::false_type,
                    typename absl::allocator_traits<
                        A>::propagate_on_container_copy_assignment>::value));

  struct HasPropagateOnMove {
    using value_type = X;
    struct propagate_on_container_move_assignment {};
  };

  EXPECT_TRUE(
      (std::is_same<HasPropagateOnMove::propagate_on_container_move_assignment,
                    typename absl::allocator_traits<HasPropagateOnMove>::
                        propagate_on_container_move_assignment>::value));
  EXPECT_TRUE(
      (std::is_same<std::false_type,
                    typename absl::allocator_traits<
                        A>::propagate_on_container_move_assignment>::value));

  struct HasPropagateOnSwap {
    using value_type = X;
    struct propagate_on_container_swap {};
  };

  EXPECT_TRUE(
      (std::is_same<HasPropagateOnSwap::propagate_on_container_swap,
                    typename absl::allocator_traits<HasPropagateOnSwap>::
                        propagate_on_container_swap>::value));
  EXPECT_TRUE(
      (std::is_same<std::false_type, typename absl::allocator_traits<A>::
                                         propagate_on_container_swap>::value));

  struct HasIsAlwaysEqual {
    using value_type = X;
    struct is_always_equal {};
  };

  EXPECT_TRUE((std::is_same<HasIsAlwaysEqual::is_always_equal,
                            typename absl::allocator_traits<
                                HasIsAlwaysEqual>::is_always_equal>::value));
  EXPECT_TRUE((std::is_same<std::true_type, typename absl::allocator_traits<
                                                A>::is_always_equal>::value));
  struct NonEmpty {
    using value_type = X;
    int i;
  };
  EXPECT_TRUE(
      (std::is_same<std::false_type,
                    absl::allocator_traits<NonEmpty>::is_always_equal>::value));
}

template <typename T>
struct AllocWithPrivateInheritance : private std::allocator<T> {
  using value_type = T;
};

TEST(AllocatorTraits, RebindWithPrivateInheritance) {
  // Regression test for some versions of gcc that do not like the sfinae we
  // used in combination with private inheritance.
  EXPECT_TRUE(
      (std::is_same<AllocWithPrivateInheritance<int>,
                    absl::allocator_traits<AllocWithPrivateInheritance<char>>::
                        rebind_alloc<int>>::value));
}

template <typename T>
struct Rebound {};

struct AllocWithRebind {
  using value_type = int;
  template <typename T>
  struct rebind {
    using other = Rebound<T>;
  };
};

template <typename T, typename U>
struct AllocWithoutRebind {
  using value_type = int;
};

TEST(AllocatorTraits, Rebind) {
  EXPECT_TRUE(
      (std::is_same<Rebound<int>,
                    typename absl::allocator_traits<
                        AllocWithRebind>::template rebind_alloc<int>>::value));
  EXPECT_TRUE(
      (std::is_same<absl::allocator_traits<Rebound<int>>,
                    typename absl::allocator_traits<
                        AllocWithRebind>::template rebind_traits<int>>::value));

  EXPECT_TRUE(
      (std::is_same<AllocWithoutRebind<double, char>,
                    typename absl::allocator_traits<AllocWithoutRebind<
                        int, char>>::template rebind_alloc<double>>::value));
  EXPECT_TRUE(
      (std::is_same<absl::allocator_traits<AllocWithoutRebind<double, char>>,
                    typename absl::allocator_traits<AllocWithoutRebind<
                        int, char>>::template rebind_traits<double>>::value));
}

struct TestValue {
  TestValue() {}
  explicit TestValue(int* trace) : trace(trace) { ++*trace; }
  ~TestValue() {
    if (trace) --*trace;
  }
  int* trace = nullptr;
};

struct MinimalMockAllocator {
  MinimalMockAllocator() : value(0) {}
  explicit MinimalMockAllocator(int value) : value(value) {}
  MinimalMockAllocator(const MinimalMockAllocator& other)
      : value(other.value) {}
  using value_type = TestValue;
  MOCK_METHOD(value_type*, allocate, (size_t));
  MOCK_METHOD(void, deallocate, (value_type*, size_t));

  int value;
};

TEST(AllocatorTraits, FunctionsMinimal) {
  int trace = 0;
  int hint;
  TestValue x(&trace);
  MinimalMockAllocator mock;
  using Traits = absl::allocator_traits<MinimalMockAllocator>;
  EXPECT_CALL(mock, allocate(7)).WillRepeatedly(Return(&x));
  EXPECT_CALL(mock, deallocate(&x, 7));

  EXPECT_EQ(&x, Traits::allocate(mock, 7));
  Traits::allocate(mock, 7, static_cast<const void*>(&hint));
  EXPECT_EQ(&x, Traits::allocate(mock, 7, static_cast<const void*>(&hint)));
  Traits::deallocate(mock, &x, 7);

  EXPECT_EQ(1, trace);
  Traits::construct(mock, &x, &trace);
  EXPECT_EQ(2, trace);
  Traits::destroy(mock, &x);
  EXPECT_EQ(1, trace);

  EXPECT_EQ(std::numeric_limits<size_t>::max() / sizeof(TestValue),
            Traits::max_size(mock));

  EXPECT_EQ(0, mock.value);
  EXPECT_EQ(0, Traits::select_on_container_copy_construction(mock).value);
}

struct FullMockAllocator {
  FullMockAllocator() : value(0) {}
  explicit FullMockAllocator(int value) : value(value) {}
  FullMockAllocator(const FullMockAllocator& other) : value(other.value) {}
  using value_type = TestValue;
  MOCK_METHOD(value_type*, allocate, (size_t));
  MOCK_METHOD(value_type*, allocate, (size_t, const void*));
  MOCK_METHOD(void, construct, (value_type*, int*));
  MOCK_METHOD(void, destroy, (value_type*));
  MOCK_METHOD(size_t, max_size, (),
              (const));
  MOCK_METHOD(FullMockAllocator, select_on_container_copy_construction, (),
              (const));

  int value;
};

TEST(AllocatorTraits, FunctionsFull) {
  int trace = 0;
  int hint;
  TestValue x(&trace), y;
  FullMockAllocator mock;
  using Traits = absl::allocator_traits<FullMockAllocator>;
  EXPECT_CALL(mock, allocate(7)).WillRepeatedly(Return(&x));
  EXPECT_CALL(mock, allocate(13, &hint)).WillRepeatedly(Return(&y));
  EXPECT_CALL(mock, construct(&x, &trace));
  EXPECT_CALL(mock, destroy(&x));
  EXPECT_CALL(mock, max_size()).WillRepeatedly(Return(17));
  EXPECT_CALL(mock, select_on_container_copy_construction())
      .WillRepeatedly(Return(FullMockAllocator(23)));

  EXPECT_EQ(&x, Traits::allocate(mock, 7));
  EXPECT_EQ(&y, Traits::allocate(mock, 13, static_cast<const void*>(&hint)));

  EXPECT_EQ(1, trace);
  Traits::construct(mock, &x, &trace);
  EXPECT_EQ(1, trace);
  Traits::destroy(mock, &x);
  EXPECT_EQ(1, trace);

  EXPECT_EQ(17, Traits::max_size(mock));

  EXPECT_EQ(0, mock.value);
  EXPECT_EQ(23, Traits::select_on_container_copy_construction(mock).value);
}

TEST(AllocatorNoThrowTest, DefaultAllocator) {
#if defined(ABSL_ALLOCATOR_NOTHROW) && ABSL_ALLOCATOR_NOTHROW
  EXPECT_TRUE(absl::default_allocator_is_nothrow::value);
#else
  EXPECT_FALSE(absl::default_allocator_is_nothrow::value);
#endif
}

TEST(AllocatorNoThrowTest, StdAllocator) {
#if defined(ABSL_ALLOCATOR_NOTHROW) && ABSL_ALLOCATOR_NOTHROW
  EXPECT_TRUE(absl::allocator_is_nothrow<std::allocator<int>>::value);
#else
  EXPECT_FALSE(absl::allocator_is_nothrow<std::allocator<int>>::value);
#endif
}

TEST(AllocatorNoThrowTest, CustomAllocator) {
  struct NoThrowAllocator {
    using is_nothrow = std::true_type;
  };
  struct CanThrowAllocator {
    using is_nothrow = std::false_type;
  };
  struct UnspecifiedAllocator {};
  EXPECT_TRUE(absl::allocator_is_nothrow<NoThrowAllocator>::value);
  EXPECT_FALSE(absl::allocator_is_nothrow<CanThrowAllocator>::value);
  EXPECT_FALSE(absl::allocator_is_nothrow<UnspecifiedAllocator>::value);
}

}  // namespace


text:
package my.delite.framework.codegen.delite.generators

import scala.virtualization.lms.common.{ VariablesExp, ScalaGenEffect, CGenEffect }
import java.io.PrintWriter

trait DeliteGenScalaVariables extends ScalaGenEffect {
  val IR: VariablesExp
  import IR._

  override def emitNode(sym: Sym[Any], rhs: Def[Any]) = rhs match {
    case ReadVar(Variable(a)) => emitValDef(sym, quote(a) + ".get")
    case NewVar(init) => emitValDef(sym, "generated.scala.Ref(" + quote(init) + ")")
    case Assign(Variable(a), b) => stream.println(quote(a) + ".set(" + quote(b) + ")")
    case VarPlusEquals(Variable(a), b) => emitValDef(sym, quote(a) + ".set(" + quote(a) + ".get +" + quote(b) + ")")
    case _ => super.emitNode(sym, rhs)
  }
}


text:
	<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm'); ?>

	Title:
	<input type="text" class="span4" name="title" id="title" />

	Sort By:
	<select name="sortby" id="sortby">
		<option value="id">ID</option>
		<option value="title">Title</option>
		<option value="order">Order</option>
	</select>

	Exclude:
	<input type="text" class="span4" name="title" id="title" />
	Page ID, separated by comma

	    Show

	    Close

	<?php $this->endWidget(); ?>


text:
import { DialogManager } from './dialog-manager';

export interface IDialogConfig {
    viewModel: Function;
    view: Function;
}

export default class DialogsViewFactory
{
    createView(config: IDialogConfig[]) {

        return class implements js.IView<DialogManager> {
            template =
`

`;

            init(dom: js.IDom, dialogManager: DialogManager) {
                const viewSelector = (dialog) => {
                    for (let i = 0; i < config.length; i++) {
                        if (dialog instanceof config[i].viewModel) {
                            return config[i].view;
                        }
                    }

                    throw new Error('Unknown dialog view model');
                };

                const $overlay = dom('.js_dialogsOverlay').$;

                dom('.js_dialogs').observes(dialogManager.visibleDialogs, viewSelector);

                var timerRef = null;
                dom.manager.manage(dialogManager.visibleDialogs.count().listen(visibleDialogsCount => {
                    if (timerRef) {
                        clearTimeout(timerRef);
                        timerRef = null;
                    }

                    if (visibleDialogsCount) {
                        $overlay.css('display', 'block');
                        timerRef = setTimeout(() => {
                            $overlay.css('opacity', '0.8');
                        }, 10);
                    } else {
                        $overlay.css('opacity', '0');
                        timerRef = setTimeout(() => {
                            $overlay.css('display', 'none');
                        }, 1000);
                    }
                }));

                /**
                 * Handle escape button click.
                 */
                $(document).keyup(e => {
                    if (e.keyCode === 27) {
                        dialogManager.closeTopModal();
                    }
                });
            }
        }
    }
}


text:
package bridge;

public class Trouser extends Clothing {
    @Override
    public void personDressCloth(Person person) {
        System.out.println(person.getType() + " dress trouser");
    }
}


text:
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"sort"
	"sync"
	"path"

	"github.com/giagiannis/data-profiler/core"
)

type trainParams struct {
	testset     *core.Dataset   // path of the test set
	script      *string         // path of the ML script
	datasets    []*core.Dataset // path of the input datasets
	concurrency *int            // number of threads to be utilized
	output      *string         // path of the outfile
	logfile     *string         // logfile path
	repetition  *int            // times to execute experiments
}

func trainParseParams() *trainParams {
	params := new(trainParams)
	testset :=
		flag.String("t", "", "path of the test set")
	params.script =
		flag.String("s", "", "path of the ML script")
	input :=
		flag.String("i", "", "path of the datasets dir")
	params.output =
		flag.String("o", "", "path of the output file")
	params.logfile =
		flag.String("l", "", "path of the log file")
	params.concurrency =
		flag.Int("p", 1, "number of threads")
	params.repetition =
		flag.Int("r", 1, "times to repeat experiments (prints median if >1)")
	flag.Parse()
	setLogger(*params.logfile)
	if *testset == "" ||
		*params.script == "" ||
		*params.output == "" ||
		*input == "" {
		fmt.Println("Options:")
		flag.PrintDefaults()
		os.Exit(1)
	}
	params.datasets = core.DiscoverDatasets(*input)
	params.testset = core.NewDataset(*testset)
	return params
}

func trainRun() {
	params := trainParseParams()
	confparams := make(map[string]string)
	confparams["script"] = *params.script
	confparams["testset"] = params.testset.Path()
	eval, err := core.NewDatasetEvaluator(core.OnlineEval, confparams)
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		os.Exit(1)
	}
	results := core.NewDatasetScores()
	done := make(chan bool)
	c := make(chan bool, *params.concurrency)
	for i := 0; i < *params.concurrency; i++ {
		c <- true
	}
	lock := new(sync.Mutex)
	for _, d := range params.datasets {
		go func(d core.Dataset, c, done chan bool) {
			<-c
			log.Println("Training with ", d.Path())
			res := make([]float64, 0)
			for i := 0; i < *params.repetition; i++ {
				val, err := eval.Evaluate(d.Path())
				if err != nil {
					fmt.Fprintf(os.Stderr, err.Error())
					os.Exit(1)
				}
				res = append(res, val)
			}
			sort.Float64s(res)
			lock.Lock()
			results.Scores[path.Base(d.Path())] = res[len(res)/2]
			lock.Unlock()
			c <- true
			done <- true
		}(*d, c, done)
	}
	for range params.datasets {
		<-done
	}
	log.Println("Serializing output to ", *params.output)
	outfile, er := os.OpenFile(*params.output, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
	defer outfile.Close()

	if er != nil {
		fmt.Fprintln(os.Stderr, er)
		os.Exit(1)
	}
	b, err := results.Serialize()
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		os.Exit(1)
	}

	outfile.Write(b)
}


text:
layout: post
title: Kerf lamp& quote research
---

Kerf table lamp research

Kerf lamp is interactive, customized and assembled design made by industrial designers in Massey University.
It is an open design that anyone can edit and adjust. They have used MDF for the body of the kerf table lamp; also they had simple Arduino circuit and an ultra sensor to control LED. This sensor senses hand movements allowing people to turn lamp on/off, and also change brightness. Their pattern for the lamp has been designed on the best curling result and also shows the beauty.

[Kerflamp tumblr](http://opendesignlab.tumblr.com/archive "opendesigntumblr")

Quote Research

 'The maker movement is not about the 'stuff' we can make, it's about the 'meaning' we can make.'
This quote from Jay Silver was inspired by maker movement trend. The maker movement was first developed by people who wanted to develop unique technology products and now anyone could be part of it. By looking at Maker Movement manifesto written by Mark Hatch you can simply discover that maker movement was possible because everyone was willing to share their creation and ideas for others to recreate.
Like this Silver didn't want everybody to be the same, instead he wanted people with different worldview to be part of this movement and to share ideas in order to create something better than before, this way our world will be developed by our own hands.

[Jaysilver quote](http://www.linkedin.com/pulse/maker-movement-3d-printers-jay-silver "jaysilver quote")

Here are more information on Maker movement trend:
[Makermovement trend](http://www.techopedia.com/definition/28408/maker-movement "makermovementtrend")

Here are two other case studies that illustrate these ideas:
Mark Hatch CEO of tech shop
[Mark Hatch makermovement](http://www.techshop.ws/images/0071821139%20Maker%20Movement%20Manifesto%20Sample%20Chapter.pdf "makermovementtrend")

Maker media
[Maker media](http://makermedia.com/wp-content/uploads/2014/10/impact-of-the-maker-movement.pdf "makermovementtrend")

After the research on Kerf table lamp I've noticed that the MDF wasn't the best option for sustainability but their ultra sensor and the design of the lamp had their own uniqueness which fascinated our group. Our group will follow our own manifesto and always challenge ourselves, work to create sustainable outcome, be customized, be adaptable, be open minded, work to the best of our skills but ask for help when we need it, make prototype, be organized and keep moving forward. Together as a group we will always remember that we are part of this maker movement and like others who shared their ideas we want to do the same.


text:
package org.onosproject.pcepio.types;

import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
import org.jboss.netty.buffer.ChannelBuffer;
import org.onosproject.pcepio.protocol.PcepVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

/**
 * Provides IPv6 Sub Object.
 */
public class IPv6SubObject implements PcepValueType {

    /* reference :RFC 4874.
    Subobject : IPv6 address

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |      Type     |     Length    | IPv6 address (16 bytes)       |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    | IPv6 address (continued)                                      |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    | IPv6 address (continued)                                      |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    | IPv6 address (continued)                                      |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    | IPv6 address (continued)      | Prefix Length |      Flags    |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

      Type

         0x02  IPv6 address

      Length

         The Length contains the total length of the subobject in bytes,
         including the Type and Length fields.  The Length is always 20.

      IPv6 address

         A 128-bit unicast host address.

      Prefix length

         128

      Flags

         0x01  Local protection available

               Indicates that the link downstream of this node is
               protected via a local repair mechanism.  This flag can
               only be set if the Local protection flag was set in the
               SESSION_ATTRIBUTE object of the corresponding Path
               message.

         0x02  Local protection in use

               Indicates that a local repair mechanism is in use to
               maintain this tunnel (usually in the face of an outage
               of the link it was previously routed over).
     */
    protected static final Logger log = LoggerFactory.getLogger(IPv6SubObject.class);

    public static final short TYPE = 0x02;
    public static final short LENGTH = 20;
    public static final byte VALUE_LENGTH = 18;

    private static final byte[] NONE_VAL = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    public static final IPv6SubObject NONE = new IPv6SubObject(NONE_VAL);

    private static final byte[] NO_MASK_VAL = {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
        (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
        (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF };
    public static final IPv6SubObject NO_MASK = new IPv6SubObject(NO_MASK_VAL);
    public static final IPv6SubObject FULL_MASK = NONE;

    private final byte[] rawValue;

    /**
     * constructor to initialize rawValue with ipv6 address.
     *
     * @param rawValue ipv6 address
     */
    public IPv6SubObject(byte[] rawValue) {
        this.rawValue = rawValue;
    }

    /**
     * To create instance of IPv6SubObject.
     *
     * @param raw byte array of ipv6 address
     * @return object of IPv6SubObject
     */
    public static IPv6SubObject of(final byte[] raw) {
        //check NONE_VAL
        boolean bFoundNone = true;
        //value starts from 3rd byte.
        for (int i = 2; i < 20; ++i) {
            if (NONE_VAL[i] != raw[i]) {
                bFoundNone = false;
            }
        }

        if (bFoundNone) {
            return NONE;
        }

        //check NO_MASK_VAL
        boolean bFoundNoMask = true;
        //value starts from 3rd byte.
        for (int i = 2; i < 20; ++i) {
            if (0xFF != raw[i]) {
                bFoundNoMask = false;
            }
        }
        if (bFoundNoMask) {
            return NO_MASK;
        }

        return new IPv6SubObject(raw);
    }

    /**
     * Returns value of IPv6 Sub Object.
     *
     * @return byte array of ipv6 address
     */
    public byte[] getValue() {
        return rawValue;
    }

    @Override
    public PcepVersion getVersion() {
        return PcepVersion.PCEP_1;
    }

    @Override
    public short getType() {
        return TYPE;
    }

    @Override
    public short getLength() {
        return LENGTH;
    }

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

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof IPv6SubObject) {
            IPv6SubObject other = (IPv6SubObject) obj;
            return Arrays.equals(rawValue, other.rawValue);
        }
        return false;
    }

    @Override
    public int write(ChannelBuffer c) {
        int iStartIndex = c.writerIndex();
        c.writeShort(TYPE);
        c.writeShort(LENGTH);
        c.writeBytes(rawValue);
        return c.writerIndex() - iStartIndex;
    }

    /**
     * Reads the channel buffer and returns object of IPv6SubObject.
     *
     * @param c type of channel buffer
     * @return object of IPv6SubObject
     */
    public static IPv6SubObject read20Bytes(ChannelBuffer c) {
        byte[] yTemp = new byte[20];
        c.readBytes(yTemp, 0, 20);
        return IPv6SubObject.of(yTemp);
    }

    @Override
    public String toString() {
        ToStringHelper toStrHelper = MoreObjects.toStringHelper(getClass());

        toStrHelper.add("Type", TYPE);
        toStrHelper.add("Length", LENGTH);

        StringBuffer result = new StringBuffer();
        for (byte b : rawValue) {
            result.append(String.format("%02X ", b));
        }
        toStrHelper.add("Value", result);

        return toStrHelper.toString();
    }
}


text:
// -----------------------------------------------------------------------
//  <copyright file="FunctionConfiguration.cs" company="OSharp开源团队">
//      Copyright (c) 2014-2015 OSharp. All rights reserved.
//  </copyright>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2015-07-14 3:29</last-date>
// -----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using OSharp.Core.Data.Entity;
using OSharp.Core.Security;

namespace OSharp.Demo.ModelConfigurations.Security
{
    /// <summary>
    /// 实体映射类——功能信息
    /// </summary>
    public class FunctionConfiguration : EntityConfigurationBase<Function, Guid>
    { }
}


text:
<?php

namespace Arrow\JwtAuth;

use DateInterval;
use Lcobucci\JWT\Signer;
use Lcobucci\Clock\FrozenClock;
use Lcobucci\JWT\Configuration;
use Illuminate\Support\Facades\Auth;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Validation\Constraint;
use Spatie\LaravelPackageTools\Package;
use Arrow\JwtAuth\Commands\Publish\Config;
use Arrow\JwtAuth\Contracts\JwtConfiguration;
use Spatie\LaravelPackageTools\PackageServiceProvider;

class JwtAuthenticationServiceProvider extends PackageServiceProvider
{
    public function configurePackage(Package $package): void
    {
        $package->name('laravel-jwt-auth')
            ->hasCommand(Config::class)
            ->hasConfigFile('jwt-auth');
    }

    /**
     * Register any application authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();

        //merge our config into auth
        $this->app['config']['auth'] = array_replace_recursive(
            $this->app['config']['auth'],
            $this->app['config']['jwt-auth']
        );

        $this->app->bind(JwtConfiguration::class, function ($app) {
            $config = $app['config']->get('auth.providers.jwt');
            $signer = $this->getSigner($config);
            $jwtConfig = null;
            if ($config['signature'] === 'hmac') {
                $jwtConfig = Configuration::forSymmetricSigner(
                    $signer,
                    InMemory::plainText($config['key'])
                );
            } else {
                $jwtConfig = Configuration::forAsymmetricSigner(
                    $signer,
                    file_exists($config['private-key']) ? InMemory::file($config['private-key']) : InMemory::empty(),
                    file_exists($config['public-key']) ? InMemory::file($config['public-key']) : InMemory::empty()
                );
            }

            $jwtConfig->setValidationConstraints(
                new Constraint\SignedWith($jwtConfig->signer(), $jwtConfig->verificationKey()),
                //10 second leeway, this deals with testing and setting up the constraint before the token is generated
                new Constraint\StrictValidAt(new FrozenClock(now()->toDateTimeImmutable()), DateInterval::createFromDateString('10 seconds')),
            );

            return $jwtConfig;
        });

        Auth::extend('jwt', function ($app, $name, array $config) {
            return new Guard(Auth::createUserProvider($config['provider']));
        });

        Auth::provider('jwt', function ($app, array $config) {
            return new UserProvider($app->make(JwtConfiguration::class));
        });
    }

    /**
     * This is baddd - redo this
     * @return Signer gets a signer based on the config
     */
    protected function getSigner($config): Signer
    {
        $className = "\Lcobucci\JWT\Signer\\" . ucwords($config['signature']) . "\\" . ucwords($config['hash']);
        $func = new \ReflectionClass($className);
        if ($config['signature'] === 'ecdsa') {
            return call_user_func($func->getName() . '::create');
        }

        return app()->make($func->getName());
    }
}


text:
import errno
import gzip
import hashlib
import os
import platform
import re
import shutil
import stat
import sys
import tarfile
import tempfile

from os.path import abspath, join as joinpath, realpath
from contextlib import contextmanager

import six

from conans.util.log import logger

def walk(top, **kwargs):
    if six.PY2:
        # If py2 os.walk receives a unicode object, it will fail if a non-ascii file name is found
        # during the iteration. More info:
        # https://stackoverflow.com/questions/21772271/unicodedecodeerror-when-performing-os-walk
        try:
            top = str(top)
        except UnicodeDecodeError:
            pass

    return os.walk(top, **kwargs)

def make_read_only(folder_path):
    for root, _, files in walk(folder_path):
        for f in files:
            full_path = os.path.join(root, f)
            make_file_read_only(full_path)

def make_file_read_only(file_path):
    mode = os.stat(file_path).st_mode
    os.chmod(file_path, mode & ~ stat.S_IWRITE)

_DIRTY_FOLDER = ".dirty"

def set_dirty(folder):
    dirty_file = os.path.normpath(folder) + _DIRTY_FOLDER
    assert not os.path.exists(dirty_file), "Folder '{}' is already dirty".format(folder)
    save(dirty_file, "")

def clean_dirty(folder):
    dirty_file = os.path.normpath(folder) + _DIRTY_FOLDER
    os.remove(dirty_file)

def is_dirty(folder):
    dirty_file = os.path.normpath(folder) + _DIRTY_FOLDER
    return os.path.exists(dirty_file)

@contextmanager
def set_dirty_context_manager(folder):
    set_dirty(folder)
    yield
    clean_dirty(folder)

def _detect_encoding(text):
    import codecs
    encodings = {codecs.BOM_UTF8: "utf_8_sig",
                 codecs.BOM_UTF16_BE: "utf_16_be",
                 codecs.BOM_UTF16_LE: "utf_16_le",
                 codecs.BOM_UTF32_BE: "utf_32_be",
                 codecs.BOM_UTF32_LE: "utf_32_le",
                 b'\x2b\x2f\x76\x38': "utf_7",
                 b'\x2b\x2f\x76\x39': "utf_7",
                 b'\x2b\x2f\x76\x2b': "utf_7",
                 b'\x2b\x2f\x76\x2f': "utf_7",
                 b'\x2b\x2f\x76\x38\x2d': "utf_7"}
    for bom in sorted(encodings, key=len, reverse=True):
        if text.startswith(bom):
            try:
                return encodings[bom], len(bom)
            except UnicodeDecodeError:
                continue
    decoders = ["utf-8", "Windows-1252"]
    for decoder in decoders:
        try:
            text.decode(decoder)
            return decoder, 0
        except UnicodeDecodeError:
            continue
    return None, 0

def decode_text(text, encoding="auto"):
    bom_length = 0
    if encoding == "auto":
        encoding, bom_length = _detect_encoding(text)
        if encoding is None:
            logger.warning("can't decode %s" % str(text))
            return text.decode("utf-8", "ignore")  # Ignore not compatible characters
    return text[bom_length:].decode(encoding)

def touch(fname, times=None):
    os.utime(fname, times)

def touch_folder(folder):
    for dirname, _, filenames in walk(folder):
        for fname in filenames:
            try:
                os.utime(os.path.join(dirname, fname), None)
            except Exception:
                pass

def normalize(text):
    if platform.system() == "Windows":
        return re.sub("\r?\n", "\r\n", text)
    else:
        return text

def md5(content):
    try:
        md5alg = hashlib.md5()
    except ValueError:  # FIPS error https://github.com/conan-io/conan/issues/7800
        md5alg = hashlib.md5(usedforsecurity=False)
    if isinstance(content, bytes):
        tmp = content
    else:
        tmp = content.encode("utf-8")
    md5alg.update(tmp)
    return md5alg.hexdigest()

def md5sum(file_path):
    return _generic_algorithm_sum(file_path, "md5")

def sha1sum(file_path):
    return _generic_algorithm_sum(file_path, "sha1")

def sha256sum(file_path):
    return _generic_algorithm_sum(file_path, "sha256")

def _generic_algorithm_sum(file_path, algorithm_name):

    with open(file_path, 'rb') as fh:
        try:
            m = hashlib.new(algorithm_name)
        except ValueError:  # FIPS error https://github.com/conan-io/conan/issues/7800
            m = hashlib.new(algorithm_name, usedforsecurity=False)
        while True:
            data = fh.read(8192)
            if not data:
                break
            m.update(data)
        return m.hexdigest()

def save_append(path, content, encoding="utf-8"):
    try:
        os.makedirs(os.path.dirname(path))
    except Exception:
        pass

    with open(path, "ab") as handle:
        handle.write(to_file_bytes(content, encoding=encoding))

def save(path, content, only_if_modified=False, encoding="utf-8"):
    """
    Saves a file with given content
    Params:
        path: path to write file to
        content: contents to save in the file
        only_if_modified: file won't be modified if the content hasn't changed
        encoding: target file text encoding
    """
    dir_path = os.path.dirname(path)
    if not os.path.isdir(dir_path):
        try:
            os.makedirs(dir_path)
        except OSError as error:
            if error.errno not in (errno.EEXIST, errno.ENOENT):
                raise OSError("The folder {} does not exist and could not be created ({})."
                              .format(dir_path, error.strerror))
        except Exception:
            raise

    new_content = to_file_bytes(content, encoding)

    if only_if_modified and os.path.exists(path):
        old_content = load(path, binary=True, encoding=encoding)
        if old_content == new_content:
            return

    with open(path, "wb") as handle:
        handle.write(new_content)

def mkdir_tmp():
    return tempfile.mkdtemp(suffix='tmp_conan')

def to_file_bytes(content, encoding="utf-8"):
    if six.PY3:
        if not isinstance(content, bytes):
            content = bytes(content, encoding)
    elif isinstance(content, unicode):
        content = content.encode(encoding)
    return content

def save_files(path, files, only_if_modified=False, encoding="utf-8"):
    for name, content in files.items():
        save(os.path.join(path, name), content, only_if_modified=only_if_modified, encoding=encoding)

def load(path, binary=False, encoding="auto"):
    """ Loads a file content """
    with open(path, 'rb') as handle:
        tmp = handle.read()
        return tmp if binary else decode_text(tmp, encoding)

def relative_dirs(path):
    """ Walks a dir and return a list with the relative paths """
    ret = []
    for dirpath, _, fnames in walk(path):
        for filename in fnames:
            tmp = os.path.join(dirpath, filename)
            tmp = tmp[len(path) + 1:]
            ret.append(tmp)
    return ret

def get_abs_path(folder, origin):
    if folder:
        if os.path.isabs(folder):
            return folder
        return os.path.join(origin, folder)
    return origin

def _change_permissions(func, path, exc_info):
    if not os.access(path, os.W_OK):
        os.chmod(path, stat.S_IWUSR)
        func(path)
    else:
        raise OSError("Cannot change permissions for {}! Exception info: {}".format(path, exc_info))

def rmdir(path):
    try:
        shutil.rmtree(path, onerror=_change_permissions)
    except OSError as err:
        if err.errno == errno.ENOENT:
            return
        raise

def remove(path):
    try:
        assert os.path.isfile(path)
        os.remove(path)
    except (IOError, OSError) as e:  # for py3, handle just PermissionError
        if e.errno == errno.EPERM or e.errno == errno.EACCES:
            os.chmod(path, stat.S_IRWXU)
            os.remove(path)
            return
        raise

def mkdir(path):
    """Recursive mkdir, doesnt fail if already existing"""
    if os.path.exists(path):
        return
    os.makedirs(path)

def path_exists(path, basedir):
    """Case sensitive, for windows, optional
    basedir for skip caps check for tmp folders in testing for example (returned always
    in lowercase for some strange reason)"""
    exists = os.path.exists(path)
    if not exists or sys.platform == "linux2":
        return exists

    path = os.path.normpath(path)
    path = os.path.relpath(path, basedir)
    chunks = path.split(os.sep)
    tmp = basedir

    for chunk in chunks:
        if chunk and chunk not in os.listdir(tmp):
            return False
        tmp = os.path.normpath(tmp + os.sep + chunk)
    return True

def gzopen_without_timestamps(name, mode="r", fileobj=None, **kwargs):
    """ !! Method overrided by laso to pass mtime=0 (!=None) to avoid time.time() was
        setted in Gzip file causing md5 to change. Not possible using the
        previous tarfile open because arguments are not passed to GzipFile constructor
    """
    compresslevel = int(os.getenv("CONAN_COMPRESSION_LEVEL", 9))

    if mode not in ("r", "w"):
        raise ValueError("mode must be 'r' or 'w'")

    try:
        fileobj = gzip.GzipFile(name, mode, compresslevel, fileobj, mtime=0)
    except OSError:
        if fileobj is not None and mode == 'r':
            raise tarfile.ReadError("not a gzip file")
        raise

    try:
        # Format is forced because in Python3.8, it changed and it generates different tarfiles
        # with different checksums, which break hashes of tgzs
        t = tarfile.TarFile.taropen(name, mode, fileobj, format=tarfile.GNU_FORMAT, **kwargs)
    except IOError:
        fileobj.close()
        if mode == 'r':
            raise tarfile.ReadError("not a gzip file")
        raise
    except Exception:
        fileobj.close()
        raise
    t._extfileobj = False
    return t

def tar_extract(fileobj, destination_dir):
    """Extract tar file controlling not absolute paths and fixing the routes
    if the tar was zipped in windows"""
    def badpath(path, base):
        # joinpath will ignore base if path is absolute
        return not realpath(abspath(joinpath(base, path))).startswith(base)

    def safemembers(members):
        base = realpath(abspath(destination_dir))

        for finfo in members:
            if badpath(finfo.name, base) or finfo.islnk():
                logger.warning("file:%s is skipped since it's not safe." % str(finfo.name))
                continue
            else:
                # Fixes unzip a windows zipped file in linux
                finfo.name = finfo.name.replace("\\", "/")
                yield finfo

    the_tar = tarfile.open(fileobj=fileobj)
    # NOTE: The errorlevel=2 has been removed because it was failing in Win10, it didn't allow to
    # "could not change modification time", with time=0
    # the_tar.errorlevel = 2  # raise exception if any error
    the_tar.extractall(path=destination_dir, members=safemembers(the_tar))
    the_tar.close()

def list_folder_subdirs(basedir, level):
    ret = []
    for root, dirs, _ in walk(basedir):
        rel_path = os.path.relpath(root, basedir)
        if rel_path == ".":
            continue
        dir_split = rel_path.split(os.sep)
        if len(dir_split) == level:
            ret.append("/".join(dir_split))
            dirs[:] = []  # Stop iterate subdirs
    return ret

def exception_message_safe(exc):
    try:
        return str(exc)
    except Exception:
        return decode_text(repr(exc))

def merge_directories(src, dst, excluded=None):
    src = os.path.normpath(src)
    dst = os.path.normpath(dst)
    excluded = excluded or []
    excluded = [os.path.normpath(entry) for entry in excluded]

    def is_excluded(origin_path):
        if origin_path == dst:
            return True
        rel_path = os.path.normpath(os.path.relpath(origin_path, src))
        if rel_path in excluded:
            return True
        return False

    def link_to_rel(pointer_src):
        linkto = os.readlink(pointer_src)
        if not os.path.isabs(linkto):
            linkto = os.path.join(os.path.dirname(pointer_src), linkto)

        # Check if it is outside the sources
        out_of_source = os.path.relpath(linkto, os.path.realpath(src)).startswith(".")
        if out_of_source:
            # May warn about out of sources symlink
            return

        # Create the symlink
        linkto_rel = os.path.relpath(linkto, os.path.dirname(pointer_src))
        pointer_dst = os.path.normpath(os.path.join(dst, os.path.relpath(pointer_src, src)))
        os.symlink(linkto_rel, pointer_dst)

    for src_dir, dirs, files in walk(src, followlinks=True):
        if is_excluded(src_dir):
            dirs[:] = []
            continue

        if os.path.islink(src_dir):
            link_to_rel(src_dir)
            dirs[:] = []  # Do not enter subdirectories
            continue

        # Overwriting the dirs will prevents walk to get into them
        files[:] = [d for d in files if not is_excluded(os.path.join(src_dir, d))]

        dst_dir = os.path.normpath(os.path.join(dst, os.path.relpath(src_dir, src)))
        if not os.path.exists(dst_dir):
            os.makedirs(dst_dir)
        for file_ in files:
            src_file = os.path.join(src_dir, file_)
            dst_file = os.path.join(dst_dir, file_)
            if os.path.islink(src_file):
                link_to_rel(src_file)
            else:
                shutil.copy2(src_file, dst_file)


text:
'use strict'

$(function(){
	$('#updateBt').on('click',appSiteMailUpdate.update);
	webCommon.initICheck();
	appSiteMailUpdate.initUI();
    $('#smtitle').focus();
});

var appSiteMailUpdate=new Object({
	updateIsClick:true,
	update:function(){
		if(appSiteMailUpdate.updateIsClick==false) return false;
		var fid=$('#fid').val();
		var smtitle=$('#smtitle').val();
		var smcontent=$('#smcontent').val();
		var state=$('input[name="state"]:checked').val();

		if(smtitle.length<2){
			toastr.error('标题不能为空');
			$('#smtitle').focus();
			return false;
		}
		if(smcontent.length<=0){
			toastr.error('内容不能为空');
			$('#smcontent').focus();
			return false;
		}

		var myBasePath='/webapi/v1/appsitemailupdate';
		$.post(myBasePath,{
			token:$('#servertoken').val(),
			fid:fid,
			smtitle: smtitle ,
			smcontent: smcontent ,
			state:state
		},function (dt){
			  if('000000'==dt.code){
				  toastr.success(dt.msg);
			  }else{
				  toastr.error(dt.msg);
			  }
	    },'json');

		appSiteMailUpdate.updateIsClick=false;
		setTimeout(function() {	appSiteMailUpdate.updateIsClick = true;	}, 3000);//3秒内不可以重复点击

	},
	initUI:function(){
	}
});


text:
<?php
/**
 * Created by PhpStorm.
 * User: Yury Maltsev
 * Email: dev.ymalcev@gmail.com
 * Date: 1/29/14
 * Time: 2:57 PM
 */

namespace Fp\JsFormValidatorBundle\Tests\TestBundles\DefaultTestBundle\Entity;

abstract class BaseEntityRepository
{
    abstract public function getData();

    /**
     * This method just should return some not empty data
     *
     * @param string $id
     *
     * @return array
     */
    public function find($id)
    {
        return array('a' => $id);
    }

    /**
     * This method searches the data in the artificial storage of this repository
     *
     * @param array $criteria
     *
     * @return array
     */
    public function findBy(array $criteria)
    {
        $entities = array();
        foreach ($this->getData() as $entity) {
            $result = array();
            foreach ($criteria as $field => $value) {
                if ((isset($entity[$field]) || null == $entity[$field]) && $value == $entity[$field]) {
                    $result[$field] = $value;
                }
            }
            if ($result === $criteria) {
                $entities[] = $entity;
            }
        }

        return $entities;
    }
}


text:
package io.jenetics.prog.op;

import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author Franz Wilhelmstötter
 */
public final class CSV {
	private CSV() {
	}

	public static List<String> read(final InputStream in) {
		try (in) {
			final var value = new String(in.readAllBytes());
			return Arrays.asList(value.split("\n"));
		} catch (IOException e) {
			throw new UncheckedIOException(e);
		}
	}

}


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

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
    internal partial class ITypeSymbolExtensions
    {
        private class TypeSyntaxGeneratorVisitor : SymbolVisitor<TypeSyntax>
        {
            private readonly bool _nameOnly;

            private static readonly TypeSyntaxGeneratorVisitor NameOnlyInstance = new(nameOnly: true);
            private static readonly TypeSyntaxGeneratorVisitor NotNameOnlyInstance = new(nameOnly: false);

            private TypeSyntaxGeneratorVisitor(bool nameOnly)
                => _nameOnly = nameOnly;

            public static TypeSyntaxGeneratorVisitor Create(bool nameOnly = false)
                => nameOnly ? NameOnlyInstance : NotNameOnlyInstance;

            public override TypeSyntax DefaultVisit(ISymbol node)
                => throw new NotImplementedException();

            private static TTypeSyntax AddInformationTo<TTypeSyntax>(TTypeSyntax syntax, ISymbol symbol)
                where TTypeSyntax : TypeSyntax
            {
                syntax = syntax.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker);
                syntax = syntax.WithAdditionalAnnotations(SymbolAnnotation.Create(symbol));

                return syntax;
            }

            public override TypeSyntax VisitAlias(IAliasSymbol symbol)
                => AddInformationTo(symbol.Name.ToIdentifierName(), symbol);

            private void ThrowIfNameOnly()
            {
                if (_nameOnly)
                {
                    throw new InvalidOperationException("This symbol cannot be converted into a NameSyntax");
                }
            }

            public override TypeSyntax VisitArrayType(IArrayTypeSymbol symbol)
            {
                ThrowIfNameOnly();

                ITypeSymbol underlyingType = symbol;

                while (underlyingType is IArrayTypeSymbol innerArray)
                {
                    underlyingType = innerArray.ElementType;

                    if (underlyingType.NullableAnnotation == NullableAnnotation.Annotated)
                    {
                        // If the inner array we just moved to is also nullable, then
                        // we must terminate the digging now so we produce the syntax for that,
                        // and then append the ranks we passed through at the end. This is because
                        // nullability annotations acts as a "barrier" where we won't reorder array
                        // through. So whereas:
                        //
                        //     string[][,]
                        //
                        // is really an array of rank 1 that has an element of rank 2,
                        //
                        //     string[]?[,]
                        //
                        // is really an array of rank 2 that has nullable elements of rank 1.

                        break;
                    }
                }

                var elementTypeSyntax = underlyingType.GenerateTypeSyntax();
                using var _ = ArrayBuilder<ArrayRankSpecifierSyntax>.GetInstance(out var ranks);

                var arrayType = symbol;
                while (arrayType != null && !arrayType.Equals(underlyingType))
                {
                    ranks.Add(SyntaxFactory.ArrayRankSpecifier(
                        SyntaxFactory.SeparatedList(Enumerable.Repeat<ExpressionSyntax>(SyntaxFactory.OmittedArraySizeExpression(), arrayType.Rank))));

                    arrayType = arrayType.ElementType as IArrayTypeSymbol;
                }

                TypeSyntax arrayTypeSyntax = SyntaxFactory.ArrayType(elementTypeSyntax, ranks.ToSyntaxList());

                if (symbol.NullableAnnotation == NullableAnnotation.Annotated)
                {
                    arrayTypeSyntax = SyntaxFactory.NullableType(arrayTypeSyntax);
                }

                return AddInformationTo(arrayTypeSyntax, symbol);
            }

            public override TypeSyntax VisitDynamicType(IDynamicTypeSymbol symbol)
                => AddInformationTo(SyntaxFactory.IdentifierName("dynamic"), symbol);

            public static bool TryCreateNativeIntegerType(INamedTypeSymbol symbol, [NotNullWhen(true)] out TypeSyntax? syntax)
            {
                if (symbol.IsNativeIntegerType)
                {
                    syntax = SyntaxFactory.IdentifierName(symbol.SpecialType == SpecialType.System_IntPtr ? "nint" : "nuint");
                    return true;
                }

                syntax = null;
                return false;
            }

            public override TypeSyntax VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol)
            {
                FunctionPointerCallingConventionSyntax? callingConventionSyntax = null;
                // For varargs there is no C# syntax. You get a use-site diagnostic if you attempt to use it, and just
                // making a default-convention symbol is likely good enough. This is only observable through metadata
                // that always be uncompilable in C# anyway.
                if (symbol.Signature.CallingConvention != System.Reflection.Metadata.SignatureCallingConvention.Default
                    && symbol.Signature.CallingConvention != System.Reflection.Metadata.SignatureCallingConvention.VarArgs)
                {
                    var conventionsList = symbol.Signature.CallingConvention switch
                    {
                        System.Reflection.Metadata.SignatureCallingConvention.CDecl => new[] { GetConventionForString("Cdecl") },
                        System.Reflection.Metadata.SignatureCallingConvention.StdCall => new[] { GetConventionForString("Stdcall") },
                        System.Reflection.Metadata.SignatureCallingConvention.ThisCall => new[] { GetConventionForString("Thiscall") },
                        System.Reflection.Metadata.SignatureCallingConvention.FastCall => new[] { GetConventionForString("Fastcall") },
                        System.Reflection.Metadata.SignatureCallingConvention.Unmanaged =>
                            // All types that come from CallingConventionTypes start with "CallConv". We don't want the prefix for the actual
                            // syntax, so strip it off
                            symbol.Signature.UnmanagedCallingConventionTypes.IsEmpty
                                ? null : symbol.Signature.UnmanagedCallingConventionTypes.Select(type => GetConventionForString(type.Name["CallConv".Length..])),

                        _ => throw ExceptionUtilities.UnexpectedValue(symbol.Signature.CallingConvention),
                    };

                    callingConventionSyntax = SyntaxFactory.FunctionPointerCallingConvention(
                        SyntaxFactory.Token(SyntaxKind.UnmanagedKeyword),
                        conventionsList is object
                            ? SyntaxFactory.FunctionPointerUnmanagedCallingConventionList(SyntaxFactory.SeparatedList(conventionsList))
                            : null);

                    static FunctionPointerUnmanagedCallingConventionSyntax GetConventionForString(string identifier)
                        => SyntaxFactory.FunctionPointerUnmanagedCallingConvention(SyntaxFactory.Identifier(identifier));
                }

                var parameters = symbol.Signature.Parameters.Select(p => (p.Type, RefKindModifiers: CSharpSyntaxGeneratorInternal.GetParameterModifiers(p.RefKind)))
                    .Concat(SpecializedCollections.SingletonEnumerable((
                        Type: symbol.Signature.ReturnType,
                        RefKindModifiers: CSharpSyntaxGeneratorInternal.GetParameterModifiers(symbol.Signature.RefKind, forFunctionPointerReturnParameter: true))))
                    .SelectAsArray(t => SyntaxFactory.FunctionPointerParameter(t.Type.GenerateTypeSyntax()).WithModifiers(t.RefKindModifiers));

                return AddInformationTo(
                    SyntaxFactory.FunctionPointerType(callingConventionSyntax, SyntaxFactory.FunctionPointerParameterList(SyntaxFactory.SeparatedList(parameters))), symbol);
            }

            public TypeSyntax CreateSimpleTypeSyntax(INamedTypeSymbol symbol)
            {
                if (!_nameOnly)
                {
                    var syntax = TryCreateSpecializedNamedTypeSyntax(symbol);
                    if (syntax != null)
                        return syntax;
                }

                if (symbol.IsTupleType && symbol.TupleUnderlyingType != null && !symbol.Equals(symbol.TupleUnderlyingType))
                {
                    return CreateSimpleTypeSyntax(symbol.TupleUnderlyingType);
                }

                if (symbol.Name == string.Empty || symbol.IsAnonymousType)
                {
                    return CreateSystemObject();
                }

                if (symbol.TypeParameters.Length == 0)
                {
                    if (symbol.TypeKind == TypeKind.Error && symbol.Name == "var")
                    {
                        return CreateSystemObject();
                    }

                    return symbol.Name.ToIdentifierName();
                }

                var typeArguments = symbol.IsUnboundGenericType
                    ? Enumerable.Repeat((TypeSyntax)SyntaxFactory.OmittedTypeArgument(), symbol.TypeArguments.Length)
                    : symbol.TypeArguments.SelectAsArray(t => t.GenerateTypeSyntax());

                return SyntaxFactory.GenericName(
                    symbol.Name.ToIdentifierToken(),
                    SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments)));
            }

            private static QualifiedNameSyntax CreateSystemObject()
            {
                return SyntaxFactory.QualifiedName(
                    SyntaxFactory.AliasQualifiedName(
                        CreateGlobalIdentifier(),
                        SyntaxFactory.IdentifierName("System")),
                    SyntaxFactory.IdentifierName("Object"));
            }

            private static IdentifierNameSyntax CreateGlobalIdentifier()
                => SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword));

            private static TypeSyntax? TryCreateSpecializedNamedTypeSyntax(INamedTypeSymbol symbol)
            {
                if (symbol.SpecialType == SpecialType.System_Void)
                {
                    return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword));
                }

                if (symbol.IsTupleType && symbol.TupleElements.Length >= 2)
                {
                    return CreateTupleTypeSyntax(symbol);
                }

                if (symbol.IsNullable())
                {
                    // Can't have a nullable of a pointer type.  i.e. "int*?" is illegal.
                    var innerType = symbol.TypeArguments.First();
                    if (innerType.TypeKind != TypeKind.Pointer)
                    {
                        return AddInformationTo(
                            SyntaxFactory.NullableType(innerType.GenerateTypeSyntax()), symbol);
                    }
                }

                return null;
            }

            private static TupleTypeSyntax CreateTupleTypeSyntax(INamedTypeSymbol symbol)
            {
                var list = new SeparatedSyntaxList<TupleElementSyntax>();

                foreach (var element in symbol.TupleElements)
                {
                    var name = element.IsImplicitlyDeclared ? default : SyntaxFactory.Identifier(element.Name);
                    list = list.Add(SyntaxFactory.TupleElement(element.Type.GenerateTypeSyntax(), name));
                }

                return AddInformationTo(SyntaxFactory.TupleType(list), symbol);
            }

            public override TypeSyntax VisitNamedType(INamedTypeSymbol symbol)
            {
                if (TryCreateNativeIntegerType(symbol, out var typeSyntax))
                    return typeSyntax;

                typeSyntax = CreateSimpleTypeSyntax(symbol);
                if (!(typeSyntax is SimpleNameSyntax))
                    return typeSyntax;

                var simpleNameSyntax = (SimpleNameSyntax)typeSyntax;
                if (symbol.ContainingType != null)
                {
                    if (symbol.ContainingType.TypeKind != TypeKind.Submission)
                    {
                        var containingTypeSyntax = symbol.ContainingType.Accept(this);
                        if (containingTypeSyntax is NameSyntax name)
                        {
                            typeSyntax = AddInformationTo(
                                SyntaxFactory.QualifiedName(name, simpleNameSyntax),
                                symbol);
                        }
                        else
                        {
                            typeSyntax = AddInformationTo(simpleNameSyntax, symbol);
                        }
                    }
                }
                else if (symbol.ContainingNamespace != null)
                {
                    if (symbol.ContainingNamespace.IsGlobalNamespace)
                    {
                        if (symbol.TypeKind != TypeKind.Error)
                        {
                            typeSyntax = AddGlobalAlias(symbol, simpleNameSyntax);
                        }
                    }
                    else
                    {
                        var container = symbol.ContainingNamespace.Accept(this);
                        typeSyntax = AddInformationTo(SyntaxFactory.QualifiedName(
                            (NameSyntax)container,
                            simpleNameSyntax), symbol);
                    }
                }

                if (symbol.NullableAnnotation == NullableAnnotation.Annotated)
                {
                    typeSyntax = AddInformationTo(SyntaxFactory.NullableType(typeSyntax), symbol);
                }

                return typeSyntax;
            }

            public override TypeSyntax VisitNamespace(INamespaceSymbol symbol)
            {
                var syntax = AddInformationTo(symbol.Name.ToIdentifierName(), symbol);
                if (symbol.ContainingNamespace == null)
                {
                    return syntax;
                }

                if (symbol.ContainingNamespace.IsGlobalNamespace)
                {
                    return AddGlobalAlias(symbol, syntax);
                }
                else
                {
                    var container = symbol.ContainingNamespace.Accept(this);
                    return AddInformationTo(SyntaxFactory.QualifiedName(
                        (NameSyntax)container,
                        syntax), symbol);
                }
            }

            /// <summary>
            /// We always unilaterally add "global::" to all named types/namespaces.  This
            /// will then be trimmed off if possible by calls to
            /// <see cref="Simplifier.ReduceAsync(Document, OptionSet, CancellationToken)"/>
            /// </summary>
            private static TypeSyntax AddGlobalAlias(INamespaceOrTypeSymbol symbol, SimpleNameSyntax syntax)
            {
                return AddInformationTo(
                    SyntaxFactory.AliasQualifiedName(
                        CreateGlobalIdentifier(),
                        syntax), symbol);
            }

            public override TypeSyntax VisitPointerType(IPointerTypeSymbol symbol)
            {
                ThrowIfNameOnly();

                return AddInformationTo(
                    SyntaxFactory.PointerType(symbol.PointedAtType.GenerateTypeSyntax()),
                    symbol);
            }

            public override TypeSyntax VisitTypeParameter(ITypeParameterSymbol symbol)
            {
                TypeSyntax typeSyntax = AddInformationTo(symbol.Name.ToIdentifierName(), symbol);
                if (symbol.NullableAnnotation == NullableAnnotation.Annotated)
                    typeSyntax = AddInformationTo(SyntaxFactory.NullableType(typeSyntax), symbol);

                return typeSyntax;
            }
        }
    }
}