code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
#### প্রারম্ভিকা
Go আসলে বেশি পরিচিত golang নামেই। এটি ২০০৭ সালে Google -এ ডেভেলপ করা হয়েছিল রবার্ট গ্রিজমার, রব পাইক এবং কেইন থম্পসন এর দ্বারা। ২০০৯ সালের দিকে এই ল্যাঙ্গুয়েজটি প্রকাশ করা হয়। ইতোমধ্যে এটি Google এর বেশ কিছু প্রোডাকশন সিস্টেমে ব্যবহৃত হচ্ছে।
- বিষয় : Go Language সম্পর্কে জানা
- গবেষণা ক্ষেত্র : যেকোন
| Java |
import cx from 'clsx'
import PropTypes from 'prop-types'
import React from 'react'
import { customPropTypes, getElementType, getUnhandledProps, useKeyOnly } from '../../lib'
/**
* A placeholder can contain an image.
*/
function PlaceholderImage(props) {
const { className, square, rectangular } = props
const classes = cx(
useKeyOnly(square, 'square'),
useKeyOnly(rectangular, 'rectangular'),
'image',
className,
)
const rest = getUnhandledProps(PlaceholderImage, props)
const ElementType = getElementType(PlaceholderImage, props)
return <ElementType {...rest} className={classes} />
}
PlaceholderImage.propTypes = {
/** An element type to render as (string or function). */
as: PropTypes.elementType,
/** Additional classes. */
className: PropTypes.string,
/** An image can modify size correctly with responsive styles. */
square: customPropTypes.every([customPropTypes.disallow(['rectangular']), PropTypes.bool]),
/** An image can modify size correctly with responsive styles. */
rectangular: customPropTypes.every([customPropTypes.disallow(['square']), PropTypes.bool]),
}
export default PlaceholderImage
| Java |
(function (angular) {
"use strict";
var appFooter = angular.module('myApp.footer', []);
appFooter.controller("footerCtrl", ['$scope', function ($scope) {
}]);
myApp.directive("siteFooter",function(){
return {
restrict: 'A',
templateUrl:'app/components/footer/footer.html'
};
});
} (angular)); | Java |
xss-test
========
| Java |
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/db2utils.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/db2utils.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/db2utils"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/db2utils"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
| Java |
<?php
namespace App\Http\Controllers\API\V2;
use App\Beacon;
use App\Http\Requests\BeaconRequest;
use Illuminate\Http\Request;
class BeaconController extends Controller
{
/**
* Return a list of items.
*
* @param Request $request
*
* @return json
*/
public function index(Request $request)
{
return $this->filteredAndOrdered($request, new Beacon())->paginate($this->pageSize);
}
/**
* Save a new item.
*
* @param Request $request
*
* @return json
*/
public function store(BeaconRequest $request)
{
return response(Beacon::create($request->all()), 201);
}
/**
* Return a single item.
*
* @param Request $request
* @param Beacon $beacon
*
* @return json
*/
public function show(Request $request, Beacon $beacon)
{
return $this->attachResources($request, $beacon);
}
/**
* Update a single item.
*
* @param BeaconRequest $request
* @param Beacon $beacon
*
* @return json
*/
public function update(BeaconRequest $request, Beacon $beacon)
{
$beacon->update($request->all());
return $beacon;
}
/**
* Delete a single item.
*
* @param Beacon $beacon
*
* @return empty
*/
public function destroy(Beacon $beacon)
{
$beacon->delete();
return response('', 204);
}
/**
* Return a list of deleted items.
*
* @return json
*/
public function deleted()
{
return Beacon::onlyTrashed()->get();
}
}
| Java |
#!/bin/sh
usage() {
cat <<EOF
USAGE: \${DOTFILES}/shell/csh/launcher.sh <function> [arg ...]
FUNCTION:
exit <return_code>
EOF
}
# Print usage if not specify the function that need to run.
if [ $# -eq 0 ]; then
usage
exit 1
fi
# The function name is the first argument.
func_name=${1}
# Remove the first argument "function name".
shift 1
# Dispatch to the corresponding function.
case ${func_name} in
exit)
exit ${@}
;;
*)
cat <<EOF
Error: Specify unknow function "${func_name}",
this shell script now only support run function "exit".
EOF
usage
exit 1
;;
esac
| Java |
/* -*- C++ -*- */
// $Id: ntsvc.h 80826 2008-03-04 14:51:23Z wotte $
// ============================================================================
//
// = LIBRARY
// examples/NT_Service
//
// = FILENAME
// ntsvc.h
//
// = DESCRIPTION
// This is the definition of the sample NT Service class. This example
// only runs on Win32 platforms.
//
// = AUTHOR
// Gonzalo Diethelm and Steve Huston
//
// ============================================================================
#ifndef NTSVC_H_
#define NTSVC_H_
#include "ace/config-lite.h"
#if defined (ACE_WIN32) && !defined (ACE_LACKS_WIN32_SERVICES)
#include "ace/Event_Handler.h"
#include "ace/NT_Service.h"
#include "ace/Singleton.h"
#include "ace/Mutex.h"
class Service : public ACE_NT_Service
{
public:
Service (void);
~Service (void);
virtual void handle_control (DWORD control_code);
// We override <handle_control> because it handles stop requests
// privately.
virtual int handle_exception (ACE_HANDLE h);
// We override <handle_exception> so a 'stop' control code can pop
// the reactor off of its wait.
virtual int svc (void);
// This is a virtual method inherited from ACE_NT_Service.
virtual int handle_timeout (const ACE_Time_Value& tv,
const void *arg = 0);
// Where the real work is done:
private:
typedef ACE_NT_Service inherited;
private:
int stop_;
};
// Define a singleton class as a way to insure that there's only one
// Service instance in the program, and to protect against access from
// multiple threads. The first reference to it at runtime creates it,
// and the ACE_Object_Manager deletes it at run-down.
typedef ACE_Singleton<Service, ACE_Mutex> SERVICE;
#endif /* ACE_WIN32 && !ACE_LACKS_WIN32_SERVICES */
#endif /* #ifndef NTSVC_H_ */
| Java |
import {IDetailsService} from '../services/details.service';
class DetailsController implements ng.IComponentController {
private detailsService: IDetailsService;
private detailsData: any;
private previousState: any;
constructor($stateParams: any, detailsService: IDetailsService) {
console.log('details controller');
console.log("$stateParams.id=", $stateParams.id);
console.log("this.previousState=", this.previousState);
let id = $stateParams.id;
detailsService.searchByIMDbID(id, 'full').then((result) => {
console.log("detailsData = ", result.data);
this.detailsData = result.data;
});
}
}
export default DetailsController;
DetailsController.$inject = ['$stateParams', 'detailsService'];
| Java |
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"strings"
"sync"
)
func checkError(err error, prefix string) {
if err != nil {
panic(fmt.Sprintf("%s %s", prefix, err.Error()))
}
}
func cleanFeedbackLine(s string) (out string) {
out = s
out = strings.TrimSpace(out)
out = strings.Replace(out, "\r", "", -1)
out = strings.Replace(out, "\n", "\\n", -1)
return
}
func runCommand(wg *sync.WaitGroup, resultCollector *ResultCollector, commandIndex int, phase *nodeData, cmd *exec.Cmd) {
if wg != nil {
defer wg.Done()
}
defer func() {
if r := recover(); r != nil {
errMsg := fmt.Sprintf("%s", r)
if !phase.ContinueOnFailure {
logger.Fatallnf(errMsg)
} else {
logger.Errorlnf(errMsg)
}
resultCollector.AppendResult(&result{Cmd: cmd, Successful: false})
} else {
resultCollector.AppendResult(&result{Cmd: cmd, Successful: true})
}
}()
stdout, err := cmd.StdoutPipe()
checkError(err, "cmd.StdoutPipe")
stderr, err := cmd.StderrPipe()
checkError(err, "cmd.StderrPipe")
outLines := []string{}
stdoutScanner := bufio.NewScanner(stdout)
go func() {
for stdoutScanner.Scan() {
txt := cleanFeedbackLine(stdoutScanner.Text())
outLines = append(outLines, txt)
logger.Tracelnf("COMMAND %d STDOUT: %s", commandIndex, txt)
}
}()
errLines := []string{}
stderrScanner := bufio.NewScanner(stderr)
go func() {
for stderrScanner.Scan() {
txt := cleanFeedbackLine(stderrScanner.Text())
errLines = append(errLines, txt)
logger.Warninglnf("COMMAND %d STDERR: %s", commandIndex, txt)
}
}()
err = cmd.Start()
checkError(err, "cmd.Start")
err = cmd.Wait()
if err != nil {
newErr := fmt.Errorf("%s - lines: %s", err.Error(), strings.Join(errLines, "\\n"))
outCombined := cleanFeedbackLine(strings.Join(outLines, "\n"))
errMsg := fmt.Sprintf("FAILED COMMAND %d. Continue: %t. ERROR: %s. OUT: %s", commandIndex, phase.ContinueOnFailure, newErr.Error(), outCombined)
panic(errMsg)
}
}
func runPhase(setup *setup, phaseName string, phase *nodeData) {
var wg sync.WaitGroup
resultCollector := &ResultCollector{}
cmds, err := phase.GetExecCommandsFromSteps(setup.StringVariablesOnly(), setup.Variables)
if err != nil {
logger.Fatallnf(err.Error())
}
if phase.RunParallel {
wg.Add(len(cmds))
}
logger.Infolnf("Running step %s", phaseName)
for ind, c := range cmds {
logger.Tracelnf(strings.TrimSpace(fmt.Sprintf(`INDEX %d = %s`, ind, execCommandToDisplayString(c))))
var wgToUse *sync.WaitGroup = nil
if phase.RunParallel {
wgToUse = &wg
go runCommand(wgToUse, resultCollector, ind, phase, c)
} else {
runCommand(wgToUse, resultCollector, ind, phase, c)
}
}
if phase.RunParallel {
wg.Wait()
}
if resultCollector.FailedCount() == 0 {
logger.Infolnf("There were no failures - %d/%d successful", resultCollector.SuccessCount(), resultCollector.TotalCount())
} else {
logger.Errorlnf("There were %d/%d failures: ", resultCollector.FailedCount(), resultCollector.TotalCount())
for _, failure := range resultCollector.FailedDisplayList() {
logger.Errorlnf("- %s", failure)
}
}
}
func main() {
logger.Infolnf("Running version '%s'", Version)
if len(os.Args) < 2 {
logger.Fatallnf("The first command-line argument must be the YAML file path.")
}
yamlFilePath := os.Args[1]
setup, err := ParseYamlFile(yamlFilePath)
if err != nil {
logger.Fatallnf(err.Error())
}
for _, phase := range setup.Phases {
runPhase(setup, phase.Name, phase.Data)
}
}
| Java |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Header <boost/icl/iterator.hpp></title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Boost.Icl">
<link rel="up" href="../../../interval_container_library_reference.html" title="Interval Container Library Reference">
<link rel="prev" href="../../../boost/icl/size_typ_idm45536290362624.html" title="Struct template size_type_of<interval_traits< Type >>">
<link rel="next" href="../../../boost/icl/add_iterator.html" title="Class template add_iterator">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../../../boost/icl/size_typ_idm45536290362624.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../interval_container_library_reference.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../../../boost/icl/add_iterator.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h3 class="title">
<a name="header.boost.icl.iterator_hpp"></a>Header <<a href="../../../../../../../boost/icl/iterator.hpp" target="_top">boost/icl/iterator.hpp</a>></h3></div></div></div>
<pre class="synopsis"><span class="keyword">namespace</span> <span class="identifier">boost</span> <span class="special">{</span>
<span class="keyword">namespace</span> <span class="identifier">icl</span> <span class="special">{</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> ContainerT<span class="special">></span> <span class="keyword">class</span> <a class="link" href="../../../boost/icl/add_iterator.html" title="Class template add_iterator">add_iterator</a><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> ContainerT<span class="special">></span> <span class="keyword">class</span> <a class="link" href="../../../boost/icl/insert_iterator.html" title="Class template insert_iterator">insert_iterator</a><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> ContainerT<span class="special">,</span> <span class="keyword">typename</span> IteratorT<span class="special">></span>
<a class="link" href="../../../boost/icl/add_iterator.html" title="Class template add_iterator">add_iterator</a><span class="special"><</span> <span class="identifier">ContainerT</span> <span class="special">></span> <a class="link" href="../../../boost/icl/adder.html" title="Function template adder"><span class="identifier">adder</span></a><span class="special">(</span><span class="identifier">ContainerT</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">IteratorT</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> ContainerT<span class="special">,</span> <span class="keyword">typename</span> IteratorT<span class="special">></span>
<a class="link" href="../../../boost/icl/insert_iterator.html" title="Class template insert_iterator">insert_iterator</a><span class="special"><</span> <span class="identifier">ContainerT</span> <span class="special">></span> <a class="link" href="../../../boost/icl/inserter.html" title="Function template inserter"><span class="identifier">inserter</span></a><span class="special">(</span><span class="identifier">ContainerT</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">IteratorT</span><span class="special">)</span><span class="special">;</span>
<span class="special">}</span>
<span class="special">}</span></pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2007-2010 Joachim
Faulhaber<br>Copyright © 1999-2006 Cortex Software
GmbH<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../../../boost/icl/size_typ_idm45536290362624.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../interval_container_library_reference.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../../../boost/icl/add_iterator.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| Java |
<html>
<head>
<title>Progmia | Game | Level Selection</title>
<link href="<?php echo base_url(); ?>assets/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/levels.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/stars.css">
<script type="text/javascript" src="<?php echo base_url();?>assets/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/bootstrap.min.js""></script>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/bootstrap.min.js"></script>
<link rel="icon" href="<?php echo base_url(); ?>assets/images/icon_jFd_icon.ico">
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/fonts/font-awesome-4.7.0/css/font-awesome.min.css">
<script type="text/javascript" src="<?php echo base_url();?>assets/js/drag-on.js"></script>
</head>
<body>
<nav id="primary-nav" class="primary-nav">
<div class="container-fluid">
<div class="row" style="display: flex;align-items: center;">
<div class="col-md-3 col-lg-3 col-xs-4 col-sm-4" style="text-align: center;">
<a class="back" href="<?php echo base_url(); ?>Game/MainMenu"><i class="fa fa-arrow-left"></i></a>
</div>
<div class="col-md-6 col-lg-6 col-xs-4 col-sm-4">
</div>
<div class="col-md-3 col-lg-3 col-xs-4 col-sm-4">
<ul class="nav-left">
<li class="music-control">
<button id="playpausebtn" class="playpausebtn"><i class="fa fa-music"></i></button>
<input id="volumeslider" class="volumeslider" type="range" min="0" max="100" value="100" step="1">
</li>
</ul>
</div>
</div>
</div>
</nav>
<script>
$(document).ready(function(){
$("button.playpausebtn").click(function() {
if(jQuery('#playpausebtn').hasClass('paused')){
$("button").removeClass("paused");
}
else
{
$(this).addClass("paused");
}
});
$("button#back").click(function() {
});
});
var audio, playbtn, mutebtn, seekslider, volumeslider, seeking=false, seekto;
function initAudioPlayer(){
audio = new Audio();
audio.src = "<?php echo base_url();?>/assets/sounds/bgm/03 Civil (Explore).mp3";
audio.loop = true;
audio.play();
// Set object references
playbtn = document.getElementById("playpausebtn");
volumeslider = document.getElementById("volumeslider");
// Add Event Handling
playbtn.addEventListener("click",playPause);
volumeslider.addEventListener("mousemove", setvolume);
// Functions
function playPause(){
if(audio.paused){
audio.play();
} else {
audio.pause();
}
}
function setvolume(){
audio.volume = volumeslider.value / 100;
}
}
window.addEventListener("load", initAudioPlayer);
</script> | Java |
--[[checkboxData = {
type = "checkbox",
name = "My Checkbox",
tooltip = "Checkbox's tooltip text.",
getFunc = function() return db.var end,
setFunc = function(value) db.var = value doStuff() end,
width = "full", --or "half" (optional)
disabled = function() return db.someBooleanSetting end, --or boolean (optional)
warning = "Will need to reload the UI.", --(optional)
default = defaults.var, --(optional)
reference = "MyAddonCheckbox" --(optional) unique global reference to control
} ]]
local widgetVersion = 7
local LAM = LibStub("LibAddonMenu-2.0")
if not LAM:RegisterWidget("checkbox", widgetVersion) then return end
local wm = WINDOW_MANAGER
local cm = CALLBACK_MANAGER
local tinsert = table.insert
--label
local enabledColor = ZO_DEFAULT_ENABLED_COLOR
local enabledHLcolor = ZO_HIGHLIGHT_TEXT
local disabledColor = ZO_DEFAULT_DISABLED_COLOR
local disabledHLcolor = ZO_DEFAULT_DISABLED_MOUSEOVER_COLOR
--checkbox
local checkboxColor = ZO_NORMAL_TEXT
local checkboxHLcolor = ZO_HIGHLIGHT_TEXT
local function UpdateDisabled(control)
local disable
if type(control.data.disabled) == "function" then
disable = control.data.disabled()
else
disable = control.data.disabled
end
control.label:SetColor((disable and ZO_DEFAULT_DISABLED_COLOR or control.value and ZO_DEFAULT_ENABLED_COLOR or ZO_DEFAULT_DISABLED_COLOR):UnpackRGBA())
control.checkbox:SetColor((disable and ZO_DEFAULT_DISABLED_COLOR or ZO_NORMAL_TEXT):UnpackRGBA())
--control:SetMouseEnabled(not disable)
--control:SetMouseEnabled(true)
control.isDisabled = disable
end
local function ToggleCheckbox(control)
if control.value then
control.label:SetColor(ZO_DEFAULT_ENABLED_COLOR:UnpackRGBA())
control.checkbox:SetText(control.checkedText)
else
control.label:SetColor(ZO_DEFAULT_DISABLED_COLOR:UnpackRGBA())
control.checkbox:SetText(control.uncheckedText)
end
end
local function UpdateValue(control, forceDefault, value)
if forceDefault then --if we are forcing defaults
value = control.data.default
control.data.setFunc(value)
elseif value ~= nil then --our value could be false
control.data.setFunc(value)
--after setting this value, let's refresh the others to see if any should be disabled or have their settings changed
if control.panel.data.registerForRefresh then
cm:FireCallbacks("LAM-RefreshPanel", control)
end
else
value = control.data.getFunc()
end
control.value = value
ToggleCheckbox(control)
end
local function OnMouseEnter(control)
ZO_Options_OnMouseEnter(control)
if control.isDisabled then return end
local label = control.label
if control.value then
label:SetColor(ZO_HIGHLIGHT_TEXT:UnpackRGBA())
else
label:SetColor(ZO_DEFAULT_DISABLED_MOUSEOVER_COLOR:UnpackRGBA())
end
control.checkbox:SetColor(ZO_HIGHLIGHT_TEXT:UnpackRGBA())
end
local function OnMouseExit(control)
ZO_Options_OnMouseExit(control)
if control.isDisabled then return end
local label = control.label
if control.value then
label:SetColor(ZO_DEFAULT_ENABLED_COLOR:UnpackRGBA())
else
label:SetColor(ZO_DEFAULT_DISABLED_COLOR:UnpackRGBA())
end
control.checkbox:SetColor(ZO_NORMAL_TEXT:UnpackRGBA())
end
--controlName is optional
function LAMCreateControl.checkbox(parent, checkboxData, controlName)
local control = wm:CreateTopLevelWindow(controlName or checkboxData.reference)
control:SetParent(parent.scroll or parent)
control:SetMouseEnabled(true)
--control.tooltipText = checkboxData.tooltip
control:SetHandler("OnMouseEnter", OnMouseEnter)
control:SetHandler("OnMouseExit", OnMouseExit)
control:SetHandler("OnMouseUp", function(control)
if control.isDisabled then return end
PlaySound(SOUNDS.DEFAULT_CLICK)
control.value = not control.value
control:UpdateValue(false, control.value)
end)
control.label = wm:CreateControl(nil, control, CT_LABEL)
local label = control.label
label:SetFont("ZoFontWinH4")
label:SetText(checkboxData.name)
label:SetWrapMode(TEXT_WRAP_MODE_ELLIPSIS)
label:SetHeight(26)
control.checkbox = wm:CreateControl(nil, control, CT_LABEL)
local checkbox = control.checkbox
checkbox:SetFont("ZoFontGameBold")
checkbox:SetColor(ZO_NORMAL_TEXT:UnpackRGBA())
control.checkedText = GetString(SI_CHECK_BUTTON_ON):upper()
control.uncheckedText = GetString(SI_CHECK_BUTTON_OFF):upper()
local isHalfWidth = checkboxData.width == "half"
if isHalfWidth then
control:SetDimensions(250, 55)
checkbox:SetDimensions(100, 26)
checkbox:SetAnchor(BOTTOMRIGHT)
label:SetAnchor(TOPLEFT)
label:SetAnchor(TOPRIGHT)
else
control:SetDimensions(510, 30)
checkbox:SetDimensions(200, 26)
checkbox:SetAnchor(RIGHT)
label:SetAnchor(LEFT)
label:SetAnchor(RIGHT, checkbox, LEFT, -5, 0)
end
if checkboxData.warning then
control.warning = wm:CreateControlFromVirtual(nil, control, "ZO_Options_WarningIcon")
control.warning:SetAnchor(RIGHT, checkbox, LEFT, -5, 0)
--control.warning.tooltipText = checkboxData.warning
control.warning.data = {tooltipText = checkboxData.warning}
end
control.panel = parent.panel or parent --if this is in a submenu, panel is its parent
control.data = checkboxData
control.data.tooltipText = checkboxData.tooltip
if checkboxData.disabled then
control.UpdateDisabled = UpdateDisabled
control:UpdateDisabled()
end
control.UpdateValue = UpdateValue
control:UpdateValue()
if control.panel.data.registerForRefresh or control.panel.data.registerForDefaults then --if our parent window wants to refresh controls, then add this to the list
tinsert(control.panel.controlsToRefresh, control)
end
return control
end | Java |
import base64
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.3, 2.4 fallback.
from django import http, template
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.shortcuts import render_to_response
from django.utils.translation import ugettext_lazy, ugettext as _
ERROR_MESSAGE = ugettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.")
LOGIN_FORM_KEY = 'this_is_the_login_form'
def _display_login_form(request, error_message=''):
request.session.set_test_cookie()
return render_to_response('admin/login.html', {
'title': _('Log in'),
'app_path': request.get_full_path(),
'error_message': error_message
}, context_instance=template.RequestContext(request))
def staff_member_required(view_func):
"""
Decorator for views that checks that the user is logged in and is a staff
member, displaying the login page if necessary.
"""
def _checklogin(request, *args, **kwargs):
if request.user.is_authenticated() and request.user.is_staff:
# The user is valid. Continue to the admin page.
return view_func(request, *args, **kwargs)
assert hasattr(request, 'session'), "The Django admin requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
# If this isn't already the login page, display it.
if LOGIN_FORM_KEY not in request.POST:
if request.POST:
message = _("Please log in again, because your session has expired.")
else:
message = ""
return _display_login_form(request, message)
# Check that the user accepts cookies.
if not request.session.test_cookie_worked():
message = _("Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.")
return _display_login_form(request, message)
else:
request.session.delete_test_cookie()
# Check the password.
username = request.POST.get('username', None)
password = request.POST.get('password', None)
user = authenticate(username=username, password=password)
if user is None:
message = ERROR_MESSAGE
if '@' in username:
# Mistakenly entered e-mail address instead of username? Look it up.
users = list(User.all().filter('email =', username))
if len(users) == 1 and users[0].check_password(password):
message = _("Your e-mail address is not your username. Try '%s' instead.") % users[0].username
else:
# Either we cannot find the user, or if more than 1
# we cannot guess which user is the correct one.
message = _("Usernames cannot contain the '@' character.")
return _display_login_form(request, message)
# The user data is correct; log in the user in and continue.
else:
if user.is_active and user.is_staff:
login(request, user)
return http.HttpResponseRedirect(request.get_full_path())
else:
return _display_login_form(request, ERROR_MESSAGE)
return wraps(view_func)(_checklogin)
| Java |
// BEGIN CUT HERE
// END CUT HERE
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <map>
#include <string>
#include <set>
#include <algorithm>
using namespace std;
const int V = 64;
const int E = V * V * 2;
const int INF = 1 << 29;
int d[V], how[V], eCapacity[E], eU[E], eV[E], eCost[E];
int eIndex = 0;
void addEdge(int u, int v, int capacity, int cost) {
eU[eIndex] = u, eV[eIndex] = v, eCapacity[eIndex] = capacity, eCost[eIndex++] = cost;
eU[eIndex] = v, eV[eIndex] = u, eCapacity[eIndex] = 0, eCost[eIndex++] = -cost;
}
pair <int, int> minCostMaxFlow(int n, int s, int t) {
int flow = 0, cost = 0;
for (;;) {
for (int i = 0; i < n; i++) {
d[i] = INF;
}
d[s] = 0;
for(;;) {
bool done = true;
for (int e = 0; e < eIndex; e++) {
if (eCapacity[e] > 0) {
int u = eU[e], v = eV[e], cost = eCost[e];
if (d[v] > d[u] + cost) {
d[v] = d[u] + cost;
how[v] = e;
done = false;
}
}
}
if (done) {
break;
}
}
if (d[t] >= INF / 2) {
break;
}
int augment = INF;
for (int v = t; v != s; v = eU[how[v]]) {
augment = min(augment, eCapacity[how[v]]);
}
for (int v = t; v != s; v = eU[how[v]]) {
int e = how[v];
eCapacity[e] -= augment;
eCapacity[e ^ 1] += augment;
}
flow += augment;
cost += d[t] * augment;
}
pair <int, int> ret = make_pair(cost, flow);
return ret;
}
class SpecialCells
{
public:
int guess(vector <int> x, vector <int> y) {
eIndex = 0;
map <int, int> xMap, yMap;
set <pair <int, int> > pairSet;
int n = x.size();
for (int i = 0; i < n; i++) {
xMap[x[i]]++;
yMap[y[i]]++;
pairSet.insert(make_pair(x[i], y[i]));
}
int grpahVertexNumber = xMap.size() + yMap.size() + 2;
int s = grpahVertexNumber - 2, t = grpahVertexNumber - 1, xIndex = 0, yIndex = xMap.size();
for (map <int, int> :: iterator it = xMap.begin(); it != xMap.end(); it++, xIndex++) {
addEdge(s, xIndex, it->second, 0);
}
for (map <int, int> :: iterator it = yMap.begin(); it != yMap.end(); it++, yIndex++) {
addEdge(yIndex, t, it->second, 0);
}
xIndex = 0;
for (map <int, int> :: iterator it = xMap.begin(); it != xMap.end(); it++, xIndex++) {
yIndex = xMap.size();
for (map <int, int> :: iterator jt = yMap.begin(); jt != yMap.end(); jt++, yIndex++) {
int cost = pairSet.find(make_pair(it->first, jt->first)) == pairSet.end() ? 0 : 1;
addEdge(xIndex, yIndex, 1, cost);
}
}
pair <int, int> mcmf = minCostMaxFlow(grpahVertexNumber, s, t);
int ret = mcmf.first;
return ret;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {1,2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,2}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 0; verify_case(0, Arg2, guess(Arg0, Arg1)); }
void test_case_1() { int Arr0[] = {1,1,2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,2,1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; verify_case(1, Arg2, guess(Arg0, Arg1)); }
void test_case_2() { int Arr0[] = {1,2,1,2,1,2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,2,3,1,2,3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 6; verify_case(2, Arg2, guess(Arg0, Arg1)); }
void test_case_3() { int Arr0[] = {1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 9; verify_case(3, Arg2, guess(Arg0, Arg1)); }
void test_case_4() { int Arr0[] = {1,100000}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,100000}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 0; verify_case(4, Arg2, guess(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main(){
SpecialCells ___test;
___test.run_test(-1);
return 0;
}
// END CUT HERE
| Java |
<?php
/**
* wCMF - wemove Content Management Framework
* Copyright (C) 2005-2020 wemove digital solutions GmbH
*
* Licensed under the terms of the MIT License.
*
* See the LICENSE file distributed with this work for
* additional information.
*/
namespace wcmf\lib\core;
/**
* A session that requires clients to send a token for authentication.
*
* @author ingo herwig <ingo@wemove.com>
*/
interface TokenBasedSession extends Session {
/**
* Get the name of the auth token header.
* @return String
*/
public function getHeaderName();
/**
* Get the name of the auth token cookie.
* @return String
*/
public function getCookieName();
} | Java |
happy_photo_data
================
| Java |
export default function formatList(xs, { ifEmpty = 'нет', joint = ', ' } = {}) {
return (!xs || xs.length === 0) ? ifEmpty : xs.join(joint)
}
| Java |
<?php
namespace Tests\Builders;
class SaveCardBuilder extends AbstractModelBuilder
{
public function __construct()
{
$this->attributeValues = array(
'yourConsumerReference' => '12345',
'cardNumber' => '4976000000003436',
'expiryDate' => '12/20',
'cv2' => 452,
);
}
}
| Java |
// $Author: benine $
// $Date$
// $Log$
// Contains the mismatch class for afin
#ifndef MISMATCH_H
#define MISMATCH_H
//////////////////////////////////////////////\
// Mismatch Class: ////////////////////////////>
//////////////////////////////////////////////
//
// Mismatch object, contains all classes, methods, data, and data references necessary for processing mismatches for contig fusion
// There will be only one Process object needed per iteration of this program
class Mismatch{
private:
double score;
int length;
int index_i;
int index_j;
int end_i;
int end_j;
public:
Mismatch();
Mismatch( double score, int length, int index_i, int index_j, int end_i, int end_j );
// set mismatch score
void set_score( double score );
// set length
void set_length( int length );
// set index_i
void set_index_i( int index );
// set index_j
void set_index_j( int index );
// set index
void set_indices( int index_i, int index_j );
// set end_i
void set_end_i( int end_i );
// set end_j
void set_end_j( int end_j );
// return mismatch score
double get_score();
// return length
int get_length();
// return index i
int get_index_i();
// return index j
int get_index_j();
// return end_i
int get_end_i();
// return end_j
int get_end_j();
};
#endif
| Java |
<?php
/*
* 注意:此文件由itpl_engine编译型模板引擎编译生成。
* 如果您的模板要进行修改,请修改 templates/default/shop/map.html
* 如果您的模型要进行修改,请修改 models/shop/map.php
*
* 修改完成之后需要您进入后台重新编译,才会重新生成。
* 如果您开启了debug模式运行,那么您可以省去上面这一步,但是debug模式每次都会判断程序是否更新,debug模式只适合开发调试。
* 如果您正式运行此程序时,请切换到service模式运行!
*
* 如您有问题请到官方论坛()提问,谢谢您的支持。
*/
?><?php
/*
* 此段代码由debug模式下生成运行,请勿改动!
* 如果debug模式下出错不能再次自动编译时,请进入后台手动编译!
*/
/* debug模式运行生成代码 开始 */
if (!function_exists("tpl_engine")) {
require("foundation/ftpl_compile.php");
}
if(filemtime("templates/default/shop/map.html") > filemtime(__file__) || (file_exists("models/shop/map.php") && filemtime("models/shop/map.php") > filemtime(__file__)) ) {
tpl_engine("default", "shop/map.html", 1);
include(__file__);
} else {
/* debug模式运行生成代码 结束 */
?><?php
if (!$IWEB_SHOP_IN) {
trigger_error('Hacking attempt');
}
/* 公共信息处理 header, left, footer */
require("foundation/module_shop.php");
require("foundation/module_users.php");
require("foundation/module_shop_category.php");
//引入语言包
$s_langpackage = new shoplp;
$i_langpackage = new indexlp;
/* 数据库操作 */
dbtarget('r', $dbServs);
$dbo = new dbex();
/* 定义文件表 */
$t_shop_info = $tablePreStr . "shop_info";
$t_users = $tablePreStr . "users";
$t_shop_category = $tablePreStr . "shop_category";
$t_shop_categories = $tablePreStr . "shop_categories";
/* 商铺信息处理 */
$SHOP = get_shop_info($dbo, $t_shop_info, $shop_id);
//商铺分类
$shop_rank = $SHOP['shop_categories'];
$shop_rank_arr = get_categories_rank($shop_rank, $dbo, $t_shop_categories);
if ($shop_rank_arr) {
$num = count($shop_rank_arr) - 1;
}
if (!$SHOP) {
trigger_error($s_langpackage->s_shop_error);
}//无此商铺
if ($SHOP['lock_flg']) {
trigger_error($s_langpackage->s_shop_locked);
}//锁定
if ($SHOP['open_flg']) {
trigger_error($s_langpackage->s_shop_close);
}//关闭
$sql = "select rank_id,user_name,last_login_time from $t_users where user_id='" . $SHOP['user_id'] . "'";
$ranks = $dbo->getRow($sql);
$SHOP['rank_id'] = $ranks[0];
/* 文章头部信息 */
$header = get_shop_header($s_langpackage->s_shop_index, $SHOP);
//$nav_selected=3;
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo $header['title']; ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/>
<meta name="keywords" content="<?php echo $header['keywords']; ?>"/>
<meta name="description" content="<?php echo $header['description']; ?>"/>
<base href="<?php echo $baseUrl; ?>"/>
<link href="skin/<?php echo $SYSINFO['templates']; ?>/css/shop.css" rel="stylesheet" type="text/css"/>
<link href="skin/<?php echo $SYSINFO['templates']; ?>/css/import.css" type="text/css" rel="stylesheet"/>
<link href="skin/<?php echo $SYSINFO['templates']; ?>/css/article.css" type="text/css" rel="stylesheet"/>
<link href="skin/<?php echo $SYSINFO['templates']; ?>/css/shop_<?php echo $SHOP['shop_template']; ?>.css"
rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="skin/<?php echo $SYSINFO['templates']; ?>/js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="skin/<?php echo $SYSINFO['templates']; ?>/js/changeStyle.js"></script>
<style>
<?php if($SHOP['shop_template_img']){?>
#shopHeader {
background: transparent url(<?php echo $SHOP['shop_template_img'];?>) no-repeat scroll 0 0 #4A9DA5;
}
<?php }?>
</style>
</head>
<body onload="initialize()" onunload="GUnload()">
<!-- wrapper -->
<div id="wrapper">
<?php require("shop/index_header.php"); ?>
<!-- contents -->
<div id="contents" class="clearfix">
<div id="pkz">
<?php echo $s_langpackage->s_this_location; ?><a href="index.php"><?php echo $SYSINFO['sys_name']; ?></a>
> <a href="shop_list.php"><?php echo $s_langpackage->s_shop_category; ?></a> >
<?php foreach ($shop_rank_arr as $k => $value) { ?>
<?php if ($num == $k) { ?>
<a href=""><?php echo $value['cat_name']; ?></a>
<?php } else { ?>
<a href=""><?php echo $value['cat_name']; ?></a> >
<?php } ?>
<?php } ?>
</div>
<div id="shopHeader" class=" mg12b clearfix">
<p class="shopName"><?php echo $SHOP['shop_name']; ?></p>
<div class="shop_nav">
<?php require("shop/menu.php"); ?>
</div>
</div>
<?php require("shop/left.php"); ?>
<div id="rightCloumn">
<div class="bigpart">
<div class="shop_notice top10">
<div class="c_t">
<div class="c_t_l left"></div>
<div class="c_t_r right"></div>
<h2><a href="javascript:;"><?php echo $s_langpackage->s_shop_seat; ?></a><span></span></h2>
</div>
<div class="c_m">
<div id="map_canvas" style="width: 688px; height: 500px"></div>
</div>
<div class="c_bt">
<div class="c_bt_l left"></div>
<div class="c_bt_r right"></div>
</div>
</div>
</div>
</div>
</div>
<?php require("shop/index_footer.php"); ?>
<script src="http://maps.google.com/maps?file=api&v=2.x&key=<?php echo $SYSINFO['map_key']; ?>"
type="text/javascript"></script>
<script type="text/javascript">
var now_x = <?php echo $SHOP['map_x'];?>;
var now_y = <?php echo $SHOP['map_y'];?>;
var now_zoom = <?php echo $SHOP['map_zoom'];?>;
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
var center = new GLatLng(now_y, now_x);
map.setCenter(center, now_zoom);
var point = new GLatLng(now_y, now_x);
var marker = new GMarker(point);
map.addOverlay(marker);
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
}
}
</script>
</body>
</html><?php } ?> | Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>fairisle: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.9.1 / fairisle - 8.7.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
fairisle
<small>
8.7.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-02-16 00:21:27 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-16 00:21:27 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.9.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.07.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.07.1 Official release 4.07.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/fairisle"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Fairisle"]
depends: [
"ocaml"
"coq" {>= "8.7" & < "8.8~"}
]
tags: [
"keyword: circuits"
"keyword: automata"
"keyword: co-induction"
"keyword: dependent types"
"category: Computer Science/Architecture"
"date: 2005-12-15"
]
authors: [ "Solange Coupet-Grimal <Solange.Coupet@lif.univ-mrs.fr> [http://www.cmi.univ-mrs.fr/~solange/]" "Line Jakubiec-Jamet <Line.Jakubiec@lif.univ-mrs.fr> [http://www.dil.univ-mrs.fr/~jakubiec/]" ]
bug-reports: "https://github.com/coq-contribs/fairisle/issues"
dev-repo: "git+https://github.com/coq-contribs/fairisle.git"
synopsis: "Proof of the Fairisle 4x4 Switch Element"
description: """
http://www.dil.univ-mrs.fr/~jakubiec/fairisle.tar.gz
This library contains the development of general definitions dedicated
to the verification of sequential synchronous devices (based on Moore and Mealy automata)
and the formal verification of the Fairisle 4x4 Switch Element."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/fairisle/archive/v8.7.0.tar.gz"
checksum: "md5=709bcd94237492a8980a2807936b80b5"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-fairisle.8.7.0 coq.8.9.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.9.1).
The following dependencies couldn't be met:
- coq-fairisle -> coq < 8.8~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-fairisle.8.7.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| Java |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<!--
ZeepIt
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>ZeepIt</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<frameset rows="20%, 80%">
<frameset cols="25%,35%,45%">
<frame src="fr_file_index.html" title="Files" name="Files" />
<frame src="fr_class_index.html" name="Classes" />
<frame src="fr_method_index.html" name="Methods" />
</frameset>
<frame src="files/README_rdoc.html" name="docwin" />
</frameset>
</html> | Java |
package com.example;
import java.util.Set;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class ServletContainerInitializerImpl implements ServletContainerInitializer {
@Override
public void onStartup(final Set<Class<?>> c, final ServletContext ctx) throws ServletException {
final AnnotationConfigWebApplicationContext wac = new AnnotationConfigWebApplicationContext();
wac.register(MvcConfig.class);
wac.refresh();
final DispatcherServlet servlet = new DispatcherServlet(wac);
final ServletRegistration.Dynamic reg = ctx.addServlet("dispatcher", servlet);
reg.addMapping("/*");
}
}
| Java |
import React from 'react';
const EditHero = props => {
if (props.selectedHero) {
return (
<div>
<div className="editfields">
<div>
<label>id: </label>
{props.addingHero
? <input
type="number"
name="id"
placeholder="id"
value={props.selectedHero.id}
onChange={props.onChange}
/>
: <label className="value">
{props.selectedHero.id}
</label>}
</div>
<div>
<label>name: </label>
<input
name="name"
value={props.selectedHero.name}
placeholder="name"
onChange={props.onChange}
/>
</div>
<div>
<label>saying: </label>
<input
name="saying"
value={props.selectedHero.saying}
placeholder="saying"
onChange={props.onChange}
/>
</div>
</div>
<button onClick={props.onCancel}>Cancel</button>
<button onClick={props.onSave}>Save</button>
</div>
);
} else {
return <div />;
}
};
export default EditHero;
| Java |
#ifndef SE_SCANNNER_H
#define SE_SCANNNER_H
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "read.h"
#include "fusion.h"
#include "match.h"
#include <cstdlib>
#include <condition_variable>
#include <mutex>
#include <thread>
#include "fusionmapper.h"
using namespace std;
struct ReadPack {
Read** data;
int count;
};
typedef struct ReadPack ReadPack;
struct ReadRepository {
ReadPack** packBuffer;
size_t readPos;
size_t writePos;
size_t readCounter;
std::mutex mtx;
std::mutex readCounterMtx;
std::condition_variable repoNotFull;
std::condition_variable repoNotEmpty;
};
typedef struct ReadRepository ReadRepository;
class SingleEndScanner{
public:
SingleEndScanner(string fusionFile, string refFile, string read1File, string html, string json, int threadnum);
~SingleEndScanner();
bool scan();
void textReport();
void htmlReport();
void jsonReport();
private:
bool scanSingleEnd(ReadPack* pack);
void initPackRepository();
void destroyPackRepository();
void producePack(ReadPack* pack);
void consumePack();
void producerTask();
void consumerTask();
void pushMatch(Match* m);
private:
string mFusionFile;
string mRefFile;
string mRead1File;
string mRead2File;
string mHtmlFile;
string mJsonFile;
ReadRepository mRepo;
bool mProduceFinished;
std::mutex mFusionMtx;
int mThreadNum;
FusionMapper* mFusionMapper;
};
#endif | Java |
/**
* Module dependencies.
*/
var express = require('express')
var MemoryStore = express.session.MemoryStore
var mongoStore = require('connect-mongo')(express)
var path = require('path')
var fs = require('fs')
var _ = require('underscore')
var mongoose = require('mongoose')
var passport = require('passport')
var http = require('http')
var socketio = require('socket.io')
var passportSocketIo = require('passport.socketio')
// Load configurations
var env = process.env.NODE_ENV || 'development'
var config = require('./config/config')[env]
// Bootstrap db connection
mongoose.connect(config.db)
// Bootstrap models
var modelsDir = path.join(__dirname, '/app/models')
fs.readdirSync(modelsDir).forEach(function (file) {
if (~file.indexOf('.js')) require(modelsDir + '/' + file)
})
// Bootstrap passport config
require('./config/passport')(passport, config)
var app = express()
var store = new mongoStore({ url : config.db, collection : 'sessions' });
//var store = new MemoryStore()
// express settings
require('./config/express')(app, config, passport, store)
// Bootstrap routes
require('./config/routes')(app, passport)
var server = http.createServer(app)
var sio = socketio.listen(server)
var clients = {}
var socketsOfClients = {}
sio.configure(function () {
sio.set('authorization', passportSocketIo.authorize({
cookieParser: express.cookieParser, //or connect.cookieParser
key: 'express.sid', //the cookie where express (or connect) stores the session id.
secret: 'dirty', //the session secret to parse the cookie
store: store, //the session store that express uses
fail: function (data, accept) { // *optional* callbacks on success or fail
accept(null, false) // second parameter takes boolean on whether or not to allow handshake
},
success: function (data, accept) {
accept(null, true)
}
}))
})
// upon connection, start a periodic task that emits (every 1s) the current timestamp
sio.sockets.on('connection', function (socket) {
var username = socket.handshake.user.username;
clients[username] = socket.id
socketsOfClients[socket.id] = username
userNameAvailable(socket.id, username)
userJoined(username)
socket.on('data', function (data) {
socket.broadcast.emit('data', { 'drawing' : data })
})
socket.on('message', function (data) {
var now = new Date();
sio.sockets.emit('message', {
'source': socketsOfClients[socket.id],
'time': now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds(),
'message': data.message
})
})
socket.on('disconnect', function() {
var username = socketsOfClients[socket.id]
delete socketsOfClients[socket.id]
delete clients[username];
// relay this message to all the clients
userLeft(username)
})
})
// Start the application by listening on port <>
var port = process.env.PORT || 3000
server.listen(port, function(){
console.log('Express server listening on port ' + port)
});
function userNameAvailable(socketId, username) {
setTimeout(function(){
sio.sockets.sockets[socketId].emit('user welcome', {
"currentUsers": JSON.stringify(Object.keys(clients))
});
}, 500);
}
function userJoined(username) {
Object.keys(socketsOfClients).forEach(function(socketId) {
sio.sockets.sockets[socketId].emit('user joined', {
"username": username
});
});
}
function userLeft(username) {
sio.sockets.emit('user left', {
"username": username
});
}
// expose app
exports = module.exports = app;
| Java |
#guimporter.py
import sys
from PySide import QtGui, QtCore, QtWebKit
Signal = QtCore.Signal | Java |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SearchForANumber")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SearchForANumber")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fe6220fa-63b8-4168-9867-f466b571c2a5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Java |
'use strict';
var redis = require('redis')
, xtend = require('xtend')
, hyperquest = require('hyperquest')
;
module.exports = FetchAndCache;
/**
* Creates a fetchncache instance.
*
* #### redis opts
*
* - **opts.redis.host** *{number=}* host at which redis is listening, defaults to `127.0.0.1`
* - **opts.redis.port** *{string=}* port at which redis is listening, defaults to `6379`
*
* #### service opts
*
* - **opts.service.url** *{string=}* url at which to reach the service
*
* @name fetchncache
* @function
* @param {Object=} opts
* @param {Object=} opts.redis redis options passed straight to [redis](https://github.com/mranney/node_redis) (@see above)
* @param {Object=} opts.service options specifying how to reach the service that provides the data (@see above)
* @param {number=} opts.expire the default number of seconds after which to expire a resource from the redis cache (defaults to 15mins)
* @return {Object} fetchncache instance
*/
function FetchAndCache(opts) {
if (!(this instanceof FetchAndCache)) return new FetchAndCache(opts);
opts = opts || {};
var redisOpts = xtend({ port: 6379, host: '127.0.0.1' }, opts.redis)
, serviceOpts = xtend({ url: 'http://127.0.0.1' }, opts.service)
this._defaultExpire = opts.expire || 15 * 60 // 15min
this._serviceOpts = serviceOpts;
this._markCached = opts.markCached !== false;
this._client = redis.createClient(redisOpts.port, redisOpts.host, redisOpts)
}
var proto = FetchAndCache.prototype;
/**
* Fetches the resource, probing the redis cache first and falling back to the service.
* If a transform function is provided (@see opts), that is applied to the result before returning or caching it.
* When fetched from the service it is added to the redis cached according to the provided options.
*
* @name fetcncache::fetch
* @function
* @param {string} uri path to the resource, i.e. `/reource1?q=1234`
* @param {Object=} opts configure caching and transformation behavior for this particular resource
* @param {number=} opts.expire overrides default expire for this particular resource
* @param {function=} opts.transform specify the transform function to be applied, default: `function (res} { return res }`
* @param {function} cb called back with an error or the transformed resource
*/
proto.fetch = function (uri, opts, cb) {
var self = this;
if (!self._client) return cb(new Error('fetchncache was stopped and can no longer be used to fetch data'));
if (typeof opts === 'function') {
cb = opts;
opts = null;
}
opts = xtend({ expire: self._defaultExpire, transform: function (x) { return x } }, opts);
self._client.get(uri, function (err, res) {
if (err) return cb(err);
if (res) return cb(null, res, true);
self._get(uri, function (err, res) {
if (err) return cb(err);
self._cache(uri, res, opts, cb);
})
});
}
/**
* Stops the redis client in order to allow exiting the application.
* At this point this fetchncache instance becomes unusable and throws errors on any attempts to use it.
*
* @name fetchncache::stop
* @function
* @param {boolean=} force will make it more aggressive about ending the underlying redis client (default: false)
*/
proto.stop = function (force) {
if (!this._client) throw new Error('fetchncache was stopped previously and cannot be stopped again');
if (force) this._client.end(); else this._client.unref();
this._client = null;
}
/**
* Clears the entire redis cache, so use with care.
* Mainly useful for testing or to ensure that all resources get refreshed.
*
* @name fetchncache::clearCache
* @function
* @return {Object} fetchncache instance
*/
proto.clearCache = function () {
if (!this._client) throw new Error('fetchncache was stopped previously and cannot be cleared');
this._client.flushdb();
return this;
}
proto._get = function (uri, cb) {
var body = '';
var url = this._serviceOpts.url + uri;
console.log('url', url);
hyperquest
.get(url)
.on('error', cb)
.on('data', function (d) { body += d.toString() })
.on('end', function () { cb(null, body) })
}
proto._cache = function (uri, res, opts, cb) {
var self = this;
var val;
try {
val = opts.transform(res);
} catch (e) {
return cb(e);
}
// assuming that value is now a string we use set to add it
self._client.set(uri, val, function (err) {
if (err) return cb(err);
self._client.expire(uri, opts.expire, function (err) {
if (err) return cb(err);
cb(null, val);
})
});
}
| Java |
package org.blendee.jdbc;
/**
* プレースホルダを持つ SQL 文と、プレースホルダにセットする値を持つものを表すインターフェイスです。
* @author 千葉 哲嗣
*/
public interface ComposedSQL extends ChainPreparedStatementComplementer {
/**
* このインスタンスが持つ SQL 文を返します。
* @return SQL 文
*/
String sql();
/**
* {@link PreparedStatementComplementer} を入れ替えた新しい {@link ComposedSQL} を生成します。
* @param complementer 入れ替える {@link PreparedStatementComplementer}
* @return 同じ SQL を持つ、別のインスタンス
*/
default ComposedSQL reproduce(PreparedStatementComplementer complementer) {
var sql = sql();
return new ComposedSQL() {
@Override
public String sql() {
return sql;
}
@Override
public int complement(int done, BPreparedStatement statement) {
complementer.complement(statement);
return Integer.MIN_VALUE;
}
};
}
/**
* {@link ChainPreparedStatementComplementer} を入れ替えた新しい {@link ComposedSQL} を生成します。
* @param complementer 入れ替える {@link ChainPreparedStatementComplementer}
* @return 同じ SQL を持つ、別のインスタンス
*/
default ComposedSQL reproduce(ChainPreparedStatementComplementer complementer) {
var sql = sql();
return new ComposedSQL() {
@Override
public String sql() {
return sql;
}
@Override
public int complement(int done, BPreparedStatement statement) {
return complementer.complement(done, statement);
}
};
}
}
| Java |
# basic-data-structure
basic data strcture in python from THU Data Structure 3rd Edition, including:
* Vector (Chapter 2)
* LinkedList (Chapter 3)
* Stack based on Vector and LinkedList (Chapter 4)
* Queue based on Vector and LinkedList (Chapter 4)
* Deque based on Vector and LinkedList (Chapter 4)
* BinTree based on BinNode (Chapter 5)
* GraphMatrix based on Vector and Edge (Chapter 6)
* GraphList based on Vector and Edge (Chapter 6)
* DisjointSet based on Vector and Edge (Chapter 6)
* BinSearchTree based on BinTree (Chapter 7)
* AVLTree based on BinSearchTree (Chapter 7)
* SkipList based on LinkedList (Chapter 9)
* HashTable (Chapter 9)
* Bucket for bucket sort (Chapter 9)
* Heap (Chapter 10)
| Java |
<TS language="es_419" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Right-click to edit address or label</source>
<translation>Haga clic para editar la dirección o etiqueta</translation>
</message>
<message>
<source>Create a new address</source>
<translation>Crear una nueva dirección</translation>
</message>
<message>
<source>&New</source>
<translation>&New</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copia la dirección seleccionada al portapapeles del sistema</translation>
</message>
<message>
<source>Delete the currently selected address from the list</source>
<translation>Borrar la dirección que esta seleccionada en la lista</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Exportar los datos de la actual tabla hacia un archivo</translation>
</message>
<message>
<source>Choose the address to send coins to</source>
<translation>Seleccione la dirección a la que enviará las monedas</translation>
</message>
<message>
<source>Choose the address to receive coins with</source>
<translation>Seleccione la dirección con la que recibirá las monedas</translation>
</message>
<message>
<source>Sending addresses</source>
<translation>Enviando direcciones</translation>
</message>
<message>
<source>Receiving addresses</source>
<translation>Recibiendo direcciones</translation>
</message>
<message>
<source>These are your Pandacoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Estas son sus direcciones de Pandacoin para enviar sus pagos. Siempre revise el monto y la dirección recibida antes de enviar monedas.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
</context>
<context>
<name>AskPassphraseDialog</name>
</context>
<context>
<name>BanTableModel</name>
</context>
<context>
<name>BitcoinGUI</name>
</context>
<context>
<name>CoinControlDialog</name>
</context>
<context>
<name>EditAddressDialog</name>
</context>
<context>
<name>FreespaceChecker</name>
</context>
<context>
<name>HelpMessageDialog</name>
</context>
<context>
<name>Intro</name>
</context>
<context>
<name>ModalOverlay</name>
</context>
<context>
<name>OpenURIDialog</name>
</context>
<context>
<name>OptionsDialog</name>
</context>
<context>
<name>OverviewPage</name>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
</context>
<context>
<name>QObject</name>
</context>
<context>
<name>QObject::QObject</name>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
</context>
<context>
<name>ReceiveCoinsDialog</name>
</context>
<context>
<name>ReceiveRequestDialog</name>
</context>
<context>
<name>RecentRequestsTableModel</name>
</context>
<context>
<name>SendCoinsDialog</name>
</context>
<context>
<name>SendCoinsEntry</name>
</context>
<context>
<name>SendConfirmationDialog</name>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
</context>
<context>
<name>SplashScreen</name>
</context>
<context>
<name>TrafficGraphWidget</name>
</context>
<context>
<name>TransactionDesc</name>
</context>
<context>
<name>TransactionDescDialog</name>
</context>
<context>
<name>TransactionTableModel</name>
</context>
<context>
<name>TransactionView</name>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
</context>
<context>
<name>WalletView</name>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Exportar los datos de la actual tabla hacia un archivo</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
</context>
</TS>
| Java |
package com.github.sixro.minihabits.core.infrastructure.domain;
import java.util.*;
import com.badlogic.gdx.Preferences;
import com.github.sixro.minihabits.core.domain.*;
public class PreferencesBasedRepository implements Repository {
private final Preferences prefs;
public PreferencesBasedRepository(Preferences prefs) {
super();
this.prefs = prefs;
}
@Override
public Set<MiniHabit> findAll() {
String text = prefs.getString("mini_habits");
if (text == null || text.trim().isEmpty())
return new LinkedHashSet<MiniHabit>();
return newMiniHabits(text);
}
@Override
public void add(MiniHabit miniHabit) {
Set<MiniHabit> list = findAll();
list.add(miniHabit);
prefs.putString("mini_habits", asString(list));
prefs.flush();
}
@Override
public void update(Collection<MiniHabit> list) {
Set<MiniHabit> currentList = findAll();
currentList.removeAll(list);
currentList.addAll(list);
prefs.putString("mini_habits", asString(currentList));
prefs.flush();
}
@Override
public void updateProgressDate(DateAtMidnight aDate) {
prefs.putLong("last_feedback_timestamp", aDate.getTime());
prefs.flush();
}
@Override
public DateAtMidnight lastFeedbackDate() {
long timestamp = prefs.getLong("last_feedback_timestamp");
if (timestamp == 0L)
return null;
return DateAtMidnight.from(timestamp);
}
private Set<MiniHabit> newMiniHabits(String text) {
String[] parts = text.split(",");
Set<MiniHabit> ret = new LinkedHashSet<MiniHabit>();
for (String part: parts)
ret.add(newMiniHabit(part));
return ret;
}
private MiniHabit newMiniHabit(String part) {
int indexOfColon = part.indexOf(':');
String label = part.substring(0, indexOfColon);
Integer daysInProgress = Integer.parseInt(part.substring(indexOfColon +1));
MiniHabit habit = new MiniHabit(label, daysInProgress);
return habit;
}
private String asString(Collection<MiniHabit> list) {
StringBuilder b = new StringBuilder();
int i = 0;
for (MiniHabit each: list) {
b.append(each.label() + ":" + each.daysInProgress());
if (i < list.size()-1)
b.append(',');
i++;
}
return b.toString();
}
}
| Java |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
let _ = require('lodash');
let async = require('async');
const pip_services3_commons_node_1 = require("pip-services3-commons-node");
const pip_services3_facade_node_1 = require("pip-services3-facade-node");
class RolesOperationsV1 extends pip_services3_facade_node_1.FacadeOperations {
constructor() {
super();
this._dependencyResolver.put('roles', new pip_services3_commons_node_1.Descriptor('pip-services-roles', 'client', '*', '*', '1.0'));
}
setReferences(references) {
super.setReferences(references);
this._rolesClient = this._dependencyResolver.getOneRequired('roles');
}
getUserRolesOperation() {
return (req, res) => {
this.getUserRoles(req, res);
};
}
grantUserRolesOperation() {
return (req, res) => {
this.grantUserRoles(req, res);
};
}
revokeUserRolesOperation() {
return (req, res) => {
this.revokeUserRoles(req, res);
};
}
getUserRoles(req, res) {
let userId = req.route.params.user_id;
this._rolesClient.getRolesById(null, userId, this.sendResult(req, res));
}
grantUserRoles(req, res) {
let userId = req.route.params.user_id;
let roles = req.body;
this._rolesClient.grantRoles(null, userId, roles, this.sendResult(req, res));
}
revokeUserRoles(req, res) {
let userId = req.route.params.user_id;
let roles = req.body;
this._rolesClient.revokeRoles(null, userId, roles, this.sendResult(req, res));
}
}
exports.RolesOperationsV1 = RolesOperationsV1;
//# sourceMappingURL=RolesOperationsV1.js.map | Java |
local core = require ("core")
local function echo (prefix, channel, suffix)
core:respond (channel, "My life meaning: Marry Ratbot!")
end
core:addCommand ("meaning", echo)
| Java |
require_relative 'rules_factory_common'
FactoryBot.define do
factory :priority_bills, parent: :answers do
factory :S6_H1_missed_payment_low, traits: [:country, :S6_H1_missed_payment_low_answers]
factory :S6_H2_council_tax_severe, traits: [:country, :S6_H2_tax_severe_answers]
factory :S6_H2_domestic_rates_severe, traits: [:country, :S6_H2_tax_severe_answers]
factory :S6_H2_council_tax_temp_worried, traits: [:country, :S6_H2_tax_temp_worried_answers]
factory :S6_H2_domestic_rates_temp_worried, traits: [:country, :S6_H2_tax_temp_worried_answers]
factory :S6_H2_council_tax_temp_normal, traits: [:country, :S6_H2_tax_temp_normal_answers]
factory :S6_H2_domestic_rates_temp_normal, traits: [:country, :S6_H2_tax_temp_normal_answers]
factory :S6_H2_council_tax_no_change, traits: [:country, :S6_H2_tax_no_change_answers]
factory :S6_H2_domestic_rates_no_change, traits: [:country, :S6_H2_tax_no_change_answers]
factory :S6_H3_gas_electricity_severe, traits: [:country, :S6_H3_gas_electricity_severe_answers]
factory :S6_H3_gas_electricity_temp_worried, traits: [:country, :S6_H3_gas_electricity_temp_worried_answers]
factory :S6_H3_gas_electricity_temp_normal, traits: [:country, :S6_H3_gas_electricity_temp_normal_answers]
factory :S6_H3_gas_electricity_no_change, traits: [:country, :S6_H3_gas_electricity_no_change_answers]
factory :S6_H4_dmp_hmrc_severe, traits: [:country, :S6_H4_dmp_hmrc_severe_answers]
factory :S6_H4_dmp_hmrc_temp_worried, traits: [:country, :S6_H4_dmp_hmrc_temp_worried_answers]
factory :S6_H4_dmp_hmrc_temp_normal, traits: [:country, :S6_H4_dmp_hmrc_temp_normal_answers]
factory :S6_H4_dmp_hmrc_no_change, traits: [:country, :S6_H4_dmp_hmrc_no_change_answers]
factory :S6_H5_tv_licence_severe, traits: [:country, :S6_H5_tv_licence_severe_answers]
factory :S6_H5_tv_licence_temp_worried, traits: [:country, :S6_H5_tv_licence_temp_worried_answers]
factory :S6_H5_tv_licence_temp_normal, traits: [:country, :S6_H5_tv_licence_temp_normal_answers]
factory :S6_H5_tv_licence_no_change, traits: [:country, :S6_H5_tv_licence_no_change_answers]
factory :S6_H6_income_tax_severe, traits: [:country, :S6_H6_income_tax_severe_answers]
factory :S6_H6_income_tax_temp_worried, traits: [:country, :S6_H6_income_tax_temp_worried_answers]
factory :S6_H6_income_tax_temp_normal, traits: [:country, :S6_H6_income_tax_temp_normal_answers]
factory :S6_H6_income_tax_no_change, traits: [:country, :S6_H6_income_tax_no_change_answers]
factory :S6_H7_child_maintenance_severe, traits: [:country, :S6_H7_child_maintenance_severe_answers]
factory :S6_H7_child_maintenance_temp_worried, traits: [:country, :S6_H7_child_maintenance_temp_worried_answers]
factory :S6_H7_child_maintenance_temp_normal, traits: [:country, :S6_H7_child_maintenance_temp_normal_answers]
factory :S6_H7_child_maintenance_no_change, traits: [:country, :S6_H7_child_maintenance_no_change_answers]
factory :S6_H8_court_fines_severe, traits: [:country, :S6_H8_court_fines_severe_answers]
factory :S6_H8_court_fines_temp_worried, traits: [:country, :S6_H8_court_fines_temp_worried_answers]
factory :S6_H8_court_fines_temp_normal, traits: [:country, :S6_H8_court_fines_temp_normal_answers]
factory :S6_H8_court_fines_temp_normal_ni, traits: [:country, :S6_H8_court_fines_temp_normal_ni_answers]
factory :S6_H8_court_fines_temp_normal_scotland, traits: [:country, :S6_H8_court_fines_temp_normal_scotland_answers]
factory :S6_H8_court_fines_no_change, traits: [:country, :S6_H8_court_fines_no_change_answers]
factory :S6_H9_hire_purchase_severe, traits: [:country, :S6_H9_hire_purchase_severe_answers]
factory :S6_H9_hire_purchase_temp_worried, traits: [:country, :S6_H9_hire_purchase_temp_worried_answers]
factory :S6_H9_hire_purchase_temp_normal, traits: [:country, :S6_H9_hire_purchase_temp_normal_answers]
factory :S6_H9_hire_purchase_no_change, traits: [:country, :S6_H9_hire_purchase_no_change_answers]
factory :S6_H10_car_park_severe, traits: [:country, :S6_H10_car_park_severe_answers]
factory :S6_H10_car_park_temp_worried, traits: [:country, :S6_H10_car_park_temp_worried_answers]
factory :S6_H10_car_park_temp_normal, traits: [:country, :S6_H10_car_park_temp_normal_answers]
factory :S6_H10_car_park_temp_normal_ni, traits: [:country, :S6_H10_car_park_temp_normal_ni_answers]
factory :S6_H10_car_park_temp_normal_scotland, traits: [:country, :S6_H10_car_park_temp_normal_scotland_answers]
factory :S6_H10_car_park_no_change, traits: [:country, :S6_H10_car_park_no_change_answers]
trait :S6_H1_missed_payment_low_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', [], nil) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H2_tax_severe_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a1'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a1'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H2_tax_temp_worried_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a2'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a1'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H2_tax_temp_normal_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a3'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a1'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H2_tax_no_change_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a4'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a1'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H3_gas_electricity_severe_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a1'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a2'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H3_gas_electricity_temp_worried_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a2'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a2'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H3_gas_electricity_temp_normal_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a3'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a2'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H3_gas_electricity_no_change_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a4'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a2'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H4_dmp_hmrc_severe_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a1'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a3'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H4_dmp_hmrc_temp_worried_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a2'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a3'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H4_dmp_hmrc_temp_normal_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a3'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a3'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H4_dmp_hmrc_no_change_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a4'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a3'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H5_tv_licence_severe_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a1'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a4'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H5_tv_licence_temp_worried_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a2'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a4'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H5_tv_licence_temp_normal_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a3'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a4'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H5_tv_licence_no_change_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a4'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a4'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H6_income_tax_severe_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a1'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a5'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H6_income_tax_temp_worried_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a2'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a5'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H6_income_tax_temp_normal_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a3'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a5'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H6_income_tax_no_change_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a4'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a5'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H7_child_maintenance_severe_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a1'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a6'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H7_child_maintenance_temp_worried_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a2'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a6'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H7_child_maintenance_temp_normal_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a3'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a6'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H7_child_maintenance_no_change_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a4'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a6'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H8_court_fines_severe_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a1'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a7'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H8_court_fines_temp_worried_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a2'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a7'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H8_court_fines_temp_normal_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a3'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a7'], []) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H8_court_fines_temp_normal_ni_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a3'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a7'], []) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H8_court_fines_temp_normal_scotland_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a3'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a7'], []) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H8_court_fines_no_change_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a4'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a7'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H9_hire_purchase_severe_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a1'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a8'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H9_hire_purchase_temp_worried_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a2'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a8'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H9_hire_purchase_temp_normal_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a3'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a8'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H9_hire_purchase_no_change_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a4'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a8'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H10_car_park_severe_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a1'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a9'], []) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H10_car_park_temp_worried_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a2'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a9'], []) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H10_car_park_temp_normal_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a3'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a9'], nil) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H10_car_park_temp_normal_ni_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a3'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a9'], []) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H10_car_park_temp_normal_scotland_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a3'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a9'], []) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
trait :S6_H10_car_park_no_change_answers do
q1 { answers_with_entropy('q1', [], nil) }
q2 { answers_with_entropy('q2', [], nil) }
q3 { answers_with_entropy('q3', [], nil) }
q4 { answers_with_entropy('q4', ['a4'], []) }
q5 { answers_with_entropy('q5', [], nil) }
q6 { answers_with_entropy('q6', [], nil) }
q7 { answers_with_entropy('q7', ['a9'],[] ) }
q8 { answers_with_entropy('q8', [], nil) }
q9 { answers_with_entropy('q9', [], nil) }
q11 { answers_with_entropy('q11', [], nil) }
q12 { answers_with_entropy('q12', [], nil) }
q13 { answers_with_entropy('q13', [], nil) }
q14 { answers_with_entropy('q14', [], nil) }
end
end
end
| Java |
var config = require('../lib/config')();
var Changeset = require('./Changeset');
var queries = require('./queries');
var helpers = require('../helpers');
require('../validators');
var validate = require('validate.js');
var errors = require('../errors');
var pgPromise = helpers.pgPromise;
var promisifyQuery = helpers.promisifyQuery;
var changesets = {};
module.exports = changesets;
var pgURL = config.PostgresURL;
changesets.search = function(params) {
var parseError = validateParams(params);
if (parseError) {
return Promise.reject(new errors.ParseError(parseError));
}
var searchQuery = queries.getSearchQuery(params);
var countQuery = queries.getCountQuery(params);
console.log('searchQ', searchQuery);
console.log('countQ', countQuery);
return pgPromise(pgURL)
.then(function (pg) {
var query = promisifyQuery(pg.client);
var searchProm = query(searchQuery.text, searchQuery.values);
var countProm = query(countQuery.text, countQuery.values);
return Promise.all([searchProm, countProm])
.then(function (r) {
pg.done();
return r;
})
.catch(function (e) {
pg.done();
return Promise.reject(e);
});
})
.then(processSearchResults);
};
changesets.get = function(id) {
if (!validate.isNumber(parseInt(id, 10))) {
return Promise.reject(new errors.ParseError('Changeset id must be a number'));
}
var changesetQuery = queries.getChangesetQuery(id);
var changesetCommentsQuery = queries.getChangesetCommentsQuery(id);
return pgPromise(pgURL)
.then(function (pg) {
var query = promisifyQuery(pg.client);
var changesetProm = query(changesetQuery.text, changesetQuery.values);
var changesetCommentsProm = query(changesetCommentsQuery.text, changesetCommentsQuery.values);
return Promise.all([changesetProm, changesetCommentsProm])
.then(function (results) {
pg.done();
return results;
})
.catch(function (e) {
pg.done();
return Promise.reject(e);
});
})
.then(function (results) {
var changesetResult = results[0];
if (changesetResult.rows.length === 0) {
return Promise.reject(new errors.NotFoundError('Changeset not found'));
}
var changeset = new Changeset(results[0].rows[0], results[1].rows);
return changeset.getGeoJSON();
});
};
function processSearchResults(results) {
var searchResult = results[0];
var countResult = results[1];
var changesetsArray = searchResult.rows.map(function (row) {
var changeset = new Changeset(row);
return changeset.getGeoJSON();
});
var count;
if (countResult.rows.length > 0) {
count = countResult.rows[0].count;
} else {
count = 0;
}
var featureCollection = {
'type': 'FeatureCollection',
'features': changesetsArray,
'total': count
};
return featureCollection;
}
function validateParams(params) {
var constraints = {
'from': {
'presence': false,
'datetime': true
},
'to': {
'presence': false,
'datetime': true
},
'bbox': {
'presence': false,
'bbox': true
}
};
var errs = validate(params, constraints);
if (errs) {
var errMsg = Object.keys(errs).map(function(key) {
return errs[key][0];
}).join(', ');
return errMsg;
}
return null;
} | Java |
# Nancy.Rest.Client
Dynamic proxy client generation for [Nancy](http://nancyfx.org) using [Nancy.Rest.Module](https://github.com/maxpiva/Nancy.Rest.Module).
## Prerequisites
A server using [Nancy](http://nancyfx.org) & [Nancy.Rest.Module](https://github.com/maxpiva/Nancy.Rest.Module).
It is recommended you read the [Nancy.Rest.Module](https://github.com/maxpiva/Nancy.Rest.Module) documentation to understand how the server mount the services before continuing reading.
## Installation
* Add [Nancy.Rest.Client](https://github.com/maxpiva/Nancy.Rest.Client) and [Nancy.Rest.Annotations](https://github.com/maxpiva/Nancy.Rest.Annotations) to your client project.
Or
* Add the Nuget package [Nancy.Rest.Client](https://www.nuget.org/packages/Nancy.Rest.Client/)
Add your server models and interface with the method signatures to use.
## Basic Usage
####Your Server signatures:
```csharp
namespace Nancy.Rest.ExampleServer
{
[RestBasePath("/api")]
public interface IExample
{
[Rest("Person", Verbs.Get)]
List<Person> GetAllPersons();
[Rest("Person/{personid}", Verbs.Get)]
Person GetPerson(int personid);
[Rest("Person", Verbs.Post)]
bool SavePerson(Person person);
[Rest("Person/{personid}", Verbs.Delete)]
bool DeletePerson(int personid);
}
}
```
####Your Server Models
```csharp
namespace Nancy.Rest.ExampleServer
{
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
[Level(1)]
public bool IsProgrammer { get; set; }
[Tags("Attr")]
public List<string> Attributes { get; set; }
}
}
```
#### Your Client
```csharp
namespace Nancy.Rest.ExampleClient
{
public class Example
{
public void Run()
{
IExample server=ClientFactory.Create<IExample>("http://yourserver/api"); `
List<Person> persons=server.GetPersons();
}
}
}
```
##Advanced Usage
###Transversal Filtering
[Nancy.Rest.Client](https://github.com/maxpiva/Nancy.Rest.Client) includes this interface.
```csharp
using System.Collections.Generic;
namespace Nancy.Rest.Client.Interfaces
{
public interface IFilter<T>
{
T FilterWithLevel(int level);
T FilterWithTags(IEnumerable<string> tags);
T FilterWithLevelAndTags(int level, IEnumerable<string> tags);
}
}
```
Create a new interface in your client that includes, both, [IFilter](https://github.com/maxpiva/Nancy.Rest.Client/blob/master/Interfaces/IFilter.cs) interface and your server interface.
```csharp
namespace Nancy.Rest.ExampleClient
{
public interface IExampleWithFiltering : IExample, IFilter<IExample>
{
}
}
```
Then you can use the transversal filtering capabilities of the server like this:
```csharp
namespace Nancy.Rest.ExampleClient
{
public class Example
{
public void Run()
{
IExampleWithFiltering server=ClientFactory.Create<IExampleWithFiltering>("http://yourserver/api"); `
//Per example, you can ask the server to not serialize any property with level bigger than the number provided.
//Here we can filter the IsProgrammer property using levels.
List<Person> persons=server.FilterWithLevel(0).GetPersons();
//Or remove the Attributes property using Tags.
List<Person> persons=server.FilterWithTags(new string[] { "Attr"}).GetPersons();
}
}
}
```
###Controlable deserialization
Imagine you have your poco models from the server, but you need to add some properties, methods or INotifyPropertyChanged to that objects, you create a child class from the model, and add all those things. The problem is, the deserialzer will deserialize your poco model, so you have to create a new child class, and copy all properties to your child. Nancy.Rest.Client have the capability of deserializing the objects to child objects.
####Client model
```csharp
namespace Nancy.Rest.ExampleClient
{
public class ClientPerson : Person
{
public bool IsSuperman { get; set; }
public void DoSomeNastyThings()
{
//Kidding
}
}
}
```
####Example
```csharp
namespace Nancy.Rest.ExampleClient
{
public class Example
{
public void Run()
{
Dictionary<Type,Type> mappings=new Dictionary<Type,Type>();
//Here we add the mapping, we want every person to be deserialized as ClientPerson
mappings.Add(typeof(Person), typeof(ClientPerson));
IExample server=ClientFactory.Create<IExample>("http://yourserver/api", mappings); `
//Here is your list of client persons
List<ClientPerson> persons=server.GetPersons().Cast<ClientPerson>.ToList();
}
}
}
```
##WARNING
THIS IS AN BETA VERSION, so far it works on my machine ;)
## TODO
* Fill the blanks :P
## History
**1.4.3-Beta**: Removed bugs, published nugets.
**1.4.3-Alpha**: First Release
## Built With
* [JSON.Net](newtonsoft.com/json/)
* [impromptu-interface](https://github.com/ekonbenefits/impromptu-interface)
## Credits
* **Maximo Piva** - [maxpiva](https://github.com/maxpiva)
## License
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
| Java |
Setlocal EnableDelayedExpansion
@rem BUILD SOLUTIONS
C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild META\make.msbuild /t:All /m /nodeReuse:false || exit /b !ERRORLEVEL!
C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild tonka\make.msbuild /t:All /m /nodeReuse:false || exit /b !ERRORLEVEL!
@rem RUN TONKA TESTS
del tonka\test\*_result.xml
del tonka\test\*_results.xml
tonka\run_tests_console_output_xml_parallel.py || exit /b !ERRORLEVEL!
@rem RUN META TESTS
del META\test\*_result.xml
del META\test\*_results.xml
c:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild META\test\run.msbuild || exit /b !ERRORLEVEL!
@rem BUILD INSTALLER
pushd META\deploy
..\bin\Python27\Scripts\python.exe build_msi.py || (popd & exit /b !ERRORLEVEL!)
popd | Java |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System;
using System.Windows.Automation.Peers;
using System.Windows.Media;
using System.Windows.Threading;
using MS.Internal.KnownBoxes;
namespace System.Windows.Controls.Primitives
{
/// <summary>
/// StatusBar is a visual indicator of the operational status of an application and/or
/// its components running in a window. StatusBar control consists of a series of zones
/// on a band that can display text, graphics, or other rich content. The control can
/// group items within these zones to emphasize relational similarities or functional
/// connections. The StatusBar can accommodate multiple sets of UI or functionality that
/// can be chosen even within the same application.
/// </summary>
[StyleTypedProperty(Property = "ItemContainerStyle", StyleTargetType = typeof(StatusBarItem))]
public class StatusBar : ItemsControl
{
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
#region Constructors
static StatusBar()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(StatusBar), new FrameworkPropertyMetadata(typeof(StatusBar)));
_dType = DependencyObjectType.FromSystemTypeInternal(typeof(StatusBar));
IsTabStopProperty.OverrideMetadata(typeof(StatusBar), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox));
ItemsPanelTemplate template = new ItemsPanelTemplate(new FrameworkElementFactory(typeof(DockPanel)));
template.Seal();
ItemsPanelProperty.OverrideMetadata(typeof(StatusBar), new FrameworkPropertyMetadata(template));
}
#endregion
#region Public Properties
/// <summary>
/// DependencyProperty for ItemContainerTemplateSelector property.
/// </summary>
public static readonly DependencyProperty ItemContainerTemplateSelectorProperty =
MenuBase.ItemContainerTemplateSelectorProperty.AddOwner(
typeof(StatusBar),
new FrameworkPropertyMetadata(new DefaultItemContainerTemplateSelector()));
/// <summary>
/// DataTemplateSelector property which provides the DataTemplate to be used to create an instance of the ItemContainer.
/// </summary>
public ItemContainerTemplateSelector ItemContainerTemplateSelector
{
get { return (ItemContainerTemplateSelector)GetValue(ItemContainerTemplateSelectorProperty); }
set { SetValue(ItemContainerTemplateSelectorProperty, value); }
}
/// <summary>
/// DependencyProperty for UsesItemContainerTemplate property.
/// </summary>
public static readonly DependencyProperty UsesItemContainerTemplateProperty =
MenuBase.UsesItemContainerTemplateProperty.AddOwner(typeof(StatusBar));
/// <summary>
/// UsesItemContainerTemplate property which says whether the ItemContainerTemplateSelector property is to be used.
/// </summary>
public bool UsesItemContainerTemplate
{
get { return (bool)GetValue(UsesItemContainerTemplateProperty); }
set { SetValue(UsesItemContainerTemplateProperty, value); }
}
#endregion
//-------------------------------------------------------------------
//
// Protected Methods
//
//-------------------------------------------------------------------
#region Protected Methods
private object _currentItem;
/// <summary>
/// Return true if the item is (or is eligible to be) its own ItemUI
/// </summary>
protected override bool IsItemItsOwnContainerOverride(object item)
{
bool ret = (item is StatusBarItem) || (item is Separator);
if (!ret)
{
_currentItem = item;
}
return ret;
}
protected override DependencyObject GetContainerForItemOverride()
{
object currentItem = _currentItem;
_currentItem = null;
if (UsesItemContainerTemplate)
{
DataTemplate itemContainerTemplate = ItemContainerTemplateSelector.SelectTemplate(currentItem, this);
if (itemContainerTemplate != null)
{
object itemContainer = itemContainerTemplate.LoadContent();
if (itemContainer is StatusBarItem || itemContainer is Separator)
{
return itemContainer as DependencyObject;
}
else
{
throw new InvalidOperationException(SR.Get(SRID.InvalidItemContainer, this.GetType().Name, typeof(StatusBarItem).Name, typeof(Separator).Name, itemContainer));
}
}
}
return new StatusBarItem();
}
/// <summary>
/// Prepare the element to display the item. This may involve
/// applying styles, setting bindings, etc.
/// </summary>
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
base.PrepareContainerForItemOverride(element, item);
Separator separator = element as Separator;
if (separator != null)
{
bool hasModifiers;
BaseValueSourceInternal vs = separator.GetValueSource(StyleProperty, null, out hasModifiers);
if (vs <= BaseValueSourceInternal.ImplicitReference)
separator.SetResourceReference(StyleProperty, SeparatorStyleKey);
separator.DefaultStyleKey = SeparatorStyleKey;
}
}
/// <summary>
/// Determine whether the ItemContainerStyle/StyleSelector should apply to the container
/// </summary>
/// <returns>false if item is a Separator, otherwise return true</returns>
protected override bool ShouldApplyItemContainerStyle(DependencyObject container, object item)
{
if (item is Separator)
{
return false;
}
else
{
return base.ShouldApplyItemContainerStyle(container, item);
}
}
#endregion
#region Accessibility
/// <summary>
/// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>)
/// </summary>
protected override AutomationPeer OnCreateAutomationPeer()
{
return new StatusBarAutomationPeer(this);
}
#endregion
#region DTypeThemeStyleKey
// Returns the DependencyObjectType for the registered ThemeStyleKey's default
// value. Controls will override this method to return approriate types.
internal override DependencyObjectType DTypeThemeStyleKey
{
get { return _dType; }
}
private static DependencyObjectType _dType;
#endregion DTypeThemeStyleKey
#region ItemsStyleKey
/// <summary>
/// Resource Key for the SeparatorStyle
/// </summary>
public static ResourceKey SeparatorStyleKey
{
get
{
return SystemResourceKey.StatusBarSeparatorStyleKey;
}
}
#endregion
}
}
| Java |
// John Meyer
// CSE 271 F
// Dr. Angel Bravo
import java.util.Scanner;
import java.io.*;
/**
* Copies a file with line numbers prefixed to every line
*/
public class Lab2InputOutput {
public static void main(String[] args) throws Exception {
// Define variables
Scanner keyboardReader = new Scanner(System.in);
String inputFileName;
String outputFileName;
// Check arguments
if (args.length == 0) {
System.out.println("Usage: java Lab2InputOutput /path/to/file");
return;
}
inputFileName = args[0];
// Find input file
File inputFile = new File(inputFileName);
Scanner fileInput = new Scanner(inputFile);
// Get output file name
System.out.print("Output File Name: ");
outputFileName = keyboardReader.next();
File outputFile = new File(outputFileName);
// Start copying
PrintWriter fileOutput = new PrintWriter(outputFile);
String lineContent;
for (int lineNumber = 1; fileInput.hasNext(); lineNumber++) {
lineContent = fileInput.nextLine();
fileOutput.printf("/* %d */ %s%n", lineNumber, lineContent);
}
fileInput.close();
fileOutput.close();
} // end method main
} // end class Lab2InputOutput
| Java |
/*
' Copyright (c) 2013 Christoc.com Software Solutions
' All rights reserved.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
'
*/
using System;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Framework.Providers;
namespace Christoc.Modules.DNNSignalR.Data
{
/// -----------------------------------------------------------------------------
/// <summary>
/// SQL Server implementation of the abstract DataProvider class
///
/// This concreted data provider class provides the implementation of the abstract methods
/// from data dataprovider.cs
///
/// In most cases you will only modify the Public methods region below.
/// </summary>
/// -----------------------------------------------------------------------------
public class SqlDataProvider : DataProvider
{
#region Private Members
private const string ProviderType = "data";
private const string ModuleQualifier = "DNNSignalR_";
private readonly ProviderConfiguration _providerConfiguration = ProviderConfiguration.GetProviderConfiguration(ProviderType);
private readonly string _connectionString;
private readonly string _providerPath;
private readonly string _objectQualifier;
private readonly string _databaseOwner;
#endregion
#region Constructors
public SqlDataProvider()
{
// Read the configuration specific information for this provider
Provider objProvider = (Provider)(_providerConfiguration.Providers[_providerConfiguration.DefaultProvider]);
// Read the attributes for this provider
//Get Connection string from web.config
_connectionString = Config.GetConnectionString();
if (string.IsNullOrEmpty(_connectionString))
{
// Use connection string specified in provider
_connectionString = objProvider.Attributes["connectionString"];
}
_providerPath = objProvider.Attributes["providerPath"];
_objectQualifier = objProvider.Attributes["objectQualifier"];
if (!string.IsNullOrEmpty(_objectQualifier) && _objectQualifier.EndsWith("_", StringComparison.Ordinal) == false)
{
_objectQualifier += "_";
}
_databaseOwner = objProvider.Attributes["databaseOwner"];
if (!string.IsNullOrEmpty(_databaseOwner) && _databaseOwner.EndsWith(".", StringComparison.Ordinal) == false)
{
_databaseOwner += ".";
}
}
#endregion
#region Properties
public string ConnectionString
{
get
{
return _connectionString;
}
}
public string ProviderPath
{
get
{
return _providerPath;
}
}
public string ObjectQualifier
{
get
{
return _objectQualifier;
}
}
public string DatabaseOwner
{
get
{
return _databaseOwner;
}
}
// used to prefect your database objects (stored procedures, tables, views, etc)
private string NamePrefix
{
get { return DatabaseOwner + ObjectQualifier + ModuleQualifier; }
}
#endregion
#region Private Methods
private static object GetNull(object field)
{
return Null.GetNull(field, DBNull.Value);
}
#endregion
#region Public Methods
//public override IDataReader GetItem(int itemId)
//{
// return SqlHelper.ExecuteReader(ConnectionString, NamePrefix + "spGetItem", itemId);
//}
//public override IDataReader GetItems(int userId, int portalId)
//{
// return SqlHelper.ExecuteReader(ConnectionString, NamePrefix + "spGetItemsForUser", userId, portalId);
//}
#endregion
}
} | Java |
module ClassifyCluster
VERSION = "0.4.17"
end
| Java |
set Path=%PATH%;"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Bin\"
makecert -r -pe -n "CN=ChangeDynamix LLC" -sr localmachine -a sha1 -cy authority -sky signature -sv changedynamix.ca.pvk changedynamix.ca.cer
makecert -pe -n CN="WinPCAP NDIS 6.x Filter Driver" -a sha1 -sky signature -eku 1.3.6.1.5.5.7.3.3 -ic changedynamix.ca.cer -iv changedynamix.ca.pvk -sv pcap-ndis6.pvk pcap-ndis6.cer
pvk2pfx -pvk pcap-ndis6.pvk -spc pcap-ndis6.cer -pfx pcap-ndis6.pfx | Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_91) on Mon Jun 20 22:26:50 PDT 2016 -->
<title>Rational</title>
<meta name="date" content="2016-06-20">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Rational";
}
}
catch(err) {
}
//-->
var methods = {"i0":9,"i1":10,"i2":10,"i3":9,"i4":10};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-all.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="Main.html" title="class in <Unnamed>"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="RationalTest.html" title="class in <Unnamed>"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="index.html?Rational.html" target="_top">Frames</a></li>
<li><a href="Rational.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<h2 title="Class Rational" class="title">Class Rational</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>Rational</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">Rational</span>
extends java.lang.Object</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="Rational.html#Rational--">Rational</a></span>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="Rational.html#Rational-int-int-">Rational</a></span>(int num,
int denom)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="Rational.html#gcd-int-int-">gcd</a></span>(int a,
int b)</code>
<div class="block">greatest common divisor of a and b</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="Rational.html#getDenominator--">getDenominator</a></span>()</code> </td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="Rational.html#getNumerator--">getNumerator</a></span>()</code> </td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="Rational.html#main-java.lang.String:A-">main</a></span>(java.lang.String[] args)</code>
<div class="block">For testing getters.</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="Rational.html#toString--">toString</a></span>()</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="Rational--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>Rational</h4>
<pre>public Rational()</pre>
</li>
</ul>
<a name="Rational-int-int-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Rational</h4>
<pre>public Rational(int num,
int denom)</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="gcd-int-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>gcd</h4>
<pre>public static int gcd(int a,
int b)</pre>
<div class="block">greatest common divisor of a and b</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>a</code> - first number</dd>
<dd><code>b</code> - second number</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>gcd of a and b</dd>
</dl>
</li>
</ul>
<a name="toString--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>toString</h4>
<pre>public java.lang.String toString()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>toString</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
<a name="getNumerator--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getNumerator</h4>
<pre>public int getNumerator()</pre>
</li>
</ul>
<a name="getDenominator--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDenominator</h4>
<pre>public int getDenominator()</pre>
</li>
</ul>
<a name="main-java.lang.String:A-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>main</h4>
<pre>public static void main(java.lang.String[] args)</pre>
<div class="block">For testing getters.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>args</code> - unused</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-all.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="Main.html" title="class in <Unnamed>"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="RationalTest.html" title="class in <Unnamed>"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="index.html?Rational.html" target="_top">Frames</a></li>
<li><a href="Rational.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/><!-- using block title in layout.dt--><!-- using block ddox.defs in ddox.layout.dt--><!-- using block ddox.title in ddox.layout.dt-->
<title>Method Adapter.renderContext</title>
<link rel="stylesheet" type="text/css" href="../../../styles/ddox.css"/>
<link rel="stylesheet" href="../../../prettify/prettify.css" type="text/css"/>
<script type="text/javascript" src="../../../scripts/jquery.js">/**/</script>
<script type="text/javascript" src="../../../prettify/prettify.js">/**/</script>
<script type="text/javascript" src="../../../scripts/ddox.js">/**/</script>
</head>
<body onload="prettyPrint(); setupDdox();">
<nav id="main-nav"><!-- using block navigation in layout.dt-->
<ul class="tree-view">
<li class="collapsed tree-view">
<a href="#" class="package">components</a>
<ul class="tree-view">
<li>
<a href="../../../components/animation.html" class=" module">animation</a>
</li>
<li>
<a href="../../../components/assets.html" class=" module">assets</a>
</li>
<li>
<a href="../../../components/camera.html" class=" module">camera</a>
</li>
<li>
<a href="../../../components/component.html" class=" module">component</a>
</li>
<li>
<a href="../../../components/lights.html" class=" module">lights</a>
</li>
<li>
<a href="../../../components/material.html" class=" module">material</a>
</li>
<li>
<a href="../../../components/mesh.html" class=" module">mesh</a>
</li>
<li>
<a href="../../../components/userinterface.html" class=" module">userinterface</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">core</a>
<ul class="tree-view">
<li>
<a href="../../../core/dgame.html" class=" module">dgame</a>
</li>
<li>
<a href="../../../core/gameobject.html" class=" module">gameobject</a>
</li>
<li>
<a href="../../../core/prefabs.html" class=" module">prefabs</a>
</li>
<li>
<a href="../../../core/properties.html" class=" module">properties</a>
</li>
<li>
<a href="../../../core/reflection.html" class=" module">reflection</a>
</li>
<li>
<a href="../../../core/scene.html" class=" module">scene</a>
</li>
</ul>
</li>
<li class=" tree-view">
<a href="#" class="package">graphics</a>
<ul class="tree-view">
<li class=" tree-view">
<a href="#" class="package">adapters</a>
<ul class="tree-view">
<li>
<a href="../../../graphics/adapters/adapter.html" class="selected module">adapter</a>
</li>
<li>
<a href="../../../graphics/adapters/linux.html" class=" module">linux</a>
</li>
<li>
<a href="../../../graphics/adapters/mac.html" class=" module">mac</a>
</li>
<li>
<a href="../../../graphics/adapters/win32.html" class=" module">win32</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">shaders</a>
<ul class="tree-view">
<li class="collapsed tree-view">
<a href="#" class="package">glsl</a>
<ul class="tree-view">
<li>
<a href="../../../graphics/shaders/glsl/ambientlight.html" class=" module">ambientlight</a>
</li>
<li>
<a href="../../../graphics/shaders/glsl/animatedgeometry.html" class=" module">animatedgeometry</a>
</li>
<li>
<a href="../../../graphics/shaders/glsl/directionallight.html" class=" module">directionallight</a>
</li>
<li>
<a href="../../../graphics/shaders/glsl/geometry.html" class=" module">geometry</a>
</li>
<li>
<a href="../../../graphics/shaders/glsl/pointlight.html" class=" module">pointlight</a>
</li>
<li>
<a href="../../../graphics/shaders/glsl/shadowmap.html" class=" module">shadowmap</a>
</li>
<li>
<a href="../../../graphics/shaders/glsl/userinterface.html" class=" module">userinterface</a>
</li>
</ul>
</li>
<li>
<a href="../../../graphics/shaders/glsl.html" class=" module">glsl</a>
</li>
<li>
<a href="../../../graphics/shaders/shaders.html" class=" module">shaders</a>
</li>
</ul>
</li>
<li>
<a href="../../../graphics/adapters.html" class=" module">adapters</a>
</li>
<li>
<a href="../../../graphics/graphics.html" class=" module">graphics</a>
</li>
<li>
<a href="../../../graphics/shaders.html" class=" module">shaders</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">utility</a>
<ul class="tree-view">
<li>
<a href="../../../utility/awesomium.html" class=" module">awesomium</a>
</li>
<li>
<a href="../../../utility/concurrency.html" class=" module">concurrency</a>
</li>
<li>
<a href="../../../utility/config.html" class=" module">config</a>
</li>
<li>
<a href="../../../utility/filepath.html" class=" module">filepath</a>
</li>
<li>
<a href="../../../utility/input.html" class=" module">input</a>
</li>
<li>
<a href="../../../utility/output.html" class=" module">output</a>
</li>
<li>
<a href="../../../utility/resources.html" class=" module">resources</a>
</li>
<li>
<a href="../../../utility/string.html" class=" module">string</a>
</li>
<li>
<a href="../../../utility/tasks.html" class=" module">tasks</a>
</li>
<li>
<a href="../../../utility/time.html" class=" module">time</a>
</li>
</ul>
</li>
<li>
<a href="../../../components.html" class=" module">components</a>
</li>
<li>
<a href="../../../core.html" class=" module">core</a>
</li>
<li>
<a href="../../../graphics.html" class=" module">graphics</a>
</li>
<li>
<a href="../../../utility.html" class=" module">utility</a>
</li>
</ul>
<noscript>
<p style="color: red">The search functionality needs JavaScript enabled</p>
</noscript>
<div id="symbolSearchPane" style="display: none">
<p>
<input id="symbolSearch" type="text" placeholder="Search for symbols" onchange="performSymbolSearch(24);" onkeypress="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();"/>
</p>
<ul id="symbolSearchResults" style="display: none"></ul>
<script type="application/javascript" src="../../../symbols.js"></script>
<script type="application/javascript">
//<![CDATA[
var symbolSearchRootDir = "../../../"; $('#symbolSearchPane').show();
//]]>
</script>
</div>
</nav>
<div id="main-contents">
<h1>Method Adapter.renderContext</h1><!-- using block body in layout.dt--><!-- Default block ddox.description in ddox.layout.dt--><!-- Default block ddox.sections in ddox.layout.dt--><!-- using block ddox.members in ddox.layout.dt-->
<h2>Overload group</h2>
<p></p>
<section>
<h3>Prototype</h3>
<pre class="code prettyprint lang-d prototype">
void* renderContext() pure nothrow @property @safe auto final;</pre>
</section>
<h2>Overload group</h2>
<p></p>
<section>
<h3>Prototype</h3>
<pre class="code prettyprint lang-d prototype">
void renderContext(
void* newVal
) pure nothrow @property @safe final;</pre>
</section>
<section>
<h2>Authors</h2><!-- using block ddox.authors in ddox.layout.dt-->
</section>
<section>
<h2>Copyright</h2><!-- using block ddox.copyright in ddox.layout.dt-->
</section>
<section>
<h2>License</h2><!-- using block ddox.license in ddox.layout.dt-->
</section>
</div>
</body>
</html> | Java |
// Copyright 2013 The Changkong Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package dmt
const VersionNo = "20131207"
/* 图片分类 */
type PictureCategory struct {
Created string `json:"created"`
Modified string `json:"modified"`
ParentId int `json:"parent_id"`
PictureCategoryId int `json:"picture_category_id"`
PictureCategoryName string `json:"picture_category_name"`
Position int `json:"position"`
Type string `json:"type"`
}
/* 图片 */
type Picture struct {
ClientType string `json:"client_type"`
Created string `json:"created"`
Deleted string `json:"deleted"`
Md5 string `json:"md5"`
Modified string `json:"modified"`
PictureCategoryId int `json:"picture_category_id"`
PictureId int `json:"picture_id"`
PicturePath string `json:"picture_path"`
Pixel string `json:"pixel"`
Referenced bool `json:"referenced"`
Sizes int `json:"sizes"`
Status string `json:"status"`
Title string `json:"title"`
Uid int `json:"uid"`
}
/* 图片空间的用户信息获取,包括订购容量等 */
type UserInfo struct {
AvailableSpace string `json:"available_space"`
FreeSpace string `json:"free_space"`
OrderExpiryDate string `json:"order_expiry_date"`
OrderSpace string `json:"order_space"`
RemainingSpace string `json:"remaining_space"`
UsedSpace string `json:"used_space"`
WaterMark string `json:"water_mark"`
}
/* 搜索返回的结果类 */
type TOPSearchResult struct {
Paginator *TOPPaginator `json:"paginator"`
VideoItems struct {
VideoItem []*VideoItem `json:"video_item"`
} `json:"video_items"`
}
/* 分页信息 */
type TOPPaginator struct {
CurrentPage int `json:"current_page"`
IsLastPage bool `json:"is_last_page"`
PageSize int `json:"page_size"`
TotalResults int `json:"total_results"`
}
/* 视频 */
type VideoItem struct {
CoverUrl string `json:"cover_url"`
Description string `json:"description"`
Duration int `json:"duration"`
IsOpenToOther bool `json:"is_open_to_other"`
State int `json:"state"`
Tags []string `json:"tags"`
Title string `json:"title"`
UploadTime string `json:"upload_time"`
UploaderId int `json:"uploader_id"`
VideoId int `json:"video_id"`
VideoPlayInfo *VideoPlayInfo `json:"video_play_info"`
}
/* 视频播放信息 */
type VideoPlayInfo struct {
AndroidpadUrl string `json:"androidpad_url"`
AndroidpadV23Url *AndroidVlowUrl `json:"androidpad_v23_url"`
AndroidphoneUrl string `json:"androidphone_url"`
AndroidphoneV23Url *AndroidVlowUrl `json:"androidphone_v23_url"`
FlashUrl string `json:"flash_url"`
IpadUrl string `json:"ipad_url"`
IphoneUrl string `json:"iphone_url"`
WebUrl string `json:"web_url"`
}
/* android phone和pad播放的mp4文件类。适用2.3版本的Android。 */
type AndroidVlowUrl struct {
Hd string `json:"hd"`
Ld string `json:"ld"`
Sd string `json:"sd"`
Ud string `json:"ud"`
}
| Java |
'use strict';
const assert = require('assert');
const HttpResponse = require('./http-response');
describe('HttpResponse', () => {
const mockResponse = {
version: '1.0',
status: '200 OK'
};
it('should create an instance', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.ok(httpResponse instanceof HttpResponse);
});
describe('isProtocolVersion()', () => {
it('should determine if protocol version matches', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.ok(httpResponse.isProtocolVersion('1.0'));
});
it('should return false if versions do not match', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.isProtocolVersion('2.0'), false);
});
it('should throw an error if no version specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.isProtocolVersion, /Specify a protocol `version`/);
});
it('should throw an error if no version specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() =>
httpResponse.isProtocolVersion(false), /The protocol `version` must be a string/);
});
});
describe('getProtocolVersion()', () => {
it('should get the protocol version', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getProtocolVersion(), '1.0');
});
});
describe('setProtocolVersion()', () => {
it('should set the protocol version', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getProtocolVersion(), '1.0');
httpResponse.setProtocolVersion('2.0');
assert.equal(httpResponse.getProtocolVersion(), '2.0');
});
it('should throw an error if no version specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.setProtocolVersion, /Specify a protocol `version`/);
});
it('should throw an error if no version specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() =>
httpResponse.setProtocolVersion(Boolean), /The protocol `version` must be a string/);
});
});
describe('isStatus()', () => {
it('should determine if status matches', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.ok(httpResponse.isStatus('200 OK'));
});
it('should return false if status do not match', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.isStatus('400 Bad Request'), false);
});
it('should throw an error if no status specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.isStatus, /Specify a `status`/);
});
it('should throw an error if specified status is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.isStatus({}), /The `status` must be a string/);
});
});
describe('getStatus()', () => {
it('should return the status', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
});
});
describe('getStatusCode()', () => {
it('should return status code', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatusCode(), '200');
});
});
describe('getStatusText()', () => {
it('should return status text', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatusText(), 'OK');
});
});
describe('setStatus()', () => {
it('should set the status', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
httpResponse.setStatus(400, 'Bad Request');
assert.equal(httpResponse.getStatus(), '400 Bad Request');
});
it('should throw an error if no code specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
assert.throws(() => httpResponse.setStatus(void 0, 'Bad Request'), /Specify a status `code`/);
});
it('should throw an error if the code is not an integer', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
assert.throws(() =>
httpResponse.setStatus('200', 'Bad Request'), /The status `code` must be an integer/);
});
it('should throw an error if no text specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
assert.throws(() => httpResponse.setStatus(400, void 0), /Specify a status `text`/);
});
it('should throw an error if specified text is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
assert.throws(() => httpResponse.setStatus(400, true), /The status `text` must be a string/);
});
});
describe('hasHeader()', () => {
it('should determine if header has been set', () => {
const _mockResponse = Object.assign({headers: {'Content-Type': 'test'}}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.ok(httpResponse.hasHeader('Content-Type'));
});
it('should return false if header has not been set', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.hasHeader('Content-Type'), false);
});
it('should throw an error if no header `name` specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.hasHeader, /Specify a header `name`/);
});
it('should throw an error if specified header `name` is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.hasHeader({}), /The header `name` must be a string/);
});
});
describe('getHeader()', () => {
it('should return the header with the specified `name`', () => {
const _mockResponse = Object.assign({headers: {'Content-Type': ['test']}}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.equal(httpResponse.getHeader('Content-Type'), 'test');
});
it('should return the default value if specified header does not exist', () => {
const _mockResponse = Object.assign({headers: {}}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
const defaultValue = 'text/plain';
assert.equal(httpResponse.getHeader('Content-Type', defaultValue), defaultValue);
});
it('should throw an error if no header `name` specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.getHeader, /Specify a header `name`/);
});
it('should throw an error if specified header `name` is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.getHeader({}), /The header `name` must be a string/);
});
});
describe('getHeaders()', () => {
it('should return all headers', () => {
const headers = {'Content-Type': ['test']};
const _mockResponse = Object.assign({headers}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.deepEqual(httpResponse.getHeaders(), {'Content-Type': 'test'});
});
it('should return an empty set of headers when none are set', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.deepEqual(httpResponse.getHeaders(), {});
});
});
describe('setHeader()', () => {
it('should set a header in the httpResponse', () => {
const httpResponse = new HttpResponse(mockResponse);
httpResponse.setHeader('Content-Type', 'test');
assert.ok(httpResponse.hasHeader('Content-Type'));
assert.equal(httpResponse.getHeader('Content-Type'), 'test');
});
it('should throw an error if a header `name` is not defined', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.setHeader(void 0, 'test'), /Specify a header `name`/);
});
it('should throw an error if a header `name` is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() =>
httpResponse.setHeader(false, 'test'), /The header `name` must be a string/);
});
it('should throw an error if a header `value` is not defined', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() =>
httpResponse.setHeader('Content-Type', void 0), /Specify a header `value`/);
});
it('should throw an error if a header `name` is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.setHeader('Content-Type', []),
/The header `value` must be a string/);
});
it('should register a new header as an array with 1 value', () => {
const httpResponse = new HttpResponse(mockResponse);
httpResponse.setHeader('X-Test', 'test');
assert.ok(httpResponse.hasHeader('X-Test'));
assert.deepEqual(httpResponse.getHeaderArray('X-Test'), ['test']);
});
});
describe('hasBody()', () => {
it('should determine if the httpResponse has a `body`', () => {
const _mockResponse = Object.assign({body: ' '}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.ok(httpResponse.hasBody());
});
it('should return false if the esponse do not have a `body`', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.hasBody(), false);
});
});
describe('getBody()', () => {
it('should return the content of the httpResponse `body`', () => {
const body = ' ';
const _mockResponse = Object.assign({body}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.equal(httpResponse.getBody(), body);
});
});
describe('setBody()', () => {
it('should set the content of the httpResponse `body`', () => {
const body = ' ';
const httpResponse = new HttpResponse(mockResponse);
httpResponse.setBody(body);
assert.equal(httpResponse.getBody(), body);
});
});
});
| Java |
"use strict";
let datafire = require('datafire');
let openapi = require('./openapi.json');
module.exports = datafire.Integration.fromOpenAPI(openapi, "azure_sql_failoverdatabases"); | Java |
---
layout: sidebar-right
title: 'Meet the Author: Rose Tremain'
date: 2016-08-16
author: brandon-king
category: meet-the-author
excerpt: Brandon King interviews Whitbread winner Rose Tremain.
breadcrumb: meet-the-author
---

Rose Tremain was one of only five women writers to be included in Granta’s original list of 20 Best of Young British Novelists in 1983. Her novels and short stories have been published worldwide in 27 countries and have won many prizes, including the Sunday Express book of the Year Award (for <cite>Restoration</cite>, also shortlisted for the Booker Prize); the Prix Femina Etranger, France (for <cite>Sacred Country</cite>); the Whitbread Novel of the Year Award (for <cite>Music & Silence</cite>) and the Orange Prize for Fiction 2008 (for <cite>The Road Home</cite>). Restoration was filmed in 1995 and a stage version was produced in 2009.
Her latest novel is the acclaimed <cite>The Gustav Sonata</cite> which sees Rose <q>writing at the height of her inimitable powers</q> (<cite>Observer</cite>). [Rose’s books are available through Suffolk Libraries.](https://suffolk.spydus.co.uk/cgi-bin/spydus.exe/ENQ/OPAC/BIBENQ/19571153?QRY=CAUBIB%3C%20IRN(3632)&QRYTEXT=Tremain%2C%20Rose)
**Who were your literary influences when you were growing up?**
At my school, we read no contemporary literature at all. It wasn’t until I was about sixteen that I discovered, for instance, Lawrence Durrell, whose over-rated purple prose felt beautiful to me then. I loved it so much, I wanted to eat the text! Meanwhile, I tried to write lyric poetry like Keats and gripping yarns, like Conrad. But the then Poet Laureate, John Masefield was watching over me. Our class made some poster-paint pictures of scenes from his novel, <cite>Lost Endeavour</cite>, and sent them to Masefield, and he was so touched that he invited us all to tea. I was then about 14 and I confided to him that I wanted to be a writer and he quoted W.B. Yeats to me: “Do not hurry, do not rest.” And I have never forgotten this.
**Do you spend a lot of time researching? What is your writing routine?**
Research is important. If, like me, you write about experiences outside your own, you have to know the world you’re trying to evoke. I work not only from written research, but a lot from pictures and photographs. For my recent novel, <cite>The Gustav Sonata</cite>, one of the most helpful sources was a traveller’s guide to Switzerland, heavily illustrated with pictures of everything from pastures to patisserie, cathedrals to cheese manufacture. Interior scenes and indeed landscapes can be evoked by the tiniest details, but they have to feel real and true. But here, I was also helped by my own memorable experiences of being taken to Switzerland as a young child and, later being sent to school there for a year.
Writing routines vary for every one of us. The most important thing, when I’m working on a novel, is to try to clear the diary of interruptions. This isn’t always easy because talking to audiences about our work has become part of a writer’s life. But my happiest days are those when I can work without being disturbed for six or seven hours.
**What draws you to a new subject?**
This is a mysterious process. Over a long writing life, I’ve been drawn to a variety of subjects and themes and I can never predict where I’m likely to go next. But this, I think, is what has kept me going over forty years as a published author. I seldom recycle any part of my own biography, but search for new places and characters who are distant from me in age, type and (often) gender. This is the process which gets my imagination working. Dreaming a new story into existence is as enthralling to me now as it was when I was 30.
**Robert Merivel: What makes people love this man?**
I think people love Robert Merivel because we are all – every one of us – like him, in certain ways. We are courageous and yet afraid, boastful and yet uncertain of our capacities, drawn to material splendour but pricked by a puritanical conscience. We can also usually predict – ahead of him – the troubles he is going to tumble into, and then laugh or cry with him. In other words, he is human and fallible, but often saved by irony and wit and a tendency to collapse into drunken monologues or unstoppable giggling at inappropriate moments.
Once this character was ‘found’, via his voice and his appetites, it was easy to become him. I always knew that, one day, I would write the sequel to <cite>Restoration</cite> and this came out (<cite>Merivel: A Man of His Time</cite>) in 2013. In the second book, Sir Robert is older, but not much wiser and the world around him begins to darken.
**Are Anton and Gustav in <cite>The Gustav Sonata</cite> based on anyone?**
These boys are pure inventions, not based on anyone. However, in the opening section, I draw on some personal recollections of the loneliness of childhood and its terrors and the way adult behaviour is so unpredictable. Connected to the idea of Swiss ‘neutrality’ (a state much harder to sustain that we might suppose), I wanted to create a person, Gustav, who, because he is not loved, strives for a kind of ‘neutrality of feeling’ all his life. He achieves a high degree of self-mastery, but his passionate love for Anton threatens to undermine this from the day they first meet at Kindergarten, aged 5. Anton is Gustav’s antithesis, the spoilt child of loving parents, with seemingly boundless self-belief. Yet Anton, too, is overwhelmed by destructive forces within himself and he comes to realise that the only person who can save him is Gustav.
**What is your latest project?**
I’m working on several things: a stage play based on my short story, <cite>The Darkness of Wallis Simpson</cite>, a 3-part TV adaptation of my novel, <cite>Trespass</cite>, a mystery with incest at its troubled heart, set in the Cevennes region of France, and a story for children about an iron bird. I have a new idea for a novel, but this is a tiny, hard-to-see embryo, which may or may not put on flesh and acquire a beating heart. Watch this space – or rather, perhaps, don’t watch it!
**Do you have a message for your many readers in Suffolk Libraries?**
You’ve been patient with my many excursions into different forms and subjects and I hope most of you have found something to love. I’ll try to keep on working and experimenting and not let you down.
| Java |
---
layout: post
title: "Visão da Verdade"
date: 2018-01-01
source: Módulo Básico 209, Módulo Básico Edição Revisada 219.
tags: [nenhum, bardo]
---
**arcana 6, divina 5 (adivinhação)**
**Alcance**: toque
**Teste de Resistência**: nenhum.
**Duração**: 10 minutos
**Alvo**: criatura tocada
**Tempo de Execução**: ação padrão
Esta magia faz o alvo ver a forma real das coisas. Ele enxerga através de escuridão (normal e mágica), ilusões (tanto invisibilidade quanto formas ilusórias) e transmutações (vê a forma real de criaturas ou objetos transformados).
Esta magia não atravessa objetos sólidos, nem cancela camuflagem causada por efeitos mundanos. Assim, ela não revela coisas como disfarces comuns.
| Java |
<!DOCTYPE html>
<head>
<title>Terrible Treats - Cookie Recipe</title>
<link rel="stylesheet" type="text/css" href="styling.css">
</head>
<body>
<div id="header">
<p id="title">Terrible Treats</p>
<p id="subTitle">Desserts For Your Worst Enemies</p>
</div>
<div id="navCon" class="flex-container">
<div id="navBar" class="flex-nav">
<p class="navButton"><a href="index.html">Home</a></p>
<p class="navButton"><a href="cookies.html">Cookies</a></p>
<p class="navButton"><a href="cakes.html">Cakes</a></p>
<p class="navButton"><a href="pies.html">Pies</a></p>
</div>
<div id="contentSection">
<p id="subTitle">Wasabi Cookies</p>
<!-- Image taken from https://commons.wikimedia.org/wiki/File:Lemon_shortbread_cookies_with_lemon_royal_icing.jpg -->
<img src="greenCookie.jpg" alt="Green Cookies">
<table id="ingredients">
<tr>
<th>Ingredients</th>
<th>Amount</th>
</tr>
<tr>
<td>Eggs</td>
<td>4</td>
</tr>
<tr>
<td>Flour</td>
<td>3 cups</td>
</tr>
<tr>
<td>Butter</td>
<td>1/4 pound</td>
</tr>
<tr>
<td>Salt</td>
<td>2 tbs</td>
</tr>
<tr>
<td>Wasabi</td>
<td>1 cup</td>
</tr>
</table>
<h4>Instructions</h4>
<ol>
<li>Preheat oven to 350 degrees fahrenheit</li>
<li>Add egg, flour, butter, wasabi, and salt into a bowl and mix untill fully blended</li>
<li>Drop tablespoon size amounts of batter on a baking sheet with some distance between them</li>
<li>Bake for 30 minutes</li>
<li>Let stand for 15 minutes</li>
</ol>
</div>
</div>
</body>
| Java |
package generated.zcsclient.mail;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for messagePartHitInfo complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="messagePartHitInfo">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="e" type="{urn:zimbraMail}emailInfo" minOccurs="0"/>
* <element name="su" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="sf" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="s" type="{http://www.w3.org/2001/XMLSchema}long" />
* <attribute name="d" type="{http://www.w3.org/2001/XMLSchema}long" />
* <attribute name="cid" type="{http://www.w3.org/2001/XMLSchema}int" />
* <attribute name="mid" type="{http://www.w3.org/2001/XMLSchema}int" />
* <attribute name="ct" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="part" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "messagePartHitInfo", propOrder = {
"e",
"su"
})
public class testMessagePartHitInfo {
protected testEmailInfo e;
protected String su;
@XmlAttribute(name = "id")
protected String id;
@XmlAttribute(name = "sf")
protected String sf;
@XmlAttribute(name = "s")
protected Long s;
@XmlAttribute(name = "d")
protected Long d;
@XmlAttribute(name = "cid")
protected Integer cid;
@XmlAttribute(name = "mid")
protected Integer mid;
@XmlAttribute(name = "ct")
protected String ct;
@XmlAttribute(name = "name")
protected String name;
@XmlAttribute(name = "part")
protected String part;
/**
* Gets the value of the e property.
*
* @return
* possible object is
* {@link testEmailInfo }
*
*/
public testEmailInfo getE() {
return e;
}
/**
* Sets the value of the e property.
*
* @param value
* allowed object is
* {@link testEmailInfo }
*
*/
public void setE(testEmailInfo value) {
this.e = value;
}
/**
* Gets the value of the su property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSu() {
return su;
}
/**
* Sets the value of the su property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSu(String value) {
this.su = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the sf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSf() {
return sf;
}
/**
* Sets the value of the sf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSf(String value) {
this.sf = value;
}
/**
* Gets the value of the s property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getS() {
return s;
}
/**
* Sets the value of the s property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setS(Long value) {
this.s = value;
}
/**
* Gets the value of the d property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getD() {
return d;
}
/**
* Sets the value of the d property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setD(Long value) {
this.d = value;
}
/**
* Gets the value of the cid property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getCid() {
return cid;
}
/**
* Sets the value of the cid property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setCid(Integer value) {
this.cid = value;
}
/**
* Gets the value of the mid property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getMid() {
return mid;
}
/**
* Sets the value of the mid property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setMid(Integer value) {
this.mid = value;
}
/**
* Gets the value of the ct property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCt() {
return ct;
}
/**
* Sets the value of the ct property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCt(String value) {
this.ct = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the part property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPart() {
return part;
}
/**
* Sets the value of the part property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPart(String value) {
this.part = value;
}
}
| Java |
#!/bin/bash -ex
cd "$(dirname "$0")"
docker run --rm \
-v "$PWD/.:/work" \
-w "/work" \
ruby:2.5 bash -ec "
gem install -N parse_a_changelog
parse ./CHANGELOG.md
"
| Java |
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="description" content="" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
<script type="text/javascript" src="../../../core/uni.js"></script>
<script type="text/javascript">
uni
.require('kits/xhr.js')
.require('core/notify.js')
.within(function() {
this
.xhr
// No callback argument, just complete, also showing how to pass
// through data.
//
.get('get.html', {
async: true,
// This will pass through to `ob`, below.
//
here: 'there',
complete: function(data, ob) {
this
.notify(data)
.notify(ob)
}
})
})
</script>
</head>
<body>
<div id="test">
</div>
</body>
</html> | Java |
<template name="loading">
<div class="ui active inline loader"></div>
</template> | Java |
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_model/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module ClassroomLibrary
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
end
end
| Java |
/*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, node: true, nomen: true,
indent: 4, maxerr: 50 */
/*global expect, describe, it, beforeEach, afterEach */
"use strict";
var ExtensionsDomain = require("../ExtensionManagerDomain"),
fs = require("fs-extra"),
async = require("async"),
path = require("path");
var testFilesDirectory = path.join(path.dirname(module.filename),
"..", // node
"..", // extensibility
"..", // src
"..", // brackets
"test",
"spec",
"extension-test-files"),
installParent = path.join(path.dirname(module.filename), "extensions"),
installDirectory = path.join(installParent, "good"),
disabledDirectory = path.join(installParent, "disabled");
var basicValidExtension = path.join(testFilesDirectory, "basic-valid-extension.zip"),
basicValidExtension2 = path.join(testFilesDirectory, "basic-valid-extension-2.0.zip"),
missingMain = path.join(testFilesDirectory, "missing-main.zip"),
oneLevelDown = path.join(testFilesDirectory, "one-level-extension-master.zip"),
incompatibleVersion = path.join(testFilesDirectory, "incompatible-version.zip"),
invalidZip = path.join(testFilesDirectory, "invalid-zip-file.zip"),
missingPackageJSON = path.join(testFilesDirectory, "missing-package-json.zip");
describe("Package Installation", function () {
var standardOptions = {
disabledDirectory: disabledDirectory,
apiVersion: "0.22.0"
};
beforeEach(function (done) {
fs.mkdirs(installDirectory, function (err) {
fs.mkdirs(disabledDirectory, function (err) {
done();
});
});
});
afterEach(function (done) {
fs.remove(installParent, function (err) {
done();
});
});
function checkPaths(pathsToCheck, callback) {
var existsCalls = [];
pathsToCheck.forEach(function (path) {
existsCalls.push(function (callback) {
fs.exists(path, async.apply(callback, null));
});
});
async.parallel(existsCalls, function (err, results) {
expect(err).toBeNull();
results.forEach(function (result, num) {
expect(result ? "" : pathsToCheck[num] + " does not exist").toEqual("");
});
callback();
});
}
it("should validate the package", function (done) {
ExtensionsDomain._cmdInstall(missingMain, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
var errors = result.errors;
expect(errors.length).toEqual(1);
done();
});
});
it("should work fine if all is well", function (done) {
ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) {
var extensionDirectory = path.join(installDirectory, "basic-valid-extension");
expect(err).toBeNull();
var errors = result.errors;
expect(errors.length).toEqual(0);
expect(result.metadata.name).toEqual("basic-valid-extension");
expect(result.name).toEqual("basic-valid-extension");
expect(result.installedTo).toEqual(extensionDirectory);
var pathsToCheck = [
path.join(extensionDirectory, "package.json"),
path.join(extensionDirectory, "main.js")
];
checkPaths(pathsToCheck, done);
});
});
// This is mildly redundant. the validation check should catch this.
// But, I wanted to be sure that the install function doesn't try to
// do anything with the file before validation.
it("should fail for missing package", function (done) {
ExtensionsDomain._cmdInstall(path.join(testFilesDirectory, "NOT A PACKAGE"),
installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
var errors = result.errors;
expect(errors.length).toEqual(1);
expect(errors[0][0]).toEqual("NOT_FOUND_ERR");
done();
});
});
it("should install to the disabled directory if it's already installed", function (done) {
ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
expect(result.disabledReason).toBeNull();
ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
expect(result.disabledReason).toEqual("ALREADY_INSTALLED");
var extensionDirectory = path.join(disabledDirectory, "basic-valid-extension");
var pathsToCheck = [
path.join(extensionDirectory, "package.json"),
path.join(extensionDirectory, "main.js")
];
checkPaths(pathsToCheck, done);
});
});
});
it("should yield an error if there's no disabled directory set", function (done) {
ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, { apiVersion: "0.22.0" }, function (err, result) {
expect(err.message).toEqual("MISSING_REQUIRED_OPTIONS");
done();
});
});
it("should yield an error if there's no apiVersion set", function (done) {
ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, { disabledDirectory: disabledDirectory }, function (err, result) {
expect(err.message).toEqual("MISSING_REQUIRED_OPTIONS");
done();
});
});
it("should overwrite the disabled directory copy if there's already one", function (done) {
ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
expect(result.disabledReason).toBeNull();
ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
expect(result.disabledReason).toEqual("ALREADY_INSTALLED");
ExtensionsDomain._cmdInstall(basicValidExtension2, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
expect(result.disabledReason).toEqual("ALREADY_INSTALLED");
var extensionDirectory = path.join(disabledDirectory, "basic-valid-extension");
fs.readJson(path.join(extensionDirectory, "package.json"), function (err, packageObj) {
expect(err).toBeNull();
expect(packageObj.version).toEqual("2.0.0");
done();
});
});
});
});
});
it("should derive the name from the zip if there's no package.json", function (done) {
ExtensionsDomain._cmdInstall(missingPackageJSON, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
expect(result.disabledReason).toBeNull();
var extensionDirectory = path.join(installDirectory, "missing-package-json");
var pathsToCheck = [
path.join(extensionDirectory, "main.js")
];
checkPaths(pathsToCheck, done);
});
});
it("should install with the common prefix removed", function (done) {
ExtensionsDomain._cmdInstall(oneLevelDown, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
var extensionDirectory = path.join(installDirectory, "one-level-extension");
var pathsToCheck = [
path.join(extensionDirectory, "main.js"),
path.join(extensionDirectory, "package.json"),
path.join(extensionDirectory, "lib", "foo.js")
];
checkPaths(pathsToCheck, done);
});
});
it("should disable extensions that are not compatible with the current Brackets API", function (done) {
ExtensionsDomain._cmdInstall(incompatibleVersion, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
expect(result.disabledReason).toEqual("API_NOT_COMPATIBLE");
var extensionDirectory = path.join(disabledDirectory, "incompatible-version");
var pathsToCheck = [
path.join(extensionDirectory, "main.js"),
path.join(extensionDirectory, "package.json")
];
checkPaths(pathsToCheck, done);
});
});
it("should not have trouble with invalid zip files", function (done) {
ExtensionsDomain._cmdInstall(invalidZip, installDirectory, standardOptions, function (err, result) {
expect(err).toBeNull();
expect(result.errors.length).toEqual(1);
done();
});
});
}); | Java |
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:2.0.50727.1433
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings),MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.pmDebug.My.MySettings
Get
Return Global.pmDebug.My.MySettings.Default
End Get
End Property
End Module
End Namespace
| Java |
#include "stdafx.h"
#include "Renderer.h"
#include "RenderMethod_PhongPoint_CG.h"
RenderMethod_PhongPoint_CG::RenderMethod_PhongPoint_CG(class Renderer *r) {
ASSERT(r, "Null pointer: r");
renderer = r;
useCG = true;
}
bool RenderMethod_PhongPoint_CG::isSupported() const {
return areShadersAvailable();
}
void RenderMethod_PhongPoint_CG::setupShader(CGcontext &cg,
CGprofile &_cgVertexProfile,
CGprofile &_cgFragmentProfile) {
RenderMethod::setupShader(cg, _cgVertexProfile, _cgFragmentProfile);
createVertexProgram(cg, FileName("data/shaders/cg/phong_point.vp.cg"));
createFragmentProgram(cg, FileName("data/shaders/cg/phong_point.fp.cg"));
// Vertex program parameters
cgMVP = getVertexProgramParameter (cg, "MVP");
cgView = getVertexProgramParameter (cg, "View");
cgLightPos = getVertexProgramParameter (cg, "LightPos");
cgCameraPos = getVertexProgramParameter (cg, "CameraPos");
cgTexture = getFragmentProgramParameter(cg, "tex0");
cgKa = getFragmentProgramParameter(cg, "Ka");
cgKd = getFragmentProgramParameter(cg, "Kd");
cgKs = getFragmentProgramParameter(cg, "Ks");
cgShininess = getFragmentProgramParameter(cg, "shininess");
cgkC = getFragmentProgramParameter(cg, "kC");
cgkL = getFragmentProgramParameter(cg, "kL");
cgkQ = getFragmentProgramParameter(cg, "kQ");
}
void RenderMethod_PhongPoint_CG::renderPass(RENDER_PASS pass) {
switch (pass) {
case OPAQUE_PASS:
pass_opaque();
break;
default:
return;
}
}
void RenderMethod_PhongPoint_CG::pass_opaque() {
CHECK_GL_ERROR();
// Setup state
glPushAttrib(GL_ALL_ATTRIB_BITS);
glColor4fv(white);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_TEXTURE_2D);
// Setup client state
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
// Render the geometry chunks
renderChunks();
// Restore client state
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
// Restore settings
glPopAttrib();
CHECK_GL_ERROR();
}
void RenderMethod_PhongPoint_CG::setShaderData(const GeometryChunk &gc) {
const Renderer::Light &light0 = renderer->getLight();
ASSERT(light0.type == Renderer::Light::POINT, "point lights only pls");
mat4 MI = (gc.transformation).inverse(); // world -> object projection
// Set the position of the light (in object-space)
vec3 LightPosObj = MI.transformVector(light0.position);
cgGLSetParameter3fv(cgLightPos, LightPosObj);
// Set the position of the camera (in object-space)
vec3 CameraPosWld = renderer->getCamera().getPosition();
vec3 CameraPosObj = MI.transformVector(CameraPosWld);
cgGLSetParameter3fv(cgCameraPos, CameraPosObj);
// Set the light properties
cgGLSetParameter1fv(cgkC, &light0.kC);
cgGLSetParameter1fv(cgkL, &light0.kL);
cgGLSetParameter1fv(cgkQ, &light0.kQ);
// Set the material properties
cgGLSetParameter4fv(cgKa, gc.material.Ka);
cgGLSetParameter4fv(cgKd, gc.material.Kd);
cgGLSetParameter4fv(cgKs, gc.material.Ks);
cgGLSetParameter1fv(cgShininess, &gc.material.shininess);
// Everything else
cgGLSetStateMatrixParameter(cgMVP, CG_GL_MODELVIEW_PROJECTION_MATRIX, CG_GL_MATRIX_IDENTITY);
cgGLSetStateMatrixParameter(cgView, CG_GL_MODELVIEW_MATRIX, CG_GL_MATRIX_IDENTITY);
}
| Java |
#ifndef _SYSAPPDB_SYSAPPDBHELPER_H_
#define _SYSAPPDB_SYSAPPDBHELPER_H_
#include <vector>
#include <map>
#include <string>
#include "sqlite3.h"
std::vector<std::string> read_text_file(std::string path);
std::vector<std::string> split_str(std::string src, char c);
std::string join_str(std::vector<std::string> strings, std::string connector);
template<typename K, typename V>
std::vector<K> map_get_keys(std::map<K, V> map);
template<typename K, typename V>
std::vector<V> map_get_values(std::map<K, V> map);
int db_insert(sqlite3* con, std::string table, std::map<std::string, std::string> values);
template<typename C>
std::vector<C> db_select(sqlite3* con, std::string table, std::string coloumn, std::string where_stmt);
#endif | Java |
class AddOriginalMd5ChecksumToVideos < ActiveRecord::Migration
def change
add_column :videos, :original_md5_checksum, :string, :limit => 40
end
end
| Java |
function SendMessage(a_Player, a_Message)
a_Player:SendMessageInfo(a_Message)
end
function SendMessageSuccess(a_Player, a_Message)
a_Player:SendMessageSuccess(a_Message)
end
function SendMessageFailure(a_Player, a_Message)
a_Player:SendMessageFailure(a_Message)
end
--- Kicks a player by name, with the specified reason; returns bool whether found and player's real name
function KickPlayer( PlayerName, Reason )
local RealName = ""
if (Reason == nil) then
Reason = "You have been kicked"
end
local FoundPlayerCallback = function( a_Player )
a_Player:GetClientHandle():Kick(Reason)
return true
end
if not cRoot:Get():FindAndDoWithPlayer( PlayerName, FoundPlayerCallback ) then
-- Could not find player
return false
end
return true -- Player has been kicked
end
function ReturnColorFromChar(char)
-- Check if the char represents a color. Else return nil.
if char == "0" then
return cChatColor.Black
elseif char == "1" then
return cChatColor.Navy
elseif char == "2" then
return cChatColor.Green
elseif char == "3" then
return cChatColor.Blue
elseif char == "4" then
return cChatColor.Red
elseif char == "5" then
return cChatColor.Purple
elseif char == "6" then
return cChatColor.Gold
elseif char == "7" then
return cChatColor.LightGray
elseif char == "8" then
return cChatColor.Gray
elseif char == "9" then
return cChatColor.DarkPurple
elseif char == "a" then
return cChatColor.LightGreen
elseif char == "b" then
return cChatColor.LightBlue
elseif char == "c" then
return cChatColor.Rose
elseif char == "d" then
return cChatColor.LightPurple
elseif char == "e" then
return cChatColor.Yellow
elseif char == "f" then
return cChatColor.White
elseif char == "k" then
return cChatColor.Random
elseif char == "l" then
return cChatColor.Bold
elseif char == "m" then
return cChatColor.Strikethrough
elseif char == "n" then
return cChatColor.Underlined
elseif char == "o" then
return cChatColor.Italic
elseif char == "r" then
return cChatColor.Plain
end
end
-- Teleports a_SrcPlayer to a player named a_DstPlayerName; if a_TellDst is true, will send a notice to the destination player
function TeleportToPlayer( a_SrcPlayer, a_DstPlayerName, a_TellDst )
local teleport = function(a_DstPlayerName)
if a_DstPlayerName == a_SrcPlayer then
-- Asked to teleport to self?
SendMessageFailure( a_SrcPlayer, "Y' can't teleport to yerself" )
else
-- If destination player is not in the same world, move to the correct world
if a_SrcPlayer:GetWorld():GetName() ~= a_DstPlayerName:GetWorld():GetName() then
a_SrcPlayer:MoveToWorld( a_DstPlayerName:GetWorld():GetName() )
end
a_SrcPlayer:TeleportToEntity( a_DstPlayerName )
SendMessageSuccess( a_SrcPlayer, "You teleported to " .. a_DstPlayerName:GetName() )
if (a_TellDst) then
SendMessage( a_DstPlayerName, a_SrcPlayer:GetName().." teleported to you" )
end
end
end
if not cRoot:Get():FindAndDoWithPlayer( a_DstPlayerName, teleport ) then
SendMessageFailure( a_SrcPlayer, "Player " .. a_DstPlayerName .. " not found" )
end
end
function getSpawnProtectRadius(WorldName)
return WorldsSpawnProtect[WorldName]
end
function GetWorldDifficulty(a_World)
local Difficulty = WorldsWorldDifficulty[a_World:GetName()]
if (Difficulty == nil) then
Difficulty = 1
end
return Clamp(Difficulty, 0, 3)
end
function SetWorldDifficulty(a_World, a_Difficulty)
local Difficulty = Clamp(a_Difficulty, 0, 3)
WorldsWorldDifficulty[a_World:GetName()] = Difficulty
-- Update world.ini
local WorldIni = cIniFile()
WorldIni:ReadFile(a_World:GetIniFileName())
WorldIni:SetValue("Difficulty", "WorldDifficulty", Difficulty)
WorldIni:WriteFile(a_World:GetIniFileName())
end
function LoadWorldSettings(a_World)
local WorldIni = cIniFile()
WorldIni:ReadFile(a_World:GetIniFileName())
WorldsSpawnProtect[a_World:GetName()] = WorldIni:GetValueSetI("SpawnProtect", "ProtectRadius", 10)
WorldsWorldLimit[a_World:GetName()] = WorldIni:GetValueSetI("WorldLimit", "LimitRadius", 0)
WorldsWorldDifficulty[a_World:GetName()] = WorldIni:GetValueSetI("Difficulty", "WorldDifficulty", 1)
WorldIni:WriteFile(a_World:GetIniFileName())
end
--- Returns the cWorld object represented by the given WorldName,
-- if no world of the given name is found, returns nil and informs the Player, if given, otherwise logs to console.
-- If no WorldName was given, returns the default world if called without a Player,
-- or the current world that the player is in if called with a Player.
--
-- @param WorldName String containing the name of the world to find
-- @param Player cPlayer object representing the player calling the command
--
-- @return cWorld object representing the requested world, or nil if not found
--
-- Called from: time.lua, weather.lua,
--
function GetWorld( WorldName, Player )
if not WorldName then
return Player and Player:GetWorld() or cRoot:Get():GetDefaultWorld()
else
local World = cRoot:Get():GetWorld(WorldName)
if not World then
local Message = "There is no world \"" .. WorldName .. "\""
if Player then
SendMessage( Player, Message )
else
LOG( Message )
end
end
return World
end
end
| Java |
import ReactIdSwiper from './ReactIdSwiper';
// Types
export {
ReactIdSwiperProps,
ReactIdSwiperRenderProps,
SelectableElement,
SwiperInstance,
WrappedElementType,
ReactIdSwiperChildren,
SwiperModuleName,
SwiperRefNode
} from './types';
// React-id-swiper
export default ReactIdSwiper;
| Java |
# -*- coding: utf-8 -*-
# @Author: karthik
# @Date: 2016-12-10 21:40:07
# @Last Modified by: chandan
# @Last Modified time: 2016-12-11 12:55:27
from models.portfolio import Portfolio
from models.company import Company
from models.position import Position
import tenjin
from tenjin.helpers import *
import wikipedia
import matplotlib.pyplot as plt
from data_helpers import *
from stock_data import *
import BeautifulSoup as bs
import urllib2
import re
from datetime import date as dt
engine = tenjin.Engine(path=['templates'])
# info fetch handler
def send_info_handler(bot, update, args):
args = list(parse_args(args))
if len(args) == 0 or "portfolio" in [arg.lower() for arg in args] :
send_portfolio_info(bot, update)
else:
info_companies = get_companies(args)
send_companies_info(bot, update, info_companies)
# get portfolio function
def send_portfolio_info(bot, update):
print "Userid: %d requested portfolio information" %(update.message.chat_id)
context = {
'positions': Portfolio.instance.positions,
'wallet_value': Portfolio.instance.wallet_value,
}
html_str = engine.render('portfolio_info.pyhtml', context)
bot.sendMessage(parse_mode="HTML", chat_id=update.message.chat_id, text=html_str)
# get companies information
def send_companies_info(bot, update, companies):
print "Userid: requested information for following companies %s" %','.join([c.name for c in companies])
for company in companies:
context = {
'company': company,
'current_price': get_current_price(company),
'description': wikipedia.summary(company.name.split()[0], sentences=2)
}
wiki_page = wikipedia.page(company.name.split()[0])
html_page = urllib2.urlopen(wiki_page.url)
soup = bs.BeautifulSoup(html_page)
img_url = 'http:' + soup.find('td', { "class" : "logo" }).find('img')['src']
bot.sendPhoto(chat_id=update.message.chat_id, photo=img_url)
html_str = engine.render('company_template.pyhtml', context)
bot.sendMessage(parse_mode="HTML", chat_id=update.message.chat_id, text=html_str)
symbols = [c.symbol for c in companies]
if len(symbols) >= 2:
symbol_string = ", ".join(symbols[:-1]) + " and " + symbols[-1]
else:
symbol_string = symbols[0]
last_n_days = 10
if len(companies) < 4:
create_graph(companies, last_n_days)
history_text = '''
Here's the price history for {} for the last {} days
'''.format(symbol_string, last_n_days)
bot.sendMessage(chat_id=update.message.chat_id, text=history_text)
bot.sendPhoto(chat_id=update.message.chat_id, photo=open("plots/temp.png",'rb'))
def create_graph(companies, timedel):
fig, ax = plt.subplots()
for company in companies:
dates, lookback_prices = get_lookback_prices(company, timedel)
# dates = [i.strftime('%d/%m') for i in dates]
h = ax.plot(dates, lookback_prices, label=company.symbol)
ax.legend()
plt.xticks(rotation=45)
plt.savefig('plots/temp.png')
| Java |
using System;
using System.Collections.Generic;
using System.Html;
namespace wwtlib
{
public class PlotTile : Tile
{
bool topDown = true;
protected PositionTexture[] bounds;
protected bool backslash = false;
List<PositionTexture> vertexList = null;
List<Triangle>[] childTriangleList = null;
protected float[] demArray;
protected void ComputeBoundingSphere()
{
InitializeGrids();
TopLeft = bounds[0 + 3 * 0].Position.Copy();
BottomRight = bounds[2 + 3 * 2].Position.Copy();
TopRight = bounds[2 + 3 * 0].Position.Copy();
BottomLeft = bounds[0 + 3 * 2].Position.Copy();
CalcSphere();
}
public override void RenderPart(RenderContext renderContext, int part, double opacity, bool combine)
{
if (renderContext.gl != null)
{
//todo draw in WebGL
}
else
{
if (part == 0)
{
foreach(Star star in stars)
{
double radDec = 25 / Math.Pow(1.6, star.Magnitude);
Planets.DrawPointPlanet(renderContext, star.Position, radDec, star.Col, false);
}
}
}
}
WebFile webFile;
public override void RequestImage()
{
if (!Downloading && !ReadyToRender)
{
Downloading = true;
webFile = new WebFile(Util.GetProxiedUrl(this.URL));
webFile.OnStateChange = FileStateChange;
webFile.Send();
}
}
public void FileStateChange()
{
if(webFile.State == StateType.Error)
{
Downloading = false;
ReadyToRender = false;
errored = true;
RequestPending = false;
TileCache.RemoveFromQueue(this.Key, true);
}
else if(webFile.State == StateType.Received)
{
texReady = true;
Downloading = false;
errored = false;
ReadyToRender = texReady && (DemReady || !demTile);
RequestPending = false;
TileCache.RemoveFromQueue(this.Key, true);
LoadData(webFile.GetText());
}
}
List<Star> stars = new List<Star>();
private void LoadData(string data)
{
string[] rows = data.Replace("\r\n","\n").Split("\n");
bool firstRow = true;
PointType type = PointType.Move;
Star star = null;
foreach (string row in rows)
{
if (firstRow)
{
firstRow = false;
continue;
}
if (row.Trim().Length > 5)
{
star = new Star(row);
star.Position = Coordinates.RADecTo3dAu(star.RA, star.Dec, 1);
stars.Add(star);
}
}
}
public override bool IsPointInTile(double lat, double lng)
{
if (Level == 0)
{
return true;
}
if (Level == 1)
{
if ((lng >= 0 && lng <= 90) && (tileX == 0 && tileY == 1))
{
return true;
}
if ((lng > 90 && lng <= 180) && (tileX == 1 && tileY == 1))
{
return true;
}
if ((lng < 0 && lng >= -90) && (tileX == 0 && tileY == 0))
{
return true;
}
if ((lng < -90 && lng >= -180) && (tileX == 1 && tileY == 0))
{
return true;
}
return false;
}
if (!this.DemReady || this.DemData == null)
{
return false;
}
Vector3d testPoint = Coordinates.GeoTo3dDouble(-lat, lng);
bool top = IsLeftOfHalfSpace(TopLeft.Copy(), TopRight.Copy(), testPoint);
bool right = IsLeftOfHalfSpace(TopRight.Copy(), BottomRight.Copy(), testPoint);
bool bottom = IsLeftOfHalfSpace(BottomRight.Copy(), BottomLeft.Copy(), testPoint);
bool left = IsLeftOfHalfSpace(BottomLeft.Copy(), TopLeft.Copy(), testPoint);
if (top && right && bottom && left)
{
// showSelected = true;
return true;
}
return false; ;
}
private bool IsLeftOfHalfSpace(Vector3d pntA, Vector3d pntB, Vector3d pntTest)
{
pntA.Normalize();
pntB.Normalize();
Vector3d cross = Vector3d.Cross(pntA, pntB);
double dot = Vector3d.Dot(cross, pntTest);
return dot < 0;
}
private void InitializeGrids()
{
vertexList = new List<PositionTexture>();
childTriangleList = new List<Triangle>[4];
childTriangleList[0] = new List<Triangle>();
childTriangleList[1] = new List<Triangle>();
childTriangleList[2] = new List<Triangle>();
childTriangleList[3] = new List<Triangle>();
bounds = new PositionTexture[9];
if (Level > 0)
{
// Set in constuctor now
//ToastTile parent = (ToastTile)TileCache.GetTile(level - 1, x / 2, y / 2, dataset, null);
if (Parent == null)
{
Parent = TileCache.GetTile(Level - 1, tileX / 2, tileY / 2, dataset, null);
}
PlotTile parent = (PlotTile)Parent;
int xIndex = tileX % 2;
int yIndex = tileY % 2;
if (Level > 1)
{
backslash = parent.backslash;
}
else
{
backslash = xIndex == 1 ^ yIndex == 1;
}
bounds[0 + 3 * 0] = parent.bounds[xIndex + 3 * yIndex].Copy();
bounds[1 + 3 * 0] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * yIndex]);
bounds[2 + 3 * 0] = parent.bounds[xIndex + 1 + 3 * yIndex].Copy();
bounds[0 + 3 * 1] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]);
if (backslash)
{
bounds[1 + 3 * 1] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]);
}
else
{
bounds[1 + 3 * 1] = Midpoint(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]);
}
bounds[2 + 3 * 1] = Midpoint(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]);
bounds[0 + 3 * 2] = parent.bounds[xIndex + 3 * (yIndex + 1)].Copy();
bounds[1 + 3 * 2] = Midpoint(parent.bounds[xIndex + 3 * (yIndex + 1)], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]);
bounds[2 + 3 * 2] = parent.bounds[xIndex + 1 + 3 * (yIndex + 1)].Copy();
bounds[0 + 3 * 0].Tu = 0*uvMultiple;
bounds[0 + 3 * 0].Tv = 0 * uvMultiple;
bounds[1 + 3 * 0].Tu = .5f * uvMultiple;
bounds[1 + 3 * 0].Tv = 0 * uvMultiple;
bounds[2 + 3 * 0].Tu = 1 * uvMultiple;
bounds[2 + 3 * 0].Tv = 0 * uvMultiple;
bounds[0 + 3 * 1].Tu = 0 * uvMultiple;
bounds[0 + 3 * 1].Tv = .5f * uvMultiple;
bounds[1 + 3 * 1].Tu = .5f * uvMultiple;
bounds[1 + 3 * 1].Tv = .5f * uvMultiple;
bounds[2 + 3 * 1].Tu = 1 * uvMultiple;
bounds[2 + 3 * 1].Tv = .5f * uvMultiple;
bounds[0 + 3 * 2].Tu = 0 * uvMultiple;
bounds[0 + 3 * 2].Tv = 1 * uvMultiple;
bounds[1 + 3 * 2].Tu = .5f * uvMultiple;
bounds[1 + 3 * 2].Tv = 1 * uvMultiple;
bounds[2 + 3 * 2].Tu = 1 * uvMultiple;
bounds[2 + 3 * 2].Tv = 1 * uvMultiple;
}
else
{
bounds[0 + 3 * 0] = PositionTexture.Create(0, -1, 0, 0, 0);
bounds[1 + 3 * 0] = PositionTexture.Create(0, 0, 1, .5f, 0);
bounds[2 + 3 * 0] = PositionTexture.Create(0, -1, 0, 1, 0);
bounds[0 + 3 * 1] = PositionTexture.Create(-1, 0, 0, 0, .5f);
bounds[1 + 3 * 1] = PositionTexture.Create(0, 1, 0, .5f, .5f);
bounds[2 + 3 * 1] = PositionTexture.Create(1, 0, 0, 1, .5f);
bounds[0 + 3 * 2] = PositionTexture.Create(0, -1, 0, 0, 1);
bounds[1 + 3 * 2] = PositionTexture.Create(0, 0, -1, .5f, 1);
bounds[2 + 3 * 2] = PositionTexture.Create(0, -1, 0, 1, 1);
// Setup default matrix of points.
}
}
private PositionTexture Midpoint(PositionTexture positionNormalTextured, PositionTexture positionNormalTextured_2)
{
Vector3d a1 = Vector3d.Lerp(positionNormalTextured.Position, positionNormalTextured_2.Position, .5f);
Vector2d a1uv = Vector2d.Lerp(Vector2d.Create(positionNormalTextured.Tu, positionNormalTextured.Tv), Vector2d.Create(positionNormalTextured_2.Tu, positionNormalTextured_2.Tv), .5f);
a1.Normalize();
return PositionTexture.CreatePos(a1, a1uv.X, a1uv.Y);
}
int subDivisionLevel = 4;
bool subDivided = false;
public override bool CreateGeometry(RenderContext renderContext)
{
if (GeometryCreated)
{
return true;
}
GeometryCreated = true;
base.CreateGeometry(renderContext);
return true;
}
public PlotTile()
{
}
public static PlotTile Create(int level, int xc, int yc, Imageset dataset, Tile parent)
{
PlotTile temp = new PlotTile();
temp.Parent = parent;
temp.Level = level;
temp.tileX = xc;
temp.tileY = yc;
temp.dataset = dataset;
temp.topDown = !dataset.BottomsUp;
if (temp.tileX != (int)xc)
{
Script.Literal("alert('bad')");
}
//temp.ComputeQuadrant();
if (dataset.MeanRadius != 0)
{
temp.DemScaleFactor = dataset.MeanRadius;
}
else
{
if (dataset.DataSetType == ImageSetType.Earth)
{
temp.DemScaleFactor = 6371000;
}
else
{
temp.DemScaleFactor = 3396010;
}
}
temp.ComputeBoundingSphere();
return temp;
}
public override void CleanUp(bool removeFromParent)
{
base.CleanUp(removeFromParent);
if (vertexList != null)
{
vertexList = null;
}
if (childTriangleList != null)
{
childTriangleList = null;
}
subDivided = false;
demArray = null;
}
}
}
| Java |
<?php
/**
* This file is part of the browscap-json-cache package.
*
* (c) Thomas Mueller <mimmi20@live.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types = 1);
namespace Browscap\Cache;
use BrowscapPHP\Cache\BrowscapCacheInterface;
use WurflCache\Adapter\AdapterInterface;
/**
* a cache proxy to be able to use the cache adapters provided by the WurflCache package
*
* @category Browscap-PHP
*
* @copyright Copyright (c) 1998-2014 Browser Capabilities Project
*
* @version 3.0
*
* @license http://www.opensource.org/licenses/MIT MIT License
*
* @see https://github.com/browscap/browscap-php/
*/
final class JsonCache implements BrowscapCacheInterface
{
/**
* The cache livetime in seconds.
*
* @var int
*/
public const CACHE_LIVETIME = 315360000; // ~10 years (60 * 60 * 24 * 365 * 10)
/**
* Path to the cache directory
*
* @var \WurflCache\Adapter\AdapterInterface
*/
private $cache;
/**
* Detected browscap version (read from INI file)
*
* @var int
*/
private $version;
/**
* Release date of the Browscap data (read from INI file)
*
* @var string
*/
private $releaseDate;
/**
* Type of the Browscap data (read from INI file)
*
* @var string
*/
private $type;
/**
* Constructor class, checks for the existence of (and loads) the cache and
* if needed updated the definitions
*
* @param \WurflCache\Adapter\AdapterInterface $adapter
* @param int $updateInterval
*/
public function __construct(AdapterInterface $adapter, $updateInterval = self::CACHE_LIVETIME)
{
$this->cache = $adapter;
$this->cache->setExpiration($updateInterval);
}
/**
* Gets the version of the Browscap data
*
* @return int|null
*/
public function getVersion(): ?int
{
if (null === $this->version) {
$success = true;
$version = $this->getItem('browscap.version', false, $success);
if (null !== $version && $success) {
$this->version = (int) $version;
}
}
return $this->version;
}
/**
* Gets the release date of the Browscap data
*
* @return string
*/
public function getReleaseDate(): string
{
if (null === $this->releaseDate) {
$success = true;
$releaseDate = $this->getItem('browscap.releaseDate', false, $success);
if (null !== $releaseDate && $success) {
$this->releaseDate = $releaseDate;
}
}
return $this->releaseDate;
}
/**
* Gets the type of the Browscap data
*
* @return string|null
*/
public function getType(): ?string
{
if (null === $this->type) {
$success = true;
$type = $this->getItem('browscap.type', false, $success);
if (null !== $type && $success) {
$this->type = $type;
}
}
return $this->type;
}
/**
* Get an item.
*
* @param string $cacheId
* @param bool $withVersion
* @param bool|null $success
*
* @return mixed Data on success, null on failure
*/
public function getItem(string $cacheId, bool $withVersion = true, ?bool &$success = null)
{
if ($withVersion) {
$cacheId .= '.' . $this->getVersion();
}
if (!$this->cache->hasItem($cacheId)) {
$success = false;
return null;
}
$success = null;
$data = $this->cache->getItem($cacheId, $success);
if (!$success) {
$success = false;
return null;
}
if (!property_exists($data, 'content')) {
$success = false;
return null;
}
$success = true;
return $data->content;
}
/**
* save the content into an php file
*
* @param string $cacheId The cache id
* @param mixed $content The content to store
* @param bool $withVersion
*
* @return bool whether the file was correctly written to the disk
*/
public function setItem(string $cacheId, $content, bool $withVersion = true): bool
{
$data = new \stdClass();
// Get the whole PHP code
$data->content = $content;
if ($withVersion) {
$cacheId .= '.' . $this->getVersion();
}
// Save and return
return $this->cache->setItem($cacheId, $data);
}
/**
* Test if an item exists.
*
* @param string $cacheId
* @param bool $withVersion
*
* @return bool
*/
public function hasItem(string $cacheId, bool $withVersion = true): bool
{
if ($withVersion) {
$cacheId .= '.' . $this->getVersion();
}
return $this->cache->hasItem($cacheId);
}
/**
* Remove an item.
*
* @param string $cacheId
* @param bool $withVersion
*
* @return bool
*/
public function removeItem(string $cacheId, bool $withVersion = true): bool
{
if ($withVersion) {
$cacheId .= '.' . $this->getVersion();
}
return $this->cache->removeItem($cacheId);
}
/**
* Flush the whole storage
*
* @return bool
*/
public function flush(): bool
{
return $this->cache->flush();
}
}
| Java |
(function () {
"use strict";
require('futures/forEachAsync');
var fs = require('fs'),
crypto = require('crypto'),
path = require('path'),
exec = require('child_process').exec,
mime = require('mime'),
FileStat = require('filestat'),
dbaccess = require('../dbaccess'),
utils = require('../utils'),
hashAlgo = "md5";
function readFile(filePath, callback) {
var readStream, hash = crypto.createHash(hashAlgo);
readStream = fs.createReadStream(filePath);
readStream.on('data', function (data) {
hash.update(data);
});
readStream.on('error', function (err) {
console.log("Read Error: " + err.toString());
readStream.destroy();
fs.unlink(filePath);
callback(err);
});
readStream.on('end', function () {
callback(null, hash.digest("hex"));
});
}
function saveToFs(md5, filePath, callback) {
var newPath = utils.hashToPath(md5);
path.exists(newPath, function (exists) {
if (exists) {
fs.move(filePath, newPath, function (err) {
callback(err, newPath);
});
return;
}
exec('mkdir -p ' + newPath, function (err, stdout, stderr) {
var tError;
if (err || stderr) {
console.log("Err: " + (err ? err : "none"));
console.log("stderr: " + (stderr ? stderr : "none"));
tError = {error: err, stderr: stderr, stdout: stdout};
return callback(tError, newPath);
}
console.log("stdout: " + (stdout ? stdout : "none"));
fs.move(filePath, newPath, function (moveErr) {
callback(moveErr, newPath);
});
});
});
}
function addKeysToFileStats(fieldNames, stats) {
var fileStats = [];
stats.forEach(function (item) {
var fileStat = new FileStat();
item.forEach(function (fieldValue, i) {
fileStat[fieldNames[i]] = fieldValue;
});
if (fileStat.path) {
fileStat.type = mime.lookup(fileStat.path);
}
fileStats.push(fileStat);
});
return fileStats;
}
function importFile(fileStat, tmpFile, username, callback) {
var oldPath;
oldPath = tmpFile.path;
readFile(oldPath, function (err, md5) {
if (err) {
fileStat.err = err;
callback(err, fileStat);
return;
}
// if we have an md5sum and they don't match, abandon ship
if (fileStat.md5 && fileStat.md5 !== md5) {
callback("MD5 sums don't match");
return;
}
fileStat.md5 = md5;
fileStat.genTmd5(function (error, tmd5) {
if (!error) {
fileStat.tmd5 = tmd5;
saveToFs(fileStat.md5, oldPath, function (fserr) {
if (fserr) {
// ignoring possible unlink error
fs.unlink(oldPath);
fileStat.err = "File did not save";
} else {
dbaccess.put(fileStat, username);
}
callback(fserr, fileStat);
});
}
});
});
}
function handleUpload(req, res, next) {
if (!req.form) {
return next();
}
req.form.complete(function (err, fields, files) {
var fileStats, bFirst;
fields.statsHeader = JSON.parse(fields.statsHeader);
fields.stats = JSON.parse(fields.stats);
fileStats = addKeysToFileStats(fields.statsHeader, fields.stats);
dbaccess.createViews(req.remoteUser, fileStats);
res.writeHead(200, {'Content-Type': 'application/json'});
// response as array
res.write("[");
bFirst = true;
function handleFileStat(next, fileStat) {
// this callback is synchronous
fileStat.checkMd5(function (qmd5Error, qmd5) {
function finishReq(err) {
console.log(fileStat);
fileStat.err = err;
// we only want to add a comma after the first one
if (!bFirst) {
res.write(",");
}
bFirst = false;
res.write(JSON.stringify(fileStat));
return next();
}
if (qmd5Error) {
return finishReq(qmd5Error);
}
importFile(fileStat, files[qmd5], req.remoteUser, finishReq);
});
}
fileStats.forEachAsync(handleFileStat).then(function () {
// end response array
res.end("]");
});
});
}
module.exports = handleUpload;
}());
| Java |
#!/usr/bin/python
from typing import List, Optional
"""
16. 3Sum Closest
https://leetcode.com/problems/3sum-closest/
"""
def bsearch(nums, left, right, res, i, j, target):
while left <= right:
middle = (left + right) // 2
candidate = nums[i] + nums[j] + nums[middle]
if res is None or abs(candidate - target) < abs(res - target):
res = candidate
if candidate == target:
return res
elif candidate > target:
right = middle - 1
else:
left = middle + 1
return res
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> Optional[int]:
res = None
nums = sorted(nums)
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
res = bsearch(nums, j + 1, len(nums) - 1, res, i, j, target)
return res
def main():
sol = Solution()
print(sol.threeSumClosest([-111, -111, 3, 6, 7, 16, 17, 18, 19], 13))
return 0
if __name__ == '__main__':
raise SystemExit(main())
| Java |
package bits;
/**
* Created by krzysztofkaczor on 3/10/15.
*/
public class ExclusiveOrOperator implements BinaryOperator
{
@Override
public BitArray combine(BitArray operand1, BitArray operand2) {
if(operand1.size() != operand2.size()) {
throw new IllegalArgumentException("ExclusiveOrOperator operands must have same size");
}
int size = operand1.size();
BitArray result = new BitArray(size);
for (int i = 0;i < size;i++) {
boolean a = operand1.get(i);
boolean b = operand2.get(i);
result.set(i, a != b );
}
return result;
}
}
| Java |
---
layout: post
title: "Using the right terms: Method?"
date: 2015-08-05 12:00:00
comments: true
tags: [components, programming, components programming, componentsprogramming, stepanov, knuth, stroustrup, generic, genericprogramming, generic programming, genericity, concepts, math, mathematics, elements, eop, contracts, performance, c++, cpp, c, java, dotnet, c#, csharp, python, ruby, javascript, haskell, dlang, rust, golang, eiffel, templates, metaprogramming, book, fmgp]
---
(REVISIONISMO)
En esta serie de articulos mi intension es revisar por qué algunos programadores usamos cierta terminologia, ciertas palabras, algunas de las cuales, considero inadecuadas.
En este caso quiero hablar sobre la palabra "method".
Algunos colegas mios, más que nada colegas con background en Java o .Net suelen usar esta palabra, como por ejemplo: "Escribí un método que tome una fecha y retorne un string con el nombre del día".
Yo me pregunto: ¿Por qué decimos "metodo" y no utilizamos otra palabra como "procedimiento", "función", etc?
Cuando yo empecé a programar, casi nadie usaba la palabra "metodo" y de repente ahora es muy común.
Pero, antes de continuar con mi conjetura, me gustaría repasar (muy burdamente) sobre teoría de objetos.
¿Qué es un método?
Cualquier programador Java o C# (y otros lenguajes) le diría que un objeto tiene estado y comportamiento.
El estado se almacena en Fields y el comportamiento shown via Métodos.
O sea, un método es un procedimiento, funcion, routine, subroutine, pero que está incluido dentro de una clase en particular.
>>> O sea, un método es una serie de instrucciones, a las que se les pone un nombre.
Java y C# copian gran parte de su sintáxis y terminologia (glosario) de C++ (no así la semántica).
Pero en C++ no se usa el termino Method, sino que al comportamiento de los objetos se los codifica usando Member Functions.
(Al estado de los objetos se lo almacena en Data Members)
C++ es un lenguaje que soporta el paradigma de objetos, pero desde el nacimiento de C++, este no está atado a un solo paradigma.
C++ hereda de C el paradigma de programación estructurada, o sea, C++ es un lenguaje multi-paradigma, por lo tanto, permite la creacion de funciones, tanto dentro de una clase como fuera de ella. A las funciones que son creadas fuera de una clase se las suele llamar Non-Member Functions o Free Functions.
Más allá de esto, el termino "Method" se ha popularizado de tal forma que si dicen "metodo" cualquier programador C++ sabe de que estás hablando.
¿Por qué Java y C# no adoptaron la misma terminologia que C++? (En lo que respecta a comportamiento de objetos)
Bueno, C# borrowed a lot from Java, así que la pregunta sería, ¿Por qué Java no adoptaró la misma terminologia que C++?
(
Al margen: mas alla de que C# en sus comienzos era casi identico a Java, en ciertas cuestiones toma un camino separado a Java y quizás más cercano a C++, por ejemplo:
- No todos los métodos son virtuales
- In C# a parent and child classes are named Base and Derived clases, respectively (like in C++, see D&E of C++), but in Java are called Super and Sub classes.
)
Eso es dificil de saber, habría que charlar con los creadores del lenguaje para saber el porqué de la nomenclatura.
Para saber que es un método, primero me gustaría explorar distintas fuentes para saber cual es el origen de esa palabra en el ámbito informático.
...............................................................
Procedure
Function
Routine
Subroutine
Feature
Method
FORTRAN
FORTRAN was the first high-level programming language and the first high-quality optimizing compiler.
PROGRAM, FUNCTION, SUBROUTINE
Statement function
External function
Subroutine
"Method"
Fortran STANDARs Committee
http://www.nag.co.uk/sc22wg5/
Fortran 66
ftp://ftp.nag.co.uk/sc22wg5/ARCHIVE/Fortran66.pdf
Fortran 77
ftp://ftp.nag.co.uk/sc22wg5/ARCHIVE/Fortran77.html
Fortran 90
ftp://ftp.nag.co.uk/sc22wg5/N001-N1100/N692.pdf
Fortran 95
ftp://ftp.nag.co.uk/sc22wg5/N1151-N1200/N1191.pdf
Fortran 2003
ftp://ftp.nag.co.uk/sc22wg5/N1601-N1650/N1601.pdf
Fortran 2008 (working)
http://j3-fortran.org/doc/year/10/10-007r1.pdf
http://www.softwarepreservation.org/projects/FORTRAN/
Algol
ALGOL (short for ALGOrithmic Language)[1] is a family of imperative computer programming languages, originally developed in the mid-1950s, which greatly influenced many other languages and was the standard method for algorithm description used by the ACM in textbooks and academic sources for more than thirty years.[2]
In the sense that most modern languages are "algol-like",[3] it was arguably the most successful of the four high-level programming languages with which it was roughly contemporary
http://www.softwarepreservation.org/projects/ALGOL/
Simula
Procedure (ALGOL)
function procedure (ALGOL)
Parece que en SIMULA I un objeto (de OOP) es llamado Process
slp-complete.pdf - Chapter 2 - page 10
"It has its own local data and
its own behaviour pattern.
A system may contain several processes with a similar data
structure and the same behaviour pattern. Such processes are
said to belong to the same class, called an activity.""
SIMULA 67
1. 3. 3 Classes
A central new concept in SIMULA 67 is the "object".
An object is a self-contained program (block instance)
having its own local data and actions defined by a
"class declaration". The class declaration defines a
program (data and action) pattern, and objects conforming
to that pattern are said to "belong to the same class".
If no actions are specified in the class declaration,
a class of pure data structures is defined.
Smalltalk
NCITS J20 DRAFT December, 1997 of ANSI Smalltalk Standard revision 1.9
ANSI Smalltalk Standard v1.9 199712 NCITS X3J20 draft (PDF)
A Smalltalk program is a means for describing a dynamic computational process. This section
defines the entities that exist in the computational environment of Smalltalk programs.
A variable is a computational entity that stores a single reference (the value of the variable) to an
object.
A message is a request to perform a designated computation. An object is a computational entity
that is capable of responding to a well defined set of messages. An object may also encapsulate
some (possibly mutable) state.
An object responds to a message by executing a method. Each method is identified by an
associated method selector. A behavior is the set of methods used by an object to respond to
messages.
A method consists of a sequence of expressions. Program execution proceeds by sequentially
evaluating the expressions in one of more methods. There are three types of expressions:
assignments, message sends, and returns.
CLOS
C
C++
n3936.pdf
9.3 Member functions [class.mfct]
1 Functions declared in the definition of a class, excluding those declared with a friend specifier (11.3), are called member functions of that class. A member function may be declared static in which case it is a static member function of its class (9.4); otherwise it is a non-static member function of its class (9.3.1, 9.3.2).
Eiffel
1. ECMA Standard
2. BM - Object Oriented Software Construction vol.2
Eiffel - Object-Oriented Software Construction (2nd Ed) - Bertrand Meyer
Representing a
point in
cartesian
coordinates
Feature: Computation or Memory
This example shows the need for two kinds of feature:
• Some features will be represented by space, that is to say by associating a certain
piece of information with every instance of the class. They will be called attributes.
For points, x and y are attributes in cartesian representation; rho and theta are
attributes in polar representation.
• Some features will be represented by time, that is to say by defining a certain
computation (an algorithm) applicable to all instances of the class. They will be
called routines. For points, rho and theta are routines in cartesian representation; x
and y are routines in polar representation.
A further distinction affects routines (the second of these categories). Some routines
will return a result; they are called functions. Here x and y in polar representation, as well
as rho and theta in cartesian representation, are functions since they return a result, of type
REAL. Routines which do not return a result correspond to the commands of an ADT
specification and are called procedures. For example the class POINT will include
procedures translate, rotate and scale.
Java
Java Language Specification
8.4 Method Declarations
A method declares executable code that can be invoked, passing a fixed number of values as arguments.
227
8.4 Method Declarations
CLASSES
228
MethodDeclaration:
{MethodModifier} MethodHeader MethodBody
MethodHeader:
Result MethodDeclarator [Throws]
TypeParameters {Annotation} Result MethodDeclarator [Throws]
MethodDeclarator:
Identifier ( [FormalParameterList] ) [Dims]
The following production from §4.3 is shown here for convenience:
Dims:
{Annotation} [ ] {{Annotation} [ ]}
The FormalParameterList is described in §8.4.1, the MethodModifier clause in §8.4.3, the TypeParameters clause in §8.4.4, the Result clause in §8.4.5, the Throws clause in §8.4.6, and the MethodBody in §8.4.7.
The Identifier in a MethodDeclarator may be used in a name to refer to the method (§6.5.7.1, §15.12).
It is a compile-time error for the body of a class to declare as members two methods with override-equivalent signatures (§8.4.2).
The scope and shadowing of a method declaration is specified in §6.3 and §6.4.
The declaration of a method that returns an array is allowed to place some or all of the bracket pairs that denote the array type after the formal parameter list. This syntax is supported for compatibility with early versions of the Java programming language. It is very strongly recommended that this syntax is not used in new code.
Java Tutorials
Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.
https://docs.oracle.com/javase/tutorial/java/concepts/object.html
C#
C# Specification
C# ECMA Standard (ISO Standard)
8.7.3 Methods
A method is a member that implements a computation or action that can be performed by an object or class. Methods have a (possibly empty) list of formal parameters, a return value (unless the method’s return-type is void), and are either static or non-static. Static methods are accessed through the class. Non-static methods, which are also called instance methods, are accessed through instances of the class. A generic method (§25.6) has a list of one or more type parameters. The example
Python
APPENDIX A - GLOSSARY
method A function which is defined inside a class body. If called as an attribute of an instance of that class, the
method will get the instance object as its first argument (which is usually called self). See function and
nested scope.
function A series of statements which returns some value to a caller. It can also be passed zero or more arguments
which may be used in the execution of the body. See also parameter, method, and the Function definitions
section.
6.1 Expression statements
procedure
(a function that returns no meaningful result; in Python, procedures return the value None).
Knuth - The Art of Computer Programming
- Concrete Mathematics
Elements of Programming
Dijstra ?
Wirth ?
RAE
Britsh
Mathematics
"asymptotic methods"
"repertoire method"
general method
Real Academia Espanola
método.
(Del lat. methŏdus, y este del gr. μέθοδος).
1. m. Modo de decir o hacer con orden.
2. m. Modo de obrar o proceder, hábito o costumbre que cada uno tiene y observa.
3. m. Obra que enseña los elementos de una ciencia o arte.
4. m. Fil. Procedimiento que se sigue en las ciencias para hallar la verdad y enseñarla.
...............................................................
{% highlight cpp %}
class employee {
id: natural32
other: natural32
}
class test {
a: natural32 := 0x88FF7799
employees: array<employee> := { {0xA1B2C3D4, 0x11223344},
{0x92817348, 0x96161728},
{0x61592308, 0xa8857472 } }
b: natural32 := 0x12345678
}
//program entry-point
main() {
tc := test{}
// analyze memory here!
}
{% endhighlight %}
The program consists of a main function (entry-point) in which is created an object of type "test".
The test class has three data members (or Fields, in order to use Java/C# jargons):
- a: it is 32-bits natural number (like C/C++'s uint32_t). It is set to 88FF7799 (base16)
- employees: it is a sequence of elements of type "employee".
The employees sequence is filled with three elements.
- b: it is 32-bits natural number. It is set to 12345678 (base16)
The employee class has two data members:
- id: it is 32-bits natural number
- other: it is 32-bits natural number
Note: "array" is a data structure that stores elements contiguosly in memory.
The size of the sequence is dynamic, it is resizable.
Equivalents: C++ std::vector, .Net List<T>, Java ArrayList<T>
For example it is not necessary runtime polymorphism neither runtime type introspection (aka Reflection).
For simplicity all the data members are public.
Now, let's code in real programming languages:
C++ code
{% highlight cpp %}
#include <vector>
using namespace std;
struct employee {
uint32_t id;
uint32_t other;
};
struct test {
uint32_t a {0x88FF7799};
vector<employee> employees { {0xA1B2C3D4, 0x11223344},
{0x92817348, 0x96161728},
{0x61592308, 0xa8857472}};
uint32_t b {0x12345678};
};
int main(int argc, char const* argv[]) {
test t;
// analyze memory here!
return 0;
}
{% endhighlight %}
Java code:
{% highlight cpp %}
import java.util.ArrayList;
class Employee {
public int id;
public int other;
public Employee(int id, int other) {
this.id = id;
this.other = other;
}
}
class Test {
public int a = 0x88FF7799;
public ArrayList<Employee> employees = new ArrayList<Employee>();
public int b = 0x12345678;
public Test() {
employees.add(new Employee(0xA1B2C3D4, 0x11223344));
employees.add(new Employee(0x92817348, 0x96161728));
employees.add(new Employee(0x61592308, 0xa8857472));
}
}
public class MainClass {
public static void main(String args[]) {
Test t = new Test();
// analyze memory here!
}
}
{% endhighlight %}
C# code
{% highlight cpp %}
using System;
using System.Collections.Generic;
internal class Employee
{
public uint Id;
public uint Other;
public Employee(uint id, uint other)
{
Id = id;
Other = other;
}
}
internal class Test
{
public uint A = 0x88FF7799;
public List<Employee> Employees = new List<Employee> {
new Employee(0xA1B2C3D4, 0x11223344),
new Employee(0x92817348, 0x96161728),
new Employee(0x61592308, 0xa8857472) };
public uint B = 0x12345678;
}
class Program
{
static void Main(string[] args)
{
var t = new Test();
// analyze memory here!
}
}
{% endhighlight %}
I tried to write idiomatic code (as possible) in each of the languages.
I am not trying to be OO-purist.
I just tried to write the simplest code to later analyze the memory more easily.
Disclaimer: ....
References:
.Net BCL System.Array class specification:
https://msdn.microsoft.com/en-us/library/system.array%28v=vs.110%29.aspx
.Net BCL System.Array class source code:
http://referencesource.microsoft.com/#mscorlib/system/array.cs,1f52f2a267c6dbe7
.Net BCL System.Collections.Generic.List<T> class specification:
https://msdn.microsoft.com/en-us/library/6sh2ey19%28v=vs.110%29.aspx
.Net BCL System.Collections.Generic.List<T> class source code:
http://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs,cf7f4095e4de7646
Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects
https://msdn.microsoft.com/en-us/magazine/cc163791.aspx
Java ARTICLES
https://www.yourkit.com/docs/kb/sizes.jsp
https://wikis.oracle.com/display/HotSpotInternals/CompressedOops
http://www.docjar.com/docs/api/sun/misc/Unsafe.html
http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/
http://java-performance.info/memory-introspection-using-sun-misc-unsafe-and-reflection/
| Java |
/*"use strict";
var expect = require("expect.js"),
ShellController = require("../lib/shell-controller"),
testView = require("./test-shell-view");
describe("ShellController", function() {
var ctrl;
it("is defined", function() {
expect(ShellController).to.be.an("function");
});
describe("constructor", function() {
before(function() {
ctrl = new ShellController(testView);
});
it("create an object", function() {
expect(ctrl).to.be.an("object");
});
});
describe("on command event", function() {
before(function(done) {
ctrl.events.on("commandExecuted", done);
testView.invokeCommand("ls test/files --color");
});
after(function() {
testView.reset();
});
it("write commands output to view", function() {
var expected =
" <span style=\'color:rgba(170,170,170,255)\'>1.txt<br> 2.txt<br><br><br></span>";
expect(testView.content).to.be.equal(expected);
});
});
describe("findCommandRunner", function() {
var runner;
before(function(done) {
ctrl.findCommandRunner("ls test/files", function(cmdRunner) {
runner = cmdRunner;
done();
});
});
it("return a command runner", function() {
expect(runner.run).to.be.a("function");
});
});
});*/ | Java |
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// Database
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/mydb');
var index = require('./routes/index');
var buyer = require('./routes/buyer');
var seller = require('./routes/seller');
var products = require('./routes/products');
var app = express();
const ObjectID = mongo.ObjectID;
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Make our db accessible to our router
app.use(function(req,res,next){
req.db = db;
req.ObjectID = ObjectID;
next();
});
app.use('/', index);
app.use('/buyer', buyer);
app.use('/seller', seller);
app.use('/products', products);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error.html', err);
});
module.exports = app;
| Java |
# Smallest Integer
# I worked on this challenge [by myself, with: ].
# smallest_integer is a method that takes an array of integers as its input
# and returns the smallest integer in the array
#
# +list_of_nums+ is an array of integers
# smallest_integer(list_of_nums) should return the smallest integer in +list_of_nums+
#
# If +list_of_nums+ is empty the method should return nil
# Your Solution Below
def smallest_integer(list_of_nums)
if list_of_nums.empty?
return nil
else
list_of_nums.sort!
return list_of_nums[0]
end
end | Java |
FactoryGirl.define do
factory :user do
provider 'trello'
uid 'trello-special-uid'
full_name 'Dennis Martinez'
nickname 'dennmart'
oauth_token 'trello-token'
trait :admin do
admin true
end
end
end
| Java |
<!DOCTYPE html>
<html lang="en" ng-app="bookmarkApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bookmark</title>
<link type="text/css" href="app/bootstrap/css/bootstrap.min.css"
rel="stylesheet">
<link type="text/css"
href="app/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet">
<link href="app/css/bootstrap-combined.min.css" rel="stylesheet">
<link type="text/css" href="app/css/theme.css" rel="stylesheet">
<link type="text/css" href="app/css/ng-table.css" rel="stylesheet">
<link type="text/css" href="app/images/icons/css/font-awesome.css"
rel="stylesheet">
<link type="text/css"
href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600'
rel='stylesheet'>
</head>
<body >
<!-- /navbar -->
<div data-ng-view=""></div>
<script src="app/scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="app/scripts/jquery-ui-1.10.1.custom.min.js" type="text/javascript"></script>
<script src="app/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="app/scripts/angular.min.js"></script>
<script src="app/scripts/angular-route.js"></script>
<script src="app/scripts/angular-resource.min.js"></script>
<script src="app/scripts/angular-resource.min.js.map"></script>
<script src="app/scripts/angular-cookies.min.js"></script>
<script src="app/app.js"></script>
<script src="app/scripts/ng-table.js" type="text/javascript"></script>
<script src="app/bootstrap/js/ui-bootstrap-tpls-0.11.2.js"></script>
<script src="app/directives/commonDirective.js"></script>
<script src="app/controllers/resourceController.js"></script>
<script src="app/controllers/resourceGroupController.js"></script>
<script src="app/services/resourcegroupService.js"></script>
<script src="app/services/resourceService.js"></script>
<script src="app/services/loginService.js"></script>
<script src="app/controllers/userController.js"></script>
<script src="app/services/userservice.js"></script>
<script src="app/services/servicehelper.js"></script>
</body> | Java |
from multiprocessing import Pool
import os, time, random
def long_time_task(name):
print 'Run task %s (%s)...' % (name, os.getpid())
start = time.time()
time.sleep(random.random() * 3)
end = time.time()
print 'Task %s runs %0.2f seconds.' % (name, (end - start))
if __name__ == '__main__':
print 'Parent process %s.' % os.getpid()
p = Pool()
for i in range(5):
p.apply_async(long_time_task, args=(i,))
print 'Waiting for all subprocesses done...'
p.close()
p.join()
print 'All subprocesses done.'
"""
代码解读:
对Pool对象调用join()方法会等待所有子进程执行完毕,调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了。
请注意输出的结果,task 0,1,2,3是立刻执行的,而task 4要等待前面某个task完成后才执行,这是因为Pool的默认大小在我的电脑上是4,因此,最多同时执行4个进程。这是Pool有意设计的限制,并不是操作系统的限制。如果改成:
p = Pool(5)
""" | Java |
package net.comfreeze.lib;
import android.app.AlarmManager;
import android.app.Application;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.res.Resources;
import android.location.LocationManager;
import android.media.AudioManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import net.comfreeze.lib.audio.SoundManager;
import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.TimeZone;
abstract public class CFZApplication extends Application {
public static final String TAG = "CFZApplication";
public static final String PACKAGE = "com.rastermedia";
public static final String KEY_DEBUG = "debug";
public static final String KEY_SYNC_PREFEX = "sync_";
public static SharedPreferences preferences = null;
protected static Context context = null;
protected static CFZApplication instance;
public static LocalBroadcastManager broadcast;
public static boolean silent = true;
@Override
public void onCreate() {
if (!silent)
Log.d(TAG, "Initializing");
instance = this;
setContext();
setPreferences();
broadcast = LocalBroadcastManager.getInstance(context);
super.onCreate();
}
@Override
public void onLowMemory() {
if (!silent)
Log.d(TAG, "Low memory!");
super.onLowMemory();
}
@Override
public void onTerminate() {
unsetContext();
if (!silent)
Log.d(TAG, "Terminating");
super.onTerminate();
}
abstract public void setPreferences();
abstract public void setContext();
abstract public void unsetContext();
abstract public String getProductionKey();
public static CFZApplication getInstance(Class<?> className) {
// log("Returning current application instance");
if (instance == null) {
synchronized (className) {
if (instance == null)
try {
instance = (CFZApplication) className.newInstance();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
return instance;
}
public void clearApplicationData() {
File cache = getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String dir : children) {
if (!dir.equals("lib")) {
deleteDir(new File(appDir, dir));
}
}
}
preferences.edit().clear().commit();
}
private static boolean deleteDir(File dir) {
if (dir != null) {
if (!silent)
Log.d(PACKAGE, "Deleting: " + dir.getAbsolutePath());
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success)
return false;
}
}
return dir.delete();
}
return false;
}
public static int dipsToPixel(float value, float scale) {
return (int) (value * scale + 0.5f);
}
public static long timezoneOffset() {
Calendar calendar = Calendar.getInstance();
return (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET));
}
public static long timezoneOffset(String timezone) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(timezone));
return (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET));
}
public static Resources res() {
return context.getResources();
}
public static LocationManager getLocationManager(Context context) {
return (LocationManager) context.getSystemService(LOCATION_SERVICE);
}
public static AlarmManager getAlarmManager(Context context) {
return (AlarmManager) context.getSystemService(ALARM_SERVICE);
}
public static NotificationManager getNotificationManager(Context context) {
return (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
}
public static AudioManager getAudioManager(Context context) {
return (AudioManager) context.getSystemService(AUDIO_SERVICE);
}
public static SoundManager getSoundManager(CFZApplication application) {
return (SoundManager) SoundManager.instance(application);
}
public static void setSyncDate(String key, long date) {
preferences.edit().putLong(KEY_SYNC_PREFEX + key, date).commit();
}
public static long getSyncDate(String key) {
return preferences.getLong(KEY_SYNC_PREFEX + key, -1L);
}
public static boolean needSync(String key, long limit) {
return (System.currentTimeMillis() - getSyncDate(key) > limit);
}
public static String hash(final String algorithm, final String s) {
try {
// Create specified hash
MessageDigest digest = java.security.MessageDigest.getInstance(algorithm);
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// Create hex string
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String h = Integer.toHexString(0xFF & messageDigest[i]);
while (h.length() < 2)
h = "0" + h;
hexString.append(h);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
public boolean isProduction(Context context) {
boolean result = false;
try {
ComponentName component = new ComponentName(context, instance.getClass());
PackageInfo info = context.getPackageManager().getPackageInfo(component.getPackageName(), PackageManager.GET_SIGNATURES);
Signature[] sigs = info.signatures;
for (int i = 0; i < sigs.length; i++)
if (!silent)
Log.d(TAG, "Signing key: " + sigs[i].toCharsString());
String targetKey = getProductionKey();
if (null == targetKey)
targetKey = "";
if (targetKey.equals(sigs[0].toCharsString())) {
result = true;
if (!silent)
Log.d(TAG, "Signed with production key");
} else {
if (!silent)
Log.d(TAG, "Not signed with production key");
}
} catch (PackageManager.NameNotFoundException e) {
if (!silent)
Log.e(TAG, "Package exception", e);
}
return result;
}
public static class LOG {
// Without Throwables
public static void v(String tag, String message) {
if (!silent) Log.v(tag, message);
}
public static void d(String tag, String message) {
if (!silent) Log.d(tag, message);
}
public static void i(String tag, String message) {
if (!silent) Log.i(tag, message);
}
public static void w(String tag, String message) {
if (!silent) Log.w(tag, message);
}
public static void e(String tag, String message) {
if (!silent) Log.e(tag, message);
}
public static void wtf(String tag, String message) {
if (!silent) Log.wtf(tag, message);
}
// With Throwables
public static void v(String tag, String message, Throwable t) {
if (!silent) Log.v(tag, message, t);
}
public static void d(String tag, String message, Throwable t) {
if (!silent) Log.d(tag, message, t);
}
public static void i(String tag, String message, Throwable t) {
if (!silent) Log.i(tag, message, t);
}
public static void w(String tag, String message, Throwable t) {
if (!silent) Log.w(tag, message, t);
}
public static void e(String tag, String message, Throwable t) {
if (!silent) Log.e(tag, message, t);
}
public static void wtf(String tag, String message, Throwable t) {
if (!silent) Log.wtf(tag, message, t);
}
}
}
| Java |
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "WFBTLEServiceProcessor.h"
@class NSData, WFNordicDFUControlPointCh, WFNordicDFUPacketCh;
@interface WFBTLENordicDFUService : WFBTLEServiceProcessor
{
id <WFNordicDFUDelegate> delegate;
WFNordicDFUControlPointCh *dfuControlPointCh;
WFNordicDFUPacketCh *dfuPacketCh;
BOOL bDFUInProgress;
BOOL bStartTransferOnACK;
BOOL bFinishOnACK;
BOOL bWaitingForReceiveImageACK;
unsigned long ulImageSize;
unsigned long ulBytesSent;
NSData *firmwareData;
double startTime;
unsigned short usCRC;
unsigned short usProductId;
unsigned int packetIntervalTime;
unsigned char ucMaxRetries;
unsigned char ucRetryCount;
BOOL bTransferThreadRunning;
BOOL bBlockTransferThread;
BOOL bTransferCheckPassed;
BOOL bAbortImageTransfer;
}
@property(retain, nonatomic) id <WFNordicDFUDelegate> delegate; // @synthesize delegate;
- (void)setMaxRetries:(unsigned char)arg1;
- (void)setPacketIntervalTime:(unsigned int)arg1;
- (BOOL)sendHardReset;
- (BOOL)sendExitDFU;
- (BOOL)sendFirmware:(id)arg1;
- (void)sendFirmwareImage_TM;
- (void)sendFirmwareImage;
- (void)sendDFUInitParams;
- (BOOL)sendStartDFU;
- (void)restartTransfer;
- (void)delegateFinish:(unsigned char)arg1;
- (void)delegateUpdateBytesSent:(unsigned long)arg1;
- (void)delegateValidateFirmwareResponse:(unsigned char)arg1;
- (void)delegateReceiveFirmwareImageResponse:(unsigned char)arg1;
- (void)delegateInitDFUParamsResponse:(unsigned char)arg1;
- (void)delegateStartDFUResponse:(unsigned char)arg1 imageSize:(unsigned long)arg2;
- (void)reset;
- (id)getData;
- (BOOL)startUpdatingForService:(id)arg1 onPeripheral:(id)arg2;
- (void)peripheral:(id)arg1 didWriteValueForCharacteristic:(id)arg2 error:(id)arg3;
- (void)peripheral:(id)arg1 didUpdateValueForCharacteristic:(id)arg2 error:(id)arg3;
- (void)peripheral:(id)arg1 didUpdateNotificationStateForCharacteristic:(id)arg2 error:(id)arg3;
- (void)dealloc;
- (id)init;
@end
| Java |
/**
* @author yomboprime https://github.com/yomboprime
*
* GPUComputationRenderer, based on SimulationRenderer by zz85
*
* The GPUComputationRenderer uses the concept of variables. These variables are RGBA float textures that hold 4 floats
* for each compute element (texel)
*
* Each variable has a fragment shader that defines the computation made to obtain the variable in question.
* You can use as many variables you need, and make dependencies so you can use textures of other variables in the shader
* (the sampler uniforms are added automatically) Most of the variables will need themselves as dependency.
*
* The renderer has actually two render targets per variable, to make ping-pong. Textures from the current frame are used
* as inputs to render the textures of the next frame.
*
* The render targets of the variables can be used as input textures for your visualization shaders.
*
* Variable names should be valid identifiers and should not collide with THREE GLSL used identifiers.
* a common approach could be to use 'texture' prefixing the variable name; i.e texturePosition, textureVelocity...
*
* The size of the computation (sizeX * sizeY) is defined as 'resolution' automatically in the shader. For example:
* #DEFINE resolution vec2( 1024.0, 1024.0 )
*
* -------------
*
* Basic use:
*
* // Initialization...
*
* // Create computation renderer
* var gpuCompute = new GPUComputationRenderer( 1024, 1024, renderer );
*
* // Create initial state float textures
* var pos0 = gpuCompute.createTexture();
* var vel0 = gpuCompute.createTexture();
* // and fill in here the texture data...
*
* // Add texture variables
* var velVar = gpuCompute.addVariable( "textureVelocity", fragmentShaderVel, pos0 );
* var posVar = gpuCompute.addVariable( "texturePosition", fragmentShaderPos, vel0 );
*
* // Add variable dependencies
* gpuCompute.setVariableDependencies( velVar, [ velVar, posVar ] );
* gpuCompute.setVariableDependencies( posVar, [ velVar, posVar ] );
*
* // Add custom uniforms
* velVar.material.uniforms.time = { value: 0.0 };
*
* // Check for completeness
* var error = gpuCompute.init();
* if ( error !== null ) {
* console.error( error );
* }
*
*
* // In each frame...
*
* // Compute!
* gpuCompute.compute();
*
* // Update texture uniforms in your visualization materials with the gpu renderer output
* myMaterial.uniforms.myTexture.value = gpuCompute.getCurrentRenderTarget( posVar ).texture;
*
* // Do your rendering
* renderer.render( myScene, myCamera );
*
* -------------
*
* Also, you can use utility functions to create ShaderMaterial and perform computations (rendering between textures)
* Note that the shaders can have multiple input textures.
*
* var myFilter1 = gpuCompute.createShaderMaterial( myFilterFragmentShader1, { theTexture: { value: null } } );
* var myFilter2 = gpuCompute.createShaderMaterial( myFilterFragmentShader2, { theTexture: { value: null } } );
*
* var inputTexture = gpuCompute.createTexture();
*
* // Fill in here inputTexture...
*
* myFilter1.uniforms.theTexture.value = inputTexture;
*
* var myRenderTarget = gpuCompute.createRenderTarget();
* myFilter2.uniforms.theTexture.value = myRenderTarget.texture;
*
* var outputRenderTarget = gpuCompute.createRenderTarget();
*
* // Now use the output texture where you want:
* myMaterial.uniforms.map.value = outputRenderTarget.texture;
*
* // And compute each frame, before rendering to screen:
* gpuCompute.doRenderTarget( myFilter1, myRenderTarget );
* gpuCompute.doRenderTarget( myFilter2, outputRenderTarget );
*
*
*
* @param {int} sizeX Computation problem size is always 2d: sizeX * sizeY elements.
* @param {int} sizeY Computation problem size is always 2d: sizeX * sizeY elements.
* @param {WebGLRenderer} renderer The renderer
*/
import {
Camera,
ClampToEdgeWrapping,
DataTexture,
FloatType,
HalfFloatType,
Mesh,
NearestFilter,
PlaneBufferGeometry,
RGBAFormat,
Scene,
ShaderMaterial,
WebGLRenderTarget
} from "./three.module.js";
var GPUComputationRenderer = function ( sizeX, sizeY, renderer ) {
this.variables = [];
this.currentTextureIndex = 0;
var scene = new Scene();
var camera = new Camera();
camera.position.z = 1;
var passThruUniforms = {
passThruTexture: { value: null }
};
var passThruShader = createShaderMaterial( getPassThroughFragmentShader(), passThruUniforms );
var mesh = new Mesh( new PlaneBufferGeometry( 2, 2 ), passThruShader );
scene.add( mesh );
this.addVariable = function ( variableName, computeFragmentShader, initialValueTexture ) {
var material = this.createShaderMaterial( computeFragmentShader );
var variable = {
name: variableName,
initialValueTexture: initialValueTexture,
material: material,
dependencies: null,
renderTargets: [],
wrapS: null,
wrapT: null,
minFilter: NearestFilter,
magFilter: NearestFilter
};
this.variables.push( variable );
return variable;
};
this.setVariableDependencies = function ( variable, dependencies ) {
variable.dependencies = dependencies;
};
this.init = function () {
if ( ! renderer.extensions.get( "OES_texture_float" ) &&
! renderer.capabilities.isWebGL2 ) {
return "No OES_texture_float support for float textures.";
}
if ( renderer.capabilities.maxVertexTextures === 0 ) {
return "No support for vertex shader textures.";
}
for ( var i = 0; i < this.variables.length; i ++ ) {
var variable = this.variables[ i ];
// Creates rendertargets and initialize them with input texture
variable.renderTargets[ 0 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
variable.renderTargets[ 1 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 0 ] );
this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 1 ] );
// Adds dependencies uniforms to the ShaderMaterial
var material = variable.material;
var uniforms = material.uniforms;
if ( variable.dependencies !== null ) {
for ( var d = 0; d < variable.dependencies.length; d ++ ) {
var depVar = variable.dependencies[ d ];
if ( depVar.name !== variable.name ) {
// Checks if variable exists
var found = false;
for ( var j = 0; j < this.variables.length; j ++ ) {
if ( depVar.name === this.variables[ j ].name ) {
found = true;
break;
}
}
if ( ! found ) {
return "Variable dependency not found. Variable=" + variable.name + ", dependency=" + depVar.name;
}
}
uniforms[ depVar.name ] = { value: null };
material.fragmentShader = "\nuniform sampler2D " + depVar.name + ";\n" + material.fragmentShader;
}
}
}
this.currentTextureIndex = 0;
return null;
};
this.compute = function () {
var currentTextureIndex = this.currentTextureIndex;
var nextTextureIndex = this.currentTextureIndex === 0 ? 1 : 0;
for ( var i = 0, il = this.variables.length; i < il; i ++ ) {
var variable = this.variables[ i ];
// Sets texture dependencies uniforms
if ( variable.dependencies !== null ) {
var uniforms = variable.material.uniforms;
for ( var d = 0, dl = variable.dependencies.length; d < dl; d ++ ) {
var depVar = variable.dependencies[ d ];
uniforms[ depVar.name ].value = depVar.renderTargets[ currentTextureIndex ].texture;
}
}
// Performs the computation for this variable
this.doRenderTarget( variable.material, variable.renderTargets[ nextTextureIndex ] );
}
this.currentTextureIndex = nextTextureIndex;
};
this.getCurrentRenderTarget = function ( variable ) {
return variable.renderTargets[ this.currentTextureIndex ];
};
this.getAlternateRenderTarget = function ( variable ) {
return variable.renderTargets[ this.currentTextureIndex === 0 ? 1 : 0 ];
};
function addResolutionDefine( materialShader ) {
materialShader.defines.resolution = 'vec2( ' + sizeX.toFixed( 1 ) + ', ' + sizeY.toFixed( 1 ) + " )";
}
this.addResolutionDefine = addResolutionDefine;
// The following functions can be used to compute things manually
function createShaderMaterial( computeFragmentShader, uniforms ) {
uniforms = uniforms || {};
var material = new ShaderMaterial( {
uniforms: uniforms,
vertexShader: getPassThroughVertexShader(),
fragmentShader: computeFragmentShader
} );
addResolutionDefine( material );
return material;
}
this.createShaderMaterial = createShaderMaterial;
this.createRenderTarget = function ( sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter ) {
sizeXTexture = sizeXTexture || sizeX;
sizeYTexture = sizeYTexture || sizeY;
wrapS = wrapS || ClampToEdgeWrapping;
wrapT = wrapT || ClampToEdgeWrapping;
minFilter = minFilter || NearestFilter;
magFilter = magFilter || NearestFilter;
var renderTarget = new WebGLRenderTarget( sizeXTexture, sizeYTexture, {
wrapS: wrapS,
wrapT: wrapT,
minFilter: minFilter,
magFilter: magFilter,
format: RGBAFormat,
type: ( /(iPad|iPhone|iPod)/g.test( navigator.userAgent ) ) ? HalfFloatType : FloatType,
stencilBuffer: false,
depthBuffer: false
} );
return renderTarget;
};
this.createTexture = function () {
var a = new Float32Array( sizeX * sizeY * 4 );
var texture = new DataTexture( a, sizeX, sizeY, RGBAFormat, FloatType );
texture.needsUpdate = true;
return texture;
};
this.renderTexture = function ( input, output ) {
// Takes a texture, and render out in rendertarget
// input = Texture
// output = RenderTarget
passThruUniforms.passThruTexture.value = input;
this.doRenderTarget( passThruShader, output );
passThruUniforms.passThruTexture.value = null;
};
this.doRenderTarget = function ( material, output ) {
var currentRenderTarget = renderer.getRenderTarget();
mesh.material = material;
renderer.setRenderTarget( output );
renderer.render( scene, camera );
mesh.material = passThruShader;
renderer.setRenderTarget( currentRenderTarget );
};
// Shaders
function getPassThroughVertexShader() {
return "void main() {\n" +
"\n" +
" gl_Position = vec4( position, 1.0 );\n" +
"\n" +
"}\n";
}
function getPassThroughFragmentShader() {
return "uniform sampler2D passThruTexture;\n" +
"\n" +
"void main() {\n" +
"\n" +
" vec2 uv = gl_FragCoord.xy / resolution.xy;\n" +
"\n" +
" gl_FragColor = texture2D( passThruTexture, uv );\n" +
"\n" +
"}\n";
}
};
export { GPUComputationRenderer };
| Java |
package com.example.mesh;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class EndpointControlResource {
/**
* @see <a href="https://relay.bluejeans.com/docs/mesh.html#capabilities">https://relay.bluejeans.com/docs/mesh.html#capabilities</a>
*/
@GET
@Path("{ipAddress}/capabilities")
public Map<String, Boolean> capabilities(@PathParam("ipAddress") final String ipAddress,
@QueryParam("port") final Integer port,
@QueryParam("name") final String name) {
System.out.println("Received capabilities request");
System.out.println(" ipAddress = " + ipAddress);
System.out.println(" port = " + port);
System.out.println(" name = " + name);
final Map<String, Boolean> capabilities = new HashMap<>();
capabilities.put("JOIN", true);
capabilities.put("HANGUP", true);
capabilities.put("STATUS", true);
capabilities.put("MUTEMICROPHONE", true);
return capabilities;
}
/**
* @see <a href="https://relay.bluejeans.com/docs/mesh.html#status">https://relay.bluejeans.com/docs/mesh.html#status</a>
*/
@GET
@Path("{ipAddress}/status")
public Map<String, Boolean> status(@PathParam("ipAddress") final String ipAddress, @QueryParam("port") final Integer port,
@QueryParam("name") final String name) {
System.out.println("Received status request");
System.out.println(" ipAddress = " + ipAddress);
System.out.println(" port = " + port);
System.out.println(" name = " + name);
final Map<String, Boolean> status = new HashMap<>();
status.put("callActive", false);
status.put("microphoneMuted", false);
return status;
}
/**
* @see <a href="https://relay.bluejeans.com/docs/mesh.html#join">https://relay.bluejeans.com/docs/mesh.html#join</a>
*/
@POST
@Path("{ipAddress}/join")
public void join(@PathParam("ipAddress") final String ipAddress, @QueryParam("dialString") final String dialString,
@QueryParam("meetingId") final String meetingId, @QueryParam("passcode") final String passcode,
@QueryParam("bridgeAddress") final String bridgeAddress, final Endpoint endpoint) {
System.out.println("Received join request");
System.out.println(" ipAddress = " + ipAddress);
System.out.println(" dialString = " + dialString);
System.out.println(" meetingId = " + meetingId);
System.out.println(" passcode = " + passcode);
System.out.println(" bridgeAddress = " + bridgeAddress);
System.out.println(" endpoint = " + endpoint);
}
/**
* @see <a href="https://relay.bluejeans.com/docs/mesh.html#hangup">https://relay.bluejeans.com/docs/mesh.html#hangup</a>
*/
@POST
@Path("{ipAddress}/hangup")
public void hangup(@PathParam("ipAddress") final String ipAddress, final Endpoint endpoint) {
System.out.println("Received hangup request");
System.out.println(" ipAddress = " + ipAddress);
System.out.println(" endpoint = " + endpoint);
}
/**
* @see <a href="https://relay.bluejeans.com/docs/mesh.html#mutemicrophone">https://relay.bluejeans.com/docs/mesh.html#mutemicrophone</a>
*/
@POST
@Path("{ipAddress}/mutemicrophone")
public void muteMicrophone(@PathParam("ipAddress") final String ipAddress, final Endpoint endpoint) {
System.out.println("Received mutemicrophone request");
System.out.println(" ipAddress = " + ipAddress);
System.out.println(" endpoint = " + endpoint);
}
/**
* @see <a href="https://relay.bluejeans.com/docs/mesh.html#mutemicrophone">https://relay.bluejeans.com/docs/mesh.html#mutemicrophone</a>
*/
@POST
@Path("{ipAddress}/unmutemicrophone")
public void unmuteMicrophone(@PathParam("ipAddress") final String ipAddress, final Endpoint endpoint) {
System.out.println("Received unmutemicrophone request");
System.out.println(" ipAddress = " + ipAddress);
System.out.println(" endpoint = " + endpoint);
}
}
| Java |
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#include <errno.h>
#include "semaphore.h"
typedef struct lock {
Semaphore *sem;
} Lock;
Lock *make_lock ()
{
Lock *lock = (Lock *) malloc (sizeof(Lock));
lock->sem = make_semaphore(1);
return lock;
}
void lock_acquire (Lock *lock)
{
semaphore_wait(lock->sem);
}
void lock_release (Lock *lock)
{
semaphore_signal(lock->sem);
}
| Java |
<section id="main">
<a href="./#/mocks"><- Back to mocks list</a>
<nav id="secondary" class="main-nav">
<div class="mock-picture">
<div class="avatar">
<img ng-show="mock" src="img/mocks/{{mock.Mock.mockId}}.png" />
<img ng-show="mock" src="img/flags/{{mock.Mock.nationality}}.png" /><br/>
{{mock.mock.givenName}} {{mock.mock.familyName}}
</div>
</div>
<div class="mock-status">
Country: {{mock.mock.nationality}} <br/>
Team: {{mock.Constructors[0].name}}<br/>
Birth: {{mock.mock.dateOfBirth}}<br/>
<a href="{{mock.Mock.url}}" target="_blank">Biography</a>
</div>
</nav>
<div class="main-content">
<table class="result-table">
<thead>
<tr><th colspan="5">Formula 1 2013 Results</th></tr>
</thead>
<tbody>
<tr>
<td>Round</td> <td>Grand Prix</td> <td>Team</td> <td>Grid</td> <td>Race</td>
</tr>
<tr ng-repeat="race in races">
<td>{{race.round}}</td>
<td><img src="img/flags/{{race.Circuit.Location.country}}.png" />{{race.raceName}}</td>
<td>{{race.Results[0].Constructor.name}}</td>
<td>{{race.Results[0].grid}}</td>
<td>{{race.Results[0].position}}</td>
</tr>
</tbody>
</table>
</div>
</section>
| Java |
/*jshint node:true*/
/*global test, suite, setup, teardown*/
'use strict';
var assert = require('assert');
var tika = require('../');
suite('document tests', function() {
test('detect txt content-type', function(done) {
tika.type('test/data/file.txt', function(err, contentType) {
assert.ifError(err);
assert.equal(typeof contentType, 'string');
assert.equal(contentType, 'text/plain');
done();
});
});
test('detect txt content-type and charset', function(done) {
tika.typeAndCharset('test/data/file.txt', function(err, contentType) {
assert.ifError(err);
assert.equal(typeof contentType, 'string');
assert.equal(contentType, 'text/plain; charset=ISO-8859-1');
done();
});
});
test('extract from txt', function(done) {
tika.text('test/data/file.txt', function(err, text) {
assert.ifError(err);
assert.equal(typeof text, 'string');
assert.equal(text, 'Just some text.\n\n');
done();
});
});
test('extract meta from txt', function(done) {
tika.meta('test/data/file.txt', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.equal(typeof meta.resourceName[0], 'string');
assert.deepEqual(meta.resourceName, ['file.txt']);
assert.deepEqual(meta['Content-Type'], ['text/plain; charset=ISO-8859-1']);
assert.deepEqual(meta['Content-Encoding'], ['ISO-8859-1']);
done();
});
});
test('extract meta and text from txt', function(done) {
tika.extract('test/data/file.txt', function(err, text, meta) {
assert.ifError(err);
assert.equal(typeof text, 'string');
assert.equal(text, 'Just some text.\n\n');
assert.ok(meta);
assert.equal(typeof meta.resourceName[0], 'string');
assert.deepEqual(meta.resourceName, ['file.txt']);
assert.deepEqual(meta['Content-Type'], ['text/plain; charset=ISO-8859-1']);
assert.deepEqual(meta['Content-Encoding'], ['ISO-8859-1']);
done();
});
});
test('extract from extensionless txt', function(done) {
tika.text('test/data/extensionless/txt', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Just some text.\n\n');
done();
});
});
test('extract from doc', function(done) {
tika.text('test/data/file.doc', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Just some text.\n');
done();
});
});
test('extract meta from doc', function(done) {
tika.meta('test/data/file.doc', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['file.doc']);
assert.deepEqual(meta['Content-Type'], ['application/msword']);
assert.deepEqual(meta['dcterms:created'], ['2013-12-06T21:15:26Z']);
done();
});
});
test('extract from extensionless doc', function(done) {
tika.text('test/data/extensionless/doc', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Just some text.\n');
done();
});
});
test('extract from docx', function(done) {
tika.text('test/data/file.docx', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Just some text.\n');
done();
});
});
test('extract meta from docx', function(done) {
tika.meta('test/data/file.docx', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['file.docx']);
assert.deepEqual(meta['Content-Type'], ['application/vnd.openxmlformats-officedocument.wordprocessingml.document']);
assert.deepEqual(meta['Application-Name'], ['LibreOffice/4.1.3.2$MacOSX_x86 LibreOffice_project/70feb7d99726f064edab4605a8ab840c50ec57a']);
done();
});
});
test('extract from extensionless docx', function(done) {
tika.text('test/data/extensionless/docx', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Just some text.\n');
done();
});
});
test('extract meta from extensionless docx', function(done) {
tika.meta('test/data/extensionless/docx', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['docx']);
assert.deepEqual(meta['Content-Type'], ['application/vnd.openxmlformats-officedocument.wordprocessingml.document']);
assert.deepEqual(meta['Application-Name'], ['LibreOffice/4.1.3.2$MacOSX_x86 LibreOffice_project/70feb7d99726f064edab4605a8ab840c50ec57a']);
done();
});
});
test('extract from pdf', function(done) {
tika.text('test/data/file.pdf', function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'Just some text.');
done();
});
});
test('detect content-type of pdf', function(done) {
tika.type('test/data/file.pdf', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'application/pdf');
done();
});
});
test('extract meta from pdf', function(done) {
tika.meta('test/data/file.pdf', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['file.pdf']);
assert.deepEqual(meta['Content-Type'], ['application/pdf']);
assert.deepEqual(meta.producer, ['LibreOffice 4.1']);
done();
});
});
test('extract from extensionless pdf', function(done) {
tika.text('test/data/extensionless/pdf', function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'Just some text.');
done();
});
});
test('extract meta from extensionless pdf', function(done) {
tika.meta('test/data/extensionless/pdf', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['pdf']);
assert.deepEqual(meta['Content-Type'], ['application/pdf']);
assert.deepEqual(meta.producer, ['LibreOffice 4.1']);
done();
});
});
test('extract from protected pdf', function(done) {
tika.text('test/data/protected/file.pdf', function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'Just some text.');
done();
});
});
test('extract meta from protected pdf', function(done) {
tika.meta('test/data/protected/file.pdf', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['file.pdf']);
assert.deepEqual(meta['Content-Type'], ['application/pdf']);
assert.deepEqual(meta.producer, ['LibreOffice 4.1']);
done();
});
});
});
suite('partial document extraction tests', function() {
test('extract from long txt', function(done) {
tika.text('test/data/big/file.txt', { maxLength: 10 }, function(err, text) {
assert.ifError(err);
assert.equal(text.length, 10);
assert.equal(text, 'Lorem ipsu');
done();
});
});
test('extract from pdf', function(done) {
tika.text('test/data/file.pdf', { maxLength: 10 }, function(err, text) {
assert.ifError(err);
assert.equal(text.length, 10);
assert.equal(text.trim(), 'Just some');
done();
});
});
});
suite('obscure document tests', function() {
test('extract from Word 2003 XML', function(done) {
tika.text('test/data/obscure/word2003.xml', function(err, text) {
assert.ifError(err);
assert.ok(-1 !== text.indexOf('Just some text.'));
assert.ok(-1 === text.indexOf('<?xml'));
done();
});
});
});
suite('structured data tests', function() {
test('extract from plain XML', function(done) {
tika.text('test/data/structured/plain.xml', function(err, text) {
assert.ifError(err);
assert.ok(-1 !== text.indexOf('Just some text.'));
assert.ok(-1 === text.indexOf('<?xml'));
done();
});
});
});
suite('image tests', function() {
test('extract from png', function(done) {
tika.text('test/data/file.png', function(err, text) {
assert.ifError(err);
assert.equal(text, '');
done();
});
});
test('extract from extensionless png', function(done) {
tika.text('test/data/extensionless/png', function(err, text) {
assert.ifError(err);
assert.equal(text, '');
done();
});
});
test('extract from gif', function(done) {
tika.text('test/data/file.gif', function(err, text) {
assert.ifError(err);
assert.equal(text, '');
done();
});
});
test('extract meta from gif', function(done) {
tika.meta('test/data/file.gif', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['file.gif']);
assert.deepEqual(meta['Content-Type'], ['image/gif']);
assert.deepEqual(meta['Dimension ImageOrientation'], ['Normal']);
done();
});
});
test('extract from extensionless gif', function(done) {
tika.text('test/data/extensionless/gif', function(err, text) {
assert.ifError(err);
assert.equal(text, '');
done();
});
});
test('extract meta from extensionless gif', function(done) {
tika.meta('test/data/extensionless/gif', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['gif']);
assert.deepEqual(meta['Content-Type'], ['image/gif']);
assert.deepEqual(meta['Dimension ImageOrientation'], ['Normal']);
done();
});
});
});
suite('non-utf8 encoded document tests', function() {
test('extract Windows Latin 1 text', function(done) {
tika.text('test/data/nonutf8/windows-latin1.txt', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Algún pequeño trozo de texto.\n\n');
done();
});
});
test('detect Windows Latin 1 text charset', function(done) {
tika.charset('test/data/nonutf8/windows-latin1.txt', function(err, charset) {
assert.ifError(err);
assert.equal(typeof charset, 'string');
assert.equal(charset, 'ISO-8859-1');
done();
});
});
test('detect Windows Latin 1 text content-type and charset', function(done) {
tika.typeAndCharset('test/data/nonutf8/windows-latin1.txt', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'text/plain; charset=ISO-8859-1');
done();
});
});
test('extract UTF-16 English-language text', function(done) {
tika.text('test/data/nonutf8/utf16-english.txt', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Just some text.\n\n');
done();
});
});
test('detect UTF-16 English-language text charset', function(done) {
tika.charset('test/data/nonutf8/utf16-english.txt', function(err, charset) {
assert.ifError(err);
assert.equal(charset, 'UTF-16LE');
done();
});
});
test('detect UTF-16 English-language text content-type and charset', function(done) {
tika.typeAndCharset('test/data/nonutf8/utf16-english.txt', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'text/plain; charset=UTF-16LE');
done();
});
});
test('extract UTF-16 Chinese (Simplified) text', function(done) {
tika.text('test/data/nonutf8/utf16-chinese.txt', function(err, text) {
assert.ifError(err);
assert.equal(text, '\u53ea\u662f\u4e00\u4e9b\u6587\u5b57\u3002\n\n');
done();
});
});
test('detect UTF-16 Chinese (Simplified) text charset', function(done) {
tika.charset('test/data/nonutf8/utf16-chinese.txt', function(err, charset) {
assert.ifError(err);
assert.equal(charset, 'UTF-16LE');
done();
});
});
test('detect UTF-16 Chinese (Simplified) text content-type and charset', function(done) {
tika.typeAndCharset('test/data/nonutf8/utf16-chinese.txt', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'text/plain; charset=UTF-16LE');
done();
});
});
});
suite('archive tests', function() {
test('extract from compressed archive', function(done) {
tika.text('test/data/archive/files.zip', function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'file1.txt\nSome text 1.\n\n\n\n\nfile2.txt\nSome text 2.\n\n\n\n\nfile3.txt\nSome text 3.');
done();
});
});
test('extract from compressed zlib archive', function(done) {
tika.text('test/data/archive/files.zlib', function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'files\nSome text 1.\nSome text 2.\nSome text 3.');
done();
});
});
test('detect compressed archive content-type', function(done) {
tika.type('test/data/archive/files.zip', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'application/zip');
done();
});
});
test('extract from twice compressed archive', function(done) {
tika.text('test/data/archive/files-files.zip', function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'file4.txt\nSome text 4.\n\n\n\n\nfile5.txt\nSome text 5.\n\n\n\n\nfile6.txt\nSome text 6.\n\n\n\n\nfiles.zip\n\n\nfile1.txt\n\nSome text 1.\n\n\n\n\n\n\n\nfile2.txt\n\nSome text 2.\n\n\n\n\n\n\n\nfile3.txt\n\nSome text 3.');
done();
});
});
});
suite('encrypted doc tests', function() {
test('detect encrypted pdf content-type', function(done) {
tika.type('test/data/encrypted/file.pdf', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'application/pdf');
done();
});
});
test('detect encrypted doc content-type', function(done) {
tika.type('test/data/encrypted/file.doc', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'application/msword');
done();
});
});
test('specify password to decrypt document', function(done) {
tika.text('test/data/encrypted/file.pdf', {
password: 'password'
}, function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'Just some text.');
done();
});
});
});
suite('error handling tests', function() {
test('extract from encrypted doc', function(done) {
tika.text('test/data/encrypted/file.doc', function(err, text) {
assert.ok(err);
assert.ok(-1 !== err.toString().indexOf('EncryptedDocumentException: Cannot process encrypted word file'));
done();
});
});
test('extract from encrypted pdf', function(done) {
tika.text('test/data/encrypted/file.pdf', function(err, text) {
assert.ok(err);
assert.ok(-1 !== err.toString().indexOf('Unable to process: document is encrypted'));
done();
});
});
});
suite('http extraction tests', function() {
test('extract from pdf over http', function(done) {
tika.text('http://www.ohchr.org/EN/UDHR/Documents/UDHR_Translations/eng.pdf', function(err, text) {
assert.ifError(err);
assert.ok(-1 !== text.indexOf('Universal Declaration of Human Rights'));
done();
});
});
});
suite('ftp extraction tests', function() {
test('extract from text file over ftp', function(done) {
tika.text('ftp://ftp.ed.ac.uk/INSTRUCTIONS-FOR-USING-THIS-SERVICE', function(err, text) {
assert.ifError(err);
assert.ok(-1 !== text.indexOf('This service is managed by Information Services'));
done();
});
});
});
suite('language detection tests', function() {
test('detect English text', function(done) {
tika.language('This just some text in English.', function(err, language, reasonablyCertain) {
assert.ifError(err);
assert.equal(typeof language, 'string');
assert.equal(typeof reasonablyCertain, 'boolean');
assert.equal(language, 'en');
done();
});
});
});
| Java |
---
title: Workshop Title
layout: workshop
---
# Introduction to REDCap
--------
---------
Please have a REDCap account if you want to follow along.
- **REDCap**: [login here](https://edc.camhx.ca/redcap/)
---------
***Demographics Form***
- Record ID
- Date of assessment
- Initials
- DOB
- Handedness
- Sex
- Race
- White.
- Black or African American.
- American Indian or Alaska Native.
- Asian.
- Native Hawaiian or Other Pacific Islander.
- Other, not specified above.
- Mixed, more than 1 Race.
- Unknown or Not Reported (participants always have the right to not identify with any category)
- Ethnicity
- Not Hispanic or Latino
- Hispanic, of Spanish Origin or Latino (e.g. Cuban, Mexican, Puerto Rican, South American)
- Unknown or Not Reported (participants always have the right to not identify with any category)
- Comments
---------
***Example instrument for us to program***
1. On most days, I feel happy
2. My temperament is similar to that of my peers
3. I usually find it hard to get out of bed
4. I often cry for no reason
5. Overall, I lead a good life
---------
***Example instrument for us to upload***
[SANS.xlsx](/compucool/workshops/data/SANS.xlsx)
---------
***Example data for us to upload***
[SANS_data.csv](/compucool/workshops/data/SANS_data.csv)
| Java |
<html>
<head>
<title>im a title</title>
<META http-equiv='x-ua-compatible' content="IE=edge,chrome=1" />
<script>
junk
</script>
</head>
<body>im some body text</body>
</html>
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React Webpack Boilerplate</title>
</head>
<body>
<div id="root"></div>
<script src="/bundle.js"></script>
</body>
</html> | Java |
<?php
namespace Screeenly\Screenshot;
/**
* Interface description.
*
* @author Stefan Zweifel
*/
interface ClientInterface
{
/**
* Method description.
*
* @author Stefan Zweifel
*
* @param type $parameter
*
* @return type
*/
public function build();
public function capture(Screenshot $screenshot);
}
| Java |
// cpu/test/unique-strings.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// Copyright (C) 2015 Dietmar Kuehl http://www.dietmar-kuehl.de
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify,
// merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// ----------------------------------------------------------------------------
#include "cpu/tube/context.hpp"
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <iterator>
#include <string>
#include <random>
#include <set>
#include <unordered_set>
#include <vector>
#if defined(HAS_BSL)
#include <bsl_set.h>
#include <bsl_unordered_set.h>
#endif
#include <stdlib.h>
// ----------------------------------------------------------------------------
namespace std {
template <typename Algo>
void hashAppend(Algo& algo, std::string const& value) {
algo(value.c_str(), value.size());
}
}
// ----------------------------------------------------------------------------
namespace {
struct std_algos {
std::string name() const { return "std::sort()/std::unique()"; }
std::size_t run(std::vector<std::string> const& keys) const {
std::vector<std::string> values(keys.begin(), keys.end());
std::sort(values.begin(), values.end());
auto end = std::unique(values.begin(), values.end());
values.erase(end, values.end());
return values.size();
}
};
struct std_set {
std::string name() const { return "std::set<std::string>"; }
std::size_t run(std::vector<std::string> const& keys) const {
std::set<std::string> values(keys.begin(), keys.end());
return values.size();
}
};
struct std_insert_set {
std::string name() const { return "std::set<std::string> (insert)"; }
std::size_t run(std::vector<std::string> const& keys) const {
std::set<std::string> values;
for (std::string value: keys) {
values.insert(value);
}
return values.size();
}
};
struct std_reverse_set {
std::string name() const { return "std::set<std::string> (reverse)"; }
std::size_t run(std::vector<std::string> const& keys) const {
std::set<std::string> values;
for (std::string value: keys) {
std::reverse(value.begin(), value.end());
values.insert(value);
}
return values.size();
}
};
struct std_unordered_set {
std::string name() const { return "std::unordered_set<std::string>"; }
std::size_t run(std::vector<std::string> const& keys) const {
std::unordered_set<std::string> values(keys.begin(), keys.end());
return values.size();
}
};
struct std_insert_unordered_set {
std::string name() const { return "std::unordered_set<std::string> (insert)"; }
std::size_t run(std::vector<std::string> const& keys) const {
std::unordered_set<std::string> values;
for (std::string value: keys) {
values.insert(value);
}
return values.size();
}
};
struct std_reserve_unordered_set {
std::string name() const { return "std::unordered_set<std::string> (reserve)"; }
std::size_t run(std::vector<std::string> const& keys) const {
std::unordered_set<std::string> values;
values.reserve(keys.size());
for (std::string value: keys) {
values.insert(value);
}
return values.size();
}
};
#if defined(HAS_BSL)
struct bsl_set {
std::string name() const { return "bsl::set<std::string>"; }
std::size_t run(std::vector<std::string> const& keys) const {
bsl::set<std::string> values(keys.begin(), keys.end());
return values.size();
}
};
struct bsl_insert_set {
std::string name() const { return "bsl::set<std::string> (insert)"; }
std::size_t run(std::vector<std::string> const& keys) const {
bsl::set<std::string> values;
for (std::string value: keys) {
values.insert(value);
}
return values.size();
}
};
struct bsl_reverse_set {
std::string name() const { return "bsl::set<std::string> (reverse)"; }
std::size_t run(std::vector<std::string> const& keys) const {
bsl::set<std::string> values;
for (std::string value: keys) {
std::reverse(value.begin(), value.end());
values.insert(value);
}
return values.size();
}
};
struct bsl_unordered_set {
std::string name() const { return "bsl::unordered_set<std::string>"; }
std::size_t run(std::vector<std::string> const& keys) const {
bsl::unordered_set<std::string> values(keys.begin(), keys.end());
return values.size();
}
};
struct bsl_insert_unordered_set {
std::string name() const { return "bsl::unordered_set<std::string> (insert)"; }
std::size_t run(std::vector<std::string> const& keys) const {
bsl::unordered_set<std::string> values;
for (std::string value: keys) {
values.insert(value);
}
return values.size();
}
};
struct bsl_reserve_unordered_set {
std::string name() const { return "bsl::unordered_set<std::string> (reserve)"; }
std::size_t run(std::vector<std::string> const& keys) const {
bsl::unordered_set<std::string> values;
values.reserve(keys.size());
for (std::string value: keys) {
values.insert(value);
}
return values.size();
}
};
#endif
}
// ----------------------------------------------------------------------------
namespace {
template <typename Algo>
void measure(cpu::tube::context& context,
std::vector<std::string> const& keys,
std::size_t basesize,
Algo algo)
{
auto timer = context.start();
std::size_t size = algo.run(keys);
auto time = timer.measure();
std::ostringstream out;
out << std::left << std::setw(50) << algo.name()
<< " [" << keys.size() << "/" << basesize << "]";
context.report(out.str(), time, size);
}
}
static void measure(cpu::tube::context& context,
std::vector<std::string> const& keys,
std::size_t basesize)
{
measure(context, keys, basesize, std_algos());
measure(context, keys, basesize, std_set());
measure(context, keys, basesize, std_insert_set());
measure(context, keys, basesize, std_reverse_set());
measure(context, keys, basesize, std_unordered_set());
measure(context, keys, basesize, std_insert_unordered_set());
measure(context, keys, basesize, std_reserve_unordered_set());
#if defined(HAS_BSL)
measure(context, keys, basesize, bsl_set());
measure(context, keys, basesize, bsl_insert_set());
measure(context, keys, basesize, bsl_reverse_set());
measure(context, keys, basesize, bsl_unordered_set());
measure(context, keys, basesize, bsl_insert_unordered_set());
measure(context, keys, basesize, bsl_reserve_unordered_set());
#endif
}
// ----------------------------------------------------------------------------
static void run_tests(cpu::tube::context& context, int size) {
std::string const bases[] = {
"/usr/local/include/",
"/some/medium/sized/path/as/a/prefix/to/the/actual/interesting/names/",
"/finally/a/rather/long/string/including/pointless/sequences/like/"
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/"
"just/to/make/the/string/longer/to/qualify/as/an/actual/long/string/"
};
std::mt19937 gen(4711);
std::uniform_int_distribution<> rand(0, size * 0.8);
for (std::string const& base: bases) {
std::vector<std::string> keys;
keys.reserve(size);
int i = 0;
std::generate_n(std::back_inserter(keys), size,
[i, &base, &rand, &gen]()mutable{
return base + std::to_string(rand(gen));
});
measure(context, keys, base.size());
}
}
// ----------------------------------------------------------------------------
int main(int ac, char* av[])
{
cpu::tube::context context(CPUTUBE_CONTEXT_ARGS(ac, av));
int size(ac == 1? 0: atoi(av[1]));
if (size) {
run_tests(context, size);
}
else {
for (int i(10); i <= 100000; i *= 10) {
for (int j(1); j < 10; j *= 2) {
run_tests(context, i * j);
}
}
}
}
| Java |
#!/usr/bin/env bash
PIDFILE="$HOME/.brianbondy_nodejs.pid"
if [ -e "${PIDFILE}" ] && (ps -u $USER -f | grep "[ ]$(cat ${PIDFILE})[ ]"); then
echo "Already running."
exit 99
fi
PATH=/home/tweetpig/webapps/brianbondy_node/bin:$PATH LD_LIBRARY_PATH=/home/tweetpig/lib/libgif NODE_ENV=production PORT=32757 /home/tweetpig/webapps/brianbondy_node/bin/node --harmony --max-old-space-size=200 /home/tweetpig/webapps/brianbondy_node/dist/server.js --brianbondy_node > $HOME/.brianbondy_nodejs.log &
echo $! > "${PIDFILE}"
chmod 644 "${PIDFILE}"
| Java |
/*
* Encog(tm) Core v3.1 - Java Version
* http://www.heatonresearch.com/encog/
* http://code.google.com/p/encog-java/
* Copyright 2008-2012 Heaton Research, Inc.
*
* 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.plugin.system;
import org.encog.EncogError;
import org.encog.engine.network.activation.ActivationFunction;
import org.encog.ml.MLMethod;
import org.encog.ml.data.MLDataSet;
import org.encog.ml.factory.MLTrainFactory;
import org.encog.ml.factory.train.AnnealFactory;
import org.encog.ml.factory.train.BackPropFactory;
import org.encog.ml.factory.train.ClusterSOMFactory;
import org.encog.ml.factory.train.GeneticFactory;
import org.encog.ml.factory.train.LMAFactory;
import org.encog.ml.factory.train.ManhattanFactory;
import org.encog.ml.factory.train.NeighborhoodSOMFactory;
import org.encog.ml.factory.train.NelderMeadFactory;
import org.encog.ml.factory.train.PNNTrainFactory;
import org.encog.ml.factory.train.PSOFactory;
import org.encog.ml.factory.train.QuickPropFactory;
import org.encog.ml.factory.train.RBFSVDFactory;
import org.encog.ml.factory.train.RPROPFactory;
import org.encog.ml.factory.train.SCGFactory;
import org.encog.ml.factory.train.SVMFactory;
import org.encog.ml.factory.train.SVMSearchFactory;
import org.encog.ml.factory.train.TrainBayesianFactory;
import org.encog.ml.train.MLTrain;
import org.encog.plugin.EncogPluginBase;
import org.encog.plugin.EncogPluginService1;
public class SystemTrainingPlugin implements EncogPluginService1 {
/**
* The factory for K2
*/
private final TrainBayesianFactory bayesianFactory = new TrainBayesianFactory();
/**
* The factory for backprop.
*/
private final BackPropFactory backpropFactory = new BackPropFactory();
/**
* The factory for LMA.
*/
private final LMAFactory lmaFactory = new LMAFactory();
/**
* The factory for RPROP.
*/
private final RPROPFactory rpropFactory = new RPROPFactory();
/**
* THe factory for basic SVM.
*/
private final SVMFactory svmFactory = new SVMFactory();
/**
* The factory for SVM-Search.
*/
private final SVMSearchFactory svmSearchFactory = new SVMSearchFactory();
/**
* The factory for SCG.
*/
private final SCGFactory scgFactory = new SCGFactory();
/**
* The factory for simulated annealing.
*/
private final AnnealFactory annealFactory = new AnnealFactory();
/**
* Nelder Mead Factory.
*/
private final NelderMeadFactory nmFactory = new NelderMeadFactory();
/**
* The factory for neighborhood SOM.
*/
private final NeighborhoodSOMFactory neighborhoodFactory
= new NeighborhoodSOMFactory();
/**
* The factory for SOM cluster.
*/
private final ClusterSOMFactory somClusterFactory = new ClusterSOMFactory();
/**
* The factory for genetic.
*/
private final GeneticFactory geneticFactory = new GeneticFactory();
/**
* The factory for Manhattan networks.
*/
private final ManhattanFactory manhattanFactory = new ManhattanFactory();
/**
* Factory for SVD.
*/
private final RBFSVDFactory svdFactory = new RBFSVDFactory();
/**
* Factory for PNN.
*/
private final PNNTrainFactory pnnFactory = new PNNTrainFactory();
/**
* Factory for quickprop.
*/
private final QuickPropFactory qpropFactory = new QuickPropFactory();
private final PSOFactory psoFactory = new PSOFactory();
/**
* {@inheritDoc}
*/
@Override
public final String getPluginDescription() {
return "This plugin provides the built in training " +
"methods for Encog.";
}
/**
* {@inheritDoc}
*/
@Override
public final String getPluginName() {
return "HRI-System-Training";
}
/**
* @return This is a type-1 plugin.
*/
@Override
public final int getPluginType() {
return 1;
}
/**
* This plugin does not support activation functions, so it will
* always return null.
* @return Null, because this plugin does not support activation functions.
*/
@Override
public ActivationFunction createActivationFunction(String name) {
return null;
}
@Override
public MLMethod createMethod(String methodType, String architecture,
int input, int output) {
// TODO Auto-generated method stub
return null;
}
@Override
public MLTrain createTraining(MLMethod method, MLDataSet training,
String type, String args) {
String args2 = args;
if (args2 == null) {
args2 = "";
}
if (MLTrainFactory.TYPE_RPROP.equalsIgnoreCase(type)) {
return this.rpropFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_BACKPROP.equalsIgnoreCase(type)) {
return this.backpropFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_SCG.equalsIgnoreCase(type)) {
return this.scgFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_LMA.equalsIgnoreCase(type)) {
return this.lmaFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_SVM.equalsIgnoreCase(type)) {
return this.svmFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_SVM_SEARCH.equalsIgnoreCase(type)) {
return this.svmSearchFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_SOM_NEIGHBORHOOD.equalsIgnoreCase(
type)) {
return this.neighborhoodFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_ANNEAL.equalsIgnoreCase(type)) {
return this.annealFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_GENETIC.equalsIgnoreCase(type)) {
return this.geneticFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_SOM_CLUSTER.equalsIgnoreCase(type)) {
return this.somClusterFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_MANHATTAN.equalsIgnoreCase(type)) {
return this.manhattanFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_SVD.equalsIgnoreCase(type)) {
return this.svdFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_PNN.equalsIgnoreCase(type)) {
return this.pnnFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_QPROP.equalsIgnoreCase(type)) {
return this.qpropFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_BAYESIAN.equals(type) ) {
return this.bayesianFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_NELDER_MEAD.equals(type) ) {
return this.nmFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_PSO.equals(type) ) {
return this.psoFactory.create(method, training, args2);
}
else {
throw new EncogError("Unknown training type: " + type);
}
}
/**
* {@inheritDoc}
*/
@Override
public int getPluginServiceType() {
return EncogPluginBase.TYPE_SERVICE;
}
}
| Java |
# Strict Mode
To enable strict mode, simply pass in `strict: true` when creating a Vuex store:
```js
const store = createStore({
// ...
strict: true
})
```
In strict mode, whenever Vuex state is mutated outside of mutation handlers, an error will be thrown. This ensures that all state mutations can be explicitly tracked by debugging tools.
## Development vs. Production
**Do not enable strict mode when deploying for production!** Strict mode runs a synchronous deep watcher on the state tree for detecting inappropriate mutations, and it can be quite expensive when you make large amount of mutations to the state. Make sure to turn it off in production to avoid the performance cost.
Similar to plugins, we can let the build tools handle that:
```js
const store = createStore({
// ...
strict: process.env.NODE_ENV !== 'production'
})
```
| Java |
/**
* React Static Boilerplate
* https://github.com/koistya/react-static-boilerplate
* Copyright (c) Konstantin Tarkus (@koistya) | MIT license
*/
import './index.scss'
import React, { Component } from 'react'
// import { Grid, Col, Row } from 'react-bootstrap';
export default class IndexPage extends Component {
render() {
return (
<div className="top-page">
<div>
<img
className="top-image"
src="/cover2.jpg"
width="100%"
alt="cover image"
/>
</div>
<div className="top-page--footer">
The source code of this website is available
<a
href="https://github.com/odoruinu/odoruinu.net-pug"
target="_blank"
rel="noopener noreferrer"
>
here on GitHub
</a>
.
</div>
</div>
)
}
}
| Java |
# coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import pytest
from os import path, remove, sys, urandom
import platform
import uuid
from azure.storage.blob import (
BlobServiceClient,
ContainerClient,
BlobClient,
ContentSettings
)
if sys.version_info >= (3,):
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
from settings.testcase import BlobPreparer
from devtools_testutils.storage import StorageTestCase
# ------------------------------------------------------------------------------
TEST_BLOB_PREFIX = 'largeblob'
LARGE_BLOB_SIZE = 12 * 1024 * 1024
LARGE_BLOCK_SIZE = 6 * 1024 * 1024
# ------------------------------------------------------------------------------
if platform.python_implementation() == 'PyPy':
pytest.skip("Skip tests for Pypy", allow_module_level=True)
class StorageLargeBlockBlobTest(StorageTestCase):
def _setup(self, storage_account_name, key):
# test chunking functionality by reducing the threshold
# for chunking and the size of each chunk, otherwise
# the tests would take too long to execute
self.bsc = BlobServiceClient(
self.account_url(storage_account_name, "blob"),
credential=key,
max_single_put_size=32 * 1024,
max_block_size=2 * 1024 * 1024,
min_large_block_upload_threshold=1 * 1024 * 1024)
self.config = self.bsc._config
self.container_name = self.get_resource_name('utcontainer')
if self.is_live:
try:
self.bsc.create_container(self.container_name)
except:
pass
def _teardown(self, file_name):
if path.isfile(file_name):
try:
remove(file_name)
except:
pass
# --Helpers-----------------------------------------------------------------
def _get_blob_reference(self):
return self.get_resource_name(TEST_BLOB_PREFIX)
def _create_blob(self):
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
blob.upload_blob(b'')
return blob
def assertBlobEqual(self, container_name, blob_name, expected_data):
blob = self.bsc.get_blob_client(container_name, blob_name)
actual_data = blob.download_blob()
self.assertEqual(b"".join(list(actual_data.chunks())), expected_data)
# --Test cases for block blobs --------------------------------------------
@pytest.mark.live_test_only
@BlobPreparer()
def test_put_block_bytes_large(self, storage_account_name, storage_account_key):
self._setup(storage_account_name, storage_account_key)
blob = self._create_blob()
# Act
for i in range(5):
resp = blob.stage_block(
'block {0}'.format(i).encode('utf-8'), urandom(LARGE_BLOCK_SIZE))
self.assertIsNotNone(resp)
assert 'content_md5' in resp
assert 'content_crc64' in resp
assert 'request_id' in resp
# Assert
@pytest.mark.live_test_only
@BlobPreparer()
def test_put_block_bytes_large_with_md5(self, storage_account_name, storage_account_key):
self._setup(storage_account_name, storage_account_key)
blob = self._create_blob()
# Act
for i in range(5):
resp = blob.stage_block(
'block {0}'.format(i).encode('utf-8'),
urandom(LARGE_BLOCK_SIZE),
validate_content=True)
self.assertIsNotNone(resp)
assert 'content_md5' in resp
assert 'content_crc64' in resp
assert 'request_id' in resp
@pytest.mark.live_test_only
@BlobPreparer()
def test_put_block_stream_large(self, storage_account_name, storage_account_key):
self._setup(storage_account_name, storage_account_key)
blob = self._create_blob()
# Act
for i in range(5):
stream = BytesIO(bytearray(LARGE_BLOCK_SIZE))
resp = resp = blob.stage_block(
'block {0}'.format(i).encode('utf-8'),
stream,
length=LARGE_BLOCK_SIZE)
self.assertIsNotNone(resp)
assert 'content_md5' in resp
assert 'content_crc64' in resp
assert 'request_id' in resp
# Assert
@pytest.mark.live_test_only
@BlobPreparer()
def test_put_block_stream_large_with_md5(self, storage_account_name, storage_account_key):
self._setup(storage_account_name, storage_account_key)
blob = self._create_blob()
# Act
for i in range(5):
stream = BytesIO(bytearray(LARGE_BLOCK_SIZE))
resp = resp = blob.stage_block(
'block {0}'.format(i).encode('utf-8'),
stream,
length=LARGE_BLOCK_SIZE,
validate_content=True)
self.assertIsNotNone(resp)
assert 'content_md5' in resp
assert 'content_crc64' in resp
assert 'request_id' in resp
# Assert
@pytest.mark.live_test_only
@BlobPreparer()
def test_create_large_blob_from_path(self, storage_account_name, storage_account_key):
# parallel tests introduce random order of requests, can only run live
self._setup(storage_account_name, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(urandom(LARGE_BLOB_SIZE))
FILE_PATH = 'large_blob_from_path.temp.{}.dat'.format(str(uuid.uuid4()))
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(stream, max_concurrency=2, overwrite=True)
block_list = blob.get_block_list()
# Assert
self.assertIsNot(len(block_list), 0)
self.assertBlobEqual(self.container_name, blob_name, data)
self._teardown(FILE_PATH)
@pytest.mark.live_test_only
@BlobPreparer()
def test_create_large_blob_from_path_with_md5(self, storage_account_name, storage_account_key):
# parallel tests introduce random order of requests, can only run live
self._setup(storage_account_name, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(urandom(LARGE_BLOB_SIZE))
FILE_PATH = "blob_from_path_with_md5.temp.dat"
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(stream, validate_content=True, max_concurrency=2)
# Assert
self.assertBlobEqual(self.container_name, blob_name, data)
self._teardown(FILE_PATH)
@pytest.mark.live_test_only
@BlobPreparer()
def test_create_large_blob_from_path_non_parallel(self, storage_account_name, storage_account_key):
self._setup(storage_account_name, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(self.get_random_bytes(100))
FILE_PATH = "blob_from_path_non_parallel.temp.dat"
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(stream, max_concurrency=1)
# Assert
self.assertBlobEqual(self.container_name, blob_name, data)
self._teardown(FILE_PATH)
@pytest.mark.live_test_only
@BlobPreparer()
def test_create_large_blob_from_path_with_progress(self, storage_account_name, storage_account_key):
# parallel tests introduce random order of requests, can only run live
self._setup(storage_account_name, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(urandom(LARGE_BLOB_SIZE))
FILE_PATH = "blob_from_path_with_progress.temp.dat"
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
progress = []
def callback(response):
current = response.context['upload_stream_current']
total = response.context['data_stream_total']
if current is not None:
progress.append((current, total))
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(stream, max_concurrency=2, raw_response_hook=callback)
# Assert
self.assertBlobEqual(self.container_name, blob_name, data)
self.assert_upload_progress(len(data), self.config.max_block_size, progress)
self._teardown(FILE_PATH)
@pytest.mark.live_test_only
@BlobPreparer()
def test_create_large_blob_from_path_with_properties(self, storage_account_name, storage_account_key):
# parallel tests introduce random order of requests, can only run live
self._setup(storage_account_name, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(urandom(LARGE_BLOB_SIZE))
FILE_PATH = 'blob_from_path_with_properties.temp.{}.dat'.format(str(uuid.uuid4()))
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
content_settings = ContentSettings(
content_type='image/png',
content_language='spanish')
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(stream, content_settings=content_settings, max_concurrency=2)
# Assert
self.assertBlobEqual(self.container_name, blob_name, data)
properties = blob.get_blob_properties()
self.assertEqual(properties.content_settings.content_type, content_settings.content_type)
self.assertEqual(properties.content_settings.content_language, content_settings.content_language)
self._teardown(FILE_PATH)
@pytest.mark.live_test_only
@BlobPreparer()
def test_create_large_blob_from_stream_chunked_upload(self, storage_account_name, storage_account_key):
# parallel tests introduce random order of requests, can only run live
self._setup(storage_account_name, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(urandom(LARGE_BLOB_SIZE))
FILE_PATH = 'blob_from_stream_chunked_upload.temp.{}.dat'.format(str(uuid.uuid4()))
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(stream, max_concurrency=2)
# Assert
self.assertBlobEqual(self.container_name, blob_name, data)
self._teardown(FILE_PATH)
@pytest.mark.live_test_only
@BlobPreparer()
def test_creat_lrgblob_frm_stream_w_progress_chnkd_upload(self, storage_account_name, storage_account_key):
# parallel tests introduce random order of requests, can only run live
self._setup(storage_account_name, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(urandom(LARGE_BLOB_SIZE))
FILE_PATH = 'stream_w_progress_chnkd_upload.temp.{}.dat'.format(str(uuid.uuid4()))
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
progress = []
def callback(response):
current = response.context['upload_stream_current']
total = response.context['data_stream_total']
if current is not None:
progress.append((current, total))
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(stream, max_concurrency=2, raw_response_hook=callback)
# Assert
self.assertBlobEqual(self.container_name, blob_name, data)
self.assert_upload_progress(len(data), self.config.max_block_size, progress)
self._teardown(FILE_PATH)
@pytest.mark.live_test_only
@BlobPreparer()
def test_create_large_blob_from_stream_chunked_upload_with_count(self, storage_account_name, storage_account_key):
# parallel tests introduce random order of requests, can only run live
self._setup(storage_account_name, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(urandom(LARGE_BLOB_SIZE))
FILE_PATH = 'chunked_upload_with_count.temp.{}.dat'.format(str(uuid.uuid4()))
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
blob_size = len(data) - 301
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(stream, length=blob_size, max_concurrency=2)
# Assert
self.assertBlobEqual(self.container_name, blob_name, data[:blob_size])
self._teardown(FILE_PATH)
@pytest.mark.live_test_only
@BlobPreparer()
def test_creat_lrgblob_frm_strm_chnkd_uplod_w_count_n_props(self, storage_account_name, storage_account_key):
# parallel tests introduce random order of requests, can only run live
self._setup(storage_account_name, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(urandom(LARGE_BLOB_SIZE))
FILE_PATH = 'plod_w_count_n_props.temp.{}.dat'.format(str(uuid.uuid4()))
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
content_settings = ContentSettings(
content_type='image/png',
content_language='spanish')
blob_size = len(data) - 301
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(
stream, length=blob_size, content_settings=content_settings, max_concurrency=2)
# Assert
self.assertBlobEqual(self.container_name, blob_name, data[:blob_size])
properties = blob.get_blob_properties()
self.assertEqual(properties.content_settings.content_type, content_settings.content_type)
self.assertEqual(properties.content_settings.content_language, content_settings.content_language)
self._teardown(FILE_PATH)
@pytest.mark.live_test_only
@BlobPreparer()
def test_creat_lrg_blob_frm_stream_chnked_upload_w_props(self, storage_account_name, storage_account_key):
# parallel tests introduce random order of requests, can only run live
self._setup(storage_account_name, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(urandom(LARGE_BLOB_SIZE))
FILE_PATH = 'creat_lrg_blob.temp.{}.dat'.format(str(uuid.uuid4()))
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
content_settings = ContentSettings(
content_type='image/png',
content_language='spanish')
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(stream, content_settings=content_settings, max_concurrency=2)
# Assert
self.assertBlobEqual(self.container_name, blob_name, data)
properties = blob.get_blob_properties()
self.assertEqual(properties.content_settings.content_type, content_settings.content_type)
self.assertEqual(properties.content_settings.content_language, content_settings.content_language)
self._teardown(FILE_PATH)
# ------------------------------------------------------------------------------ | Java |
package controllers;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Date;
import models.Usuario;
import play.Play;
import play.mvc.*;
import play.data.validation.*;
import play.libs.*;
import play.utils.*;
public class Secure extends Controller {
@Before(unless={"login", "authenticate", "logout"})
static void checkAccess() throws Throwable {
// Authent
if(!session.contains("username")) {
flash.put("url", "GET".equals(request.method) ? request.url : Play.ctxPath + "/"); // seems a good default
login();
}
// Checks
Check check = getActionAnnotation(Check.class);
if(check != null) {
check(check);
}
check = getControllerInheritedAnnotation(Check.class);
if(check != null) {
check(check);
}
}
private static void check(Check check) throws Throwable {
for(String profile : check.value()) {
boolean hasProfile = (Boolean)Security.invoke("check", profile);
if(!hasProfile) {
Security.invoke("onCheckFailed", profile);
}
}
}
// ~~~ Login
public static void login() throws Throwable {
Http.Cookie remember = request.cookies.get("rememberme");
if(remember != null) {
int firstIndex = remember.value.indexOf("-");
int lastIndex = remember.value.lastIndexOf("-");
if (lastIndex > firstIndex) {
String sign = remember.value.substring(0, firstIndex);
String restOfCookie = remember.value.substring(firstIndex + 1);
String username = remember.value.substring(firstIndex + 1, lastIndex);
String time = remember.value.substring(lastIndex + 1);
Date expirationDate = new Date(Long.parseLong(time)); // surround with try/catch?
Date now = new Date();
if (expirationDate == null || expirationDate.before(now)) {
logout();
}
if(Crypto.sign(restOfCookie).equals(sign)) {
session.put("username", username);
redirectToOriginalURL();
}
}
}
flash.keep("url");
render();
}
public static void authenticate(@Required String username, String password, boolean remember) throws Throwable {
// Check tokens
//Boolean allowed = false;
Usuario usuario = Usuario.find("usuario = ? and clave = ?", username, password).first();
if(usuario != null){
//session.put("nombreCompleto", usuario.nombreCompleto);
//session.put("idUsuario", usuario.id);
//if(usuario.tienda != null){
//session.put("idTienda", usuario.id);
//}
//allowed = true;
} else {
flash.keep("url");
flash.error("secure.error");
params.flash();
login();
}
/*try {
// This is the deprecated method name
allowed = (Boolean)Security.invoke("authenticate", username, password);
} catch (UnsupportedOperationException e ) {
// This is the official method name
allowed = (Boolean)Security.invoke("authenticate", username, password);
}*/
/*if(validation.hasErrors() || !allowed) {
flash.keep("url");
flash.error("secure.error");
params.flash();
login();
}*/
// Mark user as connected
session.put("username", username);
// Remember if needed
if(remember) {
Date expiration = new Date();
String duration = "30d"; // maybe make this override-able
expiration.setTime(expiration.getTime() + Time.parseDuration(duration));
response.setCookie("rememberme", Crypto.sign(username + "-" + expiration.getTime()) + "-" + username + "-" + expiration.getTime(), duration);
}
// Redirect to the original URL (or /)
redirectToOriginalURL();
}
public static void logout() throws Throwable {
Security.invoke("onDisconnect");
session.clear();
response.removeCookie("rememberme");
Security.invoke("onDisconnected");
flash.success("secure.logout");
login();
}
// ~~~ Utils
static void redirectToOriginalURL() throws Throwable {
Security.invoke("onAuthenticated");
String url = flash.get("url");
if(url == null) {
url = Play.ctxPath + "/";
}
redirect(url);
}
public static class Security extends Controller {
/**
* @Deprecated
*
* @param username
* @param password
* @return
*/
static boolean authentify(String username, String password) {
throw new UnsupportedOperationException();
}
/**
* This method is called during the authentication process. This is where you check if
* the user is allowed to log in into the system. This is the actual authentication process
* against a third party system (most of the time a DB).
*
* @param username
* @param password
* @return true if the authentication process succeeded
*/
static boolean authenticate(String username, String password) {
return true;
}
/**
* This method checks that a profile is allowed to view this page/method. This method is called prior
* to the method's controller annotated with the @Check method.
*
* @param profile
* @return true if you are allowed to execute this controller method.
*/
static boolean check(String profile) {
return true;
}
/**
* This method returns the current connected username
* @return
*/
static String connected() {
return session.get("username");
}
/**
* Indicate if a user is currently connected
* @return true if the user is connected
*/
static boolean isConnected() {
return session.contains("username");
}
/**
* This method is called after a successful authentication.
* You need to override this method if you with to perform specific actions (eg. Record the time the user signed in)
*/
static void onAuthenticated() {
}
/**
* This method is called before a user tries to sign off.
* You need to override this method if you wish to perform specific actions (eg. Record the name of the user who signed off)
*/
static void onDisconnect() {
}
/**
* This method is called after a successful sign off.
* You need to override this method if you wish to perform specific actions (eg. Record the time the user signed off)
*/
static void onDisconnected() {
}
/**
* This method is called if a check does not succeed. By default it shows the not allowed page (the controller forbidden method).
* @param profile
*/
static void onCheckFailed(String profile) {
forbidden();
}
private static Object invoke(String m, Object... args) throws Throwable {
try {
return Java.invokeChildOrStatic(Security.class, m, args);
} catch(InvocationTargetException e) {
throw e.getTargetException();
}
}
}
}
| Java |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
import os
import re
import subprocess
import sys
from datetime import date
import click
import yaml
from indico.util.console import cformat
# Dictionary listing the files for which to change the header.
# The key is the extension of the file (without the dot) and the value is another
# dictionary containing two keys:
# - 'regex' : A regular expression matching comments in the given file type
# - 'format': A dictionary with the comment characters to add to the header.
# There must be a `comment_start` inserted before the header,
# `comment_middle` inserted at the beginning of each line except the
# first and last one, and `comment_end` inserted at the end of the
# header. (See the `HEADER` above)
SUPPORTED_FILES = {
'py': {
'regex': re.compile(r'((^#|[\r\n]#).*)*'),
'format': {'comment_start': '#', 'comment_middle': '#', 'comment_end': ''}},
'wsgi': {
'regex': re.compile(r'((^#|[\r\n]#).*)*'),
'format': {'comment_start': '#', 'comment_middle': '#', 'comment_end': ''}},
'js': {
'regex': re.compile(r'/\*(.|[\r\n])*?\*/|((^//|[\r\n]//).*)*'),
'format': {'comment_start': '//', 'comment_middle': '//', 'comment_end': ''}},
'jsx': {
'regex': re.compile(r'/\*(.|[\r\n])*?\*/|((^//|[\r\n]//).*)*'),
'format': {'comment_start': '//', 'comment_middle': '//', 'comment_end': ''}},
'css': {
'regex': re.compile(r'/\*(.|[\r\n])*?\*/'),
'format': {'comment_start': '/*', 'comment_middle': ' *', 'comment_end': ' */'}},
'scss': {
'regex': re.compile(r'/\*(.|[\r\n])*?\*/|((^//|[\r\n]//).*)*'),
'format': {'comment_start': '//', 'comment_middle': '//', 'comment_end': ''}},
}
# The substring which must be part of a comment block in order for the comment to be updated by the header.
SUBSTRING = 'This file is part of'
USAGE = '''
Updates all the headers in the supported files ({supported_files}).
By default, all the files tracked by git in the current repository are updated
to the current year.
You can specify a year to update to as well as a file or directory.
This will update all the supported files in the scope including those not tracked
by git. If the directory does not contain any supported files (or if the file
specified is not supported) nothing will be updated.
'''.format(supported_files=', '.join(SUPPORTED_FILES)).strip()
def _walk_to_root(path):
"""Yield directories starting from the given directory up to the root."""
# Based on code from python-dotenv (BSD-licensed):
# https://github.com/theskumar/python-dotenv/blob/e13d957b/src/dotenv/main.py#L245
if os.path.isfile(path):
path = os.path.dirname(path)
last_dir = None
current_dir = os.path.abspath(path)
while last_dir != current_dir:
yield current_dir
parent_dir = os.path.abspath(os.path.join(current_dir, os.path.pardir))
last_dir, current_dir = current_dir, parent_dir
def _get_config(path, end_year):
config = {}
for dirname in _walk_to_root(path):
check_path = os.path.join(dirname, 'headers.yml')
if os.path.isfile(check_path):
with open(check_path) as f:
config.update((k, v) for k, v in yaml.safe_load(f.read()).items() if k not in config)
if config.pop('root', False):
break
if 'start_year' not in config:
click.echo('no valid headers.yml files found: start_year missing')
sys.exit(1)
if 'name' not in config:
click.echo('no valid headers.yml files found: name missing')
sys.exit(1)
if 'header' not in config:
click.echo('no valid headers.yml files found: header missing')
sys.exit(1)
config['end_year'] = end_year
return config
def gen_header(data):
if data['start_year'] == data['end_year']:
data['dates'] = data['start_year']
else:
data['dates'] = '{} - {}'.format(data['start_year'], data['end_year'])
return '\n'.join(line.rstrip() for line in data['header'].format(**data).strip().splitlines())
def _update_header(file_path, config, substring, regex, data, ci):
found = False
with open(file_path) as file_read:
content = orig_content = file_read.read()
if not content.strip():
return False
shebang_line = None
if content.startswith('#!/'):
shebang_line, content = content.split('\n', 1)
for match in regex.finditer(content):
if substring in match.group():
found = True
content = content[:match.start()] + gen_header(data | config) + content[match.end():]
if shebang_line:
content = shebang_line + '\n' + content
if content != orig_content:
msg = 'Incorrect header in {}' if ci else cformat('%{green!}Updating header of %{blue!}{}')
print(msg.format(os.path.relpath(file_path)))
if not ci:
with open(file_path, 'w') as file_write:
file_write.write(content)
return True
elif not found:
msg = 'Missing header in {}' if ci else cformat('%{red!}Missing header%{reset} in %{blue!}{}')
print(msg.format(os.path.relpath(file_path)))
return True
def update_header(file_path, year, ci):
config = _get_config(file_path, year)
ext = file_path.rsplit('.', 1)[-1]
if ext not in SUPPORTED_FILES or not os.path.isfile(file_path):
return False
if os.path.basename(file_path)[0] == '.':
return False
return _update_header(file_path, config, SUBSTRING, SUPPORTED_FILES[ext]['regex'],
SUPPORTED_FILES[ext]['format'], ci)
def blacklisted(root, path, _cache={}):
orig_path = path
if path not in _cache:
_cache[orig_path] = False
while (path + os.path.sep).startswith(root):
if os.path.exists(os.path.join(path, '.no-headers')):
_cache[orig_path] = True
break
path = os.path.normpath(os.path.join(path, '..'))
return _cache[orig_path]
@click.command(help=USAGE)
@click.option('--ci', is_flag=True, help='Indicate that the script is running during CI and should use a non-zero '
'exit code unless all headers were already up to date. This also prevents '
'files from actually being updated.')
@click.option('--year', '-y', type=click.IntRange(min=1000), default=date.today().year, metavar='YEAR',
help='Indicate the target year')
@click.option('--path', '-p', type=click.Path(exists=True), help='Restrict updates to a specific file or directory')
@click.pass_context
def main(ctx, ci, year, path):
error = False
if path and os.path.isdir(path):
if not ci:
print(cformat('Updating headers to the year %{yellow!}{year}%{reset} for all the files in '
'%{yellow!}{path}%{reset}...').format(year=year, path=path))
for root, _, filenames in os.walk(path):
for filename in filenames:
if not blacklisted(path, root):
if update_header(os.path.join(root, filename), year, ci):
error = True
elif path and os.path.isfile(path):
if not ci:
print(cformat('Updating headers to the year %{yellow!}{year}%{reset} for the file '
'%{yellow!}{file}%{reset}...').format(year=year, file=path))
if update_header(path, year, ci):
error = True
else:
if not ci:
print(cformat('Updating headers to the year %{yellow!}{year}%{reset} for all '
'git-tracked files...').format(year=year))
try:
for filepath in subprocess.check_output(['git', 'ls-files'], text=True).splitlines():
filepath = os.path.abspath(filepath)
if not blacklisted(os.getcwd(), os.path.dirname(filepath)):
if update_header(filepath, year, ci):
error = True
except subprocess.CalledProcessError:
raise click.UsageError(cformat('%{red!}You must be within a git repository to run this script.'))
if not error:
print(cformat('%{green}\u2705 All headers are up to date'))
elif ci:
print(cformat('%{red}\u274C Some headers need to be updated or added'))
sys.exit(1)
else:
print(cformat('%{yellow}\U0001F504 Some headers have been updated (or are missing)'))
if __name__ == '__main__':
main()
| Java |
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from paste.models import Paste, Language
@csrf_exempt
def add(request):
print "jojo"
if request.method == 'POST':
language = request.POST['language']
content = request.POST['content']
try:
lang = Language.objects.get(pk=language)
except:
print "lang not avalible", language
lang = Language.objects.get(pk='txt')
paste = Paste(content=content, language=lang)
paste.save()
paste = Paste.objects.latest()
return HttpResponse(paste.pk, content_type='text/plain')
else:
return redirect('/api')
| Java |
module Ahoy
module Stores
class ActiveRecordStore < BaseStore
def track_visit(options, &block)
visit =
visit_model.new do |v|
v.id = ahoy.visit_id
v.visitor_id = ahoy.visitor_id
v.user = user if v.respond_to?(:user=)
end
set_visit_properties(visit)
yield(visit) if block_given?
begin
visit.save!
geocode(visit)
rescue *unique_exception_classes
# do nothing
end
end
def track_event(name, properties, options, &block)
event =
event_model.new do |e|
e.id = options[:id]
e.visit_id = ahoy.visit_id
e.visitor_id = ahoy.visitor_id
e.user = user
e.name = name
properties.each do |name, value|
e.properties.build(name: name, value: value)
end
end
yield(event) if block_given?
begin
event.save!
rescue *unique_exception_classes
# do nothing
end
end
def visit
@visit ||= visit_model.where(id: ahoy.visit_id).first if ahoy.visit_id
end
protected
def visit_model
::Visit
end
def event_model
::Ahoy::Event
end
end
end
end
| Java |
import {extend} from 'lodash';
export default class User {
/**
* The User class
* @class
* @param {Object} user
* @return {Object} A User
*/
constructor(user) {
extend(this, user);
console.log(this);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.