text:
package graphmock

import (
	"strconv"

	"github.com/cayleygraph/cayley/graph"
	"github.com/cayleygraph/cayley/graph/iterator"
	"github.com/cayleygraph/cayley/quad"
)

var (
	_ graph.Value = IntVal(0)
	_ graph.Value = StringNode("")
)

type IntVal int

func (v IntVal) Key() interface{} { return v }

type StringNode string

func (s StringNode) Key() interface{} { return s }

// Oldstore is a mocked version of the QuadStore interface, for use in tests.
type Oldstore struct {
	Parse bool
	Data  []string
	Iter  graph.Iterator
}

func (qs *Oldstore) valueAt(i int) quad.Value {
	if !qs.Parse {
		return quad.Raw(qs.Data[i])
	}
	iv, err := strconv.Atoi(qs.Data[i])
	if err == nil {
		return quad.Int(iv)
	}
	return quad.String(qs.Data[i])
}

func (qs *Oldstore) ValueOf(s quad.Value) graph.Value {
	if s == nil {
		return nil
	}
	for i := range qs.Data {
		if s.String() == qs.valueAt(i).String() {
			return iterator.Int64Node(i)
		}
	}
	return nil
}

func (qs *Oldstore) ApplyDeltas([]graph.Delta, graph.IgnoreOpts) error { return nil }

func (qs *Oldstore) Quad(graph.Value) quad.Quad { return quad.Quad{} }

func (qs *Oldstore) QuadIterator(d quad.Direction, i graph.Value) graph.Iterator {
	return qs.Iter
}

func (qs *Oldstore) NodesAllIterator() graph.Iterator { return &iterator.Null{} }

func (qs *Oldstore) QuadsAllIterator() graph.Iterator { return &iterator.Null{} }

func (qs *Oldstore) NameOf(v graph.Value) quad.Value {
	switch v.(type) {
	case iterator.Int64Node:
		i := int(v.(iterator.Int64Node))
		if i < 0 || i >= len(qs.Data) {
			return nil
		}
		return qs.valueAt(i)
	case StringNode:
		if qs.Parse {
			return quad.String(v.(StringNode))
		}
		return quad.Raw(v.(StringNode))
	default:
		return nil
	}
}

func (qs *Oldstore) Size() int64 { return 0 }

func (qs *Oldstore) Horizon() graph.PrimaryKey { return graph.NewSequentialKey(0) }

func (qs *Oldstore) DebugPrint() {}

func (qs *Oldstore) OptimizeIterator(it graph.Iterator) (graph.Iterator, bool) {
	return &iterator.Null{}, false
}

func (qs *Oldstore) FixedIterator() graph.FixedIterator {
	return iterator.NewFixed(iterator.Identity)
}

func (qs *Oldstore) Close() error { return nil }

func (qs *Oldstore) QuadDirection(graph.Value, quad.Direction) graph.Value {
	return iterator.Int64Node(0)
}

func (qs *Oldstore) RemoveQuad(t quad.Quad) {}

func (qs *Oldstore) Type() string { return "oldmockstore" }

type Store struct {
	Data []quad.Quad
}

var _ graph.QuadStore = &Store{}

func (qs *Store) ValueOf(s quad.Value) graph.Value {
	return graph.PreFetched(s)
}

func (qs *Store) ApplyDeltas([]graph.Delta, graph.IgnoreOpts) error { return nil }

type quadValue struct {
	q quad.Quad
}

func (q quadValue) Key() interface{} {
	return q.q.String()
}

func (qs *Store) Quad(v graph.Value) quad.Quad { return v.(quadValue).q }

func (qs *Store) NameOf(v graph.Value) quad.Value {
	if v == nil {
		return nil
	}
	return v.(graph.PreFetchedValue).NameOf()
}

func (qs *Store) RemoveQuad(t quad.Quad) {}

func (qs *Store) Type() string { return "mockstore" }

func (qs *Store) QuadDirection(v graph.Value, d quad.Direction) graph.Value {
	return graph.PreFetched(qs.Quad(v).Get(d))
}

func (qs *Store) OptimizeIterator(it graph.Iterator) (graph.Iterator, bool) {
	return &iterator.Null{}, false
}

func (qs *Store) FixedIterator() graph.FixedIterator {
	return iterator.NewFixed(iterator.Identity)
}

func (qs *Store) Close() error { return nil }

func (qs *Store) Horizon() graph.PrimaryKey { return graph.NewSequentialKey(0) }

func (qs *Store) DebugPrint() {}

func (qs *Store) QuadIterator(d quad.Direction, i graph.Value) graph.Iterator {
	fixed := qs.FixedIterator()
	v := i.(graph.PreFetchedValue).NameOf()
	for _, q := range qs.Data {
		if q.Get(d) == v {
			fixed.Add(quadValue{q})
		}
	}
	return fixed
}

func (qs *Store) NodesAllIterator() graph.Iterator {
	set := make(map[string]bool)
	for _, q := range qs.Data {
		for _, d := range quad.Directions {
			n := qs.NameOf(graph.PreFetched(q.Get(d)))
			if n != nil {
				set[n.String()] = true
			}
		}
	}
	fixed := qs.FixedIterator()
	for k, _ := range set {
		fixed.Add(graph.PreFetched(quad.Raw(k)))
	}
	return fixed
}

func (qs *Store) QuadsAllIterator() graph.Iterator {
	fixed := qs.FixedIterator()
	for _, q := range qs.Data {
		fixed.Add(quadValue{q})
	}
	return fixed
}

func (qs *Store) Size() int64 { return int64(len(qs.Data)) }


text:
<?php

namespace Faker\Provider\be_BE;

/**
 * Class Payment
 *
 * @package Faker\Provider\be_BE
 */
class Payment extends \Faker\Provider\Payment
{
    /**
     * Value Added Tax (VAT)
     *
     * @example 'BE0123456789', ('spaced') 'BE 0123456789'
     *
     * @see http://ec.europa.eu/taxation_customs/vies/faq.html?locale=en#item_11
     * @see http://www.iecomputersystems.com/ordering/eu_vat_numbers.htm
     * @see http://en.wikipedia.org/wiki/VAT_identification_number
     *
     * @param bool $spacedNationalPrefix
     *
     * @return string VAT Number
     */
    public static function vat($spacedNationalPrefix = true)
    {
        $prefix = ($spacedNationalPrefix) ? "BE " : "BE";

        return sprintf("%s0%d", $prefix, self::randomNumber(9, true));
    }
}

redpajama_set_name: RedPajamaGithub


text:
module.exports.base = require('./base.js');
module.exports.volumes = require('./volumes.js');
module.exports.categories = require('./categories.js');
module.exports.auth = require('./auth.js');


text:
import StoreWatcher from './src/StoreWatcher';
import StoreEventHandler from './src/StoreEventHandler.js';
import ActionCreatorFactory from './src/ActionCreatorFactory';
import StoreFactory from './src/StoreFactory';
import FlaxDispatcher from './src/FlaxDispatcher'

const createActionCreator = ActionCreatorFactory.createActionCreator;
const createStore = StoreFactory.createStore;

export {
  createActionCreator,
  createStore,
  FlaxDispatcher,
  StoreWatcher,
  StoreEventHandler
};

const Flax = {
  createActionCreator,
  createStore,
  FlaxDispatcher,
  StoreWatcher,
  StoreEventHandler
};

export default Flax;


text:
<?php

namespace Investor\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Http\Request;

use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use DoctrineORMModule\Form\Annotation\AnnotationBuilder;

class InvestorController extends AbstractActionController {

    // ------------------------------ Properties ------------------------------ //
    /**
    * It is the Entity manager provided by Doctrine
    * @var Service
    */
    protected $objectManager;

    // ------------------------------ Methods ------------------------------ //
    /**
    * @return Service Entity Manager instance
    */
    private function getObjectManager() {
        return $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
    }

    /**
    * @param string $repoStr The name of the Class
    * @return Repository Should return the corresponding repository
    */
    private function getRepository($repoStr) {
        if ($this->objectManager == null) {
            $this->objectManager = $this->getObjectManager();
        }
        return $this->objectManager->getRepository($repoStr . "\\Entity\\" . $repoStr);
    }

    private function updateCounts() {
        if ($this->objectManager == null) {
            $this->objectManager = $this->getObjectManager();
        }
        \Client\Entity\Client::updateCount($this->objectManager);
        \Investor\Entity\Investor::updateCount($this->objectManager);
        \Account\Entity\Account::updateCount($this->objectManager);
        \Contribution\Entity\Contribution::updateCount($this->objectManager);
    }

    // ============================== Action Methods ============================== //
    public function showAllAction() {
        $this->updateCounts();
        $this->objectManager = $this->getObjectManager();
        return new ViewModel( array(
            'allInvestors' => $this->getRepository('Investor')->findAll()
            )
        );
    }

    public function showAction() {
        $this->updateCounts();
        if ($this->params()->fromRoute('investorId', 0) != "") {
            $investorId = (int)$this->params()->fromRoute('investorId', 0);
            $this->objectManager = $this->getObjectManager();
            $investor = $this->getRepository('Investor')->findOneBy(array("investorId" => $investorId));
            if ($investor != null) {
                $builder = new AnnotationBuilder($this->objectManager);
                $form = $builder->createForm($investor);
                $form->setHydrator(new DoctrineHydrator($this->objectManager,'Investor\Entity\Investor'));
                $form->setBindOnValidate(false);
                $form->bind($investor);
                return new ViewModel( array(
                    'investor' => $investor,
                    'form' => $form
                    )
                );
            }
        }
        $this->redirect()->toRoute('home');
    }

