code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
/**
* This file defines the fitness_params object.
*
* TODOs:
* - a few TODOs in the file but ok
*
* FINISHED!
*
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using toolbox;
/**
* namespace for biogas plant optimization
*
* Definition of:
* - fitness_params
* - objective function
* - weights used inside objective function
*
*/
namespace biooptim
{
/// <summary>
/// definition of fitness parameters used in objective function
/// </summary>
public partial class fitness_params
{
// -------------------------------------------------------------------------------------
// !!! CONSTRUCTOR METHODS !!!
// -------------------------------------------------------------------------------------
/// <summary>
/// Standard Constructor creates the fitness_params object with default params
/// </summary>
/// <param name="numDigesters">number of digesters on plant</param>
public fitness_params(int numDigesters/*biogas.plant myPlant*/)
{
set_params_to_default(/*myPlant*/numDigesters);
}
/// <summary>
/// Constructor used to read fitness_params out of a XML file
/// </summary>
/// <param name="XMLfile">name of the xml file</param>
public fitness_params(string XMLfile)
{
XmlTextReader reader= new System.Xml.XmlTextReader(XMLfile);
getParamsFromXMLReader(ref reader);
reader.Close();
}
// -------------------------------------------------------------------------------------
// !!! PUBLIC METHODS !!!
// -------------------------------------------------------------------------------------
/// <summary>
/// set fitness params to values read out of a xml file
/// </summary>
/// <param name="reader"></param>
public void getParamsFromXMLReader(ref XmlTextReader reader)
{
string xml_tag = "";
int digester_index = 0;
// do not set params, because plant is not known
// TODO - macht probleme wenn ein neuer parameter hinzugefügt wird, da dann
// dessen list leer bleibt
// im grunde müsste man am ende der funktion die listen füllen, welche
// leer geblieben sind mit default werten
bool do_while = true;
// go through the file
while (reader.Read() && do_while)
{
switch (reader.NodeType)
{
case System.Xml.XmlNodeType.Element: // this knot is an element
xml_tag = reader.Name;
while (reader.MoveToNextAttribute())
{ // read the attributes, here only the attribute of digester
// is of interest, all other attributes are ignored,
// actually there usally are no other attributes
if (xml_tag == "digester" && reader.Name == "index")
{
// TODO
// index of digester, not used at the moment
digester_index = Convert.ToInt32(reader.Value);
break;
}
}
if (xml_tag == "weights")
{
myWeights.getParamsFromXMLReader(ref reader);
}
else if (xml_tag == "setpoints")
{
mySetpoints.getParamsFromXMLReader(ref reader);
}
break;
case System.Xml.XmlNodeType.Text: // text, thus value, of each element
switch (xml_tag)
{
// TODO - use digester_index here, compare with size of pH_min, ...
// here we assume that params are given in the correct
// order, thus first the first digester, then the 2nd digester, ...
case "pH_min":
pH_min.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "pH_max":
pH_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "pH_optimum":
pH_optimum.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "TS_max":
TS_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "VFA_TAC_min":
VFA_TAC_min.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "VFA_TAC_max":
VFA_TAC_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "VFA_min":
VFA_min.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "VFA_max":
VFA_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "TAC_min":
TAC_min.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "HRT_min":
HRT_min.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "HRT_max":
HRT_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "OLR_max":
OLR_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "Snh4_max":
Snh4_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "Snh3_max":
Snh3_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "AcVsPro_min":
AcVsPro_min.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "TS_feed_max":
_TS_feed_max= System.Xml.XmlConvert.ToDouble(reader.Value);
break;
case "HRT_plant_min":
_HRT_plant_min = System.Xml.XmlConvert.ToDouble(reader.Value);
break;
case "HRT_plant_max":
_HRT_plant_max = System.Xml.XmlConvert.ToDouble(reader.Value);
break;
case "OLR_plant_max":
_OLR_plant_max = System.Xml.XmlConvert.ToDouble(reader.Value);
break;
// read in manurebonus
case "manurebonus":
_manurebonus = System.Xml.XmlConvert.ToBoolean(reader.Value);
break;
case "fitness_function":
_fitness_function = reader.Value;
break;
case "nObjectives":
_nObjectives = System.Xml.XmlConvert.ToInt32(reader.Value);
break;
//case "Ndelta":
// _Ndelta = System.Xml.XmlConvert.ToInt32(reader.Value);
// break;
}
break;
case System.Xml.XmlNodeType.EndElement: // end of fitness_params
if (reader.Name == "fitness_params")
do_while = false; // end while loop
break;
}
}
}
/// <summary>
/// Returns fitness params as XML string, such that it can be saved
/// in a XML file
/// </summary>
/// <returns></returns>
public string getParamsAsXMLString()
{
StringBuilder sb = new StringBuilder();
sb.Append("<fitness_params>\n");
for (int idigester = 0; idigester < pH_min.Count; idigester++)
{
sb.Append(String.Format("<digester index= \"{0}\">\n", idigester));
sb.Append(xmlInterface.setXMLTag("pH_min", pH_min[idigester]));
sb.Append(xmlInterface.setXMLTag("pH_max", pH_max[idigester]));
sb.Append(xmlInterface.setXMLTag("pH_optimum", pH_optimum[idigester]));
sb.Append(xmlInterface.setXMLTag("TS_max", TS_max[idigester]));
sb.Append(xmlInterface.setXMLTag("VFA_TAC_min", VFA_TAC_min[idigester]));
sb.Append(xmlInterface.setXMLTag("VFA_TAC_max", VFA_TAC_max[idigester]));
sb.Append(xmlInterface.setXMLTag("VFA_min", VFA_min[idigester]));
sb.Append(xmlInterface.setXMLTag("VFA_max", VFA_max[idigester]));
sb.Append(xmlInterface.setXMLTag("TAC_min", TAC_min[idigester]));
sb.Append(xmlInterface.setXMLTag("HRT_min", HRT_min[idigester]));
sb.Append(xmlInterface.setXMLTag("HRT_max", HRT_max[idigester]));
sb.Append(xmlInterface.setXMLTag("OLR_max", OLR_max[idigester]));
sb.Append(xmlInterface.setXMLTag("Snh4_max", Snh4_max[idigester]));
sb.Append(xmlInterface.setXMLTag("Snh3_max", Snh3_max[idigester]));
sb.Append(xmlInterface.setXMLTag("AcVsPro_min", AcVsPro_min[idigester]));
sb.Append("</digester>\n");
}
sb.Append(xmlInterface.setXMLTag("TS_feed_max", TS_feed_max));
// add weights
sb.Append(myWeights.getParamsAsXMLString());
sb.Append(xmlInterface.setXMLTag("HRT_plant_min", HRT_plant_min));
sb.Append(xmlInterface.setXMLTag("HRT_plant_max", HRT_plant_max));
sb.Append(xmlInterface.setXMLTag("OLR_plant_max", OLR_plant_max));
// write manurebonus inside file
sb.Append(xmlInterface.setXMLTag("manurebonus", manurebonus));
sb.Append(xmlInterface.setXMLTag("fitness_function", fitness_function));
sb.Append(xmlInterface.setXMLTag("nObjectives", nObjectives));
//sb.Append(xmlInterface.setXMLTag("Ndelta", _Ndelta));
// add setpoints
sb.Append(mySetpoints.getParamsAsXMLString());
//
sb.Append("</fitness_params>\n");
return sb.ToString();
}
/// <summary>
/// Saves the fitness_params in a xml file
/// </summary>
/// <param name="XMLfile">name of the xml file</param>
public void saveAsXML(string XMLfile)
{
StreamWriter writer = File.CreateText(XMLfile);
writer.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
writer.Write(getParamsAsXMLString());
writer.Close();
}
/// <summary>
/// Prints the fitness params to a string, such that the string
/// can be written to a console.
///
/// For Custom Numeric Format Strings see:
///
/// http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
///
/// </summary>
/// <returns></returns>
public string print()
{
StringBuilder sb = new StringBuilder();
sb.Append(" ---------- fitness_params: ---------- \r\n");
for (int idigester = 0; idigester < pH_min.Count; idigester++)
{
sb.Append(String.Format("digester: {0}\n", idigester));
sb.Append(String.Format("pH_min: {0}\t\t\t", pH_min[idigester]));
sb.Append(String.Format("pH_max: {0}\t\t\t", pH_max[idigester]));
sb.Append(String.Format("pH_optimum: {0}\n", pH_optimum[idigester]));
sb.Append(String.Format("TS_max: {0}\t\t\t", TS_max[idigester]));
sb.Append(String.Format("VFA_TAC_min: {0}\t\t\t", VFA_TAC_min[idigester]));
sb.Append(String.Format("VFA_TAC_max: {0}\n", VFA_TAC_max[idigester]));
sb.Append(String.Format("VFA_min: {0}\t\t\t", VFA_min[idigester]));
sb.Append(String.Format("VFA_max: {0}\t\t\t", VFA_max[idigester]));
sb.Append(String.Format("TAC_min: {0}\n", TAC_min[idigester]));
sb.Append(String.Format("HRT_min: {0}\t\t\t", HRT_min[idigester]));
sb.Append(String.Format("HRT_max: {0}\t\t\t", HRT_max[idigester]));
sb.Append(String.Format("OLR_max: {0}\n", OLR_max[idigester]));
sb.Append(String.Format("Snh4_max: {0}\t\t\t", Snh4_max[idigester]));
sb.Append(String.Format("Snh3_max: {0}\t\t\t", Snh3_max[idigester]));
sb.Append(String.Format("AcVsPro_min: {0}\r\n", AcVsPro_min[idigester]));
}
sb.Append(String.Format("TS_feed_max: {0}\r\n", TS_feed_max));
// add weights
sb.Append(myWeights.print());
sb.Append(String.Format("\nHRT_plant_min: {0}\t\t\t", HRT_plant_min));
sb.Append(String.Format("HRT_plant_max: {0}\t\t\t", HRT_plant_max));
sb.Append(String.Format("OLR_plant_max: {0}\n", OLR_plant_max));
sb.Append(String.Format("manurebonus: {0}\n", manurebonus));
sb.Append(String.Format("fitness_function: {0}\t\t", fitness_function));
sb.Append(String.Format("nObjectives: {0}\r\n", nObjectives));
//sb.Append(String.Format("Ndelta: {0}\n", _Ndelta));
// add setpoints
sb.Append(mySetpoints.print());
sb.Append(" ---------- ---------- ---------- ---------- \n");
return sb.ToString();
}
}
}
| Java |
/* This file is part of libcuzmem
Copyright (C) 2011 James A. Shackleford
libcuzmem is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <math.h>
#include "context.h"
#include "plans.h"
#include "tuner_util.h"
#include "tuner_exhaust.h"
//------------------------------------------------------------------------------
// TUNER INTERFACE
//------------------------------------------------------------------------------
cuzmem_plan*
cuzmem_tuner_exhaust (enum cuzmem_tuner_action action, void* parm)
{
CUZMEM_CONTEXT ctx = get_context();
// =========================================================================
// TUNER START
// =========================================================================
if (CUZMEM_TUNER_START == action) {
// For now, do nothing special.
if (ctx->tune_iter == 0) {
// if we are in the 0th tuning cycle, do nothing here.
// CUZMEM_TUNER_LOOKUP is determining the search space
return NULL;
}
else {
// start timing the iteration
ctx->start_time = get_time ();
}
// Return value currently has no meaning
return NULL;
}
// =========================================================================
// TUNER LOOKUP
// =========================================================================
else if (CUZMEM_TUNER_LOOKUP == action) {
// parm: pointer to size of allocation
size_t size = *(size_t*)(parm);
CUresult ret;
int loopy = 0;
cuzmem_plan* entry = NULL;
int loc;
// default 0th tuning iteration handling
if (ctx->tune_iter == 0) {
return zeroth_lookup_handler (ctx, size);
}
// handle looping allocations & get current entry
if (loopy_entry (ctx, &entry, size)) {
return loopy_entry_handler (entry, size);
}
// exhaustive tuning
// ---------------------------------------------------------------------
entry->loc = (ctx->tune_iter >> ctx->current_knob) & 0x0001;
loc = entry->loc;
ret = alloc_mem (entry, size);
// "natural mutation"
if (loc != entry->loc) {
// add large value to timer to invalidate this plan
ctx->start_time -= (0.50*ctx->start_time);
}
// ---------------------------------------------------------------------
ctx->current_knob++;
return entry;
}
// =========================================================================
// TUNER END
// =========================================================================
else if (CUZMEM_TUNER_END == action) {
int i;
double time;
cuzmem_plan* entry = NULL;
int all_global = 1;
int satisfied = 0;
unsigned int gpu_mem_free, gpu_mem_total, gpu_mem_req;
unsigned int gpu_mem_min;
CUresult ret;
// standard tuner structure
// ---------------------------------------------------------------------
if (ctx->tune_iter == 0) {
if (zeroth_end_handler (ctx)) {
// everything fits in GPU memory, returning ends search
return NULL;
}
// exhaustive search specific: compute # of tune iterations
ctx->tune_iter_max = (unsigned long long)pow (2, ctx->num_knobs);
}
// get the time to complete this iteration
time = get_time() - ctx->start_time;
if (time < ctx->best_time) {
ctx->best_time = time;
ctx->best_plan = ctx->tune_iter; // algorithm dependent
}
// reset current knob for next tune iteration
ctx->current_knob = 0;
// ---------------------------------------------------------------------
printf ("libcuzmem: best plan is #%llu of %llu\n", ctx->best_plan, ctx->tune_iter_max);
// pull down GPU global memory usage from CUDA driver
ret = cuMemGetInfo (&gpu_mem_free, &gpu_mem_total);
if (ret != CUDA_SUCCESS) {
fprintf (stderr, "libcuzmem: could not retrieve GPU memory info from CUDA Driver!\n");
exit (1);
} else {
gpu_mem_min = (unsigned int)((float)gpu_mem_free * (float)ctx->gpu_mem_percent * 0.01f);
gpu_mem_free -= 20000000;
}
// check to make sure the next iteration's plan draft meets the GPU
// global memory utilization constraint if it doesn't, we will skip it
// and subsequent plans until we find one that does.
//
// we also use this oppurtunity to clear out all of our inloop entry's
// 1st hit flags
i = ctx->tune_iter + 1;
do {
gpu_mem_req = 0;
entry = ctx->plan;
while (entry != NULL) {
entry->loc = (i >> entry->id) & 0x0001;
entry->first_hit = 1;
if (entry->loc == 1 && entry->gold_member) {
gpu_mem_req += entry->size;
}
entry = entry->next;
}
fprintf (stderr,
" Request for Plan %i of %llu: %i (min: %i)\n",
i,
ctx->tune_iter_max,
gpu_mem_req,
gpu_mem_min
);
if ((gpu_mem_req >= gpu_mem_min) && (gpu_mem_req < gpu_mem_free)) {
// we subtract one beacuse tune_iter is auto-increment after this
// function returns (before the next tune iterations starts)
ctx->tune_iter = i - 1;
satisfied = 1;
} else {
i++;
}
} while (!satisfied);
// always end with this
max_iteration_handler (ctx);
return NULL;
}
// =========================================================================
// TUNER: UNKNOWN ACTION SPECIFIED
// =========================================================================
else {
printf ("libcuzmem: tuner asked to perform unknown action!\n");
exit (1);
return NULL;
}
// =========================================================================
}
| Java |
/* Copyright 2004,2007,2008,2010,2011,2014 IPB, Universite de Bordeaux, INRIA & CNRS
**
** This file is part of the Scotch software package for static mapping,
** graph partitioning and sparse matrix ordering.
**
** This software is governed by the CeCILL-C license under French law
** and abiding by the rules of distribution of free software. You can
** use, modify and/or redistribute the software under the terms of the
** CeCILL-C license as circulated by CEA, CNRS and INRIA at the following
** URL: "http://www.cecill.info".
**
** As a counterpart to the access to the source code and rights to copy,
** modify and redistribute granted by the license, users are provided
** only with a limited warranty and the software's author, the holder of
** the economic rights, and the successive licensors have only limited
** liability.
**
** In this respect, the user's attention is drawn to the risks associated
** with loading, using, modifying and/or developing or reproducing the
** software by the user in light of its specific status of free software,
** that may mean that it is complicated to manipulate, and that also
** therefore means that it is reserved for developers and experienced
** professionals having in-depth computer knowledge. Users are therefore
** encouraged to load and test the software's suitability as regards
** their requirements in conditions enabling the security of their
** systems and/or data to be ensured and, more generally, to use and
** operate it in the same conditions as regards security.
**
** The fact that you are presently reading this means that you have had
** knowledge of the CeCILL-C license and that you accept its terms.
*/
/************************************************************/
/** **/
/** NAME : bgraph_bipart_bd.c **/
/** **/
/** AUTHOR : Francois PELLEGRINI **/
/** **/
/** FUNCTION : This module builds a band graph around **/
/** the frontier in order to decrease **/
/** problem size for the strategy to be **/
/** applied. **/
/** **/
/** DATES : # Version 5.0 : from : 27 nov 2006 **/
/** to : 23 dec 2007 **/
/** # Version 5.1 : from : 09 nov 2008 **/
/** to : 26 mar 2011 **/
/** # Version 6.0 : from : 07 nov 2011 **/
/** to : 08 aug 2014 **/
/** **/
/************************************************************/
/*
** The defines and includes.
*/
#define BGRAPH_BIPART_BD
#include "module.h"
#include "common.h"
#include "parser.h"
#include "graph.h"
#include "arch.h"
#include "bgraph.h"
#include "bgraph_bipart_bd.h"
#include "bgraph_bipart_st.h"
/*****************************/
/* */
/* This is the main routine. */
/* */
/*****************************/
int
bgraphBipartBd (
Bgraph * restrict const orggrafptr, /*+ Active graph +*/
const BgraphBipartBdParam * const paraptr) /*+ Method parameters +*/
{
Gnum * restrict queutab;
Gnum queuheadval;
Gnum queutailval;
Gnum distmax; /* Maximum distance allowed */
Gnum * restrict orgindxtax; /* Based access to index array for original graph */
Gnum orgfronnum;
Gnum ancfronnum;
Gnum bndfronnum;
Bgraph bndgrafdat; /* Band graph structure */
Gnum bndvertnbr; /* Number of regular vertices in band graph (without anchors) */
Gnum bndvertnnd;
const Gnum * restrict bndvnumtax; /* Band vertex number array, recycling queutab */
Gnum * restrict bndveextax; /* External gain array of band graph, if present */
Gnum bndveexnbr; /* Number of external array vertices */
Gnum bndvelosum; /* Load of regular vertices in band graph */
Gnum bndedlosum; /* Sum of edge loads */
Gnum bndcompsize1; /* Number of regular vertices in part 1 of band graph */
Gnum bndcompload1; /* Load of regular vertices in part 1 */
Gnum bndvlvlnum; /* Index of first band graph vertex to belong to the last layer */
Gnum bndvertnum;
Gnum bndeancnbr; /* Number of anchor edges */
Gnum bndedgenbr; /* Upper bound on the number of edges, including anchor edges */
Gnum bndedgenum;
Gnum * restrict bndedgetax;
Gnum * restrict bndedlotax;
Gnum bndedgetmp;
Gnum bnddegrmax;
Gnum bndcommgainextn; /* Sum of all external gains in band graph */
Gnum bndcommgainextn1; /* Sum of external gains accounted for in load, since in part 1 */
size_t bndedlooftval; /* Offset of edge load array with respect to edge array */
const Gnum * restrict const orgverttax = orggrafptr->s.verttax; /* Fast accesses */
const Gnum * restrict const orgvendtax = orggrafptr->s.vendtax;
const Gnum * restrict const orgvelotax = orggrafptr->s.velotax;
const Gnum * restrict const orgedgetax = orggrafptr->s.edgetax;
const Gnum * restrict const orgedlotax = orggrafptr->s.edlotax;
GraphPart * restrict const orgparttax = orggrafptr->parttax;
Gnum * restrict const orgfrontab = orggrafptr->frontab;
if (orggrafptr->fronnbr == 0) /* If no separator vertices, apply strategy to full (original) graph */
return (bgraphBipartSt (orggrafptr, paraptr->stratorg));
distmax = (Gnum) paraptr->distmax;
if (distmax < 1) /* Always at least one layer of vertices around separator */
distmax = 1;
if (memAllocGroup ((void **) (void *)
&queutab, (size_t) (orggrafptr->s.vertnbr * sizeof (Gnum)),
&orgindxtax, (size_t) (orggrafptr->s.vertnbr * sizeof (Gnum)), NULL) == NULL) {
errorPrint ("bgraphBipartBd: out of memory (1)");
return (1);
}
memSet (orgindxtax, ~0, orggrafptr->s.vertnbr * sizeof (Gnum)); /* Initialize index array */
orgindxtax -= orggrafptr->s.baseval;
queuheadval = orggrafptr->fronnbr; /* First layer is vertices in frontier array */
for (orgfronnum = 0, bndvertnnd = orggrafptr->s.baseval; /* Flag vertices belonging to frontier as band vertices */
orgfronnum < queuheadval; orgfronnum ++) {
Gnum orgvertnum;
orgvertnum = orgfrontab[orgfronnum];
orgindxtax[orgvertnum] = bndvertnnd ++;
queutab[orgfronnum] = orgvertnum; /* Copy frontier array in queue array */
}
bndvelosum = 0;
bndedgenbr = 0; /* Estimate upper bound on the number of edges */
bndcompsize1 = 0;
bndcompload1 = 0;
queutailval = 0;
bndvlvlnum = 0; /* Assume first layer is last layer */
while (distmax -- > 0) { /* For all passes except the last one */
Gnum orgvertnum;
Gnum orgdistval;
bndvlvlnum = queuheadval; /* Record start of last layer */
while (queutailval < bndvlvlnum) { /* For all vertices in queue */
Gnum orgvertnum;
Gnum orgedgenum;
Gnum orgpartval;
orgvertnum = queutab[queutailval ++];
#ifdef SCOTCH_DEBUG_BGRAPH2
if ((orgvertnum < orggrafptr->s.baseval) || (orgvertnum >= orggrafptr->s.vertnnd)) {
errorPrint ("bgraphBipartBd: internal error (1)");
return (1);
}
#endif /* SCOTCH_DEBUG_BGRAPH2 */
bndedgenbr += orgvendtax[orgvertnum] - orgverttax[orgvertnum]; /* Exact number of edges */
orgpartval = orgparttax[orgvertnum];
bndcompsize1 += orgpartval; /* Count vertices in part 1 */
if (orgvelotax != NULL) {
Gnum orgveloval;
orgveloval = orgvelotax[orgvertnum];
bndvelosum += orgveloval;
bndcompload1 += orgveloval * orgpartval;
}
for (orgedgenum = orgverttax[orgvertnum];
orgedgenum < orgvendtax[orgvertnum]; orgedgenum ++) {
Gnum orgvertend;
orgvertend = orgedgetax[orgedgenum];
if (orgindxtax[orgvertend] == ~0) { /* If vertex not visited yet */
orgindxtax[orgvertend] = bndvertnnd ++; /* Flag it as enqueued */
queutab[queuheadval ++] = orgvertend; /* Enqueue it */
}
}
}
}
bndedgenbr += queuheadval - queutailval; /* As many edges from anchors as remaining vertices */
while (queutailval < queuheadval) { /* Process vertices in last layer */
Gnum orgvertnum;
Gnum orgpartval;
orgvertnum = queutab[queutailval ++];
#ifdef SCOTCH_DEBUG_BGRAPH2
if ((orgvertnum < orggrafptr->s.baseval) || (orgvertnum >= orggrafptr->s.vertnnd)) {
errorPrint ("bgraphBipartBd: internal error (2)");
return (1);
}
#endif /* SCOTCH_DEBUG_BGRAPH2 */
bndedgenbr += orgvendtax[orgvertnum] - orgverttax[orgvertnum]; /* Upper bound on number of edges, including anchor edge */
orgpartval = orgparttax[orgvertnum];
bndcompsize1 += orgpartval; /* Count vertices in part 1 */
if (orgvelotax != NULL) {
Gnum orgveloval;
orgveloval = orgvelotax[orgvertnum];
bndvelosum += orgveloval;
bndcompload1 += orgveloval * orgpartval;
}
}
bndvertnbr = bndvertnnd - orggrafptr->s.baseval;
if (orgvelotax == NULL) {
bndvelosum = bndvertnbr;
bndcompload1 = bndcompsize1;
}
if ((bndcompsize1 >= (orggrafptr->s.vertnbr - orggrafptr->compsize0)) || /* If either part has all of its vertices in band, use plain graph instead */
((bndvertnbr - bndcompsize1) >= orggrafptr->compsize0)) {
memFree (queutab);
return (bgraphBipartSt (orggrafptr, paraptr->stratorg));
} /* TRICK: since always at least one missing vertex per part, there is room for anchor vertices */
queutab[bndvertnbr] = /* Anchor vertices do not have original vertex numbers */
queutab[bndvertnbr + 1] = -1;
memSet (&bndgrafdat, 0, sizeof (Bgraph));
bndgrafdat.s.flagval = GRAPHFREETABS | GRAPHVERTGROUP | GRAPHEDGEGROUP | BGRAPHHASANCHORS; /* All Bgraph arrays are non-freeable by bgraphExit() */
bndgrafdat.s.baseval = orggrafptr->s.baseval;
bndgrafdat.s.vertnbr = bndvertnbr += 2; /* "+ 2" for anchor vertices */
bndgrafdat.s.vertnnd = bndvertnnd + 2;
bndveexnbr = (orggrafptr->veextax != NULL) ? bndvertnbr : 0;
if (memAllocGroup ((void **) (void *) /* Do not allocate vnumtax but keep queutab instead */
&bndgrafdat.s.verttax, (size_t) ((bndvertnbr + 1) * sizeof (Gnum)),
&bndgrafdat.s.velotax, (size_t) (bndvertnbr * sizeof (Gnum)),
&bndveextax, (size_t) (bndveexnbr * sizeof (Gnum)),
&bndgrafdat.frontab, (size_t) (bndvertnbr * sizeof (Gnum)),
&bndgrafdat.parttax, (size_t) (bndvertnbr * sizeof (GraphPart)), NULL) == NULL) {
errorPrint ("bgraphBipartBd: out of memory (2)");
memFree (queutab);
return (1);
}
bndgrafdat.parttax -= orggrafptr->s.baseval; /* From now on we should free a Bgraph and not a Graph */
bndgrafdat.s.verttax -= orggrafptr->s.baseval;
bndgrafdat.s.vendtax = bndgrafdat.s.verttax + 1; /* Band graph is compact */
bndgrafdat.s.velotax -= orggrafptr->s.baseval;
bndgrafdat.s.vnumtax = queutab - orggrafptr->s.baseval; /* TRICK: re-use queue array as vertex number array since vertices taken in queue order; will not be freed as graph vertex arrays are said to be grouped */
bndgrafdat.s.velosum = orggrafptr->s.velosum;
bndgrafdat.s.velotax[bndvertnnd] = orggrafptr->compload0 - (bndvelosum - bndcompload1); /* Set loads of anchor vertices */
bndgrafdat.s.velotax[bndvertnnd + 1] = orggrafptr->s.velosum - orggrafptr->compload0 - bndcompload1;
if (bndveexnbr != 0) {
bndveextax -= orggrafptr->s.baseval;
bndgrafdat.veextax = bndveextax;
}
else
bndveextax = NULL;
if (memAllocGroup ((void **) (void *)
&bndgrafdat.s.edgetax, (size_t) (bndedgenbr * sizeof (Gnum)),
&bndgrafdat.s.edlotax, (size_t) (bndedgenbr * sizeof (Gnum)), NULL) == NULL) {
errorPrint ("bgraphBipartBd: out of memory (3)");
bgraphExit (&bndgrafdat);
memFree (queutab);
return (1);
}
bndgrafdat.s.edgetax -= orggrafptr->s.baseval;
bndgrafdat.s.edlotax -= orggrafptr->s.baseval;
bndedgetax = bndgrafdat.s.edgetax;
bndedlotax = bndgrafdat.s.edlotax;
bndvnumtax = bndgrafdat.s.vnumtax;
for (bndvertnum = bndedgenum = orggrafptr->s.baseval, bnddegrmax = bndedlosum = bndcommgainextn = bndcommgainextn1 = 0;
bndvertnum < bndvlvlnum; bndvertnum ++) { /* Fill index array for vertices not belonging to last level */
Gnum orgvertnum;
GraphPart orgpartval;
Gnum orgedgenum;
Gnum orgedloval;
Gnum bnddegrval;
orgvertnum = bndvnumtax[bndvertnum];
orgpartval = orgparttax[orgvertnum];
bndgrafdat.s.verttax[bndvertnum] = bndedgenum;
bndgrafdat.s.velotax[bndvertnum] = (orgvelotax != NULL) ? orgvelotax[orgvertnum] : 1;
bndgrafdat.parttax[bndvertnum] = orgpartval;
if (bndveextax != NULL) {
Gnum orgveexval;
orgveexval = orggrafptr->veextax[orgvertnum];
bndveextax[bndvertnum] = orgveexval;
bndcommgainextn += orgveexval;
bndcommgainextn1 += orgveexval * (Gnum) orgpartval;
}
orgedloval = 1; /* Assume unity edge loads if not present */
for (orgedgenum = orgverttax[orgvertnum]; /* All edges of first levels are kept */
orgedgenum < orgvendtax[orgvertnum]; orgedgenum ++, bndedgenum ++) {
#ifdef SCOTCH_DEBUG_BGRAPH2
if ((bndedgenum >= (bndedgenbr + orggrafptr->s.baseval)) ||
(orgindxtax[orgedgetax[orgedgenum]] < 0)) {
errorPrint ("bgraphBipartBd: internal error (3)");
return (1);
}
#endif /* SCOTCH_DEBUG_BGRAPH2 */
if (orgedlotax != NULL)
orgedloval = orgedlotax[orgedgenum];
bndedlosum += orgedloval;
bndedgetax[bndedgenum] = orgindxtax[orgedgetax[orgedgenum]];
bndedlotax[bndedgenum] = orgedloval;
}
bnddegrval = bndedgenum - bndgrafdat.s.verttax[bndvertnum];
if (bnddegrmax < bnddegrval)
bnddegrmax = bnddegrval;
}
bndeancnbr = 0;
for ( ; bndvertnum < bndvertnnd; bndvertnum ++) { /* Fill index array for vertices belonging to last level */
Gnum orgvertnum;
Gnum orgedgenum;
GraphPart orgpartval;
Gnum bnddegrval;
Gnum orgedloval;
Gnum ancedloval; /* Accumulated edge load for anchor edge */
orgvertnum = bndvnumtax[bndvertnum];
orgpartval = orgparttax[orgvertnum];
bndgrafdat.s.verttax[bndvertnum] = bndedgenum;
bndgrafdat.s.velotax[bndvertnum] = (orgvelotax != NULL) ? orgvelotax[orgvertnum] : 1;
bndgrafdat.parttax[bndvertnum] = orgpartval; /* Record part for vertices of last level */
if (bndveextax != NULL) {
Gnum orgveexval;
orgveexval = orggrafptr->veextax[orgvertnum];
bndveextax[bndvertnum] = orgveexval;
bndcommgainextn += orgveexval;
bndcommgainextn1 += orgveexval * (Gnum) orgpartval;
}
ancedloval = 0;
orgedloval = 1; /* Assume unity edge loads if not present */
for (orgedgenum = orgverttax[orgvertnum]; /* Keep only band edges */
orgedgenum < orgvendtax[orgvertnum]; orgedgenum ++) {
Gnum bndvertend;
#ifdef SCOTCH_DEBUG_BGRAPH2
if (bndedgenum >= (bndedgenbr + orggrafptr->s.baseval)) {
errorPrint ("bgraphBipartBd: internal error (4)");
return (1);
}
#endif /* SCOTCH_DEBUG_BGRAPH2 */
if (orgedlotax != NULL)
orgedloval = orgedlotax[orgedgenum];
bndedlosum += orgedloval; /* Normal arcs are accounted for twice; anchor arcs only once */
bndvertend = orgindxtax[orgedgetax[orgedgenum]];
if (bndvertend != ~0) {
bndedgetax[bndedgenum] = bndvertend;
bndedlotax[bndedgenum ++] = orgedloval;
}
else
ancedloval += orgedloval; /* Accumulate loads of edges linking to anchor vertex */
}
bndedlosum += ancedloval; /* Account for anchor edges a second time */
if (ancedloval > 0) { /* If vertex is connected to rest of part */
bndedlotax[bndedgenum] = ancedloval;
bndedgetax[bndedgenum ++] = bndvertnnd + (Gnum) orgpartval; /* Add anchor edge to proper anchor vertex */
bndeancnbr ++;
}
bnddegrval = bndedgenum - bndgrafdat.s.verttax[bndvertnum];
if (bnddegrmax < bnddegrval)
bnddegrmax = bnddegrval;
}
bndgrafdat.parttax[bndvertnnd] = 0; /* Set parts of anchor vertices */
bndgrafdat.parttax[bndvertnnd + 1] = 1;
bndgrafdat.s.edlosum = bndedlosum;
bndgrafdat.s.verttax[bndvertnnd] = bndedgenum; /* Mark end of regular edge array and start of first anchor edge array */
bndedgetmp = bndedgenum + bndeancnbr;
#ifdef SCOTCH_DEBUG_BGRAPH2
if ((bndedgetmp - 1) >= (bndedgenbr + orggrafptr->s.baseval)) {
errorPrint ("bgraphBipartBd: internal error (5)");
return (1);
}
#endif /* SCOTCH_DEBUG_BGRAPH2 */
bndgrafdat.s.edgenbr = bndedgetmp - orggrafptr->s.baseval;
bndgrafdat.s.verttax[bndvertnnd + 2] = bndedgetmp; /* Mark end of edge array with anchor vertices */
for (bndvertnum = bndvlvlnum; bndvertnum < bndvertnnd; bndvertnum ++) { /* Fill anchor edge arrays */
Gnum orgvertnum;
orgvertnum = bndvnumtax[bndvertnum];
if (bndgrafdat.s.verttax[bndvertnum + 1] > bndgrafdat.s.verttax[bndvertnum]) { /* If vertex is not isolated */
Gnum bndedgelst; /* Number of last edge */
Gnum bndvertend;
bndedgelst = bndgrafdat.s.verttax[bndvertnum + 1] - 1;
bndvertend = bndedgetax[bndedgelst]; /* Get last neighbor of its edge sub-array */
if (bndvertend >= bndvertnnd) { /* If it is an anchor */
Gnum bndedloval;
bndedloval = bndedlotax[bndedgelst];
bndedlosum += bndedloval;
if (bndvertend == bndvertnnd) { /* Add edge from proper anchor */
bndedgetax[bndedgenum] = bndvertnum;
bndedlotax[bndedgenum ++] = bndedloval;
}
else {
bndedgetax[-- bndedgetmp] = bndvertnum;
bndedlotax[bndedgetmp] = bndedloval;
}
}
}
}
bndgrafdat.s.verttax[bndvertnnd + 1] = bndedgenum; /* Mark end of edge array of first anchor and start of second */
#ifdef SCOTCH_DEBUG_BGRAPH2
if (bndedgenum != bndedgetmp) {
errorPrint ("bgraphBipartBd: internal error (6)");
return (1);
}
#endif /* SCOTCH_DEBUG_BGRAPH2 */
if ((bndedgenum == bndgrafdat.s.verttax[bndvertnnd]) || /* If any of the anchor edges is isolated */
(bndedgenum == bndgrafdat.s.verttax[bndvertnnd + 2])) {
bgraphExit (&bndgrafdat); /* Free all band graph related data */
memFree (queutab);
return (bgraphBipartSt (orggrafptr, paraptr->stratorg)); /* Work on original graph */
}
if (bnddegrmax < (bndgrafdat.s.verttax[bndvertnnd + 1] - bndgrafdat.s.verttax[bndvertnnd]))
bnddegrmax = (bndgrafdat.s.verttax[bndvertnnd + 1] - bndgrafdat.s.verttax[bndvertnnd]);
if (bnddegrmax < (bndgrafdat.s.verttax[bndvertnnd + 2] - bndgrafdat.s.verttax[bndvertnnd + 1]))
bnddegrmax = (bndgrafdat.s.verttax[bndvertnnd + 2] - bndgrafdat.s.verttax[bndvertnnd + 1]);
bndgrafdat.s.degrmax = bnddegrmax;
bndedlooftval = bndedlotax - bndedgetax;
bndgrafdat.s.edgetax = (Gnum *) memRealloc (bndedgetax + bndgrafdat.s.baseval, (bndedlooftval + bndgrafdat.s.edgenbr) * sizeof (Gnum)) - bndgrafdat.s.baseval;
bndgrafdat.s.edlotax = bndgrafdat.s.edgetax + bndedlooftval; /* Use old index into old array as new index */
bndedgetax = bndgrafdat.s.edgetax;
bndedlotax = bndgrafdat.s.edlotax;
for (bndfronnum = 0, bndvertnum = orggrafptr->s.baseval; /* Fill band frontier array with first vertex indices as they make the separator */
bndfronnum < orggrafptr->fronnbr; bndfronnum ++, bndvertnum ++)
bndgrafdat.frontab[bndfronnum] = bndvertnum;
if (bndveextax != NULL) {
Gnum bndcommloadintn;
Gnum bndfronnnd;
Gnum bndvertnum;
Gnum bndedgenum;
Gnum bndedloval;
bndedloval = 1; /* Assume unity edge weights */
bndcommloadintn = 0;
for (bndvertnum = orggrafptr->s.baseval, bndfronnnd = bndvertnum + orggrafptr->fronnbr; /* Compute communication load at frontier */
bndvertnum < bndfronnnd; bndvertnum ++) {
Gnum bndpartval;
bndpartval = (Gnum) bndgrafdat.parttax[bndvertnum];
if (bndpartval != 0) /* Process only frontier vertices in part 0 */
continue;
for (bndedgenum = bndgrafdat.s.verttax[bndvertnum]; bndedgenum < bndgrafdat.s.vendtax[bndvertnum]; bndedgenum ++) {
Gnum bndpartend;
bndpartend = (Gnum) bndgrafdat.parttax[bndedgetax[bndedgenum]];
bndedloval = bndedlotax[bndedgenum];
bndcommloadintn += bndedloval * bndpartend;
}
}
bndcommloadintn *= orggrafptr->domndist;
bndveextax[bndvertnnd + 1] = (orggrafptr->commload - orggrafptr->commloadextn0 - bndcommloadintn) - bndcommgainextn1;
bndveextax[bndvertnnd] = (orggrafptr->commload - orggrafptr->commloadextn0 - bndcommloadintn) - bndcommgainextn + bndcommgainextn1 + orggrafptr->commgainextn;
}
bndgrafdat.fronnbr = orggrafptr->fronnbr;
bndgrafdat.compload0 = orggrafptr->compload0;
bndgrafdat.compload0min = orggrafptr->compload0min;
bndgrafdat.compload0max = orggrafptr->compload0max;
bndgrafdat.compload0avg = orggrafptr->compload0avg;
bndgrafdat.compload0dlt = orggrafptr->compload0dlt;
bndgrafdat.compsize0 = bndvertnbr - bndcompsize1 - 1; /* "- 1" for anchor vertex in part 0 */
bndgrafdat.commload = orggrafptr->commload;
bndgrafdat.commloadextn0 = orggrafptr->commloadextn0;
bndgrafdat.commgainextn = orggrafptr->commgainextn;
bndgrafdat.commgainextn0 = orggrafptr->commgainextn0;
bndgrafdat.domndist = orggrafptr->domndist;
bndgrafdat.domnwght[0] = orggrafptr->domnwght[0];
bndgrafdat.domnwght[1] = orggrafptr->domnwght[1];
bndgrafdat.vfixload[0] = orggrafptr->vfixload[0];
bndgrafdat.vfixload[1] = orggrafptr->vfixload[1];
bndgrafdat.bbalval = orggrafptr->bbalval;
bndgrafdat.levlnum = orggrafptr->levlnum;
#ifdef SCOTCH_DEBUG_BGRAPH2
if ((graphCheck (&bndgrafdat.s) != 0) || /* Check band graph consistency */
(bgraphCheck (&bndgrafdat) != 0)) {
errorPrint ("bgraphBipartBd: inconsistent band graph data");
bgraphExit (&bndgrafdat);
memFree (queutab);
return (1);
}
#endif /* SCOTCH_DEBUG_BGRAPH2 */
if (bgraphBipartSt (&bndgrafdat, paraptr->stratbnd) != 0) { /* Apply strategy to band graph */
errorPrint ("bgraphBipartBd: cannot bipartition band graph");
bgraphExit (&bndgrafdat);
memFree (queutab);
return (1);
}
if (bndgrafdat.parttax[bndvertnnd] == /* If band graph was too small and anchors went to the same part, apply strategy on full graph */
bndgrafdat.parttax[bndvertnnd + 1]) {
bgraphExit (&bndgrafdat);
memFree (queutab);
return (bgraphBipartSt (orggrafptr, paraptr->stratorg));
}
orggrafptr->compload0 = bndgrafdat.compload0;
orggrafptr->compload0dlt = bndgrafdat.compload0dlt;
orggrafptr->commload = bndgrafdat.commload;
orggrafptr->commgainextn = bndgrafdat.commgainextn;
orggrafptr->bbalval = bndgrafdat.bbalval;
if (bndgrafdat.parttax[bndvertnnd] != 0) { /* If anchors swapped parts, swap all parts of original vertices */
Gnum orgvertnum;
orggrafptr->compsize0 = orggrafptr->s.vertnbr - orggrafptr->compsize0 - bndcompsize1 + bndgrafdat.compsize0 - 1; /* "- 1" for anchor 0 */
for (orgvertnum = orggrafptr->s.baseval; orgvertnum < orggrafptr->s.vertnnd; orgvertnum ++)
orgparttax[orgvertnum] ^= 1;
}
else
orggrafptr->compsize0 = orggrafptr->compsize0 - (bndvertnbr - bndcompsize1) + bndgrafdat.compsize0 + 1; /* "+ 1" for anchor 0 */
for (bndvertnum = bndgrafdat.s.baseval; bndvertnum < bndvertnnd; bndvertnum ++) /* Update part array of full graph */
orgparttax[bndvnumtax[bndvertnum]] = bndgrafdat.parttax[bndvertnum];
for (bndfronnum = orgfronnum = ancfronnum = 0; /* Update frontier array of full graph */
bndfronnum < bndgrafdat.fronnbr; bndfronnum ++) {
Gnum bndvertnum;
Gnum orgvertnum;
bndvertnum = bndgrafdat.frontab[bndfronnum];
orgvertnum = bndvnumtax[bndvertnum];
if (orgvertnum != -1) /* If frontier vertex is not an anchor vertex */
orgfrontab[orgfronnum ++] = orgvertnum; /* Record it as original frontier vertex */
else
bndgrafdat.frontab[ancfronnum ++] = bndvertnum; /* Else record it for future processing */
}
while (ancfronnum > 0) { /* For all recorded frontier anchor vertices */
Gnum bndvertnum; /* Index of frontier anchor vertex in band graph */
GraphPart ancpartval;
bndvertnum = bndgrafdat.frontab[-- ancfronnum];
ancpartval = bndgrafdat.parttax[bndvertnum];
for (bndedgenum = bndgrafdat.s.verttax[bndvertnum];
bndedgenum < bndgrafdat.s.vendtax[bndvertnum]; bndedgenum ++) {
Gnum bndvertend; /* Index of neighbor of anchor vertex in band graph */
Gnum orgvertnum; /* Index of neighbor of anchor vertex in original graph */
Gnum orgedgenum;
bndvertend = bndedgetax[bndedgenum];
if (bndgrafdat.parttax[bndvertend] == ancpartval) /* If neighbor is in same part as anchor, skip to next */
continue;
orgvertnum = bndvnumtax[bndvertend];
for (orgedgenum = orgverttax[orgvertnum]; /* For all neighbors of neighbor */
orgedgenum < orgvendtax[orgvertnum]; orgedgenum ++) {
Gnum orgvertend;
orgvertend = orgedgetax[orgedgenum]; /* Get end vertex in original graph */
if (orgindxtax[orgvertend] == ~0) { /* If vertex never considered before */
#ifdef SCOTCH_DEBUG_BGRAPH2
if (orgparttax[orgvertend] != ancpartval) { /* Original vertex should always be in same part as anchor */
errorPrint ("bgraphBipartBd: internal error (7)");
return (1);
}
#endif /* SCOTCH_DEBUG_BGRAPH2 */
orggrafptr->frontab[orgfronnum ++] = orgvertend; /* Add vertex to frontier array */
orgindxtax[orgvertend] = 0; /* Flag vertex as already enqueued */
}
}
}
}
orggrafptr->fronnbr = orgfronnum;
bgraphExit (&bndgrafdat); /* Free band graph structures */
memFree (queutab);
#ifdef SCOTCH_DEBUG_BGRAPH2
if (bgraphCheck (orggrafptr) != 0) {
errorPrint ("bgraphBipartBd: inconsistent graph data");
return (1);
}
#endif /* SCOTCH_DEBUG_BGRAPH2 */
return (0);
}
| Java |
<?php
/**
* Usage Statistics
*
* @package MyAAC
* @author Slawkens <slawkens@gmail.com>
* @copyright 2019 MyAAC
* @link https://my-aac.org
*/
defined('MYAAC') or die('Direct access not allowed!');
class Usage_Statistics {
private static $report_url = 'https://my-aac.org/report_usage.php';
public static function report() {
$data = json_encode(self::getStats());
$options = array(
'http' => array(
'header' => 'Content-type: application/json' . "\r\n"
. 'Content-Length: ' . strlen($data) . "\r\n",
'content' => $data
)
);
$context = stream_context_create($options);
$result = file_get_contents(self::$report_url, false, $context);
return $result !== false;
}
public static function getStats() {
global $config, $db;
$ret = array();
$ret['unique_id'] = hash('sha1', $config['server_path']);
$ret['server_os'] = php_uname('s') . ' ' . php_uname('r');
$ret['myaac_version'] = MYAAC_VERSION;
$ret['myaac_db_version'] = DATABASE_VERSION;
if($db->hasTable('server_config')) {
$query = $db->query('SELECT `value` FROM `server_config` WHERE `config` = ' . $db->quote('database_version'));
if($query->rowCount() == 1) {
$query = $query->fetch();
$ret['otserv_db_version'] = $query['value'];
}
}
$ret['client_version'] = $config['client'];
$ret['php_version'] = phpversion();
$query = $db->query('SELECT VERSION() as `version`;');
if($query->rowCount() == 1) {
$query = $query->fetch();
$ret['mysql_version'] = $query['version'];
}
$query = $db->query('SELECT SUM(ROUND(((DATA_LENGTH + INDEX_LENGTH) / 1024 ), 0)) AS "size"
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = "' . $config['database_name'] . '";');
if($query->rowCount() == 1) {
$query = $query->fetch();
$ret['database_size'] = $query['size'];
}
$ret['views_counter'] = getDatabaseConfig('views_counter');
$query = $db->query('SELECT COUNT(`id`) as `size` FROM `accounts`;');
if($query->rowCount() == 1) {
$query = $query->fetch();
$ret['accounts_size'] = $query['size'];
}
$query = $db->query('SELECT COUNT(`id`) as `size` FROM `players`;');
if($query->rowCount() == 1) {
$query = $query->fetch();
$ret['players_size'] = $query['size'];
}
$query = $db->query('SELECT COUNT(`id`) as `size` FROM `' . TABLE_PREFIX . 'monsters`;');
if($query->rowCount() == 1) {
$query = $query->fetch();
$ret['monsters_size'] = $query['size'];
}
$query = $db->query('SELECT COUNT(`id`) as `size` FROM `' . TABLE_PREFIX . 'spells`;');
if($query->rowCount() == 1) {
$query = $query->fetch();
$ret['spells_size'] = $query['size'];
}
$ret['locales'] = get_locales();
$ret['plugins'] = array();
foreach(get_plugins() as $plugin) {
$string = file_get_contents(BASE . 'plugins/' . $plugin . '.json');
$plugin_info = json_decode($string, true);
if($plugin_info != false) {
if(isset($plugin_info['version'])) {
$ret['plugins'][$plugin] = $plugin_info['version'];
}
}
}
$ret['templates'] = get_templates();
$ret['date_timezone'] = $config['date_timezone'];
$ret['backward_support'] = $config['backward_support'];
$cache_engine = strtolower($config['cache_engine']);
if($cache_engine == 'auto') {
$cache_engine = Cache::detect();
}
$ret['cache_engine'] = $cache_engine;
return $ret;
}
} | Java |
<style>
ion-content{
background-color: #00091a;
color:#e6eeff;
}
ion-card{
text-align: right;
}
/*global CSS*/
#gems{
background-color: inherit;
}
.more {
float: none;
}
.menu{
transform: translate(-50%, 55%);
}
/*small devices*/
@media (min-width: 320px) and (max-width: 480px) {
.more{
margin-top: 20vh;
}
.container{
margin-top: 20vh;
}
#avatar{
float: center;
height:50px;
width:50px;
margin-left: 19vw;
margin-top: 2vh;
border-radius: 50%;
}
.menu {
position: relative;
margin-top: 25%;
left: 50%;
width: 0px;
}
.toggle + .style {
width: 190px;
height: 190px;
border-radius: 50%;
cursor: pointer;
transform: translate(-50%, -50%) scale(1);
z-index: 5;
display: block;
max-width: 50vw;
margin-bottom: 0;
background-size: 200px 200px;
background-position: center;
background-repeat: no-repeat;
color: #fff;
font-size: 2.5em;
text-align: center;
-webkit-transition: all .8s;
-moz-transition: all .8s;
-o-transition: all .8s;
-ms-transition: all .8s;
transition: all .8s;
}
.menu p{
max-width: 20vw;
text-align: center;
margin: 0 auto;
line-height: 25px;
padding-top: 30px;
font-weight: 300;
font-size: 1.5em;
}
.toggle {
display: none;
}
.toggle + .style:hover{
-webkit-box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
-moz-box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
-ms-box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
-o-box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
}
.toggle:checked + .style {
transform: translate(-50%, -50%) scale(.5);
}
.menu input[type=checkbox] + label:before {
content: "";
position: absolute;
}
.toggle + .style:before, .toggle + .style:after {
content: "";
position: absolute;
margin: -3px;
border-radius:5px;
transition: all 0.3s;
}
.toggle + .style:before {
width: 30px;
height: 0px;
left: 10px;
top: 25px;
}
.toggle + .style:after {
width: 0px;
height: 30px;
left: 25px;
top: 10px;
}
.toggle:checked + .style:before, .toggle:checked + .style:after {
transform: rotate(135deg);
}
.toggle ~ .tab {
position: absolute;
background: #008DFF;
color: #fff;
width: 100px;
height: 100px;
left: 0px;
top: 0px;
transform: translate(-50%, -50%) scale(0);
transition: all 0.3s;
opacity: 0;
border-radius: 50%;
}
.toggle:checked ~ .tab {
opacity: 1;
transform: translate(-50%, -50%) scale(1);
}
.menu > .toggle:checked ~ .tab:nth-of-type(1) {
top: -110px;
left: 0px;
transition-delay: 0s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(2) {
top: -60px;
left: 110px;
transition-delay: 0.125s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(3) {
top: 50px;
left: 110px;
transition-delay: 0.25s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(4) {
top: 100px;
left: 0px;
transition-delay: 0.375s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(5) {
top: 45px;
left: -100px;
transition-delay: 0.5s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(6) {
top: -70px;
left: -100px;
transition-delay: 0.625s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(7) {
top: 0px;
left: -133.33333px;
transition-delay: 0.75s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(8) {
top: -94.2809px;
left: -94.2809px;
transition-delay: 0.875s;
}
#nickname{
float: right;
color: black;
font-size: 1.3em;
}
#conn_status{
margin-top:3vh;
margin-left: 21vw;
height: 5vh;
width: 10vw;
float: left;
}
#gems{
margin-top:3vh;
font-size: 4vh;
float: left;
margin-left: 1vw;
}
#gem-icon{
margin-top:3vh;
float: left;
height: 5vh;
width: 10vw;
}
hr{
margin-top:5vh;
}
}
@media (min-width: 481px) and (max-width: 767px) {
.more{
float: none;
margin-top: 20vh;
}
.container{
margin-top: 20vh;
}
#avatar{
float: center;
height:80px;
width:80px;
margin-left: 24vw;
margin-top: 2vh;
border-radius: 50%;
}
#style{
background-size: 100% 100%;
}
.menu {
position: relative;
margin-top: 25%;
left: 50%;
width: 0px;
transform: translate(-50%, 55%);
}
.toggle + .style {
width: 200px;
height: 200px;
border-radius: 50%;
cursor: pointer;
transform: translate(-50%, -50%) scale(1);
z-index: 5;
display: block;
max-width: 50vw;
margin-bottom: 100px;
background-position: center;
color: #fff;
font-size: 2.5em;
padding-top: 40px;
text-align: center;
-webkit-transition: all .8s;
-moz-transition: all .8s;
-o-transition: all .8s;
-ms-transition: all .8s;
transition: all .8s;
}
.menu p{
max-width: 20vw;
text-align: center;
margin: 0 auto;
line-height: 25px;
padding-top: 30px;
font-weight: 300;
font-size: 1.5em;
}
.toggle + .style:hover{
-webkit-box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
-moz-box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
-ms-box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
-o-box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
}
.toggle:checked + .style {
transform: translate(-50%, -50%) scale(.5);
}
.menu input[type=checkbox] + label:before {
content: "";
position: absolute;
}
.toggle + .style:before, .toggle + .style:after {
content: "";
position: absolute;
margin: -3px;
border-radius:5px;
transition: all 0.3s;
}
.toggle + .style:before {
width: 30px;
height: 0px;
left: 10px;
top: 25px;
}
.toggle + .style:after {
width: 0px;
height: 30px;
left: 25px;
top: 10px;
}
.toggle:checked + .style:before, .toggle:checked + .style:after {
transform: rotate(135deg);
}
.toggle ~ .tab {
position: absolute;
background: #008DFF;
color: #fff;
width: 100px;
height: 100px;
left: 0px;
top: 10px;
transform: translate(-50%, -50%) scale(0);
transition: all 0.3s;
opacity: 0;
border-radius: 50%;
}
.toggle:checked ~ .tab {
opacity: 1;
transform: translate(-50%, -50%) scale(1);
}
.menu > .toggle:checked ~ .tab:nth-of-type(1) {
top: -110px;
left: 0px;
transition-delay: 0s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(2) {
top: -60px;
left: 110px;
transition-delay: 0.125s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(3) {
top: 50px;
left: 110px;
transition-delay: 0.25s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(4) {
top: 100px;
left: 0px;
transition-delay: 0.375s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(5) {
top: 45px;
left: -100px;
transition-delay: 0.5s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(6) {
top: -70px;
left: -100px;
transition-delay: 0.625s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(7) {
top: 0px;
left: -133.33333px;
transition-delay: 0.75s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(8) {
top: -94.2809px;
left: -94.2809px;
transition-delay: 0.875s;
}
#nickname {
float: right;
color: black;
font-size: 3vh;
}
#conn_status{
margin-top:3vh;
margin-left: 21vw;
height: 5vh;
width: 10vw;
float: left;
}
#gems{
margin-top:3vh;
font-size: 4vh;
float: left;
margin-left: 1vw;
}
#gem-icon{
margin-top:3vh;
float: left;
height: 5vh;
width: 10vw;
}
hr{
margin-top:15vh;
}
}
@media (min-width: 768px) and (max-width: 1024px) {
.more{
float: none;
margin-top: 30vh;
}
.container{
margin-top: 100px;
}
#avatar{
float: center;
height:80px;
width:80px;
margin-left: 30vw;
border-radius: 50%;
}
.menu {
position: relative;
margin-top: 25%;
left: 50%;
width: 0px;
transform: translate(-50%, 55%);
}
.toggle + .style {
width: 200px;
height: 200px;
border-radius: 50%;
cursor: pointer;
transform: translate(-50%, -50%) scale(1);
z-index: 5;
display: block;
max-width: 50vw;
margin-bottom: 0;
background-size: cover;
background-position: center;
font-size: 2.5em;
padding-top: 75px;
text-align: center;
-webkit-transition: all .8s;
-moz-transition: all .8s;
-o-transition: all .8s;
-ms-transition: all .8s;
transition: all .8s;
}
.menu p{
max-width: 20vw;
text-align: center;
margin: 0 auto;
line-height: 25px;
padding-top: 50px;
font-weight: 300;
font-size: 1.5em;
}
.toggle + .style:hover{
-webkit-box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
-moz-box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
-ms-box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
-o-box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
}
.toggle:checked + .style {
transform: translate(-50%, -50%) scale(.5);
}
.menu input[type=checkbox] + label:before {
content: "";
position: absolute;
}
.toggle:checked + .style:before, .toggle:checked + .style:after {
transform: rotate(135deg);
}
.toggle ~ .tab {
position: absolute;
background: #008DFF;
color: #fff;
width: 120px;
height: 120px;
left: 0px;
top: 0px;
transform: translate(-50%, -50%) scale(0);
transition: all 0.3s;
opacity: 0;
border-radius: 50%;
}
.toggle:checked ~ .tab {
opacity: 1;
transform: translate(-50%, -50%) scale(1);
}
.menu > .toggle:checked ~ .tab:nth-of-type(1) {
top: -130px;
left: 0px;
transition-delay: 0s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(2) {
top: -70px;
left: 120px;
transition-delay: 0.125s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(3) {
top: 70px;
left: 130px;
transition-delay: 0.25s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(4) {
top: 150px;
left: 0px;
transition-delay: 0.375s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(5) {
top: 80px;
left: -120px;
transition-delay: 0.5s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(6) {
top: -50px;
left: -120px;
transition-delay: 0.625s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(7) {
top: 0px;
left: -133.33333px;
transition-delay: 0.75s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(8) {
top: -94.2809px;
left: -94.2809px;
transition-delay: 0.875s;
}
#nickname{
float:right;
margin-right: 1vw;
color: black;
font-size: 2vh;
}
#conn_status{
margin-top:3vh;
margin-left: 220px;
height: 50px;
width: 50px;
float: left;
}
#gems{
margin-top:2vh;
font-size: 2vh;
float: left;
margin-left: 1vw;
}
#gem-icon{
margin-top:1vh;
float: left;
height: 5vh;
width: 10vw;
}
hr{
margin-top:5vh;
}
#nickname{
float: right;
}
}
@media (min-width: 1025px) and (max-width: 1280px){
.more{
float: none;
margin-top: 30vh;
}
.container{
margin-top: 100px;
}
#avatar{
float: center;
height:100px;
width:100px;
margin-left: 28vw;
border-radius: 50%;
}
.menu {
position: relative;
margin-top: 25%;
left: 50%;
width: 0px;
transform: translate(-50%, 55%);
}
.toggle + .style {
width: 200px;
height: 200px;
border-radius: 50%;
cursor: pointer;
transform: translate(-50%, -50%) scale(1);
z-index: 5;
display: block;
max-width: 50vw;
margin-bottom: 0;
background: #008DFF;
color: #fff;
font-size: 2.5em;
background-size: 100% 100%;
padding-top: 75px;
text-align: center;
-webkit-transition: all .8s;
-moz-transition: all .8s;
-o-transition: all .8s;
-ms-transition: all .8s;
transition: all .8s;
}
.menu p{
max-width: 20vw;
text-align: center;
margin: 0 auto;
line-height: 25px;
padding-top: 50px;
font-weight: 300;
font-size: 1.5em;
}
.toggle + .style:hover{
-webkit-box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
-moz-box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
-ms-box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
-o-box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
box-shadow: 0px 1px 20px 0px rgba(0, 0, 0, .7);
}
.toggle:checked + .style {
transform: translate(-50%, -50%) scale(.5);
}
.menu input[type=checkbox] + label:before {
content: "";
position: absolute;
}
.toggle:checked + .style:before, .toggle:checked + .style:after {
transform: rotate(135deg);
}
.toggle ~ .tab {
position: absolute;
background: #008DFF;
color: #fff;
width: 120px;
height: 120px;
left: 0px;
top: 0px;
transform: translate(-50%, -50%) scale(0);
transition: all 0.3s;
opacity: 0;
border-radius: 50%;
}
.toggle:checked ~ .tab {
opacity: 1;
transform: translate(-50%, -50%) scale(1);
}
.menu > .toggle:checked ~ .tab:nth-of-type(1) {
top: -130px;
left: 0px;
transition-delay: 0s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(2) {
top: -70px;
left: 120px;
transition-delay: 0.125s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(3) {
top: 70px;
left: 130px;
transition-delay: 0.25s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(4) {
top: 150px;
left: 0px;
transition-delay: 0.375s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(5) {
top: 80px;
left: -120px;
transition-delay: 0.5s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(6) {
top: -50px;
left: -120px;
transition-delay: 0.625s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(7) {
top: 0px;
left: -133.33333px;
transition-delay: 0.75s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(8) {
top: -94.2809px;
left: -94.2809px;
transition-delay: 0.875s;
}
#nickname{
float:right;
margin-right: 1vw;
color: black;
font-size: 3vh;
}
#conn_status{
margin-top:3vh;
margin-left: 220px;
height: 50px;
width: 50px;
float: left;
}
#gems{
margin-top:3vh;
font-size: 4vh;
float: left;
margin-left: 1vw;
}
#gem-icon{
margin-top:3vh;
float: left;
height: 80px;
width: 80px;
}
hr{
margin-top:5vh;
}
#nickname{
float: right;
}
}
@media (min-width: 1281px) {/*Desktops*/
.container{
margin-top: 50px;
}
#avatar{
float: right;
height:200px;
width:300px;
border-radius: 50%;
}
.menu {
position: relative;
margin-top: 200px;
left: 50%;
width: 0px;
transform: translate(-50%, 55%);
}
.toggle + .style {
width: 700px;
height: 200px;
border-radius: 50%;
cursor: pointer;
transform: translate(-50%, -50%) scale(1);
z-index: 5;
display: block;
max-width: 100px;
margin-bottom: 0;
background: #008DFF;
color: #fff;
font-size: 2.5em;
padding-top: 75px;
text-align: center;
-webkit-transition: all .8s;
-moz-transition: all .8s;
-o-transition: all .8s;
-ms-transition: all .8s;
transition: all .8s;
}
.menu p{
max-width: 20vw;
text-align: center;
margin: 0 auto;
line-height: 25px;
padding-top: 30px;
font-weight: 500;
font-size: 1.5em;
}
.toggle:checked + .style {
transform: translate(-50%, -50%) scale(.5);
}
.menu input[type=checkbox] + label:before {
content: "";
position: absolute;
}
.toggle + .style:after {
content: "";
position: absolute;
margin: -3px;
border-radius:5px;
transition: all 0.3s;
}
.toggle + .style:after {
width: 100px;
height: 30px;
left: 25px;
top: 10px;
}
.toggle ~ .tab {
position: absolute;
background: #008DFF;
color: #fff;
width: 150px;
height: 150px;
left: 0px;
top: 0px;
transform: translate(-50%, -50%) scale(0);
transition: all 0.3s;
opacity: 0;
border-radius: 50%;
}
.toggle:checked ~ .tab {
opacity: 1;
transform: translate(-50%, -50%) scale(1);
}
.menu > .toggle:checked ~ .tab:nth-of-type(1) {
top: -180px;
left: 0px;
transition-delay: 0s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(2) {
top: -90px;
left: 150px;
transition-delay: 0.125s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(3) {
top: 80px;
left: 160px;
transition-delay: 0.25s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(4) {
top: 200px;
left: 0px;
transition-delay: 0.375s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(5) {
top: 100px;
left: -150px;
transition-delay: 0.5s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(6) {
top: -80px;
left: -150px;
transition-delay: 0.625s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(7) {
top: 0px;
left: -133.33333px;
transition-delay: 0.75s;
}
.menu > .toggle:checked ~ .tab:nth-of-type(8) {
top: -94.2809px;
left: -94.2809px;
transition-delay: 0.875s;
}
#conn_status{
margin-top:3vh;
margin-left: 34vw;
height: 10vh;
width: 7vw;
float: left;
}
#gems{
margin-top:5vh;
font-size: 4vh;
float: left;
margin-left: 1vw;
}
#gem-icon{
margin-top:3vh;
float: left;
height: 10vh;
width: 7vw;
}
hr{
margin-top:10vh;
}
#nickname{
margin-top: 10vh
}
}
#game{
background-image: url("assets/static/icons/bazi.png");
background-size: 100% 100%;
}
#history{
background-image: url("assets/static/icons/eftekharat.png");
background-size: 100% 100%;
}
#about{
background-image: url("assets/static/icons/info.ico");
background-size: 100% 100%;
}
#news{
background-image: url("assets/static/icons/notif.png");
background-size: 100% 100%;
}
#store{
background-image: url("assets/static/icons/forushgah.png");
background-size: 100% 100%;
}
#cup{
background-image: url("assets/static/icons/jam.png");
background-size: 100% 100%;
}
#best_avatar{
float: left;
display: inline;
width: 18vw;
height: 12vh;
}
#best_info{
font-size: 1.3em;
}
</style>
<ion-content padding >
<div id ="status">
<img id=avatar src='' (click)="myHistory()"><img id='gem-icon' src='assets/static/gem.png' (click)="Store()"><span id='gems'>{{score}}</span><p align=right id=nickname>{{nickname}}</p>
</div>
<hr>
<button ion-button (click)="new_HOME()">new ui</button>>
<div class="container">
<div class='menu'>
<input id='toggle' class='toggle' type='checkbox' checked >
<label id='style' class='style' for='menu' (click)="Avatar()">
<i class="fa fa-bars" aria-hidden="true"></i>
</label>
<a id="game" class='tab' (click)="Game()" >
<p></p>
</a>
<a id="history" class='tab' (click)="myHistory()">
<p></p>
</a>
<a id="about" class='tab' (click)="AboutUs()">
<p> </p>
</a>
<a id="news" class='tab' (click)="News()">
<p></p>
</a>
<a id="store" class='tab' (click)="Store()">
<P></P>
</a>
<a id="cup" class='tab' (click)="Cups()">
<P></P>
</a>
</div>
</div>
<br><br>
<br>
<br>
<br>
<div>
<ion-card>
<ion-card-header>
<img id="best_avatar" src="{{best_player_avatar}}">
<p id="best_info">{{best_player_name}}: {{best_player_gems}}</p>
</ion-card-header>
<ion-card-content>
</ion-card-content>
</ion-card>
</div>
</ion-content>
| Java |
# piconf
##Before we begin:
* This is my first project using Git & GitHub
* My first complex C project
* First attempt at a autotools project
* My Main languages are Java, JScript, Python & BASIC
* It will contain stupid / beginners mistakes & bad smelling
* The proof on concept was written in python but C has been choosen for the rewrite for preformance perticularly startup times
##Graphical Raspberry Pi settings
###What about raspi-config?
raspi-config is a text based script that isnt all to user friendly, pi-conf uses a Gtk3 UI but it is / will be used as the backend for many features
###Hang on isnt that rc_gui?
No. rc_gui is a dialog for accessing raspi-config featues but still isnt great in its friendless and only has limited funtionality leaving you needing other utilities such a pipanel with yet another incosistant UI
###So what is it?
pi-conf aims to replace the likes of:
* ru_gui
* pipanel
* alacarte
with one consistant easy to use extendable application.
####What do you mean extendable
as in Window Control Panel where that new hardware you added conviniently adds its little icon so anyone can add a page for the app or addon for the pi
giving you on centeral configuration platform.
###How can i use it?
piconf is in the early stages but to give it a go grab a copy of this repo open a termnal in the projects roor and enter `autoreconf && ./configure && make all && sudo make install && pi-conf` although you may have to install `libgtk-3-dev` first.
| Java |
using System;
using System.Linq;
using LeagueSharp;
using LeagueSharp.Common;
using Slutty_ryze.Properties;
namespace Slutty_ryze
{
internal class Program
{
readonly static Random Seeder = new Random();
private static bool _casted;
private static int _lastw;
#region onload
private static void Main(string[] args)
{
if (args == null) throw new ArgumentNullException("args");
// So you can test if it in VS wihout crahses
#if !DEBUG
CustomEvents.Game.OnGameLoad += OnLoad;
#endif
}
private static void OnLoad(EventArgs args)
{
if (GlobalManager.GetHero.ChampionName != Champion.ChampName)
return;
Console.WriteLine(@"Loading Your Slutty Ryze");
Humanizer.AddAction("generalDelay",35.0f);
Champion.Q = new Spell(SpellSlot.Q, 865);
Champion.Qn = new Spell(SpellSlot.Q, 865);
Champion.W = new Spell(SpellSlot.W, 585);
Champion.E = new Spell(SpellSlot.E, 585);
Champion.R = new Spell(SpellSlot.R);
Champion.Q.SetSkillshot(0.26f, 50f, 1700f, true, SkillshotType.SkillshotLine);
Champion.Qn.SetSkillshot(0.26f, 50f, 1700f, false, SkillshotType.SkillshotLine);
//assign menu from MenuManager to Config
Console.WriteLine(@"Loading Your Slutty Menu...");
GlobalManager.Config = MenuManager.GetMenu();
GlobalManager.Config.AddToMainMenu();
Printmsg("Ryze Assembly Loaded");
Printmsg1("Current Version: " + typeof(Program).Assembly.GetName().Version);
Printmsg2("Don't Forget To " + "<font color='#00ff00'>[Upvote]</font> <font color='#FFFFFF'>" + "The Assembly In The Databse" + "</font>");
//Other damge inficators in MenuManager ????
GlobalManager.DamageToUnit = Champion.GetComboDamage;
Drawing.OnDraw += DrawManager.Drawing_OnDraw;
Game.OnUpdate += Game_OnUpdate;
#pragma warning disable 618
Interrupter.OnPossibleToInterrupt += Champion.RyzeInterruptableSpell;
Spellbook.OnCastSpell += Champion.OnProcess;
#pragma warning restore 618
Orbwalking.BeforeAttack += Champion.Orbwalking_BeforeAttack;
//CustomEvents.Unit.OnDash += Champion;
ShowDisplayMessage();
}
#endregion
private static void Printmsg(string message)
{
Game.PrintChat(
"<font color='#6f00ff'>[Slutty Ryze]:</font> <font color='#FFFFFF'>" + message + "</font>");
}
private static void Printmsg1(string message)
{
Game.PrintChat(
"<font color='#ff00ff'>[Slutty Ryze]:</font> <font color='#FFFFFF'>" + message + "</font>");
}
private static void Printmsg2(string message)
{
Game.PrintChat(
"<font color='#00abff'>[Slutty Ryze]:</font> <font color='#FFFFFF'>" + message + "</font>");
}
#region onGameUpdate
private static void ShowDisplayMessage()
{
var r = new Random();
var txt = Resources.display.Split('\n');
switch (r.Next(1, 3))
{
case 2:
txt = Resources.display2.Split('\n');
break;
case 3:
txt = Resources.display3.Split('\n');
break;
}
foreach (var s in txt)
Console.WriteLine(s);
#region L# does not allow D:
//try
//{
// var sr = new System.IO.StreamReader(System.Net.WebRequest.Create(string.Format("http://www.fiikus.net/asciiart/pokemon/{0}{1}{2}.txt", r.Next(0, 1), r.Next(0, 3), r.Next(0, 9))).GetResponse().GetResponseStream());
// string line;
// while ((line = sr.ReadLine()) != null)
// {
// Console.WriteLine(line);
// }
//}
//catch
//{
// // ignored
//}
#endregion
}
private static void Game_OnUpdate(EventArgs args)
{
try // lazy
{
if (GlobalManager.Config.Item("test").GetValue<KeyBind>().Active)
{
GlobalManager.GetHero.IssueOrder(GameObjectOrder.MoveTo, Game.CursorPos);
var targets = TargetSelector.GetTarget(Champion.W.Range, TargetSelector.DamageType.Magical);
if (targets == null)
return;
if (Champion.W.IsReady())
{
LaneOptions.CastW(targets);
{
_lastw = Environment.TickCount;
}
}
if (Environment.TickCount - _lastw >= 700 - Game.Ping)
{
if (Champion.Q.IsReady())
{
LaneOptions.CastQn(targets);
_casted = true;
}
}
if (_casted)
{
LaneOptions.CastE(targets);
LaneOptions.CastQn(targets);
_casted = false;
}
}
if (GlobalManager.Config.Item("chase").GetValue<KeyBind>().Active)
{
GlobalManager.GetHero.IssueOrder(GameObjectOrder.MoveTo, Game.CursorPos);
var targets = TargetSelector.GetTarget(Champion.W.Range + 200, TargetSelector.DamageType.Magical);
if (targets == null)
return;
if (GlobalManager.Config.Item("usewchase").GetValue<bool>())
LaneOptions.CastW(targets);
if (GlobalManager.Config.Item("chaser").GetValue<bool>() &&
targets.Distance(GlobalManager.GetHero) > Champion.W.Range + 200)
Champion.R.Cast();
}
if (GlobalManager.GetHero.IsDead)
return;
if (GlobalManager.GetHero.IsRecalling())
return;
if (Champion.casted == false)
{
MenuManager.Orbwalker.SetAttack(true);
}
var target = TargetSelector.GetTarget(Champion.Q.Range, TargetSelector.DamageType.Magical);
if (GlobalManager.Config.Item("doHuman").GetValue<bool>())
{
if (!Humanizer.CheckDelay("generalDelay")) // Wait for delay for all other events
{
Console.WriteLine(@"Waiting on Human delay");
return;
}
//Console.WriteLine("Seeding Human Delay");
var nDelay = Seeder.Next(GlobalManager.Config.Item("minDelay").GetValue<Slider>().Value, GlobalManager.Config.Item("maxDelay").GetValue<Slider>().Value); // set a new random delay :D
Humanizer.ChangeDelay("generalDelay", nDelay);
}
if (MenuManager.Orbwalker.ActiveMode == Orbwalking.OrbwalkingMode.Combo)
{
//
// if (target.IsValidTarget()
// && GlobalManager.GetHero.Distance(target) > 400 && (Champion.Q.IsReady() && Champion.W.IsReady() && Champion.E.IsReady()))
// {
// MenuManager.Orbwalker.SetAttack(false);
// }
//
// if (target.IsValidTarget() && GlobalManager.GetHero.Distance(target) > 400
// && (GlobalManager.GetPassiveBuff == 4 || GlobalManager.GetHero.HasBuff("ryzepassivecharged"))
// &&
// ((!Champion.Q.IsReady() && !Champion.W.IsReady() && !Champion.E.IsReady()) ||
// (Champion.Q.IsReady() && Champion.W.IsReady() && Champion.E.IsReady())))
// {
// MenuManager.Orbwalker.SetAttack(false);
// }
Champion.AABlock();
LaneOptions.ImprovedCombo();
if (target.Distance(GlobalManager.GetHero) >=
GlobalManager.Config.Item("minaarange").GetValue<Slider>().Value)
{
MenuManager.Orbwalker.SetAttack(false);
}
else
{
MenuManager.Orbwalker.SetAttack(true);
}
}
if (MenuManager.Orbwalker.ActiveMode == Orbwalking.OrbwalkingMode.Mixed)
{
LaneOptions.Mixed();
MenuManager.Orbwalker.SetAttack(true);
}
if (MenuManager.Orbwalker.ActiveMode == Orbwalking.OrbwalkingMode.LaneClear)
{
if (!GlobalManager.Config.Item("disablelane").GetValue<KeyBind>().Active)
LaneOptions.LaneClear();
LaneOptions.JungleClear();
}
if (MenuManager.Orbwalker.ActiveMode == Orbwalking.OrbwalkingMode.LastHit)
LaneOptions.LastHit();
if (MenuManager.Orbwalker.ActiveMode == Orbwalking.OrbwalkingMode.None)
{
if (GlobalManager.Config.Item("tearS").GetValue<KeyBind>().Active)
ItemManager.TearStack();
if (GlobalManager.Config.Item("autoPassive").GetValue<KeyBind>().Active)
Champion.AutoPassive();
ItemManager.Potion();
MenuManager.Orbwalker.SetAttack(true);
}
if (GlobalManager.Config.Item("UseQauto").GetValue<bool>() && target != null)
{
if (Champion.Q.IsReady() && target.IsValidTarget(Champion.Q.Range))
Champion.Q.Cast(target);
}
// Seplane();
ItemManager.Item();
Champion.KillSteal();
ItemManager.Potion();
if (GlobalManager.Config.Item("level").GetValue<bool>())
{
AutoLevelManager.LevelUpSpells();
}
if (!GlobalManager.Config.Item("autow").GetValue<bool>() || !target.UnderTurret(true)) return;
if (target == null)
return;
if (!ObjectManager.Get<Obj_AI_Turret>()
.Any(turret => turret.IsValidTarget(300) && turret.IsAlly && turret.Health > 0))
return;
Champion.W.CastOnUnit(target);
// DebugClass.ShowDebugInfo(true);
}
catch
{
// ignored
}
}
#endregion
/*
private static void Seplane()
{
if (GlobalManager.GetHero.IsValid &&
GlobalManager.Config.Item("seplane").GetValue<KeyBind>().Active)
{
ObjectManager.GlobalManager.GetHero.IssueOrder(GameObjectOrder.MoveTo, Game.CursorPos);
LaneClear();
}
}
*/
}
}
| Java |
@import "../startbootstrap-agency/css/agency.min.css";
.text-primary {
color: #ff7058;
}
a {
color: #ff7058;
}
a:hover,
a:focus,
a:active,
a.active {
color: #324a5e;
}
.btn-primary {
background-color: #ff7058;
border-color: #ff7058;
}
.btn-primary:hover,
.btn-primary:focus,
.btn-primary:active,
.btn-primary.active,
.open .dropdown-toggle.btn-primary {
background-color: #324a5e;
border-color: #324a5e;
}
.btn-primary.disabled,
.btn-primary[disabled],
fieldset[disabled] .btn-primary,
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled:active,
.btn-primary[disabled]:active,
fieldset[disabled] .btn-primary:active,
.btn-primary.disabled.active,
.btn-primary[disabled].active,
fieldset[disabled] .btn-primary.active {
background-color: #ff7058;
border-color: #ff7058;
}
.btn-primary .badge {
color: #ff7058;
}
.btn-xl {
background-color: #ff7058;
border-color: #ff7058;
}
.btn-xl:hover,
.btn-xl:focus,
.btn-xl:active,
.btn-xl.active,
.open .dropdown-toggle.btn-xl {
background-color: #324a5e;
border-color: #324a5e;
}
.btn-xl.disabled,
.btn-xl[disabled],
fieldset[disabled] .btn-xl,
.btn-xl.disabled:hover,
.btn-xl[disabled]:hover,
fieldset[disabled] .btn-xl:hover,
.btn-xl.disabled:focus,
.btn-xl[disabled]:focus,
fieldset[disabled] .btn-xl:focus,
.btn-xl.disabled:active,
.btn-xl[disabled]:active,
fieldset[disabled] .btn-xl:active,
.btn-xl.disabled.active,
.btn-xl[disabled].active,
fieldset[disabled] .btn-xl.active {
background-color: #ff7058;
border-color: #ff7058;
}
.btn-xl .badge {
color: #ff7058;
}
.navbar-custom .navbar-brand {
color: #ff7058;
}
.navbar-custom .navbar-brand:hover,
.navbar-custom .navbar-brand:focus,
.navbar-custom .navbar-brand:active,
.navbar-custom .navbar-brand.active {
color: #324a5e;
}
.navbar-custom .navbar-toggle {
background-color: #ff7058;
border-color: #ff7058;
}
.navbar-custom .navbar-toggle:hover,
.navbar-custom .navbar-toggle:focus {
background-color: #ff7058;
}
.navbar-custom .nav li a:hover,
.navbar-custom .nav li a:focus {
color: #ff7058;
}
.navbar-custom .navbar-nav > .active > a {
background-color: #ff7058;
}
.navbar-custom .navbar-nav > .active > a:hover,
.navbar-custom .navbar-nav > .active > a:focus {
background-color: #324a5e;
}
header {
background-color: #cccbc9;
background-image: url('../img/header-bg.jpg');
}
.timeline > li .timeline-image {
background-color: #ff7058;
}
section#contact .form-control:focus {
border-color: #ff7058;
}
ul.social-buttons li a:hover,
ul.social-buttons li a:focus,
ul.social-buttons li a:active {
background-color: #ff7058;
}
::-moz-selection {
background: #ff7058;
}
::selection {
background: #ff7058;
}
body {
webkit-tap-highlight-color: #ff7058;
}
| Java |
/* Copyright (C) 2011 CZ.NIC, z.s.p.o. <knot-dns@labs.nic.cz>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*!
* \file journal.h
*
* \author Marek Vavrusa <marek.vavrusa@nic.cz>
*
* \brief Journal for storing transactions on permanent storage.
*
* Journal stores entries on a permanent storage.
* Each written entry is guaranteed to persist until
* the maximum file size or node count is reached.
* Entries are removed from the least recent.
*
* Journal file structure
* <pre>
* uint16_t node_count
* uint16_t node_queue_head
* uint16_t node_queue_tail
* journal_entry_t free_segment
* node_count *journal_entry_t
* ...data...
* </pre>
* \addtogroup utils
* @{
*/
#ifndef _KNOTD_JOURNAL_H_
#define _KNOTD_JOURNAL_H_
#include <stdint.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdbool.h>
/*!
* \brief Journal entry flags.
*/
typedef enum journal_flag_t {
JOURNAL_NULL = 0 << 0, /*!< Invalid journal entry. */
JOURNAL_FREE = 1 << 0, /*!< Free journal entry. */
JOURNAL_VALID = 1 << 1, /*!< Valid journal entry. */
JOURNAL_DIRTY = 1 << 2, /*!< Journal entry cannot be evicted. */
JOURNAL_TRANS = 1 << 3 /*!< Entry is in transaction (uncommited). */
} journal_flag_t;
/*!
* \brief Journal node structure.
*
* Each node represents journal entry and points
* to position of the data in the permanent storage.
*/
typedef struct journal_node_t
{
uint64_t id; /*!< Node ID. */
uint16_t flags; /*!< Node flags. */
uint16_t next; /*!< Next node ptr. */
uint32_t pos; /*!< Position in journal file. */
uint32_t len; /*!< Entry data length. */
} journal_node_t;
/*!
* \brief Journal structure.
*
* Journal organizes entries as nodes.
* Nodes are stored in-memory for fast lookup and also
* backed by a permanent storage.
* Each journal has a fixed number of nodes.
*
* \todo Organize nodes in an advanced structure, like
* btree or hash table to improve lookup time (issue #964).
*/
typedef struct journal_t
{
int fd;
struct flock fl; /*!< File lock. */
pthread_mutex_t mutex; /*!< Synchronization mutex. */
char *path; /*!< Path to journal file. */
uint16_t tmark; /*!< Transaction start mark. */
uint16_t max_nodes; /*!< Number of nodes. */
uint16_t qhead; /*!< Node queue head. */
uint16_t qtail; /*!< Node queue tail. */
uint16_t bflags; /*!< Initial flags for each written node. */
size_t fsize; /*!< Journal file size. */
size_t fslimit; /*!< File size limit. */
journal_node_t free; /*!< Free segment. */
journal_node_t *nodes; /*!< Array of nodes. */
} journal_t;
/*!
* \brief Entry identifier compare function.
*
* \retval -n if k1 < k2
* \retval +n if k1 > k2
* \retval 0 if k1 == k2
*/
typedef int (*journal_cmp_t)(uint64_t k1, uint64_t k2);
/*!
* \brief Function prototype for journal_walk() function.
*
* \param j Associated journal.
* \param n Pointer to target node.
*/
typedef int (*journal_apply_t)(journal_t *j, journal_node_t *n);
/*
* Journal defaults and constants.
*/
#define JOURNAL_NCOUNT 1024 /*!< Default node count. */
#define JOURNAL_MAGIC {'k', 'n', 'o', 't', '1', '5', '0'}
#define MAGIC_LENGTH 7
/* HEADER = magic, crc, max_entries, qhead, qtail */
#define JOURNAL_HSIZE (MAGIC_LENGTH + sizeof(crc_t) + sizeof(uint16_t) * 3)
/*!
* \brief Create new journal.
*
* \param fn Journal file name, will be created if not exist.
* \param max_nodes Maximum number of nodes in journal.
*
* \retval KNOT_EOK if successful.
* \retval KNOT_EINVAL if the file with given name cannot be created.
* \retval KNOT_ERROR on I/O error.
*/
int journal_create(const char *fn, uint16_t max_nodes);
/*!
* \brief Open journal.
*
* \warning This doesn't open the file yet, just sets up the structure.
* Call \fn journal_retain before reading/writing the journal.
*
* \param fn Journal file name.
* \param fslimit File size limit (0 for no limit).
* \param bflags Initial flags for each written node.
*
* \retval new journal instance if successful.
* \retval NULL on error.
*/
journal_t* journal_open(const char *fn, size_t fslimit, uint16_t bflags);
/*!
* \brief Fetch entry node for given identifier.
*
* \param journal Associated journal.
* \param id Entry identifier.
* \param cf Compare function (NULL for equality).
* \param dst Destination for journal entry.
*
* \retval KNOT_EOK if successful.
* \retval KNOT_ENOENT if not found.
*/
int journal_fetch(journal_t *journal, uint64_t id,
journal_cmp_t cf, journal_node_t** dst);
/*!
* \brief Read journal entry data.
*
* \param journal Associated journal.
* \param id Entry identifier.
* \param cf Compare function (NULL for equality).
* \param dst Pointer to destination memory.
*
* \retval KNOT_EOK if successful.
* \retval KNOT_ENOENT if the entry cannot be found.
* \retval KNOT_EINVAL if the entry is invalid.
* \retval KNOT_ERROR on I/O error.
*/
int journal_read(journal_t *journal, uint64_t id, journal_cmp_t cf, char *dst);
/*!
* \brief Read journal entry data.
*
* \param journal Associated journal.
* \param n Entry.
* \param dst Pointer to destination memory.
*
* \retval KNOT_EOK if successful.
* \retval KNOT_ENOENT if the entry cannot be found.
* \retval KNOT_EINVAL if the entry is invalid.
* \retval KNOT_ERROR on I/O error.
*/
int journal_read_node(journal_t *journal, journal_node_t *n, char *dst);
/*!
* \brief Write journal entry data.
*
* \param journal Associated journal.
* \param id Entry identifier.
* \param src Pointer to source data.
*
* \retval KNOT_EOK if successful.
* \retval KNOT_EAGAIN if no free node is available, need to remove dirty nodes.
* \retval KNOT_ERROR on I/O error.
*/
int journal_write(journal_t *journal, uint64_t id, const char *src, size_t size);
/*!
* \brief Map journal entry for read/write.
*
* \warning New nodes shouldn't be created until the entry is unmapped.
*
* \param journal Associated journal.
* \param id Entry identifier.
* \param dst Will contain mapped memory.
*
* \retval KNOT_EOK if successful.
* \retval KNOT_EAGAIN if no free node is available, need to remove dirty nodes.
* \retval KNOT_ERROR on I/O error.
*/
int journal_map(journal_t *journal, uint64_t id, char **dst, size_t size);
/*!
* \brief Finalize mapped journal entry.
*
* \param journal Associated journal.
* \param id Entry identifier.
* \param ptr Mapped memory.
* \param finalize Set to true to finalize node or False to discard it.
*
* \retval KNOT_EOK if successful.
* \retval KNOT_ENOENT if the entry cannot be found.
* \retval KNOT_EAGAIN if no free node is available, need to remove dirty nodes.
* \retval KNOT_ERROR on I/O error.
*/
int journal_unmap(journal_t *journal, uint64_t id, void *ptr, int finalize);
/*!
* \brief Return least recent node (journal head).
*
* \param journal Associated journal.
*
* \retval node if successful.
* \retval NULL if empty.
*/
static inline journal_node_t *journal_head(journal_t *journal) {
return journal->nodes + journal->qhead;
}
/*!
* \brief Return node after most recent node (journal tail).
*
* \param journal Associated journal.
*
* \retval node if successful.
* \retval NULL if empty.
*/
static inline journal_node_t *journal_end(journal_t *journal) {
return journal->nodes + journal->qtail;
}
/*!
* \brief Apply function to each node.
*
* \param journal Associated journal.
* \param apply Function to apply to each node.
*
* \retval KNOT_EOK if successful.
* \retval KNOT_EINVAL on invalid parameters.
*/
int journal_walk(journal_t *journal, journal_apply_t apply);
/*!
* \brief Sync node state to permanent storage.
*
* \note May be used for journal_walk().
*
* \param journal Associated journal.
* \param n Pointer to node (must belong to associated journal).
*
* \retval KNOT_EOK on success.
* \retval KNOT_EINVAL on invalid parameters.
*/
int journal_update(journal_t *journal, journal_node_t *n);
/*!
* \brief Begin transaction of multiple entries.
*
* \note Only one transaction at a time is supported.
*
* \param journal Associated journal.
*
* \retval KNOT_EOK on success.
* \retval KNOT_EINVAL on invalid parameters.
* \retval KNOT_EBUSY if transaction is already pending.
*/
int journal_trans_begin(journal_t *journal);
/*!
* \brief Commit pending transaction.
*
* \note Only one transaction at a time is supported.
*
* \param journal Associated journal.
*
* \retval KNOT_EOK on success.
* \retval KNOT_EINVAL on invalid parameters.
* \retval KNOT_ENOENT if no transaction is pending.
*/
int journal_trans_commit(journal_t *journal);
/*!
* \brief Rollback pending transaction.
*
* \note Only one transaction at a time is supported.
*
* \param journal Associated journal.
*
* \retval KNOT_EOK on success.
* \retval KNOT_EINVAL on invalid parameters.
* \retval KNOT_ENOENT if no transaction is pending.
*/
int journal_trans_rollback(journal_t *journal);
/*!
* \brief Close journal file.
*
* \param journal Associated journal.
*
* \retval KNOT_EOK on success.
* \retval KNOT_EINVAL on invalid parameter.
*/
int journal_close(journal_t *journal);
/*!
* \brief Check if the journal file is used or not.
*
* \param journal Journal.
*
* \return true or false
*/
bool journal_is_used(journal_t *journal);
/*!
* \brief Retain journal for use.
*
* \param journal Journal.
*
* \retval KNOT_EOK
* \retval KNOT_EBUSY
* \retval KNOT_EINVAL
* \retval KNOT_ERROR
*/
int journal_retain(journal_t *journal);
/*!
* \brief Release retained journal.
*
* \param journal Retained journal.
*/
void journal_release(journal_t *journal);
/*!
* \brief Recompute journal CRC.
*
* \warning Use only if you altered the journal file somehow
* and need it to pass CRC checks. CRC check normally
* checks file integrity, so you should not touch it unless
* you know what you're doing.
*
* \param fd Open journal file.
*
* \retval KNOT_EOK on success.
* \retval KNOT_EINVAL if not valid fd.
*/
int journal_update_crc(int fd);
#endif /* _KNOTD_JOURNAL_H_ */
/*! @} */
| Java |
#ifndef TNUICOLORSTREAMEFFECT_H
#define TNUICOLORSTREAMEFFECT_H
#include <QObject>
class TNuiColorStream;
class TNuiColorStreamEffect : public QObject
{
Q_OBJECT
public:
TNuiColorStreamEffect(TNuiColorStream *stream);
void setEnabled(bool enabled);
bool isEnabled() const { return m_enabled; }
void draw(uchar *data, uint length);
signals:
void enabledChanged(bool enabled);
protected:
virtual void updateFrameData(uchar *data, uint length) = 0;
TNuiColorStream *m_colorStream;
bool m_enabled;
};
#endif // TNUICOLORSTREAMEFFECT_H
| Java |
#include "../lib/includes.h"
#include "../lib/utils.h"
#include "../lib/methnum.h"
#include "../Enum_type.h"
#include "../Var/var.h"
#include "../T0/t0.h"
#include "upot.h"
void test_der ( Upot * U , U_type upot_t , T0_type t0_t, bool phi_eq_phibar );
#define TD_T(f,df,nf,str) do{ testderiv(f,df,Tmin ,Tmax ,N,0.001,nf,str); } while(0)
#define TD_phi(f,df,nf,str) do{ testderiv(f,df,phimin,phimax,N,0.001,nf,str); } while(0)
#define TD_mu(f,df,nf,str) do{ testderiv(f,df,mumin ,mumax ,N,0.001,nf,str); } while(0)
#define TOTO(i) do{ printf("toto %d\n", i); } while(0)
int main ( void )
{
bool all_test = false ;
printf ("testing Gluonic potential derivatives \n" );
bool phi_eq_phibar = true ;
Upot * U = Upot_alloc_32 ( U_POW, T0_CST, C_ANA, 0.650, phi_eq_phibar );
test_der ( U , U_POW , T0_T2, true );
if ( false ){
test_der ( U , U_POW , T0_CST, phi_eq_phibar );
test_der ( U , U_POW , T0_T1, phi_eq_phibar );
test_der ( U , U_POW , T0_T2, phi_eq_phibar );
}
if ( false )
{
test_der ( U , U_POW , T0_T2, phi_eq_phibar );
test_der ( U , U_LOG , T0_T2, phi_eq_phibar );
test_der ( U , U_FUK , T0_T2, phi_eq_phibar );
test_der ( U , U_DEX , T0_T2, phi_eq_phibar );
}
if ( all_test )
{
test_der ( U , U_POW , T0_CST, phi_eq_phibar );
test_der ( U , U_POW , T0_T1, phi_eq_phibar );
test_der ( U , U_POW , T0_T2, phi_eq_phibar );
test_der ( U , U_LOG , T0_CST, phi_eq_phibar );
test_der ( U , U_LOG , T0_T1, phi_eq_phibar );
test_der ( U , U_LOG , T0_T2, phi_eq_phibar );
test_der ( U , U_FUK , T0_CST, phi_eq_phibar );
test_der ( U , U_DEX , T0_CST, phi_eq_phibar );
test_der ( U , U_DEX , T0_T1, phi_eq_phibar );
test_der ( U , U_DEX , T0_T2, phi_eq_phibar );
}
Upot_free ( U );
return 0 ;
}
void test_der ( Upot * U , U_type upot_t , T0_type t0_t, bool phi_eq_phibar )
{
// Upot_set_type ( U , upot_t, t0_t, ANA );
double T_ = 0.1 , phi_ = 0.5 , phibar_= 0.7, mu_= 0.1 ;
double Tmin= 0.1, Tmax=0.5, mumin=0., mumax=0.2, phimin=0.01,phimax=0.1 ;
int N = 40 ;
char pref[128], nf[256] ;
Var * V = Var_alloc ( );
if ( upot_t == U_POW )
{
Upot_set_pow_std ( U , t0_t, phi_eq_phibar);
if ( phi_eq_phibar )
{
if ( t0_t == T0_CST ) sprintf (pref ,"%s" ,"Upow_T0_cst_phi_eq_phibar" );
else if ( t0_t == T0_T1 ) sprintf (pref ,"%s" ,"Upow_T0_t1_phi_eq_phibar" );
else if ( t0_t == T0_T2 ) sprintf (pref ,"%s" ,"Upow_T0_t2_phi_eq_phibar" );
else { Var_free ( V ); Upot_free ( U ); ERROR ( stdout , "T0 type error"); }
}
else
{
if ( t0_t == T0_CST ) sprintf (pref ,"%s" ,"Upow_T0_cst" );
else if ( t0_t == T0_T1 ) sprintf (pref ,"%s" ,"Upow_T0_t1" );
else if ( t0_t == T0_T2 ) sprintf (pref ,"%s" ,"Upow_T0_t2" );
else { Var_free ( V ); Upot_free ( U ); ERROR ( stdout , "T0 type error"); }
}
}
else if ( upot_t == U_LOG )
{
Upot_set_log_std ( U , t0_t, phi_eq_phibar);
if ( phi_eq_phibar )
{
if ( t0_t == T0_CST ) sprintf (pref ,"%s" ,"Ulog_T0_cst_phi_eq_phibar" );
else if ( t0_t == T0_T1 ) sprintf (pref ,"%s" ,"Ulog_T0_t1_phi_eq_phibar" );
else if ( t0_t == T0_T2 ) sprintf (pref ,"%s" ,"Ulog_T0_t2_phi_eq_phibar" );
else { Var_free ( V ); Upot_free ( U ); ERROR ( stdout , "T0 type error");}
}
else
{
if ( t0_t == T0_CST ) sprintf (pref ,"%s" ,"Ulog_T0_cst" );
else if ( t0_t == T0_T1 ) sprintf (pref ,"%s" ,"Ulog_T0_t1" );
else if ( t0_t == T0_T2 ) sprintf (pref ,"%s" ,"Ulog_T0_t2" );
else { Var_free ( V ); Upot_free ( U ); ERROR ( stdout , "T0 type error");}
}
}
else if ( upot_t == U_FUK )
{
Upot_set_fuk_std ( U , t0_t, 0.650, phi_eq_phibar);
if ( phi_eq_phibar )
sprintf (pref ,"%s" ,"Ufuk_phi_eq_phibar" );
else
sprintf (pref ,"%s" ,"Ufuk" );
}
else if ( upot_t == U_DEX )
{
Upot_set_dex_std ( U , t0_t, phi_eq_phibar);
if ( phi_eq_phibar )
{
if ( t0_t == T0_CST ) sprintf (pref ,"%s" ,"Udex_T0_cst_phi_eq_phibar" );
else if ( t0_t == T0_T1 ) sprintf (pref ,"%s" ,"Udex_T0_t1_phi_eq_phibar" );
else if ( t0_t == T0_T2 ) sprintf (pref ,"%s" ,"Udex_T0_t2_phi_eq_phibar" );
else { Var_free ( V ); Upot_free ( U );ERROR ( stdout , "T0 type error"); }
}
else
{
if ( t0_t == T0_CST ) sprintf (pref ,"%s" ,"Udex_T0_cst" );
else if ( t0_t == T0_T1 ) sprintf (pref ,"%s" ,"Udex_T0_t1" );
else if ( t0_t == T0_T2 ) sprintf (pref ,"%s" ,"Udex_T0_t2" );
else { Var_free ( V ); Upot_free ( U );ERROR ( stdout , "T0 type error"); }
}
}
else
{
Var_free ( V ); Upot_free ( U );ERROR ( stdout , "U type error");
}
if ( !phi_eq_phibar )
{
//////////// GRAND POTENTIAL
////
double u_phi ( double phi ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi , phibar_); return U->Ug( U->P , U->T0, V ); }
double u_phibar ( double phibar ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi_, phibar ); return U->Ug( U->P , U->T0, V ); }
double u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->Ug( U->P , U->T0, V ); }
double u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->Ug( U->P , U->T0, V ); }
sprintf ( nf , "%s_phi" , pref ); plot_2D ( u_phi , phimin,phimax,N,nf,"set xla \"phi\"; set xzeroaxis" , false );
sprintf ( nf , "%s_phibar", pref ); plot_2D ( u_phibar, phimin,phimax,N,nf,"set xla \"phibar\"; set xzeroaxis", false );
sprintf ( nf , "%s_T" , pref ); plot_2D ( u_T , Tmin ,Tmax ,N,nf,"set xla \"T\"; set xzeroaxis" , false );
sprintf ( nf , "%s_mu" , pref ); plot_2D ( u_mu , mumin ,mumax ,N,nf,"set xla \"mu\"; set xzeroaxis" , false );
//////////// 1ST DERIVATIVES
////
double dphi_u_phi ( double phi ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi , phibar_); return U->dphi_Ug ( U->P , U->T0, V ); }
double dphibar_u_phibar ( double phibar ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi_, phibar ); return U->dphibar_Ug( U->P , U->T0, V ); }
double dT_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dT_Ug ( U->P , U->T0, V ); }
double dmu_u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmu_Ug ( U->P , U->T0, V ); }
sprintf ( nf , "dphi_%s_phi" , pref ); TD_phi(u_phi ,dphi_u_phi ,nf,"set xla\"phi\"");
sprintf ( nf , "dphibar_%s_phibar", pref ); TD_phi(u_phibar,dphibar_u_phibar,nf,"set xla\"phibar\"");
sprintf ( nf , "dT_%s_T" , pref ); TD_T (u_T ,dT_u_T ,nf,"set xla\"T\"");
sprintf ( nf , "dmu_%s_mu" , pref ); TD_mu (u_mu ,dmu_u_mu ,nf,"set xla\"mu\"");
//////////// 2ND DERIVATIVES
////
double dT2_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dT2_Ug ( U->P , U->T0, V ); }
double dTmu_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dTmu_Ug ( U->P , U->T0, V ); }
double dmu_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dmu_Ug ( U->P , U->T0, V ); }
double dTphi_u_T( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dTphi_Ug ( U->P , U->T0, V ); }
double dphi_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dphi_Ug ( U->P , U->T0, V ); }
double dTphibar_u_T( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dTphibar_Ug ( U->P , U->T0, V ); }
double dphibar_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dphibar_Ug ( U->P , U->T0, V ); }
double dmu2_u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmu2_Ug ( U->P , U->T0, V ); }
double dmuphi_u_mu ( double mu ){ Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmuphi_Ug ( U->P , U->T0, V ); }
double dphi_u_mu( double mu ){ Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dphi_Ug ( U->P , U->T0, V ); }
double dmuphibar_u_mu ( double mu ){ Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmuphibar_Ug ( U->P , U->T0, V ); }
double dphibar_u_mu( double mu ){ Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dphibar_Ug ( U->P , U->T0, V ); }
double dphi2_u_phi ( double phi ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi , phibar_); return U->dphi2_Ug ( U->P , U->T0, V ); }
double dphiphibar_u_phi ( double phi ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi , phibar_); return U->dphiphibar_Ug ( U->P , U->T0, V ); }
double dphibar_u_phi ( double phi ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi , phibar_); return U->dphibar_Ug ( U->P , U->T0, V ); }
double dphibar2_u_phibar ( double phibar ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi_, phibar ); return U->dphibar2_Ug( U->P , U->T0, V ); }
sprintf ( nf , "dT2_%s_T", pref ); TD_T(dT_u_T, dT2_u_T,nf , "set xla\"T\"");
sprintf ( nf , "dTmu_%s_T", pref ); TD_T(dmu_u_T, dTmu_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTphi_%s_T", pref ); TD_T(dphi_u_T, dTphi_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTphibar_%s_T", pref ); TD_T(dphibar_u_T, dTphibar_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dmu2_%s_mu", pref ); TD_mu (dmu_u_mu,dmu2_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmuphi_%s_mu", pref ); TD_mu (dphi_u_mu,dmuphi_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmuphibar_%s_mu", pref ); TD_mu (dphibar_u_mu,dmuphibar_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dphi2_%s_phi" , pref ); TD_phi(dphi_u_phi,dphi2_u_phi,nf,"set xla\"phi\"");
sprintf ( nf , "dphiphibar_%s_phi" , pref ); TD_phi(dphibar_u_phi,dphiphibar_u_phi,nf,"set xla\"phi\"");
sprintf ( nf , "dphibar2_%s_phibar", pref ); TD_phi(dphibar_u_phibar,dphibar2_u_phibar,nf,"set xla\"phibar\"");
//////////// 3RD DERIVATIVES
////
double dT3_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dT3_Ug ( U->P , U->T0, V ); }
double dT2mu_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dT2mu_Ug ( U->P , U->T0, V ); }
double dT2phi_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dT2phi_Ug ( U->P , U->T0, V ); }
double dT2phibar_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dT2phibar_Ug ( U->P , U->T0, V ); }
double dTmu2_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dTmu2_Ug ( U->P , U->T0, V ); }
double dmu2_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dmu2_Ug ( U->P , U->T0, V ); }
double dTmuphi_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dTmuphi_Ug ( U->P , U->T0, V ); }
double dmuphi_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dmuphi_Ug ( U->P , U->T0, V ); }
double dTmuphibar_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dTmuphibar_Ug ( U->P , U->T0, V ); }
double dmuphibar_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dmuphibar_Ug ( U->P , U->T0, V ); }
double dTphi2_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dTphi2_Ug ( U->P , U->T0, V ); }
double dphi2_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dphi2_Ug ( U->P , U->T0, V ); }
double dTphiphibar_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dTphiphibar_Ug ( U->P , U->T0, V ); }
double dphiphibar_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dphiphibar_Ug ( U->P , U->T0, V ); }
double dTphibar2_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dTphibar2_Ug ( U->P , U->T0, V ); }
double dphibar2_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dphibar2_Ug ( U->P , U->T0, V ); }
double dmu3_u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmu3_Ug ( U->P , U->T0, V ); }
double dmu2phi_u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmu2phi_Ug ( U->P , U->T0, V ); }
double dmu2phibar_u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmu2phibar_Ug ( U->P , U->T0, V ); }
double dmuphi2_u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmuphi2_Ug ( U->P , U->T0, V ); }
double dphi2_u_mu ( double mu ) {Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dphi2_Ug ( U->P , U->T0, V ); }
double dmuphiphibar_u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmuphiphibar_Ug ( U->P , U->T0, V ); }
double dphiphibar_u_mu ( double mu ) {Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dphiphibar_Ug ( U->P , U->T0, V ); }
double dmuphibar2_u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmuphibar2_Ug ( U->P , U->T0, V ); }
double dphibar2_u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dphibar2_Ug ( U->P , U->T0, V ); }
double dphi3_u_phi ( double phi ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi , phibar_); return U->dphi3_Ug ( U->P , U->T0, V ); }
double dphi2phibar_u_phi ( double phi ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi , phibar_); return U->dphi2phibar_Ug ( U->P , U->T0, V ); }
double dphiphibar2_u_phi ( double phi ) {Var_set_Tmuphiphibar ( V, T_, mu_, phi , phibar_); return U->dphiphibar2_Ug ( U->P , U->T0, V ); }
double dphibar2_u_phi ( double phi ){Var_set_Tmuphiphibar ( V, T_, mu_, phi , phibar_); return U->dphibar2_Ug ( U->P , U->T0, V ); }
double dphibar3_u_phibar ( double phibar ) { Var_set_Tmuphiphibar( V, T_, mu_, phi_, phibar ); return U->dphibar3_Ug( U->P , U->T0, V ); }
sprintf ( nf , "dT3_%s_T", pref ); TD_T(dT2_u_T, dT3_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dT2mu_%s_T", pref ); TD_T(dTmu_u_T, dT2mu_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dT2phi_%s_T", pref ); TD_T(dTphi_u_T, dT2phi_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dT2phibar_%s_T", pref ); TD_T(dTphibar_u_T, dT2phibar_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTmu2_%s_T", pref ); TD_T(dmu2_u_T, dTmu2_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTmuphi_%s_T", pref ); TD_T(dmuphi_u_T, dTmuphi_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTmuphibar_%s_T", pref ); TD_T(dmuphibar_u_T, dTmuphibar_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTphi2_%s_T", pref ); TD_T(dphi2_u_T, dTphi2_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTphiphibar_%s_T", pref ); TD_T(dphiphibar_u_T, dTphiphibar_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTphibar2_%s_T", pref ); TD_T(dphibar2_u_T, dTphibar2_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dmu3_%s_mu", pref ); TD_mu (dmu2_u_mu,dmu3_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmu2phi_%s_mu", pref ); TD_mu (dmuphi_u_mu,dmu2phi_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmu2phibar_%s_mu", pref ); TD_mu (dmuphibar_u_mu,dmu2phibar_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmuphi2_%s_mu", pref ); TD_mu (dphi2_u_mu,dmuphi2_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmuphiphibar_%s_mu", pref ); TD_mu (dphiphibar_u_mu,dmuphiphibar_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmuphibar2_%s_mu", pref ); TD_mu (dphibar2_u_mu,dmuphibar2_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dphi3_%s_phi", pref ); TD_phi(dphi2_u_phi,dphi3_u_phi,nf,"set xla\"phi\"");
sprintf ( nf , "dphiphibar_%s_phi", pref ); TD_phi(dphiphibar_u_phi,dphi2phibar_u_phi,nf,"set xla\"phi\"");
sprintf ( nf , "dphiphibar2_%s_phi", pref ); TD_phi(dphibar2_u_phi,dphiphibar2_u_phi,nf,"set xla\"phi\"");
sprintf ( nf , "dphibar3_%s_phibar", pref ); TD_phi(dphibar2_u_phibar,dphibar3_u_phibar,nf,"set xla\"phibar\"");
}
else // phi = phibar
{
//////////// GRAND POTENTIAL
////
double u_phi ( double phi ) { Var_set_Tmuphi ( V, T_, mu_, phi ); return U->Ug( U->P , U->T0, V ); }
double u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->Ug( U->P , U->T0, V ); }
double u_mu ( double mu ) { Var_set_Tmuphi ( V, T_, mu , phi_); return U->Ug( U->P , U->T0, V ); }
sprintf ( nf , "%s_phi" , pref ); plot_2D ( u_phi , phimin,phimax,N,nf,"set xla \"phi\"; set xzeroaxis" , false );
sprintf ( nf , "%s_T" , pref ); plot_2D ( u_T , Tmin ,Tmax ,N,nf,"set xla \"T\"; set xzeroaxis" , false );
sprintf ( nf , "%s_mu" , pref ); plot_2D ( u_mu , mumin ,mumax ,N,nf,"set xla \"mu\"; set xzeroaxis" , false );
//////////// 1ST DERIVATIVES
////
double dphi_u_phi ( double phi ) { Var_set_Tmuphi ( V, T_, mu_, phi ); return U->dphi_Ug ( U->P , U->T0, V ); }
double dT_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dT_Ug ( U->P , U->T0, V ); }
double dmu_u_mu ( double mu ) { Var_set_Tmuphi ( V, T_, mu , phi_); return U->dmu_Ug ( U->P , U->T0, V ); }
sprintf ( nf , "dphi_%s_phi" , pref ); TD_phi(u_phi ,dphi_u_phi ,nf,"set xla\"phi\"");
sprintf ( nf , "dT_%s_T" , pref ); TD_T (u_T ,dT_u_T ,nf,"set xla\"T\"");
sprintf ( nf , "dmu_%s_mu" , pref ); TD_mu (u_mu ,dmu_u_mu ,nf,"set xla\"mu\"");
//////////// 2ND DERIVATIVES
////
double dT2_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dT2_Ug ( U->P , U->T0, V ); }
double dTmu_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dTmu_Ug ( U->P , U->T0, V ); }
double dmu_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dmu_Ug ( U->P , U->T0, V ); }
double dTphi_u_T( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dTphi_Ug ( U->P , U->T0, V ); }
double dphi_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dphi_Ug ( U->P , U->T0, V ); }
double dmu2_u_mu ( double mu ) { Var_set_Tmuphi ( V, T_, mu , phi_); return U->dmu2_Ug ( U->P , U->T0, V ); }
double dmuphi_u_mu ( double mu ){ Var_set_Tmuphi ( V, T_, mu , phi_); return U->dmuphi_Ug ( U->P , U->T0, V ); }
double dphi_u_mu( double mu ){ Var_set_Tmuphi ( V, T_, mu , phi_); return U->dphi_Ug ( U->P , U->T0, V ); }
double dphi2_u_phi ( double phi ) { Var_set_Tmuphi ( V, T_, mu_, phi ); return U->dphi2_Ug ( U->P , U->T0, V ); }
//if ( false ) {
sprintf ( nf , "dT2_%s_T", pref ); TD_T(dT_u_T, dT2_u_T,nf , "set xla\"T\"");
sprintf ( nf , "dTmu_%s_T", pref ); TD_T(dmu_u_T, dTmu_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTphi_%s_T", pref ); TD_T(dphi_u_T, dTphi_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dmu2_%s_mu", pref ); TD_mu (dmu_u_mu,dmu2_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmuphi_%s_mu", pref ); TD_mu (dphi_u_mu,dmuphi_u_mu ,nf,"set xla\"mu\""); //}
sprintf ( nf , "dphi2_%s_phi" , pref ); TD_phi(dphi_u_phi,dphi2_u_phi,nf,"set xla\"phi\""); //}
//////////// 3RD DERIVATIVES
////
double dT3_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dT3_Ug ( U->P , U->T0, V ); }
double dT2mu_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dT2mu_Ug ( U->P , U->T0, V ); }
double dT2phi_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dT2phi_Ug ( U->P , U->T0, V ); }
double dTmu2_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dTmu2_Ug ( U->P , U->T0, V ); }
double dmu2_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dmu2_Ug ( U->P , U->T0, V ); }
double dTmuphi_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dTmuphi_Ug ( U->P , U->T0, V ); }
double dmuphi_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dmuphi_Ug ( U->P , U->T0, V ); }
double dTphi2_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dTphi2_Ug ( U->P , U->T0, V ); }
double dphi2_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dphi2_Ug ( U->P , U->T0, V ); }
double dmu3_u_mu ( double mu ) { Var_set_Tmuphi ( V, T_, mu , phi_); return U->dmu3_Ug ( U->P , U->T0, V ); }
double dmu2phi_u_mu ( double mu ) { Var_set_Tmuphi ( V, T_, mu , phi_); return U->dmu2phi_Ug ( U->P , U->T0, V ); }
double dmuphi2_u_mu ( double mu ) { Var_set_Tmuphi ( V, T_, mu , phi_); return U->dmuphi2_Ug ( U->P , U->T0, V ); }
double dphi2_u_mu ( double mu ) {Var_set_Tmuphi ( V, T_, mu , phi_); return U->dphi2_Ug ( U->P , U->T0, V ); }
double dphi3_u_phi ( double phi ) { Var_set_Tmuphi ( V, T_, mu_, phi ); return U->dphi3_Ug ( U->P , U->T0, V ); }
//if ( false ){
sprintf ( nf , "dT3_%s_T", pref ); TD_T(dT2_u_T, dT3_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dT2mu_%s_T", pref ); TD_T(dTmu_u_T, dT2mu_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dT2phi_%s_T", pref ); TD_T(dTphi_u_T, dT2phi_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTmu2_%s_T", pref ); TD_T(dmu2_u_T, dTmu2_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTmuphi_%s_T", pref ); TD_T(dmuphi_u_T, dTmuphi_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTphi2_%s_T", pref ); TD_T(dphi2_u_T, dTphi2_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dmu3_%s_mu", pref ); TD_mu (dmu2_u_mu,dmu3_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmu2phi_%s_mu", pref ); TD_mu (dmuphi_u_mu,dmu2phi_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmuphi2_%s_mu", pref ); TD_mu (dphi2_u_mu,dmuphi2_u_mu ,nf,"set xla\"mu\""); // }
sprintf ( nf , "dphi3_%s_phi", pref ); TD_phi(dphi2_u_phi,dphi3_u_phi,nf,"set xla\"phi\"");
/* double dphi2_u ( double phi ) */
/* { */
/* Var_set_Tmuphi( V, T_, mu_, phi ); */
/* double dphi_u( double phi ) */
/* { */
/* Var_set_Tmuphi( V, T_, mu_, phi); */
/* double u ( double phi ) */
/* { */
/* Var_set_Tmuphi( V, T_, mu_, phi); */
/* return upot_pow_phi_eq_phibar( U->P, U->T0, V ); */
/* } */
/* return deriv ( u, phi, 0.001 ) ; */
/* } */
/* return deriv( dphi_u, phi, 0.001 ) ; */
/* } */
/* sprintf( nf, "all-num__dphi3_%s_phi", pref ) ; TD_phi( dphi2_u, dphi3_u_phi,nf, "set xla\"phi\"" ); */
}
Var_free ( V );
}
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- Created by texi2html, http://www.gnu.org/software/texinfo/ -->
<head>
<title>top section: About This Document</title>
<meta name="description" content="top section: About This Document">
<meta name="keywords" content="top section: About This Document">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="texi2html">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="top section">
<link href="section-node.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="#SEC_About" rel="help" title="About This Document">
<style type="text/css">
<!--
a.summary-letter {text-decoration: none}
blockquote.smallquotation {font-size: smaller}
div.display {margin-left: 3.2em}
div.example {margin-left: 3.2em}
div.lisp {margin-left: 3.2em}
div.smalldisplay {margin-left: 3.2em}
div.smallexample {margin-left: 3.2em}
div.smalllisp {margin-left: 3.2em}
pre.display {font-family: serif}
pre.format {font-family: serif}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: serif; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: serif; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.nocodebreak {white-space:pre}
span.nolinebreak {white-space:pre}
span.roman {font-family:serif; font-weight:normal}
span.sansserif {font-family:sans-serif; font-weight:normal}
ul.no-bullet {list-style: none}
-->
</style>
</head>
<body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000">
<a name="SEC_About"></a>
<table class="header" cellpadding="1" cellspacing="1" border="0">
<tr><td valign="middle" align="left">node: </td>
<td valign="middle" align="left"></td>
<td valign="middle" align="left"></td>
<td valign="middle" align="left">,</td>
<td valign="middle" align="left"></td>
<td valign="middle" align="left">,</td>
<td valign="middle" align="left"></td>
<td valign="middle" align="left">[ > ]</td>
</tr></table>
<hr>
<h1>About This Document</h1>
<p>
This document was generated on <em>a sunny day</em> using <a href="http://www.gnu.org/software/texinfo/"><em>texi2html</em></a>.
</p>
<p>
The buttons in the navigation panels have the following meaning:
</p>
<table border="1">
<tr>
<th> Button </th>
<th> Name </th>
<th> Go to </th>
<th> From 1.2.3 go to</th>
</tr>
<tr>
<td align="center"> [ > ] </td>
<td align="center">NodeForward</td>
<td>Next node in node reading order</td>
<td>1.2.4</td>
</tr>
</table>
<p>
where the <strong> Example </strong> assumes that the current position is at <strong> Subsubsection One-Two-Three </strong> of a document of the following structure:
</p>
<ul>
<li> 1. Section One
<ul>
<li>1.1 Subsection One-One
<ul>
<li>...</li>
</ul>
</li>
<li>1.2 Subsection One-Two
<ul>
<li>1.2.1 Subsubsection One-Two-One</li>
<li>1.2.2 Subsubsection One-Two-Two</li>
<li>1.2.3 Subsubsection One-Two-Three
<strong><== Current Position </strong></li>
<li>1.2.4 Subsubsection One-Two-Four</li>
</ul>
</li>
<li>1.3 Subsection One-Three
<ul>
<li>...</li>
</ul>
</li>
<li>1.4 Subsection One-Four</li>
</ul>
</li>
</ul>
<hr>
<table class="header" cellpadding="1" cellspacing="1" border="0">
<tr><td valign="middle" align="left">node: </td>
<td valign="middle" align="left"></td>
<td valign="middle" align="left"></td>
<td valign="middle" align="left">,</td>
<td valign="middle" align="left"></td>
<td valign="middle" align="left">,</td>
<td valign="middle" align="left"></td>
<td valign="middle" align="left">[ > ]</td>
</tr></table>
<p>
<font size="-1">
This document was generated on <em>a sunny day</em> using <a href="http://www.gnu.org/software/texinfo/"><em>texi2html</em></a>.
</font>
<br>
</p>
</body>
</html>
| Java |
/*
_ _ _ _
___| (_) ___| | __ (_)___
/ __| | |/ __| |/ / | / __|
\__ \ | | (__| < _ | \__ \
|___/_|_|\___|_|\_(_)/ |___/
|__/
Version: 1.8.1
Author: Ken Wheeler
Website: http://kenwheeler.github.io
Docs: http://kenwheeler.github.io/slick
Repo: http://github.com/kenwheeler/slick
Issues: http://github.com/kenwheeler/slick/issues
*/
/* global window, document, define, jQuery, setInterval, clearInterval */
;(function(factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof exports !== 'undefined') {
module.exports = factory(require('jquery'));
} else {
factory(jQuery);
}
}(function($) {
'use strict';
var Slick = window.Slick || {};
Slick = (function() {
var instanceUid = 0;
function Slick(element, settings) {
var _ = this, dataSettings;
_.defaults = {
accessibility: true,
adaptiveHeight: false,
appendArrows: $(element),
appendDots: $(element),
arrows: true,
asNavFor: null,
prevArrow: '<button class="slick-prev" aria-label="Previous" type="button">Previous</button>',
nextArrow: '<button class="slick-next" aria-label="Next" type="button">Next</button>',
autoplay: false,
autoplaySpeed: 3000,
centerMode: false,
centerPadding: '50px',
cssEase: 'ease',
customPaging: function(slider, i) {
return $('<button type="button" />').text(i + 1);
},
dots: false,
dotsClass: 'slick-dots',
draggable: true,
easing: 'linear',
edgeFriction: 0.35,
fade: false,
focusOnSelect: false,
focusOnChange: false,
infinite: true,
initialSlide: 0,
lazyLoad: 'ondemand',
mobileFirst: false,
pauseOnHover: true,
pauseOnFocus: true,
pauseOnDotsHover: false,
respondTo: 'window',
responsive: null,
rows: 1,
rtl: false,
slide: '',
slidesPerRow: 1,
slidesToShow: 1,
slidesToScroll: 1,
speed: 500,
swipe: true,
swipeToSlide: false,
touchMove: true,
touchThreshold: 5,
useCSS: true,
useTransform: true,
variableWidth: false,
vertical: false,
verticalSwiping: false,
waitForAnimate: true,
zIndex: 1000
};
_.initials = {
animating: false,
dragging: false,
autoPlayTimer: null,
currentDirection: 0,
currentLeft: null,
currentSlide: 0,
direction: 1,
$dots: null,
listWidth: null,
listHeight: null,
loadIndex: 0,
$nextArrow: null,
$prevArrow: null,
scrolling: false,
slideCount: null,
slideWidth: null,
$slideTrack: null,
$slides: null,
sliding: false,
slideOffset: 0,
swipeLeft: null,
swiping: false,
$list: null,
touchObject: {},
transformsEnabled: false,
unslicked: false
};
$.extend(_, _.initials);
_.activeBreakpoint = null;
_.animType = null;
_.animProp = null;
_.breakpoints = [];
_.breakpointSettings = [];
_.cssTransitions = false;
_.focussed = false;
_.interrupted = false;
_.hidden = 'hidden';
_.paused = true;
_.positionProp = null;
_.respondTo = null;
_.rowCount = 1;
_.shouldClick = true;
_.$slider = $(element);
_.$slidesCache = null;
_.transformType = null;
_.transitionType = null;
_.visibilityChange = 'visibilitychange';
_.windowWidth = 0;
_.windowTimer = null;
dataSettings = $(element).data('slick') || {};
_.options = $.extend({}, _.defaults, settings, dataSettings);
_.currentSlide = _.options.initialSlide;
_.originalSettings = _.options;
if (typeof document.mozHidden !== 'undefined') {
_.hidden = 'mozHidden';
_.visibilityChange = 'mozvisibilitychange';
} else if (typeof document.webkitHidden !== 'undefined') {
_.hidden = 'webkitHidden';
_.visibilityChange = 'webkitvisibilitychange';
}
_.autoPlay = $.proxy(_.autoPlay, _);
_.autoPlayClear = $.proxy(_.autoPlayClear, _);
_.autoPlayIterator = $.proxy(_.autoPlayIterator, _);
_.changeSlide = $.proxy(_.changeSlide, _);
_.clickHandler = $.proxy(_.clickHandler, _);
_.selectHandler = $.proxy(_.selectHandler, _);
_.setPosition = $.proxy(_.setPosition, _);
_.swipeHandler = $.proxy(_.swipeHandler, _);
_.dragHandler = $.proxy(_.dragHandler, _);
_.keyHandler = $.proxy(_.keyHandler, _);
_.instanceUid = instanceUid++;
// A simple way to check for HTML strings
// Strict HTML recognition (must start with <)
// Extracted from jQuery v1.11 source
_.htmlExpr = /^(?:\s*(<[\w\W]+>)[^>]*)$/;
_.registerBreakpoints();
_.init(true);
}
return Slick;
}());
Slick.prototype.activateADA = function() {
var _ = this;
_.$slideTrack.find('.slick-active').attr({
'aria-hidden': 'false'
}).find('a, input, button, select').attr({
'tabindex': '0'
});
};
Slick.prototype.addSlide = Slick.prototype.slickAdd = function(markup, index, addBefore) {
var _ = this;
if (typeof(index) === 'boolean') {
addBefore = index;
index = null;
} else if (index < 0 || (index >= _.slideCount)) {
return false;
}
_.unload();
if (typeof(index) === 'number') {
if (index === 0 && _.$slides.length === 0) {
$(markup).appendTo(_.$slideTrack);
} else if (addBefore) {
$(markup).insertBefore(_.$slides.eq(index));
} else {
$(markup).insertAfter(_.$slides.eq(index));
}
} else {
if (addBefore === true) {
$(markup).prependTo(_.$slideTrack);
} else {
$(markup).appendTo(_.$slideTrack);
}
}
_.$slides = _.$slideTrack.children(this.options.slide);
_.$slideTrack.children(this.options.slide).detach();
_.$slideTrack.append(_.$slides);
_.$slides.each(function(index, element) {
$(element).attr('data-slick-index', index);
});
_.$slidesCache = _.$slides;
_.reinit();
};
Slick.prototype.animateHeight = function() {
var _ = this;
if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
_.$list.animate({
height: targetHeight
}, _.options.speed);
}
};
Slick.prototype.animateSlide = function(targetLeft, callback) {
var animProps = {},
_ = this;
_.animateHeight();
if (_.options.rtl === true && _.options.vertical === false) {
targetLeft = -targetLeft;
}
if (_.transformsEnabled === false) {
if (_.options.vertical === false) {
_.$slideTrack.animate({
left: targetLeft
}, _.options.speed, _.options.easing, callback);
} else {
_.$slideTrack.animate({
top: targetLeft
}, _.options.speed, _.options.easing, callback);
}
} else {
if (_.cssTransitions === false) {
if (_.options.rtl === true) {
_.currentLeft = -(_.currentLeft);
}
$({
animStart: _.currentLeft
}).animate({
animStart: targetLeft
}, {
duration: _.options.speed,
easing: _.options.easing,
step: function(now) {
now = Math.ceil(now);
if (_.options.vertical === false) {
animProps[_.animType] = 'translate(' +
now + 'px, 0px)';
_.$slideTrack.css(animProps);
} else {
animProps[_.animType] = 'translate(0px,' +
now + 'px)';
_.$slideTrack.css(animProps);
}
},
complete: function() {
if (callback) {
callback.call();
}
}
});
} else {
_.applyTransition();
targetLeft = Math.ceil(targetLeft);
if (_.options.vertical === false) {
animProps[_.animType] = 'translate3d(' + targetLeft + 'px, 0px, 0px)';
} else {
animProps[_.animType] = 'translate3d(0px,' + targetLeft + 'px, 0px)';
}
_.$slideTrack.css(animProps);
if (callback) {
setTimeout(function() {
_.disableTransition();
callback.call();
}, _.options.speed);
}
}
}
};
Slick.prototype.getNavTarget = function() {
var _ = this,
asNavFor = _.options.asNavFor;
if ( asNavFor && asNavFor !== null ) {
asNavFor = $(asNavFor).not(_.$slider);
}
return asNavFor;
};
Slick.prototype.asNavFor = function(index) {
var _ = this,
asNavFor = _.getNavTarget();
if ( asNavFor !== null && typeof asNavFor === 'object' ) {
asNavFor.each(function() {
var target = $(this).slick('getSlick');
if(!target.unslicked) {
target.slideHandler(index, true);
}
});
}
};
Slick.prototype.applyTransition = function(slide) {
var _ = this,
transition = {};
if (_.options.fade === false) {
transition[_.transitionType] = _.transformType + ' ' + _.options.speed + 'ms ' + _.options.cssEase;
} else {
transition[_.transitionType] = 'opacity ' + _.options.speed + 'ms ' + _.options.cssEase;
}
if (_.options.fade === false) {
_.$slideTrack.css(transition);
} else {
_.$slides.eq(slide).css(transition);
}
};
Slick.prototype.autoPlay = function() {
var _ = this;
_.autoPlayClear();
if ( _.slideCount > _.options.slidesToShow ) {
_.autoPlayTimer = setInterval( _.autoPlayIterator, _.options.autoplaySpeed );
}
};
Slick.prototype.autoPlayClear = function() {
var _ = this;
if (_.autoPlayTimer) {
clearInterval(_.autoPlayTimer);
}
};
Slick.prototype.autoPlayIterator = function() {
var _ = this,
slideTo = _.currentSlide + _.options.slidesToScroll;
if ( !_.paused && !_.interrupted && !_.focussed ) {
if ( _.options.infinite === false ) {
if ( _.direction === 1 && ( _.currentSlide + 1 ) === ( _.slideCount - 1 )) {
_.direction = 0;
}
else if ( _.direction === 0 ) {
slideTo = _.currentSlide - _.options.slidesToScroll;
if ( _.currentSlide - 1 === 0 ) {
_.direction = 1;
}
}
}
_.slideHandler( slideTo );
}
};
Slick.prototype.buildArrows = function() {
var _ = this;
if (_.options.arrows === true ) {
_.$prevArrow = $(_.options.prevArrow).addClass('slick-arrow');
_.$nextArrow = $(_.options.nextArrow).addClass('slick-arrow');
if( _.slideCount > _.options.slidesToShow ) {
_.$prevArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');
_.$nextArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');
if (_.htmlExpr.test(_.options.prevArrow)) {
_.$prevArrow.prependTo(_.options.appendArrows);
}
if (_.htmlExpr.test(_.options.nextArrow)) {
_.$nextArrow.appendTo(_.options.appendArrows);
}
if (_.options.infinite !== true) {
_.$prevArrow
.addClass('slick-disabled')
.attr('aria-disabled', 'true');
}
} else {
_.$prevArrow.add( _.$nextArrow )
.addClass('slick-hidden')
.attr({
'aria-disabled': 'true',
'tabindex': '-1'
});
}
}
};
Slick.prototype.buildDots = function() {
var _ = this,
i, dot;
if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
_.$slider.addClass('slick-dotted');
dot = $('<ul />').addClass(_.options.dotsClass);
for (i = 0; i <= _.getDotCount(); i += 1) {
dot.append($('<li />').append(_.options.customPaging.call(this, _, i)));
}
_.$dots = dot.appendTo(_.options.appendDots);
_.$dots.find('li').first().addClass('slick-active');
}
};
Slick.prototype.buildOut = function() {
var _ = this;
_.$slides =
_.$slider
.children( _.options.slide + ':not(.slick-cloned)')
.addClass('slick-slide');
_.slideCount = _.$slides.length;
_.$slides.each(function(index, element) {
$(element)
.attr('data-slick-index', index)
.data('originalStyling', $(element).attr('style') || '');
});
_.$slider.addClass('slick-slider');
_.$slideTrack = (_.slideCount === 0) ?
$('<div class="slick-track"/>').appendTo(_.$slider) :
_.$slides.wrapAll('<div class="slick-track"/>').parent();
_.$list = _.$slideTrack.wrap(
'<div class="slick-list"/>').parent();
_.$slideTrack.css('opacity', 0);
if (_.options.centerMode === true || _.options.swipeToSlide === true) {
_.options.slidesToScroll = 1;
}
$('img[data-lazy]', _.$slider).not('[src]').addClass('slick-loading');
_.setupInfinite();
_.buildArrows();
_.buildDots();
_.updateDots();
_.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);
if (_.options.draggable === true) {
_.$list.addClass('draggable');
}
};
Slick.prototype.buildRows = function() {
var _ = this, a, b, c, newSlides, numOfSlides, originalSlides,slidesPerSection;
newSlides = document.createDocumentFragment();
originalSlides = _.$slider.children();
if(_.options.rows > 0) {
slidesPerSection = _.options.slidesPerRow * _.options.rows;
numOfSlides = Math.ceil(
originalSlides.length / slidesPerSection
);
for(a = 0; a < numOfSlides; a++){
var slide = document.createElement('div');
for(b = 0; b < _.options.rows; b++) {
var row = document.createElement('div');
for(c = 0; c < _.options.slidesPerRow; c++) {
var target = (a * slidesPerSection + ((b * _.options.slidesPerRow) + c));
if (originalSlides.get(target)) {
row.appendChild(originalSlides.get(target));
}
}
slide.appendChild(row);
}
newSlides.appendChild(slide);
}
_.$slider.empty().append(newSlides);
_.$slider.children().children().children()
.css({
'width':(100 / _.options.slidesPerRow) + '%',
'display': 'inline-block'
});
}
};
Slick.prototype.checkResponsive = function(initial, forceUpdate) {
var _ = this,
breakpoint, targetBreakpoint, respondToWidth, triggerBreakpoint = false;
var sliderWidth = _.$slider.width();
var windowWidth = window.innerWidth || $(window).width();
if (_.respondTo === 'window') {
respondToWidth = windowWidth;
} else if (_.respondTo === 'slider') {
respondToWidth = sliderWidth;
} else if (_.respondTo === 'min') {
respondToWidth = Math.min(windowWidth, sliderWidth);
}
if ( _.options.responsive &&
_.options.responsive.length &&
_.options.responsive !== null) {
targetBreakpoint = null;
for (breakpoint in _.breakpoints) {
if (_.breakpoints.hasOwnProperty(breakpoint)) {
if (_.originalSettings.mobileFirst === false) {
if (respondToWidth < _.breakpoints[breakpoint]) {
targetBreakpoint = _.breakpoints[breakpoint];
}
} else {
if (respondToWidth > _.breakpoints[breakpoint]) {
targetBreakpoint = _.breakpoints[breakpoint];
}
}
}
}
if (targetBreakpoint !== null) {
if (_.activeBreakpoint !== null) {
if (targetBreakpoint !== _.activeBreakpoint || forceUpdate) {
_.activeBreakpoint =
targetBreakpoint;
if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
_.unslick(targetBreakpoint);
} else {
_.options = $.extend({}, _.originalSettings,
_.breakpointSettings[
targetBreakpoint]);
if (initial === true) {
_.currentSlide = _.options.initialSlide;
}
_.refresh(initial);
}
triggerBreakpoint = targetBreakpoint;
}
} else {
_.activeBreakpoint = targetBreakpoint;
if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
_.unslick(targetBreakpoint);
} else {
_.options = $.extend({}, _.originalSettings,
_.breakpointSettings[
targetBreakpoint]);
if (initial === true) {
_.currentSlide = _.options.initialSlide;
}
_.refresh(initial);
}
triggerBreakpoint = targetBreakpoint;
}
} else {
if (_.activeBreakpoint !== null) {
_.activeBreakpoint = null;
_.options = _.originalSettings;
if (initial === true) {
_.currentSlide = _.options.initialSlide;
}
_.refresh(initial);
triggerBreakpoint = targetBreakpoint;
}
}
// only trigger breakpoints during an actual break. not on initialize.
if( !initial && triggerBreakpoint !== false ) {
_.$slider.trigger('breakpoint', [_, triggerBreakpoint]);
}
}
};
Slick.prototype.changeSlide = function(event, dontAnimate) {
var _ = this,
$target = $(event.currentTarget),
indexOffset, slideOffset, unevenOffset;
// If target is a link, prevent default action.
if($target.is('a')) {
event.preventDefault();
}
// If target is not the <li> element (ie: a child), find the <li>.
if(!$target.is('li')) {
$target = $target.closest('li');
}
unevenOffset = (_.slideCount % _.options.slidesToScroll !== 0);
indexOffset = unevenOffset ? 0 : (_.slideCount - _.currentSlide) % _.options.slidesToScroll;
switch (event.data.message) {
case 'previous':
slideOffset = indexOffset === 0 ? _.options.slidesToScroll : _.options.slidesToShow - indexOffset;
if (_.slideCount > _.options.slidesToShow) {
_.slideHandler(_.currentSlide - slideOffset, false, dontAnimate);
}
break;
case 'next':
slideOffset = indexOffset === 0 ? _.options.slidesToScroll : indexOffset;
if (_.slideCount > _.options.slidesToShow) {
_.slideHandler(_.currentSlide + slideOffset, false, dontAnimate);
}
break;
case 'index':
var index = event.data.index === 0 ? 0 :
event.data.index || $target.index() * _.options.slidesToScroll;
_.slideHandler(_.checkNavigable(index), false, dontAnimate);
$target.children().trigger('focus');
break;
default:
return;
}
};
Slick.prototype.checkNavigable = function(index) {
var _ = this,
navigables, prevNavigable;
navigables = _.getNavigableIndexes();
prevNavigable = 0;
if (index > navigables[navigables.length - 1]) {
index = navigables[navigables.length - 1];
} else {
for (var n in navigables) {
if (index < navigables[n]) {
index = prevNavigable;
break;
}
prevNavigable = navigables[n];
}
}
return index;
};
Slick.prototype.cleanUpEvents = function() {
var _ = this;
if (_.options.dots && _.$dots !== null) {
$('li', _.$dots)
.off('click.slick', _.changeSlide)
.off('mouseenter.slick', $.proxy(_.interrupt, _, true))
.off('mouseleave.slick', $.proxy(_.interrupt, _, false));
if (_.options.accessibility === true) {
_.$dots.off('keydown.slick', _.keyHandler);
}
}
_.$slider.off('focus.slick blur.slick');
if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
_.$prevArrow && _.$prevArrow.off('click.slick', _.changeSlide);
_.$nextArrow && _.$nextArrow.off('click.slick', _.changeSlide);
if (_.options.accessibility === true) {
_.$prevArrow && _.$prevArrow.off('keydown.slick', _.keyHandler);
_.$nextArrow && _.$nextArrow.off('keydown.slick', _.keyHandler);
}
}
_.$list.off('touchstart.slick mousedown.slick', _.swipeHandler);
_.$list.off('touchmove.slick mousemove.slick', _.swipeHandler);
_.$list.off('touchend.slick mouseup.slick', _.swipeHandler);
_.$list.off('touchcancel.slick mouseleave.slick', _.swipeHandler);
_.$list.off('click.slick', _.clickHandler);
$(document).off(_.visibilityChange, _.visibility);
_.cleanUpSlideEvents();
if (_.options.accessibility === true) {
_.$list.off('keydown.slick', _.keyHandler);
}
if (_.options.focusOnSelect === true) {
$(_.$slideTrack).children().off('click.slick', _.selectHandler);
}
$(window).off('orientationchange.slick.slick-' + _.instanceUid, _.orientationChange);
$(window).off('resize.slick.slick-' + _.instanceUid, _.resize);
$('[draggable!=true]', _.$slideTrack).off('dragstart', _.preventDefault);
$(window).off('load.slick.slick-' + _.instanceUid, _.setPosition);
};
Slick.prototype.cleanUpSlideEvents = function() {
var _ = this;
_.$list.off('mouseenter.slick', $.proxy(_.interrupt, _, true));
_.$list.off('mouseleave.slick', $.proxy(_.interrupt, _, false));
};
Slick.prototype.cleanUpRows = function() {
var _ = this, originalSlides;
if(_.options.rows > 0) {
originalSlides = _.$slides.children().children();
originalSlides.removeAttr('style');
_.$slider.empty().append(originalSlides);
}
};
Slick.prototype.clickHandler = function(event) {
var _ = this;
if (_.shouldClick === false) {
event.stopImmediatePropagation();
event.stopPropagation();
event.preventDefault();
}
};
Slick.prototype.destroy = function(refresh) {
var _ = this;
_.autoPlayClear();
_.touchObject = {};
_.cleanUpEvents();
$('.slick-cloned', _.$slider).detach();
if (_.$dots) {
_.$dots.remove();
}
if ( _.$prevArrow && _.$prevArrow.length ) {
_.$prevArrow
.removeClass('slick-disabled slick-arrow slick-hidden')
.removeAttr('aria-hidden aria-disabled tabindex')
.css('display','');
if ( _.htmlExpr.test( _.options.prevArrow )) {
_.$prevArrow.remove();
}
}
if ( _.$nextArrow && _.$nextArrow.length ) {
_.$nextArrow
.removeClass('slick-disabled slick-arrow slick-hidden')
.removeAttr('aria-hidden aria-disabled tabindex')
.css('display','');
if ( _.htmlExpr.test( _.options.nextArrow )) {
_.$nextArrow.remove();
}
}
if (_.$slides) {
_.$slides
.removeClass('slick-slide slick-active slick-center slick-visible slick-current')
.removeAttr('aria-hidden')
.removeAttr('data-slick-index')
.each(function(){
$(this).attr('style', $(this).data('originalStyling'));
});
_.$slideTrack.children(this.options.slide).detach();
_.$slideTrack.detach();
_.$list.detach();
_.$slider.append(_.$slides);
}
_.cleanUpRows();
_.$slider.removeClass('slick-slider');
_.$slider.removeClass('slick-initialized');
_.$slider.removeClass('slick-dotted');
_.unslicked = true;
if(!refresh) {
_.$slider.trigger('destroy', [_]);
}
};
Slick.prototype.disableTransition = function(slide) {
var _ = this,
transition = {};
transition[_.transitionType] = '';
if (_.options.fade === false) {
_.$slideTrack.css(transition);
} else {
_.$slides.eq(slide).css(transition);
}
};
Slick.prototype.fadeSlide = function(slideIndex, callback) {
var _ = this;
if (_.cssTransitions === false) {
_.$slides.eq(slideIndex).css({
zIndex: _.options.zIndex
});
_.$slides.eq(slideIndex).animate({
opacity: 1
}, _.options.speed, _.options.easing, callback);
} else {
_.applyTransition(slideIndex);
_.$slides.eq(slideIndex).css({
opacity: 1,
zIndex: _.options.zIndex
});
if (callback) {
setTimeout(function() {
_.disableTransition(slideIndex);
callback.call();
}, _.options.speed);
}
}
};
Slick.prototype.fadeSlideOut = function(slideIndex) {
var _ = this;
if (_.cssTransitions === false) {
_.$slides.eq(slideIndex).animate({
opacity: 0,
zIndex: _.options.zIndex - 2
}, _.options.speed, _.options.easing);
} else {
_.applyTransition(slideIndex);
_.$slides.eq(slideIndex).css({
opacity: 0,
zIndex: _.options.zIndex - 2
});
}
};
Slick.prototype.filterSlides = Slick.prototype.slickFilter = function(filter) {
var _ = this;
if (filter !== null) {
_.$slidesCache = _.$slides;
_.unload();
_.$slideTrack.children(this.options.slide).detach();
_.$slidesCache.filter(filter).appendTo(_.$slideTrack);
_.reinit();
}
};
Slick.prototype.focusHandler = function() {
var _ = this;
_.$slider
.off('focus.slick blur.slick')
.on('focus.slick blur.slick', '*', function(event) {
event.stopImmediatePropagation();
var $sf = $(this);
setTimeout(function() {
if( _.options.pauseOnFocus ) {
_.focussed = $sf.is(':focus');
_.autoPlay();
}
}, 0);
});
};
Slick.prototype.getCurrent = Slick.prototype.slickCurrentSlide = function() {
var _ = this;
return _.currentSlide;
};
Slick.prototype.getDotCount = function() {
var _ = this;
var breakPoint = 0;
var counter = 0;
var pagerQty = 0;
if (_.options.infinite === true) {
if (_.slideCount <= _.options.slidesToShow) {
++pagerQty;
} else {
while (breakPoint < _.slideCount) {
++pagerQty;
breakPoint = counter + _.options.slidesToScroll;
counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
}
}
} else if (_.options.centerMode === true) {
pagerQty = _.slideCount;
} else if(!_.options.asNavFor) {
pagerQty = 1 + Math.ceil((_.slideCount - _.options.slidesToShow) / _.options.slidesToScroll);
}else {
while (breakPoint < _.slideCount) {
++pagerQty;
breakPoint = counter + _.options.slidesToScroll;
counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
}
}
return pagerQty - 1;
};
Slick.prototype.getLeft = function(slideIndex) {
var _ = this,
targetLeft,
verticalHeight,
verticalOffset = 0,
targetSlide,
coef;
_.slideOffset = 0;
verticalHeight = _.$slides.first().outerHeight(true);
if (_.options.infinite === true) {
if (_.slideCount > _.options.slidesToShow) {
_.slideOffset = (_.slideWidth * _.options.slidesToShow) * -1;
coef = -1
if (_.options.vertical === true && _.options.centerMode === true) {
if (_.options.slidesToShow === 2) {
coef = -1.5;
} else if (_.options.slidesToShow === 1) {
coef = -2
}
}
verticalOffset = (verticalHeight * _.options.slidesToShow) * coef;
}
if (_.slideCount % _.options.slidesToScroll !== 0) {
if (slideIndex + _.options.slidesToScroll > _.slideCount && _.slideCount > _.options.slidesToShow) {
if (slideIndex > _.slideCount) {
_.slideOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * _.slideWidth) * -1;
verticalOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * verticalHeight) * -1;
} else {
_.slideOffset = ((_.slideCount % _.options.slidesToScroll) * _.slideWidth) * -1;
verticalOffset = ((_.slideCount % _.options.slidesToScroll) * verticalHeight) * -1;
}
}
}
} else {
if (slideIndex + _.options.slidesToShow > _.slideCount) {
_.slideOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * _.slideWidth;
verticalOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * verticalHeight;
}
}
if (_.slideCount <= _.options.slidesToShow) {
_.slideOffset = 0;
verticalOffset = 0;
}
if (_.options.centerMode === true && _.slideCount <= _.options.slidesToShow) {
_.slideOffset = ((_.slideWidth * Math.floor(_.options.slidesToShow)) / 2) - ((_.slideWidth * _.slideCount) / 2);
} else if (_.options.centerMode === true && _.options.infinite === true) {
_.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2) - _.slideWidth;
} else if (_.options.centerMode === true) {
_.slideOffset = 0;
_.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2);
}
if (_.options.vertical === false) {
targetLeft = ((slideIndex * _.slideWidth) * -1) + _.slideOffset;
} else {
targetLeft = ((slideIndex * verticalHeight) * -1) + verticalOffset;
}
if (_.options.variableWidth === true) {
if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
} else {
targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow);
}
if (_.options.rtl === true) {
if (targetSlide[0]) {
targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
} else {
targetLeft = 0;
}
} else {
targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
}
if (_.options.centerMode === true) {
if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
} else {
targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow + 1);
}
if (_.options.rtl === true) {
if (targetSlide[0]) {
targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
} else {
targetLeft = 0;
}
} else {
targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
}
targetLeft += (_.$list.width() - targetSlide.outerWidth()) / 2;
}
}
return targetLeft;
};
Slick.prototype.getOption = Slick.prototype.slickGetOption = function(option) {
var _ = this;
return _.options[option];
};
Slick.prototype.getNavigableIndexes = function() {
var _ = this,
breakPoint = 0,
counter = 0,
indexes = [],
max;
if (_.options.infinite === false) {
max = _.slideCount;
} else {
breakPoint = _.options.slidesToScroll * -1;
counter = _.options.slidesToScroll * -1;
max = _.slideCount * 2;
}
var fs = 0;
while (breakPoint < max) {
indexes.push(breakPoint);
breakPoint = counter + _.options.slidesToScroll;
counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
fs++;
if ( fs > 200 ) {
console.log( 'WARNING! Infinite loop!' );
break;
}
}
return indexes;
};
Slick.prototype.getSlick = function() {
return this;
};
Slick.prototype.getSlideCount = function() {
var _ = this,
slidesTraversed, swipedSlide, centerOffset;
centerOffset = _.options.centerMode === true ? _.slideWidth * Math.floor(_.options.slidesToShow / 2) : 0;
if (_.options.swipeToSlide === true) {
_.$slideTrack.find('.slick-slide').each(function(index, slide) {
if (slide.offsetLeft - centerOffset + ($(slide).outerWidth() / 2) > (_.swipeLeft * -1)) {
swipedSlide = slide;
return false;
}
});
slidesTraversed = Math.abs($(swipedSlide).attr('data-slick-index') - _.currentSlide) || 1;
return slidesTraversed;
} else {
return _.options.slidesToScroll;
}
};
Slick.prototype.goTo = Slick.prototype.slickGoTo = function(slide, dontAnimate) {
var _ = this;
_.changeSlide({
data: {
message: 'index',
index: parseInt(slide)
}
}, dontAnimate);
};
Slick.prototype.init = function(creation) {
var _ = this;
if (!$(_.$slider).hasClass('slick-initialized')) {
$(_.$slider).addClass('slick-initialized');
_.buildRows();
_.buildOut();
_.setProps();
_.startLoad();
_.loadSlider();
_.initializeEvents();
_.updateArrows();
_.updateDots();
_.checkResponsive(true);
_.focusHandler();
}
if (creation) {
_.$slider.trigger('init', [_]);
}
if (_.options.accessibility === true) {
_.initADA();
}
if ( _.options.autoplay ) {
_.paused = false;
_.autoPlay();
}
};
Slick.prototype.initADA = function() {
var _ = this,
numDotGroups = Math.ceil(_.slideCount / _.options.slidesToShow),
tabControlIndexes = _.getNavigableIndexes().filter(function(val) {
return (val >= 0) && (val < _.slideCount);
});
_.$slides.add(_.$slideTrack.find('.slick-cloned')).attr({
'aria-hidden': 'true',
'tabindex': '-1'
}).find('a, input, button, select').attr({
'tabindex': '-1'
});
if (_.$dots !== null) {
_.$slides.not(_.$slideTrack.find('.slick-cloned')).each(function(i) {
var slideControlIndex = tabControlIndexes.indexOf(i);
$(this).attr({
'role': 'tabpanel',
'id': 'slick-slide' + _.instanceUid + i,
'tabindex': -1
});
if (slideControlIndex !== -1) {
var ariaButtonControl = 'slick-slide-control' + _.instanceUid + slideControlIndex
if ($('#' + ariaButtonControl).length) {
$(this).attr({
'aria-describedby': ariaButtonControl
});
}
}
});
_.$dots.attr('role', 'tablist').find('li').each(function(i) {
var mappedSlideIndex = tabControlIndexes[i];
$(this).attr({
'role': 'presentation'
});
$(this).find('button').first().attr({
'role': 'tab',
'id': 'slick-slide-control' + _.instanceUid + i,
'aria-controls': 'slick-slide' + _.instanceUid + mappedSlideIndex,
'aria-label': (i + 1) + ' of ' + numDotGroups,
'aria-selected': null,
'tabindex': '-1'
});
}).eq(_.currentSlide).find('button').attr({
'aria-selected': 'true',
'tabindex': '0'
}).end();
}
for (var i=_.currentSlide, max=i+_.options.slidesToShow; i < max; i++) {
if (_.options.focusOnChange) {
_.$slides.eq(i).attr({'tabindex': '0'});
} else {
_.$slides.eq(i).removeAttr('tabindex');
}
}
_.activateADA();
};
Slick.prototype.initArrowEvents = function() {
var _ = this;
if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
_.$prevArrow
.off('click.slick')
.on('click.slick', {
message: 'previous'
}, _.changeSlide);
_.$nextArrow
.off('click.slick')
.on('click.slick', {
message: 'next'
}, _.changeSlide);
if (_.options.accessibility === true) {
_.$prevArrow.on('keydown.slick', _.keyHandler);
_.$nextArrow.on('keydown.slick', _.keyHandler);
}
}
};
Slick.prototype.initDotEvents = function() {
var _ = this;
if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
$('li', _.$dots).on('click.slick', {
message: 'index'
}, _.changeSlide);
if (_.options.accessibility === true) {
_.$dots.on('keydown.slick', _.keyHandler);
}
}
if (_.options.dots === true && _.options.pauseOnDotsHover === true && _.slideCount > _.options.slidesToShow) {
$('li', _.$dots)
.on('mouseenter.slick', $.proxy(_.interrupt, _, true))
.on('mouseleave.slick', $.proxy(_.interrupt, _, false));
}
};
Slick.prototype.initSlideEvents = function() {
var _ = this;
if ( _.options.pauseOnHover ) {
_.$list.on('mouseenter.slick', $.proxy(_.interrupt, _, true));
_.$list.on('mouseleave.slick', $.proxy(_.interrupt, _, false));
}
};
Slick.prototype.initializeEvents = function() {
var _ = this;
_.initArrowEvents();
_.initDotEvents();
_.initSlideEvents();
_.$list.on('touchstart.slick mousedown.slick', {
action: 'start'
}, _.swipeHandler);
_.$list.on('touchmove.slick mousemove.slick', {
action: 'move'
}, _.swipeHandler);
_.$list.on('touchend.slick mouseup.slick', {
action: 'end'
}, _.swipeHandler);
_.$list.on('touchcancel.slick mouseleave.slick', {
action: 'end'
}, _.swipeHandler);
_.$list.on('click.slick', _.clickHandler);
$(document).on(_.visibilityChange, $.proxy(_.visibility, _));
if (_.options.accessibility === true) {
_.$list.on('keydown.slick', _.keyHandler);
}
if (_.options.focusOnSelect === true) {
$(_.$slideTrack).children().on('click.slick', _.selectHandler);
}
$(window).on('orientationchange.slick.slick-' + _.instanceUid, $.proxy(_.orientationChange, _));
$(window).on('resize.slick.slick-' + _.instanceUid, $.proxy(_.resize, _));
$('[draggable!=true]', _.$slideTrack).on('dragstart', _.preventDefault);
$(window).on('load.slick.slick-' + _.instanceUid, _.setPosition);
$(_.setPosition);
};
Slick.prototype.initUI = function() {
var _ = this;
if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
_.$prevArrow.show();
_.$nextArrow.show();
}
if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
_.$dots.show();
}
};
Slick.prototype.keyHandler = function(event) {
var _ = this;
//Dont slide if the cursor is inside the form fields and arrow keys are pressed
if(!event.target.tagName.match('TEXTAREA|INPUT|SELECT')) {
if (event.keyCode === 37 && _.options.accessibility === true) {
_.changeSlide({
data: {
message: _.options.rtl === true ? 'next' : 'previous'
}
});
} else if (event.keyCode === 39 && _.options.accessibility === true) {
_.changeSlide({
data: {
message: _.options.rtl === true ? 'previous' : 'next'
}
});
}
}
};
Slick.prototype.lazyLoad = function() {
var _ = this,
loadRange, cloneRange, rangeStart, rangeEnd;
function loadImages(imagesScope) {
$('img[data-lazy]', imagesScope).each(function() {
var image = $(this),
imageSource = $(this).attr('data-lazy'),
imageSrcSet = $(this).attr('data-srcset'),
imageSizes = $(this).attr('data-sizes') || _.$slider.attr('data-sizes'),
imageToLoad = document.createElement('img');
imageToLoad.onload = function() {
image
.animate({ opacity: 0 }, 100, function() {
if (imageSrcSet) {
image
.attr('srcset', imageSrcSet );
if (imageSizes) {
image
.attr('sizes', imageSizes );
}
}
image
.attr('src', imageSource)
.animate({ opacity: 1 }, 200, function() {
image
.removeAttr('data-lazy data-srcset data-sizes')
.removeClass('slick-loading');
});
_.$slider.trigger('lazyLoaded', [_, image, imageSource]);
});
};
imageToLoad.onerror = function() {
image
.removeAttr( 'data-lazy' )
.removeClass( 'slick-loading' )
.addClass( 'slick-lazyload-error' );
_.$slider.trigger('lazyLoadError', [ _, image, imageSource ]);
};
imageToLoad.src = imageSource;
});
}
if (_.options.centerMode === true) {
if (_.options.infinite === true) {
rangeStart = _.currentSlide + (_.options.slidesToShow / 2 + 1);
rangeEnd = rangeStart + _.options.slidesToShow + 2;
} else {
rangeStart = Math.max(0, _.currentSlide - (_.options.slidesToShow / 2 + 1));
rangeEnd = 2 + (_.options.slidesToShow / 2 + 1) + _.currentSlide;
}
} else {
rangeStart = _.options.infinite ? _.options.slidesToShow + _.currentSlide : _.currentSlide;
rangeEnd = Math.ceil(rangeStart + _.options.slidesToShow);
if (_.options.fade === true) {
if (rangeStart > 0) rangeStart--;
if (rangeEnd <= _.slideCount) rangeEnd++;
}
}
loadRange = _.$slider.find('.slick-slide').slice(rangeStart, rangeEnd);
if (_.options.lazyLoad === 'anticipated') {
var prevSlide = rangeStart - 1,
nextSlide = rangeEnd,
$slides = _.$slider.find('.slick-slide');
for (var i = 0; i < _.options.slidesToScroll; i++) {
if (prevSlide < 0) prevSlide = _.slideCount - 1;
loadRange = loadRange.add($slides.eq(prevSlide));
loadRange = loadRange.add($slides.eq(nextSlide));
prevSlide--;
nextSlide++;
}
}
loadImages(loadRange);
if (_.slideCount <= _.options.slidesToShow) {
cloneRange = _.$slider.find('.slick-slide');
loadImages(cloneRange);
} else
if (_.currentSlide >= _.slideCount - _.options.slidesToShow) {
cloneRange = _.$slider.find('.slick-cloned').slice(0, _.options.slidesToShow);
loadImages(cloneRange);
} else if (_.currentSlide === 0) {
cloneRange = _.$slider.find('.slick-cloned').slice(_.options.slidesToShow * -1);
loadImages(cloneRange);
}
};
Slick.prototype.loadSlider = function() {
var _ = this;
_.setPosition();
_.$slideTrack.css({
opacity: 1
});
_.$slider.removeClass('slick-loading');
_.initUI();
if (_.options.lazyLoad === 'progressive') {
_.progressiveLazyLoad();
}
};
Slick.prototype.next = Slick.prototype.slickNext = function() {
var _ = this;
_.changeSlide({
data: {
message: 'next'
}
});
};
Slick.prototype.orientationChange = function() {
var _ = this;
_.checkResponsive();
_.setPosition();
};
Slick.prototype.pause = Slick.prototype.slickPause = function() {
var _ = this;
_.autoPlayClear();
_.paused = true;
};
Slick.prototype.play = Slick.prototype.slickPlay = function() {
var _ = this;
_.autoPlay();
_.options.autoplay = true;
_.paused = false;
_.focussed = false;
_.interrupted = false;
};
Slick.prototype.postSlide = function(index) {
var _ = this;
if( !_.unslicked ) {
_.$slider.trigger('afterChange', [_, index]);
_.animating = false;
if (_.slideCount > _.options.slidesToShow) {
_.setPosition();
}
_.swipeLeft = null;
if ( _.options.autoplay ) {
_.autoPlay();
}
if (_.options.accessibility === true) {
_.initADA();
if (_.options.focusOnChange) {
var $currentSlide = $(_.$slides.get(_.currentSlide));
$currentSlide.attr('tabindex', 0).focus();
}
}
}
};
Slick.prototype.prev = Slick.prototype.slickPrev = function() {
var _ = this;
_.changeSlide({
data: {
message: 'previous'
}
});
};
Slick.prototype.preventDefault = function(event) {
event.preventDefault();
};
Slick.prototype.progressiveLazyLoad = function( tryCount ) {
tryCount = tryCount || 1;
var _ = this,
$imgsToLoad = $( 'img[data-lazy]', _.$slider ),
image,
imageSource,
imageSrcSet,
imageSizes,
imageToLoad;
if ( $imgsToLoad.length ) {
image = $imgsToLoad.first();
imageSource = image.attr('data-lazy');
imageSrcSet = image.attr('data-srcset');
imageSizes = image.attr('data-sizes') || _.$slider.attr('data-sizes');
imageToLoad = document.createElement('img');
imageToLoad.onload = function() {
if (imageSrcSet) {
image
.attr('srcset', imageSrcSet );
if (imageSizes) {
image
.attr('sizes', imageSizes );
}
}
image
.attr( 'src', imageSource )
.removeAttr('data-lazy data-srcset data-sizes')
.removeClass('slick-loading');
if ( _.options.adaptiveHeight === true ) {
_.setPosition();
}
_.$slider.trigger('lazyLoaded', [ _, image, imageSource ]);
_.progressiveLazyLoad();
};
imageToLoad.onerror = function() {
if ( tryCount < 3 ) {
/**
* try to load the image 3 times,
* leave a slight delay so we don't get
* servers blocking the request.
*/
setTimeout( function() {
_.progressiveLazyLoad( tryCount + 1 );
}, 500 );
} else {
image
.removeAttr( 'data-lazy' )
.removeClass( 'slick-loading' )
.addClass( 'slick-lazyload-error' );
_.$slider.trigger('lazyLoadError', [ _, image, imageSource ]);
_.progressiveLazyLoad();
}
};
imageToLoad.src = imageSource;
} else {
_.$slider.trigger('allImagesLoaded', [ _ ]);
}
};
Slick.prototype.refresh = function( initializing ) {
var _ = this, currentSlide, lastVisibleIndex;
lastVisibleIndex = _.slideCount - _.options.slidesToShow;
// in non-infinite sliders, we don't want to go past the
// last visible index.
if( !_.options.infinite && ( _.currentSlide > lastVisibleIndex )) {
_.currentSlide = lastVisibleIndex;
}
// if less slides than to show, go to start.
if ( _.slideCount <= _.options.slidesToShow ) {
_.currentSlide = 0;
}
currentSlide = _.currentSlide;
_.destroy(true);
$.extend(_, _.initials, { currentSlide: currentSlide });
_.init();
if( !initializing ) {
_.changeSlide({
data: {
message: 'index',
index: currentSlide
}
}, false);
}
};
Slick.prototype.registerBreakpoints = function() {
var _ = this, breakpoint, currentBreakpoint, l,
responsiveSettings = _.options.responsive || null;
if ( $.type(responsiveSettings) === 'array' && responsiveSettings.length ) {
_.respondTo = _.options.respondTo || 'window';
for ( breakpoint in responsiveSettings ) {
l = _.breakpoints.length-1;
if (responsiveSettings.hasOwnProperty(breakpoint)) {
currentBreakpoint = responsiveSettings[breakpoint].breakpoint;
// loop through the breakpoints and cut out any existing
// ones with the same breakpoint number, we don't want dupes.
while( l >= 0 ) {
if( _.breakpoints[l] && _.breakpoints[l] === currentBreakpoint ) {
_.breakpoints.splice(l,1);
}
l--;
}
_.breakpoints.push(currentBreakpoint);
_.breakpointSettings[currentBreakpoint] = responsiveSettings[breakpoint].settings;
}
}
_.breakpoints.sort(function(a, b) {
return ( _.options.mobileFirst ) ? a-b : b-a;
});
}
};
Slick.prototype.reinit = function() {
var _ = this;
_.$slides =
_.$slideTrack
.children(_.options.slide)
.addClass('slick-slide');
_.slideCount = _.$slides.length;
if (_.currentSlide >= _.slideCount && _.currentSlide !== 0) {
_.currentSlide = _.currentSlide - _.options.slidesToScroll;
}
if (_.slideCount <= _.options.slidesToShow) {
_.currentSlide = 0;
}
_.registerBreakpoints();
_.setProps();
_.setupInfinite();
_.buildArrows();
_.updateArrows();
_.initArrowEvents();
_.buildDots();
_.updateDots();
_.initDotEvents();
_.cleanUpSlideEvents();
_.initSlideEvents();
_.checkResponsive(false, true);
if (_.options.focusOnSelect === true) {
$(_.$slideTrack).children().on('click.slick', _.selectHandler);
}
_.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);
_.setPosition();
_.focusHandler();
_.paused = !_.options.autoplay;
_.autoPlay();
_.$slider.trigger('reInit', [_]);
};
Slick.prototype.resize = function() {
var _ = this;
if ($(window).width() !== _.windowWidth) {
clearTimeout(_.windowDelay);
_.windowDelay = window.setTimeout(function() {
_.windowWidth = $(window).width();
_.checkResponsive();
if( !_.unslicked ) { _.setPosition(); }
}, 50);
}
};
Slick.prototype.removeSlide = Slick.prototype.slickRemove = function(index, removeBefore, removeAll) {
var _ = this;
if (typeof(index) === 'boolean') {
removeBefore = index;
index = removeBefore === true ? 0 : _.slideCount - 1;
} else {
index = removeBefore === true ? --index : index;
}
if (_.slideCount < 1 || index < 0 || index > _.slideCount - 1) {
return false;
}
_.unload();
if (removeAll === true) {
_.$slideTrack.children().remove();
} else {
_.$slideTrack.children(this.options.slide).eq(index).remove();
}
_.$slides = _.$slideTrack.children(this.options.slide);
_.$slideTrack.children(this.options.slide).detach();
_.$slideTrack.append(_.$slides);
_.$slidesCache = _.$slides;
_.reinit();
};
Slick.prototype.setCSS = function(position) {
var _ = this,
positionProps = {},
x, y;
if (_.options.rtl === true) {
position = -position;
}
x = _.positionProp == 'left' ? Math.ceil(position) + 'px' : '0px';
y = _.positionProp == 'top' ? Math.ceil(position) + 'px' : '0px';
positionProps[_.positionProp] = position;
if (_.transformsEnabled === false) {
_.$slideTrack.css(positionProps);
} else {
positionProps = {};
if (_.cssTransitions === false) {
positionProps[_.animType] = 'translate(' + x + ', ' + y + ')';
_.$slideTrack.css(positionProps);
} else {
positionProps[_.animType] = 'translate3d(' + x + ', ' + y + ', 0px)';
_.$slideTrack.css(positionProps);
}
}
};
Slick.prototype.setDimensions = function() {
var _ = this;
if (_.options.vertical === false) {
if (_.options.centerMode === true) {
_.$list.css({
padding: ('0px ' + _.options.centerPadding)
});
}
} else {
_.$list.height(_.$slides.first().outerHeight(true) * _.options.slidesToShow);
if (_.options.centerMode === true) {
_.$list.css({
padding: (_.options.centerPadding + ' 0px')
});
}
}
_.listWidth = _.$list.width();
_.listHeight = _.$list.height();
if (_.options.vertical === false && _.options.variableWidth === false) {
_.slideWidth = Math.ceil(_.listWidth / _.options.slidesToShow);
_.$slideTrack.width(Math.ceil((_.slideWidth * _.$slideTrack.children('.slick-slide').length)));
} else if (_.options.variableWidth === true) {
_.$slideTrack.width(5000 * _.slideCount);
} else {
_.slideWidth = Math.ceil(_.listWidth);
_.$slideTrack.height(Math.ceil((_.$slides.first().outerHeight(true) * _.$slideTrack.children('.slick-slide').length)));
}
var offset = _.$slides.first().outerWidth(true) - _.$slides.first().width();
if (_.options.variableWidth === false) _.$slideTrack.children('.slick-slide').width(_.slideWidth - offset);
};
Slick.prototype.setFade = function() {
var _ = this,
targetLeft;
_.$slides.each(function(index, element) {
targetLeft = (_.slideWidth * index) * -1;
if (_.options.rtl === true) {
$(element).css({
position: 'relative',
right: targetLeft,
top: 0,
zIndex: _.options.zIndex - 2,
opacity: 0
});
} else {
$(element).css({
position: 'relative',
left: targetLeft,
top: 0,
zIndex: _.options.zIndex - 2,
opacity: 0
});
}
});
_.$slides.eq(_.currentSlide).css({
zIndex: _.options.zIndex - 1,
opacity: 1
});
};
Slick.prototype.setHeight = function() {
var _ = this;
if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
_.$list.css('height', targetHeight);
}
};
Slick.prototype.setOption =
Slick.prototype.slickSetOption = function() {
/**
* accepts arguments in format of:
*
* - for changing a single option's value:
* .slick("setOption", option, value, refresh )
*
* - for changing a set of responsive options:
* .slick("setOption", 'responsive', [{}, ...], refresh )
*
* - for updating multiple values at once (not responsive)
* .slick("setOption", { 'option': value, ... }, refresh )
*/
var _ = this, l, item, option, value, refresh = false, type;
if( $.type( arguments[0] ) === 'object' ) {
option = arguments[0];
refresh = arguments[1];
type = 'multiple';
} else if ( $.type( arguments[0] ) === 'string' ) {
option = arguments[0];
value = arguments[1];
refresh = arguments[2];
if ( arguments[0] === 'responsive' && $.type( arguments[1] ) === 'array' ) {
type = 'responsive';
} else if ( typeof arguments[1] !== 'undefined' ) {
type = 'single';
}
}
if ( type === 'single' ) {
_.options[option] = value;
} else if ( type === 'multiple' ) {
$.each( option , function( opt, val ) {
_.options[opt] = val;
});
} else if ( type === 'responsive' ) {
for ( item in value ) {
if( $.type( _.options.responsive ) !== 'array' ) {
_.options.responsive = [ value[item] ];
} else {
l = _.options.responsive.length-1;
// loop through the responsive object and splice out duplicates.
while( l >= 0 ) {
if( _.options.responsive[l].breakpoint === value[item].breakpoint ) {
_.options.responsive.splice(l,1);
}
l--;
}
_.options.responsive.push( value[item] );
}
}
}
if ( refresh ) {
_.unload();
_.reinit();
}
};
Slick.prototype.setPosition = function() {
var _ = this;
_.setDimensions();
_.setHeight();
if (_.options.fade === false) {
_.setCSS(_.getLeft(_.currentSlide));
} else {
_.setFade();
}
_.$slider.trigger('setPosition', [_]);
};
Slick.prototype.setProps = function() {
var _ = this,
bodyStyle = document.body.style;
_.positionProp = _.options.vertical === true ? 'top' : 'left';
if (_.positionProp === 'top') {
_.$slider.addClass('slick-vertical');
} else {
_.$slider.removeClass('slick-vertical');
}
if (bodyStyle.WebkitTransition !== undefined ||
bodyStyle.MozTransition !== undefined ||
bodyStyle.msTransition !== undefined) {
if (_.options.useCSS === true) {
_.cssTransitions = true;
}
}
if ( _.options.fade ) {
if ( typeof _.options.zIndex === 'number' ) {
if( _.options.zIndex < 3 ) {
_.options.zIndex = 3;
}
} else {
_.options.zIndex = _.defaults.zIndex;
}
}
if (bodyStyle.OTransform !== undefined) {
_.animType = 'OTransform';
_.transformType = '-o-transform';
_.transitionType = 'OTransition';
if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
}
if (bodyStyle.MozTransform !== undefined) {
_.animType = 'MozTransform';
_.transformType = '-moz-transform';
_.transitionType = 'MozTransition';
if (bodyStyle.perspectiveProperty === undefined && bodyStyle.MozPerspective === undefined) _.animType = false;
}
if (bodyStyle.webkitTransform !== undefined) {
_.animType = 'webkitTransform';
_.transformType = '-webkit-transform';
_.transitionType = 'webkitTransition';
if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
}
if (bodyStyle.msTransform !== undefined) {
_.animType = 'msTransform';
_.transformType = '-ms-transform';
_.transitionType = 'msTransition';
if (bodyStyle.msTransform === undefined) _.animType = false;
}
if (bodyStyle.transform !== undefined && _.animType !== false) {
_.animType = 'transform';
_.transformType = 'transform';
_.transitionType = 'transition';
}
_.transformsEnabled = _.options.useTransform && (_.animType !== null && _.animType !== false);
};
Slick.prototype.setSlideClasses = function(index) {
var _ = this,
centerOffset, allSlides, indexOffset, remainder;
allSlides = _.$slider
.find('.slick-slide')
.removeClass('slick-active slick-center slick-current')
.attr('aria-hidden', 'true');
_.$slides
.eq(index)
.addClass('slick-current');
if (_.options.centerMode === true) {
var evenCoef = _.options.slidesToShow % 2 === 0 ? 1 : 0;
centerOffset = Math.floor(_.options.slidesToShow / 2);
if (_.options.infinite === true) {
if (index >= centerOffset && index <= (_.slideCount - 1) - centerOffset) {
_.$slides
.slice(index - centerOffset + evenCoef, index + centerOffset + 1)
.addClass('slick-active')
.attr('aria-hidden', 'false');
} else {
indexOffset = _.options.slidesToShow + index;
allSlides
.slice(indexOffset - centerOffset + 1 + evenCoef, indexOffset + centerOffset + 2)
.addClass('slick-active')
.attr('aria-hidden', 'false');
}
if (index === 0) {
allSlides
.eq(allSlides.length - 1 - _.options.slidesToShow)
.addClass('slick-center');
} else if (index === _.slideCount - 1) {
allSlides
.eq(_.options.slidesToShow)
.addClass('slick-center');
}
}
_.$slides
.eq(index)
.addClass('slick-center');
} else {
if (index >= 0 && index <= (_.slideCount - _.options.slidesToShow)) {
_.$slides
.slice(index, index + _.options.slidesToShow)
.addClass('slick-active')
.attr('aria-hidden', 'false');
} else if (allSlides.length <= _.options.slidesToShow) {
allSlides
.addClass('slick-active')
.attr('aria-hidden', 'false');
} else {
remainder = _.slideCount % _.options.slidesToShow;
indexOffset = _.options.infinite === true ? _.options.slidesToShow + index : index;
if (_.options.slidesToShow == _.options.slidesToScroll && (_.slideCount - index) < _.options.slidesToShow) {
allSlides
.slice(indexOffset - (_.options.slidesToShow - remainder), indexOffset + remainder)
.addClass('slick-active')
.attr('aria-hidden', 'false');
} else {
allSlides
.slice(indexOffset, indexOffset + _.options.slidesToShow)
.addClass('slick-active')
.attr('aria-hidden', 'false');
}
}
}
if (_.options.lazyLoad === 'ondemand' || _.options.lazyLoad === 'anticipated') {
_.lazyLoad();
}
};
Slick.prototype.setupInfinite = function() {
var _ = this,
i, slideIndex, infiniteCount;
if (_.options.fade === true) {
_.options.centerMode = false;
}
if (_.options.infinite === true && _.options.fade === false) {
slideIndex = null;
if (_.slideCount > _.options.slidesToShow) {
if (_.options.centerMode === true) {
infiniteCount = _.options.slidesToShow + 1;
} else {
infiniteCount = _.options.slidesToShow;
}
for (i = _.slideCount; i > (_.slideCount -
infiniteCount); i -= 1) {
slideIndex = i - 1;
$(_.$slides[slideIndex]).clone(true).attr('id', '')
.attr('data-slick-index', slideIndex - _.slideCount)
.prependTo(_.$slideTrack).addClass('slick-cloned');
}
for (i = 0; i < infiniteCount + _.slideCount; i += 1) {
slideIndex = i;
$(_.$slides[slideIndex]).clone(true).attr('id', '')
.attr('data-slick-index', slideIndex + _.slideCount)
.appendTo(_.$slideTrack).addClass('slick-cloned');
}
_.$slideTrack.find('.slick-cloned').find('[id]').each(function() {
$(this).attr('id', '');
});
}
}
};
Slick.prototype.interrupt = function( toggle ) {
var _ = this;
if( !toggle ) {
_.autoPlay();
}
_.interrupted = toggle;
};
Slick.prototype.selectHandler = function(event) {
var _ = this;
var targetElement =
$(event.target).is('.slick-slide') ?
$(event.target) :
$(event.target).parents('.slick-slide');
var index = parseInt(targetElement.attr('data-slick-index'));
if (!index) index = 0;
if (_.slideCount <= _.options.slidesToShow) {
_.slideHandler(index, false, true);
return;
}
_.slideHandler(index);
};
Slick.prototype.slideHandler = function(index, sync, dontAnimate) {
var targetSlide, animSlide, oldSlide, slideLeft, targetLeft = null,
_ = this, navTarget;
sync = sync || false;
if (_.animating === true && _.options.waitForAnimate === true) {
return;
}
if (_.options.fade === true && _.currentSlide === index) {
return;
}
if (sync === false) {
_.asNavFor(index);
}
targetSlide = index;
targetLeft = _.getLeft(targetSlide);
slideLeft = _.getLeft(_.currentSlide);
_.currentLeft = _.swipeLeft === null ? slideLeft : _.swipeLeft;
if (_.options.infinite === false && _.options.centerMode === false && (index < 0 || index > _.getDotCount() * _.options.slidesToScroll)) {
if (_.options.fade === false) {
targetSlide = _.currentSlide;
if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
_.animateSlide(slideLeft, function() {
_.postSlide(targetSlide);
});
} else {
_.postSlide(targetSlide);
}
}
return;
} else if (_.options.infinite === false && _.options.centerMode === true && (index < 0 || index > (_.slideCount - _.options.slidesToScroll))) {
if (_.options.fade === false) {
targetSlide = _.currentSlide;
if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
_.animateSlide(slideLeft, function() {
_.postSlide(targetSlide);
});
} else {
_.postSlide(targetSlide);
}
}
return;
}
if ( _.options.autoplay ) {
clearInterval(_.autoPlayTimer);
}
if (targetSlide < 0) {
if (_.slideCount % _.options.slidesToScroll !== 0) {
animSlide = _.slideCount - (_.slideCount % _.options.slidesToScroll);
} else {
animSlide = _.slideCount + targetSlide;
}
} else if (targetSlide >= _.slideCount) {
if (_.slideCount % _.options.slidesToScroll !== 0) {
animSlide = 0;
} else {
animSlide = targetSlide - _.slideCount;
}
} else {
animSlide = targetSlide;
}
_.animating = true;
_.$slider.trigger('beforeChange', [_, _.currentSlide, animSlide]);
oldSlide = _.currentSlide;
_.currentSlide = animSlide;
_.setSlideClasses(_.currentSlide);
if ( _.options.asNavFor ) {
navTarget = _.getNavTarget();
navTarget = navTarget.slick('getSlick');
if ( navTarget.slideCount <= navTarget.options.slidesToShow ) {
navTarget.setSlideClasses(_.currentSlide);
}
}
_.updateDots();
_.updateArrows();
if (_.options.fade === true) {
if (dontAnimate !== true) {
_.fadeSlideOut(oldSlide);
_.fadeSlide(animSlide, function() {
_.postSlide(animSlide);
});
} else {
_.postSlide(animSlide);
}
_.animateHeight();
return;
}
if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
_.animateSlide(targetLeft, function() {
_.postSlide(animSlide);
});
} else {
_.postSlide(animSlide);
}
};
Slick.prototype.startLoad = function() {
var _ = this;
if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
_.$prevArrow.hide();
_.$nextArrow.hide();
}
if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
_.$dots.hide();
}
_.$slider.addClass('slick-loading');
};
Slick.prototype.swipeDirection = function() {
var xDist, yDist, r, swipeAngle, _ = this;
xDist = _.touchObject.startX - _.touchObject.curX;
yDist = _.touchObject.startY - _.touchObject.curY;
r = Math.atan2(yDist, xDist);
swipeAngle = Math.round(r * 180 / Math.PI);
if (swipeAngle < 0) {
swipeAngle = 360 - Math.abs(swipeAngle);
}
if ((swipeAngle <= 45) && (swipeAngle >= 0)) {
return (_.options.rtl === false ? 'left' : 'right');
}
if ((swipeAngle <= 360) && (swipeAngle >= 315)) {
return (_.options.rtl === false ? 'left' : 'right');
}
if ((swipeAngle >= 135) && (swipeAngle <= 225)) {
return (_.options.rtl === false ? 'right' : 'left');
}
if (_.options.verticalSwiping === true) {
if ((swipeAngle >= 35) && (swipeAngle <= 135)) {
return 'down';
} else {
return 'up';
}
}
return 'vertical';
};
Slick.prototype.swipeEnd = function(event) {
var _ = this,
slideCount,
direction;
_.dragging = false;
_.swiping = false;
if (_.scrolling) {
_.scrolling = false;
return false;
}
_.interrupted = false;
_.shouldClick = ( _.touchObject.swipeLength > 10 ) ? false : true;
if ( _.touchObject.curX === undefined ) {
return false;
}
if ( _.touchObject.edgeHit === true ) {
_.$slider.trigger('edge', [_, _.swipeDirection() ]);
}
if ( _.touchObject.swipeLength >= _.touchObject.minSwipe ) {
direction = _.swipeDirection();
switch ( direction ) {
case 'left':
case 'down':
slideCount =
_.options.swipeToSlide ?
_.checkNavigable( _.currentSlide + _.getSlideCount() ) :
_.currentSlide + _.getSlideCount();
_.currentDirection = 0;
break;
case 'right':
case 'up':
slideCount =
_.options.swipeToSlide ?
_.checkNavigable( _.currentSlide - _.getSlideCount() ) :
_.currentSlide - _.getSlideCount();
_.currentDirection = 1;
break;
default:
}
if( direction != 'vertical' ) {
_.slideHandler( slideCount );
_.touchObject = {};
_.$slider.trigger('swipe', [_, direction ]);
}
} else {
if ( _.touchObject.startX !== _.touchObject.curX ) {
_.slideHandler( _.currentSlide );
_.touchObject = {};
}
}
};
Slick.prototype.swipeHandler = function(event) {
var _ = this;
if ((_.options.swipe === false) || ('ontouchend' in document && _.options.swipe === false)) {
return;
} else if (_.options.draggable === false && event.type.indexOf('mouse') !== -1) {
return;
}
_.touchObject.fingerCount = event.originalEvent && event.originalEvent.touches !== undefined ?
event.originalEvent.touches.length : 1;
_.touchObject.minSwipe = _.listWidth / _.options
.touchThreshold;
if (_.options.verticalSwiping === true) {
_.touchObject.minSwipe = _.listHeight / _.options
.touchThreshold;
}
switch (event.data.action) {
case 'start':
_.swipeStart(event);
break;
case 'move':
_.swipeMove(event);
break;
case 'end':
_.swipeEnd(event);
break;
}
};
Slick.prototype.swipeMove = function(event) {
var _ = this,
edgeWasHit = false,
curLeft, swipeDirection, swipeLength, positionOffset, touches, verticalSwipeLength;
touches = event.originalEvent !== undefined ? event.originalEvent.touches : null;
if (!_.dragging || _.scrolling || touches && touches.length !== 1) {
return false;
}
curLeft = _.getLeft(_.currentSlide);
_.touchObject.curX = touches !== undefined ? touches[0].pageX : event.clientX;
_.touchObject.curY = touches !== undefined ? touches[0].pageY : event.clientY;
_.touchObject.swipeLength = Math.round(Math.sqrt(
Math.pow(_.touchObject.curX - _.touchObject.startX, 2)));
verticalSwipeLength = Math.round(Math.sqrt(
Math.pow(_.touchObject.curY - _.touchObject.startY, 2)));
if (!_.options.verticalSwiping && !_.swiping && verticalSwipeLength > 4) {
_.scrolling = true;
return false;
}
if (_.options.verticalSwiping === true) {
_.touchObject.swipeLength = verticalSwipeLength;
}
swipeDirection = _.swipeDirection();
if (event.originalEvent !== undefined && _.touchObject.swipeLength > 4) {
_.swiping = true;
event.preventDefault();
}
positionOffset = (_.options.rtl === false ? 1 : -1) * (_.touchObject.curX > _.touchObject.startX ? 1 : -1);
if (_.options.verticalSwiping === true) {
positionOffset = _.touchObject.curY > _.touchObject.startY ? 1 : -1;
}
swipeLength = _.touchObject.swipeLength;
_.touchObject.edgeHit = false;
if (_.options.infinite === false) {
if ((_.currentSlide === 0 && swipeDirection === 'right') || (_.currentSlide >= _.getDotCount() && swipeDirection === 'left')) {
swipeLength = _.touchObject.swipeLength * _.options.edgeFriction;
_.touchObject.edgeHit = true;
}
}
if (_.options.vertical === false) {
_.swipeLeft = curLeft + swipeLength * positionOffset;
} else {
_.swipeLeft = curLeft + (swipeLength * (_.$list.height() / _.listWidth)) * positionOffset;
}
if (_.options.verticalSwiping === true) {
_.swipeLeft = curLeft + swipeLength * positionOffset;
}
if (_.options.fade === true || _.options.touchMove === false) {
return false;
}
if (_.animating === true) {
_.swipeLeft = null;
return false;
}
_.setCSS(_.swipeLeft);
};
Slick.prototype.swipeStart = function(event) {
var _ = this,
touches;
_.interrupted = true;
if (_.touchObject.fingerCount !== 1 || _.slideCount <= _.options.slidesToShow) {
_.touchObject = {};
return false;
}
if (event.originalEvent !== undefined && event.originalEvent.touches !== undefined) {
touches = event.originalEvent.touches[0];
}
_.touchObject.startX = _.touchObject.curX = touches !== undefined ? touches.pageX : event.clientX;
_.touchObject.startY = _.touchObject.curY = touches !== undefined ? touches.pageY : event.clientY;
_.dragging = true;
};
Slick.prototype.unfilterSlides = Slick.prototype.slickUnfilter = function() {
var _ = this;
if (_.$slidesCache !== null) {
_.unload();
_.$slideTrack.children(this.options.slide).detach();
_.$slidesCache.appendTo(_.$slideTrack);
_.reinit();
}
};
Slick.prototype.unload = function() {
var _ = this;
$('.slick-cloned', _.$slider).remove();
if (_.$dots) {
_.$dots.remove();
}
if (_.$prevArrow && _.htmlExpr.test(_.options.prevArrow)) {
_.$prevArrow.remove();
}
if (_.$nextArrow && _.htmlExpr.test(_.options.nextArrow)) {
_.$nextArrow.remove();
}
_.$slides
.removeClass('slick-slide slick-active slick-visible slick-current')
.attr('aria-hidden', 'true')
.css('width', '');
};
Slick.prototype.unslick = function(fromBreakpoint) {
var _ = this;
_.$slider.trigger('unslick', [_, fromBreakpoint]);
_.destroy();
};
Slick.prototype.updateArrows = function() {
var _ = this,
centerOffset;
centerOffset = Math.floor(_.options.slidesToShow / 2);
if ( _.options.arrows === true &&
_.slideCount > _.options.slidesToShow &&
!_.options.infinite ) {
_.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
_.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
if (_.currentSlide === 0) {
_.$prevArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
_.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
} else if (_.currentSlide >= _.slideCount - _.options.slidesToShow && _.options.centerMode === false) {
_.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
_.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
} else if (_.currentSlide >= _.slideCount - 1 && _.options.centerMode === true) {
_.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
_.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
}
}
};
Slick.prototype.updateDots = function() {
var _ = this;
if (_.$dots !== null) {
_.$dots
.find('li')
.removeClass('slick-active')
.end();
_.$dots
.find('li')
.eq(Math.floor(_.currentSlide / _.options.slidesToScroll))
.addClass('slick-active');
}
};
Slick.prototype.visibility = function() {
var _ = this;
if ( _.options.autoplay ) {
if ( document[_.hidden] ) {
_.interrupted = true;
} else {
_.interrupted = false;
}
}
};
$.fn.slick = function() {
var _ = this,
opt = arguments[0],
args = Array.prototype.slice.call(arguments, 1),
l = _.length,
i,
ret;
for (i = 0; i < l; i++) {
if (typeof opt == 'object' || typeof opt == 'undefined')
_[i].slick = new Slick(_[i], opt);
else
ret = _[i].slick[opt].apply(_[i].slick, args);
if (typeof ret != 'undefined') return ret;
}
return _;
};
$( document ).ready(function() {
$( '.exopite-multifilter-items.slick-carousel' ).each(function ( idx, item ) {
var carouselId = "slick-carousel" + idx;
var data = $( this ).parent( '.exopite-multifilter-container' ).data( 'carousel' );
if ( typeof data !== "undefined" ) {
this.id = carouselId;
$( this ).slick({
autoplay: ( data.autoplay === 'false' ) ? false : true,
arrows: ( data.arrows === 'false' ) ? false : true,
autoplaySpeed: data.autoplay_speed,
infinite: ( data.infinite === 'false' ) ? false : true,
speed: parseInt( data.speed ),
pauseOnHover: ( data.pause_on_hover === 'false' ) ? false : true,
dots: ( data.dots === 'false' ) ? false : true,
adaptiveHeight: ( data.adaptive_height === 'false' ) ? false : true,
mobileFirst: ( data.mobile_first === 'false' ) ? false : true,
slidesPerRow: parseInt( data.slides_per_row ),
slidesToShow: parseInt( data.slides_to_show ),
slidesToScroll: parseInt( data.slides_to_scroll ),
useTransform: ( data.use_transform === 'false' ) ? false : true,
});
}
});
});
}));
| Java |
/*******************************************************************************************************************************************************
* Copyright ¨Ï 2016 <WIZnet Co.,Ltd.>
* 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.
*********************************************************************************************************************************************************/
/**
******************************************************************************
* @file ADC/Illumination_RGBLED/W7500x_it.h
* @author IOP Team
* @version V1.0.0
* @date 26-AUG-2015
* @brief This file contains the headers of the interrupt handlers.
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, WIZnet SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2015 WIZnet Co.,Ltd.</center></h2>
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __W7500X_IT_H
#define __W7500X_IT_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "W7500x.h"
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
void NMI_Handler(void);
void HardFault_Handler(void);
void SVC_Handler(void);
void PendSV_Handler(void);
void SysTick_Handler(void);
void SSP0_Handler(void);
void SSP1_Handler(void);
void UART0_Handler(void);
void UART0_Handler(void);
void UART1_Handler(void);
void UART2_Handler(void);
void I2C0_Handler(void);
void I2C1_Handler(void);
void PORT0_Handler(void);
void PORT1_Handler(void);
void PORT2_Handler(void);
void DMA_Handler(void);
void DUALTIMER0_Handler(void);
void DUALTIMER1_Handler(void);
void PWM0_Handler(void);
void PWM1_Handler(void);
void PWM2_Handler(void);
void PWM3_Handler(void);
void PWM4_Handler(void);
void PWM5_Handler(void);
void PWM6_Handler(void);
void PWM7_Handler(void);
void ADC_Handler(void);
void WZTOE_Handler(void);
void EXTI_Handler(void);
#endif /* __W7500X_IT_H */
/******************* (C) COPYRIGHT 2015 WIZnet Co.,Ltd. *****END OF FILE****/
| Java |
namespace BarionClientLibrary.Operations.Common
{
public class ShippingAddress
{
public string Country { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string Zip { get; set; }
public string Street { get; set; }
public string Street2 { get; set; }
public string Street3 { get; set; }
public string FullName { get; set; }
}
}
| Java |
/*
* Moondust, a free game engine for platform game making
* Copyright (c) 2014-2019 Vitaly Novichkov <admin@wohlnet.ru>
*
* This software is licensed under a dual license system (MIT or GPL version 3 or later).
* This means you are free to choose with which of both licenses (MIT or GPL version 3 or later)
* you want to use this software.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* You can see text of MIT license in the LICENSE.mit file you can see in Engine folder,
* or see https://mit-license.org/.
*
* You can see text of GPLv3 license in the LICENSE.gpl3 file you can see in Engine folder,
* or see <http://www.gnu.org/licenses/>.
*/
#ifndef OBJ_NPC_H
#define OBJ_NPC_H
#include <string>
#include <common_features/size.h>
#include <ConfigPackManager/level/config_npc.h>
#include "../graphics/graphics.h"
#include "spawn_effect_def.h"
// //Defines:// //
// obj_npc //
// npc_Markers //
// //////////// //
struct obj_npc
{
/* OpenGL */
bool isInit;
PGE_Texture *image;
GLuint textureID;
int textureArrayId;
int animator_ID;
PGE_Size image_size;
/* OpenGL */
//! Generic NPC settings and parameters
NpcSetup setup;
SpawnEffectDef effect_1_def;
SpawnEffectDef effect_2_def;
enum blockSpawn
{
spawn_warp = 0,
spawn_bump
};
//!Type of NPC spawn from block
unsigned int block_spawn_type;
//!NPC's initial Y Velocity after spawn from block
double block_spawn_speed;
//!Play sound on spawn from block (if false - spawn without 'radish' sound)
bool block_spawn_sound;
};
struct NPC_GlobalSetup
{
// ;Defines for SMBX64
uint64_t bubble; // bubble=283 ; NPC-Container for packed in bubble
uint64_t egg; // egg=96 ; NPC-Container for packed in egg
uint64_t lakitu; // lakitu=284 ; NPC-Container for spawn by lakitu
uint64_t buried; // burred=91 ; NPC-Container for packed in herb
uint64_t ice_cube; // icecube=263 ; NPC-Container for frozen NPCs
// ;markers
uint64_t iceball; // iceball=265
uint64_t fireball; // fireball=13
uint64_t hammer; // hammer=171
uint64_t boomerang;// boomerang=292
uint64_t coin_in_block; // coin-in-block=10
// some physics settings
double phs_gravity_accel;
double phs_max_fall_speed;
//effects
uint64_t eff_lava_burn; //Lava burn effect [Effect to spawn on contact with lava]
//projectile properties
SpawnEffectDef projectile_effect;
uint64_t projectile_sound_id;
double projectile_speed;
//Talking NPC's properties
std::string talking_sign_img;
};
#endif // OBJ_NPC_H
| Java |
-----------------------------------
-- Catastrophe
-- Scythe weapon skill
-- Skill Level: N/A
-- Drain target's HP. Bec de Faucon/Apocalypse: Additional effect: Haste
-- This weapon skill is available with the stage 5 relic Scythe Apocalypse or within Dynamis with the stage 4 Bec de Faucon.
-- Also available without Aftermath effects with the Crisis Scythe. After 13 weapon skills have been used successfully, gives one "charge" of Catastrophe.
-- Aligned with the Shadow Gorget & Soil Gorget.
-- Aligned with the Shadow Belt & Soil Belt.
-- Element: None
-- Modifiers: INT:40% ; AGI:40%
-- 100%TP 200%TP 300%TP
-- 2.75 2.75 2.75
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.numHits = 1;
params.ftp100 = 2.75; params.ftp200 = 2.75; params.ftp300 = 2.75;
params.str_wsc = 0.40; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.4; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.4; params.agi_wsc = 0.0; params.int_wsc = 0.4;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, primary);
-- TODO: Whoever codes those level 85 weapons with the latent that grants this WS needs to code a check to not give the aftermath effect.
if (damage > 0) then
local amDuration = 20 * math.floor(tp/100);
player:addStatusEffect(EFFECT_AFTERMATH, 100, 0, amDuration, 0, 6);
end
if (target:isUndead() == false) then
local drain = (damage * 0.4);
player:addHP(drain);
end
return tpHits, extraHits, criticalHit, damage;
end | Java |
/*! \file st.h
\brief Class representing FPU's ST register.
*/
#ifdef ST_H
#error Already included
#else
#define ST_H
class st: public reg
{
public:
st();
st(std::string const &name);
~st();
st &operator()(size_t i);
std::string name() const override;
private:
std::string const m_name;
public:
st(const st &instance) = default;
st(st &&instance) = default;
st &operator=(const st &instance) = delete;
st &operator=(const st &&instance) = delete;
};
#endif
| Java |
#include <iostream>
#include <stdexcept>
#include <vector>
#include "latticeBase.hpp"
#include "collisionBase.hxx"
#include "latticeNode.hxx"
#include "latticeModel.hxx"
#include "ZouHeNode.hpp"
#include "latticeNode.hxx"
ZouHeNode::ZouHeNode
(
latticeBase &lb,
collisionBase &cb,
latticeModelD2Q9 &D2Q9,
fluidField &field
)
: boundaryNode(false, false, lb),
nodes {},
cb_ (cb),
is_normal_flow_ {false},
beta1_ {},
beta2_ {},
beta3_ {},
D2Q9_ (D2Q9),
field_ (field)
{
const auto c = lb_.getLatticeSpeed();
const auto cs_sqr = c * c / 3.0;
beta1_ = c / (9.0 *cs_sqr);
beta2_ = 0.5 / c;
beta3_ = beta2_ - beta1_;
}
void ZouHeNode::addNode
(
std::size_t x,
std::size_t y,
double u_x,
double u_y
)
{
const auto nx = lb_.getNumberOfNx();
const auto ny = lb_.getNumberOfNy();
const auto n = y * nx + x;
const auto left = x == 0;
const auto right = x == nx - 1;
const auto bottom = y == 0;
const auto top = y == ny - 1;
auto edge_i = -1;
if (right) edge_i = 0;
if (top) edge_i = 1;
if (left) edge_i = 2;
if (bottom) edge_i = 3;
// adds a corner node
if ((top || bottom) && (left || right))
{
auto corner_i = -1;
if (bottom && left) corner_i = 0;
if (bottom && right) corner_i = 1;
if (top && left) corner_i = 2;
if (top && right) corner_i = 3;
nodes.push_back(latticeNode(x, y, n, u_x, u_y, true, corner_i));
}
// adds a side node
else
{
nodes.push_back(latticeNode(x, y, n, u_x, u_y, false, edge_i));
}
}
void ZouHeNode::updateNode
(
std::vector<std::vector<double>> &df,
bool is_modify_stream
)
{
if (!is_modify_stream)
{
for (auto node : nodes)
{
if (node.corner)
{
ZouHeNode::updateCorner(df, node);
}
else
{
ZouHeNode::updateEdge(df, node);
}
} // n
}
}
void ZouHeNode::updateEdge
(
std::vector<std::vector<double>> &df,
latticeNode &node
)
{
const auto n = node.n_node;
const auto nx = lb_.getNumberOfNx();
const auto c = lb_.getLatticeSpeed();
switch(node.index_i)
{
case 0:
{ // right
auto vel = is_normal_flow_ ? field_.u[n - 1] : node.u_node;
const auto rho_node = (df[n][0] + df[n][D2Q9_.N] + df[n][D2Q9_.S] + 2.0 * (df[n][D2Q9_.E] +
df[n][D2Q9_.NE] + df[n][D2Q9_.SE])) / (1.0 + vel[0] / c);
const auto df_diff = 0.5 * (df[n][D2Q9_.S] - df[n][D2Q9_.N]);
for (auto &u : vel) u *= rho_node;
df[n][D2Q9_.W] = df[n][D2Q9_.E] - 2.0 * beta1_ * vel[0];
df[n][D2Q9_.NW] = df[n][D2Q9_.SE] + df_diff - beta3_ * vel[0] + beta2_ * vel[1];
df[n][D2Q9_.SW] = df[n][D2Q9_.NE] - df_diff - beta3_ * vel[0] - beta2_ * vel[1];
break;
}
case 1:
{ // top
auto vel = is_normal_flow_ ? field_.u[n - nx] : node.u_node;
const auto rho_node = (df[n][0] + df[n][D2Q9_.E] + df[n][D2Q9_.W] + 2.0 * (df[n][D2Q9_.N] +
df[n][D2Q9_.NE] + df[n][D2Q9_.NW])) / (1.0 + vel[1] / c);
const auto df_diff = 0.5 * (df[n][D2Q9_.E] - df[n][D2Q9_.W]);
for (auto &u : vel) u *= rho_node;
df[n][D2Q9_.S] = df[n][D2Q9_.N] - 2.0 * beta1_ * vel[1];
df[n][D2Q9_.SW] = df[n][D2Q9_.NE] + df_diff - beta2_ * vel[0] - beta3_ * vel[1];
df[n][D2Q9_.SE] = df[n][D2Q9_.NW] - df_diff + beta2_ * vel[0] - beta3_ * vel[1];
break;
}
case 2:
{ // left
auto vel = is_normal_flow_ ? field_.u[n + 1] : node.u_node;
const auto rho_node = (df[n][0] + df[n][D2Q9_.N] + df[n][D2Q9_.S] + 2.0 * (df[n][D2Q9_.W] +
df[n][D2Q9_.NW] + df[n][D2Q9_.SW])) / (1.0 - vel[0] / c);
const auto df_diff = 0.5 * (df[n][D2Q9_.S] - df[n][D2Q9_.N]);
for (auto &u : vel) u *= rho_node;
df[n][D2Q9_.E] = df[n][D2Q9_.W] + 2.0 * beta1_ * vel[0];
df[n][D2Q9_.NE] = df[n][D2Q9_.SW] + df_diff + beta3_ * vel[0] + beta2_ * vel[1];
df[n][D2Q9_.SE] = df[n][D2Q9_.NW] - df_diff + beta3_ * vel[0] - beta2_ * vel[1];
break;
}
case 3:
{ // bottom
auto vel = is_normal_flow_ ? field_.u[n + nx] : node.u_node;
const auto rho_node = (df[n][0] + df[n][D2Q9_.E] + df[n][D2Q9_.W] + 2.0 * (df[n][D2Q9_.S] +
df[n][D2Q9_.SW] + df[n][D2Q9_.SE])) / (1.0 - vel[1] / c);
const auto df_diff = 0.5 * (df[n][D2Q9_.W] - df[n][D2Q9_.E]);
for (auto &u : vel) u *= rho_node;
df[n][D2Q9_.N] = df[n][D2Q9_.S] + 2.0 * beta1_ * vel[1];
df[n][D2Q9_.NE] = df[n][D2Q9_.SW] + df_diff + beta2_ * vel[0] + beta3_ * vel[1];
df[n][D2Q9_.NW] = df[n][D2Q9_.SE] - df_diff - beta2_ * vel[0] + beta3_ * vel[1];
break;
}
default:
{
throw std::runtime_error("Not a side");
}
}
}
void ZouHeNode::updateCorner
(
std::vector<std::vector<double>> &df,
latticeNode &node
)
{
const auto n = node.n_node;
auto vel = node.u_node;
const auto nx = lb_.getNumberOfNx();
const auto nc = lb_.getNumberOfDirections();
switch (node.index_i)
{
case 0:
{ // bottom-left
auto rho_node = 0.5 * (cb_.rho_[n + nx] + cb_.rho_[n + 1]);
for (auto &u : vel) u *= rho_node;
df[n][D2Q9_.E] = df[n][D2Q9_.W] + 2.0 * beta1_ * vel[0];
df[n][D2Q9_.N] = df[n][D2Q9_.S] + 2.0 * beta1_ * vel[1];
df[n][D2Q9_.NE] = df[n][D2Q9_.SW] + 0.5 * beta1_ * vel[0] + 0.5 * beta1_ * vel[1];
df[n][D2Q9_.NW] = -0.5 * beta3_ * vel[0] + 0.5 * beta3_ * vel[1];
df[n][D2Q9_.SE] = 0.5 * beta3_ * vel[0] - 0.5 * beta3_ * vel[1];
for (auto i = 1u; i < nc; ++i) rho_node -= df[n][i];
df[n][0] = rho_node;
break;
}
case 1:
{ // bottom-right
auto rho_node = 0.5 * (cb_.rho_[n + nx] + cb_.rho_[n - 1]);
for (auto &u : vel) u *= rho_node;
df[n][D2Q9_.W] = df[n][D2Q9_.E] - 2.0 * beta1_ * vel[0];
df[n][D2Q9_.N] = df[n][D2Q9_.S] + 2.0 * beta1_ * vel[1];
df[n][D2Q9_.NW] = df[n][D2Q9_.SE] - 0.5 * beta1_ * vel[0] + 0.5 * beta1_ * vel[1];
df[n][D2Q9_.NE] = 0.5 * beta3_ * vel[0] + 0.5 * beta3_ * vel[1];
df[n][D2Q9_.SW] = -0.5 * beta3_ * vel[0] - 0.5 * beta3_ * vel[1];
for (auto i = 1u; i < nc; ++i) rho_node -= df[n][i];
df[n][0] = rho_node;
break;
}
case 2:
{ // top-left
auto rho_node = 0.5 * (cb_.rho_[n - nx] + cb_.rho_[n + 1]);
for (auto &u : vel) u *= rho_node;
df[n][D2Q9_.E] = df[n][D2Q9_.W] + 2.0 * beta1_ * vel[0];
df[n][D2Q9_.S] = df[n][D2Q9_.N] - 2.0 * beta1_ * vel[1];
df[n][D2Q9_.SE] = df[n][D2Q9_.NW] + 0.5 * beta1_ * vel[0] - 0.5 * beta1_ * vel[1];
df[n][D2Q9_.NE] = 0.5 * beta3_ * vel[0] + 0.5 * beta3_ * vel[1];
df[n][D2Q9_.SW] = -0.5 * beta3_ * vel[0] - 0.5 * beta3_ * vel[1];
for (auto i = 1u; i < nc; ++i) rho_node -= df[n][i];
df[n][0] = rho_node;
break;
}
case 3:
{ // top-right
auto rho_node = 0.5 * (cb_.rho_[n - nx] + cb_.rho_[n - 1]);
for (auto &u : vel) u *= rho_node;
df[n][D2Q9_.W] = df[n][D2Q9_.E] - 2.0 * beta1_ * vel[0];
df[n][D2Q9_.S] = df[n][D2Q9_.N] - 2.0 * beta1_ * vel[1];
df[n][D2Q9_.SW] = df[n][D2Q9_.NE] - 0.5 * beta1_ * vel[0] - 0.5 * beta1_ * vel[1];
df[n][D2Q9_.NW] = -0.5 * beta3_ * vel[0] + 0.5 * beta3_ * vel[1];
df[n][D2Q9_.SE] = 0.5 * beta3_ * vel[0] - 0.5 * beta3_ * vel[1];
for (auto i = 1u; i < nc; ++i) rho_node -= df[n][i];
df[n][0] = rho_node;
break;
}
default:
{
throw std::runtime_error("Not a corner");
}
}
}
void ZouHeNode::toggleNormalFlow()
{
is_normal_flow_ = true;
}
| Java |
package net.minecraft.server;
import java.io.IOException;
public class PacketPlayOutEntityHeadRotation implements Packet<PacketListenerPlayOut> {
private int a;
private byte b;
public PacketPlayOutEntityHeadRotation() {}
public PacketPlayOutEntityHeadRotation(Entity entity, byte b0) {
this.a = entity.getId();
this.b = b0;
}
public void a(PacketDataSerializer packetdataserializer) throws IOException {
this.a = packetdataserializer.g();
this.b = packetdataserializer.readByte();
}
public void b(PacketDataSerializer packetdataserializer) throws IOException {
packetdataserializer.d(this.a);
packetdataserializer.writeByte(this.b);
}
public void a(PacketListenerPlayOut packetlistenerplayout) {
packetlistenerplayout.a(this);
}
}
| Java |
@{
# Script module or binary module file associated with this manifest.
ModuleToProcess = 'AntivirusBypass.psm1'
# Version number of this module.
ModuleVersion = '3.0.0.0'
# ID used to uniquely identify this module
GUID = '7cf9de61-2bfc-41b4-a397-9d7cf3a8e66b'
# Author of this module
Author = 'Matthew Graeber'
# Copyright statement for this module
Copyright = 'BSD 3-Clause'
# Description of the functionality provided by this module
Description = 'PowerSploit Antivirus Avoidance/Bypass Module'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '2.0'
# Functions to export from this module
FunctionsToExport = '*'
# List of all files packaged with this module
FileList = 'AntivirusBypass.psm1', 'AntivirusBypass.psd1', 'Find-AVSignature.ps1', 'Usage.md'
}
| Java |
@charset "utf-8";
/* CSS Document */
*{margin:0;padding:0;}
ul{list-style:none;}
a{text-decoration:none;}
img,input,textarea{border:none;}
.clear{clear:both;}
::-moz-selection{background:#41EC49;}
::selection{background:#41EC49;}
@font-face{
font-family:ziti;
src:url(../fonts/Munro.eot),url(../fonts/Munro.otf),url(../fonts/Munro.svg),url(../fonts/Munro.ttf),url(../fonts/Munro.woff);
}
@keyframes sunny{
0%{text-shadow:0 0 0 #fff;}
25%{text-shadow:0 0 10px rgba(255,255,255,1);}
50%{text-shadow:0 0 10px rgba(255,255,255,1),0 0 20px rgba(255,255,255,1);}
75%{text-shadow:0 0 10px rgba(255,255,255,1);}
100%{text-shadow:0 0 0 #fff;}
}
.inner{width:1000px;margin:0 auto;}
header{width:100%;background-color:#e5e5e5;}
header .logo{float:left;font-family:ziti;color:#49879e;font-size:37px;line-height:101px;padding-top:9px;}
header i{margin-right:21px;}
header .nav{float:right;padding-top:36px;}
.one{background-image:linear-gradient(45deg,#9dc66a 5%,#4fa59a 30%,#4361c3);}
.one .inner{text-align:center;padding:100px 0;}
.one .icon i{font-size:80px;color:#fff;animation:sunny 5s infinite linear;}
.one h1{font:36px/60px arial;color:#fff;padding-bottom:14px;}
.one h1 span{font-weight:bolder;}
.one h1 a{color:#fff;border-bottom:1px dotted #fff;position:relative;}
.one h1 a:before{content:"";color:#fff;border-bottom:1px dotted #fff;position:absolute;width:100%;top:100%;left:0;opacity:0;transition:all 0.7s;}
.one h1 a:hover:before{top:0;left:0;opacity:1;}
.one p{padding-bottom:33px;font:18px/40px arial;color:#fff;}
.one .btn a{display:inline-block;width:175px;height:50px;border:1px solid #fff;line-height:50px;font-size:21px;color:#fff;border-radius:4px;text-transform:uppercase;position:relative;transition:all 1s;}
.one .btn a:after{content:"";background-color:#fff;width:1px;height:100px;position:absolute;top:51px;left:50%;}
.one .btn a:hover{padding:0 30px;background-color:rgba(255,255,255,.5);}
.two{background-color:#eaf9fe;padding:104px 0 127px 0;}
.two .icon_list{float:left;width:500px;}
.two .icon_list li{display:inline-block;border:1px solid #6e98ae;border-radius:4px;margin:40px;transform:rotate(45deg);overflow:hidden;transition:all 0.7s;}
.two .icon_list li:hover{background-color:#31D7D4;}
.two .icon_list li a{display:inline-block;width:140px;height:140px;text-align:center;line-height:140px;font-size:60px;transform:rotate(-45deg);transition:all 0.7s;}
.two .icon_list li:nth-child(1) a{color:#c3e6a2;}
.two .icon_list li:nth-child(1):hover a{transform:rotate(-45deg) scale(1.8);}
.two .icon_list li:nth-child(2) a{color:#86d9ab;}
.two .icon_list li:nth-child(2):hover a{transform:rotate(315deg);}
.two .icon_list li:nth-child(3) a{color:#6cd4c9;}
.two .icon_list li:nth-child(3):hover a{transform:rotate(-45deg) skewX(45deg);}
.two .icon_list li:nth-child(4) a{color:#5fb3d8;}
.two .icon_list li:nth-child(4):hover a{transform:rotate(180deg) scale(1.8)}
.two .icon_list li:nth-child(5) a{color:#4e84ce;}
.two .icon_list li:nth-child(5):hover a{transform:rotate(-45deg) scale(0.5);}
.two .icon_list li:nth-child(6) a{color:#6c87f0;}
.two .icon_list li:nth-child(6):hover a{transform:rotate(-45deg) translateY(-20px);}
.two .icon_list li a:hover i{color:#fff;text-shadow:0 0 10px #fff;}
.two .text{float:right;width:500px;}
.two .text h2{font:30px/52px arial;font-weight:bolder;color:#45899c;position:relative;padding-bottom:57px;}
.two .text h2:after{content:"";width:160px;height:1px;background-color:#4984a2;position:absolute;top:130px;left:0;}
.two .text p{font:15px/32px arial;padding-top:31px;}
footer{background-image:linear-gradient(45deg,#9dc66a 5%,#4fa59a 30%,#4361c3);padding:51px 0;text-align:center;}
footer .icon ul li{display:inline-block;transition:all 0.7s;}
footer .icon ul li:nth-child(1):hover{transform:scale(1.8);}
footer .icon ul li:nth-child(2):hover{transform:scale(1.8) rotate(360deg);}
footer .icon ul li:nth-child(3):hover{transform:scale(0.8) skewX(45deg);}
footer .icon ul li:nth-child(4):hover{transform:scale(1.8) translateY(-20px);}
footer .icon ul li:nth-child(5):hover{transform:scale(0.8) translateY(20px);}
footer i{padding:0 14px 21px 14px;color:#fff;font-size:20px !important;}
footer p{font:16px/23px "宋体";color:#00000d;}
footer span{font:13px/16px arial;color:#1a0000;}
footer span a{color:#551b93;border-bottom:1px solid #551b93;} | Java |
package cmake.icons;
import com.intellij.openapi.util.IconLoader;
import javax.swing.*;
/**
* Created by alex on 12/21/14.
*/
public class CMakeIcons {
public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png");
public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png");
public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg");
public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png");
}
| Java |
# Initialise
#
# Load lib functions if not already loaded
unless($_SHARED{lib}) {
spi_exec_query("select lib()");
}
my $lib = $_SHARED{lib};
$lib->{clear_cache}();
| Java |
/*
* Cantata
*
* Copyright (c) 2011-2013 Craig Drummond <craig.p.drummond@gmail.com>
*
* ----
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "umsdevice.h"
#include "utils.h"
#include "devicepropertiesdialog.h"
#include "devicepropertieswidget.h"
#include "actiondialog.h"
#include "localize.h"
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QTextStream>
static const QLatin1String constSettingsFile("/.is_audio_player");
static const QLatin1String constMusicFolderKey("audio_folder");
UmsDevice::UmsDevice(MusicModel *m, Solid::Device &dev)
: FsDevice(m, dev)
, access(dev.as<Solid::StorageAccess>())
{
spaceInfo.setPath(access->filePath());
setup();
}
UmsDevice::~UmsDevice()
{
}
void UmsDevice::connectionStateChanged()
{
if (isConnected()) {
spaceInfo.setPath(access->filePath());
setup();
if (opts.autoScan || scanned){ // Only scan if we are set to auto scan, or we have already scanned before...
rescan(false); // Read from cache if we have it!
} else {
setStatusMessage(i18n("Not Scanned"));
}
} else {
clear();
}
}
void UmsDevice::toggle()
{
if (solidDev.isValid() && access && access->isValid()) {
if (access->isAccessible()) {
if (scanner) {
scanner->stop();
}
access->teardown();
} else {
access->setup();
}
}
}
bool UmsDevice::isConnected() const
{
return solidDev.isValid() && access && access->isValid() && access->isAccessible();
}
double UmsDevice::usedCapacity()
{
if (cacheProgress>-1) {
return (cacheProgress*1.0)/100.0;
}
if (!isConnected()) {
return -1.0;
}
return spaceInfo.size()>0 ? (spaceInfo.used()*1.0)/(spaceInfo.size()*1.0) : -1.0;
}
QString UmsDevice::capacityString()
{
if (cacheProgress>-1) {
return statusMessage();
}
if (!isConnected()) {
return i18n("Not Connected");
}
return i18n("%1 free", Utils::formatByteSize(spaceInfo.size()-spaceInfo.used()));
}
qint64 UmsDevice::freeSpace()
{
if (!isConnected()) {
return 0;
}
return spaceInfo.size()-spaceInfo.used();
}
void UmsDevice::setup()
{
if (!isConnected()) {
return;
}
QString path=spaceInfo.path();
audioFolder = path;
QFile file(path+constSettingsFile);
QString audioFolderSetting;
opts=DeviceOptions();
if (file.open(QIODevice::ReadOnly|QIODevice::Text)) {
configured=true;
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
if (line.startsWith(constMusicFolderKey+"=")) {
audioFolderSetting=audioFolder=Utils::cleanPath(path+'/'+line.section('=', 1, 1));
if (!QDir(audioFolder).exists()) {
audioFolder = path;
}
} else if (line.startsWith(constMusicFilenameSchemeKey+"=")) {
QString scheme = line.section('=', 1, 1);
//protect against empty setting.
if( !scheme.isEmpty() ) {
opts.scheme = scheme;
}
} else if (line.startsWith(constVfatSafeKey+"=")) {
opts.vfatSafe = QLatin1String("true")==line.section('=', 1, 1);
} else if (line.startsWith(constAsciiOnlyKey+"=")) {
opts.asciiOnly = QLatin1String("true")==line.section('=', 1, 1);
} else if (line.startsWith(constIgnoreTheKey+"=")) {
opts.ignoreThe = QLatin1String("true")==line.section('=', 1, 1);
} else if (line.startsWith(constReplaceSpacesKey+"=")) {
opts.replaceSpaces = QLatin1String("true")==line.section('=', 1, 1);
} else {
unusedParams+=line;
}
}
}
bool haveOpts=FsDevice::readOpts(path+constCantataSettingsFile, opts, false);
if (!configured) {
configured=haveOpts;
}
if (opts.coverName.isEmpty()) {
opts.coverName=constDefCoverFileName;
}
// No setting, see if any standard dirs exist in path...
if (audioFolderSetting.isEmpty() || audioFolderSetting!=audioFolder) {
QStringList dirs;
dirs << QLatin1String("Music") << QLatin1String("MUSIC")
<< QLatin1String("Albums") << QLatin1String("ALBUMS");
foreach (const QString &d, dirs) {
if (QDir(path+d).exists()) {
audioFolder=path+d;
break;
}
}
}
if (!audioFolder.endsWith('/')) {
audioFolder+='/';
}
if (opts.autoScan || scanned){ // Only scan if we are set to auto scan, or we have already scanned before...
rescan(false); // Read from cache if we have it!
} else {
setStatusMessage(i18n("Not Scanned"));
}
}
void UmsDevice::configure(QWidget *parent)
{
if (!isIdle()) {
return;
}
DevicePropertiesDialog *dlg=new DevicePropertiesDialog(parent);
connect(dlg, SIGNAL(updatedSettings(const QString &, const DeviceOptions &)), SLOT(saveProperties(const QString &, const DeviceOptions &)));
if (!configured) {
connect(dlg, SIGNAL(cancelled()), SLOT(saveProperties()));
}
dlg->show(audioFolder, opts,
qobject_cast<ActionDialog *>(parent) ? (DevicePropertiesWidget::Prop_All-DevicePropertiesWidget::Prop_Folder)
: DevicePropertiesWidget::Prop_All);
}
void UmsDevice::saveProperties()
{
saveProperties(audioFolder, opts);
}
static inline QString toString(bool b)
{
return b ? QLatin1String("true") : QLatin1String("false");
}
void UmsDevice::saveOptions()
{
if (!isConnected()) {
return;
}
QString path=spaceInfo.path();
QFile file(path+constSettingsFile);
QString fixedPath(audioFolder);
if (fixedPath.startsWith(path)) {
fixedPath=QLatin1String("./")+fixedPath.mid(path.length());
}
DeviceOptions def;
if (file.open(QIODevice::WriteOnly|QIODevice::Text)) {
QTextStream out(&file);
if (!fixedPath.isEmpty()) {
out << constMusicFolderKey << '=' << fixedPath << '\n';
}
if (opts.scheme!=def.scheme) {
out << constMusicFilenameSchemeKey << '=' << opts.scheme << '\n';
}
if (opts.scheme!=def.scheme) {
out << constVfatSafeKey << '=' << toString(opts.vfatSafe) << '\n';
}
if (opts.asciiOnly!=def.asciiOnly) {
out << constAsciiOnlyKey << '=' << toString(opts.asciiOnly) << '\n';
}
if (opts.ignoreThe!=def.ignoreThe) {
out << constIgnoreTheKey << '=' << toString(opts.ignoreThe) << '\n';
}
if (opts.replaceSpaces!=def.replaceSpaces) {
out << constReplaceSpacesKey << '=' << toString(opts.replaceSpaces) << '\n';
}
foreach (const QString &u, unusedParams) {
out << u << '\n';
}
}
}
void UmsDevice::saveProperties(const QString &newPath, const DeviceOptions &newOpts)
{
QString nPath=Utils::fixPath(newPath);
if (configured && opts==newOpts && nPath==audioFolder) {
return;
}
configured=true;
bool diffCacheSettings=opts.useCache!=newOpts.useCache;
opts=newOpts;
if (diffCacheSettings) {
if (opts.useCache) {
saveCache();
} else {
removeCache();
}
}
emit configurationChanged();
QString oldPath=audioFolder;
if (!isConnected()) {
return;
}
audioFolder=nPath;
saveOptions();
FsDevice::writeOpts(spaceInfo.path()+constCantataSettingsFile, opts, false);
if (oldPath!=audioFolder) {
rescan(); // Path changed, so we can ignore cache...
}
}
| Java |
HostCMS 6.7 = 9fdd2118a94f53ca1c411a7629edf565
| Java |
def _setup_pkgresources():
import pkg_resources
import os
import plistlib
pl = plistlib.readPlist(os.path.join(
os.path.dirname(os.getenv('RESOURCEPATH')), "Info.plist"))
appname = pl.get('CFBundleIdentifier')
if appname is None:
appname = pl['CFBundleDisplayName']
path = os.path.expanduser('~/Library/Caches/%s/python-eggs' % (appname,))
pkg_resources.set_extraction_path(path)
_setup_pkgresources()
| Java |
<?php
/**
* Kunena Plugin
* @package Kunena.Plugins
* @subpackage Joomla16
*
* @Copyright (C) 2008 - 2012 Kunena Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @link http://www.kunena.org
**/
defined ( '_JEXEC' ) or die ();
class plgKunenaJoomla extends JPlugin {
public function __construct(&$subject, $config) {
// Do not load if Kunena version is not supported or Kunena is offline
if (!(class_exists('KunenaForum') && KunenaForum::isCompatible('2.0') && KunenaForum::installed())) return;
parent::__construct ( $subject, $config );
$this->loadLanguage ( 'plg_kunena_joomla.sys', JPATH_ADMINISTRATOR ) || $this->loadLanguage ( 'plg_kunena_joomla.sys', KPATH_ADMIN );
$this->path = dirname ( __FILE__ );
}
/*
* Get Kunena access control object.
*
* @return KunenaAccess
*/
public function onKunenaGetAccessControl() {
if (!$this->params->get('access', 1)) return;
require_once "{$this->path}/access.php";
return new KunenaAccessJoomla($this->params);
}
/*
* Get Kunena login integration object.
*
* @return KunenaLogin
*/
public function onKunenaGetLogin() {
if (!$this->params->get('login', 1)) return;
require_once "{$this->path}/login.php";
return new KunenaLoginJoomla($this->params);
}
}
| Java |
#!/bin/bash
#change to develop branch
git checkout develop
#create new branch from develop
git checkout -b feature/dummy
git add dummy.py
git commit -m"added dummy.py"
#push to remote
git push -u origin feature/dummy
#after that is sufficient
git push | Java |
#include "gremlin.h"
void cs_kroneckerIupdate(const cs *A, int nI, const cs *C){
int i, j, k, cnt, an, am;
double *Ax;
an = A->n;
am = A->m;
Ax = A->x;
cnt = 0;
for(i = 0; i < an; i++){
for(j = 0 ; j < nI ; j++){
for(k = 0; k < am; k++){
C->x[cnt] = Ax[i*an+k];
cnt++;
}
}
}
}
| Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<style>
table.head, table.foot { width: 100%; }
td.head-rtitle, td.foot-os { text-align: right; }
td.head-vol { text-align: center; }
table.foot td { width: 50%; }
table.head td { width: 33%; }
div.spacer { margin: 1em 0; }
</style>
<title>
PTHREAD_CONDATTR_SETPSHARED(3P)</title>
</head>
<body>
<div class="mandoc">
<table class="head">
<tbody>
<tr>
<td class="head-ltitle">
PTHREAD_CONDATTR_SETPSHARED(3P)</td>
<td class="head-vol">
POSIX Programmer's Manual</td>
<td class="head-rtitle">
PTHREAD_CONDATTR_SETPSHARED(3P)</td>
</tr>
</tbody>
</table>
<div class="section">
<h1>PROLOG</h1> This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.<div style="height: 1.00em;">
 </div>
</div>
<div class="section">
<h1>NAME</h1> pthread_condattr_setpshared — set the process-shared condition variable attribute</div>
<div class="section">
<h1>SYNOPSIS</h1><br/>
#include <pthread.h><div class="spacer">
</div>
int pthread_condattr_setpshared(pthread_condattr_t *<i>attr</i>,<br/>
int <i>pshared</i>);<br/>
</div>
<div class="section">
<h1>DESCRIPTION</h1> Refer to <i><i>pthread_condattr_getpshared</i>()</i>.</div>
<div class="section">
<h1>COPYRIGHT</h1> Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2013 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, Copyright (C) 2013 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. (This is POSIX.1-2008 with the 2013 Technical Corrigendum 1 applied.) In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.unix.org/online.html .<div style="height: 1.00em;">
 </div>
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .</div>
<table class="foot">
<tr>
<td class="foot-date">
2013</td>
<td class="foot-os">
IEEE/The Open Group</td>
</tr>
</table>
</div>
</body>
</html>
| Java |
<?php
/**
* Automatically loads the specified file.
*
* @package PluginName\Lib
*/
namespace PluginName\Lib;
/**
* Automatically loads the specified file.
*
* Examines the fully qualified class name, separates it into components, then creates
* a string that represents where the file is loaded on disk.
*
* @package PluginName\Lib
*/
spl_autoload_register( function ( $filename ) {
// First, separate the components of the incoming file.
$file_path = explode( '\\', $filename );
/**
* - The first index will always be WCATL since it's part of the plugin.
* - All but the last index will be the path to the file.
*/
// Get the last index of the array. This is the class we're loading.
if ( isset( $file_path[ count( $file_path ) - 1 ] ) ) {
$class_file = strtolower(
$file_path[ count( $file_path ) - 1 ]
);
// The classname has an underscore, so we need to replace it with a hyphen for the file name.
$class_file = str_ireplace( '_', '-', $class_file );
$class_file = "class-$class_file.php";
}
/**
* Find the fully qualified path to the class file by iterating through the $file_path array.
* We ignore the first index since it's always the top-level package. The last index is always
* the file so we append that at the end.
*/
$fully_qualified_path = trailingslashit(
dirname(
dirname( __FILE__ )
)
);
for ( $i = 1; $i < count( $file_path ) - 1; $i++ ) {
$dir = strtolower( $file_path[ $i ] );
$fully_qualified_path .= trailingslashit( $dir );
}
$fully_qualified_path .= $class_file;
// Now we include the file.
if ( file_exists( $fully_qualified_path ) ) {
include_once( $fully_qualified_path );
}
}); | Java |
-----------------------------------
-- Area: Cloister of Storms
-- BCNM: Trial by Lightning
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
local ID = require("scripts/zones/Cloister_of_Storms/IDs");
-----------------------------------
-- What should go here:
-- giving key items, playing ENDING cutscenes
--
-- What should NOT go here:
-- Handling of "battlefield" status, spawning of monsters,
-- putting loot into treasure pool,
-- enforcing ANY rules (SJ/number of people/etc), moving
-- chars around, playing entrance CSes (entrance CSes go in bcnm.lua)
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
trialLightning = player:getQuestStatus(OTHER_AREAS_LOG,TRIAL_BY_LIGHTNING)
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (trialLightning == QUEST_COMPLETED) then
player:startEvent(32001,1,1,1,instance:getTimeInside(),1,0,1);
else
player:startEvent(32001,1,1,1,instance:getTimeInside(),1,0,0);
end
elseif (leavecode == 4) then
player:startEvent(32002);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if (csid == 32001) then
player:delKeyItem(dsp.ki.TUNING_FORK_OF_LIGHTNING);
player:addKeyItem(dsp.ki.WHISPER_OF_STORMS);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.WHISPER_OF_STORMS);
end
end;
| Java |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Iterating Over the Matches Within An MFC String</title>
<link rel="stylesheet" href="../../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.74.0">
<link rel="home" href="../../../../index.html" title="Boost.Regex">
<link rel="up" href="../mfc_strings.html" title="Using Boost Regex With MFC Strings">
<link rel="prev" href="mfc_algo.html" title="Overloaded Algorithms For MFC String Types">
<link rel="next" href="../../posix.html" title="POSIX Compatible C API's">
</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="../../../../../../../../libs/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="mfc_algo.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../mfc_strings.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="../../posix.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section" lang="en">
<div class="titlepage"><div><div><h5 class="title">
<a name="boost_regex.ref.non_std_strings.mfc_strings.mfc_iter"></a><a class="link" href="mfc_iter.html" title="Iterating Over the Matches Within An MFC String">Iterating
Over the Matches Within An MFC String</a>
</h5></div></div></div>
<p>
The following helper functions are provided to ease the conversion from
an MFC/ATL string to a <a class="link" href="../../regex_iterator.html" title="regex_iterator"><code class="computeroutput"><span class="identifier">regex_iterator</span></code></a> or <a class="link" href="../../regex_token_iterator.html" title="regex_token_iterator"><code class="computeroutput"><span class="identifier">regex_token_iterator</span></code></a>:
</p>
<a name="boost_regex.ref.non_std_strings.mfc_strings.mfc_iter.regex_iterator_creation_helper"></a><h5>
<a name="id1108946"></a>
<a class="link" href="mfc_iter.html#boost_regex.ref.non_std_strings.mfc_strings.mfc_iter.regex_iterator_creation_helper">regex_iterator
creation helper</a>
</h5>
<pre class="programlisting"><span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">charT</span><span class="special">></span>
<span class="identifier">regex_iterator</span><span class="special"><</span><span class="identifier">charT</span> <span class="keyword">const</span><span class="special">*></span>
<span class="identifier">make_regex_iterator</span><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">ATL</span><span class="special">::</span><span class="identifier">CSimpleStringT</span><span class="special"><</span><span class="identifier">charT</span><span class="special">>&</span> <span class="identifier">s</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">basic_regex</span><span class="special"><</span><span class="identifier">charT</span><span class="special">>&</span> <span class="identifier">e</span><span class="special">,</span>
<span class="special">::</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">regex_constants</span><span class="special">::</span><span class="identifier">match_flag_type</span> <span class="identifier">f</span> <span class="special">=</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">regex_constants</span><span class="special">::</span><span class="identifier">match_default</span><span class="special">);</span>
</pre>
<p>
<span class="bold"><strong>Effects</strong></span>: returns <code class="computeroutput"><span class="identifier">regex_iterator</span><span class="special">(</span><span class="identifier">s</span><span class="special">.</span><span class="identifier">GetString</span><span class="special">(),</span> <span class="identifier">s</span><span class="special">.</span><span class="identifier">GetString</span><span class="special">()</span> <span class="special">+</span> <span class="identifier">s</span><span class="special">.</span><span class="identifier">GetLength</span><span class="special">(),</span>
<span class="identifier">e</span><span class="special">,</span>
<span class="identifier">f</span><span class="special">);</span></code>
</p>
<p>
<span class="bold"><strong>Example</strong></span>:
</p>
<pre class="programlisting"><span class="keyword">void</span> <span class="identifier">enumerate_links</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">CString</span><span class="special">&</span> <span class="identifier">html</span><span class="special">)</span>
<span class="special">{</span>
<span class="comment">// enumerate and print all the links in some HTML text,
</span> <span class="comment">// the expression used is by Andew Lee on www.regxlib.com:
</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">tregex</span> <span class="identifier">r</span><span class="special">(</span>
<span class="identifier">__T</span><span class="special">(</span><span class="string">"href=[\"\']((http:\\/\\/|\\.\\/|\\/)?\\w+"</span>
<span class="string">"(\\.\\w+)*(\\/\\w+(\\.\\w+)?)*"</span>
<span class="string">"(\\/|\\?\\w*=\\w*(&\\w*=\\w*)*)?)[\"\']"</span><span class="special">));</span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">tregex_iterator</span> <span class="identifier">i</span><span class="special">(</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">make_regex_iterator</span><span class="special">(</span><span class="identifier">html</span><span class="special">,</span> <span class="identifier">r</span><span class="special">)),</span> <span class="identifier">j</span><span class="special">;</span>
<span class="keyword">while</span><span class="special">(</span><span class="identifier">i</span> <span class="special">!=</span> <span class="identifier">j</span><span class="special">)</span>
<span class="special">{</span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">cout</span> <span class="special"><<</span> <span class="special">(*</span><span class="identifier">i</span><span class="special">)[</span><span class="number">1</span><span class="special">]</span> <span class="special"><<</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">endl</span><span class="special">;</span>
<span class="special">++</span><span class="identifier">i</span><span class="special">;</span>
<span class="special">}</span>
<span class="special">}</span>
</pre>
<a name="boost_regex.ref.non_std_strings.mfc_strings.mfc_iter.regex_token_iterator_creation_helpers"></a><h5>
<a name="id1109494"></a>
<a class="link" href="mfc_iter.html#boost_regex.ref.non_std_strings.mfc_strings.mfc_iter.regex_token_iterator_creation_helpers">regex_token_iterator
creation helpers</a>
</h5>
<pre class="programlisting"><span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">charT</span><span class="special">></span>
<span class="identifier">regex_token_iterator</span><span class="special"><</span><span class="identifier">charT</span> <span class="keyword">const</span><span class="special">*></span>
<span class="identifier">make_regex_token_iterator</span><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">ATL</span><span class="special">::</span><span class="identifier">CSimpleStringT</span><span class="special"><</span><span class="identifier">charT</span><span class="special">>&</span> <span class="identifier">s</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">basic_regex</span><span class="special"><</span><span class="identifier">charT</span><span class="special">>&</span> <span class="identifier">e</span><span class="special">,</span>
<span class="keyword">int</span> <span class="identifier">sub</span> <span class="special">=</span> <span class="number">0</span><span class="special">,</span>
<span class="special">::</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">regex_constants</span><span class="special">::</span><span class="identifier">match_flag_type</span> <span class="identifier">f</span> <span class="special">=</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">regex_constants</span><span class="special">::</span><span class="identifier">match_default</span><span class="special">);</span>
</pre>
<p>
<span class="bold"><strong>Effects</strong></span>: returns <code class="computeroutput"><span class="identifier">regex_token_iterator</span><span class="special">(</span><span class="identifier">s</span><span class="special">.</span><span class="identifier">GetString</span><span class="special">(),</span> <span class="identifier">s</span><span class="special">.</span><span class="identifier">GetString</span><span class="special">()</span> <span class="special">+</span> <span class="identifier">s</span><span class="special">.</span><span class="identifier">GetLength</span><span class="special">(),</span>
<span class="identifier">e</span><span class="special">,</span>
<span class="identifier">sub</span><span class="special">,</span>
<span class="identifier">f</span><span class="special">);</span></code>
</p>
<pre class="programlisting"><span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">charT</span><span class="special">></span>
<span class="identifier">regex_token_iterator</span><span class="special"><</span><span class="identifier">charT</span> <span class="keyword">const</span><span class="special">*></span>
<span class="identifier">make_regex_token_iterator</span><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">ATL</span><span class="special">::</span><span class="identifier">CSimpleStringT</span><span class="special"><</span><span class="identifier">charT</span><span class="special">>&</span> <span class="identifier">s</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">basic_regex</span><span class="special"><</span><span class="identifier">charT</span><span class="special">>&</span> <span class="identifier">e</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">vector</span><span class="special"><</span><span class="keyword">int</span><span class="special">>&</span> <span class="identifier">subs</span><span class="special">,</span>
<span class="special">::</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">regex_constants</span><span class="special">::</span><span class="identifier">match_flag_type</span> <span class="identifier">f</span> <span class="special">=</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">regex_constants</span><span class="special">::</span><span class="identifier">match_default</span><span class="special">);</span>
</pre>
<p>
<span class="bold"><strong>Effects</strong></span>: returns <code class="computeroutput"><span class="identifier">regex_token_iterator</span><span class="special">(</span><span class="identifier">s</span><span class="special">.</span><span class="identifier">GetString</span><span class="special">(),</span> <span class="identifier">s</span><span class="special">.</span><span class="identifier">GetString</span><span class="special">()</span> <span class="special">+</span> <span class="identifier">s</span><span class="special">.</span><span class="identifier">GetLength</span><span class="special">(),</span>
<span class="identifier">e</span><span class="special">,</span>
<span class="identifier">subs</span><span class="special">,</span>
<span class="identifier">f</span><span class="special">);</span></code>
</p>
<pre class="programlisting"><span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">charT</span><span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <span class="identifier">N</span><span class="special">></span>
<span class="identifier">regex_token_iterator</span><span class="special"><</span><span class="identifier">charT</span> <span class="keyword">const</span><span class="special">*></span>
<span class="identifier">make_regex_token_iterator</span><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">ATL</span><span class="special">::</span><span class="identifier">CSimpleStringT</span><span class="special"><</span><span class="identifier">charT</span><span class="special">>&</span> <span class="identifier">s</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">basic_regex</span><span class="special"><</span><span class="identifier">charT</span><span class="special">>&</span> <span class="identifier">e</span><span class="special">,</span>
<span class="keyword">const</span> <span class="keyword">int</span> <span class="special">(&</span> <span class="identifier">subs</span><span class="special">)[</span><span class="identifier">N</span><span class="special">],</span>
<span class="special">::</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">regex_constants</span><span class="special">::</span><span class="identifier">match_flag_type</span> <span class="identifier">f</span> <span class="special">=</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">regex_constants</span><span class="special">::</span><span class="identifier">match_default</span><span class="special">);</span>
</pre>
<p>
<span class="bold"><strong>Effects</strong></span>: returns <code class="computeroutput"><span class="identifier">regex_token_iterator</span><span class="special">(</span><span class="identifier">s</span><span class="special">.</span><span class="identifier">GetString</span><span class="special">(),</span> <span class="identifier">s</span><span class="special">.</span><span class="identifier">GetString</span><span class="special">()</span> <span class="special">+</span> <span class="identifier">s</span><span class="special">.</span><span class="identifier">GetLength</span><span class="special">(),</span>
<span class="identifier">e</span><span class="special">,</span>
<span class="identifier">subs</span><span class="special">,</span>
<span class="identifier">f</span><span class="special">);</span></code>
</p>
<p>
<span class="bold"><strong>Example</strong></span>:
</p>
<pre class="programlisting"><span class="keyword">void</span> <span class="identifier">enumerate_links2</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">CString</span><span class="special">&</span> <span class="identifier">html</span><span class="special">)</span>
<span class="special">{</span>
<span class="comment">// enumerate and print all the links in some HTML text,
</span> <span class="comment">// the expression used is by Andew Lee on www.regxlib.com:
</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">tregex</span> <span class="identifier">r</span><span class="special">(</span>
<span class="identifier">__T</span><span class="special">(</span><span class="string">"href=[\"\']((http:\\/\\/|\\.\\/|\\/)?\\w+"</span>
<span class="string">"(\\.\\w+)*(\\/\\w+(\\.\\w+)?)*"</span>
<span class="string">"(\\/|\\?\\w*=\\w*(&\\w*=\\w*)*)?)[\"\']"</span><span class="special">));</span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">tregex_token_iterator</span> <span class="identifier">i</span><span class="special">(</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">make_regex_token_iterator</span><span class="special">(</span><span class="identifier">html</span><span class="special">,</span> <span class="identifier">r</span><span class="special">,</span> <span class="number">1</span><span class="special">)),</span> <span class="identifier">j</span><span class="special">;</span>
<span class="keyword">while</span><span class="special">(</span><span class="identifier">i</span> <span class="special">!=</span> <span class="identifier">j</span><span class="special">)</span>
<span class="special">{</span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">cout</span> <span class="special"><<</span> <span class="special">*</span><span class="identifier">i</span> <span class="special"><<</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">endl</span><span class="special">;</span>
<span class="special">++</span><span class="identifier">i</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 © 1998 -2010 John Maddock<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="mfc_algo.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../mfc_strings.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="../../posix.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| Java |
/*
Copyright (C) 2011 Equinor ASA, Norway.
The file 'rsh_driver.c' is part of ERT - Ensemble based Reservoir Tool.
ERT is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ERT is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
for more details.
*/
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netdb.h>
#include <pthread.h>
#include <errno.h>
#include <ert/util/util.hpp>
#include <ert/res_util/arg_pack.hpp>
#include <ert/job_queue/queue_driver.hpp>
#include <ert/job_queue/rsh_driver.hpp>
struct rsh_job_struct {
UTIL_TYPE_ID_DECLARATION;
bool active; /* Means that it allocated - not really in use */
job_status_type status;
pthread_t run_thread;
const char * host_name; /* Currently not set */
char * run_path;
};
typedef struct {
char * host_name;
int max_running; /* How many can the host handle. */
int running; /* How many are currently running on the host (goverened by this driver instance that is). */
pthread_mutex_t host_mutex;
} rsh_host_type;
#define RSH_DRIVER_TYPE_ID 44963256
#define RSH_JOB_TYPE_ID 63256701
struct rsh_driver_struct {
UTIL_TYPE_ID_DECLARATION;
pthread_mutex_t submit_lock;
pthread_attr_t thread_attr;
char * rsh_command;
int num_hosts;
int last_host_index;
rsh_host_type **host_list;
hash_type *__host_hash; /* Stupid redundancy ... */
};
/******************************************************************/
static UTIL_SAFE_CAST_FUNCTION_CONST( rsh_driver , RSH_DRIVER_TYPE_ID )
static UTIL_SAFE_CAST_FUNCTION( rsh_driver , RSH_DRIVER_TYPE_ID )
static UTIL_SAFE_CAST_FUNCTION( rsh_job , RSH_JOB_TYPE_ID )
/**
If the host is for some reason not available, NULL should be
returned. Will also return NULL if some funny guy tries to allocate
with max_running <= 0.
*/
static rsh_host_type * rsh_host_alloc(const char * host_name , int max_running) {
if (max_running > 0) {
struct addrinfo * result;
if (getaddrinfo(host_name , NULL , NULL , &result) == 0) {
rsh_host_type * host = (rsh_host_type*)util_malloc(sizeof * host );
host->host_name = util_alloc_string_copy(host_name);
host->max_running = max_running;
host->running = 0;
pthread_mutex_init( &host->host_mutex , NULL );
freeaddrinfo( result );
return host;
} else {
fprintf(stderr,"** Warning: could not locate server: %s \n",host_name);
return NULL;
}
} else
return NULL;
}
static void rsh_host_free(rsh_host_type * rsh_host) {
free(rsh_host->host_name);
free(rsh_host);
}
static bool rsh_host_available(rsh_host_type * rsh_host) {
bool available;
pthread_mutex_lock( &rsh_host->host_mutex );
{
available = false;
if ((rsh_host->max_running - rsh_host->running) > 0) { // The host has free slots()
available = true;
rsh_host->running++;
}
}
pthread_mutex_unlock( &rsh_host->host_mutex );
return available;
}
static void rsh_host_submit_job(rsh_host_type * rsh_host , rsh_job_type * job, const char * rsh_cmd , const char * submit_cmd , int num_cpu , int job_argc , const char ** job_argv) {
/*
Observe that this job has already been added to the running jobs
in the rsh_host_available function.
*/
int argc = job_argc + 2;
const char ** argv = (const char**)util_malloc( argc * sizeof * argv );
argv[0] = rsh_host->host_name;
argv[1] = submit_cmd;
{
int iarg;
for (iarg = 0; iarg < job_argc; iarg++)
argv[iarg + 2] = job_argv[iarg];
}
util_spawn_blocking(rsh_cmd, argc, argv, NULL, NULL); /* This call is blocking. */
job->status = JOB_QUEUE_DONE;
pthread_mutex_lock( &rsh_host->host_mutex );
rsh_host->running--;
pthread_mutex_unlock( &rsh_host->host_mutex );
free( argv );
}
/*
static const char * rsh_host_get_hostname(const rsh_host_type * host) { return host->host_name; }
*/
static void * rsh_host_submit_job__(void * __arg_pack) {
arg_pack_type * arg_pack = arg_pack_safe_cast(__arg_pack);
char * rsh_cmd = (char *) arg_pack_iget_ptr(arg_pack , 0);
rsh_host_type * rsh_host = (rsh_host_type *)arg_pack_iget_ptr(arg_pack , 1);
char * submit_cmd = (char *) arg_pack_iget_ptr(arg_pack , 2);
int num_cpu = arg_pack_iget_int(arg_pack , 3);
int argc = arg_pack_iget_int(arg_pack , 4);
const char ** argv = (const char **) arg_pack_iget_ptr(arg_pack , 5);
rsh_job_type * job = (rsh_job_type*) arg_pack_iget_ptr(arg_pack , 6);
rsh_host_submit_job(rsh_host , job , rsh_cmd , submit_cmd , num_cpu , argc , argv);
pthread_exit( NULL );
arg_pack_free( arg_pack );
}
/*****************************************************************/
/*****************************************************************/
rsh_job_type * rsh_job_alloc(const char * run_path) {
rsh_job_type * job;
job = (rsh_job_type*)util_malloc(sizeof * job );
job->active = false;
job->status = JOB_QUEUE_WAITING;
job->run_path = util_alloc_string_copy(run_path);
UTIL_TYPE_ID_INIT( job , RSH_JOB_TYPE_ID );
return job;
}
void rsh_job_free(rsh_job_type * job) {
free(job->run_path);
free(job);
}
job_status_type rsh_driver_get_job_status(void * __driver , void * __job) {
if (__job == NULL)
/* The job has not been registered at all ... */
return JOB_QUEUE_NOT_ACTIVE;
else {
rsh_job_type * job = rsh_job_safe_cast( __job );
{
if (job->active == false) {
util_abort("%s: internal error - should not query status on inactive jobs \n" , __func__);
return JOB_QUEUE_NOT_ACTIVE; /* Dummy to shut up compiler */
} else
return job->status;
}
}
}
void rsh_driver_free_job( void * __job ) {
rsh_job_type * job = rsh_job_safe_cast( __job );
rsh_job_free(job);
}
void rsh_driver_kill_job(void * __driver ,void * __job) {
rsh_job_type * job = rsh_job_safe_cast( __job );
if (job->active)
pthread_cancel( job->run_thread );
rsh_job_free( job );
}
void * rsh_driver_submit_job(void * __driver,
const char * submit_cmd ,
int num_cpu , /* Ignored */
const char * run_path ,
const char * job_name ,
int argc,
const char ** argv ) {
rsh_driver_type * driver = rsh_driver_safe_cast( __driver );
rsh_job_type * job = NULL;
{
/*
command is freed in the start_routine() function
*/
pthread_mutex_lock( &driver->submit_lock );
{
rsh_host_type * host = NULL;
int ihost;
int host_index = 0;
if (driver->num_hosts == 0)
util_abort("%s: fatal error - no hosts added to the rsh driver.\n",__func__);
for (ihost = 0; ihost < driver->num_hosts; ihost++) {
host_index = (ihost + driver->last_host_index) % driver->num_hosts;
if (rsh_host_available(driver->host_list[host_index])) {
host = driver->host_list[host_index];
break;
}
}
driver->last_host_index = (host_index + 1) % driver->num_hosts;
if (host != NULL) {
/* A host is available */
arg_pack_type * arg_pack = arg_pack_alloc(); /* The arg_pack is freed() in the rsh_host_submit_job__() function.
freeing it here is dangerous, because we might free it before the
thread-called function is finished with it. */
job = rsh_job_alloc(run_path);
arg_pack_append_ptr(arg_pack , driver->rsh_command);
arg_pack_append_ptr(arg_pack , host);
arg_pack_append_ptr(arg_pack , (char *) submit_cmd);
arg_pack_append_int(arg_pack , num_cpu );
arg_pack_append_int(arg_pack , argc );
arg_pack_append_ptr(arg_pack , argv );
arg_pack_append_ptr(arg_pack , job);
{
int pthread_return_value = pthread_create( &job->run_thread , &driver->thread_attr , rsh_host_submit_job__ , arg_pack);
if (pthread_return_value != 0)
util_abort("%s failed to create thread ERROR:%d \n", __func__ , pthread_return_value);
}
job->status = JOB_QUEUE_RUNNING;
job->active = true;
}
}
pthread_mutex_unlock( &driver->submit_lock );
}
return job;
}
void rsh_driver_clear_host_list( rsh_driver_type * driver ) {
int ihost;
for (ihost =0; ihost < driver->num_hosts; ihost++)
rsh_host_free(driver->host_list[ihost]);
free(driver->host_list);
driver->num_hosts = 0;
driver->host_list = NULL;
driver->last_host_index = 0;
}
void rsh_driver_free(rsh_driver_type * driver) {
rsh_driver_clear_host_list( driver );
pthread_attr_destroy ( &driver->thread_attr );
free(driver->rsh_command );
hash_free( driver->__host_hash );
free(driver);
driver = NULL;
}
void rsh_driver_free__(void * __driver) {
rsh_driver_type * driver = rsh_driver_safe_cast( __driver );
rsh_driver_free( driver );
}
void rsh_driver_set_host_list( rsh_driver_type * rsh_driver , const hash_type * rsh_host_list) {
rsh_driver_clear_host_list( rsh_driver );
if (rsh_host_list != NULL) {
hash_iter_type * hash_iter = hash_iter_alloc( rsh_host_list );
while (!hash_iter_is_complete( hash_iter )) {
const char * host = hash_iter_get_next_key( hash_iter );
int max_running = hash_get_int( rsh_host_list , host );
rsh_driver_add_host(rsh_driver , host , max_running);
}
if (rsh_driver->num_hosts == 0)
util_abort("%s: failed to add any valid RSH hosts - aborting.\n",__func__);
}
}
/**
*/
void * rsh_driver_alloc( ) {
rsh_driver_type * rsh_driver = (rsh_driver_type*)util_malloc( sizeof * rsh_driver );
UTIL_TYPE_ID_INIT( rsh_driver , RSH_DRIVER_TYPE_ID );
pthread_mutex_init( &rsh_driver->submit_lock , NULL );
pthread_attr_init( &rsh_driver->thread_attr );
pthread_attr_setdetachstate( &rsh_driver->thread_attr , PTHREAD_CREATE_DETACHED );
/**
To simplify the Python wrapper it is possible to pass in NULL as
rsh_host_list pointer, and then subsequently add hosts with
rsh_driver_add_host().
*/
rsh_driver->num_hosts = 0;
rsh_driver->host_list = NULL;
rsh_driver->last_host_index = 0;
rsh_driver->rsh_command = NULL;
rsh_driver->__host_hash = hash_alloc();
return rsh_driver;
}
void rsh_driver_add_host(rsh_driver_type * rsh_driver , const char * hostname , int host_max_running) {
rsh_host_type * new_host = rsh_host_alloc(hostname , host_max_running); /* Could in principle update an existing node if the host name is old. */
if (new_host != NULL) {
rsh_driver->num_hosts++;
rsh_driver->host_list = (rsh_host_type**)util_realloc(rsh_driver->host_list , rsh_driver->num_hosts * sizeof * rsh_driver->host_list );
rsh_driver->host_list[(rsh_driver->num_hosts - 1)] = new_host;
}
}
/**
Hostname should be a string as host:max_running, the ":max_running"
part is optional, and will default to 1.
*/
void rsh_driver_add_host_from_string(rsh_driver_type * rsh_driver , const char * hostname) {
int host_max_running;
char ** tmp;
char * host;
int tokens;
util_split_string( hostname , ":" , &tokens , &tmp);
if (tokens > 1) {
if (!util_sscanf_int( tmp[tokens - 1] , &host_max_running))
util_abort("%s: failed to parse out integer from: %s \n",__func__ , hostname);
host = util_alloc_joined_string((const char **) tmp , tokens - 1 , ":");
} else
host = util_alloc_string_copy( tmp[0] );
rsh_driver_add_host( rsh_driver , host , host_max_running );
util_free_stringlist( tmp , tokens );
free( host );
}
bool rsh_driver_set_option( void * __driver , const char * option_key , const void * value_ ) {
const char * value = (const char*) value_;
rsh_driver_type * driver = rsh_driver_safe_cast( __driver );
bool has_option = true;
{
if (strcmp(RSH_HOST , option_key) == 0) /* Add one host - value should be hostname:max */
rsh_driver_add_host_from_string( driver , value );
else if (strcmp(RSH_HOSTLIST , option_key) == 0) { /* Set full host list - value should be hash of integers. */
if (value != NULL) {
const hash_type * hash_value = hash_safe_cast_const( value );
rsh_driver_set_host_list( driver , hash_value );
}
} else if (strcmp( RSH_CLEAR_HOSTLIST , option_key) == 0)
/* Value is not considered - this is an action, and not a _set operation. */
rsh_driver_set_host_list( driver , NULL );
else if (strcmp( RSH_CMD , option_key) == 0)
driver->rsh_command = util_realloc_string_copy( driver->rsh_command , value );
else
has_option = false;
}
return has_option;
}
const void * rsh_driver_get_option( const void * __driver , const char * option_key ) {
const rsh_driver_type * driver = rsh_driver_safe_cast_const( __driver );
{
if (strcmp( RSH_CMD , option_key ) == 0)
return driver->rsh_command;
else if (strcmp( RSH_HOSTLIST , option_key) == 0) {
int ihost;
hash_clear( driver->__host_hash );
for (ihost = 0; ihost < driver->num_hosts; ihost++) {
rsh_host_type * host = driver->host_list[ ihost ];
hash_insert_int( driver->__host_hash , host->host_name , host->max_running);
}
return driver->__host_hash;
} else {
util_abort("%s: get not implemented fro option_id:%s for rsh \n",__func__ , option_key );
return NULL;
}
}
}
void rsh_driver_init_option_list(stringlist_type * option_list) {
stringlist_append_copy(option_list, RSH_HOST);
stringlist_append_copy(option_list, RSH_HOSTLIST);
stringlist_append_copy(option_list, RSH_CMD);
stringlist_append_copy(option_list, RSH_CLEAR_HOSTLIST);
}
#undef RSH_JOB_ID
/*****************************************************************/
| Java |
# GeoCalle
Modelo socioespacial de la población sin hogar en el Centro Histórico
de la Ciudad de México.
[Página web del Repositorio](http://www.geocalle.org)
| Java |
require 'package'
class Harfbuzz < Package
description 'HarfBuzz is an OpenType text shaping engine.'
homepage 'https://www.freedesktop.org/wiki/Software/HarfBuzz/'
version '1.7.6-0'
source_url 'https://github.com/harfbuzz/harfbuzz/releases/download/1.7.6/harfbuzz-1.7.6.tar.bz2'
source_sha256 'da7bed39134826cd51e57c29f1dfbe342ccedb4f4773b1c951ff05ff383e2e9b'
binary_url ({
aarch64: 'https://dl.bintray.com/chromebrew/chromebrew/harfbuzz-1.7.6-0-chromeos-armv7l.tar.xz',
armv7l: 'https://dl.bintray.com/chromebrew/chromebrew/harfbuzz-1.7.6-0-chromeos-armv7l.tar.xz',
i686: 'https://dl.bintray.com/chromebrew/chromebrew/harfbuzz-1.7.6-0-chromeos-i686.tar.xz',
x86_64: 'https://dl.bintray.com/chromebrew/chromebrew/harfbuzz-1.7.6-0-chromeos-x86_64.tar.xz',
})
binary_sha256 ({
aarch64: 'd92567e640f2b847ff35d1dcb5e0fcabaa640cea8c709755a3fed8b1ed59a598',
armv7l: 'd92567e640f2b847ff35d1dcb5e0fcabaa640cea8c709755a3fed8b1ed59a598',
i686: '220ae1416d6fb21e9d5621d97c66e65dddd15eb63108fb4c5e3d5fe6c75e662a',
x86_64: '3dd360778d0ffbd12b23a9d1e2fe5d3031f8a93eb9f9618cd430dc91349bee7d',
})
depends_on 'glib'
depends_on 'icu4c'
depends_on 'freetype_sub'
def self.build
system "./configure --prefix=#{CREW_PREFIX} --libdir=#{CREW_LIB_PREFIX}"
system "make"
end
def self.install
system "pip install six"
system "make", "DESTDIR=#{CREW_DEST_DIR}", "install"
system "pip uninstall --yes six"
end
end
| Java |
---
title: "2017-09-14 Indentation"
date: 2017-09-13T20:38:45-05:00
tags:
- haskell
draft: false
description: Indentation matters. A lot.
---
Indentation is significant in Haskell. Haskell uses indentation to
group pieces of code together. This is similar to Python, but there
are "false cognates" - similar code that is indented differently in
the two languages. In Racket, grouping is done only by parentheses.
## Indenting to the same level
{{% notice tip %}} "All grouped expressions must be exactly aligned."
{{% /notice %}}
Example 1a: good indentation
```haskell
if x `mod` 3 == 0 &&
x `mod` 5 == 0 -- good. aligned with top x.
...
```
Example 1a: bad indentation
```haskell
if x `mod` 3 == 0 &&
x `mod` 5 == 0 -- wrong. not aligned with top x
...
```
## Indenting further
{{% notice warning %}} "Code which is part of some expression [must]
be indented further than the beginning of that expression.
{{% /notice %}}
### Not enough indentation
On one hand, this means that if you do not indent, you are not continuing
a preceding expression. Example 2:
```haskell
if x `mod` 3 == 0 &&
x `mod` 5 == 0
then -- wrong; needs to be indented further than the if
x
else -- wrong again
0
```
### Too much indentation
On the other hand, if you do indent, you may be
continuing something you wrote previously.
How could this be an issue? If you write one function and then indent a
later function, Haskell thinks you want the second function to be inside
the first function (as in, a "sub-function").
Example:
```haskell
main = do
putStrLn $ helper 5
-- all this space does not change anything... --
answer x = 200 * x
helper x = answer x + 1
```
Notice how `answer` is indented more than `main`? That makes the `answer`
function live inside of `main`... this will cause all sorts of
problems, but the first one is that `helper` cannot see `answer`
because `helper` cannot see anything inside of another function like
`main`.
The source for all quotes in this article is the [Haskell article on indentation][1].
Other example issues came from observations in class.
[1]: https://en.wikibooks.org/wiki/Haskell/Indentation
| Java |
package com.brejza.matt.habmodem;
import group.pals.android.lib.ui.filechooser.FileChooserActivity;
import group.pals.android.lib.ui.filechooser.io.localfile.LocalFile;
import java.io.File;
import java.util.List;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.view.Menu;
public class StartActivity extends Activity implements FirstRunMessage.NoticeDialogListener, MapFileMessage.NoticeDialogListener {
private static final int _ReqChooseFile = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_start, menu);
return true;
}
@Override
public void onResume()
{
super.onResume();
boolean firstrun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("firstrun1", false);
if (!firstrun){
FragmentManager fm = getFragmentManager();
FirstRunMessage di = new FirstRunMessage();
di.show(fm, "firstrun");
}
else
{
String mapst = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()).getString("pref_map_path", "");
File file = new File(mapst);
if(file.exists())
{
//start main activity
Intent intent = new Intent(this, Map_Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );
startActivity(intent);
finish();
}
else
{
FragmentManager fm = getFragmentManager();
MapFileMessage di = new MapFileMessage();
di.show(fm, "mapmessage");
}
}
}
@Override
public void onDialogPositiveClickFirstRun(DialogFragment dialog) {
// TODO Auto-generated method stub
getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.edit()
.putBoolean("firstrun1", true)
.commit();
FragmentManager fm = getFragmentManager();
MapFileMessage di = new MapFileMessage();
di.show(fm, "mapmessage");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case _ReqChooseFile:
if (resultCode == RESULT_OK) {
List<LocalFile> files = (List<LocalFile>)
data.getSerializableExtra(FileChooserActivity._Results);
for (File f : files)
{
PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()).edit().putString("pref_map_path", f.getPath()).commit();
System.out.println(f.toString());
}
}
break;
}
}
private void showMapChooser()
{
Intent intent = new Intent(StartActivity.this, FileChooserActivity.class);
intent.putExtra(FileChooserActivity._Rootpath, (Parcelable) new LocalFile(Environment.getExternalStorageDirectory().getPath() ));
intent.putExtra(FileChooserActivity._RegexFilenameFilter, "(?si).*\\.(map)$");
intent.putExtra(FileChooserActivity._Theme, android.R.style.Theme_Dialog);
startActivityForResult(intent, _ReqChooseFile);
}
@Override
public void onDialogNegativeClickFirstRun(DialogFragment dialog) {
// TODO Auto-generated method stub
this.finish();
}
@Override
public void onDialogPositiveClickMapHelp(DialogFragment dialog) {
// TODO Auto-generated method stub
showMapChooser();
}
@Override
public void onDialogNegativeClickMapHelp(DialogFragment dialog) {
// TODO Auto-generated method stub
Intent intent = new Intent(this, StatusScreen.class);
startActivity(intent);
}
}
| Java |
#!/usr/bin/env python
# sample module
from jira.client import JIRA
def main():
jira = JIRA()
JIRA(options={'server': 'http://localhost:8100'})
projects = jira.projects()
print projects
for project in projects:
print project.key
# Standard boilerplate to call the main() function.
if __name__ == '__main__':
main() | Java |
package ai.hellbound;
import l2s.commons.util.Rnd;
import l2s.gameserver.ai.CtrlEvent;
import l2s.gameserver.ai.Mystic;
import l2s.gameserver.model.Creature;
import l2s.gameserver.model.Playable;
import l2s.gameserver.model.World;
import l2s.gameserver.model.instances.NpcInstance;
import bosses.BelethManager;
/**
* @author pchayka
*/
public class Beleth extends Mystic
{
private long _lastFactionNotifyTime = 0;
private static final int CLONE = 29119;
public Beleth(NpcInstance actor)
{
super(actor);
}
@Override
protected void onEvtDead(Creature killer)
{
BelethManager.setBelethDead();
super.onEvtDead(killer);
}
@Override
protected void onEvtAttacked(Creature attacker, int damage)
{
NpcInstance actor = getActor();
if(System.currentTimeMillis() - _lastFactionNotifyTime > _minFactionNotifyInterval)
{
_lastFactionNotifyTime = System.currentTimeMillis();
for(NpcInstance npc : World.getAroundNpc(actor))
if(npc.getNpcId() == CLONE)
npc.getAI().notifyEvent(CtrlEvent.EVT_AGGRESSION, attacker, Rnd.get(1, 100));
}
super.onEvtAttacked(attacker, damage);
}
@Override
protected boolean randomWalk()
{
return false;
}
@Override
protected boolean randomAnimation()
{
return false;
}
@Override
public boolean canSeeInSilentMove(Playable target)
{
return true;
}
@Override
public boolean canSeeInHide(Playable target)
{
return true;
}
@Override
public void addTaskAttack(Creature target)
{
return;
}
} | Java |
#ifndef PHOTONS_PhaseSpace_Generate_Dipole_Photon_Angle_H
#define PHOTONS_PhaseSpace_Generate_Dipole_Photon_Angle_H
#include "ATOOLS/Math/Vector.H"
namespace PHOTONS {
class Generate_Dipole_Photon_Angle {
private:
double m_b1;
double m_b2;
double m_c;
double m_theta;
double m_phi;
ATOOLS::Vec4D m_dir;
double CalculateBeta(const ATOOLS::Vec4D&);
void GenerateDipoleAngle();
void GenerateNullVector();
public:
Generate_Dipole_Photon_Angle(ATOOLS::Vec4D, ATOOLS::Vec4D);
Generate_Dipole_Photon_Angle(const double&, const double&);
~Generate_Dipole_Photon_Angle();
inline double GetCosTheta() { return m_c; }
inline double GetTheta() { return m_theta; }
inline double GetPhi() { return m_phi; }
inline const ATOOLS::Vec4D& GetVector() { return m_dir; }
};
/*!
\file Generate_Dipole_Photon_Angle.H
\brief contains the class Generate_Dipole_Photon_Angle
*/
/*!
\class Generate_Dipole_Photon_Angle
\brief generates the photon angular distribution in dipoles
*/
////////////////////////////////////////////////////////////////////////////////////////////////////
// Description of the member variables for Generate_Dipole_Photon_Angle
////////////////////////////////////////////////////////////////////////////////////////////////////
/*!
\var double Generate_Dipole_Photon_Angle::m_b1
\brief \f$ \beta_1 \f$
*/
/*!
\var double Generate_Dipole_Photon_Angle::m_b2
\brief \f$ \beta_2 \f$
*/
/*!
\var double Generate_Dipole_Photon_Angle::m_c
\brief \f$ c = \cos\theta \f$
*/
/*!
\var double Generate_Dipole_Photon_Angle::m_theta
\brief \f$ \theta \f$
*/
/*!
\var double Generate_Dipole_Photon_Angle::m_phi
\brief \f$ \varphi \f$
*/
/*!
\var Vec4D Generate_Dipole_Photon_Angle::m_dir
\brief null vector of unit spatial length in direction \f$ (\theta,\varphi) \f$
*/
////////////////////////////////////////////////////////////////////////////////////////////////////
// Description of member methods for Generate_Dipole_Photon_Angle
////////////////////////////////////////////////////////////////////////////////////////////////////
/*!
\fn Generate_Dipole_Photon_Angle::Generate_Dipole_Photon_Angle(Vec4D, Vec4D)
\brief generates dipole angles for two arbitrary timelike 4-vectors \f$ p_1 \f$ and \f$ p_2 \f$
\f$ p_1 \f$ and \f$ p_2 \f$ are boosted in their CMS, there the photon angles are calculated and m_dir is generated. Finally, m_dir is boosted to the original system of \f$ p_1 \f$ and \f$ p_2 \f$ and \f$ \theta \f$ and \f$ \varphi \f$ are recalculated.
This constructor is used by the Generate_Multipole_Photon_Angle class.
*/
/*!
\fn Generate_Dipole_Photon_Angle::Generate_Dipole_Photon_Angle(double, double)
\brief generates dipole angles for two 4-vectors with \f$ \beta_1 \f$ and \f$ \beta_2 \f$ assumed to be in their CMS and aligned along the z-axis
Both angles are calculated via <tt>GenerateDipoleAngle()</tt>. No null vector will be produced.
This constructor is used by the Generate_One_Photon class.
*/
/*!
\fn double Generate_Dipole_Photon_Angle::CalculateBeta(Vec4D)
\brief calculates \f$ \beta \f$ for a given 4-vector
*/
/*!
\fn void Generate_Dipole_Photon_Angle::GenerateDipoleAngle()
\brief generates both photon angles
Works in the dipole's CMS. \f$ \varphi \f$ is distributed uniformly, \f$ \theta \f$ according to the eikonal factor \f$ \tilde{S}_{ij} \f$ .
*/
/*!
\fn void Generate_Dipole_Photon_Angle::GenerateNullVector()
\brief m_dir is generated
This null vector can be Poincare transformed to any frame to have the photon angular configuration there. To get the full photon its energy/3-momentum simply has to be multiplied by the generated energy.
*/
/*!
\fn double Generate_Dipole_Photon_Angle::GetCosTheta()
\brief returns m_c ( \f$ c = \cos\theta \f$ )
*/
/*!
\fn double Generate_Dipole_Photon_Angle::GetTheta()
\brief returns m_theta ( \f$ \theta \f$ )
*/
/*!
\fn double Generate_Dipole_Photon_Angle::GetPhi()
\brief returns m_phi ( \f$ \varphi \f$ )
*/
/*!
\fn Vec4D Generate_Dipole_Photon_Angle::GetVector()
\brief returns m_dir
*/
}
// this class will take two four vectors and generate a null vector of unit 3D length which is distributed according to eikonal factor
// if two doubles (b1,b2) are given it assumed they are in their respective rest frame and then this vector is generated in that frame
#endif
| Java |
package be.ipl.mobile.projet.historypub;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | Java |
/**********************************************************
* Filename: MDBRow.cpp
* Text Encoding: utf-8
*
* Description:
*
*
* Author: moxichang (ishego@gmail.com)
* Harbin Engineering University
* Information Security Research Center
*
*********************************************************/
#include "Exception.h"
#include "MDB/MDBRow.h"
MDB::MDBRow:: MDBRow(MDBField** fields_, int numcols_ )
: field_m(fields_), numcols_m(numcols_)
{
}
MDB::MDBRow:: ~MDBRow()
{
for(int i=0; i< numcols_m; i++)
{
delete field_m[i];
}
delete [] field_m;
}
MDB::MDBField& MDB::MDBRow:: operator [] (int index_)
{
if(index_ >= numcols_m || index_ < 0)
{
Throw("Row index out of range", MException::ME_OUTRANGE);
}
return **(field_m + index_);
}
| 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("Model")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Model")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("4d2c65ee-e3a3-41f0-aeef-4b412134fa25")]
// 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 |
//
// Copyright (c) 2008-2018 the Urho3D project.
//
// 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.
//
#pragma once
#include "../../Graphics/ShaderProgram.h"
#include "../../Graphics/VertexDeclaration.h"
#include "../../Math/Color.h"
#include <d3d9.h>
namespace Urho3D
{
#define URHO3D_SAFE_RELEASE(p) if (p) { ((IUnknown*)p)->Release(); p = 0; }
#define URHO3D_LOGD3DERROR(msg, hr) URHO3D_LOGERRORF("%s (HRESULT %x)", msg, (unsigned)hr)
using ShaderProgramMap = HashMap<Pair<ShaderVariation*, ShaderVariation*>, SharedPtr<ShaderProgram> >;
using VertexDeclarationMap = HashMap<unsigned long long, SharedPtr<VertexDeclaration> >;
/// %Graphics implementation. Holds API-specific objects.
class URHO3D_API GraphicsImpl
{
friend class Graphics;
public:
/// Construct.
GraphicsImpl();
/// Return Direct3D device.
IDirect3DDevice9* GetDevice() const { return device_; }
/// Return device capabilities.
const D3DCAPS9& GetDeviceCaps() const { return deviceCaps_; }
/// Return adapter identifier.
const D3DADAPTER_IDENTIFIER9& GetAdapterIdentifier() const { return adapterIdentifier_; }
/// Return whether a texture format and usage is supported.
bool CheckFormatSupport(D3DFORMAT format, DWORD usage, D3DRESOURCETYPE type);
/// Return whether a multisample level is supported.
bool CheckMultiSampleSupport(D3DFORMAT format, int level);
private:
/// Direct3D interface.
IDirect3D9* interface_;
/// Direct3D device.
IDirect3DDevice9* device_;
/// Default color surface.
IDirect3DSurface9* defaultColorSurface_;
/// Default depth-stencil surface.
IDirect3DSurface9* defaultDepthStencilSurface_;
/// Frame query for flushing the GPU command queue.
IDirect3DQuery9* frameQuery_;
/// Adapter number.
DWORD adapter_;
/// Device type.
D3DDEVTYPE deviceType_;
/// Device capabilities.
D3DCAPS9 deviceCaps_;
/// Adapter identifier.
D3DADAPTER_IDENTIFIER9 adapterIdentifier_;
/// Direct3D presentation parameters.
D3DPRESENT_PARAMETERS presentParams_;
/// Texture min filter modes in use.
D3DTEXTUREFILTERTYPE minFilters_[MAX_TEXTURE_UNITS];
/// Texture mag filter modes in use.
D3DTEXTUREFILTERTYPE magFilters_[MAX_TEXTURE_UNITS];
/// Texture mip filter modes in use.
D3DTEXTUREFILTERTYPE mipFilters_[MAX_TEXTURE_UNITS];
/// Texture U coordinate addressing modes in use.
D3DTEXTUREADDRESS uAddressModes_[MAX_TEXTURE_UNITS];
/// Texture V coordinate addressing modes in use.
D3DTEXTUREADDRESS vAddressModes_[MAX_TEXTURE_UNITS];
/// Texture W coordinate addressing modes in use.
D3DTEXTUREADDRESS wAddressModes_[MAX_TEXTURE_UNITS];
/// Texture anisotropy setting in use.
unsigned maxAnisotropy_[MAX_TEXTURE_UNITS];
/// Texture border colors in use.
Color borderColors_[MAX_TEXTURE_UNITS];
/// Device lost flag.
bool deviceLost_;
/// Frame query issued flag.
bool queryIssued_;
/// sRGB mode in use.
bool sRGBModes_[MAX_TEXTURE_UNITS];
/// sRGB write flag.
bool sRGBWrite_;
/// Color surfaces in use.
IDirect3DSurface9* colorSurfaces_[MAX_RENDERTARGETS];
/// Depth-stencil surface in use.
IDirect3DSurface9* depthStencilSurface_;
/// Blending enabled flag.
DWORD blendEnable_;
/// Source blend mode.
D3DBLEND srcBlend_;
/// Destination blend mode.
D3DBLEND destBlend_;
/// Blend operation.
D3DBLENDOP blendOp_;
/// Vertex declarations.
VertexDeclarationMap vertexDeclarations_;
/// Stream frequencies by vertex buffer.
unsigned streamFrequencies_[MAX_VERTEX_STREAMS];
/// Stream offsets by vertex buffer.
unsigned streamOffsets_[MAX_VERTEX_STREAMS];
/// Vertex declaration in use.
VertexDeclaration* vertexDeclaration_;
/// Shader programs.
ShaderProgramMap shaderPrograms_;
/// Shader program in use.
ShaderProgram* shaderProgram_;
};
}
| Java |
CREATE TABLE `UserState`(
`StateId` NVARCHAR(64) NOT NULL UNIQUE,
`Description` NVARCHAR(512),
PRIMARY KEY(`StateId`)
);
INSERT INTO `UserState`
VALUES
('Active','Пользователь активен'),
('Bloked','Пользователь заблокирован'); | Java |
<!-- Admin info view -->
<!-- Title -->
<h2 class="accordion-toggle chevron">
<!-- Toggle -->
<button type="button" aria-expanded="false" bb-accordion>
<span>
<i class="fas fa-info-circle fa-fw"></i> {{_t('info')}}
</span>
</button>
</h2>
<!-- Content -->
<div class="accordion" hidden>
<div class="form form-inline form-page">
<div class="fieldset">
<h3>{{_t('software_info')}}</h3>
<table class="table table-report">
<tbody>
<tr>
<td>{{_t('firmware_version')}}</td>
<td class="td20">{{controllerInfo.softwareRevisionVersion}}</td>
</tr>
<tr>
<td>{{_t('ui_version')}}</td>
<td class="td20">{{cfg.app_version}}</td>
</tr>
<tr>
<td>{{_t('built_date')}}</td>
<td class="td20">{{builtInfo.built}}</td>
</tr>
<tr>
<td>{{_t('ctrl_info_caps_cap_title')}}</td>
<td class="td20">{{controllerInfo.capabillities}}</td>
</tr>
</tbody>
</table>
</div>
<div class="fieldset">
<h3>{{_t('translation')}}</h3>
<div>
{{_t('management_trans_info')}}
</div>
</div>
</div>
</div> | Java |
<?php
// include.php - Handles options for subscribe2
// DO NOT EDIT THIS FILE AS IT IS SET BY THE OPTIONS PAGE
if (!isset($this->subscribe2_options['autosub'])) {
$this->subscribe2_options['autosub'] = "no";
} // option to autosubscribe registered users to new categories
if (!isset($this->subscribe2_options['newreg_override'])) {
$this->subscribe2_options['newreg_override'] = "no";
} // option to autosubscribe registered users to new categories
if (!isset($this->subscribe2_options['wpregdef'])) {
$this->subscribe2_options['wpregdef'] = "no";
} // option to check registration form box by default
if (!isset($this->subscribe2_options['autoformat'])) {
$this->subscribe2_options['autoformat'] = "post";
} // option for default auto-subscription email format
if (!isset($this->subscribe2_options['show_autosub'])) {
$this->subscribe2_options['show_autosub'] = "yes";
} // option to display auto-subscription option to registered users
if (!isset($this->subscribe2_options['autosub_def'])) {
$this->subscribe2_options['autosub_def'] = "yes";
} // option for user default auto-subscription to new categories
if (!isset($this->subscribe2_options['comment_subs'])) {
$this->subscribe2_options['comment_subs'] = "no";
} // option for commenters to subscribe as public subscribers
if (!isset($this->subscribe2_options['comment_def'])) {
$this->subscribe2_options['comment_def'] = "no";
} // option for comments box to be checked by default
if (!isset($this->subscribe2_options['one_click_profile'])) {
$this->subscribe2_options['one_click_profile'] = "no";
} // option for displaying 'one-click' option on profile page
if (!isset($this->subscribe2_options['bcclimit'])) {
$this->subscribe2_options['bcclimit'] = 1;
} // option for default bcc limit on email notifications
if (!isset($this->subscribe2_options['admin_email'])) {
$this->subscribe2_options['admin_email'] = "subs";
} // option for sending new subscriber notifications to admins
if (!isset($this->subscribe2_options['tracking'])) {
$this->subscribe2_options['tracking'] = "";
} // option for tracking
if (!isset($this->subscribe2_options['s2page'])) {
$this->subscribe2_options['s2page'] = 0;
} // option for default WordPress page for Subscribe2 to use
if (!isset($this->subscribe2_options['stylesheet'])) {
$this->subscribe2_options['stylesheet'] = "yes";
} // option to include link to theme stylesheet from HTML notifications
if (!isset($this->subscribe2_options['pages'])) {
$this->subscribe2_options['pages'] = "no";
} // option for sending notifications for WordPress pages
if (!isset($this->subscribe2_options['password'])) {
$this->subscribe2_options['password'] = "no";
} // option for sending notifications for posts that are password protected
if (!isset($this->subscribe2_options['stickies'])) {
$this->subscribe2_options['stickies'] = "no";
} // option for including sticky posts in digest notifications
if (!isset($this->subscribe2_options['private'])) {
$this->subscribe2_options['private'] = "no";
} // option for sending notifications for posts that are private
if (!isset($this->subscribe2_options['email_freq'])) {
$this->subscribe2_options['email_freq'] = "never";
} // option for sending emails per-post or as a digest email on a cron schedule
if (!isset($this->subscribe2_options['cron_order'])) {
$this->subscribe2_options['cron_order'] = "desc";
} // option for ordering of posts in digest email
if (!isset($this->subscribe2_options['compulsory'])) {
$this->subscribe2_options['compulsory'] = "";
} // option for compulsory categories
if (!isset($this->subscribe2_options['exclude'])) {
$this->subscribe2_options['exclude'] = "";
} // option for excluded categories
if (!isset($this->subscribe2_options['sender'])) {
$this->subscribe2_options['sender'] = "blogname";
} // option for email notification sender
if (!isset($this->subscribe2_options['reg_override'])) {
$this->subscribe2_options['reg_override'] = "1";
} // option for excluded categories to be overriden for registered users
if (!isset($this->subscribe2_options['show_meta'])) {
$this->subscribe2_options['show_meta'] = "0";
} // option to display link to subscribe2 page from 'meta'
if (!isset($this->subscribe2_options['show_button'])) {
$this->subscribe2_options['show_button'] = "1";
} // option to show Subscribe2 button on Write page
if (!isset($this->subscribe2_options['ajax'])) {
$this->subscribe2_options['ajax'] = "0";
} // option to enable an AJAX style form
if (!isset($this->subscribe2_options['widget'])) {
$this->subscribe2_options['widget'] = "1";
} // option to enable Subscribe2 Widget
if (!isset($this->subscribe2_options['counterwidget'])) {
$this->subscribe2_options['counterwidget'] = "0";
} // option to enable Subscribe2 Counter Widget
if (!isset($this->subscribe2_options['s2meta_default'])) {
$this->subscribe2_options['s2meta_default'] = "0";
} // option for Subscribe2 over ride postmeta to be checked by default
if (!isset($this->subscribe2_options['entries'])) {
$this->subscribe2_options['entries'] = 25;
} // option for the number of subscribers displayed on each page
if (!isset($this->subscribe2_options['barred'])) {
$this->subscribe2_options['barred'] = "";
} // option containing domains barred from public registration
if (!isset($this->subscribe2_options['exclude_formats'])) {
$this->subscribe2_options['exclude_formats'] = "";
} // option for excluding post formats as supported by the current theme
if (!isset($this->subscribe2_options['mailtext'])) {
$this->subscribe2_options['mailtext'] = __("{BLOGNAME} has posted a new item, '{TITLE}'\n\n{POST}\n\nYou may view the latest post at\n{PERMALINK}\n\nYou received this e-mail because you asked to be notified when new updates are posted.\nBest regards,\n{MYNAME}\n{EMAIL}", "subscribe2");
} // Default notification email text
if (!isset($this->subscribe2_options['notification_subject'])) {
$this->subscribe2_options['notification_subject'] = "[{BLOGNAME}] {TITLE}";
} // Default notification email subject
if (!isset($this->subscribe2_options['confirm_email'])) {
$this->subscribe2_options['confirm_email'] = __("{BLOGNAME} has received a request to {ACTION} for this email address. To complete your request please click on the link below:\n\n{LINK}\n\nIf you did not request this, please feel free to disregard this notice!\n\nThank you,\n{MYNAME}.", "subscribe2");
} // Default confirmation email text
if (!isset($this->subscribe2_options['confirm_subject'])) {
$this->subscribe2_options['confirm_subject'] = "[{BLOGNAME}] " . __('Please confirm your request', 'subscribe2');
} // Default confirmation email subject
if (!isset($this->subscribe2_options['remind_email'])) {
$this->subscribe2_options['remind_email'] = __("This email address was subscribed for notifications at {BLOGNAME} ({BLOGLINK}) but the subscription remains incomplete.\n\nIf you wish to complete your subscription please click on the link below:\n\n{LINK}\n\nIf you do not wish to complete your subscription please ignore this email and your address will be removed from our database.\n\nRegards,\n{MYNAME}", "subscribe2");
} // Default reminder email text
if (!isset($this->subscribe2_options['remind_subject'])) {
$this->subscribe2_options['remind_subject'] = "[{BLOGNAME}] " . __('Subscription Reminder', 'subscribe2');;
} // Default reminder email subject
?> | Java |
/* Utilities for MPFR developers, not exported.
Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
Contributed by the Arenaire and Caramel projects, INRIA.
This file is part of the GNU MPFR Library.
The GNU MPFR Library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
The GNU MPFR Library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the GNU MPFR Library; see the file COPYING.LESSER. If not, see
http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */
#ifndef __MPFR_IMPL_H__
#define __MPFR_IMPL_H__
/* Let's include some standard headers unconditionally as they are
already needed by several source files or when some options are
enabled/disabled, and it is easy to forget them (some configure
options may hide the error).
Note: If some source file must not have such a header included
(which is very unlikely and probably means something broken in
this source file), we should do that with some macro (that would
also force to disable incompatible features). */
#if defined (__cplusplus)
#include <cstdio>
#include <cstring>
#else
#include <stdio.h>
#include <string.h>
#endif
#include <limits.h>
#if _MPFR_EXP_FORMAT == 4
/* mpfr_exp_t will be defined as intmax_t */
# include "mpfr-intmax.h"
#endif
/* Check if we are inside a build of MPFR or inside the test suite.
This is needed in mpfr.h to export or import the functions.
It matters only for Windows DLL */
#ifndef __MPFR_TEST_H__
# define __MPFR_WITHIN_MPFR 1
#endif
/******************************************************
****************** Include files *********************
******************************************************/
/* Include 'config.h' before using ANY configure macros if needed
NOTE: It isn't MPFR 'config.h', but GMP's one! */
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#ifdef MPFR_HAVE_GMP_IMPL /* Build with gmp internals*/
# ifndef __GMP_H__
# include "gmp.h"
# endif
# ifndef __GMP_IMPL_H__
# include "gmp-impl.h"
# endif
# ifdef MPFR_NEED_LONGLONG_H
# include "longlong.h"
# endif
# ifndef __MPFR_H
# include "mpfr.h"
# endif
#else /* Build without gmp internals */
# ifndef __GMP_H__
# include "gmp.h"
# endif
# ifndef __MPFR_H
# include "mpfr.h"
# endif
# ifndef __GMPFR_GMP_H__
# include "mpfr-gmp.h"
# endif
# ifdef MPFR_NEED_LONGLONG_H
# define LONGLONG_STANDALONE
# include "mpfr-longlong.h"
# endif
#endif
#undef MPFR_NEED_LONGLONG_H
/* If a mpn_sqr_n macro is not defined, use mpn_mul. GMP 4.x defines a
mpn_sqr_n macro in gmp-impl.h (and this macro disappeared in GMP 5),
so that GMP's macro can only be used when MPFR has been configured
with --with-gmp-build (and only with GMP 4.x). */
#ifndef mpn_sqr_n
# define mpn_sqr_n(dst,src,n) mpn_mul((dst),(src),(n),(src),(n))
#endif
/* For the definition of MPFR_THREAD_ATTR. GCC/ICC detection macros are
no longer used, as they sometimes gave incorrect information about
the support of thread-local variables. A configure check is now done.
If the use of detection macros is needed in the future, this could be
moved below (after the detection macros are defined). */
#include "mpfr-thread.h"
/******************************************************
***************** Detection macros *******************
******************************************************/
/* Macros to detect STDC, GCC, GLIBC, GMP and ICC version */
#if defined(__STDC_VERSION__)
# define __MPFR_STDC(version) (__STDC_VERSION__>=(version))
#elif defined(__STDC__)
# define __MPFR_STDC(version) (0 == (version))
#else
# define __MPFR_STDC(version) 0
#endif
#if defined(_WIN32)
/* Under MS Windows (e.g. with VS2008 or VS2010), Intel's compiler doesn't
support/enable extensions like the ones seen under GNU/Linux.
http://websympa.loria.fr/wwsympa/arc/mpfr/2011-02/msg00032.html */
# define __MPFR_ICC(a,b,c) 0
#elif defined(__ICC)
# define __MPFR_ICC(a,b,c) (__ICC >= (a)*100+(b)*10+(c))
#elif defined(__INTEL_COMPILER)
# define __MPFR_ICC(a,b,c) (__INTEL_COMPILER >= (a)*100+(b)*10+(c))
#else
# define __MPFR_ICC(a,b,c) 0
#endif
#if defined(__GNUC__) && defined(__GNUC_MINOR__) && ! __MPFR_ICC(0,0,0)
# define __MPFR_GNUC(a,i) \
(MPFR_VERSION_NUM(__GNUC__,__GNUC_MINOR__,0) >= MPFR_VERSION_NUM(a,i,0))
#else
# define __MPFR_GNUC(a,i) 0
#endif
#if defined(__GLIBC__) && defined(__GLIBC_MINOR__)
# define __MPFR_GLIBC(a,i) \
(MPFR_VERSION_NUM(__GLIBC__,__GLIBC_MINOR__,0) >= MPFR_VERSION_NUM(a,i,0))
#else
# define __MPFR_GLIBC(a,i) 0
#endif
#if defined(__GNU_MP_VERSION) && \
defined(__GNU_MP_VERSION_MINOR) && \
defined(__GNU_MP_VERSION_PATCHLEVEL)
# define __MPFR_GMP(a,b,c) \
(MPFR_VERSION_NUM(__GNU_MP_VERSION,__GNU_MP_VERSION_MINOR,__GNU_MP_VERSION_PATCHLEVEL) >= MPFR_VERSION_NUM(a,b,c))
#else
# define __MPFR_GMP(a,b,c) 0
#endif
/******************************************************
************* GMP Basic Pointer Types ****************
******************************************************/
typedef mp_limb_t *mpfr_limb_ptr;
typedef __gmp_const mp_limb_t *mpfr_limb_srcptr;
/******************************************************
****************** (U)INTMAX_MAX *********************
******************************************************/
/* Let's try to fix UINTMAX_MAX and INTMAX_MAX if these macros don't work
(e.g. with gcc -ansi -pedantic-errors in 32-bit mode under GNU/Linux),
see <http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=582698>. */
#ifdef _MPFR_H_HAVE_INTMAX_T
# ifdef MPFR_HAVE_INTMAX_MAX
# define MPFR_UINTMAX_MAX UINTMAX_MAX
# define MPFR_INTMAX_MAX INTMAX_MAX
# define MPFR_INTMAX_MIN INTMAX_MIN
# else
# define MPFR_UINTMAX_MAX ((uintmax_t) -1)
# define MPFR_INTMAX_MAX ((intmax_t) (MPFR_UINTMAX_MAX >> 1))
# define MPFR_INTMAX_MIN (INT_MIN + INT_MAX - MPFR_INTMAX_MAX)
# endif
#endif
/******************************************************
******************** Check GMP ***********************
******************************************************/
#if !__MPFR_GMP(4,1,0)
# error "GMP 4.1.0 or newer needed"
#endif
#if GMP_NAIL_BITS != 0
# error "MPFR doesn't support nonzero values of GMP_NAIL_BITS"
#endif
#if (GMP_NUMB_BITS<32) || (GMP_NUMB_BITS & (GMP_NUMB_BITS - 1))
# error "GMP_NUMB_BITS must be a power of 2, and >= 32"
#endif
#if GMP_NUMB_BITS == 16
# define MPFR_LOG2_GMP_NUMB_BITS 4
#elif GMP_NUMB_BITS == 32
# define MPFR_LOG2_GMP_NUMB_BITS 5
#elif GMP_NUMB_BITS == 64
# define MPFR_LOG2_GMP_NUMB_BITS 6
#elif GMP_NUMB_BITS == 128
# define MPFR_LOG2_GMP_NUMB_BITS 7
#elif GMP_NUMB_BITS == 256
# define MPFR_LOG2_GMP_NUMB_BITS 8
#else
# error "Can't compute log2(GMP_NUMB_BITS)"
#endif
#if __MPFR_GNUC(3,0) || __MPFR_ICC(8,1,0)
/* For the future: N1478: Supporting the 'noreturn' property in C1x
http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1478.htm */
# define MPFR_NORETURN_ATTR __attribute__ ((noreturn))
# define MPFR_CONST_ATTR __attribute__ ((const))
#else
# define MPFR_NORETURN_ATTR
# define MPFR_CONST_ATTR
#endif
/******************************************************
************* Global Internal Variables **************
******************************************************/
/* Cache struct */
struct __gmpfr_cache_s {
mpfr_t x;
int inexact;
int (*func)(mpfr_ptr, mpfr_rnd_t);
};
typedef struct __gmpfr_cache_s mpfr_cache_t[1];
typedef struct __gmpfr_cache_s *mpfr_cache_ptr;
#if defined (__cplusplus)
extern "C" {
#endif
__MPFR_DECLSPEC extern MPFR_THREAD_ATTR unsigned int __gmpfr_flags;
__MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_exp_t __gmpfr_emin;
__MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_exp_t __gmpfr_emax;
__MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_prec_t __gmpfr_default_fp_bit_precision;
__MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_rnd_t __gmpfr_default_rounding_mode;
__MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_t __gmpfr_cache_const_euler;
__MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_t __gmpfr_cache_const_catalan;
#ifndef MPFR_USE_LOGGING
__MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_t __gmpfr_cache_const_pi;
__MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_t __gmpfr_cache_const_log2;
#else
/* Two constants are used by the logging functions (via mpfr_fprintf,
then mpfr_log, for the base conversion): pi and log(2). Since the
mpfr_cache function isn't re-entrant when working on the same cache,
we need to define two caches for each constant. */
__MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_t __gmpfr_normal_pi;
__MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_t __gmpfr_normal_log2;
__MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_t __gmpfr_logging_pi;
__MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_t __gmpfr_logging_log2;
__MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_ptr __gmpfr_cache_const_pi;
__MPFR_DECLSPEC extern MPFR_THREAD_ATTR mpfr_cache_ptr __gmpfr_cache_const_log2;
#endif
#define BASE_MAX 62
__MPFR_DECLSPEC extern const __mpfr_struct __gmpfr_l2b[BASE_MAX-1][2];
/* Note: do not use the following values when they can be outside the
current exponent range, e.g. when the exponent range has not been
extended yet; under such a condition, they can be used only in
mpfr_cmpabs. */
__MPFR_DECLSPEC extern const mpfr_t __gmpfr_one;
__MPFR_DECLSPEC extern const mpfr_t __gmpfr_two;
__MPFR_DECLSPEC extern const mpfr_t __gmpfr_four;
#if defined (__cplusplus)
}
#endif
/* Flags of __gmpfr_flags */
#define MPFR_FLAGS_UNDERFLOW 1
#define MPFR_FLAGS_OVERFLOW 2
#define MPFR_FLAGS_NAN 4
#define MPFR_FLAGS_INEXACT 8
#define MPFR_FLAGS_ERANGE 16
#define MPFR_FLAGS_DIVBY0 32
#define MPFR_FLAGS_ALL 63
/* Replace some common functions for direct access to the global vars */
#define mpfr_get_emin() (__gmpfr_emin + 0)
#define mpfr_get_emax() (__gmpfr_emax + 0)
#define mpfr_get_default_rounding_mode() (__gmpfr_default_rounding_mode + 0)
#define mpfr_get_default_prec() (__gmpfr_default_fp_bit_precision + 0)
#define mpfr_clear_flags() \
((void) (__gmpfr_flags = 0))
#define mpfr_clear_underflow() \
((void) (__gmpfr_flags &= MPFR_FLAGS_ALL ^ MPFR_FLAGS_UNDERFLOW))
#define mpfr_clear_overflow() \
((void) (__gmpfr_flags &= MPFR_FLAGS_ALL ^ MPFR_FLAGS_OVERFLOW))
#define mpfr_clear_nanflag() \
((void) (__gmpfr_flags &= MPFR_FLAGS_ALL ^ MPFR_FLAGS_NAN))
#define mpfr_clear_inexflag() \
((void) (__gmpfr_flags &= MPFR_FLAGS_ALL ^ MPFR_FLAGS_INEXACT))
#define mpfr_clear_erangeflag() \
((void) (__gmpfr_flags &= MPFR_FLAGS_ALL ^ MPFR_FLAGS_ERANGE))
#define mpfr_clear_divby0() \
((void) (__gmpfr_flags &= MPFR_FLAGS_ALL ^ MPFR_FLAGS_DIVBY0))
#define mpfr_underflow_p() \
((int) (__gmpfr_flags & MPFR_FLAGS_UNDERFLOW))
#define mpfr_overflow_p() \
((int) (__gmpfr_flags & MPFR_FLAGS_OVERFLOW))
#define mpfr_nanflag_p() \
((int) (__gmpfr_flags & MPFR_FLAGS_NAN))
#define mpfr_inexflag_p() \
((int) (__gmpfr_flags & MPFR_FLAGS_INEXACT))
#define mpfr_erangeflag_p() \
((int) (__gmpfr_flags & MPFR_FLAGS_ERANGE))
#define mpfr_divby0_p() \
((int) (__gmpfr_flags & MPFR_FLAGS_DIVBY0))
/* Testing an exception flag correctly is tricky. There are mainly two
pitfalls: First, one needs to remember to clear the corresponding
flag, in case it was set before the function call or during some
intermediate computations (in practice, one can clear all the flags).
Secondly, one needs to test the flag early enough, i.e. before it
can be modified by another function. Moreover, it is quite difficult
(if not impossible) to reliably check problems with "make check". To
avoid these pitfalls, it is recommended to use the following macros.
Other use of the exception-flag predicate functions/macros will be
detected by mpfrlint.
Note: _op can be either a statement or an expression.
MPFR_BLOCK_EXCEP should be used only inside a block; it is useful to
detect some exception in order to exit the block as soon as possible. */
#define MPFR_BLOCK_DECL(_flags) unsigned int _flags
/* The (void) (_flags) makes sure that _flags is read at least once (it
makes sense to use MPFR_BLOCK while _flags will never be read in the
source, so that we wish to avoid the corresponding warning). */
#define MPFR_BLOCK(_flags,_op) \
do \
{ \
mpfr_clear_flags (); \
_op; \
(_flags) = __gmpfr_flags; \
(void) (_flags); \
} \
while (0)
#define MPFR_BLOCK_TEST(_flags,_f) MPFR_UNLIKELY ((_flags) & (_f))
#define MPFR_BLOCK_EXCEP (__gmpfr_flags & (MPFR_FLAGS_UNDERFLOW | \
MPFR_FLAGS_OVERFLOW | \
MPFR_FLAGS_DIVBY0 | \
MPFR_FLAGS_NAN))
/* Let's use a MPFR_ prefix, because e.g. OVERFLOW is defined by glibc's
math.h, though this is not a reserved identifier! */
#define MPFR_UNDERFLOW(_flags) MPFR_BLOCK_TEST (_flags, MPFR_FLAGS_UNDERFLOW)
#define MPFR_OVERFLOW(_flags) MPFR_BLOCK_TEST (_flags, MPFR_FLAGS_OVERFLOW)
#define MPFR_NANFLAG(_flags) MPFR_BLOCK_TEST (_flags, MPFR_FLAGS_NAN)
#define MPFR_INEXFLAG(_flags) MPFR_BLOCK_TEST (_flags, MPFR_FLAGS_INEXACT)
#define MPFR_ERANGEFLAG(_flags) MPFR_BLOCK_TEST (_flags, MPFR_FLAGS_ERANGE)
#define MPFR_DIVBY0(_flags) MPFR_BLOCK_TEST (_flags, MPFR_FLAGS_DIVBY0)
/******************************************************
******************** Assertions **********************
******************************************************/
/* Compile with -DWANT_ASSERT to check all assert statements */
/* Note: do not use GMP macros ASSERT_ALWAYS and ASSERT as they are not
expressions, and as a consequence, they cannot be used in a for(),
with a comma operator and so on. */
/* MPFR_ASSERTN(expr): assertions that should always be checked */
#define MPFR_ASSERTN(expr) \
((void) ((MPFR_UNLIKELY(expr)) || MPFR_UNLIKELY( (ASSERT_FAIL(expr),0) )))
/* MPFR_ASSERTD(expr): assertions that should be checked when testing */
#ifdef WANT_ASSERT
# define MPFR_EXP_CHECK 1
# define MPFR_ASSERTD(expr) MPFR_ASSERTN (expr)
#else
# define MPFR_ASSERTD(expr) ((void) 0)
#endif
/* Code to deal with impossible
WARNING: It doesn't use do { } while (0) for Insure++*/
#define MPFR_RET_NEVER_GO_HERE() {MPFR_ASSERTN(0); return 0;}
/******************************************************
******************** Warnings ************************
******************************************************/
/* MPFR_WARNING is no longer useful, but let's keep the macro in case
it needs to be used again in the future. */
#ifdef MPFR_USE_WARNINGS
# include <stdlib.h>
# define MPFR_WARNING(W) \
do \
{ \
char *q = getenv ("MPFR_QUIET"); \
if (q == NULL || *q == 0) \
fprintf (stderr, "MPFR: %s\n", W); \
} \
while (0)
#else
# define MPFR_WARNING(W) ((void) 0)
#endif
/******************************************************
****************** double macros *********************
******************************************************/
/* Precision used for lower precision computations */
#define MPFR_SMALL_PRECISION 32
/* Definition of constants */
#define LOG2 0.69314718055994528622 /* log(2) rounded to zero on 53 bits */
#define ALPHA 4.3191365662914471407 /* a+2 = a*log(a), rounded to +infinity */
#define EXPM1 0.36787944117144227851 /* exp(-1), rounded to zero */
/* MPFR_DOUBLE_SPEC = 1 if the C type 'double' corresponds to IEEE-754
double precision, 0 if it doesn't, and undefined if one doesn't know.
On all the tested machines, MPFR_DOUBLE_SPEC = 1. To have this macro
defined here, #include <float.h> is needed. If need be, other values
could be defined for other specs (once they are known). */
#if !defined(MPFR_DOUBLE_SPEC) && defined(FLT_RADIX) && \
defined(DBL_MANT_DIG) && defined(DBL_MIN_EXP) && defined(DBL_MAX_EXP)
# if FLT_RADIX == 2 && DBL_MANT_DIG == 53 && \
DBL_MIN_EXP == -1021 && DBL_MAX_EXP == 1024
# define MPFR_DOUBLE_SPEC 1
# else
# define MPFR_DOUBLE_SPEC 0
# endif
#endif
/* Debug non IEEE floats */
#ifdef XDEBUG
# undef _GMP_IEEE_FLOATS
#endif
#ifndef _GMP_IEEE_FLOATS
# define _GMP_IEEE_FLOATS 0
#endif
#ifndef IEEE_DBL_MANT_DIG
#define IEEE_DBL_MANT_DIG 53
#endif
#define MPFR_LIMBS_PER_DOUBLE ((IEEE_DBL_MANT_DIG-1)/GMP_NUMB_BITS+1)
#ifndef IEEE_FLT_MANT_DIG
#define IEEE_FLT_MANT_DIG 24
#endif
#define MPFR_LIMBS_PER_FLT ((IEEE_FLT_MANT_DIG-1)/GMP_NUMB_BITS+1)
/* Visual C++ doesn't support +1.0/0.0, -1.0/0.0 and 0.0/0.0
at compile time. */
#if defined(_MSC_VER) && defined(_WIN32) && (_MSC_VER >= 1200)
static double double_zero = 0.0;
# define DBL_NAN (double_zero/double_zero)
# define DBL_POS_INF ((double) 1.0/double_zero)
# define DBL_NEG_INF ((double)-1.0/double_zero)
# define DBL_NEG_ZERO (-double_zero)
#else
# define DBL_POS_INF ((double) 1.0/0.0)
# define DBL_NEG_INF ((double)-1.0/0.0)
# define DBL_NAN ((double) 0.0/0.0)
# define DBL_NEG_ZERO (-0.0)
#endif
/* Note: In the past, there was specific code for _GMP_IEEE_FLOATS, which
was based on NaN and Inf memory representations. This code was breaking
the aliasing rules (see ISO C99, 6.5#6 and 6.5#7 on the effective type)
and for this reason it did not behave correctly with GCC 4.5.0 20091119.
The code needed a memory transfer and was probably not better than the
macros below with a good compiler (a fix based on the NaN / Inf memory
representation would be even worse due to C limitations), and this code
could be selected only when MPFR was built with --with-gmp-build, thus
introducing a difference (bad for maintaining/testing MPFR); therefore
it has been removed. The old code required that the argument x be an
lvalue of type double. We still require that, in case one would need
to change the macros below, e.g. for some broken compiler. But the
LVALUE(x) condition could be removed if really necessary. */
/* Below, the &(x) == &(x) || &(x) != &(x) allows to make sure that x
is a lvalue without (probably) any warning from the compiler. The
&(x) != &(x) is needed to avoid a failure under Mac OS X 10.4.11
(with Xcode 2.4.1, i.e. the latest one). */
#define LVALUE(x) (&(x) == &(x) || &(x) != &(x))
#define DOUBLE_ISINF(x) (LVALUE(x) && ((x) > DBL_MAX || (x) < -DBL_MAX))
#ifdef MPFR_NANISNAN
/* Avoid MIPSpro / IRIX64 / gcc -ffast-math (incorrect) optimizations.
The + must not be replaced by a ||. With gcc -ffast-math, NaN is
regarded as a positive number or something like that; the second
test catches this case. */
# define DOUBLE_ISNAN(x) \
(LVALUE(x) && !((((x) >= 0.0) + ((x) <= 0.0)) && -(x)*(x) <= 0.0))
#else
# define DOUBLE_ISNAN(x) (LVALUE(x) && (x) != (x))
#endif
/******************************************************
*************** Long double macros *******************
******************************************************/
/* We try to get the exact value of the precision of long double
(provided by the implementation) in order to provide correct
rounding in this case (not guaranteed if the C implementation
does not have an adequate long double arithmetic). Note that
it may be lower than the precision of some numbers that can
be represented in a long double; e.g. on FreeBSD/x86, it is
53 because the processor is configured to round in double
precision (even when using the long double type -- this is a
limitation of the x87 arithmetic), and on Mac OS X, it is 106
because the implementation is a double-double arithmetic.
Otherwise (e.g. in base 10), we get an upper bound of the
precision, and correct rounding isn't currently provided.
*/
#if defined(LDBL_MANT_DIG) && FLT_RADIX == 2
# define MPFR_LDBL_MANT_DIG LDBL_MANT_DIG
#else
# define MPFR_LDBL_MANT_DIG \
(sizeof(long double)*GMP_NUMB_BITS/sizeof(mp_limb_t))
#endif
#define MPFR_LIMBS_PER_LONG_DOUBLE \
((sizeof(long double)-1)/sizeof(mp_limb_t)+1)
/* LONGDOUBLE_NAN_ACTION executes the code "action" if x is a NaN. */
/* On hppa2.0n-hp-hpux10 with the unbundled HP cc, the test x!=x on a NaN
has been seen false, meaning NaNs are not detected. This seemed to
happen only after other comparisons, not sure what's really going on. In
any case we can pick apart the bytes to identify a NaN. */
#ifdef HAVE_LDOUBLE_IEEE_QUAD_BIG
# define LONGDOUBLE_NAN_ACTION(x, action) \
do { \
union { \
long double ld; \
struct { \
unsigned int sign : 1; \
unsigned int exp : 15; \
unsigned int man3 : 16; \
unsigned int man2 : 32; \
unsigned int man1 : 32; \
unsigned int man0 : 32; \
} s; \
} u; \
u.ld = (x); \
if (u.s.exp == 0x7FFFL \
&& (u.s.man0 | u.s.man1 | u.s.man2 | u.s.man3) != 0) \
{ action; } \
} while (0)
#endif
#ifdef HAVE_LDOUBLE_IEEE_QUAD_LITTLE
# define LONGDOUBLE_NAN_ACTION(x, action) \
do { \
union { \
long double ld; \
struct { \
unsigned int man0 : 32; \
unsigned int man1 : 32; \
unsigned int man2 : 32; \
unsigned int man3 : 16; \
unsigned int exp : 15; \
unsigned int sign : 1; \
} s; \
} u; \
u.ld = (x); \
if (u.s.exp == 0x7FFFL \
&& (u.s.man0 | u.s.man1 | u.s.man2 | u.s.man3) != 0) \
{ action; } \
} while (0)
#endif
/* Under IEEE rules, NaN is not equal to anything, including itself.
"volatile" here stops "cc" on mips64-sgi-irix6.5 from optimizing away
x!=x. */
#ifndef LONGDOUBLE_NAN_ACTION
# define LONGDOUBLE_NAN_ACTION(x, action) \
do { \
volatile long double __x = LONGDOUBLE_VOLATILE (x); \
if ((x) != __x) \
{ action; } \
} while (0)
# define WANT_LONGDOUBLE_VOLATILE 1
#endif
/* If we don't have a proper "volatile" then volatile is #defined to empty,
in this case call through an external function to stop the compiler
optimizing anything. */
#ifdef WANT_LONGDOUBLE_VOLATILE
# ifdef volatile
__MPFR_DECLSPEC long double __gmpfr_longdouble_volatile _MPFR_PROTO ((long double)) MPFR_CONST_ATTR;
# define LONGDOUBLE_VOLATILE(x) (__gmpfr_longdouble_volatile (x))
# define WANT_GMPFR_LONGDOUBLE_VOLATILE 1
# else
# define LONGDOUBLE_VOLATILE(x) (x)
# endif
#endif
/* Some special case for IEEE_EXT Litle Endian */
#if HAVE_LDOUBLE_IEEE_EXT_LITTLE
typedef union {
long double ld;
struct {
unsigned int manl : 32;
unsigned int manh : 32;
unsigned int expl : 8 ;
unsigned int exph : 7;
unsigned int sign : 1;
} s;
} mpfr_long_double_t;
/* #undef MPFR_LDBL_MANT_DIG */
#undef MPFR_LIMBS_PER_LONG_DOUBLE
/* #define MPFR_LDBL_MANT_DIG 64 */
#define MPFR_LIMBS_PER_LONG_DOUBLE ((64-1)/GMP_NUMB_BITS+1)
#endif
/******************************************************
*************** _Decimal64 support *******************
******************************************************/
#ifdef MPFR_WANT_DECIMAL_FLOATS
/* to cast between binary64 and decimal64 */
union ieee_double_decimal64 { double d; _Decimal64 d64; };
#endif
/******************************************************
**************** mpfr_t properties *******************
******************************************************/
#define MPFR_PREC(x) ((x)->_mpfr_prec)
#define MPFR_EXP(x) ((x)->_mpfr_exp)
#define MPFR_MANT(x) ((x)->_mpfr_d)
#define MPFR_LIMB_SIZE(x) ((MPFR_PREC((x))-1)/GMP_NUMB_BITS+1)
/******************************************************
**************** exponent properties *****************
******************************************************/
/* Limits of the mpfr_exp_t type (NOT those of valid exponent values).
These macros can be used in preprocessor directives. */
#if _MPFR_EXP_FORMAT == 1
# define MPFR_EXP_MAX (SHRT_MAX)
# define MPFR_EXP_MIN (SHRT_MIN)
#elif _MPFR_EXP_FORMAT == 2
# define MPFR_EXP_MAX (INT_MAX)
# define MPFR_EXP_MIN (INT_MIN)
#elif _MPFR_EXP_FORMAT == 3
# define MPFR_EXP_MAX (LONG_MAX)
# define MPFR_EXP_MIN (LONG_MIN)
#elif _MPFR_EXP_FORMAT == 4
# define MPFR_EXP_MAX (MPFR_INTMAX_MAX)
# define MPFR_EXP_MIN (MPFR_INTMAX_MIN)
#else
# error "Invalid MPFR Exp format"
#endif
/* Before doing a cast to mpfr_uexp_t, make sure that the value is
nonnegative. */
#define MPFR_UEXP(X) (MPFR_ASSERTD ((X) >= 0), (mpfr_uexp_t) (X))
#if MPFR_EXP_MIN >= LONG_MIN && MPFR_EXP_MAX <= LONG_MAX
typedef long int mpfr_eexp_t;
# define mpfr_get_exp_t(x,r) mpfr_get_si((x),(r))
# define mpfr_set_exp_t(x,e,r) mpfr_set_si((x),(e),(r))
# define MPFR_EXP_FSPEC "l"
#elif defined (_MPFR_H_HAVE_INTMAX_T)
typedef intmax_t mpfr_eexp_t;
# define mpfr_get_exp_t(x,r) mpfr_get_sj((x),(r))
# define mpfr_set_exp_t(x,e,r) mpfr_set_sj((x),(e),(r))
# define MPFR_EXP_FSPEC "j"
#else
# error "Cannot define mpfr_get_exp_t and mpfr_set_exp_t"
#endif
/* Invalid exponent value (to track bugs...) */
#define MPFR_EXP_INVALID \
((mpfr_exp_t) 1 << (GMP_NUMB_BITS*sizeof(mpfr_exp_t)/sizeof(mp_limb_t)-2))
/* Definition of the exponent limits for MPFR numbers.
* These limits are chosen so that if e is such an exponent, then 2e-1 and
* 2e+1 are representable. This is useful for intermediate computations,
* in particular the multiplication.
*/
#undef MPFR_EMIN_MIN
#undef MPFR_EMIN_MAX
#undef MPFR_EMAX_MIN
#undef MPFR_EMAX_MAX
#define MPFR_EMIN_MIN (1-MPFR_EXP_INVALID)
#define MPFR_EMIN_MAX (MPFR_EXP_INVALID-1)
#define MPFR_EMAX_MIN (1-MPFR_EXP_INVALID)
#define MPFR_EMAX_MAX (MPFR_EXP_INVALID-1)
/* Use MPFR_GET_EXP and MPFR_SET_EXP instead of MPFR_EXP directly,
unless when the exponent may be out-of-range, for instance when
setting the exponent before calling mpfr_check_range.
MPFR_EXP_CHECK is defined when WANT_ASSERT is defined, but if you
don't use WANT_ASSERT (for speed reasons), you can still define
MPFR_EXP_CHECK by setting -DMPFR_EXP_CHECK in $CFLAGS. */
#ifdef MPFR_EXP_CHECK
# define MPFR_GET_EXP(x) (mpfr_get_exp) (x)
# define MPFR_SET_EXP(x, exp) MPFR_ASSERTN (!mpfr_set_exp ((x), (exp)))
# define MPFR_SET_INVALID_EXP(x) ((void) (MPFR_EXP (x) = MPFR_EXP_INVALID))
#else
# define MPFR_GET_EXP(x) MPFR_EXP (x)
# define MPFR_SET_EXP(x, exp) ((void) (MPFR_EXP (x) = (exp)))
# define MPFR_SET_INVALID_EXP(x) ((void) 0)
#endif
/******************************************************
********** Singular Values (NAN, INF, ZERO) **********
******************************************************/
/* Enum special value of exponent. */
# define MPFR_EXP_ZERO (MPFR_EXP_MIN+1)
# define MPFR_EXP_NAN (MPFR_EXP_MIN+2)
# define MPFR_EXP_INF (MPFR_EXP_MIN+3)
#define MPFR_IS_NAN(x) (MPFR_EXP(x) == MPFR_EXP_NAN)
#define MPFR_SET_NAN(x) (MPFR_EXP(x) = MPFR_EXP_NAN)
#define MPFR_IS_INF(x) (MPFR_EXP(x) == MPFR_EXP_INF)
#define MPFR_SET_INF(x) (MPFR_EXP(x) = MPFR_EXP_INF)
#define MPFR_IS_ZERO(x) (MPFR_EXP(x) == MPFR_EXP_ZERO)
#define MPFR_SET_ZERO(x) (MPFR_EXP(x) = MPFR_EXP_ZERO)
#define MPFR_NOTZERO(x) (MPFR_EXP(x) != MPFR_EXP_ZERO)
#define MPFR_IS_FP(x) (!MPFR_IS_NAN(x) && !MPFR_IS_INF(x))
#define MPFR_IS_SINGULAR(x) (MPFR_EXP(x) <= MPFR_EXP_INF)
#define MPFR_IS_PURE_FP(x) (!MPFR_IS_SINGULAR(x) && \
(MPFR_ASSERTD (MPFR_MANT(x)[MPFR_LIMB_SIZE(x)-1] & MPFR_LIMB_HIGHBIT), 1))
#define MPFR_ARE_SINGULAR(x,y) \
(MPFR_UNLIKELY(MPFR_IS_SINGULAR(x)) || MPFR_UNLIKELY(MPFR_IS_SINGULAR(y)))
#define MPFR_IS_POWER_OF_2(x) \
(mpfr_cmp_ui_2exp ((x), 1, MPFR_GET_EXP (x) - 1) == 0)
/******************************************************
********************* Sign Macros ********************
******************************************************/
#define MPFR_SIGN_POS (1)
#define MPFR_SIGN_NEG (-1)
#define MPFR_IS_STRICTPOS(x) (MPFR_NOTZERO((x)) && MPFR_SIGN(x) > 0)
#define MPFR_IS_STRICTNEG(x) (MPFR_NOTZERO((x)) && MPFR_SIGN(x) < 0)
#define MPFR_IS_NEG(x) (MPFR_SIGN(x) < 0)
#define MPFR_IS_POS(x) (MPFR_SIGN(x) > 0)
#define MPFR_SET_POS(x) (MPFR_SIGN(x) = MPFR_SIGN_POS)
#define MPFR_SET_NEG(x) (MPFR_SIGN(x) = MPFR_SIGN_NEG)
#define MPFR_CHANGE_SIGN(x) (MPFR_SIGN(x) = -MPFR_SIGN(x))
#define MPFR_SET_SAME_SIGN(x, y) (MPFR_SIGN(x) = MPFR_SIGN(y))
#define MPFR_SET_OPPOSITE_SIGN(x, y) (MPFR_SIGN(x) = -MPFR_SIGN(y))
#define MPFR_ASSERT_SIGN(s) \
(MPFR_ASSERTD((s) == MPFR_SIGN_POS || (s) == MPFR_SIGN_NEG))
#define MPFR_SET_SIGN(x, s) \
(MPFR_ASSERT_SIGN(s), MPFR_SIGN(x) = s)
#define MPFR_IS_POS_SIGN(s1) (s1 > 0)
#define MPFR_IS_NEG_SIGN(s1) (s1 < 0)
#define MPFR_MULT_SIGN(s1, s2) ((s1) * (s2))
/* Transform a sign to 1 or -1 */
#define MPFR_FROM_SIGN_TO_INT(s) (s)
#define MPFR_INT_SIGN(x) MPFR_FROM_SIGN_TO_INT(MPFR_SIGN(x))
/******************************************************
***************** Ternary Value Macros ***************
******************************************************/
/* Special inexact value */
#define MPFR_EVEN_INEX 2
/* Macros for functions returning two inexact values in an 'int' */
#define INEXPOS(y) ((y) == 0 ? 0 : (((y) > 0) ? 1 : 2))
#define INEX(y,z) (INEXPOS(y) | (INEXPOS(z) << 2))
/* When returning the ternary inexact value, ALWAYS use one of the
following two macros, unless the flag comes from another function
returning the ternary inexact value */
#define MPFR_RET(I) return \
(I) ? ((__gmpfr_flags |= MPFR_FLAGS_INEXACT), (I)) : 0
#define MPFR_RET_NAN return (__gmpfr_flags |= MPFR_FLAGS_NAN), 0
#define MPFR_SET_ERANGE() (__gmpfr_flags |= MPFR_FLAGS_ERANGE)
#define SIGN(I) ((I) < 0 ? -1 : (I) > 0)
#define SAME_SIGN(I1,I2) (SIGN (I1) == SIGN (I2))
/******************************************************
************** Rounding mode macros *****************
******************************************************/
/* MPFR_RND_MAX gives the number of supported rounding modes by all functions.
* Once faithful rounding is implemented, MPFR_RNDA should be changed
* to MPFR_RNDF. But this will also require more changes in the tests.
*/
#define MPFR_RND_MAX ((mpfr_rnd_t)((MPFR_RNDA)+1))
/* We want to test this :
* (rnd == MPFR_RNDU && test) || (rnd == RNDD && !test)
* ie it transforms RNDU or RNDD to Away or Zero according to the sign */
#define MPFR_IS_RNDUTEST_OR_RNDDNOTTEST(rnd, test) \
(((rnd) + (test)) == MPFR_RNDD)
/* We want to test if rnd = Zero, or Away.
'test' is 1 if negative, and 0 if positive. */
#define MPFR_IS_LIKE_RNDZ(rnd, test) \
((rnd==MPFR_RNDZ) || MPFR_IS_RNDUTEST_OR_RNDDNOTTEST (rnd, test))
#define MPFR_IS_LIKE_RNDU(rnd, sign) \
((rnd==MPFR_RNDU) || (rnd==MPFR_RNDZ && sign<0) || (rnd==MPFR_RNDA && sign>0))
#define MPFR_IS_LIKE_RNDD(rnd, sign) \
((rnd==MPFR_RNDD) || (rnd==MPFR_RNDZ && sign>0) || (rnd==MPFR_RNDA && sign<0))
/* Invert a rounding mode, RNDZ and RNDA are unchanged */
#define MPFR_INVERT_RND(rnd) ((rnd == MPFR_RNDU) ? MPFR_RNDD : \
((rnd == MPFR_RNDD) ? MPFR_RNDU : rnd))
/* Transform RNDU and RNDD to RNDZ according to test */
#define MPFR_UPDATE_RND_MODE(rnd, test) \
do { \
if (MPFR_UNLIKELY(MPFR_IS_RNDUTEST_OR_RNDDNOTTEST(rnd, test))) \
rnd = MPFR_RNDZ; \
} while (0)
/* Transform RNDU and RNDD to RNDZ or RNDA according to sign,
leave the other modes unchanged */
#define MPFR_UPDATE2_RND_MODE(rnd, sign) \
do { \
if (rnd == MPFR_RNDU) \
rnd = (sign > 0) ? MPFR_RNDA : MPFR_RNDZ; \
else if (rnd == MPFR_RNDD) \
rnd = (sign < 0) ? MPFR_RNDA : MPFR_RNDZ; \
} while (0)
/******************************************************
******************* Limb Macros **********************
******************************************************/
/* Definition of MPFR_LIMB_HIGHBIT */
#if defined(GMP_LIMB_HIGHBIT)
# define MPFR_LIMB_HIGHBIT GMP_LIMB_HIGHBIT
#elif defined(MP_LIMB_T_HIGHBIT)
# define MPFR_LIMB_HIGHBIT MP_LIMB_T_HIGHBIT
#else
# error "Neither GMP_LIMB_HIGHBIT nor MP_LIMB_T_HIGHBIT defined in GMP"
#endif
/* Mask to get the Most Significant Bit of a limb */
#define MPFR_LIMB_MSB(l) ((l)&MPFR_LIMB_HIGHBIT)
/* Definition of MPFR_LIMB_ONE & MPFR_LIMB_ZERO */
#ifdef CNST_LIMB
# define MPFR_LIMB_ONE CNST_LIMB(1)
# define MPFR_LIMB_ZERO CNST_LIMB(0)
#else
# define MPFR_LIMB_ONE ((mp_limb_t) 1L)
# define MPFR_LIMB_ZERO ((mp_limb_t) 0L)
#endif
/* Mask for the low 's' bits of a limb */
#define MPFR_LIMB_MASK(s) ((MPFR_LIMB_ONE<<(s))-MPFR_LIMB_ONE)
/******************************************************
********************** Memory ************************
******************************************************/
/* Heap Memory gestion */
typedef union { mp_size_t s; mp_limb_t l; } mpfr_size_limb_t;
#define MPFR_GET_ALLOC_SIZE(x) \
( ((mp_size_t*) MPFR_MANT(x))[-1] + 0)
#define MPFR_SET_ALLOC_SIZE(x, n) \
( ((mp_size_t*) MPFR_MANT(x))[-1] = n)
#define MPFR_MALLOC_SIZE(s) \
( sizeof(mpfr_size_limb_t) + BYTES_PER_MP_LIMB * ((size_t) s) )
#define MPFR_SET_MANT_PTR(x,p) \
(MPFR_MANT(x) = (mp_limb_t*) ((mpfr_size_limb_t*) p + 1))
#define MPFR_GET_REAL_PTR(x) \
((mp_limb_t*) ((mpfr_size_limb_t*) MPFR_MANT(x) - 1))
/* Temporary memory gestion */
#ifndef TMP_SALLOC
/* GMP 4.1.x or below or internals */
#define MPFR_TMP_DECL TMP_DECL
#define MPFR_TMP_MARK TMP_MARK
#define MPFR_TMP_ALLOC TMP_ALLOC
#define MPFR_TMP_FREE TMP_FREE
#else
#define MPFR_TMP_DECL(x) TMP_DECL
#define MPFR_TMP_MARK(x) TMP_MARK
#define MPFR_TMP_ALLOC(s) TMP_ALLOC(s)
#define MPFR_TMP_FREE(x) TMP_FREE
#endif
/* This code is experimental: don't use it */
#ifdef MPFR_USE_OWN_MPFR_TMP_ALLOC
extern unsigned char *mpfr_stack;
#undef MPFR_TMP_DECL
#undef MPFR_TMP_MARK
#undef MPFR_TMP_ALLOC
#undef MPFR_TMP_FREE
#define MPFR_TMP_DECL(_x) unsigned char *(_x)
#define MPFR_TMP_MARK(_x) ((_x) = mpfr_stack)
#define MPFR_TMP_ALLOC(_s) (mpfr_stack += (_s), mpfr_stack - (_s))
#define MPFR_TMP_FREE(_x) (mpfr_stack = (_x))
#endif
#define MPFR_TMP_LIMBS_ALLOC(N) \
((mp_limb_t *) MPFR_TMP_ALLOC ((size_t) (N) * BYTES_PER_MP_LIMB))
/* temporary allocate 1 limb at xp, and initialize mpfr variable x */
/* The temporary var doesn't have any size field, but it doesn't matter
* since only functions dealing with the Heap care about it */
#define MPFR_TMP_INIT1(xp, x, p) \
( MPFR_PREC(x) = (p), \
MPFR_MANT(x) = (xp), \
MPFR_SET_POS(x), \
MPFR_SET_INVALID_EXP(x))
#define MPFR_TMP_INIT(xp, x, p, s) \
(xp = MPFR_TMP_LIMBS_ALLOC(s), \
MPFR_TMP_INIT1(xp, x, p))
#define MPFR_TMP_INIT_ABS(d, s) \
( MPFR_PREC(d) = MPFR_PREC(s), \
MPFR_MANT(d) = MPFR_MANT(s), \
MPFR_SET_POS(d), \
MPFR_EXP(d) = MPFR_EXP(s))
/******************************************************
***************** Cache macros **********************
******************************************************/
#define mpfr_const_pi(_d,_r) mpfr_cache(_d, __gmpfr_cache_const_pi,_r)
#define mpfr_const_log2(_d,_r) mpfr_cache(_d, __gmpfr_cache_const_log2, _r)
#define mpfr_const_euler(_d,_r) mpfr_cache(_d, __gmpfr_cache_const_euler, _r)
#define mpfr_const_catalan(_d,_r) mpfr_cache(_d,__gmpfr_cache_const_catalan,_r)
#define MPFR_DECL_INIT_CACHE(_cache,_func) \
mpfr_cache_t MPFR_THREAD_ATTR _cache = \
{{{{0,MPFR_SIGN_POS,0,(mp_limb_t*)0}},0,_func}}
/******************************************************
******************* Threshold ***********************
******************************************************/
#include "mparam.h"
/******************************************************
***************** Useful macros *********************
******************************************************/
/* Theses macros help the compiler to determine if a test is
likely or unlikely. The !! is necessary in case x is larger
than a long. */
#if __MPFR_GNUC(3,0) || __MPFR_ICC(8,1,0)
# define MPFR_LIKELY(x) (__builtin_expect(!!(x),1))
# define MPFR_UNLIKELY(x) (__builtin_expect(!!(x),0))
#else
# define MPFR_LIKELY(x) (x)
# define MPFR_UNLIKELY(x) (x)
#endif
/* Declare that some variable is initialized before being used (without a
dummy initialization) in order to avoid some compiler warnings. Use the
VAR = VAR trick (see http://gcc.gnu.org/bugzilla/show_bug.cgi?id=36296)
only with gcc as this is undefined behavior, and we don't know what
other compilers do (they may also be smarter). This trick could be
disabled with future gcc versions. */
#if defined(__GNUC__)
# define INITIALIZED(VAR) VAR = VAR
#else
# define INITIALIZED(VAR) VAR
#endif
/* Ceil log 2: If GCC, uses a GCC extension, otherwise calls a function */
/* Warning:
* Needs to define MPFR_NEED_LONGLONG.
* Computes ceil(log2(x)) only for x integer (unsigned long)
* Undefined if x is 0 */
#if __MPFR_GNUC(2,95) || __MPFR_ICC(8,1,0)
# define MPFR_INT_CEIL_LOG2(x) \
(MPFR_UNLIKELY ((x) == 1) ? 0 : \
__extension__ ({ int _b; mp_limb_t _limb; \
MPFR_ASSERTN ((x) > 1); \
_limb = (x) - 1; \
MPFR_ASSERTN (_limb == (x) - 1); \
count_leading_zeros (_b, _limb); \
(GMP_NUMB_BITS - _b); }))
#else
# define MPFR_INT_CEIL_LOG2(x) (__gmpfr_int_ceil_log2(x))
#endif
/* Add two integers with overflow handling */
/* Example: MPFR_SADD_OVERFLOW (c, a, b, long, unsigned long,
* LONG_MIN, LONG_MAX,
* goto overflow, goto underflow); */
#define MPFR_UADD_OVERFLOW(c,a,b,ACTION_IF_OVERFLOW) \
do { \
(c) = (a) + (b); \
if ((c) < (a)) ACTION_IF_OVERFLOW; \
} while (0)
#define MPFR_SADD_OVERFLOW(c,a,b,STYPE,UTYPE,MIN,MAX,ACTION_IF_POS_OVERFLOW,ACTION_IF_NEG_OVERFLOW) \
do { \
if ((a) >= 0 && (b) >= 0) { \
UTYPE uc,ua,ub; \
ua = (UTYPE) (a); ub = (UTYPE) (b); \
MPFR_UADD_OVERFLOW (uc, ua, ub, ACTION_IF_POS_OVERFLOW); \
if (uc > (UTYPE)(MAX)) ACTION_IF_POS_OVERFLOW; \
else (c) = (STYPE) uc; \
} else if ((a) < 0 && (b) < 0) { \
UTYPE uc,ua,ub; \
ua = -(UTYPE) (a); ub = -(UTYPE) (b); \
MPFR_UADD_OVERFLOW (uc, ua, ub, ACTION_IF_NEG_OVERFLOW); \
if (uc >= -(UTYPE)(MIN) || uc > (UTYPE)(MAX)) { \
if (uc == -(UTYPE)(MIN)) (c) = (MIN); \
else ACTION_IF_NEG_OVERFLOW; } \
else (c) = -(STYPE) uc; \
} else (c) = (a) + (b); \
} while (0)
/* Set a number to 1 (Fast) - It doesn't check if 1 is in the exponent range */
#define MPFR_SET_ONE(x) \
do { \
mp_size_t _size = MPFR_LIMB_SIZE(x) - 1; \
MPFR_SET_POS(x); \
MPFR_EXP(x) = 1; \
MPN_ZERO ( MPFR_MANT(x), _size); \
MPFR_MANT(x)[_size] = MPFR_LIMB_HIGHBIT; \
} while (0)
/* Compute s = (-a) % GMP_NUMB_BITS as unsigned */
#define MPFR_UNSIGNED_MINUS_MODULO(s, a) \
do \
{ \
if (IS_POW2 (GMP_NUMB_BITS)) \
(s) = (- (unsigned int) (a)) % GMP_NUMB_BITS; \
else \
{ \
(s) = (a) % GMP_NUMB_BITS; \
if ((s) != 0) \
(s) = GMP_NUMB_BITS - (s); \
} \
MPFR_ASSERTD ((s) >= 0 && (s) < GMP_NUMB_BITS); \
} \
while (0)
/* Use it only for debug reasons */
/* MPFR_TRACE (operation) : execute operation iff DEBUG flag is set */
/* MPFR_DUMP (x) : print x (a mpfr_t) on stdout */
#ifdef DEBUG
# define MPFR_TRACE(x) x
#else
# define MPFR_TRACE(x) (void) 0
#endif
#define MPFR_DUMP(x) ( printf(#x"="), mpfr_dump(x) )
/* Test if X (positive) is a power of 2 */
#define IS_POW2(X) (((X) & ((X) - 1)) == 0)
#define NOT_POW2(X) (((X) & ((X) - 1)) != 0)
/* Safe absolute value (to avoid possible integer overflow) */
/* type is the target (unsigned) type */
#define SAFE_ABS(type,x) ((x) >= 0 ? (type)(x) : -(type)(x))
#define mpfr_get_d1(x) mpfr_get_d(x,__gmpfr_default_rounding_mode)
/* Store in r the size in bits of the mpz_t z */
#define MPFR_MPZ_SIZEINBASE2(r, z) \
do { \
int _cnt; \
mp_size_t _size; \
MPFR_ASSERTD (mpz_sgn (z) != 0); \
_size = ABSIZ(z); \
count_leading_zeros (_cnt, PTR(z)[_size-1]); \
(r) = _size * GMP_NUMB_BITS - _cnt; \
} while (0)
/* Needs <locale.h> */
#ifdef HAVE_LOCALE_H
#include <locale.h>
/* Warning! In case of signed char, the value of MPFR_DECIMAL_POINT may
be negative (the ISO C99 does not seem to forbid negative values). */
#define MPFR_DECIMAL_POINT (localeconv()->decimal_point[0])
#define MPFR_THOUSANDS_SEPARATOR (localeconv()->thousands_sep[0])
#else
#define MPFR_DECIMAL_POINT ((char) '.')
#define MPFR_THOUSANDS_SEPARATOR ('\0')
#endif
/* Set y to s*significand(x)*2^e, for example MPFR_ALIAS(y,x,1,MPFR_EXP(x))
sets y to |x|, and MPFR_ALIAS(y,x,MPFR_SIGN(x),0) sets y to x*2^f such
that 1/2 <= |y| < 1. Does not check y is in the valid exponent range.
WARNING! x and y share the same mantissa. So, some operations are
not valid if x has been provided via an argument, e.g., trying to
modify the mantissa of y, even temporarily, or calling mpfr_clear on y.
*/
#define MPFR_ALIAS(y,x,s,e) \
do \
{ \
MPFR_PREC(y) = MPFR_PREC(x); \
MPFR_SIGN(y) = (s); \
MPFR_EXP(y) = (e); \
MPFR_MANT(y) = MPFR_MANT(x); \
} while (0)
/******************************************************
************** Save exponent macros ****************
******************************************************/
/* See README.dev for details on how to use the macros.
They are used to set the exponent range to the maximum
temporarily */
typedef struct {
unsigned int saved_flags;
mpfr_exp_t saved_emin;
mpfr_exp_t saved_emax;
} mpfr_save_expo_t;
/* Minimum and maximum exponents of the extended exponent range. */
#define MPFR_EXT_EMIN MPFR_EMIN_MIN
#define MPFR_EXT_EMAX MPFR_EMAX_MAX
#define MPFR_SAVE_EXPO_DECL(x) mpfr_save_expo_t x
#define MPFR_SAVE_EXPO_MARK(x) \
((x).saved_flags = __gmpfr_flags, \
(x).saved_emin = __gmpfr_emin, \
(x).saved_emax = __gmpfr_emax, \
__gmpfr_emin = MPFR_EXT_EMIN, \
__gmpfr_emax = MPFR_EXT_EMAX)
#define MPFR_SAVE_EXPO_FREE(x) \
(__gmpfr_flags = (x).saved_flags, \
__gmpfr_emin = (x).saved_emin, \
__gmpfr_emax = (x).saved_emax)
#define MPFR_SAVE_EXPO_UPDATE_FLAGS(x, flags) \
(x).saved_flags |= (flags)
/* Speed up final checking */
#define mpfr_check_range(x,t,r) \
(MPFR_LIKELY (MPFR_EXP (x) >= __gmpfr_emin && MPFR_EXP (x) <= __gmpfr_emax) \
? ((t) ? (__gmpfr_flags |= MPFR_FLAGS_INEXACT, (t)) : 0) \
: mpfr_check_range(x,t,r))
/******************************************************
***************** Inline Rounding *******************
******************************************************/
/*
* Note: due to the labels, one cannot use a macro MPFR_RNDRAW* more than
* once in a function (otherwise these labels would not be unique).
*/
/*
* Round mantissa (srcp, sprec) to mpfr_t dest using rounding mode rnd
* assuming dest's sign is sign.
* In rounding to nearest mode, execute MIDDLE_HANDLER when the value
* is the middle of two consecutive numbers in dest precision.
* Execute OVERFLOW_HANDLER in case of overflow when rounding.
*/
#define MPFR_RNDRAW_GEN(inexact, dest, srcp, sprec, rnd, sign, \
MIDDLE_HANDLER, OVERFLOW_HANDLER) \
do { \
mp_size_t _dests, _srcs; \
mp_limb_t *_destp; \
mpfr_prec_t _destprec, _srcprec; \
\
/* Check Trivial Case when Dest Mantissa has more bits than source */ \
_srcprec = (sprec); \
_destprec = MPFR_PREC (dest); \
_destp = MPFR_MANT (dest); \
if (MPFR_UNLIKELY (_destprec >= _srcprec)) \
{ \
_srcs = (_srcprec + GMP_NUMB_BITS-1)/GMP_NUMB_BITS; \
_dests = (_destprec + GMP_NUMB_BITS-1)/GMP_NUMB_BITS - _srcs; \
MPN_COPY (_destp + _dests, srcp, _srcs); \
MPN_ZERO (_destp, _dests); \
inexact = 0; \
} \
else \
{ \
/* Non trivial case: rounding needed */ \
mpfr_prec_t _sh; \
mp_limb_t *_sp; \
mp_limb_t _rb, _sb, _ulp; \
\
/* Compute Position and shift */ \
_srcs = (_srcprec + GMP_NUMB_BITS-1)/GMP_NUMB_BITS; \
_dests = (_destprec + GMP_NUMB_BITS-1)/GMP_NUMB_BITS; \
MPFR_UNSIGNED_MINUS_MODULO (_sh, _destprec); \
_sp = (srcp) + _srcs - _dests; \
\
/* General case when prec % GMP_NUMB_BITS != 0 */ \
if (MPFR_LIKELY (_sh != 0)) \
{ \
mp_limb_t _mask; \
/* Compute Rounding Bit and Sticky Bit */ \
/* Note: in directed rounding modes, if the rounding bit */ \
/* is 1, the behavior does not depend on the sticky bit; */ \
/* thus we will not try to compute it in this case (this */ \
/* can be much faster and avoids to read uninitialized */ \
/* data in the current mpfr_mul implementation). We just */ \
/* make sure that _sb is initialized. */ \
_mask = MPFR_LIMB_ONE << (_sh - 1); \
_rb = _sp[0] & _mask; \
_sb = _sp[0] & (_mask - 1); \
if (MPFR_UNLIKELY (_sb == 0) && \
((rnd) == MPFR_RNDN || _rb == 0)) \
{ /* TODO: Improve it */ \
mp_limb_t *_tmp; \
mp_size_t _n; \
for (_tmp = _sp, _n = _srcs - _dests ; \
_n != 0 && _sb == 0 ; _n--) \
_sb = *--_tmp; \
} \
_ulp = 2 * _mask; \
} \
else /* _sh == 0 */ \
{ \
MPFR_ASSERTD (_dests < _srcs); \
/* Compute Rounding Bit and Sticky Bit - see note above */ \
_rb = _sp[-1] & MPFR_LIMB_HIGHBIT; \
_sb = _sp[-1] & (MPFR_LIMB_HIGHBIT-1); \
if (MPFR_UNLIKELY (_sb == 0) && \
((rnd) == MPFR_RNDN || _rb == 0)) \
{ \
mp_limb_t *_tmp; \
mp_size_t _n; \
for (_tmp = _sp - 1, _n = _srcs - _dests - 1 ; \
_n != 0 && _sb == 0 ; _n--) \
_sb = *--_tmp; \
} \
_ulp = MPFR_LIMB_ONE; \
} \
/* Rounding */ \
if (MPFR_LIKELY (rnd == MPFR_RNDN)) \
{ \
if (_rb == 0) \
{ \
trunc: \
inexact = MPFR_LIKELY ((_sb | _rb) != 0) ? -sign : 0; \
trunc_doit: \
MPN_COPY (_destp, _sp, _dests); \
_destp[0] &= ~(_ulp - 1); \
} \
else if (MPFR_UNLIKELY (_sb == 0)) \
{ /* Middle of two consecutive representable numbers */ \
MIDDLE_HANDLER; \
} \
else \
{ \
if (0) \
goto addoneulp_doit; /* dummy code to avoid warning */ \
addoneulp: \
inexact = sign; \
addoneulp_doit: \
if (MPFR_UNLIKELY (mpn_add_1 (_destp, _sp, _dests, _ulp))) \
{ \
_destp[_dests - 1] = MPFR_LIMB_HIGHBIT; \
OVERFLOW_HANDLER; \
} \
_destp[0] &= ~(_ulp - 1); \
} \
} \
else \
{ /* Directed rounding mode */ \
if (MPFR_LIKELY (MPFR_IS_LIKE_RNDZ (rnd, \
MPFR_IS_NEG_SIGN (sign)))) \
goto trunc; \
else if (MPFR_UNLIKELY ((_sb | _rb) == 0)) \
{ \
inexact = 0; \
goto trunc_doit; \
} \
else \
goto addoneulp; \
} \
} \
} while (0)
/*
* Round mantissa (srcp, sprec) to mpfr_t dest using rounding mode rnd
* assuming dest's sign is sign.
* Execute OVERFLOW_HANDLER in case of overflow when rounding.
*/
#define MPFR_RNDRAW(inexact, dest, srcp, sprec, rnd, sign, OVERFLOW_HANDLER) \
MPFR_RNDRAW_GEN (inexact, dest, srcp, sprec, rnd, sign, \
if ((_sp[0] & _ulp) == 0) \
{ \
inexact = -sign; \
goto trunc_doit; \
} \
else \
goto addoneulp; \
, OVERFLOW_HANDLER)
/*
* Round mantissa (srcp, sprec) to mpfr_t dest using rounding mode rnd
* assuming dest's sign is sign.
* Execute OVERFLOW_HANDLER in case of overflow when rounding.
* Set inexact to +/- MPFR_EVEN_INEX in case of even rounding.
*/
#define MPFR_RNDRAW_EVEN(inexact, dest, srcp, sprec, rnd, sign, \
OVERFLOW_HANDLER) \
MPFR_RNDRAW_GEN (inexact, dest, srcp, sprec, rnd, sign, \
if ((_sp[0] & _ulp) == 0) \
{ \
inexact = -MPFR_EVEN_INEX * sign; \
goto trunc_doit; \
} \
else \
{ \
inexact = MPFR_EVEN_INEX * sign; \
goto addoneulp_doit; \
} \
, OVERFLOW_HANDLER)
/* Return TRUE if b is non singular and we can round it to precision 'prec'
and determine the ternary value, with rounding mode 'rnd', and with
error at most 'error' */
#define MPFR_CAN_ROUND(b,err,prec,rnd) \
(!MPFR_IS_SINGULAR (b) && mpfr_round_p (MPFR_MANT (b), MPFR_LIMB_SIZE (b), \
(err), (prec) + ((rnd)==MPFR_RNDN)))
/* Copy the sign and the significand, and handle the exponent in exp. */
#define MPFR_SETRAW(inexact,dest,src,exp,rnd) \
if (MPFR_UNLIKELY (dest != src)) \
{ \
MPFR_SET_SIGN (dest, MPFR_SIGN (src)); \
if (MPFR_LIKELY (MPFR_PREC (dest) == MPFR_PREC (src))) \
{ \
MPN_COPY (MPFR_MANT (dest), MPFR_MANT (src), \
(MPFR_PREC (src) + GMP_NUMB_BITS-1)/GMP_NUMB_BITS); \
inexact = 0; \
} \
else \
{ \
MPFR_RNDRAW (inexact, dest, MPFR_MANT (src), MPFR_PREC (src), \
rnd, MPFR_SIGN (src), exp++); \
} \
} \
else \
inexact = 0;
/* TODO: fix this description (see round_near_x.c). */
/* Assuming that the function has a Taylor expansion which looks like:
y=o(f(x)) = o(v + g(x)) with |g(x)| <= 2^(EXP(v)-err)
we can quickly set y to v if x is small (ie err > prec(y)+1) in most
cases. It assumes that f(x) is not representable exactly as a FP number.
v must not be a singular value (NAN, INF or ZERO); usual values are
v=1 or v=x.
y is the destination (a mpfr_t), v the value to set (a mpfr_t),
err1+err2 with err2 <= 3 the error term (mpfr_exp_t's), dir (an int) is
the direction of the committed error (if dir = 0, it rounds toward 0,
if dir=1, it rounds away from 0), rnd the rounding mode.
It returns from the function a ternary value in case of success.
If you want to free something, you must fill the "extra" field
in consequences, otherwise put nothing in it.
The test is less restrictive than necessary, but the function
will finish the check itself.
Note: err1 + err2 is allowed to overflow as mpfr_exp_t, but it must give
its real value as mpfr_uexp_t.
*/
#define MPFR_FAST_COMPUTE_IF_SMALL_INPUT(y,v,err1,err2,dir,rnd,extra) \
do { \
mpfr_ptr _y = (y); \
mpfr_exp_t _err1 = (err1); \
mpfr_exp_t _err2 = (err2); \
if (_err1 > 0) \
{ \
mpfr_uexp_t _err = (mpfr_uexp_t) _err1 + _err2; \
if (MPFR_UNLIKELY (_err > MPFR_PREC (_y) + 1)) \
{ \
int _inexact = mpfr_round_near_x (_y,(v),_err,(dir),(rnd)); \
if (_inexact != 0) \
{ \
extra; \
return _inexact; \
} \
} \
} \
} while (0)
/* Variant, to be called somewhere after MPFR_SAVE_EXPO_MARK. This variant
is needed when there are some computations before or when some non-zero
real constant is used, such as __gmpfr_one for mpfr_cos. */
#define MPFR_SMALL_INPUT_AFTER_SAVE_EXPO(y,v,err1,err2,dir,rnd,expo,extra) \
do { \
mpfr_ptr _y = (y); \
mpfr_exp_t _err1 = (err1); \
mpfr_exp_t _err2 = (err2); \
if (_err1 > 0) \
{ \
mpfr_uexp_t _err = (mpfr_uexp_t) _err1 + _err2; \
if (MPFR_UNLIKELY (_err > MPFR_PREC (_y) + 1)) \
{ \
int _inexact; \
mpfr_clear_flags (); \
_inexact = mpfr_round_near_x (_y,(v),_err,(dir),(rnd)); \
if (_inexact != 0) \
{ \
extra; \
MPFR_SAVE_EXPO_UPDATE_FLAGS (expo, __gmpfr_flags); \
MPFR_SAVE_EXPO_FREE (expo); \
return mpfr_check_range (_y, _inexact, (rnd)); \
} \
} \
} \
} while (0)
/******************************************************
*************** Ziv Loop Macro *********************
******************************************************/
#ifndef MPFR_USE_LOGGING
#define MPFR_ZIV_DECL(_x) mpfr_prec_t _x
#define MPFR_ZIV_INIT(_x, _p) (_x) = GMP_NUMB_BITS
#define MPFR_ZIV_NEXT(_x, _p) ((_p) += (_x), (_x) = (_p)/2)
#define MPFR_ZIV_FREE(x)
#else
/* The following test on glibc is there mainly for Darwin (Mac OS X), to
obtain a better error message. The real test should have been a test
concerning nested functions in gcc, which are disabled by default on
Darwin; but it is not possible to do that without a configure test. */
# if defined (__cplusplus) || !(__MPFR_GNUC(3,0) && __MPFR_GLIBC(2,0))
# error "Logging not supported (needs gcc >= 3.0 and GNU C Library >= 2.0)."
# endif
/* Use LOGGING */
/* Note: the mpfr_log_level >= 0 below avoids to take into account
Ziv loops used by the MPFR functions called by the mpfr_fprintf
in LOG_PRINT. */
#define MPFR_ZIV_DECL(_x) \
mpfr_prec_t _x; \
int _x ## _cpt = 1; \
static unsigned long _x ## _loop = 0, _x ## _bad = 0; \
static const char *_x ## _fname = __func__; \
auto void __attribute__ ((destructor)) x ## _f (void); \
void __attribute__ ((destructor)) x ## _f (void) { \
if (_x ## _loop != 0 && (MPFR_LOG_STAT_F & mpfr_log_type)) \
fprintf (mpfr_log_file, \
"%s: Ziv failed %2.2f%% (%lu bad cases / %lu calls)\n", \
_x ## _fname, (double) 100.0 * _x ## _bad / _x ## _loop, \
_x ## _bad, _x ## _loop ); }
#define MPFR_ZIV_INIT(_x, _p) \
do \
{ \
(_x) = GMP_NUMB_BITS; \
if (mpfr_log_level >= 0) \
_x ## _loop ++; \
if ((MPFR_LOG_BADCASE_F & mpfr_log_type) && \
(mpfr_log_current <= mpfr_log_level)) \
LOG_PRINT ("%s:ZIV 1st prec=%Pd\n", \
__func__, (mpfr_prec_t) (_p)); \
} \
while (0)
#define MPFR_ZIV_NEXT(_x, _p) \
do \
{ \
(_p) += (_x); \
(_x) = (_p) / 2; \
if (mpfr_log_level >= 0) \
_x ## _bad += (_x ## _cpt == 1); \
_x ## _cpt ++; \
if ((MPFR_LOG_BADCASE_F & mpfr_log_type) && \
(mpfr_log_current <= mpfr_log_level)) \
LOG_PRINT ("%s:ZIV new prec=%Pd\n", \
__func__, (mpfr_prec_t) (_p)); \
} \
while (0)
#define MPFR_ZIV_FREE(_x) \
do \
{ \
if ((MPFR_LOG_BADCASE_F & mpfr_log_type) && _x ## _cpt > 1 && \
(mpfr_log_current <= mpfr_log_level)) \
fprintf (mpfr_log_file, "%s:ZIV %d loops\n", \
__func__, _x ## _cpt); \
} \
while (0)
#endif
/******************************************************
*************** Logging Macros *********************
******************************************************/
/* The different kind of LOG */
#define MPFR_LOG_INPUT_F 1
#define MPFR_LOG_OUTPUT_F 2
#define MPFR_LOG_INTERNAL_F 4
#define MPFR_LOG_TIME_F 8
#define MPFR_LOG_BADCASE_F 16
#define MPFR_LOG_MSG_F 32
#define MPFR_LOG_STAT_F 64
#ifdef MPFR_USE_LOGGING
/* Check if we can support this feature */
# ifdef MPFR_USE_THREAD_SAFE
# error "Enable either `Logging' or `thread-safe', not both"
# endif
# if !__MPFR_GNUC(3,0)
# error "Logging not supported (GCC >= 3.0)"
# endif
#if defined (__cplusplus)
extern "C" {
#endif
__MPFR_DECLSPEC extern FILE *mpfr_log_file;
__MPFR_DECLSPEC extern int mpfr_log_type;
__MPFR_DECLSPEC extern int mpfr_log_level;
__MPFR_DECLSPEC extern int mpfr_log_current;
__MPFR_DECLSPEC extern mpfr_prec_t mpfr_log_prec;
#if defined (__cplusplus)
}
#endif
/* LOG_PRINT calls mpfr_fprintf on mpfr_log_file with logging disabled
(recursive logging is not wanted and freezes MPFR). */
#define LOG_PRINT(format, ...) \
do \
{ \
int old_level = mpfr_log_level; \
mpfr_log_level = -1; /* disable logging in mpfr_fprintf */ \
__gmpfr_cache_const_pi = __gmpfr_logging_pi; \
__gmpfr_cache_const_log2 = __gmpfr_logging_log2; \
mpfr_fprintf (mpfr_log_file, format, __VA_ARGS__); \
mpfr_log_level = old_level; \
__gmpfr_cache_const_pi = __gmpfr_normal_pi; \
__gmpfr_cache_const_log2 = __gmpfr_normal_log2; \
} \
while (0)
#define MPFR_LOG_VAR(x) \
do \
if ((MPFR_LOG_INTERNAL_F & mpfr_log_type) && \
(mpfr_log_current <= mpfr_log_level)) \
LOG_PRINT ("%s.%d:%s[%#Pu]=%.*Rf\n", __func__, __LINE__, \
#x, mpfr_get_prec (x), mpfr_log_prec, x); \
while (0)
#define MPFR_LOG_MSG2(format, ...) \
do \
if ((MPFR_LOG_MSG_F & mpfr_log_type) && \
(mpfr_log_current <= mpfr_log_level)) \
LOG_PRINT ("%s.%d: "format, __func__, __LINE__, __VA_ARGS__); \
while (0)
#define MPFR_LOG_MSG(x) MPFR_LOG_MSG2 x
#define MPFR_LOG_BEGIN2(format, ...) \
mpfr_log_current ++; \
if ((MPFR_LOG_INPUT_F & mpfr_log_type) && \
(mpfr_log_current <= mpfr_log_level)) \
LOG_PRINT ("%s:IN "format"\n", __func__, __VA_ARGS__); \
if ((MPFR_LOG_TIME_F & mpfr_log_type) && \
(mpfr_log_current <= mpfr_log_level)) \
__gmpfr_log_time = mpfr_get_cputime ();
#define MPFR_LOG_BEGIN(x) \
int __gmpfr_log_time = 0; \
MPFR_LOG_BEGIN2 x
#define MPFR_LOG_END2(format, ...) \
if ((MPFR_LOG_TIME_F & mpfr_log_type) && \
(mpfr_log_current <= mpfr_log_level)) \
fprintf (mpfr_log_file, "%s:TIM %dms\n", __mpfr_log_fname, \
mpfr_get_cputime () - __gmpfr_log_time); \
if ((MPFR_LOG_OUTPUT_F & mpfr_log_type) && \
(mpfr_log_current <= mpfr_log_level)) \
LOG_PRINT ("%s:OUT "format"\n", __mpfr_log_fname, __VA_ARGS__); \
mpfr_log_current --;
#define MPFR_LOG_END(x) \
static const char *__mpfr_log_fname = __func__; \
MPFR_LOG_END2 x
#define MPFR_LOG_FUNC(begin,end) \
static const char *__mpfr_log_fname = __func__; \
auto void __mpfr_log_cleanup (int *time); \
void __mpfr_log_cleanup (int *time) { \
int __gmpfr_log_time = *time; \
MPFR_LOG_END2 end; } \
int __gmpfr_log_time __attribute__ ((cleanup (__mpfr_log_cleanup))); \
__gmpfr_log_time = 0; \
MPFR_LOG_BEGIN2 begin
#else /* MPFR_USE_LOGGING */
/* Define void macro for logging */
#define MPFR_LOG_VAR(x)
#define MPFR_LOG_BEGIN(x)
#define MPFR_LOG_END(x)
#define MPFR_LOG_MSG(x)
#define MPFR_LOG_FUNC(x,y)
#endif /* MPFR_USE_LOGGING */
/**************************************************************
************ Group Initialize Functions Macros *************
**************************************************************/
#ifndef MPFR_GROUP_STATIC_SIZE
# define MPFR_GROUP_STATIC_SIZE 16
#endif
struct mpfr_group_t {
size_t alloc;
mp_limb_t *mant;
mp_limb_t tab[MPFR_GROUP_STATIC_SIZE];
};
#define MPFR_GROUP_DECL(g) struct mpfr_group_t g
#define MPFR_GROUP_CLEAR(g) do { \
MPFR_LOG_MSG (("GROUP_CLEAR: ptr = 0x%lX, size = %lu\n", \
(unsigned long) (g).mant, \
(unsigned long) (g).alloc)); \
if (MPFR_UNLIKELY ((g).alloc != 0)) { \
MPFR_ASSERTD ((g).mant != (g).tab); \
(*__gmp_free_func) ((g).mant, (g).alloc); \
}} while (0)
#define MPFR_GROUP_INIT_TEMPLATE(g, prec, num, handler) do { \
mpfr_prec_t _prec = (prec); \
mp_size_t _size; \
MPFR_ASSERTD (_prec >= MPFR_PREC_MIN); \
if (MPFR_UNLIKELY (_prec > MPFR_PREC_MAX)) \
mpfr_abort_prec_max (); \
_size = (mpfr_prec_t) (_prec + GMP_NUMB_BITS - 1) / GMP_NUMB_BITS; \
if (MPFR_UNLIKELY (_size * (num) > MPFR_GROUP_STATIC_SIZE)) \
{ \
(g).alloc = (num) * _size * sizeof (mp_limb_t); \
(g).mant = (mp_limb_t *) (*__gmp_allocate_func) ((g).alloc); \
} \
else \
{ \
(g).alloc = 0; \
(g).mant = (g).tab; \
} \
MPFR_LOG_MSG (("GROUP_INIT: ptr = 0x%lX, size = %lu\n", \
(unsigned long) (g).mant, (unsigned long) (g).alloc)); \
handler; \
} while (0)
#define MPFR_GROUP_TINIT(g, n, x) \
MPFR_TMP_INIT1 ((g).mant + _size * (n), x, _prec)
#define MPFR_GROUP_INIT_1(g, prec, x) \
MPFR_GROUP_INIT_TEMPLATE(g, prec, 1, MPFR_GROUP_TINIT(g, 0, x))
#define MPFR_GROUP_INIT_2(g, prec, x, y) \
MPFR_GROUP_INIT_TEMPLATE(g, prec, 2, \
MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y))
#define MPFR_GROUP_INIT_3(g, prec, x, y, z) \
MPFR_GROUP_INIT_TEMPLATE(g, prec, 3, \
MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y); \
MPFR_GROUP_TINIT(g, 2, z))
#define MPFR_GROUP_INIT_4(g, prec, x, y, z, t) \
MPFR_GROUP_INIT_TEMPLATE(g, prec, 4, \
MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y); \
MPFR_GROUP_TINIT(g, 2, z);MPFR_GROUP_TINIT(g, 3, t))
#define MPFR_GROUP_INIT_5(g, prec, x, y, z, t, a) \
MPFR_GROUP_INIT_TEMPLATE(g, prec, 5, \
MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y); \
MPFR_GROUP_TINIT(g, 2, z);MPFR_GROUP_TINIT(g, 3, t); \
MPFR_GROUP_TINIT(g, 4, a))
#define MPFR_GROUP_INIT_6(g, prec, x, y, z, t, a, b) \
MPFR_GROUP_INIT_TEMPLATE(g, prec, 6, \
MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y); \
MPFR_GROUP_TINIT(g, 2, z);MPFR_GROUP_TINIT(g, 3, t); \
MPFR_GROUP_TINIT(g, 4, a);MPFR_GROUP_TINIT(g, 5, b))
#define MPFR_GROUP_REPREC_TEMPLATE(g, prec, num, handler) do { \
mpfr_prec_t _prec = (prec); \
size_t _oalloc = (g).alloc; \
mp_size_t _size; \
MPFR_LOG_MSG (("GROUP_REPREC: oldptr = 0x%lX, oldsize = %lu\n", \
(unsigned long) (g).mant, (unsigned long) _oalloc)); \
MPFR_ASSERTD (_prec >= MPFR_PREC_MIN); \
if (MPFR_UNLIKELY (_prec > MPFR_PREC_MAX)) \
mpfr_abort_prec_max (); \
_size = (mpfr_prec_t) (_prec + GMP_NUMB_BITS - 1) / GMP_NUMB_BITS; \
(g).alloc = (num) * _size * sizeof (mp_limb_t); \
if (MPFR_LIKELY (_oalloc == 0)) \
(g).mant = (mp_limb_t *) (*__gmp_allocate_func) ((g).alloc); \
else \
(g).mant = (mp_limb_t *) \
(*__gmp_reallocate_func) ((g).mant, _oalloc, (g).alloc); \
MPFR_LOG_MSG (("GROUP_REPREC: newptr = 0x%lX, newsize = %lu\n", \
(unsigned long) (g).mant, (unsigned long) (g).alloc)); \
handler; \
} while (0)
#define MPFR_GROUP_REPREC_1(g, prec, x) \
MPFR_GROUP_REPREC_TEMPLATE(g, prec, 1, MPFR_GROUP_TINIT(g, 0, x))
#define MPFR_GROUP_REPREC_2(g, prec, x, y) \
MPFR_GROUP_REPREC_TEMPLATE(g, prec, 2, \
MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y))
#define MPFR_GROUP_REPREC_3(g, prec, x, y, z) \
MPFR_GROUP_REPREC_TEMPLATE(g, prec, 3, \
MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y); \
MPFR_GROUP_TINIT(g, 2, z))
#define MPFR_GROUP_REPREC_4(g, prec, x, y, z, t) \
MPFR_GROUP_REPREC_TEMPLATE(g, prec, 4, \
MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y); \
MPFR_GROUP_TINIT(g, 2, z);MPFR_GROUP_TINIT(g, 3, t))
#define MPFR_GROUP_REPREC_5(g, prec, x, y, z, t, a) \
MPFR_GROUP_REPREC_TEMPLATE(g, prec, 5, \
MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y); \
MPFR_GROUP_TINIT(g, 2, z);MPFR_GROUP_TINIT(g, 3, t); \
MPFR_GROUP_TINIT(g, 4, a))
#define MPFR_GROUP_REPREC_6(g, prec, x, y, z, t, a, b) \
MPFR_GROUP_REPREC_TEMPLATE(g, prec, 6, \
MPFR_GROUP_TINIT(g, 0, x);MPFR_GROUP_TINIT(g, 1, y); \
MPFR_GROUP_TINIT(g, 2, z);MPFR_GROUP_TINIT(g, 3, t); \
MPFR_GROUP_TINIT(g, 4, a);MPFR_GROUP_TINIT(g, 5, b))
/******************************************************
*************** Internal Functions *****************
******************************************************/
#if defined (__cplusplus)
extern "C" {
#endif
__MPFR_DECLSPEC int mpfr_underflow _MPFR_PROTO ((mpfr_ptr, mpfr_rnd_t, int));
__MPFR_DECLSPEC int mpfr_overflow _MPFR_PROTO ((mpfr_ptr, mpfr_rnd_t, int));
__MPFR_DECLSPEC int mpfr_add1 _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,
mpfr_srcptr, mpfr_rnd_t));
__MPFR_DECLSPEC int mpfr_sub1 _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,
mpfr_srcptr, mpfr_rnd_t));
__MPFR_DECLSPEC int mpfr_add1sp _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,
mpfr_srcptr, mpfr_rnd_t));
__MPFR_DECLSPEC int mpfr_sub1sp _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,
mpfr_srcptr, mpfr_rnd_t));
__MPFR_DECLSPEC int mpfr_can_round_raw _MPFR_PROTO ((const mp_limb_t *,
mp_size_t, int, mpfr_exp_t, mpfr_rnd_t, mpfr_rnd_t, mpfr_prec_t));
__MPFR_DECLSPEC int mpfr_cmp2 _MPFR_PROTO ((mpfr_srcptr, mpfr_srcptr,
mpfr_prec_t *));
__MPFR_DECLSPEC long __gmpfr_ceil_log2 _MPFR_PROTO ((double));
__MPFR_DECLSPEC long __gmpfr_floor_log2 _MPFR_PROTO ((double));
__MPFR_DECLSPEC double __gmpfr_ceil_exp2 _MPFR_PROTO ((double));
__MPFR_DECLSPEC unsigned long __gmpfr_isqrt _MPFR_PROTO ((unsigned long));
__MPFR_DECLSPEC unsigned long __gmpfr_cuberoot _MPFR_PROTO ((unsigned long));
__MPFR_DECLSPEC int __gmpfr_int_ceil_log2 _MPFR_PROTO ((unsigned long));
__MPFR_DECLSPEC mpfr_exp_t mpfr_ceil_mul _MPFR_PROTO ((mpfr_exp_t, int, int));
__MPFR_DECLSPEC int mpfr_exp_2 _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,mpfr_rnd_t));
__MPFR_DECLSPEC int mpfr_exp_3 _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,mpfr_rnd_t));
__MPFR_DECLSPEC int mpfr_powerof2_raw _MPFR_PROTO ((mpfr_srcptr));
__MPFR_DECLSPEC int mpfr_pow_general _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,
mpfr_srcptr, mpfr_rnd_t, int, mpfr_save_expo_t *));
__MPFR_DECLSPEC void mpfr_setmax _MPFR_PROTO ((mpfr_ptr, mpfr_exp_t));
__MPFR_DECLSPEC void mpfr_setmin _MPFR_PROTO ((mpfr_ptr, mpfr_exp_t));
__MPFR_DECLSPEC long mpfr_mpn_exp _MPFR_PROTO ((mp_limb_t *, mpfr_exp_t *, int,
mpfr_exp_t, size_t));
#ifdef _MPFR_H_HAVE_FILE
__MPFR_DECLSPEC void mpfr_fprint_binary _MPFR_PROTO ((FILE *, mpfr_srcptr));
#endif
__MPFR_DECLSPEC void mpfr_print_binary _MPFR_PROTO ((mpfr_srcptr));
__MPFR_DECLSPEC void mpfr_print_mant_binary _MPFR_PROTO ((const char*,
const mp_limb_t*, mpfr_prec_t));
__MPFR_DECLSPEC void mpfr_set_str_binary _MPFR_PROTO((mpfr_ptr, const char*));
__MPFR_DECLSPEC int mpfr_round_raw _MPFR_PROTO ((mp_limb_t *,
const mp_limb_t *, mpfr_prec_t, int, mpfr_prec_t, mpfr_rnd_t, int *));
__MPFR_DECLSPEC int mpfr_round_raw_2 _MPFR_PROTO ((const mp_limb_t *,
mpfr_prec_t, int, mpfr_prec_t, mpfr_rnd_t));
/* No longer defined (see round_prec.c).
Uncomment if it needs to be defined again.
__MPFR_DECLSPEC int mpfr_round_raw_3 _MPFR_PROTO ((const mp_limb_t *,
mpfr_prec_t, int, mpfr_prec_t, mpfr_rnd_t, int *));
*/
__MPFR_DECLSPEC int mpfr_round_raw_4 _MPFR_PROTO ((mp_limb_t *,
const mp_limb_t *, mpfr_prec_t, int, mpfr_prec_t, mpfr_rnd_t));
#define mpfr_round_raw2(xp, xn, neg, r, prec) \
mpfr_round_raw_2((xp),(xn)*GMP_NUMB_BITS,(neg),(prec),(r))
__MPFR_DECLSPEC int mpfr_check _MPFR_PROTO ((mpfr_srcptr));
__MPFR_DECLSPEC int mpfr_sum_sort _MPFR_PROTO ((mpfr_srcptr *const,
unsigned long, mpfr_srcptr *));
__MPFR_DECLSPEC int mpfr_get_cputime _MPFR_PROTO ((void));
__MPFR_DECLSPEC void mpfr_nexttozero _MPFR_PROTO ((mpfr_ptr));
__MPFR_DECLSPEC void mpfr_nexttoinf _MPFR_PROTO ((mpfr_ptr));
__MPFR_DECLSPEC int mpfr_const_pi_internal _MPFR_PROTO ((mpfr_ptr,mpfr_rnd_t));
__MPFR_DECLSPEC int mpfr_const_log2_internal _MPFR_PROTO((mpfr_ptr,mpfr_rnd_t));
__MPFR_DECLSPEC int mpfr_const_euler_internal _MPFR_PROTO((mpfr_ptr, mpfr_rnd_t));
__MPFR_DECLSPEC int mpfr_const_catalan_internal _MPFR_PROTO((mpfr_ptr, mpfr_rnd_t));
#if 0
__MPFR_DECLSPEC void mpfr_init_cache _MPFR_PROTO ((mpfr_cache_t,
int(*)(mpfr_ptr,mpfr_rnd_t)));
#endif
__MPFR_DECLSPEC void mpfr_clear_cache _MPFR_PROTO ((mpfr_cache_t));
__MPFR_DECLSPEC int mpfr_cache _MPFR_PROTO ((mpfr_ptr, mpfr_cache_t,
mpfr_rnd_t));
__MPFR_DECLSPEC void mpfr_mulhigh_n _MPFR_PROTO ((mpfr_limb_ptr,
mpfr_limb_srcptr, mpfr_limb_srcptr, mp_size_t));
__MPFR_DECLSPEC void mpfr_mullow_n _MPFR_PROTO ((mpfr_limb_ptr,
mpfr_limb_srcptr, mpfr_limb_srcptr, mp_size_t));
__MPFR_DECLSPEC void mpfr_sqrhigh_n _MPFR_PROTO ((mpfr_limb_ptr,
mpfr_limb_srcptr, mp_size_t));
__MPFR_DECLSPEC mp_limb_t mpfr_divhigh_n _MPFR_PROTO ((mpfr_limb_ptr,
mpfr_limb_ptr, mpfr_limb_ptr, mp_size_t));
__MPFR_DECLSPEC int mpfr_round_p _MPFR_PROTO ((mp_limb_t *, mp_size_t,
mpfr_exp_t, mpfr_prec_t));
__MPFR_DECLSPEC void mpfr_dump_mant _MPFR_PROTO ((const mp_limb_t *,
mpfr_prec_t, mpfr_prec_t,
mpfr_prec_t));
__MPFR_DECLSPEC int mpfr_round_near_x _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,
mpfr_uexp_t, int,
mpfr_rnd_t));
__MPFR_DECLSPEC void mpfr_abort_prec_max _MPFR_PROTO ((void))
MPFR_NORETURN_ATTR;
__MPFR_DECLSPEC void mpfr_rand_raw _MPFR_PROTO((mpfr_limb_ptr, gmp_randstate_t,
unsigned long));
__MPFR_DECLSPEC mpz_t* mpfr_bernoulli_internal _MPFR_PROTO((mpz_t*,
unsigned long));
__MPFR_DECLSPEC int mpfr_sincos_fast _MPFR_PROTO((mpfr_t, mpfr_t,
mpfr_srcptr, mpfr_rnd_t));
__MPFR_DECLSPEC double mpfr_scale2 _MPFR_PROTO((double, int));
__MPFR_DECLSPEC void mpfr_div_ui2 _MPFR_PROTO((mpfr_ptr, mpfr_srcptr,
unsigned long int, unsigned long int,
mpfr_rnd_t));
__MPFR_DECLSPEC void mpfr_gamma_one_and_two_third _MPFR_PROTO((mpfr_ptr, mpfr_ptr, mpfr_prec_t));
#if defined (__cplusplus)
}
#endif
#endif
| Java |
/**
*/
package net.paissad.waqtsalat.core.impl;
import java.util.Calendar;
import net.paissad.waqtsalat.core.WaqtSalatPackage;
import net.paissad.waqtsalat.core.api.Pray;
import net.paissad.waqtsalat.core.api.PrayName;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
/**
* <!-- begin-user-doc --> An implementation of the model object ' <em><b>Pray</b></em>'. <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link net.paissad.waqtsalat.core.impl.PrayImpl#getName <em>Name</em>}</li>
* <li>{@link net.paissad.waqtsalat.core.impl.PrayImpl#getTime <em>Time</em>}</li>
* <li>{@link net.paissad.waqtsalat.core.impl.PrayImpl#isPlayingAdhan <em>Playing Adhan</em>}</li>
* <li>{@link net.paissad.waqtsalat.core.impl.PrayImpl#getAdhanPlayer <em>Adhan Player</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class PrayImpl extends MinimalEObjectImpl.Container implements Pray {
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @see #getName()
* @generated
* @ordered
*/
protected static final PrayName NAME_EDEFAULT = PrayName.FADJR;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @see #getName()
* @generated
* @ordered
*/
protected PrayName name = NAME_EDEFAULT;
/**
* The default value of the '{@link #getTime() <em>Time</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @see #getTime()
* @generated
* @ordered
*/
protected static final Calendar TIME_EDEFAULT = null;
/**
* The cached value of the '{@link #getTime() <em>Time</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @see #getTime()
* @generated
* @ordered
*/
protected Calendar time = TIME_EDEFAULT;
/**
* The default value of the '{@link #isPlayingAdhan() <em>Playing Adhan</em>}' attribute. <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #isPlayingAdhan()
* @generated
* @ordered
*/
protected static final boolean PLAYING_ADHAN_EDEFAULT = false;
/**
* The cached value of the '{@link #isPlayingAdhan() <em>Playing Adhan</em>}' attribute. <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #isPlayingAdhan()
* @generated
* @ordered
*/
protected boolean playingAdhan = PLAYING_ADHAN_EDEFAULT;
/**
* The default value of the '{@link #getAdhanPlayer() <em>Adhan Player</em>}' attribute. <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getAdhanPlayer()
* @generated
* @ordered
*/
protected static final Object ADHAN_PLAYER_EDEFAULT = null;
/**
* The cached value of the '{@link #getAdhanPlayer() <em>Adhan Player</em>}' attribute. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @see #getAdhanPlayer()
* @generated
* @ordered
*/
protected Object adhanPlayer = ADHAN_PLAYER_EDEFAULT;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected PrayImpl() {
super();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
protected EClass eStaticClass() {
return WaqtSalatPackage.Literals.PRAY;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public PrayName getName() {
return name;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setName(PrayName newName) {
PrayName oldName = name;
name = newName == null ? NAME_EDEFAULT : newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, WaqtSalatPackage.PRAY__NAME, oldName, name));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public Calendar getTime() {
return time;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setTime(Calendar newTime) {
Calendar oldTime = time;
time = newTime;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, WaqtSalatPackage.PRAY__TIME, oldTime, time));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public boolean isPlayingAdhan() {
return playingAdhan;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setPlayingAdhan(boolean newPlayingAdhan) {
boolean oldPlayingAdhan = playingAdhan;
playingAdhan = newPlayingAdhan;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, WaqtSalatPackage.PRAY__PLAYING_ADHAN,
oldPlayingAdhan, playingAdhan));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public Object getAdhanPlayer() {
return adhanPlayer;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setAdhanPlayer(Object newAdhanPlayer) {
Object oldAdhanPlayer = adhanPlayer;
adhanPlayer = newAdhanPlayer;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, WaqtSalatPackage.PRAY__ADHAN_PLAYER, oldAdhanPlayer,
adhanPlayer));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case WaqtSalatPackage.PRAY__NAME:
return getName();
case WaqtSalatPackage.PRAY__TIME:
return getTime();
case WaqtSalatPackage.PRAY__PLAYING_ADHAN:
return isPlayingAdhan();
case WaqtSalatPackage.PRAY__ADHAN_PLAYER:
return getAdhanPlayer();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case WaqtSalatPackage.PRAY__NAME:
setName((PrayName) newValue);
return;
case WaqtSalatPackage.PRAY__TIME:
setTime((Calendar) newValue);
return;
case WaqtSalatPackage.PRAY__PLAYING_ADHAN:
setPlayingAdhan((Boolean) newValue);
return;
case WaqtSalatPackage.PRAY__ADHAN_PLAYER:
setAdhanPlayer(newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case WaqtSalatPackage.PRAY__NAME:
setName(NAME_EDEFAULT);
return;
case WaqtSalatPackage.PRAY__TIME:
setTime(TIME_EDEFAULT);
return;
case WaqtSalatPackage.PRAY__PLAYING_ADHAN:
setPlayingAdhan(PLAYING_ADHAN_EDEFAULT);
return;
case WaqtSalatPackage.PRAY__ADHAN_PLAYER:
setAdhanPlayer(ADHAN_PLAYER_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case WaqtSalatPackage.PRAY__NAME:
return name != NAME_EDEFAULT;
case WaqtSalatPackage.PRAY__TIME:
return TIME_EDEFAULT == null ? time != null : !TIME_EDEFAULT.equals(time);
case WaqtSalatPackage.PRAY__PLAYING_ADHAN:
return playingAdhan != PLAYING_ADHAN_EDEFAULT;
case WaqtSalatPackage.PRAY__ADHAN_PLAYER:
return ADHAN_PLAYER_EDEFAULT == null ? adhanPlayer != null : !ADHAN_PLAYER_EDEFAULT.equals(adhanPlayer);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (name: "); //$NON-NLS-1$
result.append(name);
result.append(", time: "); //$NON-NLS-1$
result.append(time);
result.append(", playingAdhan: "); //$NON-NLS-1$
result.append(playingAdhan);
result.append(", adhanPlayer: "); //$NON-NLS-1$
result.append(adhanPlayer);
result.append(')');
return result.toString();
}
} // PrayImpl
| Java |
package xigua.battle.of.elements.model;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class IntWithMaxTest {
private IntWithMax intWithMax;
@Before
public void setUp() {
intWithMax = new IntWithMax(42);
}
@Test
public void getValue_WithCorrectValue() {
assertThat(intWithMax.getValue()).isEqualTo(42);
}
@Test
public void setWhenValueBiggerThanMax_CorrectValueSet() {
intWithMax.setValue(100);
assertThat(intWithMax.getValue()).isEqualTo(42);
}
@Test
public void setWhenValueSmallerThanMax_CorrectValueSet() {
intWithMax.setValue(1);
assertThat(intWithMax.getValue()).isEqualTo(1);
}
@Test
public void getMax_WithCorrectMax() {
assertThat(intWithMax.getMaxValue()).isEqualTo(42);
}
}
| Java |
import {
DASHBOARD_ACTIVE_COIN_CHANGE,
DASHBOARD_ACTIVE_COIN_BALANCE,
DASHBOARD_ACTIVE_COIN_SEND_FORM,
DASHBOARD_ACTIVE_COIN_RECEIVE_FORM,
DASHBOARD_ACTIVE_COIN_RESET_FORMS,
DASHBOARD_ACTIVE_SECTION,
DASHBOARD_ACTIVE_TXINFO_MODAL,
ACTIVE_COIN_GET_ADDRESSES,
DASHBOARD_ACTIVE_COIN_NATIVE_BALANCE,
DASHBOARD_ACTIVE_COIN_NATIVE_TXHISTORY,
DASHBOARD_ACTIVE_COIN_NATIVE_OPIDS,
DASHBOARD_ACTIVE_COIN_SENDTO,
DASHBOARD_ACTIVE_ADDRESS,
DASHBOARD_ACTIVE_COIN_GETINFO_FAILURE,
SYNCING_NATIVE_MODE,
DASHBOARD_UPDATE,
DASHBOARD_ELECTRUM_BALANCE,
DASHBOARD_ELECTRUM_TRANSACTIONS,
DASHBOARD_REMOVE_COIN,
DASHBOARD_ACTIVE_COIN_NET_PEERS,
DASHBOARD_ACTIVE_COIN_NET_TOTALS,
KV_HISTORY,
DASHBOARD_ETHEREUM_BALANCE,
DASHBOARD_ETHEREUM_TRANSACTIONS,
DASHBOARD_CLEAR_ACTIVECOIN,
} from '../actions/storeType';
// TODO: refactor current coin props copy on change
const defaults = {
native: {
coin: null,
mode: null,
send: false,
receive: false,
balance: 0,
addresses: null,
activeSection: 'default',
showTransactionInfo: false,
showTransactionInfoTxIndex: null,
txhistory: [],
opids: null,
lastSendToResponse: null,
progress: null,
rescanInProgress: false,
getinfoFetchFailures: 0,
net: {
peers: null,
totals: null,
},
},
spv: {
coin: null,
mode: null,
send: false,
receive: false,
balance: 0,
addresses: null,
activeSection: 'default',
showTransactionInfo: false,
showTransactionInfoTxIndex: null,
txhistory: [],
lastSendToResponse: null,
},
eth: {
coin: null,
mode: null,
send: false,
receive: false,
balance: 0,
addresses: null,
activeSection: 'default',
showTransactionInfo: false,
showTransactionInfoTxIndex: null,
txhistory: [],
lastSendToResponse: null,
},
};
const checkCoinObjectKeys = (obj, mode) => {
if (Object.keys(obj).length &&
mode) {
for (let key in obj) {
if (!defaults[mode].hasOwnProperty(key)) {
delete obj[key];
}
}
}
return obj;
};
export const ActiveCoin = (state = {
coins: {
native: {},
spv: {},
eth: {},
},
coin: null,
mode: null,
send: false,
receive: false,
balance: 0,
addresses: null,
activeSection: 'default',
showTransactionInfo: false,
showTransactionInfoTxIndex: null,
txhistory: [],
opids: null,
lastSendToResponse: null,
activeAddress: null,
progress: null,
rescanInProgress: false,
getinfoFetchFailures: 0,
net: {
peers: null,
totals: null,
},
}, action) => {
switch (action.type) {
case DASHBOARD_REMOVE_COIN:
delete state.coins[action.mode][action.coin];
if (state.coin === action.coin) {
return {
...state,
...defaults[action.mode],
};
} else {
return {
...state,
};
}
case DASHBOARD_ACTIVE_COIN_CHANGE:
if (state.coins[action.mode] &&
state.coins[action.mode][action.coin]) {
let _coins = state.coins;
if (action.mode === state.mode) {
const _coinData = state.coins[action.mode][action.coin];
const _coinDataToStore = checkCoinObjectKeys({
addresses: state.addresses,
coin: state.coin,
mode: state.mode,
balance: state.balance,
txhistory: state.txhistory,
send: state.send,
receive: state.receive,
showTransactionInfo: state.showTransactionInfo,
showTransactionInfoTxIndex: state.showTransactionInfoTxIndex,
activeSection: state.activeSection,
lastSendToResponse: state.lastSendToResponse,
opids: state.mode === 'native' ? state.opids : null,
activeAddress: state.activeAddress,
progress: state.mode === 'native' ? state.progress : null,
rescanInProgress: state.mode === 'native' ? state.rescanInProgress : false,
getinfoFetchFailures: state.mode === 'native' ? state.getinfoFetchFailures : 0,
net: state.mode === 'native' ? state.net : {},
}, action.mode);
if (!action.skip) {
_coins[action.mode][state.coin] = _coinDataToStore;
}
delete _coins.undefined;
return {
...state,
coins: _coins,
...checkCoinObjectKeys({
addresses: _coinData.addresses,
coin: _coinData.coin,
mode: _coinData.mode,
balance: _coinData.balance,
txhistory: _coinData.txhistory,
send: _coinData.send,
receive: _coinData.receive,
showTransactionInfo: _coinData.showTransactionInfo,
showTransactionInfoTxIndex: _coinData.showTransactionInfoTxIndex,
activeSection: _coinData.activeSection,
lastSendToResponse: _coinData.lastSendToResponse,
opids: _coinData.mode === 'native' ? _coinData.opids : null,
activeAddress: _coinData.activeAddress,
progress: _coinData.mode === 'native' ? _coinData.progress : null,
rescanInProgress: _coinData.mode === 'native' ? _coinData.rescanInProgress : false,
getinfoFetchFailures: _coinData.mode === 'native' ? _coinData.getinfoFetchFailures : 0,
net: _coinData.mode === 'native' ? _coinData.net : {},
}, _coinData.mode),
};
} else {
delete _coins.undefined;
return {
...state,
coins: state.coins,
...checkCoinObjectKeys({
coin: action.coin,
mode: action.mode,
balance: 0,
addresses: null,
txhistory: 'loading',
send: false,
receive: false,
showTransactionInfo: false,
showTransactionInfoTxIndex: null,
activeSection: 'default',
progress: null,
rescanInProgress: false,
net: {
peers: null,
totals: null,
},
}, action.mode),
};
}
} else {
if (state.coin) {
const _coinData = checkCoinObjectKeys({
addresses: state.addresses,
coin: state.coin,
mode: state.mode,
balance: state.balance,
txhistory: state.txhistory,
send: state.send,
receive: state.receive,
showTransactionInfo: state.showTransactionInfo,
showTransactionInfoTxIndex: state.showTransactionInfoTxIndex,
activeSection: state.activeSection,
lastSendToResponse: state.lastSendToResponse,
opids: state.mode === 'native' ? state.opids : null,
activeAddress: state.activeAddress,
progress: state.mode === 'native' ? state.progress : null,
rescanInProgress: state.mode === 'native' ? state.rescanInProgress : false,
getinfoFetchFailures: state.mode === 'native' ? state.getinfoFetchFailures : 0,
net: state.mode === 'native' ? state.net : {},
}, state.mode);
let _coins = state.coins;
if (!action.skip &&
_coins[action.mode]) {
_coins[action.mode][state.coin] = _coinData;
}
return {
...state,
coins: _coins,
...checkCoinObjectKeys({
coin: action.coin,
mode: action.mode,
balance: 0,
addresses: null,
txhistory: 'loading',
send: false,
receive: false,
showTransactionInfo: false,
showTransactionInfoTxIndex: null,
activeSection: 'default',
progress: null,
rescanInProgress: false,
net: {
peers: null,
totals: null,
},
}, action.mode),
};
} else {
return {
...state,
...checkCoinObjectKeys({
coin: action.coin,
mode: action.mode,
balance: 0,
addresses: null,
txhistory: 'loading',
send: false,
receive: false,
showTransactionInfo: false,
showTransactionInfoTxIndex: null,
activeSection: 'default',
progress: null,
rescanInProgress: false,
net: {
peers: null,
totals: null,
},
}, action.mode),
};
}
}
case DASHBOARD_ELECTRUM_BALANCE:
return {
...state,
balance: action.balance,
};
case DASHBOARD_ELECTRUM_TRANSACTIONS:
return {
...state,
txhistory: action.txhistory,
};
case DASHBOARD_ACTIVE_COIN_BALANCE:
return {
...state,
balance: action.balance,
};
case DASHBOARD_ACTIVE_COIN_SEND_FORM:
return {
...state,
send: action.send,
receive: false,
};
case DASHBOARD_ACTIVE_COIN_RECEIVE_FORM:
return {
...state,
send: false,
receive: action.receive,
};
case DASHBOARD_ACTIVE_COIN_RESET_FORMS:
return {
...state,
send: false,
receive: false,
};
case ACTIVE_COIN_GET_ADDRESSES:
return {
...state,
addresses: action.addresses,
};
case DASHBOARD_ACTIVE_SECTION:
return {
...state,
activeSection: action.section,
};
case DASHBOARD_ACTIVE_TXINFO_MODAL:
return {
...state,
showTransactionInfo: action.showTransactionInfo,
showTransactionInfoTxIndex: action.showTransactionInfoTxIndex,
};
case DASHBOARD_ACTIVE_COIN_NATIVE_BALANCE:
return {
...state,
balance: action.balance,
};
case DASHBOARD_ACTIVE_COIN_NATIVE_TXHISTORY:
return {
...state,
txhistory: action.txhistory,
};
case DASHBOARD_ACTIVE_COIN_NATIVE_OPIDS:
return {
...state,
opids: action.opids,
};
case DASHBOARD_ACTIVE_COIN_SENDTO:
return {
...state,
lastSendToResponse: action.lastSendToResponse,
};
case DASHBOARD_ACTIVE_ADDRESS:
return {
...state,
activeAddress: action.address,
};
case SYNCING_NATIVE_MODE:
return {
...state,
progress: state.mode === 'native' ? action.progress : null,
getinfoFetchFailures: typeof action.progress === 'string' && action.progress.indexOf('"code":-777') ? state.getinfoFetchFailures + 1 : 0,
};
case DASHBOARD_ACTIVE_COIN_GETINFO_FAILURE:
return {
...state,
getinfoFetchFailures: state.getinfoFetchFailures + 1,
};
case DASHBOARD_UPDATE:
if (state.coin === action.coin) {
return {
...state,
opids: action.opids,
txhistory: action.txhistory,
balance: action.balance,
addresses: action.addresses,
rescanInProgress: action.rescanInProgress,
};
}
case DASHBOARD_ACTIVE_COIN_NET_PEERS:
return {
...state,
net: {
peers: action.peers,
totals: state.net.totals,
},
};
case DASHBOARD_ACTIVE_COIN_NET_TOTALS:
return {
...state,
net: {
peers: state.net.peers,
totals: action.totals,
},
};
case DASHBOARD_ETHEREUM_BALANCE:
return {
...state,
balance: action.balance,
};
case DASHBOARD_ETHEREUM_TRANSACTIONS:
return {
...state,
txhistory: action.txhistory,
};
case DASHBOARD_CLEAR_ACTIVECOIN:
return {
coins: {
native: {},
spv: {},
eth: {},
},
coin: null,
mode: null,
balance: 0,
addresses: null,
txhistory: 'loading',
send: false,
receive: false,
showTransactionInfo: false,
showTransactionInfoTxIndex: null,
activeSection: 'default',
progress: null,
rescanInProgress: false,
net: {
peers: null,
totals: null,
},
getinfoFetchFailures: 0,
};
default:
return state;
}
}
export default ActiveCoin; | Java |
#ifndef DATASOURCE_H
#define DATASOURCE_H
#include <QArray>
#include <QVector3D>
#include <QColor4ub>
#include <QObject>
#include <QVector2D>
#include <QGLVertexBundle>
#include <iostream>
#include "databundle.h"
using std::cerr;
using std::endl;
class DataSource : public QObject
{
Q_OBJECT
public:
DataSource(QObject *parent = 0);
virtual QArray<DataBundle*> *dataBundles() {
cerr << "Returning from abstract DataSource."
"This should not happen." << endl;
return 0;
}
};
#endif
| Java |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <volk_fft/volk_fft_prefs.h>
//#if defined(_WIN32)
//#include <Windows.h>
//#endif
void volk_fft_get_config_path(char *path)
{
if (!path) return;
const char *suffix = "/.volk_fft/volk_fft_config";
char *home = NULL;
if (home == NULL) home = getenv("HOME");
if (home == NULL) home = getenv("APPDATA");
if (home == NULL){
path[0] = 0;
return;
}
strcpy(path, home);
strcat(path, suffix);
}
size_t volk_fft_load_preferences(volk_fft_arch_pref_t **prefs_res)
{
FILE *config_file;
char path[512], line[512];
size_t n_arch_prefs = 0;
volk_fft_arch_pref_t *prefs = NULL;
//get the config path
volk_fft_get_config_path(path);
if (!path[0]) return n_arch_prefs; //no prefs found
config_file = fopen(path, "r");
if(!config_file) return n_arch_prefs; //no prefs found
//reset the file pointer and write the prefs into volk_fft_arch_prefs
while(fgets(line, sizeof(line), config_file) != NULL)
{
prefs = (volk_fft_arch_pref_t *) realloc(prefs, (n_arch_prefs+1) * sizeof(*prefs));
volk_fft_arch_pref_t *p = prefs + n_arch_prefs;
if(sscanf(line, "%s %s %s", p->name, p->impl_a, p->impl_u) == 3 && !strncmp(p->name, "volk_fft_", 5))
{
n_arch_prefs++;
}
}
fclose(config_file);
*prefs_res = prefs;
return n_arch_prefs;
}
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- Created by texi2html, http://www.gnu.org/software/texinfo/ -->
<head>
<title>Singular 2-0-4 Manual: D.6.2 ainvar_lib</title>
<meta name="description" content="Singular 2-0-4 Manual: D.6.2 ainvar_lib">
<meta name="keywords" content="Singular 2-0-4 Manual: D.6.2 ainvar_lib">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="texi2html">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
<!--
a.summary-letter {text-decoration: none}
blockquote.smallquotation {font-size: smaller}
div.display {margin-left: 3.2em}
div.example {margin-left: 3.2em}
div.lisp {margin-left: 3.2em}
div.smalldisplay {margin-left: 3.2em}
div.smallexample {margin-left: 3.2em}
div.smalllisp {margin-left: 3.2em}
pre.display {font-family: serif}
pre.format {font-family: serif}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: serif; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: serif; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.nocodebreak {white-space:pre}
span.nolinebreak {white-space:pre}
span.roman {font-family:serif; font-weight:normal}
span.sansserif {font-family:sans-serif; font-weight:normal}
ul.no-bullet {list-style: none}
-->
</style>
</head>
<body lang="en" background="../singular_images/Mybg.png">
<a name="ainvar_005flib"></a>
<table border="0" cellpadding="0" cellspacing="0">
<tr valign="top">
<td align="left">
<table class="header" cellpadding="1" cellspacing="1" border="0">
<tr valign="top" align="left">
<td valign="middle" align="left"> <a href="index.htm"><img
src="../singular_images/singular-icon-transparent.png" width="50"
border="0" alt="Top"></a>
</td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="image_005fof_005fvariety.html#image_005fof_005fvariety" title="Previous section in reading order"><img src="../singular_images/a_left.png" border="0" alt="Back: D.6.1.31 image_of_variety" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="invariantRing.html#invariantRing" title="Next section in reading order"><img src="../singular_images/a_right.png" border="0" alt="Forward: D.6.2.1 invariantRing" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="SINGULAR-libraries.html#SINGULAR-libraries" title="Beginning of this chapter or previous chapter"><img src="../singular_images/a_leftdouble.png" border="0" alt="FastBack: Appendix D SINGULAR libraries" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="Release-Notes.html#Release-Notes" title="Next chapter"><img src="../singular_images/a_rightdouble.png" border="0" alt="FastForward: E Release Notes" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="Invariant-theory.html#Invariant-theory" title="Up section"><img src="../singular_images/a_up.png" border="0" alt="Up: D.6 Invariant theory" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="index.htm#Preface" title="Cover (top) of document"><img src="../singular_images/a_top.png" border="0" alt="Top: 1 Preface" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="sing_toc.htm#SEC_Contents" title="Table of contents"><img src="../singular_images/a_tableofcon.png" border="0" alt="Contents: Table of Contents" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="Index.html#Index" title="Index"><img src="../singular_images/a_index.png" border="0" alt="Index: F Index" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="sing_abt.htm#SEC_About" title="About (help)"><img src="../singular_images/a_help.png" border="0" alt="About: About This Document" align="middle"></a></td>
</tr>
</table>
</td>
<td align="left">
<a name="ainvar_005flib-1"></a>
<h3 class="subsection">D.6.2 ainvar_lib</h3>
<a name="index-ainvar_002elib"></a>
<a name="index-ainvar_005flib"></a>
<dl compact="compact">
<dt><strong>Library:</strong></dt>
<dd><p>ainvar.lib
</p></dd>
<dt><strong>Purpose:</strong></dt>
<dd><p> Invariant Rings of the Additive Group
</p></dd>
<dt><strong>Authors:</strong></dt>
<dd><p>Gerhard Pfister (email: pfister@mathematik.uni-kl.de),
Gert-Martin Greuel (email: greuel@mathematik.uni-kl.de)
</p>
</dd>
</dl>
<p><strong>Procedures:</strong>
</p><blockquote><table class="menu" border="0" cellspacing="0">
<tr><td align="left" valign="top"><a href="invariantRing.html#invariantRing">D.6.2.1 invariantRing</a></td><td> </td><td align="left" valign="top"> compute ring of invariants of (K,+)-action given by m
</td></tr>
<tr><td align="left" valign="top"><a href="derivate.html#derivate">D.6.2.2 derivate</a></td><td> </td><td align="left" valign="top"> derivation of f with respect to the vector field m
</td></tr>
<tr><td align="left" valign="top"><a href="actionIsProper.html#actionIsProper">D.6.2.3 actionIsProper</a></td><td> </td><td align="left" valign="top"> tests whether action defined by m is proper
</td></tr>
<tr><td align="left" valign="top"><a href="reduction.html#reduction">D.6.2.4 reduction</a></td><td> </td><td align="left" valign="top"> SAGBI reduction of p in the subring generated by I
</td></tr>
<tr><td align="left" valign="top"><a href="completeReduction.html#completeReduction">D.6.2.5 completeReduction</a></td><td> </td><td align="left" valign="top"> complete SAGBI reduction
</td></tr>
<tr><td align="left" valign="top"><a href="localInvar.html#localInvar">D.6.2.6 localInvar</a></td><td> </td><td align="left" valign="top"> invariant polynomial under m computed from p,...
</td></tr>
<tr><td align="left" valign="top"><a href="furtherInvar.html#furtherInvar">D.6.2.7 furtherInvar</a></td><td> </td><td align="left" valign="top"> compute further invariants of m from the given ones
</td></tr>
<tr><td align="left" valign="top"><a href="sortier.html#sortier">D.6.2.8 sortier</a></td><td> </td><td align="left" valign="top"> sorts generators of id by increasing leading terms
</td></tr>
</table></blockquote>
</td>
</tr>
</table>
<hr>
<table class="header" cellpadding="1" cellspacing="1" border="0">
<tr><td valign="middle" align="left"> <a href="index.htm"><img
src="../singular_images/singular-icon-transparent.png" width="50"
border="0" alt="Top"></a>
</td>
<td valign="middle" align="left"><a href="image_005fof_005fvariety.html#image_005fof_005fvariety" title="Previous section in reading order"><img src="../singular_images/a_left.png" border="0" alt="Back: D.6.1.31 image_of_variety" align="middle"></a></td>
<td valign="middle" align="left"><a href="invariantRing.html#invariantRing" title="Next section in reading order"><img src="../singular_images/a_right.png" border="0" alt="Forward: D.6.2.1 invariantRing" align="middle"></a></td>
<td valign="middle" align="left"><a href="SINGULAR-libraries.html#SINGULAR-libraries" title="Beginning of this chapter or previous chapter"><img src="../singular_images/a_leftdouble.png" border="0" alt="FastBack: Appendix D SINGULAR libraries" align="middle"></a></td>
<td valign="middle" align="left"><a href="Release-Notes.html#Release-Notes" title="Next chapter"><img src="../singular_images/a_rightdouble.png" border="0" alt="FastForward: E Release Notes" align="middle"></a></td>
<td valign="middle" align="left"><a href="Invariant-theory.html#Invariant-theory" title="Up section"><img src="../singular_images/a_up.png" border="0" alt="Up: D.6 Invariant theory" align="middle"></a></td>
<td valign="middle" align="left"><a href="index.htm#Preface" title="Cover (top) of document"><img src="../singular_images/a_top.png" border="0" alt="Top: 1 Preface" align="middle"></a></td>
<td valign="middle" align="left"><a href="sing_toc.htm#SEC_Contents" title="Table of contents"><img src="../singular_images/a_tableofcon.png" border="0" alt="Contents: Table of Contents" align="middle"></a></td>
<td valign="middle" align="left"><a href="Index.html#Index" title="Index"><img src="../singular_images/a_index.png" border="0" alt="Index: F Index" align="middle"></a></td>
<td valign="middle" align="left"><a href="sing_abt.htm#SEC_About" title="About (help)"><img src="../singular_images/a_help.png" border="0" alt="About: About This Document" align="middle"></a></td>
</tr></table>
<font size="-1">
User manual for <a href="http://www.singular.uni-kl.de/"><i>Singular</i></a> version 2-0-4, October 2002,
generated by <a href="http://www.gnu.org/software/texinfo/"><i>texi2html</i></a>.
</font>
</body>
</html>
| Java |
package ninja.mbedded.ninjaterm.util.rxProcessing.timeStamp;
import javafx.scene.paint.Color;
import ninja.mbedded.ninjaterm.JavaFXThreadingRule;
import ninja.mbedded.ninjaterm.util.rxProcessing.streamedData.StreamedData;
import ninja.mbedded.ninjaterm.util.rxProcessing.streamingFilter.StreamingFilter;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.time.Instant;
import java.time.ZoneId;
import static org.junit.Assert.assertEquals;
/**
* Unit tests for the {@link TimeStampParser} class.
*
* @author Geoffrey Hunter <gbmhunter@gmail.com> (www.mbedded.ninja)
* @since 2016-11-23
* @last-modified 2016-11-23
*/
public class TimeStampParserTests {
/**
* Including this variable in class allows JavaFX objects to be created in tests.
*/
@Rule
public JavaFXThreadingRule javafxRule = new JavaFXThreadingRule();
private TimeStampParser timeStampParser;
private StreamedData inputStreamedData;
private StreamedData outputStreamedData;
@Before
public void setUp() throws Exception {
timeStampParser = new TimeStampParser("EOL");
inputStreamedData = new StreamedData();
outputStreamedData = new StreamedData();
}
@Test
public void firstCharTest() throws Exception {
inputStreamedData.append("abc");
timeStampParser.parse(inputStreamedData, outputStreamedData);
// Check input
assertEquals("", inputStreamedData.getText());
// Check output
assertEquals("abc", outputStreamedData.getText());
assertEquals(1, outputStreamedData.getTimeStampMarkers().size());
assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos);
}
@Test
public void oneNewLineTest() throws Exception {
inputStreamedData.append("abcEOLd");
timeStampParser.parse(inputStreamedData, outputStreamedData);
// Check input
assertEquals("", inputStreamedData.getText());
// Check output
assertEquals("abcEOLd", outputStreamedData.getText());
assertEquals(2, outputStreamedData.getTimeStampMarkers().size());
assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos);
assertEquals(6, outputStreamedData.getTimeStampMarkers().get(1).charPos);
}
@Test
public void temporalTest() throws Exception {
inputStreamedData.append("abcEOL");
timeStampParser.parse(inputStreamedData, outputStreamedData);
// Check input
assertEquals("", inputStreamedData.getText());
// Check output
assertEquals("abcEOL", outputStreamedData.getText());
assertEquals(1, outputStreamedData.getTimeStampMarkers().size());
assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos);
// Sleep enough that the next TimeStamp is guaranteed to be greater than
// the first (delay must be larger than the min. LocalDateTime resolution)
Thread.sleep(10);
//==============================================//
//====================== RUN 2 =================//
//==============================================//
inputStreamedData.append("d");
timeStampParser.parse(inputStreamedData, outputStreamedData);
// Check input
assertEquals("", inputStreamedData.getText());
// Check output
assertEquals("abcEOLd", outputStreamedData.getText());
assertEquals(2, outputStreamedData.getTimeStampMarkers().size());
assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos);
assertEquals(6, outputStreamedData.getTimeStampMarkers().get(1).charPos);
// Check time
Instant time0 = outputStreamedData.getTimeStampMarkers().get(0).localDateTime.atZone(ZoneId.systemDefault()).toInstant();
Instant time1 = outputStreamedData.getTimeStampMarkers().get(1).localDateTime.atZone(ZoneId.systemDefault()).toInstant();
assertEquals(true, time1.isAfter(time0));
}
@Test
public void partialLineTest() throws Exception {
inputStreamedData.append("123EO");
timeStampParser.parse(inputStreamedData, outputStreamedData);
// Check input
assertEquals("EO", inputStreamedData.getText());
// Check output
assertEquals("123", outputStreamedData.getText());
assertEquals(1, outputStreamedData.getTimeStampMarkers().size());
assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos);
inputStreamedData.append("L456");
timeStampParser.parse(inputStreamedData, outputStreamedData);
// Check input
assertEquals("", inputStreamedData.getText());
// Check output
assertEquals("123EOL456", outputStreamedData.getText());
assertEquals(2, outputStreamedData.getTimeStampMarkers().size());
assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos);
assertEquals(6, outputStreamedData.getTimeStampMarkers().get(1).charPos);
}
// @Test
// public void multipleLinesTest() throws Exception {
//
// inputStreamedData.append("abcEOLabcEOLdefEOL");
// inputStreamedData.addNewLineMarkerAt(6);
// inputStreamedData.addNewLineMarkerAt(12);
// inputStreamedData.addNewLineMarkerAt(18);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check input. Since "defEOL" counts as a valid line, but has no match,
// // it should be removed from the input
// assertEquals("", inputStreamedData.getText());
// assertEquals(0, inputStreamedData.getColourMarkers().size());
//
// // Check output
// assertEquals("abcEOLabcEOL", outputStreamedData.getText());
// assertEquals(0, outputStreamedData.getColourMarkers().size());
// assertEquals(2, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
// assertEquals(12, outputStreamedData.getNewLineMarkers().get(1).intValue());
// }
//
// @Test
// public void MatchedLinesBetweenNonMatchTest() throws Exception {
//
// inputStreamedData.append("abcEOLdefEOLabcEOL");
// inputStreamedData.addNewLineMarkerAt(6);
// inputStreamedData.addNewLineMarkerAt(12);
// inputStreamedData.addNewLineMarkerAt(18);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check input. Since "defEOL" counts as a valid line, but has no match,
// // it should be removed from the input
// assertEquals("", inputStreamedData.getText());
// assertEquals(0, inputStreamedData.getColourMarkers().size());
//
// // Check output
// assertEquals("abcEOLabcEOL", outputStreamedData.getText());
// assertEquals(0, outputStreamedData.getColourMarkers().size());
// assertEquals(2, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
// assertEquals(12, outputStreamedData.getNewLineMarkers().get(1).intValue());
// }
//
// @Test
// public void streamTest() throws Exception {
//
// inputStreamedData.append("ab");
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("", inputStreamedData.getText());
// assertEquals("ab", outputStreamedData.getText());
//
// inputStreamedData.append("cEOL");
// inputStreamedData.addNewLineMarkerAt(4);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("", inputStreamedData.getText());
// assertEquals(0, inputStreamedData.getNewLineMarkers().size());
//
// // Check output
// assertEquals("abcEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
// }
//
// @Test
// public void streamWithNonMatchLineInMiddleTest() throws Exception {
//
// //==============================================//
// //==================== PASS 1 ==================//
// //==============================================//
//
// inputStreamedData.append("ab");
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check input
// assertEquals("", inputStreamedData.getText());
//
// // Check output
// assertEquals("ab", outputStreamedData.getText());
//
// //==============================================//
// //==================== PASS 2 ==================//
// //==============================================//
//
// inputStreamedData.append("cEOLde");
// inputStreamedData.addNewLineMarkerAt(4);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check input
// assertEquals(inputStreamedData.getText(), "de");
//
// // Check output
// assertEquals("abcEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
//
// //==============================================//
// //==================== PASS 3 ==================//
// //==============================================//
//
// inputStreamedData.append("fEOLa");
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length() - 1);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check input
// assertEquals(inputStreamedData.getText(), "");
// assertEquals(0, inputStreamedData.getNewLineMarkers().size());
//
// // Check output
// assertEquals("abcEOLa", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
//
// //==============================================//
// //==================== PASS 4 ==================//
// //==============================================//
//
// inputStreamedData.append("bcEOL");
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length());
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check input
// assertEquals(inputStreamedData.getText(), "");
// assertEquals(0, inputStreamedData.getNewLineMarkers().size());
//
// // Check output
// assertEquals("abcEOLabcEOL", outputStreamedData.getText());
// assertEquals(2, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
// assertEquals(12, outputStreamedData.getNewLineMarkers().get(1).intValue());
//
// }
//
// @Test
// public void coloursAndNewLinesTest() throws Exception {
//
// inputStreamedData.append("abcEOL");
// inputStreamedData.addColour(2, Color.RED);
// inputStreamedData.addNewLineMarkerAt(6);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check output
// assertEquals("abcEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getColourMarkers().size());
// assertEquals(2, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
// }
//
// @Test
// public void complexNodesTest() throws Exception {
//
// inputStreamedData.append("abcdefEOL");
// inputStreamedData.addColour(2, Color.RED);
// inputStreamedData.addColour(3, Color.GREEN);
// inputStreamedData.addNewLineMarkerAt(9);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("abcdefEOL", outputStreamedData.getText());
// assertEquals(2, outputStreamedData.getColourMarkers().size());
//
// assertEquals(2, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
//
// assertEquals(3, outputStreamedData.getColourMarkers().get(1).position);
// assertEquals(Color.GREEN, outputStreamedData.getColourMarkers().get(1).color);
//
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(9, outputStreamedData.getNewLineMarkers().get(0).intValue());
// }
//
// @Test
// public void complexNodes2Test() throws Exception {
//
// //==============================================//
// //==================== PASS 1 ==================//
// //==============================================//
//
// inputStreamedData.append("abcEOL");
// inputStreamedData.addColour(2, Color.RED);
// inputStreamedData.addNewLineMarkerAt(6);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("abcEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getColourMarkers().size());
// assertEquals(2, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
//
// //==============================================//
// //==================== PASS 2 ==================//
// //==============================================//
//
// inputStreamedData.append("defEOL");
// inputStreamedData.addColour(0, Color.GREEN);
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length());
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("abcEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getColourMarkers().size());
// assertEquals(2, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
// }
//
// @Test
// public void bigTest() throws Exception {
//
// streamingFilter.setFilterPattern("d");
//
// inputStreamedData.append("re");
// inputStreamedData.addColour(0, Color.RED);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("", outputStreamedData.getText());
// assertEquals(0, outputStreamedData.getColourMarkers().size());
//
// inputStreamedData.append("dEOL");
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length());
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("redEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getColourMarkers().size());
// assertEquals(0, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Nothing should of changed
// assertEquals("redEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getColourMarkers().size());
// assertEquals(0, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
//
// inputStreamedData.append("greenEOL");
// inputStreamedData.addColour(inputStreamedData.getText().length() - 8, Color.GREEN);
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length());
//
// inputStreamedData.append("redEOL");
// inputStreamedData.addColour(inputStreamedData.getText().length() - 6, Color.RED);
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length());
//
// inputStreamedData.append("greenEOL");
// inputStreamedData.addColour(inputStreamedData.getText().length() - 8, Color.GREEN);
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length());
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("redEOLredEOL", outputStreamedData.getText());
// assertEquals(2, outputStreamedData.getColourMarkers().size());
//
// assertEquals(0, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
//
// assertEquals(6, outputStreamedData.getColourMarkers().get(1).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(1).color);
// }
} | Java |
// urlParams is null when used for embedding
window.urlParams = window.urlParams || {};
// isLocalStorage controls access to local storage
window.isLocalStorage = window.isLocalStorage || false;
// Checks for SVG support
window.isSvgBrowser = window.isSvgBrowser || (navigator.userAgent.indexOf('MSIE') < 0 || document.documentMode >= 9);
// CUSTOM_PARAMETERS - URLs for save and export
window.EXPORT_URL = window.EXPORT_URL || 'https://exp.draw.io/ImageExport4/export';
window.SAVE_URL = window.SAVE_URL || 'save';
window.OPEN_URL = window.OPEN_URL || 'open';
window.PROXY_URL = window.PROXY_URL || 'proxy';
// Paths and files
window.SHAPES_PATH = window.SHAPES_PATH || 'shapes';
// Path for images inside the diagram
window.GRAPH_IMAGE_PATH = window.GRAPH_IMAGE_PATH || 'img';
window.ICONSEARCH_PATH = window.ICONSEARCH_PATH || (navigator.userAgent.indexOf('MSIE') >= 0 ||
urlParams['dev']) ? 'iconSearch' : 'https://www.draw.io/iconSearch';
window.TEMPLATE_PATH = window.TEMPLATE_PATH || '/templates';
// Directory for i18 files and basename for main i18n file
window.RESOURCES_PATH = window.RESOURCES_PATH || 'resources';
window.RESOURCE_BASE = window.RESOURCE_BASE || RESOURCES_PATH + '/dia';
// URL for logging
window.DRAWIO_LOG_URL = window.DRAWIO_LOG_URL || '';
// Sets the base path, the UI language via URL param and configures the
// supported languages to avoid 404s. The loading of all core language
// resources is disabled as all required resources are in grapheditor.
// properties. Note that in this example the loading of two resource
// files (the special bundle and the default bundle) is disabled to
// save a GET request. This requires that all resources be present in
// the special bundle.
window.mxLoadResources = window.mxLoadResources || false;
window.mxLanguage = window.mxLanguage || (function()
{
var lang = (urlParams['offline'] == '1') ? 'en' : urlParams['lang'];
// Known issue: No JSON object at this point in quirks in IE8
if (lang == null && typeof(JSON) != 'undefined')
{
// Cannot use mxSettings here
if (isLocalStorage)
{
try
{
var value = localStorage.getItem('.drawio-config');
if (value != null)
{
lang = JSON.parse(value).language || null;
}
}
catch (e)
{
// cookies are disabled, attempts to use local storage will cause
// a DOM error at a minimum on Chrome
isLocalStorage = false;
}
}
}
return lang;
})();
// Add new languages here. First entry is translated to [Automatic]
// in the menu defintion in Diagramly.js.
window.mxLanguageMap = window.mxLanguageMap ||
{
'i18n': '',
'id' : 'Bahasa Indonesia',
'ms' : 'Bahasa Melayu',
'bs' : 'Bosanski',
'ca' : 'Català',
'cs' : 'Čeština',
'da' : 'Dansk',
'de' : 'Deutsch',
'et' : 'Eesti',
'en' : 'English',
'es' : 'Español',
'eo' : 'Esperanto',
'fil' : 'Filipino',
'fr' : 'Français',
'it' : 'Italiano',
'hu' : 'Magyar',
'nl' : 'Nederlands',
'no' : 'Norsk',
'pl' : 'Polski',
'pt-br' : 'Português (Brasil)',
'pt' : 'Português (Portugal)',
'ro' : 'Română',
'fi' : 'Suomi',
'sv' : 'Svenska',
'vi' : 'Tiếng Việt',
'tr' : 'Türkçe',
'el' : 'Ελληνικά',
'ru' : 'Русский',
'sr' : 'Српски',
'uk' : 'Українська',
'he' : 'עברית',
'ar' : 'العربية',
'th' : 'ไทย',
'ko' : '한국어',
'ja' : '日本語',
'zh' : '中文(中国)',
'zh-tw' : '中文(台灣)'
};
if (typeof window.mxBasePath === 'undefined')
{
window.mxBasePath = 'mxgraph';
}
if (window.mxLanguages == null)
{
window.mxLanguages = [];
// Populates the list of supported special language bundles
for (var lang in mxLanguageMap)
{
// Empty means default (ie. browser language), "en" means English (default for unsupported languages)
// Since "en" uses no extension this must not be added to the array of supported language bundles.
if (lang != 'en')
{
window.mxLanguages.push(lang);
}
}
}
/**
* Returns the global UI setting before runngin static draw.io code
*/
window.uiTheme = window.uiTheme || (function()
{
var ui = urlParams['ui'];
// Known issue: No JSON object at this point in quirks in IE8
if (ui == null && typeof JSON !== 'undefined')
{
// Cannot use mxSettings here
if (isLocalStorage)
{
try
{
var value = localStorage.getItem('.drawio-config');
if (value != null)
{
ui = JSON.parse(value).ui || null;
}
}
catch (e)
{
// cookies are disabled, attempts to use local storage will cause
// a DOM error at a minimum on Chrome
isLocalStorage = false;
}
}
}
return ui;
})();
/**
* Global function for loading local files via servlet
*/
function setCurrentXml(data, filename)
{
if (window.parent != null && window.parent.openFile != null)
{
window.parent.openFile.setData(data, filename);
}
};
/**
* Overrides splash URL parameter via local storage
*/
(function()
{
// Known issue: No JSON object at this point in quirks in IE8
if (typeof JSON !== 'undefined')
{
// Cannot use mxSettings here
if (isLocalStorage)
{
try
{
var value = localStorage.getItem('.drawio-config');
var showSplash = true;
if (value != null)
{
showSplash = JSON.parse(value).showStartScreen;
}
// Undefined means true
if (showSplash == false)
{
urlParams['splash'] = '0';
}
}
catch (e)
{
// ignore
}
}
}
})();
// Customizes export URL
var ex = urlParams['export'];
if (ex != null)
{
if (ex.substring(0, 7) != 'http://' && ex.substring(0, 8) != 'https://')
{
ex = 'http://' + ex;
}
EXPORT_URL = ex;
}
// Enables offline mode
if (urlParams['offline'] == '1' || urlParams['demo'] == '1' || urlParams['stealth'] == '1' || urlParams['local'] == '1')
{
urlParams['analytics'] = '0';
urlParams['picker'] = '0';
urlParams['gapi'] = '0';
urlParams['db'] = '0';
urlParams['od'] = '0';
urlParams['gh'] = '0';
}
// Disables math in offline mode
if (urlParams['offline'] == '1' || urlParams['local'] == '1')
{
urlParams['math'] = '0';
}
// Lightbox enabled chromeless mode
if (urlParams['lightbox'] == '1')
{
urlParams['chrome'] = '0';
}
// Adds hard-coded logging domain for draw.io domains
var host = window.location.host;
var searchString = 'draw.io';
var position = host.length - searchString.length;
var lastIndex = host.lastIndexOf(searchString, position);
if (lastIndex !== -1 && lastIndex === position && host != 'test.draw.io')
{
// endsWith polyfill
window.DRAWIO_LOG_URL = 'https://log.draw.io';
} | Java |
<div class="col-lg-6 col-12">
<section widget class="widget widget-chart-stats-simple">
<header>
<div class="row">
<div class="col-3">
<h6>
Total Sales
</h6>
<p class="value5">
January, 2014
</p>
</div>
<div class="col-3">
<h5>
<small>Best</small>
</h5>
<p class="value6 fs-sm">
March, 2013 + 1
</p>
</div>
</div>
<div class="widget-controls">
<a href="#"><i class="glyphicon glyphicon-cog"></i></a>
<a href="#" data-widgster="close"><i class="glyphicon glyphicon-remove"></i></a>
</div>
</header>
<div class="widget-body">
<div class="chart-stats">
<p class="text-muted fs-mini mt-xs">
<i class="fa fa-map-marker fa-5x pull-left"></i>
<span class="fw-semi-bold text-gray-dark">Jess:</span> Seems like statically it's getting impossible to achieve any sort of
results in nearest future. The only thing we can hope for is pressing one of these two buttons:
</p>
<div class="btn-toolbar">
<button class="btn btn-xs btn-success">Accept</button>
<button class="btn btn-xs btn-default">Reject</button>
</div>
</div>
<div class="chart bg-body-light">
<div flot-chart [data]="generateRandomData([{
label: 'Visitors', color: configFn.darkenColor(config.settings.colors['gray-lighter'], .05)
},{
label: 'Charts', color: config.settings.colors['brand-danger']
}])" class="chart-inner"></div>
</div>
</div>
</section>
</div>
<div class="col-lg-6 col-12">
<section widget class="widget widget-chart-stats-simple">
<header>
<h6 class="mb-0">
<span class="fw-semi-bold">Budget</span> <span class="badge badge-pill badge-danger">2017</span>
</h6>
<span class="text-muted fs-mini">monthly report will be available in <a href="#">6 hours</a></span>
<div class="widget-controls">
<a href="#"><i class="glyphicon glyphicon-cog"></i></a>
<a href="#" data-widgster="close"><i class="glyphicon glyphicon-remove"></i></a>
</div>
</header>
<div class="widget-body">
<div class="chart-stats">
<div class="row">
<div class="col-md-5">
<div class="clearfix m-t-1">
<h6 class="pull-left text-muted mb-xs">
Income
</h6>
<p class="pull-right h6 mb-xs">
<span class="fw-semi-bold">$14,595</span>
</p>
</div>
<div class="clearfix">
<h6 class="pull-left m-0 text-muted">
Recent
</h6>
<p class="pull-right">
<span class="fw-semi-bold">$7,647</span>
</p>
</div>
</div>
<div class="col-md-3 text-right m-t-1">
<h6 class="text-muted mb-xs">Inqueries</h6>
<p class="fw-semi-bold">73 at 14am</p>
</div>
<div class="col-md-4 text-right m-t-1">
<h6 class="text-muted mb-xs">Last Updated</h6>
<p class="fw-semi-bold">23.06.2013</p>
</div>
</div>
</div>
<div class="chart bg-body-light">
<div flot-chart [data] = "generateRandomData([{
label: 'Controllers', color: '#777'
},{
label: 'Scopes', color: config.settings.colors['brand-warning']
}])" class="chart-inner"></div>
</div>
</div>
</section>
</div>
| Java |
<?php
/**
* Part of the Sentinel package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file.
*
* @package Sentinel
* @version 2.0.18
* @author Cartalyst LLC
* @license BSD License (3-clause)
* @copyright (c) 2011-2019, Cartalyst LLC
* @link http://cartalyst.com
*/
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class MigrationCartalystSentinel extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('activations', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('code');
$table->boolean('completed')->default(0);
$table->timestamp('completed_at')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
});
Schema::create('persistences', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('code');
$table->timestamps();
$table->engine = 'InnoDB';
$table->unique('code');
});
Schema::create('reminders', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('code');
$table->boolean('completed')->default(0);
$table->timestamp('completed_at')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
});
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('slug');
$table->string('name');
$table->text('permissions')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
$table->unique('slug');
});
Schema::create('role_users', function (Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->nullableTimestamps();
$table->engine = 'InnoDB';
$table->primary(['user_id', 'role_id']);
});
Schema::create('throttle', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable();
$table->string('type');
$table->string('ip')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
$table->index('user_id');
});
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->string('password');
$table->text('permissions')->nullable();
$table->timestamp('last_login')->nullable();
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
$table->unique('email');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('activations');
Schema::drop('persistences');
Schema::drop('reminders');
Schema::drop('roles');
Schema::drop('role_users');
Schema::drop('throttle');
Schema::drop('users');
}
}
| Java |
/*
* File: Worker2.cpp
* Author: saulario
*
* Created on 15 de septiembre de 2016, 6:40
*/
#include "Worker2.h"
#include "Csoft.h"
using namespace csoft::mod2;
Worker2::Worker2(const csoft::Csoft * csoft) {
}
Worker2::Worker2(const Worker2& orig) {
}
Worker2::~Worker2() {
}
void Worker2::doIt(void) {
BOOST_LOG_SEV(lg, boost::log::trivial::info) << __PRETTY_FUNCTION__ << "---> Begin";
BOOST_LOG_SEV(lg, boost::log::trivial::info) << __PRETTY_FUNCTION__ << "<--- End";
} | Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace YSchool
{
public class Person
{
public int id;
public string name ;
public int gender;//1
public string birthDate;//"1900-00-00T00:00:00"
public int mobileNumber;
public int altMobileNumber;
public string fatherName;
public string motherName;
public int batchType;//2
}
} | Java |
var chai = require('chai')
, sinon = require('sinon')
, sinonChai = require('sinon-chai')
, expect = chai.expect
, Promise = require('es6-promise').Promise
, UpdateTemplatesController = require('../../../platypi-cli/controllers/cli/updatetemplates.controller');
chai.use(sinonChai);
describe('TemplateUpdate controller', function () {
it('should return a new controller', function (done) {
try {
var controller = new UpdateTemplatesController({
viewStuff: 'fakeview'
});
expect(controller).to.be.an.object;
expect(controller.model).to.be.an.object;
expect(controller.view).to.be.an.object;
expect(controller.view.model).to.equal(controller.model);
done();
} catch (e) {
done(e);
}
});
describe('getResponseView method', function () {
var sandbox, controller, updateFunc;
beforeEach(function (done) {
sandbox = sinon.sandbox.create();
controller = new UpdateTemplatesController({
viewStuff: 'fakeview'
});
updateFunc = sandbox.stub(controller.__provider, 'update');
done();
});
afterEach(function (done) {
sandbox.restore();
done();
});
it('should call the clean method and return the view', function (done) {
updateFunc.returns(Promise.resolve(''));
controller.getResponseView().then(function (view) {
try {
expect(updateFunc).to.have.been.called;
expect(controller.model.successMessage).not.to.equal('');
expect(view).to.exist;
done();
} catch (e) {
done(e);
}
}, function (err) {
done(err);
});
});
it('should call the update method and throw an error', function (done) {
updateFunc.returns(Promise.reject('Err'));
controller.getResponseView().then(function (view) {
try {
expect(updateFunc).to.have.been.called;
expect(controller.model.errorMessage).not.to.equal('');
expect(view).to.exist;
done();
} catch (e) {
done(e);
}
}, function (err) {
done(err);
});
});
});
}); | Java |
""" Class that contains client access to the transformation DB handler. """
__RCSID__ = "$Id$"
import types
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.Base.Client import Client
from DIRAC.Core.Utilities.List import breakListIntoChunks
from DIRAC.Resources.Catalog.FileCatalogueBase import FileCatalogueBase
from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations
rpc = None
url = None
class TransformationClient( Client, FileCatalogueBase ):
""" Exposes the functionality available in the DIRAC/TransformationHandler
This inherits the DIRAC base Client for direct execution of server functionality.
The following methods are available (although not visible here).
Transformation (table) manipulation
deleteTransformation(transName)
getTransformationParameters(transName,paramNames)
getTransformationWithStatus(status)
setTransformationParameter(transName,paramName,paramValue)
deleteTransformationParameter(transName,paramName)
TransformationFiles table manipulation
addFilesToTransformation(transName,lfns)
addTaskForTransformation(transName,lfns=[],se='Unknown')
getTransformationStats(transName)
TransformationTasks table manipulation
setTaskStatus(transName, taskID, status)
setTaskStatusAndWmsID(transName, taskID, status, taskWmsID)
getTransformationTaskStats(transName)
deleteTasks(transName, taskMin, taskMax)
extendTransformation( transName, nTasks)
getTasksToSubmit(transName,numTasks,site='')
TransformationLogging table manipulation
getTransformationLogging(transName)
File/directory manipulation methods (the remainder of the interface can be found below)
getFileSummary(lfns)
exists(lfns)
Web monitoring tools
getDistinctAttributeValues(attribute, selectDict)
getTransformationStatusCounters()
getTransformationSummary()
getTransformationSummaryWeb(selectDict, sortList, startItem, maxItems)
"""
def __init__( self, **kwargs ):
Client.__init__( self, **kwargs )
opsH = Operations()
self.maxResetCounter = opsH.getValue( 'Productions/ProductionFilesMaxResetCounter', 10 )
self.setServer( 'Transformation/TransformationManager' )
def setServer( self, url ):
self.serverURL = url
def getCounters( self, table, attrList, condDict, older = None, newer = None, timeStamp = None,
rpc = '', url = '' ):
rpcClient = self._getRPC( rpc = rpc, url = url )
return rpcClient. getCounters( table, attrList, condDict, older, newer, timeStamp )
def addTransformation( self, transName, description, longDescription, transType, plugin, agentType, fileMask,
transformationGroup = 'General',
groupSize = 1,
inheritedFrom = 0,
body = '',
maxTasks = 0,
eventsPerTask = 0,
addFiles = True,
rpc = '', url = '', timeout = 1800 ):
""" add a new transformation
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.addTransformation( transName, description, longDescription, transType, plugin,
agentType, fileMask, transformationGroup, groupSize, inheritedFrom,
body, maxTasks, eventsPerTask, addFiles )
def getTransformations( self, condDict = {}, older = None, newer = None, timeStamp = 'CreationDate',
orderAttribute = None, limit = 100, extraParams = False, rpc = '', url = '', timeout = None ):
""" gets all the transformations in the system, incrementally. "limit" here is just used to determine the offset.
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
transformations = []
# getting transformations - incrementally
offsetToApply = 0
while True:
res = rpcClient.getTransformations( condDict, older, newer, timeStamp, orderAttribute, limit,
extraParams, offsetToApply )
if not res['OK']:
return res
else:
gLogger.verbose( "Result for limit %d, offset %d: %d" % ( limit, offsetToApply, len( res['Value'] ) ) )
if res['Value']:
transformations = transformations + res['Value']
offsetToApply += limit
if len( res['Value'] ) < limit:
break
return S_OK( transformations )
def getTransformation( self, transName, extraParams = False, rpc = '', url = '', timeout = None ):
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.getTransformation( transName, extraParams )
def getTransformationFiles( self, condDict = {}, older = None, newer = None, timeStamp = 'LastUpdate',
orderAttribute = None, limit = 10000, rpc = '', url = '', timeout = 1800 ):
""" gets all the transformation files for a transformation, incrementally.
"limit" here is just used to determine the offset.
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
transformationFiles = []
# getting transformationFiles - incrementally
offsetToApply = 0
while True:
res = rpcClient.getTransformationFiles( condDict, older, newer, timeStamp, orderAttribute, limit, offsetToApply )
if not res['OK']:
return res
else:
gLogger.verbose( "Result for limit %d, offset %d: %d" % ( limit, offsetToApply, len( res['Value'] ) ) )
if res['Value']:
transformationFiles = transformationFiles + res['Value']
offsetToApply += limit
if len( res['Value'] ) < limit:
break
return S_OK( transformationFiles )
def getTransformationTasks( self, condDict = {}, older = None, newer = None, timeStamp = 'CreationTime',
orderAttribute = None, limit = 10000, inputVector = False, rpc = '',
url = '', timeout = None ):
""" gets all the transformation tasks for a transformation, incrementally.
"limit" here is just used to determine the offset.
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
transformationTasks = []
# getting transformationFiles - incrementally
offsetToApply = 0
while True:
res = rpcClient.getTransformationTasks( condDict, older, newer, timeStamp, orderAttribute, limit,
inputVector, offsetToApply )
if not res['OK']:
return res
else:
gLogger.verbose( "Result for limit %d, offset %d: %d" % ( limit, offsetToApply, len( res['Value'] ) ) )
if res['Value']:
transformationTasks = transformationTasks + res['Value']
offsetToApply += limit
if len( res['Value'] ) < limit:
break
return S_OK( transformationTasks )
def cleanTransformation( self, transID, rpc = '', url = '', timeout = None ):
""" Clean the transformation, and set the status parameter (doing it here, for easier extensibility)
"""
# Cleaning
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
res = rpcClient.cleanTransformation( transID )
if not res['OK']:
return res
# Setting the status
return self.setTransformationParameter( transID, 'Status', 'TransformationCleaned' )
def moveFilesToDerivedTransformation( self, transDict, resetUnused = True ):
""" move files input to a transformation, to the derived one
"""
prod = transDict['TransformationID']
parentProd = int( transDict.get( 'InheritedFrom', 0 ) )
movedFiles = {}
if not parentProd:
gLogger.warn( "[None] [%d] .moveFilesToDerivedTransformation: Transformation was not derived..." % prod )
return S_OK( ( parentProd, movedFiles ) )
# get the lfns in status Unused/MaxReset of the parent production
res = self.getTransformationFiles( condDict = {'TransformationID': parentProd, 'Status': [ 'Unused', 'MaxReset' ]} )
if not res['OK']:
gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error getting Unused files from transformation %s:" % ( prod, parentProd ), res['Message'] )
return res
parentFiles = res['Value']
lfns = [lfnDict['LFN'] for lfnDict in parentFiles]
if not lfns:
gLogger.info( "[None] [%d] .moveFilesToDerivedTransformation: No files found to be moved from transformation %d" % ( prod, parentProd ) )
return S_OK( ( parentProd, movedFiles ) )
# get the lfns of the derived production that were Unused/MaxReset in the parent one
res = self.getTransformationFiles( condDict = { 'TransformationID': prod, 'LFN': lfns} )
if not res['OK']:
gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error getting files from derived transformation" % prod, res['Message'] )
return res
derivedFiles = res['Value']
suffix = '-%d' % parentProd
derivedStatusDict = dict( [( derivedDict['LFN'], derivedDict['Status'] ) for derivedDict in derivedFiles] )
newStatusFiles = {}
parentStatusFiles = {}
force = False
for parentDict in parentFiles:
lfn = parentDict['LFN']
derivedStatus = derivedStatusDict.get( lfn )
if derivedStatus:
parentStatus = parentDict['Status']
if resetUnused and parentStatus == 'MaxReset':
status = 'Unused'
moveStatus = 'Unused from MaxReset'
force = True
else:
status = parentStatus
moveStatus = parentStatus
if derivedStatus.endswith( suffix ):
# This file is Unused or MaxReset while it was most likely Assigned at the time of derivation
parentStatusFiles.setdefault( 'Moved-%s' % str( prod ), [] ).append( lfn )
newStatusFiles.setdefault( ( status, parentStatus ), [] ).append( lfn )
movedFiles[moveStatus] = movedFiles.setdefault( moveStatus, 0 ) + 1
elif parentDict['Status'] == 'Unused':
# If the file was Unused already at derivation time, set it NotProcessed
parentStatusFiles.setdefault( 'NotProcessed', [] ).append( lfn )
# Set the status in the parent transformation first
for status, lfnList in parentStatusFiles.items():
for lfnChunk in breakListIntoChunks( lfnList, 5000 ):
res = self.setFileStatusForTransformation( parentProd, status, lfnChunk )
if not res['OK']:
gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error setting status %s for %d files in transformation %d "
% ( prod, status, len( lfnList ), parentProd ),
res['Message'] )
# Set the status in the new transformation
for ( status, oldStatus ), lfnList in newStatusFiles.items():
for lfnChunk in breakListIntoChunks( lfnList, 5000 ):
res = self.setFileStatusForTransformation( prod, status, lfnChunk, force = force )
if not res['OK']:
gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error setting status %s for %d files; resetting them %s in transformation %d"
% ( prod, status, len( lfnChunk ), oldStatus, parentProd ),
res['Message'] )
res = self.setFileStatusForTransformation( parentProd, oldStatus, lfnChunk )
if not res['OK']:
gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error setting status %s for %d files in transformation %d"
% ( prod, oldStatus, len( lfnChunk ), parentProd ),
res['Message'] )
return S_OK( ( parentProd, movedFiles ) )
def setFileStatusForTransformation( self, transName, newLFNsStatus = {}, lfns = [], force = False,
rpc = '', url = '', timeout = 120 ):
""" sets the file status for LFNs of a transformation
For backward compatibility purposes, the status and LFNs can be passed in 2 ways:
- newLFNsStatus is a dictionary with the form:
{'/this/is/an/lfn1.txt': 'StatusA', '/this/is/an/lfn2.txt': 'StatusB', ... }
and at this point lfns is not considered
- newLFNStatus is a string, that applies to all the LFNs in lfns
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
# create dictionary in case newLFNsStatus is a string
if type( newLFNsStatus ) == type( '' ):
newLFNsStatus = dict( [( lfn, newLFNsStatus ) for lfn in lfns ] )
# gets status as of today
tsFiles = self.getTransformationFiles( {'TransformationID':transName, 'LFN': newLFNsStatus.keys()} )
if not tsFiles['OK']:
return tsFiles
tsFiles = tsFiles['Value']
if tsFiles:
# for convenience, makes a small dictionary out of the tsFiles, with the lfn as key
tsFilesAsDict = {}
for tsFile in tsFiles:
tsFilesAsDict[tsFile['LFN']] = [tsFile['Status'], tsFile['ErrorCount'], tsFile['FileID']]
# applying the state machine to the proposed status
newStatuses = self._applyTransformationFilesStateMachine( tsFilesAsDict, newLFNsStatus, force )
if newStatuses: # if there's something to update
# must do it for the file IDs...
newStatusForFileIDs = dict( [( tsFilesAsDict[lfn][2], newStatuses[lfn] ) for lfn in newStatuses.keys()] )
res = rpcClient.setFileStatusForTransformation( transName, newStatusForFileIDs )
if not res['OK']:
return res
return S_OK( newStatuses )
def _applyTransformationFilesStateMachine( self, tsFilesAsDict, dictOfProposedLFNsStatus, force ):
""" For easier extension, here we apply the state machine of the production files.
VOs might want to replace the standard here with something they prefer.
tsFiles is a dictionary with the lfn as key and as value a list of [Status, ErrorCount, FileID]
dictOfNewLFNsStatus is a dictionary with the proposed status
force is a boolean
It returns a dictionary with the status updates
"""
newStatuses = {}
for lfn in dictOfProposedLFNsStatus.keys():
if lfn not in tsFilesAsDict.keys():
continue
else:
newStatus = dictOfProposedLFNsStatus[lfn]
# Apply optional corrections
if tsFilesAsDict[lfn][0].lower() == 'processed' and dictOfProposedLFNsStatus[lfn].lower() != 'processed':
if not force:
newStatus = 'Processed'
elif tsFilesAsDict[lfn][0].lower() == 'maxreset':
if not force:
newStatus = 'MaxReset'
elif dictOfProposedLFNsStatus[lfn].lower() == 'unused':
errorCount = tsFilesAsDict[lfn][1]
# every 10 retries (by default)
if errorCount and ( ( errorCount % self.maxResetCounter ) == 0 ):
if not force:
newStatus = 'MaxReset'
if tsFilesAsDict[lfn][0].lower() != newStatus:
newStatuses[lfn] = newStatus
return newStatuses
def setTransformationParameter( self, transID, paramName, paramValue, force = False,
rpc = '', url = '', timeout = 120 ):
""" Sets a transformation parameter. There's a special case when coming to setting the status of a transformation.
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
if paramName.lower() == 'status':
# get transformation Type
transformation = self.getTransformation( transID )
if not transformation['OK']:
return transformation
transformationType = transformation['Value']['Type']
# get status as of today
originalStatus = self.getTransformationParameters( transID, 'Status' )
if not originalStatus['OK']:
return originalStatus
originalStatus = originalStatus['Value']
transIDAsDict = {transID: [originalStatus, transformationType]}
dictOfProposedstatus = {transID: paramValue}
# applying the state machine to the proposed status
value = self._applyTransformationStatusStateMachine( transIDAsDict, dictOfProposedstatus, force )
else:
value = paramValue
return rpcClient.setTransformationParameter( transID, paramName, value )
def _applyTransformationStatusStateMachine( self, transIDAsDict, dictOfProposedstatus, force ):
""" For easier extension, here we apply the state machine of the transformation status.
VOs might want to replace the standard here with something they prefer.
transIDAsDict is a dictionary with the transID as key and as value a list with [Status, Type]
dictOfProposedstatus is a dictionary with the proposed status
force is a boolean
It returns the new status (the standard is just doing nothing: everything is possible)
"""
return dictOfProposedstatus.values()[0]
#####################################################################
#
# These are the file catalog interface methods
#
def isOK( self ):
return self.valid
def getName( self, DN = '' ):
""" Get the file catalog type name
"""
return self.name
def addDirectory( self, path, force = False, rpc = '', url = '', timeout = None ):
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.addDirectory( path, force )
def getReplicas( self, lfn, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfns = res['Value'].keys()
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.getReplicas( lfns )
def addFile( self, lfn, force = False, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfndicts = res['Value']
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.addFile( lfndicts, force )
def addReplica( self, lfn, force = False, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfndicts = res['Value']
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.addReplica( lfndicts, force )
def removeFile( self, lfn, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfns = res['Value'].keys()
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
successful = {}
failed = {}
listOfLists = breakListIntoChunks( lfns, 100 )
for fList in listOfLists:
res = rpcClient.removeFile( fList )
if not res['OK']:
return res
successful.update( res['Value']['Successful'] )
failed.update( res['Value']['Failed'] )
resDict = {'Successful': successful, 'Failed':failed}
return S_OK( resDict )
def removeReplica( self, lfn, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfndicts = res['Value']
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
successful = {}
failed = {}
# as lfndicts is a dict, the breakListIntoChunks will fail. Fake it!
listOfDicts = []
localdicts = {}
for lfn, info in lfndicts.items():
localdicts.update( { lfn : info } )
if len( localdicts.keys() ) % 100 == 0:
listOfDicts.append( localdicts )
localdicts = {}
for fDict in listOfDicts:
res = rpcClient.removeReplica( fDict )
if not res['OK']:
return res
successful.update( res['Value']['Successful'] )
failed.update( res['Value']['Failed'] )
resDict = {'Successful': successful, 'Failed':failed}
return S_OK( resDict )
def getReplicaStatus( self, lfn, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfndict = res['Value']
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.getReplicaStatus( lfndict )
def setReplicaStatus( self, lfn, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfndict = res['Value']
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.setReplicaStatus( lfndict )
def setReplicaHost( self, lfn, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfndict = res['Value']
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.setReplicaHost( lfndict )
def removeDirectory( self, lfn, rpc = '', url = '', timeout = None ):
return self.__returnOK( lfn )
def createDirectory( self, lfn, rpc = '', url = '', timeout = None ):
return self.__returnOK( lfn )
def createLink( self, lfn, rpc = '', url = '', timeout = None ):
return self.__returnOK( lfn )
def removeLink( self, lfn, rpc = '', url = '', timeout = None ):
return self.__returnOK( lfn )
def __returnOK( self, lfn ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
successful = {}
for lfn in res['Value'].keys():
successful[lfn] = True
resDict = {'Successful':successful, 'Failed':{}}
return S_OK( resDict )
def __checkArgumentFormat( self, path ):
if type( path ) in types.StringTypes:
urls = {path:False}
elif type( path ) == types.ListType:
urls = {}
for url in path:
urls[url] = False
elif type( path ) == types.DictType:
urls = path
else:
return S_ERROR( "TransformationClient.__checkArgumentFormat: Supplied path is not of the correct format." )
return S_OK( urls )
| Java |
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "serial.h"
#include "inputprocessor.h"
#include "commandsender.h"
#include "plothelper.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void verticalSlider();
void sendmotor();
public slots:
void refreshDevices();
private slots:
void on_openButton_pressed();
void on_closeButton_pressed();
void on_clearButton_pressed();
void on_Send_pressed();
void rollPIDPressed();
void pitchPIDPressed();
void yawPIDPressed();
void rollRatePIDPressed();
void pitchRatePIDPressed();
void yawRatePIDPressed();
void rollSliderChanged();
void pitchSliderChanged();
void yawSliderChanged();
void rollRateSliderChanged();
void pitchRateSliderChanged();
void yawRateSliderChanged();
void sendRollPIDParam();
void sendPitchPIDParam();
void sendYawPIDParam();
void sendRollRatePIDParam();
void sendPitchRatePIDParam();
void sendYawRatePIDParam();
void on_pushButton_pressed();
void on_pushButton_4_pressed();
void on_pushButton_3_pressed();
void on_pushButton_2_pressed();
void on_lineEdit_2_returnPressed();
void on_lineEdit_5_returnPressed();
void on_lineEdit_4_returnPressed();
void on_lineEdit_3_returnPressed();
signals:
void rollPIDReleased();
void pitchPIDReleased();
void yawPIDReleased();
void rollRatePIDReleased();
void pitchRatePIDReleased();
void yawRatePIDReleased();
private:
void sendSetPoints();
Ui::MainWindow *ui;
Serial serial;
InputProcessor *ip;
CommandSender *cs;
QTimer *timer;
PlotHelper controllerLine1, controllerLine2, controllerLine3;
PlotHelper grawLine1, grawLine2, grawLine3;
PlotHelper arawLine1, arawLine2, arawLine3;
PlotHelper filterLine1, filterLine2, filterLine3;
};
#endif // MAINWINDOW_H
| Java |
-- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2016 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
load("/data/general/traps/complex.lua")
load("/data/general/traps/alarm.lua")
load("/data/general/traps/natural_forest.lua")
| Java |
/******************************************************************************
*
* MantaFlow fluid solver framework
* Copyright 2011 Tobias Pfaff, Nils Thuerey
*
* This program is free software, distributed under the terms of the
* GNU General Public License (GPL)
* http://www.gnu.org/licenses
*
* Plugin timing
*
******************************************************************************/
#ifndef _TIMING_H
#define _TIMING_H
#include "manta.h"
#include <map>
namespace Manta {
class TimingData {
private:
TimingData();
public:
static TimingData& instance() { static TimingData a; return a; }
void print();
void saveMean(const std::string& filename);
void start(FluidSolver* parent, const std::string& name);
void stop(FluidSolver* parent, const std::string& name);
protected:
void step();
struct TimingSet {
TimingSet() : num(0),updated(false) { cur.clear(); total.clear(); }
MuTime cur, total;
int num;
bool updated;
std::string solver;
};
bool updated;
int num;
MuTime mPluginTimer;
std::string mLastPlugin;
std::map<std::string, std::vector<TimingSet> > mData;
};
// Python interface
PYTHON() class Timings : public PbClass {
public:
PYTHON() Timings() : PbClass(0) {}
PYTHON() void display() { TimingData::instance().print(); }
PYTHON() void saveMean(std::string file) { TimingData::instance().saveMean(file); }
};
}
#endif
| Java |
from django.db import models
from django.contrib.auth.models import User
import MySQLdb
# Create your models here.
class Comentario(models.Model):
"""Comentario"""
contenido = models.TextField(help_text='Escribe un comentario')
fecha_coment = models.DateField(auto_now=True)
def __unicode__(self):
return self.contenido
class Estado(models.Model):
"""Estado"""
nom_estado = models.CharField(max_length=50)
def __unicode__(self):
return nom_estado
class Categoria(models.Model):
"""Categoria"""
nombre = models.CharField(max_length=50)
descripcion = models.TextField(help_text='Escribe una descripcion de la categoria')
class Entrada(models.Model):
"""Entrada"""
autor = models.ForeignKey(User)
comentario = models.ForeignKey(Comentario)
estado = models.ForeignKey(Estado)
titulo = models.CharField(max_length=100)
contenido = models.TextField(help_text='Redacta el contenido')
fecha_pub = models.DateField(auto_now=True)
def __unicode__(self):
return self.titulo
class Agregador(models.Model):
"""agreador"""
entrada = models.ForeignKey(Entrada)
categoria = models.ManyToManyField(Categoria) | Java |
XBMC Notify MQTT
=============================
An XBMC addon to display notifications received over mqtt.
Install
-------
Install the zip file through the XBMC add on interface.
Configure
---------
Insert the broker host, port, and the root path on in the configuration.
Topics
------
The root topic is configurable, but defaults to "/house/xbmc".
Status will be published to the root + "/status".
The service will display notifications published to root + "/all/messages".
Play status is published under the topic root + "player/status". It will be json string of with at least a state attribute, with optional type, current, and total time attributes.
Usage
-----
Publish a JSON message to the notification topic with title, text, duration (in seconds), and optional image attributes.
An example `{"title":"Here's a message", "text":"Here's the body", "image":"http://example.com/image.png, "duration":10}`
| Java |
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/** @file CommonIO.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include <libsolutil/CommonIO.h>
#include <libsolutil/Assertions.h>
#include <fstream>
#if defined(_WIN32)
#include <windows.h>
#else
#include <unistd.h>
#include <termios.h>
#endif
using namespace std;
using namespace solidity::util;
namespace
{
template <typename T>
inline T readFile(boost::filesystem::path const& _file)
{
assertThrow(boost::filesystem::exists(_file), FileNotFound, _file.string());
// ifstream does not always fail when the path leads to a directory. Instead it might succeed
// with tellg() returning a nonsensical value so that std::length_error gets raised in resize().
assertThrow(boost::filesystem::is_regular_file(_file), NotAFile, _file.string());
T ret;
size_t const c_elementSize = sizeof(typename T::value_type);
std::ifstream is(_file.string(), std::ifstream::binary);
// Technically, this can still fail even though we checked above because FS content can change at any time.
assertThrow(is, FileNotFound, _file.string());
// get length of file:
is.seekg(0, is.end);
streamoff length = is.tellg();
if (length == 0)
return ret; // do not read empty file (MSVC does not like it)
is.seekg(0, is.beg);
ret.resize((static_cast<size_t>(length) + c_elementSize - 1) / c_elementSize);
is.read(const_cast<char*>(reinterpret_cast<char const*>(ret.data())), static_cast<streamsize>(length));
return ret;
}
}
string solidity::util::readFileAsString(boost::filesystem::path const& _file)
{
return readFile<string>(_file);
}
string solidity::util::readUntilEnd(istream& _stdin)
{
ostringstream ss;
ss << _stdin.rdbuf();
return ss.str();
}
string solidity::util::readBytes(istream& _input, size_t _length)
{
string output;
output.resize(_length);
_input.read(output.data(), static_cast<streamsize>(_length));
// If read() reads fewer bytes it sets failbit in addition to eofbit.
if (_input.fail())
output.resize(static_cast<size_t>(_input.gcount()));
return output;
}
#if defined(_WIN32)
class DisableConsoleBuffering
{
public:
DisableConsoleBuffering()
{
m_stdin = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(m_stdin, &m_oldMode);
SetConsoleMode(m_stdin, m_oldMode & (~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT)));
}
~DisableConsoleBuffering()
{
SetConsoleMode(m_stdin, m_oldMode);
}
private:
HANDLE m_stdin;
DWORD m_oldMode;
};
#else
class DisableConsoleBuffering
{
public:
DisableConsoleBuffering()
{
tcgetattr(0, &m_termios);
m_termios.c_lflag &= ~tcflag_t(ICANON);
m_termios.c_lflag &= ~tcflag_t(ECHO);
m_termios.c_cc[VMIN] = 1;
m_termios.c_cc[VTIME] = 0;
tcsetattr(0, TCSANOW, &m_termios);
}
~DisableConsoleBuffering()
{
m_termios.c_lflag |= ICANON;
m_termios.c_lflag |= ECHO;
tcsetattr(0, TCSADRAIN, &m_termios);
}
private:
struct termios m_termios;
};
#endif
int solidity::util::readStandardInputChar()
{
DisableConsoleBuffering disableConsoleBuffering;
return cin.get();
}
string solidity::util::absolutePath(string const& _path, string const& _reference)
{
boost::filesystem::path p(_path);
// Anything that does not start with `.` is an absolute path.
if (p.begin() == p.end() || (*p.begin() != "." && *p.begin() != ".."))
return _path;
boost::filesystem::path result(_reference);
// If filename is "/", then remove_filename() throws.
// See: https://github.com/boostorg/filesystem/issues/176
if (result.filename() != boost::filesystem::path("/"))
result.remove_filename();
for (boost::filesystem::path::iterator it = p.begin(); it != p.end(); ++it)
if (*it == "..")
result = result.parent_path();
else if (*it != ".")
result /= *it;
return result.generic_string();
}
string solidity::util::sanitizePath(string const& _path) {
return boost::filesystem::path(_path).generic_string();
}
| Java |
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.reminders;
import android.app.Dialog;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;
import com.todoroo.astrid.activity.AstridActivity;
import com.todoroo.astrid.activity.TaskListFragment;
import org.tasks.Broadcaster;
import org.tasks.R;
import org.tasks.reminders.SnoozeActivity;
import javax.inject.Inject;
/**
* This activity is launched when a user opens up a notification from the
* tray. It launches the appropriate activity based on the passed in parameters.
*
* @author timsu
*
*/
public class NotificationFragment extends TaskListFragment {
public static final String TOKEN_ID = "id"; //$NON-NLS-1$
@Inject Broadcaster broadcaster;
@Override
protected void initializeData() {
displayNotificationPopup();
super.initializeData();
}
private void displayNotificationPopup() {
final String title = extras.getString(Notifications.EXTRAS_TITLE);
final long taskId = extras.getLong(TOKEN_ID);
final AstridActivity activity = (AstridActivity) getActivity();
new Dialog(activity, R.style.ReminderDialog) {{
setContentView(R.layout.astrid_reminder_view_portrait);
findViewById(R.id.speech_bubble_container).setVisibility(View.GONE);
// set up listeners
findViewById(R.id.dismiss).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
dismiss();
}
});
findViewById(R.id.reminder_snooze).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
dismiss();
activity.startActivity(new Intent(activity, SnoozeActivity.class) {{
putExtra(SnoozeActivity.TASK_ID, taskId);
}});
}
});
findViewById(R.id.reminder_complete).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
broadcaster.completeTask(taskId);
dismiss();
}
});
findViewById(R.id.reminder_edit).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
activity.onTaskListItemClicked(taskId);
}
});
((TextView) findViewById(R.id.reminder_title)).setText(activity.getString(R.string.rmd_NoA_dlg_title) + " " + title);
setOwnerActivity(activity);
}}.show();
}
}
| Java |
package com.simplecity.amp_library.model;
import android.content.Context;
import com.simplecity.amp_library.R;
import java.io.File;
public class ArtworkModel {
private static final String TAG = "ArtworkModel";
@ArtworkProvider.Type
public int type;
public File file;
public ArtworkModel(@ArtworkProvider.Type int type, File file) {
this.type = type;
this.file = file;
}
public static String getTypeString(Context context, @ArtworkProvider.Type int type) {
switch (type) {
case ArtworkProvider.Type.MEDIA_STORE:
return context.getString(R.string.artwork_type_media_store);
case ArtworkProvider.Type.TAG:
return context.getString(R.string.artwork_type_tag);
case ArtworkProvider.Type.FOLDER:
return "Folder";
case ArtworkProvider.Type.REMOTE:
return context.getString(R.string.artwork_type_internet);
}
return null;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ArtworkModel that = (ArtworkModel) o;
if (type != that.type) return false;
return file != null ? file.equals(that.file) : that.file == null;
}
@Override
public int hashCode() {
int result = type;
result = 31 * result + (file != null ? file.hashCode() : 0);
return result;
}
} | Java |
package com.newppt.android.ui;
import com.newppt.android.data.AnimUtils2;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;
public class ScaleImage extends ImageView {
final private int FLIP_DISTANCE = 30;
public ScaleImage(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public ScaleImage(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public ScaleImage(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
private int count = 0;
private long firClick;
private long secClick;
private boolean scaleTip = true;
private float x;
private float y;
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
if (MotionEvent.ACTION_DOWN == event.getAction()) {
count++;
if (count == 1) {
firClick = System.currentTimeMillis();
x = event.getX();
y = event.getY();
} else if (count == 2) {
secClick = System.currentTimeMillis();
float mx = event.getX();
float my = event.getY();
if (secClick - firClick < 700
&& Math.abs(mx - x) < FLIP_DISTANCE
&& Math.abs(my - y) < FLIP_DISTANCE) {
// ˫���¼�
if (scaleTip) {
x = event.getX();
y = event.getY();
AnimUtils2 animUtils2 = new AnimUtils2();
animUtils2.imageZoomOut(this, 200, x, y);
scaleTip = false;
}
else {
AnimUtils2 animUtils2 = new AnimUtils2();
animUtils2.imageZoomIn(this, 200, x, y);
scaleTip = true;
}
}
count = 0;
firClick = 0;
secClick = 0;
}
}
return true;
// return super.onTouchEvent(event);
}
}
| Java |
pyVenture - A python text-based adventure game engine
-----------------------------------------------------
This is a generalized framework that allows construction and playing of text-based-adventure-style worlds. Stores world information in JSON files.
This code is licensed under the General Public License Version 3 (http://www.gnu.org/licenses/gpl-3.0.html)
The following dependencies are required:
* Python 2.6+
* Qt4
* PyQt4
* GraphViz
* pydot
| Java |
/*
* Generic DSI Command Mode panel driver
*
* Copyright (C) 2013 Texas Instruments
* Author: Tomi Valkeinen <tomi.valkeinen@ti.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*/
/* #define DEBUG */
#include <linux/backlight.h>
#include <linux/delay.h>
#include <linux/fb.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/jiffies.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <linux/of_device.h>
#include <linux/of_gpio.h>
#include <video/omapfb_dss.h>
#include <video/mipi_display.h>
/* DSI Virtual channel. Hardcoded for now. */
#define TCH 0
#define DCS_READ_NUM_ERRORS 0x05
#define DCS_BRIGHTNESS 0x51
#define DCS_CTRL_DISPLAY 0x53
#define DCS_GET_ID1 0xda
#define DCS_GET_ID2 0xdb
#define DCS_GET_ID3 0xdc
struct panel_drv_data
{
struct omap_dss_device dssdev;
struct omap_dss_device *in;
struct omap_video_timings timings;
struct platform_device *pdev;
struct mutex lock;
struct backlight_device *bldev;
unsigned long hw_guard_end; /* next value of jiffies when we can
* issue the next sleep in/out command
*/
unsigned long hw_guard_wait; /* max guard time in jiffies */
/* panel HW configuration from DT or platform data */
int reset_gpio;
int ext_te_gpio;
bool use_dsi_backlight;
struct omap_dsi_pin_config pin_config;
/* runtime variables */
bool enabled;
bool te_enabled;
atomic_t do_update;
int channel;
struct delayed_work te_timeout_work;
bool intro_printed;
bool ulps_enabled;
unsigned ulps_timeout;
struct delayed_work ulps_work;
};
#define to_panel_data(p) container_of(p, struct panel_drv_data, dssdev)
static irqreturn_t dsicm_te_isr(int irq, void *data);
static void dsicm_te_timeout_work_callback(struct work_struct *work);
static int _dsicm_enable_te(struct panel_drv_data *ddata, bool enable);
static int dsicm_panel_reset(struct panel_drv_data *ddata);
static void dsicm_ulps_work(struct work_struct *work);
static void hw_guard_start(struct panel_drv_data *ddata, int guard_msec)
{
ddata->hw_guard_wait = msecs_to_jiffies(guard_msec);
ddata->hw_guard_end = jiffies + ddata->hw_guard_wait;
}
static void hw_guard_wait(struct panel_drv_data *ddata)
{
unsigned long wait = ddata->hw_guard_end - jiffies;
if ((long)wait > 0 && wait <= ddata->hw_guard_wait)
{
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_timeout(wait);
}
}
static int dsicm_dcs_read_1(struct panel_drv_data *ddata, u8 dcs_cmd, u8 *data)
{
struct omap_dss_device *in = ddata->in;
int r;
u8 buf[1];
r = in->ops.dsi->dcs_read(in, ddata->channel, dcs_cmd, buf, 1);
if (r < 0)
{
return r;
}
*data = buf[0];
return 0;
}
static int dsicm_dcs_write_0(struct panel_drv_data *ddata, u8 dcs_cmd)
{
struct omap_dss_device *in = ddata->in;
return in->ops.dsi->dcs_write(in, ddata->channel, &dcs_cmd, 1);
}
static int dsicm_dcs_write_1(struct panel_drv_data *ddata, u8 dcs_cmd, u8 param)
{
struct omap_dss_device *in = ddata->in;
u8 buf[2] = { dcs_cmd, param };
return in->ops.dsi->dcs_write(in, ddata->channel, buf, 2);
}
static int dsicm_sleep_in(struct panel_drv_data *ddata)
{
struct omap_dss_device *in = ddata->in;
u8 cmd;
int r;
hw_guard_wait(ddata);
cmd = MIPI_DCS_ENTER_SLEEP_MODE;
r = in->ops.dsi->dcs_write_nosync(in, ddata->channel, &cmd, 1);
if (r)
{
return r;
}
hw_guard_start(ddata, 120);
usleep_range(5000, 10000);
return 0;
}
static int dsicm_sleep_out(struct panel_drv_data *ddata)
{
int r;
hw_guard_wait(ddata);
r = dsicm_dcs_write_0(ddata, MIPI_DCS_EXIT_SLEEP_MODE);
if (r)
{
return r;
}
hw_guard_start(ddata, 120);
usleep_range(5000, 10000);
return 0;
}
static int dsicm_get_id(struct panel_drv_data *ddata, u8 *id1, u8 *id2, u8 *id3)
{
int r;
r = dsicm_dcs_read_1(ddata, DCS_GET_ID1, id1);
if (r)
{
return r;
}
r = dsicm_dcs_read_1(ddata, DCS_GET_ID2, id2);
if (r)
{
return r;
}
r = dsicm_dcs_read_1(ddata, DCS_GET_ID3, id3);
if (r)
{
return r;
}
return 0;
}
static int dsicm_set_update_window(struct panel_drv_data *ddata,
u16 x, u16 y, u16 w, u16 h)
{
struct omap_dss_device *in = ddata->in;
int r;
u16 x1 = x;
u16 x2 = x + w - 1;
u16 y1 = y;
u16 y2 = y + h - 1;
u8 buf[5];
buf[0] = MIPI_DCS_SET_COLUMN_ADDRESS;
buf[1] = (x1 >> 8) & 0xff;
buf[2] = (x1 >> 0) & 0xff;
buf[3] = (x2 >> 8) & 0xff;
buf[4] = (x2 >> 0) & 0xff;
r = in->ops.dsi->dcs_write_nosync(in, ddata->channel, buf, sizeof(buf));
if (r)
{
return r;
}
buf[0] = MIPI_DCS_SET_PAGE_ADDRESS;
buf[1] = (y1 >> 8) & 0xff;
buf[2] = (y1 >> 0) & 0xff;
buf[3] = (y2 >> 8) & 0xff;
buf[4] = (y2 >> 0) & 0xff;
r = in->ops.dsi->dcs_write_nosync(in, ddata->channel, buf, sizeof(buf));
if (r)
{
return r;
}
in->ops.dsi->bta_sync(in, ddata->channel);
return r;
}
static void dsicm_queue_ulps_work(struct panel_drv_data *ddata)
{
if (ddata->ulps_timeout > 0)
schedule_delayed_work(&ddata->ulps_work,
msecs_to_jiffies(ddata->ulps_timeout));
}
static void dsicm_cancel_ulps_work(struct panel_drv_data *ddata)
{
cancel_delayed_work(&ddata->ulps_work);
}
static int dsicm_enter_ulps(struct panel_drv_data *ddata)
{
struct omap_dss_device *in = ddata->in;
int r;
if (ddata->ulps_enabled)
{
return 0;
}
dsicm_cancel_ulps_work(ddata);
r = _dsicm_enable_te(ddata, false);
if (r)
{
goto err;
}
if (gpio_is_valid(ddata->ext_te_gpio))
{
disable_irq(gpio_to_irq(ddata->ext_te_gpio));
}
in->ops.dsi->disable(in, false, true);
ddata->ulps_enabled = true;
return 0;
err:
dev_err(&ddata->pdev->dev, "enter ULPS failed");
dsicm_panel_reset(ddata);
ddata->ulps_enabled = false;
dsicm_queue_ulps_work(ddata);
return r;
}
static int dsicm_exit_ulps(struct panel_drv_data *ddata)
{
struct omap_dss_device *in = ddata->in;
int r;
if (!ddata->ulps_enabled)
{
return 0;
}
r = in->ops.dsi->enable(in);
if (r)
{
dev_err(&ddata->pdev->dev, "failed to enable DSI\n");
goto err1;
}
in->ops.dsi->enable_hs(in, ddata->channel, true);
r = _dsicm_enable_te(ddata, true);
if (r)
{
dev_err(&ddata->pdev->dev, "failed to re-enable TE");
goto err2;
}
if (gpio_is_valid(ddata->ext_te_gpio))
{
enable_irq(gpio_to_irq(ddata->ext_te_gpio));
}
dsicm_queue_ulps_work(ddata);
ddata->ulps_enabled = false;
return 0;
err2:
dev_err(&ddata->pdev->dev, "failed to exit ULPS");
r = dsicm_panel_reset(ddata);
if (!r)
{
if (gpio_is_valid(ddata->ext_te_gpio))
{
enable_irq(gpio_to_irq(ddata->ext_te_gpio));
}
ddata->ulps_enabled = false;
}
err1:
dsicm_queue_ulps_work(ddata);
return r;
}
static int dsicm_wake_up(struct panel_drv_data *ddata)
{
if (ddata->ulps_enabled)
{
return dsicm_exit_ulps(ddata);
}
dsicm_cancel_ulps_work(ddata);
dsicm_queue_ulps_work(ddata);
return 0;
}
static int dsicm_bl_update_status(struct backlight_device *dev)
{
struct panel_drv_data *ddata = dev_get_drvdata(&dev->dev);
struct omap_dss_device *in = ddata->in;
int r;
int level;
if (dev->props.fb_blank == FB_BLANK_UNBLANK &&
dev->props.power == FB_BLANK_UNBLANK)
{
level = dev->props.brightness;
}
else
{
level = 0;
}
dev_dbg(&ddata->pdev->dev, "update brightness to %d\n", level);
mutex_lock(&ddata->lock);
if (ddata->enabled)
{
in->ops.dsi->bus_lock(in);
r = dsicm_wake_up(ddata);
if (!r)
{
r = dsicm_dcs_write_1(ddata, DCS_BRIGHTNESS, level);
}
in->ops.dsi->bus_unlock(in);
}
else
{
r = 0;
}
mutex_unlock(&ddata->lock);
return r;
}
static int dsicm_bl_get_intensity(struct backlight_device *dev)
{
if (dev->props.fb_blank == FB_BLANK_UNBLANK &&
dev->props.power == FB_BLANK_UNBLANK)
{
return dev->props.brightness;
}
return 0;
}
static const struct backlight_ops dsicm_bl_ops =
{
.get_brightness = dsicm_bl_get_intensity,
.update_status = dsicm_bl_update_status,
};
static void dsicm_get_resolution(struct omap_dss_device *dssdev,
u16 *xres, u16 *yres)
{
*xres = dssdev->panel.timings.x_res;
*yres = dssdev->panel.timings.y_res;
}
static ssize_t dsicm_num_errors_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
struct omap_dss_device *in = ddata->in;
u8 errors = 0;
int r;
mutex_lock(&ddata->lock);
if (ddata->enabled)
{
in->ops.dsi->bus_lock(in);
r = dsicm_wake_up(ddata);
if (!r)
r = dsicm_dcs_read_1(ddata, DCS_READ_NUM_ERRORS,
&errors);
in->ops.dsi->bus_unlock(in);
}
else
{
r = -ENODEV;
}
mutex_unlock(&ddata->lock);
if (r)
{
return r;
}
return snprintf(buf, PAGE_SIZE, "%d\n", errors);
}
static ssize_t dsicm_hw_revision_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
struct omap_dss_device *in = ddata->in;
u8 id1, id2, id3;
int r;
mutex_lock(&ddata->lock);
if (ddata->enabled)
{
in->ops.dsi->bus_lock(in);
r = dsicm_wake_up(ddata);
if (!r)
{
r = dsicm_get_id(ddata, &id1, &id2, &id3);
}
in->ops.dsi->bus_unlock(in);
}
else
{
r = -ENODEV;
}
mutex_unlock(&ddata->lock);
if (r)
{
return r;
}
return snprintf(buf, PAGE_SIZE, "%02x.%02x.%02x\n", id1, id2, id3);
}
static ssize_t dsicm_store_ulps(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct platform_device *pdev = to_platform_device(dev);
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
struct omap_dss_device *in = ddata->in;
unsigned long t;
int r;
r = kstrtoul(buf, 0, &t);
if (r)
{
return r;
}
mutex_lock(&ddata->lock);
if (ddata->enabled)
{
in->ops.dsi->bus_lock(in);
if (t)
{
r = dsicm_enter_ulps(ddata);
}
else
{
r = dsicm_wake_up(ddata);
}
in->ops.dsi->bus_unlock(in);
}
mutex_unlock(&ddata->lock);
if (r)
{
return r;
}
return count;
}
static ssize_t dsicm_show_ulps(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
unsigned t;
mutex_lock(&ddata->lock);
t = ddata->ulps_enabled;
mutex_unlock(&ddata->lock);
return snprintf(buf, PAGE_SIZE, "%u\n", t);
}
static ssize_t dsicm_store_ulps_timeout(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct platform_device *pdev = to_platform_device(dev);
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
struct omap_dss_device *in = ddata->in;
unsigned long t;
int r;
r = kstrtoul(buf, 0, &t);
if (r)
{
return r;
}
mutex_lock(&ddata->lock);
ddata->ulps_timeout = t;
if (ddata->enabled)
{
/* dsicm_wake_up will restart the timer */
in->ops.dsi->bus_lock(in);
r = dsicm_wake_up(ddata);
in->ops.dsi->bus_unlock(in);
}
mutex_unlock(&ddata->lock);
if (r)
{
return r;
}
return count;
}
static ssize_t dsicm_show_ulps_timeout(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
unsigned t;
mutex_lock(&ddata->lock);
t = ddata->ulps_timeout;
mutex_unlock(&ddata->lock);
return snprintf(buf, PAGE_SIZE, "%u\n", t);
}
static DEVICE_ATTR(num_dsi_errors, S_IRUGO, dsicm_num_errors_show, NULL);
static DEVICE_ATTR(hw_revision, S_IRUGO, dsicm_hw_revision_show, NULL);
static DEVICE_ATTR(ulps, S_IRUGO | S_IWUSR,
dsicm_show_ulps, dsicm_store_ulps);
static DEVICE_ATTR(ulps_timeout, S_IRUGO | S_IWUSR,
dsicm_show_ulps_timeout, dsicm_store_ulps_timeout);
static struct attribute *dsicm_attrs[] =
{
&dev_attr_num_dsi_errors.attr,
&dev_attr_hw_revision.attr,
&dev_attr_ulps.attr,
&dev_attr_ulps_timeout.attr,
NULL,
};
static struct attribute_group dsicm_attr_group =
{
.attrs = dsicm_attrs,
};
static void dsicm_hw_reset(struct panel_drv_data *ddata)
{
if (!gpio_is_valid(ddata->reset_gpio))
{
return;
}
gpio_set_value(ddata->reset_gpio, 1);
udelay(10);
/* reset the panel */
gpio_set_value(ddata->reset_gpio, 0);
/* assert reset */
udelay(10);
gpio_set_value(ddata->reset_gpio, 1);
/* wait after releasing reset */
usleep_range(5000, 10000);
}
static int dsicm_power_on(struct panel_drv_data *ddata)
{
struct omap_dss_device *in = ddata->in;
u8 id1, id2, id3;
int r;
struct omap_dss_dsi_config dsi_config =
{
.mode = OMAP_DSS_DSI_CMD_MODE,
.pixel_format = OMAP_DSS_DSI_FMT_RGB888,
.timings = &ddata->timings,
.hs_clk_min = 150000000,
.hs_clk_max = 300000000,
.lp_clk_min = 7000000,
.lp_clk_max = 10000000,
};
if (ddata->pin_config.num_pins > 0)
{
r = in->ops.dsi->configure_pins(in, &ddata->pin_config);
if (r)
{
dev_err(&ddata->pdev->dev,
"failed to configure DSI pins\n");
goto err0;
}
}
r = in->ops.dsi->set_config(in, &dsi_config);
if (r)
{
dev_err(&ddata->pdev->dev, "failed to configure DSI\n");
goto err0;
}
r = in->ops.dsi->enable(in);
if (r)
{
dev_err(&ddata->pdev->dev, "failed to enable DSI\n");
goto err0;
}
dsicm_hw_reset(ddata);
in->ops.dsi->enable_hs(in, ddata->channel, false);
r = dsicm_sleep_out(ddata);
if (r)
{
goto err;
}
r = dsicm_get_id(ddata, &id1, &id2, &id3);
if (r)
{
goto err;
}
r = dsicm_dcs_write_1(ddata, DCS_BRIGHTNESS, 0xff);
if (r)
{
goto err;
}
r = dsicm_dcs_write_1(ddata, DCS_CTRL_DISPLAY,
(1 << 2) | (1 << 5)); /* BL | BCTRL */
if (r)
{
goto err;
}
r = dsicm_dcs_write_1(ddata, MIPI_DCS_SET_PIXEL_FORMAT,
MIPI_DCS_PIXEL_FMT_24BIT);
if (r)
{
goto err;
}
r = dsicm_dcs_write_0(ddata, MIPI_DCS_SET_DISPLAY_ON);
if (r)
{
goto err;
}
r = _dsicm_enable_te(ddata, ddata->te_enabled);
if (r)
{
goto err;
}
r = in->ops.dsi->enable_video_output(in, ddata->channel);
if (r)
{
goto err;
}
ddata->enabled = 1;
if (!ddata->intro_printed)
{
dev_info(&ddata->pdev->dev, "panel revision %02x.%02x.%02x\n",
id1, id2, id3);
ddata->intro_printed = true;
}
in->ops.dsi->enable_hs(in, ddata->channel, true);
return 0;
err:
dev_err(&ddata->pdev->dev, "error while enabling panel, issuing HW reset\n");
dsicm_hw_reset(ddata);
in->ops.dsi->disable(in, true, false);
err0:
return r;
}
static void dsicm_power_off(struct panel_drv_data *ddata)
{
struct omap_dss_device *in = ddata->in;
int r;
in->ops.dsi->disable_video_output(in, ddata->channel);
r = dsicm_dcs_write_0(ddata, MIPI_DCS_SET_DISPLAY_OFF);
if (!r)
{
r = dsicm_sleep_in(ddata);
}
if (r)
{
dev_err(&ddata->pdev->dev,
"error disabling panel, issuing HW reset\n");
dsicm_hw_reset(ddata);
}
in->ops.dsi->disable(in, true, false);
ddata->enabled = 0;
}
static int dsicm_panel_reset(struct panel_drv_data *ddata)
{
dev_err(&ddata->pdev->dev, "performing LCD reset\n");
dsicm_power_off(ddata);
dsicm_hw_reset(ddata);
return dsicm_power_on(ddata);
}
static int dsicm_connect(struct omap_dss_device *dssdev)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
struct device *dev = &ddata->pdev->dev;
int r;
if (omapdss_device_is_connected(dssdev))
{
return 0;
}
r = in->ops.dsi->connect(in, dssdev);
if (r)
{
dev_err(dev, "Failed to connect to video source\n");
return r;
}
r = in->ops.dsi->request_vc(ddata->in, &ddata->channel);
if (r)
{
dev_err(dev, "failed to get virtual channel\n");
goto err_req_vc;
}
r = in->ops.dsi->set_vc_id(ddata->in, ddata->channel, TCH);
if (r)
{
dev_err(dev, "failed to set VC_ID\n");
goto err_vc_id;
}
return 0;
err_vc_id:
in->ops.dsi->release_vc(ddata->in, ddata->channel);
err_req_vc:
in->ops.dsi->disconnect(in, dssdev);
return r;
}
static void dsicm_disconnect(struct omap_dss_device *dssdev)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
if (!omapdss_device_is_connected(dssdev))
{
return;
}
in->ops.dsi->release_vc(in, ddata->channel);
in->ops.dsi->disconnect(in, dssdev);
}
static int dsicm_enable(struct omap_dss_device *dssdev)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
int r;
dev_dbg(&ddata->pdev->dev, "enable\n");
mutex_lock(&ddata->lock);
if (!omapdss_device_is_connected(dssdev))
{
r = -ENODEV;
goto err;
}
if (omapdss_device_is_enabled(dssdev))
{
r = 0;
goto err;
}
in->ops.dsi->bus_lock(in);
r = dsicm_power_on(ddata);
in->ops.dsi->bus_unlock(in);
if (r)
{
goto err;
}
dssdev->state = OMAP_DSS_DISPLAY_ACTIVE;
mutex_unlock(&ddata->lock);
return 0;
err:
dev_dbg(&ddata->pdev->dev, "enable failed\n");
mutex_unlock(&ddata->lock);
return r;
}
static void dsicm_disable(struct omap_dss_device *dssdev)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
int r;
dev_dbg(&ddata->pdev->dev, "disable\n");
mutex_lock(&ddata->lock);
dsicm_cancel_ulps_work(ddata);
in->ops.dsi->bus_lock(in);
if (omapdss_device_is_enabled(dssdev))
{
r = dsicm_wake_up(ddata);
if (!r)
{
dsicm_power_off(ddata);
}
}
in->ops.dsi->bus_unlock(in);
dssdev->state = OMAP_DSS_DISPLAY_DISABLED;
mutex_unlock(&ddata->lock);
}
static void dsicm_framedone_cb(int err, void *data)
{
struct panel_drv_data *ddata = data;
struct omap_dss_device *in = ddata->in;
dev_dbg(&ddata->pdev->dev, "framedone, err %d\n", err);
in->ops.dsi->bus_unlock(ddata->in);
}
static irqreturn_t dsicm_te_isr(int irq, void *data)
{
struct panel_drv_data *ddata = data;
struct omap_dss_device *in = ddata->in;
int old;
int r;
old = atomic_cmpxchg(&ddata->do_update, 1, 0);
if (old)
{
cancel_delayed_work(&ddata->te_timeout_work);
r = in->ops.dsi->update(in, ddata->channel, dsicm_framedone_cb,
ddata);
if (r)
{
goto err;
}
}
return IRQ_HANDLED;
err:
dev_err(&ddata->pdev->dev, "start update failed\n");
in->ops.dsi->bus_unlock(in);
return IRQ_HANDLED;
}
static void dsicm_te_timeout_work_callback(struct work_struct *work)
{
struct panel_drv_data *ddata = container_of(work, struct panel_drv_data,
te_timeout_work.work);
struct omap_dss_device *in = ddata->in;
dev_err(&ddata->pdev->dev, "TE not received for 250ms!\n");
atomic_set(&ddata->do_update, 0);
in->ops.dsi->bus_unlock(in);
}
static int dsicm_update(struct omap_dss_device *dssdev,
u16 x, u16 y, u16 w, u16 h)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
int r;
dev_dbg(&ddata->pdev->dev, "update %d, %d, %d x %d\n", x, y, w, h);
mutex_lock(&ddata->lock);
in->ops.dsi->bus_lock(in);
r = dsicm_wake_up(ddata);
if (r)
{
goto err;
}
if (!ddata->enabled)
{
r = 0;
goto err;
}
/* XXX no need to send this every frame, but dsi break if not done */
r = dsicm_set_update_window(ddata, 0, 0,
dssdev->panel.timings.x_res,
dssdev->panel.timings.y_res);
if (r)
{
goto err;
}
if (ddata->te_enabled && gpio_is_valid(ddata->ext_te_gpio))
{
schedule_delayed_work(&ddata->te_timeout_work,
msecs_to_jiffies(250));
atomic_set(&ddata->do_update, 1);
}
else
{
r = in->ops.dsi->update(in, ddata->channel, dsicm_framedone_cb,
ddata);
if (r)
{
goto err;
}
}
/* note: no bus_unlock here. unlock is in framedone_cb */
mutex_unlock(&ddata->lock);
return 0;
err:
in->ops.dsi->bus_unlock(in);
mutex_unlock(&ddata->lock);
return r;
}
static int dsicm_sync(struct omap_dss_device *dssdev)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
dev_dbg(&ddata->pdev->dev, "sync\n");
mutex_lock(&ddata->lock);
in->ops.dsi->bus_lock(in);
in->ops.dsi->bus_unlock(in);
mutex_unlock(&ddata->lock);
dev_dbg(&ddata->pdev->dev, "sync done\n");
return 0;
}
static int _dsicm_enable_te(struct panel_drv_data *ddata, bool enable)
{
struct omap_dss_device *in = ddata->in;
int r;
if (enable)
{
r = dsicm_dcs_write_1(ddata, MIPI_DCS_SET_TEAR_ON, 0);
}
else
{
r = dsicm_dcs_write_0(ddata, MIPI_DCS_SET_TEAR_OFF);
}
if (!gpio_is_valid(ddata->ext_te_gpio))
{
in->ops.dsi->enable_te(in, enable);
}
/* possible panel bug */
msleep(100);
return r;
}
static int dsicm_enable_te(struct omap_dss_device *dssdev, bool enable)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
int r;
mutex_lock(&ddata->lock);
if (ddata->te_enabled == enable)
{
goto end;
}
in->ops.dsi->bus_lock(in);
if (ddata->enabled)
{
r = dsicm_wake_up(ddata);
if (r)
{
goto err;
}
r = _dsicm_enable_te(ddata, enable);
if (r)
{
goto err;
}
}
ddata->te_enabled = enable;
in->ops.dsi->bus_unlock(in);
end:
mutex_unlock(&ddata->lock);
return 0;
err:
in->ops.dsi->bus_unlock(in);
mutex_unlock(&ddata->lock);
return r;
}
static int dsicm_get_te(struct omap_dss_device *dssdev)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
int r;
mutex_lock(&ddata->lock);
r = ddata->te_enabled;
mutex_unlock(&ddata->lock);
return r;
}
static int dsicm_memory_read(struct omap_dss_device *dssdev,
void *buf, size_t size,
u16 x, u16 y, u16 w, u16 h)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
int r;
int first = 1;
int plen;
unsigned buf_used = 0;
if (size < w * h * 3)
{
return -ENOMEM;
}
mutex_lock(&ddata->lock);
if (!ddata->enabled)
{
r = -ENODEV;
goto err1;
}
size = min(w * h * 3,
dssdev->panel.timings.x_res *
dssdev->panel.timings.y_res * 3);
in->ops.dsi->bus_lock(in);
r = dsicm_wake_up(ddata);
if (r)
{
goto err2;
}
/* plen 1 or 2 goes into short packet. until checksum error is fixed,
* use short packets. plen 32 works, but bigger packets seem to cause
* an error. */
if (size % 2)
{
plen = 1;
}
else
{
plen = 2;
}
dsicm_set_update_window(ddata, x, y, w, h);
r = in->ops.dsi->set_max_rx_packet_size(in, ddata->channel, plen);
if (r)
{
goto err2;
}
while (buf_used < size)
{
u8 dcs_cmd = first ? 0x2e : 0x3e;
first = 0;
r = in->ops.dsi->dcs_read(in, ddata->channel, dcs_cmd,
buf + buf_used, size - buf_used);
if (r < 0)
{
dev_err(dssdev->dev, "read error\n");
goto err3;
}
buf_used += r;
if (r < plen)
{
dev_err(&ddata->pdev->dev, "short read\n");
break;
}
if (signal_pending(current))
{
dev_err(&ddata->pdev->dev, "signal pending, "
"aborting memory read\n");
r = -ERESTARTSYS;
goto err3;
}
}
r = buf_used;
err3:
in->ops.dsi->set_max_rx_packet_size(in, ddata->channel, 1);
err2:
in->ops.dsi->bus_unlock(in);
err1:
mutex_unlock(&ddata->lock);
return r;
}
static void dsicm_ulps_work(struct work_struct *work)
{
struct panel_drv_data *ddata = container_of(work, struct panel_drv_data,
ulps_work.work);
struct omap_dss_device *dssdev = &ddata->dssdev;
struct omap_dss_device *in = ddata->in;
mutex_lock(&ddata->lock);
if (dssdev->state != OMAP_DSS_DISPLAY_ACTIVE || !ddata->enabled)
{
mutex_unlock(&ddata->lock);
return;
}
in->ops.dsi->bus_lock(in);
dsicm_enter_ulps(ddata);
in->ops.dsi->bus_unlock(in);
mutex_unlock(&ddata->lock);
}
static struct omap_dss_driver dsicm_ops =
{
.connect = dsicm_connect,
.disconnect = dsicm_disconnect,
.enable = dsicm_enable,
.disable = dsicm_disable,
.update = dsicm_update,
.sync = dsicm_sync,
.get_resolution = dsicm_get_resolution,
.get_recommended_bpp = omapdss_default_get_recommended_bpp,
.enable_te = dsicm_enable_te,
.get_te = dsicm_get_te,
.memory_read = dsicm_memory_read,
};
static int dsicm_probe_of(struct platform_device *pdev)
{
struct device_node *node = pdev->dev.of_node;
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
struct omap_dss_device *in;
int gpio;
gpio = of_get_named_gpio(node, "reset-gpios", 0);
if (!gpio_is_valid(gpio))
{
dev_err(&pdev->dev, "failed to parse reset gpio\n");
return gpio;
}
ddata->reset_gpio = gpio;
gpio = of_get_named_gpio(node, "te-gpios", 0);
if (gpio_is_valid(gpio) || gpio == -ENOENT)
{
ddata->ext_te_gpio = gpio;
}
else
{
dev_err(&pdev->dev, "failed to parse TE gpio\n");
return gpio;
}
in = omapdss_of_find_source_for_first_ep(node);
if (IS_ERR(in))
{
dev_err(&pdev->dev, "failed to find video source\n");
return PTR_ERR(in);
}
ddata->in = in;
/* TODO: ulps, backlight */
return 0;
}
static int dsicm_probe(struct platform_device *pdev)
{
struct backlight_properties props;
struct panel_drv_data *ddata;
struct backlight_device *bldev = NULL;
struct device *dev = &pdev->dev;
struct omap_dss_device *dssdev;
int r;
dev_dbg(dev, "probe\n");
if (!pdev->dev.of_node)
{
return -ENODEV;
}
ddata = devm_kzalloc(dev, sizeof(*ddata), GFP_KERNEL);
if (!ddata)
{
return -ENOMEM;
}
platform_set_drvdata(pdev, ddata);
ddata->pdev = pdev;
r = dsicm_probe_of(pdev);
if (r)
{
return r;
}
ddata->timings.x_res = 864;
ddata->timings.y_res = 480;
ddata->timings.pixelclock = 864 * 480 * 60;
dssdev = &ddata->dssdev;
dssdev->dev = dev;
dssdev->driver = &dsicm_ops;
dssdev->panel.timings = ddata->timings;
dssdev->type = OMAP_DISPLAY_TYPE_DSI;
dssdev->owner = THIS_MODULE;
dssdev->panel.dsi_pix_fmt = OMAP_DSS_DSI_FMT_RGB888;
dssdev->caps = OMAP_DSS_DISPLAY_CAP_MANUAL_UPDATE |
OMAP_DSS_DISPLAY_CAP_TEAR_ELIM;
r = omapdss_register_display(dssdev);
if (r)
{
dev_err(dev, "Failed to register panel\n");
goto err_reg;
}
mutex_init(&ddata->lock);
atomic_set(&ddata->do_update, 0);
if (gpio_is_valid(ddata->reset_gpio))
{
r = devm_gpio_request_one(dev, ddata->reset_gpio,
GPIOF_OUT_INIT_LOW, "taal rst");
if (r)
{
dev_err(dev, "failed to request reset gpio\n");
return r;
}
}
if (gpio_is_valid(ddata->ext_te_gpio))
{
r = devm_gpio_request_one(dev, ddata->ext_te_gpio,
GPIOF_IN, "taal irq");
if (r)
{
dev_err(dev, "GPIO request failed\n");
return r;
}
r = devm_request_irq(dev, gpio_to_irq(ddata->ext_te_gpio),
dsicm_te_isr,
IRQF_TRIGGER_RISING,
"taal vsync", ddata);
if (r)
{
dev_err(dev, "IRQ request failed\n");
return r;
}
INIT_DEFERRABLE_WORK(&ddata->te_timeout_work,
dsicm_te_timeout_work_callback);
dev_dbg(dev, "Using GPIO TE\n");
}
INIT_DELAYED_WORK(&ddata->ulps_work, dsicm_ulps_work);
dsicm_hw_reset(ddata);
if (ddata->use_dsi_backlight)
{
memset(&props, 0, sizeof(struct backlight_properties));
props.max_brightness = 255;
props.type = BACKLIGHT_RAW;
bldev = backlight_device_register(dev_name(dev),
dev, ddata, &dsicm_bl_ops, &props);
if (IS_ERR(bldev))
{
r = PTR_ERR(bldev);
goto err_reg;
}
ddata->bldev = bldev;
bldev->props.fb_blank = FB_BLANK_UNBLANK;
bldev->props.power = FB_BLANK_UNBLANK;
bldev->props.brightness = 255;
dsicm_bl_update_status(bldev);
}
r = sysfs_create_group(&dev->kobj, &dsicm_attr_group);
if (r)
{
dev_err(dev, "failed to create sysfs files\n");
goto err_sysfs_create;
}
return 0;
err_sysfs_create:
if (bldev != NULL)
{
backlight_device_unregister(bldev);
}
err_reg:
return r;
}
static int __exit dsicm_remove(struct platform_device *pdev)
{
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
struct omap_dss_device *dssdev = &ddata->dssdev;
struct backlight_device *bldev;
dev_dbg(&pdev->dev, "remove\n");
omapdss_unregister_display(dssdev);
dsicm_disable(dssdev);
dsicm_disconnect(dssdev);
sysfs_remove_group(&pdev->dev.kobj, &dsicm_attr_group);
bldev = ddata->bldev;
if (bldev != NULL)
{
bldev->props.power = FB_BLANK_POWERDOWN;
dsicm_bl_update_status(bldev);
backlight_device_unregister(bldev);
}
omap_dss_put_device(ddata->in);
dsicm_cancel_ulps_work(ddata);
/* reset, to be sure that the panel is in a valid state */
dsicm_hw_reset(ddata);
return 0;
}
static const struct of_device_id dsicm_of_match[] =
{
{ .compatible = "omapdss,panel-dsi-cm", },
{},
};
MODULE_DEVICE_TABLE(of, dsicm_of_match);
static struct platform_driver dsicm_driver =
{
.probe = dsicm_probe,
.remove = __exit_p(dsicm_remove),
.driver = {
.name = "panel-dsi-cm",
.of_match_table = dsicm_of_match,
.suppress_bind_attrs = true,
},
};
module_platform_driver(dsicm_driver);
MODULE_AUTHOR("Tomi Valkeinen <tomi.valkeinen@ti.com>");
MODULE_DESCRIPTION("Generic DSI Command Mode Panel Driver");
MODULE_LICENSE("GPL");
| Java |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**************************************************************************
*
* Copyright 2010 American Public Media Group
*
* This file is part of AIR2.
*
* AIR2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AIR2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with AIR2. If not, see <http://www.gnu.org/licenses/>.
*
*************************************************************************/
require_once "AIR2Logger.php";
require_once 'AirValidHtml.php'; //custom validator extension
require_once 'AirValidNoHtml.php'; //custom validator extension
/**
* AIR2_Record base class
*
* @author pkarman
* @package default
*/
abstract class AIR2_Record extends Doctrine_Record {
/* fields which the discriminator will treat as case-insensitive */
protected static $DISC_CASE_INSENSITIVE_FLDS = array('src_username',
'src_first_name', 'src_last_name', 'src_middle_initial', 'src_pre_name',
'src_post_name', 'sa_name', 'sa_first_name', 'sa_last_name', 'sa_post_name',
'smadd_line_1', 'smadd_line_2', 'smadd_city', 'sf_src_value');
/**
* tests validity of the record using the current data.
*
* (This is an override of base Doctrine functionality, to fix a bug with validation.)
*
* @param boolean $deep (optional) run the validation process on the relations
* @param boolean $hooks (optional) invoke save hooks before start
* @return boolean whether or not this record is valid
*/
public function isValid($deep = false, $hooks = true) {
if ( ! $this->_table->getAttribute(Doctrine_Core::ATTR_VALIDATE)) {
return true;
}
if ($this->_state == self::STATE_LOCKED || $this->_state == self::STATE_TLOCKED) {
return true;
}
if ($hooks) {
$this->invokeSaveHooks('pre', 'save');
$this->invokeSaveHooks('pre', $this->exists() ? 'update' : 'insert');
}
// Clear the stack from any previous errors.
$this->getErrorStack()->clear();
// Run validation process
$event = new Doctrine_Event($this, Doctrine_Event::RECORD_VALIDATE);
$this->preValidate($event);
$this->getTable()->getRecordListener()->preValidate($event);
if ( ! $event->skipOperation) {
$validator = new Doctrine_Validator();
$validator->validateRecord($this);
$this->validate();
if ($this->_state == self::STATE_TDIRTY || $this->_state == self::STATE_TCLEAN) {
$this->validateOnInsert();
}
else {
$this->validateOnUpdate();
}
}
$this->getTable()->getRecordListener()->postValidate($event);
$this->postValidate($event);
$valid = $this->getErrorStack()->count() == 0 ? true : false;
if ($valid && $deep) {
$stateBeforeLock = $this->_state;
$this->_state = $this->exists() ? self::STATE_LOCKED : self::STATE_TLOCKED;
foreach ($this->_references as $reference) {
if ($reference instanceof Doctrine_Record) {
if ( ! $valid = $reference->isValid($deep)) {
break;
}
}
elseif ($reference instanceof Doctrine_Collection) {
foreach ($reference as $record) {
if ( ! $valid = $record->isValid($deep, $hooks)) {
break;
}
}
// Bugfix.
if (!$valid) {
break;
}
}
}
$this->_state = $stateBeforeLock;
}
return $valid;
}
/**
* Save the record to the database
*
* @param object $conn (optional)
*/
public function save( Doctrine_Connection $conn=null ) {
// unless explicitly passed, we find the _master connection
// for the current env.
if ( $conn === null ) {
$conn = AIR2_DBManager::get_master_connection();
}
parent::save($conn);
}
/**
* Insert or update record in the database.
*
* @param object $conn (optional)
*/
public function replace( Doctrine_Connection $conn=null ) {
// unless explicitly passed, we find the _master connection
// for the current env.
if ( $conn === null ) {
$conn = AIR2_DBManager::get_master_connection();
}
parent::replace($conn);
}
/**
* All AIR2_Record tables should be UTF8
*/
public function setTableDefinition() {
// utf8 charset
$this->option('collate', 'utf8_unicode_ci');
$this->option('charset', 'utf8');
}
/**
* Detect whether to add CreUser and UpdUser relations
*/
public function setUp() {
parent::setUp();
$cols = $this->getTable()->getColumnNames();
foreach ($cols as $name) {
if (preg_match('/_cre_user$/', $name)) {
$this->hasOne('UserStamp as CreUser',
array('local' => $name, 'foreign' => 'user_id')
);
}
elseif (preg_match('/_upd_user$/', $name)) {
$this->hasOne('UserStamp as UpdUser',
array('local' => $name, 'foreign' => 'user_id')
);
}
}
}
/**
* Custom AIR2 validation before update/save
*
* @param Doctrine_Event $event
*/
public function preValidate($event) {
air2_model_prevalidate($this);
}
/**
* Determines if a record produced from the tank can be safely moved into
* AIR2, or if it conflicts with existing AIR2 data.
*
* @param array $data
* @param TankSource $tsrc
* @param int $op
*/
public function discriminate($data, &$tsrc, $op=null) {
// update the record
$exists = $this->exists();
foreach ($data as $key => $val) {
// trim any incoming string values
if ($val && is_string($val)) {
$val = trim($val);
}
// always update new records
if (!$exists) {
$this->$key = $val;
}
// replace NULLs
elseif (is_null($this->$key)) {
$this->$key = $val;
}
// check for conflict
elseif ($this->disc_is_conflict($key, $this->$key, $val)) {
// CONFLICT! check the $op value
if ($op == AIR2_DISCRIM_REPLACE) {
$this->$key = $val;
}
else {
$this->disc_add_conflict($tsrc, $key, $this->$key, $val);
}
}
}
}
/**
* Compares 2 values, and determines if there is a conflict. Returning
* false will NOT update the field, so do it yourself if that's what you
* want.
*
* @param string $field
* @param mixed $oldval
* @param mixed $newval
* @return boolean
*/
protected function disc_is_conflict($field, $oldval, $newval) {
// check for case-insensitive fields
if (in_array($field, self::$DISC_CASE_INSENSITIVE_FLDS)) {
$oldval = strtolower($oldval);
$newval = strtolower($newval);
}
$result = ($oldval != $newval); // default php comparison
return $result;
}
/**
* Add a conflict to the tank_source
*
* @param TankSource $tsrc
* @param string $field
* @param mixed $oldval
* @param mixed $newval
*/
protected function disc_add_conflict($tsrc, $field, $oldval, $newval) {
$cls = $this->getTable()->getClassnameToReturn();
$uuidcol = air2_get_model_uuid_col($cls);
$uuid = $this->$uuidcol;
$tsrc->add_conflict($cls, $field, 'Conflicting tank value', $uuid);
}
/**
* Determine if a User has permission to read this record.
*
* @param User $u
* @return authz integer
*/
public function user_may_read(User $u) {
throw new Exception('user_may_read not implemented for ' . get_class($this));
return false;
}
/**
* Determine if a User has permission to write to this record.
*
* @param User $u
* @return authz integer
*/
public function user_may_write(User $u) {
throw new Exception('user_may_write not implemented for ' . get_class($this));
return false;
}
/**
* Determine if a User has permission to manage this record.
*
* @param User $u
* @return authz integer
*/
public function user_may_manage(User $u) {
throw new Exception('user_may_manage not implemented for ' . get_class($this));
return false;
}
/**
* Determine if a User has permission delete this record.
* By default calls through to user_may_manage().
*
* @param User $u
* @return authz integer
*/
public function user_may_delete(User $u) {
return $this->user_may_manage($u);
}
/**
* Record a visit against this record by a given user, at a given IPv4 address.
*
* @return void
* @author sgilbertson
* @param array $config Keys: user (@see User); ip (string|int).
* */
public function visit($config) {
$user = null;
$ip = null;
extract($config);
UserVisit::create_visit(
array(
'record' => $this,
'user' => $user,
'ip' => $ip,
)
);
}
/**
* Add User reading-authorization conditions to a Doctrine Query. By
* default, any restrictions must come from subclasses.
*
* @param AIR2_Query $q
* @param User $u
* @param string $alias (optional)
*/
public static function query_may_read(AIR2_Query $q, User $u, $alias=null) {
//TODO: alter query in subclasses
}
/**
* Add User write-authorization conditions to a Doctrine Query.
* TODO: by default, this is the same as read permissions.
*
* @param AIR2_Query $q
* @param User $u
* @param string $alias (optional)
*/
public static function query_may_write(AIR2_Query $q, User $u, $alias=null) {
self::query_may_read($q, $u, $alias);
}
/**
* Add User managing-authorization conditions to a Doctrine Query.
* TODO: by default, this is the same as write permissions.
*
* @param AIR2_Query $q
* @param User $u
* @param string $alias (optional)
*/
public static function query_may_manage(AIR2_Query $q, User $u, $alias=null) {
self::query_may_write($q, $u, $alias);
}
/**
*
*
* @param string $model_name
* @param string $uuid
* @return AIR2_Record object for $model_name
*/
public static function find($model_name, $uuid) {
$tbl = Doctrine::getTable($model_name);
$col = air2_get_model_uuid_col($model_name);
return $tbl->findOneBy($col, $uuid);
}
/**
* Preinsert hook for transactional activity logging.
*
* @param Doctrine_Event $event
*/
public function preInsert($event) {
parent::preInsert($event);
AIR2Logger::log($this, 'insert');
}
/**
* Preupdate hook for transactional activity logging.
*
* @param Doctrine_Event $event
*/
public function preUpdate($event) {
parent::preUpdate($event);
AIR2Logger::log($this, 'update');
}
/**
* Postdelete hook for transactional activity logging.
*
* @param Doctrine_Event $event
*/
public function postDelete($event) {
AIR2Logger::log($this, 'delete');
parent::postDelete($event);
}
/**
* Returns object as JSON string. Only immediate columns
* (no related objects) are encoded.
*
* @return $json
*/
public function asJSON() {
$cols = $this->toArray(false);
return Encoding::json_encode_utf8($cols);
}
/**
* Custom mutator to reset timestamp to NULL value.
*
* @param unknown $field
* @param timestamp $value
*/
public function _set_timestamp($field, $value) {
if (empty($value) || !isset($value)) {
$this->_set($field, null);
}
else {
$this->_set($field, $value);
}
}
}
| Java |
<?php
/*
oauthcallback.php
This script handles the oAuth grant 'code' that is returned from the provider
(google/fb/openid), and calls the 'authenticate' method of the PBS_LAAS_Client.
That method exchanges the grant 'code' with PBS's endpoints to get access and refresh tokens,
uses those to get user info (email, name, etc), and then stores the tokens and userinfo encrypted
in session variables.
If the 'rememberme' variable was true, those tokens are also stored in an encrypted cookie.
*/
show_admin_bar(false);
remove_all_actions('wp_footer',1);
remove_all_actions('wp_header',1);
$defaults = get_option('pbs_passport_authenticate');
$passport = new PBS_Passport_Authenticate(dirname(__FILE__));
$laas_client = $passport->get_laas_client();
// log any current session out
$laas_client->logout();
$login_referrer = !empty($defaults['landing_page_url']) ? $defaults['landing_page_url'] : site_url();
if (!empty($_COOKIE["pbsoauth_login_referrer"])){
$login_referrer = $_COOKIE["pbsoauth_login_referrer"];
setcookie( 'pbsoauth_login_referrer', '', 1, '/', $_SERVER['HTTP_HOST']);
}
$membership_id = false;
// where to direct a logged in visitor who isn't a member
$not_member_path = 'pbsoauth/userinfo';
if (isset($_GET["state"])){
$state=($_GET["state"]);
$jwt = $passport->read_jwt($state);
if ($jwt) {
$membership_id = !empty($jwt['sub']) ? $jwt['sub'] : false;
// allow the jwt to override the current value with a return_path
$login_referrer = !empty($jwt['return_path']) ? site_url($jwt['return_path']) : $login_referrer;
// allow the jwt to set where the authenticated visitor who is not a member is sent
$not_member_path = !empty($jwt['not_member_path']) ? $jwt['not_member_path'] : $not_member_path;
} else {
// fallback case for older clients when membership_id was passed as a plaintext string
$membership_id = (!empty($state) ? $state : false);
}
}
$rememberme = false;
if (!empty($_COOKIE["pbsoauth_rememberme"])) {
$rememberme = $_COOKIE["pbsoauth_rememberme"];
}
// nonce is going to be in the jwt
$nonce = false;
$errors = array();
if (isset($_GET["code"])){
$code = $_GET["code"];
$userinfo = $laas_client->authenticate($code, $rememberme, $nonce);
}
// now we either have userinfo or null.
if (isset($userinfo["pid"])){
$pbs_uid = $userinfo["pid"];
// now we work with the mvault
$mvault_client = $passport->get_mvault_client();
$mvaultinfo = array();
if ($membership_id) {
// this is an activation!
$mvaultinfo = $mvault_client->get_membership($membership_id);
if (isset($mvaultinfo["membership_id"])) {
$mvaultinfo = $mvault_client->activate($membership_id, $pbs_uid);
}
}
// is the person activated now?
if (!isset($mvaultinfo["membership_id"])) {
$mvaultinfo = $mvault_client->get_membership_by_uid($pbs_uid);
if (!isset($mvaultinfo["membership_id"])) {
// still not activated, redirect the member as needed
$login_referrer = site_url($not_member_path);
}
}
}
wp_redirect($login_referrer);
exit();
?>
| Java |
@ECHO OFF
IF EXIST %cd%\fwservice.exe (
c:\windows\microsoft.net\framework\v4.0.30319\installutil.exe %cd%\fwsyslog.exe
) ELSE (
GOTO FNFAbort
)
ECHO.
ECHO Batch complete.
ECHO.
GOTO EOB
:FNFAbort
ECHO.
ECHO Batch aborted! File fwsyslog.exe not found in current directory.
ECHO.
:EOB
ECHO ON
| Java |
CREATE TABLE "alameda_county_content_config" (
"homepage" text,
"about_page" text
);
| Java |
<!doctype html><html><head><title>Easy Image Mapper</title><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1"><link rel="stylesheet" href="easy-mapper.css">
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script><script src="easy-mapper-1.2.0.js"></script></head><body>
<!-- 딤 스크린 -->
<div id="dim"></div>
<div class="pop" id="pop-local">
<p class="pop-title">LOAD LOCAL IMAGE</p>
<div class="pop-content">
<input type="file" id="pop-local-input">
</div>
<div class="pop-btn">
<div class="pop-btn-confirm">LOAD</div>
<div class="pop-btn-cancel">CANCEL</div>
</div>
</div>
<div class="pop" id="pop-url">
<p class="pop-title">LINK IMAGE URL</p>
<div class="pop-content">
<input type="text" id="pop-url-input">
</div>
<div class="pop-btn">
<div class="pop-btn-confirm">LINK</div>
<div class="pop-btn-cancel">CANCEL</div>
</div>
</div>
<div class="pop" id="pop-code">
<p class="pop-title">CODE GENERATED</p>
<div class="pop-btn">
<div class="pop-btn-copy" id="pop-btn-copy-a">SHOW MARKUP AS <em><A> TAG</em> FORM</div>
<div class="pop-btn-copy" id="pop-btn-copy-im">SHOW MARKUP AS <em>IMAGE MAP</em> FORM</div>
<div class="pop-btn-cancel _full">CLOSE</div>
</div>
</div>
<div class="pop" id="pop-codegen-a">
<p class="pop-title"><A> TAG FORM</p>
<div class="pop-content">
<p></p>
</div>
<div class="pop-btn-cancel _back">BACK</div>
<div class="pop-btn-cancel">CLOSE</div>
</div>
<div class="pop" id="pop-codegen-im">
<p class="pop-title">IMAGE MAP FORM</p>
<div class="pop-content">
<p></p>
</div>
<div class="pop-btn-cancel _back">BACK</div>
<div class="pop-btn-cancel">CLOSE</div>
</div>
<div class="pop" id="pop-info">
<p class="pop-title">APP INFORMATION</p>
<div class="pop-content">
<p>
<em class="pop-content-alert">⚠ This app works on IE10+ only.</em>
<strong>Easy Image Mapper (v1.2.0)</strong><br>
Author: Inpyo Jeon<br>
Contact: inpyoj@gmail.com<br>
Website: <a class="_hover-ul" href="https://github.com/1npy0/easy-mapper" target="_blank">GitHub Repository</a>
</p>
</div>
<div class="pop-btn-cancel _full">CLOSE</div>
</div>
<div class="pop" id="pop-addlink">
<p class="pop-title">ADD URL LINK</p>
<div class="pop-content">
<input type="text" id="pop-addlink-input">
<label><input type="radio" name="pop-addlink-target" value="_blank" checked>New Window (target:_blank)</label>
<label><input type="radio" name="pop-addlink-target" value="_self">Self Frame (target:_self)</label>
<label><input type="radio" name="pop-addlink-target" value="_parent">Parent Frame (target:_parent)</label>
<label><input type="radio" name="pop-addlink-target" value="_top">Full Body (target:_top)</label>
</div>
<div class="pop-btn">
<div class="pop-btn-confirm">ADD LINK</div>
<div class="pop-btn-cancel">CANCEL</div>
</div>
</div>
<!-- 헤더 -->
<div id="gnb">
<a id="gnb-title" href="easy-mapper.html" onclick="if (!confirm('Do you want to reset all the changes?')) return false;">↻ REFRESH</a>
<!-- 드롭다운 메뉴 -->
<ul id="gnb-menu">
<li id="gnb-menu-source">
<span>SOURCE ▾</span>
<ul class="gnb-menu-sub">
<li id="gnb-menu-local">LOCAL</li>
<li id="gnb-menu-url">URL</li>
</ul>
</li>
<li id="gnb-menu-measure">
<span>MEASURE ▾</span>
<ul class="gnb-menu-sub _toggle">
<li id="gnb-menu-drag" class="_active">DRAG<em> ✓</em></li>
<li id="gnb-menu-click">CLICK<em> ✓</em></li>
</ul>
</li>
<li id="gnb-menu-unit">
<span>UNIT ▾</span>
<ul class="gnb-menu-sub _toggle">
<li id="gnb-menu-pixel" class="_active">PX<em> ✓</em></li>
<li id="gnb-menu-percent">%<em> ✓</em></li>
</ul>
</li>
<li id="gnb-menu-clear">
<span>CLEAR</span>
</li>
<li id="gnb-menu-generate">
<span>GENERATE</span>
</li>
<li id="gnb-menu-info">
<span>?</span>
</li>
</ul>
</div>
<!-- 작업공간 -->
<div id="workspace">
<!-- 눈금자 -->
<div id="workspace-ruler">
<div id="workspace-ruler-x">
<div id="workspace-ruler-x-2"></div>
<div id="workspace-ruler-x-1"></div>
</div>
<div id="workspace-ruler-y">
<div id="workspace-ruler-y-2"></div>
<div id="workspace-ruler-y-1"></div>
</div>
</div>
<!-- 이미지 -->
<div id="workspace-img-wrap">
<img id="workspace-img" src="sampleimg.png">
<!-- 그리드 -->
<div id="grid-x1" class="grid-1"></div>
<div id="grid-y1" class="grid-1"></div>
<div id="grid-x2" class="grid-2"></div>
<div id="grid-y2" class="grid-2"></div>
<span id="grid-coords"></span>
</div>
</div>
</body></html> | Java |
#ifndef MUSPLAY_USE_WINAPI
#include <QtDebug>
#include <QFileDialog>
#include <QMessageBox>
#include <QSlider>
#include <QSettings>
#include <QMenu>
#include <QDesktopServices>
#include <QUrl>
#include "ui_mainwindow.h"
#include "musplayer_qt.h"
#include "../Player/mus_player.h"
#include "../AssocFiles/assoc_files.h"
#include "../Effects/reverb.h"
#include <math.h>
#include "../version.h"
MusPlayer_Qt::MusPlayer_Qt(QWidget *parent) : QMainWindow(parent),
MusPlayerBase(),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
PGE_MusicPlayer::setMainWindow(this);
#ifdef Q_OS_MAC
this->setWindowIcon(QIcon(":/cat_musplay.icns"));
#endif
#ifdef Q_OS_WIN
this->setWindowIcon(QIcon(":/cat_musplay.ico"));
#endif
ui->fmbank->clear();
int totalBakns = MIX_ADLMIDI_getTotalBanks();
const char *const *names = MIX_ADLMIDI_getBankNames();
for(int i = 0; i < totalBakns; i++)
ui->fmbank->addItem(QString("%1 = %2").arg(i).arg(names[i]));
ui->centralWidget->window()->setWindowFlags(
Qt::WindowTitleHint |
Qt::WindowSystemMenuHint |
Qt::WindowCloseButtonHint |
Qt::WindowMinimizeButtonHint |
Qt::MSWindowsFixedSizeDialogHint);
connect(&m_blinker, SIGNAL(timeout()), this, SLOT(_blink_red()));
connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenu(QPoint)));
connect(ui->volume, &QSlider::valueChanged, [this](int x)
{
on_volume_valueChanged(x);
});
connect(ui->fmbank, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [this](int x)
{
on_fmbank_currentIndexChanged(x);
});
connect(ui->volumeModel, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [this](int x)
{
on_volumeModel_currentIndexChanged(x);
});
connect(ui->tremolo, &QCheckBox::clicked, this, [this](int x)
{
on_tremolo_clicked(x);
});
connect(ui->vibrato, &QCheckBox::clicked, this, [this](int x)
{
on_vibrato_clicked(x);
});
connect(ui->modulation, &QCheckBox::clicked, this, [this](int x)
{
on_modulation_clicked(x);
});
connect(ui->adlibMode, &QCheckBox::clicked, this, [this](int x)
{
on_adlibMode_clicked(x);
});
connect(ui->logVolumes, &QCheckBox::clicked, this, [this](int x)
{
on_logVolumes_clicked(x);
});
connect(ui->playListPush, &QPushButton::clicked, this, &MusPlayer_Qt::playList_pushCurrent);
connect(ui->playListPop, &QPushButton::clicked, this, &MusPlayer_Qt::playList_popCurrent);
QApplication::setOrganizationName(_COMPANY);
QApplication::setOrganizationDomain(_PGE_URL);
QApplication::setApplicationName("PGE Music Player");
ui->playList->setModel(&playList);
ui->playList->setVisible(false);
ui->playListPush->setVisible(false);
ui->playListPop->setVisible(false);
ui->sfx_testing->setVisible(false);
QSettings setup;
restoreGeometry(setup.value("Window-Geometry").toByteArray());
ui->mididevice->setCurrentIndex(setup.value("MIDI-Device", 0).toInt());
ui->opnmidi_extra->setVisible(ui->mididevice->currentIndex() == 3);
ui->adlmidi_xtra->setVisible(ui->mididevice->currentIndex() == 0);
switch(ui->mididevice->currentIndex())
{
case 0:
MIX_SetMidiDevice(MIDI_ADLMIDI);
break;
case 1:
MIX_SetMidiDevice(MIDI_Timidity);
break;
case 2:
MIX_SetMidiDevice(MIDI_Native);
break;
case 3:
MIX_SetMidiDevice(MIDI_OPNMIDI);
break;
case 4:
MIX_SetMidiDevice(MIDI_Fluidsynth);
break;
default:
MIX_SetMidiDevice(MIDI_ADLMIDI);
break;
}
ui->fmbank->setCurrentIndex(setup.value("ADLMIDI-Bank-ID", 58).toInt());
MIX_ADLMIDI_setBankID(ui->fmbank->currentIndex());
ui->volumeModel->setCurrentIndex(setup.value("ADLMIDI-VolumeModel", 0).toInt());
MIX_ADLMIDI_setVolumeModel(ui->volumeModel->currentIndex());
ui->tremolo->setChecked(setup.value("ADLMIDI-Tremolo", true).toBool());
MIX_ADLMIDI_setTremolo(static_cast<int>(ui->tremolo->isChecked()));
ui->vibrato->setChecked(setup.value("ADLMIDI-Vibrato", true).toBool());
MIX_ADLMIDI_setVibrato(static_cast<int>(ui->vibrato->isChecked()));
ui->adlibMode->setChecked(setup.value("ADLMIDI-AdLib-Drums-Mode", false).toBool());
MIX_ADLMIDI_setAdLibMode(static_cast<int>(ui->adlibMode->isChecked()));
ui->modulation->setChecked(setup.value("ADLMIDI-Scalable-Modulation", false).toBool());
MIX_ADLMIDI_setScaleMod(static_cast<int>(ui->modulation->isChecked()));
ui->logVolumes->setChecked(setup.value("ADLMIDI-LogarithmicVolumes", false).toBool());
MIX_ADLMIDI_setScaleMod(static_cast<int>(ui->logVolumes->isChecked()));
ui->volume->setValue(setup.value("Volume", 128).toInt());
m_prevTrackID = ui->trackID->value();
ui->adlmidi_xtra->setVisible(false);
ui->opnmidi_extra->setVisible(false);
ui->midi_setup->setVisible(false);
ui->gme_setup->setVisible(false);
currentMusic = setup.value("RecentMusic", "").toString();
m_testSfxDir = setup.value("RecentSfxDir", "").toString();
adjustSize();
}
MusPlayer_Qt::~MusPlayer_Qt()
{
on_stop_clicked();
if(m_testSfx)
Mix_FreeChunk(m_testSfx);
m_testSfx = nullptr;
Mix_CloseAudio();
QSettings setup;
setup.setValue("Window-Geometry", saveGeometry());
setup.setValue("MIDI-Device", ui->mididevice->currentIndex());
setup.setValue("ADLMIDI-Bank-ID", ui->fmbank->currentIndex());
setup.setValue("ADLMIDI-VolumeModel", ui->volumeModel->currentIndex());
setup.setValue("ADLMIDI-Tremolo", ui->tremolo->isChecked());
setup.setValue("ADLMIDI-Vibrato", ui->vibrato->isChecked());
setup.setValue("ADLMIDI-AdLib-Drums-Mode", ui->adlibMode->isChecked());
setup.setValue("ADLMIDI-Scalable-Modulation", ui->modulation->isChecked());
setup.setValue("ADLMIDI-LogarithmicVolumes", ui->logVolumes->isChecked());
setup.setValue("Volume", ui->volume->value());
setup.setValue("RecentMusic", currentMusic);
setup.setValue("RecentSfxDir", m_testSfxDir);
delete ui;
}
void MusPlayer_Qt::dropEvent(QDropEvent *e)
{
this->raise();
this->setFocus(Qt::ActiveWindowFocusReason);
if(ui->recordWav->isChecked())
return;
for(const QUrl &url : e->mimeData()->urls())
{
const QString &fileName = url.toLocalFile();
currentMusic = fileName;
}
ui->recordWav->setEnabled(!currentMusic.endsWith(".wav", Qt::CaseInsensitive));//Avoid self-trunkling!
PGE_MusicPlayer::MUS_stopMusic();
on_play_clicked();
this->raise();
e->accept();
}
void MusPlayer_Qt::dragEnterEvent(QDragEnterEvent *e)
{
if(e->mimeData()->hasUrls())
e->acceptProposedAction();
}
void MusPlayer_Qt::contextMenu(const QPoint &pos)
{
QMenu x;
QAction *open = x.addAction("Open");
QAction *playpause = x.addAction("Play/Pause");
QAction *stop = x.addAction("Stop");
x.addSeparator();
QAction *reverb = x.addAction("Reverb");
reverb->setCheckable(true);
reverb->setChecked(PGE_MusicPlayer::reverbEnabled);
QAction *assoc_files = x.addAction("Associate files");
QAction *play_list = x.addAction("Play-list mode [WIP]");
play_list->setCheckable(true);
play_list->setChecked(playListMode);
QAction *sfx_testing = x.addAction("SFX testing");
sfx_testing->setCheckable(true);
sfx_testing->setChecked(ui->sfx_testing->isVisible());
x.addSeparator();
QMenu *about = x.addMenu("About");
QAction *version = about->addAction("SDL Mixer X Music Player v." _FILE_VERSION);
version->setEnabled(false);
QAction *license = about->addAction("Licensed under GNU GPLv3 license");
about->addSeparator();
QAction *source = about->addAction("Get source code");
QAction *ret = x.exec(this->mapToGlobal(pos));
if(open == ret)
on_open_clicked();
else if(playpause == ret)
on_play_clicked();
else if(stop == ret)
on_stop_clicked();
else if(reverb == ret)
{
PGE_MusicPlayer::reverbEnabled = reverb->isChecked();
if(PGE_MusicPlayer::reverbEnabled)
Mix_RegisterEffect(MIX_CHANNEL_POST, reverbEffect, reverbEffectDone, NULL);
else
Mix_UnregisterEffect(MIX_CHANNEL_POST, reverbEffect);
}
else if(assoc_files == ret)
{
AssocFiles af(this);
af.setWindowModality(Qt::WindowModal);
af.exec();
}
else if(ret == play_list)
{
setPlayListMode(!playListMode);
}
else if(ret == sfx_testing)
{
ui->sfx_testing->setVisible(!ui->sfx_testing->isVisible());
updateGeometry();
adjustSize();
}
else if(ret == license)
QDesktopServices::openUrl(QUrl("http://www.gnu.org/licenses/gpl"));
else if(ret == source)
QDesktopServices::openUrl(QUrl("https://github.com/WohlSoft/PGE-Project"));
}
void MusPlayer_Qt::openMusicByArg(QString musPath)
{
if(ui->recordWav->isChecked()) return;
currentMusic = musPath;
//ui->recordWav->setEnabled(!currentMusic.endsWith(".wav", Qt::CaseInsensitive));//Avoid self-trunkling!
PGE_MusicPlayer::MUS_stopMusic();
on_play_clicked();
}
void MusPlayer_Qt::setPlayListMode(bool plMode)
{
on_stop_clicked();
playListMode = plMode;
if(!plMode)
{
playList.clear();
} else {
playList_pushCurrent();
}
ui->playList->setVisible(plMode);
ui->playListPush->setVisible(plMode);
ui->playListPop->setVisible(plMode);
if(ui->recordWav->isChecked())
ui->recordWav->click();
ui->recordWav->setVisible(!plMode);
PGE_MusicPlayer::setPlayListMode(playListMode);
adjustSize();
}
void MusPlayer_Qt::playList_pushCurrent(bool)
{
PlayListEntry e;
e.name = ui->musTitle->text();
e.fullPath = currentMusic;
e.gme_trackNum = ui->trackID->value();
e.midi_device = ui->mididevice->currentIndex();
e.adl_bankNo = ui->fmbank->currentIndex();
e.adl_cmfVolumes = ui->volumeModel->currentIndex();
e.adl_tremolo = ui->tremolo->isChecked();
e.adl_vibrato = ui->vibrato->isChecked();
e.adl_adlibDrums = ui->adlibMode->isChecked();
e.adl_modulation = ui->modulation->isChecked();
e.adl_cmfVolumes = ui->logVolumes->isChecked();
playList.insertEntry(e);
}
void MusPlayer_Qt::playList_popCurrent(bool)
{
playList.removeEntry();
}
void MusPlayer_Qt::playListNext()
{
PlayListEntry e = playList.nextEntry();
currentMusic = e.fullPath;
switchMidiDevice(e.midi_device);
ui->trackID->setValue(e.gme_trackNum);
ui->fmbank->setCurrentIndex(e.adl_bankNo);
ui->volumeModel->setCurrentIndex(e.adl_volumeModel);
ui->tremolo->setChecked(e.adl_tremolo);
ui->vibrato->setChecked(e.adl_vibrato);
ui->adlibMode->setChecked(e.adl_adlibDrums);
ui->modulation->setChecked(e.adl_modulation);
ui->logVolumes->setChecked(e.adl_cmfVolumes);
MIX_ADLMIDI_setBankID(e.adl_bankNo);
MIX_ADLMIDI_setVolumeModel(e.adl_volumeModel);
MIX_ADLMIDI_setTremolo(static_cast<int>(ui->tremolo->isChecked()));
MIX_ADLMIDI_setVibrato(static_cast<int>(ui->vibrato->isChecked()));
MIX_ADLMIDI_setAdLibMode(static_cast<int>(ui->adlibMode->isChecked()));
MIX_ADLMIDI_setScaleMod(static_cast<int>(ui->modulation->isChecked()));
MIX_ADLMIDI_setLogarithmicVolumes(static_cast<int>(ui->logVolumes->isChecked()));
PGE_MusicPlayer::MUS_stopMusic();
on_play_clicked();
}
void MusPlayer_Qt::switchMidiDevice(int index)
{
ui->midi_setup->setVisible(false);
ui->adlmidi_xtra->setVisible(false);
ui->opnmidi_extra->setVisible(false);
ui->midi_setup->setVisible(true);
switch(index)
{
case 0:
MIX_SetMidiDevice(MIDI_ADLMIDI);
ui->adlmidi_xtra->setVisible(true);
break;
case 1:
MIX_SetMidiDevice(MIDI_Timidity);
break;
case 2:
MIX_SetMidiDevice(MIDI_Native);
break;
case 3:
MIX_SetMidiDevice(MIDI_OPNMIDI);
ui->opnmidi_extra->setVisible(true);
break;
case 4:
MIX_SetMidiDevice(MIDI_Fluidsynth);
break;
default:
MIX_SetMidiDevice(MIDI_ADLMIDI);
ui->adlmidi_xtra->setVisible(true);
break;
}
}
void MusPlayer_Qt::on_open_clicked()
{
QString file = QFileDialog::getOpenFileName(this, tr("Open music file"),
(currentMusic.isEmpty() ? QApplication::applicationDirPath() : currentMusic), "All (*.*)");
if(file.isEmpty())
return;
currentMusic = file;
//ui->recordWav->setEnabled(!currentMusic.endsWith(".wav", Qt::CaseInsensitive));//Avoid self-trunkling!
PGE_MusicPlayer::MUS_stopMusic();
on_play_clicked();
}
void MusPlayer_Qt::on_stop_clicked()
{
PGE_MusicPlayer::MUS_stopMusic();
ui->play->setText(tr("Play"));
if(ui->recordWav->isChecked())
{
ui->recordWav->setChecked(false);
PGE_MusicPlayer::stopWavRecording();
ui->open->setEnabled(true);
ui->play->setEnabled(true);
ui->frame->setEnabled(true);
m_blinker.stop();
ui->recordWav->setStyleSheet("");
}
}
void MusPlayer_Qt::on_play_clicked()
{
if(Mix_PlayingMusic())
{
if(Mix_PausedMusic())
{
Mix_ResumeMusic();
ui->play->setText(tr("Pause"));
return;
}
else
{
Mix_PauseMusic();
ui->play->setText(tr("Resume"));
return;
}
}
ui->play->setText(tr("Play"));
m_prevTrackID = ui->trackID->value();
if(PGE_MusicPlayer::MUS_openFile(currentMusic + "|" + ui->trackID->text()))
{
PGE_MusicPlayer::MUS_changeVolume(ui->volume->value());
PGE_MusicPlayer::MUS_playMusic();
ui->play->setText(tr("Pause"));
}
ui->musTitle->setText(PGE_MusicPlayer::MUS_getMusTitle());
ui->musArtist->setText(PGE_MusicPlayer::MUS_getMusArtist());
ui->musAlbum->setText(PGE_MusicPlayer::MUS_getMusAlbum());
ui->musCopyright->setText(PGE_MusicPlayer::MUS_getMusCopy());
ui->gme_setup->setVisible(false);
ui->adlmidi_xtra->setVisible(false);
ui->opnmidi_extra->setVisible(false);
ui->midi_setup->setVisible(false);
ui->frame->setVisible(false);
ui->frame->setVisible(true);
ui->smallInfo->setText(PGE_MusicPlayer::musicType());
ui->gridLayout->update();
switch(PGE_MusicPlayer::type)
{
case MUS_MID:
ui->adlmidi_xtra->setVisible(ui->mididevice->currentIndex() == 0);
ui->opnmidi_extra->setVisible(ui->mididevice->currentIndex() == 3);
ui->midi_setup->setVisible(true);
ui->frame->setVisible(true);
break;
case MUS_SPC:
ui->gme_setup->setVisible(true);
ui->frame->setVisible(true);
break;
default:
break;
}
adjustSize();
}
void MusPlayer_Qt::on_mididevice_currentIndexChanged(int index)
{
switchMidiDevice(index);
adjustSize();
if(Mix_PlayingMusic())
{
if(PGE_MusicPlayer::type == MUS_MID)
{
PGE_MusicPlayer::MUS_stopMusic();
on_play_clicked();
}
}
}
void MusPlayer_Qt::on_trackID_editingFinished()
{
if(Mix_PlayingMusic())
{
if((PGE_MusicPlayer::type == MUS_SPC) && (m_prevTrackID != ui->trackID->value()))
{
PGE_MusicPlayer::MUS_stopMusic();
on_play_clicked();
}
}
}
void MusPlayer_Qt::on_recordWav_clicked(bool checked)
{
if(checked)
{
PGE_MusicPlayer::MUS_stopMusic();
ui->play->setText(tr("Play"));
QFileInfo twav(currentMusic);
PGE_MusicPlayer::stopWavRecording();
QString wavPathBase = twav.absoluteDir().absolutePath() + "/" + twav.baseName();
QString wavPath = wavPathBase + ".wav";
int count = 1;
while(QFile::exists(wavPath))
wavPath = wavPathBase + QString("-%1.wav").arg(count++);
PGE_MusicPlayer::startWavRecording(wavPath);
on_play_clicked();
ui->open->setEnabled(false);
ui->play->setEnabled(false);
ui->frame->setEnabled(false);
m_blinker.start(500);
}
else
{
on_stop_clicked();
PGE_MusicPlayer::stopWavRecording();
ui->open->setEnabled(true);
ui->play->setEnabled(true);
ui->frame->setEnabled(true);
m_blinker.stop();
ui->recordWav->setStyleSheet("");
}
}
void MusPlayer_Qt::on_resetDefaultADLMIDI_clicked()
{
ui->fmbank->setCurrentIndex(58);
ui->tremolo->setChecked(true);
ui->vibrato->setChecked(true);
ui->adlibMode->setChecked(false);
ui->modulation->setChecked(false);
ui->logVolumes->setChecked(false);
MIX_ADLMIDI_setTremolo(static_cast<int>(ui->tremolo->isChecked()));
MIX_ADLMIDI_setVibrato(static_cast<int>(ui->vibrato->isChecked()));
MIX_ADLMIDI_setAdLibMode(static_cast<int>(ui->adlibMode->isChecked()));
MIX_ADLMIDI_setScaleMod(static_cast<int>(ui->modulation->isChecked()));
MIX_ADLMIDI_setLogarithmicVolumes(static_cast<int>(ui->logVolumes->isChecked()));
on_volumeModel_currentIndexChanged(ui->volumeModel->currentIndex());
on_fmbank_currentIndexChanged(ui->fmbank->currentIndex());
}
void MusPlayer_Qt::_blink_red()
{
m_blink_state = !m_blink_state;
if(m_blink_state)
ui->recordWav->setStyleSheet("background-color : red; color : black;");
else
ui->recordWav->setStyleSheet("background-color : black; color : red;");
}
void MusPlayer_Qt::on_sfx_open_clicked()
{
QString file = QFileDialog::getOpenFileName(this, tr("Open SFX file"),
(m_testSfxDir.isEmpty() ? QApplication::applicationDirPath() : m_testSfxDir), "All (*.*)");
if(file.isEmpty())
return;
if(m_testSfx)
{
Mix_HaltChannel(0);
Mix_FreeChunk(m_testSfx);
m_testSfx = nullptr;
}
m_testSfx = Mix_LoadWAV(file.toUtf8().data());
if(!m_testSfx)
QMessageBox::warning(this, "SFX open error!", QString("Mix_LoadWAV: ") + Mix_GetError());
else
{
QFileInfo f(file);
m_testSfxDir = f.absoluteDir().absolutePath();
ui->sfx_file->setText(f.fileName());
}
}
void MusPlayer_Qt::on_sfx_play_clicked()
{
if(!m_testSfx)
return;
if(Mix_PlayChannelTimedVolume(0,
m_testSfx,
ui->sfx_loops->value(),
ui->sfx_timed->value(),
ui->sfx_volume->value()) == -1)
{
QMessageBox::warning(this, "SFX play error!", QString("Mix_PlayChannelTimedVolume: ") + Mix_GetError());
}
}
void MusPlayer_Qt::on_sfx_fadeIn_clicked()
{
if(!m_testSfx)
return;
if(Mix_FadeInChannelTimedVolume(0,
m_testSfx,
ui->sfx_loops->value(),
ui->sfx_fadems->value(),
ui->sfx_timed->value(),
ui->sfx_volume->value()) == -1)
{
QMessageBox::warning(this, "SFX play error!", QString("Mix_PlayChannelTimedVolume: ") + Mix_GetError());
}
}
void MusPlayer_Qt::on_sfx_stop_clicked()
{
if(!m_testSfx)
return;
Mix_HaltChannel(0);
}
void MusPlayer_Qt::on_sfx_fadeout_clicked()
{
if(!m_testSfx)
return;
Mix_FadeOutChannel(0, ui->sfx_fadems->value());
}
#endif
| Java |
namespace Freenex.FeexRanks.Database
{
public enum EQueryType
{
Scalar,
Reader,
NonQuery
}
} | Java |
/*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */
/**
* 1. Set default font family to sans-serif.
* 2. Prevent iOS and IE text size adjust after device orientation change,
* without disabling user zoom.
*/
html {
font-family: sans-serif; /* 1 */
height: 100%;
-ms-text-size-adjust: 100%; /* 2 */
-webkit-text-size-adjust: 100%; /* 2 */
width: 100%;
}
/**
* Remove default margin.
*/
body {
background-color: #e6e7e8;
height: 100%;
margin: 0;
width: 100%;
}
/* HTML5 display definitions
========================================================================== */
/**
* Correct `block` display not defined for any HTML5 element in IE 8/9.
* Correct `block` display not defined for `details` or `summary` in IE 10/11
* and Firefox.
* Correct `block` display not defined for `main` in IE 11.
*/
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
menu,
nav,
section,
summary {
display: block;
}
/**
* 1. Correct `inline-block` display not defined in IE 8/9.
* 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera.
*/
audio,
canvas,
progress,
video {
display: inline-block; /* 1 */
vertical-align: baseline; /* 2 */
}
/**
* Prevent modern browsers from displaying `audio` without controls.
* Remove excess height in iOS 5 devices.
*/
audio:not([controls]) {
display: none;
height: 0;
}
/**
* Address `[hidden]` styling not present in IE 8/9/10.
* Hide the `template` element in IE 8/9/10/11, Safari, and Firefox < 22.
*/
[hidden],
template {
display: none;
}
/* Links
========================================================================== */
/**
* Remove the gray background color from active links in IE 10.
*/
a {
background-color: transparent;
}
/**
* Improve readability of focused elements when they are also in an
* active/hover state.
*/
a:active,
a:hover {
outline: 0;
}
/* Text-level semantics
========================================================================== */
/**
* Address styling not present in IE 8/9/10/11, Safari, and Chrome.
*/
abbr[title] {
border-bottom: 1px dotted;
}
/**
* Address style set to `bolder` in Firefox 4+, Safari, and Chrome.
*/
b,
strong {
font-weight: bold;
}
/**
* Address styling not present in Safari and Chrome.
*/
dfn {
font-style: italic;
}
/**
* Address variable `h1` font-size and margin within `section` and `article`
* contexts in Firefox 4+, Safari, and Chrome.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/**
* Address styling not present in IE 8/9.
*/
mark {
background: #ff0;
color: #000;
}
/**
* Address inconsistent and variable font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` affecting `line-height` in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
/* Embedded content
========================================================================== */
/**
* Remove border when inside `a` element in IE 8/9/10.
*/
img {
border: 0;
}
/**
* Correct overflow not hidden in IE 9/10/11.
*/
svg:not(:root) {
overflow: hidden;
}
/* Grouping content
========================================================================== */
/**
* Address margin not present in IE 8/9 and Safari.
*/
figure {
margin: 1em 40px;
}
/**
* Address differences between Firefox and other browsers.
*/
hr {
box-sizing: content-box;
height: 0;
}
/**
* Contain overflow in all browsers.
*/
pre {
overflow: auto;
}
/**
* Address odd `em`-unit font size rendering in all browsers.
*/
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
/* Forms
========================================================================== */
/**
* Known limitation: by default, Chrome and Safari on OS X allow very limited
* styling of `select`, unless a `border` property is set.
*/
/**
* 1. Correct color not being inherited.
* Known issue: affects color of disabled elements.
* 2. Correct font properties not being inherited.
* 3. Address margins set differently in Firefox 4+, Safari, and Chrome.
*/
button,
input,
optgroup,
select,
textarea {
color: inherit; /* 1 */
font: inherit; /* 2 */
margin: 0; /* 3 */
}
/**
* Address `overflow` set to `hidden` in IE 8/9/10/11.
*/
button {
overflow: visible;
}
/**
* Address inconsistent `text-transform` inheritance for `button` and `select`.
* All other form control elements do not inherit `text-transform` values.
* Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera.
* Correct `select` style inheritance in Firefox.
*/
button,
select {
text-transform: none;
}
/**
* 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
* and `video` controls.
* 2. Correct inability to style clickable `input` types in iOS.
* 3. Improve usability and consistency of cursor style between image-type
* `input` and others.
*/
button,
html input[type="button"], /* 1 */
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button; /* 2 */
cursor: pointer; /* 3 */
}
/**
* Re-set default cursor for disabled elements.
*/
button[disabled],
html input[disabled] {
cursor: default;
}
/**
* Remove inner padding and border in Firefox 4+.
*/
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
/**
* Address Firefox 4+ setting `line-height` on `input` using `!important` in
* the UA stylesheet.
*/
input {
line-height: normal;
}
/**
* It's recommended that you don't attempt to style these elements.
* Firefox's implementation doesn't respect box-sizing, padding, or width.
*
* 1. Address box sizing set to `content-box` in IE 8/9/10.
* 2. Remove excess padding in IE 8/9/10.
*/
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
}
/**
* Fix the cursor style for Chrome's increment/decrement buttons. For certain
* `font-size` values of the `input`, it causes the cursor style of the
* decrement button to change from `default` to `text`.
*/
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Address `appearance` set to `searchfield` in Safari and Chrome.
* 2. Address `box-sizing` set to `border-box` in Safari and Chrome.
*/
input[type="search"] {
-webkit-appearance: textfield; /* 1 */
box-sizing: content-box; /* 2 */
}
/**
* Remove inner padding and search cancel button in Safari and Chrome on OS X.
* Safari (but not Chrome) clips the cancel button when the search input has
* padding (and `textfield` appearance).
*/
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* Define consistent border, margin, and padding.
*/
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
/**
* 1. Correct `color` not being inherited in IE 8/9/10/11.
* 2. Remove padding so people aren't caught out if they zero out fieldsets.
*/
legend {
border: 0; /* 1 */
padding: 0; /* 2 */
}
/**
* Remove default vertical scrollbar in IE 8/9/10/11.
*/
textarea {
overflow: auto;
}
/**
* Don't inherit the `font-weight` (applied by a rule above).
* NOTE: the default cannot safely be changed in Chrome and Safari on OS X.
*/
optgroup {
font-weight: bold;
}
/* Tables
========================================================================== */
/**
* Remove most spacing between table cells.
*/
table {
border-collapse: collapse;
border-spacing: 0;
}
td,
th {
padding: 0;
}
| Java |
import unittest
from itertools import izip
import numpy as np
from numpy import cos, sin, pi
from pele.angleaxis import RBTopology, RigidFragment, RBPotentialWrapper
from pele.potentials import LJ
from pele.angleaxis._otp_cluster import OTPCluster
from pele.thermodynamics import get_thermodynamic_information
from pele.utils import rotations
from pele.angleaxis._aa_utils import _rot_mat_derivative, _sitedist_grad, _sitedist
from pele.angleaxis.aamindist import MeasureRigidBodyCluster
_x03 = np.array([2.550757898788, 2.591553038507, 3.696836364193,
2.623281513163, 3.415794212648, 3.310786279789,
1.791383852327, 2.264321752809, 4.306217333671,
0.761945654023, -0.805817782109, 1.166981882601,
0.442065301864, -2.747066418223, -1.784325262714,
-1.520905562598, 0.403670860200, -0.729768985400])
_x03_atomistic = np.array([3.064051819556, 2.474533745459, 3.646107658946,
2.412011983074, 2.941152759499, 4.243695098053,
2.176209893734, 2.358972610563, 3.200706335581,
2.786627589565, 3.211876105193, 2.850924310983,
1.962626909252, 3.436918873216, 3.370903763850,
3.120590040673, 3.598587659535, 3.710530764535,
1.697360211099, 2.317229950712, 4.823998989452,
2.283487958310, 1.840698306602, 4.168734267290,
1.393303387573, 2.635037001113, 3.925918744272
])
class TestOTPExplicit(unittest.TestCase):
def make_otp(self):
"""this constructs a single OTP molecule"""
otp = RigidFragment()
otp.add_atom("O", np.array([0.0, -2./3 * np.sin( 7.*pi/24.), 0.0]), 1.)
otp.add_atom("O", np.array([cos( 7.*pi/24.), 1./3. * sin( 7.* pi/24.), 0.0]), 1.)
otp.add_atom("O", np.array([-cos( 7.* pi/24.), 1./3. * sin( 7.*pi/24), 0.0]), 1.)
otp.finalize_setup()
return otp
def setUp(self):
nrigid = 3
self.topology = RBTopology()
self.topology.add_sites([self.make_otp() for i in xrange(nrigid)])
self.topology.finalize_setup()
cartesian_potential = LJ()
self.pot = RBPotentialWrapper(self.topology, cartesian_potential)
self.x0 = _x03
self.x0 = np.array(self.x0)
self.e0 = -17.3387670023
assert nrigid * 6 == self.x0.size
self.x0atomistic = _x03_atomistic
self.nrigid = nrigid
def test_energy(self):
e = self.pot.getEnergy(self.x0)
self.assertAlmostEqual(e, self.e0, delta=1e-4)
def test_energy_gradient(self):
e = self.pot.getEnergy(self.x0)
gnum = self.pot.NumericalDerivative(self.x0)
e2, g = self.pot.getEnergyGradient(self.x0)
self.assertAlmostEqual(e, e2, delta=1e-4)
for i in xrange(g.size):
self.assertAlmostEqual(g[i], gnum[i], 2)
def test_to_atomistic(self):
xatom = self.topology.to_atomistic(self.x0).flatten()
for i in xrange(xatom.size):
self.assertAlmostEqual(xatom[i], self.x0atomistic[i], 2)
def test_site_to_atomistic(self):
rf = self.make_otp()
p = np.array([1., 2, 3])
p /= np.linalg.norm(p)
com = np.array([4., 5, 6])
print "otp to atomistic"
print rf.to_atomistic(com, p)
print "otp transform grad"
g = np.array(range(9), dtype=float).reshape([-1,3])
print g.reshape(-1)
print rf.transform_grad(p, g)
def test_to_atomistic2(self):
x0 = np.array(range(self.nrigid * 6), dtype=float)
x2 = x0.reshape([-1,3])
for p in x2[self.nrigid:,:]:
p /= np.linalg.norm(p)
atomistic = self.topology.to_atomistic(x0).flatten()
from pele.potentials import LJ
lj = LJ()
e, g = lj.getEnergyGradient(atomistic.reshape(-1))
grb = self.topology.transform_gradient(x0, g)
rbpot = RBPotentialWrapper(self.topology, lj)
print rbpot.getEnergy(x0)
class TestCppRBPotentialWrapper(TestOTPExplicit):
def test_pot_wrapper(self):
from pele.angleaxis import _cpp_aa
from pele.potentials import LJ
rbpot_cpp = _cpp_aa.RBPotentialWrapper(self.topology, LJ())
rbpot = RBPotentialWrapper(self.topology, LJ())
self.assertAlmostEqual(rbpot_cpp.getEnergy(self.x0),
rbpot.getEnergy(self.x0), 4)
e1, grad1 = rbpot_cpp.getEnergyGradient(self.x0)
e2, grad2 = rbpot.getEnergyGradient(self.x0)
self.assertAlmostEqual(e1, e2, 4)
for g1, g2 in zip(grad1, grad2):
self.assertAlmostEqual(g1, g2, 3)
# print "energy cpp"
# print e1, e2
# print grad1
# print grad2
_x1 = np.array([ 1.9025655 , 0.39575842, 2.70994994, 1.12711741, 0.63413933,
1.99433564, 1.86553644, 1.71434811, 2.22927686, 0.80189315,
1.19513512, 3.02357997, 1.25845172, -0.06244027, 1.27217385,
-2.26564485, 0.25537024, 0.66231258, -1.49510664, 0.94428774,
-0.04120075, -0.87664883, -0.21441754, 2.05796547])
_x2 = np.array([ 2.01932983, 0.32928065, 2.34949584, 1.12261277, 0.84195098,
2.08827517, 1.42644916, 1.83608794, 2.23147536, 1.12872074,
0.93206141, 3.28789605, 1.73243138, -0.1199651 , 1.02925229,
-1.64603729, 0.30701482, 0.90204992, -1.96259809, 0.06557119,
0.11010908, -0.37462588, -0.42374544, 1.97728056])
class TestOTPCluster(unittest.TestCase):
def setUp(self):
np.random.seed(0)
self.nmol = 4
self.system = OTPCluster(self.nmol)
pot = self.system.get_potential()
self.db = self.system.create_database()
self.m1 = self.db.addMinimum(pot.getEnergy(_x1), _x1)
self.m2 = self.db.addMinimum(pot.getEnergy(_x2), _x2)
def test1(self):
pot = self.system.get_potential()
self.assertLess(np.linalg.norm(pot.getGradient(self.m1.coords)), .1)
self.assertLess(np.linalg.norm(pot.getGradient(self.m2.coords)), .1)
def test_basinhopping(self):
db = self.system.create_database()
bh = self.system.get_basinhopping(db)
bh.setPrinting(ostream=None)
bh.run(5)
self.assertGreaterEqual(db.number_of_minima(), 1)
def test_double_ended_connect(self):
connect = self.system.get_double_ended_connect(self.m1, self.m2, self.db)
connect.connect()
self.assertTrue(connect.success())
path = connect.returnPath()
def test_thermodynamics(self):
get_thermodynamic_information(self.system, self.db, nproc=None, recalculate=True)
self.assertIsNotNone(self.m1.fvib)
mt = self.system.get_metric_tensor(self.m1.coords)
print "metric tensor"
print mt
class TestRBTopologyOTP(unittest.TestCase):
def setUp(self):
np.random.seed(0)
self.nmol = 3
self.system = OTPCluster(self.nmol)
# pot = self.system.get_potential()
# self.db = self.system.create_database()
# self.m1 = self.db.addMinimum(pot.getEnergy(_x1), _x1)
# self.m2 = self.db.addMinimum(pot.getEnergy(_x2), _x2)
self.x0 = np.array([ 0, 1, 2, 3, 4, 5, 6, 7, 8,
0.517892, 0.575435, 0.632979,
0.531891, 0.576215, 0.620539,
0.540562, 0.5766, 0.612637 ])
from pele.angleaxis.aamindist import TransformAngleAxisCluster
self.topology = self.system.aatopology
self.transform = TransformAngleAxisCluster(self.topology)
self.p0 = np.array(range(1,4), dtype=float)
self.p0 /= np.linalg.norm(self.p0)
def test_transform_rotate(self):
print "\ntest rotate"
x = self.x0.copy()
p = np.array(range(1,4), dtype=float)
p /= np.linalg.norm(p)
self.transform.rotate(x, rotations.aa2mx(p))
xnewtrue = np.array([ 0.48757698, 0.61588594, 2.09355038, 2.02484605, 4.76822812,
4.81289924, 3.56211511, 8.92057031, 7.53224809, 0.71469473,
1.23875927, 1.36136748, 0.72426504, 1.24674367, 1.34426835,
0.73015833, 1.25159032, 1.33345003])
for v1, v2 in izip(x, xnewtrue):
self.assertAlmostEqual(v1, v2, 5)
def test_align_path(self):
print "\ntest align_path"
x1 = self.x0.copy()
x2 = self.x0 + 5
self.topology.align_path([x1, x2])
x2true = np.array([ 5. , 6. , 7. , 8. ,
9. , 10. , 11. , 12. ,
13. , 1.92786071, 1.94796529, 1.96807021,
1.93320298, 1.94869267, 1.96418236, 1.93645608,
1.94905155, 1.96164668])
for v1, v2 in izip(x1, self.x0):
self.assertAlmostEqual(v1, v2, 5)
for v1, v2 in izip(x2, x2true):
self.assertAlmostEqual(v1, v2, 5)
def test_cpp_zero_ev(self):
print "\ntest zeroEV cpp"
x = self.x0.copy()
zev = self.topology._zeroEV_python(x)
czev = self.topology.cpp_topology.get_zero_modes(x)
self.assertEqual(len(czev), 6)
for ev, cev in izip(zev, czev):
for v1, v2 in izip(ev, cev):
self.assertAlmostEqual(v1, v2, 5)
def test_site_distance_squared(self):
print "\ntest site distance squared"
c0 = np.zeros(3)
c1 = np.ones(3)
p0 = self.p0.copy()
p1 = p0 + 1
site = self.system.make_otp()
d2 = site.distance_squared(c0, p0, c1, p1)
d2p = _sitedist(c1-c0, p0, p1, site.S, site.W, site.cog)
self.assertAlmostEqual(d2, 10.9548367929, 5)
def test_distance_squared(self):
print "\ntest distance squared"
x1 = self.x0.copy()
x2 = self.x0 + 1.1
d2 = self.topology.distance_squared(x1, x2)
d3 = self.topology._distance_squared_python(x1, x2)
self.assertAlmostEqual(d2, 38.9401810973, 5)
self.assertAlmostEqual(d2, d3, 5)
def test_distance_squared_grad(self):
print "\ntest distance squared grad"
x1 = self.x0.copy()
x2 = self.x0 + 1.1
grad = self.topology.distance_squared_grad(x1, x2)
g2 = self.topology._distance_squared_grad_python(x1, x2)
gtrue = np.array([-6.6 , -6.6 , -6.6 , -6.6 , -6.6 ,
-6.6 , -6.6 , -6.6 , -6.6 , -1.21579025,
-0.07013805, -1.2988823 , -1.21331786, -0.06984532, -1.28945301,
-1.2116105 , -0.06975828, -1.28362943])
for v1, v2 in izip(grad, gtrue):
self.assertAlmostEqual(v1, v2, 5)
for v1, v2 in izip(grad, g2):
self.assertAlmostEqual(v1, v2, 5)
def test_measure_align(self):
print "\ntest measure align"
x1 = self.x0.copy()
x2 = self.x0 + 5.1
x2[-1] = x1[-1] + .1
x20 = x2.copy()
measure = MeasureRigidBodyCluster(self.topology)
measure.align(x1, x2)
if __name__ == "__main__":
unittest.main()
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace guess_word_game
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new DAOForm());
}
}
}
| Java |
# We borrow heavily from the kernel build setup, though we are simpler since
# we don't have Kconfig tweaking settings on us.
# The implicit make rules have it looking for RCS files, among other things.
# We instead explicitly write all the rules we care about.
# It's even quicker (saves ~200ms) to pass -r on the command line.
MAKEFLAGS=-r
# The source directory tree.
srcdir := ..
abs_srcdir := $(abspath $(srcdir))
# The name of the builddir.
builddir_name ?= .
# The V=1 flag on command line makes us verbosely print command lines.
ifdef V
quiet=
else
quiet=quiet_
endif
# Specify BUILDTYPE=Release on the command line for a release build.
BUILDTYPE ?= Release
# Directory all our build output goes into.
# Note that this must be two directories beneath src/ for unit tests to pass,
# as they reach into the src/ directory for data with relative paths.
builddir ?= $(builddir_name)/$(BUILDTYPE)
abs_builddir := $(abspath $(builddir))
depsdir := $(builddir)/.deps
# Object output directory.
obj := $(builddir)/obj
abs_obj := $(abspath $(obj))
# We build up a list of every single one of the targets so we can slurp in the
# generated dependency rule Makefiles in one pass.
all_deps :=
# C++ apps need to be linked with g++.
#
# Note: flock is used to seralize linking. Linking is a memory-intensive
# process so running parallel links can often lead to thrashing. To disable
# the serialization, override LINK via an envrionment variable as follows:
#
# export LINK=g++
#
# This will allow make to invoke N linker processes as specified in -jN.
LINK ?= flock $(builddir)/linker.lock $(CXX)
CC.target ?= $(CC)
CFLAGS.target ?= $(CFLAGS)
CXX.target ?= $(CXX)
CXXFLAGS.target ?= $(CXXFLAGS)
LINK.target ?= $(LINK)
LDFLAGS.target ?= $(LDFLAGS)
AR.target ?= $(AR)
# TODO(evan): move all cross-compilation logic to gyp-time so we don't need
# to replicate this environment fallback in make as well.
CC.host ?= gcc
CFLAGS.host ?=
CXX.host ?= g++
CXXFLAGS.host ?=
LINK.host ?= g++
LDFLAGS.host ?=
AR.host ?= ar
# Define a dir function that can handle spaces.
# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
# "leading spaces cannot appear in the text of the first argument as written.
# These characters can be put into the argument value by variable substitution."
empty :=
space := $(empty) $(empty)
# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
replace_spaces = $(subst $(space),?,$1)
unreplace_spaces = $(subst ?,$(space),$1)
dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
# Flags to make gcc output dependency info. Note that you need to be
# careful here to use the flags that ccache and distcc can understand.
# We write to a dep file on the side first and then rename at the end
# so we can't end up with a broken dep file.
depfile = $(depsdir)/$(call replace_spaces,$@).d
DEPFLAGS = -MMD -MF $(depfile).raw
# We have to fixup the deps output in a few ways.
# (1) the file output should mention the proper .o file.
# ccache or distcc lose the path to the target, so we convert a rule of
# the form:
# foobar.o: DEP1 DEP2
# into
# path/to/foobar.o: DEP1 DEP2
# (2) we want missing files not to cause us to fail to build.
# We want to rewrite
# foobar.o: DEP1 DEP2 \
# DEP3
# to
# DEP1:
# DEP2:
# DEP3:
# so if the files are missing, they're just considered phony rules.
# We have to do some pretty insane escaping to get those backslashes
# and dollar signs past make, the shell, and sed at the same time.
# Doesn't work with spaces, but that's fine: .d files have spaces in
# their names replaced with other characters.
define fixup_dep
# The depfile may not exist if the input file didn't have any #includes.
touch $(depfile).raw
# Fixup path as in (1).
sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
# Add extra rules as in (2).
# We remove slashes and replace spaces with new lines;
# remove blank lines;
# delete the first line and append a colon to the remaining lines.
sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
grep -v '^$$' |\
sed -e 1d -e 's|$$|:|' \
>> $(depfile)
rm $(depfile).raw
endef
# Command definitions:
# - cmd_foo is the actual command to run;
# - quiet_cmd_foo is the brief-output summary of the command.
quiet_cmd_cc = CC($(TOOLSET)) $@
cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_cxx = CXX($(TOOLSET)) $@
cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_touch = TOUCH $@
cmd_touch = touch $@
quiet_cmd_copy = COPY $@
# send stderr to /dev/null to ignore messages when linking directories.
cmd_copy = rm -rf "$@" && cp -af "$<" "$@"
quiet_cmd_alink = AR($(TOOLSET)) $@
cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
quiet_cmd_alink_thin = AR($(TOOLSET)) $@
cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
# Due to circular dependencies between libraries :(, we wrap the
# special "figure out circular dependencies" flags around the entire
# input list during linking.
quiet_cmd_link = LINK($(TOOLSET)) $@
cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS)
# We support two kinds of shared objects (.so):
# 1) shared_library, which is just bundling together many dependent libraries
# into a link line.
# 2) loadable_module, which is generating a module intended for dlopen().
#
# They differ only slightly:
# In the former case, we want to package all dependent code into the .so.
# In the latter case, we want to package just the API exposed by the
# outermost module.
# This means shared_library uses --whole-archive, while loadable_module doesn't.
# (Note that --whole-archive is incompatible with the --start-group used in
# normal linking.)
# Other shared-object link notes:
# - Set SONAME to the library filename so our binaries don't reference
# the local, absolute paths used on the link command-line.
quiet_cmd_solink = SOLINK($(TOOLSET)) $@
cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS)
quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS)
# Define an escape_quotes function to escape single quotes.
# This allows us to handle quotes properly as long as we always use
# use single quotes and escape_quotes.
escape_quotes = $(subst ','\'',$(1))
# This comment is here just to include a ' to unconfuse syntax highlighting.
# Define an escape_vars function to escape '$' variable syntax.
# This allows us to read/write command lines with shell variables (e.g.
# $LD_LIBRARY_PATH), without triggering make substitution.
escape_vars = $(subst $$,$$$$,$(1))
# Helper that expands to a shell command to echo a string exactly as it is in
# make. This uses printf instead of echo because printf's behaviour with respect
# to escape sequences is more portable than echo's across different shells
# (e.g., dash, bash).
exact_echo = printf '%s\n' '$(call escape_quotes,$(1))'
# Helper to compare the command we're about to run against the command
# we logged the last time we ran the command. Produces an empty
# string (false) when the commands match.
# Tricky point: Make has no string-equality test function.
# The kernel uses the following, but it seems like it would have false
# positives, where one string reordered its arguments.
# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \
# $(filter-out $(cmd_$@), $(cmd_$(1))))
# We instead substitute each for the empty string into the other, and
# say they're equal if both substitutions produce the empty string.
# .d files contain ? instead of spaces, take that into account.
command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\
$(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
# Helper that is non-empty when a prerequisite changes.
# Normally make does this implicitly, but we force rules to always run
# so we can check their command lines.
# $? -- new prerequisites
# $| -- order-only dependencies
prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
# Helper that executes all postbuilds, and deletes the output file when done
# if any of the postbuilds failed.
define do_postbuilds
@E=0;\
for p in $(POSTBUILDS); do\
eval $$p;\
F=$$?;\
if [ $$F -ne 0 ]; then\
E=$$F;\
fi;\
done;\
if [ $$E -ne 0 ]; then\
rm -rf "$@";\
exit $$E;\
fi
endef
# do_cmd: run a command via the above cmd_foo names, if necessary.
# Should always run for a given target to handle command-line changes.
# Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
# Third argument, if non-zero, makes it do POSTBUILDS processing.
# Note: We intentionally do NOT call dirx for depfile, since it contains ? for
# spaces already and dirx strips the ? characters.
define do_cmd
$(if $(or $(command_changed),$(prereq_changed)),
@$(call exact_echo, $($(quiet)cmd_$(1)))
@mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
$(if $(findstring flock,$(word 1,$(cmd_$1))),
@$(cmd_$(1))
@echo " $(quiet_cmd_$(1)): Finished",
@$(cmd_$(1))
)
@$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
@$(if $(2),$(fixup_dep))
$(if $(and $(3), $(POSTBUILDS)),
$(call do_postbuilds)
)
)
endef
# Declare the "all" target first so it is the default,
# even though we don't have the deps yet.
.PHONY: all
all:
# make looks for ways to re-generate included makefiles, but in our case, we
# don't have a direct way. Explicitly telling make that it has nothing to do
# for them makes it go faster.
%.d: ;
# Use FORCE_DO_CMD to force a target to run. Should be coupled with
# do_cmd.
.PHONY: FORCE_DO_CMD
FORCE_DO_CMD:
TOOLSET := target
# Suffix rules, putting all outputs into $(obj).
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
# Try building from generated source, too.
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
$(findstring $(join ^,$(prefix)),\
$(join ^,bson.target.mk)))),)
include bson.target.mk
endif
quiet_cmd_regen_makefile = ACTION Regenerating $@
cmd_regen_makefile = /usr/lib/nodejs/npm/node_modules/node-gyp/gyp/gyp -fmake --ignore-environment "--toplevel-dir=." -I/home/madateam/RNC/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/config.gypi -I/usr/lib/nodejs/npm/node_modules/node-gyp/addon.gypi -I/home/madateam/.node-gyp/0.8.23/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/madateam/.node-gyp/0.8.23" "-Dmodule_root_dir=/home/madateam/RNC/node_modules/mongoose/node_modules/mongodb/node_modules/bson" binding.gyp
Makefile: $(srcdir)/../../../../../../../../../usr/lib/nodejs/npm/node_modules/node-gyp/addon.gypi $(srcdir)/../../../../../../../.node-gyp/0.8.23/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp
$(call do_cmd,regen_makefile)
# "all" is a concatenation of the "all" targets from all the included
# sub-makefiles. This is just here to clarify.
all:
# Add in dependency-tracking rules. $(all_deps) is the list of every single
# target in our tree. Only consider the ones with .d (dependency) info:
d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
ifneq ($(d_files),)
include $(d_files)
endif
| Java |
// Copyright 2020 Google LLC
//
// 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.
#ifndef HIGHWAY_HWY_TARGETS_H_
#define HIGHWAY_HWY_TARGETS_H_
#include <vector>
// For SIMD module implementations and their callers. Defines which targets to
// generate and call.
#include "hwy/base.h"
#include "hwy/detect_targets.h"
namespace hwy {
// Returns (cached) bitfield of enabled targets that are supported on this CPU.
// Implemented in targets.cc; unconditionally compiled to support the use case
// of binary-only distributions. The HWY_SUPPORTED_TARGETS wrapper may allow
// eliding calls to this function.
uint32_t SupportedTargets();
// Evaluates to a function call, or literal if there is a single target.
#if (HWY_TARGETS & (HWY_TARGETS - 1)) == 0
#define HWY_SUPPORTED_TARGETS HWY_TARGETS
#else
#define HWY_SUPPORTED_TARGETS hwy::SupportedTargets()
#endif
// Disable from runtime dispatch the mask of compiled in targets. Targets that
// were not enabled at compile time are ignored. This function is useful to
// disable a target supported by the CPU that is known to have bugs or when a
// lower target is desired. For this reason, attempts to disable targets which
// are in HWY_ENABLED_BASELINE have no effect so SupportedTargets() always
// returns at least the baseline target.
void DisableTargets(uint32_t disabled_targets);
// Set the mock mask of CPU supported targets instead of the actual CPU
// supported targets computed in SupportedTargets(). The return value of
// SupportedTargets() will still be affected by the DisableTargets() mask
// regardless of this mock, to prevent accidentally adding targets that are
// known to be buggy in the current CPU. Call with a mask of 0 to disable the
// mock and use the actual CPU supported targets instead.
void SetSupportedTargetsForTest(uint32_t targets);
// Returns whether the SupportedTargets() function was called since the last
// SetSupportedTargetsForTest() call.
bool SupportedTargetsCalledForTest();
// Return the list of targets in HWY_TARGETS supported by the CPU as a list of
// individual HWY_* target macros such as HWY_SCALAR or HWY_NEON. This list
// is affected by the current SetSupportedTargetsForTest() mock if any.
HWY_INLINE std::vector<uint32_t> SupportedAndGeneratedTargets() {
std::vector<uint32_t> ret;
for (uint32_t targets = SupportedTargets() & HWY_TARGETS; targets != 0;
targets = targets & (targets - 1)) {
uint32_t current_target = targets & ~(targets - 1);
ret.push_back(current_target);
}
return ret;
}
static inline HWY_MAYBE_UNUSED const char* TargetName(uint32_t target) {
switch (target) {
#if HWY_ARCH_X86
case HWY_SSSE3:
return "SSSE3";
case HWY_SSE4:
return "SSE4";
case HWY_AVX2:
return "AVX2";
case HWY_AVX3:
return "AVX3";
case HWY_AVX3_DL:
return "AVX3_DL";
#endif
#if HWY_ARCH_ARM
case HWY_SVE2:
return "SVE2";
case HWY_SVE:
return "SVE";
case HWY_NEON:
return "Neon";
#endif
#if HWY_ARCH_PPC
case HWY_PPC8:
return "Power8";
#endif
#if HWY_ARCH_WASM
case HWY_WASM:
return "Wasm";
#endif
#if HWY_ARCH_RVV
case HWY_RVV:
return "RVV";
#endif
case HWY_SCALAR:
return "Scalar";
default:
return "Unknown"; // must satisfy gtest IsValidParamName()
}
}
// The maximum number of dynamic targets on any architecture is defined by
// HWY_MAX_DYNAMIC_TARGETS and depends on the arch.
// For the ChosenTarget mask and index we use a different bit arrangement than
// in the HWY_TARGETS mask. Only the targets involved in the current
// architecture are used in this mask, and therefore only the least significant
// (HWY_MAX_DYNAMIC_TARGETS + 2) bits of the uint32_t mask are used. The least
// significant bit is set when the mask is not initialized, the next
// HWY_MAX_DYNAMIC_TARGETS more significant bits are a range of bits from the
// HWY_TARGETS or SupportedTargets() mask for the given architecture shifted to
// that position and the next more significant bit is used for the scalar
// target. Because of this we need to define equivalent values for HWY_TARGETS
// in this representation.
// This mask representation allows to use ctz() on this mask and obtain a small
// number that's used as an index of the table for dynamic dispatch. In this
// way the first entry is used when the mask is uninitialized, the following
// HWY_MAX_DYNAMIC_TARGETS are for dynamic dispatch and the last one is for
// scalar.
// The HWY_SCALAR bit in the ChosenTarget mask format.
#define HWY_CHOSEN_TARGET_MASK_SCALAR (1u << (HWY_MAX_DYNAMIC_TARGETS + 1))
// Converts from a HWY_TARGETS mask to a ChosenTarget mask format for the
// current architecture.
#define HWY_CHOSEN_TARGET_SHIFT(X) \
((((X) >> (HWY_HIGHEST_TARGET_BIT + 1 - HWY_MAX_DYNAMIC_TARGETS)) & \
((1u << HWY_MAX_DYNAMIC_TARGETS) - 1)) \
<< 1)
// The HWY_TARGETS mask in the ChosenTarget mask format.
#define HWY_CHOSEN_TARGET_MASK_TARGETS \
(HWY_CHOSEN_TARGET_SHIFT(HWY_TARGETS) | HWY_CHOSEN_TARGET_MASK_SCALAR | 1u)
#if HWY_ARCH_X86
// Maximum number of dynamic targets, changing this value is an ABI incompatible
// change
#define HWY_MAX_DYNAMIC_TARGETS 10
#define HWY_HIGHEST_TARGET_BIT HWY_HIGHEST_TARGET_BIT_X86
// These must match the order in which the HWY_TARGETS are defined
// starting by the least significant (HWY_HIGHEST_TARGET_BIT + 1 -
// HWY_MAX_DYNAMIC_TARGETS) bit. This list must contain exactly
// HWY_MAX_DYNAMIC_TARGETS elements and does not include SCALAR. The first entry
// corresponds to the best target. Don't include a "," at the end of the list.
#define HWY_CHOOSE_TARGET_LIST(func_name) \
nullptr, /* reserved */ \
nullptr, /* reserved */ \
HWY_CHOOSE_AVX3_DL(func_name), /* AVX3_DL */ \
HWY_CHOOSE_AVX3(func_name), /* AVX3 */ \
HWY_CHOOSE_AVX2(func_name), /* AVX2 */ \
nullptr, /* AVX */ \
HWY_CHOOSE_SSE4(func_name), /* SSE4 */ \
HWY_CHOOSE_SSSE3(func_name), /* SSSE3 */ \
nullptr, /* SSE3 */ \
nullptr /* SSE2 */
#elif HWY_ARCH_ARM
// See HWY_ARCH_X86 above for details.
#define HWY_MAX_DYNAMIC_TARGETS 4
#define HWY_HIGHEST_TARGET_BIT HWY_HIGHEST_TARGET_BIT_ARM
#define HWY_CHOOSE_TARGET_LIST(func_name) \
HWY_CHOOSE_SVE2(func_name), /* SVE2 */ \
HWY_CHOOSE_SVE(func_name), /* SVE */ \
nullptr, /* reserved */ \
HWY_CHOOSE_NEON(func_name) /* NEON */
#elif HWY_ARCH_PPC
// See HWY_ARCH_X86 above for details.
#define HWY_MAX_DYNAMIC_TARGETS 5
#define HWY_HIGHEST_TARGET_BIT HWY_HIGHEST_TARGET_BIT_PPC
#define HWY_CHOOSE_TARGET_LIST(func_name) \
nullptr, /* reserved */ \
nullptr, /* reserved */ \
HWY_CHOOSE_PPC8(func_name), /* PPC8 */ \
nullptr, /* VSX */ \
nullptr /* AltiVec */
#elif HWY_ARCH_WASM
// See HWY_ARCH_X86 above for details.
#define HWY_MAX_DYNAMIC_TARGETS 4
#define HWY_HIGHEST_TARGET_BIT HWY_HIGHEST_TARGET_BIT_WASM
#define HWY_CHOOSE_TARGET_LIST(func_name) \
nullptr, /* reserved */ \
nullptr, /* reserved */ \
HWY_CHOOSE_WASM2(func_name), /* WASM2 */ \
HWY_CHOOSE_WASM(func_name) /* WASM */
#elif HWY_ARCH_RVV
// See HWY_ARCH_X86 above for details.
#define HWY_MAX_DYNAMIC_TARGETS 4
#define HWY_HIGHEST_TARGET_BIT HWY_HIGHEST_TARGET_BIT_RVV
#define HWY_CHOOSE_TARGET_LIST(func_name) \
nullptr, /* reserved */ \
nullptr, /* reserved */ \
nullptr, /* reserved */ \
HWY_CHOOSE_RVV(func_name) /* RVV */
#else
// Unknown architecture, will use HWY_SCALAR without dynamic dispatch, though
// still creating single-entry tables in HWY_EXPORT to ensure portability.
#define HWY_MAX_DYNAMIC_TARGETS 1
#define HWY_HIGHEST_TARGET_BIT HWY_HIGHEST_TARGET_BIT_SCALAR
#endif
struct ChosenTarget {
public:
// Update the ChosenTarget mask based on the current CPU supported
// targets.
void Update();
// Reset the ChosenTarget to the uninitialized state.
void DeInit() { mask_.store(1); }
// Whether the ChosenTarget was initialized. This is useful to know whether
// any HWY_DYNAMIC_DISPATCH function was called.
bool IsInitialized() const { return mask_.load() != 1; }
// Return the index in the dynamic dispatch table to be used by the current
// CPU. Note that this method must be in the header file so it uses the value
// of HWY_CHOSEN_TARGET_MASK_TARGETS defined in the translation unit that
// calls it, which may be different from others. This allows to only consider
// those targets that were actually compiled in this module.
size_t HWY_INLINE GetIndex() const {
return hwy::Num0BitsBelowLS1Bit_Nonzero32(mask_.load() &
HWY_CHOSEN_TARGET_MASK_TARGETS);
}
private:
// Initialized to 1 so GetChosenTargetIndex() returns 0.
std::atomic<uint32_t> mask_{1};
};
extern ChosenTarget chosen_target;
} // namespace hwy
#endif // HIGHWAY_HWY_TARGETS_H_
| Java |
// tinygettext - A gettext replacement that works directly on .po files
// Copyright (C) 2006 Ingo Ruhnke <grumbel@gmx.de>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include <assert.h>
#include "log_stream.hpp"
#include "dictionary.hpp"
namespace tinygettext {
Dictionary::Dictionary(const std::string& charset_) :
entries(),
ctxt_entries(),
charset(charset_),
plural_forms()
{
m_has_fallback = false;
}
Dictionary::~Dictionary()
{
}
std::string
Dictionary::get_charset() const
{
return charset;
}
void
Dictionary::set_plural_forms(const PluralForms& plural_forms_)
{
plural_forms = plural_forms_;
}
PluralForms
Dictionary::get_plural_forms() const
{
return plural_forms;
}
std::string
Dictionary::translate_plural(const std::string& msgid, const std::string& msgid_plural, int num)
{
return translate_plural(entries, msgid, msgid_plural, num);
}
std::string
Dictionary::translate_plural(const Entries& dict, const std::string& msgid, const std::string& msgid_plural, int count)
{
Entries::const_iterator i = dict.find(msgid);
const std::vector<std::string>& msgstrs = i->second;
if (i != dict.end())
{
unsigned int n = 0;
n = plural_forms.get_plural(count);
assert(/*n >= 0 &&*/ n < msgstrs.size());
if (!msgstrs[n].empty())
return msgstrs[n];
else
if (count == 1) // default to english rules
return msgid;
else
return msgid_plural;
}
else
{
//log_info << "Couldn't translate: " << msgid << std::endl;
//log_info << "Candidates: " << std::endl;
//for (i = dict.begin(); i != dict.end(); ++i)
// log_info << "'" << i->first << "'" << std::endl;
if (count == 1) // default to english rules
return msgid;
else
return msgid_plural;
}
}
std::string
Dictionary::translate(const std::string& msgid)
{
return translate(entries, msgid);
}
std::string
Dictionary::translate(const Entries& dict, const std::string& msgid)
{
Entries::const_iterator i = dict.find(msgid);
if (i != dict.end() && !i->second.empty())
{
return i->second[0];
}
else
{
//log_info << "Couldn't translate: " << msgid << std::endl;
if (m_has_fallback) return m_fallback->translate(msgid);
else return msgid;
}
}
std::string
Dictionary::translate_ctxt(const std::string& msgctxt, const std::string& msgid)
{
CtxtEntries::iterator i = ctxt_entries.find(msgctxt);
if (i != ctxt_entries.end())
{
return translate(i->second, msgid);
}
else
{
//log_info << "Couldn't translate: " << msgid << std::endl;
return msgid;
}
}
std::string
Dictionary::translate_ctxt_plural(const std::string& msgctxt,
const std::string& msgid, const std::string& msgidplural, int num)
{
CtxtEntries::iterator i = ctxt_entries.find(msgctxt);
if (i != ctxt_entries.end())
{
return translate_plural(i->second, msgid, msgidplural, num);
}
else
{
//log_info << "Couldn't translate: " << msgid << std::endl;
if (num != 1) // default to english
return msgidplural;
else
return msgid;
}
}
void
Dictionary::add_translation(const std::string& msgid, const std::string& ,
const std::vector<std::string>& msgstrs)
{
// Do we need msgid2 for anything? its after all supplied to the
// translate call, so we just throw it away here
entries[msgid] = msgstrs;
}
void
Dictionary::add_translation(const std::string& msgid, const std::string& msgstr)
{
std::vector<std::string>& vec = entries[msgid];
if (vec.empty())
{
vec.push_back(msgstr);
}
else
{
log_warning << "collision in add_translation: '"
<< msgid << "' -> '" << msgstr << "' vs '" << vec[0] << "'" << std::endl;
vec[0] = msgstr;
}
}
void
Dictionary::add_translation(const std::string& msgctxt,
const std::string& msgid, const std::string& msgid_plural,
const std::vector<std::string>& msgstrs)
{
std::vector<std::string>& vec = ctxt_entries[msgctxt][msgid];
if (vec.empty())
{
vec = msgstrs;
}
else
{
log_warning << "collision in add_translation(\"" << msgctxt << "\", \"" << msgid << "\", \"" << msgid_plural << "\")" << std::endl;
vec = msgstrs;
}
}
void
Dictionary::add_translation(const std::string& msgctxt, const std::string& msgid, const std::string& msgstr)
{
std::vector<std::string>& vec = ctxt_entries[msgctxt][msgid];
if (vec.empty())
{
vec.push_back(msgstr);
}
else
{
log_warning << "collision in add_translation(\"" << msgctxt << "\", \"" << msgid << "\")" << std::endl;
vec[0] = msgstr;
}
}
} // namespace tinygettext
/* EOF */
| Java |
/* Copyright (C) 2014 CZ.NIC, z.s.p.o. <knot-dns@labs.nic.cz>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <tap/basic.h>
#include <string.h>
#include <stdlib.h>
#include "libknot/internal/mempattern.h"
#include "libknot/internal/mempool.h"
#include "libknot/errcode.h"
#include "knot/nameserver/query_module.h"
#include "libknot/packet/pkt.h"
/* Universal processing stage. */
int state_visit(int state, knot_pkt_t *pkt, struct query_data *qdata, void *ctx)
{
/* Visit current state */
bool *state_map = ctx;
state_map[state] = true;
return state + 1;
}
int main(int argc, char *argv[])
{
plan(4);
/* Create processing context. */
mm_ctx_t mm;
mm_ctx_mempool(&mm, MM_DEFAULT_BLKSIZE);
/* Create a map of expected steps. */
bool state_map[QUERY_PLAN_STAGES] = { false };
/* Prepare query plan. */
struct query_plan *plan = query_plan_create(&mm);
ok(plan != NULL, "query_plan: create");
/* Register all stage visits. */
int ret = KNOT_EOK;
for (unsigned stage = QPLAN_BEGIN; stage < QUERY_PLAN_STAGES; ++stage) {
ret = query_plan_step(plan, stage, state_visit, state_map);
if (ret != KNOT_EOK) {
break;
}
}
ok(ret == KNOT_EOK, "query_plan: planned all steps");
/* Execute the plan. */
int state = 0, next_state = 0;
for (unsigned stage = QPLAN_BEGIN; stage < QUERY_PLAN_STAGES; ++stage) {
struct query_step *step = NULL;
WALK_LIST(step, plan->stage[stage]) {
next_state = step->process(state, NULL, NULL, step->ctx);
if (next_state != state + 1) {
break;
}
state = next_state;
}
}
ok(state == QUERY_PLAN_STAGES, "query_plan: executed all steps");
/* Verify if all steps executed their callback. */
for (state = 0; state < QUERY_PLAN_STAGES; ++state) {
if (state_map[state] == false) {
break;
}
}
ok(state == QUERY_PLAN_STAGES, "query_plan: executed all callbacks");
/* Free the query plan. */
query_plan_free(plan);
/* Cleanup. */
mp_delete((struct mempool *)mm.ctx);
return 0;
}
| Java |
/*
* gtpm-mgr
*
* Version 1.00
* Copyright (C) 2012-2014 Nicolas Provost dev AT doronic DOT fr
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <gtk/gtk.h>
#include "llib_tpm.h"
#include "llib_opt.h"
#include "llib_print.h"
#include "llib_gtk.h"
#include "gtpm_mgr.h"
#include "gtpm_ui.h"
#include "gtpm_tpm.h"
#include "gtpm_uio.h"
static void gtpm_mgr_reset_vars(gtpm_config_t* gmgr)
{
llib_data_free(&gmgr->args.output);
llib_data_free(&gmgr->args.data);
llib_data_free(&gmgr->args.data2);
llib_data_free(&gmgr->args.encdata);
gmgr->args.set = 0;
llib_tpm_keystore_release_one_shot_key(gmgr->args.keystore);
}
/* run a command from the label of the clicked item */
void gtpm_mgr_run (gtpm_config_t* gmgr, const char* label)
{
lbool res;
const struct gtpm_menu_action_t* entry = >pm_tpm_menu_entries[0];
/* find the command from the label */
while (entry && entry->label && entry->job)
{
if (llib_str_equ(entry->label, label,0))
break;
entry++;
}
if (!entry || !entry->label || !entry->job)
{
gmgr->tpm.last_error = LLIB_TPM_ERROR_UNIMPLEMENTED;
llib_tpm_uio_error (&gmgr->args, "Unable to run command");
llib_print_f(2, "[gtpm-mgr] unknown command label '%s'\n", label);
return;
}
/* get descriptor */
gmgr->args.desc = llib_tpm_find_descriptor (entry->job);
if (!gmgr->args.desc)
{
gmgr->tpm.last_error = LLIB_TPM_ERROR_UNIMPLEMENTED;
llib_tpm_uio_error (&gmgr->args, "Unable to run command");
llib_print_f(2, "[gtpm-mgr] unknown descriptor '%s'\n",
gmgr->args.desc);
return;
}
/* set standard output if no other choice */
if ((gmgr->args.desc->in & LLIB_TPM_FOUTPUT) &&
!gmgr->args.cargs->output &&
!(gmgr->args.desc->sin & LLIB_TPM_FSOUTPUTNODEF))
{
gmgr->args.output = llib_data_create_text_buffer();
if (!gmgr->args.output)
{
llib_tpm_uio_printf (&gmgr->args, LLIB_TPM_UIO_ERR,
"unable to open standard output\n");
return;
}
gmgr->args.set |= LLIB_TPM_FOUTPUT;
}
/* run the command */
llib_gtku_set_cursor (GTK_WIDGET(gmgr->ui.gWindow), GDK_CIRCLE);
llib_gtku_process_signals ();
if (llib_tpm_run (&gmgr->tpm, entry->job, &gmgr->args, &res) && res)
{
llib_gtku_set_cursor (GTK_WIDGET(gmgr->ui.gWindow), GDK_ARROW);
llib_tpm_keystore_add_one_shot_key (gmgr->args.keystore);
if (gmgr->args.output &&
(gmgr->args.output->type == LLIB_DATA_TYPE_BUFFER) &&
(llib_buffer_type(&gmgr->args.output->data.buffer)
== LLIB_BUFFER_TEXT))
{
gtpmuio_output_text (&gmgr->args, "command result",
&gmgr->args.output->data.buffer);
}
}
else
{
llib_gtku_set_cursor (GTK_WIDGET(gmgr->ui.gWindow), GDK_ARROW);
llib_tpm_uio_error (&gmgr->args, "Unable to run command");
}
gtpm_mgr_reset_vars(gmgr);
llib_gtku_set_cursor(GTK_WIDGET(gmgr->ui.gWindow), GDK_ARROW);
}
static void gtpm_mgr_clean(gtpm_config_t* gmgr) {
llib_tpm_free(&gmgr->tpm);
llib_tpm_store_free(gmgr->args.store);
llib_tpm_keystore_free(gmgr->args.keystore);
llib_tpm_uio_free(&gmgr->uio);
}
int main(int argc, char* argv[])
{
gtpm_config_t gmgr;
int retcode = EXIT_FAILURE;
char c;
char* arg = NULL;
char* devpath = NULL;
llib_mem_zero(&gmgr, sizeof(gtpm_config_t));
gmgr.args.cargs = &gmgr.cargs;
gmgr.args.store = gmgr.cargs.store = &gmgr.cargs.st.store;
llib_tpm_key_init(&gmgr.cargs.st.store_key);
llib_tpm_store_init(gmgr.args.store, &gmgr.tpm, NULL);
gmgr.cargs.st.store.key = &gmgr.cargs.st.store_key;
gmgr.args.uio = &gmgr.uio;
gmgr.cargs.st.ui = &gmgr.ui;
gmgr.args.tpm = &gmgr.tpm;
gmgr.args.keystore = &gmgr.cargs.st.keystore;
gmgr.args.o = gmgr.cargs.o = &gmgr.cargs.st.o;
llib_tpm_store_object_init(gmgr.args.o, NULL, NULL);
gtpmuio_init(&gmgr.uio, &gmgr.args);
llib_tpm_keystore_init(gmgr.args.keystore);
llib_print_f(1, "gtpm-mgr v" VERSION "\n");
llib_print_f(1, "usage: [-dtpm|store|all (debug)] [-v (verbose)] "
"[-tTPM_DEV_PATH (default is /dev/tpm0)]\n");
while ((c = llib_opt_get_short(argc, argv, "vd::t::", &arg)) != -1)
{
switch (c)
{
case 'v':
gmgr.args.verbose = TRUE;
break;
case 'd':
if (llib_str_equ(arg, "all", 0) ||
llib_str_equ(arg, "store", 0))
{
gmgr.args.debug = TRUE;
gmgr.args.store->debug = TRUE;
}
if (llib_str_equ(arg, "all", 0) ||
llib_str_equ(arg, "tpm",0))
gmgr.tpm.debug = TRUE;
break;
case 't':
if (!arg)
{
llib_print_f(2, "[gtpm-mgr] FATAL: missing TPM device path\n");
return EXIT_FAILURE;
}
devpath = llib_str_dup(arg);
llib_print_f(2, "[gtpm-mgr] using TPM at %s\n", arg);
break;
}
llib_str_release(&arg);
}
gtk_init(&argc, &argv);
if (!gtpm_ui_build(&gmgr))
{
llib_print_f(2, "[gtpm-mgr] FATAL: unable to build graphical "
"interface, aborting\n");
}
else
{
if (!llib_tpm_init(&gmgr.tpm, devpath, 30, gmgr.tpm.debug))
llib_tpm_uio_error(&gmgr.args, "TPM initialization error");
else
{
gtk_widget_show_all(GTK_WIDGET(gmgr.ui.gWindow));
gtk_main();
retcode = EXIT_SUCCESS;
}
}
llib_mem_free(devpath);
gtpm_mgr_clean(&gmgr);
return retcode;
}
| Java |
/*
Copyright 2011 Anton Kraievoy akraievoy@gmail.com
This file is part of Holonet.
Holonet is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Holonet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Holonet. If not, see <http://www.gnu.org/licenses/>.
*/
package algores.holonet.core.events;
import algores.holonet.core.CommunicationException;
import algores.holonet.core.Network;
import algores.holonet.core.Node;
import algores.holonet.core.RequestPair;
import algores.holonet.core.api.Address;
import algores.holonet.core.api.Key;
import algores.holonet.core.api.tier1.delivery.LookupService;
import com.google.common.base.Optional;
import org.akraievoy.cnet.gen.vo.EntropySource;
import java.util.Collection;
/**
* Lookup entry event.
*/
public class EventNetLookup extends Event<EventNetLookup> {
protected int retries = 1;
public Result executeInternal(final Network network, final EntropySource eSource) {
Result aggregateResult = Result.PASSIVE;
for (int sequentialIndex = 0; sequentialIndex < retries; sequentialIndex++) {
Optional<RequestPair> optRequest =
network.generateRequestPair(eSource);
if (!optRequest.isPresent()) {
if (sequentialIndex > 0) {
throw new IllegalStateException(
"request model became empty amid request generation streak?"
);
}
break;
}
RequestPair request = optRequest.get();
Collection<Key> serverKeys =
request.server.getServices().getStorage().getKeys();
final Key mapping =
serverKeys.isEmpty() ?
// we may also pull other keys from the range, not only the greatest one
request.server.getServices().getRouting().ownRoute().getRange().getRKey().prev() :
eSource.randomElement(serverKeys);
final LookupService lookupSvc =
request.client.getServices().getLookup();
final Address address;
try {
address = lookupSvc.lookup(
mapping.getKey(), true, LookupService.Mode.GET,
Optional.of(request.server.getAddress())
);
} catch (CommunicationException e) {
if (!aggregateResult.equals(Result.FAILURE)) {
aggregateResult = handleEventFailure(e, null);
}
continue;
}
final Node lookupResult = network.getEnv().getNode(address);
if (
!lookupResult.equals(request.server)
) {
network.getInterceptor().reportInconsistentLookup(LookupService.Mode.GET);
}
aggregateResult = Result.SUCCESS;
}
return aggregateResult;
}
public void setRetries(int retryCount) {
this.retries = retryCount;
}
public EventNetLookup withRetries(int retryCount) {
setRetries(retryCount);
return this;
}
}
| Java |
var path = require('path');
var Q = require('q');
var fs = require('fs');
var mv = require('mv');
var Upload = require('./upload.model');
exports.upload = function (req, res) {
var tmpPath = req.files[0].path;
var newFileName = Math.random().toString(36).substring(7)+path.extname(tmpPath);
var targetPath = path.resolve(process.env.UPLOAD_PATH, newFileName);
var defer = Q.defer();
mv(tmpPath, targetPath, function (err) {
if (err) {
return nextIteration.reject(err);
}
targetPath = targetPath.substring(targetPath.indexOf('upload'));
Upload.createUpload(targetPath).then(function(upload) {
defer.resolve(upload);
}, function(err) {
defer.reject(err);
});
});
defer.promise.then(function (upload) {
res.json({
status: true,
data: upload._id
});
}, function(err) {
console.log(err);
res.json({
status: false,
reason: err.toString()
});
});
}; | Java |
/* LIBGIMP - The GIMP Library
* Copyright (C) 1995-2003 Peter Mattis and Spencer Kimball
*
* gimplayer_pdb.c
*
* This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* <http://www.gnu.org/licenses/>.
*/
/* NOTE: This file is auto-generated by pdbgen.pl */
#include "config.h"
#include "gimp.h"
/**
* SECTION: gimplayer
* @title: gimplayer
* @short_description: Operations on a single layer.
*
* Operations on a single layer.
**/
/**
* _gimp_layer_new:
* @image_ID: The image to which to add the layer.
* @width: The layer width.
* @height: The layer height.
* @type: The layer type.
* @name: The layer name.
* @opacity: The layer opacity.
* @mode: The layer combination mode.
*
* Create a new layer.
*
* This procedure creates a new layer with the specified width, height,
* and type. Name, opacity, and mode are also supplied parameters. The
* new layer still needs to be added to the image, as this is not
* automatic. Add the new layer with the gimp_image_insert_layer()
* command. Other attributes such as layer mask modes, and offsets
* should be set with explicit procedure calls.
*
* Returns: The newly created layer.
**/
gint32
_gimp_layer_new (gint32 image_ID,
gint width,
gint height,
GimpImageType type,
const gchar *name,
gdouble opacity,
GimpLayerModeEffects mode)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 layer_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-new",
&nreturn_vals,
GIMP_PDB_IMAGE, image_ID,
GIMP_PDB_INT32, width,
GIMP_PDB_INT32, height,
GIMP_PDB_INT32, type,
GIMP_PDB_STRING, name,
GIMP_PDB_FLOAT, opacity,
GIMP_PDB_INT32, mode,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
layer_ID = return_vals[1].data.d_layer;
gimp_destroy_params (return_vals, nreturn_vals);
return layer_ID;
}
/**
* gimp_layer_new_from_visible:
* @image_ID: The source image from where the content is copied.
* @dest_image_ID: The destination image to which to add the layer.
* @name: The layer name.
*
* Create a new layer from what is visible in an image.
*
* This procedure creates a new layer from what is visible in the given
* image. The new layer still needs to be added to the destination
* image, as this is not automatic. Add the new layer with the
* gimp_image_insert_layer() command. Other attributes such as layer
* mask modes, and offsets should be set with explicit procedure calls.
*
* Returns: The newly created layer.
*
* Since: GIMP 2.6
**/
gint32
gimp_layer_new_from_visible (gint32 image_ID,
gint32 dest_image_ID,
const gchar *name)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 layer_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-new-from-visible",
&nreturn_vals,
GIMP_PDB_IMAGE, image_ID,
GIMP_PDB_IMAGE, dest_image_ID,
GIMP_PDB_STRING, name,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
layer_ID = return_vals[1].data.d_layer;
gimp_destroy_params (return_vals, nreturn_vals);
return layer_ID;
}
/**
* gimp_layer_new_from_drawable:
* @drawable_ID: The source drawable from where the new layer is copied.
* @dest_image_ID: The destination image to which to add the layer.
*
* Create a new layer by copying an existing drawable.
*
* This procedure creates a new layer as a copy of the specified
* drawable. The new layer still needs to be added to the image, as
* this is not automatic. Add the new layer with the
* gimp_image_insert_layer() command. Other attributes such as layer
* mask modes, and offsets should be set with explicit procedure calls.
*
* Returns: The newly copied layer.
**/
gint32
gimp_layer_new_from_drawable (gint32 drawable_ID,
gint32 dest_image_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 layer_copy_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-new-from-drawable",
&nreturn_vals,
GIMP_PDB_DRAWABLE, drawable_ID,
GIMP_PDB_IMAGE, dest_image_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
layer_copy_ID = return_vals[1].data.d_layer;
gimp_destroy_params (return_vals, nreturn_vals);
return layer_copy_ID;
}
/**
* gimp_layer_group_new:
* @image_ID: The image to which to add the layer group.
*
* Create a new layer group.
*
* This procedure creates a new layer group. Attributes such as layer
* mode and opacity should be set with explicit procedure calls. Add
* the new layer group (which is a kind of layer) with the
* gimp_image_insert_layer() command.
*
* Returns: The newly created layer group.
*
* Since: GIMP 2.8
**/
gint32
gimp_layer_group_new (gint32 image_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 layer_group_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-group-new",
&nreturn_vals,
GIMP_PDB_IMAGE, image_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
layer_group_ID = return_vals[1].data.d_layer;
gimp_destroy_params (return_vals, nreturn_vals);
return layer_group_ID;
}
/**
* _gimp_layer_copy:
* @layer_ID: The layer to copy.
* @add_alpha: Add an alpha channel to the copied layer.
*
* Copy a layer.
*
* This procedure copies the specified layer and returns the copy. The
* newly copied layer is for use within the original layer's image. It
* should not be subsequently added to any other image. The copied
* layer can optionally have an added alpha channel. This is useful if
* the background layer in an image is being copied and added to the
* same image.
*
* Returns: The newly copied layer.
**/
gint32
_gimp_layer_copy (gint32 layer_ID,
gboolean add_alpha)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 layer_copy_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-copy",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, add_alpha,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
layer_copy_ID = return_vals[1].data.d_layer;
gimp_destroy_params (return_vals, nreturn_vals);
return layer_copy_ID;
}
/**
* gimp_layer_add_alpha:
* @layer_ID: The layer.
*
* Add an alpha channel to the layer if it doesn't already have one.
*
* This procedure adds an additional component to the specified layer
* if it does not already possess an alpha channel. An alpha channel
* makes it possible to clear and erase to transparency, instead of the
* background color. This transforms layers of type RGB to RGBA, GRAY
* to GRAYA, and INDEXED to INDEXEDA.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_add_alpha (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-add-alpha",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_flatten:
* @layer_ID: The layer.
*
* Remove the alpha channel from the layer if it has one.
*
* This procedure removes the alpha channel from a layer, blending all
* (partially) transparent pixels in the layer against the background
* color. This transforms layers of type RGBA to RGB, GRAYA to GRAY,
* and INDEXEDA to INDEXED.
*
* Returns: TRUE on success.
*
* Since: GIMP 2.4
**/
gboolean
gimp_layer_flatten (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-flatten",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_scale:
* @layer_ID: The layer.
* @new_width: New layer width.
* @new_height: New layer height.
* @local_origin: Use a local origin (as opposed to the image origin).
*
* Scale the layer using the default interpolation method.
*
* This procedure scales the layer so that its new width and height are
* equal to the supplied parameters. The 'local-origin' parameter
* specifies whether to scale from the center of the layer, or from the
* image origin. This operation only works if the layer has been added
* to an image. The interpolation method used can be set with
* gimp_context_set_interpolation().
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_scale (gint32 layer_ID,
gint new_width,
gint new_height,
gboolean local_origin)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-scale",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, new_width,
GIMP_PDB_INT32, new_height,
GIMP_PDB_INT32, local_origin,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_scale_full:
* @layer_ID: The layer.
* @new_width: New layer width.
* @new_height: New layer height.
* @local_origin: Use a local origin (as opposed to the image origin).
* @interpolation: Type of interpolation.
*
* Deprecated: Use gimp_layer_scale() instead.
*
* Returns: TRUE on success.
*
* Since: GIMP 2.6
**/
gboolean
gimp_layer_scale_full (gint32 layer_ID,
gint new_width,
gint new_height,
gboolean local_origin,
GimpInterpolationType interpolation)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-scale-full",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, new_width,
GIMP_PDB_INT32, new_height,
GIMP_PDB_INT32, local_origin,
GIMP_PDB_INT32, interpolation,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_resize:
* @layer_ID: The layer.
* @new_width: New layer width.
* @new_height: New layer height.
* @offx: x offset between upper left corner of old and new layers: (old - new).
* @offy: y offset between upper left corner of old and new layers: (old - new).
*
* Resize the layer to the specified extents.
*
* This procedure resizes the layer so that its new width and height
* are equal to the supplied parameters. Offsets are also provided
* which describe the position of the previous layer's content. This
* operation only works if the layer has been added to an image.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_resize (gint32 layer_ID,
gint new_width,
gint new_height,
gint offx,
gint offy)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-resize",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, new_width,
GIMP_PDB_INT32, new_height,
GIMP_PDB_INT32, offx,
GIMP_PDB_INT32, offy,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_resize_to_image_size:
* @layer_ID: The layer to resize.
*
* Resize a layer to the image size.
*
* This procedure resizes the layer so that it's new width and height
* are equal to the width and height of its image container.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_resize_to_image_size (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-resize-to-image-size",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_translate:
* @layer_ID: The layer.
* @offx: Offset in x direction.
* @offy: Offset in y direction.
*
* Translate the layer by the specified offsets.
*
* This procedure translates the layer by the amounts specified in the
* x and y arguments. These can be negative, and are considered offsets
* from the current position. This command only works if the layer has
* been added to an image. All additional layers contained in the image
* which have the linked flag set to TRUE w ill also be translated by
* the specified offsets.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_translate (gint32 layer_ID,
gint offx,
gint offy)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-translate",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, offx,
GIMP_PDB_INT32, offy,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_set_offsets:
* @layer_ID: The layer.
* @offx: Offset in x direction.
* @offy: Offset in y direction.
*
* Set the layer offsets.
*
* This procedure sets the offsets for the specified layer. The offsets
* are relative to the image origin and can be any values. This
* operation is valid only on layers which have been added to an image.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_offsets (gint32 layer_ID,
gint offx,
gint offy)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-offsets",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, offx,
GIMP_PDB_INT32, offy,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_create_mask:
* @layer_ID: The layer to which to add the mask.
* @mask_type: The type of mask.
*
* Create a layer mask for the specified layer.
*
* This procedure creates a layer mask for the specified layer. Layer
* masks serve as an additional alpha channel for a layer. A number of
* different types of masks are allowed for initialisation: completely
* white masks (which will leave the layer fully visible), completely
* black masks (which will give the layer complete transparency, the
* layer's already existing alpha channel (which will leave the layer
* fully visible, but which may be more useful than a white mask), the
* current selection or a grayscale copy of the layer. The layer mask
* still needs to be added to the layer. This can be done with a call
* to gimp_layer_add_mask().
*
* Returns: The newly created mask.
**/
gint32
gimp_layer_create_mask (gint32 layer_ID,
GimpAddMaskType mask_type)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 mask_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-create-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, mask_type,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
mask_ID = return_vals[1].data.d_layer_mask;
gimp_destroy_params (return_vals, nreturn_vals);
return mask_ID;
}
/**
* gimp_layer_get_mask:
* @layer_ID: The layer.
*
* Get the specified layer's mask if it exists.
*
* This procedure returns the specified layer's mask, or -1 if none
* exists.
*
* Returns: The layer mask.
**/
gint32
gimp_layer_get_mask (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 mask_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-get-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
mask_ID = return_vals[1].data.d_layer_mask;
gimp_destroy_params (return_vals, nreturn_vals);
return mask_ID;
}
/**
* gimp_layer_from_mask:
* @mask_ID: Mask for which to return the layer.
*
* Get the specified mask's layer.
*
* This procedure returns the specified mask's layer , or -1 if none
* exists.
*
* Returns: The mask's layer.
*
* Since: GIMP 2.2
**/
gint32
gimp_layer_from_mask (gint32 mask_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 layer_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-from-mask",
&nreturn_vals,
GIMP_PDB_CHANNEL, mask_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
layer_ID = return_vals[1].data.d_layer;
gimp_destroy_params (return_vals, nreturn_vals);
return layer_ID;
}
/**
* gimp_layer_add_mask:
* @layer_ID: The layer to receive the mask.
* @mask_ID: The mask to add to the layer.
*
* Add a layer mask to the specified layer.
*
* This procedure adds a layer mask to the specified layer. Layer masks
* serve as an additional alpha channel for a layer. This procedure
* will fail if a number of prerequisites aren't met. The layer cannot
* already have a layer mask. The specified mask must exist and have
* the same dimensions as the layer. The layer must have been created
* for use with the specified image and the mask must have been created
* with the procedure 'gimp-layer-create-mask'.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_add_mask (gint32 layer_ID,
gint32 mask_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-add-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_CHANNEL, mask_ID,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_remove_mask:
* @layer_ID: The layer from which to remove mask.
* @mode: Removal mode.
*
* Remove the specified layer mask from the layer.
*
* This procedure removes the specified layer mask from the layer. If
* the mask doesn't exist, an error is returned.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_remove_mask (gint32 layer_ID,
GimpMaskApplyMode mode)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-remove-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, mode,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_is_floating_sel:
* @layer_ID: The layer.
*
* Is the specified layer a floating selection?
*
* This procedure returns whether the layer is a floating selection.
* Floating selections are special cases of layers which are attached
* to a specific drawable.
*
* Returns: TRUE if the layer is a floating selection.
**/
gboolean
gimp_layer_is_floating_sel (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean is_floating_sel = FALSE;
return_vals = gimp_run_procedure ("gimp-layer-is-floating-sel",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
is_floating_sel = return_vals[1].data.d_int32;
gimp_destroy_params (return_vals, nreturn_vals);
return is_floating_sel;
}
/**
* gimp_layer_get_lock_alpha:
* @layer_ID: The layer.
*
* Get the lock alpha channel setting of the specified layer.
*
* This procedure returns the specified layer's lock alpha channel
* setting.
*
* Returns: The layer's lock alpha channel setting.
**/
gboolean
gimp_layer_get_lock_alpha (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean lock_alpha = FALSE;
return_vals = gimp_run_procedure ("gimp-layer-get-lock-alpha",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
lock_alpha = return_vals[1].data.d_int32;
gimp_destroy_params (return_vals, nreturn_vals);
return lock_alpha;
}
/**
* gimp_layer_set_lock_alpha:
* @layer_ID: The layer.
* @lock_alpha: The new layer's lock alpha channel setting.
*
* Set the lock alpha channel setting of the specified layer.
*
* This procedure sets the specified layer's lock alpha channel
* setting.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_lock_alpha (gint32 layer_ID,
gboolean lock_alpha)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-lock-alpha",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, lock_alpha,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_get_apply_mask:
* @layer_ID: The layer.
*
* Get the apply mask setting of the specified layer.
*
* This procedure returns the specified layer's apply mask setting. If
* the value is TRUE, then the layer mask for this layer is currently
* being composited with the layer's alpha channel.
*
* Returns: The layer's apply mask setting.
**/
gboolean
gimp_layer_get_apply_mask (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean apply_mask = FALSE;
return_vals = gimp_run_procedure ("gimp-layer-get-apply-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
apply_mask = return_vals[1].data.d_int32;
gimp_destroy_params (return_vals, nreturn_vals);
return apply_mask;
}
/**
* gimp_layer_set_apply_mask:
* @layer_ID: The layer.
* @apply_mask: The new layer's apply mask setting.
*
* Set the apply mask setting of the specified layer.
*
* This procedure sets the specified layer's apply mask setting. This
* controls whether the layer's mask is currently affecting the alpha
* channel. If there is no layer mask, this function will return an
* error.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_apply_mask (gint32 layer_ID,
gboolean apply_mask)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-apply-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, apply_mask,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_get_show_mask:
* @layer_ID: The layer.
*
* Get the show mask setting of the specified layer.
*
* This procedure returns the specified layer's show mask setting. This
* controls whether the layer or its mask is visible. TRUE indicates
* that the mask should be visible. If the layer has no mask, then this
* function returns an error.
*
* Returns: The layer's show mask setting.
**/
gboolean
gimp_layer_get_show_mask (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean show_mask = FALSE;
return_vals = gimp_run_procedure ("gimp-layer-get-show-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
show_mask = return_vals[1].data.d_int32;
gimp_destroy_params (return_vals, nreturn_vals);
return show_mask;
}
/**
* gimp_layer_set_show_mask:
* @layer_ID: The layer.
* @show_mask: The new layer's show mask setting.
*
* Set the show mask setting of the specified layer.
*
* This procedure sets the specified layer's show mask setting. This
* controls whether the layer or its mask is visible. TRUE indicates
* that the mask should be visible. If there is no layer mask, this
* function will return an error.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_show_mask (gint32 layer_ID,
gboolean show_mask)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-show-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, show_mask,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_get_edit_mask:
* @layer_ID: The layer.
*
* Get the edit mask setting of the specified layer.
*
* This procedure returns the specified layer's edit mask setting. If
* the value is TRUE, then the layer mask for this layer is currently
* active, and not the layer.
*
* Returns: The layer's edit mask setting.
**/
gboolean
gimp_layer_get_edit_mask (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean edit_mask = FALSE;
return_vals = gimp_run_procedure ("gimp-layer-get-edit-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
edit_mask = return_vals[1].data.d_int32;
gimp_destroy_params (return_vals, nreturn_vals);
return edit_mask;
}
/**
* gimp_layer_set_edit_mask:
* @layer_ID: The layer.
* @edit_mask: The new layer's edit mask setting.
*
* Set the edit mask setting of the specified layer.
*
* This procedure sets the specified layer's edit mask setting. This
* controls whether the layer or it's mask is currently active for
* editing. If the specified layer has no layer mask, then this
* procedure will return an error.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_edit_mask (gint32 layer_ID,
gboolean edit_mask)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-edit-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, edit_mask,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_get_opacity:
* @layer_ID: The layer.
*
* Get the opacity of the specified layer.
*
* This procedure returns the specified layer's opacity.
*
* Returns: The layer opacity.
**/
gdouble
gimp_layer_get_opacity (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gdouble opacity = 0.0;
return_vals = gimp_run_procedure ("gimp-layer-get-opacity",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
opacity = return_vals[1].data.d_float;
gimp_destroy_params (return_vals, nreturn_vals);
return opacity;
}
/**
* gimp_layer_set_opacity:
* @layer_ID: The layer.
* @opacity: The new layer opacity.
*
* Set the opacity of the specified layer.
*
* This procedure sets the specified layer's opacity.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_opacity (gint32 layer_ID,
gdouble opacity)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-opacity",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_FLOAT, opacity,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_get_mode:
* @layer_ID: The layer.
*
* Get the combination mode of the specified layer.
*
* This procedure returns the specified layer's combination mode.
*
* Returns: The layer combination mode.
**/
GimpLayerModeEffects
gimp_layer_get_mode (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
GimpLayerModeEffects mode = 0;
return_vals = gimp_run_procedure ("gimp-layer-get-mode",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
mode = return_vals[1].data.d_int32;
gimp_destroy_params (return_vals, nreturn_vals);
return mode;
}
/**
* gimp_layer_set_mode:
* @layer_ID: The layer.
* @mode: The new layer combination mode.
*
* Set the combination mode of the specified layer.
*
* This procedure sets the specified layer's combination mode.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_mode (gint32 layer_ID,
GimpLayerModeEffects mode)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-mode",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, mode,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
| Java |
// Karma configuration
// Generated on Thu Jul 24 2014 18:11:41 GMT-0700 (PDT)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'src/*.js',
'test/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: [],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
| Java |
package br.ifrn.meutcc.visao;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.ifrn.meutcc.modelo.Aluno;
import br.ifrn.meutcc.modelo.Orientador;
@WebServlet("/ViewAlunoCandidatou")
public class ViewAlunoCandidatou extends HttpServlet {
private static final long serialVersionUID = 1L;
public ViewAlunoCandidatou() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
int idCandidato = 2;
int idTema = -1;
try {
idTema = Integer.parseInt(id);
} catch (NumberFormatException nfex) {
nfex.printStackTrace();
}
Orientador a = new Orientador();
Orientador orientador = a.getOrientadorPorTema(idTema);
Aluno logic = new Aluno();
logic.registraObserver(orientador);
boolean aluno = logic.addCandidato(idTema, idCandidato);
request.setAttribute("candidatou", logic.getStatus());
request.setAttribute("aluno", aluno);
request.getRequestDispatcher("viewAluno.jsp").forward(request, response);
}
}
| Java |
/* Template filled out by CMake */
/*
* *** THIS HEADER IS INCLUDED BY PdfCompilerCompat.h ***
* *** DO NOT INCLUDE DIRECTLY ***
*/
#ifndef _PDF_COMPILERCOMPAT_H
#error Please include PdfDefines.h instead
#endif
#define PODOFO_VERSION_MAJOR 0
#define PODOFO_VERSION_MINOR 9
#define PODOFO_VERSION_PATCH 0
/* PoDoFo configuration options */
#define PODOFO_MULTI_THREAD
/* somewhat platform-specific headers */
#define PODOFO_HAVE_STRINGS_H 1
#define PODOFO_HAVE_ARPA_INET_H 1
/* #undef PODOFO_HAVE_WINSOCK2_H */
/* #undef PODOFO_HAVE_MEM_H */
/* #undef PODOFO_HAVE_CTYPE_H */
/* Integer types - headers */
#define PODOFO_HAVE_STDINT_H 1
/* #undef PODOFO_HAVE_BASETSD_H */
#define PODOFO_HAVE_SYS_TYPES_H 1
/* Integer types - type names */
#define PDF_INT8_TYPENAME int8_t
#define PDF_INT16_TYPENAME int16_t
#define PDF_INT32_TYPENAME int32_t
#define PDF_INT64_TYPENAME int64_t
#define PDF_UINT8_TYPENAME uint8_t
#define PDF_UINT16_TYPENAME uint16_t
#define PDF_UINT32_TYPENAME uint32_t
#define PDF_UINT64_TYPENAME uint64_t
/* Endianness */
/* #undef TEST_BIG */
/* Libraries */
#define PODOFO_HAVE_JPEG_LIB
#define PODOFO_HAVE_PNG_LIB
#define PODOFO_HAVE_TIFF_LIB
#define PODOFO_HAVE_FONTCONFIG
#define PODOFO_HAVE_LUA
/* #undef PODOFO_HAVE_BOOST */
#define PODOFO_HAVE_CPPUNIT
/* Platform quirks */
#define PODOFO_JPEG_RUNTIME_COMPATIBLE
| Java |
<?php
class test_frmx_concepto_form_frame1 extends bas_frmx_cardframe{
public function __construct($id, $tabs='', $grid=array('width'=>4,'height'=>4)) {
parent::__construct($id,$tabs,$grid);
//addComponent($tab, $x, $y, $width, $height, $field);
//construct FIELD ($id,$type,$name, $caption, $editable, $value,$visible). ##Nota: el campo type deberia quitarse.
$width=2;
$height = 1;
$this->SetMode("edit");
$this->tabs = array("Primera","Segunda","Tercera","Cuarta");
$this->query = new bas_sqlx_querydef();
$this->query->add("concepto","test");
$this->query->setkey(array('idconcepto'));
$this->query->order= array("idconcepto"=>"asc");
/*
idconcepto varchar(20) NOT NULL,
descripcion varchar(200) DEFAULT NULL,
caption varchar(30) NOT NULL, ## Nota: ¿Para que se usa este campo?
tipo enum('editable','fijo','calculado') NOT NULL DEFAULT 'editable',
*/
$this->query->addcol("idconcepto", "Concepto","concepto" ,true,'test');
$this->query->addcol("descripcion", "Descripción","concepto" ,false,'test',"upload");
$this->query->addcol("caption", "Caption","concepto" ,false,'test');
$this->query->addcol("tipo", "Tipo:","concepto" ,false,'test',"enum");
$this->setAttr("tipo","enum",array('editable'=>'editable','fijo'=>'fijo','calculado'=>'calculado'));
$this->setAttr('idconcepto','lookup','frmx_cardframe_form');
$this->addComponent("Primera", 1, 1, $width, $height,"idconcepto",'test');
$this->addComponent("Primera", 1, 2, $width, $height, "descripcion",'test');
$this->addComponent("Primera", 1, 3, $width, $height,"caption",'test');
$this->addComponent("Primera", 1, 4, $width, $height,"tipo",'test');
/*
formato enum('numérico','moneda','booleano','opción') NOT NULL DEFAULT 'numérico',
opcionstring varchar(250) DEFAULT NULL,
imagenstring varchar(80) DEFAULT NULL,
datomultiple int(11) NOT NULL DEFAULT '0',
*/
$this->query->addcol("formato", "Tipo:","concepto" ,false,'test',"enum");
$this->query->addcol("opcionstring", "Opciones","concepto" ,false,'test');
$this->query->addcol("imagenstring", "Nombre de la imagen","concepto" ,false,'test');
$this->query->addcol("datomultiple", "Dato multiple ","concepto" ,false,'test');
$this->setAttr("formato","enum",array('numérico'=>'numérico','moneda'=>'moneda','booleano'=>'booleano','opción'=>'opción'));
$this->addComponent("Segunda", 2, 1, $width, $height,"formato");
$this->addComponent("Segunda", 2, 2, $width, $height,"opcionstring");
$this->addComponent("Segunda", 3, 3, $width, $height,"imagenstring");
$this->addComponent("Segunda", 3, 4, $width, $height,"datomultiple");
/*
valor double DEFAULT NULL,
calcorden int(11) DEFAULT NULL,
distribuirvalor int(11) DEFAULT NULL,
sumarizeoper enum('media','suma','mínimo','máximo','moda') DEFAULT NULL,
*/
$this->query->addcol("valor", "Valor","concepto" ,false,'test');
$this->query->addcol("calcorden", "Cálculo del orden","concepto" ,false,'test');
$this->query->addcol("distribuirvalor", "Valor del distibuidor","concepto" ,false,'test');
$this->query->addcol("sumarizeoper", "aritmética","concepto" ,false,'test',"enum");
$this->setAttr("sumarizeoper","enum",array('media'=>'media','suma'=>'suma','mínimo'=>'mínimo','máximo'=>'máximo','moda'=>'moda'));
$this->addComponent("Tercera", 1, 1, 1, $height, "valor");
$this->addComponent("Tercera", 1, 2, $width, $height,"calcorden");
$this->addComponent("Tercera", 3, 1, $width, $height,"distribuirvalor");
$this->addComponent("Tercera", 3, 2, $width, $height,"sumarizeoper");
/*
fechavalor enum('fecha inicio periodo','fecha factura') DEFAULT NULL,
alerta int(11) NOT NULL DEFAULT '0',
alertimage int(11) NOT NULL DEFAULT '0',
alertmincount int(11) NOT NULL DEFAULT '1',
*/
$this->query->addcol("fechavalor", "Fecha","concepto" ,false,'test');
$this->query->addcol("alerta", "alerta","concepto" ,false,'test');
$this->query->addcol("alertimage", "alertimage","concepto" ,false,'test');
$this->query->addcol("alertmincount", "alertmincount","concepto" ,false,'test',"enum");
$this->setAttr("alertmincount","enum",array('fecha inicio periodo'=>'fecha inicio periodo','fecha factura'=>'fecha factura'));
$this->addComponent("Cuarta", 1, 1, 1, $height, "fechavalor");
$this->addComponent("Cuarta", 2, 1, $width, $height, "alerta");
$this->addComponent("Cuarta", 3, 1, $width, $height,"alertimage");
$this->addComponent("Cuarta", 1, 2, $width, $height,"alertmincount");
$this->setRecord();
}
}
/*
alertrepe int(11) DEFAULT NULL,
dynclass varchar(20) DEFAULT NULL,
*/
?>
| Java |
package com.idega.development.presentation;
import com.idega.idegaweb.IWBundle;
import com.idega.idegaweb.IWMainApplication;
import com.idega.presentation.IWContext;
import com.idega.presentation.Image;
import com.idega.presentation.Layer;
import com.idega.presentation.PresentationObject;
import com.idega.presentation.Table;
import com.idega.presentation.text.HorizontalRule;
import com.idega.presentation.text.Text;
import com.idega.presentation.ui.IFrame;
import com.idega.repository.data.RefactorClassRegistry;
/**
* Title: idega Framework
* Description:
* Copyright: Copyright (c) 2001
* Company: idega
* @author <a href=mailto:"tryggvi@idega.is">Tryggvi Larusson</a>
* @version 1.0
*/
public class IWDeveloper extends com.idega.presentation.app.IWApplication {
private static final String localizerParameter = "iw_localizer";
private static final String localeswitcherParameter = "iw_localeswitcher";
private static final String bundleCreatorParameter = "iw_bundlecreator";
private static final String bundleComponentManagerParameter = "iw_bundlecompmanager";
private static final String applicationPropertiesParameter = "iw_application_properties_setter";
private static final String bundlesPropertiesParameter = "iw_bundle_properties_setter";
public static final String actionParameter = "iw_developer_action";
public static final String dbPoolStatusViewerParameter = "iw_poolstatus_viewer";
public static final String updateManagerParameter = "iw_update_manager";
public static final String frameName = "iwdv_rightFrame";
public static final String PARAMETER_CLASS_NAME = "iwdv_class_name";
public IWDeveloper() {
super("idegaWeb Developer");
add(IWDeveloper.IWDevPage.class);
super.setResizable(true);
super.setScrollbar(true);
super.setScrolling(1, true);
super.setWidth(800);
super.setHeight(600);
//super.setOnLoad("moveTo(0,0);");
}
public static class IWDevPage extends com.idega.presentation.ui.Window {
public IWDevPage() {
this.setStatus(true);
}
private Table mainTable;
private Table objectTable;
private IFrame rightFrame;
private int count = 1;
public void main(IWContext iwc) throws Exception {
IWBundle iwbCore = getBundle(iwc);
if (iwc.isIE()) {
getParentPage().setBackgroundColor("#B0B29D");
}
Layer topLayer = new Layer(Layer.DIV);
topLayer.setZIndex(3);
topLayer.setPositionType(Layer.FIXED);
topLayer.setTopPosition(0);
topLayer.setLeftPosition(0);
topLayer.setBackgroundColor("#0E2456");
topLayer.setWidth(Table.HUNDRED_PERCENT);
topLayer.setHeight(25);
add(topLayer);
Table headerTable = new Table();
headerTable.setCellpadding(0);
headerTable.setCellspacing(0);
headerTable.setWidth(Table.HUNDRED_PERCENT);
headerTable.setAlignment(2,1,Table.HORIZONTAL_ALIGN_RIGHT);
topLayer.add(headerTable);
Image idegaweb = iwbCore.getImage("/editorwindow/idegaweb.gif","idegaWeb");
headerTable.add(idegaweb,1,1);
Text adminTitle = new Text("idegaWeb Developer");
adminTitle.setStyleAttribute("color:#FFFFFF;font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:bold;margin-right:5px;");
headerTable.add(adminTitle,2,1);
Layer leftLayer = new Layer(Layer.DIV);
leftLayer.setZIndex(2);
leftLayer.setPositionType(Layer.FIXED);
leftLayer.setTopPosition(25);
leftLayer.setLeftPosition(0);
leftLayer.setPadding(5);
leftLayer.setBackgroundColor("#B0B29D");
leftLayer.setWidth(180);
leftLayer.setHeight(Table.HUNDRED_PERCENT);
add(leftLayer);
DeveloperList list = new DeveloperList();
leftLayer.add(list);
Layer rightLayer = new Layer(Layer.DIV);
rightLayer.setZIndex(1);
rightLayer.setPositionType(Layer.ABSOLUTE);
rightLayer.setTopPosition(25);
rightLayer.setPadding(5);
if (iwc.isIE()) {
rightLayer.setBackgroundColor("#FFFFFF");
rightLayer.setWidth(Table.HUNDRED_PERCENT);
rightLayer.setHeight(Table.HUNDRED_PERCENT);
rightLayer.setLeftPosition(180);
}
else {
rightLayer.setLeftPosition(190);
}
add(rightLayer);
if (iwc.isParameterSet(PARAMETER_CLASS_NAME)) {
String className = IWMainApplication.decryptClassName(iwc.getParameter(PARAMETER_CLASS_NAME));
PresentationObject obj = (PresentationObject) RefactorClassRegistry.getInstance().newInstance(className, this.getClass());
rightLayer.add(obj);
}
else {
rightLayer.add(new Localizer());
}
}
}
public static Table getTitleTable(String displayString, Image image) {
Table titleTable = new Table(1, 2);
titleTable.setCellpadding(0);
titleTable.setCellspacing(0);
titleTable.setWidth("100%");
Text headline = getText(displayString);
headline.setFontSize(Text.FONT_SIZE_14_HTML_4);
headline.setFontColor("#0E2456");
if (image != null) {
image.setHorizontalSpacing(5);
titleTable.add(image, 1, 1);
}
titleTable.add(headline, 1, 1);
titleTable.add(new HorizontalRule("100%", 2, "color: #FF9310", true), 1, 2);
return titleTable;
}
public static Table getTitleTable(String displayString) {
return getTitleTable(displayString, null);
}
public static Table getTitleTable(Class classToUse, Image image) {
return getTitleTable(classToUse.getName().substring(classToUse.getName().lastIndexOf(".") + 1), image);
}
public static Table getTitleTable(Class classToUse) {
return getTitleTable(classToUse, null);
}
public static Text getText(String text) {
Text T = new Text(text);
T.setBold();
T.setFontFace(Text.FONT_FACE_VERDANA);
T.setFontSize(Text.FONT_SIZE_10_HTML_2);
return T;
}
}
| Java |
package itaf.WsCartItemService;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>bzCollectionOrderDto complex typeµÄ Java Àà¡£
*
* <p>ÒÔÏÂģʽƬ¶ÎÖ¸¶¨°üº¬ÔÚ´ËÀàÖеÄÔ¤ÆÚÄÚÈÝ¡£
*
* <pre>
* <complexType name="bzCollectionOrderDto">
* <complexContent>
* <extension base="{itaf.framework.ws.server.cart}operateDto">
* <sequence>
* <element name="bzDistributionOrderDto" type="{itaf.framework.ws.server.cart}bzDistributionOrderDto" minOccurs="0"/>
* <element name="receivableAmount" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="actualAmount" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="distributionAmount" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "bzCollectionOrderDto", propOrder = {
"bzDistributionOrderDto",
"receivableAmount",
"actualAmount",
"distributionAmount"
})
public class BzCollectionOrderDto
extends OperateDto
{
protected BzDistributionOrderDto bzDistributionOrderDto;
protected BigDecimal receivableAmount;
protected BigDecimal actualAmount;
protected BigDecimal distributionAmount;
/**
* »ñÈ¡bzDistributionOrderDtoÊôÐÔµÄÖµ¡£
*
* @return
* possible object is
* {@link BzDistributionOrderDto }
*
*/
public BzDistributionOrderDto getBzDistributionOrderDto() {
return bzDistributionOrderDto;
}
/**
* ÉèÖÃbzDistributionOrderDtoÊôÐÔµÄÖµ¡£
*
* @param value
* allowed object is
* {@link BzDistributionOrderDto }
*
*/
public void setBzDistributionOrderDto(BzDistributionOrderDto value) {
this.bzDistributionOrderDto = value;
}
/**
* »ñÈ¡receivableAmountÊôÐÔµÄÖµ¡£
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getReceivableAmount() {
return receivableAmount;
}
/**
* ÉèÖÃreceivableAmountÊôÐÔµÄÖµ¡£
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setReceivableAmount(BigDecimal value) {
this.receivableAmount = value;
}
/**
* »ñÈ¡actualAmountÊôÐÔµÄÖµ¡£
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getActualAmount() {
return actualAmount;
}
/**
* ÉèÖÃactualAmountÊôÐÔµÄÖµ¡£
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setActualAmount(BigDecimal value) {
this.actualAmount = value;
}
/**
* »ñÈ¡distributionAmountÊôÐÔµÄÖµ¡£
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getDistributionAmount() {
return distributionAmount;
}
/**
* ÉèÖÃdistributionAmountÊôÐÔµÄÖµ¡£
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setDistributionAmount(BigDecimal value) {
this.distributionAmount = value;
}
}
| Java |
# -*- coding: utf8 -*-
SQL = """select SQL_CALC_FOUND_ROWS * FROM doc_view order by `name` asc limit %(offset)d,%(limit)d ;"""
FOUND_ROWS = True
ROOT = "doc_view_list"
ROOT_PREFIX = "<doc_view_edit />"
ROOT_POSTFIX= None
XSL_TEMPLATE = "data/af-web.xsl"
EVENT = None
WHERE = ()
PARAM = None
TITLE="Список видов документов"
MESSAGE="ошибка получения списка видов документов"
ORDER = None
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.