    public function editAction() {
        $this->updateCounts();
        if ($this->getRequest()->isPost()) {
            $this->objectManager = $this->getObjectManager();
            $investorId = (int)$this->getRequest()->getPost('investorId');
            $investor = $this->getRepository('Investor')->findOneBy(array("investorId" => $investorId));
            if ($investor != null) {
                $builder = new AnnotationBuilder($this->objectManager);
                $form = $builder->createForm($investor);
                $form->setHydrator(new DoctrineHydrator($this->objectManager,'Investor\Entity\Investor'));
                $form->bind($investor);
                $form->setData($this->getRequest()->getPost());
                if ($form->isValid()) {
                    $this->objectManager->flush();
                    $investorId = $investor->getInvestorId();
                }
                return new ViewModel( array(
                    'investor'      => $investor,
                    'form'          => $form
                    )
                );
            }
        }
        $this->redirect()->toRoute('home');
    }

    public function addAction() {
        $this->updateCounts();
        $this->objectManager = $this->getObjectManager();
        $builder = new AnnotationBuilder($this->objectManager);
        $form = $builder->createForm(new \Investor\Entity\Investor);
        $form->setHydrator(new DoctrineHydrator($this->objectManager,'Investor\Entity\Investor'));
        $investor = new \Investor\Entity\Investor;
        $form->bind($investor);
        $form->setData($this->getRequest()->getPost());
        if ($this->getRequest()->isPost()) {
            $stateId = $this->getRequest()->getPost('stateId');
            if ($form->isValid() && \Investor\Entity\Investor::isUniqueStateId($this->objectManager, $stateId, $form)) {
                $investor->setTimeStamp();
                $this->objectManager->persist($investor);
                $this->objectManager->flush();
                $investorId = $investor->getInvestorId();
                $this->redirect()->toRoute('investors/Investor',
                    array(
                        'action'        => 'show',
                        'investorId'    => $investorId,
                    )
                );
            }
        }
        return new ViewModel( array('form' => $form));
    }
}


text:
interface JQueryAutocompleteOptions {
    serviceUrl?: string;
    lookup?: AutocompleteSuggestion[];
    lookupFilter? (suggestion: AutocompleteSuggestion, query: string, queryLowercase: string): any;
    onSelect? (suggestion: AutocompleteSuggestion): void;
    minChars: number;
    maxHeight: number;
    deferRequestBy?: number;
    width?: number;
    params?: Object;
    formatResult? (suggestion: AutocompleteSuggestion, currentValue: string): string;
    delimiter?: any;
    zIndex?: number;
    type?: string;
    noCache?: boolean;
    onSearchStart? (query: string): void;
    onSearchComplete? (query: string): void;
    tabDisabled?: boolean;
    paramName?: string;
    transformResult? (response: any, originalQuery: string): AutocompleteSuggestion[];
    autoSelectFirst?: boolean;
    appendTo: any;
    dataType: string;
}

interface AutocompleteSuggestion {
    value: string;
    data: any;
}

interface AutocompleteInstance {
    setOptions(options: JQueryAutocompleteOptions): void;
    clear(): void;
    clearCache(): void;
    disable(): void;
    enable(): void;
    hide(): void;
    dispose(): void;
}


text:
package ctu.edu.vn.dlab.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import ctu.edu.vn.dlab.model.Course;
import ctu.edu.vn.dlab.model.Lab;
import ctu.edu.vn.dlab.model.LabNotify;
import ctu.edu.vn.dlab.model.LabResource;
import ctu.edu.vn.dlab.model.RegistrationLab;
import ctu.edu.vn.dlab.model.RegistrationLabStudent;
import ctu.edu.vn.dlab.model.Student;
import ctu.edu.vn.dlab.model.Teacher;
import ctu.edu.vn.dlab.model.User;
import ctu.edu.vn.dlab.service.CourseService;
import ctu.edu.vn.dlab.service.LabNotifyService;
import ctu.edu.vn.dlab.service.LabResourceService;
import ctu.edu.vn.dlab.service.LabService;
import ctu.edu.vn.dlab.service.RegistrationLabService;
import ctu.edu.vn.dlab.service.TeacherService;
import ctu.edu.vn.dlab.service.UserService;

@Controller
@RequestMapping(value = "/student")
public class StudentController {

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private RegistrationLabService registrationLabService;

	@Autowired
	private LabService labService;

	@Autowired
	private CourseService courseService;

	@Autowired
	private TeacherService teacherService;

	@Autowired
	private UserService userService;

	@Autowired
	private LabNotifyService labNotifyService;

	@Autowired
	private LabResourceService labResourceService;

	@RequestMapping(value = "/student-main-page")
	public ModelAndView studentMainPage() {
		try {
			HttpSession httpSession = request.getSession();
			Student student = (Student) httpSession.getAttribute("student");

			if (student != null) {
				List<RegistrationLabStudent> registedList = registrationLabService.findRegistedLabByIdStudent(student.getIdStudent());

				if (registedList != null) {
					request.setAttribute("registedList", registedList);
				}

				return new ModelAndView("pages/student/list_lab");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ModelAndView("redirect:/index");
		}

		return new ModelAndView("redirect:/login");
	}

	@RequestMapping(value = "/list-lab-no-registed")
	public ModelAndView listLabNoRegisted() {
		try {
			HttpSession httpSession = request.getSession();
			Student student = (Student) httpSession.getAttribute("student");
			if (student != null) {
				List<RegistrationLabStudent> noRegistedList = registrationLabService.findNoRegistedLabByIdStudent(student.getIdStudent());
				List<RegistrationLabStudent> noRegistedListWithTotal = new ArrayList<RegistrationLabStudent>();

				if (noRegistedList != null) {
					Long totalRegisted = 0L;
					RegistrationLabStudent reg = null;
					for (RegistrationLabStudent regItem : noRegistedList) {
						totalRegisted = registrationLabService.getTotalByIdLab(Integer.parseInt(regItem.getIdLab()));

						reg = regItem;
						reg.setTotalRegisted(totalRegisted.toString());

						noRegistedListWithTotal.add(reg);
					}
					request.setAttribute("noRegistedList", noRegistedListWithTotal);
				}

				return new ModelAndView("pages/student/register_lab");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ModelAndView("redirect:/index");
		}

		return new ModelAndView("redirect:/login");
	}

	@RequestMapping(value = "/register-lab")
	public ModelAndView registerLab(@RequestParam("idLab") String idLab,
			RedirectAttributes redirectAttributes) throws Exception {

		try {
			HttpSession httpSession = request.getSession();
			Student student = (Student) httpSession.getAttribute("student");

			if (student != null) {
				if (idLab != null && Integer.parseInt(idLab) > 0) {
					Lab lab = labService.findById(Integer.parseInt(idLab));

					RegistrationLab createdReg = null;

					if (lab != null) {
						Long totalRegisted = registrationLabService.getTotalByIdLab(lab.getIdLab());
						RegistrationLab reg = registrationLabService.getByIdStudent(lab.getIdLab(), student.getIdStudent());

						if (reg == null && totalRegisted < lab.getAmount()) {
							reg = new RegistrationLab();
							reg.setIdLab(Integer.parseInt(idLab));
							reg.setIdStudent(student.getIdStudent());

							createdReg = registrationLabService.create(reg);
						} else {
							redirectAttributes.addFlashAttribute("add_reglab_limited", "Lớp thực hành đã đăng ký đủ số lượng");
						}
					}

					if (createdReg != null) {
						redirectAttributes.addFlashAttribute("add_reglab_success", "Đăng ký lớp thực hành thành công");

						_log.info("ctu.edu.vn.dlab.controller.StudentController - "
			        			+ "Info. reg lab added. idRegistrationLab=" + createdReg.getIdRegistrationLab());
					} else {
						redirectAttributes.addFlashAttribute("add_reglab_error", "Có lỗi xảy ra. Xin vui lòng thử lại");

						_log.error("ctu.edu.vn.dlab.controller.StudentController - "
			        			+ "Error. failed to delete reg lab.");
					}
				}

				return new ModelAndView("redirect:/student/list-lab-no-registed");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ModelAndView("redirect:/index");
		}

		return new ModelAndView("redirect:/login");
	}

	@RequestMapping(value = "/un-register-lab")
	public ModelAndView unRegisterLab(@RequestParam("idLab") String idLab,
			RedirectAttributes redirectAttributes) throws Exception {

		HttpSession httpSession = request.getSession();
		Student student = (Student) httpSession.getAttribute("student");
		if (student != null && Integer.parseInt(idLab) > 0) {
			RegistrationLab reg = registrationLabService.getByIdStudent(Integer.parseInt(idLab), student.getIdStudent());

			if (reg != null) {
				RegistrationLab deletedReg = registrationLabService.delete(reg.getIdRegistrationLab());

				if (deletedReg != null) {
					redirectAttributes.addFlashAttribute("delete_reglab_success", "Hủy đăng ký lớp thực hành thành công");

					_log.info("ctu.edu.vn.dlab.controller.StudentController - "
		        			+ "Info. reg lab deleted. idRegistrationLab=" + deletedReg.getIdRegistrationLab());
				} else {
					redirectAttributes.addFlashAttribute("delete_reglab_error", "Có lỗi xảy ra. Xin vui lòng thử lại");

					_log.error("ctu.edu.vn.dlab.controller.StudentController - "
		        			+ "Error. failed to delete reg lab.");
				}

				return new ModelAndView("redirect:/student/student-main-page");
			}
		}

		return new ModelAndView("redirect:/login");
	}

	@RequestMapping(value = "/detail-lab")
	public ModelAndView detailLab(@RequestParam("idLab") String idLab) {
		try {
			HttpSession httpSession = request.getSession();
			Student student = (Student) httpSession.getAttribute("student");

			if (student != null) {
				// for check if student registed in lab
				RegistrationLab reg = registrationLabService.getByIdStudent(Integer.parseInt(idLab), student.getIdStudent());

				if (idLab != null && Integer.parseInt(idLab) != 0 && reg != null) {
					Lab labRequest = labService.findById(Integer.parseInt(idLab));
					request.setAttribute("lab", labRequest);

					if (labRequest != null) {
						// get info for "thong tin chung" collapse
						Course courseRequest = courseService.findById(labRequest.getIdCourse());
						Teacher teacherRequest = teacherService.findById(labRequest.getIdTeacher());
						User userRequest = userService.findById(teacherRequest.getIdUser());

						request.setAttribute("course", courseRequest);
						request.setAttribute("user", userRequest);

						//get info for "thong bao" collapse
						List<LabNotify> labNotifyListRequest = labNotifyService.findAllByIdLab(labRequest.getIdLab());
						if (labNotifyListRequest != null && labNotifyListRequest.size() > 0) {
							request.setAttribute("labNotifyList", labNotifyListRequest);
						}

						//get info for "bai thuc hanh" collapse
						List<LabResource> labResourceListRequest = labResourceService.findAllByIdLab(labRequest.getIdLab());
						if (labResourceListRequest != null && labResourceListRequest.size() > 0) {
							request.setAttribute("labResourceList", labResourceListRequest);
						}
					}
				}

				return new ModelAndView("pages/student/detail_lab");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ModelAndView("redirect:/index");
		}

		return new ModelAndView("redirect:/login");
	}

	@RequestMapping(value = "/load-file-vpn")
	public void loadFileVPN(HttpServletResponse response) {
		try {
			String fileVPN = request.getParameter("fileVPN");

			if (fileVPN != null) {
				File pdfFile = new File(fileVPN);
				String pdfPath = pdfFile.getAbsolutePath();
				String pdfName = pdfPath.substring(pdfPath.lastIndexOf("\\") + 1, pdfPath.length());

				response.setContentType("application/pdf");
				// attachment or inline
				response.addHeader("Content-Disposition", "inline; filename=" + pdfName);
				response.setContentLength((int) pdfFile.length());

				try {
					FileInputStream fis = new FileInputStream(pdfFile);
					ServletOutputStream sos = response.getOutputStream();

					int bytes;
					while ((bytes = fis.read()) != -1) {
						sos.write(bytes);
					}

					sos.flush();
					fis.close();
					sos.close();

				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static final Logger _log = Logger.getLogger(StudentController.class);
}


text:
namespace base {
class ListValue;
}

namespace cryptauth {
class ExternalDeviceInfo;
}

namespace proximity_auth {

class Authenticator;
class BluetoothConnection;
class Connection;
class ClientImpl;
class ReachablePhoneFlow;
struct RemoteStatusUpdate;
class SecureContext;

// Handles messages from the chrome://proximity-auth page.
class ProximityAuthWebUIHandler : public content::WebUIMessageHandler,
                                  public LogBuffer::Observer,
                                  public CryptAuthEnrollmentManager::Observer,
                                  public CryptAuthDeviceManager::Observer,
                                  public ConnectionObserver,
                                  public ClientObserver {
 public:
  // |delegate| is not owned and must outlive this instance.
  explicit ProximityAuthWebUIHandler(ProximityAuthUIDelegate* delegate);
  ~ProximityAuthWebUIHandler() override;

  // content::WebUIMessageHandler:
  void RegisterMessages() override;

 private:
  // LogBuffer::Observer:
  void OnLogMessageAdded(const LogBuffer::LogMessage& log_message) override;
  void OnLogBufferCleared() override;

  // CryptAuthEnrollmentManager::Observer:
  void OnEnrollmentStarted() override;
  void OnEnrollmentFinished(bool success) override;

  // CryptAuthDeviceManager::Observer:
  void OnSyncStarted() override;
  void OnSyncFinished(
      CryptAuthDeviceManager::SyncResult sync_result,
      CryptAuthDeviceManager::DeviceChangeResult device_change_result) override;

  // Message handler callbacks.
  void GetLogMessages(const base::ListValue* args);
  void ClearLogBuffer(const base::ListValue* args);
  void ToggleUnlockKey(const base::ListValue* args);
  void FindEligibleUnlockDevices(const base::ListValue* args);
  void FindReachableDevices(const base::ListValue* args);
  void GetLocalState(const base::ListValue* args);
  void ForceEnrollment(const base::ListValue* args);
  void ForceDeviceSync(const base::ListValue* args);
  void ToggleConnection(const base::ListValue* args);

  // Initializes CryptAuth managers, used for development purposes.
  void InitGCMManager();
  void InitEnrollmentManager();
  void InitDeviceManager();

  // Called when a CryptAuth request fails.
  void OnCryptAuthClientError(const std::string& error_message);

  // Called when the toggleUnlock request succeeds.
  void OnEasyUnlockToggled(const cryptauth::ToggleEasyUnlockResponse& response);

  // Called when the findEligibleUnlockDevices request succeeds.
  void OnFoundEligibleUnlockDevices(
      const cryptauth::FindEligibleUnlockDevicesResponse& response);

  // Callback when |reachable_phone_flow_| completes.
  void OnReachablePhonesFound(
      const std::vector<cryptauth::ExternalDeviceInfo>& reachable_phones);

  // Called when the key agreement of PSK of the remote device completes.
  void OnPSKDerived(const cryptauth::ExternalDeviceInfo& unlock_key,
                    const std::string& persistent_symmetric_key);

  // Callbacks for bluetooth_util::SeekDeviceByAddress().
  void OnSeekedDeviceByAddress();
  void OnSeekedDeviceByAddressError(const std::string& error_message);

  // Callback when |authenticator_| completes authentication.
  void OnAuthenticationResult(Authenticator::Result result,
                              scoped_ptr<SecureContext> secure_context);

  // Creates the client which parses status updates.
  void CreateStatusUpdateClient();

  // Returns the active connection, whether it's owned the |this| instance or
  // |client_|.
  Connection* GetConnection();

  // Converts an ExternalDeviceInfo proto to a JSON dictionary used in
  // JavaScript.
  scoped_ptr<base::DictionaryValue> ExternalDeviceInfoToDictionary(
      const cryptauth::ExternalDeviceInfo& device_info);

  // Converts an IneligibleDevice proto to a JSON dictionary used in JavaScript.
  scoped_ptr<base::DictionaryValue> IneligibleDeviceToDictionary(
      const cryptauth::IneligibleDevice& ineligible_device);

  // ConnectionObserver:
  void OnConnectionStatusChanged(Connection* connection,
                                 Connection::Status old_status,
                                 Connection::Status new_status) override;
  void OnMessageReceived(const Connection& connection,
                         const WireMessage& message) override;

  // ClientObserver:
  void OnRemoteStatusUpdate(const RemoteStatusUpdate& status_update) override;

  // Returns the current enrollment state that can be used as a JSON object.
  scoped_ptr<base::DictionaryValue> GetEnrollmentStateDictionary();

  // Returns the current device sync state that can be used as a JSON object.
  scoped_ptr<base::DictionaryValue> GetDeviceSyncStateDictionary();

  // Returns the current unlock keys that can be used as a JSON object.
  scoped_ptr<base::ListValue> GetUnlockKeysList();

  // The delegate used to fetch dependencies. Must outlive this instance.
  ProximityAuthUIDelegate* delegate_;

  // Creates CryptAuth client instances to make API calls.
  scoped_ptr<CryptAuthClientFactory> cryptauth_client_factory_;

  // We only support one concurrent API call.
  scoped_ptr<CryptAuthClient> cryptauth_client_;

  // The flow for getting a list of reachable phones.
  scoped_ptr<ReachablePhoneFlow> reachable_phone_flow_;

  // True if the WebContents backing the WebUI has been initialized.
  bool web_contents_initialized_;

  // Member variables related to CryptAuth debugging.
  // TODO(tengs): These members are temporarily used for development.
  scoped_ptr<PrefService> pref_service;
  scoped_ptr<CryptAuthGCMManager> gcm_manager_;
  scoped_ptr<CryptAuthEnrollmentManager> enrollment_manager_;
  scoped_ptr<CryptAuthDeviceManager> device_manager_;
  std::string user_public_key_;
  std::string user_private_key_;

  // Member variables for connecting to and authenticating the remote device.
  // TODO(tengs): Support multiple simultaenous connections.
  scoped_ptr<SecureMessageDelegate> secure_message_delegate_;
  scoped_ptr<BluetoothConnection> bluetooth_connection_;
  scoped_ptr<Authenticator> authenticator_;
  scoped_ptr<SecureContext> secure_context_;
  scoped_ptr<ClientImpl> client_;
  scoped_ptr<RemoteStatusUpdate> last_remote_status_update_;

  base::WeakPtrFactory<ProximityAuthWebUIHandler> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(ProximityAuthWebUIHandler);
};

}  // namespace proximity_auth

#endif  // COMPONENTS_PROXIMITY_AUTH_WEBUI_PROXIMITY_AUTH_WEBUI_HANDLER_H_


text:
package com.netflix.zeno.fastblob.restorescenarios;

public class TypeAState2 {

    private final int a1;
    private final TypeC c;

    public TypeAState2(int a1, TypeC c) {
        this.a1 = a1;
        this.c = c;
    }

    public int getA1() {
        return a1;
    }

    public TypeC getC() {
        return c;
    }
}


text:
---
uid: SolidEdgePart.ComponentSketches.Add
summary:
remarks:
---


text:
package com.xinyuan.pub.model.business.po;

import com.xinyuan.pub.model.po.BusinessBasePo;

/**
 * @Description: 省份信息 实体类
 * @author liangyongjian
 * @Version V1.0
 * @date 2017-09-29 下午07:24:37
 */
public class Province extends BusinessBasePo {

	private String province; // 省份名称
	private String namePinyin; // 省份名称的拼音全拼
	private Long createUserId; // 创建者的用户ID
	private Long updateUserId; // 修改者的用户ID
	private String note;// 备注

	// 扩展属性,页面使用
	private String createUserName; // 创建者的用户名称
	private String updateUserName; // 修改者的用户名称

	public String getProvince() {
		return province;
	}

	public String getNamePinyin() {
		return namePinyin;
	}

	public Long getCreateUserId() {
		return createUserId;
	}

	public Long getUpdateUserId() {
		return updateUserId;
	}

	public String getNote() {
		return note;
	}

	public String getCreateUserName() {
		return createUserName;
	}

	public String getUpdateUserName() {
		return updateUserName;
	}

	public void trim() {
		if (this.province != null)
			this.province = this.province.trim();

		if (this.note != null)
			this.note = this.note.trim();
	}

	public void setProvince(String province) {
		this.province = province;
	}

	public void setNamePinyin(String namePinyin) {
		this.namePinyin = namePinyin;
	}

	public void setCreateUserId(Long createUserId) {
		this.createUserId = createUserId;
	}

	public void setUpdateUserId(Long updateUserId) {
		this.updateUserId = updateUserId;
	}

	public void setNote(String note) {
		this.note = note;
	}

	public void setCreateUserName(String createUserName) {
		this.createUserName = createUserName;
	}

	public void setUpdateUserName(String updateUserName) {
		this.updateUserName = updateUserName;
	}

	public String toString() {
		return "province: " + province + ",note: " + note;
	}

}


text:
package com.palantir.atlasdb.jepsen;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyList;

import com.google.common.collect.ImmutableList;
import com.palantir.atlasdb.jepsen.events.Checker;
import com.palantir.atlasdb.jepsen.events.Event;
import com.palantir.atlasdb.jepsen.events.InfoEvent;
import com.palantir.atlasdb.jepsen.events.InvokeEvent;
import com.palantir.atlasdb.jepsen.events.OkEvent;
import com.palantir.atlasdb.jepsen.events.RequestType;
import com.palantir.atlasdb.jepsen.utils.CheckerTestUtils;
import com.palantir.atlasdb.jepsen.utils.TestEventUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import org.junit.Test;
import org.mockito.Mockito;

public class PartitionByInvokeNameCheckerHelperTest {

    private static final int PROCESS_1 = 1;
    private static final int PROCESS_2 = 2;
    private static final int PROCESS_3 = 3;
    private static final String LOCK_1 = "lock1";
    private static final String LOCK_2 = "lock2";

    private static final List<Event> eventList = ImmutableList.<Event>builder()
            .add(TestEventUtils.invokeLock(0, PROCESS_1, LOCK_1))
            .add(TestEventUtils.invokeRefresh(1, PROCESS_2, LOCK_1))
            .add(TestEventUtils.lockSuccess(2, PROCESS_1))
            .add(TestEventUtils.invokeUnlock(3, PROCESS_1, LOCK_2))
            .add(TestEventUtils.createInfoEvent(3, PROCESS_3, RequestType.LOCK))
            .add(TestEventUtils.unlockSuccess(4, PROCESS_1))
            .add(TestEventUtils.refreshFailure(5, PROCESS_2))
            .add(TestEventUtils.invokeLock(6, PROCESS_2, LOCK_2))
            .add(TestEventUtils.lockSuccess(7, PROCESS_2))
            .build();

    private static final List<Event> onlyLock2EventList = ImmutableList.<Event>builder()
            .add(TestEventUtils.invokeUnlock(3, PROCESS_1, LOCK_2))
            .add(TestEventUtils.unlockSuccess(4, PROCESS_1))
            .add(TestEventUtils.invokeLock(6, PROCESS_2, LOCK_2))
            .add(TestEventUtils.lockSuccess(7, PROCESS_2))
            .build();

    private static final CheckerResult validResult = ImmutableCheckerResult.builder()
            .valid(true)
            .errors(new ArrayList<>())
            .build();

    /**
     * This checker always fails, returning the entire list of events as the error list. This is useful to verify how
     * PartitionByInvokeNameCheckerHelper manipulates the list. The value of the valid parameter is set to false purely
     * for consistency reasons (since the list of errors is not empty).
     */
    private static final Checker identityChecker = Mockito.mock(Checker.class);

    static {
        Mockito.when(identityChecker.check(anyList())).then(list -> ImmutableCheckerResult.builder()
                .valid(false)
                .errors(list.getArgument(0))
                .build());
    }

    @Test
    public void universalSuccessCheckerShouldSucceedOnNoEvents() {
        Checker universalChecker = Mockito.mock(Checker.class);
        Mockito.when(universalChecker.check(anyList())).thenReturn(validResult);

        assertNoError(() -> universalChecker, ImmutableList.of());
    }

    @Test
    public void universalSuccessCheckerShouldSucceed() {
        Checker universalChecker = Mockito.mock(Checker.class);
        Mockito.when(universalChecker.check(anyList())).thenReturn(validResult);

        assertNoError(() -> universalChecker, eventList);
    }

    @Test
    public void infoEventsAreNotLost() {
        InfoEvent infoEvent = TestEventUtils.createInfoEvent(0, PROCESS_1, RequestType.LOCK);

        CheckerResult checkerResult = runPartitionChecker(() -> identityChecker, ImmutableList.<Event>of(infoEvent));

        assertThat(checkerResult.valid()).isFalse();
        assertThat(checkerResult.errors()).containsExactly(infoEvent);
    }

    @Test
    public void universalFailureCheckerShouldFail() {
        InvokeEvent invokeEvent = TestEventUtils.invokeLock(0, PROCESS_1, LOCK_1);
        OkEvent okEvent = TestEventUtils.lockSuccess(1, PROCESS_1);

        CheckerResult checkerResult =
                runPartitionChecker(() -> identityChecker, ImmutableList.of(invokeEvent, okEvent));

        assertThat(checkerResult.valid()).isFalse();
        assertThat(checkerResult.errors()).containsExactly(invokeEvent, okEvent);
    }

    @Test
    public void partitioningOnlyReordersEvents() {
        CheckerResult checkerResult = runPartitionChecker(() -> identityChecker, eventList);

        assertThat(checkerResult.valid()).isFalse();
        assertThat(checkerResult.errors()).hasSameSizeAs(eventList);
        assertThat(checkerResult.errors()).containsOnlyElementsOf(eventList);
    }

    @Test
    public void partitionsRetainRelativeOrdering() {
        CheckerResult checkerResult = runPartitionChecker(() -> filterChecker(LOCK_2), eventList);

        assertThat(checkerResult.valid()).isFalse();
        assertThat(checkerResult.errors()).containsExactlyElementsOf(onlyLock2EventList);
    }

    @Test
    public void infoEventsAreLockIndependent() {
        InvokeEvent invokeEvent = TestEventUtils.invokeLock(0, PROCESS_1, LOCK_1);
        OkEvent okEvent = TestEventUtils.lockSuccess(1, PROCESS_1);

        List<Event> infoEventList = ImmutableList.<Event>builder()
                .add(TestEventUtils.createInfoEvent(0, PROCESS_1, RequestType.LOCK))
                .add(invokeEvent)
                .add(okEvent)
                .add(TestEventUtils.createInfoEvent(2, PROCESS_1, RequestType.LOCK))
                .build();

        CheckerResult checkerResult = runPartitionChecker(() -> filterChecker(LOCK_1), infoEventList);

        assertThat(checkerResult.valid()).isFalse();
        assertThat(checkerResult.errors()).containsExactlyElementsOf(ImmutableList.of(invokeEvent, okEvent));
    }

    /**
     * This method generates a mocked Checker that returns the entire list of Events if and only if all Events in the
     * list are related to the specified lock name, and there is at least one InvokeEvent.
     * @param lockName The lock name to filter for
     * @return mocked Checker
     */
    private Checker filterChecker(String lockName) {
        Checker mockChecker = Mockito.mock(Checker.class);
        Mockito.when(mockChecker.check(anyList())).then(args -> {
            List<Event> events = args.getArgument(0);
            return checkLockName(lockName, events);
        });
        return mockChecker;
    }

    private CheckerResult checkLockName(String lockName, List<Event> events) {
        boolean noOtherLock = true;
        boolean atLeastOneInvoke = false;
        for (Event event : events) {
            if (event instanceof InvokeEvent) {
                atLeastOneInvoke = true;
                InvokeEvent invokeEvent = (InvokeEvent) event;
                if (!invokeEvent.value().equals(lockName)) {
                    noOtherLock = false;
                }
            }
        }
        if (noOtherLock && atLeastOneInvoke) {
            return ImmutableCheckerResult.builder().valid(false).errors(events).build();
        } else {
            return ImmutableCheckerResult.builder()
                    .valid(true)
                    .errors(new ArrayList<>())
                    .build();
        }
    }

    private static CheckerResult runPartitionChecker(Supplier<Checker> checker, List<Event> events) {
        PartitionByInvokeNameCheckerHelper partitionByInvokeNameCheckerHelper =
                new PartitionByInvokeNameCheckerHelper(checker);
        return partitionByInvokeNameCheckerHelper.check(events);
    }

    private static void assertNoError(Supplier<Checker> checker, List<Event> events) {
        CheckerTestUtils.assertNoErrors(() -> new PartitionByInvokeNameCheckerHelper(checker), events);
    }
}


text:
package com.tamargo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Introduce un valor para saber su valor absoluto o 0 para finalizar el programa.");

        int a;

        do {
            System.out.print("Valor: ");
            String valor = br.readLine();
            a = Integer.parseInt(valor);

            if (a < 0) {
                a = a * -1;
                System.out.println("Valor absoluto: "+a);
            } else {
                if (a > 0) {
                    System.out.println("Valor absoluto: "+a);
                } else  {    }
            }

        }   while (a != 0) ;
    }
}


text:
/**
 *
 */
package org.minnal.security.filter;

import java.io.IOException;
import java.util.Map;

import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.message.internal.OutboundMessageContext;
import org.minnal.security.auth.JaxrsWebContext;
import org.minnal.security.auth.User;
import org.minnal.security.config.SecurityConfiguration;
import org.minnal.security.session.Session;
import org.minnal.utils.reflection.Generics;
import org.minnal.utils.serializer.Serializer;
import org.pac4j.core.client.Client;
import org.pac4j.core.client.Clients;
import org.pac4j.core.exception.RequiresHttpAction;
import org.pac4j.core.exception.TechnicalException;
import org.pac4j.core.profile.UserProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Strings;

/**
 * @author ganeshs
 *
 */
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter {

	private Clients clients;

	public static final String PRINCIPAL = "principal";

	protected AuthenticationListener listener;

	private static final Logger logger = LoggerFactory.getLogger(AuthenticationFilter.class);

	/**
	 * @param clients
	 * @param configuration
	 */
	public AuthenticationFilter(Clients clients, SecurityConfiguration configuration) {
		super(configuration);
		this.clients = clients;
	}

	/**
	 * @return the clients
	 */
	public Clients getClients() {
		return clients;
	}

	@Override
	public void filter(ContainerRequestContext request) {
	    Session session = getSession(request, true);
        request.setProperty(SESSION, session);

		if (isWhiteListed(request)) {
		    logger.debug("Request path {} is in whitelisted set of urls. Skipping authentication", request.getUriInfo());
			return;
		}
		if (isAuthenticated(session)) {
		    logger.debug("Session is already authenticated. Skipping authentication");
			return;
		}

		JaxrsWebContext context = getContext(request, session);
		Client client = getClient(context);

		if (client != null) {
			session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName());
			getConfiguration().getSessionStore().save(session);

			try {
				client.redirect(context, false, false);
			} catch (RequiresHttpAction e) {
				logger.error("Failed while redirecting the request", e);
				context.setResponseStatus(e.getCode());
			}
		} else {
			context.setResponseStatus(Response.Status.UNAUTHORIZED.getStatusCode());
		}
		context.setResponseHeader(HttpHeaders.SET_COOKIE, createSessionCookie(session).toString());
		request.abortWith(context.getResponse());
	}

	@Override
	public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException {
	    Session session = getSession(request, true);
	    response.getHeaders().add(HttpHeaders.SET_COOKIE, createSessionCookie(session).toString());
	}

	/**
	 * Creates a session cookie
	 *
	 * @param session
	 * @return
	 */
	private NewCookie createSessionCookie(Session session) {
	    return new NewCookie(AUTH_COOKIE, session.getId(), "/", null, null, NewCookie.DEFAULT_MAX_AGE, false);
	}

	/**
	 * Checks if the session is already authenticated
	 *
	 * @param session
	 * @return
	 */
	protected boolean isAuthenticated(Session session) {
		return retrieveProfile(session) != null;
	}

	protected JaxrsWebContext getContext(ContainerRequestContext request, Session session) {
		return new JaxrsWebContext(request, new OutboundMessageContext(), session);
	}

	protected boolean isWhiteListed(ContainerRequestContext request) {
		for (String url : getConfiguration().getWhiteListedUrls()) {
			if (request.getUriInfo().getPath().startsWith(url)) {
				return true;
			}
		}
		return false;
	}

	@SuppressWarnings("rawtypes")
	protected User retrieveProfile(Session session) {
		Object profile = session.getAttribute(PRINCIPAL);
		if (profile == null) {
			return null;
		}
		Client client = getClient(session);
		Class<UserProfile> type = Generics.getTypeParameter(client.getClass(), UserProfile.class);
		if (type.isAssignableFrom(profile.getClass())) {
			return new User((UserProfile) profile);
		}
		if (profile instanceof Map) {
			String buffer = Serializer.DEFAULT_JSON_SERIALIZER.serialize(profile);
			profile = Serializer.DEFAULT_JSON_SERIALIZER.deserialize(buffer, type);
			User user = new User((UserProfile) profile);
			session.addAttribute(PRINCIPAL, profile);
			return user;
		}
		// Can't come here
		return null;
	}

    protected Client getClient(Session session) {
        String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER);
        if (Strings.isNullOrEmpty(clientName)) {
            return null;
        }
        return clients.findClient(clientName);
    }

	protected Client getClient(JaxrsWebContext context) {
	    try {
	        return clients.findClient(context);
	    } catch (TechnicalException e) {
	        logger.debug("Error while getting the client from the context", e);
	        return null;
	    }
	}

	/**
	 * Registers the authentication listener
	 *
	 * @param listener
	 */
	public void registerListener(AuthenticationListener listener) {
	    this.listener = listener;
	}
}


text:
package org.springframework.boot.autoconfigure.security.oauth2.client;

import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2SsoDefaultConfiguration.NeedsWebSecurityCondition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Configuration for OAuth2 Single Sign On (SSO). If the user only has
 * {@code @EnableOAuth2Sso} but not on a {@code WebSecurityConfigurerAdapter} then one is
 * added with all paths secured.
 *
 * @author Dave Syer
 * @since 1.3.0
 */
@Configuration
@Conditional(NeedsWebSecurityCondition.class)
public class OAuth2SsoDefaultConfiguration extends WebSecurityConfigurerAdapter {

	private final ApplicationContext applicationContext;

	public OAuth2SsoDefaultConfiguration(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.antMatcher("/**").authorizeRequests().anyRequest().authenticated();
		new SsoSecurityConfigurer(this.applicationContext).configure(http);
	}

	protected static class NeedsWebSecurityCondition extends EnableOAuth2SsoCondition {

		@Override
		public ConditionOutcome getMatchOutcome(ConditionContext context,
				AnnotatedTypeMetadata metadata) {
			return ConditionOutcome.inverse(super.getMatchOutcome(context, metadata));
		}

	}

}


text:
package oci8

import (
	"context"
	"testing"
)

// TestStatementCaching tests to ensure statement caching is working
func TestStatementCaching(t *testing.T) {
	if TestDisableDatabase {
		t.SkipNow()
	}

	t.Parallel()

	var err error

	db := testGetDB("?stmt_cache_size=10")
	if db == nil {
		t.Fatal("db is null")
	}

	defer func() {
		err = db.Close()
		if err != nil {
			t.Fatal("db close error:", err)
		}
	}()

	ctx, cancel := context.WithTimeout(context.Background(), TestContextTimeout)
	conn, err := db.Conn(ctx)
	cancel()
	// we need to get access to the raw connection so we can access the different fields on the oci8.Stmt
	var rawConn *Conn
	// NOTE that conn.Raw() is only available with Go >= 1.13
	_ = conn.Raw(func(driverConn interface{}) error {
		rawConn = driverConn.(*Conn)
		return nil
	})

	ctx, cancel = context.WithTimeout(context.Background(), TestContextTimeout)
	stmt, err := rawConn.PrepareContext(ctx, "select ?, ?, ? from dual")
	cancel()
	if err != nil {
		t.Fatal("prepare error:", err)
	}

	rawStmt := stmt.(*Stmt)
	if rawStmt.cacheKey != "select ?, ?, ? from dual" {
		err := stmt.Close()
		if err != nil {
			t.Fatal("stmt close error:", err)
		}
		t.Fatalf("cacheKey not equal: expected %s, but got %s", "select ?, ?, ? from dual", rawStmt.cacheKey)
	}

	// closing the statement should put the statement into the cache
	err = stmt.Close()
	if err != nil {
		t.Fatal("stmt close error:", err)
	}

	ctx, cancel = context.WithTimeout(context.Background(), TestContextTimeout)
	stmt, err = rawConn.PrepareContext(ctx, "select ?, ?, ? from dual")
	cancel()
	if err != nil {
		t.Fatal("prepare error:", err)
	}

	rawStmt = stmt.(*Stmt)
	if rawStmt.cacheKey != "select ?, ?, ? from dual" {
		err := stmt.Close()
		if err != nil {
			t.Fatal("stmt close error:", err)
		}
		t.Fatalf("cacheKey not equal: expected %s, but got %s", "select ?, ?, ? from dual", rawStmt.cacheKey)
	}
	err = stmt.Close()
	if err != nil {
		t.Fatal("stmt close error:", err)
	}
}


text:
<component name="libraryTable">
  <library name="SBT: org.asynchttpclient:async-http-client:2.0.11:jar">
    <CLASSES>
      <root url="jar://$USER_HOME$/.ivy2/cache/org.asynchttpclient/async-http-client/jars/async-http-client-2.0.11.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$USER_HOME$/.ivy2/cache/org.asynchttpclient/async-http-client/srcs/async-http-client-2.0.11-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
package org.apache.camel.component.atom;

import java.util.List;

import org.apache.abdera.model.Entry;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

@DisabledOnOs(OS.AIX)
public class AtomRouteTest extends CamelTestSupport {
    private static final Logger LOG = LoggerFactory.getLogger(AtomRouteTest.class);

    @Test
    void testFeedGetsUpdatedEvents() throws Exception {
        MockEndpoint endpoint = getMockEndpoint("mock:results");
        endpoint.expectedMessageCount(7);

        MockEndpoint.assertIsSatisfied(context);

        List<Exchange> list = endpoint.getReceivedExchanges();
        String[] expectedTitles = {
                "Speaking at the Irish Java Technology Conference on Thursday and Friday",
                "a great presentation on REST, JAX-WS and JSR 311",
                "my slides on ActiveMQ and Camel from last weeks Dublin Conference",
                "webcast today on Apache ActiveMQ",
                "Feedback on my Camel talk at the IJTC conference",
                "More thoughts on RESTful Message Queues",
                "ActiveMQ webinar archive available" };
        int counter = 0;
        for (Exchange exchange : list) {
            Entry entry = exchange.getIn().getBody(Entry.class);
            assertNotNull(entry, "No entry found for exchange: " + exchange);

            String expectedTitle = expectedTitles[counter];
            String title = entry.getTitle();
            assertEquals(expectedTitle, title, "Title of message " + counter);

            LOG.debug("<<<< {}", entry);

            counter++;
        }
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            public void configure() {
                from("atom:file:src/test/data/feed.atom?delay=500").to("mock:results");
            }
        };
    }
}


text:
<?php

namespace Nanbando\Backup;

interface BackupArchiveInterface
{
    const BACKUP_MODE_FULL = 'full';
    const BACKUP_MODE_DIFFERENTIAL = 'differential';

    public function storeFile(string $name, string $path, ?array $metadata = null): void;

    public function storeMetadata(string $name, array $metadata): void;

    public function getFiles(): array;

    public function set(string $name, $value): void;

    public function get(string $name);

    public function getWithDefault(string $name, $default);

    public function all(): array;
}


text:
<!doctype html>

<meta charset="utf-8">
<title>Breakpoint, podcast francophone pour dev iOS – </title>
<meta name="description" content="Describe this nonsense.">
<meta name="keywords" content="Jekyll, theme, themes, responsive, blog, modern">

<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="Breakpoint, podcast francophone pour dev iOS">
<meta property="og:description" content="Describe this nonsense.">
<meta property="og:url" content="http://www.breakpoint.fm/index.html">
<meta property="og:site_name" content="">

<link rel="canonical" href="http://www.breakpoint.fm/">
<link href="http://www.breakpoint.fm/feed.xml" type="application/atom+xml" rel="alternate" title=" Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="http://www.breakpoint.fm/assets/css/main.min.css">

<link href="http://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic" rel="stylesheet" type="text/css">

<meta http-equiv="cleartype" content="on">

<link rel="shortcut icon" href="http://www.breakpoint.fm/favicon.ico">

<link rel="shortcut icon" href="http://www.breakpoint.fm/favicon.png">

<link rel="apple-touch-icon-precomposed" href="http://www.breakpoint.fm/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://www.breakpoint.fm/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://www.breakpoint.fm/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://www.breakpoint.fm/images/apple-touch-icon-144x144-precomposed.png">

<link rel="stylesheet" href="http://www.breakpoint.fm/assets/mep/mediaelementplayer.css" />

  <button class="dl-trigger">Open Menu</button>

Accueil

On lit, on écoute

        Un avis ?

Breakpoint, podcast francophone pour dev iOS

        <time datetime="2014-07-16T11:09:09+02:00">
          July 16, 2014
        </time>

            Peter

      Épisode 19

Dans cet épisode, Jeffrey et Peter parcourent l'actualité et closent la saison 1 de Breakpoint.

<audio src="https://s3-eu-west-1.amazonaws.com/breakpointfm/episodes/19/19.m4a"></audio>

Liens

Developer uses brainwaves to control Google Glass : fucking cool

Apple se met à bloguer.

Vers une classification des apps selon leur accessibilité

Le swift évolue: Apple Changelog & Swift In Flux

        <time datetime="2014-07-08T10:08:08+02:00">
          July 08, 2014
        </time>

            Peter

      Épisode 18

Dans cet épisode, Jeffrey et Peter parcourent l'actualité post-Google IO et bebrieffent sur ce que Google a annoncé.

<audio src="https://s3-eu-west-1.amazonaws.com/breakpointfm/episodes/18/ep18.m4a"></audio>

Liens

Émulateurs de smartphones "as a service" ?

Un simple "return NO;" peut causer un crash via d'ARC

Touch ID and 1Password

        <time datetime="2014-06-25T10:09:10+02:00">
          June 25, 2014
        </time>

            Peter

      Épisode 17

Dans cet épisode, Jeffrey et Peter parcourent l'actualité post-WWDC et se permettent une petite analyse de la Google I/O 2014.

<audio src="https://s3-eu-west-1.amazonaws.com/breakpointfm/episodes/17/ep17.m4a"></audio>

Liens

Swift Is Not Functional

Only Apple Can Do It

Clang et le C++

AppleTV en tant que HomeKit Hub ?

La Google I/O 2014

        <time datetime="2014-06-15T19:42:42+02:00">
          June 15, 2014
        </time>

            Peter

      Épisode 16

Dans cet épisode, Jeffrey et Peter reviennent sur les nouveautés d'iOS8 qui réprésentent des opportunités autant techniques que commerciales (ouh le vilain mot !)

<audio src="https://s3-eu-west-1.amazonaws.com/breakpointfm/episodes/16/ep16.m4a"></audio>

        <time datetime="2014-06-10T19:42:42+02:00">
          June 10, 2014
        </time>

            Peter

      Épisode 15

Dans cet épisode, Jeffrey et Peter discutent de la WWDC en tant que lettre d'amour d'Apple envers les devs

<audio src="https://s3-eu-west-1.amazonaws.com/breakpointfm/episodes/15/ep15.m4a"></audio>

    Previous

        1

          2

          3

          4

    Next

    © 2014 . Motorisé par Jekyll, thème original par HPSTR Theme.


text:
var Promise = require('es6-promise').Promise;

var TaskRunner = function() {

    this.execute = function(taskList) {
        var promise = new Promise(function(resolve) {
            taskList.reduce(function(sequence, task) {
                return sequence.then(function() {
                    return task.execute();
                });
            }, Promise.resolve()).then(function() {
                resolve('finished tasklist');
            });
        });

        return promise;
    };

    this.shutdown = function(taskList) {
        for (var i = 0; i < taskList.length; i++) {
            if (typeof taskList[i].shutdown === 'function') {
                taskList[i].shutdown();
            }
        }
    };
};

module.exports = TaskRunner;


text:
import webapp2

import templating
import secure_hash
from entities import User, Post

class BlogHandler(webapp2.RequestHandler):
    def write(self, *a, **kw):
        self.response.out.write(*a, **kw)

    def render_str(self, template, **params):
        params['user'] = self.user
        return templating.render_template(template, **params)

    def render(self, template, **kw):
        self.write(self.render_str(template, **kw))

    def set_secure_cookie(self, name, val):
        cookie_val = secure_hash.generate_hash(val)
        self.response.headers.add_header(
            'Set-Cookie',
            '%s=%s; Path=/' % (name, cookie_val)
        )

    def read_secure_cookie(self, name):
        cookie_val = self.request.cookies.get(name)
        return cookie_val and secure_hash.validate_hash(cookie_val)

    def login_user(self, user_id):
        self.set_secure_cookie('user_id', str(user_id))

    def logout_user(self):
        self.response.headers.add_header('Set-Cookie', 'user_id=; Path=/')

    def initialize(self, *a, **kw):
        webapp2.RequestHandler.initialize(self, *a, **kw)

        user_id = self.read_secure_cookie('user_id')
        self.user = user_id and User.by_id(int(user_id))

class BlogFront(BlogHandler):
    def get(self):
        post_result = Post.by_page()
        self.render(
            'front.htm.j2',
            posts=post_result[0],
            post_cursor=post_result[1],
            more_posts=post_result[2]
        )

class BlogError(BlogHandler):
    def get(self):
        errorKey = self.request.get('error')

        errors = {
            'noPermission': "You don't have permission to do that"
        }

        if errorKey in errors:
            self.render(
                'error.htm.j2',
                error=errors[errorKey]
            )
        else:
            self.redirect('/')


text:
import hashlib

from flask import (render_template, g, session,
                   jsonify, request,redirect)

from web.app import app
from web.model import (User, UserInfo,UserSetting,BasicUser,
                        AdvancedUser,FeedSite, Feed, Sub)

@app.route("/api/feed/<feedid>/read",methods=["POST"])
def read_feed(feedid):
    feed = Feed.get_feed_by_id(feedid)
    g.user.read_feed(feed)
    return jsonify(rcode=200)

@app.route("/api/feed/<feedid>/unread",methods=["POST"])
def unread_feed(feedid):
    feed = Feed.get_feed_by_id(feedid)
    g.user.unread_feed(feed)
    return jsonify(rcode=200)

@app.route("/api/feed/<feedid>/star",methods=["POST"])
def star_feed(feedid):
    feed = Feed.get_feed_by_id(feedid)
    g.user.star_feed(feed)
    return jsonify(rcode=200)

@app.route("/api/feed/<feedid>/unstar",methods=["POST"])
def unstar_feed(feedid):
    feed = Feed.get_feed_by_id(feedid)
    g.user.unstar_feed(feed)
    return jsonify(rcode=200)


text:
Public Class Convenio

    Public Property IdConvenio As Int32
    Public Property Codigo As String
    Public Property Nombre As String
    Public Property FecIni As Date
    Public Property FecFin As Date
    Public Property IdMoneda As Int32
    Public Property MontoInicial As String
    Public Property IdTipConv As Int32
    Public Property FaseCont As String
    Public Property Estado As String
    Public Property Ejecutado As Decimal
    Public Property FechaFirma As Date
    Public Property MontoTotal As Decimal
    Public Property Comprometido As Decimal
    Public Property Presupuestado As Decimal
    Public Property IdConveMarco As Int32
    Public Property _ConveMarco As ConveMarco
    Public Property _TipoConvenio As TipoConvenio
    Public Property _Moneda As Moneda

    Public ReadOnly Property NombreconvenioMarco As String
        Get
            Return _ConveMarco.Nombre
        End Get
    End Property

    Public ReadOnly Property NombreTipoConvenio As String
        Get
            Return _TipoConvenio.Nombre
        End Get
    End Property

    Public ReadOnly Property NombreMoneda As String
        Get
            Return _Moneda.Nombre
        End Get
    End Property

End Class


text:
@implementation TTPushAnimator

#pragma mark - UIViewControllerAnimatedTransitioning

- (NSTimeInterval)transitionDuration:(id <UIViewControllerContextTransitioning>)transitionContext
{
	return kTransitionDuration;
}

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext
{
	UIViewController* toController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
	UIViewController* fromController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
	UIView* container = [transitionContext containerView];

	//get rects that represent the top and bottom halves of the screen
	CGSize viewSize = fromController.view.bounds.size;
	CGRect topFrame = CGRectMake(0, 0, viewSize.width, viewSize.height/2);
	CGRect bottomFrame = CGRectMake(0, viewSize.height/2, viewSize.width, viewSize.height/2);

	//create snapshots
	UIView* snapshotTop = [fromController.view resizableSnapshotViewFromRect:topFrame afterScreenUpdates:NO withCapInsets:UIEdgeInsetsZero];
	UIView* snapshotBottom = [fromController.view resizableSnapshotViewFromRect:bottomFrame afterScreenUpdates:NO withCapInsets:UIEdgeInsetsZero];
	snapshotTop.frame = topFrame;
	snapshotBottom.frame = bottomFrame;

	//remove the original view from the container
	fromController.view.hidden = YES;

	//add our destination view
	[container addSubview:toController.view];

	//add our snapshots on top
	[container addSubview:snapshotTop];
	[container addSubview:snapshotBottom];

	[UIView animateKeyframesWithDuration:kTransitionDuration delay:0 options:UIViewKeyframeAnimationOptionCalculationModeLinear animations:^{

		//adjust the new frames
		CGRect newTopFrame = topFrame;
		CGRect newBottomFrame = bottomFrame;
		newTopFrame.origin.y -= topFrame.size.height;
		newBottomFrame.origin.y += bottomFrame.size.height;

		//animate the top first
		[UIView addKeyframeWithRelativeStartTime:0 relativeDuration:0.5 animations:^{
			snapshotTop.frame = newTopFrame;
		}];

		//animate the bottom second
		[UIView addKeyframeWithRelativeStartTime:0.5 relativeDuration:0.5 animations:^{
			snapshotBottom.frame = newBottomFrame;
		}];

	} completion:^(BOOL finished) {

		//don't forget to clean up
		[snapshotTop removeFromSuperview];
		[snapshotBottom removeFromSuperview];
		fromController.view.hidden = NO;

		//put the original stuff back in place if the user cancelled
		if(transitionContext.transitionWasCancelled)
		{
			[toController.view removeFromSuperview];
			[container addSubview:fromController.view];
		}

		[transitionContext completeTransition:!transitionContext.transitionWasCancelled];

	}];
}

@end


text:
"""Module with class that handle performance test results and compute statistic."""
import csv

class PerfTests:
    """Class that handle performance test results."""

    INPUT_FILES = {
        "component analysis": {
            "sequenced_calls_known_component":
                "component_analysis_sequenced_calls_known_component.csv",
            "sequenced_calls_unknown_component":
                "component_analysis_sequenced_calls_unknown_component.csv",
            "parallel_calls_known_component":
                "component_analysis_parallel_calls_known_component.csv",
            "parallel_calls_unknown_component":
                "component_analysis_parallel_calls_unknown_component.csv",
        },
        "stack analysis": {
            "sequenced_calls": "stack_analysis_sequenced_calls.csv",
            "parallel_calls": "stack_analysis_parallel_calls.csv"
        }
    }

    @staticmethod
    def read_csv(filename, skip_first_line=False):
        """Read the given CSV file, parse it, and return as list of records."""
        output = []
        with open(filename, 'r') as fin:
            csv_content = csv.reader(fin, delimiter=',')
            if skip_first_line:
                csv_content.next()
            for row in csv_content:
                output.append(row)
        return output

    def __init__(self):
        """Construct an instance of the class."""
        self._results = {}
        self._statistic = {}

    def read_analysis_results(self, input_files):
        """Read the performence test results from the selected bundle of CSV files.

        Typically the bundle would be 'stack analysis' or 'component analysis').
        """
        results = {}
        for name, filename in input_files.items():
            results[name] = PerfTests.read_csv(filename)
        return results

    def read_results(self):
        """Read results generated by all performance tests."""
        for analyse_type, input_files in PerfTests.INPUT_FILES.items():
            self._results[analyse_type] = self.read_analysis_results(input_files)

    @staticmethod
    def compute_stat_for_result_set(results):
        """Compute the statistic for selected result set (that is - for 2D matrix of floats)."""
        # let make statistic for all columns, even for columns where it does not
        # make much sense to do so (like the 1st column that might contain run #)
        COLUMN_MIN_VALUES = 2
        COLUMN_MAX_VALUES = 3
        COLUMN_AVG_VALUES = 4

        n = len(results)
        columns = len(results[0])

        # initial values to be updated later
        sum_val = [0] * columns
        avg_val = [None] * columns
        max_val = [float("-inf")] * columns
        min_val = [float("inf")] * columns

        # compute min, max, and sum
        for result in results:
            for column in range(columns):
                r = float(result[column])
                sum_val[column] += r
                if r < min_val[column]:
                    min_val[column] = r
                if max_val[column] < r:
                    max_val[column] = r

        # really don't wanna to divide by zero
        if n > 0:
            for column in range(columns):
                avg_val[column] = sum_val[column] / n

        if columns == 1:
            return {
                "sum": sum_val[0],
                "avg": avg_val[0],
                "min": min_val[0],
                "max": max_val[0],
            }
        else:
            return {
                "sum": sum_val[COLUMN_MAX_VALUES],
                "avg": avg_val[COLUMN_AVG_VALUES],
                "min": min_val[COLUMN_MIN_VALUES],
                "max": max_val[COLUMN_MAX_VALUES],
            }

    def compute_statistic_for_analysis(self, results):
        """Compute the basic statistic (min, max, sum, avg) for the selected set of results."""
        stat = {}
        for key, results in results.items():
            stat[key] = PerfTests.compute_stat_for_result_set(results)
        return stat

    def compute_statistic(self):
        """Compute statistic for all results generated by performance tests."""
        for analyse in PerfTests.INPUT_FILES.keys():
            self._statistic[analyse] = self.compute_statistic_for_analysis(self._results[analyse])

    @property
    def results(self):
        """Getter for the 'results' attribute."""
        return self._results

    @property
    def statistic(self):
        """Getter for the 'statistic' attribute."""
        return self._statistic

if __name__ == "__main__":
    # execute only if run as a script
    perf_tests = PerfTests()
    perf_tests.read_results()
    perf_tests.compute_statistic()
    print("Results:")
    print(perf_tests.results)
    print("-----------------------------------------")
    print("Statistic:")
    print(perf_tests.statistic)


text:
FROM gogs/gogs

ADD data /data


text:
var vDhtmlxRadarChart = Aspectize.CreateView('DhtmlxRadarChart', aas.Controls.DhtmlxRadarChart, aas.Zones.SideBarContent.ZoneContent);
vDhtmlxRadarChart.OnActivated.BindCommand(aas.Services.Browser.BootStrapClientService.ActiveLiElement(aas.ViewName.DhtmlxRadarChart));
vDhtmlxRadarChart.OnActivated.BindCommand(aas.Services.Browser.DhtmlxChartService.RefreshGraph(aas.ViewName.DhtmlxRadarChart.DhtmlxRadarChartSales));
vDhtmlxRadarChart.DhtmlxRadarChartSales.BindGrid(aas.Data.AdventureWorksData.SalesPerson.QuotaHistory, "QuotaDate ASC");
vDhtmlxRadarChart.DhtmlxRadarChartSales.Type.BindData('radar');
vDhtmlxRadarChart.DhtmlxRadarChartSales.hLines.BindData(true);
vDhtmlxRadarChart.DhtmlxRadarChartSales.vLines.BindData(true);
vDhtmlxRadarChart.DhtmlxRadarChartSales.ShowPoints.BindData(false);
//vDhtmlxRadarChart.DhtmlxRadarChartSales.Legendlayout.BindData("y");
//vDhtmlxRadarChart.DhtmlxRadarChartSales.LegendAlign.BindData(true);

//vDhtmlxRadarChart.DhtmlxRadarChartSales.xEnd.BindData(3000);
//vDhtmlxRadarChart.DhtmlxRadarChartSales.xStart.BindData(0);
//vDhtmlxRadarChart.DhtmlxRadarChartSales.xStep.BindData(1000);

var cQuotaDate = vDhtmlxRadarChart.DhtmlxRadarChartSales.AddGridColumn("QuotaDate", aas.ColumnType.Dhtmlx.DhtmlxAxis);
cQuotaDate.Value.BindData(vDhtmlxRadarChart.DhtmlxRadarChartSales.DataSource.QuotaDate);
cQuotaDate.Label.BindData(vDhtmlxRadarChart.DhtmlxRadarChartSales.DataSource.QuotaDate, 'MM/yy');
cQuotaDate.ItemColor.BindData('#cfcfcf');
cQuotaDate.LineWidth.BindData(2);
cQuotaDate.LineColor.BindData('#cfcfcf');

//cQuotaDate.Title.BindData("Date");
//cQuotaDate.ItemColor.BindData("#FFFFFF");
//cQuotaDate.LineColor.BindData("#599EC8");
//cQuotaDate.LineWidth.BindData(2);
cQuotaDate.ItemRadius.BindData(3);
cQuotaDate.ItemBorderColor.BindData("#599EC8");
cQuotaDate.ItemBorderWidth.BindData(1);
var cSalesQuota = vDhtmlxRadarChart.DhtmlxRadarChartSales.AddGridColumn("SalesQuota", aas.ColumnType.Dhtmlx.DhtmlxAxis);
cSalesQuota.Value.BindData(vDhtmlxRadarChart.DhtmlxRadarChartSales.DataSource.SalesQuota);
cSalesQuota.Title.BindData("Sales");
//cSalesQuota.Label.BindData(vDhtmlxRadarChart.DhtmlxRadarChartSales.DataSource.SalesQuota, 'G0');
cSalesQuota.ItemColor.BindData("#FFFFFF");
cSalesQuota.LineColor.BindData("#599EC8");
cSalesQuota.LineWidth.BindData(2);
cSalesQuota.ItemRadius.BindData(3);
cSalesQuota.ItemBorderColor.BindData("#599EC8");
cSalesQuota.ItemBorderWidth.BindData(1);

vDhtmlxRadarChart.GridSalesPerson.BindGrid(aas.Data.AdventureWorksData.SalesPerson);
var cFirstName = vDhtmlxRadarChart.GridSalesPerson.AddGridColumn("FirstName", aas.ColumnType.Span);
cFirstName.Text.BindData(vDhtmlxRadarChart.GridSalesPerson.DataSource.ContactSalesPerson.Contact.FirstName);
var cLastName = vDhtmlxRadarChart.GridSalesPerson.AddGridColumn("LastName", aas.ColumnType.Span);
cLastName.Text.BindData(vDhtmlxRadarChart.GridSalesPerson.DataSource.ContactSalesPerson.Contact.LastName);


text:
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>{{ page.title }}</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css?family=Inconsolata|Roboto" rel="stylesheet">
    <link href="/assets/css/stylesheet.css" rel="stylesheet" >

    <meta name="description" content="{{ page.description }}" />
</head>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package whistleblowerclient;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author tethik
 */
public class Log {

    private static String getCallingClassName() {
        return Thread.currentThread().getStackTrace()[1].getClassName();
    }

    public static void i(String message) {
        Logger.getLogger(getCallingClassName()).log(Level.INFO, message);
    }

    public static void e(String message) {
        Logger.getLogger(getCallingClassName()).log(Level.SEVERE, message);
    }

}


text:
"""
Orgão
===================

"""
#    Copyright (C) 2016 by
#    Rion Brattig Correia <rionbr@gmail.com>
#    All rights reserved.
#    MIT license.

import numpy as np
import pandas as pd
import requests
from lxml import etree
import urlparse
#
from db import DB

__name__ = 'orgao'
__author__ = """\n""".join(['Rion Brattig Correia <rionbr@gmail.com>'])
__all__ = ['Orgao']
#
#
#
class Orgao(object):
	"""

	"""
	def __init__(self, verbose=False):

		self.url = 'http://www.portaldatransparencia.gov.br/servidores/OrgaoExercicio-ListaOrgaos.asp?CodOS=%d&Pagina=%d'
		self.verbose = verbose

	def harvest(self, codOS):
		"""

		"""
		#
		# Collect the first page, and identify how many pages there are
		#
		page = requests.get(self.url % (codOS, 1))
		tree = etree.HTML(page.content, etree.HTMLParser(encoding="windows-1252"))
		_, n_pages = tree.xpath('//div[@id="paginacao"]/p[@class="paginaAtual"]')[0].text.split('/')

		if self.verbose:
			print 'Pages found: %d' % (int(n_pages))
		#
		# Loop all Pages to insert information into DB
		#
		for i_page in np.arange(1, int(n_pages)+1):

			if self.verbose:
				print 'Page: %d/%d' % (i_page, int(n_pages))

			if i_page>1:
				page = requests.get(self.url % (codOS, i_page))
				tree = etree.HTML(page.content, etree.HTMLParser(encoding="windows-1252"))

			lista = tree.xpath('//div[@id="listagem"]/table')[0]

			items = []
			for i, item in enumerate(lista, start=0):

				if i ==0:
					continue

				_id, name, n_servidores = item.xpath('td')

				items.append( (int(_id.text), codOS, name[0].text.title(), int(n_servidores.text)) )

			# To DataFrame
			df = pd.DataFrame(items, columns=['id_orgao','id_orgao_superior','name','n_servidores'])

			# Insert into MySQL
			status = DB().DataFrameToMySQL(df, table='orgao')

	def getDF(self):
		"""

		"""
		return DB().MySQLToDataFrame("SELECT * from orgao", index_col='id_orgao')

#
#
#
if __name__ == '__main__':

	Orgao(verbose=True).harvest(codOS=15000)


text:
//package demesne
//
//import akka.actor.{ ActorContext, ActorRef }
//import akka.cluster.sharding.ClusterSharding
//import shapeless.Typeable
//import com.typesafe.scalalogging.StrictLogging
//import omnibus.commons.log.Trace
//
//
//package object factory extends StrictLogging {
//  private val trace = Trace( "demesne.factory", logger )
//
//  //todo: this factory has grown cumbersome and awkward; need to DRY it up
//  type ActorFactory = (DomainModel, Option[ActorContext]) => ( AggregateRootType, String ) => ActorRef
//
//  /**
//   * supports typesafe casting to ActorFactory since type is a type def rather than a class/trait.
//   */
//  implicit val typeableActorFactory = new Typeable[ActorFactory] {
//    override def cast( t: Any ): Option[ActorFactory] = scala.util.Try[ActorFactory]{ t.asInstanceOf[ActorFactory] }.toOption
//    override val describe: String = "ActorFactory"
//  }
//
//  val systemFactory: ActorFactory = {
//    ( model: DomainModel, context: Option[ActorContext] ) => ( rootType: AggregateRootType, name: String ) => trace.block( s"systemFactory($model, $context)($rootType)" ) {
//      model.system.actorOf( rootType.aggregateRootProps(model), name )
//    }
//  }
//
//  val contextFactory: ActorFactory = {
//    ( model: DomainModel, context: Option[ActorContext] ) => ( rootType: AggregateRootType, name: String ) => trace.block( s"contextFactory($model, $context)($rootType)") {
//      val result = for {
//        ctx <- context
//      } yield ctx.actorOf( rootType.aggregateRootProps( model ), name )
//
//      result getOrElse model.system.deadLetters
//    }
//  }
//
//  val clusteredFactory: ActorFactory = {
//      ( model: DomainModel, context: Option[ActorContext] ) => ( rootType: AggregateRootType, name: String ) => trace.block( s"clusteredFactory($model, $context)($rootType)" ) {
//      ClusterSharding( model.system ) shardRegion rootType.name
//    }
//  }
//}


text:
require 'test_helper'

class FlowmorAnalyticsTest < ActiveSupport::TestCase
end